Server.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /*
  2. * Copyright 2019, 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 Foundation
  17. import Logging
  18. import NIOCore
  19. import NIOExtras
  20. import NIOHTTP1
  21. import NIOHTTP2
  22. import NIOPosix
  23. import NIOSSL
  24. import NIOTransportServices
  25. #if canImport(Network)
  26. import Network
  27. #endif
  28. /// Wrapper object to manage the lifecycle of a gRPC server.
  29. ///
  30. /// The pipeline is configured in three stages detailed below. Note: handlers marked with
  31. /// a '*' are responsible for handling errors.
  32. ///
  33. /// 1. Initial stage, prior to pipeline configuration.
  34. ///
  35. /// ┌─────────────────────────────────┐
  36. /// │ GRPCServerPipelineConfigurator* │
  37. /// └────▲───────────────────────┬────┘
  38. /// ByteBuffer│ │ByteBuffer
  39. /// ┌─┴───────────────────────▼─┐
  40. /// │ NIOSSLHandler │
  41. /// └─▲───────────────────────┬─┘
  42. /// ByteBuffer│ │ByteBuffer
  43. /// │ ▼
  44. ///
  45. /// The `NIOSSLHandler` is optional and depends on how the framework user has configured
  46. /// their server. The `GRPCServerPipelineConfigurator` detects which HTTP version is being used
  47. /// (via ALPN if TLS is used or by parsing the first bytes on the connection otherwise) and
  48. /// configures the pipeline accordingly.
  49. ///
  50. /// 2. HTTP version detected. "HTTP Handlers" depends on the HTTP version determined by
  51. /// `GRPCServerPipelineConfigurator`. In the case of HTTP/2:
  52. ///
  53. /// ┌─────────────────────────────────┐
  54. /// │ HTTP2StreamMultiplexer │
  55. /// └─▲─────────────────────────────┬─┘
  56. /// HTTP2Frame│ │HTTP2Frame
  57. /// ┌─┴─────────────────────────────▼─┐
  58. /// │ HTTP2Handler │
  59. /// └─▲─────────────────────────────┬─┘
  60. /// ByteBuffer│ │ByteBuffer
  61. /// ┌─┴─────────────────────────────▼─┐
  62. /// │ NIOSSLHandler │
  63. /// └─▲─────────────────────────────┬─┘
  64. /// ByteBuffer│ │ByteBuffer
  65. /// │ ▼
  66. ///
  67. /// The `HTTP2StreamMultiplexer` provides one `Channel` for each HTTP/2 stream (and thus each
  68. /// RPC).
  69. ///
  70. /// 3. The frames for each stream channel are routed by the `HTTP2ToRawGRPCServerCodec` handler to
  71. /// a handler containing the user-implemented logic provided by a `CallHandlerProvider`:
  72. ///
  73. /// ┌─────────────────────────────────┐
  74. /// │ BaseCallHandler* │
  75. /// └─▲─────────────────────────────┬─┘
  76. /// GRPCServerRequestPart│ │GRPCServerResponsePart
  77. /// ┌─┴─────────────────────────────▼─┐
  78. /// │ HTTP2ToRawGRPCServerCodec │
  79. /// └─▲─────────────────────────────┬─┘
  80. /// HTTP2Frame.FramePayload│ │HTTP2Frame.FramePayload
  81. /// │ ▼
  82. ///
  83. public final class Server {
  84. /// Makes and configures a `ServerBootstrap` using the provided configuration.
  85. public class func makeBootstrap(configuration: Configuration) -> ServerBootstrapProtocol {
  86. let bootstrap = PlatformSupport.makeServerBootstrap(group: configuration.eventLoopGroup)
  87. // Backlog is only available on `ServerBootstrap`.
  88. if bootstrap is ServerBootstrap {
  89. // Specify a backlog to avoid overloading the server.
  90. _ = bootstrap.serverChannelOption(ChannelOptions.backlog, value: 256)
  91. }
  92. // Making a `NIOSSLContext` is expensive, we should only do it once per TLS configuration so
  93. // we'll do it now, before accepting connections. Unfortunately our API isn't throwing so we'll
  94. // only surface any error when initializing a child channel.
  95. //
  96. // 'nil' means we're not using TLS, or we're using the Network.framework TLS backend. If we're
  97. // using the Network.framework TLS backend we'll apply the settings just below.
  98. let sslContext: Result<NIOSSLContext, Error>?
  99. if let tlsConfiguration = configuration.tlsConfiguration {
  100. do {
  101. sslContext = try configuration.tlsConfiguration?.makeNIOSSLContext().map { .success($0) }
  102. } catch {
  103. sslContext = .failure(error)
  104. }
  105. // No SSL context means we must be using the Network.framework TLS stack (as
  106. // `tlsConfiguration` was not `nil`).
  107. if sslContext == nil {
  108. #if canImport(Network)
  109. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *),
  110. let transportServicesBootstrap = bootstrap as? NIOTSListenerBootstrap {
  111. _ = transportServicesBootstrap.tlsOptions(from: tlsConfiguration)
  112. }
  113. #else
  114. // We must be using Network.framework (because we aren't using NIOSSL) but we don't have
  115. // an a NIOTSListenerBootstrap available, something is very wrong.
  116. preconditionFailure()
  117. #endif
  118. }
  119. } else {
  120. // No TLS configuration, no SSL context.
  121. sslContext = nil
  122. }
  123. return bootstrap
  124. // Enable `SO_REUSEADDR` to avoid "address already in use" error.
  125. .serverChannelOption(
  126. ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR),
  127. value: 1
  128. )
  129. // Set the handlers that are applied to the accepted Channels
  130. .childChannelInitializer { channel in
  131. var configuration = configuration
  132. configuration.logger[metadataKey: MetadataKey.connectionID] = "\(UUID().uuidString)"
  133. configuration.logger.addIPAddressMetadata(
  134. local: channel.localAddress,
  135. remote: channel.remoteAddress
  136. )
  137. do {
  138. let sync = channel.pipeline.syncOperations
  139. if let sslContext = try sslContext?.get() {
  140. try sync.addHandler(NIOSSLServerHandler(context: sslContext))
  141. }
  142. // Configures the pipeline based on whether the connection uses TLS or not.
  143. try sync.addHandler(GRPCServerPipelineConfigurator(configuration: configuration))
  144. // Work around the zero length write issue, if needed.
  145. let requiresZeroLengthWorkaround = PlatformSupport.requiresZeroLengthWriteWorkaround(
  146. group: configuration.eventLoopGroup,
  147. hasTLS: configuration.tlsConfiguration != nil
  148. )
  149. if requiresZeroLengthWorkaround,
  150. #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  151. try sync.addHandler(NIOFilterEmptyWritesHandler())
  152. }
  153. } catch {
  154. return channel.eventLoop.makeFailedFuture(error)
  155. }
  156. // Run the debug initializer, if there is one.
  157. if let debugAcceptedChannelInitializer = configuration.debugChannelInitializer {
  158. return debugAcceptedChannelInitializer(channel)
  159. } else {
  160. return channel.eventLoop.makeSucceededVoidFuture()
  161. }
  162. }
  163. // Enable TCP_NODELAY and SO_REUSEADDR for the accepted Channels
  164. .childChannelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  165. .childChannelOption(
  166. ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR),
  167. value: 1
  168. )
  169. }
  170. /// Starts a server with the given configuration. See `Server.Configuration` for the options
  171. /// available to configure the server.
  172. public static func start(configuration: Configuration) -> EventLoopFuture<Server> {
  173. let quiescingHelper = ServerQuiescingHelper(group: configuration.eventLoopGroup)
  174. return self.makeBootstrap(configuration: configuration)
  175. .serverChannelInitializer { channel in
  176. channel.pipeline.addHandler(quiescingHelper.makeServerChannelHandler(channel: channel))
  177. }
  178. .bind(to: configuration.target)
  179. .map { channel in
  180. Server(
  181. channel: channel,
  182. quiescingHelper: quiescingHelper,
  183. errorDelegate: configuration.errorDelegate
  184. )
  185. }
  186. }
  187. public let channel: Channel
  188. private let quiescingHelper: ServerQuiescingHelper
  189. private var errorDelegate: ServerErrorDelegate?
  190. private init(
  191. channel: Channel,
  192. quiescingHelper: ServerQuiescingHelper,
  193. errorDelegate: ServerErrorDelegate?
  194. ) {
  195. self.channel = channel
  196. self.quiescingHelper = quiescingHelper
  197. // Maintain a strong reference to ensure it lives as long as the server.
  198. self.errorDelegate = errorDelegate
  199. // If we have an error delegate, add a server channel error handler as well. We don't need to wait for the handler to
  200. // be added.
  201. if let errorDelegate = errorDelegate {
  202. _ = channel.pipeline.addHandler(ServerChannelErrorHandler(errorDelegate: errorDelegate))
  203. }
  204. // nil out errorDelegate to avoid retain cycles.
  205. self.onClose.whenComplete { _ in
  206. self.errorDelegate = nil
  207. }
  208. }
  209. /// Fired when the server shuts down.
  210. public var onClose: EventLoopFuture<Void> {
  211. return self.channel.closeFuture
  212. }
  213. /// Initiates a graceful shutdown. Existing RPCs may run to completion, any new RPCs or
  214. /// connections will be rejected.
  215. public func initiateGracefulShutdown(promise: EventLoopPromise<Void>?) {
  216. self.quiescingHelper.initiateShutdown(promise: promise)
  217. }
  218. /// Initiates a graceful shutdown. Existing RPCs may run to completion, any new RPCs or
  219. /// connections will be rejected.
  220. public func initiateGracefulShutdown() -> EventLoopFuture<Void> {
  221. let promise = self.channel.eventLoop.makePromise(of: Void.self)
  222. self.initiateGracefulShutdown(promise: promise)
  223. return promise.futureResult
  224. }
  225. /// Shutdown the server immediately. Active RPCs and connections will be terminated.
  226. public func close(promise: EventLoopPromise<Void>?) {
  227. self.channel.close(mode: .all, promise: promise)
  228. }
  229. /// Shutdown the server immediately. Active RPCs and connections will be terminated.
  230. public func close() -> EventLoopFuture<Void> {
  231. return self.channel.close(mode: .all)
  232. }
  233. }
  234. public typealias BindTarget = ConnectionTarget
  235. extension Server {
  236. /// The configuration for a server.
  237. public struct Configuration {
  238. /// The target to bind to.
  239. public var target: BindTarget
  240. /// The event loop group to run the connection on.
  241. public var eventLoopGroup: EventLoopGroup
  242. /// Providers the server should use to handle gRPC requests.
  243. public var serviceProviders: [CallHandlerProvider] {
  244. get {
  245. return Array(self.serviceProvidersByName.values)
  246. }
  247. set {
  248. self
  249. .serviceProvidersByName = Dictionary(
  250. uniqueKeysWithValues: newValue
  251. .map { ($0.serviceName, $0) }
  252. )
  253. }
  254. }
  255. /// An error delegate which is called when errors are caught. Provided delegates **must not
  256. /// maintain a strong reference to this `Server`**. Doing so will cause a retain cycle.
  257. public var errorDelegate: ServerErrorDelegate?
  258. /// TLS configuration for this connection. `nil` if TLS is not desired.
  259. @available(*, deprecated, renamed: "tlsConfiguration")
  260. public var tls: TLS? {
  261. get {
  262. return self.tlsConfiguration?.asDeprecatedServerConfiguration
  263. }
  264. set {
  265. self.tlsConfiguration = newValue.map { GRPCTLSConfiguration(transforming: $0) }
  266. }
  267. }
  268. public var tlsConfiguration: GRPCTLSConfiguration?
  269. /// The connection keepalive configuration.
  270. public var connectionKeepalive = ServerConnectionKeepalive()
  271. /// The amount of time to wait before closing connections. The idle timeout will start only
  272. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  273. public var connectionIdleTimeout: TimeAmount = .nanoseconds(.max)
  274. /// The compression configuration for requests and responses.
  275. ///
  276. /// If compression is enabled for the server it may be disabled for responses on any RPC by
  277. /// setting `compressionEnabled` to `false` on the context of the call.
  278. ///
  279. /// Compression may also be disabled at the message-level for streaming responses (i.e. server
  280. /// streaming and bidirectional streaming RPCs) by passing setting `compression` to `.disabled`
  281. /// in `sendResponse(_:compression)`.
  282. ///
  283. /// Defaults to `.disabled`.
  284. public var messageEncoding: ServerMessageEncoding = .disabled
  285. /// The maximum size in bytes of a message which may be received from a client. Defaults to 4MB.
  286. public var maximumReceiveMessageLength: Int = 4 * 1024 * 1024 {
  287. willSet {
  288. precondition(newValue >= 0, "maximumReceiveMessageLength must be positive")
  289. }
  290. }
  291. /// The HTTP/2 flow control target window size. Defaults to 65535.
  292. public var httpTargetWindowSize: Int = 65535
  293. /// The HTTP/2 max number of concurrent streams. Defaults to 100. Must be non-negative.
  294. public var httpMaxConcurrentStreams: Int = 100 {
  295. willSet {
  296. precondition(newValue >= 0, "httpMaxConcurrentStreams must be non-negative")
  297. }
  298. }
  299. /// The HTTP/2 max frame size. Defaults to 16384. Value is clamped between 2^14 and 2^24-1
  300. /// octets inclusive (the minimum and maximum allowable values - HTTP/2 RFC 7540 4.2).
  301. public var httpMaxFrameSize: Int = 16384 {
  302. didSet(httpMaxFrameSize) {
  303. self.httpMaxFrameSize = httpMaxFrameSize.clamped(to: 16384 ... 16_777_215)
  304. }
  305. }
  306. /// The root server logger. Accepted connections will branch from this logger and RPCs on
  307. /// each connection will use a logger branched from the connections logger. This logger is made
  308. /// available to service providers via `context`. Defaults to a no-op logger.
  309. public var logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() })
  310. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  311. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  312. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  313. ///
  314. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  315. /// be invoked at most once per accepted connection.
  316. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
  317. /// A calculated private cache of the service providers by name.
  318. ///
  319. /// This is how gRPC consumes the service providers internally. Caching this as stored data avoids
  320. /// the need to recalculate this dictionary each time we receive an rpc.
  321. internal var serviceProvidersByName: [Substring: CallHandlerProvider]
  322. /// Create a `Configuration` with some pre-defined defaults.
  323. ///
  324. /// - Parameters:
  325. /// - target: The target to bind to.
  326. /// - eventLoopGroup: The event loop group to run the server on.
  327. /// - serviceProviders: An array of `CallHandlerProvider`s which the server should use
  328. /// to handle requests.
  329. /// - errorDelegate: The error delegate, defaulting to a logging delegate.
  330. /// - tls: TLS configuration, defaulting to `nil`.
  331. /// - connectionKeepalive: The keepalive configuration to use.
  332. /// - connectionIdleTimeout: The amount of time to wait before closing the connection, this is
  333. /// indefinite by default.
  334. /// - messageEncoding: Message compression configuration, defaulting to no compression.
  335. /// - httpTargetWindowSize: The HTTP/2 flow control target window size.
  336. /// - logger: A logger. Defaults to a no-op logger.
  337. /// - debugChannelInitializer: A channel initializer which will be called for each connection
  338. /// the server accepts after gRPC has initialized the channel. Defaults to `nil`.
  339. @available(*, deprecated, renamed: "default(target:eventLoopGroup:serviceProviders:)")
  340. public init(
  341. target: BindTarget,
  342. eventLoopGroup: EventLoopGroup,
  343. serviceProviders: [CallHandlerProvider],
  344. errorDelegate: ServerErrorDelegate? = nil,
  345. tls: TLS? = nil,
  346. connectionKeepalive: ServerConnectionKeepalive = ServerConnectionKeepalive(),
  347. connectionIdleTimeout: TimeAmount = .nanoseconds(.max),
  348. messageEncoding: ServerMessageEncoding = .disabled,
  349. httpTargetWindowSize: Int = 65535,
  350. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() }),
  351. debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? = nil
  352. ) {
  353. self.target = target
  354. self.eventLoopGroup = eventLoopGroup
  355. self
  356. .serviceProvidersByName = Dictionary(
  357. uniqueKeysWithValues: serviceProviders
  358. .map { ($0.serviceName, $0) }
  359. )
  360. self.errorDelegate = errorDelegate
  361. self.tlsConfiguration = tls.map { GRPCTLSConfiguration(transforming: $0) }
  362. self.connectionKeepalive = connectionKeepalive
  363. self.connectionIdleTimeout = connectionIdleTimeout
  364. self.messageEncoding = messageEncoding
  365. self.httpTargetWindowSize = httpTargetWindowSize
  366. self.logger = logger
  367. self.debugChannelInitializer = debugChannelInitializer
  368. }
  369. private init(
  370. eventLoopGroup: EventLoopGroup,
  371. target: BindTarget,
  372. serviceProviders: [CallHandlerProvider]
  373. ) {
  374. self.eventLoopGroup = eventLoopGroup
  375. self.target = target
  376. self.serviceProvidersByName = Dictionary(uniqueKeysWithValues: serviceProviders.map {
  377. ($0.serviceName, $0)
  378. })
  379. }
  380. /// Make a new configuration using default values.
  381. ///
  382. /// - Parameters:
  383. /// - target: The target to bind to.
  384. /// - eventLoopGroup: The `EventLoopGroup` the server should run on.
  385. /// - serviceProviders: An array of `CallHandlerProvider`s which the server should use
  386. /// to handle requests.
  387. /// - Returns: A configuration with default values set.
  388. public static func `default`(
  389. target: BindTarget,
  390. eventLoopGroup: EventLoopGroup,
  391. serviceProviders: [CallHandlerProvider]
  392. ) -> Configuration {
  393. return .init(
  394. eventLoopGroup: eventLoopGroup,
  395. target: target,
  396. serviceProviders: serviceProviders
  397. )
  398. }
  399. }
  400. }
  401. private extension ServerBootstrapProtocol {
  402. func bind(to target: BindTarget) -> EventLoopFuture<Channel> {
  403. switch target.wrapped {
  404. case let .hostAndPort(host, port):
  405. return self.bind(host: host, port: port)
  406. case let .unixDomainSocket(path):
  407. return self.bind(unixDomainSocketPath: path)
  408. case let .socketAddress(address):
  409. return self.bind(to: address)
  410. }
  411. }
  412. }
  413. extension Comparable {
  414. fileprivate func clamped(to range: ClosedRange<Self>) -> Self {
  415. return min(max(self, range.lowerBound), range.upperBound)
  416. }
  417. }