PoolManager.swift 13 KB

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