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