/
NettyLineBasedDoor.java
444 lines (382 loc) · 14.6 KB
/
NettyLineBasedDoor.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
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/*
* dCache - http://www.dcache.org/
*
* Copyright (C) 2016 Deutsches Elektronen-Synchrotron
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package diskCacheV111.doors;
import com.google.common.cache.LoadingCache;
import com.google.common.net.InetAddresses;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.ChannelInputShutdownEvent;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import io.netty.handler.codec.haproxy.HAProxyProxiedProtocol;
import io.netty.handler.codec.string.LineEncoder;
import io.netty.handler.codec.string.LineSeparator;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.nio.channels.ClosedChannelException;
import java.nio.charset.Charset;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import diskCacheV111.services.space.Space;
import dmg.cells.nucleus.CDC;
import dmg.cells.nucleus.CellCommandListener;
import dmg.cells.nucleus.CellInfoProvider;
import dmg.cells.nucleus.CellMessageReceiver;
import dmg.cells.nucleus.NoRouteToCellException;
import dmg.util.CommandExitException;
import dmg.util.LineWriter;
import org.dcache.cells.AbstractCell;
import org.dcache.poolmanager.PoolManagerHandler;
import org.dcache.services.login.IdentityResolverFactory;
import org.dcache.space.ReservationCaches.GetSpaceTokensKey;
import org.dcache.util.Args;
import org.dcache.util.BoundedExecutor;
import org.dcache.util.SequentialExecutor;
import org.dcache.util.Transfer;
import static org.dcache.util.ByteUnit.KiB;
/**
* Login cell for line based protocols.
*
* <p>To be used with LoginManager. The cell is a Netty handler and expects Netty to pass
* and accept Strings. These are passed on to an interpreter for processing.
*/
public class NettyLineBasedDoor
extends AbstractCell implements ChannelInboundHandler
{
private static final Logger LOGGER = LoggerFactory.getLogger(NettyLineBasedDoor.class);
/**
* Factory for creating the protocol interpreter.
*/
private final NettyLineBasedInterpreterFactory factory;
/**
* Executor for processing commands.
*/
private final BoundedExecutor commandExecutor;
/**
* Executor for the interpreter.
*/
private final Executor executor;
/**
* Shared handler for communicating with pool manager.
*/
private final PoolManagerHandler poolManager;
/**
* Character encoding of the protocol.
*/
private final Charset charset;
/**
* Line separator encoding of the protocol.
*/
private final LineSeparator lineSeparator;
/**
* Whether to expect an HAProxy proxy protocol header.
*/
private final boolean expectProxyProtocol;
/**
* Line oriented protocol interpreter.
*/
private LineBasedInterpreter interpreter;
/**
* Cell logging context under which protocol lines are interpreted.
*/
private CDC cdc;
/**
* Netty channel. The life cycle of this cell is bound to this channel.
*/
private Channel channel;
private String clientAddress;
/**
* The socket address of this host. The socket may be connected to the
* client directly or to a proxy.
*/
private InetSocketAddress localAddress;
/**
* The socket address the client connected to - may be the same as {@link #localAddress}
* or may be the address of some proxy service.
*/
private InetSocketAddress proxyAddress;
/**
* The address of the client's socket. May be connected directly to us
* or to a proxy.
*/
private InetSocketAddress remoteAddress;
/**
* The identity resolver factory to be injected into the interpreter.
*/
private final IdentityResolverFactory idResolverFactory;
/**
* A cache for looking up reservations based on user and description.
*/
private final LoadingCache<GetSpaceTokensKey, long[]> spaceDescriptionCache;
/**
* A cache for looking up current reservation values.
*/
private final LoadingCache<String,Optional<Space>> spaceLookupCache;
public NettyLineBasedDoor(String cellName, Args args, NettyLineBasedInterpreterFactory factory,
ExecutorService executor, PoolManagerHandler poolManagerHandler,
IdentityResolverFactory idResolverFactory,
LoadingCache<GetSpaceTokensKey, long[]> spaceDescriptionCache,
LoadingCache<String,Optional<Space>> spaceLookupCache)
{
super(cellName, args, executor);
this.factory = factory;
this.executor = executor;
this.commandExecutor = new SequentialExecutor(executor);
this.poolManager = poolManagerHandler;
this.charset = Charset.forName(args.getOption("charset", "UTF-8"));
String lineSeparator = args.getOption("lineSeparator", "WINDOWS");
switch (lineSeparator) {
case "WINDOWS":
this.lineSeparator = LineSeparator.WINDOWS;
break;
case "UNIX":
this.lineSeparator = LineSeparator.UNIX;
break;
default:
throw new IllegalArgumentException("Invalid line separator value: " + lineSeparator);
}
this.expectProxyProtocol = args.getBooleanOption("expectProxyProtocol");
this.idResolverFactory = idResolverFactory;
this.spaceDescriptionCache = spaceDescriptionCache;
this.spaceLookupCache = spaceLookupCache;
}
public void messageArrived(NoRouteToCellException e)
{
LOGGER.warn(e.getMessage());
}
protected void start(ChannelHandlerContext ctx) throws Exception
{
LineWriter writer = ctx::writeAndFlush;
clientAddress = remoteAddress.getAddress().getHostAddress();
LOGGER.debug("Client host: {}", clientAddress);
interpreter = factory.create(this, getNucleus().getThisAddress(),
remoteAddress, proxyAddress, localAddress,
writer, executor, poolManager, idResolverFactory,
spaceDescriptionCache, spaceLookupCache);
if (interpreter instanceof CellCommandListener) {
addCommandListener(interpreter);
}
if (interpreter instanceof CellMessageReceiver) {
addMessageListener((CellMessageReceiver) interpreter);
}
if (interpreter instanceof TlsStarter) {
((TlsStarter)interpreter).setTlsStarter(e -> {
e.setUseClientMode(false);
ctx.pipeline().addFirst("tls", new SslHandler(e, true));
});
}
start().get(); // Blocking to prevent that we process any commands before the cell is alive
}
/**
* Called by the cell infrastructure when the cell has been killed.
*
* The socket will be closed by this method. It is quite important
* that this does not happen earlier, as several threads use the
* output stream. This is the only place where we can be 100%
* certain, that all the other threads are done with their job.
*
* The method blocks until the worker thread has terminated.
*/
@Override
public void stopped()
{
if (interpreter != null) {
interpreter.messagingClosed();
}
channel.close().syncUninterruptibly();
super.stopped();
}
@Override
public void getInfo(PrintWriter pw)
{
pw.println(" User Host : " + clientAddress);
LineBasedInterpreter interpreter = this.interpreter;
if (interpreter instanceof CellInfoProvider) {
((CellInfoProvider) interpreter).getInfo(pw);
}
}
protected void shutdown()
{
if (!commandExecutor.isShutdown()) {
commandExecutor.shutdownNow();
commandExecutor.awaitTerminationUninterruptibly();
if (interpreter != null) {
interpreter.shutdown();
}
}
kill();
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception
{
try (CDC ignored = CDC.reset(getNucleus().getThisAddress())) {
Transfer.initSession(false, true);
cdc = new CDC();
}
channel = ctx.channel();
channel.config().setOption(ChannelOption.ALLOW_HALF_CLOSURE, true);
channel.config().setOption(ChannelOption.TCP_NODELAY, true);
channel.config().setOption(ChannelOption.SO_KEEPALIVE, true);
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception
{
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception
{
try (CDC ignored = cdc.restore()) {
proxyAddress = localAddress = (InetSocketAddress) ctx.channel().localAddress();
remoteAddress = (InetSocketAddress) ctx.channel().remoteAddress();
if (!expectProxyProtocol) {
start(ctx);
}
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception
{
try (CDC ignored = cdc.restore()) {
shutdown();
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
{
if (msg instanceof HAProxyMessage) {
HAProxyMessage proxyMessage = (HAProxyMessage) msg;
switch (proxyMessage.command()) {
case LOCAL:
ctx.close();
return;
case PROXY:
String sourceAddress = proxyMessage.sourceAddress();
String destinationAddress = proxyMessage.destinationAddress();
InetSocketAddress localAddress = (InetSocketAddress) ctx.channel().localAddress();
if (proxyMessage.proxiedProtocol() == HAProxyProxiedProtocol.TCP4 ||
proxyMessage.proxiedProtocol() == HAProxyProxiedProtocol.TCP6) {
if (Objects.equals(destinationAddress, localAddress.getAddress().getHostAddress())) {
/* Workaround for what looks like a bug in HAProxy - health checks should
* generate a LOCAL command, but it appears they do actually use PROXY.
*/
ctx.close();
return;
} else {
this.proxyAddress = new InetSocketAddress(InetAddresses.forString(destinationAddress),
proxyMessage.destinationPort());
this.remoteAddress = new InetSocketAddress(InetAddresses.forString(sourceAddress),
proxyMessage.sourcePort());
}
}
break;
}
start(ctx);
} else if (msg instanceof String) {
if (interpreter == null) {
throw new IOException("Unexpected input: " + msg);
}
commandExecutor.execute(new Command((String) msg));
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception
{
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception
{
try (CDC ignored = cdc.restore()) {
if (evt instanceof ChannelInputShutdownEvent) {
shutdown();
}
}
}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception
{
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
{
try (CDC ignored = cdc.restore()) {
if (cause instanceof ClosedChannelException) {
LOGGER.info("Connection closed");
} else if (cause instanceof RuntimeException || cause instanceof Error) {
Thread me = Thread.currentThread();
me.getUncaughtExceptionHandler().uncaughtException(me, cause);
ctx.close();
} else {
LOGGER.error(cause.toString());
ctx.close();
}
}
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception
{
ChannelPipeline pipeline = ctx.pipeline();
String self = ctx.name();
if (expectProxyProtocol) {
pipeline.addBefore("door", "haproxy", new HAProxyMessageDecoder());
}
// Decoders
pipeline.addBefore(self, "frameDecoder", new LineBasedFrameDecoder(KiB.toBytes(64)));
pipeline.addBefore(self, "stringDecoder", new StringDecoder(charset));
// Encoder
pipeline.addBefore(self, "lineEncoder", new LineEncoder(lineSeparator, charset));
pipeline.addBefore(self, "logger", new LoggingHandler());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception
{
}
private class Command implements Runnable
{
private final String command;
public Command(String command)
{
this.command = command;
}
@Override
public void run()
{
try (CDC ignored = cdc.restore()) {
try {
interpreter.execute(command);
} catch (CommandExitException e) {
channel.close();
} catch (RuntimeException e) {
LOGGER.error("Bug detected", e);
}
}
}
}
}