ConnectionManager.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. /*
  2. * Copyright 2020, 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 NIO
  17. import NIOConcurrencyHelpers
  18. import Logging
  19. import Foundation
  20. internal class ConnectionManager {
  21. internal struct IdleState {
  22. var configuration: ClientConnection.Configuration
  23. }
  24. internal enum Reconnect {
  25. case none
  26. case after(TimeInterval)
  27. }
  28. internal struct ConnectingState {
  29. var configuration: ClientConnection.Configuration
  30. var backoffIterator: ConnectionBackoffIterator?
  31. var reconnect: Reconnect
  32. var readyChannelPromise: EventLoopPromise<Channel>
  33. var candidate: EventLoopFuture<Channel>
  34. }
  35. internal struct ConnectedState {
  36. var configuration: ClientConnection.Configuration
  37. var backoffIterator: ConnectionBackoffIterator?
  38. var reconnect: Reconnect
  39. var readyChannelPromise: EventLoopPromise<Channel>
  40. var candidate: Channel
  41. init(from state: ConnectingState, candidate: Channel) {
  42. self.configuration = state.configuration
  43. self.backoffIterator = state.backoffIterator
  44. self.reconnect = state.reconnect
  45. self.readyChannelPromise = state.readyChannelPromise
  46. self.candidate = candidate
  47. }
  48. }
  49. internal struct ReadyState {
  50. var configuration: ClientConnection.Configuration
  51. var channel: Channel
  52. init(from state: ConnectedState) {
  53. self.configuration = state.configuration
  54. self.channel = state.candidate
  55. }
  56. }
  57. internal struct TransientFailureState {
  58. var configuration: ClientConnection.Configuration
  59. var backoffIterator: ConnectionBackoffIterator?
  60. var readyChannelPromise: EventLoopPromise<Channel>
  61. var scheduled: Scheduled<Void>
  62. init(from state: ConnectingState, scheduled: Scheduled<Void>) {
  63. self.configuration = state.configuration
  64. self.backoffIterator = state.backoffIterator
  65. self.readyChannelPromise = state.readyChannelPromise
  66. self.scheduled = scheduled
  67. }
  68. init(from state: ConnectedState, scheduled: Scheduled<Void>) {
  69. self.configuration = state.configuration
  70. self.backoffIterator = state.backoffIterator
  71. self.readyChannelPromise = state.readyChannelPromise
  72. self.scheduled = scheduled
  73. }
  74. init(from state: ReadyState, scheduled: Scheduled<Void>) {
  75. self.configuration = state.configuration
  76. self.backoffIterator = state.configuration.connectionBackoff?.makeIterator()
  77. self.readyChannelPromise = state.channel.eventLoop.makePromise()
  78. self.scheduled = scheduled
  79. }
  80. }
  81. internal struct ShutdownState {
  82. var closeFuture: EventLoopFuture<Void>
  83. }
  84. internal enum State {
  85. /// No `Channel` is required.
  86. ///
  87. /// Valid next states:
  88. /// - `connecting`
  89. /// - `shutdown`
  90. case idle(IdleState)
  91. /// We're actively trying to establish a connection.
  92. ///
  93. /// Valid next states:
  94. /// - `active`
  95. /// - `transientFailure` (if our attempt fails and we're going to try again)
  96. /// - `shutdown`
  97. case connecting(ConnectingState)
  98. /// We've established a `Channel`, it might not be suitable (TLS handshake may fail, etc.).
  99. /// Our signal to be 'ready' is the initial HTTP/2 SETTINGS frame.
  100. ///
  101. /// Valid next states:
  102. /// - `ready`
  103. /// - `transientFailure` (if we our handshake fails or other error happens and we can attempt
  104. /// to re-establish the connection)
  105. /// - `shutdown`
  106. case active(ConnectedState)
  107. /// We have an active `Channel` which has seen the initial HTTP/2 SETTINGS frame. We can use
  108. /// the channel for making RPCs.
  109. ///
  110. /// Valid next states:
  111. /// - `idle` (we're not serving any RPCs, we can drop the connection for now)
  112. /// - `transientFailure` (we encountered an error and will re-establish the connection)
  113. /// - `shutdown`
  114. case ready(ReadyState)
  115. /// A `Channel` is desired, we'll attempt to create one in the future.
  116. ///
  117. /// Valid next states:
  118. /// - `connecting`
  119. /// - `shutdown`
  120. case transientFailure(TransientFailureState)
  121. /// We never want another `Channel`: this state is terminal.
  122. case shutdown(ShutdownState)
  123. }
  124. private var state: State {
  125. didSet {
  126. switch self.state {
  127. case .idle:
  128. self.monitor.updateState(to: .idle, logger: self.logger)
  129. // Create a new id; it'll be used for the *next* channel we create.
  130. self.channelNumber &+= 1
  131. self.logger[metadataKey: MetadataKey.connectionID] = "\(self.connectionId)/\(self.channelNumber)"
  132. case .connecting:
  133. self.monitor.updateState(to: .connecting, logger: self.logger)
  134. // This is an internal state.
  135. case .active:
  136. ()
  137. case .ready:
  138. self.monitor.updateState(to: .ready, logger: self.logger)
  139. case .transientFailure:
  140. self.monitor.updateState(to: .transientFailure, logger: self.logger)
  141. case .shutdown:
  142. self.monitor.updateState(to: .shutdown, logger: self.logger)
  143. }
  144. }
  145. }
  146. internal let eventLoop: EventLoop
  147. internal let monitor: ConnectivityStateMonitor
  148. internal var logger: Logger
  149. private let connectionId: String
  150. private var channelNumber: UInt64
  151. // Only used for testing.
  152. private var channelProvider: (() -> EventLoopFuture<Channel>)?
  153. internal convenience init(configuration: ClientConnection.Configuration, logger: Logger) {
  154. self.init(configuration: configuration, logger: logger, channelProvider: nil)
  155. }
  156. /// Create a `ConnectionManager` for testing: uses the given `channelProvider` to create channels.
  157. internal static func testingOnly(
  158. configuration: ClientConnection.Configuration,
  159. logger: Logger,
  160. channelProvider: @escaping () -> EventLoopFuture<Channel>
  161. ) -> ConnectionManager {
  162. return ConnectionManager(
  163. configuration: configuration,
  164. logger: logger,
  165. channelProvider: channelProvider
  166. )
  167. }
  168. private init(
  169. configuration: ClientConnection.Configuration,
  170. logger: Logger,
  171. channelProvider: (() -> EventLoopFuture<Channel>)?
  172. ) {
  173. // Setup the logger.
  174. var logger = logger
  175. let connectionId = UUID().uuidString
  176. let channelNumber: UInt64 = 0
  177. logger[metadataKey: MetadataKey.connectionID] = "\(connectionId)/\(channelNumber)"
  178. let eventLoop = configuration.eventLoopGroup.next()
  179. self.eventLoop = eventLoop
  180. self.state = .idle(IdleState(configuration: configuration))
  181. self.monitor = ConnectivityStateMonitor(delegate: configuration.connectivityStateDelegate)
  182. self.channelProvider = channelProvider
  183. self.connectionId = connectionId
  184. self.channelNumber = channelNumber
  185. self.logger = logger
  186. }
  187. /// Returns a future for a connected channel.
  188. internal func getChannel() -> EventLoopFuture<Channel> {
  189. return self.eventLoop.flatSubmit {
  190. switch self.state {
  191. case .idle:
  192. self.startConnecting()
  193. // We started connecting so we must transition to the `connecting` state.
  194. guard case .connecting(let connecting) = self.state else {
  195. self.invalidState()
  196. }
  197. return connecting.readyChannelPromise.futureResult
  198. case .connecting(let state):
  199. return state.readyChannelPromise.futureResult
  200. case .active(let state):
  201. return state.readyChannelPromise.futureResult
  202. case .ready(let state):
  203. return state.channel.eventLoop.makeSucceededFuture(state.channel)
  204. case .transientFailure(let state):
  205. return state.readyChannelPromise.futureResult
  206. case .shutdown:
  207. return self.eventLoop.makeFailedFuture(GRPCStatus(code: .unavailable, message: nil))
  208. }
  209. }
  210. }
  211. /// Shutdown any connection which exists. This is a request from the application.
  212. internal func shutdown() -> EventLoopFuture<Void> {
  213. return self.eventLoop.flatSubmit {
  214. let shutdown: ShutdownState
  215. switch self.state {
  216. // We don't have a channel and we don't want one, easy!
  217. case .idle:
  218. shutdown = ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(()))
  219. self.state = .shutdown(shutdown)
  220. // We're mid-connection: the application doesn't have any 'ready' channels so we'll succeed
  221. // the shutdown future and deal with any fallout from the connecting channel without the
  222. // application knowing.
  223. case .connecting(let state):
  224. shutdown = ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(()))
  225. self.state = .shutdown(shutdown)
  226. // Fail the ready channel promise: we're shutting down so even if we manage to successfully
  227. // connect the application shouldn't should have access to the channel.
  228. state.readyChannelPromise.fail(GRPCStatus(code: .unavailable, message: nil))
  229. // In case we do successfully connect, close immediately.
  230. state.candidate.whenSuccess {
  231. $0.close(mode: .all, promise: nil)
  232. }
  233. // We have an active channel but the application doesn't know about it yet. We'll do the same
  234. // as for `.connecting`.
  235. case .active(let state):
  236. shutdown = ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(()))
  237. self.state = .shutdown(shutdown)
  238. // Fail the ready channel promise: we're shutting down so even if we manage to successfully
  239. // connect the application shouldn't should have access to the channel.
  240. state.readyChannelPromise.fail(GRPCStatus(code: .unavailable, message: nil))
  241. // We have a channel, close it.
  242. state.candidate.close(mode: .all, promise: nil)
  243. // The channel is up and running: the application could be using it. We can close it and
  244. // return the `closeFuture`.
  245. case .ready(let state):
  246. shutdown = ShutdownState(closeFuture: state.channel.closeFuture)
  247. self.state = .shutdown(shutdown)
  248. // We have a channel, close it.
  249. state.channel.close(mode: .all, promise: nil)
  250. // Like `.connecting` and `.active` the application does not have a `.ready` channel. We'll
  251. // do the same but also cancel any scheduled connection attempts and deal with any fallout
  252. // if we cancelled too late.
  253. case .transientFailure(let state):
  254. // Stop the creation of a new channel, if we can. If we can't then the task to
  255. // `startConnecting()` will see our new `shutdown` state and ignore the request to connect.
  256. state.scheduled.cancel()
  257. shutdown = ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(()))
  258. self.state = .shutdown(shutdown)
  259. // Fail the ready channel promise: we're shutting down so even if we manage to successfully
  260. // connect the application shouldn't should have access to the channel.
  261. state.readyChannelPromise.fail(GRPCStatus(code: .unavailable, message: nil))
  262. // We're already shutdown; nothing to do.
  263. case .shutdown(let state):
  264. shutdown = state
  265. }
  266. return shutdown.closeFuture
  267. }
  268. }
  269. // MARK: - State changes from the channel handler.
  270. /// The connecting channel became `active`. Must be called on the `EventLoop`.
  271. internal func channelActive(channel: Channel) {
  272. self.eventLoop.preconditionInEventLoop()
  273. switch self.state {
  274. case .connecting(let connecting):
  275. self.state = .active(ConnectedState(from: connecting, candidate: channel))
  276. // Application called shutdown before the channel become active; we should close it.
  277. case .shutdown:
  278. channel.close(mode: .all, promise: nil)
  279. case .idle, .active, .ready, .transientFailure:
  280. self.invalidState()
  281. }
  282. }
  283. /// An established channel (i.e. `active` or `ready`) has become inactive: should we reconnect?
  284. /// Must be called on the `EventLoop`.
  285. internal func channelInactive() {
  286. self.eventLoop.preconditionInEventLoop()
  287. switch self.state {
  288. // The channel is `active` but not `ready`. Should we try again?
  289. case .active(let active):
  290. switch active.reconnect {
  291. // No, shutdown instead.
  292. case .none:
  293. self.state = .shutdown(ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(())))
  294. active.readyChannelPromise.fail(GRPCStatus(code: .unavailable, message: nil))
  295. // Yes, after some time.
  296. case .after(let delay):
  297. let scheduled = self.eventLoop.scheduleTask(in: .seconds(timeInterval: delay)) {
  298. self.startConnecting()
  299. }
  300. self.state = .transientFailure(TransientFailureState(from: active, scheduled: scheduled))
  301. }
  302. // The channel was ready and working fine but something went wrong. Should we try to replace
  303. // the channel?
  304. case .ready(let ready):
  305. // No, no backoff is configured.
  306. if ready.configuration.connectionBackoff == nil {
  307. self.state = .shutdown(ShutdownState(closeFuture: ready.channel.closeFuture))
  308. } else {
  309. // Yes, start connecting now. We should go via `transientFailure`, however.
  310. let scheduled = self.eventLoop.scheduleTask(in: .nanoseconds(0)) {
  311. self.startConnecting()
  312. }
  313. self.state = .transientFailure(TransientFailureState(from: ready, scheduled: scheduled))
  314. }
  315. // This is fine: we expect the channel to become inactive after becoming idle.
  316. case .idle:
  317. ()
  318. // We're already shutdown, that's fine.
  319. case .shutdown:
  320. ()
  321. case .connecting, .transientFailure:
  322. self.invalidState()
  323. }
  324. }
  325. /// The channel has become ready, that is, it has seen the initial HTTP/2 SETTINGS frame. Must be
  326. /// called on the `EventLoop`.
  327. internal func ready() {
  328. self.eventLoop.preconditionInEventLoop()
  329. switch self.state {
  330. case .active(let connected):
  331. self.state = .ready(ReadyState(from: connected))
  332. connected.readyChannelPromise.succeed(connected.candidate)
  333. case .shutdown:
  334. ()
  335. case .idle, .transientFailure, .connecting, .ready:
  336. self.invalidState()
  337. }
  338. }
  339. /// No active RPCs are happening on 'ready' channel: close the channel for now. Must be called on
  340. /// the `EventLoop`.
  341. internal func idle() {
  342. self.eventLoop.preconditionInEventLoop()
  343. switch self.state {
  344. case .ready(let state):
  345. self.state = .idle(IdleState(configuration: state.configuration))
  346. case .idle, .connecting, .transientFailure, .active, .shutdown:
  347. self.invalidState()
  348. }
  349. }
  350. }
  351. extension ConnectionManager {
  352. // A connection attempt failed; we never established a connection.
  353. private func connectionFailed(withError error: Error) {
  354. self.eventLoop.preconditionInEventLoop()
  355. switch self.state {
  356. case .connecting(let connecting):
  357. // Should we reconnect?
  358. switch connecting.reconnect {
  359. // No, shutdown.
  360. case .none:
  361. connecting.readyChannelPromise.fail(error)
  362. self.state = .shutdown(ShutdownState(closeFuture: self.eventLoop.makeSucceededFuture(())))
  363. // Yes, after a delay.
  364. case .after(let delay):
  365. let scheduled = self.eventLoop.scheduleTask(in: .seconds(timeInterval: delay)) {
  366. self.startConnecting()
  367. }
  368. self.state = .transientFailure(TransientFailureState(from: connecting, scheduled: scheduled))
  369. }
  370. // The application must have called shutdown while we were trying to establish a connection
  371. // which was doomed to fail anyway. That's fine, we can ignore this.
  372. case .shutdown:
  373. ()
  374. // We can't fail to connect if we aren't trying.
  375. case .idle, .active, .ready, .transientFailure:
  376. self.invalidState()
  377. }
  378. }
  379. }
  380. extension ConnectionManager {
  381. // Start establishing a connection: we can only do this from the `idle` and `transientFailure`
  382. // states. Must be called on the `EventLoop`.
  383. private func startConnecting() {
  384. switch self.state {
  385. case .idle(let state):
  386. let iterator = state.configuration.connectionBackoff?.makeIterator()
  387. self.startConnecting(
  388. configuration: state.configuration,
  389. backoffIterator: iterator,
  390. channelPromise: self.eventLoop.makePromise()
  391. )
  392. case .transientFailure(let pending):
  393. self.startConnecting(
  394. configuration: pending.configuration,
  395. backoffIterator: pending.backoffIterator,
  396. channelPromise: pending.readyChannelPromise
  397. )
  398. // We shutdown before a scheduled connection attempt had started.
  399. case .shutdown:
  400. ()
  401. case .connecting, .active, .ready:
  402. self.invalidState()
  403. }
  404. }
  405. private func startConnecting(
  406. configuration: ClientConnection.Configuration,
  407. backoffIterator: ConnectionBackoffIterator?,
  408. channelPromise: EventLoopPromise<Channel>
  409. ) {
  410. let timeoutAndBackoff = backoffIterator?.next()
  411. // We're already on the event loop: submit the connect so it starts after we've made the
  412. // state change to `.connecting`.
  413. self.eventLoop.assertInEventLoop()
  414. let candidate: EventLoopFuture<Channel> = self.eventLoop.flatSubmit {
  415. let channel = self.makeChannel(
  416. configuration: configuration,
  417. connectTimeout: timeoutAndBackoff?.timeout
  418. )
  419. channel.whenFailure { error in
  420. self.connectionFailed(withError: error)
  421. }
  422. return channel
  423. }
  424. // Should we reconnect if the candidate channel fails?
  425. let reconnect: Reconnect = timeoutAndBackoff.map { .after($0.backoff) } ?? .none
  426. let connecting = ConnectingState(
  427. configuration: configuration,
  428. backoffIterator: backoffIterator,
  429. reconnect: reconnect,
  430. readyChannelPromise: channelPromise,
  431. candidate: candidate
  432. )
  433. self.state = .connecting(connecting)
  434. }
  435. }
  436. extension ConnectionManager {
  437. private func invalidState(
  438. function: StaticString = #function,
  439. file: StaticString = #file,
  440. line: UInt = #line
  441. ) -> Never {
  442. preconditionFailure("Invalid state \(self.state) for \(function)", file: file, line: line)
  443. }
  444. }
  445. extension ConnectionManager {
  446. private func makeBootstrap(
  447. configuration: ClientConnection.Configuration,
  448. connectTimeout: TimeInterval?
  449. ) -> ClientBootstrapProtocol {
  450. let serverHostname: String? = configuration.tls.flatMap { tls -> String? in
  451. if let hostnameOverride = tls.hostnameOverride {
  452. return hostnameOverride
  453. } else {
  454. return configuration.target.host
  455. }
  456. }.flatMap { hostname in
  457. if hostname.isIPAddress {
  458. return nil
  459. } else {
  460. return hostname
  461. }
  462. }
  463. let bootstrap = PlatformSupport.makeClientBootstrap(group: self.eventLoop, logger: self.logger)
  464. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  465. .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  466. .channelInitializer { channel in
  467. channel.configureGRPCClient(
  468. tlsConfiguration: configuration.tls?.configuration,
  469. tlsServerHostname: serverHostname,
  470. connectionManager: self,
  471. errorDelegate: configuration.errorDelegate,
  472. logger: self.logger
  473. )
  474. }
  475. if let connectTimeout = connectTimeout {
  476. return bootstrap.connectTimeout(.seconds(timeInterval: connectTimeout))
  477. } else {
  478. return bootstrap
  479. }
  480. }
  481. private func makeChannel(
  482. configuration: ClientConnection.Configuration,
  483. connectTimeout: TimeInterval?
  484. ) -> EventLoopFuture<Channel> {
  485. if let provider = self.channelProvider {
  486. return provider()
  487. } else {
  488. let bootstrap = self.makeBootstrap(
  489. configuration: configuration,
  490. connectTimeout: connectTimeout
  491. )
  492. return bootstrap.connect(to: configuration.target)
  493. }
  494. }
  495. }