forked from voldemort/voldemort
/
NioSocketService.java
284 lines (231 loc) · 10.6 KB
/
NioSocketService.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
/*
* Copyright 2009 Mustard Grain, Inc., 2009-2010 LinkedIn, 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 voldemort.server.niosocket;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import voldemort.VoldemortException;
import voldemort.annotations.jmx.JmxGetter;
import voldemort.server.AbstractSocketService;
import voldemort.server.ServiceType;
import voldemort.server.StatusManager;
import voldemort.server.protocol.RequestHandlerFactory;
import voldemort.utils.DaemonThreadFactory;
/**
* NioSocketService is an NIO-based socket service, comparable to the
* blocking-IO-based socket service.
* <p/>
* The NIO server is enabled in the server.properties file by setting the
* "enable.nio.connector" property to "true". If you want to adjust the number
* of SelectorManager instances that are used, change "nio.connector.selectors"
* to a positive integer value. Otherwise, the number of selectors will be equal
* to the number of CPUs visible to the JVM.
* <p/>
* This code uses the NIO APIs directly. It would be a good idea to consider
* some of the NIO frameworks to handle this more cleanly, efficiently, and to
* handle corner cases.
*
*
* @see voldemort.server.socket.SocketService
*/
public class NioSocketService extends AbstractSocketService {
private static final int SHUTDOWN_TIMEOUT_MS = 15000;
private final RequestHandlerFactory requestHandlerFactory;
private final ServerSocketChannel serverSocketChannel;
private final InetSocketAddress endpoint;
private final NioSelectorManager[] selectorManagers;
private final ExecutorService selectorManagerThreadPool;
private final int socketBufferSize;
private final int acceptorBacklog;
private final StatusManager statusManager;
private final Thread acceptorThread;
private final Logger logger = Logger.getLogger(getClass());
public NioSocketService(RequestHandlerFactory requestHandlerFactory,
int port,
int socketBufferSize,
int selectors,
String serviceName,
boolean enableJmx,
int acceptorBacklog) {
super(ServiceType.SOCKET, port, serviceName, enableJmx);
this.requestHandlerFactory = requestHandlerFactory;
this.socketBufferSize = socketBufferSize;
this.acceptorBacklog = acceptorBacklog;
try {
this.serverSocketChannel = ServerSocketChannel.open();
} catch(IOException e) {
throw new VoldemortException(e);
}
this.endpoint = new InetSocketAddress(port);
this.selectorManagers = new NioSelectorManager[selectors];
this.selectorManagerThreadPool = Executors.newFixedThreadPool(selectorManagers.length,
new DaemonThreadFactory("voldemort-niosocket-server"));
this.statusManager = new StatusManager((ThreadPoolExecutor) this.selectorManagerThreadPool);
this.acceptorThread = new Thread(new Acceptor(), "NioSocketService.Acceptor");
}
@Override
public StatusManager getStatusManager() {
return statusManager;
}
@Override
protected void startInner() {
if(logger.isEnabledFor(Level.INFO))
logger.info("Starting Voldemort NIO socket server (" + serviceName + ") on port "
+ port);
try {
for(int i = 0; i < selectorManagers.length; i++) {
selectorManagers[i] = new NioSelectorManager(endpoint,
requestHandlerFactory,
socketBufferSize);
selectorManagerThreadPool.execute(selectorManagers[i]);
}
serverSocketChannel.socket().bind(endpoint, acceptorBacklog);
serverSocketChannel.socket().setReceiveBufferSize(socketBufferSize);
serverSocketChannel.socket().setReuseAddress(true);
acceptorThread.start();
} catch(Exception e) {
throw new VoldemortException(e);
}
enableJmx(this);
}
@Override
protected void stopInner() {
if(logger.isEnabledFor(Level.INFO))
logger.info("Stopping Voldemort NIO socket server (" + serviceName + ") on port "
+ port);
try {
// Signal the thread to stop accepting new connections...
if(logger.isTraceEnabled())
logger.trace("Interrupted acceptor thread, waiting " + SHUTDOWN_TIMEOUT_MS
+ " ms for termination");
acceptorThread.interrupt();
acceptorThread.join(SHUTDOWN_TIMEOUT_MS);
if(acceptorThread.isAlive()) {
if(logger.isEnabledFor(Level.WARN))
logger.warn("Acceptor thread pool did not stop cleanly after "
+ SHUTDOWN_TIMEOUT_MS + " ms");
}
} catch(Exception e) {
if(logger.isEnabledFor(Level.WARN))
logger.warn(e.getMessage(), e);
}
try {
// We close instead of interrupting the thread pool. Why? Because as
// of 0.70, the SelectorManager services RequestHandler in the same
// thread as itself. So, if we interrupt the SelectorManager in the
// thread pool, we interrupt the request. In some RequestHandler
// implementations interruptions are not handled gracefully and/or
// indicate other errors which cause odd side effects. So we
// implement a non-interrupt-based shutdown via close.
for(int i = 0; i < selectorManagers.length; i++) {
try {
selectorManagers[i].close();
} catch(Exception e) {
if(logger.isEnabledFor(Level.WARN))
logger.warn(e.getMessage(), e);
}
}
// As per the above comment - we use shutdown and *not* shutdownNow
// to avoid using interrupts to signal shutdown.
selectorManagerThreadPool.shutdown();
if(logger.isTraceEnabled())
logger.trace("Shut down SelectorManager thread pool acceptor, waiting "
+ SHUTDOWN_TIMEOUT_MS + " ms for termination");
boolean terminated = selectorManagerThreadPool.awaitTermination(SHUTDOWN_TIMEOUT_MS,
TimeUnit.MILLISECONDS);
if(!terminated) {
if(logger.isEnabledFor(Level.WARN))
logger.warn("SelectorManager thread pool did not stop cleanly after "
+ SHUTDOWN_TIMEOUT_MS + " ms");
}
} catch(Exception e) {
if(logger.isEnabledFor(Level.WARN))
logger.warn(e.getMessage(), e);
}
try {
serverSocketChannel.socket().close();
} catch(Exception e) {
if(logger.isEnabledFor(Level.WARN))
logger.warn(e.getMessage(), e);
}
try {
serverSocketChannel.close();
} catch(Exception e) {
if(logger.isEnabledFor(Level.WARN))
logger.warn(e.getMessage(), e);
}
}
private class Acceptor implements Runnable {
public void run() {
if(logger.isInfoEnabled())
logger.info("Server now listening for connections on port " + port);
AtomicInteger counter = new AtomicInteger();
while(true) {
if(Thread.currentThread().isInterrupted()) {
if(logger.isInfoEnabled())
logger.info("Acceptor thread interrupted");
break;
}
try {
SocketChannel socketChannel = serverSocketChannel.accept();
if(socketChannel == null) {
if(logger.isEnabledFor(Level.WARN))
logger.warn("Claimed accept but nothing to select");
continue;
}
NioSelectorManager selectorManager = selectorManagers[counter.getAndIncrement()
% selectorManagers.length];
selectorManager.accept(socketChannel);
} catch(ClosedByInterruptException e) {
// If you're *really* interested...
if(logger.isTraceEnabled())
logger.trace("Acceptor thread interrupted, closing");
break;
} catch(Exception e) {
if(logger.isEnabledFor(Level.WARN))
logger.warn(e.getMessage(), e);
}
}
if(logger.isInfoEnabled())
logger.info("Server has stopped listening for connections on port " + port);
}
}
@JmxGetter(name = "numActiveConnections", description = "total number of active connections across selector managers")
public final int getNumActiveConnections() {
int sum = 0;
for(NioSelectorManager manager: selectorManagers) {
sum += manager.getNumActiveConnections();
}
return sum;
}
@JmxGetter(name = "numQueuedConnections", description = "total number of connections pending for registration with selector managers")
public final int getNumQueuedConnections() {
int sum = 0;
for(NioSelectorManager manager: selectorManagers) {
sum += manager.getNumQueuedConnections();
}
return sum;
}
}