-
Notifications
You must be signed in to change notification settings - Fork 131
/
Transfer.java
1354 lines (1205 loc) · 49.9 KB
/
Transfer.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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.dcache.util;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.util.concurrent.Futures.catchingAsync;
import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static com.google.common.util.concurrent.Futures.transformAsync;
import static java.util.Objects.requireNonNull;
import static org.dcache.namespace.FileAttribute.CREATION_TIME;
import static org.dcache.namespace.FileAttribute.PNFSID;
import static org.dcache.namespace.FileAttribute.QOS_POLICY;
import static org.dcache.namespace.FileAttribute.QOS_STATE;
import static org.dcache.namespace.FileAttribute.SIZE;
import static org.dcache.namespace.FileAttribute.STORAGEINFO;
import static org.dcache.namespace.FileAttribute.TYPE;
import static org.dcache.namespace.FileType.REGULAR;
import static org.dcache.util.MathUtils.addWithInfinity;
import static org.dcache.util.MathUtils.subWithInfinity;
import com.google.common.base.Throwables;
import com.google.common.collect.Sets;
import com.google.common.io.BaseEncoding;
import com.google.common.primitives.Longs;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import diskCacheV111.poolManager.RequestContainerV5.RequestState;
import diskCacheV111.util.CacheException;
import diskCacheV111.util.CheckStagePermission;
import diskCacheV111.util.FileExistsCacheException;
import diskCacheV111.util.FileIsNewCacheException;
import diskCacheV111.util.FileNotFoundCacheException;
import diskCacheV111.util.FsPath;
import diskCacheV111.util.NotFileCacheException;
import diskCacheV111.util.PermissionDeniedCacheException;
import diskCacheV111.util.PnfsHandler;
import diskCacheV111.util.PnfsId;
import diskCacheV111.util.TimeoutCacheException;
import diskCacheV111.vehicles.DoorRequestInfoMessage;
import diskCacheV111.vehicles.DoorTransferFinishedMessage;
import diskCacheV111.vehicles.IoDoorEntry;
import diskCacheV111.vehicles.IoJobInfo;
import diskCacheV111.vehicles.MoverInfoMessage;
import diskCacheV111.vehicles.PnfsCreateEntryMessage;
import diskCacheV111.vehicles.Pool;
import diskCacheV111.vehicles.PoolAcceptFileMessage;
import diskCacheV111.vehicles.PoolDeliverFileMessage;
import diskCacheV111.vehicles.PoolIoFileMessage;
import diskCacheV111.vehicles.PoolMgrSelectPoolMsg;
import diskCacheV111.vehicles.PoolMgrSelectReadPoolMsg;
import diskCacheV111.vehicles.PoolMgrSelectWritePoolMsg;
import diskCacheV111.vehicles.PoolMoverKillMessage;
import diskCacheV111.vehicles.ProtocolInfo;
import dmg.cells.nucleus.CDC;
import dmg.cells.nucleus.CellAddressCore;
import dmg.cells.nucleus.CellPath;
import dmg.cells.nucleus.NoRouteToCellException;
import dmg.util.TimebasedCounter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.OptionalLong;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import javax.security.auth.Subject;
import org.dcache.acl.enums.AccessMask;
import org.dcache.auth.attributes.Restriction;
import org.dcache.auth.attributes.Restrictions;
import org.dcache.cells.CellStub;
import org.dcache.namespace.FileAttribute;
import org.dcache.namespace.FileType;
import org.dcache.poolmanager.PoolManagerStub;
import org.dcache.vehicles.FileAttributes;
import org.dcache.vehicles.PnfsGetFileAttributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.kafka.KafkaException;
/**
* Facade for transfer related operations. Encapsulates information about and typical operations of
* a transfer.
*/
public class Transfer implements Comparable<Transfer> {
protected static final Logger _log = LoggerFactory.getLogger(Transfer.class);
private static final TimebasedCounter _sessionCounter =
new TimebasedCounter();
private static final BaseEncoding SESSION_ENCODING = BaseEncoding.base64().omitPadding();
private static final EnumSet<FileAttribute> QOS_ATTRIBUTES =
EnumSet.of(QOS_POLICY, QOS_STATE);
protected final PnfsHandler _pnfs;
/**
* Point in time when this transfer is created.
*/
protected final long _startedAt;
protected final FsPath _path;
protected final Subject _subject;
protected final long _id;
protected final String _session;
protected PoolManagerStub _poolManager;
protected CellStub _poolStub;
protected CellStub _billing;
protected CheckStagePermission _checkStagePermission;
private CellAddressCore _cellAddress;
private Pool _pool;
private Integer _moverId;
private boolean _hasMoverBeenCreated;
private boolean _hasMoverFinished;
private String _status;
private CacheException _error;
private FileAttributes _fileAttributes = new FileAttributes();
private ProtocolInfo _protocolInfo;
private boolean _isWrite;
private List<InetSocketAddress> _clientAddresses;
private String _ioQueue;
private Set<String> _tried;
private long _allocated;
private OptionalLong _maximumSize = OptionalLong.empty();
private PoolMgrSelectReadPoolMsg.Context _readPoolSelectionContext;
private boolean _isBillingNotified;
protected boolean _isOverwriteAllowed;
private Set<FileAttribute> _additionalAttributes =
EnumSet.noneOf(FileAttribute.class);
private MoverInfoMessage moverInfoMessage;
private Consumer<DoorRequestInfoMessage> _kafkaSender = (s) -> {
};
private static final ThreadFactory RETRY_THREAD_FACTORY =
new ThreadFactoryBuilder().setDaemon(true).setNameFormat("transfer-retry-timer-%d")
.build();
private static final ScheduledExecutorService RETRY_EXECUTOR =
new CDCScheduledExecutorServiceDecorator<>(
Executors.newScheduledThreadPool(1, RETRY_THREAD_FACTORY));
/**
* Which activities poolmanager is allowed to do.
*/
private EnumSet<RequestState> _allowedRequestStates = EnumSet.allOf(RequestState.class);
private synchronized EnumSet<RequestState> getAllowedRequestStates() {
return EnumSet.copyOf(_allowedRequestStates);
}
/**
* Constructs a new Transfer object.
*
* @param pnfs PnfsHandler used for pnfs communication
* @param namespaceSubject The subject performing the namespace operations
* @param namespaceRestriction Any additional restrictions from this users session
* @param ioSubject The subject performing the transfer
* @param path The path of the file to transfer
*/
public Transfer(PnfsHandler pnfs, Subject namespaceSubject,
Restriction namespaceRestriction, Subject ioSubject, FsPath path) {
_pnfs = new PnfsHandler(pnfs, namespaceSubject, namespaceRestriction);
_subject = ioSubject;
_path = path;
_startedAt = System.currentTimeMillis();
_id = _sessionCounter.next();
_session = CDC.getSession();
_checkStagePermission = new CheckStagePermission(null);
_checkStagePermission.setAllowAnonymousStaging(true);
}
/**
* Constructs a new Transfer object.
*
* @param pnfs PnfsHandler used for pnfs communication
* @param subject The subject performing the transfer and namespace operations
* @param restriction Any additional restrictions from this users session
* @param path The path of the file to transfer
*/
public Transfer(PnfsHandler pnfs, Subject subject, Restriction restriction, FsPath path) {
this(pnfs, subject, restriction, subject, path);
}
/**
* Returns a ProtocolInfo suitable for selecting a pool. By default the protocol info set with
* setProtocolInfo is returned.
*/
protected ProtocolInfo getProtocolInfoForPoolManager() {
checkState(_protocolInfo != null);
return _protocolInfo;
}
/**
* Returns a ProtocolInfo suitable for starting a mover. By default the protocol info set with
* setProtocolInfo is returned.
*/
protected ProtocolInfo getProtocolInfoForPool() {
checkState(_protocolInfo != null);
return _protocolInfo;
}
/**
* Sets the ProtocolInfo used for the transfer.
*/
public synchronized void setProtocolInfo(ProtocolInfo info) {
_protocolInfo = info;
}
/**
* Returns the ProtocolInfo used for the transfer. May be null.
*/
@Nullable
public synchronized ProtocolInfo getProtocolInfo() {
return _protocolInfo;
}
/**
* Orders Transfer objects according to hash value. Makes it possible to add Transfer objects to
* tree based collections.
*/
@Override
public int compareTo(Transfer o) {
return Long.compare(o.getId(), getId());
}
/**
* Returns the ID of this transfer. The transfer ID uniquely identifies this transfer object
* within this VM instance.
* <p>
* The transfer ID is used as the message ID for both the pool selection message sent to
* PoolManager and the io file message to the pool. The DoorTransferFinishedMessage from the
* pool will have the same ID.
* <p>
* IoDoorEntry instances provided for monitoring will contain the transfer ID and the active
* transfer page of the httpd service reports the transfer ID in the sequence column.
* <p>
* The transfer ID is not to be confused with session string identifier used for logging. The
* former identifies a single transfer while the latter identifies a user session and could in
* theory span multiple transfers.
*/
public long getId() {
return _id;
}
/**
* Sets CellStub for PoolManager.
*/
public synchronized void setPoolManagerStub(PoolManagerStub stub) {
_poolManager = requireNonNull(stub, "PoolManager stub can't be null");
}
/**
* Sets CellStub for pools.
*/
public synchronized void setPoolStub(CellStub stub) {
_poolStub = requireNonNull(stub, "Pool stub can't be null");
}
/**
* Sets CellStub for Billing.
*/
public synchronized void setBillingStub(CellStub stub) {
_billing = requireNonNull(stub, "Billing stub can't be null");
}
public synchronized void setKafkaSender(Consumer<DoorRequestInfoMessage> kafkaSender) {
_kafkaSender = kafkaSender;
}
public synchronized void
setCheckStagePermission(CheckStagePermission checkStagePermission) {
_checkStagePermission = checkStagePermission;
}
/**
* Sets the current status of a transfer. May be null.
*/
public synchronized void setStatus(String status) {
if (status != null) {
_log.debug("Status: {}", status);
}
_status = status;
}
/**
* Sets the current status of a pool and clear the status once the given future completes.
*/
public void setStatusUntil(String status, ListenableFuture<?> future) {
setStatus(status);
future.addListener(() -> setStatus(null), MoreExecutors.directExecutor());
}
/**
* Sets the current status of a pool. May be null.
*/
@Nullable
public synchronized String getStatus() {
return _status;
}
/**
* When true, existing files will be overwritten on write.
*/
public synchronized void setOverwriteAllowed(boolean allowed) {
_isOverwriteAllowed = allowed;
}
/**
* Sets the FileAttributes of the file to transfer.
*/
public synchronized FileAttributes getFileAttributes() {
return _fileAttributes;
}
/**
* Sets the FileAttributes of the file to transfer.
*/
public synchronized void setFileAttributes(FileAttributes fileAttributes) {
_fileAttributes = fileAttributes;
}
/**
* The name space path of the file being transferred.
*/
public synchronized String getTransferPath() {
return _path.toString();
}
/**
* The billable name space path of the file being transferred.
*/
public synchronized String getBillingPath() {
if (_fileAttributes.isDefined(STORAGEINFO)
&& _fileAttributes.getStorageInfo().getKey("path") != null) {
return _fileAttributes.getStorageInfo().getKey("path");
} else {
return _path.toString();
}
}
/**
* Returns the PnfsId of the file to be transferred.
*/
@Nullable
public synchronized PnfsId getPnfsId() {
return _fileAttributes.isDefined(PNFSID) ? _fileAttributes.getPnfsId() : null;
}
/**
* Sets the PnfsId of the file to be transferred.
*/
public synchronized void setPnfsId(PnfsId pnfsid) {
_fileAttributes.setPnfsId(pnfsid);
}
/**
* Sets whether this is an upload.
*/
protected synchronized void setWrite(boolean isWrite) {
_isWrite = isWrite;
}
/**
* Returns whether this is an upload.
*/
public synchronized boolean isWrite() {
return _isWrite;
}
/**
* Registers the fact that the transfer now has a mover.
*
* @param moverId The mover ID of the transfer.
*/
public synchronized void setMoverId(Integer moverId) {
_moverId = moverId;
_hasMoverBeenCreated = (_moverId != null);
}
/**
* Returns the ID of the mover of this transfer.
*/
@Nullable
public synchronized Integer getMoverId() {
return _moverId;
}
/**
* Returns whether this transfer has a mover (to the best of our knowledge).
*/
public synchronized boolean hasMover() {
return _hasMoverBeenCreated && !_hasMoverFinished;
}
/**
* Sets the pool to use for this transfer.
*/
public synchronized void setPool(Pool pool) {
_pool = pool;
}
/**
* Returns the pool to use for this transfer.
*/
@Nullable
public synchronized Pool getPool() {
return _pool;
}
/**
* Clear selected pool and enforce re-selection during retry procedure in {@link
* #selectPoolAndStartMoverAsync(TransferRetryPolicy)}.
*/
private synchronized void clearPoolSelection() {
_pool = null;
}
public synchronized void setAllowStaging(boolean isAllowed) {
if (isAllowed) {
_allowedRequestStates.add(RequestState.ST_STAGE);
} else {
_allowedRequestStates.remove(RequestState.ST_STAGE);
}
}
public synchronized void setAllowPool2Pool(boolean isAllowed) {
if (isAllowed) {
_allowedRequestStates.add(RequestState.ST_POOL_2_POOL);
} else {
_allowedRequestStates.remove(RequestState.ST_POOL_2_POOL);
}
}
public synchronized void setTriedHosts(Set<String> tried) {
_tried = tried;
}
/**
* Initialises the session value in the cells diagnostic context (CDC). The session value is
* attached to the thread.
* <p>
* The session key is pushed to the NDC for purposes of logging.
* <p>
* The format of the session value is chosen to be compatible with the transaction ID format as
* found in the InfoMessage.getTransaction method.
*
* @param isCellNameSiteUnique True if the cell name is unique throughout this dCache
* site, that is, it is well known or derived from a well
* known name.
* @param isCellNameTemporallyUnique True if the cell name is temporally unique, that is, two
* invocations of initSession will never have the same cell
* name.
* @throws IllegalStateException when the thread is not already associated with a cell through
* the CDC.
*/
public static void initSession(boolean isCellNameSiteUnique,
boolean isCellNameTemporallyUnique) {
Object domainName = MDC.get(CDC.MDC_DOMAIN);
Object cellName = MDC.get(CDC.MDC_CELL);
checkState(domainName != null, "Missing domain name in MDC");
checkState(cellName != null, "Missing cell name in MDC");
StringBuilder session = new StringBuilder();
session.append("door:").append(cellName);
if (!isCellNameSiteUnique) {
session.append('@').append(domainName);
}
if (!isCellNameTemporallyUnique) {
session.append(':')
.append(SESSION_ENCODING.encode(Longs.toByteArray(_sessionCounter.next())));
}
String s = session.toString();
CDC.setSession(s);
NDC.push(s);
}
/**
* The transaction uniquely (with a high probably) identifies this transfer.
*/
public synchronized String getTransaction() {
if (_session != null) {
return _session + ":" + _id;
} else if (_cellAddress != null) {
return "door:" + _cellAddress + ":" + _id;
} else {
return String.valueOf(_id);
}
}
/**
* Restore cells diagnostic context for the transfer's session.
*/
public void restoreSession() {
CDC.setSession(_session);
NDC.push(_session);
}
/**
* Signals that the mover of this transfer finished.
*/
public synchronized void finished(CacheException error) {
_hasMoverFinished = true;
_error = error;
notifyAll();
}
/**
* Signals that the mover of this transfer finished.
*/
public final synchronized void finished(int rc, String error) {
if (rc != 0) {
finished(new CacheException(rc, error));
} else {
finished((CacheException) null);
}
}
/**
* Signals that the mover of this transfer finished.
*/
public final synchronized void finished(DoorTransferFinishedMessage msg) {
setFileAttributes(msg.getFileAttributes());
setProtocolInfo(msg.getProtocolInfo());
moverInfoMessage = msg.getMoverInfo();
if (msg.getReturnCode() != 0) {
finished(CacheExceptionFactory.exceptionOf(msg));
} else {
finished((CacheException) null);
}
}
public synchronized void setCellAddress(CellAddressCore address) {
_cellAddress = address;
}
/**
* Returns the cell name of the door handling the transfer.
*/
public synchronized String getCellName() {
checkState(_cellAddress != null);
return _cellAddress.getCellName();
}
/**
* Returns the domain name of the door handling the transfer.
*/
public synchronized String getDomainName() {
checkState(_cellAddress != null);
return _cellAddress.getCellDomainName();
}
/**
* The client address is the socket address from which the transfer was initiated.
*/
public synchronized void setClientAddress(InetSocketAddress address) {
_clientAddresses = Collections.singletonList(address);
}
/**
* The client address(es) that initiated the request. If the protocol does not support
* reporting relayed requests then this is a single entry. If the protocol allows reporting of
* client addresses then the list-order represents the clients that initiated this request,
* starting with the client on the TCP connection.
*/
public synchronized void setClientAddresses(List<InetSocketAddress> addresses) {
checkArgument(!addresses.isEmpty(), "empty address list is not allowed");
_clientAddresses = addresses;
}
/**
* Report the address of the client that connected to dCache when initiated this transfer.
*/
@Nullable
public synchronized InetSocketAddress getClientAddress() {
return _clientAddresses == null ? null : _clientAddresses.get(0);
}
/**
* Report all relays and the client that initiated this transfer. The last item is the client
* that initiated the transfer; any addresses earlier in the list represent relay clients. The
* first item is the client that directly connected to dCache.
*/
@Nullable
public synchronized List<InetSocketAddress> getClientAddresses() {
return _clientAddresses;
}
public boolean waitForMover(long timeout, TimeUnit unit)
throws CacheException, InterruptedException {
return waitForMover(unit.toMillis(timeout));
}
/**
* Blocks until the mover of this transfer finished, or until a timeout is reached. Relies on
* the DoorTransferFinishedMessage being injected into the transfer through the
* <code>finished</code> method.
*
* @param millis The timeout in milliseconds
* @return true when the mover has finished
* @throws CacheException if the mover failed
* @throws InterruptedException if the thread is interrupted
*/
public synchronized boolean waitForMover(long millis)
throws CacheException, InterruptedException {
long deadline = addWithInfinity(System.currentTimeMillis(), millis);
while (!_hasMoverFinished && System.currentTimeMillis() < deadline) {
wait(subWithInfinity(deadline, System.currentTimeMillis()));
}
if (_error != null) {
throw _error;
}
return _hasMoverFinished;
}
/**
* Returns an IoDoorEntry describing the transfer. This is used by the "Active Transfer" view of
* the HTTP monitor.
*/
public synchronized IoDoorEntry getIoDoorEntry() {
return new IoDoorEntry(_id,
getPnfsId(),
getTransferPath(),
_subject,
_pool == null ? "<unknown>" : _pool.getName(),
_status,
_startedAt,
_clientAddresses.get(0)
.getAddress()
.getHostAddress());
}
/**
* Creates a new name space entry for the file to transfer. This will fill in the PnfsId and
* StorageInfo of the file and mark the transfer as an upload.
* <p>
* Will fail if the subject of the transfer doesn't have permission to create the file.
* <p>
* If the parent directories don't exist, then they will be created.
*
* @throws CacheException if creating the entry failed
*/
public void createNameSpaceEntryWithParents()
throws CacheException {
try {
createNameSpaceEntry();
} catch (FileNotFoundCacheException e) {
_pnfs.createDirectories(_path.parent());
createNameSpaceEntry();
}
}
/**
* Creates a new name space entry for the file to transfer. This will fill in the PnfsId and
* StorageInfo of the file and mark the transfer as an upload.
* <p>
* Will fail if the subject of the transfer doesn't have permission to create the file.
*
* @throws CacheException if creating the entry failed
*/
public void createNameSpaceEntry()
throws CacheException {
setStatus("PnfsManager: Creating name space entry");
try {
FileAttributes desiredAttributes = fileAttributesForNameSpace();
PnfsCreateEntryMessage msg;
try {
msg = _pnfs.createPnfsEntry(_path.toString(),
desiredAttributes);
} catch (FileExistsCacheException e) {
/* REVISIT: This should be moved to PnfsManager with a
* flag in the PnfsCreateEntryMessage.
*/
if (!_isOverwriteAllowed) {
throw e;
}
_pnfs.deletePnfsEntry(_path.toString(), EnumSet.of(REGULAR));
msg = _pnfs.createPnfsEntry(_path.toString(),
desiredAttributes);
}
FileAttributes attrs = msg.getFileAttributes();
setFileAttributes(attrs);
setWrite(true);
} finally {
setStatus(null);
}
}
protected FileAttributes fileAttributesForNameSpace() {
return FileAttributes.ofFileType(REGULAR);
}
/**
* Reads the name space entry of the file to transfer. This will fill in the PnfsId and
* FileAttributes of the file.
* <p>
* Changes the I/O mode from write to read if the file is not new.
*
* @param allowWrite whether the file may be opened for writing
* @throws PermissionDeniedCacheException if permission to read/write the file is denied
* @throws NotFileCacheException if the file is not a regular file
* @throws FileIsNewCacheException when attempting to download an incomplete file
* @throws CacheException if reading the entry failed
* @throws InterruptedException if the thread is interrupted
*/
public final void readNameSpaceEntry(boolean allowWrite)
throws CacheException, InterruptedException {
try {
getCancellable(readNameSpaceEntryAsync(allowWrite));
} catch (NoRouteToCellException e) {
throw new TimeoutCacheException(e.getMessage(), e);
}
}
/**
* Reads the name space entry of the file to transfer. This will fill in the PnfsId and
* FileAttributes of the file.
* <p>
* Changes the I/O mode from write to read if the file is not new.
*
* @param allowWrite whether the file may be opened for writing
*/
public ListenableFuture<Void> readNameSpaceEntryAsync(boolean allowWrite) {
return readNameSpaceEntryAsync(allowWrite, _pnfs.getPnfsTimeout());
}
private ListenableFuture<Void> readNameSpaceEntryAsync(boolean allowWrite, long timeout) {
Set<FileAttribute> attr = EnumSet.of(PNFSID, TYPE, STORAGEINFO, SIZE, CREATION_TIME);
attr.addAll(_additionalAttributes);
attr.addAll(PoolMgrSelectReadPoolMsg.getRequiredAttributes());
Set<AccessMask> mask;
if (allowWrite) {
attr.addAll(QOS_ATTRIBUTES);
mask = EnumSet.of(AccessMask.READ_DATA, AccessMask.WRITE_DATA);
} else {
mask = EnumSet.of(AccessMask.READ_DATA);
}
PnfsId pnfsId = getPnfsId();
PnfsGetFileAttributes request;
if (pnfsId != null) {
request = new PnfsGetFileAttributes(pnfsId, attr);
if (_path != null) {
// Needed for restriction check.
request.setPnfsPath(_path.toString());
}
} else {
request = new PnfsGetFileAttributes(_path.toString(), attr);
}
request.setAccessMask(mask);
request.setUpdateAtime(true);
ListenableFuture<PnfsGetFileAttributes> reply = _pnfs.requestAsync(request, timeout);
setStatusUntil("PnfsManager: Fetching storage info", reply);
return CellStub.transformAsync(reply,
msg -> {
FileAttributes attributes = msg.getFileAttributes();
/* We can only transfer regular files.
*/
FileType type = attributes.getFileType();
if (type == FileType.DIR || type == FileType.SPECIAL) {
throw new NotFileCacheException("Not a regular file");
}
/* I/O mode must match completeness of the file.
*/
if (!attributes.getStorageInfo().isCreatedOnly()) {
setWrite(false);
} else if (allowWrite) {
setWrite(true);
} else {
throw new FileIsNewCacheException();
}
setFileAttributes(attributes);
return immediateFuture(null);
});
}
/**
* Specify a set of additional attributes as part of this transfer's namespace operation. Any
* prior specified extra attributes are removed. In addition, some attributes required by this
* class and are always fetched.
*/
protected void setAdditionalAttributes(Set<FileAttribute> attributes) {
_additionalAttributes = Sets.immutableEnumSet(attributes);
}
/**
* Discover the set of additional attributes that will be fetched as part of this transfer's
* namespace operation. In addition to the returned set, this class will always fetch certain
* attributes, which may not be reflected in the returned set.
*/
protected Set<FileAttribute> getAdditionalAttributes() {
return _additionalAttributes;
}
/**
* Returns the length of the file to be transferred.
*
* @throws IllegalStateException if the length isn't known
*/
public synchronized long getLength() {
return _fileAttributes.getSize();
}
/**
* Sets the length of the file to be uploaded. Only valid for uploads.
*/
public synchronized void setLength(long length) {
checkState(isWrite(), "Can only set length for uploads");
// The following check is to catch bugs: the door should have already handled this situation
checkArgument(!_maximumSize.isPresent() || _maximumSize.getAsLong() >= length,
"file length is larger than the already specified maximum length");
_fileAttributes.setSize(length);
}
/**
* Sets checksum of the file to be uploaded. Can be called multiple times with different
* checksums types. Only valid for uploads.
*
* @param checksum of the file
* @throws CacheException if reading the entry failed
*/
public void setChecksum(Checksum checksum) throws CacheException {
if (!isWrite()) {
throw new IllegalStateException("Can only set checksum for uploads");
}
try {
setStatus("PnfsManager: Setting checksum");
FileAttributes attr = FileAttributes.ofChecksum(checksum);
_pnfs.setFileAttributes(_path, attr);
synchronized (this) {
_fileAttributes.addChecksums(Collections.singleton(checksum));
}
} finally {
setStatus(null);
}
}
/**
* Sets the size of the preallocation to make.
* <p>
* Only affects uploads. If the upload is larger than the preallocation, then the upload may
* fail.
*/
public synchronized void setAllocation(long length) {
_allocated = length;
}
/**
* Set the maximum allowed size for an upload. If the size of the file is known in advance then
* {@link #setLength(long)} should be used instead.
*
* @param length the maximum number of bytes for this transfer.
*/
public synchronized void setMaximumLength(long length) {
checkState(isWrite(), "Can only set maximum length for uploads");
checkArgument(length > 0, "maximum length must be a positive number");
// The following check is to catch bugs: the door should have already handled this situation
checkArgument(!_fileAttributes.isDefined(SIZE) || _fileAttributes.getSize() <= length,
"maximum file length is smaller than already specified file length");
_maximumSize = OptionalLong.of(length);
}
/**
* Sets the mover queue to use.
*/
public synchronized void setIoQueue(String queue) {
_ioQueue = queue;
}
/**
* Returns the mover queue to be used.
*/
@Nullable
public synchronized String getIoQueue() {
return _ioQueue;
}
/**
* Returns the read pool selection context.
*/
protected synchronized PoolMgrSelectReadPoolMsg.Context getReadPoolSelectionContext() {
return _readPoolSelectionContext;
}
/**
* Sets the previous read pool selection message. The message contains state that is maintained
* across repeated pool selections.
*/
protected synchronized void setReadPoolSelectionContext(
PoolMgrSelectReadPoolMsg.Context context) {
_readPoolSelectionContext = context;
}
/**
* Selects a pool suitable for the transfer.
*/
public ListenableFuture<Void> selectPoolAsync(long timeout) {
if (getPool() != null) {
// we have a valid preselected pool. Let use it as long as clearPoolSelection is not called.
return immediateFuture(null);
}
FileAttributes fileAttributes = getFileAttributes();
ProtocolInfo protocolInfo = getProtocolInfoForPoolManager();
ListenableFuture<? extends PoolMgrSelectPoolMsg> reply;
if (isWrite()) {
long allocated = _allocated;
if (allocated == 0 && fileAttributes.isDefined(SIZE)) {
allocated = fileAttributes.getSize();
}
PoolMgrSelectWritePoolMsg request =
new PoolMgrSelectWritePoolMsg(fileAttributes,
protocolInfo,
allocated);
request.setId(_id);
request.setSubject(_subject);
request.setBillingPath(getBillingPath());
request.setTransferPath(getTransferPath());
request.setIoQueueName(getIoQueue());
request.setExcludedHosts(_tried);
reply = _poolManager.sendAsync(request, timeout);
} else {
EnumSet<RequestState> allowedStates = getAllowedRequestStates();
try {
if (allowedStates.contains(RequestState.ST_STAGE) &&
!_checkStagePermission.canPerformStaging(_subject,
fileAttributes, protocolInfo)) {
allowedStates.remove(RequestState.ST_STAGE);
}
} catch (IOException e) {
return immediateFailedFuture(
new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
e.getMessage()));
}
PoolMgrSelectReadPoolMsg request =
new PoolMgrSelectReadPoolMsg(fileAttributes,
protocolInfo,
getReadPoolSelectionContext(),
allowedStates);
request.setId(_id);
request.setSubject(_subject);
request.setBillingPath(getBillingPath());
request.setTransferPath(getTransferPath());
request.setIoQueueName(getIoQueue());
request.setExcludedHosts(_tried);
reply = Futures.transform(_poolManager.sendAsync(request, timeout),
(PoolMgrSelectReadPoolMsg msg) -> {
setReadPoolSelectionContext(msg.getContext());
return msg;
}, MoreExecutors.directExecutor());
}
setStatusUntil("PoolManager: Selecting pool", reply);
return CellStub.transform(reply,
(PoolMgrSelectPoolMsg msg) -> {
setPool(msg.getPool());
setFileAttributes(msg.getFileAttributes());
return null;
});
}
/**
* Creates a mover for the transfer.
*/
public ListenableFuture<Void> startMoverAsync(long timeout) {
FileAttributes fileAttributes = getFileAttributes();