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