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 org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting; 022import org.apache.hbase.thirdparty.com.google.common.base.Throwables; 023import org.apache.hbase.thirdparty.com.google.common.collect.Iterators; 024import org.apache.hbase.thirdparty.com.google.common.primitives.Ints; 025 026import edu.umd.cs.findbugs.annotations.CheckForNull; 027 028import java.io.ByteArrayInputStream; 029import java.io.DataInputStream; 030import java.io.EOFException; 031import java.io.FileNotFoundException; 032import java.io.IOException; 033import java.io.InputStream; 034import java.io.InterruptedIOException; 035import java.lang.reflect.InvocationTargetException; 036import java.lang.reflect.Method; 037import java.net.InetSocketAddress; 038import java.util.ArrayList; 039import java.util.Arrays; 040import java.util.Collections; 041import java.util.HashMap; 042import java.util.Iterator; 043import java.util.LinkedList; 044import java.util.List; 045import java.util.Locale; 046import java.util.Map; 047import java.util.Vector; 048import java.util.concurrent.ArrayBlockingQueue; 049import java.util.concurrent.ConcurrentHashMap; 050import java.util.concurrent.ExecutionException; 051import java.util.concurrent.ExecutorService; 052import java.util.concurrent.Future; 053import java.util.concurrent.FutureTask; 054import java.util.concurrent.ThreadPoolExecutor; 055import java.util.concurrent.TimeUnit; 056import java.util.regex.Pattern; 057 058import org.apache.hadoop.conf.Configuration; 059import org.apache.hadoop.fs.BlockLocation; 060import org.apache.hadoop.fs.FSDataInputStream; 061import org.apache.hadoop.fs.FSDataOutputStream; 062import org.apache.hadoop.fs.FileStatus; 063import org.apache.hadoop.fs.FileSystem; 064import org.apache.hadoop.fs.Path; 065import org.apache.hadoop.fs.PathFilter; 066import org.apache.hadoop.fs.permission.FsAction; 067import org.apache.hadoop.fs.permission.FsPermission; 068import org.apache.hadoop.hbase.ClusterId; 069import org.apache.hadoop.hbase.HColumnDescriptor; 070import org.apache.hadoop.hbase.HConstants; 071import org.apache.hadoop.hbase.HDFSBlocksDistribution; 072import org.apache.hadoop.hbase.HRegionInfo; 073import org.apache.hadoop.hbase.TableName; 074import org.apache.yetus.audience.InterfaceAudience; 075import org.slf4j.Logger; 076import org.slf4j.LoggerFactory; 077import org.apache.hadoop.hbase.exceptions.DeserializationException; 078import org.apache.hadoop.hbase.fs.HFileSystem; 079import org.apache.hadoop.hbase.io.HFileLink; 080import org.apache.hadoop.hbase.master.HMaster; 081import org.apache.hadoop.hbase.regionserver.HRegion; 082import org.apache.hadoop.hbase.regionserver.StoreFileInfo; 083import org.apache.hadoop.hbase.security.AccessDeniedException; 084import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil; 085import org.apache.hadoop.hbase.shaded.protobuf.generated.FSProtos; 086import org.apache.hadoop.hbase.util.HBaseFsck.ErrorReporter; 087import org.apache.hadoop.hdfs.DFSClient; 088import org.apache.hadoop.hdfs.DFSHedgedReadMetrics; 089import org.apache.hadoop.hdfs.DistributedFileSystem; 090import org.apache.hadoop.hdfs.protocol.HdfsConstants; 091import org.apache.hadoop.io.IOUtils; 092import org.apache.hadoop.ipc.RemoteException; 093import org.apache.hadoop.security.UserGroupInformation; 094import org.apache.hadoop.util.Progressable; 095import org.apache.hadoop.util.ReflectionUtils; 096import org.apache.hadoop.util.StringUtils; 097 098/** 099 * Utility methods for interacting with the underlying file system. 100 */ 101@InterfaceAudience.Private 102public abstract class FSUtils extends CommonFSUtils { 103 private static final Logger LOG = LoggerFactory.getLogger(FSUtils.class); 104 105 private static final String THREAD_POOLSIZE = "hbase.client.localityCheck.threadPoolSize"; 106 private static final int DEFAULT_THREAD_POOLSIZE = 2; 107 108 /** Set to true on Windows platforms */ 109 @VisibleForTesting // currently only used in testing. TODO refactor into a test class 110 public static final boolean WINDOWS = System.getProperty("os.name").startsWith("Windows"); 111 112 protected FSUtils() { 113 super(); 114 } 115 116 /** 117 * @return True is <code>fs</code> is instance of DistributedFileSystem 118 * @throws IOException 119 */ 120 public static boolean isDistributedFileSystem(final FileSystem fs) throws IOException { 121 FileSystem fileSystem = fs; 122 // If passed an instance of HFileSystem, it fails instanceof DistributedFileSystem. 123 // Check its backing fs for dfs-ness. 124 if (fs instanceof HFileSystem) { 125 fileSystem = ((HFileSystem)fs).getBackingFs(); 126 } 127 return fileSystem instanceof DistributedFileSystem; 128 } 129 130 /** 131 * Compare path component of the Path URI; e.g. if hdfs://a/b/c and /a/b/c, it will compare the 132 * '/a/b/c' part. If you passed in 'hdfs://a/b/c and b/c, it would return true. Does not consider 133 * schema; i.e. if schemas different but path or subpath matches, the two will equate. 134 * @param pathToSearch Path we will be trying to match. 135 * @param pathTail 136 * @return True if <code>pathTail</code> is tail on the path of <code>pathToSearch</code> 137 */ 138 public static boolean isMatchingTail(final Path pathToSearch, final Path pathTail) { 139 if (pathToSearch.depth() != pathTail.depth()) return false; 140 Path tailPath = pathTail; 141 String tailName; 142 Path toSearch = pathToSearch; 143 String toSearchName; 144 boolean result = false; 145 do { 146 tailName = tailPath.getName(); 147 if (tailName == null || tailName.length() <= 0) { 148 result = true; 149 break; 150 } 151 toSearchName = toSearch.getName(); 152 if (toSearchName == null || toSearchName.length() <= 0) break; 153 // Move up a parent on each path for next go around. Path doesn't let us go off the end. 154 tailPath = tailPath.getParent(); 155 toSearch = toSearch.getParent(); 156 } while(tailName.equals(toSearchName)); 157 return result; 158 } 159 160 public static FSUtils getInstance(FileSystem fs, Configuration conf) { 161 String scheme = fs.getUri().getScheme(); 162 if (scheme == null) { 163 LOG.warn("Could not find scheme for uri " + 164 fs.getUri() + ", default to hdfs"); 165 scheme = "hdfs"; 166 } 167 Class<?> fsUtilsClass = conf.getClass("hbase.fsutil." + 168 scheme + ".impl", FSHDFSUtils.class); // Default to HDFS impl 169 FSUtils fsUtils = (FSUtils)ReflectionUtils.newInstance(fsUtilsClass, conf); 170 return fsUtils; 171 } 172 173 /** 174 * Delete the region directory if exists. 175 * @param conf 176 * @param hri 177 * @return True if deleted the region directory. 178 * @throws IOException 179 */ 180 public static boolean deleteRegionDir(final Configuration conf, final HRegionInfo hri) 181 throws IOException { 182 Path rootDir = getRootDir(conf); 183 FileSystem fs = rootDir.getFileSystem(conf); 184 return deleteDirectory(fs, 185 new Path(getTableDir(rootDir, hri.getTable()), hri.getEncodedName())); 186 } 187 188 /** 189 * Create the specified file on the filesystem. By default, this will: 190 * <ol> 191 * <li>overwrite the file if it exists</li> 192 * <li>apply the umask in the configuration (if it is enabled)</li> 193 * <li>use the fs configured buffer size (or 4096 if not set)</li> 194 * <li>use the configured column family replication or default replication if 195 * {@link HColumnDescriptor#DEFAULT_DFS_REPLICATION}</li> 196 * <li>use the default block size</li> 197 * <li>not track progress</li> 198 * </ol> 199 * @param conf configurations 200 * @param fs {@link FileSystem} on which to write the file 201 * @param path {@link Path} to the file to write 202 * @param perm permissions 203 * @param favoredNodes 204 * @return output stream to the created file 205 * @throws IOException if the file cannot be created 206 */ 207 public static FSDataOutputStream create(Configuration conf, FileSystem fs, Path path, 208 FsPermission perm, InetSocketAddress[] favoredNodes) throws IOException { 209 if (fs instanceof HFileSystem) { 210 FileSystem backingFs = ((HFileSystem)fs).getBackingFs(); 211 if (backingFs instanceof DistributedFileSystem) { 212 // Try to use the favoredNodes version via reflection to allow backwards- 213 // compatibility. 214 short replication = Short.parseShort(conf.get(HColumnDescriptor.DFS_REPLICATION, 215 String.valueOf(HColumnDescriptor.DEFAULT_DFS_REPLICATION))); 216 try { 217 return (FSDataOutputStream) (DistributedFileSystem.class.getDeclaredMethod("create", 218 Path.class, FsPermission.class, boolean.class, int.class, short.class, long.class, 219 Progressable.class, InetSocketAddress[].class).invoke(backingFs, path, perm, true, 220 getDefaultBufferSize(backingFs), 221 replication > 0 ? replication : getDefaultReplication(backingFs, path), 222 getDefaultBlockSize(backingFs, path), null, favoredNodes)); 223 } catch (InvocationTargetException ite) { 224 // Function was properly called, but threw it's own exception. 225 throw new IOException(ite.getCause()); 226 } catch (NoSuchMethodException e) { 227 LOG.debug("DFS Client does not support most favored nodes create; using default create"); 228 if (LOG.isTraceEnabled()) LOG.trace("Ignoring; use default create", e); 229 } catch (IllegalArgumentException e) { 230 LOG.debug("Ignoring (most likely Reflection related exception) " + e); 231 } catch (SecurityException e) { 232 LOG.debug("Ignoring (most likely Reflection related exception) " + e); 233 } catch (IllegalAccessException e) { 234 LOG.debug("Ignoring (most likely Reflection related exception) " + e); 235 } 236 } 237 } 238 return create(fs, path, perm, true); 239 } 240 241 /** 242 * Checks to see if the specified file system is available 243 * 244 * @param fs filesystem 245 * @throws IOException e 246 */ 247 public static void checkFileSystemAvailable(final FileSystem fs) 248 throws IOException { 249 if (!(fs instanceof DistributedFileSystem)) { 250 return; 251 } 252 IOException exception = null; 253 DistributedFileSystem dfs = (DistributedFileSystem) fs; 254 try { 255 if (dfs.exists(new Path("/"))) { 256 return; 257 } 258 } catch (IOException e) { 259 exception = e instanceof RemoteException ? 260 ((RemoteException)e).unwrapRemoteException() : e; 261 } 262 try { 263 fs.close(); 264 } catch (Exception e) { 265 LOG.error("file system close failed: ", e); 266 } 267 IOException io = new IOException("File system is not available"); 268 io.initCause(exception); 269 throw io; 270 } 271 272 /** 273 * We use reflection because {@link DistributedFileSystem#setSafeMode( 274 * HdfsConstants.SafeModeAction action, boolean isChecked)} is not in hadoop 1.1 275 * 276 * @param dfs 277 * @return whether we're in safe mode 278 * @throws IOException 279 */ 280 private static boolean isInSafeMode(DistributedFileSystem dfs) throws IOException { 281 boolean inSafeMode = false; 282 try { 283 Method m = DistributedFileSystem.class.getMethod("setSafeMode", new Class<?> []{ 284 org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction.class, boolean.class}); 285 inSafeMode = (Boolean) m.invoke(dfs, 286 org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction.SAFEMODE_GET, true); 287 } catch (Exception e) { 288 if (e instanceof IOException) throw (IOException) e; 289 290 // Check whether dfs is on safemode. 291 inSafeMode = dfs.setSafeMode( 292 org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction.SAFEMODE_GET); 293 } 294 return inSafeMode; 295 } 296 297 /** 298 * Check whether dfs is in safemode. 299 * @param conf 300 * @throws IOException 301 */ 302 public static void checkDfsSafeMode(final Configuration conf) 303 throws IOException { 304 boolean isInSafeMode = false; 305 FileSystem fs = FileSystem.get(conf); 306 if (fs instanceof DistributedFileSystem) { 307 DistributedFileSystem dfs = (DistributedFileSystem)fs; 308 isInSafeMode = isInSafeMode(dfs); 309 } 310 if (isInSafeMode) { 311 throw new IOException("File system is in safemode, it can't be written now"); 312 } 313 } 314 315 /** 316 * Verifies current version of file system 317 * 318 * @param fs filesystem object 319 * @param rootdir root hbase directory 320 * @return null if no version file exists, version string otherwise. 321 * @throws IOException e 322 * @throws org.apache.hadoop.hbase.exceptions.DeserializationException 323 */ 324 public static String getVersion(FileSystem fs, Path rootdir) 325 throws IOException, DeserializationException { 326 Path versionFile = new Path(rootdir, HConstants.VERSION_FILE_NAME); 327 FileStatus[] status = null; 328 try { 329 // hadoop 2.0 throws FNFE if directory does not exist. 330 // hadoop 1.0 returns null if directory does not exist. 331 status = fs.listStatus(versionFile); 332 } catch (FileNotFoundException fnfe) { 333 return null; 334 } 335 if (status == null || status.length == 0) return null; 336 String version = null; 337 byte [] content = new byte [(int)status[0].getLen()]; 338 FSDataInputStream s = fs.open(versionFile); 339 try { 340 IOUtils.readFully(s, content, 0, content.length); 341 if (ProtobufUtil.isPBMagicPrefix(content)) { 342 version = parseVersionFrom(content); 343 } else { 344 // Presume it pre-pb format. 345 InputStream is = new ByteArrayInputStream(content); 346 DataInputStream dis = new DataInputStream(is); 347 try { 348 version = dis.readUTF(); 349 } finally { 350 dis.close(); 351 } 352 } 353 } catch (EOFException eof) { 354 LOG.warn("Version file was empty, odd, will try to set it."); 355 } finally { 356 s.close(); 357 } 358 return version; 359 } 360 361 /** 362 * Parse the content of the ${HBASE_ROOTDIR}/hbase.version file. 363 * @param bytes The byte content of the hbase.version file. 364 * @return The version found in the file as a String. 365 * @throws DeserializationException 366 */ 367 static String parseVersionFrom(final byte [] bytes) 368 throws DeserializationException { 369 ProtobufUtil.expectPBMagicPrefix(bytes); 370 int pblen = ProtobufUtil.lengthOfPBMagic(); 371 FSProtos.HBaseVersionFileContent.Builder builder = 372 FSProtos.HBaseVersionFileContent.newBuilder(); 373 try { 374 ProtobufUtil.mergeFrom(builder, bytes, pblen, bytes.length - pblen); 375 return builder.getVersion(); 376 } catch (IOException e) { 377 // Convert 378 throw new DeserializationException(e); 379 } 380 } 381 382 /** 383 * Create the content to write into the ${HBASE_ROOTDIR}/hbase.version file. 384 * @param version Version to persist 385 * @return Serialized protobuf with <code>version</code> content and a bit of pb magic for a prefix. 386 */ 387 static byte [] toVersionByteArray(final String version) { 388 FSProtos.HBaseVersionFileContent.Builder builder = 389 FSProtos.HBaseVersionFileContent.newBuilder(); 390 return ProtobufUtil.prependPBMagic(builder.setVersion(version).build().toByteArray()); 391 } 392 393 /** 394 * Verifies current version of file system 395 * 396 * @param fs file system 397 * @param rootdir root directory of HBase installation 398 * @param message if true, issues a message on System.out 399 * 400 * @throws IOException e 401 * @throws DeserializationException 402 */ 403 public static void checkVersion(FileSystem fs, Path rootdir, boolean message) 404 throws IOException, DeserializationException { 405 checkVersion(fs, rootdir, message, 0, HConstants.DEFAULT_VERSION_FILE_WRITE_ATTEMPTS); 406 } 407 408 /** 409 * Verifies current version of file system 410 * 411 * @param fs file system 412 * @param rootdir root directory of HBase installation 413 * @param message if true, issues a message on System.out 414 * @param wait wait interval 415 * @param retries number of times to retry 416 * 417 * @throws IOException e 418 * @throws DeserializationException 419 */ 420 public static void checkVersion(FileSystem fs, Path rootdir, 421 boolean message, int wait, int retries) 422 throws IOException, DeserializationException { 423 String version = getVersion(fs, rootdir); 424 if (version == null) { 425 if (!metaRegionExists(fs, rootdir)) { 426 // rootDir is empty (no version file and no root region) 427 // just create new version file (HBASE-1195) 428 setVersion(fs, rootdir, wait, retries); 429 return; 430 } 431 } else if (version.compareTo(HConstants.FILE_SYSTEM_VERSION) == 0) return; 432 433 // version is deprecated require migration 434 // Output on stdout so user sees it in terminal. 435 String msg = "HBase file layout needs to be upgraded." 436 + " You have version " + version 437 + " and I want version " + HConstants.FILE_SYSTEM_VERSION 438 + ". Consult http://hbase.apache.org/book.html for further information about upgrading HBase." 439 + " Is your hbase.rootdir valid? If so, you may need to run " 440 + "'hbase hbck -fixVersionFile'."; 441 if (message) { 442 System.out.println("WARNING! " + msg); 443 } 444 throw new FileSystemVersionException(msg); 445 } 446 447 /** 448 * Sets version of file system 449 * 450 * @param fs filesystem object 451 * @param rootdir hbase root 452 * @throws IOException e 453 */ 454 public static void setVersion(FileSystem fs, Path rootdir) 455 throws IOException { 456 setVersion(fs, rootdir, HConstants.FILE_SYSTEM_VERSION, 0, 457 HConstants.DEFAULT_VERSION_FILE_WRITE_ATTEMPTS); 458 } 459 460 /** 461 * Sets version of file system 462 * 463 * @param fs filesystem object 464 * @param rootdir hbase root 465 * @param wait time to wait for retry 466 * @param retries number of times to retry before failing 467 * @throws IOException e 468 */ 469 public static void setVersion(FileSystem fs, Path rootdir, int wait, int retries) 470 throws IOException { 471 setVersion(fs, rootdir, HConstants.FILE_SYSTEM_VERSION, wait, retries); 472 } 473 474 475 /** 476 * Sets version of file system 477 * 478 * @param fs filesystem object 479 * @param rootdir hbase root directory 480 * @param version version to set 481 * @param wait time to wait for retry 482 * @param retries number of times to retry before throwing an IOException 483 * @throws IOException e 484 */ 485 public static void setVersion(FileSystem fs, Path rootdir, String version, 486 int wait, int retries) throws IOException { 487 Path versionFile = new Path(rootdir, HConstants.VERSION_FILE_NAME); 488 Path tempVersionFile = new Path(rootdir, HConstants.HBASE_TEMP_DIRECTORY + Path.SEPARATOR + 489 HConstants.VERSION_FILE_NAME); 490 while (true) { 491 try { 492 // Write the version to a temporary file 493 FSDataOutputStream s = fs.create(tempVersionFile); 494 try { 495 s.write(toVersionByteArray(version)); 496 s.close(); 497 s = null; 498 // Move the temp version file to its normal location. Returns false 499 // if the rename failed. Throw an IOE in that case. 500 if (!fs.rename(tempVersionFile, versionFile)) { 501 throw new IOException("Unable to move temp version file to " + versionFile); 502 } 503 } finally { 504 // Cleaning up the temporary if the rename failed would be trying 505 // too hard. We'll unconditionally create it again the next time 506 // through anyway, files are overwritten by default by create(). 507 508 // Attempt to close the stream on the way out if it is still open. 509 try { 510 if (s != null) s.close(); 511 } catch (IOException ignore) { } 512 } 513 LOG.info("Created version file at " + rootdir.toString() + " with version=" + version); 514 return; 515 } catch (IOException e) { 516 if (retries > 0) { 517 LOG.debug("Unable to create version file at " + rootdir.toString() + ", retrying", e); 518 fs.delete(versionFile, false); 519 try { 520 if (wait > 0) { 521 Thread.sleep(wait); 522 } 523 } catch (InterruptedException ie) { 524 throw (InterruptedIOException)new InterruptedIOException().initCause(ie); 525 } 526 retries--; 527 } else { 528 throw e; 529 } 530 } 531 } 532 } 533 534 /** 535 * Checks that a cluster ID file exists in the HBase root directory 536 * @param fs the root directory FileSystem 537 * @param rootdir the HBase root directory in HDFS 538 * @param wait how long to wait between retries 539 * @return <code>true</code> if the file exists, otherwise <code>false</code> 540 * @throws IOException if checking the FileSystem fails 541 */ 542 public static boolean checkClusterIdExists(FileSystem fs, Path rootdir, 543 int wait) throws IOException { 544 while (true) { 545 try { 546 Path filePath = new Path(rootdir, HConstants.CLUSTER_ID_FILE_NAME); 547 return fs.exists(filePath); 548 } catch (IOException ioe) { 549 if (wait > 0) { 550 LOG.warn("Unable to check cluster ID file in " + rootdir.toString() + 551 ", retrying in "+wait+"msec: "+StringUtils.stringifyException(ioe)); 552 try { 553 Thread.sleep(wait); 554 } catch (InterruptedException e) { 555 throw (InterruptedIOException)new InterruptedIOException().initCause(e); 556 } 557 } else { 558 throw ioe; 559 } 560 } 561 } 562 } 563 564 /** 565 * Returns the value of the unique cluster ID stored for this HBase instance. 566 * @param fs the root directory FileSystem 567 * @param rootdir the path to the HBase root directory 568 * @return the unique cluster identifier 569 * @throws IOException if reading the cluster ID file fails 570 */ 571 public static ClusterId getClusterId(FileSystem fs, Path rootdir) 572 throws IOException { 573 Path idPath = new Path(rootdir, HConstants.CLUSTER_ID_FILE_NAME); 574 ClusterId clusterId = null; 575 FileStatus status = fs.exists(idPath)? fs.getFileStatus(idPath): null; 576 if (status != null) { 577 int len = Ints.checkedCast(status.getLen()); 578 byte [] content = new byte[len]; 579 FSDataInputStream in = fs.open(idPath); 580 try { 581 in.readFully(content); 582 } catch (EOFException eof) { 583 LOG.warn("Cluster ID file " + idPath.toString() + " was empty"); 584 } finally{ 585 in.close(); 586 } 587 try { 588 clusterId = ClusterId.parseFrom(content); 589 } catch (DeserializationException e) { 590 throw new IOException("content=" + Bytes.toString(content), e); 591 } 592 // If not pb'd, make it so. 593 if (!ProtobufUtil.isPBMagicPrefix(content)) { 594 String cid = null; 595 in = fs.open(idPath); 596 try { 597 cid = in.readUTF(); 598 clusterId = new ClusterId(cid); 599 } catch (EOFException eof) { 600 LOG.warn("Cluster ID file " + idPath.toString() + " was empty"); 601 } finally { 602 in.close(); 603 } 604 rewriteAsPb(fs, rootdir, idPath, clusterId); 605 } 606 return clusterId; 607 } else { 608 LOG.warn("Cluster ID file does not exist at " + idPath.toString()); 609 } 610 return clusterId; 611 } 612 613 /** 614 * @param cid 615 * @throws IOException 616 */ 617 private static void rewriteAsPb(final FileSystem fs, final Path rootdir, final Path p, 618 final ClusterId cid) 619 throws IOException { 620 // Rewrite the file as pb. Move aside the old one first, write new 621 // then delete the moved-aside file. 622 Path movedAsideName = new Path(p + "." + System.currentTimeMillis()); 623 if (!fs.rename(p, movedAsideName)) throw new IOException("Failed rename of " + p); 624 setClusterId(fs, rootdir, cid, 100); 625 if (!fs.delete(movedAsideName, false)) { 626 throw new IOException("Failed delete of " + movedAsideName); 627 } 628 LOG.debug("Rewrote the hbase.id file as pb"); 629 } 630 631 /** 632 * Writes a new unique identifier for this cluster to the "hbase.id" file 633 * in the HBase root directory 634 * @param fs the root directory FileSystem 635 * @param rootdir the path to the HBase root directory 636 * @param clusterId the unique identifier to store 637 * @param wait how long (in milliseconds) to wait between retries 638 * @throws IOException if writing to the FileSystem fails and no wait value 639 */ 640 public static void setClusterId(FileSystem fs, Path rootdir, ClusterId clusterId, 641 int wait) throws IOException { 642 while (true) { 643 try { 644 Path idFile = new Path(rootdir, HConstants.CLUSTER_ID_FILE_NAME); 645 Path tempIdFile = new Path(rootdir, HConstants.HBASE_TEMP_DIRECTORY + 646 Path.SEPARATOR + HConstants.CLUSTER_ID_FILE_NAME); 647 // Write the id file to a temporary location 648 FSDataOutputStream s = fs.create(tempIdFile); 649 try { 650 s.write(clusterId.toByteArray()); 651 s.close(); 652 s = null; 653 // Move the temporary file to its normal location. Throw an IOE if 654 // the rename failed 655 if (!fs.rename(tempIdFile, idFile)) { 656 throw new IOException("Unable to move temp version file to " + idFile); 657 } 658 } finally { 659 // Attempt to close the stream if still open on the way out 660 try { 661 if (s != null) s.close(); 662 } catch (IOException ignore) { } 663 } 664 if (LOG.isDebugEnabled()) { 665 LOG.debug("Created cluster ID file at " + idFile.toString() + " with ID: " + clusterId); 666 } 667 return; 668 } catch (IOException ioe) { 669 if (wait > 0) { 670 LOG.warn("Unable to create cluster ID file in " + rootdir.toString() + 671 ", retrying in " + wait + "msec: " + StringUtils.stringifyException(ioe)); 672 try { 673 Thread.sleep(wait); 674 } catch (InterruptedException e) { 675 throw (InterruptedIOException)new InterruptedIOException().initCause(e); 676 } 677 } else { 678 throw ioe; 679 } 680 } 681 } 682 } 683 684 /** 685 * If DFS, check safe mode and if so, wait until we clear it. 686 * @param conf configuration 687 * @param wait Sleep between retries 688 * @throws IOException e 689 */ 690 public static void waitOnSafeMode(final Configuration conf, 691 final long wait) 692 throws IOException { 693 FileSystem fs = FileSystem.get(conf); 694 if (!(fs instanceof DistributedFileSystem)) return; 695 DistributedFileSystem dfs = (DistributedFileSystem)fs; 696 // Make sure dfs is not in safe mode 697 while (isInSafeMode(dfs)) { 698 LOG.info("Waiting for dfs to exit safe mode..."); 699 try { 700 Thread.sleep(wait); 701 } catch (InterruptedException e) { 702 throw (InterruptedIOException)new InterruptedIOException().initCause(e); 703 } 704 } 705 } 706 707 /** 708 * Checks if meta region exists 709 * 710 * @param fs file system 711 * @param rootdir root directory of HBase installation 712 * @return true if exists 713 * @throws IOException e 714 */ 715 @SuppressWarnings("deprecation") 716 public static boolean metaRegionExists(FileSystem fs, Path rootdir) 717 throws IOException { 718 Path metaRegionDir = 719 HRegion.getRegionDir(rootdir, HRegionInfo.FIRST_META_REGIONINFO); 720 return fs.exists(metaRegionDir); 721 } 722 723 /** 724 * Compute HDFS blocks distribution of a given file, or a portion of the file 725 * @param fs file system 726 * @param status file status of the file 727 * @param start start position of the portion 728 * @param length length of the portion 729 * @return The HDFS blocks distribution 730 */ 731 static public HDFSBlocksDistribution computeHDFSBlocksDistribution( 732 final FileSystem fs, FileStatus status, long start, long length) 733 throws IOException { 734 HDFSBlocksDistribution blocksDistribution = new HDFSBlocksDistribution(); 735 BlockLocation [] blockLocations = 736 fs.getFileBlockLocations(status, start, length); 737 for(BlockLocation bl : blockLocations) { 738 String [] hosts = bl.getHosts(); 739 long len = bl.getLength(); 740 blocksDistribution.addHostsAndBlockWeight(hosts, len); 741 } 742 743 return blocksDistribution; 744 } 745 746 /** 747 * Update blocksDistribution with blockLocations 748 * @param blocksDistribution the hdfs blocks distribution 749 * @param blockLocations an array containing block location 750 */ 751 static public void addToHDFSBlocksDistribution( 752 HDFSBlocksDistribution blocksDistribution, BlockLocation[] blockLocations) 753 throws IOException { 754 for (BlockLocation bl : blockLocations) { 755 String[] hosts = bl.getHosts(); 756 long len = bl.getLength(); 757 blocksDistribution.addHostsAndBlockWeight(hosts, len); 758 } 759 } 760 761 // TODO move this method OUT of FSUtils. No dependencies to HMaster 762 /** 763 * Returns the total overall fragmentation percentage. Includes hbase:meta and 764 * -ROOT- as well. 765 * 766 * @param master The master defining the HBase root and file system. 767 * @return A map for each table and its percentage. 768 * @throws IOException When scanning the directory fails. 769 */ 770 public static int getTotalTableFragmentation(final HMaster master) 771 throws IOException { 772 Map<String, Integer> map = getTableFragmentation(master); 773 return map != null && map.size() > 0 ? map.get("-TOTAL-") : -1; 774 } 775 776 /** 777 * Runs through the HBase rootdir and checks how many stores for each table 778 * have more than one file in them. Checks -ROOT- and hbase:meta too. The total 779 * percentage across all tables is stored under the special key "-TOTAL-". 780 * 781 * @param master The master defining the HBase root and file system. 782 * @return A map for each table and its percentage. 783 * 784 * @throws IOException When scanning the directory fails. 785 */ 786 public static Map<String, Integer> getTableFragmentation( 787 final HMaster master) 788 throws IOException { 789 Path path = getRootDir(master.getConfiguration()); 790 // since HMaster.getFileSystem() is package private 791 FileSystem fs = path.getFileSystem(master.getConfiguration()); 792 return getTableFragmentation(fs, path); 793 } 794 795 /** 796 * Runs through the HBase rootdir and checks how many stores for each table 797 * have more than one file in them. Checks -ROOT- and hbase:meta too. The total 798 * percentage across all tables is stored under the special key "-TOTAL-". 799 * 800 * @param fs The file system to use. 801 * @param hbaseRootDir The root directory to scan. 802 * @return A map for each table and its percentage. 803 * @throws IOException When scanning the directory fails. 804 */ 805 public static Map<String, Integer> getTableFragmentation( 806 final FileSystem fs, final Path hbaseRootDir) 807 throws IOException { 808 Map<String, Integer> frags = new HashMap<>(); 809 int cfCountTotal = 0; 810 int cfFragTotal = 0; 811 PathFilter regionFilter = new RegionDirFilter(fs); 812 PathFilter familyFilter = new FamilyDirFilter(fs); 813 List<Path> tableDirs = getTableDirs(fs, hbaseRootDir); 814 for (Path d : tableDirs) { 815 int cfCount = 0; 816 int cfFrag = 0; 817 FileStatus[] regionDirs = fs.listStatus(d, regionFilter); 818 for (FileStatus regionDir : regionDirs) { 819 Path dd = regionDir.getPath(); 820 // else its a region name, now look in region for families 821 FileStatus[] familyDirs = fs.listStatus(dd, familyFilter); 822 for (FileStatus familyDir : familyDirs) { 823 cfCount++; 824 cfCountTotal++; 825 Path family = familyDir.getPath(); 826 // now in family make sure only one file 827 FileStatus[] familyStatus = fs.listStatus(family); 828 if (familyStatus.length > 1) { 829 cfFrag++; 830 cfFragTotal++; 831 } 832 } 833 } 834 // compute percentage per table and store in result list 835 frags.put(FSUtils.getTableName(d).getNameAsString(), 836 cfCount == 0? 0: Math.round((float) cfFrag / cfCount * 100)); 837 } 838 // set overall percentage for all tables 839 frags.put("-TOTAL-", 840 cfCountTotal == 0? 0: Math.round((float) cfFragTotal / cfCountTotal * 100)); 841 return frags; 842 } 843 844 /** 845 * A {@link PathFilter} that returns only regular files. 846 */ 847 static class FileFilter extends AbstractFileStatusFilter { 848 private final FileSystem fs; 849 850 public FileFilter(final FileSystem fs) { 851 this.fs = fs; 852 } 853 854 @Override 855 protected boolean accept(Path p, @CheckForNull Boolean isDir) { 856 try { 857 return isFile(fs, isDir, p); 858 } catch (IOException e) { 859 LOG.warn("unable to verify if path=" + p + " is a regular file", e); 860 return false; 861 } 862 } 863 } 864 865 /** 866 * Directory filter that doesn't include any of the directories in the specified blacklist 867 */ 868 public static class BlackListDirFilter extends AbstractFileStatusFilter { 869 private final FileSystem fs; 870 private List<String> blacklist; 871 872 /** 873 * Create a filter on the givem filesystem with the specified blacklist 874 * @param fs filesystem to filter 875 * @param directoryNameBlackList list of the names of the directories to filter. If 876 * <tt>null</tt>, all directories are returned 877 */ 878 @SuppressWarnings("unchecked") 879 public BlackListDirFilter(final FileSystem fs, final List<String> directoryNameBlackList) { 880 this.fs = fs; 881 blacklist = 882 (List<String>) (directoryNameBlackList == null ? Collections.emptyList() 883 : directoryNameBlackList); 884 } 885 886 @Override 887 protected boolean accept(Path p, @CheckForNull Boolean isDir) { 888 if (!isValidName(p.getName())) { 889 return false; 890 } 891 892 try { 893 return isDirectory(fs, isDir, p); 894 } catch (IOException e) { 895 LOG.warn("An error occurred while verifying if [" + p.toString() 896 + "] is a valid directory. Returning 'not valid' and continuing.", e); 897 return false; 898 } 899 } 900 901 protected boolean isValidName(final String name) { 902 return !blacklist.contains(name); 903 } 904 } 905 906 /** 907 * A {@link PathFilter} that only allows directories. 908 */ 909 public static class DirFilter extends BlackListDirFilter { 910 911 public DirFilter(FileSystem fs) { 912 super(fs, null); 913 } 914 } 915 916 /** 917 * A {@link PathFilter} that returns usertable directories. To get all directories use the 918 * {@link BlackListDirFilter} with a <tt>null</tt> blacklist 919 */ 920 public static class UserTableDirFilter extends BlackListDirFilter { 921 public UserTableDirFilter(FileSystem fs) { 922 super(fs, HConstants.HBASE_NON_TABLE_DIRS); 923 } 924 925 @Override 926 protected boolean isValidName(final String name) { 927 if (!super.isValidName(name)) 928 return false; 929 930 try { 931 TableName.isLegalTableQualifierName(Bytes.toBytes(name)); 932 } catch (IllegalArgumentException e) { 933 LOG.info("INVALID NAME " + name); 934 return false; 935 } 936 return true; 937 } 938 } 939 940 /** 941 * Recover file lease. Used when a file might be suspect 942 * to be had been left open by another process. 943 * @param fs FileSystem handle 944 * @param p Path of file to recover lease 945 * @param conf Configuration handle 946 * @throws IOException 947 */ 948 public abstract void recoverFileLease(final FileSystem fs, final Path p, 949 Configuration conf, CancelableProgressable reporter) throws IOException; 950 951 public static List<Path> getTableDirs(final FileSystem fs, final Path rootdir) 952 throws IOException { 953 List<Path> tableDirs = new LinkedList<>(); 954 955 for(FileStatus status : 956 fs.globStatus(new Path(rootdir, 957 new Path(HConstants.BASE_NAMESPACE_DIR, "*")))) { 958 tableDirs.addAll(FSUtils.getLocalTableDirs(fs, status.getPath())); 959 } 960 return tableDirs; 961 } 962 963 /** 964 * @param fs 965 * @param rootdir 966 * @return All the table directories under <code>rootdir</code>. Ignore non table hbase folders such as 967 * .logs, .oldlogs, .corrupt folders. 968 * @throws IOException 969 */ 970 public static List<Path> getLocalTableDirs(final FileSystem fs, final Path rootdir) 971 throws IOException { 972 // presumes any directory under hbase.rootdir is a table 973 FileStatus[] dirs = fs.listStatus(rootdir, new UserTableDirFilter(fs)); 974 List<Path> tabledirs = new ArrayList<>(dirs.length); 975 for (FileStatus dir: dirs) { 976 tabledirs.add(dir.getPath()); 977 } 978 return tabledirs; 979 } 980 981 /** 982 * Filter for all dirs that don't start with '.' 983 */ 984 public static class RegionDirFilter extends AbstractFileStatusFilter { 985 // This pattern will accept 0.90+ style hex region dirs and older numeric region dir names. 986 final public static Pattern regionDirPattern = Pattern.compile("^[0-9a-f]*$"); 987 final FileSystem fs; 988 989 public RegionDirFilter(FileSystem fs) { 990 this.fs = fs; 991 } 992 993 @Override 994 protected boolean accept(Path p, @CheckForNull Boolean isDir) { 995 if (!regionDirPattern.matcher(p.getName()).matches()) { 996 return false; 997 } 998 999 try { 1000 return isDirectory(fs, isDir, p); 1001 } catch (IOException ioe) { 1002 // Maybe the file was moved or the fs was disconnected. 1003 LOG.warn("Skipping file " + p +" due to IOException", ioe); 1004 return false; 1005 } 1006 } 1007 } 1008 1009 /** 1010 * Given a particular table dir, return all the regiondirs inside it, excluding files such as 1011 * .tableinfo 1012 * @param fs A file system for the Path 1013 * @param tableDir Path to a specific table directory <hbase.rootdir>/<tabledir> 1014 * @return List of paths to valid region directories in table dir. 1015 * @throws IOException 1016 */ 1017 public static List<Path> getRegionDirs(final FileSystem fs, final Path tableDir) throws IOException { 1018 // assumes we are in a table dir. 1019 List<FileStatus> rds = listStatusWithStatusFilter(fs, tableDir, new RegionDirFilter(fs)); 1020 if (rds == null) { 1021 return new ArrayList<>(); 1022 } 1023 List<Path> regionDirs = new ArrayList<>(rds.size()); 1024 for (FileStatus rdfs: rds) { 1025 Path rdPath = rdfs.getPath(); 1026 regionDirs.add(rdPath); 1027 } 1028 return regionDirs; 1029 } 1030 1031 /** 1032 * Filter for all dirs that are legal column family names. This is generally used for colfam 1033 * dirs <hbase.rootdir>/<tabledir>/<regiondir>/<colfamdir>. 1034 */ 1035 public static class FamilyDirFilter extends AbstractFileStatusFilter { 1036 final FileSystem fs; 1037 1038 public FamilyDirFilter(FileSystem fs) { 1039 this.fs = fs; 1040 } 1041 1042 @Override 1043 protected boolean accept(Path p, @CheckForNull Boolean isDir) { 1044 try { 1045 // throws IAE if invalid 1046 HColumnDescriptor.isLegalFamilyName(Bytes.toBytes(p.getName())); 1047 } catch (IllegalArgumentException iae) { 1048 // path name is an invalid family name and thus is excluded. 1049 return false; 1050 } 1051 1052 try { 1053 return isDirectory(fs, isDir, p); 1054 } catch (IOException ioe) { 1055 // Maybe the file was moved or the fs was disconnected. 1056 LOG.warn("Skipping file " + p +" due to IOException", ioe); 1057 return false; 1058 } 1059 } 1060 } 1061 1062 /** 1063 * Given a particular region dir, return all the familydirs inside it 1064 * 1065 * @param fs A file system for the Path 1066 * @param regionDir Path to a specific region directory 1067 * @return List of paths to valid family directories in region dir. 1068 * @throws IOException 1069 */ 1070 public static List<Path> getFamilyDirs(final FileSystem fs, final Path regionDir) throws IOException { 1071 // assumes we are in a region dir. 1072 FileStatus[] fds = fs.listStatus(regionDir, new FamilyDirFilter(fs)); 1073 List<Path> familyDirs = new ArrayList<>(fds.length); 1074 for (FileStatus fdfs: fds) { 1075 Path fdPath = fdfs.getPath(); 1076 familyDirs.add(fdPath); 1077 } 1078 return familyDirs; 1079 } 1080 1081 public static List<Path> getReferenceFilePaths(final FileSystem fs, final Path familyDir) throws IOException { 1082 List<FileStatus> fds = listStatusWithStatusFilter(fs, familyDir, new ReferenceFileFilter(fs)); 1083 if (fds == null) { 1084 return new ArrayList<>(); 1085 } 1086 List<Path> referenceFiles = new ArrayList<>(fds.size()); 1087 for (FileStatus fdfs: fds) { 1088 Path fdPath = fdfs.getPath(); 1089 referenceFiles.add(fdPath); 1090 } 1091 return referenceFiles; 1092 } 1093 1094 /** 1095 * Filter for HFiles that excludes reference files. 1096 */ 1097 public static class HFileFilter extends AbstractFileStatusFilter { 1098 final FileSystem fs; 1099 1100 public HFileFilter(FileSystem fs) { 1101 this.fs = fs; 1102 } 1103 1104 @Override 1105 protected boolean accept(Path p, @CheckForNull Boolean isDir) { 1106 if (!StoreFileInfo.isHFile(p)) { 1107 return false; 1108 } 1109 1110 try { 1111 return isFile(fs, isDir, p); 1112 } catch (IOException ioe) { 1113 // Maybe the file was moved or the fs was disconnected. 1114 LOG.warn("Skipping file " + p +" due to IOException", ioe); 1115 return false; 1116 } 1117 } 1118 } 1119 1120 /** 1121 * Filter for HFileLinks (StoreFiles and HFiles not included). 1122 * the filter itself does not consider if a link is file or not. 1123 */ 1124 public static class HFileLinkFilter implements PathFilter { 1125 1126 @Override 1127 public boolean accept(Path p) { 1128 return HFileLink.isHFileLink(p); 1129 } 1130 } 1131 1132 public static class ReferenceFileFilter extends AbstractFileStatusFilter { 1133 1134 private final FileSystem fs; 1135 1136 public ReferenceFileFilter(FileSystem fs) { 1137 this.fs = fs; 1138 } 1139 1140 @Override 1141 protected boolean accept(Path p, @CheckForNull Boolean isDir) { 1142 if (!StoreFileInfo.isReference(p)) { 1143 return false; 1144 } 1145 1146 try { 1147 // only files can be references. 1148 return isFile(fs, isDir, p); 1149 } catch (IOException ioe) { 1150 // Maybe the file was moved or the fs was disconnected. 1151 LOG.warn("Skipping file " + p +" due to IOException", ioe); 1152 return false; 1153 } 1154 } 1155 } 1156 1157 /** 1158 * Runs through the HBase rootdir/tablename and creates a reverse lookup map for 1159 * table StoreFile names to the full Path. 1160 * <br> 1161 * Example...<br> 1162 * Key = 3944417774205889744 <br> 1163 * Value = hdfs://localhost:51169/user/userid/-ROOT-/70236052/info/3944417774205889744 1164 * 1165 * @param map map to add values. If null, this method will create and populate one to return 1166 * @param fs The file system to use. 1167 * @param hbaseRootDir The root directory to scan. 1168 * @param tableName name of the table to scan. 1169 * @return Map keyed by StoreFile name with a value of the full Path. 1170 * @throws IOException When scanning the directory fails. 1171 * @throws InterruptedException 1172 */ 1173 public static Map<String, Path> getTableStoreFilePathMap(Map<String, Path> map, 1174 final FileSystem fs, final Path hbaseRootDir, TableName tableName) 1175 throws IOException, InterruptedException { 1176 return getTableStoreFilePathMap(map, fs, hbaseRootDir, tableName, null, null, null); 1177 } 1178 1179 /** 1180 * Runs through the HBase rootdir/tablename and creates a reverse lookup map for 1181 * table StoreFile names to the full Path. Note that because this method can be called 1182 * on a 'live' HBase system that we will skip files that no longer exist by the time 1183 * we traverse them and similarly the user of the result needs to consider that some 1184 * entries in this map may not exist by the time this call completes. 1185 * <br> 1186 * Example...<br> 1187 * Key = 3944417774205889744 <br> 1188 * Value = hdfs://localhost:51169/user/userid/-ROOT-/70236052/info/3944417774205889744 1189 * 1190 * @param resultMap map to add values. If null, this method will create and populate one to return 1191 * @param fs The file system to use. 1192 * @param hbaseRootDir The root directory to scan. 1193 * @param tableName name of the table to scan. 1194 * @param sfFilter optional path filter to apply to store files 1195 * @param executor optional executor service to parallelize this operation 1196 * @param errors ErrorReporter instance or null 1197 * @return Map keyed by StoreFile name with a value of the full Path. 1198 * @throws IOException When scanning the directory fails. 1199 * @throws InterruptedException 1200 */ 1201 public static Map<String, Path> getTableStoreFilePathMap( 1202 Map<String, Path> resultMap, 1203 final FileSystem fs, final Path hbaseRootDir, TableName tableName, final PathFilter sfFilter, 1204 ExecutorService executor, final ErrorReporter errors) throws IOException, InterruptedException { 1205 1206 final Map<String, Path> finalResultMap = 1207 resultMap == null ? new ConcurrentHashMap<>(128, 0.75f, 32) : resultMap; 1208 1209 // only include the directory paths to tables 1210 Path tableDir = FSUtils.getTableDir(hbaseRootDir, tableName); 1211 // Inside a table, there are compaction.dir directories to skip. Otherwise, all else 1212 // should be regions. 1213 final FamilyDirFilter familyFilter = new FamilyDirFilter(fs); 1214 final Vector<Exception> exceptions = new Vector<>(); 1215 1216 try { 1217 List<FileStatus> regionDirs = FSUtils.listStatusWithStatusFilter(fs, tableDir, new RegionDirFilter(fs)); 1218 if (regionDirs == null) { 1219 return finalResultMap; 1220 } 1221 1222 final List<Future<?>> futures = new ArrayList<>(regionDirs.size()); 1223 1224 for (FileStatus regionDir : regionDirs) { 1225 if (null != errors) { 1226 errors.progress(); 1227 } 1228 final Path dd = regionDir.getPath(); 1229 1230 if (!exceptions.isEmpty()) { 1231 break; 1232 } 1233 1234 Runnable getRegionStoreFileMapCall = new Runnable() { 1235 @Override 1236 public void run() { 1237 try { 1238 HashMap<String,Path> regionStoreFileMap = new HashMap<>(); 1239 List<FileStatus> familyDirs = FSUtils.listStatusWithStatusFilter(fs, dd, familyFilter); 1240 if (familyDirs == null) { 1241 if (!fs.exists(dd)) { 1242 LOG.warn("Skipping region because it no longer exists: " + dd); 1243 } else { 1244 LOG.warn("Skipping region because it has no family dirs: " + dd); 1245 } 1246 return; 1247 } 1248 for (FileStatus familyDir : familyDirs) { 1249 if (null != errors) { 1250 errors.progress(); 1251 } 1252 Path family = familyDir.getPath(); 1253 if (family.getName().equals(HConstants.RECOVERED_EDITS_DIR)) { 1254 continue; 1255 } 1256 // now in family, iterate over the StoreFiles and 1257 // put in map 1258 FileStatus[] familyStatus = fs.listStatus(family); 1259 for (FileStatus sfStatus : familyStatus) { 1260 if (null != errors) { 1261 errors.progress(); 1262 } 1263 Path sf = sfStatus.getPath(); 1264 if (sfFilter == null || sfFilter.accept(sf)) { 1265 regionStoreFileMap.put( sf.getName(), sf); 1266 } 1267 } 1268 } 1269 finalResultMap.putAll(regionStoreFileMap); 1270 } catch (Exception e) { 1271 LOG.error("Could not get region store file map for region: " + dd, e); 1272 exceptions.add(e); 1273 } 1274 } 1275 }; 1276 1277 // If executor is available, submit async tasks to exec concurrently, otherwise 1278 // just do serial sync execution 1279 if (executor != null) { 1280 Future<?> future = executor.submit(getRegionStoreFileMapCall); 1281 futures.add(future); 1282 } else { 1283 FutureTask<?> future = new FutureTask<>(getRegionStoreFileMapCall, null); 1284 future.run(); 1285 futures.add(future); 1286 } 1287 } 1288 1289 // Ensure all pending tasks are complete (or that we run into an exception) 1290 for (Future<?> f : futures) { 1291 if (!exceptions.isEmpty()) { 1292 break; 1293 } 1294 try { 1295 f.get(); 1296 } catch (ExecutionException e) { 1297 LOG.error("Unexpected exec exception! Should've been caught already. (Bug?)", e); 1298 // Shouldn't happen, we already logged/caught any exceptions in the Runnable 1299 } 1300 } 1301 } catch (IOException e) { 1302 LOG.error("Cannot execute getTableStoreFilePathMap for " + tableName, e); 1303 exceptions.add(e); 1304 } finally { 1305 if (!exceptions.isEmpty()) { 1306 // Just throw the first exception as an indication something bad happened 1307 // Don't need to propagate all the exceptions, we already logged them all anyway 1308 Throwables.propagateIfInstanceOf(exceptions.firstElement(), IOException.class); 1309 throw Throwables.propagate(exceptions.firstElement()); 1310 } 1311 } 1312 1313 return finalResultMap; 1314 } 1315 1316 public static int getRegionReferenceFileCount(final FileSystem fs, final Path p) { 1317 int result = 0; 1318 try { 1319 for (Path familyDir:getFamilyDirs(fs, p)){ 1320 result += getReferenceFilePaths(fs, familyDir).size(); 1321 } 1322 } catch (IOException e) { 1323 LOG.warn("Error Counting reference files.", e); 1324 } 1325 return result; 1326 } 1327 1328 /** 1329 * Runs through the HBase rootdir and creates a reverse lookup map for 1330 * table StoreFile names to the full Path. 1331 * <br> 1332 * Example...<br> 1333 * Key = 3944417774205889744 <br> 1334 * Value = hdfs://localhost:51169/user/userid/-ROOT-/70236052/info/3944417774205889744 1335 * 1336 * @param fs The file system to use. 1337 * @param hbaseRootDir The root directory to scan. 1338 * @return Map keyed by StoreFile name with a value of the full Path. 1339 * @throws IOException When scanning the directory fails. 1340 * @throws InterruptedException 1341 */ 1342 public static Map<String, Path> getTableStoreFilePathMap( 1343 final FileSystem fs, final Path hbaseRootDir) 1344 throws IOException, InterruptedException { 1345 return getTableStoreFilePathMap(fs, hbaseRootDir, null, null, null); 1346 } 1347 1348 /** 1349 * Runs through the HBase rootdir and creates a reverse lookup map for 1350 * table StoreFile names to the full Path. 1351 * <br> 1352 * Example...<br> 1353 * Key = 3944417774205889744 <br> 1354 * Value = hdfs://localhost:51169/user/userid/-ROOT-/70236052/info/3944417774205889744 1355 * 1356 * @param fs The file system to use. 1357 * @param hbaseRootDir The root directory to scan. 1358 * @param sfFilter optional path filter to apply to store files 1359 * @param executor optional executor service to parallelize this operation 1360 * @param errors ErrorReporter instance or null 1361 * @return Map keyed by StoreFile name with a value of the full Path. 1362 * @throws IOException When scanning the directory fails. 1363 * @throws InterruptedException 1364 */ 1365 public static Map<String, Path> getTableStoreFilePathMap( 1366 final FileSystem fs, final Path hbaseRootDir, PathFilter sfFilter, 1367 ExecutorService executor, ErrorReporter errors) 1368 throws IOException, InterruptedException { 1369 ConcurrentHashMap<String, Path> map = new ConcurrentHashMap<>(1024, 0.75f, 32); 1370 1371 // if this method looks similar to 'getTableFragmentation' that is because 1372 // it was borrowed from it. 1373 1374 // only include the directory paths to tables 1375 for (Path tableDir : FSUtils.getTableDirs(fs, hbaseRootDir)) { 1376 getTableStoreFilePathMap(map, fs, hbaseRootDir, 1377 FSUtils.getTableName(tableDir), sfFilter, executor, errors); 1378 } 1379 return map; 1380 } 1381 1382 /** 1383 * Filters FileStatuses in an array and returns a list 1384 * 1385 * @param input An array of FileStatuses 1386 * @param filter A required filter to filter the array 1387 * @return A list of FileStatuses 1388 */ 1389 public static List<FileStatus> filterFileStatuses(FileStatus[] input, 1390 FileStatusFilter filter) { 1391 if (input == null) return null; 1392 return filterFileStatuses(Iterators.forArray(input), filter); 1393 } 1394 1395 /** 1396 * Filters FileStatuses in an iterator and returns a list 1397 * 1398 * @param input An iterator of FileStatuses 1399 * @param filter A required filter to filter the array 1400 * @return A list of FileStatuses 1401 */ 1402 public static List<FileStatus> filterFileStatuses(Iterator<FileStatus> input, 1403 FileStatusFilter filter) { 1404 if (input == null) return null; 1405 ArrayList<FileStatus> results = new ArrayList<>(); 1406 while (input.hasNext()) { 1407 FileStatus f = input.next(); 1408 if (filter.accept(f)) { 1409 results.add(f); 1410 } 1411 } 1412 return results; 1413 } 1414 1415 /** 1416 * Calls fs.listStatus() and treats FileNotFoundException as non-fatal 1417 * This accommodates differences between hadoop versions, where hadoop 1 1418 * does not throw a FileNotFoundException, and return an empty FileStatus[] 1419 * while Hadoop 2 will throw FileNotFoundException. 1420 * 1421 * @param fs file system 1422 * @param dir directory 1423 * @param filter file status filter 1424 * @return null if dir is empty or doesn't exist, otherwise FileStatus list 1425 */ 1426 public static List<FileStatus> listStatusWithStatusFilter(final FileSystem fs, 1427 final Path dir, final FileStatusFilter filter) throws IOException { 1428 FileStatus [] status = null; 1429 try { 1430 status = fs.listStatus(dir); 1431 } catch (FileNotFoundException fnfe) { 1432 // if directory doesn't exist, return null 1433 if (LOG.isTraceEnabled()) { 1434 LOG.trace(dir + " doesn't exist"); 1435 } 1436 } 1437 1438 if (status == null || status.length < 1) { 1439 return null; 1440 } 1441 1442 if (filter == null) { 1443 return Arrays.asList(status); 1444 } else { 1445 List<FileStatus> status2 = filterFileStatuses(status, filter); 1446 if (status2 == null || status2.isEmpty()) { 1447 return null; 1448 } else { 1449 return status2; 1450 } 1451 } 1452 } 1453 1454 /** 1455 * Throw an exception if an action is not permitted by a user on a file. 1456 * 1457 * @param ugi 1458 * the user 1459 * @param file 1460 * the file 1461 * @param action 1462 * the action 1463 */ 1464 public static void checkAccess(UserGroupInformation ugi, FileStatus file, 1465 FsAction action) throws AccessDeniedException { 1466 if (ugi.getShortUserName().equals(file.getOwner())) { 1467 if (file.getPermission().getUserAction().implies(action)) { 1468 return; 1469 } 1470 } else if (contains(ugi.getGroupNames(), file.getGroup())) { 1471 if (file.getPermission().getGroupAction().implies(action)) { 1472 return; 1473 } 1474 } else if (file.getPermission().getOtherAction().implies(action)) { 1475 return; 1476 } 1477 throw new AccessDeniedException("Permission denied:" + " action=" + action 1478 + " path=" + file.getPath() + " user=" + ugi.getShortUserName()); 1479 } 1480 1481 private static boolean contains(String[] groups, String user) { 1482 for (String group : groups) { 1483 if (group.equals(user)) { 1484 return true; 1485 } 1486 } 1487 return false; 1488 } 1489 1490 /** 1491 * This function is to scan the root path of the file system to get the 1492 * degree of locality for each region on each of the servers having at least 1493 * one block of that region. 1494 * This is used by the tool {@link org.apache.hadoop.hbase.master.RegionPlacementMaintainer} 1495 * 1496 * @param conf 1497 * the configuration to use 1498 * @return the mapping from region encoded name to a map of server names to 1499 * locality fraction 1500 * @throws IOException 1501 * in case of file system errors or interrupts 1502 */ 1503 public static Map<String, Map<String, Float>> getRegionDegreeLocalityMappingFromFS( 1504 final Configuration conf) throws IOException { 1505 return getRegionDegreeLocalityMappingFromFS( 1506 conf, null, 1507 conf.getInt(THREAD_POOLSIZE, DEFAULT_THREAD_POOLSIZE)); 1508 1509 } 1510 1511 /** 1512 * This function is to scan the root path of the file system to get the 1513 * degree of locality for each region on each of the servers having at least 1514 * one block of that region. 1515 * 1516 * @param conf 1517 * the configuration to use 1518 * @param desiredTable 1519 * the table you wish to scan locality for 1520 * @param threadPoolSize 1521 * the thread pool size to use 1522 * @return the mapping from region encoded name to a map of server names to 1523 * locality fraction 1524 * @throws IOException 1525 * in case of file system errors or interrupts 1526 */ 1527 public static Map<String, Map<String, Float>> getRegionDegreeLocalityMappingFromFS( 1528 final Configuration conf, final String desiredTable, int threadPoolSize) 1529 throws IOException { 1530 Map<String, Map<String, Float>> regionDegreeLocalityMapping = new ConcurrentHashMap<>(); 1531 getRegionLocalityMappingFromFS(conf, desiredTable, threadPoolSize, null, 1532 regionDegreeLocalityMapping); 1533 return regionDegreeLocalityMapping; 1534 } 1535 1536 /** 1537 * This function is to scan the root path of the file system to get either the 1538 * mapping between the region name and its best locality region server or the 1539 * degree of locality of each region on each of the servers having at least 1540 * one block of that region. The output map parameters are both optional. 1541 * 1542 * @param conf 1543 * the configuration to use 1544 * @param desiredTable 1545 * the table you wish to scan locality for 1546 * @param threadPoolSize 1547 * the thread pool size to use 1548 * @param regionToBestLocalityRSMapping 1549 * the map into which to put the best locality mapping or null 1550 * @param regionDegreeLocalityMapping 1551 * the map into which to put the locality degree mapping or null, 1552 * must be a thread-safe implementation 1553 * @throws IOException 1554 * in case of file system errors or interrupts 1555 */ 1556 private static void getRegionLocalityMappingFromFS( 1557 final Configuration conf, final String desiredTable, 1558 int threadPoolSize, 1559 Map<String, String> regionToBestLocalityRSMapping, 1560 Map<String, Map<String, Float>> regionDegreeLocalityMapping) 1561 throws IOException { 1562 FileSystem fs = FileSystem.get(conf); 1563 Path rootPath = FSUtils.getRootDir(conf); 1564 long startTime = EnvironmentEdgeManager.currentTime(); 1565 Path queryPath; 1566 // The table files are in ${hbase.rootdir}/data/<namespace>/<table>/* 1567 if (null == desiredTable) { 1568 queryPath = new Path(new Path(rootPath, HConstants.BASE_NAMESPACE_DIR).toString() + "/*/*/*/"); 1569 } else { 1570 queryPath = new Path(FSUtils.getTableDir(rootPath, TableName.valueOf(desiredTable)).toString() + "/*/"); 1571 } 1572 1573 // reject all paths that are not appropriate 1574 PathFilter pathFilter = new PathFilter() { 1575 @Override 1576 public boolean accept(Path path) { 1577 // this is the region name; it may get some noise data 1578 if (null == path) { 1579 return false; 1580 } 1581 1582 // no parent? 1583 Path parent = path.getParent(); 1584 if (null == parent) { 1585 return false; 1586 } 1587 1588 String regionName = path.getName(); 1589 if (null == regionName) { 1590 return false; 1591 } 1592 1593 if (!regionName.toLowerCase(Locale.ROOT).matches("[0-9a-f]+")) { 1594 return false; 1595 } 1596 return true; 1597 } 1598 }; 1599 1600 FileStatus[] statusList = fs.globStatus(queryPath, pathFilter); 1601 1602 if (null == statusList) { 1603 return; 1604 } else { 1605 LOG.debug("Query Path: " + queryPath + " ; # list of files: " + 1606 statusList.length); 1607 } 1608 1609 // lower the number of threads in case we have very few expected regions 1610 threadPoolSize = Math.min(threadPoolSize, statusList.length); 1611 1612 // run in multiple threads 1613 ThreadPoolExecutor tpe = new ThreadPoolExecutor(threadPoolSize, 1614 threadPoolSize, 60, TimeUnit.SECONDS, 1615 new ArrayBlockingQueue<>(statusList.length)); 1616 try { 1617 // ignore all file status items that are not of interest 1618 for (FileStatus regionStatus : statusList) { 1619 if (null == regionStatus) { 1620 continue; 1621 } 1622 1623 if (!regionStatus.isDirectory()) { 1624 continue; 1625 } 1626 1627 Path regionPath = regionStatus.getPath(); 1628 if (null == regionPath) { 1629 continue; 1630 } 1631 1632 tpe.execute(new FSRegionScanner(fs, regionPath, 1633 regionToBestLocalityRSMapping, regionDegreeLocalityMapping)); 1634 } 1635 } finally { 1636 tpe.shutdown(); 1637 int threadWakeFrequency = conf.getInt(HConstants.THREAD_WAKE_FREQUENCY, 1638 60 * 1000); 1639 try { 1640 // here we wait until TPE terminates, which is either naturally or by 1641 // exceptions in the execution of the threads 1642 while (!tpe.awaitTermination(threadWakeFrequency, 1643 TimeUnit.MILLISECONDS)) { 1644 // printing out rough estimate, so as to not introduce 1645 // AtomicInteger 1646 LOG.info("Locality checking is underway: { Scanned Regions : " 1647 + tpe.getCompletedTaskCount() + "/" 1648 + tpe.getTaskCount() + " }"); 1649 } 1650 } catch (InterruptedException e) { 1651 throw (InterruptedIOException)new InterruptedIOException().initCause(e); 1652 } 1653 } 1654 1655 long overhead = EnvironmentEdgeManager.currentTime() - startTime; 1656 String overheadMsg = "Scan DFS for locality info takes " + overhead + " ms"; 1657 1658 LOG.info(overheadMsg); 1659 } 1660 1661 /** 1662 * Do our short circuit read setup. 1663 * Checks buffer size to use and whether to do checksumming in hbase or hdfs. 1664 * @param conf 1665 */ 1666 public static void setupShortCircuitRead(final Configuration conf) { 1667 // Check that the user has not set the "dfs.client.read.shortcircuit.skip.checksum" property. 1668 boolean shortCircuitSkipChecksum = 1669 conf.getBoolean("dfs.client.read.shortcircuit.skip.checksum", false); 1670 boolean useHBaseChecksum = conf.getBoolean(HConstants.HBASE_CHECKSUM_VERIFICATION, true); 1671 if (shortCircuitSkipChecksum) { 1672 LOG.warn("Configuration \"dfs.client.read.shortcircuit.skip.checksum\" should not " + 1673 "be set to true." + (useHBaseChecksum ? " HBase checksum doesn't require " + 1674 "it, see https://issues.apache.org/jira/browse/HBASE-6868." : "")); 1675 assert !shortCircuitSkipChecksum; //this will fail if assertions are on 1676 } 1677 checkShortCircuitReadBufferSize(conf); 1678 } 1679 1680 /** 1681 * Check if short circuit read buffer size is set and if not, set it to hbase value. 1682 * @param conf 1683 */ 1684 public static void checkShortCircuitReadBufferSize(final Configuration conf) { 1685 final int defaultSize = HConstants.DEFAULT_BLOCKSIZE * 2; 1686 final int notSet = -1; 1687 // DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_BUFFER_SIZE_KEY is only defined in h2 1688 final String dfsKey = "dfs.client.read.shortcircuit.buffer.size"; 1689 int size = conf.getInt(dfsKey, notSet); 1690 // If a size is set, return -- we will use it. 1691 if (size != notSet) return; 1692 // But short circuit buffer size is normally not set. Put in place the hbase wanted size. 1693 int hbaseSize = conf.getInt("hbase." + dfsKey, defaultSize); 1694 conf.setIfUnset(dfsKey, Integer.toString(hbaseSize)); 1695 } 1696 1697 /** 1698 * @param c 1699 * @return The DFSClient DFSHedgedReadMetrics instance or null if can't be found or not on hdfs. 1700 * @throws IOException 1701 */ 1702 public static DFSHedgedReadMetrics getDFSHedgedReadMetrics(final Configuration c) 1703 throws IOException { 1704 if (!isHDFS(c)) return null; 1705 // getHedgedReadMetrics is package private. Get the DFSClient instance that is internal 1706 // to the DFS FS instance and make the method getHedgedReadMetrics accessible, then invoke it 1707 // to get the singleton instance of DFSHedgedReadMetrics shared by DFSClients. 1708 final String name = "getHedgedReadMetrics"; 1709 DFSClient dfsclient = ((DistributedFileSystem)FileSystem.get(c)).getClient(); 1710 Method m; 1711 try { 1712 m = dfsclient.getClass().getDeclaredMethod(name); 1713 } catch (NoSuchMethodException e) { 1714 LOG.warn("Failed find method " + name + " in dfsclient; no hedged read metrics: " + 1715 e.getMessage()); 1716 return null; 1717 } catch (SecurityException e) { 1718 LOG.warn("Failed find method " + name + " in dfsclient; no hedged read metrics: " + 1719 e.getMessage()); 1720 return null; 1721 } 1722 m.setAccessible(true); 1723 try { 1724 return (DFSHedgedReadMetrics)m.invoke(dfsclient); 1725 } catch (IllegalAccessException e) { 1726 LOG.warn("Failed invoking method " + name + " on dfsclient; no hedged read metrics: " + 1727 e.getMessage()); 1728 return null; 1729 } catch (IllegalArgumentException e) { 1730 LOG.warn("Failed invoking method " + name + " on dfsclient; no hedged read metrics: " + 1731 e.getMessage()); 1732 return null; 1733 } catch (InvocationTargetException e) { 1734 LOG.warn("Failed invoking method " + name + " on dfsclient; no hedged read metrics: " + 1735 e.getMessage()); 1736 return null; 1737 } 1738 } 1739 1740}