001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.util; 019 020import static org.apache.hadoop.hbase.util.LocatedBlockHelper.getLocatedBlockLocations; 021import static org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction.SAFEMODE_GET; 022 023import edu.umd.cs.findbugs.annotations.CheckForNull; 024import java.io.ByteArrayInputStream; 025import java.io.DataInputStream; 026import java.io.EOFException; 027import java.io.FileNotFoundException; 028import java.io.IOException; 029import java.io.InterruptedIOException; 030import java.lang.reflect.InvocationTargetException; 031import java.lang.reflect.Method; 032import java.net.InetSocketAddress; 033import java.net.URI; 034import java.util.ArrayList; 035import java.util.Arrays; 036import java.util.Collection; 037import java.util.Collections; 038import java.util.HashMap; 039import java.util.HashSet; 040import java.util.Iterator; 041import java.util.List; 042import java.util.Locale; 043import java.util.Map; 044import java.util.Optional; 045import java.util.Set; 046import java.util.Vector; 047import java.util.concurrent.CompletableFuture; 048import java.util.concurrent.ConcurrentHashMap; 049import java.util.concurrent.ExecutionException; 050import java.util.concurrent.ExecutorService; 051import java.util.concurrent.Executors; 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; 057import org.apache.commons.lang3.ArrayUtils; 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.FileUtil; 065import org.apache.hadoop.fs.FilterFileSystem; 066import org.apache.hadoop.fs.Path; 067import org.apache.hadoop.fs.PathFilter; 068import org.apache.hadoop.fs.StorageType; 069import org.apache.hadoop.fs.permission.FsPermission; 070import org.apache.hadoop.hbase.ActiveClusterSuffix; 071import org.apache.hadoop.hbase.ClusterIdFile; 072import org.apache.hadoop.hbase.ClusterIdFileParser; 073import org.apache.hadoop.hbase.HConstants; 074import org.apache.hadoop.hbase.HDFSBlocksDistribution; 075import org.apache.hadoop.hbase.TableName; 076import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; 077import org.apache.hadoop.hbase.client.RegionInfo; 078import org.apache.hadoop.hbase.client.RegionInfoBuilder; 079import org.apache.hadoop.hbase.exceptions.DeserializationException; 080import org.apache.hadoop.hbase.fs.HFileSystem; 081import org.apache.hadoop.hbase.io.HFileLink; 082import org.apache.hadoop.hbase.master.HMaster; 083import org.apache.hadoop.hbase.regionserver.StoreFileInfo; 084import org.apache.hadoop.hdfs.DFSClient; 085import org.apache.hadoop.hdfs.DFSHedgedReadMetrics; 086import org.apache.hadoop.hdfs.DFSUtil; 087import org.apache.hadoop.hdfs.DistributedFileSystem; 088import org.apache.hadoop.hdfs.client.HdfsDataInputStream; 089import org.apache.hadoop.hdfs.protocol.DatanodeInfo; 090import org.apache.hadoop.hdfs.protocol.LocatedBlock; 091import org.apache.hadoop.io.IOUtils; 092import org.apache.hadoop.ipc.RemoteException; 093import org.apache.yetus.audience.InterfaceAudience; 094import org.slf4j.Logger; 095import org.slf4j.LoggerFactory; 096 097import org.apache.hbase.thirdparty.com.google.common.base.Throwables; 098import org.apache.hbase.thirdparty.com.google.common.collect.Iterators; 099import org.apache.hbase.thirdparty.com.google.common.collect.Sets; 100import org.apache.hbase.thirdparty.com.google.common.primitives.Ints; 101import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder; 102 103import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil; 104import org.apache.hadoop.hbase.shaded.protobuf.generated.FSProtos; 105 106/** 107 * Utility methods for interacting with the underlying file system. 108 */ 109@InterfaceAudience.Private 110public final class FSUtils { 111 private static final Logger LOG = LoggerFactory.getLogger(FSUtils.class); 112 113 private static final String THREAD_POOLSIZE = "hbase.client.localityCheck.threadPoolSize"; 114 private static final int DEFAULT_THREAD_POOLSIZE = 2; 115 116 private enum OpenFileSupport { 117 SUPPORTED, 118 LEGACY_OPEN, 119 TRANSPARENT 120 } 121 122 private static final ClassValue<OpenFileSupport> OPEN_FILE_SUPPORT_BY_CLASS = 123 new ClassValue<OpenFileSupport>() { 124 @Override 125 protected OpenFileSupport computeValue(Class<?> type) { 126 if (!FilterFileSystem.class.isAssignableFrom(type)) { 127 return OpenFileSupport.SUPPORTED; 128 } 129 try { 130 boolean overridesOpen = type.getMethod("open", Path.class, int.class).getDeclaringClass() 131 != FilterFileSystem.class; 132 boolean overridesOpenFile = 133 type.getMethod("openFile", Path.class).getDeclaringClass() != FilterFileSystem.class; 134 if (overridesOpenFile) { 135 return OpenFileSupport.SUPPORTED; 136 } 137 if (overridesOpen) { 138 LOG.info("FileSystem wrapper {} overrides open(Path, int) but not openFile(Path); " 139 + "using legacy open() instead of the faster openFile() path", type.getName()); 140 return OpenFileSupport.LEGACY_OPEN; 141 } 142 return OpenFileSupport.TRANSPARENT; 143 } catch (NoSuchMethodException e) { 144 // Both methods exist in the Hadoop version supported. Keep the fallback 145 // for an unexpected or incompatible Hadoop runtime. 146 return OpenFileSupport.LEGACY_OPEN; 147 } 148 } 149 }; 150 151 /** Set to true on Windows platforms */ 152 // currently only used in testing. TODO refactor into a test class 153 public static final boolean WINDOWS = System.getProperty("os.name").startsWith("Windows"); 154 155 private static Class<?> safeModeClazz = null; 156 private static Class<?> safeModeActionClazz = null; 157 private static Object safeModeGet = null; 158 { 159 try { 160 safeModeClazz = Class.forName("org.apache.hadoop.fs.SafeMode"); 161 safeModeActionClazz = Class.forName("org.apache.hadoop.fs.SafeModeAction"); 162 safeModeGet = safeModeClazz.getField("SAFEMODE_GET").get(null); 163 } catch (ClassNotFoundException | NoSuchFieldException e) { 164 LOG.debug("SafeMode interface not in the classpath, this means Hadoop 3.3.5 or below."); 165 } catch (IllegalAccessException e) { 166 LOG.error("SafeModeAction.SAFEMODE_GET is not accessible. " 167 + "Unexpected Hadoop version or messy classpath?", e); 168 throw new RuntimeException(e); 169 } 170 } 171 172 private FSUtils() { 173 } 174 175 /** Returns True is <code>fs</code> is instance of DistributedFileSystem n */ 176 public static boolean isDistributedFileSystem(final FileSystem fs) throws IOException { 177 FileSystem fileSystem = fs; 178 // If passed an instance of HFileSystem, it fails instanceof DistributedFileSystem. 179 // Check its backing fs for dfs-ness. 180 if (fs instanceof HFileSystem) { 181 fileSystem = ((HFileSystem) fs).getBackingFs(); 182 } 183 return fileSystem instanceof DistributedFileSystem; 184 } 185 186 /** 187 * Compare path component of the Path URI; e.g. if hdfs://a/b/c and /a/b/c, it will compare the 188 * '/a/b/c' part. If you passed in 'hdfs://a/b/c and b/c, it would return true. Does not consider 189 * schema; i.e. if schemas different but path or subpath matches, the two will equate. 190 * @param pathToSearch Path we will be trying to match. 191 * @return True if <code>pathTail</code> is tail on the path of <code>pathToSearch</code> 192 */ 193 public static boolean isMatchingTail(final Path pathToSearch, final Path pathTail) { 194 Path tailPath = pathTail; 195 String tailName; 196 Path toSearch = pathToSearch; 197 String toSearchName; 198 boolean result = false; 199 200 if (pathToSearch.depth() != pathTail.depth()) { 201 return false; 202 } 203 204 do { 205 tailName = tailPath.getName(); 206 if (tailName == null || tailName.isEmpty()) { 207 result = true; 208 break; 209 } 210 toSearchName = toSearch.getName(); 211 if (toSearchName == null || toSearchName.isEmpty()) { 212 break; 213 } 214 // Move up a parent on each path for next go around. Path doesn't let us go off the end. 215 tailPath = tailPath.getParent(); 216 toSearch = toSearch.getParent(); 217 } while (tailName.equals(toSearchName)); 218 return result; 219 } 220 221 /** 222 * Delete the region directory if exists. 223 * @return True if deleted the region directory. 224 */ 225 public static boolean deleteRegionDir(final Configuration conf, final RegionInfo hri) 226 throws IOException { 227 Path rootDir = CommonFSUtils.getRootDir(conf); 228 FileSystem fs = rootDir.getFileSystem(conf); 229 return CommonFSUtils.deleteDirectory(fs, 230 new Path(CommonFSUtils.getTableDir(rootDir, hri.getTable()), hri.getEncodedName())); 231 } 232 233 /** 234 * Create the specified file on the filesystem. By default, this will: 235 * <ol> 236 * <li>overwrite the file if it exists</li> 237 * <li>apply the umask in the configuration (if it is enabled)</li> 238 * <li>use the fs configured buffer size (or 4096 if not set)</li> 239 * <li>use the configured column family replication or default replication if 240 * {@link ColumnFamilyDescriptorBuilder#DEFAULT_DFS_REPLICATION}</li> 241 * <li>use the default block size</li> 242 * <li>not track progress</li> 243 * </ol> 244 * @param conf configurations 245 * @param fs {@link FileSystem} on which to write the file 246 * @param path {@link Path} to the file to write 247 * @param perm permissions 248 * @param favoredNodes favored data nodes 249 * @return output stream to the created file 250 * @throws IOException if the file cannot be created 251 */ 252 public static FSDataOutputStream create(Configuration conf, FileSystem fs, Path path, 253 FsPermission perm, InetSocketAddress[] favoredNodes) throws IOException { 254 return create(conf, fs, path, perm, favoredNodes, true); 255 } 256 257 /** 258 * Opens a file for reading. When {@code fileStatus} is supplied and the {@link FileSystem} 259 * supports {@code FileSystem.openFile().withFileStatus()}, that path is used so the client can 260 * skip a redundant metadata lookup (for example {@code getFileInfo}). 261 * @param fs filesystem 262 * @param path file to open 263 * @param fileStatus status from a recent {@code listStatus} / {@code getFileStatus}, or 264 * {@code null} 265 * @return input stream for the file 266 * @throws IOException if the file cannot be opened 267 */ 268 public static FSDataInputStream openForRead(FileSystem fs, Path path, FileStatus fileStatus) 269 throws IOException { 270 if (fileStatus != null && supportsOpenFile(fs)) { 271 try { 272 CompletableFuture<FSDataInputStream> future = 273 fs.openFile(path).withFileStatus(fileStatus).build(); 274 try { 275 return future.get(); 276 } catch (InterruptedException e) { 277 // The open may still complete asynchronously; close whatever stream it produces since 278 // the caller will never receive it. Do not cancel the future, as a cancelled future 279 // would discard a stream that is completed later without closing it. 280 future.whenComplete((in, t) -> IOUtils.cleanupWithLogger(LOG, in)); 281 Thread.currentThread().interrupt(); 282 throw (InterruptedIOException) new InterruptedIOException("Interrupted opening " + path) 283 .initCause(e); 284 } 285 } catch (UnsupportedOperationException | ExecutionException e) { 286 if ( 287 e instanceof ExecutionException 288 && !(e.getCause() instanceof UnsupportedOperationException) 289 ) { 290 Throwable cause = e.getCause(); 291 if (cause instanceof IOException) { 292 throw (IOException) cause; 293 } 294 throw new IOException("Failed opening " + path, cause); 295 } 296 if (LOG.isDebugEnabled()) { 297 LOG.debug("openFile().withFileStatus() not supported or failed for {}, " 298 + "fail back with open()", fs.getUri(), e); 299 } 300 } 301 } 302 return fs.open(path); 303 } 304 305 /** 306 * Returns whether it is safe to use {@link FileSystem#openFile(Path)} without bypassing a 307 * {@link FilterFileSystem} wrapper's legacy {@link FileSystem#open(Path, int)} override. 308 */ 309 private static boolean supportsOpenFile(FileSystem fs) throws IOException { 310 FileSystem effectiveFs = fs instanceof HFileSystem ? ((HFileSystem) fs).getBackingFs() : fs; 311 while (true) { 312 OpenFileSupport support = OPEN_FILE_SUPPORT_BY_CLASS.get(effectiveFs.getClass()); 313 if (support == OpenFileSupport.SUPPORTED) { 314 return true; 315 } 316 if (support == OpenFileSupport.LEGACY_OPEN) { 317 return false; 318 } 319 effectiveFs = ((FilterFileSystem) effectiveFs).getRawFileSystem(); 320 if (effectiveFs == null) { 321 return false; 322 } 323 } 324 } 325 326 /** 327 * Create the specified file on the filesystem. By default, this will: 328 * <ol> 329 * <li>overwrite the file if it exists</li> 330 * <li>apply the umask in the configuration (if it is enabled)</li> 331 * <li>use the fs configured buffer size (or 4096 if not set)</li> 332 * <li>use the configured column family replication or default replication if 333 * {@link ColumnFamilyDescriptorBuilder#DEFAULT_DFS_REPLICATION}</li> 334 * <li>use the default block size</li> 335 * <li>not track progress</li> 336 * </ol> 337 * @param conf configurations 338 * @param fs {@link FileSystem} on which to write the file 339 * @param path {@link Path} to the file to write 340 * @param perm permissions 341 * @param favoredNodes favored data nodes 342 * @param isRecursiveCreate recursively create parent directories 343 * @return output stream to the created file 344 * @throws IOException if the file cannot be created 345 */ 346 public static FSDataOutputStream create(Configuration conf, FileSystem fs, Path path, 347 FsPermission perm, InetSocketAddress[] favoredNodes, boolean isRecursiveCreate) 348 throws IOException { 349 if (fs instanceof HFileSystem) { 350 FileSystem backingFs = ((HFileSystem) fs).getBackingFs(); 351 if (backingFs instanceof DistributedFileSystem) { 352 short replication = Short.parseShort(conf.get(ColumnFamilyDescriptorBuilder.DFS_REPLICATION, 353 String.valueOf(ColumnFamilyDescriptorBuilder.DEFAULT_DFS_REPLICATION))); 354 DistributedFileSystem.HdfsDataOutputStreamBuilder builder = 355 ((DistributedFileSystem) backingFs).createFile(path).recursive().permission(perm) 356 .create(); 357 if (favoredNodes != null) { 358 builder.favoredNodes(favoredNodes); 359 } 360 if (replication > 0) { 361 builder.replication(replication); 362 } 363 return builder.build(); 364 } 365 366 } 367 return CommonFSUtils.create(fs, path, perm, true, isRecursiveCreate); 368 } 369 370 /** 371 * Checks to see if the specified file system is available 372 * @param fs filesystem 373 * @throws IOException e 374 */ 375 public static void checkFileSystemAvailable(final FileSystem fs) throws IOException { 376 if (!(fs instanceof DistributedFileSystem)) { 377 return; 378 } 379 IOException exception = null; 380 DistributedFileSystem dfs = (DistributedFileSystem) fs; 381 try { 382 if (dfs.exists(new Path("/"))) { 383 return; 384 } 385 } catch (IOException e) { 386 exception = e instanceof RemoteException ? ((RemoteException) e).unwrapRemoteException() : e; 387 } 388 try { 389 fs.close(); 390 } catch (Exception e) { 391 LOG.error("file system close failed: ", e); 392 } 393 throw new IOException("File system is not available", exception); 394 } 395 396 /** 397 * Inquire the Active NameNode's safe mode status. 398 * @param dfs A DistributedFileSystem object representing the underlying HDFS. 399 * @return whether we're in safe mode 400 */ 401 private static boolean isInSafeMode(FileSystem dfs) throws IOException { 402 if (isDistributedFileSystem(dfs)) { 403 return ((DistributedFileSystem) dfs).setSafeMode(SAFEMODE_GET, true); 404 } else { 405 try { 406 Object ret = dfs.getClass() 407 .getMethod("setSafeMode", new Class[] { safeModeActionClazz, Boolean.class }) 408 .invoke(dfs, safeModeGet, true); 409 return (Boolean) ret; 410 } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) { 411 LOG.error("The file system does not support setSafeMode(). Abort.", e); 412 throw new RuntimeException(e); 413 } 414 } 415 } 416 417 /** 418 * Check whether dfs is in safemode. 419 */ 420 public static void checkDfsSafeMode(final Configuration conf) throws IOException { 421 boolean isInSafeMode = false; 422 FileSystem fs = FileSystem.get(conf); 423 if (supportSafeMode(fs)) { 424 isInSafeMode = isInSafeMode(fs); 425 } 426 if (isInSafeMode) { 427 throw new IOException("File system is in safemode, it can't be written now"); 428 } 429 } 430 431 /** 432 * Verifies current version of file system 433 * @param fs filesystem object 434 * @param rootdir root hbase directory 435 * @return null if no version file exists, version string otherwise 436 * @throws IOException if the version file fails to open 437 * @throws DeserializationException if the version data cannot be translated into a version 438 */ 439 public static String getVersion(FileSystem fs, Path rootdir) 440 throws IOException, DeserializationException { 441 final Path versionFile = new Path(rootdir, HConstants.VERSION_FILE_NAME); 442 FileStatus[] status = null; 443 try { 444 // hadoop 2.0 throws FNFE if directory does not exist. 445 // hadoop 1.0 returns null if directory does not exist. 446 status = fs.listStatus(versionFile); 447 } catch (FileNotFoundException fnfe) { 448 return null; 449 } 450 if (ArrayUtils.getLength(status) == 0) { 451 return null; 452 } 453 String version = null; 454 byte[] content = new byte[(int) status[0].getLen()]; 455 FSDataInputStream s = fs.open(versionFile); 456 try { 457 IOUtils.readFully(s, content, 0, content.length); 458 if (ProtobufUtil.isPBMagicPrefix(content)) { 459 version = parseVersionFrom(content); 460 } else { 461 // Presume it pre-pb format. 462 try (DataInputStream dis = new DataInputStream(new ByteArrayInputStream(content))) { 463 version = dis.readUTF(); 464 } 465 } 466 } catch (EOFException eof) { 467 LOG.warn("Version file was empty, odd, will try to set it."); 468 } finally { 469 s.close(); 470 } 471 return version; 472 } 473 474 /** 475 * Parse the content of the ${HBASE_ROOTDIR}/hbase.version file. 476 * @param bytes The byte content of the hbase.version file 477 * @return The version found in the file as a String 478 * @throws DeserializationException if the version data cannot be translated into a version 479 */ 480 static String parseVersionFrom(final byte[] bytes) throws DeserializationException { 481 ProtobufUtil.expectPBMagicPrefix(bytes); 482 int pblen = ProtobufUtil.lengthOfPBMagic(); 483 FSProtos.HBaseVersionFileContent.Builder builder = 484 FSProtos.HBaseVersionFileContent.newBuilder(); 485 try { 486 ProtobufUtil.mergeFrom(builder, bytes, pblen, bytes.length - pblen); 487 return builder.getVersion(); 488 } catch (IOException e) { 489 // Convert 490 throw new DeserializationException(e); 491 } 492 } 493 494 /** 495 * Create the content to write into the ${HBASE_ROOTDIR}/hbase.version file. 496 * @param version Version to persist 497 * @return Serialized protobuf with <code>version</code> content and a bit of pb magic for a 498 * prefix. 499 */ 500 static byte[] toVersionByteArray(final String version) { 501 FSProtos.HBaseVersionFileContent.Builder builder = 502 FSProtos.HBaseVersionFileContent.newBuilder(); 503 return ProtobufUtil.prependPBMagic(builder.setVersion(version).build().toByteArray()); 504 } 505 506 /** 507 * Verifies current version of file system 508 * @param fs file system 509 * @param rootdir root directory of HBase installation 510 * @param message if true, issues a message on System.out 511 * @throws IOException if the version file cannot be opened 512 * @throws DeserializationException if the contents of the version file cannot be parsed 513 */ 514 public static void checkVersion(FileSystem fs, Path rootdir, boolean message) 515 throws IOException, DeserializationException { 516 checkVersion(fs, rootdir, message, 0, HConstants.DEFAULT_VERSION_FILE_WRITE_ATTEMPTS); 517 } 518 519 /** 520 * Verifies current version of file system 521 * @param fs file system 522 * @param rootdir root directory of HBase installation 523 * @param message if true, issues a message on System.out 524 * @param wait wait interval 525 * @param retries number of times to retry 526 * @throws IOException if the version file cannot be opened 527 * @throws DeserializationException if the contents of the version file cannot be parsed 528 */ 529 public static void checkVersion(FileSystem fs, Path rootdir, boolean message, int wait, 530 int retries) throws IOException, DeserializationException { 531 String version = getVersion(fs, rootdir); 532 String msg; 533 if (version == null) { 534 if (!metaRegionExists(fs, rootdir)) { 535 // rootDir is empty (no version file and no root region) 536 // just create new version file (HBASE-1195) 537 setVersion(fs, rootdir, wait, retries); 538 return; 539 } else { 540 msg = "hbase.version file is missing. Is your hbase.rootdir valid? " 541 + "You can restore hbase.version file by running 'HBCK2 filesystem -fix'. " 542 + "See https://github.com/apache/hbase-operator-tools/tree/master/hbase-hbck2"; 543 } 544 } else if (version.compareTo(HConstants.FILE_SYSTEM_VERSION) == 0) { 545 return; 546 } else { 547 msg = "HBase file layout needs to be upgraded. Current filesystem version is " + version 548 + " but software requires version " + HConstants.FILE_SYSTEM_VERSION 549 + ". Consult https://hbase.apache.org/docs for further information about " 550 + "upgrading HBase."; 551 } 552 553 // version is deprecated require migration 554 // Output on stdout so user sees it in terminal. 555 if (message) { 556 System.out.println("WARNING! " + msg); 557 } 558 throw new FileSystemVersionException(msg); 559 } 560 561 /** 562 * Sets version of file system 563 * @param fs filesystem object 564 * @param rootdir hbase root 565 * @throws IOException e 566 */ 567 public static void setVersion(FileSystem fs, Path rootdir) throws IOException { 568 setVersion(fs, rootdir, HConstants.FILE_SYSTEM_VERSION, 0, 569 HConstants.DEFAULT_VERSION_FILE_WRITE_ATTEMPTS); 570 } 571 572 /** 573 * Sets version of file system 574 * @param fs filesystem object 575 * @param rootdir hbase root 576 * @param wait time to wait for retry 577 * @param retries number of times to retry before failing 578 * @throws IOException e 579 */ 580 public static void setVersion(FileSystem fs, Path rootdir, int wait, int retries) 581 throws IOException { 582 setVersion(fs, rootdir, HConstants.FILE_SYSTEM_VERSION, wait, retries); 583 } 584 585 /** 586 * Sets version of file system 587 * @param fs filesystem object 588 * @param rootdir hbase root directory 589 * @param version version to set 590 * @param wait time to wait for retry 591 * @param retries number of times to retry before throwing an IOException 592 * @throws IOException e 593 */ 594 public static void setVersion(FileSystem fs, Path rootdir, String version, int wait, int retries) 595 throws IOException { 596 Path versionFile = new Path(rootdir, HConstants.VERSION_FILE_NAME); 597 Path tempVersionFile = new Path(rootdir, 598 HConstants.HBASE_TEMP_DIRECTORY + Path.SEPARATOR + HConstants.VERSION_FILE_NAME); 599 while (true) { 600 try { 601 // Write the version to a temporary file 602 FSDataOutputStream s = fs.create(tempVersionFile); 603 try { 604 s.write(toVersionByteArray(version)); 605 s.close(); 606 s = null; 607 // Move the temp version file to its normal location. Returns false 608 // if the rename failed. Throw an IOE in that case. 609 if (!fs.rename(tempVersionFile, versionFile)) { 610 throw new IOException("Unable to move temp version file to " + versionFile); 611 } 612 } finally { 613 // Cleaning up the temporary if the rename failed would be trying 614 // too hard. We'll unconditionally create it again the next time 615 // through anyway, files are overwritten by default by create(). 616 617 // Attempt to close the stream on the way out if it is still open. 618 try { 619 if (s != null) s.close(); 620 } catch (IOException ignore) { 621 } 622 } 623 LOG.info("Created version file at " + rootdir.toString() + " with version=" + version); 624 return; 625 } catch (IOException e) { 626 if (retries > 0) { 627 LOG.debug("Unable to create version file at " + rootdir.toString() + ", retrying", e); 628 fs.delete(versionFile, false); 629 try { 630 if (wait > 0) { 631 Thread.sleep(wait); 632 } 633 } catch (InterruptedException ie) { 634 throw (InterruptedIOException) new InterruptedIOException().initCause(ie); 635 } 636 retries--; 637 } else { 638 throw e; 639 } 640 } 641 } 642 } 643 644 /** 645 * Checks that a cluster ID file exists in the HBase root directory 646 * @param fs the root directory FileSystem 647 * @param rootdir the HBase root directory in HDFS 648 * @param wait how long to wait between retries 649 * @return <code>true</code> if the file exists, otherwise <code>false</code> 650 * @throws IOException if checking the FileSystem fails 651 */ 652 public static boolean checkFileExistsInHbaseRootDir(FileSystem fs, Path rootdir, String file, 653 long wait) throws IOException { 654 while (true) { 655 try { 656 Path filePath = new Path(rootdir, file); 657 return fs.exists(filePath); 658 } catch (IOException ioe) { 659 if (wait > 0L) { 660 LOG.warn("Unable to check file {} in {}, retrying in {}ms", file, rootdir, wait, ioe); 661 try { 662 Thread.sleep(wait); 663 } catch (InterruptedException e) { 664 Thread.currentThread().interrupt(); 665 throw (InterruptedIOException) new InterruptedIOException().initCause(e); 666 } 667 } else { 668 throw ioe; 669 } 670 } 671 } 672 } 673 674 /** 675 * Use the given parser object to read and parse contents of Cluster Id file. e.g. Cluster Id or 676 * Active read-replica Cluster Id 677 */ 678 public static <T extends ClusterIdFile> T getClusterIdFile(FileSystem fs, Path rootdir, 679 ClusterIdFileParser<T> parser) throws IOException { 680 Path idPath = new Path(rootdir, parser.getFileName()); 681 T cs = null; 682 FileStatus status = fs.exists(idPath) ? fs.getFileStatus(idPath) : null; 683 if (status != null) { 684 int len = Ints.checkedCast(status.getLen()); 685 byte[] content = new byte[len]; 686 FSDataInputStream in = fs.open(idPath); 687 try { 688 in.readFully(content); 689 } catch (EOFException eof) { 690 LOG.warn("Cluster file {} is empty", idPath); 691 } finally { 692 in.close(); 693 } 694 try { 695 cs = parser.parseFrom(content); 696 } catch (DeserializationException e) { 697 throw new IOException("content=" + Bytes.toString(content), e); 698 } 699 // If not pb'd, make it so. 700 if (!ProtobufUtil.isPBMagicPrefix(content)) { 701 String cid = null; 702 in = fs.open(idPath); 703 try { 704 cid = in.readUTF(); 705 cs = parser.readString(cid); 706 } catch (EOFException eof) { 707 LOG.warn("Cluster file {} is empty", idPath); 708 } finally { 709 in.close(); 710 } 711 rewriteAsPb(fs, rootdir, idPath, parser.getFileName(), cs); 712 } 713 return cs; 714 } else { 715 LOG.warn("Cluster file does not exist at {}", idPath); 716 } 717 return cs; 718 } 719 720 public static String getClusterIdFromActiveClusterFile(FileSystem fs, Path rootDir) { 721 String activeClusterId = null; 722 try { 723 ActiveClusterSuffix parsedClusterIdFile = 724 FSUtils.getClusterIdFile(fs, rootDir, new ActiveClusterSuffix.Parser()); 725 if (parsedClusterIdFile != null) { 726 activeClusterId = parsedClusterIdFile.toString(); 727 } 728 } catch (IOException e) { 729 LOG.debug("Failed to read active cluster ID from file", e); 730 } 731 return activeClusterId; 732 } 733 734 private static <T extends ClusterIdFile> void rewriteAsPb(final FileSystem fs, final Path rootdir, 735 final Path p, final String fileName, final T cs) throws IOException { 736 // Rewrite the file as pb. Move aside the old one first, write new 737 // then delete the moved-aside file. 738 Path movedAsideName = new Path(p + "." + EnvironmentEdgeManager.currentTime()); 739 if (!fs.rename(p, movedAsideName)) throw new IOException("Failed rename of " + p); 740 setClusterIdFile(fs, rootdir, fileName, cs, 100); 741 if (!fs.delete(movedAsideName, false)) { 742 throw new IOException("Failed delete of " + movedAsideName); 743 } 744 LOG.debug("Rewrote the {} file as pb", fileName); 745 } 746 747 /** 748 * Writes a new unique identifier for this cluster to the Cluster Id ("hbase.id" or 749 * "active.cluster.suffix.id") file in the HBase root directory. If any operations on the ID file 750 * fails, and {@code wait} is a positive value, the method will retry to produce the ID file until 751 * the thread is forcibly interrupted. 752 * @param fs the root directory FileSystem 753 * @param rootdir the path to the HBase root directory 754 * @param fileName name of the file to be written 755 * @param cs the object to be written 756 * @param wait how long (in milliseconds) to wait between retries 757 * @throws IOException if writing to the FileSystem fails and no wait value 758 */ 759 public static <T extends ClusterIdFile> void setClusterIdFile(final FileSystem fs, 760 final Path rootdir, final String fileName, final T cs, final long wait) throws IOException { 761 final Path idFile = new Path(rootdir, fileName); 762 final Path tempDir = new Path(rootdir, HConstants.HBASE_TEMP_DIRECTORY); 763 final Path tempIdFile = new Path(tempDir, fileName); 764 765 LOG.debug("Cluster file [{}] is present and contains cluster id: {}", idFile, cs); 766 writeClusterInfo(fs, rootdir, idFile, tempIdFile, cs.toByteArray(), wait); 767 } 768 769 /** 770 * Writes information about this cluster to the specified file. For ex, it is used for writing 771 * cluster id in "hbase.id" file in the HBase root directory. Also, used for writing active 772 * cluster suffix in "active_cluster_suffix.id" file. If any operations on the ID file fails, and 773 * {@code wait} is a positive value, the method will retry to produce the ID file until the thread 774 * is forcibly interrupted. 775 */ 776 private static void writeClusterInfo(final FileSystem fs, final Path rootdir, final Path idFile, 777 final Path tempIdFile, byte[] fileData, final long wait) throws IOException { 778 while (true) { 779 Optional<IOException> failure = Optional.empty(); 780 781 LOG.debug("Write the file to a temporary location: {}", tempIdFile); 782 try (FSDataOutputStream s = fs.create(tempIdFile)) { 783 s.write(fileData); 784 } catch (IOException ioe) { 785 failure = Optional.of(ioe); 786 } 787 788 if (!failure.isPresent()) { 789 try { 790 LOG.debug("Move the temporary file to its target location [{}]:[{}]", tempIdFile, idFile); 791 792 if (!fs.rename(tempIdFile, idFile)) { 793 failure = Optional.of(new IOException("Unable to move temp file to " + idFile)); 794 } 795 } catch (IOException ioe) { 796 failure = Optional.of(ioe); 797 } 798 } 799 800 if (failure.isPresent()) { 801 final IOException cause = failure.get(); 802 if (wait > 0L) { 803 LOG.warn("Unable to create file in {}, retrying in {}ms", rootdir, wait, cause); 804 try { 805 Thread.sleep(wait); 806 } catch (InterruptedException e) { 807 Thread.currentThread().interrupt(); 808 throw (InterruptedIOException) new InterruptedIOException().initCause(e); 809 } 810 continue; 811 } else { 812 throw cause; 813 } 814 } else { 815 return; 816 } 817 } 818 } 819 820 /** 821 * If DFS, check safe mode and if so, wait until we clear it. 822 * @param conf configuration 823 * @param wait Sleep between retries 824 * @throws IOException e 825 */ 826 public static void waitOnSafeMode(final Configuration conf, final long wait) throws IOException { 827 FileSystem fs = FileSystem.get(conf); 828 if (!supportSafeMode(fs)) { 829 return; 830 } 831 // Make sure dfs is not in safe mode 832 while (isInSafeMode(fs)) { 833 LOG.info("Waiting for dfs to exit safe mode..."); 834 try { 835 Thread.sleep(wait); 836 } catch (InterruptedException e) { 837 Thread.currentThread().interrupt(); 838 throw (InterruptedIOException) new InterruptedIOException().initCause(e); 839 } 840 } 841 } 842 843 public static boolean supportSafeMode(FileSystem fs) { 844 // return true if HDFS. 845 if (fs instanceof DistributedFileSystem) { 846 return true; 847 } 848 // return true if the file system implements SafeMode interface. 849 if (safeModeClazz != null) { 850 return (safeModeClazz.isAssignableFrom(fs.getClass())); 851 } 852 // return false if the file system is not HDFS and does not implement SafeMode interface. 853 return false; 854 } 855 856 /** 857 * Checks if meta region exists 858 * @param fs file system 859 * @param rootDir root directory of HBase installation 860 * @return true if exists 861 */ 862 public static boolean metaRegionExists(FileSystem fs, Path rootDir) throws IOException { 863 Path metaRegionDir = getRegionDirFromRootDir(rootDir, RegionInfoBuilder.FIRST_META_REGIONINFO); 864 return fs.exists(metaRegionDir); 865 } 866 867 /** 868 * Compute HDFS block distribution of a given HdfsDataInputStream. All HdfsDataInputStreams are 869 * backed by a series of LocatedBlocks, which are fetched periodically from the namenode. This 870 * method retrieves those blocks from the input stream and uses them to calculate 871 * HDFSBlockDistribution. The underlying method in DFSInputStream does attempt to use locally 872 * cached blocks, but may hit the namenode if the cache is determined to be incomplete. The method 873 * also involves making copies of all LocatedBlocks rather than return the underlying blocks 874 * themselves. 875 */ 876 static public HDFSBlocksDistribution 877 computeHDFSBlocksDistribution(HdfsDataInputStream inputStream) throws IOException { 878 List<LocatedBlock> blocks = inputStream.getAllBlocks(); 879 HDFSBlocksDistribution blocksDistribution = new HDFSBlocksDistribution(); 880 for (LocatedBlock block : blocks) { 881 String[] hosts = getHostsForLocations(block); 882 long len = block.getBlockSize(); 883 StorageType[] storageTypes = block.getStorageTypes(); 884 blocksDistribution.addHostsAndBlockWeight(hosts, len, storageTypes); 885 } 886 return blocksDistribution; 887 } 888 889 private static String[] getHostsForLocations(LocatedBlock block) { 890 DatanodeInfo[] locations = getLocatedBlockLocations(block); 891 String[] hosts = new String[locations.length]; 892 for (int i = 0; i < hosts.length; i++) { 893 hosts[i] = locations[i].getHostName(); 894 } 895 return hosts; 896 } 897 898 /** 899 * Compute HDFS blocks distribution of a given file, or a portion of the file 900 * @param fs file system 901 * @param status file status of the file 902 * @param start start position of the portion 903 * @param length length of the portion 904 * @return The HDFS blocks distribution 905 */ 906 static public HDFSBlocksDistribution computeHDFSBlocksDistribution(final FileSystem fs, 907 FileStatus status, long start, long length) throws IOException { 908 HDFSBlocksDistribution blocksDistribution = new HDFSBlocksDistribution(); 909 BlockLocation[] blockLocations = fs.getFileBlockLocations(status, start, length); 910 addToHDFSBlocksDistribution(blocksDistribution, blockLocations); 911 return blocksDistribution; 912 } 913 914 /** 915 * Update blocksDistribution with blockLocations 916 * @param blocksDistribution the hdfs blocks distribution 917 * @param blockLocations an array containing block location 918 */ 919 static public void addToHDFSBlocksDistribution(HDFSBlocksDistribution blocksDistribution, 920 BlockLocation[] blockLocations) throws IOException { 921 for (BlockLocation bl : blockLocations) { 922 String[] hosts = bl.getHosts(); 923 long len = bl.getLength(); 924 StorageType[] storageTypes = bl.getStorageTypes(); 925 blocksDistribution.addHostsAndBlockWeight(hosts, len, storageTypes); 926 } 927 } 928 929 // TODO move this method OUT of FSUtils. No dependencies to HMaster 930 /** 931 * Returns the total overall fragmentation percentage. Includes hbase:meta and -ROOT- as well. 932 * @param master The master defining the HBase root and file system 933 * @return A map for each table and its percentage (never null) 934 * @throws IOException When scanning the directory fails 935 */ 936 public static int getTotalTableFragmentation(final HMaster master) throws IOException { 937 Map<String, Integer> map = getTableFragmentation(master); 938 return map.isEmpty() ? -1 : map.get("-TOTAL-"); 939 } 940 941 /** 942 * Runs through the HBase rootdir and checks how many stores for each table have more than one 943 * file in them. Checks -ROOT- and hbase:meta too. The total percentage across all tables is 944 * stored under the special key "-TOTAL-". 945 * @param master The master defining the HBase root and file system. 946 * @return A map for each table and its percentage (never null). 947 * @throws IOException When scanning the directory fails. 948 */ 949 public static Map<String, Integer> getTableFragmentation(final HMaster master) 950 throws IOException { 951 Path path = CommonFSUtils.getRootDir(master.getConfiguration()); 952 // since HMaster.getFileSystem() is package private 953 FileSystem fs = path.getFileSystem(master.getConfiguration()); 954 return getTableFragmentation(fs, path); 955 } 956 957 /** 958 * Runs through the HBase rootdir and checks how many stores for each table have more than one 959 * file in them. Checks -ROOT- and hbase:meta too. The total percentage across all tables is 960 * stored under the special key "-TOTAL-". 961 * @param fs The file system to use 962 * @param hbaseRootDir The root directory to scan 963 * @return A map for each table and its percentage (never null) 964 * @throws IOException When scanning the directory fails 965 */ 966 public static Map<String, Integer> getTableFragmentation(final FileSystem fs, 967 final Path hbaseRootDir) throws IOException { 968 Map<String, Integer> frags = new HashMap<>(); 969 int cfCountTotal = 0; 970 int cfFragTotal = 0; 971 PathFilter regionFilter = new RegionDirFilter(fs); 972 PathFilter familyFilter = new FamilyDirFilter(fs); 973 List<Path> tableDirs = getTableDirs(fs, hbaseRootDir); 974 for (Path d : tableDirs) { 975 int cfCount = 0; 976 int cfFrag = 0; 977 FileStatus[] regionDirs = fs.listStatus(d, regionFilter); 978 for (FileStatus regionDir : regionDirs) { 979 Path dd = regionDir.getPath(); 980 // else its a region name, now look in region for families 981 FileStatus[] familyDirs = fs.listStatus(dd, familyFilter); 982 for (FileStatus familyDir : familyDirs) { 983 cfCount++; 984 cfCountTotal++; 985 Path family = familyDir.getPath(); 986 // now in family make sure only one file 987 FileStatus[] familyStatus = fs.listStatus(family); 988 if (familyStatus.length > 1) { 989 cfFrag++; 990 cfFragTotal++; 991 } 992 } 993 } 994 // compute percentage per table and store in result list 995 frags.put(CommonFSUtils.getTableName(d).getNameAsString(), 996 cfCount == 0 ? 0 : Math.round((float) cfFrag / cfCount * 100)); 997 } 998 // set overall percentage for all tables 999 frags.put("-TOTAL-", 1000 cfCountTotal == 0 ? 0 : Math.round((float) cfFragTotal / cfCountTotal * 100)); 1001 return frags; 1002 } 1003 1004 public static void renameFile(FileSystem fs, Path src, Path dst) throws IOException { 1005 if (fs.exists(dst) && !fs.delete(dst, false)) { 1006 throw new IOException("Can not delete " + dst); 1007 } 1008 if (!fs.rename(src, dst)) { 1009 throw new IOException("Can not rename from " + src + " to " + dst); 1010 } 1011 } 1012 1013 /** 1014 * A {@link PathFilter} that returns only regular files. 1015 */ 1016 static class FileFilter extends AbstractFileStatusFilter { 1017 private final FileSystem fs; 1018 1019 public FileFilter(final FileSystem fs) { 1020 this.fs = fs; 1021 } 1022 1023 @Override 1024 protected boolean accept(Path p, @CheckForNull Boolean isDir) { 1025 try { 1026 return isFile(fs, isDir, p); 1027 } catch (IOException e) { 1028 LOG.warn("Unable to verify if path={} is a regular file", p, e); 1029 return false; 1030 } 1031 } 1032 } 1033 1034 /** 1035 * Directory filter that doesn't include any of the directories in the specified blacklist 1036 */ 1037 public static class BlackListDirFilter extends AbstractFileStatusFilter { 1038 private final FileSystem fs; 1039 private List<String> blacklist; 1040 1041 /** 1042 * Create a filter on the givem filesystem with the specified blacklist 1043 * @param fs filesystem to filter 1044 * @param directoryNameBlackList list of the names of the directories to filter. If 1045 * <tt>null</tt>, all directories are returned 1046 */ 1047 @SuppressWarnings("unchecked") 1048 public BlackListDirFilter(final FileSystem fs, final List<String> directoryNameBlackList) { 1049 this.fs = fs; 1050 blacklist = (List<String>) (directoryNameBlackList == null 1051 ? Collections.emptyList() 1052 : directoryNameBlackList); 1053 } 1054 1055 @Override 1056 protected boolean accept(Path p, @CheckForNull Boolean isDir) { 1057 if (!isValidName(p.getName())) { 1058 return false; 1059 } 1060 1061 try { 1062 return isDirectory(fs, isDir, p); 1063 } catch (IOException e) { 1064 LOG.warn("An error occurred while verifying if [{}] is a valid directory." 1065 + " Returning 'not valid' and continuing.", p, e); 1066 return false; 1067 } 1068 } 1069 1070 protected boolean isValidName(final String name) { 1071 return !blacklist.contains(name); 1072 } 1073 } 1074 1075 /** 1076 * A {@link PathFilter} that only allows directories. 1077 */ 1078 public static class DirFilter extends BlackListDirFilter { 1079 1080 public DirFilter(FileSystem fs) { 1081 super(fs, null); 1082 } 1083 } 1084 1085 /** 1086 * A {@link PathFilter} that returns usertable directories. To get all directories use the 1087 * {@link BlackListDirFilter} with a <tt>null</tt> blacklist 1088 */ 1089 public static class UserTableDirFilter extends BlackListDirFilter { 1090 public UserTableDirFilter(FileSystem fs) { 1091 super(fs, HConstants.HBASE_NON_TABLE_DIRS); 1092 } 1093 1094 @Override 1095 protected boolean isValidName(final String name) { 1096 if (!super.isValidName(name)) return false; 1097 1098 try { 1099 TableName.isLegalTableQualifierName(Bytes.toBytes(name)); 1100 } catch (IllegalArgumentException e) { 1101 LOG.info("Invalid table name: {}", name); 1102 return false; 1103 } 1104 return true; 1105 } 1106 } 1107 1108 public static List<Path> getTableDirs(final FileSystem fs, final Path rootdir) 1109 throws IOException { 1110 List<Path> tableDirs = new ArrayList<>(); 1111 Path baseNamespaceDir = new Path(rootdir, HConstants.BASE_NAMESPACE_DIR); 1112 if (fs.exists(baseNamespaceDir)) { 1113 for (FileStatus status : fs.globStatus(new Path(baseNamespaceDir, "*"))) { 1114 tableDirs.addAll(FSUtils.getLocalTableDirs(fs, status.getPath())); 1115 } 1116 } 1117 return tableDirs; 1118 } 1119 1120 /** 1121 * @return All the table directories under <code>rootdir</code>. Ignore non table hbase folders 1122 * such as .logs, .oldlogs, .corrupt folders. 1123 */ 1124 public static List<Path> getLocalTableDirs(final FileSystem fs, final Path rootdir) 1125 throws IOException { 1126 // presumes any directory under hbase.rootdir is a table 1127 FileStatus[] dirs = fs.listStatus(rootdir, new UserTableDirFilter(fs)); 1128 List<Path> tabledirs = new ArrayList<>(dirs.length); 1129 for (FileStatus dir : dirs) { 1130 tabledirs.add(dir.getPath()); 1131 } 1132 return tabledirs; 1133 } 1134 1135 /** 1136 * A filter to exclude meta tables belonging to foreign clusters. This is essential in a 1137 * read-replica setup where multiple clusters share the same fs. 1138 * @param tablePath The Path to the table directory. 1139 * @return {@code true} if the path is a regular table or the cluster's own meta table. 1140 * {@code false} if it is a meta table belonging to a different cluster. 1141 */ 1142 public static boolean isLocalMetaTable(Path tablePath) { 1143 if (tablePath == null) { 1144 return false; 1145 } 1146 String dirName = tablePath.getName(); 1147 if (dirName.startsWith(TableName.META_TABLE_NAME.getQualifierAsString())) { 1148 return TableName.valueOf(TableName.META_TABLE_NAME.getNamespaceAsString(), dirName) 1149 .equals(TableName.META_TABLE_NAME); 1150 } 1151 return true; 1152 } 1153 1154 /** 1155 * Filter for all dirs that don't start with '.' 1156 */ 1157 public static class RegionDirFilter extends AbstractFileStatusFilter { 1158 // This pattern will accept 0.90+ style hex region dirs and older numeric region dir names. 1159 final public static Pattern regionDirPattern = Pattern.compile("^[0-9a-f]*$"); 1160 final FileSystem fs; 1161 1162 public RegionDirFilter(FileSystem fs) { 1163 this.fs = fs; 1164 } 1165 1166 @Override 1167 protected boolean accept(Path p, @CheckForNull Boolean isDir) { 1168 if (!regionDirPattern.matcher(p.getName()).matches()) { 1169 return false; 1170 } 1171 1172 try { 1173 return isDirectory(fs, isDir, p); 1174 } catch (IOException ioe) { 1175 // Maybe the file was moved or the fs was disconnected. 1176 LOG.warn("Skipping file {} due to IOException", p, ioe); 1177 return false; 1178 } 1179 } 1180 } 1181 1182 /** 1183 * Given a particular table dir, return all the regiondirs inside it, excluding files such as 1184 * .tableinfo 1185 * @param fs A file system for the Path 1186 * @param tableDir Path to a specific table directory <hbase.rootdir>/<tabledir> 1187 * @return List of paths to valid region directories in table dir. 1188 */ 1189 public static List<Path> getRegionDirs(final FileSystem fs, final Path tableDir) 1190 throws IOException { 1191 // assumes we are in a table dir. 1192 List<FileStatus> rds = listStatusWithStatusFilter(fs, tableDir, new RegionDirFilter(fs)); 1193 if (rds == null) { 1194 return Collections.emptyList(); 1195 } 1196 List<Path> regionDirs = new ArrayList<>(rds.size()); 1197 for (FileStatus rdfs : rds) { 1198 Path rdPath = rdfs.getPath(); 1199 regionDirs.add(rdPath); 1200 } 1201 return regionDirs; 1202 } 1203 1204 public static Path getRegionDirFromRootDir(Path rootDir, RegionInfo region) { 1205 return getRegionDirFromTableDir(CommonFSUtils.getTableDir(rootDir, region.getTable()), region); 1206 } 1207 1208 public static Path getRegionDirFromTableDir(Path tableDir, RegionInfo region) { 1209 return getRegionDirFromTableDir(tableDir, 1210 ServerRegionReplicaUtil.getRegionInfoForFs(region).getEncodedName()); 1211 } 1212 1213 public static Path getRegionDirFromTableDir(Path tableDir, String encodedRegionName) { 1214 return new Path(tableDir, encodedRegionName); 1215 } 1216 1217 /** 1218 * Filter for all dirs that are legal column family names. This is generally used for colfam dirs 1219 * <hbase.rootdir>/<tabledir>/<regiondir>/<colfamdir>. 1220 */ 1221 public static class FamilyDirFilter extends AbstractFileStatusFilter { 1222 final FileSystem fs; 1223 1224 public FamilyDirFilter(FileSystem fs) { 1225 this.fs = fs; 1226 } 1227 1228 @Override 1229 protected boolean accept(Path p, @CheckForNull Boolean isDir) { 1230 try { 1231 // throws IAE if invalid 1232 ColumnFamilyDescriptorBuilder.isLegalColumnFamilyName(Bytes.toBytes(p.getName())); 1233 } catch (IllegalArgumentException iae) { 1234 // path name is an invalid family name and thus is excluded. 1235 return false; 1236 } 1237 1238 try { 1239 return isDirectory(fs, isDir, p); 1240 } catch (IOException ioe) { 1241 // Maybe the file was moved or the fs was disconnected. 1242 LOG.warn("Skipping file {} due to IOException", p, ioe); 1243 return false; 1244 } 1245 } 1246 } 1247 1248 /** 1249 * Given a particular region dir, return all the familydirs inside it 1250 * @param fs A file system for the Path 1251 * @param regionDir Path to a specific region directory 1252 * @return List of paths to valid family directories in region dir. 1253 */ 1254 public static List<Path> getFamilyDirs(final FileSystem fs, final Path regionDir) 1255 throws IOException { 1256 // assumes we are in a region dir. 1257 return getFilePaths(fs, regionDir, new FamilyDirFilter(fs)); 1258 } 1259 1260 public static List<Path> getReferenceFilePaths(final FileSystem fs, final Path familyDir) 1261 throws IOException { 1262 return getFilePaths(fs, familyDir, new ReferenceFileFilter(fs)); 1263 } 1264 1265 public static List<Path> getReferenceAndLinkFilePaths(final FileSystem fs, final Path familyDir) 1266 throws IOException { 1267 return getFilePaths(fs, familyDir, new ReferenceAndLinkFileFilter(fs)); 1268 } 1269 1270 private static List<Path> getFilePaths(final FileSystem fs, final Path dir, 1271 final PathFilter pathFilter) throws IOException { 1272 FileStatus[] fds = fs.listStatus(dir, pathFilter); 1273 List<Path> files = new ArrayList<>(fds.length); 1274 for (FileStatus fdfs : fds) { 1275 Path fdPath = fdfs.getPath(); 1276 files.add(fdPath); 1277 } 1278 return files; 1279 } 1280 1281 public static int getRegionReferenceAndLinkFileCount(final FileSystem fs, final Path p) { 1282 int result = 0; 1283 try { 1284 for (Path familyDir : getFamilyDirs(fs, p)) { 1285 result += getReferenceAndLinkFilePaths(fs, familyDir).size(); 1286 } 1287 } catch (IOException e) { 1288 LOG.warn("Error Counting reference files.", e); 1289 } 1290 return result; 1291 } 1292 1293 public static class ReferenceAndLinkFileFilter implements PathFilter { 1294 1295 private final FileSystem fs; 1296 1297 public ReferenceAndLinkFileFilter(FileSystem fs) { 1298 this.fs = fs; 1299 } 1300 1301 @Override 1302 public boolean accept(Path rd) { 1303 try { 1304 // only files can be references. 1305 return !fs.getFileStatus(rd).isDirectory() 1306 && (StoreFileInfo.isReference(rd) || HFileLink.isHFileLink(rd)); 1307 } catch (IOException ioe) { 1308 // Maybe the file was moved or the fs was disconnected. 1309 LOG.warn("Skipping file " + rd + " due to IOException", ioe); 1310 return false; 1311 } 1312 } 1313 } 1314 1315 /** 1316 * Filter for HFiles that excludes reference files. 1317 */ 1318 public static class HFileFilter extends AbstractFileStatusFilter { 1319 final FileSystem fs; 1320 1321 public HFileFilter(FileSystem fs) { 1322 this.fs = fs; 1323 } 1324 1325 @Override 1326 protected boolean accept(Path p, @CheckForNull Boolean isDir) { 1327 if (!StoreFileInfo.isHFile(p) && !StoreFileInfo.isMobFile(p)) { 1328 return false; 1329 } 1330 1331 try { 1332 return isFile(fs, isDir, p); 1333 } catch (IOException ioe) { 1334 // Maybe the file was moved or the fs was disconnected. 1335 LOG.warn("Skipping file {} due to IOException", p, ioe); 1336 return false; 1337 } 1338 } 1339 } 1340 1341 /** 1342 * Filter for HFileLinks (StoreFiles and HFiles not included). the filter itself does not consider 1343 * if a link is file or not. 1344 */ 1345 public static class HFileLinkFilter implements PathFilter { 1346 1347 @Override 1348 public boolean accept(Path p) { 1349 return HFileLink.isHFileLink(p); 1350 } 1351 } 1352 1353 public static class ReferenceFileFilter extends AbstractFileStatusFilter { 1354 1355 private final FileSystem fs; 1356 1357 public ReferenceFileFilter(FileSystem fs) { 1358 this.fs = fs; 1359 } 1360 1361 @Override 1362 protected boolean accept(Path p, @CheckForNull Boolean isDir) { 1363 if (!StoreFileInfo.isReference(p)) { 1364 return false; 1365 } 1366 1367 try { 1368 // only files can be references. 1369 return isFile(fs, isDir, p); 1370 } catch (IOException ioe) { 1371 // Maybe the file was moved or the fs was disconnected. 1372 LOG.warn("Skipping file {} due to IOException", p, ioe); 1373 return false; 1374 } 1375 } 1376 } 1377 1378 /** 1379 * Called every so-often by storefile map builder getTableStoreFilePathMap to report progress. 1380 */ 1381 interface ProgressReporter { 1382 /** 1383 * @param status File or directory we are about to process. 1384 */ 1385 void progress(FileStatus status); 1386 } 1387 1388 /** 1389 * Runs through the HBase rootdir/tablename and creates a reverse lookup map for table StoreFile 1390 * names to the full Path. <br> 1391 * Example...<br> 1392 * Key = 3944417774205889744 <br> 1393 * Value = hdfs://localhost:51169/user/userid/-ROOT-/70236052/info/3944417774205889744 1394 * @param map map to add values. If null, this method will create and populate one to 1395 * return 1396 * @param fs The file system to use. 1397 * @param hbaseRootDir The root directory to scan. 1398 * @param tableName name of the table to scan. 1399 * @return Map keyed by StoreFile name with a value of the full Path. 1400 * @throws IOException When scanning the directory fails. 1401 */ 1402 public static Map<String, Path> getTableStoreFilePathMap(Map<String, Path> map, 1403 final FileSystem fs, final Path hbaseRootDir, TableName tableName) 1404 throws IOException, InterruptedException { 1405 return getTableStoreFilePathMap(map, fs, hbaseRootDir, tableName, null, null, 1406 (ProgressReporter) null); 1407 } 1408 1409 /** 1410 * Runs through the HBase rootdir/tablename and creates a reverse lookup map for table StoreFile 1411 * names to the full Path. Note that because this method can be called on a 'live' HBase system 1412 * that we will skip files that no longer exist by the time we traverse them and similarly the 1413 * user of the result needs to consider that some entries in this map may not exist by the time 1414 * this call completes. <br> 1415 * Example...<br> 1416 * Key = 3944417774205889744 <br> 1417 * Value = hdfs://localhost:51169/user/userid/-ROOT-/70236052/info/3944417774205889744 1418 * @param resultMap map to add values. If null, this method will create and populate one to 1419 * return 1420 * @param fs The file system to use. 1421 * @param hbaseRootDir The root directory to scan. 1422 * @param tableName name of the table to scan. 1423 * @param sfFilter optional path filter to apply to store files 1424 * @param executor optional executor service to parallelize this operation 1425 * @param progressReporter Instance or null; gets called every time we move to new region of 1426 * family dir and for each store file. 1427 * @return Map keyed by StoreFile name with a value of the full Path. 1428 * @throws IOException When scanning the directory fails. 1429 * @deprecated Since 2.3.0. For removal in hbase4. Use ProgressReporter override instead. 1430 */ 1431 @Deprecated 1432 public static Map<String, Path> getTableStoreFilePathMap(Map<String, Path> resultMap, 1433 final FileSystem fs, final Path hbaseRootDir, TableName tableName, final PathFilter sfFilter, 1434 ExecutorService executor, final HbckErrorReporter progressReporter) 1435 throws IOException, InterruptedException { 1436 return getTableStoreFilePathMap(resultMap, fs, hbaseRootDir, tableName, sfFilter, executor, 1437 new ProgressReporter() { 1438 @Override 1439 public void progress(FileStatus status) { 1440 // status is not used in this implementation. 1441 progressReporter.progress(); 1442 } 1443 }); 1444 } 1445 1446 /** 1447 * Runs through the HBase rootdir/tablename and creates a reverse lookup map for table StoreFile 1448 * names to the full Path. Note that because this method can be called on a 'live' HBase system 1449 * that we will skip files that no longer exist by the time we traverse them and similarly the 1450 * user of the result needs to consider that some entries in this map may not exist by the time 1451 * this call completes. <br> 1452 * Example...<br> 1453 * Key = 3944417774205889744 <br> 1454 * Value = hdfs://localhost:51169/user/userid/-ROOT-/70236052/info/3944417774205889744 1455 * @param resultMap map to add values. If null, this method will create and populate one to 1456 * return 1457 * @param fs The file system to use. 1458 * @param hbaseRootDir The root directory to scan. 1459 * @param tableName name of the table to scan. 1460 * @param sfFilter optional path filter to apply to store files 1461 * @param executor optional executor service to parallelize this operation 1462 * @param progressReporter Instance or null; gets called every time we move to new region of 1463 * family dir and for each store file. 1464 * @return Map keyed by StoreFile name with a value of the full Path. 1465 * @throws IOException When scanning the directory fails. 1466 * @throws InterruptedException the thread is interrupted, either before or during the activity. 1467 */ 1468 public static Map<String, Path> getTableStoreFilePathMap(Map<String, Path> resultMap, 1469 final FileSystem fs, final Path hbaseRootDir, TableName tableName, final PathFilter sfFilter, 1470 ExecutorService executor, final ProgressReporter progressReporter) 1471 throws IOException, InterruptedException { 1472 1473 final Map<String, Path> finalResultMap = 1474 resultMap == null ? new ConcurrentHashMap<>(128, 0.75f, 32) : resultMap; 1475 1476 // only include the directory paths to tables 1477 Path tableDir = CommonFSUtils.getTableDir(hbaseRootDir, tableName); 1478 // Inside a table, there are compaction.dir directories to skip. Otherwise, all else 1479 // should be regions. 1480 final FamilyDirFilter familyFilter = new FamilyDirFilter(fs); 1481 final Vector<Exception> exceptions = new Vector<>(); 1482 1483 try { 1484 List<FileStatus> regionDirs = 1485 FSUtils.listStatusWithStatusFilter(fs, tableDir, new RegionDirFilter(fs)); 1486 if (regionDirs == null) { 1487 return finalResultMap; 1488 } 1489 1490 final List<Future<?>> futures = new ArrayList<>(regionDirs.size()); 1491 1492 for (FileStatus regionDir : regionDirs) { 1493 if (null != progressReporter) { 1494 progressReporter.progress(regionDir); 1495 } 1496 final Path dd = regionDir.getPath(); 1497 1498 if (!exceptions.isEmpty()) { 1499 break; 1500 } 1501 1502 Runnable getRegionStoreFileMapCall = new Runnable() { 1503 @Override 1504 public void run() { 1505 try { 1506 HashMap<String, Path> regionStoreFileMap = new HashMap<>(); 1507 List<FileStatus> familyDirs = 1508 FSUtils.listStatusWithStatusFilter(fs, dd, familyFilter); 1509 if (familyDirs == null) { 1510 if (!fs.exists(dd)) { 1511 LOG.warn("Skipping region because it no longer exists: " + dd); 1512 } else { 1513 LOG.warn("Skipping region because it has no family dirs: " + dd); 1514 } 1515 return; 1516 } 1517 for (FileStatus familyDir : familyDirs) { 1518 if (null != progressReporter) { 1519 progressReporter.progress(familyDir); 1520 } 1521 Path family = familyDir.getPath(); 1522 if (family.getName().equals(HConstants.RECOVERED_EDITS_DIR)) { 1523 continue; 1524 } 1525 // now in family, iterate over the StoreFiles and 1526 // put in map 1527 FileStatus[] familyStatus = fs.listStatus(family); 1528 for (FileStatus sfStatus : familyStatus) { 1529 if (null != progressReporter) { 1530 progressReporter.progress(sfStatus); 1531 } 1532 Path sf = sfStatus.getPath(); 1533 if (sfFilter == null || sfFilter.accept(sf)) { 1534 regionStoreFileMap.put(sf.getName(), sf); 1535 } 1536 } 1537 } 1538 finalResultMap.putAll(regionStoreFileMap); 1539 } catch (Exception e) { 1540 LOG.error("Could not get region store file map for region: " + dd, e); 1541 exceptions.add(e); 1542 } 1543 } 1544 }; 1545 1546 // If executor is available, submit async tasks to exec concurrently, otherwise 1547 // just do serial sync execution 1548 if (executor != null) { 1549 Future<?> future = executor.submit(getRegionStoreFileMapCall); 1550 futures.add(future); 1551 } else { 1552 FutureTask<?> future = new FutureTask<>(getRegionStoreFileMapCall, null); 1553 future.run(); 1554 futures.add(future); 1555 } 1556 } 1557 1558 // Ensure all pending tasks are complete (or that we run into an exception) 1559 for (Future<?> f : futures) { 1560 if (!exceptions.isEmpty()) { 1561 break; 1562 } 1563 try { 1564 f.get(); 1565 } catch (ExecutionException e) { 1566 LOG.error("Unexpected exec exception! Should've been caught already. (Bug?)", e); 1567 // Shouldn't happen, we already logged/caught any exceptions in the Runnable 1568 } 1569 } 1570 } catch (IOException e) { 1571 LOG.error("Cannot execute getTableStoreFilePathMap for " + tableName, e); 1572 exceptions.add(e); 1573 } finally { 1574 if (!exceptions.isEmpty()) { 1575 // Just throw the first exception as an indication something bad happened 1576 // Don't need to propagate all the exceptions, we already logged them all anyway 1577 Throwables.propagateIfPossible(exceptions.firstElement(), IOException.class); 1578 throw new IOException(exceptions.firstElement()); 1579 } 1580 } 1581 1582 return finalResultMap; 1583 } 1584 1585 public static int getRegionReferenceFileCount(final FileSystem fs, final Path p) { 1586 int result = 0; 1587 try { 1588 for (Path familyDir : getFamilyDirs(fs, p)) { 1589 result += getReferenceFilePaths(fs, familyDir).size(); 1590 } 1591 } catch (IOException e) { 1592 LOG.warn("Error counting reference files", e); 1593 } 1594 return result; 1595 } 1596 1597 /** 1598 * Runs through the HBase rootdir and creates a reverse lookup map for table StoreFile names to 1599 * the full Path. <br> 1600 * Example...<br> 1601 * Key = 3944417774205889744 <br> 1602 * Value = hdfs://localhost:51169/user/userid/-ROOT-/70236052/info/3944417774205889744 1603 * @param fs The file system to use. 1604 * @param hbaseRootDir The root directory to scan. 1605 * @return Map keyed by StoreFile name with a value of the full Path. 1606 * @throws IOException When scanning the directory fails. 1607 */ 1608 public static Map<String, Path> getTableStoreFilePathMap(final FileSystem fs, 1609 final Path hbaseRootDir) throws IOException, InterruptedException { 1610 return getTableStoreFilePathMap(fs, hbaseRootDir, null, null, (ProgressReporter) null); 1611 } 1612 1613 /** 1614 * Runs through the HBase rootdir and creates a reverse lookup map for table StoreFile names to 1615 * the full Path. <br> 1616 * Example...<br> 1617 * Key = 3944417774205889744 <br> 1618 * Value = hdfs://localhost:51169/user/userid/-ROOT-/70236052/info/3944417774205889744 1619 * @param fs The file system to use. 1620 * @param hbaseRootDir The root directory to scan. 1621 * @param sfFilter optional path filter to apply to store files 1622 * @param executor optional executor service to parallelize this operation 1623 * @param progressReporter Instance or null; gets called every time we move to new region of 1624 * family dir and for each store file. 1625 * @return Map keyed by StoreFile name with a value of the full Path. 1626 * @throws IOException When scanning the directory fails. 1627 * @deprecated Since 2.3.0. Will be removed in hbase4. Used 1628 * {@link #getTableStoreFilePathMap(FileSystem, Path, PathFilter, ExecutorService, ProgressReporter)} 1629 */ 1630 @Deprecated 1631 public static Map<String, Path> getTableStoreFilePathMap(final FileSystem fs, 1632 final Path hbaseRootDir, PathFilter sfFilter, ExecutorService executor, 1633 HbckErrorReporter progressReporter) throws IOException, InterruptedException { 1634 return getTableStoreFilePathMap(fs, hbaseRootDir, sfFilter, executor, new ProgressReporter() { 1635 @Override 1636 public void progress(FileStatus status) { 1637 // status is not used in this implementation. 1638 progressReporter.progress(); 1639 } 1640 }); 1641 } 1642 1643 /** 1644 * Runs through the HBase rootdir and creates a reverse lookup map for table StoreFile names to 1645 * the full Path. <br> 1646 * Example...<br> 1647 * Key = 3944417774205889744 <br> 1648 * Value = hdfs://localhost:51169/user/userid/-ROOT-/70236052/info/3944417774205889744 1649 * @param fs The file system to use. 1650 * @param hbaseRootDir The root directory to scan. 1651 * @param sfFilter optional path filter to apply to store files 1652 * @param executor optional executor service to parallelize this operation 1653 * @param progressReporter Instance or null; gets called every time we move to new region of 1654 * family dir and for each store file. 1655 * @return Map keyed by StoreFile name with a value of the full Path. 1656 * @throws IOException When scanning the directory fails. 1657 */ 1658 public static Map<String, Path> getTableStoreFilePathMap(final FileSystem fs, 1659 final Path hbaseRootDir, PathFilter sfFilter, ExecutorService executor, 1660 ProgressReporter progressReporter) throws IOException, InterruptedException { 1661 ConcurrentHashMap<String, Path> map = new ConcurrentHashMap<>(1024, 0.75f, 32); 1662 1663 // if this method looks similar to 'getTableFragmentation' that is because 1664 // it was borrowed from it. 1665 1666 // only include the directory paths to tables 1667 for (Path tableDir : FSUtils.getTableDirs(fs, hbaseRootDir)) { 1668 getTableStoreFilePathMap(map, fs, hbaseRootDir, CommonFSUtils.getTableName(tableDir), 1669 sfFilter, executor, progressReporter); 1670 } 1671 return map; 1672 } 1673 1674 /** 1675 * Filters FileStatuses in an array and returns a list 1676 * @param input An array of FileStatuses 1677 * @param filter A required filter to filter the array 1678 * @return A list of FileStatuses 1679 */ 1680 public static List<FileStatus> filterFileStatuses(FileStatus[] input, FileStatusFilter filter) { 1681 if (input == null) return null; 1682 return filterFileStatuses(Iterators.forArray(input), filter); 1683 } 1684 1685 /** 1686 * Filters FileStatuses in an iterator and returns a list 1687 * @param input An iterator of FileStatuses 1688 * @param filter A required filter to filter the array 1689 * @return A list of FileStatuses 1690 */ 1691 public static List<FileStatus> filterFileStatuses(Iterator<FileStatus> input, 1692 FileStatusFilter filter) { 1693 if (input == null) return null; 1694 ArrayList<FileStatus> results = new ArrayList<>(); 1695 while (input.hasNext()) { 1696 FileStatus f = input.next(); 1697 if (filter.accept(f)) { 1698 results.add(f); 1699 } 1700 } 1701 return results; 1702 } 1703 1704 /** 1705 * Calls fs.listStatus() and treats FileNotFoundException as non-fatal This accommodates 1706 * differences between hadoop versions, where hadoop 1 does not throw a FileNotFoundException, and 1707 * return an empty FileStatus[] while Hadoop 2 will throw FileNotFoundException. 1708 * @param fs file system 1709 * @param dir directory 1710 * @param filter file status filter 1711 * @return null if dir is empty or doesn't exist, otherwise FileStatus list 1712 */ 1713 public static List<FileStatus> listStatusWithStatusFilter(final FileSystem fs, final Path dir, 1714 final FileStatusFilter filter) throws IOException { 1715 FileStatus[] status = null; 1716 try { 1717 status = fs.listStatus(dir); 1718 } catch (FileNotFoundException fnfe) { 1719 LOG.trace("{} does not exist", dir); 1720 return null; 1721 } 1722 1723 if (ArrayUtils.getLength(status) == 0) { 1724 return null; 1725 } 1726 1727 if (filter == null) { 1728 return Arrays.asList(status); 1729 } else { 1730 List<FileStatus> status2 = filterFileStatuses(status, filter); 1731 if (status2 == null || status2.isEmpty()) { 1732 return null; 1733 } else { 1734 return status2; 1735 } 1736 } 1737 } 1738 1739 /** 1740 * This function is to scan the root path of the file system to get the degree of locality for 1741 * each region on each of the servers having at least one block of that region. This is used by 1742 * the tool {@link org.apache.hadoop.hbase.master.RegionPlacementMaintainer} the configuration to 1743 * use 1744 * @return the mapping from region encoded name to a map of server names to locality fraction in 1745 * case of file system errors or interrupts 1746 */ 1747 public static Map<String, Map<String, Float>> 1748 getRegionDegreeLocalityMappingFromFS(final Configuration conf) throws IOException { 1749 return getRegionDegreeLocalityMappingFromFS(conf, null, 1750 conf.getInt(THREAD_POOLSIZE, DEFAULT_THREAD_POOLSIZE)); 1751 1752 } 1753 1754 /** 1755 * This function is to scan the root path of the file system to get the degree of locality for 1756 * each region on each of the servers having at least one block of that region. the configuration 1757 * to use the table you wish to scan locality for the thread pool size to use 1758 * @return the mapping from region encoded name to a map of server names to locality fraction in 1759 * case of file system errors or interrupts 1760 */ 1761 public static Map<String, Map<String, Float>> getRegionDegreeLocalityMappingFromFS( 1762 final Configuration conf, final String desiredTable, int threadPoolSize) throws IOException { 1763 Map<String, Map<String, Float>> regionDegreeLocalityMapping = new ConcurrentHashMap<>(); 1764 getRegionLocalityMappingFromFS(conf, desiredTable, threadPoolSize, regionDegreeLocalityMapping); 1765 return regionDegreeLocalityMapping; 1766 } 1767 1768 /** 1769 * This function is to scan the root path of the file system to get either the mapping between the 1770 * region name and its best locality region server or the degree of locality of each region on 1771 * each of the servers having at least one block of that region. The output map parameters are 1772 * both optional. the configuration to use the table you wish to scan locality for the thread pool 1773 * size to use the map into which to put the locality degree mapping or null, must be a 1774 * thread-safe implementation in case of file system errors or interrupts 1775 */ 1776 private static void getRegionLocalityMappingFromFS(final Configuration conf, 1777 final String desiredTable, int threadPoolSize, 1778 final Map<String, Map<String, Float>> regionDegreeLocalityMapping) throws IOException { 1779 final FileSystem fs = FileSystem.get(conf); 1780 final Path rootPath = CommonFSUtils.getRootDir(conf); 1781 final long startTime = EnvironmentEdgeManager.currentTime(); 1782 final Path queryPath; 1783 // The table files are in ${hbase.rootdir}/data/<namespace>/<table>/* 1784 if (null == desiredTable) { 1785 queryPath = 1786 new Path(new Path(rootPath, HConstants.BASE_NAMESPACE_DIR).toString() + "/*/*/*/"); 1787 } else { 1788 queryPath = new Path( 1789 CommonFSUtils.getTableDir(rootPath, TableName.valueOf(desiredTable)).toString() + "/*/"); 1790 } 1791 1792 // reject all paths that are not appropriate 1793 PathFilter pathFilter = new PathFilter() { 1794 @Override 1795 public boolean accept(Path path) { 1796 // this is the region name; it may get some noise data 1797 if (null == path) { 1798 return false; 1799 } 1800 1801 // no parent? 1802 Path parent = path.getParent(); 1803 if (null == parent) { 1804 return false; 1805 } 1806 1807 String regionName = path.getName(); 1808 if (null == regionName) { 1809 return false; 1810 } 1811 1812 if (!regionName.toLowerCase(Locale.ROOT).matches("[0-9a-f]+")) { 1813 return false; 1814 } 1815 return true; 1816 } 1817 }; 1818 1819 FileStatus[] statusList = fs.globStatus(queryPath, pathFilter); 1820 1821 if (LOG.isDebugEnabled()) { 1822 LOG.debug("Query Path: {} ; # list of files: {}", queryPath, Arrays.toString(statusList)); 1823 } 1824 1825 if (null == statusList) { 1826 return; 1827 } 1828 1829 // lower the number of threads in case we have very few expected regions 1830 threadPoolSize = Math.min(threadPoolSize, statusList.length); 1831 1832 // run in multiple threads 1833 final ExecutorService tpe = Executors.newFixedThreadPool(threadPoolSize, 1834 new ThreadFactoryBuilder().setNameFormat("FSRegionQuery-pool-%d").setDaemon(true) 1835 .setUncaughtExceptionHandler(Threads.LOGGING_EXCEPTION_HANDLER).build()); 1836 try { 1837 // ignore all file status items that are not of interest 1838 for (FileStatus regionStatus : statusList) { 1839 if (null == regionStatus || !regionStatus.isDirectory()) { 1840 continue; 1841 } 1842 1843 final Path regionPath = regionStatus.getPath(); 1844 if (null != regionPath) { 1845 tpe.execute(new FSRegionScanner(fs, regionPath, null, regionDegreeLocalityMapping)); 1846 } 1847 } 1848 } finally { 1849 tpe.shutdown(); 1850 final long threadWakeFrequency = (long) conf.getInt(HConstants.THREAD_WAKE_FREQUENCY, 1851 HConstants.DEFAULT_THREAD_WAKE_FREQUENCY); 1852 try { 1853 // here we wait until TPE terminates, which is either naturally or by 1854 // exceptions in the execution of the threads 1855 while (!tpe.awaitTermination(threadWakeFrequency, TimeUnit.MILLISECONDS)) { 1856 // printing out rough estimate, so as to not introduce 1857 // AtomicInteger 1858 LOG.info("Locality checking is underway: { Scanned Regions : " 1859 + ((ThreadPoolExecutor) tpe).getCompletedTaskCount() + "/" 1860 + ((ThreadPoolExecutor) tpe).getTaskCount() + " }"); 1861 } 1862 } catch (InterruptedException e) { 1863 Thread.currentThread().interrupt(); 1864 throw (InterruptedIOException) new InterruptedIOException().initCause(e); 1865 } 1866 } 1867 1868 long overhead = EnvironmentEdgeManager.currentTime() - startTime; 1869 LOG.info("Scan DFS for locality info takes {}ms", overhead); 1870 } 1871 1872 /** 1873 * Do our short circuit read setup. Checks buffer size to use and whether to do checksumming in 1874 * hbase or hdfs. 1875 */ 1876 public static void setupShortCircuitRead(final Configuration conf) { 1877 // Check that the user has not set the "dfs.client.read.shortcircuit.skip.checksum" property. 1878 boolean shortCircuitSkipChecksum = 1879 conf.getBoolean("dfs.client.read.shortcircuit.skip.checksum", false); 1880 boolean useHBaseChecksum = conf.getBoolean(HConstants.HBASE_CHECKSUM_VERIFICATION, true); 1881 if (shortCircuitSkipChecksum) { 1882 LOG.warn("Configuration \"dfs.client.read.shortcircuit.skip.checksum\" should not " 1883 + "be set to true." 1884 + (useHBaseChecksum 1885 ? " HBase checksum doesn't require " 1886 + "it, see https://issues.apache.org/jira/browse/HBASE-6868." 1887 : "")); 1888 assert !shortCircuitSkipChecksum; // this will fail if assertions are on 1889 } 1890 checkShortCircuitReadBufferSize(conf); 1891 } 1892 1893 /** 1894 * Check if short circuit read buffer size is set and if not, set it to hbase value. 1895 */ 1896 public static void checkShortCircuitReadBufferSize(final Configuration conf) { 1897 final int defaultSize = HConstants.DEFAULT_BLOCKSIZE * 2; 1898 final int notSet = -1; 1899 // DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_BUFFER_SIZE_KEY is only defined in h2 1900 final String dfsKey = "dfs.client.read.shortcircuit.buffer.size"; 1901 int size = conf.getInt(dfsKey, notSet); 1902 // If a size is set, return -- we will use it. 1903 if (size != notSet) return; 1904 // But short circuit buffer size is normally not set. Put in place the hbase wanted size. 1905 int hbaseSize = conf.getInt("hbase." + dfsKey, defaultSize); 1906 conf.setIfUnset(dfsKey, Integer.toString(hbaseSize)); 1907 } 1908 1909 /** 1910 * Returns The DFSClient DFSHedgedReadMetrics instance or null if can't be found or not on hdfs. 1911 */ 1912 public static DFSHedgedReadMetrics getDFSHedgedReadMetrics(final Configuration c) 1913 throws IOException { 1914 if (!CommonFSUtils.isHDFS(c)) { 1915 return null; 1916 } 1917 // getHedgedReadMetrics is package private. Get the DFSClient instance that is internal 1918 // to the DFS FS instance and make the method getHedgedReadMetrics accessible, then invoke it 1919 // to get the singleton instance of DFSHedgedReadMetrics shared by DFSClients. 1920 final String name = "getHedgedReadMetrics"; 1921 DFSClient dfsclient = ((DistributedFileSystem) FileSystem.get(c)).getClient(); 1922 Method m; 1923 try { 1924 m = dfsclient.getClass().getDeclaredMethod(name); 1925 } catch (NoSuchMethodException e) { 1926 LOG.warn( 1927 "Failed find method " + name + " in dfsclient; no hedged read metrics: " + e.getMessage()); 1928 return null; 1929 } catch (SecurityException e) { 1930 LOG.warn( 1931 "Failed find method " + name + " in dfsclient; no hedged read metrics: " + e.getMessage()); 1932 return null; 1933 } 1934 m.setAccessible(true); 1935 try { 1936 return (DFSHedgedReadMetrics) m.invoke(dfsclient); 1937 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { 1938 LOG.warn("Failed invoking method " + name + " on dfsclient; no hedged read metrics: " 1939 + e.getMessage()); 1940 return null; 1941 } 1942 } 1943 1944 public static List<Path> copyFilesParallel(FileSystem srcFS, Path src, FileSystem dstFS, Path dst, 1945 Configuration conf, int threads) throws IOException { 1946 ExecutorService pool = Executors.newFixedThreadPool(threads); 1947 List<Future<Void>> futures = new ArrayList<>(); 1948 List<Path> traversedPaths; 1949 try { 1950 traversedPaths = copyFiles(srcFS, src, dstFS, dst, conf, pool, futures); 1951 for (Future<Void> future : futures) { 1952 future.get(); 1953 } 1954 } catch (ExecutionException | InterruptedException | IOException e) { 1955 throw new IOException("Copy snapshot reference files failed", e); 1956 } finally { 1957 pool.shutdownNow(); 1958 } 1959 return traversedPaths; 1960 } 1961 1962 private static List<Path> copyFiles(FileSystem srcFS, Path src, FileSystem dstFS, Path dst, 1963 Configuration conf, ExecutorService pool, List<Future<Void>> futures) throws IOException { 1964 List<Path> traversedPaths = new ArrayList<>(); 1965 traversedPaths.add(dst); 1966 FileStatus currentFileStatus = srcFS.getFileStatus(src); 1967 if (currentFileStatus.isDirectory()) { 1968 if (!dstFS.mkdirs(dst)) { 1969 throw new IOException("Create directory failed: " + dst); 1970 } 1971 FileStatus[] subPaths = srcFS.listStatus(src); 1972 for (FileStatus subPath : subPaths) { 1973 traversedPaths.addAll(copyFiles(srcFS, subPath.getPath(), dstFS, 1974 new Path(dst, subPath.getPath().getName()), conf, pool, futures)); 1975 } 1976 } else { 1977 Future<Void> future = pool.submit(() -> { 1978 FileUtil.copy(srcFS, src, dstFS, dst, false, false, conf); 1979 return null; 1980 }); 1981 futures.add(future); 1982 } 1983 return traversedPaths; 1984 } 1985 1986 /** Returns A set containing all namenode addresses of fs */ 1987 private static Set<InetSocketAddress> getNNAddresses(DistributedFileSystem fs, 1988 Configuration conf) { 1989 Set<InetSocketAddress> addresses = new HashSet<>(); 1990 String serviceName = fs.getCanonicalServiceName(); 1991 1992 if (serviceName.startsWith("ha-hdfs")) { 1993 try { 1994 Map<String, Map<String, InetSocketAddress>> addressMap = 1995 DFSUtil.getNNServiceRpcAddressesForCluster(conf); 1996 String nameService = serviceName.substring(serviceName.indexOf(":") + 1); 1997 if (addressMap.containsKey(nameService)) { 1998 Map<String, InetSocketAddress> nnMap = addressMap.get(nameService); 1999 for (Map.Entry<String, InetSocketAddress> e2 : nnMap.entrySet()) { 2000 InetSocketAddress addr = e2.getValue(); 2001 addresses.add(addr); 2002 } 2003 } 2004 } catch (Exception e) { 2005 LOG.warn("DFSUtil.getNNServiceRpcAddresses failed. serviceName=" + serviceName, e); 2006 } 2007 } else { 2008 URI uri = fs.getUri(); 2009 int port = uri.getPort(); 2010 if (port < 0) { 2011 int idx = serviceName.indexOf(':'); 2012 port = Integer.parseInt(serviceName.substring(idx + 1)); 2013 } 2014 InetSocketAddress addr = new InetSocketAddress(uri.getHost(), port); 2015 addresses.add(addr); 2016 } 2017 2018 return addresses; 2019 } 2020 2021 /** 2022 * @param conf the Configuration of HBase 2023 * @return Whether srcFs and desFs are on same hdfs or not 2024 */ 2025 public static boolean isSameHdfs(Configuration conf, FileSystem srcFs, FileSystem desFs) { 2026 // By getCanonicalServiceName, we could make sure both srcFs and desFs 2027 // show a unified format which contains scheme, host and port. 2028 String srcServiceName = srcFs.getCanonicalServiceName(); 2029 String desServiceName = desFs.getCanonicalServiceName(); 2030 2031 if (srcServiceName == null || desServiceName == null) { 2032 return false; 2033 } 2034 if (srcServiceName.equals(desServiceName)) { 2035 return true; 2036 } 2037 if (srcServiceName.startsWith("ha-hdfs") && desServiceName.startsWith("ha-hdfs")) { 2038 Collection<String> internalNameServices = 2039 conf.getTrimmedStringCollection("dfs.internal.nameservices"); 2040 if (!internalNameServices.isEmpty()) { 2041 if (internalNameServices.contains(srcServiceName.split(":")[1])) { 2042 return true; 2043 } else { 2044 return false; 2045 } 2046 } 2047 } 2048 if (srcFs instanceof DistributedFileSystem && desFs instanceof DistributedFileSystem) { 2049 // If one serviceName is an HA format while the other is a non-HA format, 2050 // maybe they refer to the same FileSystem. 2051 // For example, srcFs is "ha-hdfs://nameservices" and desFs is "hdfs://activeNamenode:port" 2052 Set<InetSocketAddress> srcAddrs = getNNAddresses((DistributedFileSystem) srcFs, conf); 2053 Set<InetSocketAddress> desAddrs = getNNAddresses((DistributedFileSystem) desFs, conf); 2054 if (Sets.intersection(srcAddrs, desAddrs).size() > 0) { 2055 return true; 2056 } 2057 } 2058 2059 return false; 2060 } 2061}