-
-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathTcpSyslogMessageSender.java
More file actions
313 lines (287 loc) · 12.5 KB
/
TcpSyslogMessageSender.java
File metadata and controls
313 lines (287 loc) · 12.5 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
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
/*
* Copyright 2010-2014, CloudBees Inc.
*
* Licensed 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
*
* http://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.cloudbees.syslog.sender;
import com.cloudbees.syslog.SyslogMessage;
import com.cloudbees.syslog.util.CachingReference;
import com.cloudbees.syslog.util.IoUtils;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import net.jcip.annotations.ThreadSafe;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
/**
* See <a href="http://tools.ietf.org/html/rfc6587">RFC 6587 - Transmission of Syslog Messages over TCP</a>
*
* @author <a href="mailto:[email protected]">Cyrille Le Clerc</a>
*/
@ThreadSafe
public class TcpSyslogMessageSender extends AbstractSyslogMessageSender implements Closeable {
public final static int SETTING_SOCKET_CONNECT_TIMEOUT_IN_MILLIS_DEFAULT_VALUE = 500;
public final static int SETTING_MAX_RETRY = 2;
/**
* {@link java.net.InetAddress InetAddress} of the remote Syslog Server.
*
* The {@code InetAddress} is refreshed regularly to handle DNS changes (default {@link #DEFAULT_INET_ADDRESS_TTL_IN_MILLIS})
*
* Default value: {@link #DEFAULT_SYSLOG_HOST}
*/
protected CachingReference<InetAddress> syslogServerHostnameReference;
/**
* Listen port of the remote Syslog server.
*
* Default: {@link #DEFAULT_SYSLOG_PORT}
*/
protected int syslogServerPort = DEFAULT_SYSLOG_PORT;
private Socket socket;
private Writer writer;
private int socketConnectTimeoutInMillis = SETTING_SOCKET_CONNECT_TIMEOUT_IN_MILLIS_DEFAULT_VALUE;
private boolean ssl;
private SSLContext sslContext;
/**
* Number of retries to send a message before throwing an exception.
*/
private int maxRetryCount = SETTING_MAX_RETRY;
/**
* Number of exceptions trying to send message.
*/
protected final AtomicInteger trySendErrorCounter = new AtomicInteger();
// use the CR LF non transparent framing as described in "3.4.2. Non-Transparent-Framing"
private String postfix = "\r\n";
@Override
public synchronized void sendMessage(@NonNull SyslogMessage message) throws IOException {
sendCounter.incrementAndGet();
long nanosBefore = System.nanoTime();
try {
Exception lastException = null;
for (int i = 0; i <= maxRetryCount; i++) {
try {
if (logger.isLoggable(Level.FINEST)) {
logger.finest("Send syslog message " + message.toSyslogMessage(messageFormat));
}
ensureSyslogServerConnection();
message.toSyslogMessage(messageFormat, writer);
writer.write(postfix);
writer.flush();
return;
} catch (IOException | RuntimeException e) {
lastException = e;
IoUtils.closeQuietly(socket, writer);
trySendErrorCounter.incrementAndGet();
}
}
if (lastException != null) {
sendErrorCounter.incrementAndGet();
if (lastException instanceof IOException) {
throw (IOException) lastException;
} else if (lastException instanceof RuntimeException) {
throw (RuntimeException) lastException;
}
}
} finally {
sendDurationInNanosCounter.addAndGet(System.nanoTime() - nanosBefore);
}
}
private synchronized void ensureSyslogServerConnection() throws IOException {
InetAddress inetAddress = syslogServerHostnameReference.get();
if (socket != null && !Objects.equals(socket.getInetAddress(), inetAddress)) {
logger.info("InetAddress of the Syslog Server have changed, create a new connection. " +
"Before=" + socket.getInetAddress() + ", new=" + inetAddress);
IoUtils.closeQuietly(socket, writer);
writer = null;
socket = null;
}
boolean socketIsValid;
try {
socketIsValid = socket != null &&
socket.isConnected()
&& socket.isBound()
&& !socket.isClosed()
&& !socket.isInputShutdown()
&& !socket.isOutputShutdown();
} catch (Exception e) {
socketIsValid = false;
}
if (socketIsValid) { //we may have received a tcp FIN. in such case we should establish a new connection.
int configuredSoTimeout = socket.getSoTimeout();//keep the current value
try {
//(Note: no 'real' data is expected to be received from the syslog server)
//we intend to read from the socket in order to check if a FIN was sent.
//if it was, read will return -1.
//but if not (which is usual case) we will remain blocked by the read().
//in order to minimize the blocking time, we're temporarily setting the timeout to the minimal possible value (1 millisecond)
socket.setSoTimeout(1);
int read = socket.getInputStream().read();
if (read == -1) { //we've received a FIN from the server
logger.fine("A TCP FIN was received from the syslog server. marking current socket as invalid");
socketIsValid = false;
}
} catch (SocketTimeoutException socketTimeoutException) {
//do nothing. this is the expected.
} catch (IOException e) {
//if any other exception, we don't know what is the problem, but we better mark the socket as invalid.
logger.finer("couldn't read from socket. (for checking if a FIN was received). marking current socket as invalid. " + e.getMessage());
socketIsValid = false;
} finally {
socket.setSoTimeout(configuredSoTimeout);//restore
}
}
if (!socketIsValid) {
writer = null;
try {
if (ssl) {
if (sslContext == null) {
socket = SSLSocketFactory.getDefault().createSocket();
} else {
socket = sslContext.getSocketFactory().createSocket();
}
} else {
socket = SocketFactory.getDefault().createSocket();
}
socket.setKeepAlive(true);
socket.connect(
new InetSocketAddress(inetAddress, syslogServerPort),
socketConnectTimeoutInMillis);
if (socket instanceof SSLSocket && logger.isLoggable(Level.FINER)) {
try {
SSLSocket sslSocket = (SSLSocket) socket;
SSLSession session = sslSocket.getSession();
logger.finer("The Certificates used by peer");
for (Certificate certificate : session.getPeerCertificates()) {
if (certificate instanceof X509Certificate) {
X509Certificate x509Certificate = (X509Certificate) certificate;
logger.finer("" + x509Certificate.getSubjectDN());
} else {
logger.finer("" + certificate);
}
}
logger.finer("Peer host is " + session.getPeerHost());
logger.finer("Cipher is " + session.getCipherSuite());
logger.finer("Protocol is " + session.getProtocol());
logger.finer("ID is " + new BigInteger(session.getId()));
logger.finer("Session created in " + session.getCreationTime());
logger.finer("Session accessed in " + session.getLastAccessedTime());
} catch (Exception e) {
logger.warn("Exception dumping debug info for " + socket, e);
}
}
} catch (IOException e) {
ConnectException ce = new ConnectException("Exception connecting to " + inetAddress + ":" + syslogServerPort);
ce.initCause(e);
throw ce;
}
}
if (writer == null) {
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
}
}
@Override
public void setSyslogServerHostname(final String syslogServerHostname) {
this.syslogServerHostnameReference = new CachingReference<InetAddress>(DEFAULT_INET_ADDRESS_TTL_IN_NANOS) {
@Nullable
@Override
protected InetAddress newObject() {
try {
return InetAddress.getByName(syslogServerHostname);
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
}
}
};
}
@Override
public void setSyslogServerPort(int syslogServerPort) {
this.syslogServerPort = syslogServerPort;
}
@Nullable
public String getSyslogServerHostname() {
if (syslogServerHostnameReference == null)
return null;
InetAddress inetAddress = syslogServerHostnameReference.get();
return inetAddress == null ? null : inetAddress.getHostName();
}
public int getSyslogServerPort() {
return syslogServerPort;
}
public boolean isSsl() {
return ssl;
}
public void setSsl(boolean ssl) {
this.ssl = ssl;
}
public synchronized void setSSLContext(SSLContext sslContext) {
this.sslContext = sslContext;
}
public synchronized SSLContext getSSLContext() {
return this.sslContext;
}
public int getSocketConnectTimeoutInMillis() {
return socketConnectTimeoutInMillis;
}
public int getMaxRetryCount() {
return maxRetryCount;
}
public int getTrySendErrorCounter() {
return trySendErrorCounter.get();
}
public void setSocketConnectTimeoutInMillis(int socketConnectTimeoutInMillis) {
this.socketConnectTimeoutInMillis = socketConnectTimeoutInMillis;
}
public void setMaxRetryCount(int maxRetryCount) {
this.maxRetryCount = maxRetryCount;
}
public synchronized void setPostfix(String postfix) {
this.postfix = postfix;
}
@Override
public String toString() {
return getClass().getName() + "{" +
"syslogServerHostname='" + this.getSyslogServerHostname() + '\'' +
", syslogServerPort='" + this.getSyslogServerPort() + '\'' +
", ssl=" + ssl +
", maxRetryCount=" + maxRetryCount +
", socketConnectTimeoutInMillis=" + socketConnectTimeoutInMillis +
", defaultAppName='" + defaultAppName + '\'' +
", defaultFacility=" + defaultFacility +
", defaultMessageHostname='" + defaultMessageHostname + '\'' +
", defaultSeverity=" + defaultSeverity +
", messageFormat=" + messageFormat +
", sendCounter=" + sendCounter +
", sendDurationInNanosCounter=" + sendDurationInNanosCounter +
", sendErrorCounter=" + sendErrorCounter +
", trySendErrorCounter=" + trySendErrorCounter +
'}';
}
@Override
public void close() throws IOException {
this.socket.close();
}
}