Server.swift 18 KB

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