GRPCIdleHandler.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. /*
  2. * Copyright 2020, 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 NIOCore
  18. import NIOHTTP2
  19. import NIOTLS
  20. internal final class GRPCIdleHandler: ChannelInboundHandler {
  21. typealias InboundIn = HTTP2Frame
  22. typealias OutboundOut = HTTP2Frame
  23. /// The amount of time to wait before closing the channel when there are no active streams.
  24. private let idleTimeout: TimeAmount
  25. /// The ping handler.
  26. private var pingHandler: PingHandler
  27. /// The scheduled task which will close the connection after the keep-alive timeout has expired.
  28. private var scheduledClose: Scheduled<Void>?
  29. /// The scheduled task which will ping.
  30. private var scheduledPing: RepeatedTask?
  31. /// The mode we're operating in.
  32. private let mode: Mode
  33. private var context: ChannelHandlerContext?
  34. /// The mode of operation: the client tracks additional connection state in the connection
  35. /// manager.
  36. internal enum Mode {
  37. case client(ConnectionManager, HTTP2StreamMultiplexer)
  38. case server
  39. var connectionManager: ConnectionManager? {
  40. switch self {
  41. case let .client(manager, _):
  42. return manager
  43. case .server:
  44. return nil
  45. }
  46. }
  47. }
  48. /// The current state.
  49. private var stateMachine: GRPCIdleHandlerStateMachine
  50. init(
  51. connectionManager: ConnectionManager,
  52. multiplexer: HTTP2StreamMultiplexer,
  53. idleTimeout: TimeAmount,
  54. keepalive configuration: ClientConnectionKeepalive,
  55. logger: Logger
  56. ) {
  57. self.mode = .client(connectionManager, multiplexer)
  58. self.idleTimeout = idleTimeout
  59. self.stateMachine = .init(role: .client, logger: logger)
  60. self.pingHandler = PingHandler(
  61. pingCode: 5,
  62. interval: configuration.interval,
  63. timeout: configuration.timeout,
  64. permitWithoutCalls: configuration.permitWithoutCalls,
  65. maximumPingsWithoutData: configuration.maximumPingsWithoutData,
  66. minimumSentPingIntervalWithoutData: configuration.minimumSentPingIntervalWithoutData
  67. )
  68. }
  69. init(
  70. idleTimeout: TimeAmount,
  71. keepalive configuration: ServerConnectionKeepalive,
  72. logger: Logger
  73. ) {
  74. self.mode = .server
  75. self.stateMachine = .init(role: .server, logger: logger)
  76. self.idleTimeout = idleTimeout
  77. self.pingHandler = PingHandler(
  78. pingCode: 10,
  79. interval: configuration.interval,
  80. timeout: configuration.timeout,
  81. permitWithoutCalls: configuration.permitWithoutCalls,
  82. maximumPingsWithoutData: configuration.maximumPingsWithoutData,
  83. minimumSentPingIntervalWithoutData: configuration.minimumSentPingIntervalWithoutData,
  84. minimumReceivedPingIntervalWithoutData: configuration.minimumReceivedPingIntervalWithoutData,
  85. maximumPingStrikes: configuration.maximumPingStrikes
  86. )
  87. }
  88. private func perform(operations: GRPCIdleHandlerStateMachine.Operations) {
  89. // Prod the connection manager.
  90. if let event = operations.connectionManagerEvent, let manager = self.mode.connectionManager {
  91. switch event {
  92. case .idle:
  93. manager.idle()
  94. case .inactive:
  95. manager.channelInactive()
  96. case .ready:
  97. manager.ready()
  98. case .quiescing:
  99. manager.beginQuiescing()
  100. }
  101. }
  102. // Max concurrent streams changed.
  103. if let manager = self.mode.connectionManager,
  104. let maxConcurrentStreams = operations.maxConcurrentStreamsChange
  105. {
  106. manager.maxConcurrentStreamsChanged(maxConcurrentStreams)
  107. }
  108. // Handle idle timeout creation/cancellation.
  109. if let idleTask = operations.idleTask {
  110. switch idleTask {
  111. case let .cancel(task):
  112. self.stateMachine.logger.debug("idle timeout task cancelled")
  113. task.cancel()
  114. case .schedule:
  115. if self.idleTimeout != .nanoseconds(.max), let context = self.context {
  116. self.stateMachine.logger.debug(
  117. "scheduling idle timeout task",
  118. metadata: [MetadataKey.delayMs: "\(self.idleTimeout.milliseconds)"]
  119. )
  120. let task = context.eventLoop.scheduleTask(in: self.idleTimeout) {
  121. self.stateMachine.logger.debug("idle timeout task fired")
  122. self.idleTimeoutFired()
  123. }
  124. self.perform(operations: self.stateMachine.scheduledIdleTimeoutTask(task))
  125. }
  126. }
  127. }
  128. // Send a GOAWAY frame.
  129. if let streamID = operations.sendGoAwayWithLastPeerInitiatedStreamID {
  130. self.stateMachine.logger.debug(
  131. "sending GOAWAY frame",
  132. metadata: [
  133. MetadataKey.h2GoAwayLastStreamID: "\(Int(streamID))"
  134. ]
  135. )
  136. let goAwayFrame = HTTP2Frame(
  137. streamID: .rootStream,
  138. payload: .goAway(lastStreamID: streamID, errorCode: .noError, opaqueData: nil)
  139. )
  140. self.context?.write(self.wrapOutboundOut(goAwayFrame), promise: nil)
  141. // We emit a ping after some GOAWAY frames.
  142. if operations.shouldPingAfterGoAway {
  143. let pingFrame = HTTP2Frame(
  144. streamID: .rootStream,
  145. payload: .ping(self.pingHandler.pingDataGoAway, ack: false)
  146. )
  147. self.context?.write(self.wrapOutboundOut(pingFrame), promise: nil)
  148. }
  149. self.context?.flush()
  150. }
  151. // Close the channel, if necessary.
  152. if operations.shouldCloseChannel, let context = self.context {
  153. // Close on the next event-loop tick so we don't drop any events which are
  154. // currently being processed.
  155. context.eventLoop.execute {
  156. self.stateMachine.logger.debug("closing connection")
  157. context.close(mode: .all, promise: nil)
  158. }
  159. }
  160. }
  161. private func handlePingAction(_ action: PingHandler.Action) {
  162. switch action {
  163. case .none:
  164. ()
  165. case .ack:
  166. // NIO's HTTP2 handler acks for us so this is a no-op. Log so it doesn't appear that we are
  167. // ignoring pings.
  168. self.stateMachine.logger.debug(
  169. "sending PING frame",
  170. metadata: [MetadataKey.h2PingAck: "true"]
  171. )
  172. case .cancelScheduledTimeout:
  173. self.scheduledClose?.cancel()
  174. self.scheduledClose = nil
  175. case let .schedulePing(delay, timeout):
  176. self.schedulePing(in: delay, timeout: timeout)
  177. case let .reply(framePayload):
  178. switch framePayload {
  179. case .ping(_, let ack):
  180. self.stateMachine.logger.debug(
  181. "sending PING frame",
  182. metadata: [MetadataKey.h2PingAck: "\(ack)"]
  183. )
  184. default:
  185. ()
  186. }
  187. let frame = HTTP2Frame(streamID: .rootStream, payload: framePayload)
  188. self.context?.writeAndFlush(self.wrapOutboundOut(frame), promise: nil)
  189. case .ratchetDownLastSeenStreamID:
  190. self.perform(operations: self.stateMachine.ratchetDownGoAwayStreamID())
  191. }
  192. }
  193. private func schedulePing(in delay: TimeAmount, timeout: TimeAmount) {
  194. guard delay != .nanoseconds(.max) else {
  195. return
  196. }
  197. self.stateMachine.logger.debug(
  198. "scheduled keepalive pings",
  199. metadata: [MetadataKey.intervalMs: "\(delay.milliseconds)"]
  200. )
  201. self.scheduledPing = self.context?.eventLoop.scheduleRepeatedTask(
  202. initialDelay: delay,
  203. delay: delay
  204. ) { _ in
  205. let action = self.pingHandler.pingFired()
  206. if case .none = action { return }
  207. self.handlePingAction(action)
  208. // `timeout` is less than `interval`, guaranteeing that the close task
  209. // will be fired before a new ping is triggered.
  210. assert(timeout < delay, "`timeout` must be less than `interval`")
  211. self.scheduleClose(in: timeout)
  212. }
  213. }
  214. private func scheduleClose(in timeout: TimeAmount) {
  215. self.scheduledClose = self.context?.eventLoop.scheduleTask(in: timeout) {
  216. self.stateMachine.logger.debug("keepalive timer expired")
  217. self.perform(operations: self.stateMachine.shutdownNow())
  218. }
  219. }
  220. private func idleTimeoutFired() {
  221. self.perform(operations: self.stateMachine.idleTimeoutTaskFired())
  222. }
  223. func handlerAdded(context: ChannelHandlerContext) {
  224. self.context = context
  225. }
  226. func handlerRemoved(context: ChannelHandlerContext) {
  227. self.context = nil
  228. }
  229. func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
  230. if let created = event as? NIOHTTP2StreamCreatedEvent {
  231. self.perform(operations: self.stateMachine.streamCreated(withID: created.streamID))
  232. self.handlePingAction(self.pingHandler.streamCreated())
  233. self.mode.connectionManager?.streamOpened()
  234. context.fireUserInboundEventTriggered(event)
  235. } else if let closed = event as? StreamClosedEvent {
  236. self.perform(operations: self.stateMachine.streamClosed(withID: closed.streamID))
  237. self.handlePingAction(self.pingHandler.streamClosed())
  238. self.mode.connectionManager?.streamClosed()
  239. context.fireUserInboundEventTriggered(event)
  240. } else if event is ChannelShouldQuiesceEvent {
  241. self.perform(operations: self.stateMachine.initiateGracefulShutdown())
  242. // Swallow this event.
  243. } else if case let .handshakeCompleted(negotiatedProtocol) = event as? TLSUserEvent {
  244. let tlsVersion = try? context.channel.getTLSVersionSync()
  245. self.stateMachine.logger.debug(
  246. "TLS handshake completed",
  247. metadata: [
  248. "alpn": "\(negotiatedProtocol ?? "nil")",
  249. "tls_version": "\(tlsVersion.map(String.init(describing:)) ?? "nil")",
  250. ]
  251. )
  252. context.fireUserInboundEventTriggered(event)
  253. } else {
  254. context.fireUserInboundEventTriggered(event)
  255. }
  256. }
  257. func errorCaught(context: ChannelHandlerContext, error: Error) {
  258. // No state machine action here.
  259. self.mode.connectionManager?.channelError(error)
  260. context.fireErrorCaught(error)
  261. }
  262. func channelActive(context: ChannelHandlerContext) {
  263. self.stateMachine.logger.addIPAddressMetadata(
  264. local: context.localAddress,
  265. remote: context.remoteAddress
  266. )
  267. // No state machine action here.
  268. switch self.mode {
  269. case let .client(connectionManager, multiplexer):
  270. connectionManager.channelActive(channel: context.channel, multiplexer: multiplexer)
  271. case .server:
  272. ()
  273. }
  274. context.fireChannelActive()
  275. }
  276. func channelInactive(context: ChannelHandlerContext) {
  277. self.perform(operations: self.stateMachine.channelInactive())
  278. self.scheduledPing?.cancel()
  279. self.scheduledClose?.cancel()
  280. self.scheduledPing = nil
  281. self.scheduledClose = nil
  282. context.fireChannelInactive()
  283. }
  284. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  285. let frame = self.unwrapInboundIn(data)
  286. switch frame.payload {
  287. case let .goAway(lastStreamID, errorCode, _):
  288. self.stateMachine.logger.debug(
  289. "received GOAWAY frame",
  290. metadata: [
  291. MetadataKey.h2GoAwayLastStreamID: "\(Int(lastStreamID))",
  292. MetadataKey.h2GoAwayError: "\(errorCode.networkCode)",
  293. ]
  294. )
  295. self.perform(operations: self.stateMachine.receiveGoAway())
  296. case let .settings(.settings(settings)):
  297. self.perform(operations: self.stateMachine.receiveSettings(settings))
  298. case let .ping(data, ack):
  299. self.stateMachine.logger.debug(
  300. "received PING frame",
  301. metadata: [MetadataKey.h2PingAck: "\(ack)"]
  302. )
  303. self.handlePingAction(self.pingHandler.read(pingData: data, ack: ack))
  304. default:
  305. // We're not interested in other events.
  306. ()
  307. }
  308. context.fireChannelRead(data)
  309. }
  310. }
  311. extension HTTP2SettingsParameter {
  312. internal var loggingMetadataKey: String {
  313. switch self {
  314. case .headerTableSize:
  315. return "h2_settings_header_table_size"
  316. case .enablePush:
  317. return "h2_settings_enable_push"
  318. case .maxConcurrentStreams:
  319. return "h2_settings_max_concurrent_streams"
  320. case .initialWindowSize:
  321. return "h2_settings_initial_window_size"
  322. case .maxFrameSize:
  323. return "h2_settings_max_frame_size"
  324. case .maxHeaderListSize:
  325. return "h2_settings_max_header_list_size"
  326. case .enableConnectProtocol:
  327. return "h2_settings_enable_connect_protocol"
  328. default:
  329. return String(describing: self)
  330. }
  331. }
  332. }
  333. extension TimeAmount {
  334. fileprivate var milliseconds: Int64 {
  335. self.nanoseconds / 1_000_000
  336. }
  337. }