PoolManager.swift 14 KB

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