-
Notifications
You must be signed in to change notification settings - Fork 131
/
ChimeraNameSpaceProvider.java
1945 lines (1755 loc) · 83.1 KB
/
ChimeraNameSpaceProvider.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.chimera.namespace;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.nullToEmpty;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.dcache.acl.enums.AccessType.ACCESS_ALLOWED;
import static org.dcache.chimera.FileSystemProvider.StatCacheOption.NO_STAT;
import static org.dcache.chimera.FileSystemProvider.StatCacheOption.STAT;
import static org.dcache.namespace.FileAttribute.ACCESS_LATENCY;
import static org.dcache.namespace.FileAttribute.CACHECLASS;
import static org.dcache.namespace.FileAttribute.CHECKSUM;
import static org.dcache.namespace.FileAttribute.CREATION_TIME;
import static org.dcache.namespace.FileAttribute.FLAGS;
import static org.dcache.namespace.FileAttribute.HSM;
import static org.dcache.namespace.FileAttribute.LABELS;
import static org.dcache.namespace.FileAttribute.LOCATIONS;
import static org.dcache.namespace.FileAttribute.MODE;
import static org.dcache.namespace.FileAttribute.NLINK;
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.SIMPLE_TYPE;
import static org.dcache.namespace.FileAttribute.SIZE;
import static org.dcache.namespace.FileAttribute.STORAGECLASS;
import static org.dcache.namespace.FileAttribute.STORAGEINFO;
import static org.dcache.namespace.FileAttribute.TYPE;
import static org.dcache.namespace.FileAttribute.XATTR;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import diskCacheV111.namespace.NameSpaceProvider;
import diskCacheV111.util.AccessLatency;
import diskCacheV111.util.AttributeExistsCacheException;
import diskCacheV111.util.CacheException;
import diskCacheV111.util.FileCorruptedCacheException;
import diskCacheV111.util.FileExistsCacheException;
import diskCacheV111.util.FileIsNewCacheException;
import diskCacheV111.util.FileNotFoundCacheException;
import diskCacheV111.util.FsPath;
import diskCacheV111.util.InvalidMessageCacheException;
import diskCacheV111.util.LockedCacheException;
import diskCacheV111.util.NoAttributeCacheException;
import diskCacheV111.util.NotDirCacheException;
import diskCacheV111.util.NotFileCacheException;
import diskCacheV111.util.PermissionDeniedCacheException;
import diskCacheV111.util.PnfsId;
import diskCacheV111.util.RetentionPolicy;
import diskCacheV111.vehicles.StorageInfo;
import dmg.cells.nucleus.CellCommandListener;
import dmg.cells.nucleus.CellInfo;
import dmg.cells.nucleus.CellInfoProvider;
import dmg.util.command.Command;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.security.auth.Subject;
import org.dcache.acl.ACE;
import org.dcache.acl.ACL;
import org.dcache.auth.Subjects;
import org.dcache.chimera.ChimeraDirectoryEntry;
import org.dcache.chimera.ChimeraFsException;
import org.dcache.chimera.DirNotEmptyChimeraFsException;
import org.dcache.chimera.DirectoryStreamB;
import org.dcache.chimera.FileExistsChimeraFsException;
import org.dcache.chimera.FileNotFoundChimeraFsException;
import org.dcache.chimera.FileState;
import org.dcache.chimera.FileSystemProvider;
import org.dcache.chimera.FileSystemProvider.SetXattrMode;
import org.dcache.chimera.FsInode;
import org.dcache.chimera.NoXdataChimeraException;
import org.dcache.chimera.NotDirChimeraException;
import org.dcache.chimera.StorageGenericLocation;
import org.dcache.chimera.StorageLocatable;
import org.dcache.chimera.UnixPermission;
import org.dcache.chimera.posix.Stat;
import org.dcache.commons.stats.MonitoringProxy;
import org.dcache.commons.stats.RequestCounters;
import org.dcache.commons.stats.RequestExecutionTimeGauges;
import org.dcache.namespace.CreateOption;
import org.dcache.namespace.FileAttribute;
import org.dcache.namespace.FileType;
import org.dcache.namespace.ListHandler;
import org.dcache.namespace.PermissionHandler;
import org.dcache.util.Checksum;
import org.dcache.util.ChecksumType;
import org.dcache.util.Exceptions;
import org.dcache.util.Glob;
import org.dcache.vehicles.FileAttributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
public class ChimeraNameSpaceProvider
implements NameSpaceProvider, CellInfoProvider, CellCommandListener {
private static final int SYMLINK_MODE = 0777;
private static final int INHERIT_MODE = -1;
public static final String TAG_EXPECTED_SIZE = "ExpectedSize";
public static final String TAG_PATH = "Path";
public static final String TAG_WRITE_TOKEN = "WriteToken";
public static final String TAG_RETENTION_POLICY = "RetentionPolicy";
public static final String TAG_ACCESS_LATENCY = "AccessLatency";
// Similar to (but not the same as) similarly named constants in
// PnfsCreateEntryMessage.
public static final EnumSet INVALID_CREATE_DIRECTORY_ATTRIBUTES =
EnumSet.of(CACHECLASS, CHECKSUM, CREATION_TIME, FLAGS, HSM,
LOCATIONS, NLINK, PNFSID, RETENTION_POLICY, SIMPLE_TYPE,
SIZE, STORAGECLASS, STORAGEINFO, TYPE);
public static final EnumSet INVALID_CREATE_FILE_ATTRIBUTES =
EnumSet.of(CACHECLASS, CREATION_TIME, NLINK, PNFSID, STORAGECLASS,
STORAGEINFO, SIMPLE_TYPE, TYPE);
public static final EnumSet INVALID_CREATE_SYM_LINK_ATTRIBUTES =
EnumSet.of(ACCESS_LATENCY, CACHECLASS, CHECKSUM, CREATION_TIME,
FLAGS, HSM, LOCATIONS, NLINK, PNFSID, RETENTION_POLICY,
SIZE, STORAGECLASS, STORAGEINFO, SIMPLE_TYPE, TYPE);
private FileSystemProvider _fs;
private ChimeraStorageInfoExtractable _extractor;
private static final Logger LOGGER = LoggerFactory.getLogger(ChimeraNameSpaceProvider.class);
private boolean _inheritFileOwnership;
private boolean _verifyAllLookups;
private boolean _aclEnabled;
private boolean _allowMoveToDirectoryWithDifferentStorageClass;
private PermissionHandler _permissionHandler;
private String _uploadDirectory;
private String _uploadSubDirectory;
private final ThreadLocal<Integer> threadId = new ThreadLocal<Integer>() {
private final AtomicInteger counter = new AtomicInteger();
@Override
protected Integer initialValue() {
return counter.getAndIncrement();
}
};
private final RequestCounters<Method> _counters =
new RequestCounters<>(ChimeraNameSpaceProvider.class.getSimpleName());
private final RequestExecutionTimeGauges<Method> _gauges =
new RequestExecutionTimeGauges<>(ChimeraNameSpaceProvider.class.getSimpleName());
@Required
public void setExtractor(ChimeraStorageInfoExtractable extractor) {
_extractor = extractor;
}
@Required
public void setInheritFileOwnership(boolean inherit) {
_inheritFileOwnership = inherit;
}
@Required
public void setVerifyAllLookups(boolean verify) {
_verifyAllLookups = verify;
}
@Required
public void setAllowMoveToDirectoryWithDifferentStorageClass(boolean allow) {
_allowMoveToDirectoryWithDifferentStorageClass = allow;
}
@Required
public void setPermissionHandler(PermissionHandler handler) {
_permissionHandler = handler;
}
@Required
public void setFileSystem(FileSystemProvider fs) {
_fs = MonitoringProxy.decorateWithMonitoringProxy(new Class[]{FileSystemProvider.class}, fs,
_counters,
_gauges);
}
@Required
public void setAclEnabled(boolean isEnabled) {
_aclEnabled = isEnabled;
}
/**
* Base directory for temporary upload directories. If not an absolute path, the directory is
* relative to the user's root directory.
*/
public void setUploadDirectory(String path) {
_uploadDirectory = path;
}
/**
* Sub directory in the upload directory in which to create temporary upload directories.
* <p>
* May be parametrised by a thread id by inserting %d into the string. This allows Chimera lock
* contention on the base directory to be reduced. If used it is important that the same set
* threads call into the provider repeatedly as otherwise a large number of base directories
* will be created.
*/
public void setUploadSubDirectory(String path) {
_uploadSubDirectory = path;
}
private void checkLookupPermissions(Subject subject, List<FsInode> inodes, String path)
throws ChimeraFsException, CacheException {
for (FsInode inode : inodes) {
if (inode.isDirectory()) {
FileAttributes attributes = getFileAttributesForPermissionHandler(inode);
if (_permissionHandler.canLookup(subject, attributes) != ACCESS_ALLOWED) {
throw new PermissionDeniedCacheException("Access denied: " + path);
}
}
}
}
private List<FsInode> findDeepestParent(String path) throws ChimeraFsException {
FsPath target = FsPath.create(path);
do {
target = target.parent();
try {
return _fs.path2inodes(target.toString());
} catch (FileNotFoundChimeraFsException ignored) {
// Continue onto next parent.
}
} while (target != FsPath.ROOT);
throw new RuntimeException("Unable to find inode for ROOT");
}
private ExtendedInode pathToInode(Subject subject, String path)
throws ChimeraFsException, CacheException {
if (Subjects.isExemptFromNamespaceChecks(subject)) {
return new ExtendedInode(_fs, _fs.path2inode(path));
}
List<FsInode> inodes;
try {
inodes = _fs.path2inodes(path);
} catch (FileNotFoundChimeraFsException e) {
// Do not leak whether a file exists if user cannot 'cd' into the parent directory.
inodes = findDeepestParent(path);
checkLookupPermissions(subject, inodes, path);
throw e;
}
if (_verifyAllLookups) {
checkLookupPermissions(subject, inodes.subList(0, inodes.size() - 1), path);
} else {
for (FsInode inode : Iterables.skip(Lists.reverse(inodes), 1)) {
if (inode.isDirectory()) {
FileAttributes attributes =
getFileAttributesForPermissionHandler(inode);
if (_permissionHandler.canLookup(subject, attributes) != ACCESS_ALLOWED) {
throw new PermissionDeniedCacheException("Access denied: " + path);
}
/* dCache only checks the lookup permissions of
* the last directory of a path.
*/
break;
}
}
}
return new ExtendedInode(_fs, inodes.get(inodes.size() - 1));
}
private int defaultUid(Subject subject, ExtendedInode parent)
throws UncheckedIOException {
try {
if (Subjects.isNobody(subject) || _inheritFileOwnership) {
return parent.statCache().getUid();
} else {
return (int) Subjects.getUid(subject);
}
} catch (ChimeraFsException e) {
throw new UncheckedIOException(e);
}
}
private int defaultGid(Subject subject, ExtendedInode parent)
throws UncheckedIOException {
try {
if (Subjects.isNobody(subject) || _inheritFileOwnership) {
return parent.statCache().getGid();
} else {
return (int) Subjects.getPrimaryGid(subject);
}
} catch (ChimeraFsException e) {
throw new UncheckedIOException(e);
}
}
@Override
public FileAttributes createFile(Subject subject, String path,
FileAttributes assignAttributes, Set<FileAttribute> requestedAttributes)
throws CacheException {
checkArgument(assignAttributes.isUndefined(INVALID_CREATE_FILE_ATTRIBUTES),
"Illegal assign attributes: %s", assignAttributes.getDefinedAttributes());
File newEntryFile = new File(path);
String parentPath = newEntryFile.getParent();
try {
if (parentPath == null) {
throw new FileExistsCacheException("File exists: " + path);
}
ExtendedInode parent = pathToInode(subject, parentPath);
if (!Subjects.isExemptFromNamespaceChecks(subject)) {
FileAttributes attributes
= getFileAttributesForPermissionHandler(parent);
if (_permissionHandler.canCreateFile(subject, attributes) != ACCESS_ALLOWED) {
throw new PermissionDeniedCacheException("Access denied: " + path);
}
}
ExtendedInode inode;
try {
int uid = assignAttributes.getOwnerIfPresent()
.orElseGet(() -> defaultUid(subject, parent));
int gid = assignAttributes.getGroupIfPresent()
.orElseGet(() -> defaultGid(subject, parent));
int mode = assignAttributes.getModeIfPresent()
.orElse(parent.statCache().getMode() & UMASK_FILE);
assignAttributes.undefine(OWNER, OWNER_GROUP, MODE);
inode = parent.create(newEntryFile.getName(), uid, gid, mode);
} catch (UncheckedIOException e) {
throw e.getCause();
}
FileAttributes fileAttributes;
if (assignAttributes.getDefinedAttributes().isEmpty()) {
fileAttributes = getFileAttributes(inode, requestedAttributes);
} else {
fileAttributes = setFileAttributes(subject, inode.getPnfsId(),
assignAttributes, requestedAttributes);
}
if (parent.getTags().containsKey(TAG_EXPECTED_SIZE)) {
ImmutableList<String> size = parent.getTag(TAG_EXPECTED_SIZE);
if (!size.isEmpty()) {
fileAttributes.setSize(Long.parseLong(size.get(0)));
}
}
return fileAttributes;
} catch (NotDirChimeraException e) {
throw new NotDirCacheException("Not a directory: " + parentPath);
} catch (FileNotFoundChimeraFsException e) {
throw new FileNotFoundCacheException("No such directory: " + parentPath);
} catch (FileExistsChimeraFsException e) {
throw new FileExistsCacheException("File exists: " + path);
} catch (IOException e) {
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
e.getMessage());
}
}
@Override
public PnfsId createDirectory(Subject subject, String path, FileAttributes attributes)
throws CacheException {
checkArgument(attributes.isUndefined(INVALID_CREATE_DIRECTORY_ATTRIBUTES),
"Illegal assign attributes: %s", attributes.getDefinedAttributes());
try {
File newEntryFile = new File(path);
String parentPath = newEntryFile.getParent();
if (parentPath == null) {
throw new FileExistsCacheException("File exists: " + path);
}
ExtendedInode parent = pathToInode(subject, parentPath);
ExtendedInode inode;
try {
int uid = attributes.getOwnerIfPresent()
.orElseGet(() -> defaultUid(subject, parent));
int gid = attributes.getGroupIfPresent()
.orElseGet(() -> defaultGid(subject, parent));
int mode = attributes.getModeIfPresent()
.orElse(parent.statCache().getMode() & UMASK_DIR);
attributes.undefine(OWNER, OWNER_GROUP, MODE);
inode = mkdir(subject, parent, newEntryFile.getName(), uid, gid,
mode);
} catch (UncheckedIOException e) {
throw e.getCause();
}
if (!attributes.getDefinedAttributes().isEmpty()) {
setFileAttributes(subject, inode.getPnfsId(), attributes,
EnumSet.noneOf(FileAttribute.class));
}
return inode.getPnfsId();
} catch (NotDirChimeraException e) {
throw new NotDirCacheException("Not a directory: " + path);
} catch (FileNotFoundChimeraFsException e) {
throw new FileNotFoundCacheException("No such file or directory: " + path);
} catch (FileExistsChimeraFsException e) {
throw new FileExistsCacheException("File exists: " + path);
} catch (IOException e) {
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
e.getMessage());
}
}
@Override
public PnfsId createSymLink(Subject subject, String path, String dest,
FileAttributes assignAttributes)
throws CacheException {
checkArgument(assignAttributes.isUndefined(INVALID_CREATE_SYM_LINK_ATTRIBUTES),
"Illegal assign attributes: %s", assignAttributes.getDefinedAttributes());
try {
File newEntryFile = new File(path);
String parentPath = newEntryFile.getParent();
if (parentPath == null) {
throw new FileExistsCacheException("File exists: " + path);
}
ExtendedInode parent = pathToInode(subject, parentPath);
if (!Subjects.isExemptFromNamespaceChecks(subject)) {
FileAttributes attributes
= getFileAttributesForPermissionHandler(parent);
if (_permissionHandler.canCreateFile(subject, attributes) != ACCESS_ALLOWED) {
throw new PermissionDeniedCacheException("Access denied: " + path);
}
}
FsInode inode;
try {
int uid = assignAttributes.getOwnerIfPresent()
.orElseGet(() -> defaultUid(subject, parent));
int gid = assignAttributes.getGroupIfPresent()
.orElseGet(() -> defaultGid(subject, parent));
int mode = assignAttributes.getModeIfPresent().orElse(SYMLINK_MODE);
assignAttributes.undefine(OWNER, OWNER_GROUP, MODE);
inode = _fs.createLink(parent, newEntryFile.getName(), uid, gid,
mode, dest.getBytes(UTF_8));
} catch (UncheckedIOException e) {
throw e.getCause();
}
PnfsId pnfsid = new PnfsId(inode.getId());
if (!assignAttributes.getDefinedAttributes().isEmpty()) {
setFileAttributes(subject, pnfsid, assignAttributes,
EnumSet.noneOf(FileAttribute.class));
}
return pnfsid;
} catch (NotDirChimeraException e) {
throw new NotDirCacheException("Not a directory: " + path);
} catch (FileNotFoundChimeraFsException e) {
throw new FileNotFoundCacheException("No such file or directory: " + path);
} catch (FileExistsChimeraFsException e) {
throw new FileExistsCacheException("File exists: " + path);
} catch (IOException e) {
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
e.getMessage());
}
}
private void checkAllowed(Set<FileType> allowed,
ExtendedInode inode)
throws ChimeraFsException, NotDirCacheException, NotFileCacheException {
FileType type = inode.getFileType();
if (!allowed.contains(type)) {
StringBuilder sb = new StringBuilder("Path exists and has type ")
.append(type).append(", which is not ");
if (allowed.size() == 1) {
FileType allowedType = allowed.iterator().next();
sb.append(allowedType);
} else {
String description = allowed.stream()
.map(FileType::toString)
.collect(Collectors.joining(", ", "{", "}"));
sb.append("one of ").append(description);
}
if (allowed.contains(FileType.DIR)) {
throw new NotDirCacheException(sb.toString());
} else {
throw new NotFileCacheException(sb.toString());
}
}
}
private boolean canDelete(Subject subject, ExtendedInode parent, ExtendedInode inode)
throws ChimeraFsException, CacheException {
FileAttributes parentAttributes = getFileAttributesForPermissionHandler(parent);
FileAttributes fileAttributes = getFileAttributesForPermissionHandler(inode);
if (inode.isDirectory()) {
if (_permissionHandler.canDeleteDir(subject,
parentAttributes,
fileAttributes) != ACCESS_ALLOWED) {
return false;
}
} else {
if (_permissionHandler.canDeleteFile(subject,
parentAttributes,
fileAttributes) != ACCESS_ALLOWED) {
return false;
}
}
return true;
}
@Override
public FileAttributes deleteEntry(Subject subject, Set<FileType> allowed, PnfsId pnfsId,
Set<FileAttribute> attr) throws CacheException {
try {
ExtendedInode inode = new ExtendedInode(_fs, pnfsId, STAT);
checkAllowed(allowed, inode);
if (!Subjects.isExemptFromNamespaceChecks(subject) && !canDelete(subject,
inode.getParent(), inode)) {
throw new PermissionDeniedCacheException("Access denied: " + pnfsId);
}
_fs.remove(inode);
return getFileAttributes(inode, attr);
} catch (FileNotFoundChimeraFsException fnf) {
throw new FileNotFoundCacheException("No such file or directory: " + pnfsId);
} catch (DirNotEmptyChimeraFsException e) {
throw new CacheException("Directory is not empty: " + pnfsId);
} catch (IOException e) {
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
e.getMessage());
}
}
@Override
public FileAttributes deleteEntry(Subject subject, Set<FileType> allowed,
String path, Set<FileAttribute> attr) throws CacheException {
try {
File filePath = new File(path);
String parentPath = filePath.getParent();
if (parentPath == null) {
throw new CacheException("Cannot delete file system root.");
}
ExtendedInode parent = pathToInode(subject, parentPath);
String name = filePath.getName();
ExtendedInode inode = parent.inodeOf(name, STAT);
checkAllowed(allowed, inode);
if (!Subjects.isExemptFromNamespaceChecks(subject) && !canDelete(subject, parent,
inode)) {
throw new PermissionDeniedCacheException("Access denied: " + path);
}
_fs.remove(parent, name, inode);
return getFileAttributes(inode, attr);
} catch (FileNotFoundChimeraFsException fnf) {
throw new FileNotFoundCacheException("No such file or directory: " + path);
} catch (DirNotEmptyChimeraFsException e) {
throw new CacheException("Directory is not empty: " + path);
} catch (IOException e) {
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
e.getMessage());
}
}
@Override
public FileAttributes deleteEntry(Subject subject, Set<FileType> allowed,
PnfsId pnfsId, String path, Set<FileAttribute> attr) throws CacheException {
try {
File filePath = new File(path);
String parentPath = filePath.getParent();
if (parentPath == null) {
throw new CacheException("Cannot delete file system root.");
}
ExtendedInode parent = pathToInode(subject, parentPath);
String name = filePath.getName();
ExtendedInode inode = parent.inodeOf(name, STAT);
if (!inode.getPnfsId().equals(pnfsId)) {
throw new FileNotFoundCacheException(
"PNFSID does not correspond to provided file.");
}
checkAllowed(allowed, inode);
if (!Subjects.isExemptFromNamespaceChecks(subject) && !canDelete(subject, parent,
inode)) {
throw new PermissionDeniedCacheException("Access denied: " + path);
}
_fs.remove(parent, name, inode);
return getFileAttributes(inode, attr);
} catch (FileNotFoundChimeraFsException fnf) {
throw new FileNotFoundCacheException("No such file or directory: " + path);
} catch (DirNotEmptyChimeraFsException e) {
throw new CacheException("Directory is not empty: " + path);
} catch (IOException e) {
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION, e.getMessage());
}
}
@Override
public void rename(Subject subject, @Nullable PnfsId pnfsId,
String sourcePath, String destinationPath, boolean overwrite)
throws CacheException {
try {
/* Resolve the source directory.
*/
File source = new File(sourcePath);
ExtendedInode sourceDir = pathToInode(subject, source.getParent());
Set<FileAttribute> attributes = EnumSet.noneOf(FileAttribute.class);
attributes.addAll(_permissionHandler.getRequiredAttributes());
if (!_allowMoveToDirectoryWithDifferentStorageClass) {
attributes.add(FileAttribute.STORAGECLASS);
attributes.add(FileAttribute.CACHECLASS);
}
FileAttributes sourceDirAttributes = getFileAttributes(sourceDir, attributes);
ExtendedInode inode;
if (pnfsId != null) {
inode = new ExtendedInode(_fs, pnfsId, STAT);
} else {
if (!Subjects.isExemptFromNamespaceChecks(subject) &&
_permissionHandler.canLookup(subject, sourceDirAttributes)
!= ACCESS_ALLOWED) {
throw new PermissionDeniedCacheException("Access denied: " + sourcePath);
}
inode = sourceDir.inodeOf(source.getName(), STAT);
}
/* Resolve the target directory.
*/
File dest = new File(destinationPath);
ExtendedInode destDir;
FileAttributes destDirAttributes;
try {
if (dest.getParent().equals(source.getParent())) {
destDir = sourceDir;
destDirAttributes = sourceDirAttributes;
} else {
destDir = pathToInode(subject, dest.getParent());
destDirAttributes = getFileAttributes(destDir, attributes);
if (!_allowMoveToDirectoryWithDifferentStorageClass) {
FileAttributes sourceAttributes = sourceDirAttributes;
if (inode.isDirectory()) {
sourceAttributes =
getFileAttributes(new ExtendedInode(_fs, inode), attributes);
}
if (!(nullToEmpty(destDirAttributes.getStorageClass()).
equals(nullToEmpty(sourceAttributes.getStorageClass())) &&
nullToEmpty(destDirAttributes.getCacheClass()).
equals(nullToEmpty(sourceAttributes.getCacheClass())))) {
throw new PermissionDeniedCacheException("Mv denied: " +
dest.getParent() +
" has different storage tags; use cp.");
}
}
}
} catch (FileNotFoundChimeraFsException e) {
throw new NotDirCacheException("No such directory: " +
dest.getParent());
}
/* Permission checks.
*/
if (!Subjects.isExemptFromNamespaceChecks(subject) || !overwrite) {
if (!Subjects.isExemptFromNamespaceChecks(subject) &&
_permissionHandler.canRename(subject,
sourceDirAttributes,
destDirAttributes,
inode.isDirectory()) != ACCESS_ALLOWED) {
throw new PermissionDeniedCacheException("Access denied: " + pnfsId);
}
try {
ExtendedInode destInode = destDir.inodeOf(dest.getName(), STAT);
if (!overwrite) {
throw new FileExistsCacheException("File exists:" + destinationPath);
}
/* Destination name exists and we were requested to
* overwrite it. Thus the subject must have delete
* permission for the destination name.
*/
FileAttributes destAttributes =
getFileAttributesForPermissionHandler(destInode);
if (destInode.isDirectory()) {
if (_permissionHandler.canDeleteDir(subject,
destDirAttributes,
destAttributes) != ACCESS_ALLOWED) {
throw new PermissionDeniedCacheException(
"Access denied: " + destinationPath);
}
} else {
if (_permissionHandler.canDeleteFile(subject,
destDirAttributes,
destAttributes) != ACCESS_ALLOWED) {
throw new PermissionDeniedCacheException(
"Access denied: " + destinationPath);
}
}
} catch (FileNotFoundChimeraFsException e) {
/* Destination doesn't exist and we can move the file;
* unfortunately there is no way to test this with
* Chimera without throwing an exception.
*/
}
}
_fs.rename(inode, sourceDir, source.getName(), destDir, dest.getName());
} catch (FileNotFoundChimeraFsException e) {
throw new FileNotFoundCacheException("No such file or directory: "
+ pnfsId);
} catch (FileExistsChimeraFsException e) {
/* With the current implementation of Chimera, I don't
* expect this to be thrown. Instead Chimera insists on
* overwriting the destination file.
*/
throw new FileExistsCacheException("File exists:" + destinationPath);
} catch (IOException e) {
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
e.getMessage());
}
}
@Override
public void addCacheLocation(Subject subject, PnfsId pnfsId, String cacheLocation)
throws CacheException {
LOGGER.debug("add cache location {} for {}", cacheLocation, pnfsId);
try {
ExtendedInode inode = new ExtendedInode(_fs, pnfsId, NO_STAT);
_fs.addInodeLocation(inode, StorageGenericLocation.DISK, cacheLocation);
} catch (FileNotFoundChimeraFsException e) {
throw new FileNotFoundCacheException("No such file: " + pnfsId);
} catch (ChimeraFsException e) {
LOGGER.error("Exception in addCacheLocation {}", e.getMessage());
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION, e.getMessage());
}
}
@Override
public List<String> getCacheLocation(Subject subject, PnfsId pnfsId) throws CacheException {
try {
List<String> locations = new ArrayList<>();
ExtendedInode inode = new ExtendedInode(_fs, pnfsId, NO_STAT);
List<StorageLocatable> localyManagerLocations = _fs.getInodeLocations(inode,
StorageGenericLocation.DISK);
for (StorageLocatable location : localyManagerLocations) {
locations.add(location.location());
}
return locations;
} catch (FileNotFoundChimeraFsException e) {
throw new FileNotFoundCacheException("No such file or directory: " + pnfsId, e);
} catch (ChimeraFsException e) {
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION, e.getMessage());
}
}
@Override
public void clearCacheLocation(Subject subject, PnfsId pnfsId, String cacheLocation,
boolean removeIfLast) throws CacheException {
LOGGER.debug("clearCacheLocation : {} for {}", cacheLocation, pnfsId);
try {
ExtendedInode inode = new ExtendedInode(_fs, pnfsId, NO_STAT);
_fs.clearInodeLocation(inode, StorageGenericLocation.DISK, cacheLocation);
if (removeIfLast) {
List<StorageLocatable> locations = _fs.getInodeLocations(inode,
StorageGenericLocation.DISK);
if (locations.isEmpty()) {
LOGGER.debug("last location cleaned. removing file {}", inode);
_fs.remove(inode);
}
}
} catch (FileNotFoundChimeraFsException e) {
throw new FileNotFoundCacheException("No such file or directory: " + pnfsId, e);
} catch (ChimeraFsException e) {
LOGGER.error("Exception in clearCacheLocation for {} : {}", pnfsId, e);
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION, e.getMessage());
}
}
@Override
public String pnfsidToPath(Subject subject, PnfsId pnfsId) throws CacheException {
try {
ExtendedInode inode = new ExtendedInode(_fs, pnfsId, STAT);
if (!inode.exists()) {
throw new FileNotFoundCacheException("No such file or directory: " + pnfsId);
}
return _fs.inode2path(inode);
} catch (ChimeraFsException e) {
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION, e.getMessage());
}
}
@Override
public PnfsId pathToPnfsid(Subject subject, String path, boolean followLink)
throws CacheException {
try {
return pathToInode(subject, path).getPnfsId();
} catch (FileNotFoundChimeraFsException e) {
throw new FileNotFoundCacheException("No such file or directory " + path);
} catch (IOException e) {
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION, e.getMessage());
}
}
@Override
public void removeFileAttribute(Subject subject, PnfsId pnfsId, String attribute)
throws CacheException {
try {
ExtendedInode inode = new ExtendedInode(_fs, pnfsId, NO_STAT).getLevel(2);
ChimeraCacheInfo info = new ChimeraCacheInfo(inode);
ChimeraCacheInfo.CacheFlags flags = info.getFlags();
flags.remove(attribute);
info.writeCacheInfo(inode);
} catch (FileNotFoundChimeraFsException e) {
throw new FileNotFoundCacheException("No such file or directory " + pnfsId);
} catch (IOException e) {
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
e.getMessage());
}
}
@Override
public void removeChecksum(Subject subject, PnfsId pnfsId, ChecksumType type)
throws CacheException {
try {
_fs.removeInodeChecksum(new ExtendedInode(_fs, pnfsId, NO_STAT), type.getType());
} catch (FileNotFoundChimeraFsException e) {
throw new FileNotFoundCacheException("No such file or directory: " + pnfsId);
} catch (ChimeraFsException e) {
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION,
e.getMessage());
}
}
@Override
public CellInfo getCellInfo(CellInfo info) {
return info;
}
@Override
public void getInfo(PrintWriter pw) {
pw.append("Acl Enabled: ").println(_aclEnabled);
pw.append(_fs.getInfo());
pw.println("Statistics:");
pw.println(_gauges);
pw.println(_counters);
}
@Command(name = "reset chimera stats", hint="reset chimera statistics", description = "Reset"
+ " the counters and gauge statistics describing the interaction with Chimera.")
public class ResetStatsCommand implements Callable<String> {
@Override
public String call() {
_gauges.reset();
_counters.reset();
return "";
}
}
@Override
public Collection<Link> find(Subject subject, PnfsId pnfsId) throws CacheException {
try {
ExtendedInode target = new ExtendedInode(_fs, pnfsId, NO_STAT);
Collection<Link> locations = _fs.find(target).stream()
.flatMap(l -> {
try {
ExtendedInode parent = new ExtendedInode(_fs, l.getParent());
PnfsId parentId = parent.getPnfsId();
return Stream.of(new Link(parentId, l.getName()));
} catch (ChimeraFsException e) {
LOGGER.error("Failed to find PnfsId of parent {}: {}",
l.getParent(), e.toString());
return Stream.of();
}
})
.collect(Collectors.toList());
if (locations.isEmpty()) {
throw new FileNotFoundCacheException("No such file or directory: " + pnfsId);
}
return locations;
} catch (FileNotFoundChimeraFsException e) {
throw new FileNotFoundCacheException("No such file or directory: " + pnfsId);
} catch (IOException e) {
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION, e.getMessage());
}
}
private FileAttributes getFileAttributesForPermissionHandler(@Nullable FsInode inode)
throws ChimeraFsException, CacheException {
return (inode == null)
? null
: getFileAttributesForPermissionHandler(new ExtendedInode(_fs, inode));
}
private FileAttributes getFileAttributesForPermissionHandler(@Nonnull ExtendedInode inode)
throws ChimeraFsException, CacheException {
return getFileAttributes(inode, _permissionHandler.getRequiredAttributes());
}
private FileAttributes getFileAttributes(ExtendedInode inode, Set<FileAttribute> attr)
throws ChimeraFsException, CacheException {
if (!inode.exists()) {
throw FileNotFoundChimeraFsException.of(inode);
}
FileAttributes attributes = new FileAttributes();
Stat stat;
for (FileAttribute attribute : attr) {
switch (attribute) {
case ACL:
if (_aclEnabled) {
attributes.setAcl(inode.getAcl());
} else {
attributes.setAcl(null);
}
break;
case ACCESS_LATENCY:
AccessLatency accessLatency = _extractor.getAccessLatency(inode);
if (accessLatency != null) {
attributes.setAccessLatency(accessLatency);
}
break;
case ACCESS_TIME:
stat = inode.statCache();
attributes.setAccessTime(stat.getATime());
break;
case RETENTION_POLICY:
RetentionPolicy retentionPolicy = _extractor.getRetentionPolicy(inode);
if (retentionPolicy != null) {
attributes.setRetentionPolicy(retentionPolicy);
}
break;
case SIZE:
stat = inode.statCache();
// REVISIT when we have another way to detect new files
ExtendedInode level2 = inode.getLevel(2);
boolean isNew = (stat.getSize() == 0) &&
!level2.exists() &&
inode.getLocations().isEmpty();
if (!isNew) {
attributes.setSize(stat.getSize());
}
break;
case CHANGE_TIME:
stat = inode.statCache();
attributes.setChangeTime(stat.getCTime());
break;
case CREATION_TIME:
stat = inode.statCache();
attributes.setCreationTime(stat.getCrTime());
break;
case MODIFICATION_TIME:
stat = inode.statCache();
attributes.setModificationTime(stat.getMTime());
break;