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 java.io.Closeable; 021import java.io.FileNotFoundException; 022import java.io.IOException; 023import java.io.InterruptedIOException; 024import java.io.PrintWriter; 025import java.io.StringWriter; 026import java.net.InetAddress; 027import java.net.URI; 028import java.util.ArrayList; 029import java.util.Arrays; 030import java.util.Collection; 031import java.util.Collections; 032import java.util.Comparator; 033import java.util.EnumSet; 034import java.util.HashMap; 035import java.util.HashSet; 036import java.util.Iterator; 037import java.util.List; 038import java.util.Locale; 039import java.util.Map; 040import java.util.Map.Entry; 041import java.util.Objects; 042import java.util.Optional; 043import java.util.Set; 044import java.util.SortedMap; 045import java.util.SortedSet; 046import java.util.TreeMap; 047import java.util.TreeSet; 048import java.util.Vector; 049import java.util.concurrent.Callable; 050import java.util.concurrent.ConcurrentSkipListMap; 051import java.util.concurrent.ExecutionException; 052import java.util.concurrent.ExecutorService; 053import java.util.concurrent.Executors; 054import java.util.concurrent.Future; 055import java.util.concurrent.FutureTask; 056import java.util.concurrent.ScheduledThreadPoolExecutor; 057import java.util.concurrent.TimeUnit; 058import java.util.concurrent.TimeoutException; 059import java.util.concurrent.atomic.AtomicBoolean; 060import java.util.concurrent.atomic.AtomicInteger; 061import org.apache.commons.io.IOUtils; 062import org.apache.commons.lang3.RandomStringUtils; 063import org.apache.commons.lang3.StringUtils; 064import org.apache.hadoop.conf.Configuration; 065import org.apache.hadoop.conf.Configured; 066import org.apache.hadoop.fs.FSDataOutputStream; 067import org.apache.hadoop.fs.FileStatus; 068import org.apache.hadoop.fs.FileSystem; 069import org.apache.hadoop.fs.Path; 070import org.apache.hadoop.fs.permission.FsAction; 071import org.apache.hadoop.fs.permission.FsPermission; 072import org.apache.hadoop.hbase.Abortable; 073import org.apache.hadoop.hbase.Cell; 074import org.apache.hadoop.hbase.CellUtil; 075import org.apache.hadoop.hbase.ClusterMetrics; 076import org.apache.hadoop.hbase.ClusterMetrics.Option; 077import org.apache.hadoop.hbase.HBaseConfiguration; 078import org.apache.hadoop.hbase.HBaseInterfaceAudience; 079import org.apache.hadoop.hbase.HConstants; 080import org.apache.hadoop.hbase.HRegionInfo; 081import org.apache.hadoop.hbase.HRegionLocation; 082import org.apache.hadoop.hbase.KeyValue; 083import org.apache.hadoop.hbase.MasterNotRunningException; 084import org.apache.hadoop.hbase.MetaTableAccessor; 085import org.apache.hadoop.hbase.RegionLocations; 086import org.apache.hadoop.hbase.ServerName; 087import org.apache.hadoop.hbase.TableName; 088import org.apache.hadoop.hbase.ZooKeeperConnectionException; 089import org.apache.hadoop.hbase.client.Admin; 090import org.apache.hadoop.hbase.client.ClusterConnection; 091import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor; 092import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; 093import org.apache.hadoop.hbase.client.Connection; 094import org.apache.hadoop.hbase.client.ConnectionFactory; 095import org.apache.hadoop.hbase.client.Delete; 096import org.apache.hadoop.hbase.client.Get; 097import org.apache.hadoop.hbase.client.Put; 098import org.apache.hadoop.hbase.client.RegionInfo; 099import org.apache.hadoop.hbase.client.RegionInfoBuilder; 100import org.apache.hadoop.hbase.client.RegionReplicaUtil; 101import org.apache.hadoop.hbase.client.Result; 102import org.apache.hadoop.hbase.client.RowMutations; 103import org.apache.hadoop.hbase.client.Table; 104import org.apache.hadoop.hbase.client.TableDescriptor; 105import org.apache.hadoop.hbase.client.TableDescriptorBuilder; 106import org.apache.hadoop.hbase.client.TableState; 107import org.apache.hadoop.hbase.io.FileLink; 108import org.apache.hadoop.hbase.io.HFileLink; 109import org.apache.hadoop.hbase.io.hfile.CacheConfig; 110import org.apache.hadoop.hbase.io.hfile.HFile; 111import org.apache.hadoop.hbase.log.HBaseMarkers; 112import org.apache.hadoop.hbase.master.MasterFileSystem; 113import org.apache.hadoop.hbase.master.RegionState; 114import org.apache.hadoop.hbase.regionserver.HRegion; 115import org.apache.hadoop.hbase.regionserver.HRegionFileSystem; 116import org.apache.hadoop.hbase.regionserver.StoreFileInfo; 117import org.apache.hadoop.hbase.security.AccessDeniedException; 118import org.apache.hadoop.hbase.security.UserProvider; 119import org.apache.hadoop.hbase.util.Bytes.ByteArrayComparator; 120import org.apache.hadoop.hbase.util.HBaseFsck.ErrorReporter.ERROR_CODE; 121import org.apache.hadoop.hbase.util.hbck.HFileCorruptionChecker; 122import org.apache.hadoop.hbase.util.hbck.ReplicationChecker; 123import org.apache.hadoop.hbase.util.hbck.TableIntegrityErrorHandler; 124import org.apache.hadoop.hbase.util.hbck.TableIntegrityErrorHandlerImpl; 125import org.apache.hadoop.hbase.wal.WAL; 126import org.apache.hadoop.hbase.wal.WALFactory; 127import org.apache.hadoop.hbase.wal.WALSplitter; 128import org.apache.hadoop.hbase.zookeeper.MetaTableLocator; 129import org.apache.hadoop.hbase.zookeeper.ZKUtil; 130import org.apache.hadoop.hbase.zookeeper.ZKWatcher; 131import org.apache.hadoop.hbase.zookeeper.ZNodePaths; 132import org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException; 133import org.apache.hadoop.ipc.RemoteException; 134import org.apache.hadoop.security.UserGroupInformation; 135import org.apache.hadoop.util.ReflectionUtils; 136import org.apache.hadoop.util.Tool; 137import org.apache.hadoop.util.ToolRunner; 138import org.apache.hbase.thirdparty.com.google.common.collect.Sets; 139import org.apache.yetus.audience.InterfaceAudience; 140import org.apache.yetus.audience.InterfaceStability; 141import org.apache.zookeeper.KeeperException; 142import org.slf4j.Logger; 143import org.slf4j.LoggerFactory; 144 145import org.apache.hbase.thirdparty.com.google.common.base.Joiner; 146import org.apache.hbase.thirdparty.com.google.common.base.Preconditions; 147import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableList; 148import org.apache.hbase.thirdparty.com.google.common.collect.Lists; 149import org.apache.hbase.thirdparty.com.google.common.collect.Multimap; 150import org.apache.hbase.thirdparty.com.google.common.collect.Ordering; 151import org.apache.hbase.thirdparty.com.google.common.collect.TreeMultimap; 152 153import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil; 154import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.AdminService.BlockingInterface; 155 156/** 157 * HBaseFsck (hbck) is a tool for checking and repairing region consistency and 158 * table integrity problems in a corrupted HBase. 159 * <p> 160 * Region consistency checks verify that hbase:meta, region deployment on region 161 * servers and the state of data in HDFS (.regioninfo files) all are in 162 * accordance. 163 * <p> 164 * Table integrity checks verify that all possible row keys resolve to exactly 165 * one region of a table. This means there are no individual degenerate 166 * or backwards regions; no holes between regions; and that there are no 167 * overlapping regions. 168 * <p> 169 * The general repair strategy works in two phases: 170 * <ol> 171 * <li> Repair Table Integrity on HDFS. (merge or fabricate regions) 172 * <li> Repair Region Consistency with hbase:meta and assignments 173 * </ol> 174 * <p> 175 * For table integrity repairs, the tables' region directories are scanned 176 * for .regioninfo files. Each table's integrity is then verified. If there 177 * are any orphan regions (regions with no .regioninfo files) or holes, new 178 * regions are fabricated. Backwards regions are sidelined as well as empty 179 * degenerate (endkey==startkey) regions. If there are any overlapping regions, 180 * a new region is created and all data is merged into the new region. 181 * <p> 182 * Table integrity repairs deal solely with HDFS and could potentially be done 183 * offline -- the hbase region servers or master do not need to be running. 184 * This phase can eventually be used to completely reconstruct the hbase:meta table in 185 * an offline fashion. 186 * <p> 187 * Region consistency requires three conditions -- 1) valid .regioninfo file 188 * present in an HDFS region dir, 2) valid row with .regioninfo data in META, 189 * and 3) a region is deployed only at the regionserver that was assigned to 190 * with proper state in the master. 191 * <p> 192 * Region consistency repairs require hbase to be online so that hbck can 193 * contact the HBase master and region servers. The hbck#connect() method must 194 * first be called successfully. Much of the region consistency information 195 * is transient and less risky to repair. 196 * <p> 197 * If hbck is run from the command line, there are a handful of arguments that 198 * can be used to limit the kinds of repairs hbck will do. See the code in 199 * {@link #printUsageAndExit()} for more details. 200 */ 201@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS) 202@InterfaceStability.Evolving 203public class HBaseFsck extends Configured implements Closeable { 204 public static final long DEFAULT_TIME_LAG = 60000; // default value of 1 minute 205 public static final long DEFAULT_SLEEP_BEFORE_RERUN = 10000; 206 private static final int MAX_NUM_THREADS = 50; // #threads to contact regions 207 private static boolean rsSupportsOffline = true; 208 private static final int DEFAULT_OVERLAPS_TO_SIDELINE = 2; 209 private static final int DEFAULT_MAX_MERGE = 5; 210 private static final String TO_BE_LOADED = "to_be_loaded"; 211 private static final String HBCK_LOCK_FILE = "hbase-hbck.lock"; 212 private static final int DEFAULT_MAX_LOCK_FILE_ATTEMPTS = 5; 213 private static final int DEFAULT_LOCK_FILE_ATTEMPT_SLEEP_INTERVAL = 200; // milliseconds 214 private static final int DEFAULT_LOCK_FILE_ATTEMPT_MAX_SLEEP_TIME = 5000; // milliseconds 215 // We have to set the timeout value > HdfsConstants.LEASE_SOFTLIMIT_PERIOD. 216 // In HADOOP-2.6 and later, the Namenode proxy now created with custom RetryPolicy for 217 // AlreadyBeingCreatedException which is implies timeout on this operations up to 218 // HdfsConstants.LEASE_SOFTLIMIT_PERIOD (60 seconds). 219 private static final int DEFAULT_WAIT_FOR_LOCK_TIMEOUT = 80; // seconds 220 private static final int DEFAULT_MAX_CREATE_ZNODE_ATTEMPTS = 5; 221 private static final int DEFAULT_CREATE_ZNODE_ATTEMPT_SLEEP_INTERVAL = 200; // milliseconds 222 private static final int DEFAULT_CREATE_ZNODE_ATTEMPT_MAX_SLEEP_TIME = 5000; // milliseconds 223 224 /********************** 225 * Internal resources 226 **********************/ 227 private static final Logger LOG = LoggerFactory.getLogger(HBaseFsck.class.getName()); 228 private ClusterMetrics status; 229 private ClusterConnection connection; 230 private Admin admin; 231 private Table meta; 232 // threads to do ||izable tasks: retrieve data from regionservers, handle overlapping regions 233 protected ExecutorService executor; 234 private long startMillis = EnvironmentEdgeManager.currentTime(); 235 private HFileCorruptionChecker hfcc; 236 private int retcode = 0; 237 private Path HBCK_LOCK_PATH; 238 private FSDataOutputStream hbckOutFd; 239 // This lock is to prevent cleanup of balancer resources twice between 240 // ShutdownHook and the main code. We cleanup only if the connect() is 241 // successful 242 private final AtomicBoolean hbckLockCleanup = new AtomicBoolean(false); 243 244 // Unsupported options in HBase 2.0+ 245 private static final Set<String> unsupportedOptionsInV2 = Sets.newHashSet("-fix", 246 "-fixAssignments", "-fixMeta", "-fixHdfsHoles", "-fixHdfsOrphans", "-fixTableOrphans", 247 "-fixHdfsOverlaps", "-sidelineBigOverlaps", "-fixSplitParents", "-removeParents", 248 "-fixEmptyMetaCells", "-repair", "-repairHoles", "-maxOverlapsToSideline", "-maxMerge"); 249 250 /*********** 251 * Options 252 ***********/ 253 private static boolean details = false; // do we display the full report 254 private long timelag = DEFAULT_TIME_LAG; // tables whose modtime is older 255 private static boolean forceExclusive = false; // only this hbck can modify HBase 256 private boolean fixAssignments = false; // fix assignment errors? 257 private boolean fixMeta = false; // fix meta errors? 258 private boolean checkHdfs = true; // load and check fs consistency? 259 private boolean fixHdfsHoles = false; // fix fs holes? 260 private boolean fixHdfsOverlaps = false; // fix fs overlaps (risky) 261 private boolean fixHdfsOrphans = false; // fix fs holes (missing .regioninfo) 262 private boolean fixTableOrphans = false; // fix fs holes (missing .tableinfo) 263 private boolean fixVersionFile = false; // fix missing hbase.version file in hdfs 264 private boolean fixSplitParents = false; // fix lingering split parents 265 private boolean removeParents = false; // remove split parents 266 private boolean fixReferenceFiles = false; // fix lingering reference store file 267 private boolean fixHFileLinks = false; // fix lingering HFileLinks 268 private boolean fixEmptyMetaCells = false; // fix (remove) empty REGIONINFO_QUALIFIER rows 269 private boolean fixReplication = false; // fix undeleted replication queues for removed peer 270 private boolean fixAny = false; // Set to true if any of the fix is required. 271 272 // limit checking/fixes to listed tables, if empty attempt to check/fix all 273 // hbase:meta are always checked 274 private Set<TableName> tablesIncluded = new HashSet<>(); 275 private int maxMerge = DEFAULT_MAX_MERGE; // maximum number of overlapping regions to merge 276 // maximum number of overlapping regions to sideline 277 private int maxOverlapsToSideline = DEFAULT_OVERLAPS_TO_SIDELINE; 278 private boolean sidelineBigOverlaps = false; // sideline overlaps with >maxMerge regions 279 private Path sidelineDir = null; 280 281 private boolean rerun = false; // if we tried to fix something, rerun hbck 282 private static boolean summary = false; // if we want to print less output 283 private boolean checkMetaOnly = false; 284 private boolean checkRegionBoundaries = false; 285 private boolean ignorePreCheckPermission = false; // if pre-check permission 286 287 /********* 288 * State 289 *********/ 290 final private ErrorReporter errors; 291 int fixes = 0; 292 293 /** 294 * This map contains the state of all hbck items. It maps from encoded region 295 * name to HbckInfo structure. The information contained in HbckInfo is used 296 * to detect and correct consistency (hdfs/meta/deployment) problems. 297 */ 298 private TreeMap<String, HbckInfo> regionInfoMap = new TreeMap<>(); 299 // Empty regioninfo qualifiers in hbase:meta 300 private Set<Result> emptyRegionInfoQualifiers = new HashSet<>(); 301 302 /** 303 * This map from Tablename -> TableInfo contains the structures necessary to 304 * detect table consistency problems (holes, dupes, overlaps). It is sorted 305 * to prevent dupes. 306 * 307 * If tablesIncluded is empty, this map contains all tables. 308 * Otherwise, it contains only meta tables and tables in tablesIncluded, 309 * unless checkMetaOnly is specified, in which case, it contains only 310 * the meta table 311 */ 312 private SortedMap<TableName, TableInfo> tablesInfo = new ConcurrentSkipListMap<>(); 313 314 /** 315 * When initially looking at HDFS, we attempt to find any orphaned data. 316 */ 317 private List<HbckInfo> orphanHdfsDirs = Collections.synchronizedList(new ArrayList<HbckInfo>()); 318 319 private Map<TableName, Set<String>> orphanTableDirs = new HashMap<>(); 320 private Map<TableName, TableState> tableStates = new HashMap<>(); 321 private final RetryCounterFactory lockFileRetryCounterFactory; 322 private final RetryCounterFactory createZNodeRetryCounterFactory; 323 324 private Map<TableName, Set<String>> skippedRegions = new HashMap<>(); 325 326 private ZKWatcher zkw = null; 327 private String hbckEphemeralNodePath = null; 328 private boolean hbckZodeCreated = false; 329 330 /** 331 * Constructor 332 * 333 * @param conf Configuration object 334 * @throws MasterNotRunningException if the master is not running 335 * @throws ZooKeeperConnectionException if unable to connect to ZooKeeper 336 */ 337 public HBaseFsck(Configuration conf) throws MasterNotRunningException, 338 ZooKeeperConnectionException, IOException, ClassNotFoundException { 339 this(conf, createThreadPool(conf)); 340 } 341 342 private static ExecutorService createThreadPool(Configuration conf) { 343 int numThreads = conf.getInt("hbasefsck.numthreads", MAX_NUM_THREADS); 344 return new ScheduledThreadPoolExecutor(numThreads, Threads.newDaemonThreadFactory("hbasefsck")); 345 } 346 347 /** 348 * Constructor 349 * 350 * @param conf 351 * Configuration object 352 * @throws MasterNotRunningException 353 * if the master is not running 354 * @throws ZooKeeperConnectionException 355 * if unable to connect to ZooKeeper 356 */ 357 public HBaseFsck(Configuration conf, ExecutorService exec) throws MasterNotRunningException, 358 ZooKeeperConnectionException, IOException, ClassNotFoundException { 359 super(conf); 360 errors = getErrorReporter(getConf()); 361 this.executor = exec; 362 lockFileRetryCounterFactory = new RetryCounterFactory( 363 getConf().getInt("hbase.hbck.lockfile.attempts", DEFAULT_MAX_LOCK_FILE_ATTEMPTS), 364 getConf().getInt( 365 "hbase.hbck.lockfile.attempt.sleep.interval", DEFAULT_LOCK_FILE_ATTEMPT_SLEEP_INTERVAL), 366 getConf().getInt( 367 "hbase.hbck.lockfile.attempt.maxsleeptime", DEFAULT_LOCK_FILE_ATTEMPT_MAX_SLEEP_TIME)); 368 createZNodeRetryCounterFactory = new RetryCounterFactory( 369 getConf().getInt("hbase.hbck.createznode.attempts", DEFAULT_MAX_CREATE_ZNODE_ATTEMPTS), 370 getConf().getInt( 371 "hbase.hbck.createznode.attempt.sleep.interval", 372 DEFAULT_CREATE_ZNODE_ATTEMPT_SLEEP_INTERVAL), 373 getConf().getInt( 374 "hbase.hbck.createznode.attempt.maxsleeptime", 375 DEFAULT_CREATE_ZNODE_ATTEMPT_MAX_SLEEP_TIME)); 376 zkw = createZooKeeperWatcher(); 377 } 378 379 private class FileLockCallable implements Callable<FSDataOutputStream> { 380 RetryCounter retryCounter; 381 382 public FileLockCallable(RetryCounter retryCounter) { 383 this.retryCounter = retryCounter; 384 } 385 @Override 386 public FSDataOutputStream call() throws IOException { 387 try { 388 FileSystem fs = FSUtils.getCurrentFileSystem(getConf()); 389 FsPermission defaultPerms = FSUtils.getFilePermissions(fs, getConf(), 390 HConstants.DATA_FILE_UMASK_KEY); 391 Path tmpDir = new Path(FSUtils.getRootDir(getConf()), HConstants.HBASE_TEMP_DIRECTORY); 392 fs.mkdirs(tmpDir); 393 HBCK_LOCK_PATH = new Path(tmpDir, HBCK_LOCK_FILE); 394 final FSDataOutputStream out = createFileWithRetries(fs, HBCK_LOCK_PATH, defaultPerms); 395 out.writeBytes(InetAddress.getLocalHost().toString()); 396 out.flush(); 397 return out; 398 } catch(RemoteException e) { 399 if(AlreadyBeingCreatedException.class.getName().equals(e.getClassName())){ 400 return null; 401 } else { 402 throw e; 403 } 404 } 405 } 406 407 private FSDataOutputStream createFileWithRetries(final FileSystem fs, 408 final Path hbckLockFilePath, final FsPermission defaultPerms) 409 throws IOException { 410 411 IOException exception = null; 412 do { 413 try { 414 return FSUtils.create(fs, hbckLockFilePath, defaultPerms, false); 415 } catch (IOException ioe) { 416 LOG.info("Failed to create lock file " + hbckLockFilePath.getName() 417 + ", try=" + (retryCounter.getAttemptTimes() + 1) + " of " 418 + retryCounter.getMaxAttempts()); 419 LOG.debug("Failed to create lock file " + hbckLockFilePath.getName(), 420 ioe); 421 try { 422 exception = ioe; 423 retryCounter.sleepUntilNextRetry(); 424 } catch (InterruptedException ie) { 425 throw (InterruptedIOException) new InterruptedIOException( 426 "Can't create lock file " + hbckLockFilePath.getName()) 427 .initCause(ie); 428 } 429 } 430 } while (retryCounter.shouldRetry()); 431 432 throw exception; 433 } 434 } 435 436 /** 437 * This method maintains a lock using a file. If the creation fails we return null 438 * 439 * @return FSDataOutputStream object corresponding to the newly opened lock file 440 * @throws IOException if IO failure occurs 441 */ 442 private FSDataOutputStream checkAndMarkRunningHbck() throws IOException { 443 RetryCounter retryCounter = lockFileRetryCounterFactory.create(); 444 FileLockCallable callable = new FileLockCallable(retryCounter); 445 ExecutorService executor = Executors.newFixedThreadPool(1); 446 FutureTask<FSDataOutputStream> futureTask = new FutureTask<>(callable); 447 executor.execute(futureTask); 448 final int timeoutInSeconds = getConf().getInt( 449 "hbase.hbck.lockfile.maxwaittime", DEFAULT_WAIT_FOR_LOCK_TIMEOUT); 450 FSDataOutputStream stream = null; 451 try { 452 stream = futureTask.get(timeoutInSeconds, TimeUnit.SECONDS); 453 } catch (ExecutionException ee) { 454 LOG.warn("Encountered exception when opening lock file", ee); 455 } catch (InterruptedException ie) { 456 LOG.warn("Interrupted when opening lock file", ie); 457 Thread.currentThread().interrupt(); 458 } catch (TimeoutException exception) { 459 // took too long to obtain lock 460 LOG.warn("Took more than " + timeoutInSeconds + " seconds in obtaining lock"); 461 futureTask.cancel(true); 462 } finally { 463 executor.shutdownNow(); 464 } 465 return stream; 466 } 467 468 private void unlockHbck() { 469 if (isExclusive() && hbckLockCleanup.compareAndSet(true, false)) { 470 RetryCounter retryCounter = lockFileRetryCounterFactory.create(); 471 do { 472 try { 473 IOUtils.closeQuietly(hbckOutFd); 474 FSUtils.delete(FSUtils.getCurrentFileSystem(getConf()), 475 HBCK_LOCK_PATH, true); 476 LOG.info("Finishing hbck"); 477 return; 478 } catch (IOException ioe) { 479 LOG.info("Failed to delete " + HBCK_LOCK_PATH + ", try=" 480 + (retryCounter.getAttemptTimes() + 1) + " of " 481 + retryCounter.getMaxAttempts()); 482 LOG.debug("Failed to delete " + HBCK_LOCK_PATH, ioe); 483 try { 484 retryCounter.sleepUntilNextRetry(); 485 } catch (InterruptedException ie) { 486 Thread.currentThread().interrupt(); 487 LOG.warn("Interrupted while deleting lock file" + 488 HBCK_LOCK_PATH); 489 return; 490 } 491 } 492 } while (retryCounter.shouldRetry()); 493 } 494 } 495 496 /** 497 * To repair region consistency, one must call connect() in order to repair 498 * online state. 499 */ 500 public void connect() throws IOException { 501 502 if (isExclusive()) { 503 // Grab the lock 504 hbckOutFd = checkAndMarkRunningHbck(); 505 if (hbckOutFd == null) { 506 setRetCode(-1); 507 LOG.error("Another instance of hbck is fixing HBase, exiting this instance. " + 508 "[If you are sure no other instance is running, delete the lock file " + 509 HBCK_LOCK_PATH + " and rerun the tool]"); 510 throw new IOException("Duplicate hbck - Abort"); 511 } 512 513 // Make sure to cleanup the lock 514 hbckLockCleanup.set(true); 515 } 516 517 518 // Add a shutdown hook to this thread, in case user tries to 519 // kill the hbck with a ctrl-c, we want to cleanup the lock so that 520 // it is available for further calls 521 Runtime.getRuntime().addShutdownHook(new Thread() { 522 @Override 523 public void run() { 524 IOUtils.closeQuietly(HBaseFsck.this); 525 cleanupHbckZnode(); 526 unlockHbck(); 527 } 528 }); 529 530 LOG.info("Launching hbck"); 531 532 connection = (ClusterConnection)ConnectionFactory.createConnection(getConf()); 533 admin = connection.getAdmin(); 534 meta = connection.getTable(TableName.META_TABLE_NAME); 535 status = admin.getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS, 536 Option.DEAD_SERVERS, Option.MASTER, Option.BACKUP_MASTERS, 537 Option.REGIONS_IN_TRANSITION, Option.HBASE_VERSION)); 538 } 539 540 /** 541 * Get deployed regions according to the region servers. 542 */ 543 private void loadDeployedRegions() throws IOException, InterruptedException { 544 // From the master, get a list of all known live region servers 545 Collection<ServerName> regionServers = status.getLiveServerMetrics().keySet(); 546 errors.print("Number of live region servers: " + regionServers.size()); 547 if (details) { 548 for (ServerName rsinfo: regionServers) { 549 errors.print(" " + rsinfo.getServerName()); 550 } 551 } 552 553 // From the master, get a list of all dead region servers 554 Collection<ServerName> deadRegionServers = status.getDeadServerNames(); 555 errors.print("Number of dead region servers: " + deadRegionServers.size()); 556 if (details) { 557 for (ServerName name: deadRegionServers) { 558 errors.print(" " + name); 559 } 560 } 561 562 // Print the current master name and state 563 errors.print("Master: " + status.getMasterName()); 564 565 // Print the list of all backup masters 566 Collection<ServerName> backupMasters = status.getBackupMasterNames(); 567 errors.print("Number of backup masters: " + backupMasters.size()); 568 if (details) { 569 for (ServerName name: backupMasters) { 570 errors.print(" " + name); 571 } 572 } 573 574 errors.print("Average load: " + status.getAverageLoad()); 575 errors.print("Number of requests: " + status.getRequestCount()); 576 errors.print("Number of regions: " + status.getRegionCount()); 577 578 List<RegionState> rits = status.getRegionStatesInTransition(); 579 errors.print("Number of regions in transition: " + rits.size()); 580 if (details) { 581 for (RegionState state: rits) { 582 errors.print(" " + state.toDescriptiveString()); 583 } 584 } 585 586 // Determine what's deployed 587 processRegionServers(regionServers); 588 } 589 590 /** 591 * Clear the current state of hbck. 592 */ 593 private void clearState() { 594 // Make sure regionInfo is empty before starting 595 fixes = 0; 596 regionInfoMap.clear(); 597 emptyRegionInfoQualifiers.clear(); 598 tableStates.clear(); 599 errors.clear(); 600 tablesInfo.clear(); 601 orphanHdfsDirs.clear(); 602 skippedRegions.clear(); 603 } 604 605 /** 606 * This repair method analyzes hbase data in hdfs and repairs it to satisfy 607 * the table integrity rules. HBase doesn't need to be online for this 608 * operation to work. 609 */ 610 public void offlineHdfsIntegrityRepair() throws IOException, InterruptedException { 611 // Initial pass to fix orphans. 612 if (shouldCheckHdfs() && (shouldFixHdfsOrphans() || shouldFixHdfsHoles() 613 || shouldFixHdfsOverlaps() || shouldFixTableOrphans())) { 614 LOG.info("Loading regioninfos HDFS"); 615 // if nothing is happening this should always complete in two iterations. 616 int maxIterations = getConf().getInt("hbase.hbck.integrityrepair.iterations.max", 3); 617 int curIter = 0; 618 do { 619 clearState(); // clears hbck state and reset fixes to 0 and. 620 // repair what's on HDFS 621 restoreHdfsIntegrity(); 622 curIter++;// limit the number of iterations. 623 } while (fixes > 0 && curIter <= maxIterations); 624 625 // Repairs should be done in the first iteration and verification in the second. 626 // If there are more than 2 passes, something funny has happened. 627 if (curIter > 2) { 628 if (curIter == maxIterations) { 629 LOG.warn("Exiting integrity repairs after max " + curIter + " iterations. " 630 + "Tables integrity may not be fully repaired!"); 631 } else { 632 LOG.info("Successfully exiting integrity repairs after " + curIter + " iterations"); 633 } 634 } 635 } 636 } 637 638 /** 639 * This repair method requires the cluster to be online since it contacts 640 * region servers and the masters. It makes each region's state in HDFS, in 641 * hbase:meta, and deployments consistent. 642 * 643 * @return If > 0 , number of errors detected, if < 0 there was an unrecoverable 644 * error. If 0, we have a clean hbase. 645 */ 646 public int onlineConsistencyRepair() throws IOException, KeeperException, 647 InterruptedException { 648 649 // get regions according to what is online on each RegionServer 650 loadDeployedRegions(); 651 // check whether hbase:meta is deployed and online 652 recordMetaRegion(); 653 // Check if hbase:meta is found only once and in the right place 654 if (!checkMetaRegion()) { 655 String errorMsg = "hbase:meta table is not consistent. "; 656 if (shouldFixAssignments()) { 657 errorMsg += "HBCK will try fixing it. Rerun once hbase:meta is back to consistent state."; 658 } else { 659 errorMsg += "Run HBCK with proper fix options to fix hbase:meta inconsistency."; 660 } 661 errors.reportError(errorMsg + " Exiting..."); 662 return -2; 663 } 664 // Not going with further consistency check for tables when hbase:meta itself is not consistent. 665 LOG.info("Loading regionsinfo from the hbase:meta table"); 666 boolean success = loadMetaEntries(); 667 if (!success) return -1; 668 669 // Empty cells in hbase:meta? 670 reportEmptyMetaCells(); 671 672 // Check if we have to cleanup empty REGIONINFO_QUALIFIER rows from hbase:meta 673 if (shouldFixEmptyMetaCells()) { 674 fixEmptyMetaCells(); 675 } 676 677 // get a list of all tables that have not changed recently. 678 if (!checkMetaOnly) { 679 reportTablesInFlux(); 680 } 681 682 // Get disabled tables states 683 loadTableStates(); 684 685 // load regiondirs and regioninfos from HDFS 686 if (shouldCheckHdfs()) { 687 LOG.info("Loading region directories from HDFS"); 688 loadHdfsRegionDirs(); 689 LOG.info("Loading region information from HDFS"); 690 loadHdfsRegionInfos(); 691 } 692 693 // fix the orphan tables 694 fixOrphanTables(); 695 696 LOG.info("Checking and fixing region consistency"); 697 // Check and fix consistency 698 checkAndFixConsistency(); 699 700 // Check integrity (does not fix) 701 checkIntegrity(); 702 return errors.getErrorList().size(); 703 } 704 705 /** 706 * This method maintains an ephemeral znode. If the creation fails we return false or throw 707 * exception 708 * 709 * @return true if creating znode succeeds; false otherwise 710 * @throws IOException if IO failure occurs 711 */ 712 private boolean setMasterInMaintenanceMode() throws IOException { 713 RetryCounter retryCounter = createZNodeRetryCounterFactory.create(); 714 hbckEphemeralNodePath = ZNodePaths.joinZNode( 715 zkw.znodePaths.masterMaintZNode, 716 "hbck-" + Long.toString(EnvironmentEdgeManager.currentTime())); 717 do { 718 try { 719 hbckZodeCreated = ZKUtil.createEphemeralNodeAndWatch(zkw, hbckEphemeralNodePath, null); 720 if (hbckZodeCreated) { 721 break; 722 } 723 } catch (KeeperException e) { 724 if (retryCounter.getAttemptTimes() >= retryCounter.getMaxAttempts()) { 725 throw new IOException("Can't create znode " + hbckEphemeralNodePath, e); 726 } 727 // fall through and retry 728 } 729 730 LOG.warn("Fail to create znode " + hbckEphemeralNodePath + ", try=" + 731 (retryCounter.getAttemptTimes() + 1) + " of " + retryCounter.getMaxAttempts()); 732 733 try { 734 retryCounter.sleepUntilNextRetry(); 735 } catch (InterruptedException ie) { 736 throw (InterruptedIOException) new InterruptedIOException( 737 "Can't create znode " + hbckEphemeralNodePath).initCause(ie); 738 } 739 } while (retryCounter.shouldRetry()); 740 return hbckZodeCreated; 741 } 742 743 private void cleanupHbckZnode() { 744 try { 745 if (zkw != null && hbckZodeCreated) { 746 ZKUtil.deleteNode(zkw, hbckEphemeralNodePath); 747 hbckZodeCreated = false; 748 } 749 } catch (KeeperException e) { 750 // Ignore 751 if (!e.code().equals(KeeperException.Code.NONODE)) { 752 LOG.warn("Delete HBCK znode " + hbckEphemeralNodePath + " failed ", e); 753 } 754 } 755 } 756 757 /** 758 * Contacts the master and prints out cluster-wide information 759 * @return 0 on success, non-zero on failure 760 */ 761 public int onlineHbck() 762 throws IOException, KeeperException, InterruptedException { 763 // print hbase server version 764 errors.print("Version: " + status.getHBaseVersion()); 765 766 // Clean start 767 clearState(); 768 // Do offline check and repair first 769 offlineHdfsIntegrityRepair(); 770 offlineReferenceFileRepair(); 771 offlineHLinkFileRepair(); 772 // If Master runs maintenance tasks (such as balancer, catalog janitor, etc) during online 773 // hbck, it is likely that hbck would be misled and report transient errors. Therefore, it 774 // is better to set Master into maintenance mode during online hbck. 775 // 776 if (!setMasterInMaintenanceMode()) { 777 LOG.warn("HBCK is running while master is not in maintenance mode, you might see transient " 778 + "error. Please run HBCK multiple times to reduce the chance of transient error."); 779 } 780 781 onlineConsistencyRepair(); 782 783 if (checkRegionBoundaries) { 784 checkRegionBoundaries(); 785 } 786 787 checkAndFixReplication(); 788 789 // Remove the hbck znode 790 cleanupHbckZnode(); 791 792 // Remove the hbck lock 793 unlockHbck(); 794 795 // Print table summary 796 printTableSummary(tablesInfo); 797 return errors.summarize(); 798 } 799 800 public static byte[] keyOnly (byte[] b) { 801 if (b == null) 802 return b; 803 int rowlength = Bytes.toShort(b, 0); 804 byte[] result = new byte[rowlength]; 805 System.arraycopy(b, Bytes.SIZEOF_SHORT, result, 0, rowlength); 806 return result; 807 } 808 809 @Override 810 public void close() throws IOException { 811 try { 812 cleanupHbckZnode(); 813 unlockHbck(); 814 } catch (Exception io) { 815 LOG.warn(io.toString(), io); 816 } finally { 817 if (zkw != null) { 818 zkw.close(); 819 zkw = null; 820 } 821 IOUtils.closeQuietly(admin); 822 IOUtils.closeQuietly(meta); 823 IOUtils.closeQuietly(connection); 824 } 825 } 826 827 private static class RegionBoundariesInformation { 828 public byte [] regionName; 829 public byte [] metaFirstKey; 830 public byte [] metaLastKey; 831 public byte [] storesFirstKey; 832 public byte [] storesLastKey; 833 @Override 834 public String toString () { 835 return "regionName=" + Bytes.toStringBinary(regionName) + 836 "\nmetaFirstKey=" + Bytes.toStringBinary(metaFirstKey) + 837 "\nmetaLastKey=" + Bytes.toStringBinary(metaLastKey) + 838 "\nstoresFirstKey=" + Bytes.toStringBinary(storesFirstKey) + 839 "\nstoresLastKey=" + Bytes.toStringBinary(storesLastKey); 840 } 841 } 842 843 public void checkRegionBoundaries() { 844 try { 845 ByteArrayComparator comparator = new ByteArrayComparator(); 846 List<RegionInfo> regions = MetaTableAccessor.getAllRegions(connection, true); 847 final RegionBoundariesInformation currentRegionBoundariesInformation = 848 new RegionBoundariesInformation(); 849 Path hbaseRoot = FSUtils.getRootDir(getConf()); 850 for (RegionInfo regionInfo : regions) { 851 Path tableDir = FSUtils.getTableDir(hbaseRoot, regionInfo.getTable()); 852 currentRegionBoundariesInformation.regionName = regionInfo.getRegionName(); 853 // For each region, get the start and stop key from the META and compare them to the 854 // same information from the Stores. 855 Path path = new Path(tableDir, regionInfo.getEncodedName()); 856 FileSystem fs = path.getFileSystem(getConf()); 857 FileStatus[] files = fs.listStatus(path); 858 // For all the column families in this region... 859 byte[] storeFirstKey = null; 860 byte[] storeLastKey = null; 861 for (FileStatus file : files) { 862 String fileName = file.getPath().toString(); 863 fileName = fileName.substring(fileName.lastIndexOf("/") + 1); 864 if (!fileName.startsWith(".") && !fileName.endsWith("recovered.edits")) { 865 FileStatus[] storeFiles = fs.listStatus(file.getPath()); 866 // For all the stores in this column family. 867 for (FileStatus storeFile : storeFiles) { 868 HFile.Reader reader = HFile.createReader(fs, storeFile.getPath(), 869 new CacheConfig(getConf()), true, getConf()); 870 if ((reader.getFirstKey() != null) 871 && ((storeFirstKey == null) || (comparator.compare(storeFirstKey, 872 ((KeyValue.KeyOnlyKeyValue) reader.getFirstKey().get()).getKey()) > 0))) { 873 storeFirstKey = ((KeyValue.KeyOnlyKeyValue)reader.getFirstKey().get()).getKey(); 874 } 875 if ((reader.getLastKey() != null) 876 && ((storeLastKey == null) || (comparator.compare(storeLastKey, 877 ((KeyValue.KeyOnlyKeyValue)reader.getLastKey().get()).getKey())) < 0)) { 878 storeLastKey = ((KeyValue.KeyOnlyKeyValue)reader.getLastKey().get()).getKey(); 879 } 880 reader.close(); 881 } 882 } 883 } 884 currentRegionBoundariesInformation.metaFirstKey = regionInfo.getStartKey(); 885 currentRegionBoundariesInformation.metaLastKey = regionInfo.getEndKey(); 886 currentRegionBoundariesInformation.storesFirstKey = keyOnly(storeFirstKey); 887 currentRegionBoundariesInformation.storesLastKey = keyOnly(storeLastKey); 888 if (currentRegionBoundariesInformation.metaFirstKey.length == 0) 889 currentRegionBoundariesInformation.metaFirstKey = null; 890 if (currentRegionBoundariesInformation.metaLastKey.length == 0) 891 currentRegionBoundariesInformation.metaLastKey = null; 892 893 // For a region to be correct, we need the META start key to be smaller or equal to the 894 // smallest start key from all the stores, and the start key from the next META entry to 895 // be bigger than the last key from all the current stores. First region start key is null; 896 // Last region end key is null; some regions can be empty and not have any store. 897 898 boolean valid = true; 899 // Checking start key. 900 if ((currentRegionBoundariesInformation.storesFirstKey != null) 901 && (currentRegionBoundariesInformation.metaFirstKey != null)) { 902 valid = valid 903 && comparator.compare(currentRegionBoundariesInformation.storesFirstKey, 904 currentRegionBoundariesInformation.metaFirstKey) >= 0; 905 } 906 // Checking stop key. 907 if ((currentRegionBoundariesInformation.storesLastKey != null) 908 && (currentRegionBoundariesInformation.metaLastKey != null)) { 909 valid = valid 910 && comparator.compare(currentRegionBoundariesInformation.storesLastKey, 911 currentRegionBoundariesInformation.metaLastKey) < 0; 912 } 913 if (!valid) { 914 errors.reportError(ERROR_CODE.BOUNDARIES_ERROR, "Found issues with regions boundaries", 915 tablesInfo.get(regionInfo.getTable())); 916 LOG.warn("Region's boundaries not aligned between stores and META for:"); 917 LOG.warn(Objects.toString(currentRegionBoundariesInformation)); 918 } 919 } 920 } catch (IOException e) { 921 LOG.error(e.toString(), e); 922 } 923 } 924 925 /** 926 * Iterates through the list of all orphan/invalid regiondirs. 927 */ 928 private void adoptHdfsOrphans(Collection<HbckInfo> orphanHdfsDirs) throws IOException { 929 for (HbckInfo hi : orphanHdfsDirs) { 930 LOG.info("Attempting to handle orphan hdfs dir: " + hi.getHdfsRegionDir()); 931 adoptHdfsOrphan(hi); 932 } 933 } 934 935 /** 936 * Orphaned regions are regions without a .regioninfo file in them. We "adopt" 937 * these orphans by creating a new region, and moving the column families, 938 * recovered edits, WALs, into the new region dir. We determine the region 939 * startkey and endkeys by looking at all of the hfiles inside the column 940 * families to identify the min and max keys. The resulting region will 941 * likely violate table integrity but will be dealt with by merging 942 * overlapping regions. 943 */ 944 @SuppressWarnings("deprecation") 945 private void adoptHdfsOrphan(HbckInfo hi) throws IOException { 946 Path p = hi.getHdfsRegionDir(); 947 FileSystem fs = p.getFileSystem(getConf()); 948 FileStatus[] dirs = fs.listStatus(p); 949 if (dirs == null) { 950 LOG.warn("Attempt to adopt orphan hdfs region skipped because no files present in " + 951 p + ". This dir could probably be deleted."); 952 return ; 953 } 954 955 TableName tableName = hi.getTableName(); 956 TableInfo tableInfo = tablesInfo.get(tableName); 957 Preconditions.checkNotNull(tableInfo, "Table '" + tableName + "' not present!"); 958 TableDescriptor template = tableInfo.getHTD(); 959 960 // find min and max key values 961 Pair<byte[],byte[]> orphanRegionRange = null; 962 for (FileStatus cf : dirs) { 963 String cfName= cf.getPath().getName(); 964 // TODO Figure out what the special dirs are 965 if (cfName.startsWith(".") || cfName.equals(HConstants.SPLIT_LOGDIR_NAME)) continue; 966 967 FileStatus[] hfiles = fs.listStatus(cf.getPath()); 968 for (FileStatus hfile : hfiles) { 969 byte[] start, end; 970 HFile.Reader hf = null; 971 try { 972 CacheConfig cacheConf = new CacheConfig(getConf()); 973 hf = HFile.createReader(fs, hfile.getPath(), cacheConf, true, getConf()); 974 hf.loadFileInfo(); 975 Optional<Cell> startKv = hf.getFirstKey(); 976 start = CellUtil.cloneRow(startKv.get()); 977 Optional<Cell> endKv = hf.getLastKey(); 978 end = CellUtil.cloneRow(endKv.get()); 979 } catch (IOException ioe) { 980 LOG.warn("Problem reading orphan file " + hfile + ", skipping"); 981 continue; 982 } catch (NullPointerException ioe) { 983 LOG.warn("Orphan file " + hfile + " is possibly corrupted HFile, skipping"); 984 continue; 985 } finally { 986 if (hf != null) { 987 hf.close(); 988 } 989 } 990 991 // expand the range to include the range of all hfiles 992 if (orphanRegionRange == null) { 993 // first range 994 orphanRegionRange = new Pair<>(start, end); 995 } else { 996 // TODO add test 997 998 // expand range only if the hfile is wider. 999 if (Bytes.compareTo(orphanRegionRange.getFirst(), start) > 0) { 1000 orphanRegionRange.setFirst(start); 1001 } 1002 if (Bytes.compareTo(orphanRegionRange.getSecond(), end) < 0 ) { 1003 orphanRegionRange.setSecond(end); 1004 } 1005 } 1006 } 1007 } 1008 if (orphanRegionRange == null) { 1009 LOG.warn("No data in dir " + p + ", sidelining data"); 1010 fixes++; 1011 sidelineRegionDir(fs, hi); 1012 return; 1013 } 1014 LOG.info("Min max keys are : [" + Bytes.toString(orphanRegionRange.getFirst()) + ", " + 1015 Bytes.toString(orphanRegionRange.getSecond()) + ")"); 1016 1017 // create new region on hdfs. move data into place. 1018 RegionInfo regionInfo = RegionInfoBuilder.newBuilder(template.getTableName()) 1019 .setStartKey(orphanRegionRange.getFirst()) 1020 .setEndKey(Bytes.add(orphanRegionRange.getSecond(), new byte[1])) 1021 .build(); 1022 LOG.info("Creating new region : " + regionInfo); 1023 HRegion region = HBaseFsckRepair.createHDFSRegionDir(getConf(), regionInfo, template); 1024 Path target = region.getRegionFileSystem().getRegionDir(); 1025 1026 // rename all the data to new region 1027 mergeRegionDirs(target, hi); 1028 fixes++; 1029 } 1030 1031 /** 1032 * This method determines if there are table integrity errors in HDFS. If 1033 * there are errors and the appropriate "fix" options are enabled, the method 1034 * will first correct orphan regions making them into legit regiondirs, and 1035 * then reload to merge potentially overlapping regions. 1036 * 1037 * @return number of table integrity errors found 1038 */ 1039 private int restoreHdfsIntegrity() throws IOException, InterruptedException { 1040 // Determine what's on HDFS 1041 LOG.info("Loading HBase regioninfo from HDFS..."); 1042 loadHdfsRegionDirs(); // populating regioninfo table. 1043 1044 int errs = errors.getErrorList().size(); 1045 // First time just get suggestions. 1046 tablesInfo = loadHdfsRegionInfos(); // update tableInfos based on region info in fs. 1047 checkHdfsIntegrity(false, false); 1048 1049 if (errors.getErrorList().size() == errs) { 1050 LOG.info("No integrity errors. We are done with this phase. Glorious."); 1051 return 0; 1052 } 1053 1054 if (shouldFixHdfsOrphans() && orphanHdfsDirs.size() > 0) { 1055 adoptHdfsOrphans(orphanHdfsDirs); 1056 // TODO optimize by incrementally adding instead of reloading. 1057 } 1058 1059 // Make sure there are no holes now. 1060 if (shouldFixHdfsHoles()) { 1061 clearState(); // this also resets # fixes. 1062 loadHdfsRegionDirs(); 1063 tablesInfo = loadHdfsRegionInfos(); // update tableInfos based on region info in fs. 1064 tablesInfo = checkHdfsIntegrity(shouldFixHdfsHoles(), false); 1065 } 1066 1067 // Now we fix overlaps 1068 if (shouldFixHdfsOverlaps()) { 1069 // second pass we fix overlaps. 1070 clearState(); // this also resets # fixes. 1071 loadHdfsRegionDirs(); 1072 tablesInfo = loadHdfsRegionInfos(); // update tableInfos based on region info in fs. 1073 tablesInfo = checkHdfsIntegrity(false, shouldFixHdfsOverlaps()); 1074 } 1075 1076 return errors.getErrorList().size(); 1077 } 1078 1079 /** 1080 * Scan all the store file names to find any lingering reference files, 1081 * which refer to some none-exiting files. If "fix" option is enabled, 1082 * any lingering reference file will be sidelined if found. 1083 * <p> 1084 * Lingering reference file prevents a region from opening. It has to 1085 * be fixed before a cluster can start properly. 1086 */ 1087 private void offlineReferenceFileRepair() throws IOException, InterruptedException { 1088 clearState(); 1089 Configuration conf = getConf(); 1090 Path hbaseRoot = FSUtils.getRootDir(conf); 1091 FileSystem fs = hbaseRoot.getFileSystem(conf); 1092 LOG.info("Computing mapping of all store files"); 1093 Map<String, Path> allFiles = FSUtils.getTableStoreFilePathMap(fs, hbaseRoot, 1094 new FSUtils.ReferenceFileFilter(fs), executor, errors); 1095 errors.print(""); 1096 LOG.info("Validating mapping using HDFS state"); 1097 for (Path path: allFiles.values()) { 1098 Path referredToFile = StoreFileInfo.getReferredToFile(path); 1099 if (fs.exists(referredToFile)) continue; // good, expected 1100 1101 // Found a lingering reference file 1102 errors.reportError(ERROR_CODE.LINGERING_REFERENCE_HFILE, 1103 "Found lingering reference file " + path); 1104 if (!shouldFixReferenceFiles()) continue; 1105 1106 // Now, trying to fix it since requested 1107 boolean success = false; 1108 String pathStr = path.toString(); 1109 1110 // A reference file path should be like 1111 // ${hbase.rootdir}/data/namespace/table_name/region_id/family_name/referred_file.region_name 1112 // Up 5 directories to get the root folder. 1113 // So the file will be sidelined to a similar folder structure. 1114 int index = pathStr.lastIndexOf(Path.SEPARATOR_CHAR); 1115 for (int i = 0; index > 0 && i < 5; i++) { 1116 index = pathStr.lastIndexOf(Path.SEPARATOR_CHAR, index - 1); 1117 } 1118 if (index > 0) { 1119 Path rootDir = getSidelineDir(); 1120 Path dst = new Path(rootDir, pathStr.substring(index + 1)); 1121 fs.mkdirs(dst.getParent()); 1122 LOG.info("Trying to sideline reference file " 1123 + path + " to " + dst); 1124 setShouldRerun(); 1125 1126 success = fs.rename(path, dst); 1127 debugLsr(dst); 1128 1129 } 1130 if (!success) { 1131 LOG.error("Failed to sideline reference file " + path); 1132 } 1133 } 1134 } 1135 1136 /** 1137 * Scan all the store file names to find any lingering HFileLink files, 1138 * which refer to some none-exiting files. If "fix" option is enabled, 1139 * any lingering HFileLink file will be sidelined if found. 1140 */ 1141 private void offlineHLinkFileRepair() throws IOException, InterruptedException { 1142 Configuration conf = getConf(); 1143 Path hbaseRoot = FSUtils.getRootDir(conf); 1144 FileSystem fs = hbaseRoot.getFileSystem(conf); 1145 LOG.info("Computing mapping of all link files"); 1146 Map<String, Path> allFiles = FSUtils 1147 .getTableStoreFilePathMap(fs, hbaseRoot, new FSUtils.HFileLinkFilter(), executor, errors); 1148 errors.print(""); 1149 1150 LOG.info("Validating mapping using HDFS state"); 1151 for (Path path : allFiles.values()) { 1152 // building HFileLink object to gather locations 1153 HFileLink actualLink = HFileLink.buildFromHFileLinkPattern(conf, path); 1154 if (actualLink.exists(fs)) continue; // good, expected 1155 1156 // Found a lingering HFileLink 1157 errors.reportError(ERROR_CODE.LINGERING_HFILELINK, "Found lingering HFileLink " + path); 1158 if (!shouldFixHFileLinks()) continue; 1159 1160 // Now, trying to fix it since requested 1161 setShouldRerun(); 1162 1163 // An HFileLink path should be like 1164 // ${hbase.rootdir}/data/namespace/table_name/region_id/family_name/linkedtable=linkedregionname-linkedhfilename 1165 // sidelineing will happen in the ${hbase.rootdir}/${sidelinedir} directory with the same folder structure. 1166 boolean success = sidelineFile(fs, hbaseRoot, path); 1167 1168 if (!success) { 1169 LOG.error("Failed to sideline HFileLink file " + path); 1170 } 1171 1172 // An HFileLink backreference path should be like 1173 // ${hbase.rootdir}/archive/data/namespace/table_name/region_id/family_name/.links-linkedhfilename 1174 // sidelineing will happen in the ${hbase.rootdir}/${sidelinedir} directory with the same folder structure. 1175 Path backRefPath = FileLink.getBackReferencesDir(HFileArchiveUtil 1176 .getStoreArchivePath(conf, HFileLink.getReferencedTableName(path.getName().toString()), 1177 HFileLink.getReferencedRegionName(path.getName().toString()), 1178 path.getParent().getName()), 1179 HFileLink.getReferencedHFileName(path.getName().toString())); 1180 success = sidelineFile(fs, hbaseRoot, backRefPath); 1181 1182 if (!success) { 1183 LOG.error("Failed to sideline HFileLink backreference file " + path); 1184 } 1185 } 1186 } 1187 1188 private boolean sidelineFile(FileSystem fs, Path hbaseRoot, Path path) throws IOException { 1189 URI uri = hbaseRoot.toUri().relativize(path.toUri()); 1190 if (uri.isAbsolute()) return false; 1191 String relativePath = uri.getPath(); 1192 Path rootDir = getSidelineDir(); 1193 Path dst = new Path(rootDir, relativePath); 1194 boolean pathCreated = fs.mkdirs(dst.getParent()); 1195 if (!pathCreated) { 1196 LOG.error("Failed to create path: " + dst.getParent()); 1197 return false; 1198 } 1199 LOG.info("Trying to sideline file " + path + " to " + dst); 1200 return fs.rename(path, dst); 1201 } 1202 1203 /** 1204 * TODO -- need to add tests for this. 1205 */ 1206 private void reportEmptyMetaCells() { 1207 errors.print("Number of empty REGIONINFO_QUALIFIER rows in hbase:meta: " + 1208 emptyRegionInfoQualifiers.size()); 1209 if (details) { 1210 for (Result r: emptyRegionInfoQualifiers) { 1211 errors.print(" " + r); 1212 } 1213 } 1214 } 1215 1216 /** 1217 * TODO -- need to add tests for this. 1218 */ 1219 private void reportTablesInFlux() { 1220 AtomicInteger numSkipped = new AtomicInteger(0); 1221 TableDescriptor[] allTables = getTables(numSkipped); 1222 errors.print("Number of Tables: " + allTables.length); 1223 if (details) { 1224 if (numSkipped.get() > 0) { 1225 errors.detail("Number of Tables in flux: " + numSkipped.get()); 1226 } 1227 for (TableDescriptor td : allTables) { 1228 errors.detail(" Table: " + td.getTableName() + "\t" + 1229 (td.isReadOnly() ? "ro" : "rw") + "\t" + 1230 (td.isMetaRegion() ? "META" : " ") + "\t" + 1231 " families: " + td.getColumnFamilyCount()); 1232 } 1233 } 1234 } 1235 1236 public ErrorReporter getErrors() { 1237 return errors; 1238 } 1239 1240 /** 1241 * Read the .regioninfo file from the file system. If there is no 1242 * .regioninfo, add it to the orphan hdfs region list. 1243 */ 1244 private void loadHdfsRegioninfo(HbckInfo hbi) throws IOException { 1245 Path regionDir = hbi.getHdfsRegionDir(); 1246 if (regionDir == null) { 1247 if (hbi.getReplicaId() == RegionInfo.DEFAULT_REPLICA_ID) { 1248 // Log warning only for default/ primary replica with no region dir 1249 LOG.warn("No HDFS region dir found: " + hbi + " meta=" + hbi.metaEntry); 1250 } 1251 return; 1252 } 1253 1254 if (hbi.hdfsEntry.hri != null) { 1255 // already loaded data 1256 return; 1257 } 1258 1259 FileSystem fs = FileSystem.get(getConf()); 1260 RegionInfo hri = HRegionFileSystem.loadRegionInfoFileContent(fs, regionDir); 1261 LOG.debug("RegionInfo read: " + hri.toString()); 1262 hbi.hdfsEntry.hri = hri; 1263 } 1264 1265 /** 1266 * Exception thrown when a integrity repair operation fails in an 1267 * unresolvable way. 1268 */ 1269 public static class RegionRepairException extends IOException { 1270 private static final long serialVersionUID = 1L; 1271 final IOException ioe; 1272 public RegionRepairException(String s, IOException ioe) { 1273 super(s); 1274 this.ioe = ioe; 1275 } 1276 } 1277 1278 /** 1279 * Populate hbi's from regionInfos loaded from file system. 1280 */ 1281 private SortedMap<TableName, TableInfo> loadHdfsRegionInfos() 1282 throws IOException, InterruptedException { 1283 tablesInfo.clear(); // regenerating the data 1284 // generate region split structure 1285 Collection<HbckInfo> hbckInfos = regionInfoMap.values(); 1286 1287 // Parallelized read of .regioninfo files. 1288 List<WorkItemHdfsRegionInfo> hbis = new ArrayList<>(hbckInfos.size()); 1289 List<Future<Void>> hbiFutures; 1290 1291 for (HbckInfo hbi : hbckInfos) { 1292 WorkItemHdfsRegionInfo work = new WorkItemHdfsRegionInfo(hbi, this, errors); 1293 hbis.add(work); 1294 } 1295 1296 // Submit and wait for completion 1297 hbiFutures = executor.invokeAll(hbis); 1298 1299 for(int i=0; i<hbiFutures.size(); i++) { 1300 WorkItemHdfsRegionInfo work = hbis.get(i); 1301 Future<Void> f = hbiFutures.get(i); 1302 try { 1303 f.get(); 1304 } catch(ExecutionException e) { 1305 LOG.warn("Failed to read .regioninfo file for region " + 1306 work.hbi.getRegionNameAsString(), e.getCause()); 1307 } 1308 } 1309 1310 Path hbaseRoot = FSUtils.getRootDir(getConf()); 1311 FileSystem fs = hbaseRoot.getFileSystem(getConf()); 1312 // serialized table info gathering. 1313 for (HbckInfo hbi: hbckInfos) { 1314 1315 if (hbi.getHdfsHRI() == null) { 1316 // was an orphan 1317 continue; 1318 } 1319 1320 1321 // get table name from hdfs, populate various HBaseFsck tables. 1322 TableName tableName = hbi.getTableName(); 1323 if (tableName == null) { 1324 // There was an entry in hbase:meta not in the HDFS? 1325 LOG.warn("tableName was null for: " + hbi); 1326 continue; 1327 } 1328 1329 TableInfo modTInfo = tablesInfo.get(tableName); 1330 if (modTInfo == null) { 1331 // only executed once per table. 1332 modTInfo = new TableInfo(tableName); 1333 tablesInfo.put(tableName, modTInfo); 1334 try { 1335 TableDescriptor htd = 1336 FSTableDescriptors.getTableDescriptorFromFs(fs, hbaseRoot, tableName); 1337 modTInfo.htds.add(htd); 1338 } catch (IOException ioe) { 1339 if (!orphanTableDirs.containsKey(tableName)) { 1340 LOG.warn("Unable to read .tableinfo from " + hbaseRoot, ioe); 1341 //should only report once for each table 1342 errors.reportError(ERROR_CODE.NO_TABLEINFO_FILE, 1343 "Unable to read .tableinfo from " + hbaseRoot + "/" + tableName); 1344 Set<String> columns = new HashSet<>(); 1345 orphanTableDirs.put(tableName, getColumnFamilyList(columns, hbi)); 1346 } 1347 } 1348 } 1349 if (!hbi.isSkipChecks()) { 1350 modTInfo.addRegionInfo(hbi); 1351 } 1352 } 1353 1354 loadTableInfosForTablesWithNoRegion(); 1355 errors.print(""); 1356 1357 return tablesInfo; 1358 } 1359 1360 /** 1361 * To get the column family list according to the column family dirs 1362 * @param columns 1363 * @param hbi 1364 * @return a set of column families 1365 * @throws IOException 1366 */ 1367 private Set<String> getColumnFamilyList(Set<String> columns, HbckInfo hbi) throws IOException { 1368 Path regionDir = hbi.getHdfsRegionDir(); 1369 FileSystem fs = regionDir.getFileSystem(getConf()); 1370 FileStatus[] subDirs = fs.listStatus(regionDir, new FSUtils.FamilyDirFilter(fs)); 1371 for (FileStatus subdir : subDirs) { 1372 String columnfamily = subdir.getPath().getName(); 1373 columns.add(columnfamily); 1374 } 1375 return columns; 1376 } 1377 1378 /** 1379 * To fabricate a .tableinfo file with following contents<br> 1380 * 1. the correct tablename <br> 1381 * 2. the correct colfamily list<br> 1382 * 3. the default properties for both {@link TableDescriptor} and {@link ColumnFamilyDescriptor}<br> 1383 * @throws IOException 1384 */ 1385 private boolean fabricateTableInfo(FSTableDescriptors fstd, TableName tableName, 1386 Set<String> columns) throws IOException { 1387 if (columns ==null || columns.isEmpty()) return false; 1388 TableDescriptorBuilder builder = TableDescriptorBuilder.newBuilder(tableName); 1389 for (String columnfamimly : columns) { 1390 builder.setColumnFamily(ColumnFamilyDescriptorBuilder.of(columnfamimly)); 1391 } 1392 fstd.createTableDescriptor(builder.build(), true); 1393 return true; 1394 } 1395 1396 /** 1397 * To fix the empty REGIONINFO_QUALIFIER rows from hbase:meta <br> 1398 * @throws IOException 1399 */ 1400 public void fixEmptyMetaCells() throws IOException { 1401 if (shouldFixEmptyMetaCells() && !emptyRegionInfoQualifiers.isEmpty()) { 1402 LOG.info("Trying to fix empty REGIONINFO_QUALIFIER hbase:meta rows."); 1403 for (Result region : emptyRegionInfoQualifiers) { 1404 deleteMetaRegion(region.getRow()); 1405 errors.getErrorList().remove(ERROR_CODE.EMPTY_META_CELL); 1406 } 1407 emptyRegionInfoQualifiers.clear(); 1408 } 1409 } 1410 1411 /** 1412 * To fix orphan table by creating a .tableinfo file under tableDir <br> 1413 * 1. if TableInfo is cached, to recover the .tableinfo accordingly <br> 1414 * 2. else create a default .tableinfo file with following items<br> 1415 * 2.1 the correct tablename <br> 1416 * 2.2 the correct colfamily list<br> 1417 * 2.3 the default properties for both {@link TableDescriptor} and {@link ColumnFamilyDescriptor}<br> 1418 * @throws IOException 1419 */ 1420 public void fixOrphanTables() throws IOException { 1421 if (shouldFixTableOrphans() && !orphanTableDirs.isEmpty()) { 1422 1423 List<TableName> tmpList = new ArrayList<>(orphanTableDirs.keySet().size()); 1424 tmpList.addAll(orphanTableDirs.keySet()); 1425 TableDescriptor[] htds = getTableDescriptors(tmpList); 1426 Iterator<Entry<TableName, Set<String>>> iter = 1427 orphanTableDirs.entrySet().iterator(); 1428 int j = 0; 1429 int numFailedCase = 0; 1430 FSTableDescriptors fstd = new FSTableDescriptors(getConf()); 1431 while (iter.hasNext()) { 1432 Entry<TableName, Set<String>> entry = 1433 iter.next(); 1434 TableName tableName = entry.getKey(); 1435 LOG.info("Trying to fix orphan table error: " + tableName); 1436 if (j < htds.length) { 1437 if (tableName.equals(htds[j].getTableName())) { 1438 TableDescriptor htd = htds[j]; 1439 LOG.info("fixing orphan table: " + tableName + " from cache"); 1440 fstd.createTableDescriptor(htd, true); 1441 j++; 1442 iter.remove(); 1443 } 1444 } else { 1445 if (fabricateTableInfo(fstd, tableName, entry.getValue())) { 1446 LOG.warn("fixing orphan table: " + tableName + " with a default .tableinfo file"); 1447 LOG.warn("Strongly recommend to modify the TableDescriptor if necessary for: " + tableName); 1448 iter.remove(); 1449 } else { 1450 LOG.error("Unable to create default .tableinfo for " + tableName + " while missing column family information"); 1451 numFailedCase++; 1452 } 1453 } 1454 fixes++; 1455 } 1456 1457 if (orphanTableDirs.isEmpty()) { 1458 // all orphanTableDirs are luckily recovered 1459 // re-run doFsck after recovering the .tableinfo file 1460 setShouldRerun(); 1461 LOG.warn("Strongly recommend to re-run manually hfsck after all orphanTableDirs being fixed"); 1462 } else if (numFailedCase > 0) { 1463 LOG.error("Failed to fix " + numFailedCase 1464 + " OrphanTables with default .tableinfo files"); 1465 } 1466 1467 } 1468 //cleanup the list 1469 orphanTableDirs.clear(); 1470 1471 } 1472 1473 /** 1474 * This borrows code from MasterFileSystem.bootstrap(). Explicitly creates it's own WAL, so be 1475 * sure to close it as well as the region when you're finished. 1476 * @param walFactoryID A unique identifier for WAL factory. Filesystem implementations will use 1477 * this ID to make a directory inside WAL directory path. 1478 * @return an open hbase:meta HRegion 1479 */ 1480 private HRegion createNewMeta(String walFactoryID) throws IOException { 1481 Path rootdir = FSUtils.getRootDir(getConf()); 1482 Configuration c = getConf(); 1483 RegionInfo metaHRI = RegionInfoBuilder.FIRST_META_REGIONINFO; 1484 TableDescriptor metaDescriptor = new FSTableDescriptors(c).get(TableName.META_TABLE_NAME); 1485 MasterFileSystem.setInfoFamilyCachingForMeta(metaDescriptor, false); 1486 // The WAL subsystem will use the default rootDir rather than the passed in rootDir 1487 // unless I pass along via the conf. 1488 Configuration confForWAL = new Configuration(c); 1489 confForWAL.set(HConstants.HBASE_DIR, rootdir.toString()); 1490 WAL wal = new WALFactory(confForWAL, walFactoryID).getWAL(metaHRI); 1491 HRegion meta = HRegion.createHRegion(metaHRI, rootdir, c, metaDescriptor, wal); 1492 MasterFileSystem.setInfoFamilyCachingForMeta(metaDescriptor, true); 1493 return meta; 1494 } 1495 1496 /** 1497 * Generate set of puts to add to new meta. This expects the tables to be 1498 * clean with no overlaps or holes. If there are any problems it returns null. 1499 * 1500 * @return An array list of puts to do in bulk, null if tables have problems 1501 */ 1502 private ArrayList<Put> generatePuts(SortedMap<TableName, TableInfo> tablesInfo) 1503 throws IOException { 1504 ArrayList<Put> puts = new ArrayList<>(); 1505 boolean hasProblems = false; 1506 for (Entry<TableName, TableInfo> e : tablesInfo.entrySet()) { 1507 TableName name = e.getKey(); 1508 1509 // skip "hbase:meta" 1510 if (name.compareTo(TableName.META_TABLE_NAME) == 0) { 1511 continue; 1512 } 1513 1514 TableInfo ti = e.getValue(); 1515 puts.add(MetaTableAccessor.makePutFromTableState( 1516 new TableState(ti.tableName, TableState.State.ENABLED), 1517 EnvironmentEdgeManager.currentTime())); 1518 for (Entry<byte[], Collection<HbckInfo>> spl : ti.sc.getStarts().asMap() 1519 .entrySet()) { 1520 Collection<HbckInfo> his = spl.getValue(); 1521 int sz = his.size(); 1522 if (sz != 1) { 1523 // problem 1524 LOG.error("Split starting at " + Bytes.toStringBinary(spl.getKey()) 1525 + " had " + sz + " regions instead of exactly 1." ); 1526 hasProblems = true; 1527 continue; 1528 } 1529 1530 // add the row directly to meta. 1531 HbckInfo hi = his.iterator().next(); 1532 RegionInfo hri = hi.getHdfsHRI(); // hi.metaEntry; 1533 Put p = MetaTableAccessor.makePutFromRegionInfo(hri, EnvironmentEdgeManager.currentTime()); 1534 puts.add(p); 1535 } 1536 } 1537 return hasProblems ? null : puts; 1538 } 1539 1540 /** 1541 * Suggest fixes for each table 1542 */ 1543 private void suggestFixes( 1544 SortedMap<TableName, TableInfo> tablesInfo) throws IOException { 1545 logParallelMerge(); 1546 for (TableInfo tInfo : tablesInfo.values()) { 1547 TableIntegrityErrorHandler handler = tInfo.new IntegrityFixSuggester(tInfo, errors); 1548 tInfo.checkRegionChain(handler); 1549 } 1550 } 1551 1552 /** 1553 * Rebuilds meta from information in hdfs/fs. Depends on configuration settings passed into 1554 * hbck constructor to point to a particular fs/dir. Assumes HBase is OFFLINE. 1555 * 1556 * @param fix flag that determines if method should attempt to fix holes 1557 * @return true if successful, false if attempt failed. 1558 */ 1559 public boolean rebuildMeta(boolean fix) throws IOException, 1560 InterruptedException { 1561 1562 // TODO check to make sure hbase is offline. (or at least the table 1563 // currently being worked on is off line) 1564 1565 // Determine what's on HDFS 1566 LOG.info("Loading HBase regioninfo from HDFS..."); 1567 loadHdfsRegionDirs(); // populating regioninfo table. 1568 1569 int errs = errors.getErrorList().size(); 1570 tablesInfo = loadHdfsRegionInfos(); // update tableInfos based on region info in fs. 1571 checkHdfsIntegrity(false, false); 1572 1573 // make sure ok. 1574 if (errors.getErrorList().size() != errs) { 1575 // While in error state, iterate until no more fixes possible 1576 while(true) { 1577 fixes = 0; 1578 suggestFixes(tablesInfo); 1579 errors.clear(); 1580 loadHdfsRegionInfos(); // update tableInfos based on region info in fs. 1581 checkHdfsIntegrity(shouldFixHdfsHoles(), shouldFixHdfsOverlaps()); 1582 1583 int errCount = errors.getErrorList().size(); 1584 1585 if (fixes == 0) { 1586 if (errCount > 0) { 1587 return false; // failed to fix problems. 1588 } else { 1589 break; // no fixes and no problems? drop out and fix stuff! 1590 } 1591 } 1592 } 1593 } 1594 1595 // we can rebuild, move old meta out of the way and start 1596 LOG.info("HDFS regioninfo's seems good. Sidelining old hbase:meta"); 1597 Path backupDir = sidelineOldMeta(); 1598 1599 LOG.info("Creating new hbase:meta"); 1600 String walFactoryId = "hbck-meta-recovery-" + RandomStringUtils.randomNumeric(8); 1601 HRegion meta = createNewMeta(walFactoryId); 1602 1603 // populate meta 1604 List<Put> puts = generatePuts(tablesInfo); 1605 if (puts == null) { 1606 LOG.error(HBaseMarkers.FATAL, "Problem encountered when creating new hbase:meta " 1607 + "entries. You may need to restore the previously sidelined hbase:meta"); 1608 return false; 1609 } 1610 meta.batchMutate(puts.toArray(new Put[puts.size()]), HConstants.NO_NONCE, HConstants.NO_NONCE); 1611 meta.close(); 1612 if (meta.getWAL() != null) { 1613 meta.getWAL().close(); 1614 } 1615 // clean up the temporary hbck meta recovery WAL directory 1616 removeHBCKMetaRecoveryWALDir(walFactoryId); 1617 LOG.info("Success! hbase:meta table rebuilt."); 1618 LOG.info("Old hbase:meta is moved into " + backupDir); 1619 return true; 1620 } 1621 1622 /** 1623 * Removes the empty Meta recovery WAL directory. 1624 * @param walFactoryId A unique identifier for WAL factory which was used by Filesystem to make a 1625 * Meta recovery WAL directory inside WAL directory path. 1626 */ 1627 private void removeHBCKMetaRecoveryWALDir(String walFactoryId) throws IOException { 1628 Path rootdir = FSUtils.getRootDir(getConf()); 1629 Path walLogDir = new Path(new Path(rootdir, HConstants.HREGION_LOGDIR_NAME), walFactoryId); 1630 FileSystem fs = FSUtils.getCurrentFileSystem(getConf()); 1631 FileStatus[] walFiles = FSUtils.listStatus(fs, walLogDir, null); 1632 if (walFiles == null || walFiles.length == 0) { 1633 LOG.info("HBCK meta recovery WAL directory is empty, removing it now."); 1634 if (!FSUtils.deleteDirectory(fs, walLogDir)) { 1635 LOG.warn("Couldn't clear the HBCK Meta recovery WAL directory " + walLogDir); 1636 } 1637 } 1638 } 1639 1640 /** 1641 * Log an appropriate message about whether or not overlapping merges are computed in parallel. 1642 */ 1643 private void logParallelMerge() { 1644 if (getConf().getBoolean("hbasefsck.overlap.merge.parallel", true)) { 1645 LOG.info("Handling overlap merges in parallel. set hbasefsck.overlap.merge.parallel to" + 1646 " false to run serially."); 1647 } else { 1648 LOG.info("Handling overlap merges serially. set hbasefsck.overlap.merge.parallel to" + 1649 " true to run in parallel."); 1650 } 1651 } 1652 1653 private SortedMap<TableName, TableInfo> checkHdfsIntegrity(boolean fixHoles, 1654 boolean fixOverlaps) throws IOException { 1655 LOG.info("Checking HBase region split map from HDFS data..."); 1656 logParallelMerge(); 1657 for (TableInfo tInfo : tablesInfo.values()) { 1658 TableIntegrityErrorHandler handler; 1659 if (fixHoles || fixOverlaps) { 1660 handler = tInfo.new HDFSIntegrityFixer(tInfo, errors, getConf(), 1661 fixHoles, fixOverlaps); 1662 } else { 1663 handler = tInfo.new IntegrityFixSuggester(tInfo, errors); 1664 } 1665 if (!tInfo.checkRegionChain(handler)) { 1666 // should dump info as well. 1667 errors.report("Found inconsistency in table " + tInfo.getName()); 1668 } 1669 } 1670 return tablesInfo; 1671 } 1672 1673 private Path getSidelineDir() throws IOException { 1674 if (sidelineDir == null) { 1675 Path hbaseDir = FSUtils.getRootDir(getConf()); 1676 Path hbckDir = new Path(hbaseDir, HConstants.HBCK_SIDELINEDIR_NAME); 1677 sidelineDir = new Path(hbckDir, hbaseDir.getName() + "-" 1678 + startMillis); 1679 } 1680 return sidelineDir; 1681 } 1682 1683 /** 1684 * Sideline a region dir (instead of deleting it) 1685 */ 1686 Path sidelineRegionDir(FileSystem fs, HbckInfo hi) throws IOException { 1687 return sidelineRegionDir(fs, null, hi); 1688 } 1689 1690 /** 1691 * Sideline a region dir (instead of deleting it) 1692 * 1693 * @param parentDir if specified, the region will be sidelined to folder like 1694 * {@literal .../parentDir/<table name>/<region name>}. The purpose is to group together 1695 * similar regions sidelined, for example, those regions should be bulk loaded back later 1696 * on. If NULL, it is ignored. 1697 */ 1698 Path sidelineRegionDir(FileSystem fs, 1699 String parentDir, HbckInfo hi) throws IOException { 1700 TableName tableName = hi.getTableName(); 1701 Path regionDir = hi.getHdfsRegionDir(); 1702 1703 if (!fs.exists(regionDir)) { 1704 LOG.warn("No previous " + regionDir + " exists. Continuing."); 1705 return null; 1706 } 1707 1708 Path rootDir = getSidelineDir(); 1709 if (parentDir != null) { 1710 rootDir = new Path(rootDir, parentDir); 1711 } 1712 Path sidelineTableDir= FSUtils.getTableDir(rootDir, tableName); 1713 Path sidelineRegionDir = new Path(sidelineTableDir, regionDir.getName()); 1714 fs.mkdirs(sidelineRegionDir); 1715 boolean success = false; 1716 FileStatus[] cfs = fs.listStatus(regionDir); 1717 if (cfs == null) { 1718 LOG.info("Region dir is empty: " + regionDir); 1719 } else { 1720 for (FileStatus cf : cfs) { 1721 Path src = cf.getPath(); 1722 Path dst = new Path(sidelineRegionDir, src.getName()); 1723 if (fs.isFile(src)) { 1724 // simple file 1725 success = fs.rename(src, dst); 1726 if (!success) { 1727 String msg = "Unable to rename file " + src + " to " + dst; 1728 LOG.error(msg); 1729 throw new IOException(msg); 1730 } 1731 continue; 1732 } 1733 1734 // is a directory. 1735 fs.mkdirs(dst); 1736 1737 LOG.info("Sidelining files from " + src + " into containing region " + dst); 1738 // FileSystem.rename is inconsistent with directories -- if the 1739 // dst (foo/a) exists and is a dir, and the src (foo/b) is a dir, 1740 // it moves the src into the dst dir resulting in (foo/a/b). If 1741 // the dst does not exist, and the src a dir, src becomes dst. (foo/b) 1742 FileStatus[] hfiles = fs.listStatus(src); 1743 if (hfiles != null && hfiles.length > 0) { 1744 for (FileStatus hfile : hfiles) { 1745 success = fs.rename(hfile.getPath(), dst); 1746 if (!success) { 1747 String msg = "Unable to rename file " + src + " to " + dst; 1748 LOG.error(msg); 1749 throw new IOException(msg); 1750 } 1751 } 1752 } 1753 LOG.debug("Sideline directory contents:"); 1754 debugLsr(sidelineRegionDir); 1755 } 1756 } 1757 1758 LOG.info("Removing old region dir: " + regionDir); 1759 success = fs.delete(regionDir, true); 1760 if (!success) { 1761 String msg = "Unable to delete dir " + regionDir; 1762 LOG.error(msg); 1763 throw new IOException(msg); 1764 } 1765 return sidelineRegionDir; 1766 } 1767 1768 /** 1769 * Side line an entire table. 1770 */ 1771 void sidelineTable(FileSystem fs, TableName tableName, Path hbaseDir, 1772 Path backupHbaseDir) throws IOException { 1773 Path tableDir = FSUtils.getTableDir(hbaseDir, tableName); 1774 if (fs.exists(tableDir)) { 1775 Path backupTableDir= FSUtils.getTableDir(backupHbaseDir, tableName); 1776 fs.mkdirs(backupTableDir.getParent()); 1777 boolean success = fs.rename(tableDir, backupTableDir); 1778 if (!success) { 1779 throw new IOException("Failed to move " + tableName + " from " 1780 + tableDir + " to " + backupTableDir); 1781 } 1782 } else { 1783 LOG.info("No previous " + tableName + " exists. Continuing."); 1784 } 1785 } 1786 1787 /** 1788 * @return Path to backup of original directory 1789 */ 1790 Path sidelineOldMeta() throws IOException { 1791 // put current hbase:meta aside. 1792 Path hbaseDir = FSUtils.getRootDir(getConf()); 1793 FileSystem fs = hbaseDir.getFileSystem(getConf()); 1794 Path backupDir = getSidelineDir(); 1795 fs.mkdirs(backupDir); 1796 1797 try { 1798 sidelineTable(fs, TableName.META_TABLE_NAME, hbaseDir, backupDir); 1799 } catch (IOException e) { 1800 LOG.error(HBaseMarkers.FATAL, "... failed to sideline meta. Currently in " 1801 + "inconsistent state. To restore try to rename hbase:meta in " + 1802 backupDir.getName() + " to " + hbaseDir.getName() + ".", e); 1803 throw e; // throw original exception 1804 } 1805 return backupDir; 1806 } 1807 1808 /** 1809 * Load the list of disabled tables in ZK into local set. 1810 * @throws ZooKeeperConnectionException 1811 * @throws IOException 1812 */ 1813 private void loadTableStates() 1814 throws IOException { 1815 tableStates = MetaTableAccessor.getTableStates(connection); 1816 // Add hbase:meta so this tool keeps working. In hbase2, meta is always enabled though it 1817 // has no entry in the table states. HBCK doesn't work right w/ hbase2 but just do this in 1818 // meantime. 1819 this.tableStates.put(TableName.META_TABLE_NAME, 1820 new TableState(TableName.META_TABLE_NAME, TableState.State.ENABLED)); 1821 } 1822 1823 /** 1824 * Check if the specified region's table is disabled. 1825 * @param tableName table to check status of 1826 */ 1827 private boolean isTableDisabled(TableName tableName) { 1828 return tableStates.containsKey(tableName) 1829 && tableStates.get(tableName) 1830 .inStates(TableState.State.DISABLED, TableState.State.DISABLING); 1831 } 1832 1833 /** 1834 * Scan HDFS for all regions, recording their information into 1835 * regionInfoMap 1836 */ 1837 public void loadHdfsRegionDirs() throws IOException, InterruptedException { 1838 Path rootDir = FSUtils.getRootDir(getConf()); 1839 FileSystem fs = rootDir.getFileSystem(getConf()); 1840 1841 // list all tables from HDFS 1842 List<FileStatus> tableDirs = Lists.newArrayList(); 1843 1844 boolean foundVersionFile = fs.exists(new Path(rootDir, HConstants.VERSION_FILE_NAME)); 1845 1846 List<Path> paths = FSUtils.getTableDirs(fs, rootDir); 1847 for (Path path : paths) { 1848 TableName tableName = FSUtils.getTableName(path); 1849 if ((!checkMetaOnly && 1850 isTableIncluded(tableName)) || 1851 tableName.equals(TableName.META_TABLE_NAME)) { 1852 tableDirs.add(fs.getFileStatus(path)); 1853 } 1854 } 1855 1856 // verify that version file exists 1857 if (!foundVersionFile) { 1858 errors.reportError(ERROR_CODE.NO_VERSION_FILE, 1859 "Version file does not exist in root dir " + rootDir); 1860 if (shouldFixVersionFile()) { 1861 LOG.info("Trying to create a new " + HConstants.VERSION_FILE_NAME 1862 + " file."); 1863 setShouldRerun(); 1864 FSUtils.setVersion(fs, rootDir, getConf().getInt( 1865 HConstants.THREAD_WAKE_FREQUENCY, 10 * 1000), getConf().getInt( 1866 HConstants.VERSION_FILE_WRITE_ATTEMPTS, 1867 HConstants.DEFAULT_VERSION_FILE_WRITE_ATTEMPTS)); 1868 } 1869 } 1870 1871 // Avoid multithreading at table-level because already multithreaded internally at 1872 // region-level. Additionally multithreading at table-level can lead to deadlock 1873 // if there are many tables in the cluster. Since there are a limited # of threads 1874 // in the executor's thread pool and if we multithread at the table-level by putting 1875 // WorkItemHdfsDir callables into the executor, then we will have some threads in the 1876 // executor tied up solely in waiting for the tables' region-level calls to complete. 1877 // If there are enough tables then there will be no actual threads in the pool left 1878 // for the region-level callables to be serviced. 1879 for (FileStatus tableDir : tableDirs) { 1880 LOG.debug("Loading region dirs from " +tableDir.getPath()); 1881 WorkItemHdfsDir item = new WorkItemHdfsDir(fs, errors, tableDir); 1882 try { 1883 item.call(); 1884 } catch (ExecutionException e) { 1885 LOG.warn("Could not completely load table dir " + 1886 tableDir.getPath(), e.getCause()); 1887 } 1888 } 1889 errors.print(""); 1890 } 1891 1892 /** 1893 * Record the location of the hbase:meta region as found in ZooKeeper. 1894 */ 1895 private boolean recordMetaRegion() throws IOException { 1896 RegionLocations rl = connection.locateRegion(TableName.META_TABLE_NAME, 1897 HConstants.EMPTY_START_ROW, false, false); 1898 if (rl == null) { 1899 errors.reportError(ERROR_CODE.NULL_META_REGION, 1900 "META region was not found in ZooKeeper"); 1901 return false; 1902 } 1903 for (HRegionLocation metaLocation : rl.getRegionLocations()) { 1904 // Check if Meta region is valid and existing 1905 if (metaLocation == null ) { 1906 errors.reportError(ERROR_CODE.NULL_META_REGION, 1907 "META region location is null"); 1908 return false; 1909 } 1910 if (metaLocation.getRegionInfo() == null) { 1911 errors.reportError(ERROR_CODE.NULL_META_REGION, 1912 "META location regionInfo is null"); 1913 return false; 1914 } 1915 if (metaLocation.getHostname() == null) { 1916 errors.reportError(ERROR_CODE.NULL_META_REGION, 1917 "META location hostName is null"); 1918 return false; 1919 } 1920 ServerName sn = metaLocation.getServerName(); 1921 MetaEntry m = new MetaEntry(metaLocation.getRegionInfo(), sn, EnvironmentEdgeManager.currentTime()); 1922 HbckInfo hbckInfo = regionInfoMap.get(metaLocation.getRegionInfo().getEncodedName()); 1923 if (hbckInfo == null) { 1924 regionInfoMap.put(metaLocation.getRegionInfo().getEncodedName(), new HbckInfo(m)); 1925 } else { 1926 hbckInfo.metaEntry = m; 1927 } 1928 } 1929 return true; 1930 } 1931 1932 private ZKWatcher createZooKeeperWatcher() throws IOException { 1933 return new ZKWatcher(getConf(), "hbase Fsck", new Abortable() { 1934 @Override 1935 public void abort(String why, Throwable e) { 1936 LOG.error(why, e); 1937 System.exit(1); 1938 } 1939 1940 @Override 1941 public boolean isAborted() { 1942 return false; 1943 } 1944 1945 }); 1946 } 1947 1948 private ServerName getMetaRegionServerName(int replicaId) 1949 throws IOException, KeeperException { 1950 return new MetaTableLocator().getMetaRegionLocation(zkw, replicaId); 1951 } 1952 1953 /** 1954 * Contacts each regionserver and fetches metadata about regions. 1955 * @param regionServerList - the list of region servers to connect to 1956 * @throws IOException if a remote or network exception occurs 1957 */ 1958 void processRegionServers(Collection<ServerName> regionServerList) 1959 throws IOException, InterruptedException { 1960 1961 List<WorkItemRegion> workItems = new ArrayList<>(regionServerList.size()); 1962 List<Future<Void>> workFutures; 1963 1964 // loop to contact each region server in parallel 1965 for (ServerName rsinfo: regionServerList) { 1966 workItems.add(new WorkItemRegion(this, rsinfo, errors, connection)); 1967 } 1968 1969 workFutures = executor.invokeAll(workItems); 1970 1971 for(int i=0; i<workFutures.size(); i++) { 1972 WorkItemRegion item = workItems.get(i); 1973 Future<Void> f = workFutures.get(i); 1974 try { 1975 f.get(); 1976 } catch(ExecutionException e) { 1977 LOG.warn("Could not process regionserver " + item.rsinfo.getHostAndPort(), 1978 e.getCause()); 1979 } 1980 } 1981 } 1982 1983 /** 1984 * Check consistency of all regions that have been found in previous phases. 1985 */ 1986 private void checkAndFixConsistency() 1987 throws IOException, KeeperException, InterruptedException { 1988 // Divide the checks in two phases. One for default/primary replicas and another 1989 // for the non-primary ones. Keeps code cleaner this way. 1990 1991 List<CheckRegionConsistencyWorkItem> workItems = new ArrayList<>(regionInfoMap.size()); 1992 for (java.util.Map.Entry<String, HbckInfo> e: regionInfoMap.entrySet()) { 1993 if (e.getValue().getReplicaId() == RegionInfo.DEFAULT_REPLICA_ID) { 1994 workItems.add(new CheckRegionConsistencyWorkItem(e.getKey(), e.getValue())); 1995 } 1996 } 1997 checkRegionConsistencyConcurrently(workItems); 1998 1999 boolean prevHdfsCheck = shouldCheckHdfs(); 2000 setCheckHdfs(false); //replicas don't have any hdfs data 2001 // Run a pass over the replicas and fix any assignment issues that exist on the currently 2002 // deployed/undeployed replicas. 2003 List<CheckRegionConsistencyWorkItem> replicaWorkItems = new ArrayList<>(regionInfoMap.size()); 2004 for (java.util.Map.Entry<String, HbckInfo> e: regionInfoMap.entrySet()) { 2005 if (e.getValue().getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) { 2006 replicaWorkItems.add(new CheckRegionConsistencyWorkItem(e.getKey(), e.getValue())); 2007 } 2008 } 2009 checkRegionConsistencyConcurrently(replicaWorkItems); 2010 setCheckHdfs(prevHdfsCheck); 2011 2012 // If some regions is skipped during checkRegionConsistencyConcurrently() phase, we might 2013 // not get accurate state of the hbase if continuing. The config here allows users to tune 2014 // the tolerance of number of skipped region. 2015 // TODO: evaluate the consequence to continue the hbck operation without config. 2016 int terminateThreshold = getConf().getInt("hbase.hbck.skipped.regions.limit", 0); 2017 int numOfSkippedRegions = skippedRegions.size(); 2018 if (numOfSkippedRegions > 0 && numOfSkippedRegions > terminateThreshold) { 2019 throw new IOException(numOfSkippedRegions 2020 + " region(s) could not be checked or repaired. See logs for detail."); 2021 } 2022 2023 if (shouldCheckHdfs()) { 2024 checkAndFixTableStates(); 2025 } 2026 } 2027 2028 /** 2029 * Check consistency of all regions using mulitple threads concurrently. 2030 */ 2031 private void checkRegionConsistencyConcurrently( 2032 final List<CheckRegionConsistencyWorkItem> workItems) 2033 throws IOException, KeeperException, InterruptedException { 2034 if (workItems.isEmpty()) { 2035 return; // nothing to check 2036 } 2037 2038 List<Future<Void>> workFutures = executor.invokeAll(workItems); 2039 for(Future<Void> f: workFutures) { 2040 try { 2041 f.get(); 2042 } catch(ExecutionException e1) { 2043 LOG.warn("Could not check region consistency " , e1.getCause()); 2044 if (e1.getCause() instanceof IOException) { 2045 throw (IOException)e1.getCause(); 2046 } else if (e1.getCause() instanceof KeeperException) { 2047 throw (KeeperException)e1.getCause(); 2048 } else if (e1.getCause() instanceof InterruptedException) { 2049 throw (InterruptedException)e1.getCause(); 2050 } else { 2051 throw new IOException(e1.getCause()); 2052 } 2053 } 2054 } 2055 } 2056 2057 class CheckRegionConsistencyWorkItem implements Callable<Void> { 2058 private final String key; 2059 private final HbckInfo hbi; 2060 2061 CheckRegionConsistencyWorkItem(String key, HbckInfo hbi) { 2062 this.key = key; 2063 this.hbi = hbi; 2064 } 2065 2066 @Override 2067 public synchronized Void call() throws Exception { 2068 try { 2069 checkRegionConsistency(key, hbi); 2070 } catch (Exception e) { 2071 // If the region is non-META region, skip this region and send warning/error message; if 2072 // the region is META region, we should not continue. 2073 LOG.warn("Unable to complete check or repair the region '" + hbi.getRegionNameAsString() 2074 + "'.", e); 2075 if (hbi.getHdfsHRI().isMetaRegion()) { 2076 throw e; 2077 } 2078 LOG.warn("Skip region '" + hbi.getRegionNameAsString() + "'"); 2079 addSkippedRegion(hbi); 2080 } 2081 return null; 2082 } 2083 } 2084 2085 private void addSkippedRegion(final HbckInfo hbi) { 2086 Set<String> skippedRegionNames = skippedRegions.get(hbi.getTableName()); 2087 if (skippedRegionNames == null) { 2088 skippedRegionNames = new HashSet<>(); 2089 } 2090 skippedRegionNames.add(hbi.getRegionNameAsString()); 2091 skippedRegions.put(hbi.getTableName(), skippedRegionNames); 2092 } 2093 2094 /** 2095 * Check and fix table states, assumes full info available: 2096 * - tableInfos 2097 * - empty tables loaded 2098 */ 2099 private void checkAndFixTableStates() throws IOException { 2100 // first check dangling states 2101 for (Entry<TableName, TableState> entry : tableStates.entrySet()) { 2102 TableName tableName = entry.getKey(); 2103 TableState tableState = entry.getValue(); 2104 TableInfo tableInfo = tablesInfo.get(tableName); 2105 if (isTableIncluded(tableName) 2106 && !tableName.isSystemTable() 2107 && tableInfo == null) { 2108 if (fixMeta) { 2109 MetaTableAccessor.deleteTableState(connection, tableName); 2110 TableState state = MetaTableAccessor.getTableState(connection, tableName); 2111 if (state != null) { 2112 errors.reportError(ERROR_CODE.ORPHAN_TABLE_STATE, 2113 tableName + " unable to delete dangling table state " + tableState); 2114 } 2115 } else if (!checkMetaOnly) { 2116 // dangling table state in meta if checkMetaOnly is false. If checkMetaOnly is 2117 // true, tableInfo will be null as tablesInfo are not polulated for all tables from hdfs 2118 errors.reportError(ERROR_CODE.ORPHAN_TABLE_STATE, 2119 tableName + " has dangling table state " + tableState); 2120 } 2121 } 2122 } 2123 // check that all tables have states 2124 for (TableName tableName : tablesInfo.keySet()) { 2125 if (isTableIncluded(tableName) && !tableStates.containsKey(tableName)) { 2126 if (fixMeta) { 2127 MetaTableAccessor.updateTableState(connection, tableName, TableState.State.ENABLED); 2128 TableState newState = MetaTableAccessor.getTableState(connection, tableName); 2129 if (newState == null) { 2130 errors.reportError(ERROR_CODE.NO_TABLE_STATE, 2131 "Unable to change state for table " + tableName + " in meta "); 2132 } 2133 } else { 2134 errors.reportError(ERROR_CODE.NO_TABLE_STATE, 2135 tableName + " has no state in meta "); 2136 } 2137 } 2138 } 2139 } 2140 2141 private void preCheckPermission() throws IOException, AccessDeniedException { 2142 if (shouldIgnorePreCheckPermission()) { 2143 return; 2144 } 2145 2146 Path hbaseDir = FSUtils.getRootDir(getConf()); 2147 FileSystem fs = hbaseDir.getFileSystem(getConf()); 2148 UserProvider userProvider = UserProvider.instantiate(getConf()); 2149 UserGroupInformation ugi = userProvider.getCurrent().getUGI(); 2150 FileStatus[] files = fs.listStatus(hbaseDir); 2151 for (FileStatus file : files) { 2152 try { 2153 FSUtils.checkAccess(ugi, file, FsAction.WRITE); 2154 } catch (AccessDeniedException ace) { 2155 LOG.warn("Got AccessDeniedException when preCheckPermission ", ace); 2156 errors.reportError(ERROR_CODE.WRONG_USAGE, "Current user " + ugi.getUserName() 2157 + " does not have write perms to " + file.getPath() 2158 + ". Please rerun hbck as hdfs user " + file.getOwner()); 2159 throw ace; 2160 } 2161 } 2162 } 2163 2164 /** 2165 * Deletes region from meta table 2166 */ 2167 private void deleteMetaRegion(HbckInfo hi) throws IOException { 2168 deleteMetaRegion(hi.metaEntry.getRegionName()); 2169 } 2170 2171 /** 2172 * Deletes region from meta table 2173 */ 2174 private void deleteMetaRegion(byte[] metaKey) throws IOException { 2175 Delete d = new Delete(metaKey); 2176 meta.delete(d); 2177 LOG.info("Deleted " + Bytes.toString(metaKey) + " from META" ); 2178 } 2179 2180 /** 2181 * Reset the split parent region info in meta table 2182 */ 2183 private void resetSplitParent(HbckInfo hi) throws IOException { 2184 RowMutations mutations = new RowMutations(hi.metaEntry.getRegionName()); 2185 Delete d = new Delete(hi.metaEntry.getRegionName()); 2186 d.addColumn(HConstants.CATALOG_FAMILY, HConstants.SPLITA_QUALIFIER); 2187 d.addColumn(HConstants.CATALOG_FAMILY, HConstants.SPLITB_QUALIFIER); 2188 mutations.add(d); 2189 2190 RegionInfo hri = RegionInfoBuilder.newBuilder(hi.metaEntry) 2191 .setOffline(false) 2192 .setSplit(false) 2193 .build(); 2194 Put p = MetaTableAccessor.makePutFromRegionInfo(hri, EnvironmentEdgeManager.currentTime()); 2195 mutations.add(p); 2196 2197 meta.mutateRow(mutations); 2198 LOG.info("Reset split parent " + hi.metaEntry.getRegionNameAsString() + " in META" ); 2199 } 2200 2201 /** 2202 * This backwards-compatibility wrapper for permanently offlining a region 2203 * that should not be alive. If the region server does not support the 2204 * "offline" method, it will use the closest unassign method instead. This 2205 * will basically work until one attempts to disable or delete the affected 2206 * table. The problem has to do with in-memory only master state, so 2207 * restarting the HMaster or failing over to another should fix this. 2208 */ 2209 private void offline(byte[] regionName) throws IOException { 2210 String regionString = Bytes.toStringBinary(regionName); 2211 if (!rsSupportsOffline) { 2212 LOG.warn("Using unassign region " + regionString 2213 + " instead of using offline method, you should" 2214 + " restart HMaster after these repairs"); 2215 admin.unassign(regionName, true); 2216 return; 2217 } 2218 2219 // first time we assume the rs's supports #offline. 2220 try { 2221 LOG.info("Offlining region " + regionString); 2222 admin.offline(regionName); 2223 } catch (IOException ioe) { 2224 String notFoundMsg = "java.lang.NoSuchMethodException: " + 2225 "org.apache.hadoop.hbase.master.HMaster.offline([B)"; 2226 if (ioe.getMessage().contains(notFoundMsg)) { 2227 LOG.warn("Using unassign region " + regionString 2228 + " instead of using offline method, you should" 2229 + " restart HMaster after these repairs"); 2230 rsSupportsOffline = false; // in the future just use unassign 2231 admin.unassign(regionName, true); 2232 return; 2233 } 2234 throw ioe; 2235 } 2236 } 2237 2238 private void undeployRegions(HbckInfo hi) throws IOException, InterruptedException { 2239 undeployRegionsForHbi(hi); 2240 // undeploy replicas of the region (but only if the method is invoked for the primary) 2241 if (hi.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) { 2242 return; 2243 } 2244 int numReplicas = admin.getTableDescriptor(hi.getTableName()).getRegionReplication(); 2245 for (int i = 1; i < numReplicas; i++) { 2246 if (hi.getPrimaryHRIForDeployedReplica() == null) continue; 2247 RegionInfo hri = RegionReplicaUtil.getRegionInfoForReplica( 2248 hi.getPrimaryHRIForDeployedReplica(), i); 2249 HbckInfo h = regionInfoMap.get(hri.getEncodedName()); 2250 if (h != null) { 2251 undeployRegionsForHbi(h); 2252 //set skip checks; we undeployed it, and we don't want to evaluate this anymore 2253 //in consistency checks 2254 h.setSkipChecks(true); 2255 } 2256 } 2257 } 2258 2259 private void undeployRegionsForHbi(HbckInfo hi) throws IOException, InterruptedException { 2260 for (OnlineEntry rse : hi.deployedEntries) { 2261 LOG.debug("Undeploy region " + rse.hri + " from " + rse.hsa); 2262 try { 2263 HBaseFsckRepair.closeRegionSilentlyAndWait(connection, rse.hsa, rse.hri); 2264 offline(rse.hri.getRegionName()); 2265 } catch (IOException ioe) { 2266 LOG.warn("Got exception when attempting to offline region " 2267 + Bytes.toString(rse.hri.getRegionName()), ioe); 2268 } 2269 } 2270 } 2271 2272 /** 2273 * Attempts to undeploy a region from a region server based in information in 2274 * META. Any operations that modify the file system should make sure that 2275 * its corresponding region is not deployed to prevent data races. 2276 * 2277 * A separate call is required to update the master in-memory region state 2278 * kept in the AssignementManager. Because disable uses this state instead of 2279 * that found in META, we can't seem to cleanly disable/delete tables that 2280 * have been hbck fixed. When used on a version of HBase that does not have 2281 * the offline ipc call exposed on the master (<0.90.5, <0.92.0) a master 2282 * restart or failover may be required. 2283 */ 2284 private void closeRegion(HbckInfo hi) throws IOException, InterruptedException { 2285 if (hi.metaEntry == null && hi.hdfsEntry == null) { 2286 undeployRegions(hi); 2287 return; 2288 } 2289 2290 // get assignment info and hregioninfo from meta. 2291 Get get = new Get(hi.getRegionName()); 2292 get.addColumn(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER); 2293 get.addColumn(HConstants.CATALOG_FAMILY, HConstants.SERVER_QUALIFIER); 2294 get.addColumn(HConstants.CATALOG_FAMILY, HConstants.STARTCODE_QUALIFIER); 2295 // also get the locations of the replicas to close if the primary region is being closed 2296 if (hi.getReplicaId() == RegionInfo.DEFAULT_REPLICA_ID) { 2297 int numReplicas = admin.getTableDescriptor(hi.getTableName()).getRegionReplication(); 2298 for (int i = 0; i < numReplicas; i++) { 2299 get.addColumn(HConstants.CATALOG_FAMILY, MetaTableAccessor.getServerColumn(i)); 2300 get.addColumn(HConstants.CATALOG_FAMILY, MetaTableAccessor.getStartCodeColumn(i)); 2301 } 2302 } 2303 Result r = meta.get(get); 2304 RegionLocations rl = MetaTableAccessor.getRegionLocations(r); 2305 if (rl == null) { 2306 LOG.warn("Unable to close region " + hi.getRegionNameAsString() + 2307 " since meta does not have handle to reach it"); 2308 return; 2309 } 2310 for (HRegionLocation h : rl.getRegionLocations()) { 2311 ServerName serverName = h.getServerName(); 2312 if (serverName == null) { 2313 errors.reportError("Unable to close region " 2314 + hi.getRegionNameAsString() + " because meta does not " 2315 + "have handle to reach it."); 2316 continue; 2317 } 2318 RegionInfo hri = h.getRegionInfo(); 2319 if (hri == null) { 2320 LOG.warn("Unable to close region " + hi.getRegionNameAsString() 2321 + " because hbase:meta had invalid or missing " 2322 + HConstants.CATALOG_FAMILY_STR + ":" 2323 + Bytes.toString(HConstants.REGIONINFO_QUALIFIER) 2324 + " qualifier value."); 2325 continue; 2326 } 2327 // close the region -- close files and remove assignment 2328 HBaseFsckRepair.closeRegionSilentlyAndWait(connection, serverName, hri); 2329 } 2330 } 2331 2332 private void tryAssignmentRepair(HbckInfo hbi, String msg) throws IOException, 2333 KeeperException, InterruptedException { 2334 // If we are trying to fix the errors 2335 if (shouldFixAssignments()) { 2336 errors.print(msg); 2337 undeployRegions(hbi); 2338 setShouldRerun(); 2339 RegionInfo hri = hbi.getHdfsHRI(); 2340 if (hri == null) { 2341 hri = hbi.metaEntry; 2342 } 2343 HBaseFsckRepair.fixUnassigned(admin, hri); 2344 HBaseFsckRepair.waitUntilAssigned(admin, hri); 2345 2346 // also assign replicas if needed (do it only when this call operates on a primary replica) 2347 if (hbi.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) return; 2348 int replicationCount = admin.getTableDescriptor(hri.getTable()).getRegionReplication(); 2349 for (int i = 1; i < replicationCount; i++) { 2350 hri = RegionReplicaUtil.getRegionInfoForReplica(hri, i); 2351 HbckInfo h = regionInfoMap.get(hri.getEncodedName()); 2352 if (h != null) { 2353 undeployRegions(h); 2354 //set skip checks; we undeploy & deploy it; we don't want to evaluate this hbi anymore 2355 //in consistency checks 2356 h.setSkipChecks(true); 2357 } 2358 HBaseFsckRepair.fixUnassigned(admin, hri); 2359 HBaseFsckRepair.waitUntilAssigned(admin, hri); 2360 } 2361 2362 } 2363 } 2364 2365 /** 2366 * Check a single region for consistency and correct deployment. 2367 */ 2368 private void checkRegionConsistency(final String key, final HbckInfo hbi) 2369 throws IOException, KeeperException, InterruptedException { 2370 2371 if (hbi.isSkipChecks()) return; 2372 String descriptiveName = hbi.toString(); 2373 boolean inMeta = hbi.metaEntry != null; 2374 // In case not checking HDFS, assume the region is on HDFS 2375 boolean inHdfs = !shouldCheckHdfs() || hbi.getHdfsRegionDir() != null; 2376 boolean hasMetaAssignment = inMeta && hbi.metaEntry.regionServer != null; 2377 boolean isDeployed = !hbi.deployedOn.isEmpty(); 2378 boolean isMultiplyDeployed = hbi.deployedOn.size() > 1; 2379 boolean deploymentMatchesMeta = 2380 hasMetaAssignment && isDeployed && !isMultiplyDeployed && 2381 hbi.metaEntry.regionServer.equals(hbi.deployedOn.get(0)); 2382 boolean splitParent = 2383 inMeta && hbi.metaEntry.isSplit() && hbi.metaEntry.isOffline(); 2384 boolean shouldBeDeployed = inMeta && !isTableDisabled(hbi.metaEntry.getTable()); 2385 boolean recentlyModified = inHdfs && 2386 hbi.getModTime() + timelag > EnvironmentEdgeManager.currentTime(); 2387 2388 // ========== First the healthy cases ============= 2389 if (hbi.containsOnlyHdfsEdits()) { 2390 return; 2391 } 2392 if (inMeta && inHdfs && isDeployed && deploymentMatchesMeta && shouldBeDeployed) { 2393 return; 2394 } else if (inMeta && inHdfs && !shouldBeDeployed && !isDeployed) { 2395 LOG.info("Region " + descriptiveName + " is in META, and in a disabled " + 2396 "tabled that is not deployed"); 2397 return; 2398 } else if (recentlyModified) { 2399 LOG.warn("Region " + descriptiveName + " was recently modified -- skipping"); 2400 return; 2401 } 2402 // ========== Cases where the region is not in hbase:meta ============= 2403 else if (!inMeta && !inHdfs && !isDeployed) { 2404 // We shouldn't have record of this region at all then! 2405 assert false : "Entry for region with no data"; 2406 } else if (!inMeta && !inHdfs && isDeployed) { 2407 errors.reportError(ERROR_CODE.NOT_IN_META_HDFS, "Region " 2408 + descriptiveName + ", key=" + key + ", not on HDFS or in hbase:meta but " + 2409 "deployed on " + Joiner.on(", ").join(hbi.deployedOn)); 2410 if (shouldFixAssignments()) { 2411 undeployRegions(hbi); 2412 } 2413 2414 } else if (!inMeta && inHdfs && !isDeployed) { 2415 if (hbi.isMerged()) { 2416 // This region has already been merged, the remaining hdfs file will be 2417 // cleaned by CatalogJanitor later 2418 hbi.setSkipChecks(true); 2419 LOG.info("Region " + descriptiveName 2420 + " got merge recently, its file(s) will be cleaned by CatalogJanitor later"); 2421 return; 2422 } 2423 errors.reportError(ERROR_CODE.NOT_IN_META_OR_DEPLOYED, "Region " 2424 + descriptiveName + " on HDFS, but not listed in hbase:meta " + 2425 "or deployed on any region server"); 2426 // restore region consistency of an adopted orphan 2427 if (shouldFixMeta()) { 2428 if (!hbi.isHdfsRegioninfoPresent()) { 2429 LOG.error("Region " + hbi.getHdfsHRI() + " could have been repaired" 2430 + " in table integrity repair phase if -fixHdfsOrphans was" + 2431 " used."); 2432 return; 2433 } 2434 2435 RegionInfo hri = hbi.getHdfsHRI(); 2436 TableInfo tableInfo = tablesInfo.get(hri.getTable()); 2437 2438 for (RegionInfo region : tableInfo.getRegionsFromMeta()) { 2439 if (Bytes.compareTo(region.getStartKey(), hri.getStartKey()) <= 0 2440 && (region.getEndKey().length == 0 || Bytes.compareTo(region.getEndKey(), 2441 hri.getEndKey()) >= 0) 2442 && Bytes.compareTo(region.getStartKey(), hri.getEndKey()) <= 0) { 2443 if(region.isSplit() || region.isOffline()) continue; 2444 Path regionDir = hbi.getHdfsRegionDir(); 2445 FileSystem fs = regionDir.getFileSystem(getConf()); 2446 List<Path> familyDirs = FSUtils.getFamilyDirs(fs, regionDir); 2447 for (Path familyDir : familyDirs) { 2448 List<Path> referenceFilePaths = FSUtils.getReferenceFilePaths(fs, familyDir); 2449 for (Path referenceFilePath : referenceFilePaths) { 2450 Path parentRegionDir = 2451 StoreFileInfo.getReferredToFile(referenceFilePath).getParent().getParent(); 2452 if (parentRegionDir.toString().endsWith(region.getEncodedName())) { 2453 LOG.warn(hri + " start and stop keys are in the range of " + region 2454 + ". The region might not be cleaned up from hdfs when region " + region 2455 + " split failed. Hence deleting from hdfs."); 2456 HRegionFileSystem.deleteRegionFromFileSystem(getConf(), fs, 2457 regionDir.getParent(), hri); 2458 return; 2459 } 2460 } 2461 } 2462 } 2463 } 2464 LOG.info("Patching hbase:meta with .regioninfo: " + hbi.getHdfsHRI()); 2465 int numReplicas = admin.getTableDescriptor(hbi.getTableName()).getRegionReplication(); 2466 HBaseFsckRepair.fixMetaHoleOnlineAndAddReplicas(getConf(), hbi.getHdfsHRI(), 2467 admin.getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS)) 2468 .getLiveServerMetrics().keySet(), numReplicas); 2469 2470 tryAssignmentRepair(hbi, "Trying to reassign region..."); 2471 } 2472 2473 } else if (!inMeta && inHdfs && isDeployed) { 2474 errors.reportError(ERROR_CODE.NOT_IN_META, "Region " + descriptiveName 2475 + " not in META, but deployed on " + Joiner.on(", ").join(hbi.deployedOn)); 2476 debugLsr(hbi.getHdfsRegionDir()); 2477 if (hbi.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) { 2478 // for replicas, this means that we should undeploy the region (we would have 2479 // gone over the primaries and fixed meta holes in first phase under 2480 // checkAndFixConsistency; we shouldn't get the condition !inMeta at 2481 // this stage unless unwanted replica) 2482 if (shouldFixAssignments()) { 2483 undeployRegionsForHbi(hbi); 2484 } 2485 } 2486 if (shouldFixMeta() && hbi.getReplicaId() == RegionInfo.DEFAULT_REPLICA_ID) { 2487 if (!hbi.isHdfsRegioninfoPresent()) { 2488 LOG.error("This should have been repaired in table integrity repair phase"); 2489 return; 2490 } 2491 2492 LOG.info("Patching hbase:meta with with .regioninfo: " + hbi.getHdfsHRI()); 2493 int numReplicas = admin.getTableDescriptor(hbi.getTableName()).getRegionReplication(); 2494 HBaseFsckRepair.fixMetaHoleOnlineAndAddReplicas(getConf(), hbi.getHdfsHRI(), 2495 admin.getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS)) 2496 .getLiveServerMetrics().keySet(), numReplicas); 2497 tryAssignmentRepair(hbi, "Trying to fix unassigned region..."); 2498 } 2499 2500 // ========== Cases where the region is in hbase:meta ============= 2501 } else if (inMeta && inHdfs && !isDeployed && splitParent) { 2502 // check whether this is an actual error, or just transient state where parent 2503 // is not cleaned 2504 if (hbi.metaEntry.splitA != null && hbi.metaEntry.splitB != null) { 2505 // check that split daughters are there 2506 HbckInfo infoA = this.regionInfoMap.get(hbi.metaEntry.splitA.getEncodedName()); 2507 HbckInfo infoB = this.regionInfoMap.get(hbi.metaEntry.splitB.getEncodedName()); 2508 if (infoA != null && infoB != null) { 2509 // we already processed or will process daughters. Move on, nothing to see here. 2510 hbi.setSkipChecks(true); 2511 return; 2512 } 2513 } 2514 2515 // For Replica region, we need to do a similar check. If replica is not split successfully, 2516 // error is going to be reported against primary daughter region. 2517 if (hbi.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) { 2518 LOG.info("Region " + descriptiveName + " is a split parent in META, in HDFS, " 2519 + "and not deployed on any region server. This may be transient."); 2520 hbi.setSkipChecks(true); 2521 return; 2522 } 2523 2524 errors.reportError(ERROR_CODE.LINGERING_SPLIT_PARENT, "Region " 2525 + descriptiveName + " is a split parent in META, in HDFS, " 2526 + "and not deployed on any region server. This could be transient, " 2527 + "consider to run the catalog janitor first!"); 2528 if (shouldFixSplitParents()) { 2529 setShouldRerun(); 2530 resetSplitParent(hbi); 2531 } 2532 } else if (inMeta && !inHdfs && !isDeployed) { 2533 errors.reportError(ERROR_CODE.NOT_IN_HDFS_OR_DEPLOYED, "Region " 2534 + descriptiveName + " found in META, but not in HDFS " 2535 + "or deployed on any region server."); 2536 if (shouldFixMeta()) { 2537 deleteMetaRegion(hbi); 2538 } 2539 } else if (inMeta && !inHdfs && isDeployed) { 2540 errors.reportError(ERROR_CODE.NOT_IN_HDFS, "Region " + descriptiveName 2541 + " found in META, but not in HDFS, " + 2542 "and deployed on " + Joiner.on(", ").join(hbi.deployedOn)); 2543 // We treat HDFS as ground truth. Any information in meta is transient 2544 // and equivalent data can be regenerated. So, lets unassign and remove 2545 // these problems from META. 2546 if (shouldFixAssignments()) { 2547 errors.print("Trying to fix unassigned region..."); 2548 undeployRegions(hbi); 2549 } 2550 if (shouldFixMeta()) { 2551 // wait for it to complete 2552 deleteMetaRegion(hbi); 2553 } 2554 } else if (inMeta && inHdfs && !isDeployed && shouldBeDeployed) { 2555 errors.reportError(ERROR_CODE.NOT_DEPLOYED, "Region " + descriptiveName 2556 + " not deployed on any region server."); 2557 tryAssignmentRepair(hbi, "Trying to fix unassigned region..."); 2558 } else if (inMeta && inHdfs && isDeployed && !shouldBeDeployed) { 2559 errors.reportError(ERROR_CODE.SHOULD_NOT_BE_DEPLOYED, 2560 "Region " + descriptiveName + " should not be deployed according " + 2561 "to META, but is deployed on " + Joiner.on(", ").join(hbi.deployedOn)); 2562 if (shouldFixAssignments()) { 2563 errors.print("Trying to close the region " + descriptiveName); 2564 setShouldRerun(); 2565 HBaseFsckRepair.fixMultiAssignment(connection, hbi.metaEntry, hbi.deployedOn); 2566 } 2567 } else if (inMeta && inHdfs && isMultiplyDeployed) { 2568 errors.reportError(ERROR_CODE.MULTI_DEPLOYED, "Region " + descriptiveName 2569 + " is listed in hbase:meta on region server " + hbi.metaEntry.regionServer 2570 + " but is multiply assigned to region servers " + 2571 Joiner.on(", ").join(hbi.deployedOn)); 2572 // If we are trying to fix the errors 2573 if (shouldFixAssignments()) { 2574 errors.print("Trying to fix assignment error..."); 2575 setShouldRerun(); 2576 HBaseFsckRepair.fixMultiAssignment(connection, hbi.metaEntry, hbi.deployedOn); 2577 } 2578 } else if (inMeta && inHdfs && isDeployed && !deploymentMatchesMeta) { 2579 errors.reportError(ERROR_CODE.SERVER_DOES_NOT_MATCH_META, "Region " 2580 + descriptiveName + " listed in hbase:meta on region server " + 2581 hbi.metaEntry.regionServer + " but found on region server " + 2582 hbi.deployedOn.get(0)); 2583 // If we are trying to fix the errors 2584 if (shouldFixAssignments()) { 2585 errors.print("Trying to fix assignment error..."); 2586 setShouldRerun(); 2587 HBaseFsckRepair.fixMultiAssignment(connection, hbi.metaEntry, hbi.deployedOn); 2588 HBaseFsckRepair.waitUntilAssigned(admin, hbi.getHdfsHRI()); 2589 } 2590 } else { 2591 errors.reportError(ERROR_CODE.UNKNOWN, "Region " + descriptiveName + 2592 " is in an unforeseen state:" + 2593 " inMeta=" + inMeta + 2594 " inHdfs=" + inHdfs + 2595 " isDeployed=" + isDeployed + 2596 " isMultiplyDeployed=" + isMultiplyDeployed + 2597 " deploymentMatchesMeta=" + deploymentMatchesMeta + 2598 " shouldBeDeployed=" + shouldBeDeployed); 2599 } 2600 } 2601 2602 /** 2603 * Checks tables integrity. Goes over all regions and scans the tables. 2604 * Collects all the pieces for each table and checks if there are missing, 2605 * repeated or overlapping ones. 2606 * @throws IOException 2607 */ 2608 SortedMap<TableName, TableInfo> checkIntegrity() throws IOException { 2609 tablesInfo = new TreeMap<>(); 2610 LOG.debug("There are " + regionInfoMap.size() + " region info entries"); 2611 for (HbckInfo hbi : regionInfoMap.values()) { 2612 // Check only valid, working regions 2613 if (hbi.metaEntry == null) { 2614 // this assumes that consistency check has run loadMetaEntry 2615 Path p = hbi.getHdfsRegionDir(); 2616 if (p == null) { 2617 errors.report("No regioninfo in Meta or HDFS. " + hbi); 2618 } 2619 2620 // TODO test. 2621 continue; 2622 } 2623 if (hbi.metaEntry.regionServer == null) { 2624 errors.detail("Skipping region because no region server: " + hbi); 2625 continue; 2626 } 2627 if (hbi.metaEntry.isOffline()) { 2628 errors.detail("Skipping region because it is offline: " + hbi); 2629 continue; 2630 } 2631 if (hbi.containsOnlyHdfsEdits()) { 2632 errors.detail("Skipping region because it only contains edits" + hbi); 2633 continue; 2634 } 2635 2636 // Missing regionDir or over-deployment is checked elsewhere. Include 2637 // these cases in modTInfo, so we can evaluate those regions as part of 2638 // the region chain in META 2639 //if (hbi.foundRegionDir == null) continue; 2640 //if (hbi.deployedOn.size() != 1) continue; 2641 if (hbi.deployedOn.isEmpty()) continue; 2642 2643 // We should be safe here 2644 TableName tableName = hbi.metaEntry.getTable(); 2645 TableInfo modTInfo = tablesInfo.get(tableName); 2646 if (modTInfo == null) { 2647 modTInfo = new TableInfo(tableName); 2648 } 2649 for (ServerName server : hbi.deployedOn) { 2650 modTInfo.addServer(server); 2651 } 2652 2653 if (!hbi.isSkipChecks()) { 2654 modTInfo.addRegionInfo(hbi); 2655 } 2656 2657 tablesInfo.put(tableName, modTInfo); 2658 } 2659 2660 loadTableInfosForTablesWithNoRegion(); 2661 2662 logParallelMerge(); 2663 for (TableInfo tInfo : tablesInfo.values()) { 2664 TableIntegrityErrorHandler handler = tInfo.new IntegrityFixSuggester(tInfo, errors); 2665 if (!tInfo.checkRegionChain(handler)) { 2666 errors.report("Found inconsistency in table " + tInfo.getName()); 2667 } 2668 } 2669 return tablesInfo; 2670 } 2671 2672 /** Loads table info's for tables that may not have been included, since there are no 2673 * regions reported for the table, but table dir is there in hdfs 2674 */ 2675 private void loadTableInfosForTablesWithNoRegion() throws IOException { 2676 Map<String, TableDescriptor> allTables = new FSTableDescriptors(getConf()).getAll(); 2677 for (TableDescriptor htd : allTables.values()) { 2678 if (checkMetaOnly && !htd.isMetaTable()) { 2679 continue; 2680 } 2681 2682 TableName tableName = htd.getTableName(); 2683 if (isTableIncluded(tableName) && !tablesInfo.containsKey(tableName)) { 2684 TableInfo tableInfo = new TableInfo(tableName); 2685 tableInfo.htds.add(htd); 2686 tablesInfo.put(htd.getTableName(), tableInfo); 2687 } 2688 } 2689 } 2690 2691 /** 2692 * Merge hdfs data by moving from contained HbckInfo into targetRegionDir. 2693 * @return number of file move fixes done to merge regions. 2694 */ 2695 public int mergeRegionDirs(Path targetRegionDir, HbckInfo contained) throws IOException { 2696 int fileMoves = 0; 2697 String thread = Thread.currentThread().getName(); 2698 LOG.debug("[" + thread + "] Contained region dir after close and pause"); 2699 debugLsr(contained.getHdfsRegionDir()); 2700 2701 // rename the contained into the container. 2702 FileSystem fs = targetRegionDir.getFileSystem(getConf()); 2703 FileStatus[] dirs = null; 2704 try { 2705 dirs = fs.listStatus(contained.getHdfsRegionDir()); 2706 } catch (FileNotFoundException fnfe) { 2707 // region we are attempting to merge in is not present! Since this is a merge, there is 2708 // no harm skipping this region if it does not exist. 2709 if (!fs.exists(contained.getHdfsRegionDir())) { 2710 LOG.warn("[" + thread + "] HDFS region dir " + contained.getHdfsRegionDir() 2711 + " is missing. Assuming already sidelined or moved."); 2712 } else { 2713 sidelineRegionDir(fs, contained); 2714 } 2715 return fileMoves; 2716 } 2717 2718 if (dirs == null) { 2719 if (!fs.exists(contained.getHdfsRegionDir())) { 2720 LOG.warn("[" + thread + "] HDFS region dir " + contained.getHdfsRegionDir() 2721 + " already sidelined."); 2722 } else { 2723 sidelineRegionDir(fs, contained); 2724 } 2725 return fileMoves; 2726 } 2727 2728 for (FileStatus cf : dirs) { 2729 Path src = cf.getPath(); 2730 Path dst = new Path(targetRegionDir, src.getName()); 2731 2732 if (src.getName().equals(HRegionFileSystem.REGION_INFO_FILE)) { 2733 // do not copy the old .regioninfo file. 2734 continue; 2735 } 2736 2737 if (src.getName().equals(HConstants.HREGION_OLDLOGDIR_NAME)) { 2738 // do not copy the .oldlogs files 2739 continue; 2740 } 2741 2742 LOG.info("[" + thread + "] Moving files from " + src + " into containing region " + dst); 2743 // FileSystem.rename is inconsistent with directories -- if the 2744 // dst (foo/a) exists and is a dir, and the src (foo/b) is a dir, 2745 // it moves the src into the dst dir resulting in (foo/a/b). If 2746 // the dst does not exist, and the src a dir, src becomes dst. (foo/b) 2747 for (FileStatus hfile : fs.listStatus(src)) { 2748 boolean success = fs.rename(hfile.getPath(), dst); 2749 if (success) { 2750 fileMoves++; 2751 } 2752 } 2753 LOG.debug("[" + thread + "] Sideline directory contents:"); 2754 debugLsr(targetRegionDir); 2755 } 2756 2757 // if all success. 2758 sidelineRegionDir(fs, contained); 2759 LOG.info("[" + thread + "] Sidelined region dir "+ contained.getHdfsRegionDir() + " into " + 2760 getSidelineDir()); 2761 debugLsr(contained.getHdfsRegionDir()); 2762 2763 return fileMoves; 2764 } 2765 2766 2767 static class WorkItemOverlapMerge implements Callable<Void> { 2768 private TableIntegrityErrorHandler handler; 2769 Collection<HbckInfo> overlapgroup; 2770 2771 WorkItemOverlapMerge(Collection<HbckInfo> overlapgroup, TableIntegrityErrorHandler handler) { 2772 this.handler = handler; 2773 this.overlapgroup = overlapgroup; 2774 } 2775 2776 @Override 2777 public Void call() throws Exception { 2778 handler.handleOverlapGroup(overlapgroup); 2779 return null; 2780 } 2781 }; 2782 2783 2784 /** 2785 * Maintain information about a particular table. 2786 */ 2787 public class TableInfo { 2788 TableName tableName; 2789 TreeSet <ServerName> deployedOn; 2790 2791 // backwards regions 2792 final List<HbckInfo> backwards = new ArrayList<>(); 2793 2794 // sidelined big overlapped regions 2795 final Map<Path, HbckInfo> sidelinedRegions = new HashMap<>(); 2796 2797 // region split calculator 2798 final RegionSplitCalculator<HbckInfo> sc = new RegionSplitCalculator<>(cmp); 2799 2800 // Histogram of different TableDescriptors found. Ideally there is only one! 2801 final Set<TableDescriptor> htds = new HashSet<>(); 2802 2803 // key = start split, values = set of splits in problem group 2804 final Multimap<byte[], HbckInfo> overlapGroups = 2805 TreeMultimap.create(RegionSplitCalculator.BYTES_COMPARATOR, cmp); 2806 2807 // list of regions derived from meta entries. 2808 private ImmutableList<RegionInfo> regionsFromMeta = null; 2809 2810 TableInfo(TableName name) { 2811 this.tableName = name; 2812 deployedOn = new TreeSet <>(); 2813 } 2814 2815 /** 2816 * @return descriptor common to all regions. null if are none or multiple! 2817 */ 2818 private TableDescriptor getHTD() { 2819 if (htds.size() == 1) { 2820 return (TableDescriptor)htds.toArray()[0]; 2821 } else { 2822 LOG.error("None/Multiple table descriptors found for table '" 2823 + tableName + "' regions: " + htds); 2824 } 2825 return null; 2826 } 2827 2828 public void addRegionInfo(HbckInfo hir) { 2829 if (Bytes.equals(hir.getEndKey(), HConstants.EMPTY_END_ROW)) { 2830 // end key is absolute end key, just add it. 2831 // ignore replicas other than primary for these checks 2832 if (hir.getReplicaId() == RegionInfo.DEFAULT_REPLICA_ID) sc.add(hir); 2833 return; 2834 } 2835 2836 // if not the absolute end key, check for cycle 2837 if (Bytes.compareTo(hir.getStartKey(), hir.getEndKey()) > 0) { 2838 errors.reportError( 2839 ERROR_CODE.REGION_CYCLE, 2840 String.format("The endkey for this region comes before the " 2841 + "startkey, startkey=%s, endkey=%s", 2842 Bytes.toStringBinary(hir.getStartKey()), 2843 Bytes.toStringBinary(hir.getEndKey())), this, hir); 2844 backwards.add(hir); 2845 return; 2846 } 2847 2848 // main case, add to split calculator 2849 // ignore replicas other than primary for these checks 2850 if (hir.getReplicaId() == RegionInfo.DEFAULT_REPLICA_ID) sc.add(hir); 2851 } 2852 2853 public void addServer(ServerName server) { 2854 this.deployedOn.add(server); 2855 } 2856 2857 public TableName getName() { 2858 return tableName; 2859 } 2860 2861 public int getNumRegions() { 2862 return sc.getStarts().size() + backwards.size(); 2863 } 2864 2865 public synchronized ImmutableList<RegionInfo> getRegionsFromMeta() { 2866 // lazy loaded, synchronized to ensure a single load 2867 if (regionsFromMeta == null) { 2868 List<RegionInfo> regions = new ArrayList<>(); 2869 for (HbckInfo h : HBaseFsck.this.regionInfoMap.values()) { 2870 if (tableName.equals(h.getTableName())) { 2871 if (h.metaEntry != null) { 2872 regions.add(h.metaEntry); 2873 } 2874 } 2875 } 2876 regionsFromMeta = Ordering.from(RegionInfo.COMPARATOR).immutableSortedCopy(regions); 2877 } 2878 2879 return regionsFromMeta; 2880 } 2881 2882 private class IntegrityFixSuggester extends TableIntegrityErrorHandlerImpl { 2883 ErrorReporter errors; 2884 2885 IntegrityFixSuggester(TableInfo ti, ErrorReporter errors) { 2886 this.errors = errors; 2887 setTableInfo(ti); 2888 } 2889 2890 @Override 2891 public void handleRegionStartKeyNotEmpty(HbckInfo hi) throws IOException{ 2892 errors.reportError(ERROR_CODE.FIRST_REGION_STARTKEY_NOT_EMPTY, 2893 "First region should start with an empty key. You need to " 2894 + " create a new region and regioninfo in HDFS to plug the hole.", 2895 getTableInfo(), hi); 2896 } 2897 2898 @Override 2899 public void handleRegionEndKeyNotEmpty(byte[] curEndKey) throws IOException { 2900 errors.reportError(ERROR_CODE.LAST_REGION_ENDKEY_NOT_EMPTY, 2901 "Last region should end with an empty key. You need to " 2902 + "create a new region and regioninfo in HDFS to plug the hole.", getTableInfo()); 2903 } 2904 2905 @Override 2906 public void handleDegenerateRegion(HbckInfo hi) throws IOException{ 2907 errors.reportError(ERROR_CODE.DEGENERATE_REGION, 2908 "Region has the same start and end key.", getTableInfo(), hi); 2909 } 2910 2911 @Override 2912 public void handleDuplicateStartKeys(HbckInfo r1, HbckInfo r2) throws IOException{ 2913 byte[] key = r1.getStartKey(); 2914 // dup start key 2915 errors.reportError(ERROR_CODE.DUPE_STARTKEYS, 2916 "Multiple regions have the same startkey: " 2917 + Bytes.toStringBinary(key), getTableInfo(), r1); 2918 errors.reportError(ERROR_CODE.DUPE_STARTKEYS, 2919 "Multiple regions have the same startkey: " 2920 + Bytes.toStringBinary(key), getTableInfo(), r2); 2921 } 2922 2923 @Override 2924 public void handleSplit(HbckInfo r1, HbckInfo r2) throws IOException{ 2925 byte[] key = r1.getStartKey(); 2926 // dup start key 2927 errors.reportError(ERROR_CODE.DUPE_ENDKEYS, 2928 "Multiple regions have the same regionID: " 2929 + Bytes.toStringBinary(key), getTableInfo(), r1); 2930 errors.reportError(ERROR_CODE.DUPE_ENDKEYS, 2931 "Multiple regions have the same regionID: " 2932 + Bytes.toStringBinary(key), getTableInfo(), r2); 2933 } 2934 2935 @Override 2936 public void handleOverlapInRegionChain(HbckInfo hi1, HbckInfo hi2) throws IOException{ 2937 errors.reportError(ERROR_CODE.OVERLAP_IN_REGION_CHAIN, 2938 "There is an overlap in the region chain.", 2939 getTableInfo(), hi1, hi2); 2940 } 2941 2942 @Override 2943 public void handleHoleInRegionChain(byte[] holeStart, byte[] holeStop) throws IOException{ 2944 errors.reportError( 2945 ERROR_CODE.HOLE_IN_REGION_CHAIN, 2946 "There is a hole in the region chain between " 2947 + Bytes.toStringBinary(holeStart) + " and " 2948 + Bytes.toStringBinary(holeStop) 2949 + ". You need to create a new .regioninfo and region " 2950 + "dir in hdfs to plug the hole."); 2951 } 2952 }; 2953 2954 /** 2955 * This handler fixes integrity errors from hdfs information. There are 2956 * basically three classes of integrity problems 1) holes, 2) overlaps, and 2957 * 3) invalid regions. 2958 * 2959 * This class overrides methods that fix holes and the overlap group case. 2960 * Individual cases of particular overlaps are handled by the general 2961 * overlap group merge repair case. 2962 * 2963 * If hbase is online, this forces regions offline before doing merge 2964 * operations. 2965 */ 2966 private class HDFSIntegrityFixer extends IntegrityFixSuggester { 2967 Configuration conf; 2968 2969 boolean fixOverlaps = true; 2970 2971 HDFSIntegrityFixer(TableInfo ti, ErrorReporter errors, Configuration conf, 2972 boolean fixHoles, boolean fixOverlaps) { 2973 super(ti, errors); 2974 this.conf = conf; 2975 this.fixOverlaps = fixOverlaps; 2976 // TODO properly use fixHoles 2977 } 2978 2979 /** 2980 * This is a special case hole -- when the first region of a table is 2981 * missing from META, HBase doesn't acknowledge the existance of the 2982 * table. 2983 */ 2984 @Override 2985 public void handleRegionStartKeyNotEmpty(HbckInfo next) throws IOException { 2986 errors.reportError(ERROR_CODE.FIRST_REGION_STARTKEY_NOT_EMPTY, 2987 "First region should start with an empty key. Creating a new " + 2988 "region and regioninfo in HDFS to plug the hole.", 2989 getTableInfo(), next); 2990 TableDescriptor htd = getTableInfo().getHTD(); 2991 // from special EMPTY_START_ROW to next region's startKey 2992 RegionInfo newRegion = RegionInfoBuilder.newBuilder(htd.getTableName()) 2993 .setStartKey(HConstants.EMPTY_START_ROW) 2994 .setEndKey(next.getStartKey()) 2995 .build(); 2996 2997 // TODO test 2998 HRegion region = HBaseFsckRepair.createHDFSRegionDir(conf, newRegion, htd); 2999 LOG.info("Table region start key was not empty. Created new empty region: " 3000 + newRegion + " " +region); 3001 fixes++; 3002 } 3003 3004 @Override 3005 public void handleRegionEndKeyNotEmpty(byte[] curEndKey) throws IOException { 3006 errors.reportError(ERROR_CODE.LAST_REGION_ENDKEY_NOT_EMPTY, 3007 "Last region should end with an empty key. Creating a new " 3008 + "region and regioninfo in HDFS to plug the hole.", getTableInfo()); 3009 TableDescriptor htd = getTableInfo().getHTD(); 3010 // from curEndKey to EMPTY_START_ROW 3011 RegionInfo newRegion = RegionInfoBuilder.newBuilder(htd.getTableName()) 3012 .setStartKey(curEndKey) 3013 .setEndKey(HConstants.EMPTY_START_ROW) 3014 .build(); 3015 3016 HRegion region = HBaseFsckRepair.createHDFSRegionDir(conf, newRegion, htd); 3017 LOG.info("Table region end key was not empty. Created new empty region: " + newRegion 3018 + " " + region); 3019 fixes++; 3020 } 3021 3022 /** 3023 * There is a hole in the hdfs regions that violates the table integrity 3024 * rules. Create a new empty region that patches the hole. 3025 */ 3026 @Override 3027 public void handleHoleInRegionChain(byte[] holeStartKey, byte[] holeStopKey) throws IOException { 3028 errors.reportError( 3029 ERROR_CODE.HOLE_IN_REGION_CHAIN, 3030 "There is a hole in the region chain between " 3031 + Bytes.toStringBinary(holeStartKey) + " and " 3032 + Bytes.toStringBinary(holeStopKey) 3033 + ". Creating a new regioninfo and region " 3034 + "dir in hdfs to plug the hole."); 3035 TableDescriptor htd = getTableInfo().getHTD(); 3036 RegionInfo newRegion = RegionInfoBuilder.newBuilder(htd.getTableName()) 3037 .setStartKey(holeStartKey) 3038 .setEndKey(holeStopKey) 3039 .build(); 3040 HRegion region = HBaseFsckRepair.createHDFSRegionDir(conf, newRegion, htd); 3041 LOG.info("Plugged hole by creating new empty region: "+ newRegion + " " +region); 3042 fixes++; 3043 } 3044 3045 /** 3046 * This takes set of overlapping regions and merges them into a single 3047 * region. This covers cases like degenerate regions, shared start key, 3048 * general overlaps, duplicate ranges, and partial overlapping regions. 3049 * 3050 * Cases: 3051 * - Clean regions that overlap 3052 * - Only .oldlogs regions (can't find start/stop range, or figure out) 3053 * 3054 * This is basically threadsafe, except for the fixer increment in mergeOverlaps. 3055 */ 3056 @Override 3057 public void handleOverlapGroup(Collection<HbckInfo> overlap) 3058 throws IOException { 3059 Preconditions.checkNotNull(overlap); 3060 Preconditions.checkArgument(overlap.size() >0); 3061 3062 if (!this.fixOverlaps) { 3063 LOG.warn("Not attempting to repair overlaps."); 3064 return; 3065 } 3066 3067 if (overlap.size() > maxMerge) { 3068 LOG.warn("Overlap group has " + overlap.size() + " overlapping " + 3069 "regions which is greater than " + maxMerge + ", the max number of regions to merge"); 3070 if (sidelineBigOverlaps) { 3071 // we only sideline big overlapped groups that exceeds the max number of regions to merge 3072 sidelineBigOverlaps(overlap); 3073 } 3074 return; 3075 } 3076 if (shouldRemoveParents()) { 3077 removeParentsAndFixSplits(overlap); 3078 } 3079 mergeOverlaps(overlap); 3080 } 3081 3082 void removeParentsAndFixSplits(Collection<HbckInfo> overlap) throws IOException { 3083 Pair<byte[], byte[]> range = null; 3084 HbckInfo parent = null; 3085 HbckInfo daughterA = null; 3086 HbckInfo daughterB = null; 3087 Collection<HbckInfo> daughters = new ArrayList<HbckInfo>(overlap); 3088 3089 String thread = Thread.currentThread().getName(); 3090 LOG.info("== [" + thread + "] Attempting fix splits in overlap state."); 3091 3092 // we only can handle a single split per group at the time 3093 if (overlap.size() > 3) { 3094 LOG.info("Too many overlaps were found on this group, falling back to regular merge."); 3095 return; 3096 } 3097 3098 for (HbckInfo hi : overlap) { 3099 if (range == null) { 3100 range = new Pair<byte[], byte[]>(hi.getStartKey(), hi.getEndKey()); 3101 } else { 3102 if (RegionSplitCalculator.BYTES_COMPARATOR 3103 .compare(hi.getStartKey(), range.getFirst()) < 0) { 3104 range.setFirst(hi.getStartKey()); 3105 } 3106 if (RegionSplitCalculator.BYTES_COMPARATOR 3107 .compare(hi.getEndKey(), range.getSecond()) > 0) { 3108 range.setSecond(hi.getEndKey()); 3109 } 3110 } 3111 } 3112 3113 LOG.info("This group range is [" + Bytes.toStringBinary(range.getFirst()) + ", " 3114 + Bytes.toStringBinary(range.getSecond()) + "]"); 3115 3116 // attempt to find a possible parent for the edge case of a split 3117 for (HbckInfo hi : overlap) { 3118 if (Bytes.compareTo(hi.getHdfsHRI().getStartKey(), range.getFirst()) == 0 3119 && Bytes.compareTo(hi.getHdfsHRI().getEndKey(), range.getSecond()) == 0) { 3120 LOG.info("This is a parent for this group: " + hi.toString()); 3121 parent = hi; 3122 } 3123 } 3124 3125 // Remove parent regions from daughters collection 3126 if (parent != null) { 3127 daughters.remove(parent); 3128 } 3129 3130 // Lets verify that daughters share the regionID at split time and they 3131 // were created after the parent 3132 for (HbckInfo hi : daughters) { 3133 if (Bytes.compareTo(hi.getHdfsHRI().getStartKey(), range.getFirst()) == 0) { 3134 if (parent.getHdfsHRI().getRegionId() < hi.getHdfsHRI().getRegionId()) { 3135 daughterA = hi; 3136 } 3137 } 3138 if (Bytes.compareTo(hi.getHdfsHRI().getEndKey(), range.getSecond()) == 0) { 3139 if (parent.getHdfsHRI().getRegionId() < hi.getHdfsHRI().getRegionId()) { 3140 daughterB = hi; 3141 } 3142 } 3143 } 3144 3145 // daughters must share the same regionID and we should have a parent too 3146 if (daughterA.getHdfsHRI().getRegionId() != daughterB.getHdfsHRI().getRegionId() || parent == null) 3147 return; 3148 3149 FileSystem fs = FileSystem.get(conf); 3150 LOG.info("Found parent: " + parent.getRegionNameAsString()); 3151 LOG.info("Found potential daughter a: " + daughterA.getRegionNameAsString()); 3152 LOG.info("Found potential daughter b: " + daughterB.getRegionNameAsString()); 3153 LOG.info("Trying to fix parent in overlap by removing the parent."); 3154 try { 3155 closeRegion(parent); 3156 } catch (IOException ioe) { 3157 LOG.warn("Parent region could not be closed, continuing with regular merge...", ioe); 3158 return; 3159 } catch (InterruptedException ie) { 3160 LOG.warn("Parent region could not be closed, continuing with regular merge...", ie); 3161 return; 3162 } 3163 3164 try { 3165 offline(parent.getRegionName()); 3166 } catch (IOException ioe) { 3167 LOG.warn("Unable to offline parent region: " + parent.getRegionNameAsString() 3168 + ". Just continuing with regular merge... ", ioe); 3169 return; 3170 } 3171 3172 try { 3173 HBaseFsckRepair.removeParentInMeta(conf, parent.getHdfsHRI()); 3174 } catch (IOException ioe) { 3175 LOG.warn("Unable to remove parent region in META: " + parent.getRegionNameAsString() 3176 + ". Just continuing with regular merge... ", ioe); 3177 return; 3178 } 3179 3180 sidelineRegionDir(fs, parent); 3181 LOG.info("[" + thread + "] Sidelined parent region dir "+ parent.getHdfsRegionDir() + " into " + 3182 getSidelineDir()); 3183 debugLsr(parent.getHdfsRegionDir()); 3184 3185 // Make sure we don't have the parents and daughters around 3186 overlap.remove(parent); 3187 overlap.remove(daughterA); 3188 overlap.remove(daughterB); 3189 3190 LOG.info("Done fixing split."); 3191 3192 } 3193 3194 void mergeOverlaps(Collection<HbckInfo> overlap) 3195 throws IOException { 3196 String thread = Thread.currentThread().getName(); 3197 LOG.info("== [" + thread + "] Merging regions into one region: " 3198 + Joiner.on(",").join(overlap)); 3199 // get the min / max range and close all concerned regions 3200 Pair<byte[], byte[]> range = null; 3201 for (HbckInfo hi : overlap) { 3202 if (range == null) { 3203 range = new Pair<>(hi.getStartKey(), hi.getEndKey()); 3204 } else { 3205 if (RegionSplitCalculator.BYTES_COMPARATOR 3206 .compare(hi.getStartKey(), range.getFirst()) < 0) { 3207 range.setFirst(hi.getStartKey()); 3208 } 3209 if (RegionSplitCalculator.BYTES_COMPARATOR 3210 .compare(hi.getEndKey(), range.getSecond()) > 0) { 3211 range.setSecond(hi.getEndKey()); 3212 } 3213 } 3214 // need to close files so delete can happen. 3215 LOG.debug("[" + thread + "] Closing region before moving data around: " + hi); 3216 LOG.debug("[" + thread + "] Contained region dir before close"); 3217 debugLsr(hi.getHdfsRegionDir()); 3218 try { 3219 LOG.info("[" + thread + "] Closing region: " + hi); 3220 closeRegion(hi); 3221 } catch (IOException ioe) { 3222 LOG.warn("[" + thread + "] Was unable to close region " + hi 3223 + ". Just continuing... ", ioe); 3224 } catch (InterruptedException e) { 3225 LOG.warn("[" + thread + "] Was unable to close region " + hi 3226 + ". Just continuing... ", e); 3227 } 3228 3229 try { 3230 LOG.info("[" + thread + "] Offlining region: " + hi); 3231 offline(hi.getRegionName()); 3232 } catch (IOException ioe) { 3233 LOG.warn("[" + thread + "] Unable to offline region from master: " + hi 3234 + ". Just continuing... ", ioe); 3235 } 3236 } 3237 3238 // create new empty container region. 3239 TableDescriptor htd = getTableInfo().getHTD(); 3240 // from start key to end Key 3241 RegionInfo newRegion = RegionInfoBuilder.newBuilder(htd.getTableName()) 3242 .setStartKey(range.getFirst()) 3243 .setEndKey(range.getSecond()) 3244 .build(); 3245 HRegion region = HBaseFsckRepair.createHDFSRegionDir(conf, newRegion, htd); 3246 LOG.info("[" + thread + "] Created new empty container region: " + 3247 newRegion + " to contain regions: " + Joiner.on(",").join(overlap)); 3248 debugLsr(region.getRegionFileSystem().getRegionDir()); 3249 3250 // all target regions are closed, should be able to safely cleanup. 3251 boolean didFix= false; 3252 Path target = region.getRegionFileSystem().getRegionDir(); 3253 for (HbckInfo contained : overlap) { 3254 LOG.info("[" + thread + "] Merging " + contained + " into " + target ); 3255 int merges = mergeRegionDirs(target, contained); 3256 if (merges > 0) { 3257 didFix = true; 3258 } 3259 } 3260 if (didFix) { 3261 fixes++; 3262 } 3263 } 3264 3265 /** 3266 * Sideline some regions in a big overlap group so that it 3267 * will have fewer regions, and it is easier to merge them later on. 3268 * 3269 * @param bigOverlap the overlapped group with regions more than maxMerge 3270 * @throws IOException 3271 */ 3272 void sidelineBigOverlaps( 3273 Collection<HbckInfo> bigOverlap) throws IOException { 3274 int overlapsToSideline = bigOverlap.size() - maxMerge; 3275 if (overlapsToSideline > maxOverlapsToSideline) { 3276 overlapsToSideline = maxOverlapsToSideline; 3277 } 3278 List<HbckInfo> regionsToSideline = 3279 RegionSplitCalculator.findBigRanges(bigOverlap, overlapsToSideline); 3280 FileSystem fs = FileSystem.get(conf); 3281 for (HbckInfo regionToSideline: regionsToSideline) { 3282 try { 3283 LOG.info("Closing region: " + regionToSideline); 3284 closeRegion(regionToSideline); 3285 } catch (IOException ioe) { 3286 LOG.warn("Was unable to close region " + regionToSideline 3287 + ". Just continuing... ", ioe); 3288 } catch (InterruptedException e) { 3289 LOG.warn("Was unable to close region " + regionToSideline 3290 + ". Just continuing... ", e); 3291 } 3292 3293 try { 3294 LOG.info("Offlining region: " + regionToSideline); 3295 offline(regionToSideline.getRegionName()); 3296 } catch (IOException ioe) { 3297 LOG.warn("Unable to offline region from master: " + regionToSideline 3298 + ". Just continuing... ", ioe); 3299 } 3300 3301 LOG.info("Before sideline big overlapped region: " + regionToSideline.toString()); 3302 Path sidelineRegionDir = sidelineRegionDir(fs, TO_BE_LOADED, regionToSideline); 3303 if (sidelineRegionDir != null) { 3304 sidelinedRegions.put(sidelineRegionDir, regionToSideline); 3305 LOG.info("After sidelined big overlapped region: " 3306 + regionToSideline.getRegionNameAsString() 3307 + " to " + sidelineRegionDir.toString()); 3308 fixes++; 3309 } 3310 } 3311 } 3312 } 3313 3314 /** 3315 * Check the region chain (from META) of this table. We are looking for 3316 * holes, overlaps, and cycles. 3317 * @return false if there are errors 3318 * @throws IOException 3319 */ 3320 public boolean checkRegionChain(TableIntegrityErrorHandler handler) throws IOException { 3321 // When table is disabled no need to check for the region chain. Some of the regions 3322 // accidently if deployed, this below code might report some issues like missing start 3323 // or end regions or region hole in chain and may try to fix which is unwanted. 3324 if (isTableDisabled(this.tableName)) { 3325 return true; 3326 } 3327 int originalErrorsCount = errors.getErrorList().size(); 3328 Multimap<byte[], HbckInfo> regions = sc.calcCoverage(); 3329 SortedSet<byte[]> splits = sc.getSplits(); 3330 3331 byte[] prevKey = null; 3332 byte[] problemKey = null; 3333 3334 if (splits.isEmpty()) { 3335 // no region for this table 3336 handler.handleHoleInRegionChain(HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW); 3337 } 3338 3339 for (byte[] key : splits) { 3340 Collection<HbckInfo> ranges = regions.get(key); 3341 if (prevKey == null && !Bytes.equals(key, HConstants.EMPTY_BYTE_ARRAY)) { 3342 for (HbckInfo rng : ranges) { 3343 handler.handleRegionStartKeyNotEmpty(rng); 3344 } 3345 } 3346 3347 // check for degenerate ranges 3348 for (HbckInfo rng : ranges) { 3349 // special endkey case converts '' to null 3350 byte[] endKey = rng.getEndKey(); 3351 endKey = (endKey.length == 0) ? null : endKey; 3352 if (Bytes.equals(rng.getStartKey(),endKey)) { 3353 handler.handleDegenerateRegion(rng); 3354 } 3355 } 3356 3357 if (ranges.size() == 1) { 3358 // this split key is ok -- no overlap, not a hole. 3359 if (problemKey != null) { 3360 LOG.warn("reached end of problem group: " + Bytes.toStringBinary(key)); 3361 } 3362 problemKey = null; // fell through, no more problem. 3363 } else if (ranges.size() > 1) { 3364 // set the new problem key group name, if already have problem key, just 3365 // keep using it. 3366 if (problemKey == null) { 3367 // only for overlap regions. 3368 LOG.warn("Naming new problem group: " + Bytes.toStringBinary(key)); 3369 problemKey = key; 3370 } 3371 overlapGroups.putAll(problemKey, ranges); 3372 3373 // record errors 3374 ArrayList<HbckInfo> subRange = new ArrayList<>(ranges); 3375 // this dumb and n^2 but this shouldn't happen often 3376 for (HbckInfo r1 : ranges) { 3377 if (r1.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) continue; 3378 subRange.remove(r1); 3379 for (HbckInfo r2 : subRange) { 3380 if (r2.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) continue; 3381 // general case of same start key 3382 if (Bytes.compareTo(r1.getStartKey(), r2.getStartKey())==0) { 3383 handler.handleDuplicateStartKeys(r1,r2); 3384 } else if (Bytes.compareTo(r1.getEndKey(), r2.getStartKey())==0 && 3385 r1.getHdfsHRI().getRegionId() == r2.getHdfsHRI().getRegionId()) { 3386 LOG.info("this is a split, log to splits"); 3387 handler.handleSplit(r1, r2); 3388 } else { 3389 // overlap 3390 handler.handleOverlapInRegionChain(r1, r2); 3391 } 3392 } 3393 } 3394 3395 } else if (ranges.isEmpty()) { 3396 if (problemKey != null) { 3397 LOG.warn("reached end of problem group: " + Bytes.toStringBinary(key)); 3398 } 3399 problemKey = null; 3400 3401 byte[] holeStopKey = sc.getSplits().higher(key); 3402 // if higher key is null we reached the top. 3403 if (holeStopKey != null) { 3404 // hole 3405 handler.handleHoleInRegionChain(key, holeStopKey); 3406 } 3407 } 3408 prevKey = key; 3409 } 3410 3411 // When the last region of a table is proper and having an empty end key, 'prevKey' 3412 // will be null. 3413 if (prevKey != null) { 3414 handler.handleRegionEndKeyNotEmpty(prevKey); 3415 } 3416 3417 // TODO fold this into the TableIntegrityHandler 3418 if (getConf().getBoolean("hbasefsck.overlap.merge.parallel", true)) { 3419 boolean ok = handleOverlapsParallel(handler, prevKey); 3420 if (!ok) { 3421 return false; 3422 } 3423 } else { 3424 for (Collection<HbckInfo> overlap : overlapGroups.asMap().values()) { 3425 handler.handleOverlapGroup(overlap); 3426 } 3427 } 3428 3429 if (details) { 3430 // do full region split map dump 3431 errors.print("---- Table '" + this.tableName 3432 + "': region split map"); 3433 dump(splits, regions); 3434 errors.print("---- Table '" + this.tableName 3435 + "': overlap groups"); 3436 dumpOverlapProblems(overlapGroups); 3437 errors.print("There are " + overlapGroups.keySet().size() 3438 + " overlap groups with " + overlapGroups.size() 3439 + " overlapping regions"); 3440 } 3441 if (!sidelinedRegions.isEmpty()) { 3442 LOG.warn("Sidelined big overlapped regions, please bulk load them!"); 3443 errors.print("---- Table '" + this.tableName 3444 + "': sidelined big overlapped regions"); 3445 dumpSidelinedRegions(sidelinedRegions); 3446 } 3447 return errors.getErrorList().size() == originalErrorsCount; 3448 } 3449 3450 private boolean handleOverlapsParallel(TableIntegrityErrorHandler handler, byte[] prevKey) 3451 throws IOException { 3452 // we parallelize overlap handler for the case we have lots of groups to fix. We can 3453 // safely assume each group is independent. 3454 List<WorkItemOverlapMerge> merges = new ArrayList<>(overlapGroups.size()); 3455 List<Future<Void>> rets; 3456 for (Collection<HbckInfo> overlap : overlapGroups.asMap().values()) { 3457 // 3458 merges.add(new WorkItemOverlapMerge(overlap, handler)); 3459 } 3460 try { 3461 rets = executor.invokeAll(merges); 3462 } catch (InterruptedException e) { 3463 LOG.error("Overlap merges were interrupted", e); 3464 return false; 3465 } 3466 for(int i=0; i<merges.size(); i++) { 3467 WorkItemOverlapMerge work = merges.get(i); 3468 Future<Void> f = rets.get(i); 3469 try { 3470 f.get(); 3471 } catch(ExecutionException e) { 3472 LOG.warn("Failed to merge overlap group" + work, e.getCause()); 3473 } catch (InterruptedException e) { 3474 LOG.error("Waiting for overlap merges was interrupted", e); 3475 return false; 3476 } 3477 } 3478 return true; 3479 } 3480 3481 /** 3482 * This dumps data in a visually reasonable way for visual debugging 3483 * 3484 * @param splits 3485 * @param regions 3486 */ 3487 void dump(SortedSet<byte[]> splits, Multimap<byte[], HbckInfo> regions) { 3488 // we display this way because the last end key should be displayed as well. 3489 StringBuilder sb = new StringBuilder(); 3490 for (byte[] k : splits) { 3491 sb.setLength(0); // clear out existing buffer, if any. 3492 sb.append(Bytes.toStringBinary(k) + ":\t"); 3493 for (HbckInfo r : regions.get(k)) { 3494 sb.append("[ "+ r.toString() + ", " 3495 + Bytes.toStringBinary(r.getEndKey())+ "]\t"); 3496 } 3497 errors.print(sb.toString()); 3498 } 3499 } 3500 } 3501 3502 public void dumpOverlapProblems(Multimap<byte[], HbckInfo> regions) { 3503 // we display this way because the last end key should be displayed as 3504 // well. 3505 for (byte[] k : regions.keySet()) { 3506 errors.print(Bytes.toStringBinary(k) + ":"); 3507 for (HbckInfo r : regions.get(k)) { 3508 errors.print("[ " + r.toString() + ", " 3509 + Bytes.toStringBinary(r.getEndKey()) + "]"); 3510 } 3511 errors.print("----"); 3512 } 3513 } 3514 3515 public void dumpSidelinedRegions(Map<Path, HbckInfo> regions) { 3516 for (Map.Entry<Path, HbckInfo> entry: regions.entrySet()) { 3517 TableName tableName = entry.getValue().getTableName(); 3518 Path path = entry.getKey(); 3519 errors.print("This sidelined region dir should be bulk loaded: " 3520 + path.toString()); 3521 errors.print("Bulk load command looks like: " 3522 + "hbase org.apache.hadoop.hbase.tool.LoadIncrementalHFiles " 3523 + path.toUri().getPath() + " "+ tableName); 3524 } 3525 } 3526 3527 public Multimap<byte[], HbckInfo> getOverlapGroups( 3528 TableName table) { 3529 TableInfo ti = tablesInfo.get(table); 3530 return ti.overlapGroups; 3531 } 3532 3533 /** 3534 * Return a list of user-space table names whose metadata have not been 3535 * modified in the last few milliseconds specified by timelag 3536 * if any of the REGIONINFO_QUALIFIER, SERVER_QUALIFIER, STARTCODE_QUALIFIER, 3537 * SPLITA_QUALIFIER, SPLITB_QUALIFIER have not changed in the last 3538 * milliseconds specified by timelag, then the table is a candidate to be returned. 3539 * @return tables that have not been modified recently 3540 * @throws IOException if an error is encountered 3541 */ 3542 TableDescriptor[] getTables(AtomicInteger numSkipped) { 3543 List<TableName> tableNames = new ArrayList<>(); 3544 long now = EnvironmentEdgeManager.currentTime(); 3545 3546 for (HbckInfo hbi : regionInfoMap.values()) { 3547 MetaEntry info = hbi.metaEntry; 3548 3549 // if the start key is zero, then we have found the first region of a table. 3550 // pick only those tables that were not modified in the last few milliseconds. 3551 if (info != null && info.getStartKey().length == 0 && !info.isMetaRegion()) { 3552 if (info.modTime + timelag < now) { 3553 tableNames.add(info.getTable()); 3554 } else { 3555 numSkipped.incrementAndGet(); // one more in-flux table 3556 } 3557 } 3558 } 3559 return getTableDescriptors(tableNames); 3560 } 3561 3562 TableDescriptor[] getTableDescriptors(List<TableName> tableNames) { 3563 LOG.info("getTableDescriptors == tableNames => " + tableNames); 3564 try (Connection conn = ConnectionFactory.createConnection(getConf()); 3565 Admin admin = conn.getAdmin()) { 3566 List<TableDescriptor> tds = admin.listTableDescriptors(tableNames); 3567 return tds.toArray(new TableDescriptor[tds.size()]); 3568 } catch (IOException e) { 3569 LOG.debug("Exception getting table descriptors", e); 3570 } 3571 return new TableDescriptor[0]; 3572 } 3573 3574 /** 3575 * Gets the entry in regionInfo corresponding to the the given encoded 3576 * region name. If the region has not been seen yet, a new entry is added 3577 * and returned. 3578 */ 3579 private synchronized HbckInfo getOrCreateInfo(String name) { 3580 HbckInfo hbi = regionInfoMap.get(name); 3581 if (hbi == null) { 3582 hbi = new HbckInfo(null); 3583 regionInfoMap.put(name, hbi); 3584 } 3585 return hbi; 3586 } 3587 3588 private void checkAndFixReplication() throws IOException { 3589 ReplicationChecker checker = new ReplicationChecker(getConf(), zkw, connection, errors); 3590 checker.checkUnDeletedQueues(); 3591 3592 if (checker.hasUnDeletedQueues() && this.fixReplication) { 3593 checker.fixUnDeletedQueues(); 3594 setShouldRerun(); 3595 } 3596 } 3597 3598 /** 3599 * Check values in regionInfo for hbase:meta 3600 * Check if zero or more than one regions with hbase:meta are found. 3601 * If there are inconsistencies (i.e. zero or more than one regions 3602 * pretend to be holding the hbase:meta) try to fix that and report an error. 3603 * @throws IOException from HBaseFsckRepair functions 3604 * @throws KeeperException 3605 * @throws InterruptedException 3606 */ 3607 boolean checkMetaRegion() throws IOException, KeeperException, InterruptedException { 3608 Map<Integer, HbckInfo> metaRegions = new HashMap<>(); 3609 for (HbckInfo value : regionInfoMap.values()) { 3610 if (value.metaEntry != null && value.metaEntry.isMetaRegion()) { 3611 metaRegions.put(value.getReplicaId(), value); 3612 } 3613 } 3614 int metaReplication = admin.getTableDescriptor(TableName.META_TABLE_NAME) 3615 .getRegionReplication(); 3616 boolean noProblem = true; 3617 // There will be always entries in regionInfoMap corresponding to hbase:meta & its replicas 3618 // Check the deployed servers. It should be exactly one server for each replica. 3619 for (int i = 0; i < metaReplication; i++) { 3620 HbckInfo metaHbckInfo = metaRegions.remove(i); 3621 List<ServerName> servers = new ArrayList<>(); 3622 if (metaHbckInfo != null) { 3623 servers = metaHbckInfo.deployedOn; 3624 } 3625 if (servers.size() != 1) { 3626 noProblem = false; 3627 if (servers.isEmpty()) { 3628 assignMetaReplica(i); 3629 } else if (servers.size() > 1) { 3630 errors 3631 .reportError(ERROR_CODE.MULTI_META_REGION, "hbase:meta, replicaId " + 3632 metaHbckInfo.getReplicaId() + " is found on more than one region."); 3633 if (shouldFixAssignments()) { 3634 errors.print("Trying to fix a problem with hbase:meta, replicaId " + 3635 metaHbckInfo.getReplicaId() +".."); 3636 setShouldRerun(); 3637 // try fix it (treat is a dupe assignment) 3638 HBaseFsckRepair.fixMultiAssignment(connection, metaHbckInfo.metaEntry, servers); 3639 } 3640 } 3641 } 3642 } 3643 // unassign whatever is remaining in metaRegions. They are excess replicas. 3644 for (Map.Entry<Integer, HbckInfo> entry : metaRegions.entrySet()) { 3645 noProblem = false; 3646 errors.reportError(ERROR_CODE.SHOULD_NOT_BE_DEPLOYED, 3647 "hbase:meta replicas are deployed in excess. Configured " + metaReplication + 3648 ", deployed " + metaRegions.size()); 3649 if (shouldFixAssignments()) { 3650 errors.print("Trying to undeploy excess replica, replicaId: " + entry.getKey() + 3651 " of hbase:meta.."); 3652 setShouldRerun(); 3653 unassignMetaReplica(entry.getValue()); 3654 } 3655 } 3656 // if noProblem is false, rerun hbck with hopefully fixed META 3657 // if noProblem is true, no errors, so continue normally 3658 return noProblem; 3659 } 3660 3661 private void unassignMetaReplica(HbckInfo hi) throws IOException, InterruptedException, 3662 KeeperException { 3663 undeployRegions(hi); 3664 ZKUtil.deleteNode(zkw, zkw.znodePaths.getZNodeForReplica(hi.metaEntry.getReplicaId())); 3665 } 3666 3667 private void assignMetaReplica(int replicaId) 3668 throws IOException, KeeperException, InterruptedException { 3669 errors.reportError(ERROR_CODE.NO_META_REGION, "hbase:meta, replicaId " + 3670 replicaId +" is not found on any region."); 3671 if (shouldFixAssignments()) { 3672 errors.print("Trying to fix a problem with hbase:meta.."); 3673 setShouldRerun(); 3674 // try to fix it (treat it as unassigned region) 3675 RegionInfo h = RegionReplicaUtil.getRegionInfoForReplica( 3676 RegionInfoBuilder.FIRST_META_REGIONINFO, replicaId); 3677 HBaseFsckRepair.fixUnassigned(admin, h); 3678 HBaseFsckRepair.waitUntilAssigned(admin, h); 3679 } 3680 } 3681 3682 /** 3683 * Scan hbase:meta, adding all regions found to the regionInfo map. 3684 * @throws IOException if an error is encountered 3685 */ 3686 boolean loadMetaEntries() throws IOException { 3687 MetaTableAccessor.Visitor visitor = new MetaTableAccessor.Visitor() { 3688 int countRecord = 1; 3689 3690 // comparator to sort KeyValues with latest modtime 3691 final Comparator<Cell> comp = new Comparator<Cell>() { 3692 @Override 3693 public int compare(Cell k1, Cell k2) { 3694 return Long.compare(k1.getTimestamp(), k2.getTimestamp()); 3695 } 3696 }; 3697 3698 @Override 3699 public boolean visit(Result result) throws IOException { 3700 try { 3701 3702 // record the latest modification of this META record 3703 long ts = Collections.max(result.listCells(), comp).getTimestamp(); 3704 RegionLocations rl = MetaTableAccessor.getRegionLocations(result); 3705 if (rl == null) { 3706 emptyRegionInfoQualifiers.add(result); 3707 errors.reportError(ERROR_CODE.EMPTY_META_CELL, 3708 "Empty REGIONINFO_QUALIFIER found in hbase:meta"); 3709 return true; 3710 } 3711 ServerName sn = null; 3712 if (rl.getRegionLocation(RegionInfo.DEFAULT_REPLICA_ID) == null || 3713 rl.getRegionLocation(RegionInfo.DEFAULT_REPLICA_ID).getRegionInfo() == null) { 3714 emptyRegionInfoQualifiers.add(result); 3715 errors.reportError(ERROR_CODE.EMPTY_META_CELL, 3716 "Empty REGIONINFO_QUALIFIER found in hbase:meta"); 3717 return true; 3718 } 3719 RegionInfo hri = rl.getRegionLocation(RegionInfo.DEFAULT_REPLICA_ID).getRegionInfo(); 3720 if (!(isTableIncluded(hri.getTable()) 3721 || hri.isMetaRegion())) { 3722 return true; 3723 } 3724 PairOfSameType<RegionInfo> daughters = MetaTableAccessor.getDaughterRegions(result); 3725 for (HRegionLocation h : rl.getRegionLocations()) { 3726 if (h == null || h.getRegionInfo() == null) { 3727 continue; 3728 } 3729 sn = h.getServerName(); 3730 hri = h.getRegionInfo(); 3731 3732 MetaEntry m = null; 3733 if (hri.getReplicaId() == RegionInfo.DEFAULT_REPLICA_ID) { 3734 m = new MetaEntry(hri, sn, ts, daughters.getFirst(), daughters.getSecond()); 3735 } else { 3736 m = new MetaEntry(hri, sn, ts, null, null); 3737 } 3738 HbckInfo previous = regionInfoMap.get(hri.getEncodedName()); 3739 if (previous == null) { 3740 regionInfoMap.put(hri.getEncodedName(), new HbckInfo(m)); 3741 } else if (previous.metaEntry == null) { 3742 previous.metaEntry = m; 3743 } else { 3744 throw new IOException("Two entries in hbase:meta are same " + previous); 3745 } 3746 } 3747 PairOfSameType<RegionInfo> mergeRegions = MetaTableAccessor.getMergeRegions(result); 3748 for (RegionInfo mergeRegion : new RegionInfo[] { 3749 mergeRegions.getFirst(), mergeRegions.getSecond() }) { 3750 if (mergeRegion != null) { 3751 // This region is already been merged 3752 HbckInfo hbInfo = getOrCreateInfo(mergeRegion.getEncodedName()); 3753 hbInfo.setMerged(true); 3754 } 3755 } 3756 3757 // show proof of progress to the user, once for every 100 records. 3758 if (countRecord % 100 == 0) { 3759 errors.progress(); 3760 } 3761 countRecord++; 3762 return true; 3763 } catch (RuntimeException e) { 3764 LOG.error("Result=" + result); 3765 throw e; 3766 } 3767 } 3768 }; 3769 if (!checkMetaOnly) { 3770 // Scan hbase:meta to pick up user regions 3771 MetaTableAccessor.fullScanRegions(connection, visitor); 3772 } 3773 3774 errors.print(""); 3775 return true; 3776 } 3777 3778 /** 3779 * Stores the regioninfo entries scanned from META 3780 */ 3781 static class MetaEntry extends HRegionInfo { 3782 ServerName regionServer; // server hosting this region 3783 long modTime; // timestamp of most recent modification metadata 3784 RegionInfo splitA, splitB; //split daughters 3785 3786 public MetaEntry(RegionInfo rinfo, ServerName regionServer, long modTime) { 3787 this(rinfo, regionServer, modTime, null, null); 3788 } 3789 3790 public MetaEntry(RegionInfo rinfo, ServerName regionServer, long modTime, 3791 RegionInfo splitA, RegionInfo splitB) { 3792 super(rinfo); 3793 this.regionServer = regionServer; 3794 this.modTime = modTime; 3795 this.splitA = splitA; 3796 this.splitB = splitB; 3797 } 3798 3799 @Override 3800 public boolean equals(Object o) { 3801 boolean superEq = super.equals(o); 3802 if (!superEq) { 3803 return superEq; 3804 } 3805 3806 MetaEntry me = (MetaEntry) o; 3807 if (!regionServer.equals(me.regionServer)) { 3808 return false; 3809 } 3810 return (modTime == me.modTime); 3811 } 3812 3813 @Override 3814 public int hashCode() { 3815 int hash = Arrays.hashCode(getRegionName()); 3816 hash = (int) (hash ^ getRegionId()); 3817 hash ^= Arrays.hashCode(getStartKey()); 3818 hash ^= Arrays.hashCode(getEndKey()); 3819 hash ^= Boolean.valueOf(isOffline()).hashCode(); 3820 hash ^= getTable().hashCode(); 3821 if (regionServer != null) { 3822 hash ^= regionServer.hashCode(); 3823 } 3824 hash = (int) (hash ^ modTime); 3825 return hash; 3826 } 3827 } 3828 3829 /** 3830 * Stores the regioninfo entries from HDFS 3831 */ 3832 static class HdfsEntry { 3833 RegionInfo hri; 3834 Path hdfsRegionDir = null; 3835 long hdfsRegionDirModTime = 0; 3836 boolean hdfsRegioninfoFilePresent = false; 3837 boolean hdfsOnlyEdits = false; 3838 } 3839 3840 /** 3841 * Stores the regioninfo retrieved from Online region servers. 3842 */ 3843 static class OnlineEntry { 3844 RegionInfo hri; 3845 ServerName hsa; 3846 3847 @Override 3848 public String toString() { 3849 return hsa.toString() + ";" + hri.getRegionNameAsString(); 3850 } 3851 } 3852 3853 /** 3854 * Maintain information about a particular region. It gathers information 3855 * from three places -- HDFS, META, and region servers. 3856 */ 3857 public static class HbckInfo implements KeyRange { 3858 private MetaEntry metaEntry = null; // info in META 3859 private HdfsEntry hdfsEntry = null; // info in HDFS 3860 private List<OnlineEntry> deployedEntries = Lists.newArrayList(); // on Region Server 3861 private List<ServerName> deployedOn = Lists.newArrayList(); // info on RS's 3862 private boolean skipChecks = false; // whether to skip further checks to this region info. 3863 private boolean isMerged = false;// whether this region has already been merged into another one 3864 private int deployedReplicaId = RegionInfo.DEFAULT_REPLICA_ID; 3865 private RegionInfo primaryHRIForDeployedReplica = null; 3866 3867 HbckInfo(MetaEntry metaEntry) { 3868 this.metaEntry = metaEntry; 3869 } 3870 3871 public synchronized int getReplicaId() { 3872 return metaEntry != null? metaEntry.getReplicaId(): deployedReplicaId; 3873 } 3874 3875 public synchronized void addServer(RegionInfo hri, ServerName server) { 3876 OnlineEntry rse = new OnlineEntry() ; 3877 rse.hri = hri; 3878 rse.hsa = server; 3879 this.deployedEntries.add(rse); 3880 this.deployedOn.add(server); 3881 // save the replicaId that we see deployed in the cluster 3882 this.deployedReplicaId = hri.getReplicaId(); 3883 this.primaryHRIForDeployedReplica = 3884 RegionReplicaUtil.getRegionInfoForDefaultReplica(hri); 3885 } 3886 3887 @Override 3888 public synchronized String toString() { 3889 StringBuilder sb = new StringBuilder(); 3890 sb.append("{ meta => "); 3891 sb.append((metaEntry != null)? metaEntry.getRegionNameAsString() : "null"); 3892 sb.append( ", hdfs => " + getHdfsRegionDir()); 3893 sb.append( ", deployed => " + Joiner.on(", ").join(deployedEntries)); 3894 sb.append( ", replicaId => " + getReplicaId()); 3895 sb.append(" }"); 3896 return sb.toString(); 3897 } 3898 3899 @Override 3900 public byte[] getStartKey() { 3901 if (this.metaEntry != null) { 3902 return this.metaEntry.getStartKey(); 3903 } else if (this.hdfsEntry != null) { 3904 return this.hdfsEntry.hri.getStartKey(); 3905 } else { 3906 LOG.error("Entry " + this + " has no meta or hdfs region start key."); 3907 return null; 3908 } 3909 } 3910 3911 @Override 3912 public byte[] getEndKey() { 3913 if (this.metaEntry != null) { 3914 return this.metaEntry.getEndKey(); 3915 } else if (this.hdfsEntry != null) { 3916 return this.hdfsEntry.hri.getEndKey(); 3917 } else { 3918 LOG.error("Entry " + this + " has no meta or hdfs region start key."); 3919 return null; 3920 } 3921 } 3922 3923 public TableName getTableName() { 3924 if (this.metaEntry != null) { 3925 return this.metaEntry.getTable(); 3926 } else if (this.hdfsEntry != null) { 3927 // we are only guaranteed to have a path and not an HRI for hdfsEntry, 3928 // so we get the name from the Path 3929 Path tableDir = this.hdfsEntry.hdfsRegionDir.getParent(); 3930 return FSUtils.getTableName(tableDir); 3931 } else { 3932 // return the info from the first online/deployed hri 3933 for (OnlineEntry e : deployedEntries) { 3934 return e.hri.getTable(); 3935 } 3936 return null; 3937 } 3938 } 3939 3940 public String getRegionNameAsString() { 3941 if (metaEntry != null) { 3942 return metaEntry.getRegionNameAsString(); 3943 } else if (hdfsEntry != null) { 3944 if (hdfsEntry.hri != null) { 3945 return hdfsEntry.hri.getRegionNameAsString(); 3946 } 3947 } else { 3948 // return the info from the first online/deployed hri 3949 for (OnlineEntry e : deployedEntries) { 3950 return e.hri.getRegionNameAsString(); 3951 } 3952 } 3953 return null; 3954 } 3955 3956 public byte[] getRegionName() { 3957 if (metaEntry != null) { 3958 return metaEntry.getRegionName(); 3959 } else if (hdfsEntry != null) { 3960 return hdfsEntry.hri.getRegionName(); 3961 } else { 3962 // return the info from the first online/deployed hri 3963 for (OnlineEntry e : deployedEntries) { 3964 return e.hri.getRegionName(); 3965 } 3966 return null; 3967 } 3968 } 3969 3970 public RegionInfo getPrimaryHRIForDeployedReplica() { 3971 return primaryHRIForDeployedReplica; 3972 } 3973 3974 Path getHdfsRegionDir() { 3975 if (hdfsEntry == null) { 3976 return null; 3977 } 3978 return hdfsEntry.hdfsRegionDir; 3979 } 3980 3981 boolean containsOnlyHdfsEdits() { 3982 if (hdfsEntry == null) { 3983 return false; 3984 } 3985 return hdfsEntry.hdfsOnlyEdits; 3986 } 3987 3988 boolean isHdfsRegioninfoPresent() { 3989 if (hdfsEntry == null) { 3990 return false; 3991 } 3992 return hdfsEntry.hdfsRegioninfoFilePresent; 3993 } 3994 3995 long getModTime() { 3996 if (hdfsEntry == null) { 3997 return 0; 3998 } 3999 return hdfsEntry.hdfsRegionDirModTime; 4000 } 4001 4002 RegionInfo getHdfsHRI() { 4003 if (hdfsEntry == null) { 4004 return null; 4005 } 4006 return hdfsEntry.hri; 4007 } 4008 4009 public void setSkipChecks(boolean skipChecks) { 4010 this.skipChecks = skipChecks; 4011 } 4012 4013 public boolean isSkipChecks() { 4014 return skipChecks; 4015 } 4016 4017 public void setMerged(boolean isMerged) { 4018 this.isMerged = isMerged; 4019 } 4020 4021 public boolean isMerged() { 4022 return this.isMerged; 4023 } 4024 } 4025 4026 final static Comparator<HbckInfo> cmp = new Comparator<HbckInfo>() { 4027 @Override 4028 public int compare(HbckInfo l, HbckInfo r) { 4029 if (l == r) { 4030 // same instance 4031 return 0; 4032 } 4033 4034 int tableCompare = l.getTableName().compareTo(r.getTableName()); 4035 if (tableCompare != 0) { 4036 return tableCompare; 4037 } 4038 4039 int startComparison = RegionSplitCalculator.BYTES_COMPARATOR.compare( 4040 l.getStartKey(), r.getStartKey()); 4041 if (startComparison != 0) { 4042 return startComparison; 4043 } 4044 4045 // Special case for absolute endkey 4046 byte[] endKey = r.getEndKey(); 4047 endKey = (endKey.length == 0) ? null : endKey; 4048 byte[] endKey2 = l.getEndKey(); 4049 endKey2 = (endKey2.length == 0) ? null : endKey2; 4050 int endComparison = RegionSplitCalculator.BYTES_COMPARATOR.compare( 4051 endKey2, endKey); 4052 4053 if (endComparison != 0) { 4054 return endComparison; 4055 } 4056 4057 // use regionId as tiebreaker. 4058 // Null is considered after all possible values so make it bigger. 4059 if (l.hdfsEntry == null && r.hdfsEntry == null) { 4060 return 0; 4061 } 4062 if (l.hdfsEntry == null && r.hdfsEntry != null) { 4063 return 1; 4064 } 4065 // l.hdfsEntry must not be null 4066 if (r.hdfsEntry == null) { 4067 return -1; 4068 } 4069 // both l.hdfsEntry and r.hdfsEntry must not be null. 4070 return Long.compare(l.hdfsEntry.hri.getRegionId(), r.hdfsEntry.hri.getRegionId()); 4071 } 4072 }; 4073 4074 /** 4075 * Prints summary of all tables found on the system. 4076 */ 4077 private void printTableSummary(SortedMap<TableName, TableInfo> tablesInfo) { 4078 StringBuilder sb = new StringBuilder(); 4079 int numOfSkippedRegions; 4080 errors.print("Summary:"); 4081 for (TableInfo tInfo : tablesInfo.values()) { 4082 numOfSkippedRegions = (skippedRegions.containsKey(tInfo.getName())) ? 4083 skippedRegions.get(tInfo.getName()).size() : 0; 4084 4085 if (errors.tableHasErrors(tInfo)) { 4086 errors.print("Table " + tInfo.getName() + " is inconsistent."); 4087 } else if (numOfSkippedRegions > 0){ 4088 errors.print("Table " + tInfo.getName() + " is okay (with " 4089 + numOfSkippedRegions + " skipped regions)."); 4090 } 4091 else { 4092 errors.print("Table " + tInfo.getName() + " is okay."); 4093 } 4094 errors.print(" Number of regions: " + tInfo.getNumRegions()); 4095 if (numOfSkippedRegions > 0) { 4096 Set<String> skippedRegionStrings = skippedRegions.get(tInfo.getName()); 4097 System.out.println(" Number of skipped regions: " + numOfSkippedRegions); 4098 System.out.println(" List of skipped regions:"); 4099 for(String sr : skippedRegionStrings) { 4100 System.out.println(" " + sr); 4101 } 4102 } 4103 sb.setLength(0); // clear out existing buffer, if any. 4104 sb.append(" Deployed on: "); 4105 for (ServerName server : tInfo.deployedOn) { 4106 sb.append(" " + server.toString()); 4107 } 4108 errors.print(sb.toString()); 4109 } 4110 } 4111 4112 static ErrorReporter getErrorReporter( 4113 final Configuration conf) throws ClassNotFoundException { 4114 Class<? extends ErrorReporter> reporter = conf.getClass("hbasefsck.errorreporter", PrintingErrorReporter.class, ErrorReporter.class); 4115 return ReflectionUtils.newInstance(reporter, conf); 4116 } 4117 4118 public interface ErrorReporter { 4119 enum ERROR_CODE { 4120 UNKNOWN, NO_META_REGION, NULL_META_REGION, NO_VERSION_FILE, NOT_IN_META_HDFS, NOT_IN_META, 4121 NOT_IN_META_OR_DEPLOYED, NOT_IN_HDFS_OR_DEPLOYED, NOT_IN_HDFS, SERVER_DOES_NOT_MATCH_META, 4122 NOT_DEPLOYED, 4123 MULTI_DEPLOYED, SHOULD_NOT_BE_DEPLOYED, MULTI_META_REGION, RS_CONNECT_FAILURE, 4124 FIRST_REGION_STARTKEY_NOT_EMPTY, LAST_REGION_ENDKEY_NOT_EMPTY, DUPE_STARTKEYS, 4125 HOLE_IN_REGION_CHAIN, OVERLAP_IN_REGION_CHAIN, REGION_CYCLE, DEGENERATE_REGION, 4126 ORPHAN_HDFS_REGION, LINGERING_SPLIT_PARENT, NO_TABLEINFO_FILE, LINGERING_REFERENCE_HFILE, 4127 LINGERING_HFILELINK, WRONG_USAGE, EMPTY_META_CELL, EXPIRED_TABLE_LOCK, BOUNDARIES_ERROR, 4128 ORPHAN_TABLE_STATE, NO_TABLE_STATE, UNDELETED_REPLICATION_QUEUE, DUPE_ENDKEYS, 4129 UNSUPPORTED_OPTION 4130 } 4131 void clear(); 4132 void report(String message); 4133 void reportError(String message); 4134 void reportError(ERROR_CODE errorCode, String message); 4135 void reportError(ERROR_CODE errorCode, String message, TableInfo table); 4136 void reportError(ERROR_CODE errorCode, String message, TableInfo table, HbckInfo info); 4137 void reportError( 4138 ERROR_CODE errorCode, 4139 String message, 4140 TableInfo table, 4141 HbckInfo info1, 4142 HbckInfo info2 4143 ); 4144 int summarize(); 4145 void detail(String details); 4146 ArrayList<ERROR_CODE> getErrorList(); 4147 void progress(); 4148 void print(String message); 4149 void resetErrors(); 4150 boolean tableHasErrors(TableInfo table); 4151 } 4152 4153 static class PrintingErrorReporter implements ErrorReporter { 4154 public int errorCount = 0; 4155 private int showProgress; 4156 // How frequently calls to progress() will create output 4157 private static final int progressThreshold = 100; 4158 4159 Set<TableInfo> errorTables = new HashSet<>(); 4160 4161 // for use by unit tests to verify which errors were discovered 4162 private ArrayList<ERROR_CODE> errorList = new ArrayList<>(); 4163 4164 @Override 4165 public void clear() { 4166 errorTables.clear(); 4167 errorList.clear(); 4168 errorCount = 0; 4169 } 4170 4171 @Override 4172 public synchronized void reportError(ERROR_CODE errorCode, String message) { 4173 if (errorCode == ERROR_CODE.WRONG_USAGE) { 4174 System.err.println(message); 4175 return; 4176 } 4177 4178 errorList.add(errorCode); 4179 if (!summary) { 4180 System.out.println("ERROR: " + message); 4181 } 4182 errorCount++; 4183 showProgress = 0; 4184 } 4185 4186 @Override 4187 public synchronized void reportError(ERROR_CODE errorCode, String message, TableInfo table) { 4188 errorTables.add(table); 4189 reportError(errorCode, message); 4190 } 4191 4192 @Override 4193 public synchronized void reportError(ERROR_CODE errorCode, String message, TableInfo table, 4194 HbckInfo info) { 4195 errorTables.add(table); 4196 String reference = "(region " + info.getRegionNameAsString() + ")"; 4197 reportError(errorCode, reference + " " + message); 4198 } 4199 4200 @Override 4201 public synchronized void reportError(ERROR_CODE errorCode, String message, TableInfo table, 4202 HbckInfo info1, HbckInfo info2) { 4203 errorTables.add(table); 4204 String reference = "(regions " + info1.getRegionNameAsString() 4205 + " and " + info2.getRegionNameAsString() + ")"; 4206 reportError(errorCode, reference + " " + message); 4207 } 4208 4209 @Override 4210 public synchronized void reportError(String message) { 4211 reportError(ERROR_CODE.UNKNOWN, message); 4212 } 4213 4214 /** 4215 * Report error information, but do not increment the error count. Intended for cases 4216 * where the actual error would have been reported previously. 4217 * @param message 4218 */ 4219 @Override 4220 public synchronized void report(String message) { 4221 if (! summary) { 4222 System.out.println("ERROR: " + message); 4223 } 4224 showProgress = 0; 4225 } 4226 4227 @Override 4228 public synchronized int summarize() { 4229 System.out.println(Integer.toString(errorCount) + 4230 " inconsistencies detected."); 4231 if (errorCount == 0) { 4232 System.out.println("Status: OK"); 4233 return 0; 4234 } else { 4235 System.out.println("Status: INCONSISTENT"); 4236 return -1; 4237 } 4238 } 4239 4240 @Override 4241 public ArrayList<ERROR_CODE> getErrorList() { 4242 return errorList; 4243 } 4244 4245 @Override 4246 public synchronized void print(String message) { 4247 if (!summary) { 4248 System.out.println(message); 4249 } 4250 } 4251 4252 @Override 4253 public boolean tableHasErrors(TableInfo table) { 4254 return errorTables.contains(table); 4255 } 4256 4257 @Override 4258 public void resetErrors() { 4259 errorCount = 0; 4260 } 4261 4262 @Override 4263 public synchronized void detail(String message) { 4264 if (details) { 4265 System.out.println(message); 4266 } 4267 showProgress = 0; 4268 } 4269 4270 @Override 4271 public synchronized void progress() { 4272 if (showProgress++ == progressThreshold) { 4273 if (!summary) { 4274 System.out.print("."); 4275 } 4276 showProgress = 0; 4277 } 4278 } 4279 } 4280 4281 /** 4282 * Contact a region server and get all information from it 4283 */ 4284 static class WorkItemRegion implements Callable<Void> { 4285 private final HBaseFsck hbck; 4286 private final ServerName rsinfo; 4287 private final ErrorReporter errors; 4288 private final ClusterConnection connection; 4289 4290 WorkItemRegion(HBaseFsck hbck, ServerName info, 4291 ErrorReporter errors, ClusterConnection connection) { 4292 this.hbck = hbck; 4293 this.rsinfo = info; 4294 this.errors = errors; 4295 this.connection = connection; 4296 } 4297 4298 @Override 4299 public synchronized Void call() throws IOException { 4300 errors.progress(); 4301 try { 4302 BlockingInterface server = connection.getAdmin(rsinfo); 4303 4304 // list all online regions from this region server 4305 List<RegionInfo> regions = ProtobufUtil.getOnlineRegions(server); 4306 regions = filterRegions(regions); 4307 4308 if (details) { 4309 errors.detail("RegionServer: " + rsinfo.getServerName() + 4310 " number of regions: " + regions.size()); 4311 for (RegionInfo rinfo: regions) { 4312 errors.detail(" " + rinfo.getRegionNameAsString() + 4313 " id: " + rinfo.getRegionId() + 4314 " encoded_name: " + rinfo.getEncodedName() + 4315 " start: " + Bytes.toStringBinary(rinfo.getStartKey()) + 4316 " end: " + Bytes.toStringBinary(rinfo.getEndKey())); 4317 } 4318 } 4319 4320 // check to see if the existence of this region matches the region in META 4321 for (RegionInfo r:regions) { 4322 HbckInfo hbi = hbck.getOrCreateInfo(r.getEncodedName()); 4323 hbi.addServer(r, rsinfo); 4324 } 4325 } catch (IOException e) { // unable to connect to the region server. 4326 errors.reportError(ERROR_CODE.RS_CONNECT_FAILURE, "RegionServer: " + rsinfo.getServerName() + 4327 " Unable to fetch region information. " + e); 4328 throw e; 4329 } 4330 return null; 4331 } 4332 4333 private List<RegionInfo> filterRegions(List<RegionInfo> regions) { 4334 List<RegionInfo> ret = Lists.newArrayList(); 4335 for (RegionInfo hri : regions) { 4336 if (hri.isMetaRegion() || (!hbck.checkMetaOnly 4337 && hbck.isTableIncluded(hri.getTable()))) { 4338 ret.add(hri); 4339 } 4340 } 4341 return ret; 4342 } 4343 } 4344 4345 /** 4346 * Contact hdfs and get all information about specified table directory into 4347 * regioninfo list. 4348 */ 4349 class WorkItemHdfsDir implements Callable<Void> { 4350 private FileStatus tableDir; 4351 private ErrorReporter errors; 4352 private FileSystem fs; 4353 4354 WorkItemHdfsDir(FileSystem fs, ErrorReporter errors, 4355 FileStatus status) { 4356 this.fs = fs; 4357 this.tableDir = status; 4358 this.errors = errors; 4359 } 4360 4361 @Override 4362 public synchronized Void call() throws InterruptedException, ExecutionException { 4363 final Vector<Exception> exceptions = new Vector<>(); 4364 4365 try { 4366 final FileStatus[] regionDirs = fs.listStatus(tableDir.getPath()); 4367 final List<Future<?>> futures = new ArrayList<>(regionDirs.length); 4368 4369 for (final FileStatus regionDir : regionDirs) { 4370 errors.progress(); 4371 final String encodedName = regionDir.getPath().getName(); 4372 // ignore directories that aren't hexadecimal 4373 if (!encodedName.toLowerCase(Locale.ROOT).matches("[0-9a-f]+")) { 4374 continue; 4375 } 4376 4377 if (!exceptions.isEmpty()) { 4378 break; 4379 } 4380 4381 futures.add(executor.submit(new Runnable() { 4382 @Override 4383 public void run() { 4384 try { 4385 LOG.debug("Loading region info from hdfs:"+ regionDir.getPath()); 4386 4387 Path regioninfoFile = new Path(regionDir.getPath(), HRegionFileSystem.REGION_INFO_FILE); 4388 boolean regioninfoFileExists = fs.exists(regioninfoFile); 4389 4390 if (!regioninfoFileExists) { 4391 // As tables become larger it is more and more likely that by the time you 4392 // reach a given region that it will be gone due to region splits/merges. 4393 if (!fs.exists(regionDir.getPath())) { 4394 LOG.warn("By the time we tried to process this region dir it was already gone: " 4395 + regionDir.getPath()); 4396 return; 4397 } 4398 } 4399 4400 HbckInfo hbi = HBaseFsck.this.getOrCreateInfo(encodedName); 4401 HdfsEntry he = new HdfsEntry(); 4402 synchronized (hbi) { 4403 if (hbi.getHdfsRegionDir() != null) { 4404 errors.print("Directory " + encodedName + " duplicate??" + 4405 hbi.getHdfsRegionDir()); 4406 } 4407 4408 he.hdfsRegionDir = regionDir.getPath(); 4409 he.hdfsRegionDirModTime = regionDir.getModificationTime(); 4410 he.hdfsRegioninfoFilePresent = regioninfoFileExists; 4411 // we add to orphan list when we attempt to read .regioninfo 4412 4413 // Set a flag if this region contains only edits 4414 // This is special case if a region is left after split 4415 he.hdfsOnlyEdits = true; 4416 FileStatus[] subDirs = fs.listStatus(regionDir.getPath()); 4417 Path ePath = WALSplitter.getRegionDirRecoveredEditsDir(regionDir.getPath()); 4418 for (FileStatus subDir : subDirs) { 4419 errors.progress(); 4420 String sdName = subDir.getPath().getName(); 4421 if (!sdName.startsWith(".") && !sdName.equals(ePath.getName())) { 4422 he.hdfsOnlyEdits = false; 4423 break; 4424 } 4425 } 4426 hbi.hdfsEntry = he; 4427 } 4428 } catch (Exception e) { 4429 LOG.error("Could not load region dir", e); 4430 exceptions.add(e); 4431 } 4432 } 4433 })); 4434 } 4435 4436 // Ensure all pending tasks are complete (or that we run into an exception) 4437 for (Future<?> f : futures) { 4438 if (!exceptions.isEmpty()) { 4439 break; 4440 } 4441 try { 4442 f.get(); 4443 } catch (ExecutionException e) { 4444 LOG.error("Unexpected exec exception! Should've been caught already. (Bug?)", e); 4445 // Shouldn't happen, we already logged/caught any exceptions in the Runnable 4446 }; 4447 } 4448 } catch (IOException e) { 4449 LOG.error("Cannot execute WorkItemHdfsDir for " + tableDir, e); 4450 exceptions.add(e); 4451 } finally { 4452 if (!exceptions.isEmpty()) { 4453 errors.reportError(ERROR_CODE.RS_CONNECT_FAILURE, "Table Directory: " 4454 + tableDir.getPath().getName() 4455 + " Unable to fetch all HDFS region information. "); 4456 // Just throw the first exception as an indication something bad happened 4457 // Don't need to propagate all the exceptions, we already logged them all anyway 4458 throw new ExecutionException("First exception in WorkItemHdfsDir", exceptions.firstElement()); 4459 } 4460 } 4461 return null; 4462 } 4463 } 4464 4465 /** 4466 * Contact hdfs and get all information about specified table directory into 4467 * regioninfo list. 4468 */ 4469 static class WorkItemHdfsRegionInfo implements Callable<Void> { 4470 private HbckInfo hbi; 4471 private HBaseFsck hbck; 4472 private ErrorReporter errors; 4473 4474 WorkItemHdfsRegionInfo(HbckInfo hbi, HBaseFsck hbck, ErrorReporter errors) { 4475 this.hbi = hbi; 4476 this.hbck = hbck; 4477 this.errors = errors; 4478 } 4479 4480 @Override 4481 public synchronized Void call() throws IOException { 4482 // only load entries that haven't been loaded yet. 4483 if (hbi.getHdfsHRI() == null) { 4484 try { 4485 errors.progress(); 4486 hbck.loadHdfsRegioninfo(hbi); 4487 } catch (IOException ioe) { 4488 String msg = "Orphan region in HDFS: Unable to load .regioninfo from table " 4489 + hbi.getTableName() + " in hdfs dir " 4490 + hbi.getHdfsRegionDir() 4491 + "! It may be an invalid format or version file. Treating as " 4492 + "an orphaned regiondir."; 4493 errors.reportError(ERROR_CODE.ORPHAN_HDFS_REGION, msg); 4494 try { 4495 hbck.debugLsr(hbi.getHdfsRegionDir()); 4496 } catch (IOException ioe2) { 4497 LOG.error("Unable to read directory " + hbi.getHdfsRegionDir(), ioe2); 4498 throw ioe2; 4499 } 4500 hbck.orphanHdfsDirs.add(hbi); 4501 throw ioe; 4502 } 4503 } 4504 return null; 4505 } 4506 }; 4507 4508 /** 4509 * Display the full report from fsck. This displays all live and dead region 4510 * servers, and all known regions. 4511 */ 4512 public static void setDisplayFullReport() { 4513 details = true; 4514 } 4515 4516 /** 4517 * Set exclusive mode. 4518 */ 4519 public static void setForceExclusive() { 4520 forceExclusive = true; 4521 } 4522 4523 /** 4524 * Only one instance of hbck can modify HBase at a time. 4525 */ 4526 public boolean isExclusive() { 4527 return fixAny || forceExclusive; 4528 } 4529 4530 /** 4531 * Set summary mode. 4532 * Print only summary of the tables and status (OK or INCONSISTENT) 4533 */ 4534 static void setSummary() { 4535 summary = true; 4536 } 4537 4538 /** 4539 * Set hbase:meta check mode. 4540 * Print only info about hbase:meta table deployment/state 4541 */ 4542 void setCheckMetaOnly() { 4543 checkMetaOnly = true; 4544 } 4545 4546 /** 4547 * Set region boundaries check mode. 4548 */ 4549 void setRegionBoundariesCheck() { 4550 checkRegionBoundaries = true; 4551 } 4552 4553 /** 4554 * Set replication fix mode. 4555 */ 4556 public void setFixReplication(boolean shouldFix) { 4557 fixReplication = shouldFix; 4558 fixAny |= shouldFix; 4559 } 4560 4561 /** 4562 * Check if we should rerun fsck again. This checks if we've tried to 4563 * fix something and we should rerun fsck tool again. 4564 * Display the full report from fsck. This displays all live and dead 4565 * region servers, and all known regions. 4566 */ 4567 void setShouldRerun() { 4568 rerun = true; 4569 } 4570 4571 boolean shouldRerun() { 4572 return rerun; 4573 } 4574 4575 /** 4576 * Fix inconsistencies found by fsck. This should try to fix errors (if any) 4577 * found by fsck utility. 4578 */ 4579 public void setFixAssignments(boolean shouldFix) { 4580 fixAssignments = shouldFix; 4581 fixAny |= shouldFix; 4582 } 4583 4584 boolean shouldFixAssignments() { 4585 return fixAssignments; 4586 } 4587 4588 public void setFixMeta(boolean shouldFix) { 4589 fixMeta = shouldFix; 4590 fixAny |= shouldFix; 4591 } 4592 4593 boolean shouldFixMeta() { 4594 return fixMeta; 4595 } 4596 4597 public void setFixEmptyMetaCells(boolean shouldFix) { 4598 fixEmptyMetaCells = shouldFix; 4599 fixAny |= shouldFix; 4600 } 4601 4602 boolean shouldFixEmptyMetaCells() { 4603 return fixEmptyMetaCells; 4604 } 4605 4606 public void setCheckHdfs(boolean checking) { 4607 checkHdfs = checking; 4608 } 4609 4610 boolean shouldCheckHdfs() { 4611 return checkHdfs; 4612 } 4613 4614 public void setFixHdfsHoles(boolean shouldFix) { 4615 fixHdfsHoles = shouldFix; 4616 fixAny |= shouldFix; 4617 } 4618 4619 boolean shouldFixHdfsHoles() { 4620 return fixHdfsHoles; 4621 } 4622 4623 public void setFixTableOrphans(boolean shouldFix) { 4624 fixTableOrphans = shouldFix; 4625 fixAny |= shouldFix; 4626 } 4627 4628 boolean shouldFixTableOrphans() { 4629 return fixTableOrphans; 4630 } 4631 4632 public void setFixHdfsOverlaps(boolean shouldFix) { 4633 fixHdfsOverlaps = shouldFix; 4634 fixAny |= shouldFix; 4635 } 4636 4637 boolean shouldFixHdfsOverlaps() { 4638 return fixHdfsOverlaps; 4639 } 4640 4641 public void setFixHdfsOrphans(boolean shouldFix) { 4642 fixHdfsOrphans = shouldFix; 4643 fixAny |= shouldFix; 4644 } 4645 4646 boolean shouldFixHdfsOrphans() { 4647 return fixHdfsOrphans; 4648 } 4649 4650 public void setFixVersionFile(boolean shouldFix) { 4651 fixVersionFile = shouldFix; 4652 fixAny |= shouldFix; 4653 } 4654 4655 public boolean shouldFixVersionFile() { 4656 return fixVersionFile; 4657 } 4658 4659 public void setSidelineBigOverlaps(boolean sbo) { 4660 this.sidelineBigOverlaps = sbo; 4661 } 4662 4663 public boolean shouldSidelineBigOverlaps() { 4664 return sidelineBigOverlaps; 4665 } 4666 4667 public void setFixSplitParents(boolean shouldFix) { 4668 fixSplitParents = shouldFix; 4669 fixAny |= shouldFix; 4670 } 4671 4672 public void setRemoveParents(boolean shouldFix) { 4673 removeParents = shouldFix; 4674 fixAny |= shouldFix; 4675 } 4676 4677 boolean shouldFixSplitParents() { 4678 return fixSplitParents; 4679 } 4680 4681 boolean shouldRemoveParents() { 4682 return removeParents; 4683 } 4684 4685 public void setFixReferenceFiles(boolean shouldFix) { 4686 fixReferenceFiles = shouldFix; 4687 fixAny |= shouldFix; 4688 } 4689 4690 boolean shouldFixReferenceFiles() { 4691 return fixReferenceFiles; 4692 } 4693 4694 public void setFixHFileLinks(boolean shouldFix) { 4695 fixHFileLinks = shouldFix; 4696 fixAny |= shouldFix; 4697 } 4698 4699 boolean shouldFixHFileLinks() { 4700 return fixHFileLinks; 4701 } 4702 4703 public boolean shouldIgnorePreCheckPermission() { 4704 return !fixAny || ignorePreCheckPermission; 4705 } 4706 4707 public void setIgnorePreCheckPermission(boolean ignorePreCheckPermission) { 4708 this.ignorePreCheckPermission = ignorePreCheckPermission; 4709 } 4710 4711 /** 4712 * @param mm maximum number of regions to merge into a single region. 4713 */ 4714 public void setMaxMerge(int mm) { 4715 this.maxMerge = mm; 4716 } 4717 4718 public int getMaxMerge() { 4719 return maxMerge; 4720 } 4721 4722 public void setMaxOverlapsToSideline(int mo) { 4723 this.maxOverlapsToSideline = mo; 4724 } 4725 4726 public int getMaxOverlapsToSideline() { 4727 return maxOverlapsToSideline; 4728 } 4729 4730 /** 4731 * Only check/fix tables specified by the list, 4732 * Empty list means all tables are included. 4733 */ 4734 boolean isTableIncluded(TableName table) { 4735 return (tablesIncluded.isEmpty()) || tablesIncluded.contains(table); 4736 } 4737 4738 public void includeTable(TableName table) { 4739 tablesIncluded.add(table); 4740 } 4741 4742 Set<TableName> getIncludedTables() { 4743 return new HashSet<>(tablesIncluded); 4744 } 4745 4746 /** 4747 * We are interested in only those tables that have not changed their state in 4748 * hbase:meta during the last few seconds specified by hbase.admin.fsck.timelag 4749 * @param seconds - the time in seconds 4750 */ 4751 public void setTimeLag(long seconds) { 4752 timelag = seconds * 1000; // convert to milliseconds 4753 } 4754 4755 /** 4756 * 4757 * @param sidelineDir - HDFS path to sideline data 4758 */ 4759 public void setSidelineDir(String sidelineDir) { 4760 this.sidelineDir = new Path(sidelineDir); 4761 } 4762 4763 protected HFileCorruptionChecker createHFileCorruptionChecker(boolean sidelineCorruptHFiles) throws IOException { 4764 return new HFileCorruptionChecker(getConf(), executor, sidelineCorruptHFiles); 4765 } 4766 4767 public HFileCorruptionChecker getHFilecorruptionChecker() { 4768 return hfcc; 4769 } 4770 4771 public void setHFileCorruptionChecker(HFileCorruptionChecker hfcc) { 4772 this.hfcc = hfcc; 4773 } 4774 4775 public void setRetCode(int code) { 4776 this.retcode = code; 4777 } 4778 4779 public int getRetCode() { 4780 return retcode; 4781 } 4782 4783 protected HBaseFsck printUsageAndExit() { 4784 StringWriter sw = new StringWriter(2048); 4785 PrintWriter out = new PrintWriter(sw); 4786 out.println(""); 4787 out.println("-----------------------------------------------------------------------"); 4788 out.println("NOTE: As of HBase version 2.0, the hbck tool is significantly changed."); 4789 out.println("In general, all Read-Only options are supported and can be be used"); 4790 out.println("safely. Most -fix/ -repair options are NOT supported. Please see usage"); 4791 out.println("below for details on which options are not supported."); 4792 out.println("-----------------------------------------------------------------------"); 4793 out.println(""); 4794 out.println("Usage: fsck [opts] {only tables}"); 4795 out.println(" where [opts] are:"); 4796 out.println(" -help Display help options (this)"); 4797 out.println(" -details Display full report of all regions."); 4798 out.println(" -timelag <timeInSeconds> Process only regions that " + 4799 " have not experienced any metadata updates in the last " + 4800 " <timeInSeconds> seconds."); 4801 out.println(" -sleepBeforeRerun <timeInSeconds> Sleep this many seconds" + 4802 " before checking if the fix worked if run with -fix"); 4803 out.println(" -summary Print only summary of the tables and status."); 4804 out.println(" -metaonly Only check the state of the hbase:meta table."); 4805 out.println(" -sidelineDir <hdfs://> HDFS path to backup existing meta."); 4806 out.println(" -boundaries Verify that regions boundaries are the same between META and store files."); 4807 out.println(" -exclusive Abort if another hbck is exclusive or fixing."); 4808 4809 out.println(""); 4810 out.println(" Datafile Repair options: (expert features, use with caution!)"); 4811 out.println(" -checkCorruptHFiles Check all Hfiles by opening them to make sure they are valid"); 4812 out.println(" -sidelineCorruptHFiles Quarantine corrupted HFiles. implies -checkCorruptHFiles"); 4813 4814 out.println(""); 4815 out.println(" Replication options"); 4816 out.println(" -fixReplication Deletes replication queues for removed peers"); 4817 4818 out.println(""); 4819 out.println(" Metadata Repair options supported as of version 2.0: (expert features, use with caution!)"); 4820 out.println(" -fixVersionFile Try to fix missing hbase.version file in hdfs."); 4821 out.println(" -fixReferenceFiles Try to offline lingering reference store files"); 4822 out.println(" -fixHFileLinks Try to offline lingering HFileLinks"); 4823 out.println(" -noHdfsChecking Don't load/check region info from HDFS." 4824 + " Assumes hbase:meta region info is good. Won't check/fix any HDFS issue, e.g. hole, orphan, or overlap"); 4825 out.println(" -ignorePreCheckPermission ignore filesystem permission pre-check"); 4826 4827 out.println(""); 4828 out.println("NOTE: Following options are NOT supported as of HBase version 2.0+."); 4829 out.println(""); 4830 out.println(" UNSUPPORTED Metadata Repair options: (expert features, use with caution!)"); 4831 out.println(" -fix Try to fix region assignments. This is for backwards compatiblity"); 4832 out.println(" -fixAssignments Try to fix region assignments. Replaces the old -fix"); 4833 out.println(" -fixMeta Try to fix meta problems. This assumes HDFS region info is good."); 4834 out.println(" -fixHdfsHoles Try to fix region holes in hdfs."); 4835 out.println(" -fixHdfsOrphans Try to fix region dirs with no .regioninfo file in hdfs"); 4836 out.println(" -fixTableOrphans Try to fix table dirs with no .tableinfo file in hdfs (online mode only)"); 4837 out.println(" -fixHdfsOverlaps Try to fix region overlaps in hdfs."); 4838 out.println(" -maxMerge <n> When fixing region overlaps, allow at most <n> regions to merge. (n=" + DEFAULT_MAX_MERGE +" by default)"); 4839 out.println(" -sidelineBigOverlaps When fixing region overlaps, allow to sideline big overlaps"); 4840 out.println(" -maxOverlapsToSideline <n> When fixing region overlaps, allow at most <n> regions to sideline per group. (n=" + DEFAULT_OVERLAPS_TO_SIDELINE +" by default)"); 4841 out.println(" -fixSplitParents Try to force offline split parents to be online."); 4842 out.println(" -removeParents Try to offline and sideline lingering parents and keep daughter regions."); 4843 out.println(" -fixEmptyMetaCells Try to fix hbase:meta entries not referencing any region" 4844 + " (empty REGIONINFO_QUALIFIER rows)"); 4845 4846 out.println(""); 4847 out.println(" UNSUPPORTED Metadata Repair shortcuts"); 4848 out.println(" -repair Shortcut for -fixAssignments -fixMeta -fixHdfsHoles " + 4849 "-fixHdfsOrphans -fixHdfsOverlaps -fixVersionFile -sidelineBigOverlaps -fixReferenceFiles" + 4850 "-fixHFileLinks"); 4851 out.println(" -repairHoles Shortcut for -fixAssignments -fixMeta -fixHdfsHoles"); 4852 4853 out.flush(); 4854 errors.reportError(ERROR_CODE.WRONG_USAGE, sw.toString()); 4855 4856 setRetCode(-2); 4857 return this; 4858 } 4859 4860 /** 4861 * Main program 4862 * 4863 * @param args 4864 * @throws Exception 4865 */ 4866 public static void main(String[] args) throws Exception { 4867 // create a fsck object 4868 Configuration conf = HBaseConfiguration.create(); 4869 Path hbasedir = FSUtils.getRootDir(conf); 4870 URI defaultFs = hbasedir.getFileSystem(conf).getUri(); 4871 FSUtils.setFsDefault(conf, new Path(defaultFs)); 4872 int ret = ToolRunner.run(new HBaseFsckTool(conf), args); 4873 System.exit(ret); 4874 } 4875 4876 /** 4877 * This is a Tool wrapper that gathers -Dxxx=yyy configuration settings from the command line. 4878 */ 4879 static class HBaseFsckTool extends Configured implements Tool { 4880 HBaseFsckTool(Configuration conf) { super(conf); } 4881 @Override 4882 public int run(String[] args) throws Exception { 4883 HBaseFsck hbck = new HBaseFsck(getConf()); 4884 hbck.exec(hbck.executor, args); 4885 hbck.close(); 4886 return hbck.getRetCode(); 4887 } 4888 }; 4889 4890 4891 public HBaseFsck exec(ExecutorService exec, String[] args) throws KeeperException, IOException, 4892 InterruptedException { 4893 long sleepBeforeRerun = DEFAULT_SLEEP_BEFORE_RERUN; 4894 4895 boolean checkCorruptHFiles = false; 4896 boolean sidelineCorruptHFiles = false; 4897 4898 // Process command-line args. 4899 for (int i = 0; i < args.length; i++) { 4900 String cmd = args[i]; 4901 if (cmd.equals("-help") || cmd.equals("-h")) { 4902 return printUsageAndExit(); 4903 } else if (cmd.equals("-details")) { 4904 setDisplayFullReport(); 4905 } else if (cmd.equals("-exclusive")) { 4906 setForceExclusive(); 4907 } else if (cmd.equals("-timelag")) { 4908 if (i == args.length - 1) { 4909 errors.reportError(ERROR_CODE.WRONG_USAGE, "HBaseFsck: -timelag needs a value."); 4910 return printUsageAndExit(); 4911 } 4912 try { 4913 long timelag = Long.parseLong(args[i+1]); 4914 setTimeLag(timelag); 4915 } catch (NumberFormatException e) { 4916 errors.reportError(ERROR_CODE.WRONG_USAGE, "-timelag needs a numeric value."); 4917 return printUsageAndExit(); 4918 } 4919 i++; 4920 } else if (cmd.equals("-sleepBeforeRerun")) { 4921 if (i == args.length - 1) { 4922 errors.reportError(ERROR_CODE.WRONG_USAGE, 4923 "HBaseFsck: -sleepBeforeRerun needs a value."); 4924 return printUsageAndExit(); 4925 } 4926 try { 4927 sleepBeforeRerun = Long.parseLong(args[i+1]); 4928 } catch (NumberFormatException e) { 4929 errors.reportError(ERROR_CODE.WRONG_USAGE, "-sleepBeforeRerun needs a numeric value."); 4930 return printUsageAndExit(); 4931 } 4932 i++; 4933 } else if (cmd.equals("-sidelineDir")) { 4934 if (i == args.length - 1) { 4935 errors.reportError(ERROR_CODE.WRONG_USAGE, "HBaseFsck: -sidelineDir needs a value."); 4936 return printUsageAndExit(); 4937 } 4938 i++; 4939 setSidelineDir(args[i]); 4940 } else if (cmd.equals("-fix")) { 4941 errors.reportError(ERROR_CODE.WRONG_USAGE, 4942 "This option is deprecated, please use -fixAssignments instead."); 4943 setFixAssignments(true); 4944 } else if (cmd.equals("-fixAssignments")) { 4945 setFixAssignments(true); 4946 } else if (cmd.equals("-fixMeta")) { 4947 setFixMeta(true); 4948 } else if (cmd.equals("-noHdfsChecking")) { 4949 setCheckHdfs(false); 4950 } else if (cmd.equals("-fixHdfsHoles")) { 4951 setFixHdfsHoles(true); 4952 } else if (cmd.equals("-fixHdfsOrphans")) { 4953 setFixHdfsOrphans(true); 4954 } else if (cmd.equals("-fixTableOrphans")) { 4955 setFixTableOrphans(true); 4956 } else if (cmd.equals("-fixHdfsOverlaps")) { 4957 setFixHdfsOverlaps(true); 4958 } else if (cmd.equals("-fixVersionFile")) { 4959 setFixVersionFile(true); 4960 } else if (cmd.equals("-sidelineBigOverlaps")) { 4961 setSidelineBigOverlaps(true); 4962 } else if (cmd.equals("-fixSplitParents")) { 4963 setFixSplitParents(true); 4964 } else if (cmd.equals("-removeParents")) { 4965 setRemoveParents(true); 4966 } else if (cmd.equals("-ignorePreCheckPermission")) { 4967 setIgnorePreCheckPermission(true); 4968 } else if (cmd.equals("-checkCorruptHFiles")) { 4969 checkCorruptHFiles = true; 4970 } else if (cmd.equals("-sidelineCorruptHFiles")) { 4971 sidelineCorruptHFiles = true; 4972 } else if (cmd.equals("-fixReferenceFiles")) { 4973 setFixReferenceFiles(true); 4974 } else if (cmd.equals("-fixHFileLinks")) { 4975 setFixHFileLinks(true); 4976 } else if (cmd.equals("-fixEmptyMetaCells")) { 4977 setFixEmptyMetaCells(true); 4978 } else if (cmd.equals("-repair")) { 4979 // this attempts to merge overlapping hdfs regions, needs testing 4980 // under load 4981 setFixHdfsHoles(true); 4982 setFixHdfsOrphans(true); 4983 setFixMeta(true); 4984 setFixAssignments(true); 4985 setFixHdfsOverlaps(true); 4986 setFixVersionFile(true); 4987 setSidelineBigOverlaps(true); 4988 setFixSplitParents(false); 4989 setCheckHdfs(true); 4990 setFixReferenceFiles(true); 4991 setFixHFileLinks(true); 4992 } else if (cmd.equals("-repairHoles")) { 4993 // this will make all missing hdfs regions available but may lose data 4994 setFixHdfsHoles(true); 4995 setFixHdfsOrphans(false); 4996 setFixMeta(true); 4997 setFixAssignments(true); 4998 setFixHdfsOverlaps(false); 4999 setSidelineBigOverlaps(false); 5000 setFixSplitParents(false); 5001 setCheckHdfs(true); 5002 } else if (cmd.equals("-maxOverlapsToSideline")) { 5003 if (i == args.length - 1) { 5004 errors.reportError(ERROR_CODE.WRONG_USAGE, 5005 "-maxOverlapsToSideline needs a numeric value argument."); 5006 return printUsageAndExit(); 5007 } 5008 try { 5009 int maxOverlapsToSideline = Integer.parseInt(args[i+1]); 5010 setMaxOverlapsToSideline(maxOverlapsToSideline); 5011 } catch (NumberFormatException e) { 5012 errors.reportError(ERROR_CODE.WRONG_USAGE, 5013 "-maxOverlapsToSideline needs a numeric value argument."); 5014 return printUsageAndExit(); 5015 } 5016 i++; 5017 } else if (cmd.equals("-maxMerge")) { 5018 if (i == args.length - 1) { 5019 errors.reportError(ERROR_CODE.WRONG_USAGE, 5020 "-maxMerge needs a numeric value argument."); 5021 return printUsageAndExit(); 5022 } 5023 try { 5024 int maxMerge = Integer.parseInt(args[i+1]); 5025 setMaxMerge(maxMerge); 5026 } catch (NumberFormatException e) { 5027 errors.reportError(ERROR_CODE.WRONG_USAGE, 5028 "-maxMerge needs a numeric value argument."); 5029 return printUsageAndExit(); 5030 } 5031 i++; 5032 } else if (cmd.equals("-summary")) { 5033 setSummary(); 5034 } else if (cmd.equals("-metaonly")) { 5035 setCheckMetaOnly(); 5036 } else if (cmd.equals("-boundaries")) { 5037 setRegionBoundariesCheck(); 5038 } else if (cmd.equals("-fixReplication")) { 5039 setFixReplication(true); 5040 } else if (cmd.startsWith("-")) { 5041 errors.reportError(ERROR_CODE.WRONG_USAGE, "Unrecognized option:" + cmd); 5042 return printUsageAndExit(); 5043 } else { 5044 includeTable(TableName.valueOf(cmd)); 5045 errors.print("Allow checking/fixes for table: " + cmd); 5046 } 5047 } 5048 5049 errors.print("HBaseFsck command line options: " + StringUtils.join(args, " ")); 5050 5051 // pre-check current user has FS write permission or not 5052 try { 5053 preCheckPermission(); 5054 } catch (AccessDeniedException ace) { 5055 Runtime.getRuntime().exit(-1); 5056 } catch (IOException ioe) { 5057 Runtime.getRuntime().exit(-1); 5058 } 5059 5060 // do the real work of hbck 5061 connect(); 5062 5063 // after connecting to server above, we have server version 5064 // check if unsupported option is specified based on server version 5065 if (!isOptionsSupported(args)) { 5066 return printUsageAndExit(); 5067 } 5068 5069 try { 5070 // if corrupt file mode is on, first fix them since they may be opened later 5071 if (checkCorruptHFiles || sidelineCorruptHFiles) { 5072 LOG.info("Checking all hfiles for corruption"); 5073 HFileCorruptionChecker hfcc = createHFileCorruptionChecker(sidelineCorruptHFiles); 5074 setHFileCorruptionChecker(hfcc); // so we can get result 5075 Collection<TableName> tables = getIncludedTables(); 5076 Collection<Path> tableDirs = new ArrayList<>(); 5077 Path rootdir = FSUtils.getRootDir(getConf()); 5078 if (tables.size() > 0) { 5079 for (TableName t : tables) { 5080 tableDirs.add(FSUtils.getTableDir(rootdir, t)); 5081 } 5082 } else { 5083 tableDirs = FSUtils.getTableDirs(FSUtils.getCurrentFileSystem(getConf()), rootdir); 5084 } 5085 hfcc.checkTables(tableDirs); 5086 hfcc.report(errors); 5087 } 5088 5089 // check and fix table integrity, region consistency. 5090 int code = onlineHbck(); 5091 setRetCode(code); 5092 // If we have changed the HBase state it is better to run hbck again 5093 // to see if we haven't broken something else in the process. 5094 // We run it only once more because otherwise we can easily fall into 5095 // an infinite loop. 5096 if (shouldRerun()) { 5097 try { 5098 LOG.info("Sleeping " + sleepBeforeRerun + "ms before re-checking after fix..."); 5099 Thread.sleep(sleepBeforeRerun); 5100 } catch (InterruptedException ie) { 5101 LOG.warn("Interrupted while sleeping"); 5102 return this; 5103 } 5104 // Just report 5105 setFixAssignments(false); 5106 setFixMeta(false); 5107 setFixHdfsHoles(false); 5108 setFixHdfsOverlaps(false); 5109 setFixVersionFile(false); 5110 setFixTableOrphans(false); 5111 errors.resetErrors(); 5112 code = onlineHbck(); 5113 setRetCode(code); 5114 } 5115 } finally { 5116 IOUtils.closeQuietly(this); 5117 } 5118 return this; 5119 } 5120 5121 private boolean isOptionsSupported(String[] args) { 5122 boolean result = true; 5123 String hbaseServerVersion = status.getHBaseVersion(); 5124 Object[] versionComponents = VersionInfo.getVersionComponents(hbaseServerVersion); 5125 if (versionComponents[0] instanceof Integer && ((Integer)versionComponents[0]) >= 2) { 5126 // Process command-line args. 5127 for (String arg : args) { 5128 if (unsupportedOptionsInV2.contains(arg)) { 5129 errors.reportError(ERROR_CODE.UNSUPPORTED_OPTION, 5130 "option '" + arg + "' is not " + "supportted!"); 5131 result = false; 5132 break; 5133 } 5134 } 5135 } 5136 return result; 5137 } 5138 5139 /** 5140 * ls -r for debugging purposes 5141 */ 5142 void debugLsr(Path p) throws IOException { 5143 debugLsr(getConf(), p, errors); 5144 } 5145 5146 /** 5147 * ls -r for debugging purposes 5148 */ 5149 public static void debugLsr(Configuration conf, 5150 Path p) throws IOException { 5151 debugLsr(conf, p, new PrintingErrorReporter()); 5152 } 5153 5154 /** 5155 * ls -r for debugging purposes 5156 */ 5157 public static void debugLsr(Configuration conf, 5158 Path p, ErrorReporter errors) throws IOException { 5159 if (!LOG.isDebugEnabled() || p == null) { 5160 return; 5161 } 5162 FileSystem fs = p.getFileSystem(conf); 5163 5164 if (!fs.exists(p)) { 5165 // nothing 5166 return; 5167 } 5168 errors.print(p.toString()); 5169 5170 if (fs.isFile(p)) { 5171 return; 5172 } 5173 5174 if (fs.getFileStatus(p).isDirectory()) { 5175 FileStatus[] fss= fs.listStatus(p); 5176 for (FileStatus status : fss) { 5177 debugLsr(conf, status.getPath(), errors); 5178 } 5179 } 5180 } 5181}