1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase.mapreduce;
19
20 import java.io.IOException;
21 import java.util.Iterator;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25 import org.apache.hadoop.conf.Configuration;
26 import org.apache.hadoop.conf.Configured;
27 import org.apache.hadoop.fs.FileStatus;
28 import org.apache.hadoop.fs.FileSystem;
29 import org.apache.hadoop.fs.Path;
30 import org.apache.hadoop.hbase.Cell;
31 import org.apache.hadoop.hbase.CellComparator;
32 import org.apache.hadoop.hbase.CellUtil;
33 import org.apache.hadoop.hbase.HBaseConfiguration;
34 import org.apache.hadoop.hbase.TableName;
35 import org.apache.hadoop.hbase.client.Connection;
36 import org.apache.hadoop.hbase.client.ConnectionFactory;
37 import org.apache.hadoop.hbase.client.Delete;
38 import org.apache.hadoop.hbase.client.Mutation;
39 import org.apache.hadoop.hbase.client.Put;
40 import org.apache.hadoop.hbase.client.Result;
41 import org.apache.hadoop.hbase.client.ResultScanner;
42 import org.apache.hadoop.hbase.client.Scan;
43 import org.apache.hadoop.hbase.client.Table;
44 import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
45 import org.apache.hadoop.hbase.util.Bytes;
46 import org.apache.hadoop.mapreduce.Counters;
47 import org.apache.hadoop.mapreduce.Job;
48 import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
49 import org.apache.hadoop.mapreduce.security.TokenCache;
50 import org.apache.hadoop.util.GenericOptionsParser;
51 import org.apache.hadoop.util.Tool;
52 import org.apache.hadoop.util.ToolRunner;
53
54 import com.google.common.base.Throwables;
55 import com.google.common.collect.Iterators;
56
57 public class SyncTable extends Configured implements Tool {
58
59 private static final Log LOG = LogFactory.getLog(SyncTable.class);
60
61 static final String SOURCE_HASH_DIR_CONF_KEY = "sync.table.source.hash.dir";
62 static final String SOURCE_TABLE_CONF_KEY = "sync.table.source.table.name";
63 static final String TARGET_TABLE_CONF_KEY = "sync.table.target.table.name";
64 static final String SOURCE_ZK_CLUSTER_CONF_KEY = "sync.table.source.zk.cluster";
65 static final String TARGET_ZK_CLUSTER_CONF_KEY = "sync.table.target.zk.cluster";
66 static final String DRY_RUN_CONF_KEY = "sync.table.dry.run";
67 static final String DO_DELETES_CONF_KEY = "sync.table.do.deletes";
68 static final String DO_PUTS_CONF_KEY = "sync.table.do.puts";
69
70 Path sourceHashDir;
71 String sourceTableName;
72 String targetTableName;
73
74 String sourceZkCluster;
75 String targetZkCluster;
76 boolean dryRun;
77 boolean doDeletes = true;
78 boolean doPuts = true;
79
80 Counters counters;
81
82 public SyncTable(Configuration conf) {
83 super(conf);
84 }
85
86 private void initCredentialsForHBase(String zookeeper, Job job) throws IOException {
87 Configuration peerConf = HBaseConfiguration.createClusterConf(job
88 .getConfiguration(), zookeeper);
89 if(peerConf.get("hbase.security.authentication").equals("kerberos")){
90 TableMapReduceUtil.initCredentialsForCluster(job, peerConf);
91 }
92 }
93
94 public Job createSubmittableJob(String[] args) throws IOException {
95 FileSystem fs = sourceHashDir.getFileSystem(getConf());
96 if (!fs.exists(sourceHashDir)) {
97 throw new IOException("Source hash dir not found: " + sourceHashDir);
98 }
99
100 Job job = Job.getInstance(getConf(),getConf().get("mapreduce.job.name",
101 "syncTable_" + sourceTableName + "-" + targetTableName));
102 Configuration jobConf = job.getConfiguration();
103 if (jobConf.get("hadoop.security.authentication").equals("kerberos")) {
104 TokenCache.obtainTokensForNamenodes(job.getCredentials(), new
105 Path[] { sourceHashDir }, getConf());
106 }
107
108 HashTable.TableHash tableHash = HashTable.TableHash.read(getConf(), sourceHashDir);
109 LOG.info("Read source hash manifest: " + tableHash);
110 LOG.info("Read " + tableHash.partitions.size() + " partition keys");
111 if (!tableHash.tableName.equals(sourceTableName)) {
112 LOG.warn("Table name mismatch - manifest indicates hash was taken from: "
113 + tableHash.tableName + " but job is reading from: " + sourceTableName);
114 }
115 if (tableHash.numHashFiles != tableHash.partitions.size() + 1) {
116 throw new RuntimeException("Hash data appears corrupt. The number of of hash files created"
117 + " should be 1 more than the number of partition keys. However, the manifest file "
118 + " says numHashFiles=" + tableHash.numHashFiles + " but the number of partition keys"
119 + " found in the partitions file is " + tableHash.partitions.size());
120 }
121
122 Path dataDir = new Path(sourceHashDir, HashTable.HASH_DATA_DIR);
123 int dataSubdirCount = 0;
124 for (FileStatus file : fs.listStatus(dataDir)) {
125 if (file.getPath().getName().startsWith(HashTable.OUTPUT_DATA_FILE_PREFIX)) {
126 dataSubdirCount++;
127 }
128 }
129
130 if (dataSubdirCount != tableHash.numHashFiles) {
131 throw new RuntimeException("Hash data appears corrupt. The number of of hash files created"
132 + " should be 1 more than the number of partition keys. However, the number of data dirs"
133 + " found is " + dataSubdirCount + " but the number of partition keys"
134 + " found in the partitions file is " + tableHash.partitions.size());
135 }
136
137 job.setJarByClass(HashTable.class);
138 jobConf.set(SOURCE_HASH_DIR_CONF_KEY, sourceHashDir.toString());
139 jobConf.set(SOURCE_TABLE_CONF_KEY, sourceTableName);
140 jobConf.set(TARGET_TABLE_CONF_KEY, targetTableName);
141 if (sourceZkCluster != null) {
142 jobConf.set(SOURCE_ZK_CLUSTER_CONF_KEY, sourceZkCluster);
143 initCredentialsForHBase(sourceZkCluster, job);
144 }
145 if (targetZkCluster != null) {
146 jobConf.set(TARGET_ZK_CLUSTER_CONF_KEY, targetZkCluster);
147 initCredentialsForHBase(targetZkCluster, job);
148 }
149 jobConf.setBoolean(DRY_RUN_CONF_KEY, dryRun);
150 jobConf.setBoolean(DO_DELETES_CONF_KEY, doDeletes);
151 jobConf.setBoolean(DO_PUTS_CONF_KEY, doPuts);
152
153 TableMapReduceUtil.initTableMapperJob(targetTableName, tableHash.initScan(),
154 SyncMapper.class, null, null, job);
155
156 job.setNumReduceTasks(0);
157
158 if (dryRun) {
159 job.setOutputFormatClass(NullOutputFormat.class);
160 } else {
161
162
163 TableMapReduceUtil.initTableReducerJob(targetTableName, null, job, null,
164 targetZkCluster, null, null);
165
166
167 }
168
169
170 if (sourceZkCluster != null) {
171 Configuration peerConf =
172 HBaseConfiguration.createClusterConf(job.getConfiguration(), sourceZkCluster);
173 TableMapReduceUtil.initCredentialsForCluster(job, peerConf);
174 }
175 return job;
176 }
177
178 public static class SyncMapper extends TableMapper<ImmutableBytesWritable, Mutation> {
179 Path sourceHashDir;
180
181 Connection sourceConnection;
182 Connection targetConnection;
183 Table sourceTable;
184 Table targetTable;
185 boolean dryRun;
186 boolean doDeletes = true;
187 boolean doPuts = true;
188
189 HashTable.TableHash sourceTableHash;
190 HashTable.TableHash.Reader sourceHashReader;
191 ImmutableBytesWritable currentSourceHash;
192 ImmutableBytesWritable nextSourceKey;
193 HashTable.ResultHasher targetHasher;
194
195 Throwable mapperException;
196
197 public static enum Counter {BATCHES, HASHES_MATCHED, HASHES_NOT_MATCHED, SOURCEMISSINGROWS,
198 SOURCEMISSINGCELLS, TARGETMISSINGROWS, TARGETMISSINGCELLS, ROWSWITHDIFFS, DIFFERENTCELLVALUES,
199 MATCHINGROWS, MATCHINGCELLS, EMPTY_BATCHES, RANGESMATCHED, RANGESNOTMATCHED};
200
201 @Override
202 protected void setup(Context context) throws IOException {
203
204 Configuration conf = context.getConfiguration();
205 sourceHashDir = new Path(conf.get(SOURCE_HASH_DIR_CONF_KEY));
206 sourceConnection = openConnection(conf, SOURCE_ZK_CLUSTER_CONF_KEY, null);
207 targetConnection = openConnection(conf, TARGET_ZK_CLUSTER_CONF_KEY,
208 TableOutputFormat.OUTPUT_CONF_PREFIX);
209 sourceTable = openTable(sourceConnection, conf, SOURCE_TABLE_CONF_KEY);
210 targetTable = openTable(targetConnection, conf, TARGET_TABLE_CONF_KEY);
211 dryRun = conf.getBoolean(DRY_RUN_CONF_KEY, false);
212 doDeletes = conf.getBoolean(DO_DELETES_CONF_KEY, true);
213 doPuts = conf.getBoolean(DO_PUTS_CONF_KEY, true);
214
215 sourceTableHash = HashTable.TableHash.read(conf, sourceHashDir);
216 LOG.info("Read source hash manifest: " + sourceTableHash);
217 LOG.info("Read " + sourceTableHash.partitions.size() + " partition keys");
218
219 TableSplit split = (TableSplit) context.getInputSplit();
220 ImmutableBytesWritable splitStartKey = new ImmutableBytesWritable(split.getStartRow());
221
222 sourceHashReader = sourceTableHash.newReader(conf, splitStartKey);
223 findNextKeyHashPair();
224
225
226
227
228 targetHasher = new HashTable.ResultHasher();
229 }
230
231 private static Connection openConnection(Configuration conf, String zkClusterConfKey,
232 String configPrefix)
233 throws IOException {
234 String zkCluster = conf.get(zkClusterConfKey);
235 Configuration clusterConf = HBaseConfiguration.createClusterConf(conf,
236 zkCluster, configPrefix);
237 return ConnectionFactory.createConnection(clusterConf);
238 }
239
240 private static Table openTable(Connection connection, Configuration conf,
241 String tableNameConfKey) throws IOException {
242 return connection.getTable(TableName.valueOf(conf.get(tableNameConfKey)));
243 }
244
245
246
247
248
249 private void findNextKeyHashPair() throws IOException {
250 boolean hasNext = sourceHashReader.next();
251 if (hasNext) {
252 nextSourceKey = sourceHashReader.getCurrentKey();
253 } else {
254
255 nextSourceKey = null;
256 }
257 }
258
259 @Override
260 protected void map(ImmutableBytesWritable key, Result value, Context context)
261 throws IOException, InterruptedException {
262 try {
263
264 while (nextSourceKey != null && key.compareTo(nextSourceKey) >= 0) {
265 moveToNextBatch(context);
266 }
267
268
269 if (targetHasher.isBatchStarted()) {
270 targetHasher.hashResult(value);
271 }
272 } catch (Throwable t) {
273 mapperException = t;
274 Throwables.propagateIfInstanceOf(t, IOException.class);
275 Throwables.propagateIfInstanceOf(t, InterruptedException.class);
276 Throwables.propagate(t);
277 }
278 }
279
280
281
282
283
284 private void moveToNextBatch(Context context) throws IOException, InterruptedException {
285 if (targetHasher.isBatchStarted()) {
286 finishBatchAndCompareHashes(context);
287 }
288 targetHasher.startBatch(nextSourceKey);
289 currentSourceHash = sourceHashReader.getCurrentHash();
290
291 findNextKeyHashPair();
292 }
293
294
295
296
297
298
299 private void finishBatchAndCompareHashes(Context context)
300 throws IOException, InterruptedException {
301 targetHasher.finishBatch();
302 context.getCounter(Counter.BATCHES).increment(1);
303 if (targetHasher.getBatchSize() == 0) {
304 context.getCounter(Counter.EMPTY_BATCHES).increment(1);
305 }
306 ImmutableBytesWritable targetHash = targetHasher.getBatchHash();
307 if (targetHash.equals(currentSourceHash)) {
308 context.getCounter(Counter.HASHES_MATCHED).increment(1);
309 } else {
310 context.getCounter(Counter.HASHES_NOT_MATCHED).increment(1);
311
312 ImmutableBytesWritable stopRow = nextSourceKey == null
313 ? new ImmutableBytesWritable(sourceTableHash.stopRow)
314 : nextSourceKey;
315
316 if (LOG.isDebugEnabled()) {
317 LOG.debug("Hash mismatch. Key range: " + toHex(targetHasher.getBatchStartKey())
318 + " to " + toHex(stopRow)
319 + " sourceHash: " + toHex(currentSourceHash)
320 + " targetHash: " + toHex(targetHash));
321 }
322
323 syncRange(context, targetHasher.getBatchStartKey(), stopRow);
324 }
325 }
326 private static String toHex(ImmutableBytesWritable bytes) {
327 return Bytes.toHex(bytes.get(), bytes.getOffset(), bytes.getLength());
328 }
329
330 private static final CellScanner EMPTY_CELL_SCANNER
331 = new CellScanner(Iterators.<Result>emptyIterator());
332
333
334
335
336
337
338 private void syncRange(Context context, ImmutableBytesWritable startRow,
339 ImmutableBytesWritable stopRow) throws IOException, InterruptedException {
340 Scan scan = sourceTableHash.initScan();
341 scan.setStartRow(startRow.copyBytes());
342 scan.setStopRow(stopRow.copyBytes());
343
344 ResultScanner sourceScanner = sourceTable.getScanner(scan);
345 CellScanner sourceCells = new CellScanner(sourceScanner.iterator());
346
347 ResultScanner targetScanner = targetTable.getScanner(new Scan(scan));
348 CellScanner targetCells = new CellScanner(targetScanner.iterator());
349
350 boolean rangeMatched = true;
351 byte[] nextSourceRow = sourceCells.nextRow();
352 byte[] nextTargetRow = targetCells.nextRow();
353 while(nextSourceRow != null || nextTargetRow != null) {
354 boolean rowMatched;
355 int rowComparison = compareRowKeys(nextSourceRow, nextTargetRow);
356 if (rowComparison < 0) {
357 if (LOG.isInfoEnabled()) {
358 LOG.info("Target missing row: " + Bytes.toHex(nextSourceRow));
359 }
360 context.getCounter(Counter.TARGETMISSINGROWS).increment(1);
361
362 rowMatched = syncRowCells(context, nextSourceRow, sourceCells, EMPTY_CELL_SCANNER);
363 nextSourceRow = sourceCells.nextRow();
364 } else if (rowComparison > 0) {
365 if (LOG.isInfoEnabled()) {
366 LOG.info("Source missing row: " + Bytes.toHex(nextTargetRow));
367 }
368 context.getCounter(Counter.SOURCEMISSINGROWS).increment(1);
369
370 rowMatched = syncRowCells(context, nextTargetRow, EMPTY_CELL_SCANNER, targetCells);
371 nextTargetRow = targetCells.nextRow();
372 } else {
373
374 rowMatched = syncRowCells(context, nextSourceRow, sourceCells, targetCells);
375 nextSourceRow = sourceCells.nextRow();
376 nextTargetRow = targetCells.nextRow();
377 }
378
379 if (!rowMatched) {
380 rangeMatched = false;
381 }
382 }
383
384 sourceScanner.close();
385 targetScanner.close();
386
387 context.getCounter(rangeMatched ? Counter.RANGESMATCHED : Counter.RANGESNOTMATCHED)
388 .increment(1);
389 }
390
391 private static class CellScanner {
392 private final Iterator<Result> results;
393
394 private byte[] currentRow;
395 private Result currentRowResult;
396 private int nextCellInRow;
397
398 private Result nextRowResult;
399
400 public CellScanner(Iterator<Result> results) {
401 this.results = results;
402 }
403
404
405
406
407
408 public byte[] nextRow() {
409 if (nextRowResult == null) {
410
411 while (results.hasNext()) {
412 nextRowResult = results.next();
413 Cell nextCell = nextRowResult.rawCells()[0];
414 if (currentRow == null
415 || !Bytes.equals(currentRow, 0, currentRow.length, nextCell.getRowArray(),
416 nextCell.getRowOffset(), nextCell.getRowLength())) {
417
418 break;
419 } else {
420
421 nextRowResult = null;
422 }
423 }
424
425 if (nextRowResult == null) {
426
427 currentRowResult = null;
428 currentRow = null;
429 return null;
430 }
431 }
432
433
434 currentRowResult = nextRowResult;
435 nextCellInRow = 0;
436 currentRow = currentRowResult.getRow();
437 nextRowResult = null;
438 return currentRow;
439 }
440
441
442
443
444 public Cell nextCellInRow() {
445 if (currentRowResult == null) {
446
447 return null;
448 }
449
450 Cell nextCell = currentRowResult.rawCells()[nextCellInRow];
451 nextCellInRow++;
452 if (nextCellInRow == currentRowResult.size()) {
453 if (results.hasNext()) {
454 Result result = results.next();
455 Cell cell = result.rawCells()[0];
456 if (Bytes.equals(currentRow, 0, currentRow.length, cell.getRowArray(),
457 cell.getRowOffset(), cell.getRowLength())) {
458
459 currentRowResult = result;
460 nextCellInRow = 0;
461 } else {
462
463 nextRowResult = result;
464
465 currentRowResult = null;
466 }
467 } else {
468
469 currentRowResult = null;
470 }
471 }
472 return nextCell;
473 }
474 }
475
476
477
478
479
480
481
482 private boolean syncRowCells(Context context, byte[] rowKey, CellScanner sourceCells,
483 CellScanner targetCells) throws IOException, InterruptedException {
484 Put put = null;
485 Delete delete = null;
486 long matchingCells = 0;
487 boolean matchingRow = true;
488 Cell sourceCell = sourceCells.nextCellInRow();
489 Cell targetCell = targetCells.nextCellInRow();
490 while (sourceCell != null || targetCell != null) {
491
492 int cellKeyComparison = compareCellKeysWithinRow(sourceCell, targetCell);
493 if (cellKeyComparison < 0) {
494 if (LOG.isDebugEnabled()) {
495 LOG.debug("Target missing cell: " + sourceCell);
496 }
497 context.getCounter(Counter.TARGETMISSINGCELLS).increment(1);
498 matchingRow = false;
499
500 if (!dryRun && doPuts) {
501 if (put == null) {
502 put = new Put(rowKey);
503 }
504 put.add(sourceCell);
505 }
506
507 sourceCell = sourceCells.nextCellInRow();
508 } else if (cellKeyComparison > 0) {
509 if (LOG.isDebugEnabled()) {
510 LOG.debug("Source missing cell: " + targetCell);
511 }
512 context.getCounter(Counter.SOURCEMISSINGCELLS).increment(1);
513 matchingRow = false;
514
515 if (!dryRun && doDeletes) {
516 if (delete == null) {
517 delete = new Delete(rowKey);
518 }
519
520 delete.addColumn(CellUtil.cloneFamily(targetCell),
521 CellUtil.cloneQualifier(targetCell), targetCell.getTimestamp());
522 }
523
524 targetCell = targetCells.nextCellInRow();
525 } else {
526
527 if (CellUtil.matchingValue(sourceCell, targetCell)) {
528 matchingCells++;
529 } else {
530 if (LOG.isDebugEnabled()) {
531 LOG.debug("Different values: ");
532 LOG.debug(" source cell: " + sourceCell
533 + " value: " + Bytes.toHex(sourceCell.getValueArray(),
534 sourceCell.getValueOffset(), sourceCell.getValueLength()));
535 LOG.debug(" target cell: " + targetCell
536 + " value: " + Bytes.toHex(targetCell.getValueArray(),
537 targetCell.getValueOffset(), targetCell.getValueLength()));
538 }
539 context.getCounter(Counter.DIFFERENTCELLVALUES).increment(1);
540 matchingRow = false;
541
542 if (!dryRun && doPuts) {
543
544 if (put == null) {
545 put = new Put(rowKey);
546 }
547 put.add(sourceCell);
548 }
549 }
550 sourceCell = sourceCells.nextCellInRow();
551 targetCell = targetCells.nextCellInRow();
552 }
553
554 if (!dryRun && sourceTableHash.scanBatch > 0) {
555 if (put != null && put.size() >= sourceTableHash.scanBatch) {
556 context.write(new ImmutableBytesWritable(rowKey), put);
557 put = null;
558 }
559 if (delete != null && delete.size() >= sourceTableHash.scanBatch) {
560 context.write(new ImmutableBytesWritable(rowKey), delete);
561 delete = null;
562 }
563 }
564 }
565
566 if (!dryRun) {
567 if (put != null) {
568 context.write(new ImmutableBytesWritable(rowKey), put);
569 }
570 if (delete != null) {
571 context.write(new ImmutableBytesWritable(rowKey), delete);
572 }
573 }
574
575 if (matchingCells > 0) {
576 context.getCounter(Counter.MATCHINGCELLS).increment(matchingCells);
577 }
578 if (matchingRow) {
579 context.getCounter(Counter.MATCHINGROWS).increment(1);
580 return true;
581 } else {
582 context.getCounter(Counter.ROWSWITHDIFFS).increment(1);
583 return false;
584 }
585 }
586
587 private static final CellComparator cellComparator = new CellComparator();
588
589
590
591
592 private static int compareRowKeys(byte[] r1, byte[] r2) {
593 if (r1 == null) {
594 return 1;
595 } else if (r2 == null) {
596 return -1;
597 } else {
598 return cellComparator.compareRows(r1, 0, r1.length, r2, 0, r2.length);
599 }
600 }
601
602
603
604
605
606
607 private static int compareCellKeysWithinRow(Cell c1, Cell c2) {
608 if (c1 == null) {
609 return 1;
610 }
611 if (c2 == null) {
612 return -1;
613 }
614
615 int result = CellComparator.compareFamilies(c1, c2);
616 if (result != 0) {
617 return result;
618 }
619
620 result = CellComparator.compareQualifiers(c1, c2);
621 if (result != 0) {
622 return result;
623 }
624
625
626 return CellComparator.compareTimestamps(c1, c2);
627 }
628
629 @Override
630 protected void cleanup(Context context)
631 throws IOException, InterruptedException {
632 if (mapperException == null) {
633 try {
634 finishRemainingHashRanges(context);
635 } catch (Throwable t) {
636 mapperException = t;
637 }
638 }
639
640 try {
641 sourceTable.close();
642 targetTable.close();
643 sourceConnection.close();
644 targetConnection.close();
645 } catch (Throwable t) {
646 if (mapperException == null) {
647 mapperException = t;
648 } else {
649 LOG.error("Suppressing exception from closing tables", t);
650 }
651 }
652
653
654 if (mapperException != null) {
655 Throwables.propagateIfInstanceOf(mapperException, IOException.class);
656 Throwables.propagateIfInstanceOf(mapperException, InterruptedException.class);
657 Throwables.propagate(mapperException);
658 }
659 }
660
661 private void finishRemainingHashRanges(Context context) throws IOException,
662 InterruptedException {
663 TableSplit split = (TableSplit) context.getInputSplit();
664 byte[] splitEndRow = split.getEndRow();
665 boolean reachedEndOfTable = HashTable.isTableEndRow(splitEndRow);
666
667
668 while (nextSourceKey != null
669 && (nextSourceKey.compareTo(splitEndRow) < 0 || reachedEndOfTable)) {
670 moveToNextBatch(context);
671 }
672
673 if (targetHasher.isBatchStarted()) {
674
675
676 if ((nextSourceKey != null && nextSourceKey.compareTo(splitEndRow) > 0)
677 || (nextSourceKey == null && !Bytes.equals(splitEndRow, sourceTableHash.stopRow))) {
678
679
680 Scan scan = sourceTableHash.initScan();
681 scan.setStartRow(splitEndRow);
682 if (nextSourceKey == null) {
683 scan.setStopRow(sourceTableHash.stopRow);
684 } else {
685 scan.setStopRow(nextSourceKey.copyBytes());
686 }
687
688 ResultScanner targetScanner = null;
689 try {
690 targetScanner = targetTable.getScanner(scan);
691 for (Result row : targetScanner) {
692 targetHasher.hashResult(row);
693 }
694 } finally {
695 if (targetScanner != null) {
696 targetScanner.close();
697 }
698 }
699 }
700
701 finishBatchAndCompareHashes(context);
702 }
703 }
704 }
705
706 private static final int NUM_ARGS = 3;
707 private static void printUsage(final String errorMsg) {
708 if (errorMsg != null && errorMsg.length() > 0) {
709 System.err.println("ERROR: " + errorMsg);
710 System.err.println();
711 }
712 System.err.println("Usage: SyncTable [options] <sourcehashdir> <sourcetable> <targettable>");
713 System.err.println();
714 System.err.println("Options:");
715
716 System.err.println(" sourcezkcluster ZK cluster key of the source table");
717 System.err.println(" (defaults to cluster in classpath's config)");
718 System.err.println(" targetzkcluster ZK cluster key of the target table");
719 System.err.println(" (defaults to cluster in classpath's config)");
720 System.err.println(" dryrun if true, output counters but no writes");
721 System.err.println(" (defaults to false)");
722 System.err.println(" doDeletes if false, does not perform deletes");
723 System.err.println(" (defaults to true)");
724 System.err.println(" doPuts if false, does not perform puts ");
725 System.err.println(" (defaults to true)");
726 System.err.println();
727 System.err.println("Args:");
728 System.err.println(" sourcehashdir path to HashTable output dir for source table");
729 System.err.println(" (see org.apache.hadoop.hbase.mapreduce.HashTable)");
730 System.err.println(" sourcetable Name of the source table to sync from");
731 System.err.println(" targettable Name of the target table to sync to");
732 System.err.println();
733 System.err.println("Examples:");
734 System.err.println(" For a dry run SyncTable of tableA from a remote source cluster");
735 System.err.println(" to a local target cluster:");
736 System.err.println(" $ bin/hbase " +
737 "org.apache.hadoop.hbase.mapreduce.SyncTable --dryrun=true"
738 + " --sourcezkcluster=zk1.example.com,zk2.example.com,zk3.example.com:2181:/hbase"
739 + " hdfs://nn:9000/hashes/tableA tableA tableA");
740 }
741
742 private boolean doCommandLine(final String[] args) {
743 if (args.length < NUM_ARGS) {
744 printUsage(null);
745 return false;
746 }
747 try {
748 sourceHashDir = new Path(args[args.length - 3]);
749 sourceTableName = args[args.length - 2];
750 targetTableName = args[args.length - 1];
751
752 for (int i = 0; i < args.length - NUM_ARGS; i++) {
753 String cmd = args[i];
754 if (cmd.equals("-h") || cmd.startsWith("--h")) {
755 printUsage(null);
756 return false;
757 }
758
759 final String sourceZkClusterKey = "--sourcezkcluster=";
760 if (cmd.startsWith(sourceZkClusterKey)) {
761 sourceZkCluster = cmd.substring(sourceZkClusterKey.length());
762 continue;
763 }
764
765 final String targetZkClusterKey = "--targetzkcluster=";
766 if (cmd.startsWith(targetZkClusterKey)) {
767 targetZkCluster = cmd.substring(targetZkClusterKey.length());
768 continue;
769 }
770
771 final String dryRunKey = "--dryrun=";
772 if (cmd.startsWith(dryRunKey)) {
773 dryRun = Boolean.parseBoolean(cmd.substring(dryRunKey.length()));
774 continue;
775 }
776
777 final String doDeletesKey = "--doDeletes=";
778 if (cmd.startsWith(doDeletesKey)) {
779 doDeletes = Boolean.parseBoolean(cmd.substring(doDeletesKey.length()));
780 continue;
781 }
782
783 final String doPutsKey = "--doPuts=";
784 if (cmd.startsWith(doPutsKey)) {
785 doPuts = Boolean.parseBoolean(cmd.substring(doPutsKey.length()));
786 continue;
787 }
788
789 printUsage("Invalid argument '" + cmd + "'");
790 return false;
791 }
792
793
794 } catch (Exception e) {
795 e.printStackTrace();
796 printUsage("Can't start because " + e.getMessage());
797 return false;
798 }
799 return true;
800 }
801
802
803
804
805 public static void main(String[] args) throws Exception {
806 int ret = ToolRunner.run(new SyncTable(HBaseConfiguration.create()), args);
807 System.exit(ret);
808 }
809
810 @Override
811 public int run(String[] args) throws Exception {
812 String[] otherArgs = new GenericOptionsParser(getConf(), args).getRemainingArgs();
813 if (!doCommandLine(otherArgs)) {
814 return 1;
815 }
816
817 Job job = createSubmittableJob(otherArgs);
818 if (!job.waitForCompletion(true)) {
819 LOG.info("Map-reduce job failed!");
820 return 1;
821 }
822 counters = job.getCounters();
823 return 0;
824 }
825
826 }