2
0

ClientConnection.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. }
  111. // Note: documentation is inherited.
  112. extension ClientConnection: GRPCChannel {
  113. public func makeUnaryCall<Request: GRPCPayload, Response: GRPCPayload>(
  114. path: String,
  115. request: Request,
  116. callOptions: CallOptions
  117. ) -> UnaryCall<Request, Response> where Request : GRPCPayload, Response : GRPCPayload {
  118. return UnaryCall(
  119. path: path,
  120. scheme: self.scheme,
  121. authority: self.authority,
  122. callOptions: callOptions,
  123. eventLoop: self.eventLoop,
  124. multiplexer: self.multiplexer,
  125. errorDelegate: self.configuration.errorDelegate,
  126. logger: self.connectionManager.logger,
  127. request: request
  128. )
  129. }
  130. public func makeClientStreamingCall<Request: GRPCPayload, Response: GRPCPayload>(
  131. path: String,
  132. callOptions: CallOptions
  133. ) -> ClientStreamingCall<Request, Response> {
  134. return ClientStreamingCall(
  135. path: path,
  136. scheme: self.scheme,
  137. authority: self.authority,
  138. callOptions: callOptions,
  139. eventLoop: self.eventLoop,
  140. multiplexer: self.multiplexer,
  141. errorDelegate: self.configuration.errorDelegate,
  142. logger: self.connectionManager.logger
  143. )
  144. }
  145. public func makeServerStreamingCall<Request: GRPCPayload, Response: GRPCPayload>(
  146. path: String,
  147. request: Request,
  148. callOptions: CallOptions,
  149. handler: @escaping (Response) -> Void
  150. ) -> ServerStreamingCall<Request, Response> {
  151. return ServerStreamingCall(
  152. path: path,
  153. scheme: self.scheme,
  154. authority: self.authority,
  155. callOptions: callOptions,
  156. eventLoop: self.eventLoop,
  157. multiplexer: self.multiplexer,
  158. errorDelegate: self.configuration.errorDelegate,
  159. logger: self.connectionManager.logger,
  160. request: request,
  161. handler: handler
  162. )
  163. }
  164. public func makeBidirectionalStreamingCall<Request: GRPCPayload, Response: GRPCPayload>(
  165. path: String,
  166. callOptions: CallOptions,
  167. handler: @escaping (Response) -> Void
  168. ) -> BidirectionalStreamingCall<Request, Response> {
  169. return BidirectionalStreamingCall(
  170. path: path,
  171. scheme: self.scheme,
  172. authority: self.authority,
  173. callOptions: callOptions,
  174. eventLoop: self.eventLoop,
  175. multiplexer: self.multiplexer,
  176. errorDelegate: self.configuration.errorDelegate,
  177. logger: self.connectionManager.logger,
  178. handler: handler
  179. )
  180. }
  181. }
  182. // MARK: - Configuration structures
  183. /// A target to connect to.
  184. public enum ConnectionTarget {
  185. /// The host and port.
  186. case hostAndPort(String, Int)
  187. /// The path of a Unix domain socket.
  188. case unixDomainSocket(String)
  189. /// A NIO socket address.
  190. case socketAddress(SocketAddress)
  191. var host: String {
  192. switch self {
  193. case .hostAndPort(let host, _):
  194. return host
  195. case .socketAddress(.v4(let address)):
  196. return address.host
  197. case .socketAddress(.v6(let address)):
  198. return address.host
  199. case .unixDomainSocket, .socketAddress(.unixDomainSocket):
  200. return "localhost"
  201. }
  202. }
  203. }
  204. extension ClientConnection {
  205. /// The configuration for a connection.
  206. public struct Configuration {
  207. /// The target to connect to.
  208. public var target: ConnectionTarget
  209. /// The event loop group to run the connection on.
  210. public var eventLoopGroup: EventLoopGroup
  211. /// An error delegate which is called when errors are caught. Provided delegates **must not
  212. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  213. /// cycle.
  214. public var errorDelegate: ClientErrorDelegate?
  215. /// A delegate which is called when the connectivity state is changed.
  216. public var connectivityStateDelegate: ConnectivityStateDelegate?
  217. /// The `DispatchQueue` on which to call the connectivity state delegate. If a delegate is
  218. /// provided but the queue is `nil` then one will be created by gRPC.
  219. public var connectivityStateDelegateQueue: DispatchQueue?
  220. /// TLS configuration for this connection. `nil` if TLS is not desired.
  221. public var tls: TLS?
  222. /// The connection backoff configuration. If no connection retrying is required then this should
  223. /// be `nil`.
  224. public var connectionBackoff: ConnectionBackoff?
  225. /// The amount of time to wait before closing the connection. The idle timeout will start only
  226. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  227. ///
  228. /// If a connection becomes idle, starting a new RPC will automatically create a new connection.
  229. public var connectionIdleTimeout: TimeAmount
  230. /// The HTTP/2 flow control target window size.
  231. public var httpTargetWindowSize: Int
  232. /// The HTTP protocol used for this connection.
  233. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  234. return self.tls == nil ? .http : .https
  235. }
  236. /// Create a `Configuration` with some pre-defined defaults. Prefer using
  237. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  238. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  239. ///
  240. /// - Parameter target: The target to connect to.
  241. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  242. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  243. /// on debug builds.
  244. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  245. /// - Parameter connectivityStateDelegateQueue: A `DispatchQueue` on which to call the
  246. /// `connectivityStateDelegate`.
  247. /// - Parameter tlsConfiguration: TLS configuration, defaulting to `nil`.
  248. /// - Parameter connectionBackoff: The connection backoff configuration to use.
  249. /// - Parameter messageEncoding: Message compression configuration, defaults to no compression.
  250. /// - Parameter targetWindowSize: The HTTP/2 flow control target window size.
  251. public init(
  252. target: ConnectionTarget,
  253. eventLoopGroup: EventLoopGroup,
  254. errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate(),
  255. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  256. connectivityStateDelegateQueue: DispatchQueue? = nil,
  257. tls: Configuration.TLS? = nil,
  258. connectionBackoff: ConnectionBackoff? = ConnectionBackoff(),
  259. connectionIdleTimeout: TimeAmount = .minutes(5),
  260. httpTargetWindowSize: Int = 65535
  261. ) {
  262. self.target = target
  263. self.eventLoopGroup = eventLoopGroup
  264. self.errorDelegate = errorDelegate
  265. self.connectivityStateDelegate = connectivityStateDelegate
  266. self.connectivityStateDelegateQueue = connectivityStateDelegateQueue
  267. self.tls = tls
  268. self.connectionBackoff = connectionBackoff
  269. self.connectionIdleTimeout = connectionIdleTimeout
  270. self.httpTargetWindowSize = httpTargetWindowSize
  271. }
  272. }
  273. }
  274. // MARK: - Configuration helpers/extensions
  275. extension ClientBootstrapProtocol {
  276. /// Connect to the given connection target.
  277. ///
  278. /// - Parameter target: The target to connect to.
  279. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  280. switch target {
  281. case .hostAndPort(let host, let port):
  282. return self.connect(host: host, port: port)
  283. case .unixDomainSocket(let path):
  284. return self.connect(unixDomainSocketPath: path)
  285. case .socketAddress(let address):
  286. return self.connect(to: address)
  287. }
  288. }
  289. }
  290. extension Channel {
  291. /// Configure the channel with TLS.
  292. ///
  293. /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and
  294. /// the `TLSVerificationHandler` which verifies that a successful handshake was completed.
  295. ///
  296. /// - Parameter configuration: The configuration to configure the channel with.
  297. /// - Parameter serverHostname: The server hostname to use if the hostname should be verified.
  298. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
  299. func configureTLS(
  300. _ configuration: TLSConfiguration,
  301. serverHostname: String?,
  302. errorDelegate: ClientErrorDelegate?,
  303. logger: Logger
  304. ) -> EventLoopFuture<Void> {
  305. do {
  306. let sslClientHandler = try NIOSSLClientHandler(
  307. context: try NIOSSLContext(configuration: configuration),
  308. serverHostname: serverHostname
  309. )
  310. return self.pipeline.addHandlers(sslClientHandler, TLSVerificationHandler(logger: logger))
  311. } catch {
  312. return self.eventLoop.makeFailedFuture(error)
  313. }
  314. }
  315. func configureGRPCClient(
  316. httpTargetWindowSize: Int,
  317. tlsConfiguration: TLSConfiguration?,
  318. tlsServerHostname: String?,
  319. connectionManager: ConnectionManager,
  320. connectionIdleTimeout: TimeAmount,
  321. errorDelegate: ClientErrorDelegate?,
  322. logger: Logger
  323. ) -> EventLoopFuture<Void> {
  324. let tlsConfigured = tlsConfiguration.map {
  325. self.configureTLS($0, serverHostname: tlsServerHostname, errorDelegate: errorDelegate, logger: logger)
  326. }
  327. return (tlsConfigured ?? self.eventLoop.makeSucceededFuture(())).flatMap {
  328. self.configureHTTP2Pipeline(mode: .client, targetWindowSize: httpTargetWindowSize)
  329. }.flatMap { _ in
  330. return self.pipeline.handler(type: NIOHTTP2Handler.self).flatMap { http2Handler in
  331. self.pipeline.addHandler(
  332. GRPCIdleHandler(mode: .client(connectionManager), idleTimeout: connectionIdleTimeout),
  333. position: .after(http2Handler)
  334. )
  335. }.flatMap {
  336. let errorHandler = DelegatingErrorHandler(
  337. logger: logger,
  338. delegate: errorDelegate
  339. )
  340. return self.pipeline.addHandler(errorHandler)
  341. }
  342. }
  343. }
  344. func configureGRPCClient(
  345. errorDelegate: ClientErrorDelegate?,
  346. logger: Logger
  347. ) -> EventLoopFuture<Void> {
  348. return self.configureHTTP2Pipeline(mode: .client).flatMap { _ in
  349. self.pipeline.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  350. }
  351. }
  352. }
  353. 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(Int64(timeInterval * 1_000_000_000))
  359. }
  360. }
  361. extension String {
  362. var isIPAddress: Bool {
  363. // We need some scratch space to let inet_pton write into.
  364. var ipv4Addr = in_addr()
  365. var ipv6Addr = in6_addr()
  366. return self.withCString { ptr in
  367. return inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
  368. inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
  369. }
  370. }
  371. }