1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.util;
20
21 import com.google.common.annotations.VisibleForTesting;
22 import com.google.common.base.Throwables;
23 import com.google.common.collect.Iterators;
24 import com.google.common.collect.Lists;
25 import com.google.common.primitives.Ints;
26
27 import edu.umd.cs.findbugs.annotations.CheckForNull;
28
29 import java.io.ByteArrayInputStream;
30 import java.io.DataInputStream;
31 import java.io.EOFException;
32 import java.io.FileNotFoundException;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.InterruptedIOException;
36 import java.lang.reflect.InvocationTargetException;
37 import java.lang.reflect.Method;
38 import java.net.InetSocketAddress;
39 import java.net.URI;
40 import java.net.URISyntaxException;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.Collections;
44 import java.util.HashMap;
45 import java.util.Iterator;
46 import java.util.LinkedList;
47 import java.util.List;
48 import java.util.Locale;
49 import java.util.Map;
50 import java.util.Vector;
51 import java.util.concurrent.ArrayBlockingQueue;
52 import java.util.concurrent.ConcurrentHashMap;
53 import java.util.concurrent.ExecutionException;
54 import java.util.concurrent.ExecutorService;
55 import java.util.concurrent.Future;
56 import java.util.concurrent.FutureTask;
57 import java.util.concurrent.ThreadPoolExecutor;
58 import java.util.concurrent.TimeUnit;
59 import java.util.regex.Pattern;
60
61 import org.apache.commons.logging.Log;
62 import org.apache.commons.logging.LogFactory;
63 import org.apache.hadoop.HadoopIllegalArgumentException;
64 import org.apache.hadoop.conf.Configuration;
65 import org.apache.hadoop.fs.BlockLocation;
66 import org.apache.hadoop.fs.FSDataInputStream;
67 import org.apache.hadoop.fs.FSDataOutputStream;
68 import org.apache.hadoop.fs.FileStatus;
69 import org.apache.hadoop.fs.FileSystem;
70 import org.apache.hadoop.fs.LocatedFileStatus;
71 import org.apache.hadoop.fs.Path;
72 import org.apache.hadoop.fs.PathFilter;
73 import org.apache.hadoop.fs.RemoteIterator;
74 import org.apache.hadoop.fs.permission.FsAction;
75 import org.apache.hadoop.fs.permission.FsPermission;
76 import org.apache.hadoop.hbase.ClusterId;
77 import org.apache.hadoop.hbase.HColumnDescriptor;
78 import org.apache.hadoop.hbase.HConstants;
79 import org.apache.hadoop.hbase.HDFSBlocksDistribution;
80 import org.apache.hadoop.hbase.HRegionInfo;
81 import org.apache.hadoop.hbase.RemoteExceptionHandler;
82 import org.apache.hadoop.hbase.TableName;
83 import org.apache.hadoop.hbase.classification.InterfaceAudience;
84 import org.apache.hadoop.hbase.exceptions.DeserializationException;
85 import org.apache.hadoop.hbase.fs.HFileSystem;
86 import org.apache.hadoop.hbase.io.HFileLink;
87 import org.apache.hadoop.hbase.master.HMaster;
88 import org.apache.hadoop.hbase.regionserver.StoreFileInfo;
89 import org.apache.hadoop.hbase.security.AccessDeniedException;
90 import org.apache.hadoop.hbase.util.HBaseFsck.ErrorReporter;
91 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
92 import org.apache.hadoop.hbase.protobuf.generated.FSProtos;
93 import org.apache.hadoop.hdfs.DistributedFileSystem;
94 import org.apache.hadoop.io.IOUtils;
95 import org.apache.hadoop.io.SequenceFile;
96 import org.apache.hadoop.ipc.RemoteException;
97 import org.apache.hadoop.security.UserGroupInformation;
98 import org.apache.hadoop.util.Progressable;
99 import org.apache.hadoop.util.ReflectionUtils;
100 import org.apache.hadoop.util.StringUtils;
101
102
103 import static org.apache.hadoop.hbase.HConstants.HBASE_DIR;
104
105
106
107
108 @InterfaceAudience.Private
109 public abstract class FSUtils {
110 private static final Log LOG = LogFactory.getLog(FSUtils.class);
111
112
113 public static final String FULL_RWX_PERMISSIONS = "777";
114 private static final String THREAD_POOLSIZE = "hbase.client.localityCheck.threadPoolSize";
115 private static final int DEFAULT_THREAD_POOLSIZE = 2;
116
117
118 public static final boolean WINDOWS = System.getProperty("os.name").startsWith("Windows");
119
120 protected FSUtils() {
121 super();
122 }
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140 public static void setStoragePolicy(final FileSystem fs, final Configuration conf,
141 final Path path, final String policyKey, final String defaultPolicy) {
142 String storagePolicy = conf.get(policyKey, defaultPolicy).toUpperCase(Locale.ROOT);
143 if (storagePolicy.equals(defaultPolicy)) {
144 if (LOG.isTraceEnabled()) {
145 LOG.trace("default policy of " + defaultPolicy + " requested, exiting early.");
146 }
147 return;
148 }
149 if (fs instanceof DistributedFileSystem) {
150 DistributedFileSystem dfs = (DistributedFileSystem)fs;
151
152 Class<? extends DistributedFileSystem> dfsClass = dfs.getClass();
153 Method m = null;
154 try {
155 m = dfsClass.getDeclaredMethod("setStoragePolicy",
156 new Class<?>[] { Path.class, String.class });
157 m.setAccessible(true);
158 } catch (NoSuchMethodException e) {
159 LOG.info("FileSystem doesn't support"
160 + " setStoragePolicy; --HDFS-6584 not available");
161 } catch (SecurityException e) {
162 LOG.info("Doesn't have access to setStoragePolicy on "
163 + "FileSystems --HDFS-6584 not available", e);
164 m = null;
165 }
166 if (m != null) {
167 try {
168 m.invoke(dfs, path, storagePolicy);
169 LOG.info("set " + storagePolicy + " for " + path);
170 } catch (Exception e) {
171
172 boolean probablyBadPolicy = false;
173 if (e instanceof InvocationTargetException) {
174 final Throwable exception = e.getCause();
175 if (exception instanceof RemoteException &&
176 HadoopIllegalArgumentException.class.getName().equals(
177 ((RemoteException)exception).getClassName())) {
178 LOG.warn("Given storage policy, '" + storagePolicy + "', was rejected and probably " +
179 "isn't a valid policy for the version of Hadoop you're running. I.e. if you're " +
180 "trying to use SSD related policies then you're likely missing HDFS-7228. For " +
181 "more information see the 'ArchivalStorage' docs for your Hadoop release.");
182 LOG.debug("More information about the invalid storage policy.", exception);
183 probablyBadPolicy = true;
184 }
185 }
186 if (!probablyBadPolicy) {
187
188
189 LOG.warn("Unable to set " + storagePolicy + " for " + path, e);
190 }
191 }
192 }
193 } else {
194 LOG.info("FileSystem isn't an instance of DistributedFileSystem; presuming it doesn't " +
195 "support setStoragePolicy.");
196 }
197 }
198
199
200
201
202
203 public static boolean isDistributedFileSystem(final FileSystem fs) throws IOException {
204 FileSystem fileSystem = fs;
205
206
207 if (fs instanceof HFileSystem) {
208 fileSystem = ((HFileSystem)fs).getBackingFs();
209 }
210 return fileSystem instanceof DistributedFileSystem;
211 }
212
213
214
215
216
217
218
219
220
221 public static boolean isStartingWithPath(final Path rootPath, final String path) {
222 String uriRootPath = rootPath.toUri().getPath();
223 String tailUriPath = (new Path(path)).toUri().getPath();
224 return tailUriPath.startsWith(uriRootPath);
225 }
226
227
228
229
230
231
232
233
234
235 public static boolean isMatchingTail(final Path pathToSearch, String pathTail) {
236 return isMatchingTail(pathToSearch, new Path(pathTail));
237 }
238
239
240
241
242
243
244
245
246
247 public static boolean isMatchingTail(final Path pathToSearch, final Path pathTail) {
248 if (pathToSearch.depth() != pathTail.depth()) return false;
249 Path tailPath = pathTail;
250 String tailName;
251 Path toSearch = pathToSearch;
252 String toSearchName;
253 boolean result = false;
254 do {
255 tailName = tailPath.getName();
256 if (tailName == null || tailName.length() <= 0) {
257 result = true;
258 break;
259 }
260 toSearchName = toSearch.getName();
261 if (toSearchName == null || toSearchName.length() <= 0) break;
262
263 tailPath = tailPath.getParent();
264 toSearch = toSearch.getParent();
265 } while(tailName.equals(toSearchName));
266 return result;
267 }
268
269 public static FSUtils getInstance(FileSystem fs, Configuration conf) {
270 String scheme = fs.getUri().getScheme();
271 if (scheme == null) {
272 LOG.warn("Could not find scheme for uri " +
273 fs.getUri() + ", default to hdfs");
274 scheme = "hdfs";
275 }
276 Class<?> fsUtilsClass = conf.getClass("hbase.fsutil." +
277 scheme + ".impl", FSHDFSUtils.class);
278 FSUtils fsUtils = (FSUtils)ReflectionUtils.newInstance(fsUtilsClass, conf);
279 return fsUtils;
280 }
281
282
283
284
285
286
287
288
289 public static boolean deleteDirectory(final FileSystem fs, final Path dir)
290 throws IOException {
291 return fs.exists(dir) && fs.delete(dir, true);
292 }
293
294
295
296
297
298
299
300
301 public static boolean deleteRegionDir(final Configuration conf, final HRegionInfo hri)
302 throws IOException {
303 Path rootDir = getRootDir(conf);
304 FileSystem fs = rootDir.getFileSystem(conf);
305 return deleteDirectory(fs,
306 new Path(getTableDir(rootDir, hri.getTable()), hri.getEncodedName()));
307 }
308
309
310
311
312
313
314
315
316
317
318
319
320 public static long getDefaultBlockSize(final FileSystem fs, final Path path) throws IOException {
321 Method m = null;
322 Class<? extends FileSystem> cls = fs.getClass();
323 try {
324 m = cls.getMethod("getDefaultBlockSize", new Class<?>[] { Path.class });
325 } catch (NoSuchMethodException e) {
326 LOG.info("FileSystem doesn't support getDefaultBlockSize");
327 } catch (SecurityException e) {
328 LOG.info("Doesn't have access to getDefaultBlockSize on FileSystems", e);
329 m = null;
330 }
331 if (m == null) {
332 return fs.getDefaultBlockSize(path);
333 } else {
334 try {
335 Object ret = m.invoke(fs, path);
336 return ((Long)ret).longValue();
337 } catch (Exception e) {
338 throw new IOException(e);
339 }
340 }
341 }
342
343
344
345
346
347
348
349
350
351
352
353
354 public static short getDefaultReplication(final FileSystem fs, final Path path) throws IOException {
355 Method m = null;
356 Class<? extends FileSystem> cls = fs.getClass();
357 try {
358 m = cls.getMethod("getDefaultReplication", new Class<?>[] { Path.class });
359 } catch (NoSuchMethodException e) {
360 LOG.info("FileSystem doesn't support getDefaultReplication");
361 } catch (SecurityException e) {
362 LOG.info("Doesn't have access to getDefaultReplication on FileSystems", e);
363 m = null;
364 }
365 if (m == null) {
366 return fs.getDefaultReplication(path);
367 } else {
368 try {
369 Object ret = m.invoke(fs, path);
370 return ((Number)ret).shortValue();
371 } catch (Exception e) {
372 throw new IOException(e);
373 }
374 }
375 }
376
377
378
379
380
381
382
383
384
385
386
387 public static int getDefaultBufferSize(final FileSystem fs) {
388 return fs.getConf().getInt("io.file.buffer.size", 4096);
389 }
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410 public static FSDataOutputStream create(Configuration conf, FileSystem fs, Path path,
411 FsPermission perm, InetSocketAddress[] favoredNodes) throws IOException {
412 if (fs instanceof HFileSystem) {
413 FileSystem backingFs = ((HFileSystem)fs).getBackingFs();
414 if (backingFs instanceof DistributedFileSystem) {
415
416
417 short replication = Short.parseShort(conf.get(HColumnDescriptor.DFS_REPLICATION,
418 String.valueOf(HColumnDescriptor.DEFAULT_DFS_REPLICATION)));
419 try {
420 return (FSDataOutputStream) (DistributedFileSystem.class.getDeclaredMethod("create",
421 Path.class, FsPermission.class, boolean.class, int.class, short.class, long.class,
422 Progressable.class, InetSocketAddress[].class).invoke(backingFs, path, perm, true,
423 getDefaultBufferSize(backingFs),
424 replication > 0 ? replication : getDefaultReplication(backingFs, path),
425 getDefaultBlockSize(backingFs, path), null, favoredNodes));
426 } catch (InvocationTargetException ite) {
427
428 throw new IOException(ite.getCause());
429 } catch (NoSuchMethodException e) {
430 LOG.debug("DFS Client does not support most favored nodes create; using default create");
431 if (LOG.isTraceEnabled()) LOG.trace("Ignoring; use default create", e);
432 } catch (IllegalArgumentException e) {
433 LOG.debug("Ignoring (most likely Reflection related exception) " + e);
434 } catch (SecurityException e) {
435 LOG.debug("Ignoring (most likely Reflection related exception) " + e);
436 } catch (IllegalAccessException e) {
437 LOG.debug("Ignoring (most likely Reflection related exception) " + e);
438 }
439 }
440 }
441 return create(fs, path, perm, true);
442 }
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461 public static FSDataOutputStream create(FileSystem fs, Path path,
462 FsPermission perm, boolean overwrite) throws IOException {
463 if (LOG.isTraceEnabled()) {
464 LOG.trace("Creating file=" + path + " with permission=" + perm + ", overwrite=" + overwrite);
465 }
466 return fs.create(path, perm, overwrite, getDefaultBufferSize(fs),
467 getDefaultReplication(fs, path), getDefaultBlockSize(fs, path), null);
468 }
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483 public static FsPermission getFilePermissions(final FileSystem fs,
484 final Configuration conf, final String permssionConfKey) {
485 boolean enablePermissions = conf.getBoolean(
486 HConstants.ENABLE_DATA_FILE_UMASK, false);
487
488 if (enablePermissions) {
489 try {
490 FsPermission perm = new FsPermission(FULL_RWX_PERMISSIONS);
491
492 String mask = conf.get(permssionConfKey);
493 if (mask == null)
494 return FsPermission.getFileDefault();
495
496 FsPermission umask = new FsPermission(mask);
497 return perm.applyUMask(umask);
498 } catch (IllegalArgumentException e) {
499 LOG.warn(
500 "Incorrect umask attempted to be created: "
501 + conf.get(permssionConfKey)
502 + ", using default file permissions.", e);
503 return FsPermission.getFileDefault();
504 }
505 }
506 return FsPermission.getFileDefault();
507 }
508
509
510
511
512
513
514
515 public static void checkFileSystemAvailable(final FileSystem fs)
516 throws IOException {
517 if (!(fs instanceof DistributedFileSystem)) {
518 return;
519 }
520 IOException exception = null;
521 DistributedFileSystem dfs = (DistributedFileSystem) fs;
522 try {
523 if (dfs.exists(new Path("/"))) {
524 return;
525 }
526 } catch (IOException e) {
527 exception = RemoteExceptionHandler.checkIOException(e);
528 }
529 try {
530 fs.close();
531 } catch (Exception e) {
532 LOG.error("file system close failed: ", e);
533 }
534 IOException io = new IOException("File system is not available");
535 io.initCause(exception);
536 throw io;
537 }
538
539
540
541
542
543
544
545
546
547 private static boolean isInSafeMode(DistributedFileSystem dfs) throws IOException {
548 boolean inSafeMode = false;
549 try {
550 Method m = DistributedFileSystem.class.getMethod("setSafeMode", new Class<?> []{
551 org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction.class, boolean.class});
552 inSafeMode = (Boolean) m.invoke(dfs,
553 org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction.SAFEMODE_GET, true);
554 } catch (Exception e) {
555 if (e instanceof IOException) throw (IOException) e;
556
557
558 inSafeMode = dfs.setSafeMode(
559 org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction.SAFEMODE_GET);
560 }
561 return inSafeMode;
562 }
563
564
565
566
567
568
569 public static void checkDfsSafeMode(final Configuration conf)
570 throws IOException {
571 boolean isInSafeMode = false;
572 FileSystem fs = FileSystem.get(conf);
573 if (fs instanceof DistributedFileSystem) {
574 DistributedFileSystem dfs = (DistributedFileSystem)fs;
575 isInSafeMode = isInSafeMode(dfs);
576 }
577 if (isInSafeMode) {
578 throw new IOException("File system is in safemode, it can't be written now");
579 }
580 }
581
582
583
584
585
586
587
588
589
590
591 public static String getVersion(FileSystem fs, Path rootdir)
592 throws IOException, DeserializationException {
593 Path versionFile = new Path(rootdir, HConstants.VERSION_FILE_NAME);
594 FileStatus[] status = null;
595 try {
596
597
598 status = fs.listStatus(versionFile);
599 } catch (FileNotFoundException fnfe) {
600 return null;
601 }
602 if (status == null || status.length == 0) return null;
603 String version = null;
604 byte [] content = new byte [(int)status[0].getLen()];
605 FSDataInputStream s = fs.open(versionFile);
606 try {
607 IOUtils.readFully(s, content, 0, content.length);
608 if (ProtobufUtil.isPBMagicPrefix(content)) {
609 version = parseVersionFrom(content);
610 } else {
611
612 InputStream is = new ByteArrayInputStream(content);
613 DataInputStream dis = new DataInputStream(is);
614 try {
615 version = dis.readUTF();
616 } finally {
617 dis.close();
618 }
619 }
620 } catch (EOFException eof) {
621 LOG.warn("Version file was empty, odd, will try to set it.");
622 } finally {
623 s.close();
624 }
625 return version;
626 }
627
628
629
630
631
632
633
634 static String parseVersionFrom(final byte [] bytes)
635 throws DeserializationException {
636 ProtobufUtil.expectPBMagicPrefix(bytes);
637 int pblen = ProtobufUtil.lengthOfPBMagic();
638 FSProtos.HBaseVersionFileContent.Builder builder =
639 FSProtos.HBaseVersionFileContent.newBuilder();
640 try {
641 ProtobufUtil.mergeFrom(builder, bytes, pblen, bytes.length - pblen);
642 return builder.getVersion();
643 } catch (IOException e) {
644
645 throw new DeserializationException(e);
646 }
647 }
648
649
650
651
652
653
654 static byte [] toVersionByteArray(final String version) {
655 FSProtos.HBaseVersionFileContent.Builder builder =
656 FSProtos.HBaseVersionFileContent.newBuilder();
657 return ProtobufUtil.prependPBMagic(builder.setVersion(version).build().toByteArray());
658 }
659
660
661
662
663
664
665
666
667
668
669
670 public static void checkVersion(FileSystem fs, Path rootdir, boolean message)
671 throws IOException, DeserializationException {
672 checkVersion(fs, rootdir, message, 0, HConstants.DEFAULT_VERSION_FILE_WRITE_ATTEMPTS);
673 }
674
675
676
677
678
679
680
681
682
683
684
685
686
687 public static void checkVersion(FileSystem fs, Path rootdir,
688 boolean message, int wait, int retries)
689 throws IOException, DeserializationException {
690 String version = getVersion(fs, rootdir);
691 if (version == null) {
692 if (!metaRegionExists(fs, rootdir)) {
693
694
695 setVersion(fs, rootdir, wait, retries);
696 return;
697 }
698 } else if (version.compareTo(HConstants.FILE_SYSTEM_VERSION) == 0) return;
699
700
701
702 String msg = "HBase file layout needs to be upgraded."
703 + " You have version " + version
704 + " and I want version " + HConstants.FILE_SYSTEM_VERSION
705 + ". Consult http://hbase.apache.org/book.html for further information about upgrading HBase."
706 + " Is your hbase.rootdir valid? If so, you may need to run "
707 + "'hbase hbck -fixVersionFile'.";
708 if (message) {
709 System.out.println("WARNING! " + msg);
710 }
711 throw new FileSystemVersionException(msg);
712 }
713
714
715
716
717
718
719
720
721 public static void setVersion(FileSystem fs, Path rootdir)
722 throws IOException {
723 setVersion(fs, rootdir, HConstants.FILE_SYSTEM_VERSION, 0,
724 HConstants.DEFAULT_VERSION_FILE_WRITE_ATTEMPTS);
725 }
726
727
728
729
730
731
732
733
734
735
736 public static void setVersion(FileSystem fs, Path rootdir, int wait, int retries)
737 throws IOException {
738 setVersion(fs, rootdir, HConstants.FILE_SYSTEM_VERSION, wait, retries);
739 }
740
741
742
743
744
745
746
747
748
749
750
751
752 public static void setVersion(FileSystem fs, Path rootdir, String version,
753 int wait, int retries) throws IOException {
754 Path versionFile = new Path(rootdir, HConstants.VERSION_FILE_NAME);
755 Path tempVersionFile = new Path(rootdir, HConstants.HBASE_TEMP_DIRECTORY + Path.SEPARATOR +
756 HConstants.VERSION_FILE_NAME);
757 while (true) {
758 try {
759
760 FSDataOutputStream s = fs.create(tempVersionFile);
761 try {
762 s.write(toVersionByteArray(version));
763 s.close();
764 s = null;
765
766
767 if (!fs.rename(tempVersionFile, versionFile)) {
768 throw new IOException("Unable to move temp version file to " + versionFile);
769 }
770 } finally {
771
772
773
774
775
776 try {
777 if (s != null) s.close();
778 } catch (IOException ignore) { }
779 }
780 LOG.info("Created version file at " + rootdir.toString() + " with version=" + version);
781 return;
782 } catch (IOException e) {
783 if (retries > 0) {
784 LOG.debug("Unable to create version file at " + rootdir.toString() + ", retrying", e);
785 fs.delete(versionFile, false);
786 try {
787 if (wait > 0) {
788 Thread.sleep(wait);
789 }
790 } catch (InterruptedException ie) {
791 throw (InterruptedIOException)new InterruptedIOException().initCause(ie);
792 }
793 retries--;
794 } else {
795 throw e;
796 }
797 }
798 }
799 }
800
801
802
803
804
805
806
807
808
809 public static boolean checkClusterIdExists(FileSystem fs, Path rootdir,
810 int wait) throws IOException {
811 while (true) {
812 try {
813 Path filePath = new Path(rootdir, HConstants.CLUSTER_ID_FILE_NAME);
814 return fs.exists(filePath);
815 } catch (IOException ioe) {
816 if (wait > 0) {
817 LOG.warn("Unable to check cluster ID file in " + rootdir.toString() +
818 ", retrying in "+wait+"msec: "+StringUtils.stringifyException(ioe));
819 try {
820 Thread.sleep(wait);
821 } catch (InterruptedException e) {
822 throw (InterruptedIOException)new InterruptedIOException().initCause(e);
823 }
824 } else {
825 throw ioe;
826 }
827 }
828 }
829 }
830
831
832
833
834
835
836
837
838 public static ClusterId getClusterId(FileSystem fs, Path rootdir)
839 throws IOException {
840 Path idPath = new Path(rootdir, HConstants.CLUSTER_ID_FILE_NAME);
841 ClusterId clusterId = null;
842 FileStatus status = fs.exists(idPath)? fs.getFileStatus(idPath): null;
843 if (status != null) {
844 int len = Ints.checkedCast(status.getLen());
845 byte [] content = new byte[len];
846 FSDataInputStream in = fs.open(idPath);
847 try {
848 in.readFully(content);
849 } catch (EOFException eof) {
850 LOG.warn("Cluster ID file " + idPath.toString() + " was empty");
851 } finally{
852 in.close();
853 }
854 try {
855 clusterId = ClusterId.parseFrom(content);
856 } catch (DeserializationException e) {
857 throw new IOException("content=" + Bytes.toString(content), e);
858 }
859
860 if (!ProtobufUtil.isPBMagicPrefix(content)) {
861 String cid = null;
862 in = fs.open(idPath);
863 try {
864 cid = in.readUTF();
865 clusterId = new ClusterId(cid);
866 } catch (EOFException eof) {
867 LOG.warn("Cluster ID file " + idPath.toString() + " was empty");
868 } finally {
869 in.close();
870 }
871 rewriteAsPb(fs, rootdir, idPath, clusterId);
872 }
873 return clusterId;
874 } else {
875 LOG.warn("Cluster ID file does not exist at " + idPath.toString());
876 }
877 return clusterId;
878 }
879
880
881
882
883
884 private static void rewriteAsPb(final FileSystem fs, final Path rootdir, final Path p,
885 final ClusterId cid)
886 throws IOException {
887
888
889 Path movedAsideName = new Path(p + "." + System.currentTimeMillis());
890 if (!fs.rename(p, movedAsideName)) throw new IOException("Failed rename of " + p);
891 setClusterId(fs, rootdir, cid, 100);
892 if (!fs.delete(movedAsideName, false)) {
893 throw new IOException("Failed delete of " + movedAsideName);
894 }
895 LOG.debug("Rewrote the hbase.id file as pb");
896 }
897
898
899
900
901
902
903
904
905
906
907 public static void setClusterId(FileSystem fs, Path rootdir, ClusterId clusterId,
908 int wait) throws IOException {
909 while (true) {
910 try {
911 Path idFile = new Path(rootdir, HConstants.CLUSTER_ID_FILE_NAME);
912 Path tempIdFile = new Path(rootdir, HConstants.HBASE_TEMP_DIRECTORY +
913 Path.SEPARATOR + HConstants.CLUSTER_ID_FILE_NAME);
914
915 FSDataOutputStream s = fs.create(tempIdFile);
916 try {
917 s.write(clusterId.toByteArray());
918 s.close();
919 s = null;
920
921
922 if (!fs.rename(tempIdFile, idFile)) {
923 throw new IOException("Unable to move temp version file to " + idFile);
924 }
925 } finally {
926
927 try {
928 if (s != null) s.close();
929 } catch (IOException ignore) { }
930 }
931 if (LOG.isDebugEnabled()) {
932 LOG.debug("Created cluster ID file at " + idFile.toString() + " with ID: " + clusterId);
933 }
934 return;
935 } catch (IOException ioe) {
936 if (wait > 0) {
937 LOG.warn("Unable to create cluster ID file in " + rootdir.toString() +
938 ", retrying in " + wait + "msec: " + StringUtils.stringifyException(ioe));
939 try {
940 Thread.sleep(wait);
941 } catch (InterruptedException e) {
942 throw (InterruptedIOException)new InterruptedIOException().initCause(e);
943 }
944 } else {
945 throw ioe;
946 }
947 }
948 }
949 }
950
951
952
953
954
955
956
957
958 public static Path validateRootPath(Path root) throws IOException {
959 try {
960 URI rootURI = new URI(root.toString());
961 String scheme = rootURI.getScheme();
962 if (scheme == null) {
963 throw new IOException("Root directory does not have a scheme");
964 }
965 return root;
966 } catch (URISyntaxException e) {
967 IOException io = new IOException("Root directory path is not a valid " +
968 "URI -- check your " + HBASE_DIR + " configuration");
969 io.initCause(e);
970 throw io;
971 }
972 }
973
974
975
976
977
978
979
980
981
982 public static String removeWALRootPath(Path path, final Configuration conf) throws IOException {
983 Path root = getWALRootDir(conf);
984 String pathStr = path.toString();
985
986 if (!pathStr.startsWith(root.toString())) return pathStr;
987
988 return pathStr.substring(root.toString().length() + 1);
989 }
990
991
992
993
994
995
996
997 public static void waitOnSafeMode(final Configuration conf,
998 final long wait)
999 throws IOException {
1000 FileSystem fs = FileSystem.get(conf);
1001 if (!(fs instanceof DistributedFileSystem)) return;
1002 DistributedFileSystem dfs = (DistributedFileSystem)fs;
1003
1004 while (isInSafeMode(dfs)) {
1005 LOG.info("Waiting for dfs to exit safe mode...");
1006 try {
1007 Thread.sleep(wait);
1008 } catch (InterruptedException e) {
1009 throw (InterruptedIOException)new InterruptedIOException().initCause(e);
1010 }
1011 }
1012 }
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024 public static String getPath(Path p) {
1025 return p.toUri().getPath();
1026 }
1027
1028
1029
1030
1031
1032
1033
1034 public static Path getRootDir(final Configuration c) throws IOException {
1035 Path p = new Path(c.get(HBASE_DIR));
1036 FileSystem fs = p.getFileSystem(c);
1037 return p.makeQualified(fs);
1038 }
1039
1040 public static void setRootDir(final Configuration c, final Path root) throws IOException {
1041 c.set(HBASE_DIR, root.toString());
1042 }
1043
1044 public static void setFsDefault(final Configuration c, final Path root) throws IOException {
1045 c.set("fs.defaultFS", root.toString());
1046 }
1047
1048 public static FileSystem getRootDirFileSystem(final Configuration c) throws IOException {
1049 Path p = getRootDir(c);
1050 return p.getFileSystem(c);
1051 }
1052
1053
1054
1055
1056
1057
1058
1059 public static Path getWALRootDir(final Configuration c) throws IOException {
1060 Path p = new Path(c.get(HFileSystem.HBASE_WAL_DIR, c.get(HBASE_DIR)));
1061 if (!isValidWALRootDir(p, c)) {
1062 return FSUtils.getRootDir(c);
1063 }
1064 FileSystem fs = p.getFileSystem(c);
1065 return p.makeQualified(fs);
1066 }
1067
1068 @VisibleForTesting
1069 public static void setWALRootDir(final Configuration c, final Path root) throws IOException {
1070 c.set(HFileSystem.HBASE_WAL_DIR, root.toString());
1071 }
1072
1073 public static FileSystem getWALFileSystem(final Configuration c) throws IOException {
1074 Path p = getWALRootDir(c);
1075 return p.getFileSystem(c);
1076 }
1077
1078 private static boolean isValidWALRootDir(Path walDir, final Configuration c) throws IOException {
1079 Path rootDir = FSUtils.getRootDir(c);
1080 if (!walDir.equals(rootDir)) {
1081 if (walDir.toString().startsWith(rootDir.toString() + "/")) {
1082 throw new IllegalStateException("Illegal WAL directory specified. " +
1083 "WAL directories are not permitted to be under the root directory if set.");
1084 }
1085 }
1086 return true;
1087 }
1088
1089
1090
1091
1092
1093
1094
1095
1096 public static Path getWALRegionDir(final Configuration conf, final HRegionInfo regionInfo)
1097 throws IOException {
1098 return new Path(getWALTableDir(conf, regionInfo.getTable()),
1099 regionInfo.getEncodedName());
1100 }
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110 public static Path getWALRegionDir(final Configuration conf, final TableName tableName,
1111 final String encodedRegionName) throws IOException {
1112 return new Path(getWALTableDir(conf, tableName), encodedRegionName);
1113 }
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123 @SuppressWarnings("deprecation")
1124 public static boolean metaRegionExists(FileSystem fs, Path rootDir) throws IOException {
1125 Path metaRegionDir = getRegionDirFromRootDir(rootDir, HRegionInfo.FIRST_META_REGIONINFO);
1126 return fs.exists(metaRegionDir);
1127 }
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137 static public HDFSBlocksDistribution computeHDFSBlocksDistribution(
1138 final FileSystem fs, FileStatus status, long start, long length)
1139 throws IOException {
1140 HDFSBlocksDistribution blocksDistribution = new HDFSBlocksDistribution();
1141 BlockLocation [] blockLocations =
1142 fs.getFileBlockLocations(status, start, length);
1143 for(BlockLocation bl : blockLocations) {
1144 String [] hosts = bl.getHosts();
1145 long len = bl.getLength();
1146 blocksDistribution.addHostsAndBlockWeight(hosts, len);
1147 }
1148
1149 return blocksDistribution;
1150 }
1151
1152
1153
1154
1155
1156
1157 static public void addToHDFSBlocksDistribution(
1158 HDFSBlocksDistribution blocksDistribution, BlockLocation[] blockLocations)
1159 throws IOException {
1160 for (BlockLocation bl : blockLocations) {
1161 String[] hosts = bl.getHosts();
1162 long len = bl.getLength();
1163 blocksDistribution.addHostsAndBlockWeight(hosts, len);
1164 }
1165 }
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176 public static int getTotalTableFragmentation(final HMaster master)
1177 throws IOException {
1178 Map<String, Integer> map = getTableFragmentation(master);
1179 return map != null && map.size() > 0 ? map.get("-TOTAL-") : -1;
1180 }
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192 public static Map<String, Integer> getTableFragmentation(
1193 final HMaster master)
1194 throws IOException {
1195 Path path = getRootDir(master.getConfiguration());
1196
1197 FileSystem fs = path.getFileSystem(master.getConfiguration());
1198 return getTableFragmentation(fs, path);
1199 }
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211 public static Map<String, Integer> getTableFragmentation(
1212 final FileSystem fs, final Path hbaseRootDir)
1213 throws IOException {
1214 Map<String, Integer> frags = new HashMap<String, Integer>();
1215 int cfCountTotal = 0;
1216 int cfFragTotal = 0;
1217 PathFilter regionFilter = new RegionDirFilter(fs);
1218 PathFilter familyFilter = new FamilyDirFilter(fs);
1219 List<Path> tableDirs = getTableDirs(fs, hbaseRootDir);
1220 for (Path d : tableDirs) {
1221 int cfCount = 0;
1222 int cfFrag = 0;
1223 FileStatus[] regionDirs = fs.listStatus(d, regionFilter);
1224 for (FileStatus regionDir : regionDirs) {
1225 Path dd = regionDir.getPath();
1226
1227 FileStatus[] familyDirs = fs.listStatus(dd, familyFilter);
1228 for (FileStatus familyDir : familyDirs) {
1229 cfCount++;
1230 cfCountTotal++;
1231 Path family = familyDir.getPath();
1232
1233 FileStatus[] familyStatus = fs.listStatus(family);
1234 if (familyStatus.length > 1) {
1235 cfFrag++;
1236 cfFragTotal++;
1237 }
1238 }
1239 }
1240
1241 frags.put(FSUtils.getTableName(d).getNameAsString(),
1242 cfCount == 0? 0: Math.round((float) cfFrag / cfCount * 100));
1243 }
1244
1245 frags.put("-TOTAL-",
1246 cfCountTotal == 0? 0: Math.round((float) cfFragTotal / cfCountTotal * 100));
1247 return frags;
1248 }
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258 public static Path getTableDir(Path rootdir, final TableName tableName) {
1259 return new Path(getNamespaceDir(rootdir, tableName.getNamespaceAsString()),
1260 tableName.getQualifierAsString());
1261 }
1262
1263
1264
1265
1266
1267
1268
1269
1270 public static Path getWALTableDir(final Configuration conf, final TableName tableName)
1271 throws IOException {
1272 Path baseDir = new Path(getWALRootDir(conf), HConstants.BASE_NAMESPACE_DIR);
1273 return new Path(new Path(baseDir, tableName.getNamespaceAsString()),
1274 tableName.getQualifierAsString());
1275 }
1276
1277
1278
1279
1280
1281
1282 @Deprecated
1283 public static Path getWrongWALRegionDir(final Configuration conf, final TableName tableName,
1284 final String encodedRegionName) throws IOException {
1285 Path wrongTableDir = new Path(new Path(getWALRootDir(conf), tableName.getNamespaceAsString()),
1286 tableName.getQualifierAsString());
1287 return new Path(wrongTableDir, encodedRegionName);
1288 }
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298 public static TableName getTableName(Path tablePath) {
1299 return TableName.valueOf(tablePath.getParent().getName(), tablePath.getName());
1300 }
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310 public static Path getNamespaceDir(Path rootdir, final String namespace) {
1311 return new Path(rootdir, new Path(HConstants.BASE_NAMESPACE_DIR,
1312 new Path(namespace)));
1313 }
1314
1315
1316
1317
1318 static class FileFilter extends AbstractFileStatusFilter {
1319 private final FileSystem fs;
1320
1321 public FileFilter(final FileSystem fs) {
1322 this.fs = fs;
1323 }
1324
1325 @Override
1326 protected boolean accept(Path p, @CheckForNull Boolean isDir) {
1327 try {
1328 return isFile(fs, isDir, p);
1329 } catch (IOException e) {
1330 LOG.warn("unable to verify if path=" + p + " is a regular file", e);
1331 return false;
1332 }
1333 }
1334 }
1335
1336
1337
1338
1339 public static class BlackListDirFilter extends AbstractFileStatusFilter {
1340 private final FileSystem fs;
1341 private List<String> blacklist;
1342
1343
1344
1345
1346
1347
1348
1349 @SuppressWarnings("unchecked")
1350 public BlackListDirFilter(final FileSystem fs, final List<String> directoryNameBlackList) {
1351 this.fs = fs;
1352 blacklist =
1353 (List<String>) (directoryNameBlackList == null ? Collections.emptyList()
1354 : directoryNameBlackList);
1355 }
1356
1357 @Override
1358 protected boolean accept(Path p, @CheckForNull Boolean isDir) {
1359 if (!isValidName(p.getName())) {
1360 return false;
1361 }
1362
1363 try {
1364 return isDirectory(fs, isDir, p);
1365 } catch (IOException e) {
1366 LOG.warn("An error occurred while verifying if [" + p.toString()
1367 + "] is a valid directory. Returning 'not valid' and continuing.", e);
1368 return false;
1369 }
1370 }
1371
1372 protected boolean isValidName(final String name) {
1373 return !blacklist.contains(name);
1374 }
1375 }
1376
1377
1378
1379
1380 public static class DirFilter extends BlackListDirFilter {
1381
1382 public DirFilter(FileSystem fs) {
1383 super(fs, null);
1384 }
1385 }
1386
1387
1388
1389
1390
1391 public static class UserTableDirFilter extends BlackListDirFilter {
1392 public UserTableDirFilter(FileSystem fs) {
1393 super(fs, HConstants.HBASE_NON_TABLE_DIRS);
1394 }
1395
1396 @Override
1397 protected boolean isValidName(final String name) {
1398 if (!super.isValidName(name))
1399 return false;
1400
1401 try {
1402 TableName.isLegalTableQualifierName(Bytes.toBytes(name));
1403 } catch (IllegalArgumentException e) {
1404 LOG.info("INVALID NAME " + name);
1405 return false;
1406 }
1407 return true;
1408 }
1409 }
1410
1411
1412
1413
1414
1415
1416
1417
1418 public static boolean isAppendSupported(final Configuration conf) {
1419 boolean append = conf.getBoolean("dfs.support.append", false);
1420 if (append) {
1421 try {
1422
1423
1424
1425 SequenceFile.Writer.class.getMethod("syncFs", new Class<?> []{});
1426 append = true;
1427 } catch (SecurityException e) {
1428 } catch (NoSuchMethodException e) {
1429 append = false;
1430 }
1431 }
1432 if (!append) {
1433
1434 try {
1435 FSDataOutputStream.class.getMethod("hflush", new Class<?> []{});
1436 append = true;
1437 } catch (NoSuchMethodException e) {
1438 append = false;
1439 }
1440 }
1441 return append;
1442 }
1443
1444
1445
1446
1447
1448
1449 public static boolean isHDFS(final Configuration conf) throws IOException {
1450 FileSystem fs = FileSystem.get(conf);
1451 String scheme = fs.getUri().getScheme();
1452 return scheme.equalsIgnoreCase("hdfs");
1453 }
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463 public abstract void recoverFileLease(final FileSystem fs, final Path p,
1464 Configuration conf, CancelableProgressable reporter) throws IOException;
1465
1466 public static List<Path> getTableDirs(final FileSystem fs, final Path rootdir)
1467 throws IOException {
1468 List<Path> tableDirs = new LinkedList<Path>();
1469
1470 for(FileStatus status :
1471 fs.globStatus(new Path(rootdir,
1472 new Path(HConstants.BASE_NAMESPACE_DIR, "*")))) {
1473 tableDirs.addAll(FSUtils.getLocalTableDirs(fs, status.getPath()));
1474 }
1475 return tableDirs;
1476 }
1477
1478
1479
1480
1481
1482
1483
1484
1485 public static List<Path> getLocalTableDirs(final FileSystem fs, final Path rootdir)
1486 throws IOException {
1487
1488 FileStatus[] dirs = fs.listStatus(rootdir, new UserTableDirFilter(fs));
1489 List<Path> tabledirs = new ArrayList<Path>(dirs.length);
1490 for (FileStatus dir: dirs) {
1491 tabledirs.add(dir.getPath());
1492 }
1493 return tabledirs;
1494 }
1495
1496
1497
1498
1499
1500
1501 public static boolean isRecoveredEdits(Path path) {
1502 return path.toString().contains(HConstants.RECOVERED_EDITS_DIR);
1503 }
1504
1505
1506
1507
1508 public static class RegionDirFilter extends AbstractFileStatusFilter {
1509
1510 final public static Pattern regionDirPattern = Pattern.compile("^[0-9a-f]*$");
1511 final FileSystem fs;
1512
1513 public RegionDirFilter(FileSystem fs) {
1514 this.fs = fs;
1515 }
1516
1517 @Override
1518 protected boolean accept(Path p, @CheckForNull Boolean isDir) {
1519 if (!regionDirPattern.matcher(p.getName()).matches()) {
1520 return false;
1521 }
1522
1523 try {
1524 return isDirectory(fs, isDir, p);
1525 } catch (IOException ioe) {
1526
1527 LOG.warn("Skipping file " + p +" due to IOException", ioe);
1528 return false;
1529 }
1530 }
1531 }
1532
1533 public static Path getRegionDirFromRootDir(Path rootDir, HRegionInfo region) {
1534 return getRegionDirFromTableDir(getTableDir(rootDir, region.getTable()), region);
1535 }
1536
1537 public static Path getRegionDirFromTableDir(Path tableDir, HRegionInfo region) {
1538 return new Path(tableDir, ServerRegionReplicaUtil.getRegionInfoForFs(region).getEncodedName());
1539 }
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549 public static List<Path> getRegionDirs(final FileSystem fs, final Path tableDir) throws IOException {
1550
1551 List<FileStatus> rds = listStatusWithStatusFilter(fs, tableDir, new RegionDirFilter(fs));
1552 if (rds == null) {
1553 return new ArrayList<Path>();
1554 }
1555 List<Path> regionDirs = new ArrayList<Path>(rds.size());
1556 for (FileStatus rdfs: rds) {
1557 Path rdPath = rdfs.getPath();
1558 regionDirs.add(rdPath);
1559 }
1560 return regionDirs;
1561 }
1562
1563
1564
1565
1566
1567 public static class FamilyDirFilter extends AbstractFileStatusFilter {
1568 final FileSystem fs;
1569
1570 public FamilyDirFilter(FileSystem fs) {
1571 this.fs = fs;
1572 }
1573
1574 @Override
1575 protected boolean accept(Path p, @CheckForNull Boolean isDir) {
1576 try {
1577
1578 HColumnDescriptor.isLegalFamilyName(Bytes.toBytes(p.getName()));
1579 } catch (IllegalArgumentException iae) {
1580
1581 return false;
1582 }
1583
1584 try {
1585 return isDirectory(fs, isDir, p);
1586 } catch (IOException ioe) {
1587
1588 LOG.warn("Skipping file " + p +" due to IOException", ioe);
1589 return false;
1590 }
1591 }
1592 }
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602 public static List<Path> getFamilyDirs(final FileSystem fs, final Path regionDir) throws IOException {
1603
1604 FileStatus[] fds = fs.listStatus(regionDir, new FamilyDirFilter(fs));
1605 List<Path> familyDirs = new ArrayList<Path>(fds.length);
1606 for (FileStatus fdfs: fds) {
1607 Path fdPath = fdfs.getPath();
1608 familyDirs.add(fdPath);
1609 }
1610 return familyDirs;
1611 }
1612
1613 public static List<Path> getReferenceFilePaths(final FileSystem fs, final Path familyDir) throws IOException {
1614 List<FileStatus> fds = listStatusWithStatusFilter(fs, familyDir, new ReferenceFileFilter(fs));
1615 if (fds == null) {
1616 return new ArrayList<Path>();
1617 }
1618 List<Path> referenceFiles = new ArrayList<Path>(fds.size());
1619 for (FileStatus fdfs: fds) {
1620 Path fdPath = fdfs.getPath();
1621 referenceFiles.add(fdPath);
1622 }
1623 return referenceFiles;
1624 }
1625
1626
1627
1628
1629 public static class HFileFilter extends AbstractFileStatusFilter {
1630 final FileSystem fs;
1631
1632 public HFileFilter(FileSystem fs) {
1633 this.fs = fs;
1634 }
1635
1636 @Override
1637 protected boolean accept(Path p, @CheckForNull Boolean isDir) {
1638 if (!StoreFileInfo.isHFile(p)) {
1639 return false;
1640 }
1641
1642 try {
1643 return isFile(fs, isDir, p);
1644 } catch (IOException ioe) {
1645
1646 LOG.warn("Skipping file " + p +" due to IOException", ioe);
1647 return false;
1648 }
1649 }
1650 }
1651
1652
1653
1654
1655
1656 public static class HFileLinkFilter implements PathFilter {
1657
1658 @Override
1659 public boolean accept(Path p) {
1660 return HFileLink.isHFileLink(p);
1661 }
1662 }
1663
1664 public static class ReferenceFileFilter extends AbstractFileStatusFilter {
1665
1666 private final FileSystem fs;
1667
1668 public ReferenceFileFilter(FileSystem fs) {
1669 this.fs = fs;
1670 }
1671
1672 @Override
1673 protected boolean accept(Path p, @CheckForNull Boolean isDir) {
1674 if (!StoreFileInfo.isReference(p)) {
1675 return false;
1676 }
1677
1678 try {
1679
1680 return isFile(fs, isDir, p);
1681 } catch (IOException ioe) {
1682
1683 LOG.warn("Skipping file " + p +" due to IOException", ioe);
1684 return false;
1685 }
1686 }
1687 }
1688
1689
1690
1691
1692
1693
1694
1695 public static FileSystem getCurrentFileSystem(Configuration conf)
1696 throws IOException {
1697 return getRootDir(conf).getFileSystem(conf);
1698 }
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717 public static Map<String, Path> getTableStoreFilePathMap(Map<String, Path> map,
1718 final FileSystem fs, final Path hbaseRootDir, TableName tableName)
1719 throws IOException, InterruptedException {
1720 return getTableStoreFilePathMap(map, fs, hbaseRootDir, tableName, null, null, null);
1721 }
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745 public static Map<String, Path> getTableStoreFilePathMap(
1746 Map<String, Path> resultMap,
1747 final FileSystem fs, final Path hbaseRootDir, TableName tableName, final PathFilter sfFilter,
1748 ExecutorService executor, final ErrorReporter errors) throws IOException, InterruptedException {
1749
1750 final Map<String, Path> finalResultMap =
1751 resultMap == null ? new ConcurrentHashMap<String, Path>(128, 0.75f, 32) : resultMap;
1752
1753
1754 Path tableDir = FSUtils.getTableDir(hbaseRootDir, tableName);
1755
1756
1757 final FamilyDirFilter familyFilter = new FamilyDirFilter(fs);
1758 final Vector<Exception> exceptions = new Vector<Exception>();
1759
1760 try {
1761 List<FileStatus> regionDirs = FSUtils.listStatusWithStatusFilter(fs, tableDir, new RegionDirFilter(fs));
1762 if (regionDirs == null) {
1763 return finalResultMap;
1764 }
1765
1766 final List<Future<?>> futures = new ArrayList<Future<?>>(regionDirs.size());
1767
1768 for (FileStatus regionDir : regionDirs) {
1769 if (null != errors) {
1770 errors.progress();
1771 }
1772 final Path dd = regionDir.getPath();
1773
1774 if (!exceptions.isEmpty()) {
1775 break;
1776 }
1777
1778 Runnable getRegionStoreFileMapCall = new Runnable() {
1779 @Override
1780 public void run() {
1781 try {
1782 HashMap<String,Path> regionStoreFileMap = new HashMap<String, Path>();
1783 List<FileStatus> familyDirs = FSUtils.listStatusWithStatusFilter(fs, dd, familyFilter);
1784 if (familyDirs == null) {
1785 if (!fs.exists(dd)) {
1786 LOG.warn("Skipping region because it no longer exists: " + dd);
1787 } else {
1788 LOG.warn("Skipping region because it has no family dirs: " + dd);
1789 }
1790 return;
1791 }
1792 for (FileStatus familyDir : familyDirs) {
1793 if (null != errors) {
1794 errors.progress();
1795 }
1796 Path family = familyDir.getPath();
1797 if (family.getName().equals(HConstants.RECOVERED_EDITS_DIR)) {
1798 continue;
1799 }
1800
1801
1802 FileStatus[] familyStatus = fs.listStatus(family);
1803 for (FileStatus sfStatus : familyStatus) {
1804 if (null != errors) {
1805 errors.progress();
1806 }
1807 Path sf = sfStatus.getPath();
1808 if (sfFilter == null || sfFilter.accept(sf)) {
1809 regionStoreFileMap.put( sf.getName(), sf);
1810 }
1811 }
1812 }
1813 finalResultMap.putAll(regionStoreFileMap);
1814 } catch (Exception e) {
1815 LOG.error("Could not get region store file map for region: " + dd, e);
1816 exceptions.add(e);
1817 }
1818 }
1819 };
1820
1821
1822
1823 if (executor != null) {
1824 Future<?> future = executor.submit(getRegionStoreFileMapCall);
1825 futures.add(future);
1826 } else {
1827 FutureTask<?> future = new FutureTask<Object>(getRegionStoreFileMapCall, null);
1828 future.run();
1829 futures.add(future);
1830 }
1831 }
1832
1833
1834 for (Future<?> f : futures) {
1835 if (!exceptions.isEmpty()) {
1836 break;
1837 }
1838 try {
1839 f.get();
1840 } catch (ExecutionException e) {
1841 LOG.error("Unexpected exec exception! Should've been caught already. (Bug?)", e);
1842
1843 }
1844 }
1845 } catch (IOException e) {
1846 LOG.error("Cannot execute getTableStoreFilePathMap for " + tableName, e);
1847 exceptions.add(e);
1848 } finally {
1849 if (!exceptions.isEmpty()) {
1850
1851
1852 Throwables.propagateIfInstanceOf(exceptions.firstElement(), IOException.class);
1853 throw Throwables.propagate(exceptions.firstElement());
1854 }
1855 }
1856
1857 return finalResultMap;
1858 }
1859
1860 public static int getRegionReferenceFileCount(final FileSystem fs, final Path p) {
1861 int result = 0;
1862 try {
1863 for (Path familyDir:getFamilyDirs(fs, p)){
1864 result += getReferenceFilePaths(fs, familyDir).size();
1865 }
1866 } catch (IOException e) {
1867 LOG.warn("Error Counting reference files.", e);
1868 }
1869 return result;
1870 }
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886 public static Map<String, Path> getTableStoreFilePathMap(
1887 final FileSystem fs, final Path hbaseRootDir)
1888 throws IOException, InterruptedException {
1889 return getTableStoreFilePathMap(fs, hbaseRootDir, null, null, null);
1890 }
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909 public static Map<String, Path> getTableStoreFilePathMap(
1910 final FileSystem fs, final Path hbaseRootDir, PathFilter sfFilter,
1911 ExecutorService executor, ErrorReporter errors)
1912 throws IOException, InterruptedException {
1913 ConcurrentHashMap<String, Path> map = new ConcurrentHashMap<String, Path>(1024, 0.75f, 32);
1914
1915
1916
1917
1918
1919 for (Path tableDir : FSUtils.getTableDirs(fs, hbaseRootDir)) {
1920 getTableStoreFilePathMap(map, fs, hbaseRootDir,
1921 FSUtils.getTableName(tableDir), sfFilter, executor, errors);
1922 }
1923 return map;
1924 }
1925
1926
1927
1928
1929
1930
1931
1932
1933 public static List<FileStatus> filterFileStatuses(FileStatus[] input,
1934 FileStatusFilter filter) {
1935 if (input == null) return null;
1936 return filterFileStatuses(Iterators.forArray(input), filter);
1937 }
1938
1939
1940
1941
1942
1943
1944
1945
1946 public static List<FileStatus> filterFileStatuses(Iterator<FileStatus> input,
1947 FileStatusFilter filter) {
1948 if (input == null) return null;
1949 ArrayList<FileStatus> results = new ArrayList<FileStatus>();
1950 while (input.hasNext()) {
1951 FileStatus f = input.next();
1952 if (filter.accept(f)) {
1953 results.add(f);
1954 }
1955 }
1956 return results;
1957 }
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970 public static List<FileStatus> listStatusWithStatusFilter(final FileSystem fs,
1971 final Path dir, final FileStatusFilter filter) throws IOException {
1972 FileStatus [] status = null;
1973 try {
1974 status = fs.listStatus(dir);
1975 } catch (FileNotFoundException fnfe) {
1976
1977 if (LOG.isTraceEnabled()) {
1978 LOG.trace(dir + " doesn't exist");
1979 }
1980 }
1981
1982 if (status == null || status.length < 1) {
1983 return null;
1984 }
1985
1986 if (filter == null) {
1987 return Arrays.asList(status);
1988 } else {
1989 List<FileStatus> status2 = filterFileStatuses(status, filter);
1990 if (status2 == null || status2.isEmpty()) {
1991 return null;
1992 } else {
1993 return status2;
1994 }
1995 }
1996 }
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012 public static FileStatus [] listStatus(final FileSystem fs,
2013 final Path dir, final PathFilter filter) throws IOException {
2014 FileStatus [] status = null;
2015 try {
2016 status = filter == null ? fs.listStatus(dir) : fs.listStatus(dir, filter);
2017 } catch (FileNotFoundException fnfe) {
2018
2019 if (LOG.isTraceEnabled()) {
2020 LOG.trace(dir + " doesn't exist");
2021 }
2022 }
2023 if (status == null || status.length < 1) return null;
2024 return status;
2025 }
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035 public static FileStatus[] listStatus(final FileSystem fs, final Path dir) throws IOException {
2036 return listStatus(fs, dir, null);
2037 }
2038
2039
2040
2041
2042
2043
2044
2045
2046 public static List<LocatedFileStatus> listLocatedStatus(final FileSystem fs,
2047 final Path dir) throws IOException {
2048 List<LocatedFileStatus> status = null;
2049 try {
2050 RemoteIterator<LocatedFileStatus> locatedFileStatusRemoteIterator = fs
2051 .listFiles(dir, false);
2052 while (locatedFileStatusRemoteIterator.hasNext()) {
2053 if (status == null) {
2054 status = Lists.newArrayList();
2055 }
2056 status.add(locatedFileStatusRemoteIterator.next());
2057 }
2058 } catch (FileNotFoundException fnfe) {
2059
2060 if (LOG.isTraceEnabled()) {
2061 LOG.trace(dir + " doesn't exist");
2062 }
2063 }
2064 return status;
2065 }
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076 public static boolean delete(final FileSystem fs, final Path path, final boolean recursive)
2077 throws IOException {
2078 return fs.delete(path, recursive);
2079 }
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089 public static boolean isExists(final FileSystem fs, final Path path) throws IOException {
2090 return fs.exists(path);
2091 }
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103 public static void checkAccess(UserGroupInformation ugi, FileStatus file,
2104 FsAction action) throws AccessDeniedException {
2105 if (ugi.getShortUserName().equals(file.getOwner())) {
2106 if (file.getPermission().getUserAction().implies(action)) {
2107 return;
2108 }
2109 } else if (contains(ugi.getGroupNames(), file.getGroup())) {
2110 if (file.getPermission().getGroupAction().implies(action)) {
2111 return;
2112 }
2113 } else if (file.getPermission().getOtherAction().implies(action)) {
2114 return;
2115 }
2116 throw new AccessDeniedException("Permission denied:" + " action=" + action
2117 + " path=" + file.getPath() + " user=" + ugi.getShortUserName());
2118 }
2119
2120 private static boolean contains(String[] groups, String user) {
2121 for (String group : groups) {
2122 if (group.equals(user)) {
2123 return true;
2124 }
2125 }
2126 return false;
2127 }
2128
2129
2130
2131
2132
2133
2134
2135
2136 public static void logFileSystemState(final FileSystem fs, final Path root, Log LOG)
2137 throws IOException {
2138 LOG.debug("Current file system:");
2139 logFSTree(LOG, fs, root, "|-");
2140 }
2141
2142
2143
2144
2145
2146
2147 private static void logFSTree(Log LOG, final FileSystem fs, final Path root, String prefix)
2148 throws IOException {
2149 FileStatus[] files = FSUtils.listStatus(fs, root, null);
2150 if (files == null) return;
2151
2152 for (FileStatus file : files) {
2153 if (file.isDirectory()) {
2154 LOG.debug(prefix + file.getPath().getName() + "/");
2155 logFSTree(LOG, fs, file.getPath(), prefix + "---");
2156 } else {
2157 LOG.debug(prefix + file.getPath().getName());
2158 }
2159 }
2160 }
2161
2162 public static boolean renameAndSetModifyTime(final FileSystem fs, final Path src, final Path dest)
2163 throws IOException {
2164
2165 fs.setTimes(src, EnvironmentEdgeManager.currentTime(), -1);
2166 return fs.rename(src, dest);
2167 }
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182 public static Map<String, Map<String, Float>> getRegionDegreeLocalityMappingFromFS(
2183 final Configuration conf) throws IOException {
2184 return getRegionDegreeLocalityMappingFromFS(
2185 conf, null,
2186 conf.getInt(THREAD_POOLSIZE, DEFAULT_THREAD_POOLSIZE));
2187
2188 }
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206 public static Map<String, Map<String, Float>> getRegionDegreeLocalityMappingFromFS(
2207 final Configuration conf, final String desiredTable, int threadPoolSize)
2208 throws IOException {
2209 Map<String, Map<String, Float>> regionDegreeLocalityMapping =
2210 new ConcurrentHashMap<String, Map<String, Float>>();
2211 getRegionLocalityMappingFromFS(conf, desiredTable, threadPoolSize, null,
2212 regionDegreeLocalityMapping);
2213 return regionDegreeLocalityMapping;
2214 }
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236 private static void getRegionLocalityMappingFromFS(
2237 final Configuration conf, final String desiredTable,
2238 int threadPoolSize,
2239 Map<String, String> regionToBestLocalityRSMapping,
2240 Map<String, Map<String, Float>> regionDegreeLocalityMapping)
2241 throws IOException {
2242 FileSystem fs = FileSystem.get(conf);
2243 Path rootPath = FSUtils.getRootDir(conf);
2244 long startTime = EnvironmentEdgeManager.currentTime();
2245 Path queryPath;
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346 public static void setupShortCircuitRead(final Configuration conf) {
2347
2348 boolean shortCircuitSkipChecksum =
2349 conf.getBoolean("dfs.client.read.shortcircuit.skip.checksum", false);
2350 boolean useHBaseChecksum = conf.getBoolean(HConstants.HBASE_CHECKSUM_VERIFICATION, true);
2351 if (shortCircuitSkipChecksum) {
2352 LOG.warn("Configuration \"dfs.client.read.shortcircuit.skip.checksum\" should not " +
2353 "be set to true." + (useHBaseChecksum ? " HBase checksum doesn't require " +
2354 "it, see https://issues.apache.org/jira/browse/HBASE-6868." : ""));
2355 assert !shortCircuitSkipChecksum;
2356 }
2357 checkShortCircuitReadBufferSize(conf);
2358 }
2359
2360
2361
2362
2363
2364 public static void checkShortCircuitReadBufferSize(final Configuration conf) {
2365 final int defaultSize = HConstants.DEFAULT_BLOCKSIZE * 2;
2366 final int notSet = -1;
2367
2368 final String dfsKey = "dfs.client.read.shortcircuit.buffer.size";
2369 int size = conf.getInt(dfsKey, notSet);
2370
2371 if (size != notSet) return;
2372
2373 int hbaseSize = conf.getInt("hbase." + dfsKey, defaultSize);
2374 conf.setIfUnset(dfsKey, Integer.toString(hbaseSize));
2375 }
2376 }