PoolManager.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /*
  2. * Copyright 2021, 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 Logging
  17. import NIOConcurrencyHelpers
  18. import NIOCore
  19. #if compiler(>=5.6)
  20. // Unchecked because all mutable state is protected by a lock.
  21. extension PooledChannel: @unchecked Sendable {}
  22. #endif // compiler(>=5.6)
  23. @usableFromInline
  24. internal final class PoolManager {
  25. /// Configuration used for each connection pool.
  26. @usableFromInline
  27. internal struct PerPoolConfiguration {
  28. /// The maximum number of connections per pool.
  29. @usableFromInline
  30. var maxConnections: Int
  31. /// The maximum number of waiters per pool.
  32. @usableFromInline
  33. var maxWaiters: Int
  34. /// A load threshold in the range `0.0 ... 1.0` beyond which another connection will be started
  35. /// (assuming there is a connection available to start).
  36. @usableFromInline
  37. var loadThreshold: Double
  38. /// The assumed value of HTTP/2 'SETTINGS_MAX_CONCURRENT_STREAMS'.
  39. @usableFromInline
  40. var assumedMaxConcurrentStreams: Int
  41. /// The assumed maximum number of streams concurrently available in the pool.
  42. @usableFromInline
  43. var assumedStreamCapacity: Int {
  44. return self.maxConnections * self.assumedMaxConcurrentStreams
  45. }
  46. @usableFromInline
  47. var connectionBackoff: ConnectionBackoff
  48. /// A `Channel` provider.
  49. @usableFromInline
  50. var channelProvider: DefaultChannelProvider
  51. @usableFromInline
  52. internal init(
  53. maxConnections: Int,
  54. maxWaiters: Int,
  55. loadThreshold: Double,
  56. assumedMaxConcurrentStreams: Int = 100,
  57. connectionBackoff: ConnectionBackoff,
  58. channelProvider: DefaultChannelProvider
  59. ) {
  60. self.maxConnections = maxConnections
  61. self.maxWaiters = maxWaiters
  62. self.loadThreshold = loadThreshold
  63. self.assumedMaxConcurrentStreams = assumedMaxConcurrentStreams
  64. self.connectionBackoff = connectionBackoff
  65. self.channelProvider = channelProvider
  66. }
  67. }
  68. /// Logging metadata keys
  69. private enum Metadata {
  70. /// The ID of the pool manager.
  71. static let id = "poolmanager.id"
  72. /// The number of managed connection pools.
  73. static let poolCount = "poolmanager.pools.count"
  74. /// The maximum number of connections per pool.
  75. static let connectionsPerPool = "poolmanager.pools.conns_per_pool"
  76. /// The maximum number of waiters per pool.
  77. static let waitersPerPool = "poolmanager.pools.waiters_per_pool"
  78. }
  79. /// The current state of the pool manager, `lock` must be held when accessing or
  80. /// modifying `state`.
  81. @usableFromInline
  82. internal var _state: PoolManagerStateMachine
  83. @usableFromInline
  84. internal var _pools: [ConnectionPool]
  85. @usableFromInline
  86. internal let lock = Lock()
  87. /// The `EventLoopGroup` providing `EventLoop`s for connection pools. Once initialized the manager
  88. /// will hold as many pools as there are loops in this `EventLoopGroup`.
  89. @usableFromInline
  90. internal let group: EventLoopGroup
  91. /// Make a new pool manager and initialize it.
  92. ///
  93. /// The pool manager manages one connection pool per event loop in the provided `EventLoopGroup`.
  94. /// Each connection pool is configured using the `perPoolConfiguration`.
  95. ///
  96. /// - Parameters:
  97. /// - group: The `EventLoopGroup` providing `EventLoop`s to connections managed by the pool
  98. /// manager.
  99. /// - perPoolConfiguration: Configuration used by each connection pool managed by the manager.
  100. /// - logger: A logger.
  101. /// - Returns: An initialized pool manager.
  102. @usableFromInline
  103. internal static func makeInitializedPoolManager(
  104. using group: EventLoopGroup,
  105. perPoolConfiguration: PerPoolConfiguration,
  106. logger: GRPCLogger
  107. ) -> PoolManager {
  108. let manager = PoolManager(privateButUsableFromInline_group: group)
  109. manager.initialize(perPoolConfiguration: perPoolConfiguration, logger: logger)
  110. return manager
  111. }
  112. @usableFromInline
  113. internal init(privateButUsableFromInline_group group: EventLoopGroup) {
  114. self._state = PoolManagerStateMachine(.inactive)
  115. self._pools = []
  116. self.group = group
  117. // The pool relies on the identity of each `EventLoop` in the `EventLoopGroup` being unique. In
  118. // practice this is unlikely to happen unless a custom `EventLoopGroup` is constructed, because
  119. // of that we'll only check when running in debug mode.
  120. debugOnly {
  121. let eventLoopIDs = group.makeIterator().map { ObjectIdentifier($0) }
  122. let uniqueEventLoopIDs = Set(eventLoopIDs)
  123. assert(
  124. eventLoopIDs.count == uniqueEventLoopIDs.count,
  125. "'group' contains non-unique event loops"
  126. )
  127. }
  128. }
  129. deinit {
  130. self.lock.withLockVoid {
  131. assert(
  132. self._state.isShutdownOrShuttingDown,
  133. "The pool manager (\(ObjectIdentifier(self))) must be shutdown before going out of scope."
  134. )
  135. }
  136. }
  137. /// Initialize the pool manager, create and initialize one connection pool per event loop in the
  138. /// pools `EventLoopGroup`.
  139. ///
  140. /// - Important: Must only be called once.
  141. /// - Parameters:
  142. /// - configuration: The configuration used for each connection pool.
  143. /// - logger: A logger.
  144. private func initialize(
  145. perPoolConfiguration configuration: PerPoolConfiguration,
  146. logger: GRPCLogger
  147. ) {
  148. var logger = logger
  149. logger[metadataKey: Metadata.id] = "\(ObjectIdentifier(self))"
  150. let pools = self.makePools(perPoolConfiguration: configuration, logger: logger)
  151. logger.debug("initializing connection pool manager", metadata: [
  152. Metadata.poolCount: "\(pools.count)",
  153. Metadata.connectionsPerPool: "\(configuration.maxConnections)",
  154. Metadata.waitersPerPool: "\(configuration.maxWaiters)",
  155. ])
  156. // The assumed maximum number of streams concurrently available in each pool.
  157. let assumedCapacity = configuration.assumedStreamCapacity
  158. // The state machine stores the per-pool state keyed by the pools `EventLoopID` and tells the
  159. // pool manager about which pool to use/operate via the pools index in `self.pools`.
  160. let poolKeys = pools.indices.map { index in
  161. return ConnectionPoolKey(
  162. index: ConnectionPoolIndex(index),
  163. eventLoopID: pools[index].eventLoop.id
  164. )
  165. }
  166. self.lock.withLockVoid {
  167. assert(self._pools.isEmpty)
  168. self._pools = pools
  169. // We'll blow up if we've already been initialized, that's fine, we don't allow callers to
  170. // call `initialize` directly.
  171. self._state.activatePools(keyedBy: poolKeys, assumingPerPoolCapacity: assumedCapacity)
  172. }
  173. for pool in pools {
  174. pool.initialize(connections: configuration.maxConnections)
  175. }
  176. }
  177. /// Make one pool per `EventLoop` in the pool's `EventLoopGroup`.
  178. /// - Parameters:
  179. /// - configuration: The configuration to make each pool with.
  180. /// - logger: A logger.
  181. /// - Returns: An array of `ConnectionPool`s.
  182. private func makePools(
  183. perPoolConfiguration configuration: PerPoolConfiguration,
  184. logger: GRPCLogger
  185. ) -> [ConnectionPool] {
  186. let eventLoops = self.group.makeIterator()
  187. return eventLoops.map { eventLoop in
  188. // We're creating a retain cycle here as each pool will reference the manager and the per-pool
  189. // state will hold the pool which will in turn be held by the pool manager. That's okay: when
  190. // the pool is shutdown the per-pool state and in turn each connection pool will be dropped.
  191. // and we'll break the cycle.
  192. return ConnectionPool(
  193. eventLoop: eventLoop,
  194. maxWaiters: configuration.maxWaiters,
  195. reservationLoadThreshold: configuration.loadThreshold,
  196. assumedMaxConcurrentStreams: configuration.assumedMaxConcurrentStreams,
  197. connectionBackoff: configuration.connectionBackoff,
  198. channelProvider: configuration.channelProvider,
  199. streamLender: self,
  200. logger: logger
  201. )
  202. }
  203. }
  204. // MARK: Stream Creation
  205. /// A future for a `Channel` from a managed connection pool. The `eventLoop` indicates the loop
  206. /// that the `Channel` is running on and therefore which event loop the RPC will use for its
  207. /// transport.
  208. @usableFromInline
  209. internal struct PooledStreamChannel {
  210. @inlinable
  211. internal init(futureResult: EventLoopFuture<Channel>) {
  212. self.futureResult = futureResult
  213. }
  214. /// The future `Channel`.
  215. @usableFromInline
  216. var futureResult: EventLoopFuture<Channel>
  217. /// The `EventLoop` that the `Channel` is using.
  218. @usableFromInline
  219. var eventLoop: EventLoop {
  220. return self.futureResult.eventLoop
  221. }
  222. }
  223. /// Make a stream and initialize it.
  224. ///
  225. /// - Parameters:
  226. /// - preferredEventLoop: The `EventLoop` that the stream should be created on, if possible. If
  227. /// a pool exists running this `EventLoop` then it will be chosen over all other pools,
  228. /// irregardless of the load on the pool. If no pool exists on the preferred `EventLoop` or
  229. /// no preference is given then the pool with the most streams available will be selected.
  230. /// The `EventLoop` of the selected pool will be the same as the `EventLoop` of
  231. /// the `EventLoopFuture<Channel>` returned from this call.
  232. /// - deadline: The point in time by which the stream must have been selected. If this deadline
  233. /// is passed then the returned `EventLoopFuture` will be failed.
  234. /// - logger: A logger.
  235. /// - initializer: A closure to initialize the `Channel` with.
  236. /// - Returns: A `PoolStreamChannel` indicating the future channel and `EventLoop` as that the
  237. /// `Channel` is using. The future will be failed if the pool manager has been shutdown,
  238. /// the deadline has passed before a stream was created or if the selected connection pool
  239. /// is unable to create a stream (if there is too much demand on that pool, for example).
  240. @inlinable
  241. internal func makeStream(
  242. preferredEventLoop: EventLoop?,
  243. deadline: NIODeadline,
  244. logger: GRPCLogger,
  245. streamInitializer initializer: @escaping (Channel) -> EventLoopFuture<Void>
  246. ) -> PooledStreamChannel {
  247. let preferredEventLoopID = preferredEventLoop.map { EventLoopID($0) }
  248. let reservedPool = self.lock.withLock {
  249. return self._state.reserveStream(preferringPoolWithEventLoopID: preferredEventLoopID).map {
  250. return self._pools[$0.value]
  251. }
  252. }
  253. switch reservedPool {
  254. case let .success(pool):
  255. let channel = pool.makeStream(deadline: deadline, logger: logger, initializer: initializer)
  256. return PooledStreamChannel(futureResult: channel)
  257. case let .failure(error):
  258. let eventLoop = preferredEventLoop ?? self.group.next()
  259. return PooledStreamChannel(futureResult: eventLoop.makeFailedFuture(error))
  260. }
  261. }
  262. // MARK: Shutdown
  263. /// Shutdown the pool manager and all connection pools it manages.
  264. @usableFromInline
  265. internal func shutdown(mode: ConnectionManager.ShutdownMode, promise: EventLoopPromise<Void>) {
  266. let (action, pools): (PoolManagerStateMachine.ShutdownAction, [ConnectionPool]?) = self.lock
  267. .withLock {
  268. let action = self._state.shutdown(promise: promise)
  269. switch action {
  270. case .shutdownPools:
  271. // Clear out the pools; we need to shut them down.
  272. let pools = self._pools
  273. self._pools.removeAll(keepingCapacity: true)
  274. return (action, pools)
  275. case .alreadyShutdown, .alreadyShuttingDown:
  276. return (action, nil)
  277. }
  278. }
  279. switch (action, pools) {
  280. case let (.shutdownPools, .some(pools)):
  281. promise.futureResult.whenComplete { _ in self.shutdownComplete() }
  282. EventLoopFuture.andAllSucceed(pools.map { $0.shutdown(mode: mode) }, promise: promise)
  283. case let (.alreadyShuttingDown(future), .none):
  284. promise.completeWith(future)
  285. case (.alreadyShutdown, .none):
  286. promise.succeed(())
  287. case (.shutdownPools, .none),
  288. (.alreadyShuttingDown, .some),
  289. (.alreadyShutdown, .some):
  290. preconditionFailure()
  291. }
  292. }
  293. private func shutdownComplete() {
  294. self.lock.withLockVoid {
  295. self._state.shutdownComplete()
  296. }
  297. }
  298. }
  299. // MARK: - Connection Pool to Pool Manager
  300. extension PoolManager: StreamLender {
  301. @usableFromInline
  302. internal func returnStreams(_ count: Int, to pool: ConnectionPool) {
  303. self.lock.withLockVoid {
  304. self._state.returnStreams(count, toPoolOnEventLoopWithID: pool.eventLoop.id)
  305. }
  306. }
  307. @usableFromInline
  308. internal func changeStreamCapacity(by delta: Int, for pool: ConnectionPool) {
  309. self.lock.withLockVoid {
  310. self._state.changeStreamCapacity(by: delta, forPoolOnEventLoopWithID: pool.eventLoop.id)
  311. }
  312. }
  313. }
  314. @usableFromInline
  315. internal enum PoolManagerError: Error {
  316. /// The pool manager has not been initialized yet.
  317. case notInitialized
  318. /// The pool manager has been shutdown or is in the process of shutting down.
  319. case shutdown
  320. }