-
Notifications
You must be signed in to change notification settings - Fork 131
/
DcacheResourceFactory.java
1886 lines (1648 loc) · 69.6 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 static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.cycle;
import static com.google.common.collect.Iterables.limit;
import static java.util.Arrays.asList;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.dcache.http.HttpPoolRequestHandler.REFERRER_QUERY_PARAM;
import static org.dcache.namespace.FileAttribute.ACCESS_LATENCY;
import static org.dcache.namespace.FileAttribute.CHECKSUM;
import static org.dcache.namespace.FileAttribute.CREATION_TIME;
import static org.dcache.namespace.FileAttribute.MODE;
import static org.dcache.namespace.FileAttribute.MODIFICATION_TIME;
import static org.dcache.namespace.FileAttribute.OWNER;
import static org.dcache.namespace.FileAttribute.OWNER_GROUP;
import static org.dcache.namespace.FileAttribute.PNFSID;
import static org.dcache.namespace.FileAttribute.RETENTION_POLICY;
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.FileAttribute.XATTR;
import static org.dcache.namespace.FileType.DIR;
import static org.dcache.namespace.FileType.LINK;
import static org.dcache.namespace.FileType.REGULAR;
import static org.dcache.util.ByteUnit.KiB;
import static org.dcache.util.TransferRetryPolicy.tryOnce;
import static org.dcache.webdav.InsufficientStorageException.checkStorageSufficient;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Splitter;
import com.google.common.base.Throwables;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.net.InetAddresses;
import com.google.common.net.MediaType;
import diskCacheV111.poolManager.PoolMonitorV5;
import diskCacheV111.services.space.Space;
import diskCacheV111.services.space.SpaceException;
import diskCacheV111.util.CacheException;
import diskCacheV111.util.FileLocality;
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.PnfsReadExtendedAttributesMessage;
import diskCacheV111.vehicles.PnfsWriteExtendedAttributesMessage.Mode;
import diskCacheV111.vehicles.PoolIoFileMessage;
import diskCacheV111.vehicles.PoolMoverKillMessage;
import diskCacheV111.vehicles.ProtocolInfo;
import dmg.cells.nucleus.AbstractCellComponent;
import dmg.cells.nucleus.CellCommandListener;
import dmg.cells.nucleus.CellInfoProvider;
import dmg.cells.nucleus.CellMessageReceiver;
import dmg.cells.nucleus.CellPath;
import dmg.cells.services.login.LoginManagerChildrenInfo;
import io.milton.http.HttpManager;
import io.milton.http.Request;
import io.milton.http.ResourceFactory;
import io.milton.http.ResponseStatus;
import io.milton.http.exceptions.BadRequestException;
import io.milton.resource.Resource;
import io.milton.servlet.ServletRequest;
import io.milton.servlet.ServletResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.QueryStringEncoder;
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.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import javax.annotation.PostConstruct;
import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import org.dcache.auth.Origin;
import org.dcache.auth.RolePrincipal;
import org.dcache.auth.RolePrincipal.Role;
import org.dcache.auth.SubjectWrapper;
import org.dcache.auth.Subjects;
import org.dcache.auth.attributes.LoginAttribute;
import org.dcache.auth.attributes.LoginAttributes;
import org.dcache.auth.attributes.Restriction;
import org.dcache.auth.attributes.Restrictions;
import org.dcache.cells.CellStub;
import org.dcache.http.AuthenticationHandler;
import org.dcache.http.PathMapper;
import org.dcache.missingfiles.AlwaysFailMissingFileStrategy;
import org.dcache.missingfiles.MissingFileStrategy;
import org.dcache.namespace.FileAttribute;
import org.dcache.poolmanager.PoolManagerStub;
import org.dcache.poolmanager.PoolMonitor;
import org.dcache.util.Args;
import org.dcache.util.Checksum;
import org.dcache.util.ChecksumType;
import org.dcache.util.Checksums;
import org.dcache.util.Exceptions;
import org.dcache.util.NetworkUtils;
import org.dcache.util.PingMoversTask;
import org.dcache.util.RedirectedTransfer;
import org.dcache.util.Transfer;
import org.dcache.util.TransferRetryPolicy;
import org.dcache.util.Xattrs;
import org.dcache.util.list.DirectoryEntry;
import org.dcache.util.list.DirectoryListPrinter;
import org.dcache.util.list.ListDirectoryHandler;
import org.dcache.vehicles.FileAttributes;
import org.dcache.webdav.owncloud.OwncloudClients;
import org.dcache.webdav.transfer.RemoteTransferHandler;
import org.eclipse.jetty.io.EofException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.kafka.KafkaException;
import org.springframework.kafka.core.KafkaTemplate;
import org.stringtemplate.v4.AutoIndentWriter;
import org.stringtemplate.v4.ST;
/**
* This ResourceFactory exposes the dCache name space through the Milton WebDAV framework.
*/
public class DcacheResourceFactory
extends AbstractCellComponent
implements ResourceFactory, CellMessageReceiver, CellCommandListener, CellInfoProvider {
private static final Logger LOGGER =
LoggerFactory.getLogger(DcacheResourceFactory.class);
public static final String TRANSACTION_ATTRIBUTE = "org.dcache.transaction";
private static final Set<FileAttribute> MINIMALLY_REQUIRED_ATTRIBUTES =
EnumSet.of(TYPE, PNFSID, CREATION_TIME, MODIFICATION_TIME, SIZE,
MODE, OWNER, OWNER_GROUP);
private static final Set<FileAttribute> REQUIRED_ATTRIBUTES =
EnumSet.of(TYPE, PNFSID, CREATION_TIME, MODIFICATION_TIME, SIZE,
MODE, OWNER, OWNER_GROUP, XATTR);
private static final String HTML_TEMPLATE_LISTING_NAME = "page";
private static final String HTML_TEMPLATE_CLIENT_NAME = "client";
// Additional attributes needed for PROPFIND requests; e.g., to supply
// values for properties.
private static final Set<FileAttribute> PROPFIND_ATTRIBUTES = Sets.union(
EnumSet.of(CHECKSUM, ACCESS_LATENCY, RETENTION_POLICY, STORAGEINFO),
PoolMonitorV5.getRequiredAttributesForFileLocality());
private static final String PROTOCOL_INFO_NAME = "Http";
private static final String PROTOCOL_INFO_SSL_NAME = "Https";
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();
enum PropfindProperties {
PERFORMANCE,
CLIENT_COMPATIBLE
};
/**
* In progress transfers. The key of the map is the session id of the transfer.
* <p>
* 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();
/**
* Cache of the current status of space reservations.
*/
private LoadingCache<String, Optional<Space>> _spaceLookupCache;
private LoadingCache<FsPath, Optional<String>> _writeTokenCache;
private ListDirectoryHandler _list;
private ScheduledExecutorService _executor;
private int _moverTimeout;
private TimeUnit _moverTimeoutUnit;
private long _killTimeout = 1500;
private TimeUnit _killTimeoutUnit = MILLISECONDS;
private long _transferConfirmationTimeout = 60000;
private TimeUnit _transferConfirmationTimeoutUnit = MILLISECONDS;
private int _bufferSize = KiB.toBytes(64);
private CellStub _poolStub;
private PoolManagerStub _poolManagerStub;
private CellStub _billingStub;
private PnfsHandler _pnfs;
private String _ioQueue;
private PathMapper _pathMapper;
private List<FsPath> _allowedPaths =
Collections.singletonList(FsPath.ROOT);
private InetAddress _internalAddress;
private String _path;
private boolean _doRedirectOnRead = true;
private boolean _doRedirectOnWrite = true;
private boolean _impatientClientProxied = true;
private boolean _isOverwriteAllowed;
private boolean _isAnonymousListingAllowed;
private boolean _includeAllAttributesForPropfind;
private String _staticContentPath;
private ReloadableTemplate _template;
private ImmutableMap<String, String> _templateConfig;
private RemoteTransferHandler _remoteTransferHandler;
private TransferRetryPolicy _retryPolicy;
private MissingFileStrategy _missingFileStrategy =
new AlwaysFailMissingFileStrategy();
private PoolMonitor _poolMonitor;
private boolean _redirectToHttps;
private Consumer<DoorRequestInfoMessage> _kafkaSender = (s) -> {
};
public DcacheResourceFactory()
throws UnknownHostException {
_internalAddress = InetAddress.getLocalHost();
}
@Autowired(required = false)
private void setTransferTemplate(KafkaTemplate kafkaTemplate) {
_kafkaSender = kafkaTemplate::sendDefault;
}
@Required
public void setSpaceLookupCache(LoadingCache<String, Optional<Space>> cache) {
_spaceLookupCache = cache;
}
@Required
public void setWriteTokenCache(LoadingCache<FsPath, Optional<String>> cache) {
_writeTokenCache = cache;
}
@Required
public void setPoolMonitor(PoolMonitor monitor) {
_poolMonitor = monitor;
}
@Required
public void setRedirectToHttps(boolean redirectToHttps) {
_redirectToHttps = redirectToHttps;
}
@Required
public void setRemoteTransferHandler(RemoteTransferHandler handler) {
_remoteTransferHandler = requireNonNull(handler);
}
/**
* 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 = requireNonNull(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
*/
@Required
public void setMoverTimeout(int timeout) {
checkState(_moverTimeout == 0, "mover timeout already set");
checkArgument(timeout > 0, "mover timeout must be positive");
_moverTimeout = timeout;
}
@Required
public void setMoverTimeoutUnit(TimeUnit unit) {
checkState(_moverTimeoutUnit == null, "mover timeout unit already set");
_moverTimeoutUnit = requireNonNull(unit);
}
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 = requireNonNull(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;
}
/**
* Provide the mapping between request path and dCache internal path.
*/
@Required
public void setPathMapper(PathMapper mapper) {
_pathMapper = mapper;
}
/**
* 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(FsPath.create(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;
}
public void setImpatientClientProxied(boolean proxied) {
_impatientClientProxied = proxied;
}
public boolean isImpatientClientProxied() {
return _impatientClientProxied;
}
/**
* 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.
*
* @param stub
*/
public void setPoolManagerStub(PoolManagerStub 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.
*/
@Required
public void setTemplate(ReloadableTemplate template) {
_template = template;
}
@Required
public void setTemplateConfig(ImmutableMap<String, String> config) {
_templateConfig = config;
}
/**
* 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 {
_internalAddress = NetworkUtils.getInternalAddress(ipString);
}
public String getInternalAddress() {
return _internalAddress.getHostAddress();
}
@PostConstruct
public void init() {
checkState(_moverTimeout > 0, "Mover timeout not specified");
checkState(_moverTimeoutUnit != null, "Mover timeout units not specified");
_retryPolicy = tryOnce().timeoutAfter(_moverTimeout, _moverTimeoutUnit);
}
public boolean isDoorRoot(FsPath path) {
return _pathMapper.isDoorRoot(ServletRequest.getRequest(), path);
}
@Override
public void getInfo(PrintWriter pw) {
pw.println("Allowed paths: " + getAllowedPaths());
pw.println("IO queue : " + getIoQueue());
}
@Override
public Resource getResource(String host, String requestPath) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Resolving {}", HttpManager.request().getAbsoluteUrl());
}
FsPath dCachePath = _pathMapper.asDcachePath(ServletRequest.getRequest(),
requestPath, m -> new ForbiddenException(m, null));
return getResource(dCachePath);
}
/**
* Returns the resource object for a path.
*
* @param path The full path
*/
public DcacheResource getResource(FsPath path) {
checkPathAllowed(path);
boolean haveRetried = false;
Subject subject = getSubject();
String requestPath = getRequestPath();
try {
while (true) {
try {
PnfsHandler pnfs = roleAwarePnfsHandler();
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 WebDavExceptions.permissionDenied(e.getMessage(), e,
new InaccessibleResource(path));
} catch (CacheException e) {
throw new WebDavException(e.getMessage(), e, new InaccessibleResource(path));
}
}
/**
* 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,
_includeAllAttributesForPropfind);
} 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);
/* Has the client started sending the entity for a PUT request that
* is using the expect-100 protocol. RFC 7231 says:
*
* o A client that sends a 100-continue expectation is not required
* to wait for any specific length of time; such a client MAY
* proceed to send the message body even if it has not yet
* received a response. Furthermore, since 100 (Continue)
* responses cannot be sent through an HTTP/1.0 intermediary, such
* a client SHOULD NOT wait for an indefinite period before
* sending the message body.
*
* By default, libcurl waits a maximum of one second for the
* "100 Continue" response before sending the content anyway,
* libwww-perl waits two seconds, Apache common httpclient waits
* three seconds.
*
* The redirection response could take longer than one second if
* the mover is queued on the pool, or the pool is busy and delays
* starting the mover, or ...
*
* If the client times out waiting for dCache's response and
* started sending the HTTP entity (the file's data) then the client
* will only notice the redirection after sending the entire fire.
* This forces the client to send the data twice.
*
* To avoid this, the door can proxy the data if the client has
* already started to send the entity.
*/
boolean proxyImpatientClient = expects100Continue
&& isImpatientClientProxied()
&& ((MiltonHandler.DcacheServletRequest) request).isClientSendingEntity();
if (proxyImpatientClient) {
LOGGER.warn(
"Proxying transfer because client has already started sending data.");
}
return isRedirectOnWriteEnabled() && expects100Continue && !proxyImpatientClient;
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, BadRequestException {
Subject subject = getSubject();
Restriction restriction = getRestriction();
checkUploadSize(length);
WriteTransfer transfer = new WriteTransfer(_pnfs, subject, restriction, path);
_transfers.put((int) transfer.getId(), transfer);
try {
boolean success = false;
transfer.setProxyTransfer(true);
transfer.createNameSpaceEntry();
try {
transfer.setLength(length);
try {
transfer.selectPoolAndStartMover(_retryPolicy);
String uri = transfer.waitForRedirect(_moverTimeout, _moverTimeoutUnit);
if (uri == null) {
throw new TimeoutCacheException("Server is busy (internal timeout)");
}
transfer.relayData(inputStream);
} catch (EofException e) {
// REVISIT: do we wish to log diagnostic/forensic details of the transfer?
LOGGER.info("Proxied upload of {} failed: client disconnected", transfer.getPnfsId());
String explanation = "Client disconnected while proxying an upload.";
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION, explanation);
transfer.killMover(explanation);
throw new ClientDisconnectedException(explanation);
} catch (IOException e) {
String message = Exceptions.messageOrClassName(e);
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
"Error relaying data: " + message);
transfer.killMover("door experienced error relaying data: " + message);
throw e;
} catch (BadRequestException e) {
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
e.getMessage());
transfer.killMover("pool reported bad request: " + e.getMessage());
throw e;
} catch (InsufficientStorageException e) {
transfer.notifyBilling(CacheException.RESOURCE, e.getMessage());
transfer.killMover("pool reported insufficient storage: " + e.getMessage());
throw e;
} catch (CacheException e) {
transfer.notifyBilling(e.getRc(), e.getMessage());
transfer.killMover("door experienced internal error: " + e.getMessage());
throw e;
} catch (InterruptedException e) {
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
"Shutting down");
transfer.killMover("door shutting down");
throw e;
} catch (RuntimeException e) {
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
"Found bug: " + e);
transfer.killMover("door encountered a bug");
throw e;
} finally {
transfer.killMover("door found orphaned mover");
}
success = true;
} finally {
if (!success) {
transfer.deleteNameSpaceEntry();
}
}
} finally {
_transfers.remove((int) transfer.getId());
}
return getResource(path);
}
public String getWriteUrl(FsPath path, Long length)
throws CacheException, InterruptedException,
URISyntaxException {
Subject subject = getSubject();
Restriction restriction = getRestriction();
checkUploadSize(length);
String uri = null;
WriteTransfer transfer = new WriteTransfer(_pnfs, subject, restriction, path);
transfer.setSSL(_redirectToHttps && ServletRequest.getRequest().isSecure());
_transfers.put((int) transfer.getId(), transfer);
try {
transfer.createNameSpaceEntry();
try {
transfer.setLength(length);
transfer.selectPoolAndStartMover(_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");
} catch (CacheException e) {
transfer.notifyBilling(e.getRc(), e.getMessage());
transfer.killMover("door experienced internal error: " + e.getMessage());
throw e;
} catch (InterruptedException e) {
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
"Shutting down");
transfer.killMover("door shutting down");
throw e;
} catch (RuntimeException e) {
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
e.toString());
transfer.killMover("door encountered a bug");
throw e;
} finally {
if (uri == null) {
transfer.killMover("door found orphaned mover");
transfer.deleteNameSpaceEntry();
}
}
} finally {
if (uri == null) {
_transfers.remove((int) transfer.getId());
}
}
return appendReferrer(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, null);
try {
transfer.relayData(outputStream, range);
} catch (CacheException e) {
transfer.notifyBilling(e.getRc(), e.getMessage());
transfer.killMover("door experienced internal error: " + e.getMessage());
throw e;
} catch (InterruptedException e) {
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
"Shutting down");
transfer.killMover("door shutting down");
throw e;
} catch (EofException e) {
// REVISIT: do we wish to log diagnostic/forensic details of the transfer?
LOGGER.info("Proxied download of {} failed: client disconnected", transfer.getPnfsId());
String explanation = "Client disconnected while proxying a download.";
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION, explanation);
transfer.killMover(explanation);
throw new ClientDisconnectedException(explanation);
} catch (IOException e) {
String message = Exceptions.messageOrClassName(e);
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
"Error relaying data: " + message);
transfer.killMover("door experienced error relaying data: " + message);
throw e;
} catch (RuntimeException e) {
transfer.notifyBilling(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
"Found bug: " + e);
transfer.killMover("door encountered a bug");
throw e;
} finally {
transfer.killMover("door found orphaned mover");
_transfers.remove((int) transfer.getId());
}
}
/**
* 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(path.child(entry.getName()),
entry.getFileAttributes()));
}
};
_list.printDirectory(getSubject(), getRestriction(), printer, path, null,
Range.<Integer>all());
return result;
}
public void setDefaultPropfindProperties(PropfindProperties defaultPropfindProperties) {
_includeAllAttributesForPropfind =
defaultPropfindProperties == PropfindProperties.CLIENT_COMPATIBLE;
}
private class FileLocalityWrapper {
private final FileLocality _inner;
FileLocalityWrapper(FileLocality inner) {
_inner = inner;
}
public boolean isOnline() {
return _inner == FileLocality.ONLINE;
}
public boolean isNearline() {
return _inner == FileLocality.NEARLINE;
}
public boolean isOnlineAndNearline() {
return _inner == FileLocality.ONLINE_AND_NEARLINE;
}
public boolean isLost() {
return _inner == FileLocality.LOST;
}
public boolean isUnavailable() {
return _inner == FileLocality.UNAVAILABLE;
}
}
private String getRequestPath() {
Request request = HttpManager.request();
return URI.create(request.getAbsoluteUrl()).getPath();
}
private String getQueryString() {
return ServletRequest.getRequest().getQueryString();
}
private String getRemoteAddr() {
return HttpManager.request().getRemoteAddr();
}
private void addTemplateAttributes(ST template) {
String requestPath = getRequestPath();
String[] base =
Iterables.toArray(PATH_SPLITTER.split(requestPath), String.class);
String relPathOfRoot = Joiner.on("/").join(limit(cycle(".."), base.length));
template.add("path", asList(UrlPathWrapper.forPaths(base)));
template.add("static", _staticContentPath);
template.add("subject", new SubjectWrapper(getSubject()));
template.add("base", UrlPathWrapper.forEmptyPath());
template.add("config", _templateConfig);
template.add("root", relPathOfRoot);
template.add("query", getQueryString());
}
/**
* Deliver a client to the user in response to a GET request on a directory. No effort is made
* to provide the client with the contents of this directory. It is expected that the client
* obtains the information it needs by itself; e.g., by executing JavaScript that is supplied