ClientConnection.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. /*
  2. * Copyright 2019, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import NIO
  18. import NIOHTTP2
  19. import NIOSSL
  20. import NIOTLS
  21. import Logging
  22. /// Underlying channel and HTTP/2 stream multiplexer.
  23. ///
  24. /// Different service clients implementing `GRPCClient` may share an instance of this class.
  25. ///
  26. /// The connection is initially setup with a handler to verify that TLS was established
  27. /// successfully (assuming TLS is being used).
  28. ///
  29. /// ▲ |
  30. /// HTTP2Frame│ │HTTP2Frame
  31. /// ┌─┴───────────────────────▼─┐
  32. /// │ HTTP2StreamMultiplexer |
  33. /// └─▲───────────────────────┬─┘
  34. /// HTTP2Frame│ │HTTP2Frame
  35. /// ┌─┴───────────────────────▼─┐
  36. /// │ NIOHTTP2Handler │
  37. /// └─▲───────────────────────┬─┘
  38. /// ByteBuffer│ │ByteBuffer
  39. /// ┌─┴───────────────────────▼─┐
  40. /// │ TLSVerificationHandler │
  41. /// └─▲───────────────────────┬─┘
  42. /// ByteBuffer│ │ByteBuffer
  43. /// ┌─┴───────────────────────▼─┐
  44. /// │ NIOSSLHandler │
  45. /// └─▲───────────────────────┬─┘
  46. /// ByteBuffer│ │ByteBuffer
  47. /// │ ▼
  48. ///
  49. /// The `TLSVerificationHandler` observes the outcome of the SSL handshake and determines
  50. /// whether a `ClientConnection` should be returned to the user. In either eventuality, the
  51. /// handler removes itself from the pipeline once TLS has been verified. There is also a delegated
  52. /// error handler after the `HTTPStreamMultiplexer` in the main channel which uses the error
  53. /// delegate associated with this connection (see `DelegatingErrorHandler`).
  54. ///
  55. /// See `BaseClientCall` for a description of the remainder of the client pipeline.
  56. public class ClientConnection {
  57. internal let logger: Logger
  58. /// The UUID of this connection, used for logging.
  59. internal let uuid: UUID
  60. /// The channel which will handle gRPC calls.
  61. internal var channel: EventLoopFuture<Channel> {
  62. willSet {
  63. self.willSetChannel(to: newValue)
  64. }
  65. didSet {
  66. self.didSetChannel(to: self.channel)
  67. }
  68. }
  69. /// HTTP multiplexer from the `channel` handling gRPC calls.
  70. internal var multiplexer: EventLoopFuture<HTTP2StreamMultiplexer>
  71. /// The configuration for this client.
  72. internal let configuration: Configuration
  73. /// A monitor for the connectivity state.
  74. public let connectivity: ConnectivityStateMonitor
  75. /// Creates a new connection from the given configuration.
  76. public init(configuration: Configuration) {
  77. self.configuration = configuration
  78. self.connectivity = ConnectivityStateMonitor(delegate: configuration.connectivityStateDelegate)
  79. self.uuid = UUID()
  80. var logger = Logger(subsystem: .clientChannel)
  81. logger[metadataKey: MetadataKey.connectionID] = "\(self.uuid)"
  82. self.logger = logger
  83. // We need to initialize `multiplexer` before we can call `willSetChannel` (which will then
  84. // assign `multiplexer` to one from the created `Channel`s pipeline).
  85. let eventLoop = configuration.eventLoopGroup.next()
  86. let unavailable = GRPCStatus(code: .unavailable, message: nil)
  87. self.multiplexer = eventLoop.makeFailedFuture(unavailable)
  88. self.channel = ClientConnection.makeChannel(
  89. configuration: self.configuration,
  90. connectivity: self.connectivity,
  91. backoffIterator: self.configuration.connectionBackoff?.makeIterator(),
  92. logger: self.logger
  93. )
  94. // `willSet` and `didSet` are called on initialization, so call them explicitly now.
  95. self.willSetChannel(to: channel)
  96. self.didSetChannel(to: channel)
  97. }
  98. // This is only internal to expose it for testing.
  99. /// Create a `ClientConnection` for testing using the given `EmbeddedChannel`.
  100. ///
  101. /// - Parameter channel: The embedded channel to create this connection on.
  102. /// - Parameter configuration: How this connection should be configured. The `eventLoopGroup`
  103. /// on the configuration will _not_ be used by the call. As such the `eventLoop` of
  104. /// the given `channel` may be used in the configuration to avoid managing an additional
  105. /// event loop group.
  106. ///
  107. /// - Important:
  108. /// The connectivity state will not be updated using this connection and should not be
  109. /// relied on.
  110. ///
  111. /// - Precondition:
  112. /// The provided connection target in the `configuration` _must_ be a `SocketAddress`.
  113. internal init(channel: EmbeddedChannel, configuration: Configuration) {
  114. // We need a .socketAddress to connect to.
  115. let socketAddress: SocketAddress
  116. switch configuration.target {
  117. case .socketAddress(let address):
  118. socketAddress = address
  119. default:
  120. preconditionFailure("target must be SocketAddress when using EmbeddedChannel")
  121. }
  122. self.uuid = UUID()
  123. var logger = Logger(subsystem: .clientChannel)
  124. logger[metadataKey: MetadataKey.connectionID] = "\(self.uuid)"
  125. self.logger = logger
  126. self.configuration = configuration
  127. self.connectivity = ConnectivityStateMonitor(delegate: configuration.connectivityStateDelegate)
  128. // Configure the channel with the correct handlers and connect to our target.
  129. let configuredChannel = ClientConnection.initializeChannel(
  130. channel,
  131. tls: configuration.tls,
  132. errorDelegate: configuration.errorDelegate
  133. ).flatMap {
  134. channel.connect(to: socketAddress)
  135. }.map { _ in
  136. return channel as Channel
  137. }
  138. self.multiplexer = configuredChannel.flatMap {
  139. $0.pipeline.handler(type: HTTP2StreamMultiplexer.self)
  140. }
  141. self.channel = configuredChannel
  142. }
  143. /// The `EventLoop` this connection is using.
  144. public var eventLoop: EventLoop {
  145. return self.channel.eventLoop
  146. }
  147. /// Closes the connection to the server.
  148. public func close() -> EventLoopFuture<Void> {
  149. if self.connectivity.state == .shutdown {
  150. // We're already shutdown or in the process of shutting down.
  151. return channel.flatMap { $0.closeFuture }
  152. } else {
  153. self.logger.info("shutting down channel")
  154. self.connectivity.initiateUserShutdown()
  155. return channel.flatMap { $0.close() }
  156. }
  157. }
  158. }
  159. // MARK: - Channel creation
  160. extension ClientConnection {
  161. /// Register a callback on the close future of the given `channel` to replace the channel (if
  162. /// possible) and also replace the `multiplexer` with that from the new channel.
  163. ///
  164. /// - Parameter channel: The channel that will be set.
  165. private func willSetChannel(to channel: EventLoopFuture<Channel>) {
  166. // If we're about to set the channel and the user has initiated a shutdown (i.e. while the new
  167. // channel was being created) then it is no longer needed.
  168. guard !self.connectivity.userHasInitiatedShutdown else {
  169. channel.whenSuccess { channel in
  170. self.logger.debug("user initiated shutdown during connection, closing channel")
  171. channel.close(mode: .all, promise: nil)
  172. }
  173. return
  174. }
  175. channel.flatMap { $0.closeFuture }.whenComplete { result in
  176. switch result {
  177. case .success:
  178. self.logger.info("client connection shutdown successfully")
  179. case .failure(let error):
  180. self.logger.warning(
  181. "client connection shutdown failed",
  182. metadata: [MetadataKey.error: "\(error)"]
  183. )
  184. }
  185. guard self.connectivity.canAttemptReconnect else { return }
  186. self.logger.debug("client connection channel closed, creating a new one")
  187. self.channel = ClientConnection.makeChannel(
  188. configuration: self.configuration,
  189. connectivity: self.connectivity,
  190. backoffIterator: self.configuration.connectionBackoff?.makeIterator(),
  191. logger: self.logger
  192. )
  193. }
  194. self.multiplexer = channel.flatMap {
  195. $0.pipeline.handler(type: HTTP2StreamMultiplexer.self)
  196. }
  197. }
  198. /// Register a callback on the given `channel` to update the connectivity state.
  199. ///
  200. /// - Parameter channel: The channel that was set.
  201. private func didSetChannel(to channel: EventLoopFuture<Channel>) {
  202. channel.whenComplete { result in
  203. switch result {
  204. case .success:
  205. self.connectivity.state = .ready
  206. case .failure:
  207. self.connectivity.state = .shutdown
  208. }
  209. }
  210. }
  211. /// Attempts to create a new `Channel` using the given configuration.
  212. ///
  213. /// This involves: creating a `ClientBootstrapProtocol`, connecting to a target and verifying that
  214. /// the TLS handshake was successful (if TLS was configured). We _may_ additiionally set a
  215. /// connection timeout and schedule a retry attempt (should the connection fail) if a
  216. /// `ConnectionBackoffIterator` is provided.
  217. ///
  218. /// - Parameter configuration: The configuration to start the connection with.
  219. /// - Parameter connectivity: A connectivity state monitor.
  220. /// - Parameter backoffIterator: An `Iterator` for `ConnectionBackoff` providing a sequence of
  221. /// connection timeouts and backoff to use when attempting to create a connection.
  222. private class func makeChannel(
  223. configuration: Configuration,
  224. connectivity: ConnectivityStateMonitor,
  225. backoffIterator: ConnectionBackoffIterator?,
  226. logger: Logger
  227. ) -> EventLoopFuture<Channel> {
  228. logger.info("attempting to connect to \(configuration.target)")
  229. connectivity.state = .connecting
  230. let timeoutAndBackoff = backoffIterator?.next()
  231. let bootstrap = self.makeBootstrap(
  232. configuration: configuration,
  233. group: configuration.eventLoopGroup,
  234. timeout: timeoutAndBackoff?.timeout,
  235. logger: logger
  236. )
  237. let channel = bootstrap.connect(to: configuration.target).flatMap { channel -> EventLoopFuture<Channel> in
  238. if configuration.tls != nil {
  239. return channel.verifyTLS().map { channel }
  240. } else {
  241. return channel.eventLoop.makeSucceededFuture(channel)
  242. }
  243. }
  244. // If we don't have backoff then we can't retry, just return the `channel` no matter what
  245. // state we are in.
  246. guard let backoff = timeoutAndBackoff?.backoff else {
  247. logger.info("backoff exhausted, no more connection attempts will be made")
  248. return channel
  249. }
  250. // If our connection attempt was unsuccessful, schedule another attempt in some time.
  251. return channel.flatMapError { error in
  252. logger.notice("connection attempt failed", metadata: [MetadataKey.error: "\(error)"])
  253. // We will try to connect again: the failure is transient.
  254. connectivity.state = .transientFailure
  255. return ClientConnection.scheduleReconnectAttempt(
  256. in: backoff,
  257. on: channel.eventLoop,
  258. configuration: configuration,
  259. connectivity: connectivity,
  260. backoffIterator: backoffIterator,
  261. logger: logger
  262. )
  263. }
  264. }
  265. /// Schedule an attempt to make a channel in `timeout` seconds on the given `eventLoop`.
  266. private class func scheduleReconnectAttempt(
  267. in timeout: TimeInterval,
  268. on eventLoop: EventLoop,
  269. configuration: Configuration,
  270. connectivity: ConnectivityStateMonitor,
  271. backoffIterator: ConnectionBackoffIterator?,
  272. logger: Logger
  273. ) -> EventLoopFuture<Channel> {
  274. logger.info("scheduling connection attempt in \(timeout) seconds")
  275. // The `futureResult` of the scheduled task is of type
  276. // `EventLoopFuture<EventLoopFuture<Channel>>`, so we need to `flatMap` it to
  277. // remove a level of indirection.
  278. return eventLoop.scheduleTask(in: .seconds(timeInterval: timeout)) {
  279. ClientConnection.makeChannel(
  280. configuration: configuration,
  281. connectivity: connectivity,
  282. backoffIterator: backoffIterator,
  283. logger: logger
  284. )
  285. }.futureResult.flatMap { channel in
  286. channel
  287. }
  288. }
  289. /// Makes and configures a `ClientBootstrap` using the provided configuration.
  290. ///
  291. /// Enables `SO_REUSEADDR` and `TCP_NODELAY` and configures the `channelInitializer` to use the
  292. /// handlers detailed in the documentation for `ClientConnection`.
  293. ///
  294. /// - Parameter configuration: The configuration to prepare the bootstrap with.
  295. /// - Parameter group: The `EventLoopGroup` to use for the bootstrap.
  296. /// - Parameter timeout: The connection timeout in seconds.
  297. private class func makeBootstrap(
  298. configuration: Configuration,
  299. group: EventLoopGroup,
  300. timeout: TimeInterval?,
  301. logger: Logger
  302. ) -> ClientBootstrapProtocol {
  303. let bootstrap = PlatformSupport.makeClientBootstrap(group: group)
  304. // Enable SO_REUSEADDR and TCP_NODELAY.
  305. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  306. .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  307. .channelInitializer { channel in
  308. initializeChannel(
  309. channel,
  310. tls: configuration.tls,
  311. errorDelegate: configuration.errorDelegate
  312. )
  313. }
  314. if let timeout = timeout {
  315. logger.info("setting connect timeout to \(timeout) seconds")
  316. return bootstrap.connectTimeout(.seconds(timeInterval: timeout))
  317. } else {
  318. return bootstrap
  319. }
  320. }
  321. /// Initialize the channel with the given TLS configuration and error delegate.
  322. ///
  323. /// - Parameter channel: The channel to initialize.
  324. /// - Parameter tls: The optional TLS configuration for the channel.
  325. /// - Parameter errorDelegate: Optional client error delegate.
  326. private class func initializeChannel(
  327. _ channel: Channel,
  328. tls: Configuration.TLS?,
  329. errorDelegate: ClientErrorDelegate?
  330. ) -> EventLoopFuture<Void> {
  331. let tlsConfigured = tls.map { tlsConfiguration in
  332. channel.configureTLS(tlsConfiguration, errorDelegate: errorDelegate)
  333. }
  334. return (tlsConfigured ?? channel.eventLoop.makeSucceededFuture(())).flatMap {
  335. channel.configureHTTP2Pipeline(mode: .client)
  336. }.flatMap { _ in
  337. let errorHandler = DelegatingErrorHandler(delegate: errorDelegate)
  338. return channel.pipeline.addHandler(errorHandler)
  339. }
  340. }
  341. }
  342. // MARK: - Configuration structures
  343. /// A target to connect to.
  344. public enum ConnectionTarget {
  345. /// The host and port.
  346. case hostAndPort(String, Int)
  347. /// The path of a Unix domain socket.
  348. case unixDomainSocket(String)
  349. /// A NIO socket address.
  350. case socketAddress(SocketAddress)
  351. var host: String {
  352. switch self {
  353. case .hostAndPort(let host, _):
  354. return host
  355. case .socketAddress(.v4(let address)):
  356. return address.host
  357. case .socketAddress(.v6(let address)):
  358. return address.host
  359. case .unixDomainSocket, .socketAddress(.unixDomainSocket):
  360. return "localhost"
  361. }
  362. }
  363. }
  364. extension ClientConnection {
  365. /// The configuration for a connection.
  366. public struct Configuration {
  367. /// The target to connect to.
  368. public var target: ConnectionTarget
  369. /// The event loop group to run the connection on.
  370. public var eventLoopGroup: EventLoopGroup
  371. /// An error delegate which is called when errors are caught. Provided delegates **must not
  372. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  373. /// cycle.
  374. public var errorDelegate: ClientErrorDelegate?
  375. /// A delegate which is called when the connectivity state is changed.
  376. public var connectivityStateDelegate: ConnectivityStateDelegate?
  377. /// TLS configuration for this connection. `nil` if TLS is not desired.
  378. public var tls: TLS?
  379. /// The connection backoff configuration. If no connection retrying is required then this should
  380. /// be `nil`.
  381. public var connectionBackoff: ConnectionBackoff?
  382. /// The HTTP protocol used for this connection.
  383. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  384. return self.tls == nil ? .http : .https
  385. }
  386. /// Create a `Configuration` with some pre-defined defaults.
  387. ///
  388. /// - Parameter target: The target to connect to.
  389. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  390. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  391. /// on debug builds.
  392. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  393. /// - Parameter tlsConfiguration: TLS configuration, defaulting to `nil`.
  394. /// - Parameter connectionBackoff: The connection backoff configuration to use, defaulting
  395. /// to `nil`.
  396. public init(
  397. target: ConnectionTarget,
  398. eventLoopGroup: EventLoopGroup,
  399. errorDelegate: ClientErrorDelegate? = DebugOnlyLoggingClientErrorDelegate.shared,
  400. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  401. tls: Configuration.TLS? = nil,
  402. connectionBackoff: ConnectionBackoff? = nil
  403. ) {
  404. self.target = target
  405. self.eventLoopGroup = eventLoopGroup
  406. self.errorDelegate = errorDelegate
  407. self.connectivityStateDelegate = connectivityStateDelegate
  408. self.tls = tls
  409. self.connectionBackoff = connectionBackoff
  410. }
  411. }
  412. }
  413. // MARK: - Configuration helpers/extensions
  414. fileprivate extension ClientBootstrapProtocol {
  415. /// Connect to the given connection target.
  416. ///
  417. /// - Parameter target: The target to connect to.
  418. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  419. switch target {
  420. case .hostAndPort(let host, let port):
  421. return self.connect(host: host, port: port)
  422. case .unixDomainSocket(let path):
  423. return self.connect(unixDomainSocketPath: path)
  424. case .socketAddress(let address):
  425. return self.connect(to: address)
  426. }
  427. }
  428. }
  429. fileprivate extension Channel {
  430. /// Configure the channel with TLS.
  431. ///
  432. /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and
  433. /// the `TLSVerificationHandler` which verifies that a successful handshake was completed.
  434. ///
  435. /// - Parameter configuration: The configuration to configure the channel with.
  436. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
  437. func configureTLS(
  438. _ configuration: ClientConnection.Configuration.TLS,
  439. errorDelegate: ClientErrorDelegate?
  440. ) -> EventLoopFuture<Void> {
  441. do {
  442. let sslClientHandler = try NIOSSLClientHandler(
  443. context: try NIOSSLContext(configuration: configuration.configuration),
  444. serverHostname: configuration.hostnameOverride)
  445. return self.pipeline.addHandlers(sslClientHandler, TLSVerificationHandler())
  446. } catch {
  447. return self.eventLoop.makeFailedFuture(error)
  448. }
  449. }
  450. /// Returns the `verification` future from the `TLSVerificationHandler` in this channels pipeline.
  451. func verifyTLS() -> EventLoopFuture<Void> {
  452. return self.pipeline.handler(type: TLSVerificationHandler.self).flatMap {
  453. $0.verification
  454. }
  455. }
  456. }
  457. fileprivate extension TimeAmount {
  458. /// Creates a new `TimeAmount` from the given time interval in seconds.
  459. ///
  460. /// - Parameter timeInterval: The amount of time in seconds
  461. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  462. return .nanoseconds(TimeAmount.Value(timeInterval * 1_000_000_000))
  463. }
  464. }