-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
DefaultFileSystemMaster.java
2761 lines (2582 loc) · 120 KB
/
DefaultFileSystemMaster.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
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.master.file;
import alluxio.AlluxioURI;
import alluxio.Configuration;
import alluxio.Constants;
import alluxio.PropertyKey;
import alluxio.clock.SystemClock;
import alluxio.collections.Pair;
import alluxio.collections.PrefixList;
import alluxio.exception.AccessControlException;
import alluxio.exception.AlluxioException;
import alluxio.exception.BlockInfoException;
import alluxio.exception.DirectoryNotEmptyException;
import alluxio.exception.ExceptionMessage;
import alluxio.exception.FileAlreadyCompletedException;
import alluxio.exception.FileAlreadyExistsException;
import alluxio.exception.FileDoesNotExistException;
import alluxio.exception.InvalidFileSizeException;
import alluxio.exception.InvalidPathException;
import alluxio.exception.PreconditionMessage;
import alluxio.exception.UnexpectedAlluxioException;
import alluxio.heartbeat.HeartbeatContext;
import alluxio.heartbeat.HeartbeatThread;
import alluxio.master.AbstractMaster;
import alluxio.master.MasterRegistry;
import alluxio.master.ProtobufUtils;
import alluxio.master.block.BlockId;
import alluxio.master.block.BlockMaster;
import alluxio.master.file.async.AsyncPersistHandler;
import alluxio.master.file.meta.FileSystemMasterView;
import alluxio.master.file.meta.Inode;
import alluxio.master.file.meta.InodeDirectory;
import alluxio.master.file.meta.InodeDirectoryIdGenerator;
import alluxio.master.file.meta.InodeFile;
import alluxio.master.file.meta.InodeLockList;
import alluxio.master.file.meta.InodePathPair;
import alluxio.master.file.meta.InodeTree;
import alluxio.master.file.meta.LockedInodePath;
import alluxio.master.file.meta.MountTable;
import alluxio.master.file.meta.PersistenceState;
import alluxio.master.file.meta.TempInodePathForChild;
import alluxio.master.file.meta.TempInodePathForDescendant;
import alluxio.master.file.meta.TtlBucketList;
import alluxio.master.file.meta.options.MountInfo;
import alluxio.master.file.options.CheckConsistencyOptions;
import alluxio.master.file.options.CompleteFileOptions;
import alluxio.master.file.options.CreateDirectoryOptions;
import alluxio.master.file.options.CreateFileOptions;
import alluxio.master.file.options.DeleteOptions;
import alluxio.master.file.options.FreeOptions;
import alluxio.master.file.options.ListStatusOptions;
import alluxio.master.file.options.LoadMetadataOptions;
import alluxio.master.file.options.MountOptions;
import alluxio.master.file.options.RenameOptions;
import alluxio.master.file.options.SetAttributeOptions;
import alluxio.master.journal.JournalFactory;
import alluxio.metrics.MetricsSystem;
import alluxio.proto.journal.File.AddMountPointEntry;
import alluxio.proto.journal.File.AsyncPersistRequestEntry;
import alluxio.proto.journal.File.CompleteFileEntry;
import alluxio.proto.journal.File.DeleteFileEntry;
import alluxio.proto.journal.File.DeleteMountPointEntry;
import alluxio.proto.journal.File.InodeDirectoryEntry;
import alluxio.proto.journal.File.InodeFileEntry;
import alluxio.proto.journal.File.InodeLastModificationTimeEntry;
import alluxio.proto.journal.File.PersistDirectoryEntry;
import alluxio.proto.journal.File.ReinitializeFileEntry;
import alluxio.proto.journal.File.RenameEntry;
import alluxio.proto.journal.File.SetAttributeEntry;
import alluxio.proto.journal.File.StringPairEntry;
import alluxio.proto.journal.Journal.JournalEntry;
import alluxio.security.authorization.Mode;
import alluxio.thrift.CommandType;
import alluxio.thrift.FileSystemCommand;
import alluxio.thrift.FileSystemCommandOptions;
import alluxio.thrift.FileSystemMasterClientService;
import alluxio.thrift.FileSystemMasterWorkerService;
import alluxio.thrift.PersistCommandOptions;
import alluxio.thrift.PersistFile;
import alluxio.underfs.UnderFileStatus;
import alluxio.underfs.UnderFileSystem;
import alluxio.underfs.options.FileLocationOptions;
import alluxio.underfs.options.MkdirsOptions;
import alluxio.util.CommonUtils;
import alluxio.util.IdUtils;
import alluxio.util.SecurityUtils;
import alluxio.util.UnderFileSystemUtils;
import alluxio.util.executor.ExecutorServiceFactories;
import alluxio.util.executor.ExecutorServiceFactory;
import alluxio.util.io.PathUtils;
import alluxio.wire.BlockInfo;
import alluxio.wire.BlockLocation;
import alluxio.wire.FileBlockInfo;
import alluxio.wire.FileInfo;
import alluxio.wire.LoadMetadataType;
import alluxio.wire.TtlAction;
import alluxio.wire.WorkerInfo;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.thrift.TProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import javax.annotation.concurrent.NotThreadSafe;
/**
* The master that handles all file system metadata management.
*/
@NotThreadSafe // TODO(jiri): make thread-safe (c.f. ALLUXIO-1664)
public final class DefaultFileSystemMaster extends AbstractMaster implements FileSystemMaster {
private static final Logger LOG = LoggerFactory.getLogger(DefaultFileSystemMaster.class);
private static final Set<Class<?>> DEPS = ImmutableSet.<Class<?>>of(BlockMaster.class);
/**
* Locking in DefaultFileSystemMaster
*
* Individual paths are locked in the inode tree. In order to read or write any inode, the path
* must be locked. A path is locked via one of the lock methods in {@link InodeTree}, such as
* {@link InodeTree#lockInodePath(AlluxioURI, InodeTree.LockMode)} or
* {@link InodeTree#lockFullInodePath(AlluxioURI, InodeTree.LockMode)}. These lock methods return
* an {@link LockedInodePath}, which represents a locked path of inodes. These locked paths
* ({@link LockedInodePath}) must be unlocked. In order to ensure a locked
* {@link LockedInodePath} is always unlocked, the following paradigm is recommended:
*
* <p><blockquote><pre>
* try (LockedInodePath inodePath = mInodeTree.lockInodePath(path, InodeTree.LockMode.READ)) {
* ...
* }
* </pre></blockquote>
*
* When locking a path in the inode tree, it is possible that other concurrent operations have
* modified the inode tree while a thread is waiting to acquire a lock on the inode. Lock
* acquisitions throw {@link InvalidPathException} to indicate that the inode structure is no
* longer consistent with what the caller original expected, for example if the inode
* previously obtained at /pathA has been renamed to /pathB during the wait for the inode lock.
* Methods which specifically act on a path will propagate this exception to the caller, while
* methods which iterate over child nodes can safely ignore the exception and treat the inode
* as no longer a child.
*
* Journaling in the FileSystemMaster
*
* Any changes to file system metadata that need to survive system restarts and / or failures
* should be journaled. The intent to journal and the actual writing of the journal is decoupled
* so that operations are not holding metadata locks waiting on the journal IO. In particular,
* file system operations are expected to create a {@link JournalContext} resource, use it
* throughout the lifetime of an operation to collect journal events through
* {@link #appendJournalEntry(JournalEntry, JournalContext)}, and then close the resource, which
* will persist the journal events. In order to ensure the journal events are always persisted,
* the following paradigm is recommended:
*
* <p><blockquote><pre>
* try (JournalContext journalContext = createJournalContext()) {
* ...
* }
* </pre></blockquote>
*
* NOTE: Because resources are released in the opposite order they are acquired, the
* {@link JournalContext} resources should be always created before any {@link LockedInodePath}
* resources to avoid holding an inode path lock while waiting for journal IO.
*
* Method Conventions in the FileSystemMaster
*
* All of the flow of the FileSystemMaster follow a convention. There are essentially 4 main
* types of methods:
* (A) public api methods
* (B) private (or package private) methods that journal
* (C) private (or package private) internal methods
* (D) private FromEntry methods used to replay entries from the journal
*
* (A) public api methods:
* These methods are public and are accessed by the RPC and REST APIs. These methods lock all
* the required paths, and also perform all permission checking.
* (A) cannot call (A)
* (A) can call (B)
* (A) can call (C)
* (A) cannot call (D)
*
* (B) private (or package private) methods that journal:
* These methods perform the work from the public apis, and also asynchronously write to the
* journal (for write operations). The names of these methods are suffixed with "AndJournal".
* (B) cannot call (A)
* (B) can call (B)
* (B) can call (C)
* (B) cannot call (D)
*
* (C) private (or package private) internal methods:
* These methods perform the rest of the work, and do not do any journaling. The names of these
* methods are suffixed by "Internal".
* (C) cannot call (A)
* (C) cannot call (B)
* (C) can call (C)
* (C) cannot call (D)
*
* (D) private FromEntry methods used to replay entries from the journal:
* These methods are used to replay entries from reading the journal. This is done on start, as
* well as for secondary masters.
* (D) cannot call (A)
* (D) cannot call (B)
* (D) can call (C)
* (D) cannot call (D)
*/
/** Handle to the block master. */
private final BlockMaster mBlockMaster;
/** This manages the file system inode structure. This must be journaled. */
private final InodeTree mInodeTree;
/** This manages the file system mount points. */
private final MountTable mMountTable;
/** This maintains inodes with ttl set, for the for the ttl checker service to use. */
private final TtlBucketList mTtlBuckets = new TtlBucketList();
/** This generates unique directory ids. This must be journaled. */
private final InodeDirectoryIdGenerator mDirectoryIdGenerator;
/** This checks user permissions on different operations. */
private final PermissionChecker mPermissionChecker;
/** List of paths to always keep in memory. */
private final PrefixList mWhitelist;
/** The handler for async persistence. */
private final AsyncPersistHandler mAsyncPersistHandler;
/**
* The service that checks for inode files with ttl set. We store it here so that it can be
* accessed from tests.
*/
@SuppressFBWarnings("URF_UNREAD_FIELD")
private Future<?> mTtlCheckerService;
/**
* The service that detects lost files. We store it here so that it can be accessed from tests.
*/
@SuppressFBWarnings("URF_UNREAD_FIELD")
private Future<?> mLostFilesDetectionService;
private Future<List<AlluxioURI>> mStartupConsistencyCheck;
/**
* Creates a new instance of {@link DefaultFileSystemMaster}.
*
* @param registry the master registry
* @param journalFactory the factory for the journal to use for tracking master operations
*/
public DefaultFileSystemMaster(MasterRegistry registry, JournalFactory journalFactory) {
this(registry, journalFactory, ExecutorServiceFactories
.fixedThreadPoolExecutorServiceFactory(Constants.FILE_SYSTEM_MASTER_NAME, 3));
}
/**
* Creates a new instance of {@link DefaultFileSystemMaster}.
*
* @param registry the master registry
* @param journalFactory the factory for the journal to use for tracking master operations
* @param executorServiceFactory a factory for creating the executor service to use for running
* maintenance threads
*/
DefaultFileSystemMaster(MasterRegistry registry, JournalFactory journalFactory,
ExecutorServiceFactory executorServiceFactory) {
super(journalFactory.create(Constants.FILE_SYSTEM_MASTER_NAME), new SystemClock(),
executorServiceFactory);
mBlockMaster = registry.get(BlockMaster.class);
mDirectoryIdGenerator = new InodeDirectoryIdGenerator(mBlockMaster);
mMountTable = new MountTable();
mInodeTree = new InodeTree(mBlockMaster, mDirectoryIdGenerator, mMountTable);
// TODO(gene): Handle default config value for whitelist.
mWhitelist = new PrefixList(Configuration.getList(PropertyKey.MASTER_WHITELIST, ","));
mAsyncPersistHandler = AsyncPersistHandler.Factory.create(new FileSystemMasterView(this));
mPermissionChecker = new PermissionChecker(mInodeTree);
registry.add(FileSystemMaster.class, this);
Metrics.registerGauges(this);
}
@Override
public Map<String, TProcessor> getServices() {
Map<String, TProcessor> services = new HashMap<>();
services.put(Constants.FILE_SYSTEM_MASTER_CLIENT_SERVICE_NAME,
new FileSystemMasterClientService.Processor<>(
new FileSystemMasterClientServiceHandler(this)));
services.put(Constants.FILE_SYSTEM_MASTER_WORKER_SERVICE_NAME,
new FileSystemMasterWorkerService.Processor<>(
new FileSystemMasterWorkerServiceHandler(this)));
return services;
}
@Override
public String getName() {
return Constants.FILE_SYSTEM_MASTER_NAME;
}
@Override
public Set<Class<?>> getDependencies() {
return DEPS;
}
@Override
public void processJournalEntry(JournalEntry entry) throws IOException {
if (entry.getSequenceNumber() == 0) {
// The mount table is the only structure to clear. The inode tree is reset when it
// processes the ROOT journal entry.
mMountTable.clear();
}
if (entry.hasInodeFile()) {
mInodeTree.addInodeFileFromJournal(entry.getInodeFile());
// Add the file to TTL buckets, the insert automatically rejects files w/ Constants.NO_TTL
InodeFileEntry inodeFileEntry = entry.getInodeFile();
if (inodeFileEntry.hasTtl()) {
mTtlBuckets.insert(InodeFile.fromJournalEntry(inodeFileEntry));
}
} else if (entry.hasInodeDirectory()) {
try {
// Add the directory to TTL buckets, the insert automatically rejects directory
// w/ Constants.NO_TTL
InodeDirectoryEntry inodeDirectoryEntry = entry.getInodeDirectory();
if (inodeDirectoryEntry.hasTtl()) {
mTtlBuckets.insert(InodeDirectory.fromJournalEntry(inodeDirectoryEntry));
}
mInodeTree.addInodeDirectoryFromJournal(entry.getInodeDirectory());
} catch (AccessControlException e) {
throw new RuntimeException(e);
}
} else if (entry.hasInodeLastModificationTime()) {
InodeLastModificationTimeEntry modTimeEntry = entry.getInodeLastModificationTime();
try (LockedInodePath inodePath = mInodeTree
.lockFullInodePath(modTimeEntry.getId(), InodeTree.LockMode.WRITE)) {
inodePath.getInode()
.setLastModificationTimeMs(modTimeEntry.getLastModificationTimeMs(), true);
} catch (FileDoesNotExistException e) {
throw new RuntimeException(e);
}
} else if (entry.hasPersistDirectory()) {
PersistDirectoryEntry typedEntry = entry.getPersistDirectory();
try (LockedInodePath inodePath = mInodeTree
.lockFullInodePath(typedEntry.getId(), InodeTree.LockMode.WRITE)) {
inodePath.getInode().setPersistenceState(PersistenceState.PERSISTED);
} catch (FileDoesNotExistException e) {
throw new RuntimeException(e);
}
} else if (entry.hasCompleteFile()) {
try {
completeFileFromEntry(entry.getCompleteFile());
} catch (InvalidPathException | InvalidFileSizeException | FileAlreadyCompletedException e) {
throw new RuntimeException(e);
}
} else if (entry.hasSetAttribute()) {
try {
setAttributeFromEntry(entry.getSetAttribute());
} catch (AccessControlException | FileDoesNotExistException | InvalidPathException e) {
throw new RuntimeException(e);
}
} else if (entry.hasDeleteFile()) {
deleteFromEntry(entry.getDeleteFile());
} else if (entry.hasRename()) {
renameFromEntry(entry.getRename());
} else if (entry.hasInodeDirectoryIdGenerator()) {
mDirectoryIdGenerator.initFromJournalEntry(entry.getInodeDirectoryIdGenerator());
} else if (entry.hasReinitializeFile()) {
resetBlockFileFromEntry(entry.getReinitializeFile());
} else if (entry.hasAddMountPoint()) {
try {
mountFromEntry(entry.getAddMountPoint());
} catch (FileAlreadyExistsException | InvalidPathException e) {
throw new RuntimeException(e);
}
} else if (entry.hasDeleteMountPoint()) {
unmountFromEntry(entry.getDeleteMountPoint());
} else if (entry.hasAsyncPersistRequest()) {
try {
long fileId = (entry.getAsyncPersistRequest()).getFileId();
try (LockedInodePath inodePath = mInodeTree
.lockFullInodePath(fileId, InodeTree.LockMode.WRITE)) {
scheduleAsyncPersistenceInternal(inodePath);
}
// NOTE: persistence is asynchronous so there is no guarantee the path will still exist
mAsyncPersistHandler.scheduleAsyncPersistence(getPath(fileId));
} catch (AlluxioException e) {
// It's possible that rescheduling the async persist calls fails, because the blocks may no
// longer be in the memory
LOG.error(e.getMessage());
}
} else {
throw new IOException(ExceptionMessage.UNEXPECTED_JOURNAL_ENTRY.getMessage(entry));
}
}
@Override
public Iterator<JournalEntry> getJournalEntryIterator() {
return Iterators.concat(mInodeTree.getJournalEntryIterator(),
CommonUtils.singleElementIterator(mDirectoryIdGenerator.toJournalEntry()),
// The mount table should be written to the checkpoint after the inodes are written, so that
// when replaying the checkpoint, the inodes exist before mount entries. Replaying a mount
// entry traverses the inode tree.
mMountTable.getJournalEntryIterator());
}
@Override
public void start(boolean isPrimary) throws IOException {
if (isPrimary) {
// Only initialize root when isPrimary because when initializing root, BlockMaster needs to
// write journal entry, if it is not primary, BlockMaster won't have a writable journal.
// If it is secondary, it should be able to load the inode tree from primary's checkpoint.
mInodeTree.initializeRoot(SecurityUtils.getOwnerFromLoginModule(),
SecurityUtils.getGroupFromLoginModule(), Mode.createFullAccess().applyDirectoryUMask());
String defaultUFS = Configuration.get(PropertyKey.MASTER_MOUNT_TABLE_ROOT_UFS);
try {
mMountTable.add(new AlluxioURI(MountTable.ROOT), new AlluxioURI(defaultUFS),
MountOptions.defaults().setShared(
UnderFileSystemUtils.isObjectStorage(defaultUFS) && Configuration
.getBoolean(PropertyKey.UNDERFS_OBJECT_STORE_MOUNT_SHARED_PUBLICLY)));
} catch (FileAlreadyExistsException e) {
// This can happen when a primary becomes a standby and then becomes a primary.
LOG.info("Root has already been mounted.");
} catch (InvalidPathException e) {
throw new IOException("Failed to mount the default UFS " + defaultUFS, e);
}
}
// Call super.start after mInodeTree is initialized because mInodeTree is needed to write
// a journal entry during super.start. Call super.start before calling
// getExecutorService() because the super.start initializes the executor service.
super.start(isPrimary);
if (isPrimary) {
mTtlCheckerService = getExecutorService().submit(
new HeartbeatThread(HeartbeatContext.MASTER_TTL_CHECK,
new InodeTtlChecker(this, mInodeTree, mTtlBuckets),
Configuration.getInt(PropertyKey.MASTER_TTL_CHECKER_INTERVAL_MS)));
mLostFilesDetectionService = getExecutorService().submit(
new HeartbeatThread(HeartbeatContext.MASTER_LOST_FILES_DETECTION,
new LostFileDetector(this, mInodeTree),
Configuration.getInt(PropertyKey.MASTER_HEARTBEAT_INTERVAL_MS)));
if (Configuration.getBoolean(PropertyKey.MASTER_STARTUP_CONSISTENCY_CHECK_ENABLED)) {
mStartupConsistencyCheck = getExecutorService().submit(new Callable<List<AlluxioURI>>() {
@Override
public List<AlluxioURI> call() throws Exception {
return startupCheckConsistency(ExecutorServiceFactories
.fixedThreadPoolExecutorServiceFactory("startup-consistency-check", 32).create());
}
});
}
}
}
/**
* Checks the consistency of the root in a multi-threaded and incremental fashion. This method
* will only READ lock the directories and files actively being checked and release them after the
* check on the file / directory is complete.
*
* @return a list of paths in Alluxio which are not consistent with the under storage
* @throws InterruptedException if the thread is interrupted during execution
* @throws IOException if an error occurs interacting with the under storage
*/
private List<AlluxioURI> startupCheckConsistency(final ExecutorService service)
throws InterruptedException, IOException {
/** A marker {@link StartupConsistencyChecker}s add to the queue to signal completion */
final long completionMarker = -1;
/** A shared queue of directories which have yet to be checked */
final BlockingQueue<Long> dirsToCheck = new LinkedBlockingQueue<>();
/**
* A {@link Callable} which checks the consistency of a directory.
*/
final class StartupConsistencyChecker implements Callable<List<AlluxioURI>> {
/** The path to check, guaranteed to be a directory in Alluxio. */
private final Long mFileId;
/**
* Creates a new callable which checks the consistency of a directory.
* @param fileId the path to check
*/
private StartupConsistencyChecker(Long fileId) {
mFileId = fileId;
}
/**
* Checks the consistency of the directory and all immediate children which are files. All
* immediate children which are directories are added to the shared queue of directories to
* check. The parent directory is READ locked during the entire call while the children are
* READ locked only during the consistency check of the children files.
*
* @return a list of inconsistent uris
* @throws IOException if an error occurs interacting with the under storage
*/
@Override
public List<AlluxioURI> call() throws IOException {
List<AlluxioURI> inconsistentUris = new ArrayList<>();
try (LockedInodePath dir = mInodeTree.lockFullInodePath(mFileId, InodeTree.LockMode.READ)) {
Inode parentInode = dir.getInode();
AlluxioURI parentUri = dir.getUri();
if (!checkConsistencyInternal(parentInode, parentUri)) {
inconsistentUris.add(parentUri);
}
for (Inode childInode : ((InodeDirectory) parentInode).getChildren()) {
try {
childInode.lockReadAndCheckParent(parentInode);
} catch (InvalidPathException e) {
// This should be safe, continue.
LOG.debug("Error during startup check consistency, ignoring and continuing.", e);
continue;
}
try {
AlluxioURI childUri = parentUri.join(childInode.getName());
if (childInode.isDirectory()) {
dirsToCheck.add(childInode.getId());
} else {
if (!checkConsistencyInternal(childInode, childUri)) {
inconsistentUris.add(childUri);
}
}
} finally {
childInode.unlockRead();
}
}
} catch (FileDoesNotExistException e) {
// This should be safe, continue.
LOG.debug("A file scheduled for consistency check was deleted before the check.");
} catch (InvalidPathException e) {
// This should not happen.
LOG.error("An invalid path was discovered during the consistency check, skipping.", e);
}
dirsToCheck.add(completionMarker);
return inconsistentUris;
}
}
// Add the root to the directories to check.
dirsToCheck.add(mInodeTree.getRoot().getId());
List<Future<List<AlluxioURI>>> results = new ArrayList<>();
// Tracks how many checkers have been started.
long started = 0;
// Tracks how many checkers have completed.
long completed = 0;
do {
Long fileId = dirsToCheck.take();
if (fileId == completionMarker) { // A thread signaled completion.
completed++;
} else { // A new directory needs to be checked.
StartupConsistencyChecker checker = new StartupConsistencyChecker(fileId);
results.add(service.submit(checker));
started++;
}
} while (started != completed);
// Return the total set of inconsistent paths discovered.
List<AlluxioURI> inconsistentUris = new ArrayList<>();
for (Future<List<AlluxioURI>> result : results) {
try {
inconsistentUris.addAll(result.get());
} catch (Exception e) {
// This shouldn't happen, all futures should be complete.
Throwables.propagate(e);
}
}
service.shutdown();
return inconsistentUris;
}
@Override
public StartupConsistencyCheck getStartupConsistencyCheck() {
if (!Configuration.getBoolean(PropertyKey.MASTER_STARTUP_CONSISTENCY_CHECK_ENABLED)) {
return StartupConsistencyCheck.disabled();
}
if (!mStartupConsistencyCheck.isDone()) {
return StartupConsistencyCheck.running();
}
try {
List<AlluxioURI> inconsistentUris = mStartupConsistencyCheck.get();
return StartupConsistencyCheck.complete(inconsistentUris);
} catch (Exception e) {
LOG.warn("Failed to complete start up consistency check.", e);
return StartupConsistencyCheck.failed();
}
}
@Override
public long getFileId(AlluxioURI path) throws AccessControlException {
try (JournalContext journalContext = createJournalContext();
LockedInodePath inodePath = mInodeTree.lockInodePath(path, InodeTree.LockMode.WRITE)) {
// This is WRITE locked, since loading metadata is possible.
mPermissionChecker.checkPermission(Mode.Bits.READ, inodePath);
loadMetadataIfNotExistAndJournal(inodePath,
LoadMetadataOptions.defaults().setCreateAncestors(true), journalContext);
mInodeTree.ensureFullInodePath(inodePath, InodeTree.LockMode.READ);
return inodePath.getInode().getId();
} catch (InvalidPathException | FileDoesNotExistException e) {
return IdUtils.INVALID_FILE_ID;
}
}
@Override
public FileInfo getFileInfo(long fileId)
throws FileDoesNotExistException, AccessControlException {
Metrics.GET_FILE_INFO_OPS.inc();
try (
LockedInodePath inodePath = mInodeTree.lockFullInodePath(fileId, InodeTree.LockMode.READ)) {
return getFileInfoInternal(inodePath);
}
}
@Override
public FileInfo getFileInfo(AlluxioURI path)
throws FileDoesNotExistException, InvalidPathException, AccessControlException {
Metrics.GET_FILE_INFO_OPS.inc();
// Get a READ lock first to see if we need to load metadata, note that this assumes load
// metadata for direct children is disabled by default.
try (LockedInodePath inodePath = mInodeTree.lockInodePath(path, InodeTree.LockMode.READ)) {
mPermissionChecker.checkPermission(Mode.Bits.READ, inodePath);
if (inodePath.fullPathExists()) {
// The file already exists, so metadata does not need to be loaded.
return getFileInfoInternal(inodePath);
}
}
try (JournalContext journalContext = createJournalContext();
LockedInodePath inodePath = mInodeTree.lockInodePath(path, InodeTree.LockMode.WRITE)) {
// This is WRITE locked, since loading metadata is possible.
mPermissionChecker.checkPermission(Mode.Bits.READ, inodePath);
loadMetadataIfNotExistAndJournal(inodePath,
LoadMetadataOptions.defaults().setCreateAncestors(true), journalContext);
mInodeTree.ensureFullInodePath(inodePath, InodeTree.LockMode.READ);
return getFileInfoInternal(inodePath);
}
}
/**
* @param inodePath the {@link LockedInodePath} to get the {@link FileInfo} for
* @return the {@link FileInfo} for the given inode
* @throws FileDoesNotExistException if the file does not exist
* @throws AccessControlException if permission denied
*/
private FileInfo getFileInfoInternal(LockedInodePath inodePath)
throws FileDoesNotExistException, AccessControlException {
Inode<?> inode = inodePath.getInode();
AlluxioURI uri = inodePath.getUri();
FileInfo fileInfo = inode.generateClientFileInfo(uri.toString());
fileInfo.setInMemoryPercentage(getInMemoryPercentage(inode));
if (inode instanceof InodeFile) {
try {
fileInfo.setFileBlockInfos(getFileBlockInfoListInternal(inodePath));
} catch (InvalidPathException e) {
throw new FileDoesNotExistException(e.getMessage(), e);
}
}
MountTable.Resolution resolution;
try {
resolution = mMountTable.resolve(uri);
} catch (InvalidPathException e) {
throw new FileDoesNotExistException(e.getMessage(), e);
}
AlluxioURI resolvedUri = resolution.getUri();
fileInfo.setUfsPath(resolvedUri.toString());
fileInfo.setAlluxioMountPoint(resolution.getMountPoint().toString());
fileInfo.setMountTableVersion(resolution.getVersion());
Metrics.FILE_INFOS_GOT.inc();
return fileInfo;
}
@Override
public PersistenceState getPersistenceState(long fileId) throws FileDoesNotExistException {
try (
LockedInodePath inodePath = mInodeTree.lockFullInodePath(fileId, InodeTree.LockMode.READ)) {
return inodePath.getInode().getPersistenceState();
}
}
@Override
public List<FileInfo> listStatus(AlluxioURI path, ListStatusOptions listStatusOptions)
throws AccessControlException, FileDoesNotExistException, InvalidPathException {
Metrics.GET_FILE_INFO_OPS.inc();
try (JournalContext journalContext = createJournalContext();
LockedInodePath inodePath = mInodeTree.lockInodePath(path, InodeTree.LockMode.WRITE)) {
// This is WRITE locked, since loading metadata is possible.
mPermissionChecker.checkPermission(Mode.Bits.READ, inodePath);
LoadMetadataOptions loadMetadataOptions =
LoadMetadataOptions.defaults().setCreateAncestors(true).setLoadDirectChildren(
listStatusOptions.getLoadMetadataType() != LoadMetadataType.Never);
Inode<?> inode;
if (inodePath.fullPathExists()) {
inode = inodePath.getInode();
if (inode.isDirectory()
&& listStatusOptions.getLoadMetadataType() != LoadMetadataType.Always
&& ((InodeDirectory) inode).isDirectChildrenLoaded()) {
loadMetadataOptions.setLoadDirectChildren(false);
}
}
loadMetadataIfNotExistAndJournal(inodePath, loadMetadataOptions, journalContext);
mInodeTree.ensureFullInodePath(inodePath, InodeTree.LockMode.READ);
inode = inodePath.getInode();
List<FileInfo> ret = new ArrayList<>();
if (inode.isDirectory()) {
TempInodePathForDescendant tempInodePath = new TempInodePathForDescendant(inodePath);
mPermissionChecker.checkPermission(Mode.Bits.EXECUTE, inodePath);
for (Inode<?> child : ((InodeDirectory) inode).getChildren()) {
child.lockReadAndCheckParent(inode);
try {
// the path to child for getPath should already be locked.
tempInodePath.setDescendant(child, mInodeTree.getPath(child));
ret.add(getFileInfoInternal(tempInodePath));
} finally {
child.unlockRead();
}
}
} else {
ret.add(getFileInfoInternal(inodePath));
}
Metrics.FILE_INFOS_GOT.inc();
return ret;
}
}
@Override
public FileSystemMasterView getFileSystemMasterView() {
return new FileSystemMasterView(this);
}
@Override
public List<AlluxioURI> checkConsistency(AlluxioURI path, CheckConsistencyOptions options)
throws AccessControlException, FileDoesNotExistException, InvalidPathException, IOException {
List<AlluxioURI> inconsistentUris = new ArrayList<>();
try (LockedInodePath parent = mInodeTree.lockInodePath(path, InodeTree.LockMode.READ)) {
mPermissionChecker.checkPermission(Mode.Bits.READ, parent);
try (InodeLockList children = mInodeTree.lockDescendants(parent, InodeTree.LockMode.READ)) {
if (!checkConsistencyInternal(parent.getInode(), parent.getUri())) {
inconsistentUris.add(parent.getUri());
}
for (Inode child : children.getInodes()) {
AlluxioURI currentPath = mInodeTree.getPath(child);
if (!checkConsistencyInternal(child, currentPath)) {
inconsistentUris.add(currentPath);
}
}
}
}
return inconsistentUris;
}
/**
* Checks if a path is consistent between Alluxio and the underlying storage.
* <p>
* A path without a backing under storage is always consistent.
* <p>
* A not persisted path is considered consistent if:
* 1. It does not shadow an object in the underlying storage.
* <p>
* A persisted path is considered consistent if:
* 1. An equivalent object exists for its under storage path.
* 2. The metadata of the Alluxio and under storage object are equal.
*
* @param inode the inode to check
* @param path the current path associated with the inode
* @return true if the path is consistent, false otherwise
* @throws FileDoesNotExistException if the path cannot be found in the Alluxio inode tree
* @throws InvalidPathException if the path is not well formed
*/
private boolean checkConsistencyInternal(Inode inode, AlluxioURI path)
throws FileDoesNotExistException, InvalidPathException, IOException {
MountTable.Resolution resolution = mMountTable.resolve(path);
UnderFileSystem ufs = resolution.getUfs();
String ufsPath = resolution.getUri().getPath();
if (ufs == null) {
return true;
}
if (!inode.isPersisted()) {
return !ufs.exists(ufsPath);
}
// TODO(calvin): Evaluate which other metadata fields should be validated.
if (inode.isDirectory()) {
return ufs.isDirectory(ufsPath);
} else {
InodeFile file = (InodeFile) inode;
return ufs.isFile(ufsPath) && ufs.getFileSize(ufsPath) == file.getLength();
}
}
@Override
public void completeFile(AlluxioURI path, CompleteFileOptions options)
throws BlockInfoException, FileDoesNotExistException, InvalidPathException,
InvalidFileSizeException, FileAlreadyCompletedException, AccessControlException {
Metrics.COMPLETE_FILE_OPS.inc();
try (JournalContext journalContext = createJournalContext();
LockedInodePath inodePath = mInodeTree.lockFullInodePath(path, InodeTree.LockMode.WRITE)) {
mPermissionChecker.checkPermission(Mode.Bits.WRITE, inodePath);
// Even readonly mount points should be able to complete a file, for UFS reads in CACHE mode.
completeFileAndJournal(inodePath, options, journalContext);
}
}
/**
* Completes a file. After a file is completed, it cannot be written to.
* <p>
* Writes to the journal.
*
* @param inodePath the {@link LockedInodePath} to complete
* @param options the method options
* @param journalContext the journal context
* @throws InvalidPathException if an invalid path is encountered
* @throws FileDoesNotExistException if the file does not exist
* @throws BlockInfoException if a block information exception is encountered
* @throws FileAlreadyCompletedException if the file is already completed
* @throws InvalidFileSizeException if an invalid file size is encountered
*/
private void completeFileAndJournal(LockedInodePath inodePath, CompleteFileOptions options,
JournalContext journalContext)
throws InvalidPathException, FileDoesNotExistException, BlockInfoException,
FileAlreadyCompletedException, InvalidFileSizeException {
Inode<?> inode = inodePath.getInode();
if (!inode.isFile()) {
throw new FileDoesNotExistException(
ExceptionMessage.PATH_MUST_BE_FILE.getMessage(inodePath.getUri()));
}
InodeFile fileInode = (InodeFile) inode;
List<Long> blockIdList = fileInode.getBlockIds();
List<BlockInfo> blockInfoList = mBlockMaster.getBlockInfoList(blockIdList);
if (!fileInode.isPersisted() && blockInfoList.size() != blockIdList.size()) {
throw new BlockInfoException("Cannot complete a file without all the blocks committed");
}
// Iterate over all file blocks committed to Alluxio, computing the length and verify that all
// the blocks (except the last one) is the same size as the file block size.
long inMemoryLength = 0;
long fileBlockSize = fileInode.getBlockSizeBytes();
for (int i = 0; i < blockInfoList.size(); i++) {
BlockInfo blockInfo = blockInfoList.get(i);
inMemoryLength += blockInfo.getLength();
if (i < blockInfoList.size() - 1 && blockInfo.getLength() != fileBlockSize) {
throw new BlockInfoException(
"Block index " + i + " has a block size smaller than the file block size (" + fileInode
.getBlockSizeBytes() + ")");
}
}
// If the file is persisted, its length is determined by UFS. Otherwise, its length is
// determined by its memory footprint.
long length = fileInode.isPersisted() ? options.getUfsLength() : inMemoryLength;
completeFileInternal(fileInode.getBlockIds(), inodePath, length, options.getOperationTimeMs());
CompleteFileEntry completeFileEntry =
CompleteFileEntry.newBuilder().addAllBlockIds(fileInode.getBlockIds()).setId(inode.getId())
.setLength(length).setOpTimeMs(options.getOperationTimeMs()).build();
appendJournalEntry(JournalEntry.newBuilder().setCompleteFile(completeFileEntry).build(),
journalContext);
}
/**
* @param blockIds the block ids to use
* @param inodePath the {@link LockedInodePath} to complete
* @param length the length to use
* @param opTimeMs the operation time (in milliseconds)
* @throws FileDoesNotExistException if the file does not exist
* @throws InvalidPathException if an invalid path is encountered
* @throws InvalidFileSizeException if an invalid file size is encountered
* @throws FileAlreadyCompletedException if the file has already been completed
*/
private void completeFileInternal(List<Long> blockIds, LockedInodePath inodePath, long length,
long opTimeMs)
throws FileDoesNotExistException, InvalidPathException, InvalidFileSizeException,
FileAlreadyCompletedException {
InodeFile inode = inodePath.getInodeFile();
inode.setBlockIds(blockIds);
inode.setLastModificationTimeMs(opTimeMs);
inode.complete(length);
if (inode.isPersisted()) {
// Commit all the file blocks (without locations) so the metadata for the block exists.
long currLength = length;
for (long blockId : inode.getBlockIds()) {
long blockSize = Math.min(currLength, inode.getBlockSizeBytes());
mBlockMaster.commitBlockInUFS(blockId, blockSize);
currLength -= blockSize;
}
}
Metrics.FILES_COMPLETED.inc();
}
/**
* @param entry the entry to use
* @throws InvalidPathException if an invalid path is encountered
* @throws InvalidFileSizeException if an invalid file size is encountered
* @throws FileAlreadyCompletedException if the file has already been completed
*/
private void completeFileFromEntry(CompleteFileEntry entry)
throws InvalidPathException, InvalidFileSizeException, FileAlreadyCompletedException {
try (LockedInodePath inodePath = mInodeTree
.lockFullInodePath(entry.getId(), InodeTree.LockMode.WRITE)) {
completeFileInternal(entry.getBlockIdsList(), inodePath, entry.getLength(),
entry.getOpTimeMs());
} catch (FileDoesNotExistException e) {
throw new RuntimeException(e);
}
}
@Override
public long createFile(AlluxioURI path, CreateFileOptions options)
throws AccessControlException, InvalidPathException, FileAlreadyExistsException,
BlockInfoException, IOException, FileDoesNotExistException {
Metrics.CREATE_FILES_OPS.inc();
try (JournalContext journalContext = createJournalContext();
LockedInodePath inodePath = mInodeTree.lockInodePath(path, InodeTree.LockMode.WRITE)) {
mPermissionChecker.checkParentPermission(Mode.Bits.WRITE, inodePath);
mMountTable.checkUnderWritableMountPoint(path);
createFileAndJournal(inodePath, options, journalContext);
return inodePath.getInode().getId();
}
}
/**
* Creates a file (not a directory) for a given path.
* <p>
* Writes to the journal.
*
* @param inodePath the file to create
* @param options method options
* @param journalContext the journal context
* @throws FileAlreadyExistsException if the file already exists
* @throws BlockInfoException if an invalid block information in encountered
* @throws FileDoesNotExistException if the parent of the path does not exist and the recursive
* option is false
* @throws InvalidPathException if an invalid path is encountered
* @throws IOException if the creation fails
*/
private void createFileAndJournal(LockedInodePath inodePath, CreateFileOptions options,
JournalContext journalContext)
throws FileAlreadyExistsException, BlockInfoException, FileDoesNotExistException,
InvalidPathException, IOException {
InodeTree.CreatePathResult createResult = createFileInternal(inodePath, options);
journalCreatePathResult(createResult, journalContext);
}
/**
* @param inodePath the path to be created
* @param options method options
* @return {@link InodeTree.CreatePathResult} with the path creation result
* @throws InvalidPathException if an invalid path is encountered
* @throws FileAlreadyExistsException if the file already exists
* @throws BlockInfoException if invalid block information is encountered
* @throws IOException if an I/O error occurs
* @throws FileDoesNotExistException if the parent of the path does not exist and the recursive
* option is false
*/
InodeTree.CreatePathResult createFileInternal(LockedInodePath inodePath,
CreateFileOptions options)
throws InvalidPathException, FileAlreadyExistsException, BlockInfoException, IOException,
FileDoesNotExistException {
InodeTree.CreatePathResult createResult = mInodeTree.createPath(inodePath, options);
// If the create succeeded, the list of created inodes will not be empty.
List<Inode<?>> created = createResult.getCreated();
InodeFile inode = (InodeFile) created.get(created.size() - 1);
if (mWhitelist.inList(inodePath.getUri().toString())) {
inode.setCacheable(true);
}
mTtlBuckets.insert(inode);
Metrics.FILES_CREATED.inc();
Metrics.DIRECTORIES_CREATED.inc();
return createResult;