ClientConnection.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 configuration this connection was created using.
  57. internal let configuration: ClientConnection.Configuration
  58. /// The channel which will handle gRPC calls.
  59. internal var channel: EventLoopFuture<Channel>
  60. /// HTTP multiplexer from the `channel` handling gRPC calls.
  61. internal var multiplexer: EventLoopFuture<HTTP2StreamMultiplexer>
  62. /// A monitor for the connectivity state.
  63. public let connectivity: ConnectivityStateMonitor
  64. /// Creates a new connection from the given configuration.
  65. public init(configuration: ClientConnection.Configuration) {
  66. let monitor = ConnectivityStateMonitor(delegate: configuration.connectivityStateDelegate)
  67. let channel = ClientConnection.makeChannel(
  68. configuration: configuration,
  69. connectivityMonitor: monitor
  70. )
  71. self.channel = channel
  72. self.multiplexer = channel.flatMap {
  73. $0.pipeline.handler(type: HTTP2StreamMultiplexer.self)
  74. }
  75. self.connectivity = monitor
  76. self.configuration = configuration
  77. self.channel.whenSuccess { _ in
  78. self.connectivity.state = .ready
  79. }
  80. self.replaceChannelAndMultiplexerOnClose(channel: channel)
  81. }
  82. /// Registers a callback on the `closeFuture` of the given channel to replace this class's
  83. /// channel and multiplexer.
  84. private func replaceChannelAndMultiplexerOnClose(channel: EventLoopFuture<Channel>) {
  85. channel.always { result in
  86. // If we failed to get a channel then we've exhausted our backoff; we should `.shutdown`.
  87. if case .failure = result {
  88. self.connectivity.state = .shutdown
  89. }
  90. }.flatMap {
  91. $0.closeFuture
  92. }.whenComplete { _ in
  93. // `.shutdown` is terminal so don't attempt a reconnection.
  94. guard self.connectivity.state != .shutdown else {
  95. return
  96. }
  97. let newChannel = ClientConnection.makeChannel(
  98. configuration: self.configuration,
  99. connectivityMonitor: self.connectivity
  100. )
  101. self.channel = newChannel
  102. self.multiplexer = newChannel.flatMap {
  103. $0.pipeline.handler(type: HTTP2StreamMultiplexer.self)
  104. }
  105. // Change the state if the connection was successful.
  106. newChannel.whenSuccess { _ in
  107. self.connectivity.state = .ready
  108. }
  109. self.replaceChannelAndMultiplexerOnClose(channel: newChannel)
  110. }
  111. }
  112. /// The `EventLoop` this connection is using.
  113. public var eventLoop: EventLoop {
  114. return self.channel.eventLoop
  115. }
  116. /// Closes the connection to the server.
  117. public func close() -> EventLoopFuture<Void> {
  118. if self.connectivity.state == .shutdown {
  119. // We're already shutdown or in the process of shutting down.
  120. return channel.flatMap { $0.closeFuture }
  121. } else {
  122. self.connectivity.state = .shutdown
  123. return channel.flatMap { $0.close() }
  124. }
  125. }
  126. }
  127. extension ClientConnection {
  128. /// Creates a `Channel` using the given configuration.
  129. ///
  130. /// This involves: creating a `ClientBootstrap`, connecting to a target and verifying that the TLS
  131. /// handshake was successful (if TLS was configured). We _may_ additiionally set a connection
  132. /// timeout and schedule a retry attempt (should the connection fail) if a
  133. /// `ConnectionBackoff.Iterator` is provided.
  134. ///
  135. /// See the individual functions for more information:
  136. /// - `makeBootstrap(configuration:)`, and
  137. /// - `verifyTLS(channel:)`.
  138. ///
  139. /// - Parameter configuration: The configuration to start the connection with.
  140. /// - Parameter connectivityMonitor: A connectivity state monitor.
  141. /// - Parameter backoffIterator: An `Iterator` for `ConnectionBackoff` providing a sequence of
  142. /// connection timeouts and backoff to use when attempting to create a connection.
  143. private class func makeChannel(
  144. configuration: ClientConnection.Configuration,
  145. connectivityMonitor: ConnectivityStateMonitor,
  146. backoffIterator: ConnectionBackoff.Iterator?
  147. ) -> EventLoopFuture<Channel> {
  148. connectivityMonitor.state = .connecting
  149. let timeoutAndBackoff = backoffIterator?.next()
  150. var bootstrap = ClientConnection.makeBootstrap(configuration: configuration)
  151. // Set a timeout, if we have one.
  152. if let timeout = timeoutAndBackoff?.timeout {
  153. bootstrap = bootstrap.connectTimeout(.seconds(timeInterval: timeout))
  154. }
  155. let channel = bootstrap.connect(to: configuration.target).flatMap { channel -> EventLoopFuture<Channel> in
  156. if configuration.tlsConfiguration != nil {
  157. return ClientConnection.verifyTLS(channel: channel).map { channel }
  158. } else {
  159. return channel.eventLoop.makeSucceededFuture(channel)
  160. }
  161. }.always { result in
  162. switch result {
  163. case .success:
  164. // Update the state once the channel has been assigned, when it may be used for making
  165. // RPCs.
  166. break
  167. case .failure:
  168. // We might try again in a moment.
  169. connectivityMonitor.state = timeoutAndBackoff == nil ? .shutdown : .transientFailure
  170. }
  171. }
  172. guard let backoff = timeoutAndBackoff?.backoff else {
  173. return channel
  174. }
  175. // If we're in error then schedule our next attempt.
  176. return channel.flatMapError { error in
  177. // The `futureResult` of the scheduled task is of type
  178. // `EventLoopFuture<EventLoopFuture<ClientConnection>>`, so we need to `flatMap` it to
  179. // remove a level of indirection.
  180. return channel.eventLoop.scheduleTask(in: .seconds(timeInterval: backoff)) {
  181. return makeChannel(
  182. configuration: configuration,
  183. connectivityMonitor: connectivityMonitor,
  184. backoffIterator: backoffIterator
  185. )
  186. }.futureResult.flatMap { nextConnection in
  187. return nextConnection
  188. }
  189. }
  190. }
  191. /// Creates a `Channel` using the given configuration amd state connectivity monitor.
  192. ///
  193. /// See `makeChannel(configuration:connectivityMonitor:backoffIterator:)`.
  194. private class func makeChannel(
  195. configuration: ClientConnection.Configuration,
  196. connectivityMonitor: ConnectivityStateMonitor
  197. ) -> EventLoopFuture<Channel> {
  198. return makeChannel(
  199. configuration: configuration,
  200. connectivityMonitor: connectivityMonitor,
  201. backoffIterator: configuration.connectionBackoff?.makeIterator()
  202. )
  203. }
  204. /// Makes and configures a `ClientBootstrap` using the provided configuration.
  205. ///
  206. /// Enables `SO_REUSEADDR` and `TCP_NODELAY` and configures the `channelInitializer` to use the
  207. /// handlers detailed in the documentation for `ClientConnection`.
  208. ///
  209. /// - Parameter configuration: The configuration to prepare the bootstrap with.
  210. private class func makeBootstrap(configuration: Configuration) -> ClientBootstrapProtocol {
  211. let bootstrap = GRPCNIO.makeClientBootstrap(group: configuration.eventLoopGroup)
  212. // Enable SO_REUSEADDR and TCP_NODELAY.
  213. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  214. .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  215. .channelInitializer { channel in
  216. let tlsConfigured = configuration.tlsConfiguration.map { tlsConfiguration in
  217. channel.configureTLS(tlsConfiguration, errorDelegate: configuration.errorDelegate)
  218. }
  219. return (tlsConfigured ?? channel.eventLoop.makeSucceededFuture(())).flatMap {
  220. channel.configureHTTP2Pipeline(mode: .client)
  221. }.flatMap { _ in
  222. let errorHandler = DelegatingErrorHandler(delegate: configuration.errorDelegate)
  223. return channel.pipeline.addHandler(errorHandler)
  224. }
  225. }
  226. return bootstrap
  227. }
  228. /// Verifies that a TLS handshake was successful by using the `TLSVerificationHandler`.
  229. ///
  230. /// - Parameter channel: The channel to verify successful TLS setup on.
  231. private class func verifyTLS(channel: Channel) -> EventLoopFuture<Void> {
  232. return channel.pipeline.handler(type: TLSVerificationHandler.self).flatMap {
  233. $0.verification
  234. }
  235. }
  236. }
  237. // MARK: - Configuration structures
  238. /// A target to connect to.
  239. public enum ConnectionTarget {
  240. /// The host and port.
  241. case hostAndPort(String, Int)
  242. /// The path of a Unix domain socket.
  243. case unixDomainSocket(String)
  244. /// A NIO socket address.
  245. case socketAddress(SocketAddress)
  246. var host: String? {
  247. guard case .hostAndPort(let host, _) = self else {
  248. return nil
  249. }
  250. return host
  251. }
  252. }
  253. extension ClientConnection {
  254. /// The configuration for a connection.
  255. public struct Configuration {
  256. /// The target to connect to.
  257. public var target: ConnectionTarget
  258. /// The event loop group to run the connection on.
  259. public var eventLoopGroup: EventLoopGroup
  260. /// An error delegate which is called when errors are caught. Provided delegates **must not
  261. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  262. /// cycle.
  263. public var errorDelegate: ClientErrorDelegate?
  264. /// A delegate which is called when the connectivity state is changed.
  265. public var connectivityStateDelegate: ConnectivityStateDelegate?
  266. /// TLS configuration for this connection. `nil` if TLS is not desired.
  267. public var tlsConfiguration: TLSConfiguration?
  268. /// The connection backoff configuration. If no connection retrying is required then this should
  269. /// be `nil`.
  270. public var connectionBackoff: ConnectionBackoff?
  271. /// The HTTP protocol used for this connection.
  272. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  273. return self.tlsConfiguration == nil ? .http : .https
  274. }
  275. /// Create a `Configuration` with some pre-defined defaults.
  276. ///
  277. /// - Parameter target: The target to connect to.
  278. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  279. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  280. /// on debug builds.
  281. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  282. /// - Parameter tlsConfiguration: TLS configuration, defaulting to `nil`.
  283. /// - Parameter connectionBackoff: The connection backoff configuration to use, defaulting
  284. /// to `nil`.
  285. public init(
  286. target: ConnectionTarget,
  287. eventLoopGroup: EventLoopGroup,
  288. errorDelegate: ClientErrorDelegate? = DebugOnlyLoggingClientErrorDelegate.shared,
  289. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  290. tlsConfiguration: TLSConfiguration? = nil,
  291. connectionBackoff: ConnectionBackoff? = nil
  292. ) {
  293. self.target = target
  294. self.eventLoopGroup = eventLoopGroup
  295. self.errorDelegate = errorDelegate
  296. self.connectivityStateDelegate = connectivityStateDelegate
  297. self.tlsConfiguration = tlsConfiguration
  298. self.connectionBackoff = connectionBackoff
  299. }
  300. }
  301. /// The TLS configuration for a connection.
  302. public struct TLSConfiguration {
  303. /// The SSL context to use.
  304. public var sslContext: NIOSSLContext
  305. /// Value to use for TLS SNI extension; this must not be an IP address.
  306. public var hostnameOverride: String?
  307. public init(sslContext: NIOSSLContext, hostnameOverride: String? = nil) {
  308. self.sslContext = sslContext
  309. self.hostnameOverride = hostnameOverride
  310. }
  311. }
  312. }
  313. // MARK: - Configuration helpers/extensions
  314. fileprivate extension ClientBootstrapProtocol {
  315. /// Connect to the given connection target.
  316. ///
  317. /// - Parameter target: The target to connect to.
  318. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  319. switch target {
  320. case .hostAndPort(let host, let port):
  321. return self.connect(host: host, port: port)
  322. case .unixDomainSocket(let path):
  323. return self.connect(unixDomainSocketPath: path)
  324. case .socketAddress(let address):
  325. return self.connect(to: address)
  326. }
  327. }
  328. }
  329. fileprivate extension Channel {
  330. /// Configure the channel with TLS.
  331. ///
  332. /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and
  333. /// the `TLSVerificationHandler` which verifies that a successful handshake was completed.
  334. ///
  335. /// - Parameter configuration: The configuration to configure the channel with.
  336. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
  337. func configureTLS(
  338. _ configuration: ClientConnection.TLSConfiguration,
  339. errorDelegate: ClientErrorDelegate?
  340. ) -> EventLoopFuture<Void> {
  341. do {
  342. let sslClientHandler = try NIOSSLClientHandler(
  343. context: configuration.sslContext,
  344. serverHostname: configuration.hostnameOverride)
  345. return self.pipeline.addHandlers(sslClientHandler, TLSVerificationHandler())
  346. } catch {
  347. return self.eventLoop.makeFailedFuture(error)
  348. }
  349. }
  350. }
  351. fileprivate extension TimeAmount {
  352. /// Creates a new `TimeAmount` from the given time interval in seconds.
  353. ///
  354. /// - Parameter timeInterval: The amount of time in seconds
  355. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  356. return .nanoseconds(TimeAmount.Value(timeInterval * 1_000_000_000))
  357. }
  358. }