PoolManager.swift 13 KB

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