001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.hadoop.hbase;
020
021import java.io.IOException;
022import java.util.List;
023import java.util.concurrent.BlockingQueue;
024import java.util.concurrent.TimeUnit;
025import org.apache.hadoop.conf.Configuration;
026import org.apache.hadoop.hbase.testclassification.IntegrationTests;
027import org.apache.hadoop.hbase.util.ConstantDelayQueue;
028import org.apache.hadoop.hbase.util.LoadTestTool;
029import org.apache.hadoop.hbase.util.MultiThreadedUpdater;
030import org.apache.hadoop.hbase.util.MultiThreadedWriter;
031import org.apache.hadoop.hbase.util.ServerRegionReplicaUtil;
032import org.apache.hadoop.hbase.util.TableDescriptorChecker;
033import org.apache.hadoop.hbase.util.Threads;
034import org.apache.hadoop.hbase.util.test.LoadTestDataGenerator;
035import org.apache.hadoop.util.StringUtils;
036import org.apache.hadoop.util.ToolRunner;
037import org.junit.Assert;
038import org.junit.Test;
039import org.junit.experimental.categories.Category;
040
041import org.apache.hbase.thirdparty.com.google.common.collect.Lists;
042
043/**
044 * Integration test for testing async wal replication to secondary region replicas. Sets up a table
045 * with given region replication (default 2), and uses LoadTestTool client writer, updater and
046 * reader threads for writes and reads and verification. It uses a delay queue with a given delay
047 * ("read_delay_ms", default 5000ms) between the writer/updater and reader threads to make the
048 * written items available to readers. This means that a reader will only start reading from a row
049 * written by the writer / updater after 5secs has passed. The reader thread performs the reads from
050 * the given region replica id (default 1) to perform the reads. Async wal replication has to finish
051 * with the replication of the edits before read_delay_ms to the given region replica id so that
052 * the read and verify will not fail.
053 *
054 * The job will run for <b>at least</b> given runtime (default 10min) by running a concurrent
055 * writer and reader workload followed by a concurrent updater and reader workload for
056 * num_keys_per_server.
057 * <p>
058 * Example usage:
059 * </p>
060 * <pre>
061 * hbase org.apache.hadoop.hbase.IntegrationTestRegionReplicaReplication
062 * -DIntegrationTestRegionReplicaReplication.num_keys_per_server=10000
063 * -Dhbase.IntegrationTestRegionReplicaReplication.runtime=600000
064 * -DIntegrationTestRegionReplicaReplication.read_delay_ms=5000
065 * -DIntegrationTestRegionReplicaReplication.region_replication=3
066 * -DIntegrationTestRegionReplicaReplication.region_replica_id=2
067 * -DIntegrationTestRegionReplicaReplication.num_read_threads=100
068 * -DIntegrationTestRegionReplicaReplication.num_write_threads=100
069 * </pre>
070 */
071@Category(IntegrationTests.class)
072public class IntegrationTestRegionReplicaReplication extends IntegrationTestIngest {
073
074  private static final String TEST_NAME
075    = IntegrationTestRegionReplicaReplication.class.getSimpleName();
076
077  private static final String OPT_READ_DELAY_MS = "read_delay_ms";
078
079  private static final int DEFAULT_REGION_REPLICATION = 2;
080  private static final int SERVER_COUNT = 1; // number of slaves for the smallest cluster
081  private static final String[] DEFAULT_COLUMN_FAMILIES = new String[] {"f1", "f2", "f3"};
082
083  @Override
084  protected int getMinServerCount() {
085    return SERVER_COUNT;
086  }
087
088  @Override
089  public void setConf(Configuration conf) {
090    conf.setIfUnset(
091      String.format("%s.%s", TEST_NAME, LoadTestTool.OPT_REGION_REPLICATION),
092      String.valueOf(DEFAULT_REGION_REPLICATION));
093
094    conf.setIfUnset(
095      String.format("%s.%s", TEST_NAME, LoadTestTool.OPT_COLUMN_FAMILIES),
096      StringUtils.join(",", DEFAULT_COLUMN_FAMILIES));
097
098    conf.setBoolean(TableDescriptorChecker.TABLE_SANITY_CHECKS, true);
099
100    // enable async wal replication to region replicas for unit tests
101    conf.setBoolean(ServerRegionReplicaUtil.REGION_REPLICA_REPLICATION_CONF_KEY, true);
102
103    conf.setLong(HConstants.HREGION_MEMSTORE_FLUSH_SIZE, 1024L * 1024 * 4); // flush every 4 MB
104    conf.setInt("hbase.hstore.blockingStoreFiles", 100);
105
106    super.setConf(conf);
107  }
108
109  @Override
110  @Test
111  public void testIngest() throws Exception {
112    runIngestTest(JUNIT_RUN_TIME, 25000, 10, 1024, 10, 20);
113  }
114
115  /**
116   * This extends MultiThreadedWriter to add a configurable delay to the keys written by the writer
117   * threads to become available to the MultiThradedReader threads. We add this delay because of
118   * the async nature of the wal replication to region replicas.
119   */
120  public static class DelayingMultiThreadedWriter extends MultiThreadedWriter {
121    private long delayMs;
122    public DelayingMultiThreadedWriter(LoadTestDataGenerator dataGen, Configuration conf,
123        TableName tableName) throws IOException {
124      super(dataGen, conf, tableName);
125    }
126    @Override
127    protected BlockingQueue<Long> createWriteKeysQueue(Configuration conf) {
128      this.delayMs = conf.getLong(String.format("%s.%s",
129        IntegrationTestRegionReplicaReplication.class.getSimpleName(), OPT_READ_DELAY_MS), 5000);
130      return new ConstantDelayQueue<>(TimeUnit.MILLISECONDS, delayMs);
131    }
132  }
133
134  /**
135   * This extends MultiThreadedWriter to add a configurable delay to the keys written by the writer
136   * threads to become available to the MultiThradedReader threads. We add this delay because of
137   * the async nature of the wal replication to region replicas.
138   */
139  public static class DelayingMultiThreadedUpdater extends MultiThreadedUpdater {
140    private long delayMs;
141    public DelayingMultiThreadedUpdater(LoadTestDataGenerator dataGen, Configuration conf,
142        TableName tableName, double updatePercent) throws IOException {
143      super(dataGen, conf, tableName, updatePercent);
144    }
145    @Override
146    protected BlockingQueue<Long> createWriteKeysQueue(Configuration conf) {
147      this.delayMs = conf.getLong(String.format("%s.%s",
148        IntegrationTestRegionReplicaReplication.class.getSimpleName(), OPT_READ_DELAY_MS), 5000);
149      return new ConstantDelayQueue<>(TimeUnit.MILLISECONDS, delayMs);
150    }
151  }
152
153  @Override
154  protected void runIngestTest(long defaultRunTime, long keysPerServerPerIter, int colsPerKey,
155      int recordSize, int writeThreads, int readThreads) throws Exception {
156
157    LOG.info("Running ingest");
158    LOG.info("Cluster size:" + util.getHBaseClusterInterface()
159      .getClusterMetrics().getLiveServerMetrics().size());
160
161    // sleep for some time so that the cache for disabled tables does not interfere.
162    Threads.sleep(
163      getConf().getInt("hbase.region.replica.replication.cache.disabledAndDroppedTables.expiryMs",
164        5000) + 1000);
165
166    long start = System.currentTimeMillis();
167    String runtimeKey = String.format(RUN_TIME_KEY, this.getClass().getSimpleName());
168    long runtime = util.getConfiguration().getLong(runtimeKey, defaultRunTime);
169    long startKey = 0;
170
171    long numKeys = getNumKeys(keysPerServerPerIter);
172    while (System.currentTimeMillis() - start < 0.9 * runtime) {
173      LOG.info("Intended run time: " + (runtime/60000) + " min, left:" +
174          ((runtime - (System.currentTimeMillis() - start))/60000) + " min");
175
176      int verifyPercent = 100;
177      int updatePercent = 20;
178      int ret = -1;
179      int regionReplicaId = conf.getInt(String.format("%s.%s"
180        , TEST_NAME, LoadTestTool.OPT_REGION_REPLICA_ID), 1);
181
182      // we will run writers and readers at the same time.
183      List<String> args = Lists.newArrayList(getArgsForLoadTestTool("", "", startKey, numKeys));
184      args.add("-write");
185      args.add(String.format("%d:%d:%d", colsPerKey, recordSize, writeThreads));
186      args.add("-" + LoadTestTool.OPT_MULTIPUT);
187      args.add("-writer");
188      args.add(DelayingMultiThreadedWriter.class.getName()); // inject writer class
189      args.add("-read");
190      args.add(String.format("%d:%d", verifyPercent, readThreads));
191      args.add("-" + LoadTestTool.OPT_REGION_REPLICA_ID);
192      args.add(String.valueOf(regionReplicaId));
193
194      ret = loadTool.run(args.toArray(new String[args.size()]));
195      if (0 != ret) {
196        String errorMsg = "Load failed with error code " + ret;
197        LOG.error(errorMsg);
198        Assert.fail(errorMsg);
199      }
200
201      args = Lists.newArrayList(getArgsForLoadTestTool("", "", startKey, numKeys));
202      args.add("-update");
203      args.add(String.format("%s:%s:1", updatePercent, writeThreads));
204      args.add("-updater");
205      args.add(DelayingMultiThreadedUpdater.class.getName()); // inject updater class
206      args.add("-read");
207      args.add(String.format("%d:%d", verifyPercent, readThreads));
208      args.add("-" + LoadTestTool.OPT_REGION_REPLICA_ID);
209      args.add(String.valueOf(regionReplicaId));
210
211      ret = loadTool.run(args.toArray(new String[args.size()]));
212      if (0 != ret) {
213        String errorMsg = "Load failed with error code " + ret;
214        LOG.error(errorMsg);
215        Assert.fail(errorMsg);
216      }
217      startKey += numKeys;
218    }
219  }
220
221  public static void main(String[] args) throws Exception {
222    Configuration conf = HBaseConfiguration.create();
223    IntegrationTestingUtility.setUseDistributedCluster(conf);
224    int ret = ToolRunner.run(conf, new IntegrationTestRegionReplicaReplication(), args);
225    System.exit(ret);
226  }
227}