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  
19  package org.apache.hadoop.hbase.snapshot;
20  
21  import java.io.IOException;
22  import java.io.FileNotFoundException;
23  import java.net.URI;
24  import java.text.SimpleDateFormat;
25  import java.util.ArrayList;
26  import java.util.Date;
27  import java.util.List;
28  import java.util.concurrent.atomic.AtomicInteger;
29  import java.util.concurrent.atomic.AtomicLong;
30  
31  import org.apache.commons.logging.Log;
32  import org.apache.commons.logging.LogFactory;
33  
34  import org.apache.hadoop.fs.Path;
35  import org.apache.hadoop.fs.FileStatus;
36  import org.apache.hadoop.fs.FileSystem;
37  import org.apache.hadoop.hbase.classification.InterfaceAudience;
38  import org.apache.hadoop.hbase.classification.InterfaceStability;
39  import org.apache.hadoop.conf.Configured;
40  import org.apache.hadoop.hbase.HRegionInfo;
41  import org.apache.hadoop.hbase.TableName;
42  import org.apache.hadoop.util.StringUtils;
43  import org.apache.hadoop.util.Tool;
44  import org.apache.hadoop.util.ToolRunner;
45  
46  import org.apache.hadoop.conf.Configuration;
47  import org.apache.hadoop.hbase.HBaseConfiguration;
48  import org.apache.hadoop.hbase.io.HFileLink;
49  import org.apache.hadoop.hbase.io.WALLink;
50  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
51  import org.apache.hadoop.hbase.protobuf.generated.SnapshotProtos.SnapshotRegionManifest;
52  import org.apache.hadoop.hbase.util.FSUtils;
53  
54  /**
55   * Tool for dumping snapshot information.
56   * <ol>
57   * <li> Table Descriptor
58   * <li> Snapshot creation time, type, format version, ...
59   * <li> List of hfiles and wals
60   * <li> Stats about hfiles and logs sizes, percentage of shared with the source table, ...
61   * </ol>
62   */
63  @InterfaceAudience.Public
64  @InterfaceStability.Evolving
65  public final class SnapshotInfo extends Configured implements Tool {
66    private static final Log LOG = LogFactory.getLog(SnapshotInfo.class);
67  
68    /**
69     * Statistics about the snapshot
70     * <ol>
71     * <li> How many store files and logs are in the archive
72     * <li> How many store files and logs are shared with the table
73     * <li> Total store files and logs size and shared amount
74     * </ol>
75     */
76    public static class SnapshotStats {
77      /** Information about the file referenced by the snapshot */
78      static class FileInfo {
79        private final boolean corrupted;
80        private final boolean inArchive;
81        private final long size;
82  
83        FileInfo(final boolean inArchive, final long size, final boolean corrupted) {
84          this.corrupted = corrupted;
85          this.inArchive = inArchive;
86          this.size = size;
87        }
88  
89        /** @return true if the file is in the archive */
90        public boolean inArchive() {
91          return this.inArchive;
92        }
93  
94        /** @return true if the file is corrupted */
95        public boolean isCorrupted() {
96          return this.corrupted;
97        }
98  
99        /** @return true if the file is missing */
100       public boolean isMissing() {
101         return this.size < 0;
102       }
103 
104       /** @return the file size */
105       public long getSize() {
106         return this.size;
107       }
108 
109       String getStateToString() {
110         if (isCorrupted()) return "CORRUPTED";
111         if (isMissing()) return "NOT FOUND";
112         if (inArchive()) return "archive";
113         return null;
114       }
115     }
116 
117     private AtomicInteger hfilesArchiveCount = new AtomicInteger();
118     private AtomicInteger hfilesCorrupted = new AtomicInteger();
119     private AtomicInteger hfilesMissing = new AtomicInteger();
120     private AtomicInteger hfilesCount = new AtomicInteger();
121     private AtomicInteger hfilesMobCount = new AtomicInteger();
122     private AtomicInteger logsMissing = new AtomicInteger();
123     private AtomicInteger logsCount = new AtomicInteger();
124     private AtomicLong hfilesArchiveSize = new AtomicLong();
125     private AtomicLong hfilesSize = new AtomicLong();
126     private AtomicLong hfilesMobSize = new AtomicLong();
127     private AtomicLong logSize = new AtomicLong();
128 
129     private final SnapshotDescription snapshot;
130     private final TableName snapshotTable;
131     private final Configuration conf;
132     private final FileSystem fs;
133 
134     SnapshotStats(final Configuration conf, final FileSystem fs, final SnapshotDescription snapshot)
135     {
136       this.snapshot = snapshot;
137       this.snapshotTable = TableName.valueOf(snapshot.getTable());
138       this.conf = conf;
139       this.fs = fs;
140     }
141 
142     /** @return the snapshot descriptor */
143     public SnapshotDescription getSnapshotDescription() {
144       return this.snapshot;
145     }
146 
147     /** @return true if the snapshot is corrupted */
148     public boolean isSnapshotCorrupted() {
149       return hfilesMissing.get() > 0 ||
150              logsMissing.get() > 0 ||
151              hfilesCorrupted.get() > 0;
152     }
153 
154     /** @return the number of available store files */
155     public int getStoreFilesCount() {
156       return hfilesCount.get() + hfilesArchiveCount.get() + hfilesMobCount.get();
157     }
158 
159     /** @return the number of available store files in the archive */
160     public int getArchivedStoreFilesCount() {
161       return hfilesArchiveCount.get();
162     }
163 
164     /** @return the number of available store files in the mob dir */
165     public int getMobStoreFilesCount() { return hfilesMobCount.get(); }
166 
167     /** @return the number of available log files */
168     public int getLogsCount() {
169       return logsCount.get();
170     }
171 
172     /** @return the number of missing store files */
173     public int getMissingStoreFilesCount() {
174       return hfilesMissing.get();
175     }
176 
177     /** @return the number of corrupted store files */
178     public int getCorruptedStoreFilesCount() {
179       return hfilesCorrupted.get();
180     }
181 
182     /** @return the number of missing log files */
183     public int getMissingLogsCount() {
184       return logsMissing.get();
185     }
186 
187     /** @return the total size of the store files referenced by the snapshot */
188     public long getStoreFilesSize() {
189       return hfilesSize.get() + hfilesArchiveSize.get() + hfilesMobSize.get();
190     }
191 
192     /** @return the total size of the store files shared */
193     public long getSharedStoreFilesSize() {
194       return hfilesSize.get();
195     }
196 
197     /** @return the total size of the store files in the archive */
198     public long getArchivedStoreFileSize() {
199       return hfilesArchiveSize.get();
200     }
201 
202     /** @return the total size of the store files in the mob store*/
203     public long getMobStoreFilesSize() { return hfilesMobSize.get(); }
204 
205     /** @return the percentage of the shared store files */
206     public float getSharedStoreFilePercentage() {
207       return ((float) hfilesSize.get() / (getStoreFilesSize())) * 100;
208     }
209 
210     /** @return the percentage of the mob store files */
211     public float getMobStoreFilePercentage() {
212       return ((float) hfilesMobSize.get() / (getStoreFilesSize())) * 100;
213     }
214 
215     /** @return the total log size */
216     public long getLogsSize() {
217       return logSize.get();
218     }
219 
220     /**
221      * Add the specified store file to the stats
222      * @param region region encoded Name
223      * @param family family name
224      * @param storeFile store file name
225      * @return the store file information
226      */
227     FileInfo addStoreFile(final HRegionInfo region, final String family,
228         final SnapshotRegionManifest.StoreFile storeFile) throws IOException {
229       HFileLink link = HFileLink.build(conf, snapshotTable, region.getEncodedName(),
230               family, storeFile.getName());
231       boolean isCorrupted = false;
232       boolean inArchive = false;
233       long size = -1;
234       try {
235         if ((inArchive = fs.exists(link.getArchivePath()))) {
236           size = fs.getFileStatus(link.getArchivePath()).getLen();
237           hfilesArchiveSize.addAndGet(size);
238           hfilesArchiveCount.incrementAndGet();
239         } else if (inArchive = fs.exists(link.getMobPath())) {
240           size = fs.getFileStatus(link.getMobPath()).getLen();
241           hfilesMobSize.addAndGet(size);
242           hfilesMobCount.incrementAndGet();
243         } else {
244           size = link.getFileStatus(fs).getLen();
245           hfilesSize.addAndGet(size);
246           hfilesCount.incrementAndGet();
247         }
248         isCorrupted = (storeFile.hasFileSize() && storeFile.getFileSize() != size);
249         if (isCorrupted) hfilesCorrupted.incrementAndGet();
250       } catch (FileNotFoundException e) {
251         hfilesMissing.incrementAndGet();
252       }
253       return new FileInfo(inArchive, size, isCorrupted);
254     }
255 
256     /**
257      * Add the specified log file to the stats
258      * @param server server name
259      * @param logfile log file name
260      * @return the log information
261      */
262     FileInfo addLogFile(final String server, final String logfile) throws IOException {
263       WALLink logLink = new WALLink(conf, server, logfile);
264       long size = -1;
265       try {
266         size = logLink.getFileStatus(fs).getLen();
267         logSize.addAndGet(size);
268         logsCount.incrementAndGet();
269       } catch (FileNotFoundException e) {
270         logsMissing.incrementAndGet();
271       }
272       return new FileInfo(false, size, false);
273     }
274   }
275 
276   private boolean printSizeInBytes = false;
277   private FileSystem fs;
278   private Path rootDir;
279 
280   private SnapshotManifest snapshotManifest;
281 
282   @Override
283   @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="REC_CATCH_EXCEPTION",
284     justification="Intentional")
285   public int run(String[] args) throws IOException, InterruptedException {
286     final Configuration conf = getConf();
287     boolean listSnapshots = false;
288     String snapshotName = null;
289     boolean showSchema = false;
290     boolean showFiles = false;
291     boolean showStats = false;
292 
293     // Process command line args
294     for (int i = 0; i < args.length; i++) {
295       String cmd = args[i];
296       try {
297         if (cmd.equals("-snapshot")) {
298           snapshotName = args[++i];
299         } else if (cmd.equals("-files")) {
300           showFiles = true;
301           showStats = true;
302         } else if (cmd.equals("-stats")) {
303           showStats = true;
304         } else if (cmd.equals("-schema")) {
305           showSchema = true;
306         } else if (cmd.equals("-remote-dir")) {
307           Path sourceDir = new Path(args[++i]);
308           URI defaultFs = sourceDir.getFileSystem(conf).getUri();
309           FSUtils.setFsDefault(conf, new Path(defaultFs));
310           FSUtils.setRootDir(conf, sourceDir);
311         } else if (cmd.equals("-list-snapshots")) {
312           listSnapshots = true;
313         } else if (cmd.equals("-size-in-bytes")) {
314           printSizeInBytes = true;
315         } else if (cmd.equals("-h") || cmd.equals("--help")) {
316           printUsageAndExit();
317         } else {
318           System.err.println("UNEXPECTED: " + cmd);
319           printUsageAndExit();
320         }
321       } catch (Exception e) {
322         printUsageAndExit(); // FindBugs: REC_CATCH_EXCEPTION
323       }
324     }
325 
326     // List Available Snapshots
327     if (listSnapshots) {
328       SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
329       System.out.printf("%-20s | %-20s | %s%n", "SNAPSHOT", "CREATION TIME", "TABLE NAME");
330       for (SnapshotDescription desc: getSnapshotList(conf)) {
331         System.out.printf("%-20s | %20s | %s%n",
332                           desc.getName(),
333                           df.format(new Date(desc.getCreationTime())),
334                           desc.getTable());
335       }
336       return 0;
337     }
338 
339     if (snapshotName == null) {
340       System.err.println("Missing snapshot name!");
341       printUsageAndExit();
342       return 1;
343     }
344 
345     rootDir = FSUtils.getRootDir(conf);
346     fs = FileSystem.get(rootDir.toUri(), conf);
347     LOG.debug("fs=" + fs.getUri().toString() + " root=" + rootDir);
348 
349     // Load snapshot information
350     if (!loadSnapshotInfo(snapshotName)) {
351       System.err.println("Snapshot '" + snapshotName + "' not found!");
352       return 1;
353     }
354 
355     printInfo();
356     if (showSchema) printSchema();
357     printFiles(showFiles, showStats);
358 
359     return 0;
360   }
361 
362   /**
363    * Load snapshot info and table descriptor for the specified snapshot
364    * @param snapshotName name of the snapshot to load
365    * @return false if snapshot is not found
366    */
367   private boolean loadSnapshotInfo(final String snapshotName) throws IOException {
368     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
369     if (!fs.exists(snapshotDir)) {
370       LOG.warn("Snapshot '" + snapshotName + "' not found in: " + snapshotDir);
371       return false;
372     }
373 
374     SnapshotDescription snapshotDesc = SnapshotDescriptionUtils.readSnapshotInfo(fs, snapshotDir);
375     snapshotManifest = SnapshotManifest.open(getConf(), fs, snapshotDir, snapshotDesc);
376     return true;
377   }
378 
379   /**
380    * Dump the {@link SnapshotDescription}
381    */
382   private void printInfo() {
383     SnapshotDescription snapshotDesc = snapshotManifest.getSnapshotDescription();
384     SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
385     System.out.println("Snapshot Info");
386     System.out.println("----------------------------------------");
387     System.out.println("   Name: " + snapshotDesc.getName());
388     System.out.println("   Type: " + snapshotDesc.getType());
389     System.out.println("  Table: " + snapshotDesc.getTable());
390     System.out.println(" Format: " + snapshotDesc.getVersion());
391     System.out.println("Created: " + df.format(new Date(snapshotDesc.getCreationTime())));
392     System.out.println();
393   }
394 
395   /**
396    * Dump the {@link HTableDescriptor}
397    */
398   private void printSchema() {
399     System.out.println("Table Descriptor");
400     System.out.println("----------------------------------------");
401     System.out.println(snapshotManifest.getTableDescriptor().toString());
402     System.out.println();
403   }
404 
405   /**
406    * Collect the hfiles and logs statistics of the snapshot and
407    * dump the file list if requested and the collected information.
408    */
409   private void printFiles(final boolean showFiles, final boolean showStats) throws IOException {
410     if (showFiles) {
411       System.out.println("Snapshot Files");
412       System.out.println("----------------------------------------");
413     }
414 
415     // Collect information about hfiles and logs in the snapshot
416     final SnapshotDescription snapshotDesc = snapshotManifest.getSnapshotDescription();
417     final String table = snapshotDesc.getTable();
418     final SnapshotStats stats = new SnapshotStats(this.getConf(), this.fs, snapshotDesc);
419     SnapshotReferenceUtil.concurrentVisitReferencedFiles(getConf(), fs, snapshotManifest,
420       new SnapshotReferenceUtil.SnapshotVisitor() {
421         @Override
422         public void storeFile(final HRegionInfo regionInfo, final String family,
423             final SnapshotRegionManifest.StoreFile storeFile) throws IOException {
424           if (storeFile.hasReference()) return;
425 
426           SnapshotStats.FileInfo info = stats.addStoreFile(regionInfo, family, storeFile);
427           if (showFiles) {
428             String state = info.getStateToString();
429             System.out.printf("%8s %s/%s/%s/%s %s%n",
430               (info.isMissing() ? "-" : fileSizeToString(info.getSize())),
431               table, regionInfo.getEncodedName(), family, storeFile.getName(),
432               state == null ? "" : "(" + state + ")");
433           }
434         }
435     });
436 
437     // Dump the stats
438     System.out.println();
439     if (stats.isSnapshotCorrupted()) {
440       System.out.println("**************************************************************");
441       System.out.printf("BAD SNAPSHOT: %d hfile(s) and %d log(s) missing.%n",
442         stats.getMissingStoreFilesCount(), stats.getMissingLogsCount());
443       System.out.printf("              %d hfile(s) corrupted.%n",
444         stats.getCorruptedStoreFilesCount());
445       System.out.println("**************************************************************");
446     }
447 
448     if (showStats) {
449       System.out.printf("%d HFiles (%d in archive, %d in mob storage), total size %s " +
450               "(%.2f%% %s shared with the source table, %.2f%% %s in mob dir)%n",
451         stats.getStoreFilesCount(), stats.getArchivedStoreFilesCount(),
452         stats.getMobStoreFilesCount(),
453         fileSizeToString(stats.getStoreFilesSize()),
454         stats.getSharedStoreFilePercentage(),
455         fileSizeToString(stats.getSharedStoreFilesSize()),
456         stats.getMobStoreFilePercentage(),
457         fileSizeToString(stats.getMobStoreFilesSize())
458       );
459       System.out.printf("%d Logs, total size %s%n",
460         stats.getLogsCount(), fileSizeToString(stats.getLogsSize()));
461       System.out.println();
462     }
463   }
464 
465   private String fileSizeToString(long size) {
466     return printSizeInBytes ? Long.toString(size) : StringUtils.humanReadableInt(size);
467   }
468 
469   private void printUsageAndExit() {
470     System.err.printf("Usage: bin/hbase %s [options]%n", getClass().getName());
471     System.err.println(" where [options] are:");
472     System.err.println("  -h|-help                Show this help and exit.");
473     System.err.println("  -remote-dir             Root directory that contains the snapshots.");
474     System.err.println("  -list-snapshots         List all the available snapshots and exit.");
475     System.err.println("  -size-in-bytes          Print the size of the files in bytes.");
476     System.err.println("  -snapshot NAME          Snapshot to examine.");
477     System.err.println("  -files                  Files and logs list.");
478     System.err.println("  -stats                  Files and logs stats.");
479     System.err.println("  -schema                 Describe the snapshotted table.");
480     System.err.println();
481     System.err.println("Examples:");
482     System.err.println("  hbase " + getClass() + " \\");
483     System.err.println("    -snapshot MySnapshot -files");
484     System.exit(1);
485   }
486 
487   /**
488    * Returns the snapshot stats
489    * @param conf the {@link Configuration} to use
490    * @param snapshot {@link SnapshotDescription} to get stats from
491    * @return the snapshot stats
492    */
493   public static SnapshotStats getSnapshotStats(final Configuration conf,
494       final SnapshotDescription snapshot) throws IOException {
495     Path rootDir = FSUtils.getRootDir(conf);
496     FileSystem fs = FileSystem.get(rootDir.toUri(), conf);
497     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshot, rootDir);
498     SnapshotManifest manifest = SnapshotManifest.open(conf, fs, snapshotDir, snapshot);
499     final SnapshotStats stats = new SnapshotStats(conf, fs, snapshot);
500     SnapshotReferenceUtil.concurrentVisitReferencedFiles(conf, fs, manifest,
501       new SnapshotReferenceUtil.SnapshotVisitor() {
502         @Override
503         public void storeFile(final HRegionInfo regionInfo, final String family,
504             final SnapshotRegionManifest.StoreFile storeFile) throws IOException {
505           if (!storeFile.hasReference()) {
506             stats.addStoreFile(regionInfo, family, storeFile);
507           }
508         }
509     });
510     return stats;
511   }
512 
513   /**
514    * Returns the list of available snapshots in the specified location
515    * @param conf the {@link Configuration} to use
516    * @return the list of snapshots
517    */
518   public static List<SnapshotDescription> getSnapshotList(final Configuration conf)
519       throws IOException {
520     Path rootDir = FSUtils.getRootDir(conf);
521     FileSystem fs = FileSystem.get(rootDir.toUri(), conf);
522     Path snapshotDir = SnapshotDescriptionUtils.getSnapshotsDir(rootDir);
523     FileStatus[] snapshots = fs.listStatus(snapshotDir,
524       new SnapshotDescriptionUtils.CompletedSnaphotDirectoriesFilter(fs));
525     List<SnapshotDescription> snapshotLists =
526       new ArrayList<SnapshotDescription>(snapshots.length);
527     for (FileStatus snapshotDirStat: snapshots) {
528       snapshotLists.add(SnapshotDescriptionUtils.readSnapshotInfo(fs, snapshotDirStat.getPath()));
529     }
530     return snapshotLists;
531   }
532 
533   /**
534    * The guts of the {@link #main} method.
535    * Call this method to avoid the {@link #main(String[])} System.exit.
536    * @param args
537    * @return errCode
538    * @throws Exception
539    */
540   static int innerMain(final String [] args) throws Exception {
541     return ToolRunner.run(HBaseConfiguration.create(), new SnapshotInfo(), args);
542   }
543 
544   public static void main(String[] args) throws Exception {
545      System.exit(innerMain(args));
546   }
547 }