View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.mapreduce.replication;
20  
21  import java.io.IOException;
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.hbase.*;
28  import org.apache.hadoop.hbase.client.HConnectable;
29  import org.apache.hadoop.hbase.client.HConnection;
30  import org.apache.hadoop.hbase.client.HConnectionManager;
31  import org.apache.hadoop.hbase.client.HTable;
32  import org.apache.hadoop.hbase.client.Put;
33  import org.apache.hadoop.hbase.client.Result;
34  import org.apache.hadoop.hbase.client.ResultScanner;
35  import org.apache.hadoop.hbase.client.Scan;
36  import org.apache.hadoop.hbase.client.Table;
37  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
38  import org.apache.hadoop.hbase.mapreduce.TableInputFormat;
39  import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
40  import org.apache.hadoop.hbase.mapreduce.TableMapper;
41  import org.apache.hadoop.hbase.mapreduce.TableSplit;
42  import org.apache.hadoop.hbase.replication.ReplicationException;
43  import org.apache.hadoop.hbase.replication.ReplicationFactory;
44  import org.apache.hadoop.hbase.replication.ReplicationPeerZKImpl;
45  import org.apache.hadoop.hbase.replication.ReplicationPeerConfig;
46  import org.apache.hadoop.hbase.replication.ReplicationPeers;
47  import org.apache.hadoop.hbase.util.Bytes;
48  import org.apache.hadoop.hbase.util.Pair;
49  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
50  import org.apache.hadoop.hbase.zookeeper.ZKUtil;
51  import org.apache.hadoop.mapreduce.Job;
52  import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
53  import org.apache.hadoop.util.Tool;
54  import org.apache.hadoop.util.ToolRunner;
55  
56  /**
57   * This map-only job compares the data from a local table with a remote one.
58   * Every cell is compared and must have exactly the same keys (even timestamp)
59   * as well as same value. It is possible to restrict the job by time range and
60   * families. The peer id that's provided must match the one given when the
61   * replication stream was setup.
62   * <p>
63   * Two counters are provided, Verifier.Counters.GOODROWS and BADROWS. The reason
64   * for a why a row is different is shown in the map's log.
65   */
66  public class VerifyReplication extends Configured implements Tool {
67  
68    private static final Log LOG =
69        LogFactory.getLog(VerifyReplication.class);
70  
71    public final static String NAME = "verifyrep";
72    static long startTime = 0;
73    static long endTime = Long.MAX_VALUE;
74    static int versions = -1;
75    static String tableName = null;
76    static String families = null;
77    static String peerId = null;
78  
79    private final static String JOB_NAME_CONF_KEY = "mapreduce.job.name";
80  
81    /**
82     * Map-only comparator for 2 tables
83     */
84    public static class Verifier
85        extends TableMapper<ImmutableBytesWritable, Put> {
86  
87      public static enum Counters {
88        GOODROWS, BADROWS, ONLY_IN_SOURCE_TABLE_ROWS, ONLY_IN_PEER_TABLE_ROWS, CONTENT_DIFFERENT_ROWS}
89  
90      private ResultScanner replicatedScanner;
91      private Result currentCompareRowInPeerTable;
92  
93      /**
94       * Map method that compares every scanned row with the equivalent from
95       * a distant cluster.
96       * @param row  The current table row key.
97       * @param value  The columns.
98       * @param context  The current context.
99       * @throws IOException When something is broken with the data.
100      */
101     @Override
102     public void map(ImmutableBytesWritable row, final Result value,
103                     Context context)
104         throws IOException {
105       if (replicatedScanner == null) {
106         Configuration conf = context.getConfiguration();
107         final Scan scan = new Scan();
108         scan.setCaching(conf.getInt(TableInputFormat.SCAN_CACHEDROWS, 1));
109         long startTime = conf.getLong(NAME + ".startTime", 0);
110         long endTime = conf.getLong(NAME + ".endTime", Long.MAX_VALUE);
111         String families = conf.get(NAME + ".families", null);
112         if(families != null) {
113           String[] fams = families.split(",");
114           for(String fam : fams) {
115             scan.addFamily(Bytes.toBytes(fam));
116           }
117         }
118         scan.setTimeRange(startTime, endTime);
119         if (versions >= 0) {
120           scan.setMaxVersions(versions);
121         }
122 
123         final TableSplit tableSplit = (TableSplit)(context.getInputSplit());
124         HConnectionManager.execute(new HConnectable<Void>(conf) {
125           @Override
126           public Void connect(HConnection conn) throws IOException {
127             String zkClusterKey = conf.get(NAME + ".peerQuorumAddress");
128             Configuration peerConf = HBaseConfiguration.create(conf);
129             ZKUtil.applyClusterKeyToConf(peerConf, zkClusterKey);
130 
131             TableName tableName = TableName.valueOf(conf.get(NAME + ".tableName"));
132             // TODO: THis HTable doesn't get closed.  Fix!
133             Table replicatedTable = new HTable(peerConf, tableName);
134             scan.setStartRow(value.getRow());
135             scan.setStopRow(tableSplit.getEndRow());
136             replicatedScanner = replicatedTable.getScanner(scan);
137             return null;
138           }
139         });
140         currentCompareRowInPeerTable = replicatedScanner.next();
141       }
142       while (true) {
143         if (currentCompareRowInPeerTable == null) {
144           // reach the region end of peer table, row only in source table
145           logFailRowAndIncreaseCounter(context, Counters.ONLY_IN_SOURCE_TABLE_ROWS, value);
146           break;
147         }
148         int rowCmpRet = Bytes.compareTo(value.getRow(), currentCompareRowInPeerTable.getRow());
149         if (rowCmpRet == 0) {
150           // rowkey is same, need to compare the content of the row
151           try {
152             Result.compareResults(value, currentCompareRowInPeerTable);
153             context.getCounter(Counters.GOODROWS).increment(1);
154           } catch (Exception e) {
155             logFailRowAndIncreaseCounter(context, Counters.CONTENT_DIFFERENT_ROWS, value);
156           }
157           currentCompareRowInPeerTable = replicatedScanner.next();
158           break;
159         } else if (rowCmpRet < 0) {
160           // row only exists in source table
161           logFailRowAndIncreaseCounter(context, Counters.ONLY_IN_SOURCE_TABLE_ROWS, value);
162           break;
163         } else {
164           // row only exists in peer table
165           logFailRowAndIncreaseCounter(context, Counters.ONLY_IN_PEER_TABLE_ROWS,
166             currentCompareRowInPeerTable);
167           currentCompareRowInPeerTable = replicatedScanner.next();
168         }
169       }
170     }
171 
172     private void logFailRowAndIncreaseCounter(Context context, Counters counter, Result row) {
173       context.getCounter(counter).increment(1);
174       context.getCounter(Counters.BADROWS).increment(1);
175       LOG.error(counter.toString() + ", rowkey=" + Bytes.toString(row.getRow()));
176     }
177 
178     @Override
179     protected void cleanup(Context context) {
180       if (replicatedScanner != null) {
181         try {
182           while (currentCompareRowInPeerTable != null) {
183             logFailRowAndIncreaseCounter(context, Counters.ONLY_IN_PEER_TABLE_ROWS,
184               currentCompareRowInPeerTable);
185             currentCompareRowInPeerTable = replicatedScanner.next();
186           }
187         } catch (Exception e) {
188           LOG.error("fail to scan peer table in cleanup", e);
189         } finally {
190           replicatedScanner.close();
191           replicatedScanner = null;
192         }
193       }
194     }
195   }
196 
197   private static String getPeerQuorumAddress(final Configuration conf) throws IOException {
198     ZooKeeperWatcher localZKW = null;
199     ReplicationPeerZKImpl peer = null;
200     try {
201       localZKW = new ZooKeeperWatcher(conf, "VerifyReplication",
202           new Abortable() {
203             @Override public void abort(String why, Throwable e) {}
204             @Override public boolean isAborted() {return false;}
205           });
206 
207       ReplicationPeers rp = ReplicationFactory.getReplicationPeers(localZKW, conf, localZKW);
208       rp.init();
209 
210       Pair<ReplicationPeerConfig, Configuration> pair = rp.getPeerConf(peerId);
211       if (pair == null) {
212         throw new IOException("Couldn't get peer conf!");
213       }
214       Configuration peerConf = rp.getPeerConf(peerId).getSecond();
215       return ZKUtil.getZooKeeperClusterKey(peerConf);
216     } catch (ReplicationException e) {
217       throw new IOException(
218           "An error occured while trying to connect to the remove peer cluster", e);
219     } finally {
220       if (peer != null) {
221         peer.close();
222       }
223       if (localZKW != null) {
224         localZKW.close();
225       }
226     }
227   }
228 
229   /**
230    * Sets up the actual job.
231    *
232    * @param conf  The current configuration.
233    * @param args  The command line parameters.
234    * @return The newly created job.
235    * @throws java.io.IOException When setting up the job fails.
236    */
237   public static Job createSubmittableJob(Configuration conf, String[] args)
238   throws IOException {
239     if (!doCommandLine(args)) {
240       return null;
241     }
242     if (!conf.getBoolean(HConstants.REPLICATION_ENABLE_KEY,
243         HConstants.REPLICATION_ENABLE_DEFAULT)) {
244       throw new IOException("Replication needs to be enabled to verify it.");
245     }
246     conf.set(NAME+".peerId", peerId);
247     conf.set(NAME+".tableName", tableName);
248     conf.setLong(NAME+".startTime", startTime);
249     conf.setLong(NAME+".endTime", endTime);
250     if (families != null) {
251       conf.set(NAME+".families", families);
252     }
253 
254     String peerQuorumAddress = getPeerQuorumAddress(conf);
255     conf.set(NAME + ".peerQuorumAddress", peerQuorumAddress);
256     LOG.info("Peer Quorum Address: " + peerQuorumAddress);
257 
258     Job job = Job.getInstance(conf, conf.get(JOB_NAME_CONF_KEY, NAME + "_" + tableName));
259     job.setJarByClass(VerifyReplication.class);
260 
261     Scan scan = new Scan();
262     scan.setTimeRange(startTime, endTime);
263     if (versions >= 0) {
264       scan.setMaxVersions(versions);
265     }
266     if(families != null) {
267       String[] fams = families.split(",");
268       for(String fam : fams) {
269         scan.addFamily(Bytes.toBytes(fam));
270       }
271     }
272     TableMapReduceUtil.initTableMapperJob(tableName, scan,
273         Verifier.class, null, null, job);
274 
275     // Obtain the auth token from peer cluster
276     TableMapReduceUtil.initCredentialsForCluster(job, peerQuorumAddress);
277 
278     job.setOutputFormatClass(NullOutputFormat.class);
279     job.setNumReduceTasks(0);
280     return job;
281   }
282 
283   private static boolean doCommandLine(final String[] args) {
284     if (args.length < 2) {
285       printUsage(null);
286       return false;
287     }
288     try {
289       for (int i = 0; i < args.length; i++) {
290         String cmd = args[i];
291         if (cmd.equals("-h") || cmd.startsWith("--h")) {
292           printUsage(null);
293           return false;
294         }
295 
296         final String startTimeArgKey = "--starttime=";
297         if (cmd.startsWith(startTimeArgKey)) {
298           startTime = Long.parseLong(cmd.substring(startTimeArgKey.length()));
299           continue;
300         }
301 
302         final String endTimeArgKey = "--endtime=";
303         if (cmd.startsWith(endTimeArgKey)) {
304           endTime = Long.parseLong(cmd.substring(endTimeArgKey.length()));
305           continue;
306         }
307 
308         final String versionsArgKey = "--versions=";
309         if (cmd.startsWith(versionsArgKey)) {
310           versions = Integer.parseInt(cmd.substring(versionsArgKey.length()));
311           continue;
312         }
313 
314         final String familiesArgKey = "--families=";
315         if (cmd.startsWith(familiesArgKey)) {
316           families = cmd.substring(familiesArgKey.length());
317           continue;
318         }
319 
320         if (i == args.length-2) {
321           peerId = cmd;
322         }
323 
324         if (i == args.length-1) {
325           tableName = cmd;
326         }
327       }
328     } catch (Exception e) {
329       e.printStackTrace();
330       printUsage("Can't start because " + e.getMessage());
331       return false;
332     }
333     return true;
334   }
335 
336   /*
337    * @param errorMsg Error message.  Can be null.
338    */
339   private static void printUsage(final String errorMsg) {
340     if (errorMsg != null && errorMsg.length() > 0) {
341       System.err.println("ERROR: " + errorMsg);
342     }
343     System.err.println("Usage: verifyrep [--starttime=X]" +
344         " [--stoptime=Y] [--families=A] <peerid> <tablename>");
345     System.err.println();
346     System.err.println("Options:");
347     System.err.println(" starttime    beginning of the time range");
348     System.err.println("              without endtime means from starttime to forever");
349     System.err.println(" endtime      end of the time range");
350     System.err.println(" versions     number of cell versions to verify");
351     System.err.println(" families     comma-separated list of families to copy");
352     System.err.println();
353     System.err.println("Args:");
354     System.err.println(" peerid       Id of the peer used for verification, must match the one given for replication");
355     System.err.println(" tablename    Name of the table to verify");
356     System.err.println();
357     System.err.println("Examples:");
358     System.err.println(" To verify the data replicated from TestTable for a 1 hour window with peer #5 ");
359     System.err.println(" $ bin/hbase " +
360         "org.apache.hadoop.hbase.mapreduce.replication.VerifyReplication" +
361         " --starttime=1265875194289 --endtime=1265878794289 5 TestTable ");
362   }
363 
364   @Override
365   public int run(String[] args) throws Exception {
366     Configuration conf = this.getConf();
367     Job job = createSubmittableJob(conf, args);
368     if (job != null) {
369       return job.waitForCompletion(true) ? 0 : 1;
370     } 
371     return 1;
372   }
373 
374   /**
375    * Main entry point.
376    *
377    * @param args  The command line parameters.
378    * @throws Exception When running the job fails.
379    */
380   public static void main(String[] args) throws Exception {
381     int res = ToolRunner.run(HBaseConfiguration.create(), new VerifyReplication(), args);
382     System.exit(res);
383   }
384 }