ClientConnection.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. // If we get a channel and it closes then create a new one, if necessary.
  191. channel.flatMap { $0.closeFuture }.whenComplete { result in
  192. switch result {
  193. case .success:
  194. self.logger.info("client connection shutdown successfully")
  195. case .failure(let error):
  196. self.logger.warning(
  197. "client connection shutdown failed",
  198. metadata: [MetadataKey.error: "\(error)"]
  199. )
  200. }
  201. guard self.connectivity.canAttemptReconnect else {
  202. return
  203. }
  204. // Something went wrong, but we'll try to fix it so let's update our state to reflect that.
  205. self.connectivity.state = .transientFailure
  206. self.logger.debug("client connection channel closed, creating a new one")
  207. self.channel = ClientConnection.makeChannel(
  208. configuration: self.configuration,
  209. connectivity: self.connectivity,
  210. backoffIterator: self.configuration.connectionBackoff?.makeIterator(),
  211. logger: self.logger
  212. )
  213. }
  214. self.multiplexer = channel.flatMap {
  215. $0.pipeline.handler(type: HTTP2StreamMultiplexer.self)
  216. }
  217. }
  218. /// Register a callback on the given `channel` to update the connectivity state.
  219. ///
  220. /// - Parameter channel: The channel that was set.
  221. private func didSetChannel(to channel: EventLoopFuture<Channel>) {
  222. channel.whenFailure { _ in
  223. self.connectivity.state = .shutdown
  224. }
  225. }
  226. /// Attempts to create a new `Channel` using the given configuration.
  227. ///
  228. /// This involves: creating a `ClientBootstrapProtocol`, connecting to a target and verifying that
  229. /// the TLS handshake was successful (if TLS was configured). We _may_ additiionally set a
  230. /// connection timeout and schedule a retry attempt (should the connection fail) if a
  231. /// `ConnectionBackoffIterator` is provided.
  232. ///
  233. /// - Parameter configuration: The configuration to start the connection with.
  234. /// - Parameter connectivity: A connectivity state monitor.
  235. /// - Parameter backoffIterator: An `Iterator` for `ConnectionBackoff` providing a sequence of
  236. /// connection timeouts and backoff to use when attempting to create a connection.
  237. private class func makeChannel(
  238. configuration: Configuration,
  239. connectivity: ConnectivityStateMonitor,
  240. backoffIterator: ConnectionBackoffIterator?,
  241. logger: Logger
  242. ) -> EventLoopFuture<Channel> {
  243. guard connectivity.state == .idle || connectivity.state == .transientFailure else {
  244. return configuration.eventLoopGroup.next().makeFailedFuture(GRPCStatus.processingError)
  245. }
  246. logger.info("attempting to connect to \(configuration.target)")
  247. connectivity.state = .connecting
  248. let timeoutAndBackoff = backoffIterator?.next()
  249. let bootstrap = self.makeBootstrap(
  250. configuration: configuration,
  251. group: configuration.eventLoopGroup,
  252. timeout: timeoutAndBackoff?.timeout,
  253. connectivityMonitor: connectivity,
  254. logger: logger
  255. )
  256. let channel = bootstrap.connect(to: configuration.target).flatMap { channel -> EventLoopFuture<Channel> in
  257. if configuration.tls != nil {
  258. return channel.verifyTLS().map { channel }
  259. } else {
  260. return channel.eventLoop.makeSucceededFuture(channel)
  261. }
  262. }
  263. // If we don't have backoff then we can't retry, just return the `channel` no matter what
  264. // state we are in.
  265. guard let backoff = timeoutAndBackoff?.backoff else {
  266. logger.info("backoff exhausted, no more connection attempts will be made")
  267. return channel
  268. }
  269. // If our connection attempt was unsuccessful, schedule another attempt in some time.
  270. return channel.flatMapError { error in
  271. logger.notice("connection attempt failed", metadata: [MetadataKey.error: "\(error)"])
  272. // We will try to connect again: the failure is transient.
  273. connectivity.state = .transientFailure
  274. return ClientConnection.scheduleReconnectAttempt(
  275. in: backoff,
  276. on: channel.eventLoop,
  277. configuration: configuration,
  278. connectivity: connectivity,
  279. backoffIterator: backoffIterator,
  280. logger: logger
  281. )
  282. }
  283. }
  284. /// Schedule an attempt to make a channel in `timeout` seconds on the given `eventLoop`.
  285. private class func scheduleReconnectAttempt(
  286. in timeout: TimeInterval,
  287. on eventLoop: EventLoop,
  288. configuration: Configuration,
  289. connectivity: ConnectivityStateMonitor,
  290. backoffIterator: ConnectionBackoffIterator?,
  291. logger: Logger
  292. ) -> EventLoopFuture<Channel> {
  293. logger.info("scheduling connection attempt in \(timeout) seconds")
  294. // The `futureResult` of the scheduled task is of type
  295. // `EventLoopFuture<EventLoopFuture<Channel>>`, so we need to `flatMap` it to
  296. // remove a level of indirection.
  297. return eventLoop.scheduleTask(in: .seconds(timeInterval: timeout)) {
  298. ClientConnection.makeChannel(
  299. configuration: configuration,
  300. connectivity: connectivity,
  301. backoffIterator: backoffIterator,
  302. logger: logger
  303. )
  304. }.futureResult.flatMap { channel in
  305. channel
  306. }
  307. }
  308. /// Makes and configures a `ClientBootstrap` using the provided configuration.
  309. ///
  310. /// Enables `SO_REUSEADDR` and `TCP_NODELAY` and configures the `channelInitializer` to use the
  311. /// handlers detailed in the documentation for `ClientConnection`.
  312. ///
  313. /// - Parameter configuration: The configuration to prepare the bootstrap with.
  314. /// - Parameter group: The `EventLoopGroup` to use for the bootstrap.
  315. /// - Parameter timeout: The connection timeout in seconds.
  316. /// - Parameter connectivityMonitor: The connectivity state monitor for the created channel.
  317. private class func makeBootstrap(
  318. configuration: Configuration,
  319. group: EventLoopGroup,
  320. timeout: TimeInterval?,
  321. connectivityMonitor: ConnectivityStateMonitor,
  322. logger: Logger
  323. ) -> ClientBootstrapProtocol {
  324. // Provide a server hostname if we're using TLS. Prefer the override.
  325. let serverHostname: String? = configuration.tls.map {
  326. if let hostnameOverride = $0.hostnameOverride {
  327. logger.debug("using hostname override for TLS", metadata: ["server-hostname": "\(hostnameOverride)"])
  328. return hostnameOverride
  329. } else {
  330. let host = configuration.target.host
  331. logger.debug("using host from connection target for TLS", metadata: ["server-hostname": "\(host)"])
  332. return host
  333. }
  334. }
  335. let bootstrap = PlatformSupport.makeClientBootstrap(group: group)
  336. // Enable SO_REUSEADDR and TCP_NODELAY.
  337. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  338. .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  339. .channelInitializer { channel in
  340. initializeChannel(
  341. channel,
  342. tls: configuration.tls?.configuration,
  343. serverHostname: serverHostname,
  344. connectivityMonitor: connectivityMonitor,
  345. errorDelegate: configuration.errorDelegate
  346. )
  347. }
  348. if let timeout = timeout {
  349. logger.info("setting connect timeout to \(timeout) seconds")
  350. return bootstrap.connectTimeout(.seconds(timeInterval: timeout))
  351. } else {
  352. return bootstrap
  353. }
  354. }
  355. /// Initialize the channel with the given TLS configuration and error delegate.
  356. ///
  357. /// - Parameter channel: The channel to initialize.
  358. /// - Parameter tls: The optional TLS configuration for the channel.
  359. /// - Parameter serverHostname: The hostname of the server to use for TLS.
  360. /// - Parameter errorDelegate: Optional client error delegate.
  361. private class func initializeChannel(
  362. _ channel: Channel,
  363. tls: TLSConfiguration?,
  364. serverHostname: String?,
  365. connectivityMonitor: ConnectivityStateMonitor,
  366. errorDelegate: ClientErrorDelegate?
  367. ) -> EventLoopFuture<Void> {
  368. let tlsConfigured = tls.map {
  369. channel.configureTLS($0, serverHostname: serverHostname, errorDelegate: errorDelegate)
  370. }
  371. return (tlsConfigured ?? channel.eventLoop.makeSucceededFuture(())).flatMap {
  372. channel.configureHTTP2Pipeline(mode: .client)
  373. }.flatMap { _ in
  374. let settingsObserver = InitialSettingsObservingHandler(connectivityStateMonitor: connectivityMonitor)
  375. let errorHandler = DelegatingErrorHandler(delegate: errorDelegate)
  376. return channel.pipeline.addHandlers(settingsObserver, errorHandler)
  377. }
  378. }
  379. }
  380. // MARK: - Configuration structures
  381. /// A target to connect to.
  382. public enum ConnectionTarget {
  383. /// The host and port.
  384. case hostAndPort(String, Int)
  385. /// The path of a Unix domain socket.
  386. case unixDomainSocket(String)
  387. /// A NIO socket address.
  388. case socketAddress(SocketAddress)
  389. var host: String {
  390. switch self {
  391. case .hostAndPort(let host, _):
  392. return host
  393. case .socketAddress(.v4(let address)):
  394. return address.host
  395. case .socketAddress(.v6(let address)):
  396. return address.host
  397. case .unixDomainSocket, .socketAddress(.unixDomainSocket):
  398. return "localhost"
  399. }
  400. }
  401. }
  402. extension ClientConnection {
  403. /// The configuration for a connection.
  404. public struct Configuration {
  405. /// The target to connect to.
  406. public var target: ConnectionTarget
  407. /// The event loop group to run the connection on.
  408. public var eventLoopGroup: EventLoopGroup
  409. /// An error delegate which is called when errors are caught. Provided delegates **must not
  410. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  411. /// cycle.
  412. public var errorDelegate: ClientErrorDelegate?
  413. /// A delegate which is called when the connectivity state is changed.
  414. public var connectivityStateDelegate: ConnectivityStateDelegate?
  415. /// TLS configuration for this connection. `nil` if TLS is not desired.
  416. public var tls: TLS?
  417. /// The connection backoff configuration. If no connection retrying is required then this should
  418. /// be `nil`.
  419. public var connectionBackoff: ConnectionBackoff?
  420. /// The HTTP protocol used for this connection.
  421. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  422. return self.tls == nil ? .http : .https
  423. }
  424. /// Create a `Configuration` with some pre-defined defaults.
  425. ///
  426. /// - Parameter target: The target to connect to.
  427. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  428. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  429. /// on debug builds.
  430. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  431. /// - Parameter tlsConfiguration: TLS configuration, defaulting to `nil`.
  432. /// - Parameter connectionBackoff: The connection backoff configuration to use.
  433. public init(
  434. target: ConnectionTarget,
  435. eventLoopGroup: EventLoopGroup,
  436. errorDelegate: ClientErrorDelegate? = DebugOnlyLoggingClientErrorDelegate.shared,
  437. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  438. tls: Configuration.TLS? = nil,
  439. connectionBackoff: ConnectionBackoff? = ConnectionBackoff()
  440. ) {
  441. self.target = target
  442. self.eventLoopGroup = eventLoopGroup
  443. self.errorDelegate = errorDelegate
  444. self.connectivityStateDelegate = connectivityStateDelegate
  445. self.tls = tls
  446. self.connectionBackoff = connectionBackoff
  447. }
  448. }
  449. }
  450. // MARK: - Configuration helpers/extensions
  451. fileprivate extension ClientBootstrapProtocol {
  452. /// Connect to the given connection target.
  453. ///
  454. /// - Parameter target: The target to connect to.
  455. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  456. switch target {
  457. case .hostAndPort(let host, let port):
  458. return self.connect(host: host, port: port)
  459. case .unixDomainSocket(let path):
  460. return self.connect(unixDomainSocketPath: path)
  461. case .socketAddress(let address):
  462. return self.connect(to: address)
  463. }
  464. }
  465. }
  466. fileprivate extension Channel {
  467. /// Configure the channel with TLS.
  468. ///
  469. /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and
  470. /// the `TLSVerificationHandler` which verifies that a successful handshake was completed.
  471. ///
  472. /// - Parameter configuration: The configuration to configure the channel with.
  473. /// - Parameter serverHostname: The server hostname to use if the hostname should be verified.
  474. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
  475. func configureTLS(
  476. _ configuration: TLSConfiguration,
  477. serverHostname: String?,
  478. errorDelegate: ClientErrorDelegate?
  479. ) -> EventLoopFuture<Void> {
  480. do {
  481. let sslClientHandler = try NIOSSLClientHandler(
  482. context: try NIOSSLContext(configuration: configuration),
  483. serverHostname: serverHostname
  484. )
  485. return self.pipeline.addHandlers(sslClientHandler, TLSVerificationHandler())
  486. } catch {
  487. return self.eventLoop.makeFailedFuture(error)
  488. }
  489. }
  490. /// Returns the `verification` future from the `TLSVerificationHandler` in this channels pipeline.
  491. func verifyTLS() -> EventLoopFuture<Void> {
  492. return self.pipeline.handler(type: TLSVerificationHandler.self).flatMap {
  493. $0.verification
  494. }
  495. }
  496. }
  497. fileprivate extension TimeAmount {
  498. /// Creates a new `TimeAmount` from the given time interval in seconds.
  499. ///
  500. /// - Parameter timeInterval: The amount of time in seconds
  501. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  502. return .nanoseconds(TimeAmount.Value(timeInterval * 1_000_000_000))
  503. }
  504. }