1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package ch.qos.logback.core.net;
16
17 import java.io.IOException;
18 import java.io.Serializable;
19 import java.net.ConnectException;
20 import java.net.InetAddress;
21 import java.net.Socket;
22 import java.net.UnknownHostException;
23 import java.util.concurrent.BlockingDeque;
24 import java.util.concurrent.Future;
25 import java.util.concurrent.TimeUnit;
26
27 import javax.net.SocketFactory;
28
29 import ch.qos.logback.core.AppenderBase;
30 import ch.qos.logback.core.spi.DeferredProcessingAware;
31 import ch.qos.logback.core.spi.PreSerializationTransformer;
32 import ch.qos.logback.core.util.CloseUtil;
33 import ch.qos.logback.core.util.Duration;
34
35
36
37
38
39
40
41
42
43
44
45 public abstract class AbstractSocketAppender<E> extends AppenderBase<E> implements SocketConnector.ExceptionHandler {
46
47
48
49
50 public static final int DEFAULT_PORT = 4560;
51
52
53
54
55 public static final int DEFAULT_RECONNECTION_DELAY = 30000;
56
57
58
59
60
61 public static final int DEFAULT_QUEUE_SIZE = 128;
62
63
64
65
66 private static final int DEFAULT_ACCEPT_CONNECTION_DELAY = 5000;
67
68
69
70
71
72 private static final int DEFAULT_EVENT_DELAY_TIMEOUT = 100;
73
74 private final ObjectWriterFactory objectWriterFactory;
75 private final QueueFactory queueFactory;
76
77 private String remoteHost;
78 private int port = DEFAULT_PORT;
79 private InetAddress address;
80 private Duration reconnectionDelay = new Duration(DEFAULT_RECONNECTION_DELAY);
81 private int queueSize = DEFAULT_QUEUE_SIZE;
82 private int acceptConnectionTimeout = DEFAULT_ACCEPT_CONNECTION_DELAY;
83 private Duration eventDelayLimit = new Duration(DEFAULT_EVENT_DELAY_TIMEOUT);
84
85 private BlockingDeque<E> deque;
86 private String peerId;
87 private SocketConnector connector;
88 private Future<?> task;
89
90 private volatile Socket socket;
91
92
93
94
95 protected AbstractSocketAppender() {
96 this(new QueueFactory(), new ObjectWriterFactory());
97 }
98
99
100
101
102
103 AbstractSocketAppender(QueueFactory queueFactory, ObjectWriterFactory objectWriterFactory) {
104 this.objectWriterFactory = objectWriterFactory;
105 this.queueFactory = queueFactory;
106 }
107
108
109
110
111 public void start() {
112 if (isStarted())
113 return;
114 int errorCount = 0;
115 if (port <= 0) {
116 errorCount++;
117 addError("No port was configured for appender" + name
118 + " For more information, please visit http://logback.qos.ch/codes.html#socket_no_port");
119 }
120
121 if (remoteHost == null) {
122 errorCount++;
123 addError("No remote host was configured for appender" + name
124 + " For more information, please visit http://logback.qos.ch/codes.html#socket_no_host");
125 }
126
127 if (queueSize == 0) {
128 addWarn("Queue size of zero is deprecated, use a size of one to indicate synchronous processing");
129 }
130
131 if (queueSize < 0) {
132 errorCount++;
133 addError("Queue size must be greater than zero");
134 }
135
136 if (errorCount == 0) {
137 try {
138 address = InetAddress.getByName(remoteHost);
139 } catch (UnknownHostException ex) {
140 addError("unknown host: " + remoteHost);
141 errorCount++;
142 }
143 }
144
145 if (errorCount == 0) {
146 deque = queueFactory.newLinkedBlockingDeque(queueSize);
147 peerId = "remote peer " + remoteHost + ":" + port + ": ";
148 connector = createConnector(address, port, 0, reconnectionDelay.getMilliseconds());
149 task = getContext().getExecutorService().submit(new Runnable() {
150 @Override
151 public void run() {
152 connectSocketAndDispatchEvents();
153 }
154 });
155 super.start();
156 }
157 }
158
159
160
161
162 @Override
163 public void stop() {
164 if (!isStarted())
165 return;
166 CloseUtil.closeQuietly(socket);
167 task.cancel(true);
168 super.stop();
169 }
170
171
172
173
174 @Override
175 protected void append(E event) {
176 if (event == null || !isStarted())
177 return;
178
179 try {
180
181
182 if(event instanceof DeferredProcessingAware) {
183 ((DeferredProcessingAware) event).prepareForDeferredProcessing();
184 }
185
186 final boolean inserted = deque.offer(event, eventDelayLimit.getMilliseconds(), TimeUnit.MILLISECONDS);
187 if (!inserted) {
188 addInfo("Dropping event due to timeout limit of [" + eventDelayLimit + "] being exceeded");
189 }
190 } catch (InterruptedException e) {
191 addError("Interrupted while appending event to SocketAppender", e);
192 Thread.currentThread().interrupt();
193
194 }
195 }
196
197 private void connectSocketAndDispatchEvents() {
198 try {
199 while (socketConnectionCouldBeEstablished()) {
200 try {
201 ObjectWriter objectWriter = createObjectWriterForSocket();
202 addInfo(peerId + "connection established");
203 dispatchEvents(objectWriter);
204 } catch (javax.net.ssl.SSLHandshakeException she) {
205
206 Thread.sleep(DEFAULT_RECONNECTION_DELAY);
207 } catch (IOException ex) {
208 addInfo(peerId + "connection failed: ", ex);
209 } finally {
210 CloseUtil.closeQuietly(socket);
211 socket = null;
212 addInfo(peerId + "connection closed");
213 }
214 }
215 } catch (InterruptedException ex) {
216 Thread.currentThread().interrupt();
217 }
218 addInfo("shutting down");
219 }
220
221 private boolean socketConnectionCouldBeEstablished() throws InterruptedException {
222 return (socket = connector.call()) != null;
223 }
224
225 private ObjectWriter createObjectWriterForSocket() throws IOException {
226 socket.setSoTimeout(acceptConnectionTimeout);
227 ObjectWriter objectWriter = objectWriterFactory.newAutoFlushingObjectWriter(socket.getOutputStream());
228 socket.setSoTimeout(0);
229 return objectWriter;
230 }
231
232 private SocketConnector createConnector(InetAddress address, int port, int initialDelay, long retryDelay) {
233 SocketConnector connector = newConnector(address, port, initialDelay, retryDelay);
234 connector.setExceptionHandler(this);
235 connector.setSocketFactory(getSocketFactory());
236 return connector;
237 }
238
239 private void dispatchEvents(ObjectWriter objectWriter) throws InterruptedException, IOException {
240 while (true) {
241 E event = deque.takeFirst();
242 postProcessEvent(event);
243 Serializable serializableEvent = getPST().transform(event);
244 try {
245 objectWriter.write(serializableEvent);
246 } catch (IOException e) {
247 tryReAddingEventToFrontOfQueue(event);
248 throw e;
249 }
250 }
251 }
252
253 private void tryReAddingEventToFrontOfQueue(E event) {
254 final boolean wasInserted = deque.offerFirst(event);
255 if (!wasInserted) {
256 addInfo("Dropping event due to socket connection error and maxed out deque capacity");
257 }
258 }
259
260
261
262
263 public void connectionFailed(SocketConnector connector, Exception ex) {
264 if (ex instanceof InterruptedException) {
265 addInfo("connector interrupted");
266 } else if (ex instanceof ConnectException) {
267 addInfo(peerId + "connection refused");
268 } else {
269 addInfo(peerId + ex);
270 }
271 }
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286 protected SocketConnector newConnector(InetAddress address, int port, long initialDelay, long retryDelay) {
287 return new DefaultSocketConnector(address, port, initialDelay, retryDelay);
288 }
289
290
291
292
293
294
295 protected SocketFactory getSocketFactory() {
296 return SocketFactory.getDefault();
297 }
298
299
300
301
302
303
304
305 protected abstract void postProcessEvent(E event);
306
307
308
309
310
311
312
313 protected abstract PreSerializationTransformer<E> getPST();
314
315
316
317
318
319 public void setRemoteHost(String host) {
320 remoteHost = host;
321 }
322
323
324
325
326 public String getRemoteHost() {
327 return remoteHost;
328 }
329
330
331
332
333
334 public void setPort(int port) {
335 this.port = port;
336 }
337
338
339
340
341 public int getPort() {
342 return port;
343 }
344
345
346
347
348
349
350
351
352
353 public void setReconnectionDelay(Duration delay) {
354 this.reconnectionDelay = delay;
355 }
356
357
358
359
360 public Duration getReconnectionDelay() {
361 return reconnectionDelay;
362 }
363
364
365
366
367
368
369
370
371
372
373
374
375 public void setQueueSize(int queueSize) {
376 this.queueSize = queueSize;
377 }
378
379
380
381
382 public int getQueueSize() {
383 return queueSize;
384 }
385
386
387
388
389
390
391
392
393 public void setEventDelayLimit(Duration eventDelayLimit) {
394 this.eventDelayLimit = eventDelayLimit;
395 }
396
397
398
399
400 public Duration getEventDelayLimit() {
401 return eventDelayLimit;
402 }
403
404
405
406
407
408
409
410
411
412
413 void setAcceptConnectionTimeout(int acceptConnectionTimeout) {
414 this.acceptConnectionTimeout = acceptConnectionTimeout;
415 }
416
417 }