GRPCIdleHandler.swift 13 KB

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