ClientConnection.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 struct ConnectionTarget {
  201. internal enum Wrapped {
  202. case hostAndPort(String, Int)
  203. case unixDomainSocket(String)
  204. case socketAddress(SocketAddress)
  205. }
  206. internal var wrapped: Wrapped
  207. private init(_ wrapped: Wrapped) {
  208. self.wrapped = wrapped
  209. }
  210. /// The host and port.
  211. public static func hostAndPort(_ host: String, _ port: Int) -> ConnectionTarget {
  212. return ConnectionTarget(.hostAndPort(host, port))
  213. }
  214. /// The path of a Unix domain socket.
  215. public static func unixDomainSocket(_ path: String) -> ConnectionTarget {
  216. return ConnectionTarget(.unixDomainSocket(path))
  217. }
  218. /// A NIO socket address.
  219. public static func socketAddress(_ address: SocketAddress) -> ConnectionTarget {
  220. return ConnectionTarget(.socketAddress(address))
  221. }
  222. var host: String {
  223. switch self.wrapped {
  224. case .hostAndPort(let host, _):
  225. return host
  226. case .socketAddress(.v4(let address)):
  227. return address.host
  228. case .socketAddress(.v6(let address)):
  229. return address.host
  230. case .unixDomainSocket, .socketAddress(.unixDomainSocket):
  231. return "localhost"
  232. }
  233. }
  234. }
  235. extension ClientConnection {
  236. /// The configuration for a connection.
  237. public struct Configuration {
  238. /// The target to connect to.
  239. public var target: ConnectionTarget
  240. /// The event loop group to run the connection on.
  241. public var eventLoopGroup: EventLoopGroup
  242. /// An error delegate which is called when errors are caught. Provided delegates **must not
  243. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  244. /// cycle.
  245. public var errorDelegate: ClientErrorDelegate?
  246. /// A delegate which is called when the connectivity state is changed.
  247. public var connectivityStateDelegate: ConnectivityStateDelegate?
  248. /// The `DispatchQueue` on which to call the connectivity state delegate. If a delegate is
  249. /// provided but the queue is `nil` then one will be created by gRPC.
  250. public var connectivityStateDelegateQueue: DispatchQueue?
  251. /// TLS configuration for this connection. `nil` if TLS is not desired.
  252. public var tls: TLS?
  253. /// The connection backoff configuration. If no connection retrying is required then this should
  254. /// be `nil`.
  255. public var connectionBackoff: ConnectionBackoff?
  256. /// The amount of time to wait before closing the connection. The idle timeout will start only
  257. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  258. ///
  259. /// If a connection becomes idle, starting a new RPC will automatically create a new connection.
  260. public var connectionIdleTimeout: TimeAmount
  261. /// The HTTP/2 flow control target window size.
  262. public var httpTargetWindowSize: Int
  263. /// The HTTP protocol used for this connection.
  264. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  265. return self.tls == nil ? .http : .https
  266. }
  267. /// Create a `Configuration` with some pre-defined defaults. Prefer using
  268. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  269. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  270. ///
  271. /// - Parameter target: The target to connect to.
  272. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  273. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  274. /// on debug builds.
  275. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  276. /// - Parameter connectivityStateDelegateQueue: A `DispatchQueue` on which to call the
  277. /// `connectivityStateDelegate`.
  278. /// - Parameter tlsConfiguration: TLS configuration, defaulting to `nil`.
  279. /// - Parameter connectionBackoff: The connection backoff configuration to use.
  280. /// - Parameter messageEncoding: Message compression configuration, defaults to no compression.
  281. /// - Parameter targetWindowSize: The HTTP/2 flow control target window size.
  282. public init(
  283. target: ConnectionTarget,
  284. eventLoopGroup: EventLoopGroup,
  285. errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate(),
  286. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  287. connectivityStateDelegateQueue: DispatchQueue? = nil,
  288. tls: Configuration.TLS? = nil,
  289. connectionBackoff: ConnectionBackoff? = ConnectionBackoff(),
  290. connectionIdleTimeout: TimeAmount = .minutes(5),
  291. httpTargetWindowSize: Int = 65535
  292. ) {
  293. self.target = target
  294. self.eventLoopGroup = eventLoopGroup
  295. self.errorDelegate = errorDelegate
  296. self.connectivityStateDelegate = connectivityStateDelegate
  297. self.connectivityStateDelegateQueue = connectivityStateDelegateQueue
  298. self.tls = tls
  299. self.connectionBackoff = connectionBackoff
  300. self.connectionIdleTimeout = connectionIdleTimeout
  301. self.httpTargetWindowSize = httpTargetWindowSize
  302. }
  303. }
  304. }
  305. // MARK: - Configuration helpers/extensions
  306. extension ClientBootstrapProtocol {
  307. /// Connect to the given connection target.
  308. ///
  309. /// - Parameter target: The target to connect to.
  310. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  311. switch target.wrapped {
  312. case .hostAndPort(let host, let port):
  313. return self.connect(host: host, port: port)
  314. case .unixDomainSocket(let path):
  315. return self.connect(unixDomainSocketPath: path)
  316. case .socketAddress(let address):
  317. return self.connect(to: address)
  318. }
  319. }
  320. }
  321. extension Channel {
  322. /// Configure the channel with TLS.
  323. ///
  324. /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and
  325. /// the `TLSVerificationHandler` which verifies that a successful handshake was completed.
  326. ///
  327. /// - Parameter configuration: The configuration to configure the channel with.
  328. /// - Parameter serverHostname: The server hostname to use if the hostname should be verified.
  329. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
  330. func configureTLS(
  331. _ configuration: TLSConfiguration,
  332. serverHostname: String?,
  333. errorDelegate: ClientErrorDelegate?,
  334. logger: Logger
  335. ) -> EventLoopFuture<Void> {
  336. do {
  337. let sslClientHandler = try NIOSSLClientHandler(
  338. context: try NIOSSLContext(configuration: configuration),
  339. serverHostname: serverHostname
  340. )
  341. return self.pipeline.addHandlers(sslClientHandler, TLSVerificationHandler(logger: logger))
  342. } catch {
  343. return self.eventLoop.makeFailedFuture(error)
  344. }
  345. }
  346. func configureGRPCClient(
  347. httpTargetWindowSize: Int,
  348. tlsConfiguration: TLSConfiguration?,
  349. tlsServerHostname: String?,
  350. connectionManager: ConnectionManager,
  351. connectionIdleTimeout: TimeAmount,
  352. errorDelegate: ClientErrorDelegate?,
  353. logger: Logger
  354. ) -> EventLoopFuture<Void> {
  355. let tlsConfigured = tlsConfiguration.map {
  356. self.configureTLS($0, serverHostname: tlsServerHostname, errorDelegate: errorDelegate, logger: logger)
  357. }
  358. return (tlsConfigured ?? self.eventLoop.makeSucceededFuture(())).flatMap {
  359. self.configureHTTP2Pipeline(mode: .client, targetWindowSize: httpTargetWindowSize)
  360. }.flatMap { _ in
  361. return self.pipeline.handler(type: NIOHTTP2Handler.self).flatMap { http2Handler in
  362. self.pipeline.addHandler(
  363. GRPCIdleHandler(mode: .client(connectionManager), idleTimeout: connectionIdleTimeout),
  364. position: .after(http2Handler)
  365. )
  366. }.flatMap {
  367. let errorHandler = DelegatingErrorHandler(
  368. logger: logger,
  369. delegate: errorDelegate
  370. )
  371. return self.pipeline.addHandler(errorHandler)
  372. }
  373. }
  374. }
  375. func configureGRPCClient(
  376. errorDelegate: ClientErrorDelegate?,
  377. logger: Logger
  378. ) -> EventLoopFuture<Void> {
  379. return self.configureHTTP2Pipeline(mode: .client).flatMap { _ in
  380. self.pipeline.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  381. }
  382. }
  383. }
  384. extension TimeAmount {
  385. /// Creates a new `TimeAmount` from the given time interval in seconds.
  386. ///
  387. /// - Parameter timeInterval: The amount of time in seconds
  388. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  389. return .nanoseconds(Int64(timeInterval * 1_000_000_000))
  390. }
  391. }
  392. extension String {
  393. var isIPAddress: Bool {
  394. // We need some scratch space to let inet_pton write into.
  395. var ipv4Addr = in_addr()
  396. var ipv6Addr = in6_addr()
  397. return self.withCString { ptr in
  398. return inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
  399. inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
  400. }
  401. }
  402. }