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