GRPCKeepaliveHandlers.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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 NIO
  17. import NIOHTTP2
  18. /// Provides keepalive pings.
  19. ///
  20. /// The logic is determined by the gRPC keepalive
  21. /// [documentation] (https://github.com/grpc/grpc/blob/master/doc/keepalive.md).
  22. internal class GRPCClientKeepaliveHandler: ChannelInboundHandler, _ChannelKeepaliveHandler {
  23. typealias InboundIn = HTTP2Frame
  24. typealias OutboundOut = HTTP2Frame
  25. init(configuration: ClientConnectionKeepalive) {
  26. self.pingHandler = PingHandler(
  27. pingCode: 5,
  28. interval: configuration.interval,
  29. timeout: configuration.timeout,
  30. permitWithoutCalls: configuration.permitWithoutCalls,
  31. maximumPingsWithoutData: configuration.maximumPingsWithoutData,
  32. minimumSentPingIntervalWithoutData: configuration.minimumSentPingIntervalWithoutData
  33. )
  34. }
  35. /// The ping handler.
  36. var pingHandler: PingHandler
  37. /// The scheduled task which will ping.
  38. var scheduledPing: RepeatedTask?
  39. /// The scheduled task which will close the connection.
  40. var scheduledClose: Scheduled<Void>?
  41. }
  42. internal class GRPCServerKeepaliveHandler: ChannelInboundHandler, _ChannelKeepaliveHandler {
  43. typealias InboundIn = HTTP2Frame
  44. typealias OutboundOut = HTTP2Frame
  45. init(configuration: ServerConnectionKeepalive) {
  46. self.pingHandler = PingHandler(
  47. pingCode: 10,
  48. interval: configuration.interval,
  49. timeout: configuration.timeout,
  50. permitWithoutCalls: configuration.permitWithoutCalls,
  51. maximumPingsWithoutData: configuration.maximumPingsWithoutData,
  52. minimumSentPingIntervalWithoutData: configuration.minimumSentPingIntervalWithoutData,
  53. minimumReceivedPingIntervalWithoutData: configuration.minimumReceivedPingIntervalWithoutData,
  54. maximumPingStrikes: configuration.maximumPingStrikes
  55. )
  56. }
  57. /// The ping handler.
  58. var pingHandler: PingHandler
  59. /// The scheduled task which will ping.
  60. var scheduledPing: RepeatedTask?
  61. /// The scheduled task which will close the connection.
  62. var scheduledClose: Scheduled<Void>?
  63. }
  64. protocol _ChannelKeepaliveHandler: ChannelInboundHandler where OutboundOut == HTTP2Frame,
  65. InboundIn == HTTP2Frame {
  66. var pingHandler: PingHandler { get set }
  67. var scheduledPing: RepeatedTask? { get set }
  68. var scheduledClose: Scheduled<Void>? { get set }
  69. }
  70. extension _ChannelKeepaliveHandler {
  71. func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
  72. if event is NIOHTTP2StreamCreatedEvent {
  73. self.perform(action: self.pingHandler.streamCreated(), context: context)
  74. } else if event is StreamClosedEvent {
  75. self.perform(action: self.pingHandler.streamClosed(), context: context)
  76. }
  77. context.fireUserInboundEventTriggered(event)
  78. }
  79. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  80. switch self.unwrapInboundIn(data).payload {
  81. case let .ping(pingData, ack: ack):
  82. self.perform(action: self.pingHandler.read(pingData: pingData, ack: ack), context: context)
  83. default:
  84. break
  85. }
  86. context.fireChannelRead(data)
  87. }
  88. func handlerRemoved(context: ChannelHandlerContext) {
  89. self.cancelScheduledPing()
  90. self.cancelScheduledTimeout()
  91. }
  92. private func perform(action: PingHandler.Action, context: ChannelHandlerContext) {
  93. switch action {
  94. case let .schedulePing(delay, timeout):
  95. self.schedulePing(delay: delay, timeout: timeout, context: context)
  96. case .cancelScheduledTimeout:
  97. self.cancelScheduledTimeout()
  98. case let .reply(payload):
  99. self.send(payload: payload, context: context)
  100. case .none:
  101. break
  102. }
  103. }
  104. private func send(payload: HTTP2Frame.FramePayload, context: ChannelHandlerContext) {
  105. let frame = self.wrapOutboundOut(.init(streamID: .rootStream, payload: payload))
  106. context.writeAndFlush(frame, promise: nil)
  107. }
  108. private func schedulePing(delay: TimeAmount, timeout: TimeAmount,
  109. context: ChannelHandlerContext) {
  110. guard delay != .nanoseconds(Int64.max) else { return }
  111. self.scheduledPing = context.eventLoop
  112. .scheduleRepeatedTask(initialDelay: delay, delay: delay) { _ in
  113. self.perform(action: self.pingHandler.pingFired(), context: context)
  114. // `timeout` is less than `interval`, guaranteeing that the close task
  115. // will be fired before a new ping is triggered.
  116. assert(timeout < delay, "`timeout` must be less than `interval`")
  117. self.scheduleClose(timeout: timeout, context: context)
  118. }
  119. }
  120. private func scheduleClose(timeout: TimeAmount, context: ChannelHandlerContext) {
  121. self.scheduledClose = context.eventLoop.scheduleTask(in: timeout) {
  122. context.fireUserInboundEventTriggered(ConnectionIdledEvent())
  123. }
  124. }
  125. private func cancelScheduledPing() {
  126. self.scheduledPing?.cancel()
  127. self.scheduledPing = nil
  128. }
  129. private func cancelScheduledTimeout() {
  130. self.scheduledClose?.cancel()
  131. self.scheduledClose = nil
  132. }
  133. }
  134. struct PingHandler {
  135. /// Code for ping
  136. private let pingCode: UInt64
  137. /// The amount of time to wait before sending a keepalive ping.
  138. private let interval: TimeAmount
  139. /// The amount of time to wait for an acknowledgment.
  140. /// If it does not receive an acknowledgment within this time, it will close the connection
  141. private let timeout: TimeAmount
  142. /// Send keepalive pings even if there are no calls in flight.
  143. private let permitWithoutCalls: Bool
  144. /// Maximum number of pings that can be sent when there is no data/header frame to be sent.
  145. private let maximumPingsWithoutData: UInt
  146. /// If there are no data/header frames being received:
  147. /// The minimum amount of time to wait between successive pings.
  148. private let minimumSentPingIntervalWithoutData: TimeAmount
  149. /// If there are no data/header frames being sent:
  150. /// The minimum amount of time expected between receiving successive pings.
  151. /// If the time between successive pings is less than this value, then the ping will be considered a bad ping from the peer.
  152. /// Such a ping counts as a "ping strike".
  153. /// Ping strikes are only applicable to server handler
  154. private let minimumReceivedPingIntervalWithoutData: TimeAmount?
  155. /// Maximum number of bad pings that the server will tolerate before sending an HTTP2 GOAWAY frame and closing the connection.
  156. /// Setting it to `0` allows the server to accept any number of bad pings.
  157. /// Ping strikes are only applicable to server handler
  158. private let maximumPingStrikes: UInt?
  159. /// When the handler started pinging
  160. private var startedAt: NIODeadline?
  161. /// When the last ping was received
  162. private var lastReceivedPingDate: NIODeadline?
  163. /// When the last ping was sent
  164. private var lastSentPingDate: NIODeadline?
  165. /// The number of pings sent on the transport without any data
  166. private var sentPingsWithoutData = 0
  167. /// Number of strikes
  168. private var pingStrikes: UInt = 0
  169. /// The scheduled task which will close the connection.
  170. private var scheduledClose: Scheduled<Void>?
  171. /// Number of active streams
  172. private var activeStreams = 0 {
  173. didSet {
  174. if activeStreams > 0 {
  175. self.sentPingsWithoutData = 0
  176. }
  177. }
  178. }
  179. private static let goAwayFrame = HTTP2Frame.FramePayload.goAway(
  180. lastStreamID: .rootStream,
  181. errorCode: .enhanceYourCalm, opaqueData: nil
  182. )
  183. // For testing only
  184. var _testingOnlyNow: NIODeadline?
  185. enum Action {
  186. case none
  187. case schedulePing(delay: TimeAmount, timeout: TimeAmount)
  188. case cancelScheduledTimeout
  189. case reply(HTTP2Frame.FramePayload)
  190. }
  191. init(
  192. pingCode: UInt64,
  193. interval: TimeAmount,
  194. timeout: TimeAmount,
  195. permitWithoutCalls: Bool,
  196. maximumPingsWithoutData: UInt,
  197. minimumSentPingIntervalWithoutData: TimeAmount,
  198. minimumReceivedPingIntervalWithoutData: TimeAmount? = nil,
  199. maximumPingStrikes: UInt? = nil
  200. ) {
  201. self.pingCode = pingCode
  202. self.interval = interval
  203. self.timeout = timeout
  204. self.permitWithoutCalls = permitWithoutCalls
  205. self.maximumPingsWithoutData = maximumPingsWithoutData
  206. self.minimumSentPingIntervalWithoutData = minimumSentPingIntervalWithoutData
  207. self.minimumReceivedPingIntervalWithoutData = minimumReceivedPingIntervalWithoutData
  208. self.maximumPingStrikes = maximumPingStrikes
  209. }
  210. mutating func streamCreated() -> Action {
  211. self.activeStreams += 1
  212. if self.startedAt == nil {
  213. self.startedAt = self.now()
  214. return .schedulePing(delay: self.interval, timeout: self.timeout)
  215. } else {
  216. return .none
  217. }
  218. }
  219. mutating func streamClosed() -> Action {
  220. self.activeStreams -= 1
  221. return .none
  222. }
  223. mutating func read(pingData: HTTP2PingData, ack: Bool) -> Action {
  224. if ack {
  225. return self.handlePong(pingData)
  226. } else {
  227. return self.handlePing(pingData)
  228. }
  229. }
  230. private func handlePong(_ pingData: HTTP2PingData) -> Action {
  231. if pingData.integer == self.pingCode {
  232. return .cancelScheduledTimeout
  233. } else {
  234. return .none
  235. }
  236. }
  237. private mutating func handlePing(_ pingData: HTTP2PingData) -> Action {
  238. // Do we support ping strikes (only servers support ping strikes)?
  239. if let maximumPingStrikes = self.maximumPingStrikes {
  240. // Is this a ping strike?
  241. if self.isPingStrike {
  242. self.pingStrikes += 1
  243. // A maximum ping strike of zero indicates that we tolerate any number of strikes.
  244. if maximumPingStrikes != 0, self.pingStrikes > maximumPingStrikes {
  245. return .reply(PingHandler.goAwayFrame)
  246. } else {
  247. return .none
  248. }
  249. } else {
  250. // This is a valid ping, reset our strike count and reply with a pong.
  251. self.pingStrikes = 0
  252. self.lastReceivedPingDate = self.now()
  253. return .reply(self.generatePingFrame(code: pingData.integer, ack: true))
  254. }
  255. } else {
  256. // We don't support ping strikes. We'll just reply with a pong.
  257. //
  258. // Note: we don't need to update `pingStrikes` or `lastReceivedPingDate` as we don't
  259. // support ping strikes.
  260. return .reply(self.generatePingFrame(code: pingData.integer, ack: true))
  261. }
  262. }
  263. mutating func pingFired() -> Action {
  264. if self.shouldBlockPing {
  265. return .none
  266. } else {
  267. return .reply(self.generatePingFrame(code: self.pingCode, ack: false))
  268. }
  269. }
  270. private mutating func generatePingFrame(code: UInt64, ack: Bool) -> HTTP2Frame.FramePayload {
  271. if self.activeStreams == 0 {
  272. self.sentPingsWithoutData += 1
  273. }
  274. self.lastSentPingDate = self.now()
  275. return HTTP2Frame.FramePayload.ping(HTTP2PingData(withInteger: code), ack: ack)
  276. }
  277. /// Returns true if, on receipt of a ping, the ping should be regarded as a ping strike.
  278. ///
  279. /// A ping is considered a 'strike' if:
  280. /// - There are no active streams.
  281. /// - We allow pings to be sent when there are no active streams (i.e. `self.permitWithoutCalls`).
  282. /// - The time since the last ping we received is less than the minimum allowed interval.
  283. ///
  284. /// - Precondition: Ping strikes are supported (i.e. `self.maximumPingStrikes != nil`)
  285. private var isPingStrike: Bool {
  286. assert(
  287. self.maximumPingStrikes != nil,
  288. "Ping strikes are not supported but we're checking for one"
  289. )
  290. guard self.activeStreams == 0, self.permitWithoutCalls,
  291. let lastReceivedPingDate = self.lastReceivedPingDate,
  292. let minimumReceivedPingIntervalWithoutData = self.minimumReceivedPingIntervalWithoutData
  293. else {
  294. return false
  295. }
  296. return self.now() - lastReceivedPingDate < minimumReceivedPingIntervalWithoutData
  297. }
  298. private var shouldBlockPing: Bool {
  299. // There is no active call on the transport and pings should not be sent
  300. guard self.activeStreams > 0 || self.permitWithoutCalls else {
  301. return true
  302. }
  303. // There is no active call on the transport but pings should be sent
  304. if self.activeStreams == 0, self.permitWithoutCalls {
  305. // The number of pings already sent on the transport without any data has already exceeded the limit
  306. if self.sentPingsWithoutData > self.maximumPingsWithoutData {
  307. return true
  308. }
  309. // The time elapsed since the previous ping is less than the minimum required
  310. if let lastSentPingDate = self.lastSentPingDate,
  311. self.now() - lastSentPingDate < self.minimumSentPingIntervalWithoutData {
  312. return true
  313. }
  314. return false
  315. }
  316. return false
  317. }
  318. private func now() -> NIODeadline {
  319. return self._testingOnlyNow ?? .now()
  320. }
  321. }