ClientConnection.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. /// Provides a single, managed connection to a server.
  23. ///
  24. /// The connection to the server is provided by a single channel which will attempt to reconnect
  25. /// to the server if the connection is dropped. This connection is guaranteed to always use the same
  26. /// event loop.
  27. ///
  28. /// The connection is initially setup with a handler to verify that TLS was established
  29. /// successfully (assuming TLS is being used).
  30. ///
  31. /// ┌──────────────────────────┐
  32. /// │ DelegatingErrorHandler │
  33. /// └──────────▲───────────────┘
  34. /// HTTP2Frame│
  35. /// ┌──────────┴───────────────┐
  36. /// │ SettingsObservingHandler │
  37. /// └──────────▲───────────────┘
  38. /// HTTP2Frame│
  39. /// │ ⠇ ⠇ ⠇ ⠇
  40. /// │ ┌┴─▼┐ ┌┴─▼┐
  41. /// │ │ | │ | HTTP/2 streams
  42. /// │ └▲─┬┘ └▲─┬┘
  43. /// │ │ │ │ │ HTTP2Frame
  44. /// ┌─┴────────────────┴─▼───┴─▼┐
  45. /// │ HTTP2StreamMultiplexer |
  46. /// └─▲───────────────────────┬─┘
  47. /// HTTP2Frame│ │HTTP2Frame
  48. /// ┌─┴───────────────────────▼─┐
  49. /// │ NIOHTTP2Handler │
  50. /// └─▲───────────────────────┬─┘
  51. /// ByteBuffer│ │ByteBuffer
  52. /// ┌─┴───────────────────────▼─┐
  53. /// │ TLSVerificationHandler │
  54. /// └─▲───────────────────────┬─┘
  55. /// ByteBuffer│ │ByteBuffer
  56. /// ┌─┴───────────────────────▼─┐
  57. /// │ NIOSSLHandler │
  58. /// └─▲───────────────────────┬─┘
  59. /// ByteBuffer│ │ByteBuffer
  60. /// │ ▼
  61. ///
  62. /// The `TLSVerificationHandler` observes the outcome of the SSL handshake and determines
  63. /// whether a `ClientConnection` should be returned to the user. In either eventuality, the
  64. /// handler removes itself from the pipeline once TLS has been verified. There is also a handler
  65. /// after the multiplexer for observing the initial settings frame, after which it determines that
  66. /// the connection state is `.ready` and removes itself from the channel. Finally there is a
  67. /// delegated error handler which uses the error delegate associated with this connection
  68. /// (see `DelegatingErrorHandler`).
  69. ///
  70. /// See `BaseClientCall` for a description of the pipelines associated with each HTTP/2 stream.
  71. public class ClientConnection {
  72. private let connectionManager: ConnectionManager
  73. /// HTTP multiplexer from the `channel` handling gRPC calls.
  74. internal var multiplexer: EventLoopFuture<HTTP2StreamMultiplexer> {
  75. return self.connectionManager.getChannel().flatMap {
  76. $0.pipeline.handler(type: HTTP2StreamMultiplexer.self)
  77. }
  78. }
  79. /// The configuration for this client.
  80. internal let configuration: Configuration
  81. internal let scheme: String
  82. internal let authority: String
  83. /// A monitor for the connectivity state.
  84. public var connectivity: ConnectivityStateMonitor {
  85. return self.connectionManager.monitor
  86. }
  87. /// The `EventLoop` this connection is using.
  88. public var eventLoop: EventLoop {
  89. return self.connectionManager.eventLoop
  90. }
  91. /// Creates a new connection from the given configuration. Prefer using
  92. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  93. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  94. ///
  95. /// - Important: Users should prefer using `ClientConnection.secure(group:)` to build a connection
  96. /// with TLS, or `ClientConnection.insecure(group:)` to build a connection without TLS.
  97. public init(configuration: Configuration) {
  98. self.configuration = configuration
  99. self.scheme = configuration.tls == nil ? "http" : "https"
  100. self.authority = configuration.target.host
  101. self.connectionManager = ConnectionManager(
  102. configuration: configuration,
  103. logger: Logger(subsystem: .clientChannel)
  104. )
  105. }
  106. /// Closes the connection to the server.
  107. public func close() -> EventLoopFuture<Void> {
  108. return self.connectionManager.shutdown()
  109. }
  110. private func loggerWithRequestID(_ requestID: String) -> Logger {
  111. var logger = self.connectionManager.logger
  112. logger[metadataKey: MetadataKey.requestID] = "\(requestID)"
  113. return logger
  114. }
  115. private func makeRequestHead(path: String, options: CallOptions, requestID: String) -> _GRPCRequestHead {
  116. return _GRPCRequestHead(
  117. scheme: self.scheme,
  118. path: path,
  119. host: self.authority,
  120. requestID: requestID,
  121. options: options
  122. )
  123. }
  124. }
  125. // Note: documentation is inherited.
  126. extension ClientConnection: GRPCChannel {
  127. public func makeUnaryCall<Request: GRPCPayload, Response: GRPCPayload>(
  128. path: String,
  129. request: Request,
  130. callOptions: CallOptions
  131. ) -> UnaryCall<Request, Response> where Request : GRPCPayload, Response : GRPCPayload {
  132. let requestID = callOptions.requestIDProvider.requestID()
  133. let logger = self.loggerWithRequestID(requestID)
  134. logger.debug("starting rpc", metadata: ["path": "\(path)"])
  135. let call = UnaryCall<Request, Response>.makeOnHTTP2Stream(
  136. multiplexer: self.multiplexer,
  137. callOptions: callOptions,
  138. errorDelegate: self.configuration.errorDelegate,
  139. logger: logger
  140. )
  141. call.send(self.makeRequestHead(path: path, options: callOptions, requestID: requestID), request: request)
  142. return call
  143. }
  144. public func makeClientStreamingCall<Request: GRPCPayload, Response: GRPCPayload>(
  145. path: String,
  146. callOptions: CallOptions
  147. ) -> ClientStreamingCall<Request, Response> {
  148. let requestID = callOptions.requestIDProvider.requestID()
  149. let logger = self.loggerWithRequestID(requestID)
  150. logger.debug("starting rpc", metadata: ["path": "\(path)"])
  151. let call = ClientStreamingCall<Request, Response>.makeOnHTTP2Stream(
  152. multiplexer: self.multiplexer,
  153. callOptions: callOptions,
  154. errorDelegate: self.configuration.errorDelegate,
  155. logger: logger
  156. )
  157. call.sendHead(self.makeRequestHead(path: path, options: callOptions, requestID: requestID))
  158. return call
  159. }
  160. public func makeServerStreamingCall<Request: GRPCPayload, Response: GRPCPayload>(
  161. path: String,
  162. request: Request,
  163. callOptions: CallOptions,
  164. handler: @escaping (Response) -> Void
  165. ) -> ServerStreamingCall<Request, Response> {
  166. let requestID = callOptions.requestIDProvider.requestID()
  167. let logger = self.loggerWithRequestID(requestID)
  168. logger.debug("starting rpc", metadata: ["path": "\(path)"])
  169. let call = ServerStreamingCall<Request, Response>.makeOnHTTP2Stream(
  170. multiplexer: multiplexer,
  171. callOptions: callOptions,
  172. errorDelegate: self.configuration.errorDelegate,
  173. logger: logger,
  174. responseHandler: handler
  175. )
  176. call.send(self.makeRequestHead(path: path, options: callOptions, requestID: requestID), request: request)
  177. return call
  178. }
  179. public func makeBidirectionalStreamingCall<Request: GRPCPayload, Response: GRPCPayload>(
  180. path: String,
  181. callOptions: CallOptions,
  182. handler: @escaping (Response) -> Void
  183. ) -> BidirectionalStreamingCall<Request, Response> {
  184. let requestID = callOptions.requestIDProvider.requestID()
  185. let logger = self.loggerWithRequestID(requestID)
  186. logger.debug("starting rpc", metadata: ["path": "\(path)"])
  187. let call = BidirectionalStreamingCall<Request, Response>.makeOnHTTP2Stream(
  188. multiplexer: multiplexer,
  189. callOptions: callOptions,
  190. errorDelegate: self.configuration.errorDelegate,
  191. logger: logger,
  192. responseHandler: handler
  193. )
  194. call.sendHead(self.makeRequestHead(path: path, options: callOptions, requestID: requestID))
  195. return call
  196. }
  197. }
  198. // MARK: - Configuration structures
  199. /// A target to connect to.
  200. public enum ConnectionTarget {
  201. /// The host and port.
  202. case hostAndPort(String, Int)
  203. /// The path of a Unix domain socket.
  204. case unixDomainSocket(String)
  205. /// A NIO socket address.
  206. case socketAddress(SocketAddress)
  207. var host: String {
  208. switch self {
  209. case .hostAndPort(let host, _):
  210. return host
  211. case .socketAddress(.v4(let address)):
  212. return address.host
  213. case .socketAddress(.v6(let address)):
  214. return address.host
  215. case .unixDomainSocket, .socketAddress(.unixDomainSocket):
  216. return "localhost"
  217. }
  218. }
  219. }
  220. extension ClientConnection {
  221. /// The configuration for a connection.
  222. public struct Configuration {
  223. /// The target to connect to.
  224. public var target: ConnectionTarget
  225. /// The event loop group to run the connection on.
  226. public var eventLoopGroup: EventLoopGroup
  227. /// An error delegate which is called when errors are caught. Provided delegates **must not
  228. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  229. /// cycle.
  230. public var errorDelegate: ClientErrorDelegate?
  231. /// A delegate which is called when the connectivity state is changed.
  232. public var connectivityStateDelegate: ConnectivityStateDelegate?
  233. /// The `DispatchQueue` on which to call the connectivity state delegate. If a delegate is
  234. /// provided but the queue is `nil` then one will be created by gRPC.
  235. public var connectivityStateDelegateQueue: DispatchQueue?
  236. /// TLS configuration for this connection. `nil` if TLS is not desired.
  237. public var tls: TLS?
  238. /// The connection backoff configuration. If no connection retrying is required then this should
  239. /// be `nil`.
  240. public var connectionBackoff: ConnectionBackoff?
  241. /// The amount of time to wait before closing the connection. The idle timeout will start only
  242. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  243. ///
  244. /// If a connection becomes idle, starting a new RPC will automatically create a new connection.
  245. public var connectionIdleTimeout: TimeAmount
  246. /// The HTTP/2 flow control target window size.
  247. public var httpTargetWindowSize: Int
  248. /// The HTTP protocol used for this connection.
  249. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  250. return self.tls == nil ? .http : .https
  251. }
  252. /// Create a `Configuration` with some pre-defined defaults. Prefer using
  253. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  254. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  255. ///
  256. /// - Parameter target: The target to connect to.
  257. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  258. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  259. /// on debug builds.
  260. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  261. /// - Parameter connectivityStateDelegateQueue: A `DispatchQueue` on which to call the
  262. /// `connectivityStateDelegate`.
  263. /// - Parameter tlsConfiguration: TLS configuration, defaulting to `nil`.
  264. /// - Parameter connectionBackoff: The connection backoff configuration to use.
  265. /// - Parameter messageEncoding: Message compression configuration, defaults to no compression.
  266. /// - Parameter targetWindowSize: The HTTP/2 flow control target window size.
  267. public init(
  268. target: ConnectionTarget,
  269. eventLoopGroup: EventLoopGroup,
  270. errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate(),
  271. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  272. connectivityStateDelegateQueue: DispatchQueue? = nil,
  273. tls: Configuration.TLS? = nil,
  274. connectionBackoff: ConnectionBackoff? = ConnectionBackoff(),
  275. connectionIdleTimeout: TimeAmount = .minutes(5),
  276. httpTargetWindowSize: Int = 65535
  277. ) {
  278. self.target = target
  279. self.eventLoopGroup = eventLoopGroup
  280. self.errorDelegate = errorDelegate
  281. self.connectivityStateDelegate = connectivityStateDelegate
  282. self.connectivityStateDelegateQueue = connectivityStateDelegateQueue
  283. self.tls = tls
  284. self.connectionBackoff = connectionBackoff
  285. self.connectionIdleTimeout = connectionIdleTimeout
  286. self.httpTargetWindowSize = httpTargetWindowSize
  287. }
  288. }
  289. }
  290. // MARK: - Configuration helpers/extensions
  291. extension ClientBootstrapProtocol {
  292. /// Connect to the given connection target.
  293. ///
  294. /// - Parameter target: The target to connect to.
  295. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  296. switch target {
  297. case .hostAndPort(let host, let port):
  298. return self.connect(host: host, port: port)
  299. case .unixDomainSocket(let path):
  300. return self.connect(unixDomainSocketPath: path)
  301. case .socketAddress(let address):
  302. return self.connect(to: address)
  303. }
  304. }
  305. }
  306. extension Channel {
  307. /// Configure the channel with TLS.
  308. ///
  309. /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and
  310. /// the `TLSVerificationHandler` which verifies that a successful handshake was completed.
  311. ///
  312. /// - Parameter configuration: The configuration to configure the channel with.
  313. /// - Parameter serverHostname: The server hostname to use if the hostname should be verified.
  314. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
  315. func configureTLS(
  316. _ configuration: TLSConfiguration,
  317. serverHostname: String?,
  318. errorDelegate: ClientErrorDelegate?,
  319. logger: Logger
  320. ) -> EventLoopFuture<Void> {
  321. do {
  322. let sslClientHandler = try NIOSSLClientHandler(
  323. context: try NIOSSLContext(configuration: configuration),
  324. serverHostname: serverHostname
  325. )
  326. return self.pipeline.addHandlers(sslClientHandler, TLSVerificationHandler(logger: logger))
  327. } catch {
  328. return self.eventLoop.makeFailedFuture(error)
  329. }
  330. }
  331. func configureGRPCClient(
  332. httpTargetWindowSize: Int,
  333. tlsConfiguration: TLSConfiguration?,
  334. tlsServerHostname: String?,
  335. connectionManager: ConnectionManager,
  336. connectionIdleTimeout: TimeAmount,
  337. errorDelegate: ClientErrorDelegate?,
  338. logger: Logger
  339. ) -> EventLoopFuture<Void> {
  340. let tlsConfigured = tlsConfiguration.map {
  341. self.configureTLS($0, serverHostname: tlsServerHostname, errorDelegate: errorDelegate, logger: logger)
  342. }
  343. return (tlsConfigured ?? self.eventLoop.makeSucceededFuture(())).flatMap {
  344. self.configureHTTP2Pipeline(mode: .client, targetWindowSize: httpTargetWindowSize)
  345. }.flatMap { _ in
  346. return self.pipeline.handler(type: NIOHTTP2Handler.self).flatMap { http2Handler in
  347. self.pipeline.addHandler(
  348. GRPCIdleHandler(mode: .client(connectionManager), idleTimeout: connectionIdleTimeout),
  349. position: .after(http2Handler)
  350. )
  351. }.flatMap {
  352. let errorHandler = DelegatingErrorHandler(
  353. logger: logger,
  354. delegate: errorDelegate
  355. )
  356. return self.pipeline.addHandler(errorHandler)
  357. }
  358. }
  359. }
  360. func configureGRPCClient(
  361. errorDelegate: ClientErrorDelegate?,
  362. logger: Logger
  363. ) -> EventLoopFuture<Void> {
  364. return self.configureHTTP2Pipeline(mode: .client).flatMap { _ in
  365. self.pipeline.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  366. }
  367. }
  368. }
  369. extension TimeAmount {
  370. /// Creates a new `TimeAmount` from the given time interval in seconds.
  371. ///
  372. /// - Parameter timeInterval: The amount of time in seconds
  373. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  374. return .nanoseconds(Int64(timeInterval * 1_000_000_000))
  375. }
  376. }
  377. extension String {
  378. var isIPAddress: Bool {
  379. // We need some scratch space to let inet_pton write into.
  380. var ipv4Addr = in_addr()
  381. var ipv6Addr = in6_addr()
  382. return self.withCString { ptr in
  383. return inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
  384. inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
  385. }
  386. }
  387. }