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.FileNotFoundException;
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.Collections;
25  import java.util.Comparator;
26  import java.util.LinkedList;
27  import java.util.List;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  
32  import org.apache.hadoop.classification.InterfaceAudience;
33  import org.apache.hadoop.classification.InterfaceStability;
34  import org.apache.hadoop.conf.Configuration;
35  import org.apache.hadoop.conf.Configured;
36  import org.apache.hadoop.fs.FSDataInputStream;
37  import org.apache.hadoop.fs.FSDataOutputStream;
38  import org.apache.hadoop.fs.FileChecksum;
39  import org.apache.hadoop.fs.FileStatus;
40  import org.apache.hadoop.fs.FileSystem;
41  import org.apache.hadoop.fs.FileUtil;
42  import org.apache.hadoop.fs.Path;
43  import org.apache.hadoop.fs.permission.FsPermission;
44  import org.apache.hadoop.hbase.HBaseConfiguration;
45  import org.apache.hadoop.hbase.HConstants;
46  import org.apache.hadoop.hbase.io.HFileLink;
47  import org.apache.hadoop.hbase.io.HLogLink;
48  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
49  import org.apache.hadoop.hbase.regionserver.StoreFile;
50  import org.apache.hadoop.hbase.snapshot.ExportSnapshotException;
51  import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
52  import org.apache.hadoop.hbase.snapshot.SnapshotReferenceUtil;
53  import org.apache.hadoop.hbase.util.Bytes;
54  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
55  import org.apache.hadoop.hbase.util.FSUtils;
56  import org.apache.hadoop.hbase.util.Pair;
57  import org.apache.hadoop.io.NullWritable;
58  import org.apache.hadoop.io.SequenceFile;
59  import org.apache.hadoop.io.Text;
60  import org.apache.hadoop.mapreduce.Job;
61  import org.apache.hadoop.mapreduce.Mapper;
62  import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
63  import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
64  import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
65  import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
66  import org.apache.hadoop.util.StringUtils;
67  import org.apache.hadoop.util.Tool;
68  import org.apache.hadoop.util.ToolRunner;
69  
70  /**
71   * Export the specified snapshot to a given FileSystem.
72   *
73   * The .snapshot/name folder is copied to the destination cluster
74   * and then all the hfiles/hlogs are copied using a Map-Reduce Job in the .archive/ location.
75   * When everything is done, the second cluster can restore the snapshot.
76   */
77  @InterfaceAudience.Public
78  @InterfaceStability.Evolving
79  public final class ExportSnapshot extends Configured implements Tool {
80    private static final Log LOG = LogFactory.getLog(ExportSnapshot.class);
81  
82    private static final String CONF_TMP_DIR = "hbase.tmp.dir";
83    private static final String CONF_FILES_USER = "snapshot.export.files.attributes.user";
84    private static final String CONF_FILES_GROUP = "snapshot.export.files.attributes.group";
85    private static final String CONF_FILES_MODE = "snapshot.export.files.attributes.mode";
86    private static final String CONF_CHECKSUM_VERIFY = "snapshot.export.checksum.verify";
87    private static final String CONF_OUTPUT_ROOT = "snapshot.export.output.root";
88    private static final String CONF_INPUT_ROOT = "snapshot.export.input.root";
89  
90    private static final String INPUT_FOLDER_PREFIX = "export-files.";
91  
92    // Export Map-Reduce Counters, to keep track of the progress
93    public enum Counter { MISSING_FILES, COPY_FAILED, BYTES_EXPECTED, BYTES_COPIED };
94  
95    private static class ExportMapper extends Mapper<Text, NullWritable, NullWritable, NullWritable> {
96      final static int REPORT_SIZE = 1 * 1024 * 1024;
97      final static int BUFFER_SIZE = 64 * 1024;
98  
99      private boolean verifyChecksum;
100     private String filesGroup;
101     private String filesUser;
102     private short filesMode;
103 
104     private FileSystem outputFs;
105     private Path outputArchive;
106     private Path outputRoot;
107 
108     private FileSystem inputFs;
109     private Path inputArchive;
110     private Path inputRoot;
111 
112     @Override
113     public void setup(Context context) {
114       Configuration conf = context.getConfiguration();
115       verifyChecksum = conf.getBoolean(CONF_CHECKSUM_VERIFY, true);
116 
117       filesGroup = conf.get(CONF_FILES_GROUP);
118       filesUser = conf.get(CONF_FILES_USER);
119       filesMode = (short)conf.getInt(CONF_FILES_MODE, 0);
120       outputRoot = new Path(conf.get(CONF_OUTPUT_ROOT));
121       inputRoot = new Path(conf.get(CONF_INPUT_ROOT));
122 
123       inputArchive = new Path(inputRoot, HConstants.HFILE_ARCHIVE_DIRECTORY);
124       outputArchive = new Path(outputRoot, HConstants.HFILE_ARCHIVE_DIRECTORY);
125 
126       try {
127         inputFs = FileSystem.get(inputRoot.toUri(), conf);
128       } catch (IOException e) {
129         throw new RuntimeException("Could not get the input FileSystem with root=" + inputRoot, e);
130       }
131 
132       try {
133         outputFs = FileSystem.get(outputRoot.toUri(), conf);
134       } catch (IOException e) {
135         throw new RuntimeException("Could not get the output FileSystem with root="+ outputRoot, e);
136       }
137     }
138 
139     @Override
140     public void map(Text key, NullWritable value, Context context)
141         throws InterruptedException, IOException {
142       Path inputPath = new Path(key.toString());
143       Path outputPath = getOutputPath(inputPath);
144 
145       LOG.info("copy file input=" + inputPath + " output=" + outputPath);
146       if (copyFile(context, inputPath, outputPath)) {
147         LOG.info("copy completed for input=" + inputPath + " output=" + outputPath);
148       }
149     }
150 
151     /**
152      * Returns the location where the inputPath will be copied.
153      *  - hfiles are encoded as hfile links hfile-region-table
154      *  - logs are encoded as serverName/logName
155      */
156     private Path getOutputPath(final Path inputPath) throws IOException {
157       Path path;
158       if (HFileLink.isHFileLink(inputPath) || StoreFile.isReference(inputPath)) {
159         String family = inputPath.getParent().getName();
160         String table = HFileLink.getReferencedTableName(inputPath.getName());
161         String region = HFileLink.getReferencedRegionName(inputPath.getName());
162         String hfile = HFileLink.getReferencedHFileName(inputPath.getName());
163         path = new Path(table, new Path(region, new Path(family, hfile)));
164       } else if (isHLogLinkPath(inputPath)) {
165         String logName = inputPath.getName();
166         path = new Path(new Path(outputRoot, HConstants.HREGION_OLDLOGDIR_NAME), logName);
167       } else {
168         path = inputPath;
169       }
170       return new Path(outputArchive, path);
171     }
172 
173     private boolean copyFile(final Context context, final Path inputPath, final Path outputPath)
174         throws IOException {
175       FSDataInputStream in = openSourceFile(inputPath);
176       if (in == null) {
177         context.getCounter(Counter.MISSING_FILES).increment(1);
178         return false;
179       }
180 
181       try {
182         // Verify if the input file exists
183         FileStatus inputStat = getFileStatus(inputFs, inputPath);
184         if (inputStat == null) return false;
185 
186         // Verify if the output file exists and is the same that we want to copy
187         if (outputFs.exists(outputPath)) {
188           FileStatus outputStat = outputFs.getFileStatus(outputPath);
189           if (sameFile(inputStat, outputStat)) {
190             LOG.info("Skip copy " + inputPath + " to " + outputPath + ", same file.");
191             return true;
192           }
193         }
194 
195         context.getCounter(Counter.BYTES_EXPECTED).increment(inputStat.getLen());
196 
197         // Ensure that the output folder is there and copy the file
198         outputFs.mkdirs(outputPath.getParent());
199         FSDataOutputStream out = outputFs.create(outputPath, true);
200         try {
201           if (!copyData(context, inputPath, in, outputPath, out, inputStat.getLen()))
202             return false;
203         } finally {
204           out.close();
205         }
206 
207         // Preserve attributes
208         return preserveAttributes(outputPath, inputStat);
209       } finally {
210         in.close();
211       }
212     }
213 
214     /**
215      * Preserve the files attribute selected by the user copying them from the source file
216      */
217     private boolean preserveAttributes(final Path path, final FileStatus refStat) {
218       FileStatus stat;
219       try {
220         stat = outputFs.getFileStatus(path);
221       } catch (IOException e) {
222         LOG.warn("Unable to get the status for file=" + path);
223         return false;
224       }
225 
226       try {
227         if (filesMode > 0 && stat.getPermission().toShort() != filesMode) {
228           outputFs.setPermission(path, new FsPermission(filesMode));
229         } else if (!stat.getPermission().equals(refStat.getPermission())) {
230           outputFs.setPermission(path, refStat.getPermission());
231         }
232       } catch (IOException e) {
233         LOG.error("Unable to set the permission for file=" + path, e);
234         return false;
235       }
236 
237       try {
238         String user = (filesUser != null) ? filesUser : refStat.getOwner();
239         String group = (filesGroup != null) ? filesGroup : refStat.getGroup();
240         if (!(user.equals(stat.getOwner()) && group.equals(stat.getGroup()))) {
241           outputFs.setOwner(path, user, group);
242         }
243       } catch (IOException e) {
244         LOG.error("Unable to set the owner/group for file=" + path, e);
245         return false;
246       }
247 
248       return true;
249     }
250 
251     private boolean copyData(final Context context,
252         final Path inputPath, final FSDataInputStream in,
253         final Path outputPath, final FSDataOutputStream out,
254         final long inputFileSize) {
255       final String statusMessage = "copied %s/" + StringUtils.humanReadableInt(inputFileSize) +
256                                    " (%.3f%%) from " + inputPath + " to " + outputPath;
257 
258       try {
259         byte[] buffer = new byte[BUFFER_SIZE];
260         long totalBytesWritten = 0;
261         int reportBytes = 0;
262         int bytesRead;
263 
264         while ((bytesRead = in.read(buffer)) > 0) {
265           out.write(buffer, 0, bytesRead);
266           totalBytesWritten += bytesRead;
267           reportBytes += bytesRead;
268 
269           if (reportBytes >= REPORT_SIZE) {
270             context.getCounter(Counter.BYTES_COPIED).increment(reportBytes);
271             context.setStatus(String.format(statusMessage,
272                               StringUtils.humanReadableInt(totalBytesWritten),
273                               reportBytes/(float)inputFileSize));
274             reportBytes = 0;
275           }
276         }
277 
278         context.getCounter(Counter.BYTES_COPIED).increment(reportBytes);
279         context.setStatus(String.format(statusMessage,
280                           StringUtils.humanReadableInt(totalBytesWritten),
281                           reportBytes/(float)inputFileSize));
282 
283         // Verify that the written size match
284         if (totalBytesWritten != inputFileSize) {
285           LOG.error("number of bytes copied not matching copied=" + totalBytesWritten +
286                     " expected=" + inputFileSize + " for file=" + inputPath);
287           context.getCounter(Counter.COPY_FAILED).increment(1);
288           return false;
289         }
290 
291         return true;
292       } catch (IOException e) {
293         LOG.error("Error copying " + inputPath + " to " + outputPath, e);
294         context.getCounter(Counter.COPY_FAILED).increment(1);
295         return false;
296       }
297     }
298 
299     private FSDataInputStream openSourceFile(final Path path) {
300       try {
301         if (HFileLink.isHFileLink(path) || StoreFile.isReference(path)) {
302           return new HFileLink(inputRoot, inputArchive, path).open(inputFs);
303         } else if (isHLogLinkPath(path)) {
304           String serverName = path.getParent().getName();
305           String logName = path.getName();
306           return new HLogLink(inputRoot, serverName, logName).open(inputFs);
307         }
308         return inputFs.open(path);
309       } catch (IOException e) {
310         LOG.error("Unable to open source file=" + path, e);
311         return null;
312       }
313     }
314 
315     private FileStatus getFileStatus(final FileSystem fs, final Path path) {
316       try {
317         if (HFileLink.isHFileLink(path) || StoreFile.isReference(path)) {
318           HFileLink link = new HFileLink(inputRoot, inputArchive, path);
319           return link.getFileStatus(fs);
320         } else if (isHLogLinkPath(path)) {
321           String serverName = path.getParent().getName();
322           String logName = path.getName();
323           return new HLogLink(inputRoot, serverName, logName).getFileStatus(fs);
324         }
325         return fs.getFileStatus(path);
326       } catch (IOException e) {
327         LOG.warn("Unable to get the status for file=" + path);
328         return null;
329       }
330     }
331 
332     private FileChecksum getFileChecksum(final FileSystem fs, final Path path) {
333       try {
334         return fs.getFileChecksum(path);
335       } catch (IOException e) {
336         LOG.warn("Unable to get checksum for file=" + path, e);
337         return null;
338       }
339     }
340 
341     /**
342      * Check if the two files are equal by looking at the file length,
343      * and at the checksum (if user has specified the verifyChecksum flag).
344      */
345     private boolean sameFile(final FileStatus inputStat, final FileStatus outputStat) {
346       // Not matching length
347       if (inputStat.getLen() != outputStat.getLen()) return false;
348 
349       // Mark files as equals, since user asked for no checksum verification
350       if (!verifyChecksum) return true;
351 
352       // If checksums are not available, files are not the same.
353       FileChecksum inChecksum = getFileChecksum(inputFs, inputStat.getPath());
354       if (inChecksum == null) return false;
355 
356       FileChecksum outChecksum = getFileChecksum(outputFs, outputStat.getPath());
357       if (outChecksum == null) return false;
358 
359       return inChecksum.equals(outChecksum);
360     }
361 
362     /**
363      * HLog files are encoded as serverName/logName
364      * and since all the other files should be in /hbase/table/..path..
365      * we can rely on the depth, for now.
366      */
367     private static boolean isHLogLinkPath(final Path path) {
368       return path.depth() == 2;
369     }
370   }
371 
372   /**
373    * Extract the list of files (HFiles/HLogs) to copy using Map-Reduce.
374    * @return list of files referenced by the snapshot (pair of path and size)
375    */
376   private List<Pair<Path, Long>> getSnapshotFiles(final FileSystem fs, final Path snapshotDir)
377       throws IOException {
378     SnapshotDescription snapshotDesc = SnapshotDescriptionUtils.readSnapshotInfo(fs, snapshotDir);
379 
380     final List<Pair<Path, Long>> files = new ArrayList<Pair<Path, Long>>();
381     final String table = snapshotDesc.getTable();
382     final Configuration conf = getConf();
383 
384     // Get snapshot files
385     SnapshotReferenceUtil.visitReferencedFiles(fs, snapshotDir,
386       new SnapshotReferenceUtil.FileVisitor() {
387         public void storeFile (final String region, final String family, final String hfile)
388             throws IOException {
389           Path path = HFileLink.createPath(table, region, family, hfile);
390           long size = new HFileLink(conf, path).getFileStatus(fs).getLen();
391           files.add(new Pair<Path, Long>(path, size));
392         }
393 
394         public void recoveredEdits (final String region, final String logfile)
395             throws IOException {
396           // copied with the snapshot referenecs
397         }
398 
399         public void logFile (final String server, final String logfile)
400             throws IOException {
401           long size = new HLogLink(conf, server, logfile).getFileStatus(fs).getLen();
402           files.add(new Pair<Path, Long>(new Path(server, logfile), size));
403         }
404     });
405 
406     return files;
407   }
408 
409   /**
410    * Given a list of file paths and sizes, create around ngroups in as balanced a way as possible.
411    * The groups created will have similar amounts of bytes.
412    * <p>
413    * The algorithm used is pretty straightforward; the file list is sorted by size,
414    * and then each group fetch the bigger file available, iterating through groups
415    * alternating the direction.
416    */
417   static List<List<Path>> getBalancedSplits(final List<Pair<Path, Long>> files, int ngroups) {
418     // Sort files by size, from small to big
419     Collections.sort(files, new Comparator<Pair<Path, Long>>() {
420       public int compare(Pair<Path, Long> a, Pair<Path, Long> b) {
421         long r = a.getSecond() - b.getSecond();
422         return (r < 0) ? -1 : ((r > 0) ? 1 : 0);
423       }
424     });
425 
426     // create balanced groups
427     List<List<Path>> fileGroups = new LinkedList<List<Path>>();
428     long[] sizeGroups = new long[ngroups];
429     int hi = files.size() - 1;
430     int lo = 0;
431 
432     List<Path> group;
433     int dir = 1;
434     int g = 0;
435 
436     while (hi >= lo) {
437       if (g == fileGroups.size()) {
438         group = new LinkedList<Path>();
439         fileGroups.add(group);
440       } else {
441         group = fileGroups.get(g);
442       }
443 
444       Pair<Path, Long> fileInfo = files.get(hi--);
445 
446       // add the hi one
447       sizeGroups[g] += fileInfo.getSecond();
448       group.add(fileInfo.getFirst());
449 
450       // change direction when at the end or the beginning
451       g += dir;
452       if (g == ngroups) {
453         dir = -1;
454         g = ngroups - 1;
455       } else if (g < 0) {
456         dir = 1;
457         g = 0;
458       }
459     }
460 
461     if (LOG.isDebugEnabled()) {
462       for (int i = 0; i < sizeGroups.length; ++i) {
463         LOG.debug("export split=" + i + " size=" + StringUtils.humanReadableInt(sizeGroups[i]));
464       }
465     }
466 
467     return fileGroups;
468   }
469 
470   private static Path getInputFolderPath(final FileSystem fs, final Configuration conf)
471       throws IOException, InterruptedException {
472     String stagingName = "exportSnapshot-" + EnvironmentEdgeManager.currentTimeMillis();
473     Path stagingDir = new Path(conf.get(CONF_TMP_DIR), stagingName);
474     fs.mkdirs(stagingDir);
475     return new Path(stagingDir, INPUT_FOLDER_PREFIX +
476       String.valueOf(EnvironmentEdgeManager.currentTimeMillis()));
477   }
478 
479   /**
480    * Create the input files, with the path to copy, for the MR job.
481    * Each input files contains n files, and each input file has a similar amount data to copy.
482    * The number of input files created are based on the number of mappers provided as argument
483    * and the number of the files to copy.
484    */
485   private static Path[] createInputFiles(final Configuration conf,
486       final List<Pair<Path, Long>> snapshotFiles, int mappers)
487       throws IOException, InterruptedException {
488     FileSystem fs = FileSystem.get(conf);
489     Path inputFolderPath = getInputFolderPath(fs, conf);
490     LOG.debug("Input folder location: " + inputFolderPath);
491 
492     List<List<Path>> splits = getBalancedSplits(snapshotFiles, mappers);
493     Path[] inputFiles = new Path[splits.size()];
494 
495     Text key = new Text();
496     for (int i = 0; i < inputFiles.length; i++) {
497       List<Path> files = splits.get(i);
498       inputFiles[i] = new Path(inputFolderPath, String.format("export-%d.seq", i));
499       SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, inputFiles[i],
500         Text.class, NullWritable.class);
501       LOG.debug("Input split: " + i);
502       try {
503         for (Path file: files) {
504           LOG.debug(file.toString());
505           key.set(file.toString());
506           writer.append(key, NullWritable.get());
507         }
508       } finally {
509         writer.close();
510       }
511     }
512 
513     return inputFiles;
514   }
515 
516   /**
517    * Run Map-Reduce Job to perform the files copy.
518    */
519   private boolean runCopyJob(final Path inputRoot, final Path outputRoot,
520       final List<Pair<Path, Long>> snapshotFiles, final boolean verifyChecksum,
521       final String filesUser, final String filesGroup, final int filesMode,
522       final int mappers) throws IOException, InterruptedException, ClassNotFoundException {
523     Configuration conf = getConf();
524     if (filesGroup != null) conf.set(CONF_FILES_GROUP, filesGroup);
525     if (filesUser != null) conf.set(CONF_FILES_USER, filesUser);
526     conf.setInt(CONF_FILES_MODE, filesMode);
527     conf.setBoolean(CONF_CHECKSUM_VERIFY, verifyChecksum);
528     conf.set(CONF_OUTPUT_ROOT, outputRoot.toString());
529     conf.set(CONF_INPUT_ROOT, inputRoot.toString());
530     conf.setInt("mapreduce.job.maps", mappers);
531 
532     // job.setMapSpeculativeExecution(false)
533     conf.setBoolean("mapreduce.map.speculative", false);
534     conf.setBoolean("mapreduce.reduce.speculative", false);
535     conf.setBoolean("mapred.map.tasks.speculative.execution", false);
536     conf.setBoolean("mapred.reduce.tasks.speculative.execution", false);
537 
538     Job job = new Job(conf);
539     job.setJobName("ExportSnapshot");
540     job.setJarByClass(ExportSnapshot.class);
541     job.setMapperClass(ExportMapper.class);
542     job.setInputFormatClass(SequenceFileInputFormat.class);
543     job.setOutputFormatClass(NullOutputFormat.class);
544     job.setNumReduceTasks(0);
545     for (Path path: createInputFiles(conf, snapshotFiles, mappers)) {
546       LOG.debug("Add Input Path=" + path);
547       SequenceFileInputFormat.addInputPath(job, path);
548     }
549 
550     return job.waitForCompletion(true);
551   }
552 
553   /**
554    * Execute the export snapshot by copying the snapshot metadata, hfiles and hlogs.
555    * @return 0 on success, and != 0 upon failure.
556    */
557   @Override
558   public int run(String[] args) throws Exception {
559     boolean verifyChecksum = true;
560     String snapshotName = null;
561     String filesGroup = null;
562     String filesUser = null;
563     Path outputRoot = null;
564     int filesMode = 0;
565     int mappers = getConf().getInt("mapreduce.job.maps", 1);
566 
567     // Process command line args
568     for (int i = 0; i < args.length; i++) {
569       String cmd = args[i];
570       try {
571         if (cmd.equals("-snapshot")) {
572           snapshotName = args[++i];
573         } else if (cmd.equals("-copy-to")) {
574           outputRoot = new Path(args[++i]);
575         } else if (cmd.equals("-no-checksum-verify")) {
576           verifyChecksum = false;
577         } else if (cmd.equals("-mappers")) {
578           mappers = Integer.parseInt(args[++i]);
579         } else if (cmd.equals("-chuser")) {
580           filesUser = args[++i];
581         } else if (cmd.equals("-chgroup")) {
582           filesGroup = args[++i];
583         } else if (cmd.equals("-chmod")) {
584           filesMode = Integer.parseInt(args[++i], 8);
585         } else if (cmd.equals("-h") || cmd.equals("--help")) {
586           printUsageAndExit();
587         } else {
588           System.err.println("UNEXPECTED: " + cmd);
589           printUsageAndExit();
590         }
591       } catch (Exception e) {
592         printUsageAndExit();
593       }
594     }
595 
596     // Check user options
597     if (snapshotName == null) {
598       System.err.println("Snapshot name not provided.");
599       printUsageAndExit();
600     }
601 
602     if (outputRoot == null) {
603       System.err.println("Destination file-system not provided.");
604       printUsageAndExit();
605     }
606 
607     Configuration conf = getConf();
608     Path inputRoot = FSUtils.getRootDir(conf);
609     FileSystem inputFs = FileSystem.get(conf);
610     FileSystem outputFs = FileSystem.get(outputRoot.toUri(), conf);
611 
612     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, inputRoot);
613     Path snapshotTmpDir = SnapshotDescriptionUtils.getWorkingSnapshotDir(snapshotName, outputRoot);
614     Path outputSnapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, outputRoot);
615 
616     // Check if the snapshot already exists
617     if (outputFs.exists(outputSnapshotDir)) {
618       System.err.println("The snapshot '" + snapshotName +
619         "' already exists in the destination: " + outputSnapshotDir);
620       return 1;
621     }
622 
623     // Check if the snapshot already in-progress
624     if (outputFs.exists(snapshotTmpDir)) {
625       System.err.println("A snapshot with the same name '" + snapshotName + "' may be in-progress");
626       System.err.println("Please check " + snapshotTmpDir + ". If the snapshot has completed, ");
627       System.err.println("consider removing " + snapshotTmpDir + " before retrying export");
628       return 1;
629     }
630 
631     // Step 0 - Extract snapshot files to copy
632     final List<Pair<Path, Long>> files = getSnapshotFiles(inputFs, snapshotDir);
633 
634     // Step 1 - Copy fs1:/.snapshot/<snapshot> to  fs2:/.snapshot/.tmp/<snapshot>
635     // The snapshot references must be copied before the hfiles otherwise the cleaner
636     // will remove them because they are unreferenced.
637     try {
638       FileUtil.copy(inputFs, snapshotDir, outputFs, snapshotTmpDir, false, false, conf);
639     } catch (IOException e) {
640       System.err.println("Failed to copy the snapshot directory: from=" + snapshotDir +
641         " to=" + snapshotTmpDir);
642       e.printStackTrace(System.err);
643       return 1;
644     }
645 
646     // Step 2 - Start MR Job to copy files
647     // The snapshot references must be copied before the files otherwise the files gets removed
648     // by the HFileArchiver, since they have no references.
649     try {
650       if (!runCopyJob(inputRoot, outputRoot, files, verifyChecksum,
651           filesUser, filesGroup, filesMode, mappers)) {
652         throw new ExportSnapshotException("Snapshot export failed!");
653       }
654 
655       // Step 3 - Rename fs2:/.snapshot/.tmp/<snapshot> fs2:/.snapshot/<snapshot>
656       if (!outputFs.rename(snapshotTmpDir, outputSnapshotDir)) {
657         System.err.println("Snapshot export failed!");
658         System.err.println("Unable to rename snapshot directory from=" +
659                            snapshotTmpDir + " to=" + outputSnapshotDir);
660         return 1;
661       }
662 
663       return 0;
664     } catch (Exception e) {
665       System.err.println("Snapshot export failed!");
666       e.printStackTrace(System.err);
667       outputFs.delete(outputSnapshotDir, true);
668       return 1;
669     }
670   }
671 
672   // ExportSnapshot
673   private void printUsageAndExit() {
674     System.err.printf("Usage: bin/hbase %s [options]%n", getClass().getName());
675     System.err.println(" where [options] are:");
676     System.err.println("  -h|-help                Show this help and exit.");
677     System.err.println("  -snapshot NAME          Snapshot to restore.");
678     System.err.println("  -copy-to NAME           Remote destination hdfs://");
679     System.err.println("  -no-checksum-verify     Do not verify checksum.");
680     System.err.println("  -chuser USERNAME        Change the owner of the files to the specified one.");
681     System.err.println("  -chgroup GROUP          Change the group of the files to the specified one.");
682     System.err.println("  -chmod MODE             Change the permission of the files to the specified one.");
683     System.err.println("  -mappers                Number of mappers to use during the copy (mapreduce.job.maps).");
684     System.err.println();
685     System.err.println("Examples:");
686     System.err.println("  hbase " + getClass() + " \\");
687     System.err.println("    -snapshot MySnapshot -copy-to hdfs:///srv2:8082/hbase \\");
688     System.err.println("    -chuser MyUser -chgroup MyGroup -chmod 700 -mappers 16");
689     System.exit(1);
690   }
691 
692   /**
693    * The guts of the {@link #main} method.
694    * Call this method to avoid the {@link #main(String[])} System.exit.
695    * @param args
696    * @return errCode
697    * @throws Exception
698    */
699   static int innerMain(final Configuration conf, final String [] args) throws Exception {
700     return ToolRunner.run(conf, new ExportSnapshot(), args);
701   }
702 
703   public static void main(String[] args) throws Exception {
704      System.exit(innerMain(HBaseConfiguration.create(), args));
705   }
706 }