PoolManager.swift 13 KB

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