001/** 002 * 003 * Licensed to the Apache Software Foundation (ASF) under one 004 * or more contributor license agreements. See the NOTICE file 005 * distributed with this work for additional information 006 * regarding copyright ownership. The ASF licenses this file 007 * to you under the Apache License, Version 2.0 (the 008 * "License"); you may not use this file except in compliance 009 * with the License. You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 */ 019package org.apache.hadoop.hbase.util; 020 021import java.io.FileNotFoundException; 022import java.io.IOException; 023import java.lang.reflect.InvocationTargetException; 024import java.lang.reflect.Method; 025import java.net.URI; 026import java.net.URISyntaxException; 027import java.util.List; 028import java.util.Locale; 029import java.util.Map; 030import java.util.concurrent.ConcurrentHashMap; 031 032import org.apache.hadoop.HadoopIllegalArgumentException; 033import org.apache.hadoop.conf.Configuration; 034import org.apache.hadoop.fs.FSDataOutputStream; 035import org.apache.hadoop.fs.FileStatus; 036import org.apache.hadoop.fs.FileSystem; 037import org.apache.hadoop.fs.LocatedFileStatus; 038import org.apache.hadoop.fs.Path; 039import org.apache.hadoop.fs.PathFilter; 040import org.apache.hadoop.fs.RemoteIterator; 041import org.apache.hadoop.fs.permission.FsPermission; 042import org.apache.hadoop.hbase.HConstants; 043import org.apache.hadoop.hbase.TableName; 044import org.apache.hadoop.ipc.RemoteException; 045import org.apache.yetus.audience.InterfaceAudience; 046import org.slf4j.Logger; 047import org.slf4j.LoggerFactory; 048 049import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting; 050import org.apache.hbase.thirdparty.com.google.common.collect.Lists; 051 052/** 053 * Utility methods for interacting with the underlying file system. 054 */ 055@InterfaceAudience.Private 056public abstract class CommonFSUtils { 057 private static final Logger LOG = LoggerFactory.getLogger(CommonFSUtils.class); 058 059 /** Parameter name for HBase WAL directory */ 060 public static final String HBASE_WAL_DIR = "hbase.wal.dir"; 061 062 /** Parameter to disable stream capability enforcement checks */ 063 public static final String UNSAFE_STREAM_CAPABILITY_ENFORCE = "hbase.unsafe.stream.capability.enforce"; 064 065 /** Full access permissions (starting point for a umask) */ 066 public static final String FULL_RWX_PERMISSIONS = "777"; 067 068 protected CommonFSUtils() { 069 super(); 070 } 071 072 /** 073 * Compare of path component. Does not consider schema; i.e. if schemas 074 * different but <code>path</code> starts with <code>rootPath</code>, 075 * then the function returns true 076 * @param rootPath value to check for 077 * @param path subject to check 078 * @return True if <code>path</code> starts with <code>rootPath</code> 079 */ 080 public static boolean isStartingWithPath(final Path rootPath, final String path) { 081 String uriRootPath = rootPath.toUri().getPath(); 082 String tailUriPath = (new Path(path)).toUri().getPath(); 083 return tailUriPath.startsWith(uriRootPath); 084 } 085 086 /** 087 * Compare path component of the Path URI; e.g. if hdfs://a/b/c and /a/b/c, it will compare the 088 * '/a/b/c' part. Does not consider schema; i.e. if schemas different but path or subpath matches, 089 * the two will equate. 090 * @param pathToSearch Path we will be trying to match against. 091 * @param pathTail what to match 092 * @return True if <code>pathTail</code> is tail on the path of <code>pathToSearch</code> 093 */ 094 public static boolean isMatchingTail(final Path pathToSearch, String pathTail) { 095 return isMatchingTail(pathToSearch, new Path(pathTail)); 096 } 097 098 /** 099 * Compare path component of the Path URI; e.g. if hdfs://a/b/c and /a/b/c, it will compare the 100 * '/a/b/c' part. If you passed in 'hdfs://a/b/c and b/c, it would return true. Does not consider 101 * schema; i.e. if schemas different but path or subpath matches, the two will equate. 102 * @param pathToSearch Path we will be trying to match agains against 103 * @param pathTail what to match 104 * @return True if <code>pathTail</code> is tail on the path of <code>pathToSearch</code> 105 */ 106 public static boolean isMatchingTail(final Path pathToSearch, final Path pathTail) { 107 if (pathToSearch.depth() != pathTail.depth()) { 108 return false; 109 } 110 Path tailPath = pathTail; 111 String tailName; 112 Path toSearch = pathToSearch; 113 String toSearchName; 114 boolean result = false; 115 do { 116 tailName = tailPath.getName(); 117 if (tailName == null || tailName.length() <= 0) { 118 result = true; 119 break; 120 } 121 toSearchName = toSearch.getName(); 122 if (toSearchName == null || toSearchName.length() <= 0) { 123 break; 124 } 125 // Move up a parent on each path for next go around. Path doesn't let us go off the end. 126 tailPath = tailPath.getParent(); 127 toSearch = toSearch.getParent(); 128 } while(tailName.equals(toSearchName)); 129 return result; 130 } 131 132 /** 133 * Delete if exists. 134 * @param fs filesystem object 135 * @param dir directory to delete 136 * @return True if deleted <code>dir</code> 137 * @throws IOException e 138 */ 139 public static boolean deleteDirectory(final FileSystem fs, final Path dir) 140 throws IOException { 141 return fs.exists(dir) && fs.delete(dir, true); 142 } 143 144 /** 145 * Return the number of bytes that large input files should be optimally 146 * be split into to minimize i/o time. 147 * 148 * use reflection to search for getDefaultBlockSize(Path f) 149 * if the method doesn't exist, fall back to using getDefaultBlockSize() 150 * 151 * @param fs filesystem object 152 * @return the default block size for the path's filesystem 153 * @throws IOException e 154 */ 155 public static long getDefaultBlockSize(final FileSystem fs, final Path path) throws IOException { 156 Method m = null; 157 Class<? extends FileSystem> cls = fs.getClass(); 158 try { 159 m = cls.getMethod("getDefaultBlockSize", new Class<?>[] { Path.class }); 160 } catch (NoSuchMethodException e) { 161 LOG.info("FileSystem doesn't support getDefaultBlockSize"); 162 } catch (SecurityException e) { 163 LOG.info("Doesn't have access to getDefaultBlockSize on FileSystems", e); 164 m = null; // could happen on setAccessible() 165 } 166 if (m == null) { 167 return fs.getDefaultBlockSize(path); 168 } else { 169 try { 170 Object ret = m.invoke(fs, path); 171 return ((Long)ret).longValue(); 172 } catch (Exception e) { 173 throw new IOException(e); 174 } 175 } 176 } 177 178 /* 179 * Get the default replication. 180 * 181 * use reflection to search for getDefaultReplication(Path f) 182 * if the method doesn't exist, fall back to using getDefaultReplication() 183 * 184 * @param fs filesystem object 185 * @param f path of file 186 * @return default replication for the path's filesystem 187 * @throws IOException e 188 */ 189 public static short getDefaultReplication(final FileSystem fs, final Path path) 190 throws IOException { 191 Method m = null; 192 Class<? extends FileSystem> cls = fs.getClass(); 193 try { 194 m = cls.getMethod("getDefaultReplication", new Class<?>[] { Path.class }); 195 } catch (NoSuchMethodException e) { 196 LOG.info("FileSystem doesn't support getDefaultReplication"); 197 } catch (SecurityException e) { 198 LOG.info("Doesn't have access to getDefaultReplication on FileSystems", e); 199 m = null; // could happen on setAccessible() 200 } 201 if (m == null) { 202 return fs.getDefaultReplication(path); 203 } else { 204 try { 205 Object ret = m.invoke(fs, path); 206 return ((Number)ret).shortValue(); 207 } catch (Exception e) { 208 throw new IOException(e); 209 } 210 } 211 } 212 213 /** 214 * Returns the default buffer size to use during writes. 215 * 216 * The size of the buffer should probably be a multiple of hardware 217 * page size (4096 on Intel x86), and it determines how much data is 218 * buffered during read and write operations. 219 * 220 * @param fs filesystem object 221 * @return default buffer size to use during writes 222 */ 223 public static int getDefaultBufferSize(final FileSystem fs) { 224 return fs.getConf().getInt("io.file.buffer.size", 4096); 225 } 226 227 /** 228 * Create the specified file on the filesystem. By default, this will: 229 * <ol> 230 * <li>apply the umask in the configuration (if it is enabled)</li> 231 * <li>use the fs configured buffer size (or 4096 if not set)</li> 232 * <li>use the default replication</li> 233 * <li>use the default block size</li> 234 * <li>not track progress</li> 235 * </ol> 236 * 237 * @param fs {@link FileSystem} on which to write the file 238 * @param path {@link Path} to the file to write 239 * @param perm intial permissions 240 * @param overwrite Whether or not the created file should be overwritten. 241 * @return output stream to the created file 242 * @throws IOException if the file cannot be created 243 */ 244 public static FSDataOutputStream create(FileSystem fs, Path path, 245 FsPermission perm, boolean overwrite) throws IOException { 246 if (LOG.isTraceEnabled()) { 247 LOG.trace("Creating file=" + path + " with permission=" + perm + ", overwrite=" + overwrite); 248 } 249 return fs.create(path, perm, overwrite, getDefaultBufferSize(fs), 250 getDefaultReplication(fs, path), getDefaultBlockSize(fs, path), null); 251 } 252 253 /** 254 * Get the file permissions specified in the configuration, if they are 255 * enabled. 256 * 257 * @param fs filesystem that the file will be created on. 258 * @param conf configuration to read for determining if permissions are 259 * enabled and which to use 260 * @param permssionConfKey property key in the configuration to use when 261 * finding the permission 262 * @return the permission to use when creating a new file on the fs. If 263 * special permissions are not specified in the configuration, then 264 * the default permissions on the the fs will be returned. 265 */ 266 public static FsPermission getFilePermissions(final FileSystem fs, 267 final Configuration conf, final String permssionConfKey) { 268 boolean enablePermissions = conf.getBoolean( 269 HConstants.ENABLE_DATA_FILE_UMASK, false); 270 271 if (enablePermissions) { 272 try { 273 FsPermission perm = new FsPermission(FULL_RWX_PERMISSIONS); 274 // make sure that we have a mask, if not, go default. 275 String mask = conf.get(permssionConfKey); 276 if (mask == null) { 277 return FsPermission.getFileDefault(); 278 } 279 // appy the umask 280 FsPermission umask = new FsPermission(mask); 281 return perm.applyUMask(umask); 282 } catch (IllegalArgumentException e) { 283 LOG.warn( 284 "Incorrect umask attempted to be created: " 285 + conf.get(permssionConfKey) 286 + ", using default file permissions.", e); 287 return FsPermission.getFileDefault(); 288 } 289 } 290 return FsPermission.getFileDefault(); 291 } 292 293 /** 294 * Verifies root directory path is a valid URI with a scheme 295 * 296 * @param root root directory path 297 * @return Passed <code>root</code> argument. 298 * @throws IOException if not a valid URI with a scheme 299 */ 300 public static Path validateRootPath(Path root) throws IOException { 301 try { 302 URI rootURI = new URI(root.toString()); 303 String scheme = rootURI.getScheme(); 304 if (scheme == null) { 305 throw new IOException("Root directory does not have a scheme"); 306 } 307 return root; 308 } catch (URISyntaxException e) { 309 IOException io = new IOException("Root directory path is not a valid " + 310 "URI -- check your " + HConstants.HBASE_DIR + " configuration"); 311 io.initCause(e); 312 throw io; 313 } 314 } 315 316 /** 317 * Checks for the presence of the WAL log root path (using the provided conf object) in the given 318 * path. If it exists, this method removes it and returns the String representation of remaining 319 * relative path. 320 * @param path must not be null 321 * @param conf must not be null 322 * @return String representation of the remaining relative path 323 * @throws IOException from underlying filesystem 324 */ 325 public static String removeWALRootPath(Path path, final Configuration conf) throws IOException { 326 Path root = getWALRootDir(conf); 327 String pathStr = path.toString(); 328 // check that the path is absolute... it has the root path in it. 329 if (!pathStr.startsWith(root.toString())) { 330 return pathStr; 331 } 332 // if not, return as it is. 333 return pathStr.substring(root.toString().length() + 1);// remove the "/" too. 334 } 335 336 /** 337 * Return the 'path' component of a Path. In Hadoop, Path is an URI. This 338 * method returns the 'path' component of a Path's URI: e.g. If a Path is 339 * <code>hdfs://example.org:9000/hbase_trunk/TestTable/compaction.dir</code>, 340 * this method returns <code>/hbase_trunk/TestTable/compaction.dir</code>. 341 * This method is useful if you want to print out a Path without qualifying 342 * Filesystem instance. 343 * @param p Filesystem Path whose 'path' component we are to return. 344 * @return Path portion of the Filesystem 345 */ 346 public static String getPath(Path p) { 347 return p.toUri().getPath(); 348 } 349 350 /** 351 * @param c configuration 352 * @return {@link Path} to hbase root directory from 353 * configuration as a qualified Path. 354 * @throws IOException e 355 */ 356 public static Path getRootDir(final Configuration c) throws IOException { 357 Path p = new Path(c.get(HConstants.HBASE_DIR)); 358 FileSystem fs = p.getFileSystem(c); 359 return p.makeQualified(fs.getUri(), fs.getWorkingDirectory()); 360 } 361 362 public static void setRootDir(final Configuration c, final Path root) throws IOException { 363 c.set(HConstants.HBASE_DIR, root.toString()); 364 } 365 366 public static void setFsDefault(final Configuration c, final Path root) throws IOException { 367 c.set("fs.defaultFS", root.toString()); // for hadoop 0.21+ 368 } 369 370 public static FileSystem getRootDirFileSystem(final Configuration c) throws IOException { 371 Path p = getRootDir(c); 372 return p.getFileSystem(c); 373 } 374 375 /** 376 * @param c configuration 377 * @return {@link Path} to hbase log root directory: e.g. {@value HBASE_WAL_DIR} from 378 * configuration as a qualified Path. Defaults to HBase root dir. 379 * @throws IOException e 380 */ 381 public static Path getWALRootDir(final Configuration c) throws IOException { 382 Path p = new Path(c.get(HBASE_WAL_DIR, c.get(HConstants.HBASE_DIR))); 383 if (!isValidWALRootDir(p, c)) { 384 return getRootDir(c); 385 } 386 FileSystem fs = p.getFileSystem(c); 387 return p.makeQualified(fs.getUri(), fs.getWorkingDirectory()); 388 } 389 390 @VisibleForTesting 391 public static void setWALRootDir(final Configuration c, final Path root) throws IOException { 392 c.set(HBASE_WAL_DIR, root.toString()); 393 } 394 395 public static FileSystem getWALFileSystem(final Configuration c) throws IOException { 396 Path p = getWALRootDir(c); 397 FileSystem fs = p.getFileSystem(c); 398 // hadoop-core does fs caching, so need to propogate this if set 399 String enforceStreamCapability = c.get(UNSAFE_STREAM_CAPABILITY_ENFORCE); 400 if (enforceStreamCapability != null) { 401 fs.getConf().set(UNSAFE_STREAM_CAPABILITY_ENFORCE, enforceStreamCapability); 402 } 403 return fs; 404 } 405 406 private static boolean isValidWALRootDir(Path walDir, final Configuration c) throws IOException { 407 Path rootDir = getRootDir(c); 408 FileSystem fs = walDir.getFileSystem(c); 409 Path qualifiedWalDir = walDir.makeQualified(fs.getUri(), fs.getWorkingDirectory()); 410 if (!qualifiedWalDir.equals(rootDir)) { 411 if (qualifiedWalDir.toString().startsWith(rootDir.toString() + "/")) { 412 throw new IllegalStateException("Illegal WAL directory specified. " + 413 "WAL directories are not permitted to be under the root directory if set."); 414 } 415 } 416 return true; 417 } 418 419 /** 420 * Returns the {@link org.apache.hadoop.fs.Path} object representing the table directory under 421 * path rootdir 422 * 423 * @param rootdir qualified path of HBase root directory 424 * @param tableName name of table 425 * @return {@link org.apache.hadoop.fs.Path} for table 426 */ 427 public static Path getTableDir(Path rootdir, final TableName tableName) { 428 return new Path(getNamespaceDir(rootdir, tableName.getNamespaceAsString()), 429 tableName.getQualifierAsString()); 430 } 431 432 /** 433 * Returns the {@link org.apache.hadoop.hbase.TableName} object representing 434 * the table directory under 435 * path rootdir 436 * 437 * @param tablePath path of table 438 * @return {@link org.apache.hadoop.fs.Path} for table 439 */ 440 public static TableName getTableName(Path tablePath) { 441 return TableName.valueOf(tablePath.getParent().getName(), tablePath.getName()); 442 } 443 444 /** 445 * Returns the {@link org.apache.hadoop.fs.Path} object representing 446 * the namespace directory under path rootdir 447 * 448 * @param rootdir qualified path of HBase root directory 449 * @param namespace namespace name 450 * @return {@link org.apache.hadoop.fs.Path} for table 451 */ 452 public static Path getNamespaceDir(Path rootdir, final String namespace) { 453 return new Path(rootdir, new Path(HConstants.BASE_NAMESPACE_DIR, 454 new Path(namespace))); 455 } 456 457 /** 458 * Sets storage policy for given path according to config setting. 459 * If the passed path is a directory, we'll set the storage policy for all files 460 * created in the future in said directory. Note that this change in storage 461 * policy takes place at the FileSystem level; it will persist beyond this RS's lifecycle. 462 * If we're running on a FileSystem implementation that doesn't support the given storage policy 463 * (or storage policies at all), then we'll issue a log message and continue. 464 * 465 * See http://hadoop.apache.org/docs/r2.6.0/hadoop-project-dist/hadoop-hdfs/ArchivalStorage.html 466 * 467 * @param fs We only do anything it implements a setStoragePolicy method 468 * @param conf used to look up storage policy with given key; not modified. 469 * @param path the Path whose storage policy is to be set 470 * @param policyKey Key to use pulling a policy from Configuration: 471 * e.g. HConstants.WAL_STORAGE_POLICY (hbase.wal.storage.policy). 472 * @param defaultPolicy if the configured policy is equal to this policy name, we will skip 473 * telling the FileSystem to set a storage policy. 474 */ 475 public static void setStoragePolicy(final FileSystem fs, final Configuration conf, 476 final Path path, final String policyKey, final String defaultPolicy) { 477 String storagePolicy = conf.get(policyKey, defaultPolicy).toUpperCase(Locale.ROOT); 478 if (storagePolicy.equals(defaultPolicy)) { 479 if (LOG.isTraceEnabled()) { 480 LOG.trace("default policy of " + defaultPolicy + " requested, exiting early."); 481 } 482 return; 483 } 484 setStoragePolicy(fs, path, storagePolicy); 485 } 486 487 // this mapping means that under a federated FileSystem implementation, we'll 488 // only log the first failure from any of the underlying FileSystems at WARN and all others 489 // will be at DEBUG. 490 private static final Map<FileSystem, Boolean> warningMap = 491 new ConcurrentHashMap<FileSystem, Boolean>(); 492 493 /** 494 * Sets storage policy for given path. 495 * If the passed path is a directory, we'll set the storage policy for all files 496 * created in the future in said directory. Note that this change in storage 497 * policy takes place at the FileSystem level; it will persist beyond this RS's lifecycle. 498 * If we're running on a version of FileSystem that doesn't support the given storage policy 499 * (or storage policies at all), then we'll issue a log message and continue. 500 * 501 * See http://hadoop.apache.org/docs/r2.6.0/hadoop-project-dist/hadoop-hdfs/ArchivalStorage.html 502 * 503 * @param fs We only do anything it implements a setStoragePolicy method 504 * @param path the Path whose storage policy is to be set 505 * @param storagePolicy Policy to set on <code>path</code>; see hadoop 2.6+ 506 * org.apache.hadoop.hdfs.protocol.HdfsConstants for possible list e.g 507 * 'COLD', 'WARM', 'HOT', 'ONE_SSD', 'ALL_SSD', 'LAZY_PERSIST'. 508 */ 509 public static void setStoragePolicy(final FileSystem fs, final Path path, 510 final String storagePolicy) { 511 if (storagePolicy == null) { 512 if (LOG.isTraceEnabled()) { 513 LOG.trace("We were passed a null storagePolicy, exiting early."); 514 } 515 return; 516 } 517 final String trimmedStoragePolicy = storagePolicy.trim(); 518 if (trimmedStoragePolicy.isEmpty()) { 519 if (LOG.isTraceEnabled()) { 520 LOG.trace("We were passed an empty storagePolicy, exiting early."); 521 } 522 return; 523 } 524 invokeSetStoragePolicy(fs, path, trimmedStoragePolicy); 525 } 526 527 /* 528 * All args have been checked and are good. Run the setStoragePolicy invocation. 529 */ 530 private static void invokeSetStoragePolicy(final FileSystem fs, final Path path, 531 final String storagePolicy) { 532 Method m = null; 533 try { 534 m = fs.getClass().getDeclaredMethod("setStoragePolicy", 535 new Class<?>[] { Path.class, String.class }); 536 m.setAccessible(true); 537 } catch (NoSuchMethodException e) { 538 final String msg = "FileSystem doesn't support setStoragePolicy; HDFS-6584, HDFS-9345 " + 539 "not available. This is normal and expected on earlier Hadoop versions."; 540 if (!warningMap.containsKey(fs)) { 541 warningMap.put(fs, true); 542 LOG.warn(msg, e); 543 } else if (LOG.isDebugEnabled()) { 544 LOG.debug(msg, e); 545 } 546 m = null; 547 } catch (SecurityException e) { 548 final String msg = "No access to setStoragePolicy on FileSystem from the SecurityManager; " + 549 "HDFS-6584, HDFS-9345 not available. This is unusual and probably warrants an email " + 550 "to the user@hbase mailing list. Please be sure to include a link to your configs, and " + 551 "logs that include this message and period of time before it. Logs around service " + 552 "start up will probably be useful as well."; 553 if (!warningMap.containsKey(fs)) { 554 warningMap.put(fs, true); 555 LOG.warn(msg, e); 556 } else if (LOG.isDebugEnabled()) { 557 LOG.debug(msg, e); 558 } 559 m = null; // could happen on setAccessible() or getDeclaredMethod() 560 } 561 if (m != null) { 562 try { 563 m.invoke(fs, path, storagePolicy); 564 if (LOG.isDebugEnabled()) { 565 LOG.debug("Set storagePolicy=" + storagePolicy + " for path=" + path); 566 } 567 } catch (Exception e) { 568 // This swallows FNFE, should we be throwing it? seems more likely to indicate dev 569 // misuse than a runtime problem with HDFS. 570 if (!warningMap.containsKey(fs)) { 571 warningMap.put(fs, true); 572 LOG.warn("Unable to set storagePolicy=" + storagePolicy + " for path=" + path + ". " + 573 "DEBUG log level might have more details.", e); 574 } else if (LOG.isDebugEnabled()) { 575 LOG.debug("Unable to set storagePolicy=" + storagePolicy + " for path=" + path, e); 576 } 577 // check for lack of HDFS-7228 578 if (e instanceof InvocationTargetException) { 579 final Throwable exception = e.getCause(); 580 if (exception instanceof RemoteException && 581 HadoopIllegalArgumentException.class.getName().equals( 582 ((RemoteException)exception).getClassName())) { 583 if (LOG.isDebugEnabled()) { 584 LOG.debug("Given storage policy, '" +storagePolicy +"', was rejected and probably " + 585 "isn't a valid policy for the version of Hadoop you're running. I.e. if you're " + 586 "trying to use SSD related policies then you're likely missing HDFS-7228. For " + 587 "more information see the 'ArchivalStorage' docs for your Hadoop release."); 588 } 589 // Hadoop 2.8+, 3.0-a1+ added FileSystem.setStoragePolicy with a default implementation 590 // that throws UnsupportedOperationException 591 } else if (exception instanceof UnsupportedOperationException) { 592 if (LOG.isDebugEnabled()) { 593 LOG.debug("The underlying FileSystem implementation doesn't support " + 594 "setStoragePolicy. This is probably intentional on their part, since HDFS-9345 " + 595 "appears to be present in your version of Hadoop. For more information check " + 596 "the Hadoop documentation on 'ArchivalStorage', the Hadoop FileSystem " + 597 "specification docs from HADOOP-11981, and/or related documentation from the " + 598 "provider of the underlying FileSystem (its name should appear in the " + 599 "stacktrace that accompanies this message). Note in particular that Hadoop's " + 600 "local filesystem implementation doesn't support storage policies.", exception); 601 } 602 } 603 } 604 } 605 } 606 } 607 608 /** 609 * @param conf must not be null 610 * @return True if this filesystem whose scheme is 'hdfs'. 611 * @throws IOException from underlying FileSystem 612 */ 613 public static boolean isHDFS(final Configuration conf) throws IOException { 614 FileSystem fs = FileSystem.get(conf); 615 String scheme = fs.getUri().getScheme(); 616 return scheme.equalsIgnoreCase("hdfs"); 617 } 618 619 /** 620 * Checks if the given path is the one with 'recovered.edits' dir. 621 * @param path must not be null 622 * @return True if we recovered edits 623 */ 624 public static boolean isRecoveredEdits(Path path) { 625 return path.toString().contains(HConstants.RECOVERED_EDITS_DIR); 626 } 627 628 /** 629 * @param conf must not be null 630 * @return Returns the filesystem of the hbase rootdir. 631 * @throws IOException from underlying FileSystem 632 */ 633 public static FileSystem getCurrentFileSystem(Configuration conf) 634 throws IOException { 635 return getRootDir(conf).getFileSystem(conf); 636 } 637 638 /** 639 * Calls fs.listStatus() and treats FileNotFoundException as non-fatal 640 * This accommodates differences between hadoop versions, where hadoop 1 641 * does not throw a FileNotFoundException, and return an empty FileStatus[] 642 * while Hadoop 2 will throw FileNotFoundException. 643 * 644 * Where possible, prefer FSUtils#listStatusWithStatusFilter(FileSystem, 645 * Path, FileStatusFilter) instead. 646 * 647 * @param fs file system 648 * @param dir directory 649 * @param filter path filter 650 * @return null if dir is empty or doesn't exist, otherwise FileStatus array 651 */ 652 public static FileStatus [] listStatus(final FileSystem fs, 653 final Path dir, final PathFilter filter) throws IOException { 654 FileStatus [] status = null; 655 try { 656 status = filter == null ? fs.listStatus(dir) : fs.listStatus(dir, filter); 657 } catch (FileNotFoundException fnfe) { 658 // if directory doesn't exist, return null 659 if (LOG.isTraceEnabled()) { 660 LOG.trace(dir + " doesn't exist"); 661 } 662 } 663 if (status == null || status.length < 1) { 664 return null; 665 } 666 return status; 667 } 668 669 /** 670 * Calls fs.listStatus() and treats FileNotFoundException as non-fatal 671 * This would accommodates differences between hadoop versions 672 * 673 * @param fs file system 674 * @param dir directory 675 * @return null if dir is empty or doesn't exist, otherwise FileStatus array 676 */ 677 public static FileStatus[] listStatus(final FileSystem fs, final Path dir) throws IOException { 678 return listStatus(fs, dir, null); 679 } 680 681 /** 682 * Calls fs.listFiles() to get FileStatus and BlockLocations together for reducing rpc call 683 * 684 * @param fs file system 685 * @param dir directory 686 * @return LocatedFileStatus list 687 */ 688 public static List<LocatedFileStatus> listLocatedStatus(final FileSystem fs, 689 final Path dir) throws IOException { 690 List<LocatedFileStatus> status = null; 691 try { 692 RemoteIterator<LocatedFileStatus> locatedFileStatusRemoteIterator = fs 693 .listFiles(dir, false); 694 while (locatedFileStatusRemoteIterator.hasNext()) { 695 if (status == null) { 696 status = Lists.newArrayList(); 697 } 698 status.add(locatedFileStatusRemoteIterator.next()); 699 } 700 } catch (FileNotFoundException fnfe) { 701 // if directory doesn't exist, return null 702 if (LOG.isTraceEnabled()) { 703 LOG.trace(dir + " doesn't exist"); 704 } 705 } 706 return status; 707 } 708 709 /** 710 * Calls fs.delete() and returns the value returned by the fs.delete() 711 * 712 * @param fs must not be null 713 * @param path must not be null 714 * @param recursive delete tree rooted at path 715 * @return the value returned by the fs.delete() 716 * @throws IOException from underlying FileSystem 717 */ 718 public static boolean delete(final FileSystem fs, final Path path, final boolean recursive) 719 throws IOException { 720 return fs.delete(path, recursive); 721 } 722 723 /** 724 * Calls fs.exists(). Checks if the specified path exists 725 * 726 * @param fs must not be null 727 * @param path must not be null 728 * @return the value returned by fs.exists() 729 * @throws IOException from underlying FileSystem 730 */ 731 public static boolean isExists(final FileSystem fs, final Path path) throws IOException { 732 return fs.exists(path); 733 } 734 735 /** 736 * Log the current state of the filesystem from a certain root directory 737 * @param fs filesystem to investigate 738 * @param root root file/directory to start logging from 739 * @param LOG log to output information 740 * @throws IOException if an unexpected exception occurs 741 */ 742 public static void logFileSystemState(final FileSystem fs, final Path root, Logger LOG) 743 throws IOException { 744 LOG.debug("File system contents for path " + root); 745 logFSTree(LOG, fs, root, "|-"); 746 } 747 748 /** 749 * Recursive helper to log the state of the FS 750 * 751 * @see #logFileSystemState(FileSystem, Path, Logger) 752 */ 753 private static void logFSTree(Logger LOG, final FileSystem fs, final Path root, String prefix) 754 throws IOException { 755 FileStatus[] files = listStatus(fs, root, null); 756 if (files == null) { 757 return; 758 } 759 760 for (FileStatus file : files) { 761 if (file.isDirectory()) { 762 LOG.debug(prefix + file.getPath().getName() + "/"); 763 logFSTree(LOG, fs, file.getPath(), prefix + "---"); 764 } else { 765 LOG.debug(prefix + file.getPath().getName()); 766 } 767 } 768 } 769 770 public static boolean renameAndSetModifyTime(final FileSystem fs, final Path src, final Path dest) 771 throws IOException { 772 // set the modify time for TimeToLive Cleaner 773 fs.setTimes(src, EnvironmentEdgeManager.currentTime(), -1); 774 return fs.rename(src, dest); 775 } 776 777 /** 778 * Do our short circuit read setup. 779 * Checks buffer size to use and whether to do checksumming in hbase or hdfs. 780 * @param conf must not be null 781 */ 782 public static void setupShortCircuitRead(final Configuration conf) { 783 // Check that the user has not set the "dfs.client.read.shortcircuit.skip.checksum" property. 784 boolean shortCircuitSkipChecksum = 785 conf.getBoolean("dfs.client.read.shortcircuit.skip.checksum", false); 786 boolean useHBaseChecksum = conf.getBoolean(HConstants.HBASE_CHECKSUM_VERIFICATION, true); 787 if (shortCircuitSkipChecksum) { 788 LOG.warn("Configuration \"dfs.client.read.shortcircuit.skip.checksum\" should not " + 789 "be set to true." + (useHBaseChecksum ? " HBase checksum doesn't require " + 790 "it, see https://issues.apache.org/jira/browse/HBASE-6868." : "")); 791 assert !shortCircuitSkipChecksum; //this will fail if assertions are on 792 } 793 checkShortCircuitReadBufferSize(conf); 794 } 795 796 /** 797 * Check if short circuit read buffer size is set and if not, set it to hbase value. 798 * @param conf must not be null 799 */ 800 public static void checkShortCircuitReadBufferSize(final Configuration conf) { 801 final int defaultSize = HConstants.DEFAULT_BLOCKSIZE * 2; 802 final int notSet = -1; 803 // DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_BUFFER_SIZE_KEY is only defined in h2 804 final String dfsKey = "dfs.client.read.shortcircuit.buffer.size"; 805 int size = conf.getInt(dfsKey, notSet); 806 // If a size is set, return -- we will use it. 807 if (size != notSet) { 808 return; 809 } 810 // But short circuit buffer size is normally not set. Put in place the hbase wanted size. 811 int hbaseSize = conf.getInt("hbase." + dfsKey, defaultSize); 812 conf.setIfUnset(dfsKey, Integer.toString(hbaseSize)); 813 } 814 815 // Holder singleton idiom. JVM spec ensures this will be run at most once per Classloader, and 816 // not until we attempt to reference it. 817 private static class StreamCapabilities { 818 public static final boolean PRESENT; 819 public static final Class<?> CLASS; 820 public static final Method METHOD; 821 static { 822 boolean tmp = false; 823 Class<?> clazz = null; 824 Method method = null; 825 try { 826 clazz = Class.forName("org.apache.hadoop.fs.StreamCapabilities"); 827 method = clazz.getMethod("hasCapability", String.class); 828 tmp = true; 829 } catch(ClassNotFoundException|NoSuchMethodException|SecurityException exception) { 830 LOG.warn("Your Hadoop installation does not include the StreamCapabilities class from " + 831 "HDFS-11644, so we will skip checking if any FSDataOutputStreams actually " + 832 "support hflush/hsync. If you are running on top of HDFS this probably just " + 833 "means you have an older version and this can be ignored. If you are running on " + 834 "top of an alternate FileSystem implementation you should manually verify that " + 835 "hflush and hsync are implemented; otherwise you risk data loss and hard to " + 836 "diagnose errors when our assumptions are violated."); 837 LOG.debug("The first request to check for StreamCapabilities came from this stacktrace.", 838 exception); 839 } finally { 840 PRESENT = tmp; 841 CLASS = clazz; 842 METHOD = method; 843 } 844 } 845 } 846 847 /** 848 * If our FileSystem version includes the StreamCapabilities class, check if 849 * the given stream has a particular capability. 850 * @param stream capabilities are per-stream instance, so check this one specifically. must not be 851 * null 852 * @param capability what to look for, per Hadoop Common's FileSystem docs 853 * @return true if there are no StreamCapabilities. false if there are, but this stream doesn't 854 * implement it. return result of asking the stream otherwise. 855 */ 856 public static boolean hasCapability(FSDataOutputStream stream, String capability) { 857 // be consistent whether or not StreamCapabilities is present 858 if (stream == null) { 859 throw new NullPointerException("stream parameter must not be null."); 860 } 861 // If o.a.h.fs.StreamCapabilities doesn't exist, assume everyone does everything 862 // otherwise old versions of Hadoop will break. 863 boolean result = true; 864 if (StreamCapabilities.PRESENT) { 865 // if StreamCapabilities is present, but the stream doesn't implement it 866 // or we run into a problem invoking the method, 867 // we treat that as equivalent to not declaring anything 868 result = false; 869 if (StreamCapabilities.CLASS.isAssignableFrom(stream.getClass())) { 870 try { 871 result = ((Boolean)StreamCapabilities.METHOD.invoke(stream, capability)).booleanValue(); 872 } catch (IllegalAccessException|IllegalArgumentException|InvocationTargetException 873 exception) { 874 LOG.warn("Your Hadoop installation's StreamCapabilities implementation doesn't match " + 875 "our understanding of how it's supposed to work. Please file a JIRA and include " + 876 "the following stack trace. In the mean time we're interpreting this behavior " + 877 "difference as a lack of capability support, which will probably cause a failure.", 878 exception); 879 } 880 } 881 } 882 return result; 883 } 884 885 /** 886 * Helper exception for those cases where the place where we need to check a stream capability 887 * is not where we have the needed context to explain the impact and mitigation for a lack. 888 */ 889 public static class StreamLacksCapabilityException extends Exception { 890 public StreamLacksCapabilityException(String message, Throwable cause) { 891 super(message, cause); 892 } 893 public StreamLacksCapabilityException(String message) { 894 super(message); 895 } 896 } 897 898}