ClientConnection.swift 22 KB

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