PoolManager.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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(
  154. "initializing connection pool manager",
  155. metadata: [
  156. Metadata.poolCount: "\(pools.count)",
  157. Metadata.connectionsPerPool: "\(configuration.maxConnections)",
  158. Metadata.waitersPerPool: "\(configuration.maxWaiters)",
  159. ]
  160. )
  161. // The assumed maximum number of streams concurrently available in each pool.
  162. let assumedCapacity = configuration.assumedStreamCapacity
  163. // The state machine stores the per-pool state keyed by the pools `EventLoopID` and tells the
  164. // pool manager about which pool to use/operate via the pools index in `self.pools`.
  165. let poolKeys = pools.indices.map { index in
  166. return ConnectionPoolKey(
  167. index: ConnectionPoolIndex(index),
  168. eventLoopID: pools[index].eventLoop.id
  169. )
  170. }
  171. self.lock.withLock {
  172. assert(self._pools.isEmpty)
  173. self._pools = pools
  174. // We'll blow up if we've already been initialized, that's fine, we don't allow callers to
  175. // call `initialize` directly.
  176. self._state.activatePools(keyedBy: poolKeys, assumingPerPoolCapacity: assumedCapacity)
  177. }
  178. for pool in pools {
  179. pool.initialize(connections: configuration.maxConnections)
  180. }
  181. }
  182. /// Make one pool per `EventLoop` in the pool's `EventLoopGroup`.
  183. /// - Parameters:
  184. /// - configuration: The configuration to make each pool with.
  185. /// - logger: A logger.
  186. /// - Returns: An array of `ConnectionPool`s.
  187. private func makePools(
  188. perPoolConfiguration configuration: PerPoolConfiguration,
  189. logger: GRPCLogger
  190. ) -> [ConnectionPool] {
  191. let eventLoops = self.group.makeIterator()
  192. return eventLoops.map { eventLoop in
  193. // We're creating a retain cycle here as each pool will reference the manager and the per-pool
  194. // state will hold the pool which will in turn be held by the pool manager. That's okay: when
  195. // the pool is shutdown the per-pool state and in turn each connection pool will be dropped.
  196. // and we'll break the cycle.
  197. return ConnectionPool(
  198. eventLoop: eventLoop,
  199. maxWaiters: configuration.maxWaiters,
  200. reservationLoadThreshold: configuration.loadThreshold,
  201. assumedMaxConcurrentStreams: configuration.assumedMaxConcurrentStreams,
  202. connectionBackoff: configuration.connectionBackoff,
  203. channelProvider: configuration.channelProvider,
  204. streamLender: self,
  205. delegate: configuration.delegate,
  206. logger: logger
  207. )
  208. }
  209. }
  210. // MARK: Stream Creation
  211. /// A future for a `Channel` from a managed connection pool. The `eventLoop` indicates the loop
  212. /// that the `Channel` is running on and therefore which event loop the RPC will use for its
  213. /// transport.
  214. @usableFromInline
  215. internal struct PooledStreamChannel {
  216. @inlinable
  217. internal init(futureResult: EventLoopFuture<Channel>) {
  218. self.futureResult = futureResult
  219. }
  220. /// The future `Channel`.
  221. @usableFromInline
  222. var futureResult: EventLoopFuture<Channel>
  223. /// The `EventLoop` that the `Channel` is using.
  224. @usableFromInline
  225. var eventLoop: EventLoop {
  226. return self.futureResult.eventLoop
  227. }
  228. }
  229. /// Make a stream and initialize it.
  230. ///
  231. /// - Parameters:
  232. /// - preferredEventLoop: The `EventLoop` that the stream should be created on, if possible. If
  233. /// a pool exists running this `EventLoop` then it will be chosen over all other pools,
  234. /// irregardless of the load on the pool. If no pool exists on the preferred `EventLoop` or
  235. /// no preference is given then the pool with the most streams available will be selected.
  236. /// The `EventLoop` of the selected pool will be the same as the `EventLoop` of
  237. /// the `EventLoopFuture<Channel>` returned from this call.
  238. /// - deadline: The point in time by which the stream must have been selected. If this deadline
  239. /// is passed then the returned `EventLoopFuture` will be failed.
  240. /// - logger: A logger.
  241. /// - initializer: A closure to initialize the `Channel` with.
  242. /// - Returns: A `PoolStreamChannel` indicating the future channel and `EventLoop` as that the
  243. /// `Channel` is using. The future will be failed if the pool manager has been shutdown,
  244. /// the deadline has passed before a stream was created or if the selected connection pool
  245. /// is unable to create a stream (if there is too much demand on that pool, for example).
  246. @inlinable
  247. internal func makeStream(
  248. preferredEventLoop: EventLoop?,
  249. deadline: NIODeadline,
  250. logger: GRPCLogger,
  251. streamInitializer initializer: @escaping @Sendable (Channel) -> EventLoopFuture<Void>
  252. ) -> PooledStreamChannel {
  253. let preferredEventLoopID = preferredEventLoop.map { EventLoopID($0) }
  254. let reservedPool = self.lock.withLock {
  255. return self._state.reserveStream(preferringPoolWithEventLoopID: preferredEventLoopID).map {
  256. return self._pools[$0.value]
  257. }
  258. }
  259. switch reservedPool {
  260. case let .success(pool):
  261. let channel = pool.makeStream(deadline: deadline, logger: logger, initializer: initializer)
  262. return PooledStreamChannel(futureResult: channel)
  263. case let .failure(error):
  264. let eventLoop = preferredEventLoop ?? self.group.next()
  265. return PooledStreamChannel(futureResult: eventLoop.makeFailedFuture(error))
  266. }
  267. }
  268. // MARK: Shutdown
  269. /// Shutdown the pool manager and all connection pools it manages.
  270. @usableFromInline
  271. internal func shutdown(mode: ConnectionManager.ShutdownMode, promise: EventLoopPromise<Void>) {
  272. let (action, pools): (PoolManagerStateMachine.ShutdownAction, [ConnectionPool]?) = self.lock
  273. .withLock {
  274. let action = self._state.shutdown(promise: promise)
  275. switch action {
  276. case .shutdownPools:
  277. // Clear out the pools; we need to shut them down.
  278. let pools = self._pools
  279. self._pools.removeAll(keepingCapacity: true)
  280. return (action, pools)
  281. case .alreadyShutdown, .alreadyShuttingDown:
  282. return (action, nil)
  283. }
  284. }
  285. switch (action, pools) {
  286. case let (.shutdownPools, .some(pools)):
  287. promise.futureResult.whenComplete { _ in self.shutdownComplete() }
  288. EventLoopFuture.andAllSucceed(pools.map { $0.shutdown(mode: mode) }, promise: promise)
  289. case let (.alreadyShuttingDown(future), .none):
  290. promise.completeWith(future)
  291. case (.alreadyShutdown, .none):
  292. promise.succeed(())
  293. case (.shutdownPools, .none),
  294. (.alreadyShuttingDown, .some),
  295. (.alreadyShutdown, .some):
  296. preconditionFailure()
  297. }
  298. }
  299. private func shutdownComplete() {
  300. self.lock.withLock {
  301. self._state.shutdownComplete()
  302. }
  303. }
  304. }
  305. // MARK: - Connection Pool to Pool Manager
  306. extension PoolManager: StreamLender {
  307. @usableFromInline
  308. internal func returnStreams(_ count: Int, to pool: ConnectionPool) {
  309. self.lock.withLock {
  310. self._state.returnStreams(count, toPoolOnEventLoopWithID: pool.eventLoop.id)
  311. }
  312. }
  313. @usableFromInline
  314. internal func changeStreamCapacity(by delta: Int, for pool: ConnectionPool) {
  315. self.lock.withLock {
  316. self._state.changeStreamCapacity(by: delta, forPoolOnEventLoopWithID: pool.eventLoop.id)
  317. }
  318. }
  319. }
  320. @usableFromInline
  321. internal enum PoolManagerError: Error {
  322. /// The pool manager has not been initialized yet.
  323. case notInitialized
  324. /// The pool manager has been shutdown or is in the process of shutting down.
  325. case shutdown
  326. }