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_FILES_USER = "snapshot.export.files.attributes.user";
83    private static final String CONF_FILES_GROUP = "snapshot.export.files.attributes.group";
84    private static final String CONF_FILES_MODE = "snapshot.export.files.attributes.mode";
85    private static final String CONF_CHECKSUM_VERIFY = "snapshot.export.checksum.verify";
86    private static final String CONF_OUTPUT_ROOT = "snapshot.export.output.root";
87    private static final String CONF_INPUT_ROOT = "snapshot.export.input.root";
88    private static final String CONF_STAGING_ROOT = "snapshot.export.staging.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 = new Path(family, HFileLink.createHFileLinkName(table, region, 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_STAGING_ROOT, fs.getWorkingDirectory().toString())
474         , stagingName);
475     fs.mkdirs(stagingDir);
476     return new Path(stagingDir, INPUT_FOLDER_PREFIX +
477       String.valueOf(EnvironmentEdgeManager.currentTimeMillis()));
478   }
479 
480   /**
481    * Create the input files, with the path to copy, for the MR job.
482    * Each input files contains n files, and each input file has a similar amount data to copy.
483    * The number of input files created are based on the number of mappers provided as argument
484    * and the number of the files to copy.
485    */
486   private static Path[] createInputFiles(final Configuration conf,
487       final List<Pair<Path, Long>> snapshotFiles, int mappers)
488       throws IOException, InterruptedException {
489     FileSystem fs = FileSystem.get(conf);
490     Path inputFolderPath = getInputFolderPath(fs, conf);
491     LOG.debug("Input folder location: " + inputFolderPath);
492 
493     List<List<Path>> splits = getBalancedSplits(snapshotFiles, mappers);
494     Path[] inputFiles = new Path[splits.size()];
495 
496     Text key = new Text();
497     for (int i = 0; i < inputFiles.length; i++) {
498       List<Path> files = splits.get(i);
499       inputFiles[i] = new Path(inputFolderPath, String.format("export-%d.seq", i));
500       SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, inputFiles[i],
501         Text.class, NullWritable.class);
502       LOG.debug("Input split: " + i);
503       try {
504         for (Path file: files) {
505           LOG.debug(file.toString());
506           key.set(file.toString());
507           writer.append(key, NullWritable.get());
508         }
509       } finally {
510         writer.close();
511       }
512     }
513 
514     return inputFiles;
515   }
516 
517   /**
518    * Run Map-Reduce Job to perform the files copy.
519    */
520   private boolean runCopyJob(final Path inputRoot, final Path outputRoot,
521       final List<Pair<Path, Long>> snapshotFiles, final boolean verifyChecksum,
522       final String filesUser, final String filesGroup, final int filesMode,
523       final int mappers) throws IOException, InterruptedException, ClassNotFoundException {
524     Configuration conf = getConf();
525     if (filesGroup != null) conf.set(CONF_FILES_GROUP, filesGroup);
526     if (filesUser != null) conf.set(CONF_FILES_USER, filesUser);
527     conf.setInt(CONF_FILES_MODE, filesMode);
528     conf.setBoolean(CONF_CHECKSUM_VERIFY, verifyChecksum);
529     conf.set(CONF_OUTPUT_ROOT, outputRoot.toString());
530     conf.set(CONF_INPUT_ROOT, inputRoot.toString());
531     conf.setInt("mapreduce.job.maps", mappers);
532 
533     // job.setMapSpeculativeExecution(false)
534     conf.setBoolean("mapreduce.map.speculative", false);
535     conf.setBoolean("mapreduce.reduce.speculative", false);
536     conf.setBoolean("mapred.map.tasks.speculative.execution", false);
537     conf.setBoolean("mapred.reduce.tasks.speculative.execution", false);
538 
539     Job job = new Job(conf);
540     job.setJobName("ExportSnapshot");
541     job.setJarByClass(ExportSnapshot.class);
542     job.setMapperClass(ExportMapper.class);
543     job.setInputFormatClass(SequenceFileInputFormat.class);
544     job.setOutputFormatClass(NullOutputFormat.class);
545     job.setNumReduceTasks(0);
546     for (Path path: createInputFiles(conf, snapshotFiles, mappers)) {
547       LOG.debug("Add Input Path=" + path);
548       SequenceFileInputFormat.addInputPath(job, path);
549     }
550 
551     return job.waitForCompletion(true);
552   }
553 
554   /**
555    * Execute the export snapshot by copying the snapshot metadata, hfiles and hlogs.
556    * @return 0 on success, and != 0 upon failure.
557    */
558   @Override
559   public int run(String[] args) throws Exception {
560     boolean verifyChecksum = true;
561     String snapshotName = null;
562     String filesGroup = null;
563     String filesUser = null;
564     Path outputRoot = null;
565     int filesMode = 0;
566     int mappers = getConf().getInt("mapreduce.job.maps", 1);
567 
568     // Process command line args
569     for (int i = 0; i < args.length; i++) {
570       String cmd = args[i];
571       try {
572         if (cmd.equals("-snapshot")) {
573           snapshotName = args[++i];
574         } else if (cmd.equals("-copy-to")) {
575           outputRoot = new Path(args[++i]);
576         } else if (cmd.equals("-no-checksum-verify")) {
577           verifyChecksum = false;
578         } else if (cmd.equals("-mappers")) {
579           mappers = Integer.parseInt(args[++i]);
580         } else if (cmd.equals("-chuser")) {
581           filesUser = args[++i];
582         } else if (cmd.equals("-chgroup")) {
583           filesGroup = args[++i];
584         } else if (cmd.equals("-chmod")) {
585           filesMode = Integer.parseInt(args[++i], 8);
586         } else if (cmd.equals("-h") || cmd.equals("--help")) {
587           printUsageAndExit();
588         } else {
589           System.err.println("UNEXPECTED: " + cmd);
590           printUsageAndExit();
591         }
592       } catch (Exception e) {
593         printUsageAndExit();
594       }
595     }
596 
597     // Check user options
598     if (snapshotName == null) {
599       System.err.println("Snapshot name not provided.");
600       printUsageAndExit();
601     }
602 
603     if (outputRoot == null) {
604       System.err.println("Destination file-system not provided.");
605       printUsageAndExit();
606     }
607 
608     Configuration conf = getConf();
609     Path inputRoot = FSUtils.getRootDir(conf);
610     FileSystem inputFs = FileSystem.get(conf);
611     FileSystem outputFs = FileSystem.get(outputRoot.toUri(), conf);
612 
613     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, inputRoot);
614     Path snapshotTmpDir = SnapshotDescriptionUtils.getWorkingSnapshotDir(snapshotName, outputRoot);
615     Path outputSnapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, outputRoot);
616 
617     // Check if the snapshot already exists
618     if (outputFs.exists(outputSnapshotDir)) {
619       System.err.println("The snapshot '" + snapshotName +
620         "' already exists in the destination: " + outputSnapshotDir);
621       return 1;
622     }
623 
624     // Check if the snapshot already in-progress
625     if (outputFs.exists(snapshotTmpDir)) {
626       System.err.println("A snapshot with the same name '" + snapshotName + "' may be in-progress");
627       System.err.println("Please check " + snapshotTmpDir + ". If the snapshot has completed, ");
628       System.err.println("consider removing " + snapshotTmpDir + " before retrying export"); 
629       return 1;
630     }
631 
632     // Step 0 - Extract snapshot files to copy
633     final List<Pair<Path, Long>> files = getSnapshotFiles(inputFs, snapshotDir);
634 
635     // Step 1 - Copy fs1:/.snapshot/<snapshot> to  fs2:/.snapshot/.tmp/<snapshot>
636     // The snapshot references must be copied before the hfiles otherwise the cleaner
637     // will remove them because they are unreferenced.
638     try {
639       FileUtil.copy(inputFs, snapshotDir, outputFs, snapshotTmpDir, false, false, conf);
640     } catch (IOException e) {
641       System.err.println("Failed to copy the snapshot directory: from=" + snapshotDir +
642         " to=" + snapshotTmpDir);
643       e.printStackTrace(System.err);
644       return 1;
645     }
646 
647     // Step 2 - Start MR Job to copy files
648     // The snapshot references must be copied before the files otherwise the files gets removed
649     // by the HFileArchiver, since they have no references.
650     try {
651       if (files.size() == 0) {
652         LOG.warn("There are 0 store file to be copied. There may be no data in the table.");
653       } else {
654         if (!runCopyJob(inputRoot, outputRoot, files, verifyChecksum,
655             filesUser, filesGroup, filesMode, mappers)) {
656           throw new ExportSnapshotException("Snapshot export failed!");
657         }
658       }
659 
660       // Step 3 - Rename fs2:/.snapshot/.tmp/<snapshot> fs2:/.snapshot/<snapshot>
661       if (!outputFs.rename(snapshotTmpDir, outputSnapshotDir)) {
662         System.err.println("Snapshot export failed!");
663         System.err.println("Unable to rename snapshot directory from=" +
664                            snapshotTmpDir + " to=" + outputSnapshotDir);
665         return 1;
666       }
667 
668       return 0;
669     } catch (Exception e) {
670       System.err.println("Snapshot export failed!");
671       e.printStackTrace(System.err);
672       outputFs.delete(outputSnapshotDir, true);
673       return 1;
674     }
675   }
676 
677   // ExportSnapshot
678   private void printUsageAndExit() {
679     System.err.printf("Usage: bin/hbase %s [options]%n", getClass().getName());
680     System.err.println(" where [options] are:");
681     System.err.println("  -h|-help                Show this help and exit.");
682     System.err.println("  -snapshot NAME          Snapshot to restore.");
683     System.err.println("  -copy-to NAME           Remote destination hdfs://");
684     System.err.println("  -no-checksum-verify     Do not verify checksum.");
685     System.err.println("  -chuser USERNAME        Change the owner of the files to the specified one.");
686     System.err.println("  -chgroup GROUP          Change the group of the files to the specified one.");
687     System.err.println("  -chmod MODE             Change the permission of the files to the specified one.");
688     System.err.println("  -mappers                Number of mappers to use during the copy (mapreduce.job.maps).");
689     System.err.println();
690     System.err.println("Examples:");
691     System.err.println("  hbase " + getClass() + " \\");
692     System.err.println("    -snapshot MySnapshot -copy-to hdfs:///srv2:8082/hbase \\");
693     System.err.println("    -chuser MyUser -chgroup MyGroup -chmod 700 -mappers 16");
694     System.exit(1);
695   }
696 
697   /**
698    * The guts of the {@link #main} method.
699    * Call this method to avoid the {@link #main(String[])} System.exit.
700    * @param args
701    * @return errCode
702    * @throws Exception
703    */
704   static int innerMain(final Configuration conf, final String [] args) throws Exception {
705     return ToolRunner.run(conf, new ExportSnapshot(), args);
706   }
707 
708   public static void main(String[] args) throws Exception {
709      System.exit(innerMain(HBaseConfiguration.create(), args));
710   }
711 }