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.replication.ReplicationException;
42  import org.apache.hadoop.hbase.replication.ReplicationFactory;
43  import org.apache.hadoop.hbase.replication.ReplicationPeerZKImpl;
44  import org.apache.hadoop.hbase.replication.ReplicationPeerConfig;
45  import org.apache.hadoop.hbase.replication.ReplicationPeers;
46  import org.apache.hadoop.hbase.util.Bytes;
47  import org.apache.hadoop.hbase.util.Pair;
48  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
49  import org.apache.hadoop.hbase.zookeeper.ZKUtil;
50  import org.apache.hadoop.mapreduce.Job;
51  import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
52  import org.apache.hadoop.util.Tool;
53  import org.apache.hadoop.util.ToolRunner;
54  
55  /**
56   * This map-only job compares the data from a local table with a remote one.
57   * Every cell is compared and must have exactly the same keys (even timestamp)
58   * as well as same value. It is possible to restrict the job by time range and
59   * families. The peer id that's provided must match the one given when the
60   * replication stream was setup.
61   * <p>
62   * Two counters are provided, Verifier.Counters.GOODROWS and BADROWS. The reason
63   * for a why a row is different is shown in the map's log.
64   */
65  public class VerifyReplication extends Configured implements Tool {
66  
67    private static final Log LOG =
68        LogFactory.getLog(VerifyReplication.class);
69  
70    public final static String NAME = "verifyrep";
71    static long startTime = 0;
72    static long endTime = Long.MAX_VALUE;
73    static int versions = -1;
74    static String tableName = null;
75    static String families = null;
76    static String peerId = null;
77  
78    private final static String JOB_NAME_CONF_KEY = "mapreduce.job.name";
79  
80    /**
81     * Map-only comparator for 2 tables
82     */
83    public static class Verifier
84        extends TableMapper<ImmutableBytesWritable, Put> {
85  
86      public static enum Counters {GOODROWS, BADROWS}
87  
88      private ResultScanner replicatedScanner;
89  
90      /**
91       * Map method that compares every scanned row with the equivalent from
92       * a distant cluster.
93       * @param row  The current table row key.
94       * @param value  The columns.
95       * @param context  The current context.
96       * @throws IOException When something is broken with the data.
97       */
98      @Override
99      public void map(ImmutableBytesWritable row, final Result value,
100                     Context context)
101         throws IOException {
102       if (replicatedScanner == null) {
103         Configuration conf = context.getConfiguration();
104         final Scan scan = new Scan();
105         scan.setCaching(conf.getInt(TableInputFormat.SCAN_CACHEDROWS, 1));
106         long startTime = conf.getLong(NAME + ".startTime", 0);
107         long endTime = conf.getLong(NAME + ".endTime", Long.MAX_VALUE);
108         String families = conf.get(NAME + ".families", null);
109         if(families != null) {
110           String[] fams = families.split(",");
111           for(String fam : fams) {
112             scan.addFamily(Bytes.toBytes(fam));
113           }
114         }
115         scan.setTimeRange(startTime, endTime);
116         if (versions >= 0) {
117           scan.setMaxVersions(versions);
118         }
119         HConnectionManager.execute(new HConnectable<Void>(conf) {
120           @Override
121           public Void connect(HConnection conn) throws IOException {
122             String zkClusterKey = conf.get(NAME + ".peerQuorumAddress");
123             Configuration peerConf = HBaseConfiguration.create(conf);
124             ZKUtil.applyClusterKeyToConf(peerConf, zkClusterKey);
125 
126             Table replicatedTable = new HTable(peerConf, conf.get(NAME + ".tableName"));
127             scan.setStartRow(value.getRow());
128             replicatedScanner = replicatedTable.getScanner(scan);
129             return null;
130           }
131         });
132       }
133       Result res = replicatedScanner.next();
134       try {
135         Result.compareResults(value, res);
136         context.getCounter(Counters.GOODROWS).increment(1);
137       } catch (Exception e) {
138         LOG.warn("Bad row", e);
139         context.getCounter(Counters.BADROWS).increment(1);
140       }
141     }
142 
143     @Override
144     protected void cleanup(Context context) {
145       if (replicatedScanner != null) {
146         replicatedScanner.close();
147         replicatedScanner = null;
148       }
149     }
150   }
151 
152   private static String getPeerQuorumAddress(final Configuration conf) throws IOException {
153     ZooKeeperWatcher localZKW = null;
154     ReplicationPeerZKImpl peer = null;
155     try {
156       localZKW = new ZooKeeperWatcher(conf, "VerifyReplication",
157           new Abortable() {
158             @Override public void abort(String why, Throwable e) {}
159             @Override public boolean isAborted() {return false;}
160           });
161 
162       ReplicationPeers rp = ReplicationFactory.getReplicationPeers(localZKW, conf, localZKW);
163       rp.init();
164 
165       Pair<ReplicationPeerConfig, Configuration> pair = rp.getPeerConf(peerId);
166       if (pair == null) {
167         throw new IOException("Couldn't get peer conf!");
168       }
169       Configuration peerConf = rp.getPeerConf(peerId).getSecond();
170       return ZKUtil.getZooKeeperClusterKey(peerConf);
171     } catch (ReplicationException e) {
172       throw new IOException(
173           "An error occured while trying to connect to the remove peer cluster", e);
174     } finally {
175       if (peer != null) {
176         peer.close();
177       }
178       if (localZKW != null) {
179         localZKW.close();
180       }
181     }
182   }
183 
184   /**
185    * Sets up the actual job.
186    *
187    * @param conf  The current configuration.
188    * @param args  The command line parameters.
189    * @return The newly created job.
190    * @throws java.io.IOException When setting up the job fails.
191    */
192   public static Job createSubmittableJob(Configuration conf, String[] args)
193   throws IOException {
194     if (!doCommandLine(args)) {
195       return null;
196     }
197     if (!conf.getBoolean(HConstants.REPLICATION_ENABLE_KEY,
198         HConstants.REPLICATION_ENABLE_DEFAULT)) {
199       throw new IOException("Replication needs to be enabled to verify it.");
200     }
201     conf.set(NAME+".peerId", peerId);
202     conf.set(NAME+".tableName", tableName);
203     conf.setLong(NAME+".startTime", startTime);
204     conf.setLong(NAME+".endTime", endTime);
205     if (families != null) {
206       conf.set(NAME+".families", families);
207     }
208 
209     String peerQuorumAddress = getPeerQuorumAddress(conf);
210     conf.set(NAME + ".peerQuorumAddress", peerQuorumAddress);
211     LOG.info("Peer Quorum Address: " + peerQuorumAddress);
212 
213     Job job = Job.getInstance(conf, conf.get(JOB_NAME_CONF_KEY, NAME + "_" + tableName));
214     job.setJarByClass(VerifyReplication.class);
215 
216     Scan scan = new Scan();
217     scan.setTimeRange(startTime, endTime);
218     if (versions >= 0) {
219       scan.setMaxVersions(versions);
220     }
221     if(families != null) {
222       String[] fams = families.split(",");
223       for(String fam : fams) {
224         scan.addFamily(Bytes.toBytes(fam));
225       }
226     }
227     TableMapReduceUtil.initTableMapperJob(tableName, scan,
228         Verifier.class, null, null, job);
229 
230     // Obtain the auth token from peer cluster
231     TableMapReduceUtil.initCredentialsForCluster(job, peerQuorumAddress);
232 
233     job.setOutputFormatClass(NullOutputFormat.class);
234     job.setNumReduceTasks(0);
235     return job;
236   }
237 
238   private static boolean doCommandLine(final String[] args) {
239     if (args.length < 2) {
240       printUsage(null);
241       return false;
242     }
243     try {
244       for (int i = 0; i < args.length; i++) {
245         String cmd = args[i];
246         if (cmd.equals("-h") || cmd.startsWith("--h")) {
247           printUsage(null);
248           return false;
249         }
250 
251         final String startTimeArgKey = "--starttime=";
252         if (cmd.startsWith(startTimeArgKey)) {
253           startTime = Long.parseLong(cmd.substring(startTimeArgKey.length()));
254           continue;
255         }
256 
257         final String endTimeArgKey = "--endtime=";
258         if (cmd.startsWith(endTimeArgKey)) {
259           endTime = Long.parseLong(cmd.substring(endTimeArgKey.length()));
260           continue;
261         }
262 
263         final String versionsArgKey = "--versions=";
264         if (cmd.startsWith(versionsArgKey)) {
265           versions = Integer.parseInt(cmd.substring(versionsArgKey.length()));
266           continue;
267         }
268 
269         final String familiesArgKey = "--families=";
270         if (cmd.startsWith(familiesArgKey)) {
271           families = cmd.substring(familiesArgKey.length());
272           continue;
273         }
274 
275         if (i == args.length-2) {
276           peerId = cmd;
277         }
278 
279         if (i == args.length-1) {
280           tableName = cmd;
281         }
282       }
283     } catch (Exception e) {
284       e.printStackTrace();
285       printUsage("Can't start because " + e.getMessage());
286       return false;
287     }
288     return true;
289   }
290 
291   /*
292    * @param errorMsg Error message.  Can be null.
293    */
294   private static void printUsage(final String errorMsg) {
295     if (errorMsg != null && errorMsg.length() > 0) {
296       System.err.println("ERROR: " + errorMsg);
297     }
298     System.err.println("Usage: verifyrep [--starttime=X]" +
299         " [--stoptime=Y] [--families=A] <peerid> <tablename>");
300     System.err.println();
301     System.err.println("Options:");
302     System.err.println(" starttime    beginning of the time range");
303     System.err.println("              without endtime means from starttime to forever");
304     System.err.println(" endtime      end of the time range");
305     System.err.println(" versions     number of cell versions to verify");
306     System.err.println(" families     comma-separated list of families to copy");
307     System.err.println();
308     System.err.println("Args:");
309     System.err.println(" peerid       Id of the peer used for verification, must match the one given for replication");
310     System.err.println(" tablename    Name of the table to verify");
311     System.err.println();
312     System.err.println("Examples:");
313     System.err.println(" To verify the data replicated from TestTable for a 1 hour window with peer #5 ");
314     System.err.println(" $ bin/hbase " +
315         "org.apache.hadoop.hbase.mapreduce.replication.VerifyReplication" +
316         " --starttime=1265875194289 --endtime=1265878794289 5 TestTable ");
317   }
318 
319   @Override
320   public int run(String[] args) throws Exception {
321     Configuration conf = this.getConf();
322     Job job = createSubmittableJob(conf, args);
323     if (job != null) {
324       return job.waitForCompletion(true) ? 0 : 1;
325     } 
326     return 1;
327   }
328 
329   /**
330    * Main entry point.
331    *
332    * @param args  The command line parameters.
333    * @throws Exception When running the job fails.
334    */
335   public static void main(String[] args) throws Exception {
336     int res = ToolRunner.run(HBaseConfiguration.create(), new VerifyReplication(), args);
337     System.exit(res);
338   }
339 }