2
0

Server.swift 16 KB

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