-
Notifications
You must be signed in to change notification settings - Fork 899
/
AbstractKeepAliveHandler.java
459 lines (387 loc) · 15.7 KB
/
AbstractKeepAliveHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/*
* Copyright 2020 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.internal.common;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import com.linecorp.armeria.common.annotation.Nullable;
import com.linecorp.armeria.common.util.Exceptions;
import io.micrometer.core.instrument.Timer;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoop;
/**
* An {@link AbstractKeepAliveHandler} that writes a PING when neither read nor write was performed for
* the specified {@code pingIntervalMillis}, and closes the connection
* when neither read nor write was performed within the given {@code idleTimeoutMillis}.
*/
public abstract class AbstractKeepAliveHandler implements KeepAliveHandler {
private static final Logger logger = LoggerFactory.getLogger(AbstractKeepAliveHandler.class);
@Nullable
private final Stopwatch stopwatch = logger.isDebugEnabled() ? Stopwatch.createUnstarted() : null;
private final ChannelFutureListener pingWriteListener = new PingWriteListener();
private final Runnable shutdownRunnable = this::closeChannelAndLog;
private final Channel channel;
private final String name;
private final boolean isServer;
private final Timer keepAliveTimer;
private final long maxNumRequestsPerConnection;
private long currentNumRequests;
@Nullable
private ScheduledFuture<?> connectionIdleTimeout;
private final long connectionIdleTimeNanos;
private long lastConnectionIdleTime;
@Nullable
private ScheduledFuture<?> pingIdleTimeout;
private final long pingIdleTimeNanos;
private long lastPingIdleTime;
private boolean firstPingIdleEvent = true;
@Nullable
private ScheduledFuture<?> maxConnectionAgeFuture;
private final long maxConnectionAgeNanos;
private boolean isMaxConnectionAgeExceeded;
private boolean isInitialized;
private boolean closed;
private boolean disconnectWhenFinished;
private PingState pingState = PingState.IDLE;
@Nullable
private ChannelFuture pingWriteFuture;
@Nullable
private Future<?> shutdownFuture;
protected AbstractKeepAliveHandler(Channel channel, String name, Timer keepAliveTimer,
long idleTimeoutMillis, long pingIntervalMillis,
long maxConnectionAgeMillis, long maxNumRequestsPerConnection) {
this.channel = channel;
this.name = name;
isServer = "server".equals(name);
this.keepAliveTimer = keepAliveTimer;
this.maxNumRequestsPerConnection = maxNumRequestsPerConnection;
if (idleTimeoutMillis <= 0) {
connectionIdleTimeNanos = 0;
} else {
connectionIdleTimeNanos = TimeUnit.MILLISECONDS.toNanos(idleTimeoutMillis);
}
if (pingIntervalMillis <= 0) {
pingIdleTimeNanos = 0;
} else {
pingIdleTimeNanos = TimeUnit.MILLISECONDS.toNanos(pingIntervalMillis);
}
if (maxConnectionAgeMillis <= 0) {
maxConnectionAgeNanos = 0;
} else {
maxConnectionAgeNanos = TimeUnit.MILLISECONDS.toNanos(maxConnectionAgeMillis);
}
}
@Override
public final void initialize(ChannelHandlerContext ctx) {
// Avoid the case where destroy() is called before scheduling timeouts.
// See: https://github.com/netty/netty/issues/143
if (isInitialized) {
return;
}
isInitialized = true;
final long connectionStartTimeNanos = System.nanoTime();
ctx.channel().closeFuture().addListener(unused -> {
keepAliveTimer.record(System.nanoTime() - connectionStartTimeNanos, TimeUnit.NANOSECONDS);
destroy();
});
lastConnectionIdleTime = lastPingIdleTime = connectionStartTimeNanos;
if (connectionIdleTimeNanos > 0) {
connectionIdleTimeout = executor().schedule(new ConnectionIdleTimeoutTask(ctx),
connectionIdleTimeNanos, TimeUnit.NANOSECONDS);
}
if (pingIdleTimeNanos > 0) {
pingIdleTimeout = executor().schedule(new PingIdleTimeoutTask(ctx),
pingIdleTimeNanos, TimeUnit.NANOSECONDS);
}
if (maxConnectionAgeNanos > 0) {
maxConnectionAgeFuture = executor().schedule(new MaxConnectionAgeExceededTask(ctx),
maxConnectionAgeNanos, TimeUnit.NANOSECONDS);
}
}
@Override
public final void destroy() {
if (closed) {
return;
}
closed = true;
isInitialized = true;
if (connectionIdleTimeout != null) {
connectionIdleTimeout.cancel(false);
connectionIdleTimeout = null;
}
if (pingIdleTimeout != null) {
pingIdleTimeout.cancel(false);
pingIdleTimeout = null;
}
if (maxConnectionAgeFuture != null) {
maxConnectionAgeFuture.cancel(false);
maxConnectionAgeFuture = null;
}
pingState = PingState.SHUTDOWN;
isMaxConnectionAgeExceeded = true;
cancelFutures();
}
@Override
public final void onReadOrWrite() {
if (pingState == PingState.SHUTDOWN) {
return;
}
if (connectionIdleTimeNanos > 0) {
lastConnectionIdleTime = System.nanoTime();
}
if (pingResetsPreviousPing()) {
if (pingIdleTimeNanos > 0) {
lastPingIdleTime = System.nanoTime();
firstPingIdleEvent = true;
}
pingState = PingState.IDLE;
cancelFutures();
}
}
@Override
public final void onPing() {
if (pingState == PingState.SHUTDOWN) {
return;
}
if (pingIdleTimeNanos > 0) {
firstPingIdleEvent = true;
lastPingIdleTime = System.nanoTime();
}
pingState = PingState.IDLE;
cancelFutures();
}
@Override
public final boolean isClosing() {
return pingState == PingState.SHUTDOWN;
}
@Override
public void disconnectWhenFinished() {
disconnectWhenFinished = true;
}
@Override
public final boolean needsDisconnection() {
return disconnectWhenFinished || pingState == PingState.SHUTDOWN || isMaxConnectionAgeExceeded ||
(currentNumRequests > 0 && currentNumRequests >= maxNumRequestsPerConnection);
}
@Override
public final void increaseNumRequests() {
if (maxNumRequestsPerConnection == 0) {
return;
}
currentNumRequests++;
}
protected abstract ChannelFuture writePing(ChannelHandlerContext ctx);
protected abstract boolean pingResetsPreviousPing();
protected abstract boolean hasRequestsInProgress(ChannelHandlerContext ctx);
@Nullable
protected final Future<?> shutdownFuture() {
return shutdownFuture;
}
protected final boolean isPendingPingAck() {
return pingState == PingState.PENDING_PING_ACK;
}
@VisibleForTesting
final PingState state() {
return pingState;
}
private void cancelFutures() {
if (shutdownFuture != null) {
shutdownFuture.cancel(false);
shutdownFuture = null;
}
if (pingWriteFuture != null) {
pingWriteFuture.cancel(false);
pingWriteFuture = null;
}
}
private void closeChannelAndLog() {
if (pingState == PingState.SHUTDOWN) {
return;
}
logger.debug("{} Closing an idle channel", channel);
pingState = PingState.SHUTDOWN;
channel.close().addListener(future -> {
if (future.isSuccess()) {
logger.debug("{} Closed an idle channel", channel);
} else {
logger.debug("{} Failed to close an idle channel", channel, future.cause());
}
});
}
private ScheduledExecutorService executor() {
return channel.eventLoop();
}
/**
* State changes from IDLE -> PING_SCHEDULED -> PENDING_PING_ACK -> IDLE and so on. When the
* channel is inactive then the state changes to SHUTDOWN.
*/
@VisibleForTesting
enum PingState {
/* Nothing happening, but waiting for IdleStateEvent */
IDLE,
/* PING is scheduled */
PING_SCHEDULED,
/* PING is sent and is pending ACK */
PENDING_PING_ACK,
/* Not active anymore */
SHUTDOWN
}
private class PingWriteListener implements ChannelFutureListener {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
logger.debug("{} PING write successful", channel);
final EventLoop el = channel.eventLoop();
shutdownFuture = el.schedule(shutdownRunnable, pingIdleTimeNanos, TimeUnit.NANOSECONDS);
pingState = PingState.PENDING_PING_ACK;
resetStopwatch();
} else {
// Mostly because the channel is already closed. So ignore and change state to IDLE.
// If the channel is closed, we change state to SHUTDOWN on destroy.
if (!future.isCancelled() && Exceptions.isExpected(future.cause())) {
logger.debug("{} PING write failed", channel, future.cause());
}
if (pingState != PingState.SHUTDOWN) {
pingState = PingState.IDLE;
}
}
}
private void resetStopwatch() {
if (stopwatch != null) {
stopwatch.reset().start();
}
}
}
private abstract static class AbstractKeepAliveTask implements Runnable {
private final ChannelHandlerContext ctx;
AbstractKeepAliveTask(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
@Override
public void run() {
if (!ctx.channel().isOpen()) {
return;
}
run(ctx);
}
protected abstract void run(ChannelHandlerContext ctx);
}
private final class ConnectionIdleTimeoutTask extends AbstractKeepAliveTask {
private boolean warn;
ConnectionIdleTimeoutTask(ChannelHandlerContext ctx) {
super(ctx);
}
@Override
protected void run(ChannelHandlerContext ctx) {
if (pingState == PingState.SHUTDOWN) {
return;
}
final long lastConnectionIdleTime = AbstractKeepAliveHandler.this.lastConnectionIdleTime;
final long nextDelay;
nextDelay = connectionIdleTimeNanos - (System.nanoTime() - lastConnectionIdleTime);
if (nextDelay <= 0) {
// Both reader and writer are idle - set a new timeout and
// notify the callback.
connectionIdleTimeout = executor().schedule(this, connectionIdleTimeNanos,
TimeUnit.NANOSECONDS);
try {
if (!hasRequestsInProgress(ctx)) {
pingState = PingState.SHUTDOWN;
logger.debug("{} Closing an idle {} connection", ctx.channel(), name);
ctx.channel().close();
}
} catch (Exception e) {
if (!warn) {
logger.warn("An error occurred while notifying an all idle event", e);
warn = true;
}
}
} else {
// Either read or write occurred before the connection idle timeout - set a new
// timeout with shorter delay.
connectionIdleTimeout = executor().schedule(this, nextDelay, TimeUnit.NANOSECONDS);
}
}
}
private final class PingIdleTimeoutTask extends AbstractKeepAliveTask {
private boolean warn;
PingIdleTimeoutTask(ChannelHandlerContext ctx) {
super(ctx);
}
@Override
protected void run(ChannelHandlerContext ctx) {
final long lastPingIdleTime = AbstractKeepAliveHandler.this.lastPingIdleTime;
final long nextDelay;
nextDelay = pingIdleTimeNanos - (System.nanoTime() - lastPingIdleTime);
if (nextDelay <= 0) {
// PING is idle - set a new timeout and notify the callback.
pingIdleTimeout = executor().schedule(this, pingIdleTimeNanos, TimeUnit.NANOSECONDS);
final boolean isFirst = firstPingIdleEvent;
firstPingIdleEvent = false;
try {
if (pingIdleTimeNanos > 0 && isFirst) {
pingState = PingState.PING_SCHEDULED;
writePing(ctx).addListener(pingWriteListener);
}
} catch (Exception e) {
if (!warn) {
logger.warn("An error occurred while notifying a ping idle event", e);
warn = true;
}
}
} else {
// A PING was sent or received within the ping timeout
// - set a new timeout with shorter delay.
pingIdleTimeout = executor().schedule(this, nextDelay, TimeUnit.NANOSECONDS);
}
}
}
private final class MaxConnectionAgeExceededTask extends AbstractKeepAliveTask {
MaxConnectionAgeExceededTask(ChannelHandlerContext ctx) {
super(ctx);
}
@Override
protected void run(ChannelHandlerContext ctx) {
try {
isMaxConnectionAgeExceeded = true;
// A connection exceeding the max age will be closed with:
// - HTTP/2 server: Sending GOAWAY frame after writing headers
// - HTTP/1 server: Sending 'Connection: close' header when writing headers
// - HTTP/2 client
// - Sending GOAWAY frame after receiving the end of a stream
// - Or closed by this task if the connection is idle
// - HTTP/1 client
// - Close the connection after fully receiving a response
// - Or closed by this task if the connection is idle
if (!isServer && !hasRequestsInProgress(ctx)) {
logger.debug("{} Closing a {} connection exceeding the max age: {}ns",
ctx.channel(), name, maxConnectionAgeNanos);
ctx.channel().close();
}
} catch (Exception e) {
logger.warn("Unexpected error occurred while closing a connection exceeding the max age", e);
}
}
}
}