ClientConnection.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. /// The `EventLoop` this connection is using.
  99. public var eventLoop: EventLoop {
  100. return self.channel.eventLoop
  101. }
  102. /// Closes the connection to the server.
  103. public func close() -> EventLoopFuture<Void> {
  104. if self.connectivity.state == .shutdown {
  105. // We're already shutdown or in the process of shutting down.
  106. return channel.flatMap { $0.closeFuture }
  107. } else {
  108. self.logger.info("shutting down channel")
  109. self.connectivity.initiateUserShutdown()
  110. return channel.flatMap { $0.close() }
  111. }
  112. }
  113. }
  114. // MARK: - Channel creation
  115. extension ClientConnection {
  116. /// Register a callback on the close future of the given `channel` to replace the channel (if
  117. /// possible) and also replace the `multiplexer` with that from the new channel.
  118. ///
  119. /// - Parameter channel: The channel that will be set.
  120. private func willSetChannel(to channel: EventLoopFuture<Channel>) {
  121. // If we're about to set the channel and the user has initiated a shutdown (i.e. while the new
  122. // channel was being created) then it is no longer needed.
  123. guard !self.connectivity.userHasInitiatedShutdown else {
  124. channel.whenSuccess { channel in
  125. self.logger.debug("user initiated shutdown during connection, closing channel")
  126. channel.close(mode: .all, promise: nil)
  127. }
  128. return
  129. }
  130. channel.flatMap { $0.closeFuture }.whenComplete { result in
  131. switch result {
  132. case .success:
  133. self.logger.info("client connection shutdown successfully")
  134. case .failure(let error):
  135. self.logger.warning(
  136. "client connection shutdown failed",
  137. metadata: [MetadataKey.error: "\(error)"]
  138. )
  139. }
  140. guard self.connectivity.canAttemptReconnect else { return }
  141. self.logger.debug("client connection channel closed, creating a new one")
  142. self.channel = ClientConnection.makeChannel(
  143. configuration: self.configuration,
  144. connectivity: self.connectivity,
  145. backoffIterator: self.configuration.connectionBackoff?.makeIterator(),
  146. logger: self.logger
  147. )
  148. }
  149. self.multiplexer = channel.flatMap {
  150. $0.pipeline.handler(type: HTTP2StreamMultiplexer.self)
  151. }
  152. }
  153. /// Register a callback on the given `channel` to update the connectivity state.
  154. ///
  155. /// - Parameter channel: The channel that was set.
  156. private func didSetChannel(to channel: EventLoopFuture<Channel>) {
  157. channel.whenComplete { result in
  158. switch result {
  159. case .success:
  160. self.connectivity.state = .ready
  161. case .failure:
  162. self.connectivity.state = .shutdown
  163. }
  164. }
  165. }
  166. /// Attempts to create a new `Channel` using the given configuration.
  167. ///
  168. /// This involves: creating a `ClientBootstrapProtocol`, connecting to a target and verifying that
  169. /// the TLS handshake was successful (if TLS was configured). We _may_ additiionally set a
  170. /// connection timeout and schedule a retry attempt (should the connection fail) if a
  171. /// `ConnectionBackoffIterator` is provided.
  172. ///
  173. /// - Parameter configuration: The configuration to start the connection with.
  174. /// - Parameter connectivity: A connectivity state monitor.
  175. /// - Parameter backoffIterator: An `Iterator` for `ConnectionBackoff` providing a sequence of
  176. /// connection timeouts and backoff to use when attempting to create a connection.
  177. private class func makeChannel(
  178. configuration: Configuration,
  179. connectivity: ConnectivityStateMonitor,
  180. backoffIterator: ConnectionBackoffIterator?,
  181. logger: Logger
  182. ) -> EventLoopFuture<Channel> {
  183. logger.info("attempting to connect to \(configuration.target)")
  184. connectivity.state = .connecting
  185. let timeoutAndBackoff = backoffIterator?.next()
  186. let bootstrap = self.makeBootstrap(
  187. configuration: configuration,
  188. group: configuration.eventLoopGroup,
  189. timeout: timeoutAndBackoff?.timeout,
  190. logger: logger
  191. )
  192. let channel = bootstrap.connect(to: configuration.target).flatMap { channel -> EventLoopFuture<Channel> in
  193. if configuration.tls != nil {
  194. return channel.verifyTLS().map { channel }
  195. } else {
  196. return channel.eventLoop.makeSucceededFuture(channel)
  197. }
  198. }
  199. // If we don't have backoff then we can't retry, just return the `channel` no matter what
  200. // state we are in.
  201. guard let backoff = timeoutAndBackoff?.backoff else {
  202. logger.info("backoff exhausted, no more connection attempts will be made")
  203. return channel
  204. }
  205. // If our connection attempt was unsuccessful, schedule another attempt in some time.
  206. return channel.flatMapError { error in
  207. logger.notice("connection attempt failed", metadata: [MetadataKey.error: "\(error)"])
  208. // We will try to connect again: the failure is transient.
  209. connectivity.state = .transientFailure
  210. return ClientConnection.scheduleReconnectAttempt(
  211. in: backoff,
  212. on: channel.eventLoop,
  213. configuration: configuration,
  214. connectivity: connectivity,
  215. backoffIterator: backoffIterator,
  216. logger: logger
  217. )
  218. }
  219. }
  220. /// Schedule an attempt to make a channel in `timeout` seconds on the given `eventLoop`.
  221. private class func scheduleReconnectAttempt(
  222. in timeout: TimeInterval,
  223. on eventLoop: EventLoop,
  224. configuration: Configuration,
  225. connectivity: ConnectivityStateMonitor,
  226. backoffIterator: ConnectionBackoffIterator?,
  227. logger: Logger
  228. ) -> EventLoopFuture<Channel> {
  229. logger.info("scheduling connection attempt in \(timeout) seconds")
  230. // The `futureResult` of the scheduled task is of type
  231. // `EventLoopFuture<EventLoopFuture<Channel>>`, so we need to `flatMap` it to
  232. // remove a level of indirection.
  233. return eventLoop.scheduleTask(in: .seconds(timeInterval: timeout)) {
  234. ClientConnection.makeChannel(
  235. configuration: configuration,
  236. connectivity: connectivity,
  237. backoffIterator: backoffIterator,
  238. logger: logger
  239. )
  240. }.futureResult.flatMap { channel in
  241. channel
  242. }
  243. }
  244. /// Makes and configures a `ClientBootstrap` using the provided configuration.
  245. ///
  246. /// Enables `SO_REUSEADDR` and `TCP_NODELAY` and configures the `channelInitializer` to use the
  247. /// handlers detailed in the documentation for `ClientConnection`.
  248. ///
  249. /// - Parameter configuration: The configuration to prepare the bootstrap with.
  250. /// - Parameter group: The `EventLoopGroup` to use for the bootstrap.
  251. /// - Parameter timeout: The connection timeout in seconds.
  252. private class func makeBootstrap(
  253. configuration: Configuration,
  254. group: EventLoopGroup,
  255. timeout: TimeInterval?,
  256. logger: Logger
  257. ) -> ClientBootstrapProtocol {
  258. let bootstrap = GRPCNIO.makeClientBootstrap(group: group)
  259. // Enable SO_REUSEADDR and TCP_NODELAY.
  260. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  261. .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  262. .channelInitializer { channel in
  263. let tlsConfigured = configuration.tls.map { tlsConfiguration in
  264. channel.configureTLS(tlsConfiguration, errorDelegate: configuration.errorDelegate)
  265. }
  266. return (tlsConfigured ?? channel.eventLoop.makeSucceededFuture(())).flatMap {
  267. channel.configureHTTP2Pipeline(mode: .client)
  268. }.flatMap { _ in
  269. let errorHandler = DelegatingErrorHandler(delegate: configuration.errorDelegate)
  270. return channel.pipeline.addHandler(errorHandler)
  271. }
  272. }
  273. if let timeout = timeout {
  274. logger.info("setting connect timeout to \(timeout) seconds")
  275. return bootstrap.connectTimeout(.seconds(timeInterval: timeout))
  276. } else {
  277. return bootstrap
  278. }
  279. }
  280. }
  281. // MARK: - Configuration structures
  282. /// A target to connect to.
  283. public enum ConnectionTarget {
  284. /// The host and port.
  285. case hostAndPort(String, Int)
  286. /// The path of a Unix domain socket.
  287. case unixDomainSocket(String)
  288. /// A NIO socket address.
  289. case socketAddress(SocketAddress)
  290. var host: String? {
  291. guard case .hostAndPort(let host, _) = self else {
  292. return nil
  293. }
  294. return host
  295. }
  296. }
  297. extension ClientConnection {
  298. /// The configuration for a connection.
  299. public struct Configuration {
  300. /// The target to connect to.
  301. public var target: ConnectionTarget
  302. /// The event loop group to run the connection on.
  303. public var eventLoopGroup: EventLoopGroup
  304. /// An error delegate which is called when errors are caught. Provided delegates **must not
  305. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  306. /// cycle.
  307. public var errorDelegate: ClientErrorDelegate?
  308. /// A delegate which is called when the connectivity state is changed.
  309. public var connectivityStateDelegate: ConnectivityStateDelegate?
  310. /// TLS configuration for this connection. `nil` if TLS is not desired.
  311. public var tls: TLS?
  312. /// The connection backoff configuration. If no connection retrying is required then this should
  313. /// be `nil`.
  314. public var connectionBackoff: ConnectionBackoff?
  315. /// The HTTP protocol used for this connection.
  316. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  317. return self.tls == nil ? .http : .https
  318. }
  319. /// Create a `Configuration` with some pre-defined defaults.
  320. ///
  321. /// - Parameter target: The target to connect to.
  322. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  323. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  324. /// on debug builds.
  325. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  326. /// - Parameter tlsConfiguration: TLS configuration, defaulting to `nil`.
  327. /// - Parameter connectionBackoff: The connection backoff configuration to use, defaulting
  328. /// to `nil`.
  329. public init(
  330. target: ConnectionTarget,
  331. eventLoopGroup: EventLoopGroup,
  332. errorDelegate: ClientErrorDelegate? = DebugOnlyLoggingClientErrorDelegate.shared,
  333. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  334. tls: Configuration.TLS? = nil,
  335. connectionBackoff: ConnectionBackoff? = nil
  336. ) {
  337. self.target = target
  338. self.eventLoopGroup = eventLoopGroup
  339. self.errorDelegate = errorDelegate
  340. self.connectivityStateDelegate = connectivityStateDelegate
  341. self.tls = tls
  342. self.connectionBackoff = connectionBackoff
  343. }
  344. }
  345. }
  346. // MARK: - Configuration helpers/extensions
  347. fileprivate extension ClientBootstrapProtocol {
  348. /// Connect to the given connection target.
  349. ///
  350. /// - Parameter target: The target to connect to.
  351. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  352. switch target {
  353. case .hostAndPort(let host, let port):
  354. return self.connect(host: host, port: port)
  355. case .unixDomainSocket(let path):
  356. return self.connect(unixDomainSocketPath: path)
  357. case .socketAddress(let address):
  358. return self.connect(to: address)
  359. }
  360. }
  361. }
  362. fileprivate extension Channel {
  363. /// Configure the channel with TLS.
  364. ///
  365. /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and
  366. /// the `TLSVerificationHandler` which verifies that a successful handshake was completed.
  367. ///
  368. /// - Parameter configuration: The configuration to configure the channel with.
  369. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
  370. func configureTLS(
  371. _ configuration: ClientConnection.Configuration.TLS,
  372. errorDelegate: ClientErrorDelegate?
  373. ) -> EventLoopFuture<Void> {
  374. do {
  375. let sslClientHandler = try NIOSSLClientHandler(
  376. context: try NIOSSLContext(configuration: configuration.configuration),
  377. serverHostname: configuration.hostnameOverride)
  378. return self.pipeline.addHandlers(sslClientHandler, TLSVerificationHandler())
  379. } catch {
  380. return self.eventLoop.makeFailedFuture(error)
  381. }
  382. }
  383. /// Returns the `verification` future from the `TLSVerificationHandler` in this channels pipeline.
  384. func verifyTLS() -> EventLoopFuture<Void> {
  385. return self.pipeline.handler(type: TLSVerificationHandler.self).flatMap {
  386. $0.verification
  387. }
  388. }
  389. }
  390. fileprivate extension TimeAmount {
  391. /// Creates a new `TimeAmount` from the given time interval in seconds.
  392. ///
  393. /// - Parameter timeInterval: The amount of time in seconds
  394. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  395. return .nanoseconds(TimeAmount.Value(timeInterval * 1_000_000_000))
  396. }
  397. }