-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathNioClient.java
More file actions
269 lines (233 loc) · 7.51 KB
/
Copy pathNioClient.java
File metadata and controls
269 lines (233 loc) · 7.51 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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2005 Brian Wellington (bwelling@xbill.org)
package org.xbill.DNS;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.function.Consumer;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.xbill.DNS.utils.hexdump;
/**
* Manages the network I/O for the {@link SimpleResolver}. It is mostly an implementation detail of
* {@code dnsjava} and the only method intended to be called is {@link #close()} - and only if
* {@code dnsjava} is used in an application container like Tomcat. In a normal JVM setup {@link
* #close()} is called by a shutdown hook.
*
* <p>The following configuration parameters are available:
*
* <dl>
* <dt>{@code dnsjava.nio.selector_timeout}
* <dd>Set selector timeout in milliseconds. Default/Max 1000, Min 1.
* <dt>{@code dnsjava.nio.register_shutdown_hook}
* <dd>Register Shutdown Hook termination of NIO. Default True.
* </dl>
*
* @since 3.4
*/
@Slf4j
@NoArgsConstructor(access = AccessLevel.NONE)
public abstract class NioClient {
static final String SELECTOR_TIMEOUT_PROPERTY = "dnsjava.nio.selector_timeout";
static final String REGISTER_SHUTDOWN_HOOK_PROPERTY = "dnsjava.nio.register_shutdown_hook";
private static final Object NIO_CLIENT_LOCK = new Object();
/** Packet logger, if available. */
private static PacketLogger packetLogger = null;
private static final Runnable[] TIMEOUT_TASKS = new Runnable[2];
private static final Runnable[] CLOSE_TASKS = new Runnable[2];
private static Consumer<Selector> tcpRegistrationsTask;
private static Consumer<Selector> udpRegistrationsTask;
private static Thread selectorThread;
private static Thread closeThread;
private static volatile Selector selector;
private static volatile boolean run;
interface KeyProcessor {
void processReadyKey(SelectionKey key);
}
static Selector selector() throws IOException {
if (selector == null) {
synchronized (NIO_CLIENT_LOCK) {
if (selector == null) {
selector = Selector.open();
log.debug("Starting dnsjava NIO selector thread");
run = true;
selectorThread = new Thread(NioClient::runSelector);
selectorThread.setDaemon(true);
selectorThread.setName("dnsjava NIO selector");
selectorThread.start();
if (Boolean.parseBoolean(System.getProperty(REGISTER_SHUTDOWN_HOOK_PROPERTY, "true"))) {
closeThread = new Thread(() -> close(true));
closeThread.setName("dnsjava NIO shutdown hook");
Runtime.getRuntime().addShutdownHook(closeThread);
}
}
}
}
return selector;
}
/**
* Shutdown the network I/O used by the {@link SimpleResolver}.
*
* @since 3.4.0
*/
public static void close() {
close(false);
}
private static void close(boolean fromHook) {
log.debug("Closing dnsjava NIO selector, fromHook={}", fromHook);
Selector localSelector;
Thread localSelectorThread;
synchronized (NIO_CLIENT_LOCK) {
run = false;
localSelector = selector;
localSelectorThread = selectorThread;
}
if (localSelector != null) {
localSelector.wakeup();
}
if (!fromHook) {
synchronized (NIO_CLIENT_LOCK) {
if (closeThread != null) {
try {
Runtime.getRuntime().removeShutdownHook(closeThread);
} catch (Exception ex) {
log.warn("Failed to remove shutdown hook, ignoring and continuing close", ex);
}
}
}
}
if (localSelector == null || localSelectorThread == null) {
// Prevent hanging when close() was called without starting
return;
}
try {
localSelectorThread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
static void runSelector() {
int timeout = Integer.getInteger(SELECTOR_TIMEOUT_PROPERTY, 1000);
if (timeout <= 0 || timeout > 1000) {
throw new IllegalArgumentException("Invalid selector_timeout, must be between 1 and 1000");
}
while (run) {
try {
int numSelects = selector.select(timeout);
if (Thread.currentThread().isInterrupted()) {
log.debug("Sector thread was interrupted, stopping");
close();
break;
}
if (numSelects == 0) {
runTasks(TIMEOUT_TASKS);
}
if (run) {
runRegistrationTasks();
processReadyKeys();
}
} catch (IOException e) {
log.error("A selection operation failed", e);
} catch (ClosedSelectorException e) {
// ignore
}
}
cleanupAfterRun();
log.debug("dnsjava NIO selector thread stopped");
}
private static void cleanupAfterRun() {
try {
runTasks(CLOSE_TASKS);
} catch (Exception e) {
log.warn("Failed to execute shutdown task, ignoring and continuing close", e);
}
Selector localSelector = selector;
if (localSelector != null) {
try {
localSelector.close();
} catch (IOException e) {
log.warn("Failed to properly close selector, ignoring and continuing close", e);
}
}
synchronized (NIO_CLIENT_LOCK) {
selector = null;
selectorThread = null;
closeThread = null;
}
}
static void setTimeoutTask(Runnable r, boolean isTcpClient) {
addTask(TIMEOUT_TASKS, r, isTcpClient);
}
static void setRegistrationsTask(Consumer<Selector> r, boolean isTcpClient) {
if (isTcpClient) {
tcpRegistrationsTask = r;
} else {
udpRegistrationsTask = r;
}
}
static void setCloseTask(Runnable r, boolean isTcpClient) {
addTask(CLOSE_TASKS, r, isTcpClient);
}
private static void addTask(Runnable[] tasks, Runnable r, boolean isTcpClient) {
if (isTcpClient) {
tasks[0] = r;
} else {
tasks[1] = r;
}
}
private static void runTasks(Runnable[] runnables) {
Runnable r0 = runnables[0];
if (r0 != null) {
r0.run();
}
Runnable r1 = runnables[1];
if (r1 != null) {
r1.run();
}
}
private static void runRegistrationTasks() {
Consumer<Selector> tcpTask = tcpRegistrationsTask;
if (tcpTask != null) {
tcpTask.accept(selector);
}
Consumer<Selector> udpTask = udpRegistrationsTask;
if (udpTask != null) {
udpTask.accept(selector);
}
}
private static void processReadyKeys() {
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
KeyProcessor t = (KeyProcessor) key.attachment();
t.processReadyKey(key);
}
}
static void verboseLog(
String prefix, SocketAddress local, SocketAddress remote, ByteBuffer data) {
if (log.isTraceEnabled() || packetLogger != null) {
byte[] dst = new byte[data.remaining()];
int pos = data.position();
data.get(dst, 0, data.remaining());
data.position(pos);
verboseLog(prefix, local, remote, dst);
}
}
static void verboseLog(String prefix, SocketAddress local, SocketAddress remote, byte[] data) {
if (log.isTraceEnabled()) {
log.trace(hexdump.dump(prefix, data));
}
if (packetLogger != null) {
packetLogger.log(prefix, local, remote, data);
}
}
static void setPacketLogger(PacketLogger logger) {
packetLogger = logger;
}
}