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