ClientConnection.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. // We could have been shutdown by the user, avoid a connection attempt if this is the case.
  149. guard connectivityMonitor.state != .shutdown else {
  150. return configuration.eventLoopGroup.next().makeFailedFuture(GRPCStatus.processingError)
  151. }
  152. connectivityMonitor.state = .connecting
  153. let timeoutAndBackoff = backoffIterator?.next()
  154. var bootstrap = ClientConnection.makeBootstrap(configuration: configuration)
  155. // Set a timeout, if we have one.
  156. if let timeout = timeoutAndBackoff?.timeout {
  157. bootstrap = bootstrap.connectTimeout(.seconds(timeInterval: timeout))
  158. }
  159. let channel = bootstrap.connect(to: configuration.target).flatMap { channel -> EventLoopFuture<Channel> in
  160. if configuration.tlsConfiguration != nil {
  161. return ClientConnection.verifyTLS(channel: channel).map { channel }
  162. } else {
  163. return channel.eventLoop.makeSucceededFuture(channel)
  164. }
  165. }
  166. channel.whenFailure { _ in
  167. // We could have been shutdown by the user whilst we were connecting. If we were then avoid
  168. // the this extra state transition.
  169. if connectivityMonitor.state != .shutdown {
  170. // We might try again in a moment.
  171. connectivityMonitor.state = timeoutAndBackoff == nil ? .shutdown : .transientFailure
  172. }
  173. }
  174. guard let backoff = timeoutAndBackoff?.backoff else {
  175. return channel
  176. }
  177. // If we're in error then schedule our next attempt.
  178. return channel.flatMapError { error in
  179. // The `futureResult` of the scheduled task is of type
  180. // `EventLoopFuture<EventLoopFuture<ClientConnection>>`, so we need to `flatMap` it to
  181. // remove a level of indirection.
  182. return channel.eventLoop.scheduleTask(in: .seconds(timeInterval: backoff)) {
  183. return makeChannel(
  184. configuration: configuration,
  185. connectivityMonitor: connectivityMonitor,
  186. backoffIterator: backoffIterator
  187. )
  188. }.futureResult.flatMap { nextConnection in
  189. return nextConnection
  190. }
  191. }
  192. }
  193. /// Creates a `Channel` using the given configuration amd state connectivity monitor.
  194. ///
  195. /// See `makeChannel(configuration:connectivityMonitor:backoffIterator:)`.
  196. private class func makeChannel(
  197. configuration: ClientConnection.Configuration,
  198. connectivityMonitor: ConnectivityStateMonitor
  199. ) -> EventLoopFuture<Channel> {
  200. return makeChannel(
  201. configuration: configuration,
  202. connectivityMonitor: connectivityMonitor,
  203. backoffIterator: configuration.connectionBackoff?.makeIterator()
  204. )
  205. }
  206. /// Makes and configures a `ClientBootstrap` using the provided configuration.
  207. ///
  208. /// Enables `SO_REUSEADDR` and `TCP_NODELAY` and configures the `channelInitializer` to use the
  209. /// handlers detailed in the documentation for `ClientConnection`.
  210. ///
  211. /// - Parameter configuration: The configuration to prepare the bootstrap with.
  212. private class func makeBootstrap(configuration: Configuration) -> ClientBootstrapProtocol {
  213. let bootstrap = GRPCNIO.makeClientBootstrap(group: configuration.eventLoopGroup)
  214. // Enable SO_REUSEADDR and TCP_NODELAY.
  215. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  216. .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  217. .channelInitializer { channel in
  218. let tlsConfigured = configuration.tlsConfiguration.map { tlsConfiguration in
  219. channel.configureTLS(tlsConfiguration, errorDelegate: configuration.errorDelegate)
  220. }
  221. return (tlsConfigured ?? channel.eventLoop.makeSucceededFuture(())).flatMap {
  222. channel.configureHTTP2Pipeline(mode: .client)
  223. }.flatMap { _ in
  224. let errorHandler = DelegatingErrorHandler(delegate: configuration.errorDelegate)
  225. return channel.pipeline.addHandler(errorHandler)
  226. }
  227. }
  228. return bootstrap
  229. }
  230. /// Verifies that a TLS handshake was successful by using the `TLSVerificationHandler`.
  231. ///
  232. /// - Parameter channel: The channel to verify successful TLS setup on.
  233. private class func verifyTLS(channel: Channel) -> EventLoopFuture<Void> {
  234. return channel.pipeline.handler(type: TLSVerificationHandler.self).flatMap {
  235. $0.verification
  236. }
  237. }
  238. }
  239. // MARK: - Configuration structures
  240. /// A target to connect to.
  241. public enum ConnectionTarget {
  242. /// The host and port.
  243. case hostAndPort(String, Int)
  244. /// The path of a Unix domain socket.
  245. case unixDomainSocket(String)
  246. /// A NIO socket address.
  247. case socketAddress(SocketAddress)
  248. var host: String? {
  249. guard case .hostAndPort(let host, _) = self else {
  250. return nil
  251. }
  252. return host
  253. }
  254. }
  255. extension ClientConnection {
  256. /// The configuration for a connection.
  257. public struct Configuration {
  258. /// The target to connect to.
  259. public var target: ConnectionTarget
  260. /// The event loop group to run the connection on.
  261. public var eventLoopGroup: EventLoopGroup
  262. /// An error delegate which is called when errors are caught. Provided delegates **must not
  263. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  264. /// cycle.
  265. public var errorDelegate: ClientErrorDelegate?
  266. /// A delegate which is called when the connectivity state is changed.
  267. public var connectivityStateDelegate: ConnectivityStateDelegate?
  268. /// TLS configuration for this connection. `nil` if TLS is not desired.
  269. public var tlsConfiguration: TLSConfiguration?
  270. /// The connection backoff configuration. If no connection retrying is required then this should
  271. /// be `nil`.
  272. public var connectionBackoff: ConnectionBackoff?
  273. /// The HTTP protocol used for this connection.
  274. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  275. return self.tlsConfiguration == nil ? .http : .https
  276. }
  277. /// Create a `Configuration` with some pre-defined defaults.
  278. ///
  279. /// - Parameter target: The target to connect to.
  280. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  281. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  282. /// on debug builds.
  283. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  284. /// - Parameter tlsConfiguration: TLS configuration, defaulting to `nil`.
  285. /// - Parameter connectionBackoff: The connection backoff configuration to use, defaulting
  286. /// to `nil`.
  287. public init(
  288. target: ConnectionTarget,
  289. eventLoopGroup: EventLoopGroup,
  290. errorDelegate: ClientErrorDelegate? = DebugOnlyLoggingClientErrorDelegate.shared,
  291. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  292. tlsConfiguration: TLSConfiguration? = nil,
  293. connectionBackoff: ConnectionBackoff? = nil
  294. ) {
  295. self.target = target
  296. self.eventLoopGroup = eventLoopGroup
  297. self.errorDelegate = errorDelegate
  298. self.connectivityStateDelegate = connectivityStateDelegate
  299. self.tlsConfiguration = tlsConfiguration
  300. self.connectionBackoff = connectionBackoff
  301. }
  302. }
  303. /// The TLS configuration for a connection.
  304. public struct TLSConfiguration {
  305. /// The SSL context to use.
  306. public var sslContext: NIOSSLContext
  307. /// Value to use for TLS SNI extension; this must not be an IP address.
  308. public var hostnameOverride: String?
  309. public init(sslContext: NIOSSLContext, hostnameOverride: String? = nil) {
  310. self.sslContext = sslContext
  311. self.hostnameOverride = hostnameOverride
  312. }
  313. }
  314. }
  315. // MARK: - Configuration helpers/extensions
  316. fileprivate extension ClientBootstrapProtocol {
  317. /// Connect to the given connection target.
  318. ///
  319. /// - Parameter target: The target to connect to.
  320. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  321. switch target {
  322. case .hostAndPort(let host, let port):
  323. return self.connect(host: host, port: port)
  324. case .unixDomainSocket(let path):
  325. return self.connect(unixDomainSocketPath: path)
  326. case .socketAddress(let address):
  327. return self.connect(to: address)
  328. }
  329. }
  330. }
  331. fileprivate extension Channel {
  332. /// Configure the channel with TLS.
  333. ///
  334. /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and
  335. /// the `TLSVerificationHandler` which verifies that a successful handshake was completed.
  336. ///
  337. /// - Parameter configuration: The configuration to configure the channel with.
  338. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
  339. func configureTLS(
  340. _ configuration: ClientConnection.TLSConfiguration,
  341. errorDelegate: ClientErrorDelegate?
  342. ) -> EventLoopFuture<Void> {
  343. do {
  344. let sslClientHandler = try NIOSSLClientHandler(
  345. context: configuration.sslContext,
  346. serverHostname: configuration.hostnameOverride)
  347. return self.pipeline.addHandlers(sslClientHandler, TLSVerificationHandler())
  348. } catch {
  349. return self.eventLoop.makeFailedFuture(error)
  350. }
  351. }
  352. }
  353. fileprivate extension TimeAmount {
  354. /// Creates a new `TimeAmount` from the given time interval in seconds.
  355. ///
  356. /// - Parameter timeInterval: The amount of time in seconds
  357. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  358. return .nanoseconds(TimeAmount.Value(timeInterval * 1_000_000_000))
  359. }
  360. }