-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathBeatsHandler.java
More file actions
192 lines (170 loc) · 7.74 KB
/
Copy pathBeatsHandler.java
File metadata and controls
192 lines (170 loc) · 7.74 KB
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
package org.logstash.beats;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Objects;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.net.ssl.SSLHandshakeException;
public class BeatsHandler extends SimpleChannelInboundHandler<Batch> {
private final static Logger logger = LogManager.getLogger(BeatsHandler.class);
private final static String executorTerminatedMessage = "event executor terminated";
private final IMessageListener messageListener;
private ChannelHandlerContext context;
private final AtomicBoolean isQuietPeriod = new AtomicBoolean(false);
public BeatsHandler(IMessageListener listener) {
messageListener = listener;
}
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
context = ctx;
if (logger.isTraceEnabled()) {
logger.trace(format("Channel Active"));
}
super.channelActive(ctx);
messageListener.onNewConnection(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
if (logger.isTraceEnabled()) {
logger.trace(format("Channel Inactive"));
}
messageListener.onConnectionClose(ctx);
}
@Override
public void channelRead0(ChannelHandlerContext ctx, Batch batch) {
if (logger.isDebugEnabled()) {
logger.debug(format("Received a new payload"));
}
try {
if (isQuietPeriod.get()) {
if (logger.isDebugEnabled()) {
logger.debug(format("Received batch but no executors available, ignoring..."));
}
} else {
processBatchAndSendAck(ctx, batch);
}
} finally {
//this channel is done processing this payload, instruct the connection handler to stop sending TCP keep alive
ctx.channel().attr(ConnectionHandler.CHANNEL_SEND_KEEP_ALIVE).get().set(false);
if (logger.isDebugEnabled()) {
logger.debug("{}: batches pending: {}", ctx.channel().id().asShortText(), ctx.channel().attr(ConnectionHandler.CHANNEL_SEND_KEEP_ALIVE).get().get());
}
batch.release();
ctx.flush();
}
}
/*
* Do not propagate the SSL handshake exception down to the ruby layer handle it locally instead and close the connection
* if the channel is still active. Calling `onException` will flush the content of the codec's buffer, this call
* may block the thread in the event loop until completion, this should only affect LS 5 because it still supports
* the multiline codec, v6 drop support for buffering codec in the beats input.
*
* For v5, I cannot drop the content of the buffer because this will create data loss because multiline content can
* overlap Filebeat transmission; we were recommending multiline at the source in v5 and in v6 we enforce it.
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
try {
if (!(cause instanceof SSLHandshakeException)) {
messageListener.onException(ctx, cause);
}
if (isNoisyException(cause)) {
if (logger.isDebugEnabled()) {
logger.info(format("closing"), cause);
} else {
logger.info(format("closing (" + cause.getMessage() + ")"));
}
} else {
final Throwable realCause = extractCause(cause, 0);
// when execution tasks rejected, no need to forward the exception to netty channel handlers
if (cause instanceof RejectedExecutionException) {
if (logger.isDebugEnabled()) {
logger.info(format("Handling exception: " + cause + " (caused by: " + realCause + ")"), cause);
} else {
logger.info(format("Handling exception: " + cause + " (caused by: " + realCause + ")"));
}
// we no longer have event executors available since they are terminated, mostly by shutdown process
if (Objects.nonNull(cause.getMessage()) && cause.getMessage().contains(executorTerminatedMessage)) {
this.isQuietPeriod.compareAndSet(false, true);
}
} else {
if (logger.isDebugEnabled()) {
logger.warn(format("Unhandled exception: " + cause + " (caused by: " + realCause + ")"), cause);
} else {
logger.warn(format("Unhandled exception: " + cause + " (caused by: " + realCause + ")"));
}
super.exceptionCaught(ctx, cause);
}
}
} finally {
ctx.flush();
ctx.close();
}
}
private void processBatchAndSendAck(ChannelHandlerContext ctx, Batch batch) {
if (batch.isEmpty()) {
logger.debug("Sending 0-seq ACK for empty batch");
writeAck(ctx, batch.getProtocol(), 0);
}
for (Message message : batch) {
if (logger.isDebugEnabled()) {
logger.debug(format("Sending a new message for the listener, sequence: " + message.getSequence()));
}
messageListener.onNewMessage(ctx, message);
if (needAck(message)) {
if (logger.isTraceEnabled()) {
logger.trace(format("Acking message number " + message.getSequence()));
}
writeAck(ctx, message.getBatch().getProtocol(), message.getSequence());
}
}
}
private boolean isNoisyException(final Throwable ex) {
if (ex instanceof IOException) {
final String message = ex.getMessage();
if ("Connection reset by peer".equals(message)) {
return true;
}
}
return false;
}
private boolean needAck(Message message) {
return message.getSequence() == message.getBatch().getHighestSequence();
}
private void writeAck(ChannelHandlerContext ctx, byte protocol, int sequence) {
ctx.write(new Ack(protocol, sequence));
}
/*
* There is no easy way in Netty to support MDC directly,
* we will use similar logic than Netty's LoggingHandler
*/
private String format(String message) {
InetSocketAddress local = (InetSocketAddress) context.channel().localAddress();
InetSocketAddress remote = (InetSocketAddress) context.channel().remoteAddress();
String localhost;
if (local != null) {
localhost = local.getAddress().getHostAddress() + ":" + local.getPort();
} else {
localhost = "undefined";
}
String remoteHost;
if (remote != null) {
remoteHost = remote.getAddress().getHostAddress() + ":" + remote.getPort();
} else {
remoteHost = "undefined";
}
return "[local: " + localhost + ", remote: " + remoteHost + "] " + message;
}
private static final int MAX_CAUSE_NESTING = 10;
private static Throwable extractCause(final Throwable ex, final int nesting) {
final Throwable cause = ex.getCause();
if (cause == null || cause == ex) return ex;
if (nesting >= MAX_CAUSE_NESTING) return cause; // do not recurse infinitely
return extractCause(cause, nesting + 1);
}
}