/
DcacheResourceFactory.java
1324 lines (1184 loc) · 42.5 KB
/
DcacheResourceFactory.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.webdav;
import com.google.common.base.Objects;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Range;
import com.google.common.io.ByteStreams;
import com.google.common.net.InetAddresses;
import io.milton.http.HttpManager;
import io.milton.http.Request;
import io.milton.http.ResourceFactory;
import io.milton.resource.Resource;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.stringtemplate.v4.AutoIndentWriter;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroup;
import org.stringtemplate.v4.STGroupFile;
import javax.security.auth.Subject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import diskCacheV111.util.CacheException;
import diskCacheV111.util.FileNotFoundCacheException;
import diskCacheV111.util.FsPath;
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.HttpDoorUrlInfoMessage;
import diskCacheV111.vehicles.HttpProtocolInfo;
import diskCacheV111.vehicles.IoDoorEntry;
import diskCacheV111.vehicles.IoDoorInfo;
import diskCacheV111.vehicles.PnfsCreateEntryMessage;
import diskCacheV111.vehicles.ProtocolInfo;
import dmg.cells.nucleus.CellMessage;
import dmg.cells.nucleus.NoRouteToCellException;
import dmg.cells.services.login.LoginManagerChildrenInfo;
import dmg.util.Args;
import org.dcache.auth.SubjectWrapper;
import org.dcache.auth.Subjects;
import dmg.cells.nucleus.AbstractCellComponent;
import dmg.cells.nucleus.CellCommandListener;
import dmg.cells.nucleus.CellMessageReceiver;
import org.dcache.cells.CellStub;
import org.dcache.missingfiles.AlwaysFailMissingFileStrategy;
import org.dcache.missingfiles.MissingFileStrategy;
import org.dcache.namespace.FileAttribute;
import org.dcache.util.PingMoversTask;
import org.dcache.util.RedirectedTransfer;
import org.dcache.util.Slf4jSTErrorListener;
import org.dcache.util.Transfer;
import org.dcache.util.TransferRetryPolicies;
import org.dcache.util.TransferRetryPolicy;
import org.dcache.util.list.DirectoryEntry;
import org.dcache.util.list.DirectoryListPrinter;
import org.dcache.util.list.ListDirectoryHandler;
import org.dcache.vehicles.FileAttributes;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Arrays.asList;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.dcache.namespace.FileAttribute.*;
import static org.dcache.namespace.FileType.*;
/**
* This ResourceFactory exposes the dCache name space through the
* Milton WebDAV framework.
*/
public class DcacheResourceFactory
extends AbstractCellComponent
implements ResourceFactory, CellMessageReceiver, CellCommandListener
{
private static final Logger _log =
LoggerFactory.getLogger(DcacheResourceFactory.class);
private static final Set<FileAttribute> REQUIRED_ATTRIBUTES =
EnumSet.of(TYPE, PNFSID, CREATION_TIME, MODIFICATION_TIME, SIZE,
MODE, OWNER, OWNER_GROUP);
// Additional attributes needed for PROPFIND requests; e.g., to supply
// values for properties.
private static final Set<FileAttribute> PROPFIND_ATTRIBUTES =
EnumSet.of(CHECKSUM, ACCESS_LATENCY, RETENTION_POLICY);
private static final String PROTOCOL_INFO_NAME = "Http";
private static final int PROTOCOL_INFO_MAJOR_VERSION = 1;
private static final int PROTOCOL_INFO_MINOR_VERSION = 1;
private static final int PROTOCOL_INFO_UNKNOWN_PORT = 0;
private static final long PING_DELAY = 300000;
private static final Splitter PATH_SPLITTER =
Splitter.on('/').omitEmptyStrings();
/**
* In progress transfers. The key of the map is the session
* id of the transfer.
*
* Note that the session id is cast to an integer - this is
* because HttpProtocolInfo uses integer ids. Casting the
* session ID increases the risk of collision due to wrapping
* of the ID. However this can only happen if transfers are
* longer than 50 days.
*/
private final Map<Integer,HttpTransfer> _transfers =
Maps.newConcurrentMap();
private ListDirectoryHandler _list;
private ScheduledExecutorService _executor;
private int _moverTimeout = 180000;
private TimeUnit _moverTimeoutUnit = MILLISECONDS;
private long _killTimeout = 1500;
private TimeUnit _killTimeoutUnit = MILLISECONDS;
private long _transferConfirmationTimeout = 60000;
private TimeUnit _transferConfirmationTimeoutUnit = MILLISECONDS;
private int _bufferSize = 65536;
private CellStub _poolStub;
private CellStub _poolManagerStub;
private CellStub _billingStub;
private PnfsHandler _pnfs;
private String _ioQueue;
private FsPath _rootPath = new FsPath();
private List<FsPath> _allowedPaths =
Collections.singletonList(new FsPath());
private InetAddress _internalAddress;
private String _path;
private boolean _doRedirectOnRead = true;
private boolean _doRedirectOnWrite = true;
private boolean _isOverwriteAllowed;
private boolean _isAnonymousListingAllowed;
private String _staticContentPath;
private STGroup _listingGroup;
private TransferRetryPolicy _retryPolicy =
TransferRetryPolicies.tryOncePolicy(_moverTimeout, _moverTimeoutUnit);
private MissingFileStrategy _missingFileStrategy =
new AlwaysFailMissingFileStrategy();
public DcacheResourceFactory()
throws UnknownHostException
{
_internalAddress = InetAddress.getLocalHost();
}
/**
* Returns the kill timeout in milliseconds.
*/
public long getKillTimeout()
{
return _killTimeout;
}
/**
* The kill timeout is the time we wait for a transfer to
* terminate after we killed the mover.
*
* @param timeout The mover timeout in milliseconds
*/
public void setKillTimeout(long timeout)
{
if (timeout <= 0) {
throw new IllegalArgumentException("Timeout must be positive");
}
_killTimeout = timeout;
}
public void setKillTimeoutUnit(TimeUnit unit)
{
_killTimeoutUnit = checkNotNull(unit);
}
public TimeUnit getKillTimeoutUnit()
{
return _killTimeoutUnit;
}
/**
* Returns the mover timeout in milliseconds.
*/
public int getMoverTimeout()
{
return _moverTimeout;
}
/**
* The mover timeout is the time we wait for the mover to start
* after having been enqueued.
*
* @param timeout The mover timeout in milliseconds
*/
public void setMoverTimeout(int timeout)
{
if (timeout <= 0) {
throw new IllegalArgumentException("Timeout must be positive");
}
_moverTimeout = timeout;
_retryPolicy = TransferRetryPolicies.tryOncePolicy(_moverTimeout, _moverTimeoutUnit);
}
public void setMoverTimeoutUnit(TimeUnit unit)
{
_moverTimeoutUnit = checkNotNull(unit);
_retryPolicy = TransferRetryPolicies.tryOncePolicy(_moverTimeout, _moverTimeoutUnit);
}
public TimeUnit getMoverTimeoutUnit()
{
return _moverTimeoutUnit;
}
/**
* Returns the transfer confirmation timeout in milliseconds.
*/
public long getTransferConfirmationTimeout()
{
return _transferConfirmationTimeout;
}
/**
* The transfer confirmation timeout is the time we wait after we
* know that an upload has finished and until we received the
* transfer confirmation message from the pool.
*
* @param timeout The transfer confirmation timeout in milliseconds
*/
public void setTransferConfirmationTimeout(long timeout)
{
_transferConfirmationTimeout = timeout;
}
public void setTransferConfirmationTimeoutUnit(TimeUnit unit)
{
_transferConfirmationTimeoutUnit = checkNotNull(unit);
}
public TimeUnit getTransferConfirmationTimeoutUnit()
{
return _transferConfirmationTimeoutUnit;
}
/**
* Returns the buffer size in bytes.
*/
public int getBufferSize()
{
return _bufferSize;
}
/**
* Sets the size of the buffer used when proxying uploads.
*
* @param bufferSize The buffer size in bytes
*/
public void setBufferSize(int bufferSize)
{
_bufferSize = bufferSize;
}
/**
* Returns the root path.
*/
public String getRootPath()
{
return _rootPath.toString();
}
/**
* Sets the root path of the WebDAV server. This path forms the
* root of the WebDAV share. All WebDAV access will be relative to
* this path.
*/
public void setRootPath(String path)
{
_rootPath = new FsPath(path);
}
/**
* Set the list of paths for which we allow access. Paths are
* separated by a colon. This paths are relative to the root path.
*/
public void setAllowedPaths(String s)
{
List<FsPath> list = new ArrayList<>();
for (String path: s.split(":")) {
list.add(new FsPath(path));
}
_allowedPaths = list;
}
/**
* Returns the list of allowed paths.
*/
public String getAllowedPaths()
{
StringBuilder s = new StringBuilder();
for (FsPath path: _allowedPaths) {
if (s.length() > 0) {
s.append(':');
}
s.append(path);
}
return s.toString();
}
/**
* Return the pool IO queue to use for WebDAV transfers.
*/
public String getIoQueue()
{
return (_ioQueue == null) ? "" : _ioQueue;
}
/**
* Sets the pool IO queue to use for WebDAV transfers.
*/
public void setIoQueue(String ioQueue)
{
_ioQueue = (ioQueue != null && !ioQueue.isEmpty()) ? ioQueue : null;
}
/**
* Sets whether read requests are redirected to the pool. If not,
* then the door will act as a proxy.
*/
public void setRedirectOnReadEnabled(boolean redirect)
{
_doRedirectOnRead = redirect;
}
public boolean isRedirectOnReadEnabled()
{
return _doRedirectOnRead;
}
public void setRedirectOnWriteEnabled(boolean redirect)
{
_doRedirectOnWrite = redirect;
}
public boolean isRedirectOnWriteEnabled()
{
return _doRedirectOnWrite;
}
/**
* Sets whether existing files may be overwritten.
*/
public void setOverwriteAllowed(boolean allowed)
{
_isOverwriteAllowed = allowed;
}
public boolean isOverwriteAllowed()
{
return _isOverwriteAllowed;
}
public void setAnonymousListing(boolean isAllowed)
{
_isAnonymousListingAllowed = isAllowed;
}
public boolean isAnonymousListing()
{
return _isAnonymousListingAllowed;
}
/**
* Sets the cell stub for PnfsManager communication.
*/
public void setPnfsStub(CellStub stub)
{
_pnfs = new PnfsHandler(stub);
}
/**
* Sets the cell stub for pool communication.
*/
public void setPoolStub(CellStub stub)
{
_poolStub = stub;
}
/**
* Sets the cell stub for PoolManager communication.
*/
public void setPoolManagerStub(CellStub stub)
{
_poolManagerStub = stub;
}
/**
* Sets the cell stub for billing communication.
*/
public void setBillingStub(CellStub stub)
{
_billingStub = stub;
}
/**
* Sets the behaviour of this door when the user requests a file
* that doesn't exist.
*/
public void setMissingFileStrategy(MissingFileStrategy strategy)
{
_missingFileStrategy = strategy;
}
/**
* Sets the ListDirectoryHandler used for directory listing.
*/
public void setListHandler(ListDirectoryHandler list)
{
_list = list;
}
/**
* Sets the resource containing the StringTemplateGroup for
* directory listing.
*/
public void setTemplateResource(org.springframework.core.io.Resource resource)
throws IOException
{
_listingGroup = new STGroupFile(resource.getURL(), "UTF-8", '$', '$');
_listingGroup.setListener(new Slf4jSTErrorListener(_log));
}
/**
* Returns the static content path.
*/
public String getStaticContentPath()
{
return _staticContentPath;
}
/**
* The static content path is the path under which the service
* exports the static content. This typically contains stylesheets
* and image files.
*/
public void setStaticContentPath(String path)
{
_staticContentPath = path;
}
/**
* Sets the ScheduledExecutorService used for periodic tasks.
*/
public void setExecutor(ScheduledExecutorService executor)
{
_executor = executor;
_executor.scheduleAtFixedRate(new PingMoversTask<>(_transfers.values()),
PING_DELAY, PING_DELAY,
MILLISECONDS);
}
public void setInternalAddress(String ipString)
throws IllegalArgumentException, UnknownHostException
{
if (!Strings.isNullOrEmpty(ipString)) {
InetAddress address = InetAddresses.forString(ipString);
if (address.isAnyLocalAddress()) {
throw new IllegalArgumentException("Wildcard address is not a valid local address: " + address);
}
_internalAddress = address;
} else {
_internalAddress = InetAddress.getLocalHost();
}
}
public String getInternalAddress()
{
return _internalAddress.getHostAddress();
}
@Override
public void getInfo(PrintWriter pw)
{
pw.println("Root path : " + getRootPath());
pw.println("Allowed paths: " + getAllowedPaths());
pw.println("IO queue : " + getIoQueue());
}
@Override
public Resource getResource(String host, String path)
{
if (_log.isDebugEnabled()) {
_log.debug("Resolving " + HttpManager.request().getAbsoluteUrl());
}
return getResource(getFullPath(path));
}
/**
* Returns the resource object for a path.
*
* @param path The full path
*/
public DcacheResource getResource(FsPath path)
{
if (!isAllowedPath(path)) {
return null;
}
FsPath requestPath = getRequestPath(path);
boolean haveRetried = false;
Subject subject = getSubject();
try {
while(true) {
try {
PnfsHandler pnfs = new PnfsHandler(_pnfs, subject);
Set<FileAttribute> requestedAttributes =
buildRequestedAttributes();
FileAttributes attributes =
pnfs.getFileAttributes(path.toString(), requestedAttributes);
return getResource(path, attributes);
} catch (FileNotFoundCacheException e) {
if(haveRetried) {
return null;
} else {
switch(_missingFileStrategy.recommendedAction(subject,
path, requestPath)) {
case FAIL:
return null;
case RETRY:
haveRetried = true;
break;
}
}
}
}
} catch (PermissionDeniedCacheException e) {
throw new UnauthorizedException(e.getMessage(), e, null);
} catch (CacheException e) {
throw new WebDavException(e.getMessage(), e, null);
}
}
/**
* Returns the resource object for a path.
*
* @param path The full path
* @param attributes The attributes of the object identified by the path
*/
private DcacheResource getResource(FsPath path, FileAttributes attributes)
{
if (attributes.getFileType() == DIR) {
return new DcacheDirectoryResource(this, path, attributes);
} else {
return new DcacheFileResource(this, path, attributes);
}
}
/**
* Returns a boolean indicating if the request should be redirected to a
* pool.
*
* @param request a Request
* @return a boolean indicating if the request should be redirected
*/
public boolean shouldRedirect(Request request)
{
switch (request.getMethod()) {
case GET:
return isRedirectOnReadEnabled();
case PUT:
boolean expects100Continue =
Objects.equal(request.getExpectHeader(), HttpHeaders.Values.CONTINUE);
return isRedirectOnWriteEnabled() && expects100Continue;
default:
return false;
}
}
/**
* Creates a new file. The door will relay all data to the pool.
*/
public DcacheResource createFile(FsPath path, InputStream inputStream, Long length)
throws CacheException, InterruptedException, IOException,
URISyntaxException
{
Subject subject = getSubject();
WriteTransfer transfer = new WriteTransfer(_pnfs, subject, path);
_transfers.put((int) transfer.getSessionId(), transfer);
try {
boolean success = false;
transfer.setProxyTransfer(true);
transfer.createNameSpaceEntry();
try {
transfer.setLength(length);
try {
transfer.selectPoolAndStartMover(_ioQueue, _retryPolicy);
String uri = transfer.waitForRedirect(_moverTimeout, _moverTimeoutUnit);
if (uri == null) {
throw new TimeoutCacheException("Server is busy (internal timeout)");
}
transfer.relayData(inputStream);
} finally {
transfer.killMover(_killTimeout, _killTimeoutUnit);
}
success = true;
} finally {
if (!success) {
transfer.deleteNameSpaceEntry();
}
}
} catch (CacheException e) {
transfer.notifyBilling(e.getRc(), e.getMessage());
throw e;
} catch (InterruptedException e) {
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
"Transfer interrupted");
throw e;
} catch (IOException | RuntimeException e) {
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
e.toString());
throw e;
} finally {
_transfers.remove((int) transfer.getSessionId());
}
return getResource(path);
}
public String getWriteUrl(FsPath path, Long length)
throws CacheException, InterruptedException,
URISyntaxException
{
Subject subject = getSubject();
String uri = null;
WriteTransfer transfer = new WriteTransfer(_pnfs, subject, path);
_transfers.put((int) transfer.getSessionId(), transfer);
try {
transfer.createNameSpaceEntry();
try {
transfer.setLength(length);
transfer.selectPoolAndStartMover(_ioQueue, _retryPolicy);
uri = transfer.waitForRedirect(_moverTimeout, _moverTimeoutUnit);
if (uri == null) {
throw new TimeoutCacheException("Server is busy (internal timeout)");
}
transfer.setStatus("Mover " + transfer.getPool() + "/" +
transfer.getMoverId() + ": Waiting for completion");
} finally {
if (uri == null) {
transfer.deleteNameSpaceEntry();
}
}
} catch (CacheException e) {
transfer.notifyBilling(e.getRc(), e.getMessage());
throw e;
} catch (InterruptedException e) {
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
"Transfer interrupted");
throw e;
} catch (RuntimeException e) {
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
e.toString());
throw e;
} finally {
if (uri == null) {
_transfers.remove((int) transfer.getSessionId());
}
}
return uri;
}
/**
* Reads the content of a file. The door will relay all data from
* a pool.
*/
public void readFile(FsPath path, PnfsId pnfsid,
OutputStream outputStream, io.milton.http.Range range)
throws CacheException, InterruptedException, IOException,
URISyntaxException
{
ReadTransfer transfer = beginRead(path, pnfsid, true);
try {
transfer.relayData(outputStream, range);
} catch (CacheException e) {
transfer.notifyBilling(e.getRc(), e.getMessage());
throw e;
} catch (InterruptedException e) {
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
"Transfer interrupted");
throw e;
} catch (IOException | RuntimeException e) {
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
e.toString());
throw e;
} finally {
_transfers.remove((int) transfer.getSessionId());
}
}
/**
* Performs a directory listing returning a list of Resource
* objects.
*/
public List<DcacheResource> list(final FsPath path)
throws InterruptedException, CacheException
{
if (!_isAnonymousListingAllowed && Subjects.isNobody(getSubject())) {
throw new PermissionDeniedCacheException("Access denied");
}
final List<DcacheResource> result = new ArrayList<>();
DirectoryListPrinter printer =
new DirectoryListPrinter()
{
@Override
public Set<FileAttribute> getRequiredAttributes()
{
return buildRequestedAttributes();
}
@Override
public void print(FsPath dir, FileAttributes dirAttr, DirectoryEntry entry)
{
result.add(getResource(new FsPath(path, entry.getName()),
entry.getFileAttributes()));
}
};
_list.printDirectory(getSubject(), printer, path, null,
Range.<Integer>all());
return result;
}
/**
* Performs a directory listing, writing an HTML view to an output
* stream.
* @throws URISyntaxException
*/
public void list(FsPath path, Writer out)
throws InterruptedException, CacheException, IOException, URISyntaxException
{
if (!_isAnonymousListingAllowed && Subjects.isNobody(getSubject())) {
throw new PermissionDeniedCacheException("Access denied");
}
Request request = HttpManager.request();
String requestPath = new URI(request.getAbsoluteUrl()).getPath();
String[] base =
Iterables.toArray(PATH_SPLITTER.split(requestPath), String.class);
final ST t = _listingGroup.getInstanceOf("page");
t.add("path", asList(UrlPathWrapper.forPaths(base)));
t.add("static", _staticContentPath);
t.add("subject", new SubjectWrapper(getSubject()));
t.add("base", UrlPathWrapper.forEmptyPath());
DirectoryListPrinter printer =
new DirectoryListPrinter() {
@Override
public Set<FileAttribute> getRequiredAttributes() {
return EnumSet.of(MODIFICATION_TIME, TYPE, SIZE);
}
@Override
public void print(FsPath dir, FileAttributes dirAttr, DirectoryEntry entry) {
FileAttributes attr = entry.getFileAttributes();
Date mtime = new Date(attr.getModificationTime());
UrlPathWrapper name =
UrlPathWrapper.forPath(entry.getName());
t.addAggr("files.{name,isDirectory,mtime,size}",
name,
attr.getFileType() == DIR,
mtime,
attr.getSize());
}
};
_list.printDirectory(getSubject(), printer, path, null,
Range.<Integer>all());
t.write(new AutoIndentWriter(out));
out.flush();
}
/**
* Deletes a file.
*/
public void deleteFile(PnfsId pnfsid, FsPath path)
throws CacheException
{
PnfsHandler pnfs = new PnfsHandler(_pnfs, getSubject());
pnfs.deletePnfsEntry(pnfsid, path.toString(),
EnumSet.of(REGULAR, LINK));
sendRemoveInfoToBilling(path);
}
private void sendRemoveInfoToBilling(FsPath path)
{
try {
DoorRequestInfoMessage infoRemove =
new DoorRequestInfoMessage(getCellAddress().toString(), "remove");
Subject subject = getSubject();
infoRemove.setSubject(subject);
infoRemove.setPath(path.toString());
infoRemove.setClient(Subjects.getOrigin(subject).getAddress().getHostAddress());
_billingStub.send(infoRemove);
} catch (NoRouteToCellException e) {
_log.error("Cannot send remove message to billing: {}",
e.getMessage());
}
}
/**
* Deletes a directory.
*/
public void deleteDirectory(PnfsId pnfsid, FsPath path)
throws CacheException
{
PnfsHandler pnfs = new PnfsHandler(_pnfs, getSubject());
pnfs.deletePnfsEntry(pnfsid, path.toString(),
EnumSet.of(DIR));
}
/**
* Create a new directory.
*/
public DcacheDirectoryResource
makeDirectory(FileAttributes parent, FsPath path)
throws CacheException
{
PnfsHandler pnfs = new PnfsHandler(_pnfs, getSubject());
PnfsCreateEntryMessage reply =
pnfs.createPnfsDirectory(path.toString());
FileAttributes attributes =
pnfs.getFileAttributes(reply.getPnfsId(), REQUIRED_ATTRIBUTES);
return new DcacheDirectoryResource(this, path, attributes);
}
public void move(PnfsId pnfsId, FsPath newPath)
throws CacheException
{
PnfsHandler pnfs = new PnfsHandler(_pnfs, getSubject());
pnfs.renameEntry(pnfsId, newPath.toString());
}
/**
* Returns a read URL for a file.
*
* @param path The full path of the file.
* @param pnfsid The PNFS ID of the file.
*/
public String getReadUrl(FsPath path, PnfsId pnfsid)
throws CacheException, InterruptedException, URISyntaxException
{
return beginRead(path, pnfsid, false).getRedirect();
}
/**
* Initiates a read operation.
*
*
* @param path The full path of the file.
* @param pnfsid The PNFS ID of the file.
* @param isProxyTransfer
* @return ReadTransfer encapsulating the read operation
*/
private ReadTransfer beginRead(FsPath path, PnfsId pnfsid, boolean isProxyTransfer)
throws CacheException, InterruptedException, URISyntaxException
{
Subject subject = getSubject();
String uri = null;
ReadTransfer transfer = new ReadTransfer(_pnfs, subject, path, pnfsid);
transfer.setIsChecksumNeeded(isDigestRequested());
_transfers.put((int) transfer.getSessionId(), transfer);
try {
transfer.setProxyTransfer(isProxyTransfer);
transfer.readNameSpaceEntry();
try {
transfer.selectPoolAndStartMover(_ioQueue, _retryPolicy);
uri = transfer.waitForRedirect(_moverTimeout, _moverTimeoutUnit);
if (uri == null) {
throw new TimeoutCacheException("Server is busy (internal timeout)");
}
} finally {
transfer.setStatus(null);
}
transfer.setStatus("Mover " + transfer.getPool() + "/" +
transfer.getMoverId() + ": Waiting for completion");
} catch (CacheException e) {
transfer.notifyBilling(e.getRc(), e.getMessage());
throw e;
} catch (InterruptedException e) {
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
"Transfer interrupted");
throw e;
} catch (RuntimeException e) {
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
e.toString());
throw e;
} finally {
if (uri == null) {
_transfers.remove((int) transfer.getSessionId());
}
}
return transfer;
}
/**
* Message handler for redirect messages from the pools.
*/
public void messageArrived(CellMessage envelope,
HttpDoorUrlInfoMessage message)
{
HttpTransfer transfer = _transfers.get((int) message.getId());
if (transfer != null) {
transfer.redirect(message.getUrl());
}
}
/**
* Message handler for transfer completion messages from the
* pools.
*/
public void messageArrived(DoorTransferFinishedMessage message)
{
Transfer transfer = _transfers.get((int) message.getId());
if (transfer != null) {
transfer.finished(message);
}
}
/**
* Given a path relative to the root path, this method returns a
* full PNFS path.
*/
private FsPath getFullPath(String path)
{
return new FsPath(_rootPath, new FsPath(path));
}
/**
* Convert a path within dCache's namespace into the corresponding
* path for a request. This is the inverse of getFullPath.
*/
private FsPath getRequestPath(FsPath internalPath)
{
return _rootPath.relativize(internalPath);
}
/**
* Returns true if access to path is allowed through the WebDAV
* door, false otherwise.
*/
private boolean isAllowedPath(FsPath path)
{
for (FsPath allowedPath: _allowedPaths) {
if (path.startsWith(allowedPath)) {
return true;
}
}
return false;