ClientConnection.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. /// Underlying channel and HTTP/2 stream multiplexer.
  22. ///
  23. /// Different service clients implementing `GRPCClient` may share an instance of this class.
  24. ///
  25. /// The connection is initially setup with a handler to verify that TLS was established
  26. /// successfully (assuming TLS is being used).
  27. ///
  28. /// ▲ |
  29. /// HTTP2Frame│ │HTTP2Frame
  30. /// ┌─┴───────────────────────▼─┐
  31. /// │ HTTP2StreamMultiplexer |
  32. /// └─▲───────────────────────┬─┘
  33. /// HTTP2Frame│ │HTTP2Frame
  34. /// ┌─┴───────────────────────▼─┐
  35. /// │ NIOHTTP2Handler │
  36. /// └─▲───────────────────────┬─┘
  37. /// ByteBuffer│ │ByteBuffer
  38. /// ┌─┴───────────────────────▼─┐
  39. /// │ TLSVerificationHandler │
  40. /// └─▲───────────────────────┬─┘
  41. /// ByteBuffer│ │ByteBuffer
  42. /// ┌─┴───────────────────────▼─┐
  43. /// │ NIOSSLHandler │
  44. /// └─▲───────────────────────┬─┘
  45. /// ByteBuffer│ │ByteBuffer
  46. /// │ ▼
  47. ///
  48. /// The `TLSVerificationHandler` observes the outcome of the SSL handshake and determines
  49. /// whether a `ClientConnection` should be returned to the user. In either eventuality, the
  50. /// handler removes itself from the pipeline once TLS has been verified. There is also a delegated
  51. /// error handler after the `HTTPStreamMultiplexer` in the main channel which uses the error
  52. /// delegate associated with this connection (see `DelegatingErrorHandler`).
  53. ///
  54. /// See `BaseClientCall` for a description of the remainder of the client pipeline.
  55. public class ClientConnection {
  56. /// The channel which will handle gRPC calls.
  57. internal var channel: EventLoopFuture<Channel> {
  58. willSet {
  59. self.willSetChannel(to: newValue)
  60. }
  61. didSet {
  62. self.didSetChannel(to: self.channel)
  63. }
  64. }
  65. /// HTTP multiplexer from the `channel` handling gRPC calls.
  66. internal var multiplexer: EventLoopFuture<HTTP2StreamMultiplexer>
  67. /// The configuration for this client.
  68. internal let configuration: Configuration
  69. /// A monitor for the connectivity state.
  70. public let connectivity: ConnectivityStateMonitor
  71. /// Creates a new connection from the given configuration.
  72. public init(configuration: Configuration) {
  73. self.configuration = configuration
  74. self.connectivity = ConnectivityStateMonitor(delegate: configuration.connectivityStateDelegate)
  75. // We need to initialize `multiplexer` before we can call `willSetChannel` (which will then
  76. // assign `multiplexer` to one from the created `Channel`s pipeline).
  77. let eventLoop = configuration.eventLoopGroup.next()
  78. let unavailable = GRPCStatus(code: .unavailable, message: nil)
  79. self.multiplexer = eventLoop.makeFailedFuture(unavailable)
  80. self.channel = ClientConnection.makeChannel(
  81. configuration: self.configuration,
  82. connectivity: self.connectivity,
  83. backoffIterator: self.configuration.connectionBackoff?.makeIterator()
  84. )
  85. // `willSet` and `didSet` are called on initialization, so call them explicitly now.
  86. self.willSetChannel(to: channel)
  87. self.didSetChannel(to: channel)
  88. }
  89. /// The `EventLoop` this connection is using.
  90. public var eventLoop: EventLoop {
  91. return self.channel.eventLoop
  92. }
  93. /// Closes the connection to the server.
  94. public func close() -> EventLoopFuture<Void> {
  95. if self.connectivity.state == .shutdown {
  96. // We're already shutdown or in the process of shutting down.
  97. return channel.flatMap { $0.closeFuture }
  98. } else {
  99. self.connectivity.initiateUserShutdown()
  100. return channel.flatMap { $0.close() }
  101. }
  102. }
  103. }
  104. // MARK: - Channel creation
  105. extension ClientConnection {
  106. /// Register a callback on the close future of the given `channel` to replace the channel (if
  107. /// possible) and also replace the `multiplexer` with that from the new channel.
  108. ///
  109. /// - Parameter channel: The channel that will be set.
  110. private func willSetChannel(to channel: EventLoopFuture<Channel>) {
  111. // If we're about to set the channel and the user has initiated a shutdown (i.e. while the new
  112. // channel was being created) then it is no longer needed.
  113. guard !self.connectivity.userHasInitiatedShutdown else {
  114. channel.whenSuccess { channel in
  115. channel.close(mode: .all, promise: nil)
  116. }
  117. return
  118. }
  119. channel.flatMap { $0.closeFuture }.whenComplete { _ in
  120. guard self.connectivity.canAttemptReconnect else { return }
  121. self.channel = ClientConnection.makeChannel(
  122. configuration: self.configuration,
  123. connectivity: self.connectivity,
  124. backoffIterator: self.configuration.connectionBackoff?.makeIterator()
  125. )
  126. }
  127. self.multiplexer = channel.flatMap {
  128. $0.pipeline.handler(type: HTTP2StreamMultiplexer.self)
  129. }
  130. }
  131. /// Register a callback on the given `channel` to update the connectivity state.
  132. ///
  133. /// - Parameter channel: The channel that was set.
  134. private func didSetChannel(to channel: EventLoopFuture<Channel>) {
  135. channel.whenComplete { result in
  136. switch result {
  137. case .success:
  138. self.connectivity.state = .ready
  139. case .failure:
  140. self.connectivity.state = .shutdown
  141. }
  142. }
  143. }
  144. /// Attempts to create a new `Channel` using the given configuration.
  145. ///
  146. /// This involves: creating a `ClientBootstrapProtocol`, connecting to a target and verifying that
  147. /// the TLS handshake was successful (if TLS was configured). We _may_ additiionally set a
  148. /// connection timeout and schedule a retry attempt (should the connection fail) if a
  149. /// `ConnectionBackoffIterator` is provided.
  150. ///
  151. /// - Parameter configuration: The configuration to start the connection with.
  152. /// - Parameter connectivity: A connectivity state monitor.
  153. /// - Parameter backoffIterator: An `Iterator` for `ConnectionBackoff` providing a sequence of
  154. /// connection timeouts and backoff to use when attempting to create a connection.
  155. private class func makeChannel(
  156. configuration: Configuration,
  157. connectivity: ConnectivityStateMonitor,
  158. backoffIterator: ConnectionBackoffIterator?
  159. ) -> EventLoopFuture<Channel> {
  160. connectivity.state = .connecting
  161. let timeoutAndBackoff = backoffIterator?.next()
  162. let bootstrap = self.makeBootstrap(
  163. configuration: configuration,
  164. group: configuration.eventLoopGroup,
  165. timeout: timeoutAndBackoff?.timeout
  166. )
  167. let channel = bootstrap.connect(to: configuration.target).flatMap { channel -> EventLoopFuture<Channel> in
  168. if configuration.tlsConfiguration != nil {
  169. return channel.verifyTLS().map { channel }
  170. } else {
  171. return channel.eventLoop.makeSucceededFuture(channel)
  172. }
  173. }
  174. // If we don't have backoff then we can't retry, just return the `channel` no matter what
  175. // state we are in.
  176. guard let backoff = timeoutAndBackoff?.backoff else {
  177. return channel
  178. }
  179. // If our connection attempt was unsuccessful, schedule another attempt in some time.
  180. return channel.flatMapError { _ in
  181. // We will try to connect again: the failure is transient.
  182. connectivity.state = .transientFailure
  183. return ClientConnection.scheduleReconnectAttempt(
  184. in: backoff,
  185. on: channel.eventLoop,
  186. configuration: configuration,
  187. connectivity: connectivity,
  188. backoffIterator: backoffIterator
  189. )
  190. }
  191. }
  192. /// Schedule an attempt to make a channel in `timeout` seconds on the given `eventLoop`.
  193. private class func scheduleReconnectAttempt(
  194. in timeout: TimeInterval,
  195. on eventLoop: EventLoop,
  196. configuration: Configuration,
  197. connectivity: ConnectivityStateMonitor,
  198. backoffIterator: ConnectionBackoffIterator?
  199. ) -> EventLoopFuture<Channel> {
  200. // The `futureResult` of the scheduled task is of type
  201. // `EventLoopFuture<EventLoopFuture<Channel>>`, so we need to `flatMap` it to
  202. // remove a level of indirection.
  203. return eventLoop.scheduleTask(in: .seconds(timeInterval: timeout)) {
  204. ClientConnection.makeChannel(
  205. configuration: configuration,
  206. connectivity: connectivity,
  207. backoffIterator: backoffIterator
  208. )
  209. }.futureResult.flatMap { channel in
  210. channel
  211. }
  212. }
  213. /// Makes and configures a `ClientBootstrap` using the provided configuration.
  214. ///
  215. /// Enables `SO_REUSEADDR` and `TCP_NODELAY` and configures the `channelInitializer` to use the
  216. /// handlers detailed in the documentation for `ClientConnection`.
  217. ///
  218. /// - Parameter configuration: The configuration to prepare the bootstrap with.
  219. /// - Parameter group: The `EventLoopGroup` to use for the bootstrap.
  220. /// - Parameter timeout: The connection timeout in seconds.
  221. private class func makeBootstrap(
  222. configuration: Configuration,
  223. group: EventLoopGroup,
  224. timeout: TimeInterval?
  225. ) -> ClientBootstrapProtocol {
  226. let bootstrap = GRPCNIO.makeClientBootstrap(group: group)
  227. // Enable SO_REUSEADDR and TCP_NODELAY.
  228. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  229. .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  230. .channelInitializer { channel in
  231. let tlsConfigured = configuration.tlsConfiguration.map { tlsConfiguration in
  232. channel.configureTLS(tlsConfiguration, errorDelegate: configuration.errorDelegate)
  233. }
  234. return (tlsConfigured ?? channel.eventLoop.makeSucceededFuture(())).flatMap {
  235. channel.configureHTTP2Pipeline(mode: .client)
  236. }.flatMap { _ in
  237. let errorHandler = DelegatingErrorHandler(delegate: configuration.errorDelegate)
  238. return channel.pipeline.addHandler(errorHandler)
  239. }
  240. }
  241. if let timeout = timeout {
  242. return bootstrap.connectTimeout(.seconds(timeInterval: timeout))
  243. } else {
  244. return bootstrap
  245. }
  246. }
  247. }
  248. // MARK: - Configuration structures
  249. /// A target to connect to.
  250. public enum ConnectionTarget {
  251. /// The host and port.
  252. case hostAndPort(String, Int)
  253. /// The path of a Unix domain socket.
  254. case unixDomainSocket(String)
  255. /// A NIO socket address.
  256. case socketAddress(SocketAddress)
  257. var host: String? {
  258. guard case .hostAndPort(let host, _) = self else {
  259. return nil
  260. }
  261. return host
  262. }
  263. }
  264. extension ClientConnection {
  265. /// The configuration for a connection.
  266. public struct Configuration {
  267. /// The target to connect to.
  268. public var target: ConnectionTarget
  269. /// The event loop group to run the connection on.
  270. public var eventLoopGroup: EventLoopGroup
  271. /// An error delegate which is called when errors are caught. Provided delegates **must not
  272. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  273. /// cycle.
  274. public var errorDelegate: ClientErrorDelegate?
  275. /// A delegate which is called when the connectivity state is changed.
  276. public var connectivityStateDelegate: ConnectivityStateDelegate?
  277. /// TLS configuration for this connection. `nil` if TLS is not desired.
  278. public var tlsConfiguration: TLSConfiguration?
  279. /// The connection backoff configuration. If no connection retrying is required then this should
  280. /// be `nil`.
  281. public var connectionBackoff: ConnectionBackoff?
  282. /// The HTTP protocol used for this connection.
  283. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  284. return self.tlsConfiguration == nil ? .http : .https
  285. }
  286. /// Create a `Configuration` with some pre-defined defaults.
  287. ///
  288. /// - Parameter target: The target to connect to.
  289. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  290. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  291. /// on debug builds.
  292. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  293. /// - Parameter tlsConfiguration: TLS configuration, defaulting to `nil`.
  294. /// - Parameter connectionBackoff: The connection backoff configuration to use, defaulting
  295. /// to `nil`.
  296. public init(
  297. target: ConnectionTarget,
  298. eventLoopGroup: EventLoopGroup,
  299. errorDelegate: ClientErrorDelegate? = DebugOnlyLoggingClientErrorDelegate.shared,
  300. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  301. tlsConfiguration: TLSConfiguration? = nil,
  302. connectionBackoff: ConnectionBackoff? = nil
  303. ) {
  304. self.target = target
  305. self.eventLoopGroup = eventLoopGroup
  306. self.errorDelegate = errorDelegate
  307. self.connectivityStateDelegate = connectivityStateDelegate
  308. self.tlsConfiguration = tlsConfiguration
  309. self.connectionBackoff = connectionBackoff
  310. }
  311. }
  312. /// The TLS configuration for a connection.
  313. public struct TLSConfiguration {
  314. /// The SSL context to use.
  315. public var sslContext: NIOSSLContext
  316. /// Value to use for TLS SNI extension; this must not be an IP address.
  317. public var hostnameOverride: String?
  318. public init(sslContext: NIOSSLContext, hostnameOverride: String? = nil) {
  319. self.sslContext = sslContext
  320. self.hostnameOverride = hostnameOverride
  321. }
  322. }
  323. }
  324. // MARK: - Configuration helpers/extensions
  325. fileprivate extension ClientBootstrapProtocol {
  326. /// Connect to the given connection target.
  327. ///
  328. /// - Parameter target: The target to connect to.
  329. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  330. switch target {
  331. case .hostAndPort(let host, let port):
  332. return self.connect(host: host, port: port)
  333. case .unixDomainSocket(let path):
  334. return self.connect(unixDomainSocketPath: path)
  335. case .socketAddress(let address):
  336. return self.connect(to: address)
  337. }
  338. }
  339. }
  340. fileprivate extension Channel {
  341. /// Configure the channel with TLS.
  342. ///
  343. /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and
  344. /// the `TLSVerificationHandler` which verifies that a successful handshake was completed.
  345. ///
  346. /// - Parameter configuration: The configuration to configure the channel with.
  347. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
  348. func configureTLS(
  349. _ configuration: ClientConnection.TLSConfiguration,
  350. errorDelegate: ClientErrorDelegate?
  351. ) -> EventLoopFuture<Void> {
  352. do {
  353. let sslClientHandler = try NIOSSLClientHandler(
  354. context: configuration.sslContext,
  355. serverHostname: configuration.hostnameOverride)
  356. return self.pipeline.addHandlers(sslClientHandler, TLSVerificationHandler())
  357. } catch {
  358. return self.eventLoop.makeFailedFuture(error)
  359. }
  360. }
  361. /// Returns the `verification` future from the `TLSVerificationHandler` in this channels pipeline.
  362. func verifyTLS() -> EventLoopFuture<Void> {
  363. return self.pipeline.handler(type: TLSVerificationHandler.self).flatMap {
  364. $0.verification
  365. }
  366. }
  367. }
  368. fileprivate extension TimeAmount {
  369. /// Creates a new `TimeAmount` from the given time interval in seconds.
  370. ///
  371. /// - Parameter timeInterval: The amount of time in seconds
  372. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  373. return .nanoseconds(TimeAmount.Value(timeInterval * 1_000_000_000))
  374. }
  375. }