ClientConnection.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. open class ClientConnection {
  56. /// Makes and configures a `ClientBootstrap` using the provided configuration.
  57. ///
  58. /// Enables `SO_REUSEADDR` and `TCP_NODELAY` and configures the `channelInitializer` to use the
  59. /// handlers detailed in the documentation for `ClientConnection`.
  60. ///
  61. /// - Parameter configuration: The configuration to prepare the bootstrap with.
  62. public class func makeBootstrap(configuration: Configuration) -> ClientBootstrapProtocol {
  63. let bootstrap = GRPCNIO.makeClientBootstrap(group: configuration.eventLoopGroup)
  64. // Enable SO_REUSEADDR and TCP_NODELAY.
  65. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  66. .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  67. .channelInitializer { channel in
  68. let tlsConfigured = configuration.tlsConfiguration.map { tlsConfiguration in
  69. channel.configureTLS(tlsConfiguration, errorDelegate: configuration.errorDelegate)
  70. }
  71. return (tlsConfigured ?? channel.eventLoop.makeSucceededFuture(())).flatMap {
  72. channel.configureHTTP2Pipeline(mode: .client)
  73. }.flatMap { _ in
  74. let errorHandler = DelegatingErrorHandler(delegate: configuration.errorDelegate)
  75. return channel.pipeline.addHandler(errorHandler)
  76. }
  77. }
  78. return bootstrap
  79. }
  80. /// Verifies that a TLS handshake was successful by using the `TLSVerificationHandler`.
  81. ///
  82. /// - Parameter channel: The channel to verify successful TLS setup on.
  83. public class func verifyTLS(channel: Channel) -> EventLoopFuture<Void> {
  84. return channel.pipeline.handler(type: TLSVerificationHandler.self).flatMap {
  85. $0.verification
  86. }
  87. }
  88. /// Makes a `ClientConnection` from the given channel and configuration.
  89. ///
  90. /// - Parameter channel: The channel to use for the connection.
  91. /// - Parameter configuration: The configuration used to create the channel.
  92. public class func makeClientConnection(
  93. channel: Channel,
  94. configuration: Configuration
  95. ) -> EventLoopFuture<ClientConnection> {
  96. return channel.pipeline.handler(type: HTTP2StreamMultiplexer.self).map { multiplexer in
  97. ClientConnection(channel: channel, multiplexer: multiplexer, configuration: configuration)
  98. }
  99. }
  100. /// Starts a client connection using the given configuration.
  101. ///
  102. /// This involves: creating a `ClientBootstrap`, connecting to a target, verifying that the TLS
  103. /// handshake was successful (if TLS was configured) and creating the `ClientConnection`.
  104. /// See the individual functions for more information:
  105. /// - `makeBootstrap(configuration:)`,
  106. /// - `verifyTLS(channel:)`, and
  107. /// - `makeClientConnection(channel:configuration:)`.
  108. ///
  109. /// - Parameter configuration: The configuration to start the connection with.
  110. public class func start(_ configuration: Configuration) -> EventLoopFuture<ClientConnection> {
  111. return start(configuration, backoffIterator: configuration.connectionBackoff?.makeIterator())
  112. }
  113. /// Starts a client connection using the given configuration and backoff.
  114. ///
  115. /// In addition to the steps taken in `start(configuration:)`, we _may_ additionally set a
  116. /// connection timeout and schedule a retry attempt (should the connection fail) if a
  117. /// `ConnectionBackoff.Iterator` is provided.
  118. ///
  119. /// - Parameter configuration: The configuration to start the connection with.
  120. /// - Parameter backoffIterator: A `ConnectionBackoff` iterator which generates connection
  121. /// timeouts and backoffs to use when attempting to retry the connection.
  122. internal class func start(
  123. _ configuration: Configuration,
  124. backoffIterator: ConnectionBackoff.Iterator?
  125. ) -> EventLoopFuture<ClientConnection> {
  126. let timeoutAndBackoff = backoffIterator?.next()
  127. var bootstrap = makeBootstrap(configuration: configuration)
  128. // Set a timeout, if we have one.
  129. if let timeout = timeoutAndBackoff?.timeout {
  130. bootstrap = bootstrap.connectTimeout(.seconds(timeInterval: timeout))
  131. }
  132. let connection = bootstrap.connect(to: configuration.target)
  133. .flatMap { channel -> EventLoopFuture<ClientConnection> in
  134. let tlsVerified: EventLoopFuture<Void>?
  135. if configuration.tlsConfiguration != nil {
  136. tlsVerified = verifyTLS(channel: channel)
  137. } else {
  138. tlsVerified = nil
  139. }
  140. return (tlsVerified ?? channel.eventLoop.makeSucceededFuture(())).flatMap {
  141. makeClientConnection(channel: channel, configuration: configuration)
  142. }
  143. }
  144. guard let backoff = timeoutAndBackoff?.backoff else {
  145. return connection
  146. }
  147. // If we're in error then schedule our next attempt.
  148. return connection.flatMapError { error in
  149. // The `futureResult` of the scheduled task is of type
  150. // `EventLoopFuture<EventLoopFuture<ClientConnection>>`, so we need to `flatMap` it to
  151. // remove a level of indirection.
  152. return connection.eventLoop.scheduleTask(in: .seconds(timeInterval: backoff)) {
  153. return start(configuration, backoffIterator: backoffIterator)
  154. }.futureResult.flatMap { nextConnection in
  155. return nextConnection
  156. }
  157. }
  158. }
  159. public let channel: Channel
  160. public let multiplexer: HTTP2StreamMultiplexer
  161. public let configuration: Configuration
  162. init(channel: Channel, multiplexer: HTTP2StreamMultiplexer, configuration: Configuration) {
  163. self.channel = channel
  164. self.multiplexer = multiplexer
  165. self.configuration = configuration
  166. }
  167. /// Fired when the client shuts down.
  168. public var onClose: EventLoopFuture<Void> {
  169. return channel.closeFuture
  170. }
  171. public func close() -> EventLoopFuture<Void> {
  172. return channel.close(mode: .all)
  173. }
  174. }
  175. // MARK: - Configuration structures
  176. /// A target to connect to.
  177. public enum ConnectionTarget {
  178. /// The host and port.
  179. case hostAndPort(String, Int)
  180. /// The path of a Unix domain socket.
  181. case unixDomainSocket(String)
  182. /// A NIO socket address.
  183. case socketAddress(SocketAddress)
  184. var host: String? {
  185. guard case .hostAndPort(let host, _) = self else {
  186. return nil
  187. }
  188. return host
  189. }
  190. }
  191. extension ClientConnection {
  192. /// The configuration for a connection.
  193. public struct Configuration {
  194. /// The target to connect to.
  195. public var target: ConnectionTarget
  196. /// The event loop group to run the connection on.
  197. public var eventLoopGroup: EventLoopGroup
  198. /// An error delegate which is called when errors are caught. Provided delegates **must not
  199. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  200. /// cycle.
  201. public var errorDelegate: ClientErrorDelegate?
  202. /// TLS configuration for this connection. `nil` if TLS is not desired.
  203. public var tlsConfiguration: TLSConfiguration?
  204. /// The connection backoff configuration. If no connection retrying is required then this should
  205. /// be `nil`.
  206. public var connectionBackoff: ConnectionBackoff?
  207. /// The HTTP protocol used for this connection.
  208. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  209. return self.tlsConfiguration == nil ? .http : .https
  210. }
  211. /// Create a `Configuration` with some pre-defined defaults.
  212. ///
  213. /// - Parameter target: The target to connect to.
  214. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  215. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  216. /// on debug builds.
  217. /// - Parameter tlsConfiguration: TLS configuration, defaulting to `nil`.
  218. /// - Parameter connectionBackoff: The connection backoff configuration to use, defaulting
  219. /// to `nil`.
  220. public init(
  221. target: ConnectionTarget,
  222. eventLoopGroup: EventLoopGroup,
  223. errorDelegate: ClientErrorDelegate? = DebugOnlyLoggingClientErrorDelegate.shared,
  224. tlsConfiguration: TLSConfiguration? = nil,
  225. connectionBackoff: ConnectionBackoff? = nil
  226. ) {
  227. self.target = target
  228. self.eventLoopGroup = eventLoopGroup
  229. self.errorDelegate = errorDelegate
  230. self.tlsConfiguration = tlsConfiguration
  231. self.connectionBackoff = connectionBackoff
  232. }
  233. }
  234. /// The TLS configuration for a connection.
  235. public struct TLSConfiguration {
  236. /// The SSL context to use.
  237. public var sslContext: NIOSSLContext
  238. /// Value to use for TLS SNI extension; this must not be an IP address.
  239. public var hostnameOverride: String?
  240. public init(sslContext: NIOSSLContext, hostnameOverride: String? = nil) {
  241. self.sslContext = sslContext
  242. self.hostnameOverride = hostnameOverride
  243. }
  244. }
  245. }
  246. // MARK: - Configuration helpers/extensions
  247. fileprivate extension ClientBootstrapProtocol {
  248. /// Connect to the given connection target.
  249. ///
  250. /// - Parameter target: The target to connect to.
  251. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  252. switch target {
  253. case .hostAndPort(let host, let port):
  254. return self.connect(host: host, port: port)
  255. case .unixDomainSocket(let path):
  256. return self.connect(unixDomainSocketPath: path)
  257. case .socketAddress(let address):
  258. return self.connect(to: address)
  259. }
  260. }
  261. }
  262. fileprivate extension Channel {
  263. /// Configure the channel with TLS.
  264. ///
  265. /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and
  266. /// the `TLSVerificationHandler` which verifies that a successful handshake was completed.
  267. ///
  268. /// - Parameter configuration: The configuration to configure the channel with.
  269. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
  270. func configureTLS(
  271. _ configuration: ClientConnection.TLSConfiguration,
  272. errorDelegate: ClientErrorDelegate?
  273. ) -> EventLoopFuture<Void> {
  274. do {
  275. let sslClientHandler = try NIOSSLClientHandler(
  276. context: configuration.sslContext,
  277. serverHostname: configuration.hostnameOverride)
  278. let verificationHandler = TLSVerificationHandler(errorDelegate: errorDelegate)
  279. return self.pipeline.addHandlers(sslClientHandler, verificationHandler)
  280. } catch {
  281. return self.eventLoop.makeFailedFuture(error)
  282. }
  283. }
  284. }
  285. fileprivate extension TimeAmount {
  286. /// Creates a new `TimeAmount` from the given time interval in seconds.
  287. ///
  288. /// - Parameter timeInterval: The amount of time in seconds
  289. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  290. return .nanoseconds(TimeAmount.Value(timeInterval * 1_000_000_000))
  291. }
  292. }