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.Collection;
030import java.util.Collections;
031import java.util.Comparator;
032import java.util.EnumSet;
033import java.util.HashMap;
034import java.util.HashSet;
035import java.util.Iterator;
036import java.util.List;
037import java.util.Locale;
038import java.util.Map;
039import java.util.Map.Entry;
040import java.util.Objects;
041import java.util.Optional;
042import java.util.Set;
043import java.util.SortedMap;
044import java.util.TreeMap;
045import java.util.Vector;
046import java.util.concurrent.Callable;
047import java.util.concurrent.ConcurrentSkipListMap;
048import java.util.concurrent.ExecutionException;
049import java.util.concurrent.ExecutorService;
050import java.util.concurrent.Executors;
051import java.util.concurrent.Future;
052import java.util.concurrent.FutureTask;
053import java.util.concurrent.ScheduledThreadPoolExecutor;
054import java.util.concurrent.TimeUnit;
055import java.util.concurrent.TimeoutException;
056import java.util.concurrent.atomic.AtomicBoolean;
057import java.util.concurrent.atomic.AtomicInteger;
058import java.util.stream.Collectors;
059
060import org.apache.commons.io.IOUtils;
061import org.apache.commons.lang3.StringUtils;
062import org.apache.hadoop.conf.Configuration;
063import org.apache.hadoop.conf.Configured;
064import org.apache.hadoop.fs.FSDataOutputStream;
065import org.apache.hadoop.fs.FileStatus;
066import org.apache.hadoop.fs.FileSystem;
067import org.apache.hadoop.fs.Path;
068import org.apache.hadoop.fs.permission.FsAction;
069import org.apache.hadoop.fs.permission.FsPermission;
070import org.apache.hadoop.hbase.Abortable;
071import org.apache.hadoop.hbase.Cell;
072import org.apache.hadoop.hbase.CellUtil;
073import org.apache.hadoop.hbase.ClusterMetrics;
074import org.apache.hadoop.hbase.ClusterMetrics.Option;
075import org.apache.hadoop.hbase.HBaseConfiguration;
076import org.apache.hadoop.hbase.HBaseInterfaceAudience;
077import org.apache.hadoop.hbase.HConstants;
078import org.apache.hadoop.hbase.HRegionLocation;
079import org.apache.hadoop.hbase.KeyValue;
080import org.apache.hadoop.hbase.MasterNotRunningException;
081import org.apache.hadoop.hbase.MetaTableAccessor;
082import org.apache.hadoop.hbase.RegionLocations;
083import org.apache.hadoop.hbase.ServerName;
084import org.apache.hadoop.hbase.TableName;
085import org.apache.hadoop.hbase.TableNotFoundException;
086import org.apache.hadoop.hbase.ZooKeeperConnectionException;
087import org.apache.hadoop.hbase.client.Admin;
088import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
089import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
090import org.apache.hadoop.hbase.client.Connection;
091import org.apache.hadoop.hbase.client.ConnectionFactory;
092import org.apache.hadoop.hbase.client.Delete;
093import org.apache.hadoop.hbase.client.Get;
094import org.apache.hadoop.hbase.client.Put;
095import org.apache.hadoop.hbase.client.RegionInfo;
096import org.apache.hadoop.hbase.client.RegionInfoBuilder;
097import org.apache.hadoop.hbase.client.RegionLocator;
098import org.apache.hadoop.hbase.client.RegionReplicaUtil;
099import org.apache.hadoop.hbase.client.Result;
100import org.apache.hadoop.hbase.client.ResultScanner;
101import org.apache.hadoop.hbase.client.RowMutations;
102import org.apache.hadoop.hbase.client.Scan;
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.master.RegionState;
112import org.apache.hadoop.hbase.regionserver.HRegion;
113import org.apache.hadoop.hbase.regionserver.HRegionFileSystem;
114import org.apache.hadoop.hbase.regionserver.StoreFileInfo;
115import org.apache.hadoop.hbase.replication.ReplicationException;
116import org.apache.hadoop.hbase.replication.ReplicationPeerDescription;
117import org.apache.hadoop.hbase.replication.ReplicationQueueStorage;
118import org.apache.hadoop.hbase.replication.ReplicationStorageFactory;
119import org.apache.hadoop.hbase.replication.ReplicationUtils;
120import org.apache.hadoop.hbase.security.AccessDeniedException;
121import org.apache.hadoop.hbase.security.UserProvider;
122import org.apache.hadoop.hbase.util.Bytes.ByteArrayComparator;
123import org.apache.hadoop.hbase.util.HbckErrorReporter.ERROR_CODE;
124import org.apache.hadoop.hbase.util.hbck.HFileCorruptionChecker;
125import org.apache.hadoop.hbase.util.hbck.ReplicationChecker;
126import org.apache.hadoop.hbase.util.hbck.TableIntegrityErrorHandler;
127import org.apache.hadoop.hbase.wal.WALSplitUtil;
128import org.apache.hadoop.hbase.zookeeper.ZKUtil;
129import org.apache.hadoop.hbase.zookeeper.ZKWatcher;
130import org.apache.hadoop.hbase.zookeeper.ZNodePaths;
131import org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException;
132import org.apache.hadoop.ipc.RemoteException;
133import org.apache.hadoop.security.UserGroupInformation;
134import org.apache.hadoop.util.ReflectionUtils;
135import org.apache.hadoop.util.Tool;
136import org.apache.hadoop.util.ToolRunner;
137import org.apache.yetus.audience.InterfaceAudience;
138import org.apache.yetus.audience.InterfaceStability;
139import org.apache.zookeeper.KeeperException;
140import org.slf4j.Logger;
141import org.slf4j.LoggerFactory;
142
143import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
144import org.apache.hbase.thirdparty.com.google.common.base.Joiner;
145import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
146import org.apache.hbase.thirdparty.com.google.common.collect.Lists;
147import org.apache.hbase.thirdparty.com.google.common.collect.Sets;
148
149/**
150 * HBaseFsck (hbck) is a tool for checking and repairing region consistency and
151 * table integrity problems in a corrupted HBase. This tool was written for hbase-1.x. It does not
152 * work with hbase-2.x; it can read state but is not allowed to change state; i.e. effect 'repair'.
153 * Even though it can 'read' state, given how so much has changed in how hbase1 and hbase2 operate,
154 * it will often misread. See hbck2 (HBASE-19121) for a hbck tool for hbase2. This class is
155 * deprecated.
156 *
157 * <p>
158 * Region consistency checks verify that hbase:meta, region deployment on region
159 * servers and the state of data in HDFS (.regioninfo files) all are in
160 * accordance.
161 * <p>
162 * Table integrity checks verify that all possible row keys resolve to exactly
163 * one region of a table.  This means there are no individual degenerate
164 * or backwards regions; no holes between regions; and that there are no
165 * overlapping regions.
166 * <p>
167 * The general repair strategy works in two phases:
168 * <ol>
169 * <li> Repair Table Integrity on HDFS. (merge or fabricate regions)
170 * <li> Repair Region Consistency with hbase:meta and assignments
171 * </ol>
172 * <p>
173 * For table integrity repairs, the tables' region directories are scanned
174 * for .regioninfo files.  Each table's integrity is then verified.  If there
175 * are any orphan regions (regions with no .regioninfo files) or holes, new
176 * regions are fabricated.  Backwards regions are sidelined as well as empty
177 * degenerate (endkey==startkey) regions.  If there are any overlapping regions,
178 * a new region is created and all data is merged into the new region.
179 * <p>
180 * Table integrity repairs deal solely with HDFS and could potentially be done
181 * offline -- the hbase region servers or master do not need to be running.
182 * This phase can eventually be used to completely reconstruct the hbase:meta table in
183 * an offline fashion.
184 * <p>
185 * Region consistency requires three conditions -- 1) valid .regioninfo file
186 * present in an HDFS region dir,  2) valid row with .regioninfo data in META,
187 * and 3) a region is deployed only at the regionserver that was assigned to
188 * with proper state in the master.
189 * <p>
190 * Region consistency repairs require hbase to be online so that hbck can
191 * contact the HBase master and region servers.  The hbck#connect() method must
192 * first be called successfully.  Much of the region consistency information
193 * is transient and less risky to repair.
194 * <p>
195 * If hbck is run from the command line, there are a handful of arguments that
196 * can be used to limit the kinds of repairs hbck will do.  See the code in
197 * {@link #printUsageAndExit()} for more details.
198 * @deprecated For removal in hbase-4.0.0. Use HBCK2 instead.
199 */
200@Deprecated
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
211  /**
212   * Here is where hbase-1.x used to default the lock for hbck1.
213   * It puts in place a lock when it goes to write/make changes.
214   */
215  @VisibleForTesting
216  public static final String HBCK_LOCK_FILE = "hbase-hbck.lock";
217  private static final int DEFAULT_MAX_LOCK_FILE_ATTEMPTS = 5;
218  private static final int DEFAULT_LOCK_FILE_ATTEMPT_SLEEP_INTERVAL = 200; // milliseconds
219  private static final int DEFAULT_LOCK_FILE_ATTEMPT_MAX_SLEEP_TIME = 5000; // milliseconds
220  // We have to set the timeout value > HdfsConstants.LEASE_SOFTLIMIT_PERIOD.
221  // In HADOOP-2.6 and later, the Namenode proxy now created with custom RetryPolicy for
222  // AlreadyBeingCreatedException which is implies timeout on this operations up to
223  // HdfsConstants.LEASE_SOFTLIMIT_PERIOD (60 seconds).
224  private static final int DEFAULT_WAIT_FOR_LOCK_TIMEOUT = 80; // seconds
225  private static final int DEFAULT_MAX_CREATE_ZNODE_ATTEMPTS = 5;
226  private static final int DEFAULT_CREATE_ZNODE_ATTEMPT_SLEEP_INTERVAL = 200; // milliseconds
227  private static final int DEFAULT_CREATE_ZNODE_ATTEMPT_MAX_SLEEP_TIME = 5000; // milliseconds
228
229  /**********************
230   * Internal resources
231   **********************/
232  private static final Logger LOG = LoggerFactory.getLogger(HBaseFsck.class.getName());
233  private ClusterMetrics status;
234  private Connection connection;
235  private Admin admin;
236  private Table meta;
237  // threads to do ||izable tasks: retrieve data from regionservers, handle overlapping regions
238  protected ExecutorService executor;
239  private long startMillis = EnvironmentEdgeManager.currentTime();
240  private HFileCorruptionChecker hfcc;
241  private int retcode = 0;
242  private Path HBCK_LOCK_PATH;
243  private FSDataOutputStream hbckOutFd;
244  // This lock is to prevent cleanup of balancer resources twice between
245  // ShutdownHook and the main code. We cleanup only if the connect() is
246  // successful
247  private final AtomicBoolean hbckLockCleanup = new AtomicBoolean(false);
248
249  // Unsupported options in HBase 2.0+
250  private static final Set<String> unsupportedOptionsInV2 = Sets.newHashSet("-fix",
251      "-fixAssignments", "-fixMeta", "-fixHdfsHoles", "-fixHdfsOrphans", "-fixTableOrphans",
252      "-fixHdfsOverlaps", "-sidelineBigOverlaps", "-fixSplitParents", "-removeParents",
253      "-fixEmptyMetaCells", "-repair", "-repairHoles", "-maxOverlapsToSideline", "-maxMerge");
254
255  /***********
256   * Options
257   ***********/
258  private static boolean details = false; // do we display the full report
259  private long timelag = DEFAULT_TIME_LAG; // tables whose modtime is older
260  private static boolean forceExclusive = false; // only this hbck can modify HBase
261  private boolean fixAssignments = false; // fix assignment errors?
262  private boolean fixMeta = false; // fix meta errors?
263  private boolean checkHdfs = true; // load and check fs consistency?
264  private boolean fixHdfsHoles = false; // fix fs holes?
265  private boolean fixHdfsOverlaps = false; // fix fs overlaps (risky)
266  private boolean fixHdfsOrphans = false; // fix fs holes (missing .regioninfo)
267  private boolean fixTableOrphans = false; // fix fs holes (missing .tableinfo)
268  private boolean fixVersionFile = false; // fix missing hbase.version file in hdfs
269  private boolean fixSplitParents = false; // fix lingering split parents
270  private boolean removeParents = false; // remove split parents
271  private boolean fixReferenceFiles = false; // fix lingering reference store file
272  private boolean fixHFileLinks = false; // fix lingering HFileLinks
273  private boolean fixEmptyMetaCells = false; // fix (remove) empty REGIONINFO_QUALIFIER rows
274  private boolean fixReplication = false; // fix undeleted replication queues for removed peer
275  private boolean cleanReplicationBarrier = false; // clean replication barriers of a table
276  private boolean fixAny = false; // Set to true if any of the fix is required.
277
278  // limit checking/fixes to listed tables, if empty attempt to check/fix all
279  // hbase:meta are always checked
280  private Set<TableName> tablesIncluded = new HashSet<>();
281  private TableName cleanReplicationBarrierTable;
282  private int maxMerge = DEFAULT_MAX_MERGE; // maximum number of overlapping regions to merge
283  // maximum number of overlapping regions to sideline
284  private int maxOverlapsToSideline = DEFAULT_OVERLAPS_TO_SIDELINE;
285  private boolean sidelineBigOverlaps = false; // sideline overlaps with >maxMerge regions
286  private Path sidelineDir = null;
287
288  private boolean rerun = false; // if we tried to fix something, rerun hbck
289  private static boolean summary = false; // if we want to print less output
290  private boolean checkMetaOnly = false;
291  private boolean checkRegionBoundaries = false;
292  private boolean ignorePreCheckPermission = false; // if pre-check permission
293
294  /*********
295   * State
296   *********/
297  final private HbckErrorReporter errors;
298  int fixes = 0;
299
300  /**
301   * This map contains the state of all hbck items.  It maps from encoded region
302   * name to HbckRegionInfo structure.  The information contained in HbckRegionInfo is used
303   * to detect and correct consistency (hdfs/meta/deployment) problems.
304   */
305  private TreeMap<String, HbckRegionInfo> regionInfoMap = new TreeMap<>();
306  // Empty regioninfo qualifiers in hbase:meta
307  private Set<Result> emptyRegionInfoQualifiers = new HashSet<>();
308
309  /**
310   * This map from Tablename -> TableInfo contains the structures necessary to
311   * detect table consistency problems (holes, dupes, overlaps).  It is sorted
312   * to prevent dupes.
313   *
314   * If tablesIncluded is empty, this map contains all tables.
315   * Otherwise, it contains only meta tables and tables in tablesIncluded,
316   * unless checkMetaOnly is specified, in which case, it contains only
317   * the meta table
318   */
319  private SortedMap<TableName, HbckTableInfo> tablesInfo = new ConcurrentSkipListMap<>();
320
321  /**
322   * When initially looking at HDFS, we attempt to find any orphaned data.
323   */
324  private List<HbckRegionInfo> orphanHdfsDirs = Collections.synchronizedList(new ArrayList<>());
325
326  private Map<TableName, Set<String>> orphanTableDirs = new HashMap<>();
327  private Map<TableName, TableState> tableStates = new HashMap<>();
328  private final RetryCounterFactory lockFileRetryCounterFactory;
329  private final RetryCounterFactory createZNodeRetryCounterFactory;
330
331  private Map<TableName, Set<String>> skippedRegions = new HashMap<>();
332
333  private ZKWatcher zkw = null;
334  private String hbckEphemeralNodePath = null;
335  private boolean hbckZodeCreated = false;
336
337  /**
338   * Constructor
339   *
340   * @param conf Configuration object
341   * @throws MasterNotRunningException if the master is not running
342   * @throws ZooKeeperConnectionException if unable to connect to ZooKeeper
343   */
344  public HBaseFsck(Configuration conf) throws IOException, ClassNotFoundException {
345    this(conf, createThreadPool(conf));
346  }
347
348  private static ExecutorService createThreadPool(Configuration conf) {
349    int numThreads = conf.getInt("hbasefsck.numthreads", MAX_NUM_THREADS);
350    return new ScheduledThreadPoolExecutor(numThreads, Threads.newDaemonThreadFactory("hbasefsck"));
351  }
352
353  /**
354   * Constructor
355   *
356   * @param conf
357   *          Configuration object
358   * @throws MasterNotRunningException
359   *           if the master is not running
360   * @throws ZooKeeperConnectionException
361   *           if unable to connect to ZooKeeper
362   */
363  public HBaseFsck(Configuration conf, ExecutorService exec) throws MasterNotRunningException,
364      ZooKeeperConnectionException, IOException, ClassNotFoundException {
365    super(conf);
366    errors = getErrorReporter(getConf());
367    this.executor = exec;
368    lockFileRetryCounterFactory = createLockRetryCounterFactory(getConf());
369    createZNodeRetryCounterFactory = createZnodeRetryCounterFactory(getConf());
370    zkw = createZooKeeperWatcher();
371  }
372
373  /**
374   * @return A retry counter factory configured for retrying lock file creation.
375   */
376  public static RetryCounterFactory createLockRetryCounterFactory(Configuration conf) {
377    return new RetryCounterFactory(
378        conf.getInt("hbase.hbck.lockfile.attempts", DEFAULT_MAX_LOCK_FILE_ATTEMPTS),
379        conf.getInt("hbase.hbck.lockfile.attempt.sleep.interval",
380            DEFAULT_LOCK_FILE_ATTEMPT_SLEEP_INTERVAL),
381        conf.getInt("hbase.hbck.lockfile.attempt.maxsleeptime",
382            DEFAULT_LOCK_FILE_ATTEMPT_MAX_SLEEP_TIME));
383  }
384
385  /**
386   * @return A retry counter factory configured for retrying znode creation.
387   */
388  private static RetryCounterFactory createZnodeRetryCounterFactory(Configuration conf) {
389    return new RetryCounterFactory(
390        conf.getInt("hbase.hbck.createznode.attempts", DEFAULT_MAX_CREATE_ZNODE_ATTEMPTS),
391        conf.getInt("hbase.hbck.createznode.attempt.sleep.interval",
392            DEFAULT_CREATE_ZNODE_ATTEMPT_SLEEP_INTERVAL),
393        conf.getInt("hbase.hbck.createznode.attempt.maxsleeptime",
394            DEFAULT_CREATE_ZNODE_ATTEMPT_MAX_SLEEP_TIME));
395  }
396
397  /**
398   * @return Return the tmp dir this tool writes too.
399   */
400  @VisibleForTesting
401  public static Path getTmpDir(Configuration conf) throws IOException {
402    return new Path(FSUtils.getRootDir(conf), HConstants.HBASE_TEMP_DIRECTORY);
403  }
404
405  private static class FileLockCallable implements Callable<FSDataOutputStream> {
406    RetryCounter retryCounter;
407    private final Configuration conf;
408    private Path hbckLockPath = null;
409
410    public FileLockCallable(Configuration conf, RetryCounter retryCounter) {
411      this.retryCounter = retryCounter;
412      this.conf = conf;
413    }
414
415    /**
416     * @return Will be <code>null</code> unless you call {@link #call()}
417     */
418    Path getHbckLockPath() {
419      return this.hbckLockPath;
420    }
421
422    @Override
423    public FSDataOutputStream call() throws IOException {
424      try {
425        FileSystem fs = FSUtils.getCurrentFileSystem(this.conf);
426        FsPermission defaultPerms = FSUtils.getFilePermissions(fs, this.conf,
427            HConstants.DATA_FILE_UMASK_KEY);
428        Path tmpDir = getTmpDir(conf);
429        this.hbckLockPath = new Path(tmpDir, HBCK_LOCK_FILE);
430        fs.mkdirs(tmpDir);
431        final FSDataOutputStream out = createFileWithRetries(fs, this.hbckLockPath, defaultPerms);
432        out.writeBytes(InetAddress.getLocalHost().toString());
433        // Add a note into the file we write on why hbase2 is writing out an hbck1 lock file.
434        out.writeBytes(" Written by an hbase-2.x Master to block an " +
435            "attempt by an hbase-1.x HBCK tool making modification to state. " +
436            "See 'HBCK must match HBase server version' in the hbase refguide.");
437        out.flush();
438        return out;
439      } catch(RemoteException e) {
440        if(AlreadyBeingCreatedException.class.getName().equals(e.getClassName())){
441          return null;
442        } else {
443          throw e;
444        }
445      }
446    }
447
448    private FSDataOutputStream createFileWithRetries(final FileSystem fs,
449        final Path hbckLockFilePath, final FsPermission defaultPerms)
450        throws IOException {
451      IOException exception = null;
452      do {
453        try {
454          return FSUtils.create(fs, hbckLockFilePath, defaultPerms, false);
455        } catch (IOException ioe) {
456          LOG.info("Failed to create lock file " + hbckLockFilePath.getName()
457              + ", try=" + (retryCounter.getAttemptTimes() + 1) + " of "
458              + retryCounter.getMaxAttempts());
459          LOG.debug("Failed to create lock file " + hbckLockFilePath.getName(),
460              ioe);
461          try {
462            exception = ioe;
463            retryCounter.sleepUntilNextRetry();
464          } catch (InterruptedException ie) {
465            throw (InterruptedIOException) new InterruptedIOException(
466                "Can't create lock file " + hbckLockFilePath.getName())
467            .initCause(ie);
468          }
469        }
470      } while (retryCounter.shouldRetry());
471
472      throw exception;
473    }
474  }
475
476  /**
477   * This method maintains a lock using a file. If the creation fails we return null
478   *
479   * @return FSDataOutputStream object corresponding to the newly opened lock file
480   * @throws IOException if IO failure occurs
481   */
482  public static Pair<Path, FSDataOutputStream> checkAndMarkRunningHbck(Configuration conf,
483      RetryCounter retryCounter) throws IOException {
484    FileLockCallable callable = new FileLockCallable(conf, retryCounter);
485    ExecutorService executor = Executors.newFixedThreadPool(1);
486    FutureTask<FSDataOutputStream> futureTask = new FutureTask<>(callable);
487    executor.execute(futureTask);
488    final int timeoutInSeconds = conf.getInt(
489      "hbase.hbck.lockfile.maxwaittime", DEFAULT_WAIT_FOR_LOCK_TIMEOUT);
490    FSDataOutputStream stream = null;
491    try {
492      stream = futureTask.get(timeoutInSeconds, TimeUnit.SECONDS);
493    } catch (ExecutionException ee) {
494      LOG.warn("Encountered exception when opening lock file", ee);
495    } catch (InterruptedException ie) {
496      LOG.warn("Interrupted when opening lock file", ie);
497      Thread.currentThread().interrupt();
498    } catch (TimeoutException exception) {
499      // took too long to obtain lock
500      LOG.warn("Took more than " + timeoutInSeconds + " seconds in obtaining lock");
501      futureTask.cancel(true);
502    } finally {
503      executor.shutdownNow();
504    }
505    return new Pair<Path, FSDataOutputStream>(callable.getHbckLockPath(), stream);
506  }
507
508  private void unlockHbck() {
509    if (isExclusive() && hbckLockCleanup.compareAndSet(true, false)) {
510      RetryCounter retryCounter = lockFileRetryCounterFactory.create();
511      do {
512        try {
513          IOUtils.closeQuietly(hbckOutFd);
514          FSUtils.delete(FSUtils.getCurrentFileSystem(getConf()), HBCK_LOCK_PATH, true);
515          LOG.info("Finishing hbck");
516          return;
517        } catch (IOException ioe) {
518          LOG.info("Failed to delete " + HBCK_LOCK_PATH + ", try="
519              + (retryCounter.getAttemptTimes() + 1) + " of "
520              + retryCounter.getMaxAttempts());
521          LOG.debug("Failed to delete " + HBCK_LOCK_PATH, ioe);
522          try {
523            retryCounter.sleepUntilNextRetry();
524          } catch (InterruptedException ie) {
525            Thread.currentThread().interrupt();
526            LOG.warn("Interrupted while deleting lock file" +
527                HBCK_LOCK_PATH);
528            return;
529          }
530        }
531      } while (retryCounter.shouldRetry());
532    }
533  }
534
535  /**
536   * To repair region consistency, one must call connect() in order to repair
537   * online state.
538   */
539  public void connect() throws IOException {
540
541    if (isExclusive()) {
542      // Grab the lock
543      Pair<Path, FSDataOutputStream> pair =
544          checkAndMarkRunningHbck(getConf(), this.lockFileRetryCounterFactory.create());
545      HBCK_LOCK_PATH = pair.getFirst();
546      this.hbckOutFd = pair.getSecond();
547      if (hbckOutFd == null) {
548        setRetCode(-1);
549        LOG.error("Another instance of hbck is fixing HBase, exiting this instance. " +
550            "[If you are sure no other instance is running, delete the lock file " +
551            HBCK_LOCK_PATH + " and rerun the tool]");
552        throw new IOException("Duplicate hbck - Abort");
553      }
554
555      // Make sure to cleanup the lock
556      hbckLockCleanup.set(true);
557    }
558
559
560    // Add a shutdown hook to this thread, in case user tries to
561    // kill the hbck with a ctrl-c, we want to cleanup the lock so that
562    // it is available for further calls
563    Runtime.getRuntime().addShutdownHook(new Thread() {
564      @Override
565      public void run() {
566        IOUtils.closeQuietly(HBaseFsck.this);
567        cleanupHbckZnode();
568        unlockHbck();
569      }
570    });
571
572    LOG.info("Launching hbck");
573
574    connection = ConnectionFactory.createConnection(getConf());
575    admin = connection.getAdmin();
576    meta = connection.getTable(TableName.META_TABLE_NAME);
577    status = admin.getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS,
578      Option.DEAD_SERVERS, Option.MASTER, Option.BACKUP_MASTERS,
579      Option.REGIONS_IN_TRANSITION, Option.HBASE_VERSION));
580  }
581
582  /**
583   * Get deployed regions according to the region servers.
584   */
585  private void loadDeployedRegions() throws IOException, InterruptedException {
586    // From the master, get a list of all known live region servers
587    Collection<ServerName> regionServers = status.getLiveServerMetrics().keySet();
588    errors.print("Number of live region servers: " + regionServers.size());
589    if (details) {
590      for (ServerName rsinfo: regionServers) {
591        errors.print("  " + rsinfo.getServerName());
592      }
593    }
594
595    // From the master, get a list of all dead region servers
596    Collection<ServerName> deadRegionServers = status.getDeadServerNames();
597    errors.print("Number of dead region servers: " + deadRegionServers.size());
598    if (details) {
599      for (ServerName name: deadRegionServers) {
600        errors.print("  " + name);
601      }
602    }
603
604    // Print the current master name and state
605    errors.print("Master: " + status.getMasterName());
606
607    // Print the list of all backup masters
608    Collection<ServerName> backupMasters = status.getBackupMasterNames();
609    errors.print("Number of backup masters: " + backupMasters.size());
610    if (details) {
611      for (ServerName name: backupMasters) {
612        errors.print("  " + name);
613      }
614    }
615
616    errors.print("Average load: " + status.getAverageLoad());
617    errors.print("Number of requests: " + status.getRequestCount());
618    errors.print("Number of regions: " + status.getRegionCount());
619
620    List<RegionState> rits = status.getRegionStatesInTransition();
621    errors.print("Number of regions in transition: " + rits.size());
622    if (details) {
623      for (RegionState state: rits) {
624        errors.print("  " + state.toDescriptiveString());
625      }
626    }
627
628    // Determine what's deployed
629    processRegionServers(regionServers);
630  }
631
632  /**
633   * Clear the current state of hbck.
634   */
635  private void clearState() {
636    // Make sure regionInfo is empty before starting
637    fixes = 0;
638    regionInfoMap.clear();
639    emptyRegionInfoQualifiers.clear();
640    tableStates.clear();
641    errors.clear();
642    tablesInfo.clear();
643    orphanHdfsDirs.clear();
644    skippedRegions.clear();
645  }
646
647  /**
648   * This repair method analyzes hbase data in hdfs and repairs it to satisfy
649   * the table integrity rules.  HBase doesn't need to be online for this
650   * operation to work.
651   */
652  public void offlineHdfsIntegrityRepair() throws IOException, InterruptedException {
653    // Initial pass to fix orphans.
654    if (shouldCheckHdfs() && (shouldFixHdfsOrphans() || shouldFixHdfsHoles()
655        || shouldFixHdfsOverlaps() || shouldFixTableOrphans())) {
656      LOG.info("Loading regioninfos HDFS");
657      // if nothing is happening this should always complete in two iterations.
658      int maxIterations = getConf().getInt("hbase.hbck.integrityrepair.iterations.max", 3);
659      int curIter = 0;
660      do {
661        clearState(); // clears hbck state and reset fixes to 0 and.
662        // repair what's on HDFS
663        restoreHdfsIntegrity();
664        curIter++;// limit the number of iterations.
665      } while (fixes > 0 && curIter <= maxIterations);
666
667      // Repairs should be done in the first iteration and verification in the second.
668      // If there are more than 2 passes, something funny has happened.
669      if (curIter > 2) {
670        if (curIter == maxIterations) {
671          LOG.warn("Exiting integrity repairs after max " + curIter + " iterations. "
672              + "Tables integrity may not be fully repaired!");
673        } else {
674          LOG.info("Successfully exiting integrity repairs after " + curIter + " iterations");
675        }
676      }
677    }
678  }
679
680  /**
681   * This repair method requires the cluster to be online since it contacts
682   * region servers and the masters.  It makes each region's state in HDFS, in
683   * hbase:meta, and deployments consistent.
684   *
685   * @return If &gt; 0 , number of errors detected, if &lt; 0 there was an unrecoverable
686   *     error.  If 0, we have a clean hbase.
687   */
688  public int onlineConsistencyRepair() throws IOException, KeeperException,
689    InterruptedException {
690
691    // get regions according to what is online on each RegionServer
692    loadDeployedRegions();
693    // check whether hbase:meta is deployed and online
694    recordMetaRegion();
695    // Check if hbase:meta is found only once and in the right place
696    if (!checkMetaRegion()) {
697      String errorMsg = "hbase:meta table is not consistent. ";
698      if (shouldFixAssignments()) {
699        errorMsg += "HBCK will try fixing it. Rerun once hbase:meta is back to consistent state.";
700      } else {
701        errorMsg += "Run HBCK with proper fix options to fix hbase:meta inconsistency.";
702      }
703      errors.reportError(errorMsg + " Exiting...");
704      return -2;
705    }
706    // Not going with further consistency check for tables when hbase:meta itself is not consistent.
707    LOG.info("Loading regionsinfo from the hbase:meta table");
708    boolean success = loadMetaEntries();
709    if (!success) return -1;
710
711    // Empty cells in hbase:meta?
712    reportEmptyMetaCells();
713
714    // Check if we have to cleanup empty REGIONINFO_QUALIFIER rows from hbase:meta
715    if (shouldFixEmptyMetaCells()) {
716      fixEmptyMetaCells();
717    }
718
719    // get a list of all tables that have not changed recently.
720    if (!checkMetaOnly) {
721      reportTablesInFlux();
722    }
723
724    // Get disabled tables states
725    loadTableStates();
726
727    // load regiondirs and regioninfos from HDFS
728    if (shouldCheckHdfs()) {
729      LOG.info("Loading region directories from HDFS");
730      loadHdfsRegionDirs();
731      LOG.info("Loading region information from HDFS");
732      loadHdfsRegionInfos();
733    }
734
735    // fix the orphan tables
736    fixOrphanTables();
737
738    LOG.info("Checking and fixing region consistency");
739    // Check and fix consistency
740    checkAndFixConsistency();
741
742    // Check integrity (does not fix)
743    checkIntegrity();
744    return errors.getErrorList().size();
745  }
746
747  /**
748   * This method maintains an ephemeral znode. If the creation fails we return false or throw
749   * exception
750   *
751   * @return true if creating znode succeeds; false otherwise
752   * @throws IOException if IO failure occurs
753   */
754  private boolean setMasterInMaintenanceMode() throws IOException {
755    RetryCounter retryCounter = createZNodeRetryCounterFactory.create();
756    hbckEphemeralNodePath = ZNodePaths.joinZNode(
757      zkw.getZNodePaths().masterMaintZNode,
758      "hbck-" + Long.toString(EnvironmentEdgeManager.currentTime()));
759    do {
760      try {
761        hbckZodeCreated = ZKUtil.createEphemeralNodeAndWatch(zkw, hbckEphemeralNodePath, null);
762        if (hbckZodeCreated) {
763          break;
764        }
765      } catch (KeeperException e) {
766        if (retryCounter.getAttemptTimes() >= retryCounter.getMaxAttempts()) {
767           throw new IOException("Can't create znode " + hbckEphemeralNodePath, e);
768        }
769        // fall through and retry
770      }
771
772      LOG.warn("Fail to create znode " + hbckEphemeralNodePath + ", try=" +
773          (retryCounter.getAttemptTimes() + 1) + " of " + retryCounter.getMaxAttempts());
774
775      try {
776        retryCounter.sleepUntilNextRetry();
777      } catch (InterruptedException ie) {
778        throw (InterruptedIOException) new InterruptedIOException(
779              "Can't create znode " + hbckEphemeralNodePath).initCause(ie);
780      }
781    } while (retryCounter.shouldRetry());
782    return hbckZodeCreated;
783  }
784
785  private void cleanupHbckZnode() {
786    try {
787      if (zkw != null && hbckZodeCreated) {
788        ZKUtil.deleteNode(zkw, hbckEphemeralNodePath);
789        hbckZodeCreated = false;
790      }
791    } catch (KeeperException e) {
792      // Ignore
793      if (!e.code().equals(KeeperException.Code.NONODE)) {
794        LOG.warn("Delete HBCK znode " + hbckEphemeralNodePath + " failed ", e);
795      }
796    }
797  }
798
799  /**
800   * Contacts the master and prints out cluster-wide information
801   * @return 0 on success, non-zero on failure
802   */
803  public int onlineHbck()
804      throws IOException, KeeperException, InterruptedException, ReplicationException {
805    // print hbase server version
806    errors.print("Version: " + status.getHBaseVersion());
807
808    // Clean start
809    clearState();
810    // Do offline check and repair first
811    offlineHdfsIntegrityRepair();
812    offlineReferenceFileRepair();
813    offlineHLinkFileRepair();
814    // If Master runs maintenance tasks (such as balancer, catalog janitor, etc) during online
815    // hbck, it is likely that hbck would be misled and report transient errors.  Therefore, it
816    // is better to set Master into maintenance mode during online hbck.
817    //
818    if (!setMasterInMaintenanceMode()) {
819      LOG.warn("HBCK is running while master is not in maintenance mode, you might see transient "
820        + "error.  Please run HBCK multiple times to reduce the chance of transient error.");
821    }
822
823    onlineConsistencyRepair();
824
825    if (checkRegionBoundaries) {
826      checkRegionBoundaries();
827    }
828
829    checkAndFixReplication();
830
831    cleanReplicationBarrier();
832
833    // Remove the hbck znode
834    cleanupHbckZnode();
835
836    // Remove the hbck lock
837    unlockHbck();
838
839    // Print table summary
840    printTableSummary(tablesInfo);
841    return errors.summarize();
842  }
843
844  public static byte[] keyOnly(byte[] b) {
845    if (b == null)
846      return b;
847    int rowlength = Bytes.toShort(b, 0);
848    byte[] result = new byte[rowlength];
849    System.arraycopy(b, Bytes.SIZEOF_SHORT, result, 0, rowlength);
850    return result;
851  }
852
853  @Override
854  public void close() throws IOException {
855    try {
856      cleanupHbckZnode();
857      unlockHbck();
858    } catch (Exception io) {
859      LOG.warn(io.toString(), io);
860    } finally {
861      if (zkw != null) {
862        zkw.close();
863        zkw = null;
864      }
865      IOUtils.closeQuietly(admin);
866      IOUtils.closeQuietly(meta);
867      IOUtils.closeQuietly(connection);
868    }
869  }
870
871  private static class RegionBoundariesInformation {
872    public byte [] regionName;
873    public byte [] metaFirstKey;
874    public byte [] metaLastKey;
875    public byte [] storesFirstKey;
876    public byte [] storesLastKey;
877    @Override
878    public String toString () {
879      return "regionName=" + Bytes.toStringBinary(regionName) +
880             "\nmetaFirstKey=" + Bytes.toStringBinary(metaFirstKey) +
881             "\nmetaLastKey=" + Bytes.toStringBinary(metaLastKey) +
882             "\nstoresFirstKey=" + Bytes.toStringBinary(storesFirstKey) +
883             "\nstoresLastKey=" + Bytes.toStringBinary(storesLastKey);
884    }
885  }
886
887  public void checkRegionBoundaries() {
888    try {
889      ByteArrayComparator comparator = new ByteArrayComparator();
890      List<RegionInfo> regions = MetaTableAccessor.getAllRegions(connection, true);
891      final RegionBoundariesInformation currentRegionBoundariesInformation =
892          new RegionBoundariesInformation();
893      Path hbaseRoot = FSUtils.getRootDir(getConf());
894      for (RegionInfo regionInfo : regions) {
895        Path tableDir = FSUtils.getTableDir(hbaseRoot, regionInfo.getTable());
896        currentRegionBoundariesInformation.regionName = regionInfo.getRegionName();
897        // For each region, get the start and stop key from the META and compare them to the
898        // same information from the Stores.
899        Path path = new Path(tableDir, regionInfo.getEncodedName());
900        FileSystem fs = path.getFileSystem(getConf());
901        FileStatus[] files = fs.listStatus(path);
902        // For all the column families in this region...
903        byte[] storeFirstKey = null;
904        byte[] storeLastKey = null;
905        for (FileStatus file : files) {
906          String fileName = file.getPath().toString();
907          fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
908          if (!fileName.startsWith(".") && !fileName.endsWith("recovered.edits")) {
909            FileStatus[] storeFiles = fs.listStatus(file.getPath());
910            // For all the stores in this column family.
911            for (FileStatus storeFile : storeFiles) {
912              HFile.Reader reader = HFile.createReader(fs, storeFile.getPath(),
913                CacheConfig.DISABLED, true, getConf());
914              if ((reader.getFirstKey() != null)
915                  && ((storeFirstKey == null) || (comparator.compare(storeFirstKey,
916                      ((KeyValue.KeyOnlyKeyValue) reader.getFirstKey().get()).getKey()) > 0))) {
917                storeFirstKey = ((KeyValue.KeyOnlyKeyValue)reader.getFirstKey().get()).getKey();
918              }
919              if ((reader.getLastKey() != null)
920                  && ((storeLastKey == null) || (comparator.compare(storeLastKey,
921                      ((KeyValue.KeyOnlyKeyValue)reader.getLastKey().get()).getKey())) < 0)) {
922                storeLastKey = ((KeyValue.KeyOnlyKeyValue)reader.getLastKey().get()).getKey();
923              }
924              reader.close();
925            }
926          }
927        }
928        currentRegionBoundariesInformation.metaFirstKey = regionInfo.getStartKey();
929        currentRegionBoundariesInformation.metaLastKey = regionInfo.getEndKey();
930        currentRegionBoundariesInformation.storesFirstKey = keyOnly(storeFirstKey);
931        currentRegionBoundariesInformation.storesLastKey = keyOnly(storeLastKey);
932        if (currentRegionBoundariesInformation.metaFirstKey.length == 0)
933          currentRegionBoundariesInformation.metaFirstKey = null;
934        if (currentRegionBoundariesInformation.metaLastKey.length == 0)
935          currentRegionBoundariesInformation.metaLastKey = null;
936
937        // For a region to be correct, we need the META start key to be smaller or equal to the
938        // smallest start key from all the stores, and the start key from the next META entry to
939        // be bigger than the last key from all the current stores. First region start key is null;
940        // Last region end key is null; some regions can be empty and not have any store.
941
942        boolean valid = true;
943        // Checking start key.
944        if ((currentRegionBoundariesInformation.storesFirstKey != null)
945            && (currentRegionBoundariesInformation.metaFirstKey != null)) {
946          valid = valid
947              && comparator.compare(currentRegionBoundariesInformation.storesFirstKey,
948                currentRegionBoundariesInformation.metaFirstKey) >= 0;
949        }
950        // Checking stop key.
951        if ((currentRegionBoundariesInformation.storesLastKey != null)
952            && (currentRegionBoundariesInformation.metaLastKey != null)) {
953          valid = valid
954              && comparator.compare(currentRegionBoundariesInformation.storesLastKey,
955                currentRegionBoundariesInformation.metaLastKey) < 0;
956        }
957        if (!valid) {
958          errors.reportError(ERROR_CODE.BOUNDARIES_ERROR, "Found issues with regions boundaries",
959            tablesInfo.get(regionInfo.getTable()));
960          LOG.warn("Region's boundaries not aligned between stores and META for:");
961          LOG.warn(Objects.toString(currentRegionBoundariesInformation));
962        }
963      }
964    } catch (IOException e) {
965      LOG.error(e.toString(), e);
966    }
967  }
968
969  /**
970   * Iterates through the list of all orphan/invalid regiondirs.
971   */
972  private void adoptHdfsOrphans(Collection<HbckRegionInfo> orphanHdfsDirs) throws IOException {
973    for (HbckRegionInfo hi : orphanHdfsDirs) {
974      LOG.info("Attempting to handle orphan hdfs dir: " + hi.getHdfsRegionDir());
975      adoptHdfsOrphan(hi);
976    }
977  }
978
979  /**
980   * Orphaned regions are regions without a .regioninfo file in them.  We "adopt"
981   * these orphans by creating a new region, and moving the column families,
982   * recovered edits, WALs, into the new region dir.  We determine the region
983   * startkey and endkeys by looking at all of the hfiles inside the column
984   * families to identify the min and max keys. The resulting region will
985   * likely violate table integrity but will be dealt with by merging
986   * overlapping regions.
987   */
988  @SuppressWarnings("deprecation")
989  private void adoptHdfsOrphan(HbckRegionInfo hi) throws IOException {
990    Path p = hi.getHdfsRegionDir();
991    FileSystem fs = p.getFileSystem(getConf());
992    FileStatus[] dirs = fs.listStatus(p);
993    if (dirs == null) {
994      LOG.warn("Attempt to adopt orphan hdfs region skipped because no files present in " +
995          p + ". This dir could probably be deleted.");
996      return ;
997    }
998
999    TableName tableName = hi.getTableName();
1000    HbckTableInfo tableInfo = tablesInfo.get(tableName);
1001    Preconditions.checkNotNull(tableInfo, "Table '" + tableName + "' not present!");
1002    TableDescriptor template = tableInfo.getTableDescriptor();
1003
1004    // find min and max key values
1005    Pair<byte[],byte[]> orphanRegionRange = null;
1006    for (FileStatus cf : dirs) {
1007      String cfName= cf.getPath().getName();
1008      // TODO Figure out what the special dirs are
1009      if (cfName.startsWith(".") || cfName.equals(HConstants.SPLIT_LOGDIR_NAME)) continue;
1010
1011      FileStatus[] hfiles = fs.listStatus(cf.getPath());
1012      for (FileStatus hfile : hfiles) {
1013        byte[] start, end;
1014        HFile.Reader hf = null;
1015        try {
1016          hf = HFile.createReader(fs, hfile.getPath(), CacheConfig.DISABLED, true, getConf());
1017          hf.loadFileInfo();
1018          Optional<Cell> startKv = hf.getFirstKey();
1019          start = CellUtil.cloneRow(startKv.get());
1020          Optional<Cell> endKv = hf.getLastKey();
1021          end = CellUtil.cloneRow(endKv.get());
1022        } catch (IOException ioe) {
1023          LOG.warn("Problem reading orphan file " + hfile + ", skipping");
1024          continue;
1025        } catch (NullPointerException ioe) {
1026          LOG.warn("Orphan file " + hfile + " is possibly corrupted HFile, skipping");
1027          continue;
1028        } finally {
1029          if (hf != null) {
1030            hf.close();
1031          }
1032        }
1033
1034        // expand the range to include the range of all hfiles
1035        if (orphanRegionRange == null) {
1036          // first range
1037          orphanRegionRange = new Pair<>(start, end);
1038        } else {
1039          // TODO add test
1040
1041          // expand range only if the hfile is wider.
1042          if (Bytes.compareTo(orphanRegionRange.getFirst(), start) > 0) {
1043            orphanRegionRange.setFirst(start);
1044          }
1045          if (Bytes.compareTo(orphanRegionRange.getSecond(), end) < 0 ) {
1046            orphanRegionRange.setSecond(end);
1047          }
1048        }
1049      }
1050    }
1051    if (orphanRegionRange == null) {
1052      LOG.warn("No data in dir " + p + ", sidelining data");
1053      fixes++;
1054      sidelineRegionDir(fs, hi);
1055      return;
1056    }
1057    LOG.info("Min max keys are : [" + Bytes.toString(orphanRegionRange.getFirst()) + ", " +
1058        Bytes.toString(orphanRegionRange.getSecond()) + ")");
1059
1060    // create new region on hdfs. move data into place.
1061    RegionInfo regionInfo = RegionInfoBuilder.newBuilder(template.getTableName())
1062        .setStartKey(orphanRegionRange.getFirst())
1063        .setEndKey(Bytes.add(orphanRegionRange.getSecond(), new byte[1]))
1064        .build();
1065    LOG.info("Creating new region : " + regionInfo);
1066    HRegion region = HBaseFsckRepair.createHDFSRegionDir(getConf(), regionInfo, template);
1067    Path target = region.getRegionFileSystem().getRegionDir();
1068
1069    // rename all the data to new region
1070    mergeRegionDirs(target, hi);
1071    fixes++;
1072  }
1073
1074  /**
1075   * This method determines if there are table integrity errors in HDFS.  If
1076   * there are errors and the appropriate "fix" options are enabled, the method
1077   * will first correct orphan regions making them into legit regiondirs, and
1078   * then reload to merge potentially overlapping regions.
1079   *
1080   * @return number of table integrity errors found
1081   */
1082  private int restoreHdfsIntegrity() throws IOException, InterruptedException {
1083    // Determine what's on HDFS
1084    LOG.info("Loading HBase regioninfo from HDFS...");
1085    loadHdfsRegionDirs(); // populating regioninfo table.
1086
1087    int errs = errors.getErrorList().size();
1088    // First time just get suggestions.
1089    tablesInfo = loadHdfsRegionInfos(); // update tableInfos based on region info in fs.
1090    checkHdfsIntegrity(false, false);
1091
1092    if (errors.getErrorList().size() == errs) {
1093      LOG.info("No integrity errors.  We are done with this phase. Glorious.");
1094      return 0;
1095    }
1096
1097    if (shouldFixHdfsOrphans() && orphanHdfsDirs.size() > 0) {
1098      adoptHdfsOrphans(orphanHdfsDirs);
1099      // TODO optimize by incrementally adding instead of reloading.
1100    }
1101
1102    // Make sure there are no holes now.
1103    if (shouldFixHdfsHoles()) {
1104      clearState(); // this also resets # fixes.
1105      loadHdfsRegionDirs();
1106      tablesInfo = loadHdfsRegionInfos(); // update tableInfos based on region info in fs.
1107      tablesInfo = checkHdfsIntegrity(shouldFixHdfsHoles(), false);
1108    }
1109
1110    // Now we fix overlaps
1111    if (shouldFixHdfsOverlaps()) {
1112      // second pass we fix overlaps.
1113      clearState(); // this also resets # fixes.
1114      loadHdfsRegionDirs();
1115      tablesInfo = loadHdfsRegionInfos(); // update tableInfos based on region info in fs.
1116      tablesInfo = checkHdfsIntegrity(false, shouldFixHdfsOverlaps());
1117    }
1118
1119    return errors.getErrorList().size();
1120  }
1121
1122  /**
1123   * Scan all the store file names to find any lingering reference files,
1124   * which refer to some none-exiting files. If "fix" option is enabled,
1125   * any lingering reference file will be sidelined if found.
1126   * <p>
1127   * Lingering reference file prevents a region from opening. It has to
1128   * be fixed before a cluster can start properly.
1129   */
1130  private void offlineReferenceFileRepair() throws IOException, InterruptedException {
1131    clearState();
1132    Configuration conf = getConf();
1133    Path hbaseRoot = FSUtils.getRootDir(conf);
1134    FileSystem fs = hbaseRoot.getFileSystem(conf);
1135    LOG.info("Computing mapping of all store files");
1136    Map<String, Path> allFiles = FSUtils.getTableStoreFilePathMap(fs, hbaseRoot,
1137      new FSUtils.ReferenceFileFilter(fs), executor, errors);
1138    errors.print("");
1139    LOG.info("Validating mapping using HDFS state");
1140    for (Path path: allFiles.values()) {
1141      Path referredToFile = StoreFileInfo.getReferredToFile(path);
1142      if (fs.exists(referredToFile)) continue;  // good, expected
1143
1144      // Found a lingering reference file
1145      errors.reportError(ERROR_CODE.LINGERING_REFERENCE_HFILE,
1146        "Found lingering reference file " + path);
1147      if (!shouldFixReferenceFiles()) continue;
1148
1149      // Now, trying to fix it since requested
1150      boolean success = false;
1151      String pathStr = path.toString();
1152
1153      // A reference file path should be like
1154      // ${hbase.rootdir}/data/namespace/table_name/region_id/family_name/referred_file.region_name
1155      // Up 5 directories to get the root folder.
1156      // So the file will be sidelined to a similar folder structure.
1157      int index = pathStr.lastIndexOf(Path.SEPARATOR_CHAR);
1158      for (int i = 0; index > 0 && i < 5; i++) {
1159        index = pathStr.lastIndexOf(Path.SEPARATOR_CHAR, index - 1);
1160      }
1161      if (index > 0) {
1162        Path rootDir = getSidelineDir();
1163        Path dst = new Path(rootDir, pathStr.substring(index + 1));
1164        fs.mkdirs(dst.getParent());
1165        LOG.info("Trying to sideline reference file "
1166          + path + " to " + dst);
1167        setShouldRerun();
1168
1169        success = fs.rename(path, dst);
1170        debugLsr(dst);
1171
1172      }
1173      if (!success) {
1174        LOG.error("Failed to sideline reference file " + path);
1175      }
1176    }
1177  }
1178
1179  /**
1180   * Scan all the store file names to find any lingering HFileLink files,
1181   * which refer to some none-exiting files. If "fix" option is enabled,
1182   * any lingering HFileLink file will be sidelined if found.
1183   */
1184  private void offlineHLinkFileRepair() throws IOException, InterruptedException {
1185    Configuration conf = getConf();
1186    Path hbaseRoot = FSUtils.getRootDir(conf);
1187    FileSystem fs = hbaseRoot.getFileSystem(conf);
1188    LOG.info("Computing mapping of all link files");
1189    Map<String, Path> allFiles = FSUtils
1190        .getTableStoreFilePathMap(fs, hbaseRoot, new FSUtils.HFileLinkFilter(), executor, errors);
1191    errors.print("");
1192
1193    LOG.info("Validating mapping using HDFS state");
1194    for (Path path : allFiles.values()) {
1195      // building HFileLink object to gather locations
1196      HFileLink actualLink = HFileLink.buildFromHFileLinkPattern(conf, path);
1197      if (actualLink.exists(fs)) continue; // good, expected
1198
1199      // Found a lingering HFileLink
1200      errors.reportError(ERROR_CODE.LINGERING_HFILELINK, "Found lingering HFileLink " + path);
1201      if (!shouldFixHFileLinks()) continue;
1202
1203      // Now, trying to fix it since requested
1204      setShouldRerun();
1205
1206      // An HFileLink path should be like
1207      // ${hbase.rootdir}/data/namespace/table_name/region_id/family_name/linkedtable=linkedregionname-linkedhfilename
1208      // sidelineing will happen in the ${hbase.rootdir}/${sidelinedir} directory with the same folder structure.
1209      boolean success = sidelineFile(fs, hbaseRoot, path);
1210
1211      if (!success) {
1212        LOG.error("Failed to sideline HFileLink file " + path);
1213      }
1214
1215      // An HFileLink backreference path should be like
1216      // ${hbase.rootdir}/archive/data/namespace/table_name/region_id/family_name/.links-linkedhfilename
1217      // sidelineing will happen in the ${hbase.rootdir}/${sidelinedir} directory with the same folder structure.
1218      Path backRefPath = FileLink.getBackReferencesDir(HFileArchiveUtil
1219              .getStoreArchivePath(conf, HFileLink.getReferencedTableName(path.getName().toString()),
1220                  HFileLink.getReferencedRegionName(path.getName().toString()),
1221                  path.getParent().getName()),
1222          HFileLink.getReferencedHFileName(path.getName().toString()));
1223      success = sidelineFile(fs, hbaseRoot, backRefPath);
1224
1225      if (!success) {
1226        LOG.error("Failed to sideline HFileLink backreference file " + path);
1227      }
1228    }
1229  }
1230
1231  private boolean sidelineFile(FileSystem fs, Path hbaseRoot, Path path) throws IOException {
1232    URI uri = hbaseRoot.toUri().relativize(path.toUri());
1233    if (uri.isAbsolute()) return false;
1234    String relativePath = uri.getPath();
1235    Path rootDir = getSidelineDir();
1236    Path dst = new Path(rootDir, relativePath);
1237    boolean pathCreated = fs.mkdirs(dst.getParent());
1238    if (!pathCreated) {
1239      LOG.error("Failed to create path: " + dst.getParent());
1240      return false;
1241    }
1242    LOG.info("Trying to sideline file " + path + " to " + dst);
1243    return fs.rename(path, dst);
1244  }
1245
1246  /**
1247   * TODO -- need to add tests for this.
1248   */
1249  private void reportEmptyMetaCells() {
1250    errors.print("Number of empty REGIONINFO_QUALIFIER rows in hbase:meta: " +
1251      emptyRegionInfoQualifiers.size());
1252    if (details) {
1253      for (Result r: emptyRegionInfoQualifiers) {
1254        errors.print("  " + r);
1255      }
1256    }
1257  }
1258
1259  /**
1260   * TODO -- need to add tests for this.
1261   */
1262  private void reportTablesInFlux() {
1263    AtomicInteger numSkipped = new AtomicInteger(0);
1264    TableDescriptor[] allTables = getTables(numSkipped);
1265    errors.print("Number of Tables: " + allTables.length);
1266    if (details) {
1267      if (numSkipped.get() > 0) {
1268        errors.detail("Number of Tables in flux: " + numSkipped.get());
1269      }
1270      for (TableDescriptor td : allTables) {
1271        errors.detail("  Table: " + td.getTableName() + "\t" +
1272                           (td.isReadOnly() ? "ro" : "rw") + "\t" +
1273                            (td.isMetaRegion() ? "META" : "    ") + "\t" +
1274                           " families: " + td.getColumnFamilyCount());
1275      }
1276    }
1277  }
1278
1279  public HbckErrorReporter getErrors() {
1280    return errors;
1281  }
1282
1283  /**
1284   * Populate hbi's from regionInfos loaded from file system.
1285   */
1286  private SortedMap<TableName, HbckTableInfo> loadHdfsRegionInfos()
1287      throws IOException, InterruptedException {
1288    tablesInfo.clear(); // regenerating the data
1289    // generate region split structure
1290    Collection<HbckRegionInfo> hbckRegionInfos = regionInfoMap.values();
1291
1292    // Parallelized read of .regioninfo files.
1293    List<WorkItemHdfsRegionInfo> hbis = new ArrayList<>(hbckRegionInfos.size());
1294    List<Future<Void>> hbiFutures;
1295
1296    for (HbckRegionInfo hbi : hbckRegionInfos) {
1297      WorkItemHdfsRegionInfo work = new WorkItemHdfsRegionInfo(hbi, this, errors);
1298      hbis.add(work);
1299    }
1300
1301    // Submit and wait for completion
1302    hbiFutures = executor.invokeAll(hbis);
1303
1304    for(int i=0; i<hbiFutures.size(); i++) {
1305      WorkItemHdfsRegionInfo work = hbis.get(i);
1306      Future<Void> f = hbiFutures.get(i);
1307      try {
1308        f.get();
1309      } catch(ExecutionException e) {
1310        LOG.warn("Failed to read .regioninfo file for region " +
1311              work.hbi.getRegionNameAsString(), e.getCause());
1312      }
1313    }
1314
1315    Path hbaseRoot = FSUtils.getRootDir(getConf());
1316    FileSystem fs = hbaseRoot.getFileSystem(getConf());
1317    // serialized table info gathering.
1318    for (HbckRegionInfo hbi: hbckRegionInfos) {
1319
1320      if (hbi.getHdfsHRI() == null) {
1321        // was an orphan
1322        continue;
1323      }
1324
1325
1326      // get table name from hdfs, populate various HBaseFsck tables.
1327      TableName tableName = hbi.getTableName();
1328      if (tableName == null) {
1329        // There was an entry in hbase:meta not in the HDFS?
1330        LOG.warn("tableName was null for: " + hbi);
1331        continue;
1332      }
1333
1334      HbckTableInfo modTInfo = tablesInfo.get(tableName);
1335      if (modTInfo == null) {
1336        // only executed once per table.
1337        modTInfo = new HbckTableInfo(tableName, this);
1338        tablesInfo.put(tableName, modTInfo);
1339        try {
1340          TableDescriptor htd =
1341              FSTableDescriptors.getTableDescriptorFromFs(fs, hbaseRoot, tableName);
1342          modTInfo.htds.add(htd);
1343        } catch (IOException ioe) {
1344          if (!orphanTableDirs.containsKey(tableName)) {
1345            LOG.warn("Unable to read .tableinfo from " + hbaseRoot, ioe);
1346            //should only report once for each table
1347            errors.reportError(ERROR_CODE.NO_TABLEINFO_FILE,
1348                "Unable to read .tableinfo from " + hbaseRoot + "/" + tableName);
1349            Set<String> columns = new HashSet<>();
1350            orphanTableDirs.put(tableName, getColumnFamilyList(columns, hbi));
1351          }
1352        }
1353      }
1354      if (!hbi.isSkipChecks()) {
1355        modTInfo.addRegionInfo(hbi);
1356      }
1357    }
1358
1359    loadTableInfosForTablesWithNoRegion();
1360    errors.print("");
1361
1362    return tablesInfo;
1363  }
1364
1365  /**
1366   * To get the column family list according to the column family dirs
1367   * @param columns
1368   * @param hbi
1369   * @return a set of column families
1370   * @throws IOException
1371   */
1372  private Set<String> getColumnFamilyList(Set<String> columns, HbckRegionInfo hbi)
1373      throws IOException {
1374    Path regionDir = hbi.getHdfsRegionDir();
1375    FileSystem fs = regionDir.getFileSystem(getConf());
1376    FileStatus[] subDirs = fs.listStatus(regionDir, new FSUtils.FamilyDirFilter(fs));
1377    for (FileStatus subdir : subDirs) {
1378      String columnfamily = subdir.getPath().getName();
1379      columns.add(columnfamily);
1380    }
1381    return columns;
1382  }
1383
1384  /**
1385   * To fabricate a .tableinfo file with following contents<br>
1386   * 1. the correct tablename <br>
1387   * 2. the correct colfamily list<br>
1388   * 3. the default properties for both {@link TableDescriptor} and {@link ColumnFamilyDescriptor}<br>
1389   * @throws IOException
1390   */
1391  private boolean fabricateTableInfo(FSTableDescriptors fstd, TableName tableName,
1392      Set<String> columns) throws IOException {
1393    if (columns ==null || columns.isEmpty()) return false;
1394    TableDescriptorBuilder builder = TableDescriptorBuilder.newBuilder(tableName);
1395    for (String columnfamimly : columns) {
1396      builder.setColumnFamily(ColumnFamilyDescriptorBuilder.of(columnfamimly));
1397    }
1398    fstd.createTableDescriptor(builder.build(), true);
1399    return true;
1400  }
1401
1402  /**
1403   * To fix the empty REGIONINFO_QUALIFIER rows from hbase:meta <br>
1404   * @throws IOException
1405   */
1406  public void fixEmptyMetaCells() throws IOException {
1407    if (shouldFixEmptyMetaCells() && !emptyRegionInfoQualifiers.isEmpty()) {
1408      LOG.info("Trying to fix empty REGIONINFO_QUALIFIER hbase:meta rows.");
1409      for (Result region : emptyRegionInfoQualifiers) {
1410        deleteMetaRegion(region.getRow());
1411        errors.getErrorList().remove(ERROR_CODE.EMPTY_META_CELL);
1412      }
1413      emptyRegionInfoQualifiers.clear();
1414    }
1415  }
1416
1417  /**
1418   * To fix orphan table by creating a .tableinfo file under tableDir <br>
1419   * 1. if TableInfo is cached, to recover the .tableinfo accordingly <br>
1420   * 2. else create a default .tableinfo file with following items<br>
1421   * &nbsp;2.1 the correct tablename <br>
1422   * &nbsp;2.2 the correct colfamily list<br>
1423   * &nbsp;2.3 the default properties for both {@link TableDescriptor} and {@link ColumnFamilyDescriptor}<br>
1424   * @throws IOException
1425   */
1426  public void fixOrphanTables() throws IOException {
1427    if (shouldFixTableOrphans() && !orphanTableDirs.isEmpty()) {
1428
1429      List<TableName> tmpList = new ArrayList<>(orphanTableDirs.keySet().size());
1430      tmpList.addAll(orphanTableDirs.keySet());
1431      TableDescriptor[] htds = getTableDescriptors(tmpList);
1432      Iterator<Entry<TableName, Set<String>>> iter =
1433          orphanTableDirs.entrySet().iterator();
1434      int j = 0;
1435      int numFailedCase = 0;
1436      FSTableDescriptors fstd = new FSTableDescriptors(getConf());
1437      while (iter.hasNext()) {
1438        Entry<TableName, Set<String>> entry =
1439            iter.next();
1440        TableName tableName = entry.getKey();
1441        LOG.info("Trying to fix orphan table error: " + tableName);
1442        if (j < htds.length) {
1443          if (tableName.equals(htds[j].getTableName())) {
1444            TableDescriptor htd = htds[j];
1445            LOG.info("fixing orphan table: " + tableName + " from cache");
1446            fstd.createTableDescriptor(htd, true);
1447            j++;
1448            iter.remove();
1449          }
1450        } else {
1451          if (fabricateTableInfo(fstd, tableName, entry.getValue())) {
1452            LOG.warn("fixing orphan table: " + tableName + " with a default .tableinfo file");
1453            LOG.warn("Strongly recommend to modify the TableDescriptor if necessary for: " + tableName);
1454            iter.remove();
1455          } else {
1456            LOG.error("Unable to create default .tableinfo for " + tableName + " while missing column family information");
1457            numFailedCase++;
1458          }
1459        }
1460        fixes++;
1461      }
1462
1463      if (orphanTableDirs.isEmpty()) {
1464        // all orphanTableDirs are luckily recovered
1465        // re-run doFsck after recovering the .tableinfo file
1466        setShouldRerun();
1467        LOG.warn("Strongly recommend to re-run manually hfsck after all orphanTableDirs being fixed");
1468      } else if (numFailedCase > 0) {
1469        LOG.error("Failed to fix " + numFailedCase
1470            + " OrphanTables with default .tableinfo files");
1471      }
1472
1473    }
1474    //cleanup the list
1475    orphanTableDirs.clear();
1476
1477  }
1478
1479  /**
1480   * Log an appropriate message about whether or not overlapping merges are computed in parallel.
1481   */
1482  private void logParallelMerge() {
1483    if (getConf().getBoolean("hbasefsck.overlap.merge.parallel", true)) {
1484      LOG.info("Handling overlap merges in parallel. set hbasefsck.overlap.merge.parallel to" +
1485          " false to run serially.");
1486    } else {
1487      LOG.info("Handling overlap merges serially.  set hbasefsck.overlap.merge.parallel to" +
1488          " true to run in parallel.");
1489    }
1490  }
1491
1492  private SortedMap<TableName, HbckTableInfo> checkHdfsIntegrity(boolean fixHoles,
1493      boolean fixOverlaps) throws IOException {
1494    LOG.info("Checking HBase region split map from HDFS data...");
1495    logParallelMerge();
1496    for (HbckTableInfo tInfo : tablesInfo.values()) {
1497      TableIntegrityErrorHandler handler;
1498      if (fixHoles || fixOverlaps) {
1499        handler = tInfo.new HDFSIntegrityFixer(tInfo, errors, getConf(),
1500          fixHoles, fixOverlaps);
1501      } else {
1502        handler = tInfo.new IntegrityFixSuggester(tInfo, errors);
1503      }
1504      if (!tInfo.checkRegionChain(handler)) {
1505        // should dump info as well.
1506        errors.report("Found inconsistency in table " + tInfo.getName());
1507      }
1508    }
1509    return tablesInfo;
1510  }
1511
1512  Path getSidelineDir() throws IOException {
1513    if (sidelineDir == null) {
1514      Path hbaseDir = FSUtils.getRootDir(getConf());
1515      Path hbckDir = new Path(hbaseDir, HConstants.HBCK_SIDELINEDIR_NAME);
1516      sidelineDir = new Path(hbckDir, hbaseDir.getName() + "-"
1517          + startMillis);
1518    }
1519    return sidelineDir;
1520  }
1521
1522  /**
1523   * Sideline a region dir (instead of deleting it)
1524   */
1525  Path sidelineRegionDir(FileSystem fs, HbckRegionInfo hi) throws IOException {
1526    return sidelineRegionDir(fs, null, hi);
1527  }
1528
1529  /**
1530   * Sideline a region dir (instead of deleting it)
1531   *
1532   * @param parentDir if specified, the region will be sidelined to folder like
1533   *     {@literal .../parentDir/<table name>/<region name>}. The purpose is to group together
1534   *     similar regions sidelined, for example, those regions should be bulk loaded back later
1535   *     on. If NULL, it is ignored.
1536   */
1537  Path sidelineRegionDir(FileSystem fs,
1538      String parentDir, HbckRegionInfo hi) throws IOException {
1539    TableName tableName = hi.getTableName();
1540    Path regionDir = hi.getHdfsRegionDir();
1541
1542    if (!fs.exists(regionDir)) {
1543      LOG.warn("No previous " + regionDir + " exists.  Continuing.");
1544      return null;
1545    }
1546
1547    Path rootDir = getSidelineDir();
1548    if (parentDir != null) {
1549      rootDir = new Path(rootDir, parentDir);
1550    }
1551    Path sidelineTableDir= FSUtils.getTableDir(rootDir, tableName);
1552    Path sidelineRegionDir = new Path(sidelineTableDir, regionDir.getName());
1553    fs.mkdirs(sidelineRegionDir);
1554    boolean success = false;
1555    FileStatus[] cfs =  fs.listStatus(regionDir);
1556    if (cfs == null) {
1557      LOG.info("Region dir is empty: " + regionDir);
1558    } else {
1559      for (FileStatus cf : cfs) {
1560        Path src = cf.getPath();
1561        Path dst =  new Path(sidelineRegionDir, src.getName());
1562        if (fs.isFile(src)) {
1563          // simple file
1564          success = fs.rename(src, dst);
1565          if (!success) {
1566            String msg = "Unable to rename file " + src +  " to " + dst;
1567            LOG.error(msg);
1568            throw new IOException(msg);
1569          }
1570          continue;
1571        }
1572
1573        // is a directory.
1574        fs.mkdirs(dst);
1575
1576        LOG.info("Sidelining files from " + src + " into containing region " + dst);
1577        // FileSystem.rename is inconsistent with directories -- if the
1578        // dst (foo/a) exists and is a dir, and the src (foo/b) is a dir,
1579        // it moves the src into the dst dir resulting in (foo/a/b).  If
1580        // the dst does not exist, and the src a dir, src becomes dst. (foo/b)
1581        FileStatus[] hfiles = fs.listStatus(src);
1582        if (hfiles != null && hfiles.length > 0) {
1583          for (FileStatus hfile : hfiles) {
1584            success = fs.rename(hfile.getPath(), dst);
1585            if (!success) {
1586              String msg = "Unable to rename file " + src +  " to " + dst;
1587              LOG.error(msg);
1588              throw new IOException(msg);
1589            }
1590          }
1591        }
1592        LOG.debug("Sideline directory contents:");
1593        debugLsr(sidelineRegionDir);
1594      }
1595    }
1596
1597    LOG.info("Removing old region dir: " + regionDir);
1598    success = fs.delete(regionDir, true);
1599    if (!success) {
1600      String msg = "Unable to delete dir " + regionDir;
1601      LOG.error(msg);
1602      throw new IOException(msg);
1603    }
1604    return sidelineRegionDir;
1605  }
1606
1607  /**
1608   * Load the list of disabled tables in ZK into local set.
1609   * @throws ZooKeeperConnectionException
1610   * @throws IOException
1611   */
1612  private void loadTableStates()
1613  throws IOException {
1614    tableStates = MetaTableAccessor.getTableStates(connection);
1615    // Add hbase:meta so this tool keeps working. In hbase2, meta is always enabled though it
1616    // has no entry in the table states. HBCK doesn't work right w/ hbase2 but just do this in
1617    // meantime.
1618    this.tableStates.put(TableName.META_TABLE_NAME,
1619        new TableState(TableName.META_TABLE_NAME, TableState.State.ENABLED));
1620  }
1621
1622  /**
1623   * Check if the specified region's table is disabled.
1624   * @param tableName table to check status of
1625   */
1626  boolean isTableDisabled(TableName tableName) {
1627    return tableStates.containsKey(tableName)
1628        && tableStates.get(tableName)
1629        .inStates(TableState.State.DISABLED, TableState.State.DISABLING);
1630  }
1631
1632  /**
1633   * Scan HDFS for all regions, recording their information into
1634   * regionInfoMap
1635   */
1636  public void loadHdfsRegionDirs() throws IOException, InterruptedException {
1637    Path rootDir = FSUtils.getRootDir(getConf());
1638    FileSystem fs = rootDir.getFileSystem(getConf());
1639
1640    // list all tables from HDFS
1641    List<FileStatus> tableDirs = Lists.newArrayList();
1642
1643    boolean foundVersionFile = fs.exists(new Path(rootDir, HConstants.VERSION_FILE_NAME));
1644
1645    List<Path> paths = FSUtils.getTableDirs(fs, rootDir);
1646    for (Path path : paths) {
1647      TableName tableName = FSUtils.getTableName(path);
1648       if ((!checkMetaOnly &&
1649           isTableIncluded(tableName)) ||
1650           tableName.equals(TableName.META_TABLE_NAME)) {
1651         tableDirs.add(fs.getFileStatus(path));
1652       }
1653    }
1654
1655    // verify that version file exists
1656    if (!foundVersionFile) {
1657      errors.reportError(ERROR_CODE.NO_VERSION_FILE,
1658          "Version file does not exist in root dir " + rootDir);
1659      if (shouldFixVersionFile()) {
1660        LOG.info("Trying to create a new " + HConstants.VERSION_FILE_NAME
1661            + " file.");
1662        setShouldRerun();
1663        FSUtils.setVersion(fs, rootDir, getConf().getInt(
1664            HConstants.THREAD_WAKE_FREQUENCY, 10 * 1000), getConf().getInt(
1665            HConstants.VERSION_FILE_WRITE_ATTEMPTS,
1666            HConstants.DEFAULT_VERSION_FILE_WRITE_ATTEMPTS));
1667      }
1668    }
1669
1670    // Avoid multithreading at table-level because already multithreaded internally at
1671    // region-level.  Additionally multithreading at table-level can lead to deadlock
1672    // if there are many tables in the cluster.  Since there are a limited # of threads
1673    // in the executor's thread pool and if we multithread at the table-level by putting
1674    // WorkItemHdfsDir callables into the executor, then we will have some threads in the
1675    // executor tied up solely in waiting for the tables' region-level calls to complete.
1676    // If there are enough tables then there will be no actual threads in the pool left
1677    // for the region-level callables to be serviced.
1678    for (FileStatus tableDir : tableDirs) {
1679      LOG.debug("Loading region dirs from " +tableDir.getPath());
1680      WorkItemHdfsDir item = new WorkItemHdfsDir(fs, errors, tableDir);
1681      try {
1682        item.call();
1683      } catch (ExecutionException e) {
1684        LOG.warn("Could not completely load table dir " +
1685            tableDir.getPath(), e.getCause());
1686      }
1687    }
1688    errors.print("");
1689  }
1690
1691  /**
1692   * Record the location of the hbase:meta region as found in ZooKeeper.
1693   */
1694  private boolean recordMetaRegion() throws IOException {
1695    List<HRegionLocation> locs;
1696    try (RegionLocator locator = connection.getRegionLocator(TableName.META_TABLE_NAME)) {
1697      locs = locator.getRegionLocations(HConstants.EMPTY_START_ROW, true);
1698    }
1699    if (locs == null || locs.isEmpty()) {
1700      errors.reportError(ERROR_CODE.NULL_META_REGION, "META region was not found in ZooKeeper");
1701      return false;
1702    }
1703    for (HRegionLocation metaLocation : locs) {
1704      // Check if Meta region is valid and existing
1705      if (metaLocation == null) {
1706        errors.reportError(ERROR_CODE.NULL_META_REGION, "META region location is null");
1707        return false;
1708      }
1709      if (metaLocation.getRegion() == null) {
1710        errors.reportError(ERROR_CODE.NULL_META_REGION, "META location regionInfo is null");
1711        return false;
1712      }
1713      if (metaLocation.getHostname() == null) {
1714        errors.reportError(ERROR_CODE.NULL_META_REGION, "META location hostName is null");
1715        return false;
1716      }
1717      ServerName sn = metaLocation.getServerName();
1718      HbckRegionInfo.MetaEntry m = new HbckRegionInfo.MetaEntry(metaLocation.getRegion(), sn,
1719          EnvironmentEdgeManager.currentTime());
1720      HbckRegionInfo hbckRegionInfo = regionInfoMap.get(metaLocation.getRegion().getEncodedName());
1721      if (hbckRegionInfo == null) {
1722        regionInfoMap.put(metaLocation.getRegion().getEncodedName(), new HbckRegionInfo(m));
1723      } else {
1724        hbckRegionInfo.setMetaEntry(m);
1725      }
1726    }
1727    return true;
1728  }
1729
1730  private ZKWatcher createZooKeeperWatcher() throws IOException {
1731    return new ZKWatcher(getConf(), "hbase Fsck", new Abortable() {
1732      @Override
1733      public void abort(String why, Throwable e) {
1734        LOG.error(why, e);
1735        System.exit(1);
1736      }
1737
1738      @Override
1739      public boolean isAborted() {
1740        return false;
1741      }
1742
1743    });
1744  }
1745
1746  /**
1747   * Contacts each regionserver and fetches metadata about regions.
1748   * @param regionServerList - the list of region servers to connect to
1749   * @throws IOException if a remote or network exception occurs
1750   */
1751  void processRegionServers(Collection<ServerName> regionServerList)
1752    throws IOException, InterruptedException {
1753
1754    List<WorkItemRegion> workItems = new ArrayList<>(regionServerList.size());
1755    List<Future<Void>> workFutures;
1756
1757    // loop to contact each region server in parallel
1758    for (ServerName rsinfo: regionServerList) {
1759      workItems.add(new WorkItemRegion(this, rsinfo, errors, connection));
1760    }
1761
1762    workFutures = executor.invokeAll(workItems);
1763
1764    for(int i=0; i<workFutures.size(); i++) {
1765      WorkItemRegion item = workItems.get(i);
1766      Future<Void> f = workFutures.get(i);
1767      try {
1768        f.get();
1769      } catch(ExecutionException e) {
1770        LOG.warn("Could not process regionserver " + item.rsinfo.getHostAndPort(),
1771            e.getCause());
1772      }
1773    }
1774  }
1775
1776  /**
1777   * Check consistency of all regions that have been found in previous phases.
1778   */
1779  private void checkAndFixConsistency()
1780  throws IOException, KeeperException, InterruptedException {
1781    // Divide the checks in two phases. One for default/primary replicas and another
1782    // for the non-primary ones. Keeps code cleaner this way.
1783
1784    List<CheckRegionConsistencyWorkItem> workItems = new ArrayList<>(regionInfoMap.size());
1785    for (java.util.Map.Entry<String, HbckRegionInfo> e: regionInfoMap.entrySet()) {
1786      if (e.getValue().getReplicaId() == RegionInfo.DEFAULT_REPLICA_ID) {
1787        workItems.add(new CheckRegionConsistencyWorkItem(e.getKey(), e.getValue()));
1788      }
1789    }
1790    checkRegionConsistencyConcurrently(workItems);
1791
1792    boolean prevHdfsCheck = shouldCheckHdfs();
1793    setCheckHdfs(false); //replicas don't have any hdfs data
1794    // Run a pass over the replicas and fix any assignment issues that exist on the currently
1795    // deployed/undeployed replicas.
1796    List<CheckRegionConsistencyWorkItem> replicaWorkItems = new ArrayList<>(regionInfoMap.size());
1797    for (java.util.Map.Entry<String, HbckRegionInfo> e: regionInfoMap.entrySet()) {
1798      if (e.getValue().getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) {
1799        replicaWorkItems.add(new CheckRegionConsistencyWorkItem(e.getKey(), e.getValue()));
1800      }
1801    }
1802    checkRegionConsistencyConcurrently(replicaWorkItems);
1803    setCheckHdfs(prevHdfsCheck);
1804
1805    // If some regions is skipped during checkRegionConsistencyConcurrently() phase, we might
1806    // not get accurate state of the hbase if continuing. The config here allows users to tune
1807    // the tolerance of number of skipped region.
1808    // TODO: evaluate the consequence to continue the hbck operation without config.
1809    int terminateThreshold =  getConf().getInt("hbase.hbck.skipped.regions.limit", 0);
1810    int numOfSkippedRegions = skippedRegions.size();
1811    if (numOfSkippedRegions > 0 && numOfSkippedRegions > terminateThreshold) {
1812      throw new IOException(numOfSkippedRegions
1813        + " region(s) could not be checked or repaired.  See logs for detail.");
1814    }
1815
1816    if (shouldCheckHdfs()) {
1817      checkAndFixTableStates();
1818    }
1819  }
1820
1821  /**
1822   * Check consistency of all regions using mulitple threads concurrently.
1823   */
1824  private void checkRegionConsistencyConcurrently(
1825    final List<CheckRegionConsistencyWorkItem> workItems)
1826    throws IOException, KeeperException, InterruptedException {
1827    if (workItems.isEmpty()) {
1828      return;  // nothing to check
1829    }
1830
1831    List<Future<Void>> workFutures = executor.invokeAll(workItems);
1832    for(Future<Void> f: workFutures) {
1833      try {
1834        f.get();
1835      } catch(ExecutionException e1) {
1836        LOG.warn("Could not check region consistency " , e1.getCause());
1837        if (e1.getCause() instanceof IOException) {
1838          throw (IOException)e1.getCause();
1839        } else if (e1.getCause() instanceof KeeperException) {
1840          throw (KeeperException)e1.getCause();
1841        } else if (e1.getCause() instanceof InterruptedException) {
1842          throw (InterruptedException)e1.getCause();
1843        } else {
1844          throw new IOException(e1.getCause());
1845        }
1846      }
1847    }
1848  }
1849
1850  class CheckRegionConsistencyWorkItem implements Callable<Void> {
1851    private final String key;
1852    private final HbckRegionInfo hbi;
1853
1854    CheckRegionConsistencyWorkItem(String key, HbckRegionInfo hbi) {
1855      this.key = key;
1856      this.hbi = hbi;
1857    }
1858
1859    @Override
1860    public synchronized Void call() throws Exception {
1861      try {
1862        checkRegionConsistency(key, hbi);
1863      } catch (Exception e) {
1864        // If the region is non-META region, skip this region and send warning/error message; if
1865        // the region is META region, we should not continue.
1866        LOG.warn("Unable to complete check or repair the region '" + hbi.getRegionNameAsString()
1867          + "'.", e);
1868        if (hbi.getHdfsHRI().isMetaRegion()) {
1869          throw e;
1870        }
1871        LOG.warn("Skip region '" + hbi.getRegionNameAsString() + "'");
1872        addSkippedRegion(hbi);
1873      }
1874      return null;
1875    }
1876  }
1877
1878  private void addSkippedRegion(final HbckRegionInfo hbi) {
1879    Set<String> skippedRegionNames = skippedRegions.get(hbi.getTableName());
1880    if (skippedRegionNames == null) {
1881      skippedRegionNames = new HashSet<>();
1882    }
1883    skippedRegionNames.add(hbi.getRegionNameAsString());
1884    skippedRegions.put(hbi.getTableName(), skippedRegionNames);
1885  }
1886
1887  /**
1888   * Check and fix table states, assumes full info available:
1889   * - tableInfos
1890   * - empty tables loaded
1891   */
1892  private void checkAndFixTableStates() throws IOException {
1893    // first check dangling states
1894    for (Entry<TableName, TableState> entry : tableStates.entrySet()) {
1895      TableName tableName = entry.getKey();
1896      TableState tableState = entry.getValue();
1897      HbckTableInfo tableInfo = tablesInfo.get(tableName);
1898      if (isTableIncluded(tableName)
1899          && !tableName.isSystemTable()
1900          && tableInfo == null) {
1901        if (fixMeta) {
1902          MetaTableAccessor.deleteTableState(connection, tableName);
1903          TableState state = MetaTableAccessor.getTableState(connection, tableName);
1904          if (state != null) {
1905            errors.reportError(ERROR_CODE.ORPHAN_TABLE_STATE,
1906                tableName + " unable to delete dangling table state " + tableState);
1907          }
1908        } else if (!checkMetaOnly) {
1909          // dangling table state in meta if checkMetaOnly is false. If checkMetaOnly is
1910          // true, tableInfo will be null as tablesInfo are not polulated for all tables from hdfs
1911          errors.reportError(ERROR_CODE.ORPHAN_TABLE_STATE,
1912              tableName + " has dangling table state " + tableState);
1913        }
1914      }
1915    }
1916    // check that all tables have states
1917    for (TableName tableName : tablesInfo.keySet()) {
1918      if (isTableIncluded(tableName) && !tableStates.containsKey(tableName)) {
1919        if (fixMeta) {
1920          MetaTableAccessor.updateTableState(connection, tableName, TableState.State.ENABLED);
1921          TableState newState = MetaTableAccessor.getTableState(connection, tableName);
1922          if (newState == null) {
1923            errors.reportError(ERROR_CODE.NO_TABLE_STATE,
1924                "Unable to change state for table " + tableName + " in meta ");
1925          }
1926        } else {
1927          errors.reportError(ERROR_CODE.NO_TABLE_STATE,
1928              tableName + " has no state in meta ");
1929        }
1930      }
1931    }
1932  }
1933
1934  private void preCheckPermission() throws IOException, AccessDeniedException {
1935    if (shouldIgnorePreCheckPermission()) {
1936      return;
1937    }
1938
1939    Path hbaseDir = FSUtils.getRootDir(getConf());
1940    FileSystem fs = hbaseDir.getFileSystem(getConf());
1941    UserProvider userProvider = UserProvider.instantiate(getConf());
1942    UserGroupInformation ugi = userProvider.getCurrent().getUGI();
1943    FileStatus[] files = fs.listStatus(hbaseDir);
1944    for (FileStatus file : files) {
1945      try {
1946        FSUtils.checkAccess(ugi, file, FsAction.WRITE);
1947      } catch (AccessDeniedException ace) {
1948        LOG.warn("Got AccessDeniedException when preCheckPermission ", ace);
1949        errors.reportError(ERROR_CODE.WRONG_USAGE, "Current user " + ugi.getUserName()
1950          + " does not have write perms to " + file.getPath()
1951          + ". Please rerun hbck as hdfs user " + file.getOwner());
1952        throw ace;
1953      }
1954    }
1955  }
1956
1957  /**
1958   * Deletes region from meta table
1959   */
1960  private void deleteMetaRegion(HbckRegionInfo hi) throws IOException {
1961    deleteMetaRegion(hi.getMetaEntry().getRegionName());
1962  }
1963
1964  /**
1965   * Deletes region from meta table
1966   */
1967  private void deleteMetaRegion(byte[] metaKey) throws IOException {
1968    Delete d = new Delete(metaKey);
1969    meta.delete(d);
1970    LOG.info("Deleted " + Bytes.toString(metaKey) + " from META" );
1971  }
1972
1973  /**
1974   * Reset the split parent region info in meta table
1975   */
1976  private void resetSplitParent(HbckRegionInfo hi) throws IOException {
1977    RowMutations mutations = new RowMutations(hi.getMetaEntry().getRegionName());
1978    Delete d = new Delete(hi.getMetaEntry().getRegionName());
1979    d.addColumn(HConstants.CATALOG_FAMILY, HConstants.SPLITA_QUALIFIER);
1980    d.addColumn(HConstants.CATALOG_FAMILY, HConstants.SPLITB_QUALIFIER);
1981    mutations.add(d);
1982
1983    RegionInfo hri = RegionInfoBuilder.newBuilder(hi.getMetaEntry())
1984        .setOffline(false)
1985        .setSplit(false)
1986        .build();
1987    Put p = MetaTableAccessor.makePutFromRegionInfo(hri, EnvironmentEdgeManager.currentTime());
1988    mutations.add(p);
1989
1990    meta.mutateRow(mutations);
1991    LOG.info("Reset split parent " + hi.getMetaEntry().getRegionNameAsString() + " in META");
1992  }
1993
1994  /**
1995   * This backwards-compatibility wrapper for permanently offlining a region
1996   * that should not be alive.  If the region server does not support the
1997   * "offline" method, it will use the closest unassign method instead.  This
1998   * will basically work until one attempts to disable or delete the affected
1999   * table.  The problem has to do with in-memory only master state, so
2000   * restarting the HMaster or failing over to another should fix this.
2001   */
2002  void offline(byte[] regionName) throws IOException {
2003    String regionString = Bytes.toStringBinary(regionName);
2004    if (!rsSupportsOffline) {
2005      LOG.warn(
2006          "Using unassign region " + regionString + " instead of using offline method, you should" +
2007              " restart HMaster after these repairs");
2008      admin.unassign(regionName, true);
2009      return;
2010    }
2011
2012    // first time we assume the rs's supports #offline.
2013    try {
2014      LOG.info("Offlining region " + regionString);
2015      admin.offline(regionName);
2016    } catch (IOException ioe) {
2017      String notFoundMsg = "java.lang.NoSuchMethodException: " +
2018          "org.apache.hadoop.hbase.master.HMaster.offline([B)";
2019      if (ioe.getMessage().contains(notFoundMsg)) {
2020        LOG.warn("Using unassign region " + regionString +
2021            " instead of using offline method, you should" +
2022            " restart HMaster after these repairs");
2023        rsSupportsOffline = false; // in the future just use unassign
2024        admin.unassign(regionName, true);
2025        return;
2026      }
2027      throw ioe;
2028    }
2029  }
2030
2031  /**
2032   * Attempts to undeploy a region from a region server based in information in
2033   * META.  Any operations that modify the file system should make sure that
2034   * its corresponding region is not deployed to prevent data races.
2035   *
2036   * A separate call is required to update the master in-memory region state
2037   * kept in the AssignementManager.  Because disable uses this state instead of
2038   * that found in META, we can't seem to cleanly disable/delete tables that
2039   * have been hbck fixed.  When used on a version of HBase that does not have
2040   * the offline ipc call exposed on the master (&lt;0.90.5, &lt;0.92.0) a master
2041   * restart or failover may be required.
2042   */
2043  void closeRegion(HbckRegionInfo hi) throws IOException, InterruptedException {
2044    if (hi.getMetaEntry() == null && hi.getHdfsEntry() == null) {
2045      undeployRegions(hi);
2046      return;
2047    }
2048
2049    // get assignment info and hregioninfo from meta.
2050    Get get = new Get(hi.getRegionName());
2051    get.addColumn(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER);
2052    get.addColumn(HConstants.CATALOG_FAMILY, HConstants.SERVER_QUALIFIER);
2053    get.addColumn(HConstants.CATALOG_FAMILY, HConstants.STARTCODE_QUALIFIER);
2054    // also get the locations of the replicas to close if the primary region is being closed
2055    if (hi.getReplicaId() == RegionInfo.DEFAULT_REPLICA_ID) {
2056      int numReplicas = admin.getDescriptor(hi.getTableName()).getRegionReplication();
2057      for (int i = 0; i < numReplicas; i++) {
2058        get.addColumn(HConstants.CATALOG_FAMILY, MetaTableAccessor.getServerColumn(i));
2059        get.addColumn(HConstants.CATALOG_FAMILY, MetaTableAccessor.getStartCodeColumn(i));
2060      }
2061    }
2062    Result r = meta.get(get);
2063    RegionLocations rl = MetaTableAccessor.getRegionLocations(r);
2064    if (rl == null) {
2065      LOG.warn("Unable to close region " + hi.getRegionNameAsString() +
2066          " since meta does not have handle to reach it");
2067      return;
2068    }
2069    for (HRegionLocation h : rl.getRegionLocations()) {
2070      ServerName serverName = h.getServerName();
2071      if (serverName == null) {
2072        errors.reportError("Unable to close region "
2073            + hi.getRegionNameAsString() +  " because meta does not "
2074            + "have handle to reach it.");
2075        continue;
2076      }
2077      RegionInfo hri = h.getRegion();
2078      if (hri == null) {
2079        LOG.warn("Unable to close region " + hi.getRegionNameAsString()
2080            + " because hbase:meta had invalid or missing "
2081            + HConstants.CATALOG_FAMILY_STR + ":"
2082            + Bytes.toString(HConstants.REGIONINFO_QUALIFIER)
2083            + " qualifier value.");
2084        continue;
2085      }
2086      // close the region -- close files and remove assignment
2087      HBaseFsckRepair.closeRegionSilentlyAndWait(connection, serverName, hri);
2088    }
2089  }
2090
2091  private void undeployRegions(HbckRegionInfo hi) throws IOException, InterruptedException {
2092    undeployRegionsForHbi(hi);
2093    // undeploy replicas of the region (but only if the method is invoked for the primary)
2094    if (hi.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) {
2095      return;
2096    }
2097    int numReplicas = admin.getDescriptor(hi.getTableName()).getRegionReplication();
2098    for (int i = 1; i < numReplicas; i++) {
2099      if (hi.getPrimaryHRIForDeployedReplica() == null) continue;
2100      RegionInfo hri = RegionReplicaUtil.getRegionInfoForReplica(
2101          hi.getPrimaryHRIForDeployedReplica(), i);
2102      HbckRegionInfo h = regionInfoMap.get(hri.getEncodedName());
2103      if (h != null) {
2104        undeployRegionsForHbi(h);
2105        //set skip checks; we undeployed it, and we don't want to evaluate this anymore
2106        //in consistency checks
2107        h.setSkipChecks(true);
2108      }
2109    }
2110  }
2111
2112  private void undeployRegionsForHbi(HbckRegionInfo hi) throws IOException, InterruptedException {
2113    for (HbckRegionInfo.OnlineEntry rse : hi.getOnlineEntries()) {
2114      LOG.debug("Undeploy region "  + rse.getRegionInfo() + " from " + rse.getServerName());
2115      try {
2116        HBaseFsckRepair
2117            .closeRegionSilentlyAndWait(connection, rse.getServerName(), rse.getRegionInfo());
2118        offline(rse.getRegionInfo().getRegionName());
2119      } catch (IOException ioe) {
2120        LOG.warn("Got exception when attempting to offline region "
2121            + Bytes.toString(rse.getRegionInfo().getRegionName()), ioe);
2122      }
2123    }
2124  }
2125
2126  private void tryAssignmentRepair(HbckRegionInfo hbi, String msg) throws IOException,
2127    KeeperException, InterruptedException {
2128    // If we are trying to fix the errors
2129    if (shouldFixAssignments()) {
2130      errors.print(msg);
2131      undeployRegions(hbi);
2132      setShouldRerun();
2133      RegionInfo hri = hbi.getHdfsHRI();
2134      if (hri == null) {
2135        hri = hbi.getMetaEntry();
2136      }
2137      HBaseFsckRepair.fixUnassigned(admin, hri);
2138      HBaseFsckRepair.waitUntilAssigned(admin, hri);
2139
2140      // also assign replicas if needed (do it only when this call operates on a primary replica)
2141      if (hbi.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) return;
2142      int replicationCount = admin.getDescriptor(hri.getTable()).getRegionReplication();
2143      for (int i = 1; i < replicationCount; i++) {
2144        hri = RegionReplicaUtil.getRegionInfoForReplica(hri, i);
2145        HbckRegionInfo h = regionInfoMap.get(hri.getEncodedName());
2146        if (h != null) {
2147          undeployRegions(h);
2148          //set skip checks; we undeploy & deploy it; we don't want to evaluate this hbi anymore
2149          //in consistency checks
2150          h.setSkipChecks(true);
2151        }
2152        HBaseFsckRepair.fixUnassigned(admin, hri);
2153        HBaseFsckRepair.waitUntilAssigned(admin, hri);
2154      }
2155
2156    }
2157  }
2158
2159  /**
2160   * Check a single region for consistency and correct deployment.
2161   */
2162  private void checkRegionConsistency(final String key, final HbckRegionInfo hbi)
2163      throws IOException, KeeperException, InterruptedException {
2164
2165    if (hbi.isSkipChecks()) return;
2166    String descriptiveName = hbi.toString();
2167    boolean inMeta = hbi.getMetaEntry() != null;
2168    // In case not checking HDFS, assume the region is on HDFS
2169    boolean inHdfs = !shouldCheckHdfs() || hbi.getHdfsRegionDir() != null;
2170    boolean hasMetaAssignment = inMeta && hbi.getMetaEntry().regionServer != null;
2171    boolean isDeployed = !hbi.getDeployedOn().isEmpty();
2172    boolean isMultiplyDeployed = hbi.getDeployedOn().size() > 1;
2173    boolean deploymentMatchesMeta =
2174      hasMetaAssignment && isDeployed && !isMultiplyDeployed &&
2175      hbi.getMetaEntry().regionServer.equals(hbi.getDeployedOn().get(0));
2176    boolean splitParent =
2177        inMeta && hbi.getMetaEntry().isSplit() && hbi.getMetaEntry().isOffline();
2178    boolean shouldBeDeployed = inMeta && !isTableDisabled(hbi.getMetaEntry().getTable());
2179    boolean recentlyModified = inHdfs &&
2180      hbi.getModTime() + timelag > EnvironmentEdgeManager.currentTime();
2181
2182    // ========== First the healthy cases =============
2183    if (hbi.containsOnlyHdfsEdits()) {
2184      return;
2185    }
2186    if (inMeta && inHdfs && isDeployed && deploymentMatchesMeta && shouldBeDeployed) {
2187      return;
2188    } else if (inMeta && inHdfs && !shouldBeDeployed && !isDeployed) {
2189      LOG.info("Region " + descriptiveName + " is in META, and in a disabled " +
2190        "tabled that is not deployed");
2191      return;
2192    } else if (recentlyModified) {
2193      LOG.warn("Region " + descriptiveName + " was recently modified -- skipping");
2194      return;
2195    }
2196    // ========== Cases where the region is not in hbase:meta =============
2197    else if (!inMeta && !inHdfs && !isDeployed) {
2198      // We shouldn't have record of this region at all then!
2199      assert false : "Entry for region with no data";
2200    } else if (!inMeta && !inHdfs && isDeployed) {
2201      errors.reportError(ERROR_CODE.NOT_IN_META_HDFS, "Region "
2202          + descriptiveName + ", key=" + key + ", not on HDFS or in hbase:meta but " +
2203          "deployed on " + Joiner.on(", ").join(hbi.getDeployedOn()));
2204      if (shouldFixAssignments()) {
2205        undeployRegions(hbi);
2206      }
2207
2208    } else if (!inMeta && inHdfs && !isDeployed) {
2209      if (hbi.isMerged()) {
2210        // This region has already been merged, the remaining hdfs file will be
2211        // cleaned by CatalogJanitor later
2212        hbi.setSkipChecks(true);
2213        LOG.info("Region " + descriptiveName
2214            + " got merge recently, its file(s) will be cleaned by CatalogJanitor later");
2215        return;
2216      }
2217      errors.reportError(ERROR_CODE.NOT_IN_META_OR_DEPLOYED, "Region "
2218          + descriptiveName + " on HDFS, but not listed in hbase:meta " +
2219          "or deployed on any region server");
2220      // restore region consistency of an adopted orphan
2221      if (shouldFixMeta()) {
2222        if (!hbi.isHdfsRegioninfoPresent()) {
2223          LOG.error("Region " + hbi.getHdfsHRI() + " could have been repaired"
2224              +  " in table integrity repair phase if -fixHdfsOrphans was" +
2225              " used.");
2226          return;
2227        }
2228
2229        RegionInfo hri = hbi.getHdfsHRI();
2230        HbckTableInfo tableInfo = tablesInfo.get(hri.getTable());
2231
2232        for (RegionInfo region : tableInfo.getRegionsFromMeta(this.regionInfoMap)) {
2233          if (Bytes.compareTo(region.getStartKey(), hri.getStartKey()) <= 0
2234              && (region.getEndKey().length == 0 || Bytes.compareTo(region.getEndKey(),
2235                hri.getEndKey()) >= 0)
2236              && Bytes.compareTo(region.getStartKey(), hri.getEndKey()) <= 0) {
2237            if(region.isSplit() || region.isOffline()) continue;
2238            Path regionDir = hbi.getHdfsRegionDir();
2239            FileSystem fs = regionDir.getFileSystem(getConf());
2240            List<Path> familyDirs = FSUtils.getFamilyDirs(fs, regionDir);
2241            for (Path familyDir : familyDirs) {
2242              List<Path> referenceFilePaths = FSUtils.getReferenceFilePaths(fs, familyDir);
2243              for (Path referenceFilePath : referenceFilePaths) {
2244                Path parentRegionDir =
2245                    StoreFileInfo.getReferredToFile(referenceFilePath).getParent().getParent();
2246                if (parentRegionDir.toString().endsWith(region.getEncodedName())) {
2247                  LOG.warn(hri + " start and stop keys are in the range of " + region
2248                      + ". The region might not be cleaned up from hdfs when region " + region
2249                      + " split failed. Hence deleting from hdfs.");
2250                  HRegionFileSystem.deleteRegionFromFileSystem(getConf(), fs,
2251                    regionDir.getParent(), hri);
2252                  return;
2253                }
2254              }
2255            }
2256          }
2257        }
2258        LOG.info("Patching hbase:meta with .regioninfo: " + hbi.getHdfsHRI());
2259        int numReplicas = admin.getDescriptor(hbi.getTableName()).getRegionReplication();
2260        HBaseFsckRepair.fixMetaHoleOnlineAndAddReplicas(getConf(), hbi.getHdfsHRI(),
2261            admin.getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS))
2262              .getLiveServerMetrics().keySet(), numReplicas);
2263
2264        tryAssignmentRepair(hbi, "Trying to reassign region...");
2265      }
2266
2267    } else if (!inMeta && inHdfs && isDeployed) {
2268      errors.reportError(ERROR_CODE.NOT_IN_META, "Region " + descriptiveName
2269          + " not in META, but deployed on " + Joiner.on(", ").join(hbi.getDeployedOn()));
2270      debugLsr(hbi.getHdfsRegionDir());
2271      if (hbi.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) {
2272        // for replicas, this means that we should undeploy the region (we would have
2273        // gone over the primaries and fixed meta holes in first phase under
2274        // checkAndFixConsistency; we shouldn't get the condition !inMeta at
2275        // this stage unless unwanted replica)
2276        if (shouldFixAssignments()) {
2277          undeployRegionsForHbi(hbi);
2278        }
2279      }
2280      if (shouldFixMeta() && hbi.getReplicaId() == RegionInfo.DEFAULT_REPLICA_ID) {
2281        if (!hbi.isHdfsRegioninfoPresent()) {
2282          LOG.error("This should have been repaired in table integrity repair phase");
2283          return;
2284        }
2285
2286        LOG.info("Patching hbase:meta with with .regioninfo: " + hbi.getHdfsHRI());
2287        int numReplicas = admin.getDescriptor(hbi.getTableName()).getRegionReplication();
2288        HBaseFsckRepair.fixMetaHoleOnlineAndAddReplicas(getConf(), hbi.getHdfsHRI(),
2289            admin.getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS))
2290              .getLiveServerMetrics().keySet(), numReplicas);
2291        tryAssignmentRepair(hbi, "Trying to fix unassigned region...");
2292      }
2293
2294    // ========== Cases where the region is in hbase:meta =============
2295    } else if (inMeta && inHdfs && !isDeployed && splitParent) {
2296      // check whether this is an actual error, or just transient state where parent
2297      // is not cleaned
2298      if (hbi.getMetaEntry().splitA != null && hbi.getMetaEntry().splitB != null) {
2299        // check that split daughters are there
2300        HbckRegionInfo infoA = this.regionInfoMap.get(hbi.getMetaEntry().splitA.getEncodedName());
2301        HbckRegionInfo infoB = this.regionInfoMap.get(hbi.getMetaEntry().splitB.getEncodedName());
2302        if (infoA != null && infoB != null) {
2303          // we already processed or will process daughters. Move on, nothing to see here.
2304          hbi.setSkipChecks(true);
2305          return;
2306        }
2307      }
2308
2309      // For Replica region, we need to do a similar check. If replica is not split successfully,
2310      // error is going to be reported against primary daughter region.
2311      if (hbi.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) {
2312        LOG.info("Region " + descriptiveName + " is a split parent in META, in HDFS, "
2313            + "and not deployed on any region server. This may be transient.");
2314        hbi.setSkipChecks(true);
2315        return;
2316      }
2317
2318      errors.reportError(ERROR_CODE.LINGERING_SPLIT_PARENT, "Region "
2319          + descriptiveName + " is a split parent in META, in HDFS, "
2320          + "and not deployed on any region server. This could be transient, "
2321          + "consider to run the catalog janitor first!");
2322      if (shouldFixSplitParents()) {
2323        setShouldRerun();
2324        resetSplitParent(hbi);
2325      }
2326    } else if (inMeta && !inHdfs && !isDeployed) {
2327      errors.reportError(ERROR_CODE.NOT_IN_HDFS_OR_DEPLOYED, "Region "
2328          + descriptiveName + " found in META, but not in HDFS "
2329          + "or deployed on any region server.");
2330      if (shouldFixMeta()) {
2331        deleteMetaRegion(hbi);
2332      }
2333    } else if (inMeta && !inHdfs && isDeployed) {
2334      errors.reportError(ERROR_CODE.NOT_IN_HDFS, "Region " + descriptiveName
2335          + " found in META, but not in HDFS, " +
2336          "and deployed on " + Joiner.on(", ").join(hbi.getDeployedOn()));
2337      // We treat HDFS as ground truth.  Any information in meta is transient
2338      // and equivalent data can be regenerated.  So, lets unassign and remove
2339      // these problems from META.
2340      if (shouldFixAssignments()) {
2341        errors.print("Trying to fix unassigned region...");
2342        undeployRegions(hbi);
2343      }
2344      if (shouldFixMeta()) {
2345        // wait for it to complete
2346        deleteMetaRegion(hbi);
2347      }
2348    } else if (inMeta && inHdfs && !isDeployed && shouldBeDeployed) {
2349      errors.reportError(ERROR_CODE.NOT_DEPLOYED, "Region " + descriptiveName
2350          + " not deployed on any region server.");
2351      tryAssignmentRepair(hbi, "Trying to fix unassigned region...");
2352    } else if (inMeta && inHdfs && isDeployed && !shouldBeDeployed) {
2353      errors.reportError(ERROR_CODE.SHOULD_NOT_BE_DEPLOYED,
2354          "Region " + descriptiveName + " should not be deployed according " +
2355          "to META, but is deployed on " + Joiner.on(", ").join(hbi.getDeployedOn()));
2356      if (shouldFixAssignments()) {
2357        errors.print("Trying to close the region " + descriptiveName);
2358        setShouldRerun();
2359        HBaseFsckRepair.fixMultiAssignment(connection, hbi.getMetaEntry(), hbi.getDeployedOn());
2360      }
2361    } else if (inMeta && inHdfs && isMultiplyDeployed) {
2362      errors.reportError(ERROR_CODE.MULTI_DEPLOYED, "Region " + descriptiveName
2363          + " is listed in hbase:meta on region server " + hbi.getMetaEntry().regionServer
2364          + " but is multiply assigned to region servers " +
2365          Joiner.on(", ").join(hbi.getDeployedOn()));
2366      // If we are trying to fix the errors
2367      if (shouldFixAssignments()) {
2368        errors.print("Trying to fix assignment error...");
2369        setShouldRerun();
2370        HBaseFsckRepair.fixMultiAssignment(connection, hbi.getMetaEntry(), hbi.getDeployedOn());
2371      }
2372    } else if (inMeta && inHdfs && isDeployed && !deploymentMatchesMeta) {
2373      errors.reportError(ERROR_CODE.SERVER_DOES_NOT_MATCH_META, "Region "
2374          + descriptiveName + " listed in hbase:meta on region server " +
2375          hbi.getMetaEntry().regionServer + " but found on region server " +
2376          hbi.getDeployedOn().get(0));
2377      // If we are trying to fix the errors
2378      if (shouldFixAssignments()) {
2379        errors.print("Trying to fix assignment error...");
2380        setShouldRerun();
2381        HBaseFsckRepair.fixMultiAssignment(connection, hbi.getMetaEntry(), hbi.getDeployedOn());
2382        HBaseFsckRepair.waitUntilAssigned(admin, hbi.getHdfsHRI());
2383      }
2384    } else {
2385      errors.reportError(ERROR_CODE.UNKNOWN, "Region " + descriptiveName +
2386          " is in an unforeseen state:" +
2387          " inMeta=" + inMeta +
2388          " inHdfs=" + inHdfs +
2389          " isDeployed=" + isDeployed +
2390          " isMultiplyDeployed=" + isMultiplyDeployed +
2391          " deploymentMatchesMeta=" + deploymentMatchesMeta +
2392          " shouldBeDeployed=" + shouldBeDeployed);
2393    }
2394  }
2395
2396  /**
2397   * Checks tables integrity. Goes over all regions and scans the tables.
2398   * Collects all the pieces for each table and checks if there are missing,
2399   * repeated or overlapping ones.
2400   * @throws IOException
2401   */
2402  SortedMap<TableName, HbckTableInfo> checkIntegrity() throws IOException {
2403    tablesInfo = new TreeMap<>();
2404    LOG.debug("There are " + regionInfoMap.size() + " region info entries");
2405    for (HbckRegionInfo hbi : regionInfoMap.values()) {
2406      // Check only valid, working regions
2407      if (hbi.getMetaEntry() == null) {
2408        // this assumes that consistency check has run loadMetaEntry
2409        Path p = hbi.getHdfsRegionDir();
2410        if (p == null) {
2411          errors.report("No regioninfo in Meta or HDFS. " + hbi);
2412        }
2413
2414        // TODO test.
2415        continue;
2416      }
2417      if (hbi.getMetaEntry().regionServer == null) {
2418        errors.detail("Skipping region because no region server: " + hbi);
2419        continue;
2420      }
2421      if (hbi.getMetaEntry().isOffline()) {
2422        errors.detail("Skipping region because it is offline: " + hbi);
2423        continue;
2424      }
2425      if (hbi.containsOnlyHdfsEdits()) {
2426        errors.detail("Skipping region because it only contains edits" + hbi);
2427        continue;
2428      }
2429
2430      // Missing regionDir or over-deployment is checked elsewhere. Include
2431      // these cases in modTInfo, so we can evaluate those regions as part of
2432      // the region chain in META
2433      //if (hbi.foundRegionDir == null) continue;
2434      //if (hbi.deployedOn.size() != 1) continue;
2435      if (hbi.getDeployedOn().isEmpty()) {
2436        continue;
2437      }
2438
2439      // We should be safe here
2440      TableName tableName = hbi.getMetaEntry().getTable();
2441      HbckTableInfo modTInfo = tablesInfo.get(tableName);
2442      if (modTInfo == null) {
2443        modTInfo = new HbckTableInfo(tableName, this);
2444      }
2445      for (ServerName server : hbi.getDeployedOn()) {
2446        modTInfo.addServer(server);
2447      }
2448
2449      if (!hbi.isSkipChecks()) {
2450        modTInfo.addRegionInfo(hbi);
2451      }
2452
2453      tablesInfo.put(tableName, modTInfo);
2454    }
2455
2456    loadTableInfosForTablesWithNoRegion();
2457
2458    logParallelMerge();
2459    for (HbckTableInfo tInfo : tablesInfo.values()) {
2460      TableIntegrityErrorHandler handler = tInfo.new IntegrityFixSuggester(tInfo, errors);
2461      if (!tInfo.checkRegionChain(handler)) {
2462        errors.report("Found inconsistency in table " + tInfo.getName());
2463      }
2464    }
2465    return tablesInfo;
2466  }
2467
2468  /** Loads table info's for tables that may not have been included, since there are no
2469   * regions reported for the table, but table dir is there in hdfs
2470   */
2471  private void loadTableInfosForTablesWithNoRegion() throws IOException {
2472    Map<String, TableDescriptor> allTables = new FSTableDescriptors(getConf()).getAll();
2473    for (TableDescriptor htd : allTables.values()) {
2474      if (checkMetaOnly && !htd.isMetaTable()) {
2475        continue;
2476      }
2477
2478      TableName tableName = htd.getTableName();
2479      if (isTableIncluded(tableName) && !tablesInfo.containsKey(tableName)) {
2480        HbckTableInfo tableInfo = new HbckTableInfo(tableName, this);
2481        tableInfo.htds.add(htd);
2482        tablesInfo.put(htd.getTableName(), tableInfo);
2483      }
2484    }
2485  }
2486
2487  /**
2488   * Merge hdfs data by moving from contained HbckRegionInfo into targetRegionDir.
2489   * @return number of file move fixes done to merge regions.
2490   */
2491  public int mergeRegionDirs(Path targetRegionDir, HbckRegionInfo contained) throws IOException {
2492    int fileMoves = 0;
2493    String thread = Thread.currentThread().getName();
2494    LOG.debug("[" + thread + "] Contained region dir after close and pause");
2495    debugLsr(contained.getHdfsRegionDir());
2496
2497    // rename the contained into the container.
2498    FileSystem fs = targetRegionDir.getFileSystem(getConf());
2499    FileStatus[] dirs = null;
2500    try {
2501      dirs = fs.listStatus(contained.getHdfsRegionDir());
2502    } catch (FileNotFoundException fnfe) {
2503      // region we are attempting to merge in is not present!  Since this is a merge, there is
2504      // no harm skipping this region if it does not exist.
2505      if (!fs.exists(contained.getHdfsRegionDir())) {
2506        LOG.warn("[" + thread + "] HDFS region dir " + contained.getHdfsRegionDir()
2507            + " is missing. Assuming already sidelined or moved.");
2508      } else {
2509        sidelineRegionDir(fs, contained);
2510      }
2511      return fileMoves;
2512    }
2513
2514    if (dirs == null) {
2515      if (!fs.exists(contained.getHdfsRegionDir())) {
2516        LOG.warn("[" + thread + "] HDFS region dir " + contained.getHdfsRegionDir()
2517            + " already sidelined.");
2518      } else {
2519        sidelineRegionDir(fs, contained);
2520      }
2521      return fileMoves;
2522    }
2523
2524    for (FileStatus cf : dirs) {
2525      Path src = cf.getPath();
2526      Path dst =  new Path(targetRegionDir, src.getName());
2527
2528      if (src.getName().equals(HRegionFileSystem.REGION_INFO_FILE)) {
2529        // do not copy the old .regioninfo file.
2530        continue;
2531      }
2532
2533      if (src.getName().equals(HConstants.HREGION_OLDLOGDIR_NAME)) {
2534        // do not copy the .oldlogs files
2535        continue;
2536      }
2537
2538      LOG.info("[" + thread + "] Moving files from " + src + " into containing region " + dst);
2539      // FileSystem.rename is inconsistent with directories -- if the
2540      // dst (foo/a) exists and is a dir, and the src (foo/b) is a dir,
2541      // it moves the src into the dst dir resulting in (foo/a/b).  If
2542      // the dst does not exist, and the src a dir, src becomes dst. (foo/b)
2543      for (FileStatus hfile : fs.listStatus(src)) {
2544        boolean success = fs.rename(hfile.getPath(), dst);
2545        if (success) {
2546          fileMoves++;
2547        }
2548      }
2549      LOG.debug("[" + thread + "] Sideline directory contents:");
2550      debugLsr(targetRegionDir);
2551    }
2552
2553    // if all success.
2554    sidelineRegionDir(fs, contained);
2555    LOG.info("[" + thread + "] Sidelined region dir "+ contained.getHdfsRegionDir() + " into " +
2556        getSidelineDir());
2557    debugLsr(contained.getHdfsRegionDir());
2558
2559    return fileMoves;
2560  }
2561
2562
2563  static class WorkItemOverlapMerge implements Callable<Void> {
2564    private TableIntegrityErrorHandler handler;
2565    Collection<HbckRegionInfo> overlapgroup;
2566
2567    WorkItemOverlapMerge(Collection<HbckRegionInfo> overlapgroup,
2568        TableIntegrityErrorHandler handler) {
2569      this.handler = handler;
2570      this.overlapgroup = overlapgroup;
2571    }
2572
2573    @Override
2574    public Void call() throws Exception {
2575      handler.handleOverlapGroup(overlapgroup);
2576      return null;
2577    }
2578  }
2579
2580  /**
2581   * Return a list of user-space table names whose metadata have not been
2582   * modified in the last few milliseconds specified by timelag
2583   * if any of the REGIONINFO_QUALIFIER, SERVER_QUALIFIER, STARTCODE_QUALIFIER,
2584   * SPLITA_QUALIFIER, SPLITB_QUALIFIER have not changed in the last
2585   * milliseconds specified by timelag, then the table is a candidate to be returned.
2586   * @return tables that have not been modified recently
2587   * @throws IOException if an error is encountered
2588   */
2589  TableDescriptor[] getTables(AtomicInteger numSkipped) {
2590    List<TableName> tableNames = new ArrayList<>();
2591    long now = EnvironmentEdgeManager.currentTime();
2592
2593    for (HbckRegionInfo hbi : regionInfoMap.values()) {
2594      HbckRegionInfo.MetaEntry info = hbi.getMetaEntry();
2595
2596      // if the start key is zero, then we have found the first region of a table.
2597      // pick only those tables that were not modified in the last few milliseconds.
2598      if (info != null && info.getStartKey().length == 0 && !info.isMetaRegion()) {
2599        if (info.modTime + timelag < now) {
2600          tableNames.add(info.getTable());
2601        } else {
2602          numSkipped.incrementAndGet(); // one more in-flux table
2603        }
2604      }
2605    }
2606    return getTableDescriptors(tableNames);
2607  }
2608
2609  TableDescriptor[] getTableDescriptors(List<TableName> tableNames) {
2610      LOG.info("getTableDescriptors == tableNames => " + tableNames);
2611    try (Connection conn = ConnectionFactory.createConnection(getConf());
2612        Admin admin = conn.getAdmin()) {
2613      List<TableDescriptor> tds = admin.listTableDescriptors(tableNames);
2614      return tds.toArray(new TableDescriptor[tds.size()]);
2615    } catch (IOException e) {
2616      LOG.debug("Exception getting table descriptors", e);
2617    }
2618    return new TableDescriptor[0];
2619  }
2620
2621  /**
2622   * Gets the entry in regionInfo corresponding to the the given encoded
2623   * region name. If the region has not been seen yet, a new entry is added
2624   * and returned.
2625   */
2626  private synchronized HbckRegionInfo getOrCreateInfo(String name) {
2627    HbckRegionInfo hbi = regionInfoMap.get(name);
2628    if (hbi == null) {
2629      hbi = new HbckRegionInfo(null);
2630      regionInfoMap.put(name, hbi);
2631    }
2632    return hbi;
2633  }
2634
2635  private void checkAndFixReplication() throws ReplicationException {
2636    ReplicationChecker checker = new ReplicationChecker(getConf(), zkw, errors);
2637    checker.checkUnDeletedQueues();
2638
2639    if (checker.hasUnDeletedQueues() && this.fixReplication) {
2640      checker.fixUnDeletedQueues();
2641      setShouldRerun();
2642    }
2643  }
2644
2645  /**
2646    * Check values in regionInfo for hbase:meta
2647    * Check if zero or more than one regions with hbase:meta are found.
2648    * If there are inconsistencies (i.e. zero or more than one regions
2649    * pretend to be holding the hbase:meta) try to fix that and report an error.
2650    * @throws IOException from HBaseFsckRepair functions
2651    * @throws KeeperException
2652    * @throws InterruptedException
2653    */
2654  boolean checkMetaRegion() throws IOException, KeeperException, InterruptedException {
2655    Map<Integer, HbckRegionInfo> metaRegions = new HashMap<>();
2656    for (HbckRegionInfo value : regionInfoMap.values()) {
2657      if (value.getMetaEntry() != null && value.getMetaEntry().isMetaRegion()) {
2658        metaRegions.put(value.getReplicaId(), value);
2659      }
2660    }
2661    int metaReplication = admin.getDescriptor(TableName.META_TABLE_NAME)
2662        .getRegionReplication();
2663    boolean noProblem = true;
2664    // There will be always entries in regionInfoMap corresponding to hbase:meta & its replicas
2665    // Check the deployed servers. It should be exactly one server for each replica.
2666    for (int i = 0; i < metaReplication; i++) {
2667      HbckRegionInfo metaHbckRegionInfo = metaRegions.remove(i);
2668      List<ServerName> servers = new ArrayList<>();
2669      if (metaHbckRegionInfo != null) {
2670        servers = metaHbckRegionInfo.getDeployedOn();
2671      }
2672      if (servers.size() != 1) {
2673        noProblem = false;
2674        if (servers.isEmpty()) {
2675          assignMetaReplica(i);
2676        } else if (servers.size() > 1) {
2677          errors
2678          .reportError(ERROR_CODE.MULTI_META_REGION, "hbase:meta, replicaId " +
2679                       metaHbckRegionInfo.getReplicaId() + " is found on more than one region.");
2680          if (shouldFixAssignments()) {
2681            errors.print("Trying to fix a problem with hbase:meta, replicaId " +
2682                metaHbckRegionInfo.getReplicaId() + "..");
2683            setShouldRerun();
2684            // try fix it (treat is a dupe assignment)
2685            HBaseFsckRepair
2686                .fixMultiAssignment(connection, metaHbckRegionInfo.getMetaEntry(), servers);
2687          }
2688        }
2689      }
2690    }
2691    // unassign whatever is remaining in metaRegions. They are excess replicas.
2692    for (Map.Entry<Integer, HbckRegionInfo> entry : metaRegions.entrySet()) {
2693      noProblem = false;
2694      errors.reportError(ERROR_CODE.SHOULD_NOT_BE_DEPLOYED,
2695          "hbase:meta replicas are deployed in excess. Configured " + metaReplication +
2696          ", deployed " + metaRegions.size());
2697      if (shouldFixAssignments()) {
2698        errors.print("Trying to undeploy excess replica, replicaId: " + entry.getKey() +
2699            " of hbase:meta..");
2700        setShouldRerun();
2701        unassignMetaReplica(entry.getValue());
2702      }
2703    }
2704    // if noProblem is false, rerun hbck with hopefully fixed META
2705    // if noProblem is true, no errors, so continue normally
2706    return noProblem;
2707  }
2708
2709  private void unassignMetaReplica(HbckRegionInfo hi)
2710      throws IOException, InterruptedException, KeeperException {
2711    undeployRegions(hi);
2712    ZKUtil
2713        .deleteNode(zkw, zkw.getZNodePaths().getZNodeForReplica(hi.getMetaEntry().getReplicaId()));
2714  }
2715
2716  private void assignMetaReplica(int replicaId)
2717      throws IOException, KeeperException, InterruptedException {
2718    errors.reportError(ERROR_CODE.NO_META_REGION, "hbase:meta, replicaId " +
2719        replicaId +" is not found on any region.");
2720    if (shouldFixAssignments()) {
2721      errors.print("Trying to fix a problem with hbase:meta..");
2722      setShouldRerun();
2723      // try to fix it (treat it as unassigned region)
2724      RegionInfo h = RegionReplicaUtil.getRegionInfoForReplica(
2725          RegionInfoBuilder.FIRST_META_REGIONINFO, replicaId);
2726      HBaseFsckRepair.fixUnassigned(admin, h);
2727      HBaseFsckRepair.waitUntilAssigned(admin, h);
2728    }
2729  }
2730
2731  /**
2732   * Scan hbase:meta, adding all regions found to the regionInfo map.
2733   * @throws IOException if an error is encountered
2734   */
2735  boolean loadMetaEntries() throws IOException {
2736    MetaTableAccessor.Visitor visitor = new MetaTableAccessor.Visitor() {
2737      int countRecord = 1;
2738
2739      // comparator to sort KeyValues with latest modtime
2740      final Comparator<Cell> comp = new Comparator<Cell>() {
2741        @Override
2742        public int compare(Cell k1, Cell k2) {
2743          return Long.compare(k1.getTimestamp(), k2.getTimestamp());
2744        }
2745      };
2746
2747      @Override
2748      public boolean visit(Result result) throws IOException {
2749        try {
2750
2751          // record the latest modification of this META record
2752          long ts =  Collections.max(result.listCells(), comp).getTimestamp();
2753          RegionLocations rl = MetaTableAccessor.getRegionLocations(result);
2754          if (rl == null) {
2755            emptyRegionInfoQualifiers.add(result);
2756            errors.reportError(ERROR_CODE.EMPTY_META_CELL,
2757              "Empty REGIONINFO_QUALIFIER found in hbase:meta");
2758            return true;
2759          }
2760          ServerName sn = null;
2761          if (rl.getRegionLocation(RegionInfo.DEFAULT_REPLICA_ID) == null ||
2762              rl.getRegionLocation(RegionInfo.DEFAULT_REPLICA_ID).getRegion() == null) {
2763            emptyRegionInfoQualifiers.add(result);
2764            errors.reportError(ERROR_CODE.EMPTY_META_CELL,
2765              "Empty REGIONINFO_QUALIFIER found in hbase:meta");
2766            return true;
2767          }
2768          RegionInfo hri = rl.getRegionLocation(RegionInfo.DEFAULT_REPLICA_ID).getRegion();
2769          if (!(isTableIncluded(hri.getTable())
2770              || hri.isMetaRegion())) {
2771            return true;
2772          }
2773          PairOfSameType<RegionInfo> daughters = MetaTableAccessor.getDaughterRegions(result);
2774          for (HRegionLocation h : rl.getRegionLocations()) {
2775            if (h == null || h.getRegion() == null) {
2776              continue;
2777            }
2778            sn = h.getServerName();
2779            hri = h.getRegion();
2780
2781            HbckRegionInfo.MetaEntry m = null;
2782            if (hri.getReplicaId() == RegionInfo.DEFAULT_REPLICA_ID) {
2783              m = new HbckRegionInfo.MetaEntry(hri, sn, ts, daughters.getFirst(),
2784                  daughters.getSecond());
2785            } else {
2786              m = new HbckRegionInfo.MetaEntry(hri, sn, ts, null, null);
2787            }
2788            HbckRegionInfo previous = regionInfoMap.get(hri.getEncodedName());
2789            if (previous == null) {
2790              regionInfoMap.put(hri.getEncodedName(), new HbckRegionInfo(m));
2791            } else if (previous.getMetaEntry() == null) {
2792              previous.setMetaEntry(m);
2793            } else {
2794              throw new IOException("Two entries in hbase:meta are same " + previous);
2795            }
2796          }
2797          List<RegionInfo> mergeParents = MetaTableAccessor.getMergeRegions(result.rawCells());
2798          if (mergeParents != null) {
2799            for (RegionInfo mergeRegion : mergeParents) {
2800              if (mergeRegion != null) {
2801                // This region is already being merged
2802                HbckRegionInfo hbInfo = getOrCreateInfo(mergeRegion.getEncodedName());
2803                hbInfo.setMerged(true);
2804              }
2805            }
2806          }
2807
2808          // show proof of progress to the user, once for every 100 records.
2809          if (countRecord % 100 == 0) {
2810            errors.progress();
2811          }
2812          countRecord++;
2813          return true;
2814        } catch (RuntimeException e) {
2815          LOG.error("Result=" + result);
2816          throw e;
2817        }
2818      }
2819    };
2820    if (!checkMetaOnly) {
2821      // Scan hbase:meta to pick up user regions
2822      MetaTableAccessor.fullScanRegions(connection, visitor);
2823    }
2824
2825    errors.print("");
2826    return true;
2827  }
2828
2829  /**
2830   * Prints summary of all tables found on the system.
2831   */
2832  private void printTableSummary(SortedMap<TableName, HbckTableInfo> tablesInfo) {
2833    StringBuilder sb = new StringBuilder();
2834    int numOfSkippedRegions;
2835    errors.print("Summary:");
2836    for (HbckTableInfo tInfo : tablesInfo.values()) {
2837      numOfSkippedRegions = (skippedRegions.containsKey(tInfo.getName())) ?
2838          skippedRegions.get(tInfo.getName()).size() : 0;
2839
2840      if (errors.tableHasErrors(tInfo)) {
2841        errors.print("Table " + tInfo.getName() + " is inconsistent.");
2842      } else if (numOfSkippedRegions > 0){
2843        errors.print("Table " + tInfo.getName() + " is okay (with "
2844          + numOfSkippedRegions + " skipped regions).");
2845      }
2846      else {
2847        errors.print("Table " + tInfo.getName() + " is okay.");
2848      }
2849      errors.print("    Number of regions: " + tInfo.getNumRegions());
2850      if (numOfSkippedRegions > 0) {
2851        Set<String> skippedRegionStrings = skippedRegions.get(tInfo.getName());
2852        System.out.println("    Number of skipped regions: " + numOfSkippedRegions);
2853        System.out.println("      List of skipped regions:");
2854        for(String sr : skippedRegionStrings) {
2855          System.out.println("        " + sr);
2856        }
2857      }
2858      sb.setLength(0); // clear out existing buffer, if any.
2859      sb.append("    Deployed on: ");
2860      for (ServerName server : tInfo.deployedOn) {
2861        sb.append(" " + server.toString());
2862      }
2863      errors.print(sb.toString());
2864    }
2865  }
2866
2867  static HbckErrorReporter getErrorReporter(final Configuration conf)
2868      throws ClassNotFoundException {
2869    Class<? extends HbckErrorReporter> reporter =
2870        conf.getClass("hbasefsck.errorreporter", PrintingErrorReporter.class,
2871            HbckErrorReporter.class);
2872    return ReflectionUtils.newInstance(reporter, conf);
2873  }
2874
2875  static class PrintingErrorReporter implements HbckErrorReporter {
2876    public int errorCount = 0;
2877    private int showProgress;
2878    // How frequently calls to progress() will create output
2879    private static final int progressThreshold = 100;
2880
2881    Set<HbckTableInfo> errorTables = new HashSet<>();
2882
2883    // for use by unit tests to verify which errors were discovered
2884    private ArrayList<ERROR_CODE> errorList = new ArrayList<>();
2885
2886    @Override
2887    public void clear() {
2888      errorTables.clear();
2889      errorList.clear();
2890      errorCount = 0;
2891    }
2892
2893    @Override
2894    public synchronized void reportError(ERROR_CODE errorCode, String message) {
2895      if (errorCode == ERROR_CODE.WRONG_USAGE) {
2896        System.err.println(message);
2897        return;
2898      }
2899
2900      errorList.add(errorCode);
2901      if (!summary) {
2902        System.out.println("ERROR: " + message);
2903      }
2904      errorCount++;
2905      showProgress = 0;
2906    }
2907
2908    @Override
2909    public synchronized void reportError(ERROR_CODE errorCode, String message,
2910        HbckTableInfo table) {
2911      errorTables.add(table);
2912      reportError(errorCode, message);
2913    }
2914
2915    @Override
2916    public synchronized void reportError(ERROR_CODE errorCode, String message, HbckTableInfo table,
2917                                         HbckRegionInfo info) {
2918      errorTables.add(table);
2919      String reference = "(region " + info.getRegionNameAsString() + ")";
2920      reportError(errorCode, reference + " " + message);
2921    }
2922
2923    @Override
2924    public synchronized void reportError(ERROR_CODE errorCode, String message, HbckTableInfo table,
2925                                         HbckRegionInfo info1, HbckRegionInfo info2) {
2926      errorTables.add(table);
2927      String reference = "(regions " + info1.getRegionNameAsString()
2928          + " and " + info2.getRegionNameAsString() + ")";
2929      reportError(errorCode, reference + " " + message);
2930    }
2931
2932    @Override
2933    public synchronized void reportError(String message) {
2934      reportError(ERROR_CODE.UNKNOWN, message);
2935    }
2936
2937    /**
2938     * Report error information, but do not increment the error count.  Intended for cases
2939     * where the actual error would have been reported previously.
2940     * @param message
2941     */
2942    @Override
2943    public synchronized void report(String message) {
2944      if (! summary) {
2945        System.out.println("ERROR: " + message);
2946      }
2947      showProgress = 0;
2948    }
2949
2950    @Override
2951    public synchronized int summarize() {
2952      System.out.println(Integer.toString(errorCount) +
2953                         " inconsistencies detected.");
2954      if (errorCount == 0) {
2955        System.out.println("Status: OK");
2956        return 0;
2957      } else {
2958        System.out.println("Status: INCONSISTENT");
2959        return -1;
2960      }
2961    }
2962
2963    @Override
2964    public ArrayList<ERROR_CODE> getErrorList() {
2965      return errorList;
2966    }
2967
2968    @Override
2969    public synchronized void print(String message) {
2970      if (!summary) {
2971        System.out.println(message);
2972      }
2973    }
2974
2975    @Override
2976    public boolean tableHasErrors(HbckTableInfo table) {
2977      return errorTables.contains(table);
2978    }
2979
2980    @Override
2981    public void resetErrors() {
2982      errorCount = 0;
2983    }
2984
2985    @Override
2986    public synchronized void detail(String message) {
2987      if (details) {
2988        System.out.println(message);
2989      }
2990      showProgress = 0;
2991    }
2992
2993    @Override
2994    public synchronized void progress() {
2995      if (showProgress++ == progressThreshold) {
2996        if (!summary) {
2997          System.out.print(".");
2998        }
2999        showProgress = 0;
3000      }
3001    }
3002  }
3003
3004  /**
3005   * Contact a region server and get all information from it
3006   */
3007  static class WorkItemRegion implements Callable<Void> {
3008    private final HBaseFsck hbck;
3009    private final ServerName rsinfo;
3010    private final HbckErrorReporter errors;
3011    private final Connection connection;
3012
3013    WorkItemRegion(HBaseFsck hbck, ServerName info, HbckErrorReporter errors,
3014        Connection connection) {
3015      this.hbck = hbck;
3016      this.rsinfo = info;
3017      this.errors = errors;
3018      this.connection = connection;
3019    }
3020
3021    @Override
3022    public synchronized Void call() throws IOException {
3023      errors.progress();
3024      try {
3025        // list all online regions from this region server
3026        List<RegionInfo> regions = connection.getAdmin().getRegions(rsinfo);
3027        regions = filterRegions(regions);
3028
3029        if (details) {
3030          errors.detail(
3031            "RegionServer: " + rsinfo.getServerName() + " number of regions: " + regions.size());
3032          for (RegionInfo rinfo : regions) {
3033            errors.detail("  " + rinfo.getRegionNameAsString() + " id: " + rinfo.getRegionId() +
3034              " encoded_name: " + rinfo.getEncodedName() + " start: " +
3035              Bytes.toStringBinary(rinfo.getStartKey()) + " end: " +
3036              Bytes.toStringBinary(rinfo.getEndKey()));
3037          }
3038        }
3039
3040        // check to see if the existence of this region matches the region in META
3041        for (RegionInfo r : regions) {
3042          HbckRegionInfo hbi = hbck.getOrCreateInfo(r.getEncodedName());
3043          hbi.addServer(r, rsinfo);
3044        }
3045      } catch (IOException e) { // unable to connect to the region server.
3046        errors.reportError(ERROR_CODE.RS_CONNECT_FAILURE,
3047          "RegionServer: " + rsinfo.getServerName() + " Unable to fetch region information. " + e);
3048        throw e;
3049      }
3050      return null;
3051    }
3052
3053    private List<RegionInfo> filterRegions(List<RegionInfo> regions) {
3054      List<RegionInfo> ret = Lists.newArrayList();
3055      for (RegionInfo hri : regions) {
3056        if (hri.isMetaRegion() || (!hbck.checkMetaOnly
3057            && hbck.isTableIncluded(hri.getTable()))) {
3058          ret.add(hri);
3059        }
3060      }
3061      return ret;
3062    }
3063  }
3064
3065  /**
3066   * Contact hdfs and get all information about specified table directory into
3067   * regioninfo list.
3068   */
3069  class WorkItemHdfsDir implements Callable<Void> {
3070    private FileStatus tableDir;
3071    private HbckErrorReporter errors;
3072    private FileSystem fs;
3073
3074    WorkItemHdfsDir(FileSystem fs, HbckErrorReporter errors, FileStatus status) {
3075      this.fs = fs;
3076      this.tableDir = status;
3077      this.errors = errors;
3078    }
3079
3080    @Override
3081    public synchronized Void call() throws InterruptedException, ExecutionException {
3082      final Vector<Exception> exceptions = new Vector<>();
3083
3084      try {
3085        final FileStatus[] regionDirs = fs.listStatus(tableDir.getPath());
3086        final List<Future<?>> futures = new ArrayList<>(regionDirs.length);
3087
3088        for (final FileStatus regionDir : regionDirs) {
3089          errors.progress();
3090          final String encodedName = regionDir.getPath().getName();
3091          // ignore directories that aren't hexadecimal
3092          if (!encodedName.toLowerCase(Locale.ROOT).matches("[0-9a-f]+")) {
3093            continue;
3094          }
3095
3096          if (!exceptions.isEmpty()) {
3097            break;
3098          }
3099
3100          futures.add(executor.submit(new Runnable() {
3101            @Override
3102            public void run() {
3103              try {
3104                LOG.debug("Loading region info from hdfs:"+ regionDir.getPath());
3105
3106                Path regioninfoFile = new Path(regionDir.getPath(), HRegionFileSystem.REGION_INFO_FILE);
3107                boolean regioninfoFileExists = fs.exists(regioninfoFile);
3108
3109                if (!regioninfoFileExists) {
3110                  // As tables become larger it is more and more likely that by the time you
3111                  // reach a given region that it will be gone due to region splits/merges.
3112                  if (!fs.exists(regionDir.getPath())) {
3113                    LOG.warn("By the time we tried to process this region dir it was already gone: "
3114                        + regionDir.getPath());
3115                    return;
3116                  }
3117                }
3118
3119                HbckRegionInfo hbi = HBaseFsck.this.getOrCreateInfo(encodedName);
3120                HbckRegionInfo.HdfsEntry he = new HbckRegionInfo.HdfsEntry();
3121                synchronized (hbi) {
3122                  if (hbi.getHdfsRegionDir() != null) {
3123                    errors.print("Directory " + encodedName + " duplicate??" +
3124                                 hbi.getHdfsRegionDir());
3125                  }
3126
3127                  he.regionDir = regionDir.getPath();
3128                  he.regionDirModTime = regionDir.getModificationTime();
3129                  he.hdfsRegioninfoFilePresent = regioninfoFileExists;
3130                  // we add to orphan list when we attempt to read .regioninfo
3131
3132                  // Set a flag if this region contains only edits
3133                  // This is special case if a region is left after split
3134                  he.hdfsOnlyEdits = true;
3135                  FileStatus[] subDirs = fs.listStatus(regionDir.getPath());
3136                  Path ePath = WALSplitUtil.getRegionDirRecoveredEditsDir(regionDir.getPath());
3137                  for (FileStatus subDir : subDirs) {
3138                    errors.progress();
3139                    String sdName = subDir.getPath().getName();
3140                    if (!sdName.startsWith(".") && !sdName.equals(ePath.getName())) {
3141                      he.hdfsOnlyEdits = false;
3142                      break;
3143                    }
3144                  }
3145                  hbi.setHdfsEntry(he);
3146                }
3147              } catch (Exception e) {
3148                LOG.error("Could not load region dir", e);
3149                exceptions.add(e);
3150              }
3151            }
3152          }));
3153        }
3154
3155        // Ensure all pending tasks are complete (or that we run into an exception)
3156        for (Future<?> f : futures) {
3157          if (!exceptions.isEmpty()) {
3158            break;
3159          }
3160          try {
3161            f.get();
3162          } catch (ExecutionException e) {
3163            LOG.error("Unexpected exec exception!  Should've been caught already.  (Bug?)", e);
3164            // Shouldn't happen, we already logged/caught any exceptions in the Runnable
3165          }
3166        }
3167      } catch (IOException e) {
3168        LOG.error("Cannot execute WorkItemHdfsDir for " + tableDir, e);
3169        exceptions.add(e);
3170      } finally {
3171        if (!exceptions.isEmpty()) {
3172          errors.reportError(ERROR_CODE.RS_CONNECT_FAILURE, "Table Directory: "
3173              + tableDir.getPath().getName()
3174              + " Unable to fetch all HDFS region information. ");
3175          // Just throw the first exception as an indication something bad happened
3176          // Don't need to propagate all the exceptions, we already logged them all anyway
3177          throw new ExecutionException("First exception in WorkItemHdfsDir", exceptions.firstElement());
3178        }
3179      }
3180      return null;
3181    }
3182  }
3183
3184  /**
3185   * Contact hdfs and get all information about specified table directory into
3186   * regioninfo list.
3187   */
3188  static class WorkItemHdfsRegionInfo implements Callable<Void> {
3189    private HbckRegionInfo hbi;
3190    private HBaseFsck hbck;
3191    private HbckErrorReporter errors;
3192
3193    WorkItemHdfsRegionInfo(HbckRegionInfo hbi, HBaseFsck hbck, HbckErrorReporter errors) {
3194      this.hbi = hbi;
3195      this.hbck = hbck;
3196      this.errors = errors;
3197    }
3198
3199    @Override
3200    public synchronized Void call() throws IOException {
3201      // only load entries that haven't been loaded yet.
3202      if (hbi.getHdfsHRI() == null) {
3203        try {
3204          errors.progress();
3205          hbi.loadHdfsRegioninfo(hbck.getConf());
3206        } catch (IOException ioe) {
3207          String msg = "Orphan region in HDFS: Unable to load .regioninfo from table "
3208              + hbi.getTableName() + " in hdfs dir "
3209              + hbi.getHdfsRegionDir()
3210              + "!  It may be an invalid format or version file.  Treating as "
3211              + "an orphaned regiondir.";
3212          errors.reportError(ERROR_CODE.ORPHAN_HDFS_REGION, msg);
3213          try {
3214            hbck.debugLsr(hbi.getHdfsRegionDir());
3215          } catch (IOException ioe2) {
3216            LOG.error("Unable to read directory " + hbi.getHdfsRegionDir(), ioe2);
3217            throw ioe2;
3218          }
3219          hbck.orphanHdfsDirs.add(hbi);
3220          throw ioe;
3221        }
3222      }
3223      return null;
3224    }
3225  }
3226
3227  /**
3228   * Display the full report from fsck. This displays all live and dead region
3229   * servers, and all known regions.
3230   */
3231  public static void setDisplayFullReport() {
3232    details = true;
3233  }
3234
3235  public static boolean shouldDisplayFullReport() {
3236    return details;
3237  }
3238
3239  /**
3240   * Set exclusive mode.
3241   */
3242  public static void setForceExclusive() {
3243    forceExclusive = true;
3244  }
3245
3246  /**
3247   * Only one instance of hbck can modify HBase at a time.
3248   */
3249  public boolean isExclusive() {
3250    return fixAny || forceExclusive;
3251  }
3252
3253  /**
3254   * Set summary mode.
3255   * Print only summary of the tables and status (OK or INCONSISTENT)
3256   */
3257  static void setSummary() {
3258    summary = true;
3259  }
3260
3261  /**
3262   * Set hbase:meta check mode.
3263   * Print only info about hbase:meta table deployment/state
3264   */
3265  void setCheckMetaOnly() {
3266    checkMetaOnly = true;
3267  }
3268
3269  /**
3270   * Set region boundaries check mode.
3271   */
3272  void setRegionBoundariesCheck() {
3273    checkRegionBoundaries = true;
3274  }
3275
3276  /**
3277   * Set replication fix mode.
3278   */
3279  public void setFixReplication(boolean shouldFix) {
3280    fixReplication = shouldFix;
3281    fixAny |= shouldFix;
3282  }
3283
3284  public void setCleanReplicationBarrier(boolean shouldClean) {
3285    cleanReplicationBarrier = shouldClean;
3286  }
3287
3288  /**
3289   * Check if we should rerun fsck again. This checks if we've tried to
3290   * fix something and we should rerun fsck tool again.
3291   * Display the full report from fsck. This displays all live and dead
3292   * region servers, and all known regions.
3293   */
3294  void setShouldRerun() {
3295    rerun = true;
3296  }
3297
3298  public boolean shouldRerun() {
3299    return rerun;
3300  }
3301
3302  /**
3303   * Fix inconsistencies found by fsck. This should try to fix errors (if any)
3304   * found by fsck utility.
3305   */
3306  public void setFixAssignments(boolean shouldFix) {
3307    fixAssignments = shouldFix;
3308    fixAny |= shouldFix;
3309  }
3310
3311  boolean shouldFixAssignments() {
3312    return fixAssignments;
3313  }
3314
3315  public void setFixMeta(boolean shouldFix) {
3316    fixMeta = shouldFix;
3317    fixAny |= shouldFix;
3318  }
3319
3320  boolean shouldFixMeta() {
3321    return fixMeta;
3322  }
3323
3324  public void setFixEmptyMetaCells(boolean shouldFix) {
3325    fixEmptyMetaCells = shouldFix;
3326    fixAny |= shouldFix;
3327  }
3328
3329  boolean shouldFixEmptyMetaCells() {
3330    return fixEmptyMetaCells;
3331  }
3332
3333  public void setCheckHdfs(boolean checking) {
3334    checkHdfs = checking;
3335  }
3336
3337  boolean shouldCheckHdfs() {
3338    return checkHdfs;
3339  }
3340
3341  public void setFixHdfsHoles(boolean shouldFix) {
3342    fixHdfsHoles = shouldFix;
3343    fixAny |= shouldFix;
3344  }
3345
3346  boolean shouldFixHdfsHoles() {
3347    return fixHdfsHoles;
3348  }
3349
3350  public void setFixTableOrphans(boolean shouldFix) {
3351    fixTableOrphans = shouldFix;
3352    fixAny |= shouldFix;
3353  }
3354
3355  boolean shouldFixTableOrphans() {
3356    return fixTableOrphans;
3357  }
3358
3359  public void setFixHdfsOverlaps(boolean shouldFix) {
3360    fixHdfsOverlaps = shouldFix;
3361    fixAny |= shouldFix;
3362  }
3363
3364  boolean shouldFixHdfsOverlaps() {
3365    return fixHdfsOverlaps;
3366  }
3367
3368  public void setFixHdfsOrphans(boolean shouldFix) {
3369    fixHdfsOrphans = shouldFix;
3370    fixAny |= shouldFix;
3371  }
3372
3373  boolean shouldFixHdfsOrphans() {
3374    return fixHdfsOrphans;
3375  }
3376
3377  public void setFixVersionFile(boolean shouldFix) {
3378    fixVersionFile = shouldFix;
3379    fixAny |= shouldFix;
3380  }
3381
3382  public boolean shouldFixVersionFile() {
3383    return fixVersionFile;
3384  }
3385
3386  public void setSidelineBigOverlaps(boolean sbo) {
3387    this.sidelineBigOverlaps = sbo;
3388  }
3389
3390  public boolean shouldSidelineBigOverlaps() {
3391    return sidelineBigOverlaps;
3392  }
3393
3394  public void setFixSplitParents(boolean shouldFix) {
3395    fixSplitParents = shouldFix;
3396    fixAny |= shouldFix;
3397  }
3398
3399  public void setRemoveParents(boolean shouldFix) {
3400    removeParents = shouldFix;
3401    fixAny |= shouldFix;
3402  }
3403
3404  boolean shouldFixSplitParents() {
3405    return fixSplitParents;
3406  }
3407
3408  boolean shouldRemoveParents() {
3409    return removeParents;
3410  }
3411
3412  public void setFixReferenceFiles(boolean shouldFix) {
3413    fixReferenceFiles = shouldFix;
3414    fixAny |= shouldFix;
3415  }
3416
3417  boolean shouldFixReferenceFiles() {
3418    return fixReferenceFiles;
3419  }
3420
3421  public void setFixHFileLinks(boolean shouldFix) {
3422    fixHFileLinks = shouldFix;
3423    fixAny |= shouldFix;
3424  }
3425
3426  boolean shouldFixHFileLinks() {
3427    return fixHFileLinks;
3428  }
3429
3430  public boolean shouldIgnorePreCheckPermission() {
3431    return !fixAny || ignorePreCheckPermission;
3432  }
3433
3434  public void setIgnorePreCheckPermission(boolean ignorePreCheckPermission) {
3435    this.ignorePreCheckPermission = ignorePreCheckPermission;
3436  }
3437
3438  /**
3439   * @param mm maximum number of regions to merge into a single region.
3440   */
3441  public void setMaxMerge(int mm) {
3442    this.maxMerge = mm;
3443  }
3444
3445  public int getMaxMerge() {
3446    return maxMerge;
3447  }
3448
3449  public void setMaxOverlapsToSideline(int mo) {
3450    this.maxOverlapsToSideline = mo;
3451  }
3452
3453  public int getMaxOverlapsToSideline() {
3454    return maxOverlapsToSideline;
3455  }
3456
3457  /**
3458   * Only check/fix tables specified by the list,
3459   * Empty list means all tables are included.
3460   */
3461  boolean isTableIncluded(TableName table) {
3462    return (tablesIncluded.isEmpty()) || tablesIncluded.contains(table);
3463  }
3464
3465  public void includeTable(TableName table) {
3466    tablesIncluded.add(table);
3467  }
3468
3469  Set<TableName> getIncludedTables() {
3470    return new HashSet<>(tablesIncluded);
3471  }
3472
3473  /**
3474   * We are interested in only those tables that have not changed their state in
3475   * hbase:meta during the last few seconds specified by hbase.admin.fsck.timelag
3476   * @param seconds - the time in seconds
3477   */
3478  public void setTimeLag(long seconds) {
3479    timelag = seconds * 1000; // convert to milliseconds
3480  }
3481
3482  /**
3483   *
3484   * @param sidelineDir - HDFS path to sideline data
3485   */
3486  public void setSidelineDir(String sidelineDir) {
3487    this.sidelineDir = new Path(sidelineDir);
3488  }
3489
3490  protected HFileCorruptionChecker createHFileCorruptionChecker(boolean sidelineCorruptHFiles) throws IOException {
3491    return new HFileCorruptionChecker(getConf(), executor, sidelineCorruptHFiles);
3492  }
3493
3494  public HFileCorruptionChecker getHFilecorruptionChecker() {
3495    return hfcc;
3496  }
3497
3498  public void setHFileCorruptionChecker(HFileCorruptionChecker hfcc) {
3499    this.hfcc = hfcc;
3500  }
3501
3502  public void setRetCode(int code) {
3503    this.retcode = code;
3504  }
3505
3506  public int getRetCode() {
3507    return retcode;
3508  }
3509
3510  protected HBaseFsck printUsageAndExit() {
3511    StringWriter sw = new StringWriter(2048);
3512    PrintWriter out = new PrintWriter(sw);
3513    out.println("");
3514    out.println("-----------------------------------------------------------------------");
3515    out.println("NOTE: As of HBase version 2.0, the hbck tool is significantly changed.");
3516    out.println("In general, all Read-Only options are supported and can be be used");
3517    out.println("safely. Most -fix/ -repair options are NOT supported. Please see usage");
3518    out.println("below for details on which options are not supported.");
3519    out.println("-----------------------------------------------------------------------");
3520    out.println("");
3521    out.println("Usage: fsck [opts] {only tables}");
3522    out.println(" where [opts] are:");
3523    out.println("   -help Display help options (this)");
3524    out.println("   -details Display full report of all regions.");
3525    out.println("   -timelag <timeInSeconds>  Process only regions that " +
3526                       " have not experienced any metadata updates in the last " +
3527                       " <timeInSeconds> seconds.");
3528    out.println("   -sleepBeforeRerun <timeInSeconds> Sleep this many seconds" +
3529        " before checking if the fix worked if run with -fix");
3530    out.println("   -summary Print only summary of the tables and status.");
3531    out.println("   -metaonly Only check the state of the hbase:meta table.");
3532    out.println("   -sidelineDir <hdfs://> HDFS path to backup existing meta.");
3533    out.println("   -boundaries Verify that regions boundaries are the same between META and store files.");
3534    out.println("   -exclusive Abort if another hbck is exclusive or fixing.");
3535
3536    out.println("");
3537    out.println("  Datafile Repair options: (expert features, use with caution!)");
3538    out.println("   -checkCorruptHFiles     Check all Hfiles by opening them to make sure they are valid");
3539    out.println("   -sidelineCorruptHFiles  Quarantine corrupted HFiles.  implies -checkCorruptHFiles");
3540
3541    out.println("");
3542    out.println(" Replication options");
3543    out.println("   -fixReplication   Deletes replication queues for removed peers");
3544
3545    out.println("");
3546    out.println("  Metadata Repair options supported as of version 2.0: (expert features, use with caution!)");
3547    out.println("   -fixVersionFile   Try to fix missing hbase.version file in hdfs.");
3548    out.println("   -fixReferenceFiles  Try to offline lingering reference store files");
3549    out.println("   -fixHFileLinks  Try to offline lingering HFileLinks");
3550    out.println("   -noHdfsChecking   Don't load/check region info from HDFS."
3551        + " Assumes hbase:meta region info is good. Won't check/fix any HDFS issue, e.g. hole, orphan, or overlap");
3552    out.println("   -ignorePreCheckPermission  ignore filesystem permission pre-check");
3553
3554    out.println("");
3555    out.println("NOTE: Following options are NOT supported as of HBase version 2.0+.");
3556    out.println("");
3557    out.println("  UNSUPPORTED Metadata Repair options: (expert features, use with caution!)");
3558    out.println("   -fix              Try to fix region assignments.  This is for backwards compatiblity");
3559    out.println("   -fixAssignments   Try to fix region assignments.  Replaces the old -fix");
3560    out.println("   -fixMeta          Try to fix meta problems.  This assumes HDFS region info is good.");
3561    out.println("   -fixHdfsHoles     Try to fix region holes in hdfs.");
3562    out.println("   -fixHdfsOrphans   Try to fix region dirs with no .regioninfo file in hdfs");
3563    out.println("   -fixTableOrphans  Try to fix table dirs with no .tableinfo file in hdfs (online mode only)");
3564    out.println("   -fixHdfsOverlaps  Try to fix region overlaps in hdfs.");
3565    out.println("   -maxMerge <n>     When fixing region overlaps, allow at most <n> regions to merge. (n=" + DEFAULT_MAX_MERGE +" by default)");
3566    out.println("   -sidelineBigOverlaps  When fixing region overlaps, allow to sideline big overlaps");
3567    out.println("   -maxOverlapsToSideline <n>  When fixing region overlaps, allow at most <n> regions to sideline per group. (n=" + DEFAULT_OVERLAPS_TO_SIDELINE +" by default)");
3568    out.println("   -fixSplitParents  Try to force offline split parents to be online.");
3569    out.println("   -removeParents    Try to offline and sideline lingering parents and keep daughter regions.");
3570    out.println("   -fixEmptyMetaCells  Try to fix hbase:meta entries not referencing any region"
3571        + " (empty REGIONINFO_QUALIFIER rows)");
3572
3573    out.println("");
3574    out.println("  UNSUPPORTED Metadata Repair shortcuts");
3575    out.println("   -repair           Shortcut for -fixAssignments -fixMeta -fixHdfsHoles " +
3576        "-fixHdfsOrphans -fixHdfsOverlaps -fixVersionFile -sidelineBigOverlaps -fixReferenceFiles" +
3577        "-fixHFileLinks");
3578    out.println("   -repairHoles      Shortcut for -fixAssignments -fixMeta -fixHdfsHoles");
3579    out.println("");
3580    out.println(" Replication options");
3581    out.println("   -fixReplication   Deletes replication queues for removed peers");
3582    out.println("   -cleanReplicationBrarier [tableName] clean the replication barriers " +
3583        "of a specified table, tableName is required");
3584    out.flush();
3585    errors.reportError(ERROR_CODE.WRONG_USAGE, sw.toString());
3586
3587    setRetCode(-2);
3588    return this;
3589  }
3590
3591  /**
3592   * Main program
3593   *
3594   * @param args
3595   * @throws Exception
3596   */
3597  public static void main(String[] args) throws Exception {
3598    // create a fsck object
3599    Configuration conf = HBaseConfiguration.create();
3600    Path hbasedir = FSUtils.getRootDir(conf);
3601    URI defaultFs = hbasedir.getFileSystem(conf).getUri();
3602    FSUtils.setFsDefault(conf, new Path(defaultFs));
3603    int ret = ToolRunner.run(new HBaseFsckTool(conf), args);
3604    System.exit(ret);
3605  }
3606
3607  /**
3608   * This is a Tool wrapper that gathers -Dxxx=yyy configuration settings from the command line.
3609   */
3610  static class HBaseFsckTool extends Configured implements Tool {
3611    HBaseFsckTool(Configuration conf) { super(conf); }
3612    @Override
3613    public int run(String[] args) throws Exception {
3614      HBaseFsck hbck = new HBaseFsck(getConf());
3615      hbck.exec(hbck.executor, args);
3616      hbck.close();
3617      return hbck.getRetCode();
3618    }
3619  }
3620
3621  public HBaseFsck exec(ExecutorService exec, String[] args)
3622      throws KeeperException, IOException, InterruptedException, ReplicationException {
3623    long sleepBeforeRerun = DEFAULT_SLEEP_BEFORE_RERUN;
3624
3625    boolean checkCorruptHFiles = false;
3626    boolean sidelineCorruptHFiles = false;
3627
3628    // Process command-line args.
3629    for (int i = 0; i < args.length; i++) {
3630      String cmd = args[i];
3631      if (cmd.equals("-help") || cmd.equals("-h")) {
3632        return printUsageAndExit();
3633      } else if (cmd.equals("-details")) {
3634        setDisplayFullReport();
3635      } else if (cmd.equals("-exclusive")) {
3636        setForceExclusive();
3637      } else if (cmd.equals("-timelag")) {
3638        if (i == args.length - 1) {
3639          errors.reportError(ERROR_CODE.WRONG_USAGE, "HBaseFsck: -timelag needs a value.");
3640          return printUsageAndExit();
3641        }
3642        try {
3643          long timelag = Long.parseLong(args[++i]);
3644          setTimeLag(timelag);
3645        } catch (NumberFormatException e) {
3646          errors.reportError(ERROR_CODE.WRONG_USAGE, "-timelag needs a numeric value.");
3647          return printUsageAndExit();
3648        }
3649      } else if (cmd.equals("-sleepBeforeRerun")) {
3650        if (i == args.length - 1) {
3651          errors.reportError(ERROR_CODE.WRONG_USAGE,
3652            "HBaseFsck: -sleepBeforeRerun needs a value.");
3653          return printUsageAndExit();
3654        }
3655        try {
3656          sleepBeforeRerun = Long.parseLong(args[++i]);
3657        } catch (NumberFormatException e) {
3658          errors.reportError(ERROR_CODE.WRONG_USAGE, "-sleepBeforeRerun needs a numeric value.");
3659          return printUsageAndExit();
3660        }
3661      } else if (cmd.equals("-sidelineDir")) {
3662        if (i == args.length - 1) {
3663          errors.reportError(ERROR_CODE.WRONG_USAGE, "HBaseFsck: -sidelineDir needs a value.");
3664          return printUsageAndExit();
3665        }
3666        setSidelineDir(args[++i]);
3667      } else if (cmd.equals("-fix")) {
3668        errors.reportError(ERROR_CODE.WRONG_USAGE,
3669          "This option is deprecated, please use  -fixAssignments instead.");
3670        setFixAssignments(true);
3671      } else if (cmd.equals("-fixAssignments")) {
3672        setFixAssignments(true);
3673      } else if (cmd.equals("-fixMeta")) {
3674        setFixMeta(true);
3675      } else if (cmd.equals("-noHdfsChecking")) {
3676        setCheckHdfs(false);
3677      } else if (cmd.equals("-fixHdfsHoles")) {
3678        setFixHdfsHoles(true);
3679      } else if (cmd.equals("-fixHdfsOrphans")) {
3680        setFixHdfsOrphans(true);
3681      } else if (cmd.equals("-fixTableOrphans")) {
3682        setFixTableOrphans(true);
3683      } else if (cmd.equals("-fixHdfsOverlaps")) {
3684        setFixHdfsOverlaps(true);
3685      } else if (cmd.equals("-fixVersionFile")) {
3686        setFixVersionFile(true);
3687      } else if (cmd.equals("-sidelineBigOverlaps")) {
3688        setSidelineBigOverlaps(true);
3689      } else if (cmd.equals("-fixSplitParents")) {
3690        setFixSplitParents(true);
3691      } else if (cmd.equals("-removeParents")) {
3692        setRemoveParents(true);
3693      } else if (cmd.equals("-ignorePreCheckPermission")) {
3694        setIgnorePreCheckPermission(true);
3695      } else if (cmd.equals("-checkCorruptHFiles")) {
3696        checkCorruptHFiles = true;
3697      } else if (cmd.equals("-sidelineCorruptHFiles")) {
3698        sidelineCorruptHFiles = true;
3699      } else if (cmd.equals("-fixReferenceFiles")) {
3700        setFixReferenceFiles(true);
3701      } else if (cmd.equals("-fixHFileLinks")) {
3702        setFixHFileLinks(true);
3703      } else if (cmd.equals("-fixEmptyMetaCells")) {
3704        setFixEmptyMetaCells(true);
3705      } else if (cmd.equals("-repair")) {
3706        // this attempts to merge overlapping hdfs regions, needs testing
3707        // under load
3708        setFixHdfsHoles(true);
3709        setFixHdfsOrphans(true);
3710        setFixMeta(true);
3711        setFixAssignments(true);
3712        setFixHdfsOverlaps(true);
3713        setFixVersionFile(true);
3714        setSidelineBigOverlaps(true);
3715        setFixSplitParents(false);
3716        setCheckHdfs(true);
3717        setFixReferenceFiles(true);
3718        setFixHFileLinks(true);
3719      } else if (cmd.equals("-repairHoles")) {
3720        // this will make all missing hdfs regions available but may lose data
3721        setFixHdfsHoles(true);
3722        setFixHdfsOrphans(false);
3723        setFixMeta(true);
3724        setFixAssignments(true);
3725        setFixHdfsOverlaps(false);
3726        setSidelineBigOverlaps(false);
3727        setFixSplitParents(false);
3728        setCheckHdfs(true);
3729      } else if (cmd.equals("-maxOverlapsToSideline")) {
3730        if (i == args.length - 1) {
3731          errors.reportError(ERROR_CODE.WRONG_USAGE,
3732            "-maxOverlapsToSideline needs a numeric value argument.");
3733          return printUsageAndExit();
3734        }
3735        try {
3736          int maxOverlapsToSideline = Integer.parseInt(args[++i]);
3737          setMaxOverlapsToSideline(maxOverlapsToSideline);
3738        } catch (NumberFormatException e) {
3739          errors.reportError(ERROR_CODE.WRONG_USAGE,
3740            "-maxOverlapsToSideline needs a numeric value argument.");
3741          return printUsageAndExit();
3742        }
3743      } else if (cmd.equals("-maxMerge")) {
3744        if (i == args.length - 1) {
3745          errors.reportError(ERROR_CODE.WRONG_USAGE,
3746            "-maxMerge needs a numeric value argument.");
3747          return printUsageAndExit();
3748        }
3749        try {
3750          int maxMerge = Integer.parseInt(args[++i]);
3751          setMaxMerge(maxMerge);
3752        } catch (NumberFormatException e) {
3753          errors.reportError(ERROR_CODE.WRONG_USAGE,
3754            "-maxMerge needs a numeric value argument.");
3755          return printUsageAndExit();
3756        }
3757      } else if (cmd.equals("-summary")) {
3758        setSummary();
3759      } else if (cmd.equals("-metaonly")) {
3760        setCheckMetaOnly();
3761      } else if (cmd.equals("-boundaries")) {
3762        setRegionBoundariesCheck();
3763      } else if (cmd.equals("-fixReplication")) {
3764        setFixReplication(true);
3765      } else if (cmd.equals("-cleanReplicationBarrier")) {
3766        setCleanReplicationBarrier(true);
3767        if(args[++i].startsWith("-")){
3768          printUsageAndExit();
3769        }
3770        setCleanReplicationBarrierTable(args[i]);
3771      } else if (cmd.startsWith("-")) {
3772        errors.reportError(ERROR_CODE.WRONG_USAGE, "Unrecognized option:" + cmd);
3773        return printUsageAndExit();
3774      } else {
3775        includeTable(TableName.valueOf(cmd));
3776        errors.print("Allow checking/fixes for table: " + cmd);
3777      }
3778    }
3779
3780    errors.print("HBaseFsck command line options: " + StringUtils.join(args, " "));
3781
3782    // pre-check current user has FS write permission or not
3783    try {
3784      preCheckPermission();
3785    } catch (AccessDeniedException ace) {
3786      Runtime.getRuntime().exit(-1);
3787    } catch (IOException ioe) {
3788      Runtime.getRuntime().exit(-1);
3789    }
3790
3791    // do the real work of hbck
3792    connect();
3793
3794    // after connecting to server above, we have server version
3795    // check if unsupported option is specified based on server version
3796    if (!isOptionsSupported(args)) {
3797      return printUsageAndExit();
3798    }
3799
3800    try {
3801      // if corrupt file mode is on, first fix them since they may be opened later
3802      if (checkCorruptHFiles || sidelineCorruptHFiles) {
3803        LOG.info("Checking all hfiles for corruption");
3804        HFileCorruptionChecker hfcc = createHFileCorruptionChecker(sidelineCorruptHFiles);
3805        setHFileCorruptionChecker(hfcc); // so we can get result
3806        Collection<TableName> tables = getIncludedTables();
3807        Collection<Path> tableDirs = new ArrayList<>();
3808        Path rootdir = FSUtils.getRootDir(getConf());
3809        if (tables.size() > 0) {
3810          for (TableName t : tables) {
3811            tableDirs.add(FSUtils.getTableDir(rootdir, t));
3812          }
3813        } else {
3814          tableDirs = FSUtils.getTableDirs(FSUtils.getCurrentFileSystem(getConf()), rootdir);
3815        }
3816        hfcc.checkTables(tableDirs);
3817        hfcc.report(errors);
3818      }
3819
3820      // check and fix table integrity, region consistency.
3821      int code = onlineHbck();
3822      setRetCode(code);
3823      // If we have changed the HBase state it is better to run hbck again
3824      // to see if we haven't broken something else in the process.
3825      // We run it only once more because otherwise we can easily fall into
3826      // an infinite loop.
3827      if (shouldRerun()) {
3828        try {
3829          LOG.info("Sleeping " + sleepBeforeRerun + "ms before re-checking after fix...");
3830          Thread.sleep(sleepBeforeRerun);
3831        } catch (InterruptedException ie) {
3832          LOG.warn("Interrupted while sleeping");
3833          return this;
3834        }
3835        // Just report
3836        setFixAssignments(false);
3837        setFixMeta(false);
3838        setFixHdfsHoles(false);
3839        setFixHdfsOverlaps(false);
3840        setFixVersionFile(false);
3841        setFixTableOrphans(false);
3842        errors.resetErrors();
3843        code = onlineHbck();
3844        setRetCode(code);
3845      }
3846    } finally {
3847      IOUtils.closeQuietly(this);
3848    }
3849    return this;
3850  }
3851
3852  private boolean isOptionsSupported(String[] args) {
3853    boolean result = true;
3854    String hbaseServerVersion = status.getHBaseVersion();
3855    if (VersionInfo.compareVersion("2.any.any", hbaseServerVersion) < 0) {
3856      // Process command-line args.
3857      for (String arg : args) {
3858        if (unsupportedOptionsInV2.contains(arg)) {
3859          errors.reportError(ERROR_CODE.UNSUPPORTED_OPTION,
3860              "option '" + arg + "' is not " + "supportted!");
3861          result = false;
3862          break;
3863        }
3864      }
3865    }
3866    return result;
3867  }
3868
3869  public void setCleanReplicationBarrierTable(String cleanReplicationBarrierTable) {
3870    this.cleanReplicationBarrierTable = TableName.valueOf(cleanReplicationBarrierTable);
3871  }
3872
3873  public void cleanReplicationBarrier() throws IOException {
3874    if (!cleanReplicationBarrier || cleanReplicationBarrierTable == null) {
3875      return;
3876    }
3877    if (cleanReplicationBarrierTable.isSystemTable()) {
3878      errors.reportError(ERROR_CODE.INVALID_TABLE,
3879        "invalid table: " + cleanReplicationBarrierTable);
3880      return;
3881    }
3882
3883    boolean isGlobalScope = false;
3884    try {
3885      isGlobalScope = admin.getDescriptor(cleanReplicationBarrierTable).hasGlobalReplicationScope();
3886    } catch (TableNotFoundException e) {
3887      LOG.info("we may need to clean some erroneous data due to bugs");
3888    }
3889
3890    if (isGlobalScope) {
3891      errors.reportError(ERROR_CODE.INVALID_TABLE,
3892        "table's replication scope is global: " + cleanReplicationBarrierTable);
3893      return;
3894    }
3895    List<byte[]> regionNames = new ArrayList<>();
3896    Scan barrierScan = new Scan();
3897    barrierScan.setCaching(100);
3898    barrierScan.addFamily(HConstants.REPLICATION_BARRIER_FAMILY);
3899    barrierScan
3900        .withStartRow(MetaTableAccessor.getTableStartRowForMeta(cleanReplicationBarrierTable,
3901          MetaTableAccessor.QueryType.REGION))
3902        .withStopRow(MetaTableAccessor.getTableStopRowForMeta(cleanReplicationBarrierTable,
3903          MetaTableAccessor.QueryType.REGION));
3904    Result result;
3905    try (ResultScanner scanner = meta.getScanner(barrierScan)) {
3906      while ((result = scanner.next()) != null) {
3907        regionNames.add(result.getRow());
3908      }
3909    }
3910    if (regionNames.size() <= 0) {
3911      errors.reportError(ERROR_CODE.INVALID_TABLE,
3912        "there is no barriers of this table: " + cleanReplicationBarrierTable);
3913      return;
3914    }
3915    ReplicationQueueStorage queueStorage =
3916        ReplicationStorageFactory.getReplicationQueueStorage(zkw, getConf());
3917    List<ReplicationPeerDescription> peerDescriptions = admin.listReplicationPeers();
3918    if (peerDescriptions != null && peerDescriptions.size() > 0) {
3919      List<String> peers = peerDescriptions.stream()
3920          .filter(peerConfig -> ReplicationUtils.contains(peerConfig.getPeerConfig(),
3921            cleanReplicationBarrierTable))
3922          .map(peerConfig -> peerConfig.getPeerId()).collect(Collectors.toList());
3923      try {
3924        List<String> batch = new ArrayList<>();
3925        for (String peer : peers) {
3926          for (byte[] regionName : regionNames) {
3927            batch.add(RegionInfo.encodeRegionName(regionName));
3928            if (batch.size() % 100 == 0) {
3929              queueStorage.removeLastSequenceIds(peer, batch);
3930              batch.clear();
3931            }
3932          }
3933          if (batch.size() > 0) {
3934            queueStorage.removeLastSequenceIds(peer, batch);
3935            batch.clear();
3936          }
3937        }
3938      } catch (ReplicationException re) {
3939        throw new IOException(re);
3940      }
3941    }
3942    for (byte[] regionName : regionNames) {
3943      meta.delete(new Delete(regionName).addFamily(HConstants.REPLICATION_BARRIER_FAMILY));
3944    }
3945    setShouldRerun();
3946  }
3947
3948  /**
3949   * ls -r for debugging purposes
3950   */
3951  void debugLsr(Path p) throws IOException {
3952    debugLsr(getConf(), p, errors);
3953  }
3954
3955  /**
3956   * ls -r for debugging purposes
3957   */
3958  public static void debugLsr(Configuration conf,
3959      Path p) throws IOException {
3960    debugLsr(conf, p, new PrintingErrorReporter());
3961  }
3962
3963  /**
3964   * ls -r for debugging purposes
3965   */
3966  public static void debugLsr(Configuration conf,
3967      Path p, HbckErrorReporter errors) throws IOException {
3968    if (!LOG.isDebugEnabled() || p == null) {
3969      return;
3970    }
3971    FileSystem fs = p.getFileSystem(conf);
3972
3973    if (!fs.exists(p)) {
3974      // nothing
3975      return;
3976    }
3977    errors.print(p.toString());
3978
3979    if (fs.isFile(p)) {
3980      return;
3981    }
3982
3983    if (fs.getFileStatus(p).isDirectory()) {
3984      FileStatus[] fss= fs.listStatus(p);
3985      for (FileStatus status : fss) {
3986        debugLsr(conf, status.getPath(), errors);
3987      }
3988    }
3989  }
3990}