1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 import java.util.Random;
29
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
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
72
73
74
75
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 private static final String CONF_BUFFER_SIZE = "snapshot.export.buffer.size";
90 private static final String CONF_MAP_GROUP = "snapshot.export.default.map.group";
91 protected static final String CONF_SKIP_TMP = "snapshot.export.skip.tmp";
92
93 static final String CONF_TEST_FAILURE = "test.snapshot.export.failure";
94 static final String CONF_TEST_RETRY = "test.snapshot.export.failure.retry";
95
96 private static final String INPUT_FOLDER_PREFIX = "export-files.";
97
98
99 public enum Counter { MISSING_FILES, COPY_FAILED, BYTES_EXPECTED, BYTES_COPIED, FILES_COPIED };
100
101 private static class ExportMapper extends Mapper<Text, NullWritable, NullWritable, NullWritable> {
102 final static int REPORT_SIZE = 1 * 1024 * 1024;
103 final static int BUFFER_SIZE = 64 * 1024;
104
105 private boolean testFailures;
106 private Random random;
107
108 private boolean verifyChecksum;
109 private String filesGroup;
110 private String filesUser;
111 private short filesMode;
112 private int bufferSize;
113
114 private FileSystem outputFs;
115 private Path outputArchive;
116 private Path outputRoot;
117
118 private FileSystem inputFs;
119 private Path inputArchive;
120 private Path inputRoot;
121
122 @Override
123 public void setup(Context context) throws IOException {
124 Configuration conf = context.getConfiguration();
125 verifyChecksum = conf.getBoolean(CONF_CHECKSUM_VERIFY, true);
126
127 filesGroup = conf.get(CONF_FILES_GROUP);
128 filesUser = conf.get(CONF_FILES_USER);
129 filesMode = (short)conf.getInt(CONF_FILES_MODE, 0);
130 outputRoot = new Path(conf.get(CONF_OUTPUT_ROOT));
131 inputRoot = new Path(conf.get(CONF_INPUT_ROOT));
132
133 inputArchive = new Path(inputRoot, HConstants.HFILE_ARCHIVE_DIRECTORY);
134 outputArchive = new Path(outputRoot, HConstants.HFILE_ARCHIVE_DIRECTORY);
135
136 testFailures = conf.getBoolean(CONF_TEST_FAILURE, false);
137
138 try {
139 inputFs = FileSystem.get(inputRoot.toUri(), conf);
140 } catch (IOException e) {
141 throw new IOException("Could not get the input FileSystem with root=" + inputRoot, e);
142 }
143
144 try {
145 outputFs = FileSystem.get(outputRoot.toUri(), conf);
146 } catch (IOException e) {
147 throw new IOException("Could not get the output FileSystem with root="+ outputRoot, e);
148 }
149
150
151 int defaultBlockSize = Math.max((int) outputFs.getDefaultBlockSize(), BUFFER_SIZE);
152 bufferSize = conf.getInt(CONF_BUFFER_SIZE, defaultBlockSize);
153 LOG.info("Using bufferSize=" + StringUtils.humanReadableInt(bufferSize));
154 }
155
156 @Override
157 public void map(Text key, NullWritable value, Context context)
158 throws InterruptedException, IOException {
159 Path inputPath = new Path(key.toString());
160 Path outputPath = getOutputPath(inputPath);
161
162 LOG.info("copy file input=" + inputPath + " output=" + outputPath);
163 copyFile(context, inputPath, outputPath);
164 }
165
166
167
168
169
170
171 private Path getOutputPath(final Path inputPath) throws IOException {
172 Path path;
173 if (HFileLink.isHFileLink(inputPath) || StoreFile.isReference(inputPath)) {
174 String family = inputPath.getParent().getName();
175 String table = HFileLink.getReferencedTableName(inputPath.getName());
176 String region = HFileLink.getReferencedRegionName(inputPath.getName());
177 String hfile = HFileLink.getReferencedHFileName(inputPath.getName());
178 path = new Path(table, new Path(region, new Path(family, hfile)));
179 } else if (isHLogLinkPath(inputPath)) {
180 String logName = inputPath.getName();
181 path = new Path(new Path(outputRoot, HConstants.HREGION_OLDLOGDIR_NAME), logName);
182 } else {
183 path = inputPath;
184 }
185 return new Path(outputArchive, path);
186 }
187
188
189
190
191 private void injectTestFailure(final Context context, final Path inputPath)
192 throws IOException {
193 if (testFailures) {
194 if (context.getConfiguration().getBoolean(CONF_TEST_RETRY, false)) {
195 if (random == null) {
196 random = new Random();
197 }
198
199
200
201
202 if (random.nextFloat() < 0.03) {
203 throw new IOException("TEST RETRY FAILURE: Unable to copy input=" + inputPath
204 + " time=" + System.currentTimeMillis());
205 }
206 } else {
207 context.getCounter(Counter.COPY_FAILED).increment(1);
208 throw new IOException("TEST FAILURE: Unable to copy input=" + inputPath);
209 }
210 }
211 }
212
213 private void copyFile(final Context context, final Path inputPath, final Path outputPath)
214 throws IOException {
215 injectTestFailure(context, inputPath);
216
217
218 FileStatus inputStat = getSourceFileStatus(context, inputPath);
219
220
221 if (outputFs.exists(outputPath)) {
222 FileStatus outputStat = outputFs.getFileStatus(outputPath);
223 if (outputStat != null && sameFile(inputStat, outputStat)) {
224 LOG.info("Skip copy " + inputPath + " to " + outputPath + ", same file.");
225 return;
226 }
227 }
228
229 FSDataInputStream in = openSourceFile(context, inputPath);
230 try {
231 context.getCounter(Counter.BYTES_EXPECTED).increment(inputStat.getLen());
232
233
234 outputFs.mkdirs(outputPath.getParent());
235 FSDataOutputStream out = outputFs.create(outputPath, true);
236 try {
237 copyData(context, inputPath, in, outputPath, out, inputStat.getLen());
238 } finally {
239 out.close();
240 }
241
242
243 if (!preserveAttributes(outputPath, inputStat)) {
244 LOG.warn("You may have to run manually chown on: " + outputPath);
245 }
246 } finally {
247 in.close();
248 }
249 }
250
251
252
253
254
255
256
257
258
259 private boolean preserveAttributes(final Path path, final FileStatus refStat) {
260 FileStatus stat;
261 try {
262 stat = outputFs.getFileStatus(path);
263 } catch (IOException e) {
264 LOG.warn("Unable to get the status for file=" + path);
265 return false;
266 }
267
268 try {
269 if (filesMode > 0 && stat.getPermission().toShort() != filesMode) {
270 outputFs.setPermission(path, new FsPermission(filesMode));
271 } else if (!stat.getPermission().equals(refStat.getPermission())) {
272 outputFs.setPermission(path, refStat.getPermission());
273 }
274 } catch (IOException e) {
275 LOG.warn("Unable to set the permission for file="+ stat.getPath() +": "+ e.getMessage());
276 return false;
277 }
278
279 String user = stringIsNotEmpty(filesUser) ? filesUser : refStat.getOwner();
280 String group = stringIsNotEmpty(filesGroup) ? filesGroup : refStat.getGroup();
281 if (stringIsNotEmpty(user) || stringIsNotEmpty(group)) {
282 try {
283 if (!(user.equals(stat.getOwner()) && group.equals(stat.getGroup()))) {
284 outputFs.setOwner(path, user, group);
285 }
286 } catch (IOException e) {
287 LOG.warn("Unable to set the owner/group for file="+ stat.getPath() +": "+ e.getMessage());
288 LOG.warn("The user/group may not exist on the destination cluster: user=" +
289 user + " group=" + group);
290 return false;
291 }
292 }
293
294 return true;
295 }
296
297 private boolean stringIsNotEmpty(final String str) {
298 return str != null && str.length() > 0;
299 }
300
301 private void copyData(final Context context,
302 final Path inputPath, final FSDataInputStream in,
303 final Path outputPath, final FSDataOutputStream out,
304 final long inputFileSize)
305 throws IOException {
306 final String statusMessage = "copied %s/" + StringUtils.humanReadableInt(inputFileSize) +
307 " (%.1f%%)";
308
309 try {
310 byte[] buffer = new byte[bufferSize];
311 long totalBytesWritten = 0;
312 int reportBytes = 0;
313 int bytesRead;
314
315 long stime = System.currentTimeMillis();
316 while ((bytesRead = in.read(buffer)) > 0) {
317 out.write(buffer, 0, bytesRead);
318 totalBytesWritten += bytesRead;
319 reportBytes += bytesRead;
320
321 if (reportBytes >= REPORT_SIZE) {
322 context.getCounter(Counter.BYTES_COPIED).increment(reportBytes);
323 context.setStatus(String.format(statusMessage,
324 StringUtils.humanReadableInt(totalBytesWritten),
325 (totalBytesWritten/(float)inputFileSize) * 100.0f) +
326 " from " + inputPath + " to " + outputPath);
327 reportBytes = 0;
328 }
329 }
330 long etime = System.currentTimeMillis();
331
332 context.getCounter(Counter.BYTES_COPIED).increment(reportBytes);
333 context.setStatus(String.format(statusMessage,
334 StringUtils.humanReadableInt(totalBytesWritten),
335 (totalBytesWritten/(float)inputFileSize) * 100.0f) +
336 " from " + inputPath + " to " + outputPath);
337
338
339 if (totalBytesWritten != inputFileSize) {
340 String msg = "number of bytes copied not matching copied=" + totalBytesWritten +
341 " expected=" + inputFileSize + " for file=" + inputPath;
342 throw new IOException(msg);
343 }
344
345 LOG.info("copy completed for input=" + inputPath + " output=" + outputPath);
346 LOG.info("size=" + totalBytesWritten +
347 " (" + StringUtils.humanReadableInt(totalBytesWritten) + ")" +
348 " time=" + StringUtils.formatTimeDiff(etime, stime) +
349 String.format(" %.3fM/sec", (totalBytesWritten / ((etime - stime)/1000.0))/1048576.0));
350 context.getCounter(Counter.FILES_COPIED).increment(1);
351 } catch (IOException e) {
352 LOG.error("Error copying " + inputPath + " to " + outputPath, e);
353 context.getCounter(Counter.COPY_FAILED).increment(1);
354 throw e;
355 }
356 }
357
358
359
360
361
362
363 private FSDataInputStream openSourceFile(Context context, final Path path) throws IOException {
364 try {
365 if (HFileLink.isHFileLink(path) || StoreFile.isReference(path)) {
366 return new HFileLink(inputRoot, inputArchive, path).open(inputFs);
367 } else if (isHLogLinkPath(path)) {
368 String serverName = path.getParent().getName();
369 String logName = path.getName();
370 return new HLogLink(inputRoot, serverName, logName).open(inputFs);
371 }
372 return inputFs.open(path);
373 } catch (IOException e) {
374 context.getCounter(Counter.MISSING_FILES).increment(1);
375 LOG.error("Unable to open source file=" + path, e);
376 throw e;
377 }
378 }
379
380 private FileStatus getSourceFileStatus(Context context, final Path path) throws IOException {
381 try {
382 if (HFileLink.isHFileLink(path) || StoreFile.isReference(path)) {
383 HFileLink link = new HFileLink(inputRoot, inputArchive, path);
384 return link.getFileStatus(inputFs);
385 } else if (isHLogLinkPath(path)) {
386 String serverName = path.getParent().getName();
387 String logName = path.getName();
388 return new HLogLink(inputRoot, serverName, logName).getFileStatus(inputFs);
389 }
390 return inputFs.getFileStatus(path);
391 } catch (FileNotFoundException e) {
392 context.getCounter(Counter.MISSING_FILES).increment(1);
393 LOG.error("Unable to get the status for source file=" + path, e);
394 throw e;
395 } catch (IOException e) {
396 LOG.error("Unable to get the status for source file=" + path, e);
397 throw e;
398 }
399 }
400
401 private FileChecksum getFileChecksum(final FileSystem fs, final Path path) {
402 try {
403 return fs.getFileChecksum(path);
404 } catch (IOException e) {
405 LOG.warn("Unable to get checksum for file=" + path, e);
406 return null;
407 }
408 }
409
410
411
412
413
414 private boolean sameFile(final FileStatus inputStat, final FileStatus outputStat) {
415
416 if (inputStat.getLen() != outputStat.getLen()) return false;
417
418
419 if (!verifyChecksum) return true;
420
421
422 FileChecksum inChecksum = getFileChecksum(inputFs, inputStat.getPath());
423 if (inChecksum == null) return false;
424
425 FileChecksum outChecksum = getFileChecksum(outputFs, outputStat.getPath());
426 if (outChecksum == null) return false;
427
428 return inChecksum.equals(outChecksum);
429 }
430
431
432
433
434
435
436 private static boolean isHLogLinkPath(final Path path) {
437 return path.depth() == 2;
438 }
439 }
440
441
442
443
444
445 private List<Pair<Path, Long>> getSnapshotFiles(final FileSystem fs, final Path snapshotDir)
446 throws IOException {
447 SnapshotDescription snapshotDesc = SnapshotDescriptionUtils.readSnapshotInfo(fs, snapshotDir);
448
449 final List<Pair<Path, Long>> files = new ArrayList<Pair<Path, Long>>();
450 final String table = snapshotDesc.getTable();
451 final Configuration conf = getConf();
452
453
454 SnapshotReferenceUtil.visitReferencedFiles(fs, snapshotDir,
455 new SnapshotReferenceUtil.FileVisitor() {
456 public void storeFile (final String region, final String family, final String hfile)
457 throws IOException {
458 Path path = HFileLink.createPath(table, region, family, hfile);
459 long size = new HFileLink(conf, path).getFileStatus(fs).getLen();
460 files.add(new Pair<Path, Long>(path, size));
461 }
462
463 public void recoveredEdits (final String region, final String logfile)
464 throws IOException {
465
466 }
467
468 public void logFile (final String server, final String logfile)
469 throws IOException {
470 long size = new HLogLink(conf, server, logfile).getFileStatus(fs).getLen();
471 files.add(new Pair<Path, Long>(new Path(server, logfile), size));
472 }
473 });
474
475 return files;
476 }
477
478
479
480
481
482
483
484
485
486 static List<List<Path>> getBalancedSplits(final List<Pair<Path, Long>> files, int ngroups) {
487
488 Collections.sort(files, new Comparator<Pair<Path, Long>>() {
489 public int compare(Pair<Path, Long> a, Pair<Path, Long> b) {
490 long r = a.getSecond() - b.getSecond();
491 return (r < 0) ? -1 : ((r > 0) ? 1 : 0);
492 }
493 });
494
495
496 List<List<Path>> fileGroups = new LinkedList<List<Path>>();
497 long[] sizeGroups = new long[ngroups];
498 int hi = files.size() - 1;
499 int lo = 0;
500
501 List<Path> group;
502 int dir = 1;
503 int g = 0;
504
505 while (hi >= lo) {
506 if (g == fileGroups.size()) {
507 group = new LinkedList<Path>();
508 fileGroups.add(group);
509 } else {
510 group = fileGroups.get(g);
511 }
512
513 Pair<Path, Long> fileInfo = files.get(hi--);
514
515
516 sizeGroups[g] += fileInfo.getSecond();
517 group.add(fileInfo.getFirst());
518
519
520 g += dir;
521 if (g == ngroups) {
522 dir = -1;
523 g = ngroups - 1;
524 } else if (g < 0) {
525 dir = 1;
526 g = 0;
527 }
528 }
529
530 if (LOG.isDebugEnabled()) {
531 for (int i = 0; i < sizeGroups.length; ++i) {
532 LOG.debug("export split=" + i + " size=" + StringUtils.humanReadableInt(sizeGroups[i]));
533 }
534 }
535
536 return fileGroups;
537 }
538
539 private static Path getInputFolderPath(final Configuration conf)
540 throws IOException, InterruptedException {
541 String stagingName = "exportSnapshot-" + EnvironmentEdgeManager.currentTimeMillis();
542 String stagingDirPath = conf.get(CONF_STAGING_ROOT);
543 if (stagingDirPath == null) {
544 stagingDirPath = FileSystem.get(conf).getWorkingDirectory().toString();
545 }
546
547 Path stagingDir = new Path(stagingDirPath, stagingName);
548 FileSystem fs = stagingDir.getFileSystem(conf);
549 fs.mkdirs(stagingDir);
550 return new Path(stagingDir, INPUT_FOLDER_PREFIX +
551 String.valueOf(EnvironmentEdgeManager.currentTimeMillis()));
552 }
553
554
555
556
557
558
559
560 private static Path[] createInputFiles(final Configuration conf,
561 final List<Pair<Path, Long>> snapshotFiles, int mappers)
562 throws IOException, InterruptedException {
563 Path inputFolderPath = getInputFolderPath(conf);
564 FileSystem fs = inputFolderPath.getFileSystem(conf);
565 LOG.debug("Input folder location: " + inputFolderPath);
566
567 List<List<Path>> splits = getBalancedSplits(snapshotFiles, mappers);
568 Path[] inputFiles = new Path[splits.size()];
569
570 Text key = new Text();
571 for (int i = 0; i < inputFiles.length; i++) {
572 List<Path> files = splits.get(i);
573 inputFiles[i] = new Path(inputFolderPath, String.format("export-%d.seq", i));
574 SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, inputFiles[i],
575 Text.class, NullWritable.class);
576 LOG.debug("Input split: " + i);
577 try {
578 for (Path file: files) {
579 LOG.debug(file.toString());
580 key.set(file.toString());
581 writer.append(key, NullWritable.get());
582 }
583 } finally {
584 writer.close();
585 }
586 }
587
588 return inputFiles;
589 }
590
591
592
593
594 private void runCopyJob(final Path inputRoot, final Path outputRoot,
595 final List<Pair<Path, Long>> snapshotFiles, final boolean verifyChecksum,
596 final String filesUser, final String filesGroup, final int filesMode,
597 final int mappers) throws IOException, InterruptedException, ClassNotFoundException {
598 Configuration conf = getConf();
599 if (filesGroup != null) conf.set(CONF_FILES_GROUP, filesGroup);
600 if (filesUser != null) conf.set(CONF_FILES_USER, filesUser);
601 conf.setInt(CONF_FILES_MODE, filesMode);
602 conf.setBoolean(CONF_CHECKSUM_VERIFY, verifyChecksum);
603 conf.set(CONF_OUTPUT_ROOT, outputRoot.toString());
604 conf.set(CONF_INPUT_ROOT, inputRoot.toString());
605 conf.setInt("mapreduce.job.maps", mappers);
606
607
608 conf.setBoolean("mapreduce.map.speculative", false);
609 conf.setBoolean("mapreduce.reduce.speculative", false);
610 conf.setBoolean("mapred.map.tasks.speculative.execution", false);
611 conf.setBoolean("mapred.reduce.tasks.speculative.execution", false);
612
613 Job job = new Job(conf);
614 job.setJobName("ExportSnapshot");
615 job.setJarByClass(ExportSnapshot.class);
616 job.setMapperClass(ExportMapper.class);
617 job.setInputFormatClass(SequenceFileInputFormat.class);
618 job.setOutputFormatClass(NullOutputFormat.class);
619 job.setNumReduceTasks(0);
620 for (Path path: createInputFiles(conf, snapshotFiles, mappers)) {
621 LOG.debug("Add Input Path=" + path);
622 SequenceFileInputFormat.addInputPath(job, path);
623 }
624
625
626 if (!job.waitForCompletion(true)) {
627
628
629 throw new ExportSnapshotException("Copy Files Map-Reduce Job failed");
630 }
631 }
632
633
634
635
636
637 @Override
638 public int run(String[] args) throws IOException {
639 boolean verifyChecksum = true;
640 String snapshotName = null;
641 String targetName = null;
642 boolean overwrite = false;
643 String filesGroup = null;
644 String filesUser = null;
645 Path outputRoot = null;
646 int filesMode = 0;
647 int mappers = 0;
648
649
650 for (int i = 0; i < args.length; i++) {
651 String cmd = args[i];
652 try {
653 if (cmd.equals("-snapshot")) {
654 snapshotName = args[++i];
655 } else if (cmd.equals("-target")) {
656 targetName = args[++i];
657 } else if (cmd.equals("-copy-to")) {
658 outputRoot = new Path(args[++i]);
659 } else if (cmd.equals("-no-checksum-verify")) {
660 verifyChecksum = false;
661 } else if (cmd.equals("-mappers")) {
662 mappers = Integer.parseInt(args[++i]);
663 } else if (cmd.equals("-chuser")) {
664 filesUser = args[++i];
665 } else if (cmd.equals("-chgroup")) {
666 filesGroup = args[++i];
667 } else if (cmd.equals("-chmod")) {
668 filesMode = Integer.parseInt(args[++i], 8);
669 } else if (cmd.equals("-overwrite")) {
670 overwrite = true;
671 } else if (cmd.equals("-h") || cmd.equals("--help")) {
672 printUsageAndExit();
673 } else {
674 System.err.println("UNEXPECTED: " + cmd);
675 printUsageAndExit();
676 }
677 } catch (Exception e) {
678 printUsageAndExit();
679 }
680 }
681
682
683 if (snapshotName == null) {
684 System.err.println("Snapshot name not provided.");
685 printUsageAndExit();
686 }
687
688 if (outputRoot == null) {
689 System.err.println("Destination file-system not provided.");
690 printUsageAndExit();
691 }
692
693 if (targetName == null) {
694 targetName = snapshotName;
695 }
696
697 Configuration conf = getConf();
698 Path inputRoot = FSUtils.getRootDir(conf);
699 FileSystem inputFs = FileSystem.get(conf);
700 FileSystem outputFs = FileSystem.get(outputRoot.toUri(), conf);
701
702 boolean skipTmp = conf.getBoolean(CONF_SKIP_TMP, false);
703
704 Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, inputRoot);
705 Path snapshotTmpDir = SnapshotDescriptionUtils.getWorkingSnapshotDir(targetName, outputRoot);
706 Path outputSnapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(targetName, outputRoot);
707 Path initialOutputSnapshotDir = skipTmp ? outputSnapshotDir : snapshotTmpDir;
708
709
710 if (outputFs.exists(outputSnapshotDir)) {
711 if (overwrite) {
712 if (!outputFs.delete(outputSnapshotDir, true)) {
713 System.err.println("Unable to remove existing snapshot directory: " + outputSnapshotDir);
714 return 1;
715 }
716 } else {
717 System.err.println("The snapshot '" + targetName +
718 "' already exists in the destination: " + outputSnapshotDir);
719 return 1;
720 }
721 }
722
723
724 if (!skipTmp) {
725
726 if (outputFs.exists(snapshotTmpDir)) {
727 if (overwrite) {
728 if (!outputFs.delete(snapshotTmpDir, true)) {
729 System.err.println("Unable to remove existing snapshot tmp directory: "+snapshotTmpDir);
730 return 1;
731 }
732 } else {
733 System.err.println("A snapshot with the same name '"+ targetName +"' may be in-progress");
734 System.err.println("Please check "+snapshotTmpDir+". If the snapshot has completed, ");
735 System.err.println("consider removing "+snapshotTmpDir+" by using the -overwrite option");
736 return 1;
737 }
738 }
739 }
740
741
742 final List<Pair<Path, Long>> files = getSnapshotFiles(inputFs, snapshotDir);
743 if (mappers == 0 && files.size() > 0) {
744 mappers = 1 + (files.size() / conf.getInt(CONF_MAP_GROUP, 10));
745 mappers = Math.min(mappers, files.size());
746 }
747
748
749
750
751 try {
752 LOG.info("Copy Snapshot Manifest");
753 FileUtil.copy(inputFs, snapshotDir, outputFs, initialOutputSnapshotDir, false, false, conf);
754 } catch (IOException e) {
755 throw new ExportSnapshotException("Failed to copy the snapshot directory: from=" +
756 snapshotDir + " to=" + initialOutputSnapshotDir, e);
757 }
758
759
760 if (!targetName.equals(snapshotName)) {
761 SnapshotDescription snapshotDesc =
762 SnapshotDescriptionUtils.readSnapshotInfo(inputFs, snapshotDir)
763 .toBuilder()
764 .setName(targetName)
765 .build();
766 SnapshotDescriptionUtils.writeSnapshotInfo(snapshotDesc, snapshotTmpDir, outputFs);
767 }
768
769
770
771
772 try {
773 if (files.size() == 0) {
774 LOG.warn("There are 0 store file to be copied. There may be no data in the table.");
775 } else {
776 runCopyJob(inputRoot, outputRoot, files, verifyChecksum,
777 filesUser, filesGroup, filesMode, mappers);
778 }
779
780
781 if (!skipTmp) {
782
783 if (!outputFs.rename(snapshotTmpDir, outputSnapshotDir)) {
784 throw new ExportSnapshotException("Unable to rename snapshot directory from=" +
785 snapshotTmpDir + " to=" + outputSnapshotDir);
786 }
787 }
788
789 LOG.info("Export Completed: " + targetName);
790 return 0;
791 } catch (Exception e) {
792 LOG.error("Snapshot export failed", e);
793 if (!skipTmp) {
794 outputFs.delete(snapshotTmpDir, true);
795 }
796 outputFs.delete(outputSnapshotDir, true);
797 return 1;
798 }
799 }
800
801
802 private void printUsageAndExit() {
803 System.err.printf("Usage: bin/hbase %s [options]%n", getClass().getName());
804 System.err.println(" where [options] are:");
805 System.err.println(" -h|-help Show this help and exit.");
806 System.err.println(" -snapshot NAME Snapshot to restore.");
807 System.err.println(" -copy-to NAME Remote destination hdfs://");
808 System.err.println(" -no-checksum-verify Do not verify checksum.");
809 System.err.println(" -overwrite Rewrite the snapshot manifest if already exists");
810 System.err.println(" -chuser USERNAME Change the owner of the files to the specified one.");
811 System.err.println(" -chgroup GROUP Change the group of the files to the specified one.");
812 System.err.println(" -chmod MODE Change the permission of the files to the specified one.");
813 System.err.println(" -mappers Number of mappers to use during the copy (mapreduce.job.maps).");
814 System.err.println();
815 System.err.println("Examples:");
816 System.err.println(" hbase " + getClass().getName() + " \\");
817 System.err.println(" -snapshot MySnapshot -copy-to hdfs://srv2:8082/hbase \\");
818 System.err.println(" -chuser MyUser -chgroup MyGroup -chmod 700 -mappers 16");
819 System.exit(1);
820 }
821
822
823
824
825
826
827
828
829 static int innerMain(final Configuration conf, final String [] args) throws Exception {
830 return ToolRunner.run(conf, new ExportSnapshot(), args);
831 }
832
833 public static void main(String[] args) throws Exception {
834 System.exit(innerMain(HBaseConfiguration.create(), args));
835 }
836 }