/
Mode.java
491 lines (441 loc) · 14.9 KB
/
Mode.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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
package org.dcache.ftp.data;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.UnresolvedAddressException;
import java.util.HashMap;
import java.util.Map;
import org.dcache.pool.repository.RepositoryChannel;
/**
* Base class for FTP transfer mode implementations.
*
* A mode may make use of several connections at the same time. The
* transfer will be coordinated by the mode object. Therefore, the
* mode object knows about the file to transfer and the direction of
* the transfer.
*/
public abstract class Mode extends AbstractMultiplexerListener
{
protected Role _role;
protected Direction _direction;
protected RepositoryChannel _file;
protected ConnectionMonitor _monitor;
private long _position;
private long _size;
private long _fileSize;
/** Buffer for transferTo and transferFrom. */
private ByteBuffer _buffer = ByteBuffer.allocate(8192);
/** The address to connect to for outgoing connections. */
private SocketAddress _address;
/** The channel used for incomming connections. */
private ServerSocketChannel _channel;
/** Size of send and recv buffer when larger than 0. */
private int _bufferSize;
/** The largest number of concurrent connections to accept. */
protected int _parallelism = 1;
/** Disabled keys. The value is the interest set of the key. */
protected Map<SelectionKey, Integer> disabled
= new HashMap<>();
/** Number of connections for which connect failed. */
protected int _failed;
/** Number of connections that have been opened. */
protected int _opened;
/** Number of connections that have been closed. */
protected int _closed;
/** Constructs a new mode for outgoing connections. */
public Mode(Role role, RepositoryChannel file, ConnectionMonitor monitor)
throws IOException
{
_fileSize = file.size();
_role = role;
_file = file;
_size = _fileSize;
_monitor = monitor;
}
/**
* Enable passive mode. Connections will be accepted on the given
* channel.
*/
public void setPassive(ServerSocketChannel channel)
{
assert _address == null && _channel == null && channel != null;
_direction = Direction.Incomming;
_channel = channel;
}
/**
* Enable active mode. Connections will be made to the given
* address.
*
* @throws UnresolvedAddressException if the address is unresolved
*/
public void setActive(InetSocketAddress address)
throws UnresolvedAddressException
{
assert _address == null && _channel == null && address != null;
if (address.isUnresolved()) {
throw new UnresolvedAddressException();
}
_direction = Direction.Outgoing;
_address = address;
}
/**
* Set parameters for partial retrive. This makes only sense when
* the role is Role.Sender.
*/
public void setPartialRetrieveParameters(long position, long size)
{
if (_position < 0 || size < 0 || position + size > _fileSize) {
throw new IllegalArgumentException();
}
_position = position;
_size = size;
}
/**
* Set socket buffer size. The same value is used for send and
* receive buffers. A value of zero enables auto tuning. Auto
* tuning is enabled by default.
*/
public void setBufferSize(int value)
{
if (value < 0) {
throw new IllegalArgumentException("Buffer size must be non-negative");
}
_bufferSize = value;
}
/**
* Sets the number of concurrent connections to use. Only relevant
* for outgoing connections. Parallelism is not supported by all
* modes.
*/
public void setParallelism(int value)
{
if (value <= 0) {
throw new IllegalArgumentException("Parallelism must be positive");
}
_parallelism = value;
}
/** Returns the starting position of the transfer. */
public long getStartPosition()
{
return _position;
}
/** Returns the number of bytes to transfer. */
public long getSize()
{
return _size;
}
/**
* Like calling _file.transferTo().
*
* This method behaves similarly to FileChannel.transferTo, except
* that it never uses zero-copy mode. FileChannel.transferTo has
* been subject to a large number of bugs throughout the history
* of Java.
*/
protected long transferTo(long position, long count, SocketChannel socket)
throws IOException
{
long tr = 0; // Total bytes read
long pos = position;
_buffer.clear();
while (tr < count) {
_buffer.limit((int)Math.min((count - tr),
(long)_buffer.capacity()));
int nr = _file.read(_buffer, pos);
if (nr < 0 && tr == 0) {
return -1;
}
if (nr <= 0) {
break;
}
_buffer.flip();
int nw = socket.write(_buffer);
tr += nw;
if (nw != nr) {
break;
}
pos += nw;
_buffer.clear();
}
return tr;
}
/**
* Similar to _file.transferFrom(). In contrast to
* FileChannel.transferFrom(), this method does detect
* end-of-stream and returns -1 in that case.
*
* Originally, this method was based on
* FileChannel.transferFrom(), but spurious behaviour was observed
* in some cases (transferFrom returning 0, even though the
* selector claimed data was ready and a normal read returned
* data).
*
* The current implementation copies data into memory and writes
* it do disk. This should be no slower than using
* FileChannel.transferFrom() from JDK 6, since that does exactly
* the same when copying from a SocketChannel.
*
* An alternative would be to map the file into memory and read
* from the socket directly into the mapped file. That however
* would be better done at a higher level and it is currently
* unknown if the performance would improve.
*/
protected long transferFrom(SocketChannel socket, long position, long count)
throws IOException
{
long tw = 0; // Total bytes written
long pos = position;
try {
_buffer.clear();
while (tw < count) {
_buffer.limit((int)Math.min((count - tw),
(long)_buffer.capacity()));
int nr = socket.read(_buffer);
if (nr < 0 && tw == 0) {
return -1;
}
if (nr <= 0) {
break;
}
_buffer.flip();
int nw = _file.write(_buffer, pos);
tw += nw;
if (nw != nr) {
break;
}
pos += nw;
_buffer.clear();
}
return tw;
} catch (IOException x) {
if (tw > 0) {
return tw;
}
throw x;
}
}
/**
* Register the mode for outgoing connections. One or more
* connections will be established asynchronously. The number of
* connections to create is controlled by the parallelism.
*
* An IOException may be thrown if all connections attempts
* fail. Failures to create a SocketChannel are propagated to the
* caller.
*
* @see setParallelism(), SocketChannel.open()
*/
protected void registerOutgoing(Multiplexer multiplexer)
throws Exception
{
IOException lastException = null;
for (int i = 0; i < _parallelism; i++) {
/* Errors in socket channel creation are likely to
* indicate some serious problems. Therefore we let the
* caller figure out what to do (i.e. we do not catch the
* exception).
*/
SocketChannel channel = SocketChannel.open();
try {
channel.configureBlocking(false);
if (_bufferSize > 0) {
channel.socket().setReceiveBufferSize(_bufferSize);
channel.socket().setSendBufferSize(_bufferSize);
}
channel.socket().setKeepAlive(true);
SelectionKey key =
multiplexer.register(this, SelectionKey.OP_CONNECT, channel);
multiplexer.say("Connecting to " + _address);
if (channel.connect(_address)) {
connect(multiplexer, key);
}
} catch (IOException e) {
// Any error is logged, but otherwise ignored. As
// long as at least one connection succeeds, the
// transfer can be completed.
channel.close();
lastException = e;
multiplexer.esay(e.toString());
_failed++;
if (allConnectionsEstablished()) {
enableDisabledKeys();
}
}
}
if (_failed == _parallelism) {
throw lastException;
}
}
/**
* Register the mode for incomming connections.
*/
protected void registerIncomming(Multiplexer multiplexer)
throws IOException
{
_channel.configureBlocking(false);
multiplexer.say("Accepting connections on " +
_channel.socket().getLocalSocketAddress());
multiplexer.register(this, SelectionKey.OP_ACCEPT, _channel);
}
/**
* Registers this mode with a multiplexer.
*/
@Override
public void register(Multiplexer multiplexer)
throws Exception
{
assert _address != null || _channel != null
: "Mode must be either set to passive or active.";
switch (_direction) {
case Incomming:
registerIncomming(multiplexer);
break;
case Outgoing:
registerOutgoing(multiplexer);
break;
default:
// Ignore
break;
}
}
/**
* Called by the multiplexer when a new incomming connection can
* be accepted. A new socket is created and newConnection() is
* called.
*
* Failure to accept the connection is propagated to the caller.
*/
@Override
public void accept(Multiplexer multiplexer, SelectionKey key)
throws Exception
{
ServerSocketChannel server = (ServerSocketChannel)key.channel();
SocketChannel channel = server.accept();
if (channel != null) {
Socket socket = channel.socket();
_opened++;
multiplexer.say("Opened " + socket);
channel.configureBlocking(false);
if (_bufferSize > 0) {
channel.socket().setSendBufferSize(_bufferSize);
}
channel.socket().setKeepAlive(true);
newConnection(multiplexer, channel);
}
}
/**
* Called by the multiplexer when a new outgoing connection has
* been established. If all outgoing connections have been
* established or failed, then all keys disabled by
* waitForConnectionCompletion() are enabled.
*
* Propagates failures to finish the connection establishment to
* the caller.
*/
@Override
public void connect(Multiplexer multiplexer, SelectionKey key)
throws Exception
{
try {
SocketChannel channel = (SocketChannel)key.channel();
if (channel.finishConnect()) {
Socket socket = channel.socket();
_opened++;
multiplexer.say("Opened " + socket);
newConnection(multiplexer, channel);
}
} catch (IOException e) {
_failed++;
if (_failed == _parallelism) {
throw e;
}
} finally {
if (allConnectionsEstablished()) {
enableDisabledKeys();
}
}
}
/**
* Close the socket channel associated with key.
*
* If mayShutdown is true and all connections have been closed,
* then the multiplexer is shut down.
*/
protected void close(Multiplexer multiplexer, SelectionKey key,
boolean mayShutdown)
throws IOException
{
SocketChannel channel = (SocketChannel)key.channel();
multiplexer.say("Closing " + channel.socket());
key.cancel();
channel.close();
_closed++;
if (mayShutdown && _closed == _opened) {
multiplexer.shutdown();
}
}
/**
* Reestablishes notification for all disabled keys.
*
* @see disableKey
*/
private void enableDisabledKeys()
{
for (Map.Entry<SelectionKey,Integer> e : disabled.entrySet()) {
e.getKey().interestOps(e.getValue());
}
disabled.clear();
}
/**
* Disables notification for a key.
*
* @see enableDisabledKeys
*/
private void disableKey(SelectionKey key)
{
if (!disabled.containsKey(key)) {
disabled.put(key, key.interestOps());
key.interestOps(0);
}
}
/**
* Returns true iff all connections have been either established
* or failed.
*/
private boolean allConnectionsEstablished()
{
return (_opened + _failed >= _parallelism);
}
/**
* Returns true if all connections have been established or
* connection establishment has failed (wrt. the parallelism),
* false otherwise. When false, the key is deactivated until
* waitForConnectionCompletion would return true.
*
* This call is only valid if the direction of the mode is set to
* Outgoing.
*/
protected boolean waitForConnectionCompletion(SelectionKey key)
{
if (_direction != Direction.Outgoing) {
throw new IllegalArgumentException("Call is only valid for outgoing connections");
}
if (allConnectionsEstablished()) {
return true;
}
disableKey(key);
return false;
}
/**
* Called by a Connection object when a new connection has been
* established.
*/
abstract protected void newConnection(Multiplexer multiplexer,
SocketChannel channel)
throws Exception;
}