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.test;
20  
21  import com.google.common.base.Joiner;
22  import org.apache.commons.cli.CommandLine;
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.Path;
28  import org.apache.hadoop.hbase.HBaseConfiguration;
29  import org.apache.hadoop.hbase.HRegionLocation;
30  import org.apache.hadoop.hbase.IntegrationTestingUtility;
31  import org.apache.hadoop.hbase.ServerName;
32  import org.apache.hadoop.hbase.TableName;
33  import org.apache.hadoop.hbase.HConstants;
34  import org.apache.hadoop.hbase.client.Connection;
35  import org.apache.hadoop.hbase.client.ConnectionFactory;
36  import org.apache.hadoop.hbase.client.replication.ReplicationAdmin;
37  import org.apache.hadoop.hbase.client.Admin;
38  import org.apache.hadoop.hbase.replication.ReplicationPeerConfig;
39  import org.apache.hadoop.util.Tool;
40  import org.apache.hadoop.util.ToolRunner;
41  
42  import java.util.ArrayList;
43  import java.util.HashMap;
44  import java.util.Set;
45  import java.util.TreeSet;
46  import java.util.UUID;
47  
48  
49  /**
50   * This is an integration test for replication. It is derived off
51   * {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList} that creates a large circular
52   * linked list in one cluster and verifies that the data is correct in a sink cluster. The test
53   * handles creating the tables and schema and setting up the replication.
54   */
55  public class IntegrationTestReplication extends IntegrationTestBigLinkedList {
56    protected String sourceClusterIdString;
57    protected String sinkClusterIdString;
58    protected int numIterations;
59    protected int numMappers;
60    protected long numNodes;
61    protected String outputDir;
62    protected int numReducers;
63    protected int generateVerifyGap;
64    protected Integer width;
65    protected Integer wrapMultiplier;
66  
67    private final String SOURCE_CLUSTER_OPT = "sourceCluster";
68    private final String DEST_CLUSTER_OPT = "destCluster";
69    private final String ITERATIONS_OPT = "iterations";
70    private final String NUM_MAPPERS_OPT = "numMappers";
71    private final String OUTPUT_DIR_OPT = "outputDir";
72    private final String NUM_REDUCERS_OPT = "numReducers";
73  
74    /**
75     * The gap (in seconds) from when data is finished being generated at the source
76     * to when it can be verified. This is the replication lag we are willing to tolerate
77     */
78    private final String GENERATE_VERIFY_GAP_OPT = "generateVerifyGap";
79  
80    /**
81     * The width of the linked list.
82     * See {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList} for more details
83     */
84    private final String WIDTH_OPT = "width";
85  
86    /**
87     * The number of rows after which the linked list points to the first row.
88     * See {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList} for more details
89     */
90    private final String WRAP_MULTIPLIER_OPT = "wrapMultiplier";
91  
92    /**
93     * The number of nodes in the test setup. This has to be a multiple of WRAP_MULTIPLIER * WIDTH
94     * in order to ensure that the linked list can is complete.
95     * See {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList} for more details
96     */
97    private final String NUM_NODES_OPT = "numNodes";
98  
99    private final int DEFAULT_NUM_MAPPERS = 1;
100   private final int DEFAULT_NUM_REDUCERS = 1;
101   private final int DEFAULT_NUM_ITERATIONS = 1;
102   private final int DEFAULT_GENERATE_VERIFY_GAP = 60;
103   private final int DEFAULT_WIDTH = 1000000;
104   private final int DEFAULT_WRAP_MULTIPLIER = 25;
105   private final int DEFAULT_NUM_NODES = DEFAULT_WIDTH * DEFAULT_WRAP_MULTIPLIER;
106 
107   /**
108    * Wrapper around an HBase ClusterID allowing us
109    * to get admin connections and configurations for it
110    */
111   protected class ClusterID {
112     private final Configuration configuration;
113     private Connection connection = null;
114 
115     /**
116      * This creates a new ClusterID wrapper that will automatically build connections and
117      * configurations to be able to talk to the specified cluster
118      *
119      * @param base the base configuration that this class will add to
120      * @param key the cluster key in the form of zk_quorum:zk_port:zk_parent_node
121      */
122     public ClusterID(Configuration base,
123                      String key) {
124       configuration = new Configuration(base);
125       String[] parts = key.split(":");
126       configuration.set(HConstants.ZOOKEEPER_QUORUM, parts[0]);
127       configuration.set(HConstants.ZOOKEEPER_CLIENT_PORT, parts[1]);
128       configuration.set(HConstants.ZOOKEEPER_ZNODE_PARENT, parts[2]);
129     }
130 
131     @Override
132     public String toString() {
133       return Joiner.on(":").join(configuration.get(HConstants.ZOOKEEPER_QUORUM),
134                                  configuration.get(HConstants.ZOOKEEPER_CLIENT_PORT),
135                                  configuration.get(HConstants.ZOOKEEPER_ZNODE_PARENT));
136     }
137 
138     public Configuration getConfiguration() {
139       return this.configuration;
140     }
141 
142     public Connection getConnection() throws Exception {
143       if (this.connection == null) {
144         this.connection = ConnectionFactory.createConnection(this.configuration);
145       }
146       return this.connection;
147     }
148 
149     public void closeConnection() throws Exception {
150       this.connection.close();
151       this.connection = null;
152     }
153 
154     public boolean equals(ClusterID other) {
155       return this.toString().equalsIgnoreCase(other.toString());
156     }
157   }
158 
159   /**
160    * The main runner loop for the test. It uses
161    * {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList}
162    * for the generation and verification of the linked list. It is heavily based on
163    * {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList.Loop}
164    */
165   protected class VerifyReplicationLoop extends Configured implements Tool {
166     private final Log LOG = LogFactory.getLog(VerifyReplicationLoop.class);
167     protected ClusterID source;
168     protected ClusterID sink;
169 
170     IntegrationTestBigLinkedList integrationTestBigLinkedList;
171 
172     /**
173      * This tears down any tables that existed from before and rebuilds the tables and schemas on
174      * the source cluster. It then sets up replication from the source to the sink cluster by using
175      * the {@link org.apache.hadoop.hbase.client.replication.ReplicationAdmin}
176      * connection.
177      *
178      * @throws Exception
179      */
180     protected void setupTablesAndReplication() throws Exception {
181       TableName tableName = getTableName(source.getConfiguration());
182 
183       ClusterID[] clusters = {source, sink};
184 
185       // delete any old tables in the source and sink
186       for (ClusterID cluster : clusters) {
187         Admin admin = cluster.getConnection().getAdmin();
188 
189         if (admin.tableExists(tableName)) {
190           if (admin.isTableEnabled(tableName)) {
191             admin.disableTable(tableName);
192           }
193 
194           /**
195            * TODO: This is a work around on a replication bug (HBASE-13416)
196            * When we recreate a table against that has recently been
197            * deleted, the contents of the logs are replayed even though
198            * they should not. This ensures that we flush the logs
199            * before the table gets deleted. Eventually the bug should be
200            * fixed and this should be removed.
201            */
202           Set<ServerName> regionServers = new TreeSet<>();
203           for (HRegionLocation rl :
204                cluster.getConnection().getRegionLocator(tableName).getAllRegionLocations()) {
205             regionServers.add(rl.getServerName());
206           }
207 
208           for (ServerName server : regionServers) {
209             source.getConnection().getAdmin().rollWALWriter(server);
210           }
211 
212           admin.deleteTable(tableName);
213         }
214       }
215 
216       // create the schema
217       Generator generator = new Generator();
218       generator.setConf(source.getConfiguration());
219       generator.createSchema();
220 
221       // setup the replication on the source
222       if (!source.equals(sink)) {
223         ReplicationAdmin replicationAdmin = new ReplicationAdmin(source.getConfiguration());
224         // remove any old replication peers
225         for (String oldPeer : replicationAdmin.listPeerConfigs().keySet()) {
226           replicationAdmin.removePeer(oldPeer);
227         }
228 
229         // set the sink to be the target
230         ReplicationPeerConfig peerConfig = new ReplicationPeerConfig();
231         peerConfig.setClusterKey(sink.toString());
232 
233         // set the test table to be the table to replicate
234         HashMap<TableName, ArrayList<String>> toReplicate = new HashMap<>();
235         toReplicate.put(tableName, new ArrayList<String>(0));
236 
237         replicationAdmin.addPeer("TestPeer", peerConfig, toReplicate);
238 
239         replicationAdmin.enableTableRep(tableName);
240         replicationAdmin.close();
241       }
242 
243       for (ClusterID cluster : clusters) {
244         cluster.closeConnection();
245       }
246     }
247 
248     protected void waitForReplication() throws Exception {
249       // TODO: we shouldn't be sleeping here. It would be better to query the region servers
250       // and wait for them to report 0 replication lag.
251       Thread.sleep(generateVerifyGap * 1000);
252     }
253 
254     /**
255      * Run the {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList.Generator} in the
256      * source cluster. This assumes that the tables have been setup via setupTablesAndReplication.
257      *
258      * @throws Exception
259      */
260     protected void runGenerator() throws Exception {
261       Path outputPath = new Path(outputDir);
262       UUID uuid = UUID.randomUUID(); //create a random UUID.
263       Path generatorOutput = new Path(outputPath, uuid.toString());
264 
265       Generator generator = new Generator();
266       generator.setConf(source.getConfiguration());
267 
268       int retCode = generator.run(numMappers, numNodes, generatorOutput, width, wrapMultiplier);
269       if (retCode > 0) {
270         throw new RuntimeException("Generator failed with return code: " + retCode);
271       }
272     }
273 
274 
275     /**
276      * Run the {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList.Verify}
277      * in the sink cluster. If replication is working properly the data written at the source
278      * cluster should be available in the sink cluster after a reasonable gap
279      *
280      * @param expectedNumNodes the number of nodes we are expecting to see in the sink cluster
281      * @throws Exception
282      */
283     protected void runVerify(long expectedNumNodes) throws Exception {
284       Path outputPath = new Path(outputDir);
285       UUID uuid = UUID.randomUUID(); //create a random UUID.
286       Path iterationOutput = new Path(outputPath, uuid.toString());
287 
288       Verify verify = new Verify();
289       verify.setConf(sink.getConfiguration());
290 
291       int retCode = verify.run(iterationOutput, numReducers);
292       if (retCode > 0) {
293         throw new RuntimeException("Verify.run failed with return code: " + retCode);
294       }
295 
296       if (!verify.verify(expectedNumNodes)) {
297         throw new RuntimeException("Verify.verify failed");
298       }
299 
300       LOG.info("Verify finished with success. Total nodes=" + expectedNumNodes);
301     }
302 
303     /**
304      * The main test runner
305      *
306      * This test has 4 steps:
307      *  1: setupTablesAndReplication
308      *  2: generate the data into the source cluster
309      *  3: wait for replication to propagate
310      *  4: verify that the data is available in the sink cluster
311      *
312      * @param args should be empty
313      * @return 0 on success
314      * @throws Exception on an error
315      */
316     @Override
317     public int run(String[] args) throws Exception {
318       source = new ClusterID(getConf(), sourceClusterIdString);
319       sink = new ClusterID(getConf(), sinkClusterIdString);
320 
321       setupTablesAndReplication();
322       int expectedNumNodes = 0;
323       for (int i = 0; i < numIterations; i++) {
324         LOG.info("Starting iteration = " + i);
325 
326         expectedNumNodes += numMappers * numNodes;
327 
328         runGenerator();
329         waitForReplication();
330         runVerify(expectedNumNodes);
331       }
332 
333       /**
334        * we are always returning 0 because exceptions are thrown when there is an error
335        * in the verification step.
336        */
337       return 0;
338     }
339   }
340 
341   @Override
342   protected void addOptions() {
343     super.addOptions();
344     addRequiredOptWithArg("s", SOURCE_CLUSTER_OPT,
345                           "Cluster ID of the source cluster (e.g. localhost:2181:/hbase)");
346     addRequiredOptWithArg("r", DEST_CLUSTER_OPT,
347                           "Cluster ID of the sink cluster (e.g. localhost:2182:/hbase)");
348     addRequiredOptWithArg("d", OUTPUT_DIR_OPT,
349                           "Temporary directory where to write keys for the test");
350 
351 
352     addOptWithArg("nm", NUM_MAPPERS_OPT,
353                   "Number of mappers (default: " + DEFAULT_NUM_MAPPERS + ")");
354     addOptWithArg("nr", NUM_REDUCERS_OPT,
355                   "Number of reducers (default: " + DEFAULT_NUM_MAPPERS + ")");
356     addOptWithArg("n", NUM_NODES_OPT,
357                   "Number of nodes. This should be a multiple of width * wrapMultiplier."  +
358                   " (default: " + DEFAULT_NUM_NODES + ")");
359     addOptWithArg("i", ITERATIONS_OPT, "Number of iterations to run (default: " +
360                   DEFAULT_NUM_ITERATIONS +  ")");
361     addOptWithArg("t", GENERATE_VERIFY_GAP_OPT,
362                   "Gap between generate and verify steps in seconds (default: " +
363                   DEFAULT_GENERATE_VERIFY_GAP + ")");
364     addOptWithArg("w", WIDTH_OPT,
365                   "Width of the linked list chain (default: " + DEFAULT_WIDTH + ")");
366     addOptWithArg("wm", WRAP_MULTIPLIER_OPT, "How many times to wrap around (default: " +
367                   DEFAULT_WRAP_MULTIPLIER + ")");
368   }
369 
370   @Override
371   protected void processOptions(CommandLine cmd) {
372     processBaseOptions(cmd);
373 
374     sourceClusterIdString = cmd.getOptionValue(SOURCE_CLUSTER_OPT);
375     sinkClusterIdString = cmd.getOptionValue(DEST_CLUSTER_OPT);
376     outputDir = cmd.getOptionValue(OUTPUT_DIR_OPT);
377 
378     /** This uses parseInt from {@link org.apache.hadoop.hbase.util.AbstractHBaseTool} */
379     numMappers = parseInt(cmd.getOptionValue(NUM_MAPPERS_OPT,
380                                              Integer.toString(DEFAULT_NUM_MAPPERS)),
381                           1, Integer.MAX_VALUE);
382     numReducers = parseInt(cmd.getOptionValue(NUM_REDUCERS_OPT,
383                                               Integer.toString(DEFAULT_NUM_REDUCERS)),
384                            1, Integer.MAX_VALUE);
385     numNodes = parseInt(cmd.getOptionValue(NUM_NODES_OPT, Integer.toString(DEFAULT_NUM_NODES)),
386                         1, Integer.MAX_VALUE);
387     generateVerifyGap = parseInt(cmd.getOptionValue(GENERATE_VERIFY_GAP_OPT,
388                                                     Integer.toString(DEFAULT_GENERATE_VERIFY_GAP)),
389                                  1, Integer.MAX_VALUE);
390     numIterations = parseInt(cmd.getOptionValue(ITERATIONS_OPT,
391                                                 Integer.toString(DEFAULT_NUM_ITERATIONS)),
392                              1, Integer.MAX_VALUE);
393     width = parseInt(cmd.getOptionValue(WIDTH_OPT, Integer.toString(DEFAULT_WIDTH)),
394                                         1, Integer.MAX_VALUE);
395     wrapMultiplier = parseInt(cmd.getOptionValue(WRAP_MULTIPLIER_OPT,
396                                                  Integer.toString(DEFAULT_WRAP_MULTIPLIER)),
397                               1, Integer.MAX_VALUE);
398 
399     if (numNodes % (width * wrapMultiplier) != 0) {
400       throw new RuntimeException("numNodes must be a multiple of width and wrap multiplier");
401     }
402   }
403 
404   @Override
405   public int runTestFromCommandLine() throws Exception {
406     VerifyReplicationLoop tool = new  VerifyReplicationLoop();
407     tool.integrationTestBigLinkedList = this;
408     return ToolRunner.run(getConf(), tool, null);
409   }
410 
411   public static void main(String[] args) throws Exception {
412     Configuration conf = HBaseConfiguration.create();
413     IntegrationTestingUtility.setUseDistributedCluster(conf);
414     int ret = ToolRunner.run(conf, new IntegrationTestReplication(), args);
415     System.exit(ret);
416   }
417 }