View Javadoc

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