Server.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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[metadataKey: MetadataKey.remoteAddress] = channel.remoteAddress
  107. .map { "\($0)" } ?? "n/a"
  108. do {
  109. let sync = channel.pipeline.syncOperations
  110. if let sslContext = try sslContext?.get() {
  111. try sync.addHandler(NIOSSLServerHandler(context: sslContext))
  112. }
  113. // Configures the pipeline based on whether the connection uses TLS or not.
  114. try sync.addHandler(GRPCServerPipelineConfigurator(configuration: configuration))
  115. // Work around the zero length write issue, if needed.
  116. let requiresZeroLengthWorkaround = PlatformSupport.requiresZeroLengthWriteWorkaround(
  117. group: configuration.eventLoopGroup,
  118. hasTLS: configuration.tls != nil
  119. )
  120. if requiresZeroLengthWorkaround,
  121. #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  122. try sync.addHandler(NIOFilterEmptyWritesHandler())
  123. }
  124. } catch {
  125. return channel.eventLoop.makeFailedFuture(error)
  126. }
  127. // Run the debug initializer, if there is one.
  128. if let debugAcceptedChannelInitializer = configuration.debugChannelInitializer {
  129. return debugAcceptedChannelInitializer(channel)
  130. } else {
  131. return channel.eventLoop.makeSucceededVoidFuture()
  132. }
  133. }
  134. // Enable TCP_NODELAY and SO_REUSEADDR for the accepted Channels
  135. .childChannelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  136. .childChannelOption(
  137. ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR),
  138. value: 1
  139. )
  140. }
  141. /// Starts a server with the given configuration. See `Server.Configuration` for the options
  142. /// available to configure the server.
  143. public static func start(configuration: Configuration) -> EventLoopFuture<Server> {
  144. let quiescingHelper = ServerQuiescingHelper(group: configuration.eventLoopGroup)
  145. return self.makeBootstrap(configuration: configuration)
  146. .serverChannelInitializer { channel in
  147. channel.pipeline.addHandler(quiescingHelper.makeServerChannelHandler(channel: channel))
  148. }
  149. .bind(to: configuration.target)
  150. .map { channel in
  151. Server(
  152. channel: channel,
  153. quiescingHelper: quiescingHelper,
  154. errorDelegate: configuration.errorDelegate
  155. )
  156. }
  157. }
  158. public let channel: Channel
  159. private let quiescingHelper: ServerQuiescingHelper
  160. private var errorDelegate: ServerErrorDelegate?
  161. private init(
  162. channel: Channel,
  163. quiescingHelper: ServerQuiescingHelper,
  164. errorDelegate: ServerErrorDelegate?
  165. ) {
  166. self.channel = channel
  167. self.quiescingHelper = quiescingHelper
  168. // Maintain a strong reference to ensure it lives as long as the server.
  169. self.errorDelegate = errorDelegate
  170. // If we have an error delegate, add a server channel error handler as well. We don't need to wait for the handler to
  171. // be added.
  172. if let errorDelegate = errorDelegate {
  173. _ = channel.pipeline.addHandler(ServerChannelErrorHandler(errorDelegate: errorDelegate))
  174. }
  175. // nil out errorDelegate to avoid retain cycles.
  176. self.onClose.whenComplete { _ in
  177. self.errorDelegate = nil
  178. }
  179. }
  180. /// Fired when the server shuts down.
  181. public var onClose: EventLoopFuture<Void> {
  182. return self.channel.closeFuture
  183. }
  184. /// Initiates a graceful shutdown. Existing RPCs may run to completion, any new RPCs or
  185. /// connections will be rejected.
  186. public func initiateGracefulShutdown(promise: EventLoopPromise<Void>?) {
  187. self.quiescingHelper.initiateShutdown(promise: promise)
  188. }
  189. /// Initiates a graceful shutdown. Existing RPCs may run to completion, any new RPCs or
  190. /// connections will be rejected.
  191. public func initiateGracefulShutdown() -> EventLoopFuture<Void> {
  192. let promise = self.channel.eventLoop.makePromise(of: Void.self)
  193. self.initiateGracefulShutdown(promise: promise)
  194. return promise.futureResult
  195. }
  196. /// Shutdown the server immediately. Active RPCs and connections will be terminated.
  197. public func close(promise: EventLoopPromise<Void>?) {
  198. self.channel.close(mode: .all, promise: promise)
  199. }
  200. /// Shutdown the server immediately. Active RPCs and connections will be terminated.
  201. public func close() -> EventLoopFuture<Void> {
  202. return self.channel.close(mode: .all)
  203. }
  204. }
  205. public typealias BindTarget = ConnectionTarget
  206. extension Server {
  207. /// The configuration for a server.
  208. public struct Configuration {
  209. /// The target to bind to.
  210. public var target: BindTarget
  211. /// The event loop group to run the connection on.
  212. public var eventLoopGroup: EventLoopGroup
  213. /// Providers the server should use to handle gRPC requests.
  214. public var serviceProviders: [CallHandlerProvider] {
  215. get {
  216. return Array(self.serviceProvidersByName.values)
  217. }
  218. set {
  219. self
  220. .serviceProvidersByName = Dictionary(
  221. uniqueKeysWithValues: newValue
  222. .map { ($0.serviceName, $0) }
  223. )
  224. }
  225. }
  226. /// An error delegate which is called when errors are caught. Provided delegates **must not
  227. /// maintain a strong reference to this `Server`**. Doing so will cause a retain cycle.
  228. public var errorDelegate: ServerErrorDelegate?
  229. /// TLS configuration for this connection. `nil` if TLS is not desired.
  230. public var tls: TLS?
  231. /// The connection keepalive configuration.
  232. public var connectionKeepalive: ServerConnectionKeepalive
  233. /// The amount of time to wait before closing connections. The idle timeout will start only
  234. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  235. public var connectionIdleTimeout: TimeAmount
  236. /// The compression configuration for requests and responses.
  237. ///
  238. /// If compression is enabled for the server it may be disabled for responses on any RPC by
  239. /// setting `compressionEnabled` to `false` on the context of the call.
  240. ///
  241. /// Compression may also be disabled at the message-level for streaming responses (i.e. server
  242. /// streaming and bidirectional streaming RPCs) by passing setting `compression` to `.disabled`
  243. /// in `sendResponse(_:compression)`.
  244. public var messageEncoding: ServerMessageEncoding
  245. /// The HTTP/2 flow control target window size.
  246. public var httpTargetWindowSize: Int
  247. /// The root server logger. Accepted connections will branch from this logger and RPCs on
  248. /// each connection will use a logger branched from the connections logger. This logger is made
  249. /// available to service providers via `context`. Defaults to a no-op logger.
  250. public var logger: Logger
  251. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  252. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  253. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  254. ///
  255. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  256. /// be invoked at most once per accepted connection.
  257. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
  258. /// A calculated private cache of the service providers by name.
  259. ///
  260. /// This is how gRPC consumes the service providers internally. Caching this as stored data avoids
  261. /// the need to recalculate this dictionary each time we receive an rpc.
  262. internal var serviceProvidersByName: [Substring: CallHandlerProvider]
  263. /// Create a `Configuration` with some pre-defined defaults.
  264. ///
  265. /// - Parameters:
  266. /// - target: The target to bind to.
  267. /// - eventLoopGroup: The event loop group to run the server on.
  268. /// - serviceProviders: An array of `CallHandlerProvider`s which the server should use
  269. /// to handle requests.
  270. /// - errorDelegate: The error delegate, defaulting to a logging delegate.
  271. /// - tls: TLS configuration, defaulting to `nil`.
  272. /// - connectionKeepalive: The keepalive configuration to use.
  273. /// - connectionIdleTimeout: The amount of time to wait before closing the connection, this is
  274. /// indefinite by default.
  275. /// - messageEncoding: Message compression configuration, defaulting to no compression.
  276. /// - httpTargetWindowSize: The HTTP/2 flow control target window size.
  277. /// - logger: A logger. Defaults to a no-op logger.
  278. /// - debugChannelInitializer: A channel initializer which will be called for each connection
  279. /// the server accepts after gRPC has initialized the channel. Defaults to `nil`.
  280. public init(
  281. target: BindTarget,
  282. eventLoopGroup: EventLoopGroup,
  283. serviceProviders: [CallHandlerProvider],
  284. errorDelegate: ServerErrorDelegate? = nil,
  285. tls: TLS? = nil,
  286. connectionKeepalive: ServerConnectionKeepalive = ServerConnectionKeepalive(),
  287. connectionIdleTimeout: TimeAmount = .nanoseconds(.max),
  288. messageEncoding: ServerMessageEncoding = .disabled,
  289. httpTargetWindowSize: Int = 65535,
  290. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() }),
  291. debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? = nil
  292. ) {
  293. self.target = target
  294. self.eventLoopGroup = eventLoopGroup
  295. self
  296. .serviceProvidersByName = Dictionary(
  297. uniqueKeysWithValues: serviceProviders
  298. .map { ($0.serviceName, $0) }
  299. )
  300. self.errorDelegate = errorDelegate
  301. self.tls = tls
  302. self.connectionKeepalive = connectionKeepalive
  303. self.connectionIdleTimeout = connectionIdleTimeout
  304. self.messageEncoding = messageEncoding
  305. self.httpTargetWindowSize = httpTargetWindowSize
  306. self.logger = logger
  307. self.debugChannelInitializer = debugChannelInitializer
  308. }
  309. }
  310. }
  311. private extension ServerBootstrapProtocol {
  312. func bind(to target: BindTarget) -> EventLoopFuture<Channel> {
  313. switch target.wrapped {
  314. case let .hostAndPort(host, port):
  315. return self.bind(host: host, port: port)
  316. case let .unixDomainSocket(path):
  317. return self.bind(unixDomainSocketPath: path)
  318. case let .socketAddress(address):
  319. return self.bind(to: address)
  320. }
  321. }
  322. }