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 */
018package org.apache.hadoop.hbase.mapreduce;
019
020import static org.apache.hadoop.hbase.mapreduce.TableSnapshotInputFormatImpl.SNAPSHOT_INPUTFORMAT_LOCALITY_ENABLED_DEFAULT;
021import static org.apache.hadoop.hbase.mapreduce.TableSnapshotInputFormatImpl.SNAPSHOT_INPUTFORMAT_LOCALITY_ENABLED_KEY;
022import static org.mockito.Mockito.mock;
023import static org.mockito.Mockito.when;
024
025import java.io.IOException;
026import java.util.Arrays;
027import java.util.List;
028import org.apache.hadoop.conf.Configuration;
029import org.apache.hadoop.fs.FileSystem;
030import org.apache.hadoop.fs.Path;
031import org.apache.hadoop.hbase.HBaseClassTestRule;
032import org.apache.hadoop.hbase.HBaseTestingUtility;
033import org.apache.hadoop.hbase.HConstants;
034import org.apache.hadoop.hbase.HDFSBlocksDistribution;
035import org.apache.hadoop.hbase.TableName;
036import org.apache.hadoop.hbase.client.Admin;
037import org.apache.hadoop.hbase.client.Result;
038import org.apache.hadoop.hbase.client.Scan;
039import org.apache.hadoop.hbase.client.Table;
040import org.apache.hadoop.hbase.client.TestTableSnapshotScanner;
041import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
042import org.apache.hadoop.hbase.mapreduce.TableSnapshotInputFormat.TableSnapshotRegionSplit;
043import org.apache.hadoop.hbase.snapshot.SnapshotTestingUtils;
044import org.apache.hadoop.hbase.testclassification.LargeTests;
045import org.apache.hadoop.hbase.testclassification.VerySlowMapReduceTests;
046import org.apache.hadoop.hbase.util.Bytes;
047import org.apache.hadoop.hbase.util.FSUtils;
048import org.apache.hadoop.hbase.util.RegionSplitter;
049import org.apache.hadoop.io.NullWritable;
050import org.apache.hadoop.mapreduce.InputSplit;
051import org.apache.hadoop.mapreduce.Job;
052import org.apache.hadoop.mapreduce.RecordReader;
053import org.apache.hadoop.mapreduce.Reducer;
054import org.apache.hadoop.mapreduce.TaskAttemptContext;
055import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
056import org.junit.After;
057import org.junit.Assert;
058import org.junit.ClassRule;
059import org.junit.Rule;
060import org.junit.Test;
061import org.junit.experimental.categories.Category;
062import org.junit.rules.TestName;
063import org.slf4j.Logger;
064import org.slf4j.LoggerFactory;
065
066import org.apache.hbase.thirdparty.com.google.common.collect.Lists;
067
068@Category({VerySlowMapReduceTests.class, LargeTests.class})
069public class TestTableSnapshotInputFormat extends TableSnapshotInputFormatTestBase {
070
071  @ClassRule
072  public static final HBaseClassTestRule CLASS_RULE =
073      HBaseClassTestRule.forClass(TestTableSnapshotInputFormat.class);
074
075  private static final Logger LOG = LoggerFactory.getLogger(TestTableSnapshotInputFormat.class);
076
077  private static final byte[] bbb = Bytes.toBytes("bbb");
078  private static final byte[] yyy = Bytes.toBytes("yyy");
079
080  @Rule
081  public TestName name = new TestName();
082
083  @Override
084  protected byte[] getStartRow() {
085    return bbb;
086  }
087
088  @Override
089  protected byte[] getEndRow() {
090    return yyy;
091  }
092
093  @After
094  public void tearDown() throws Exception {
095  }
096
097  @Test
098  public void testGetBestLocations() throws IOException {
099    TableSnapshotInputFormatImpl tsif = new TableSnapshotInputFormatImpl();
100    Configuration conf = UTIL.getConfiguration();
101
102    HDFSBlocksDistribution blockDistribution = new HDFSBlocksDistribution();
103    Assert.assertEquals(null,
104      TableSnapshotInputFormatImpl.getBestLocations(conf, blockDistribution));
105
106    blockDistribution.addHostsAndBlockWeight(new String[] {"h1"}, 1);
107    Assert.assertEquals(Lists.newArrayList("h1"),
108      TableSnapshotInputFormatImpl.getBestLocations(conf, blockDistribution));
109
110    blockDistribution.addHostsAndBlockWeight(new String[] {"h1"}, 1);
111    Assert.assertEquals(Lists.newArrayList("h1"),
112      TableSnapshotInputFormatImpl.getBestLocations(conf, blockDistribution));
113
114    blockDistribution.addHostsAndBlockWeight(new String[] {"h2"}, 1);
115    Assert.assertEquals(Lists.newArrayList("h1"),
116      TableSnapshotInputFormatImpl.getBestLocations(conf, blockDistribution));
117
118    blockDistribution = new HDFSBlocksDistribution();
119    blockDistribution.addHostsAndBlockWeight(new String[] {"h1"}, 10);
120    blockDistribution.addHostsAndBlockWeight(new String[] {"h2"}, 7);
121    blockDistribution.addHostsAndBlockWeight(new String[] {"h3"}, 5);
122    blockDistribution.addHostsAndBlockWeight(new String[] {"h4"}, 1);
123    Assert.assertEquals(Lists.newArrayList("h1"),
124      TableSnapshotInputFormatImpl.getBestLocations(conf, blockDistribution));
125
126    blockDistribution.addHostsAndBlockWeight(new String[] {"h2"}, 2);
127    Assert.assertEquals(Lists.newArrayList("h1", "h2"),
128      TableSnapshotInputFormatImpl.getBestLocations(conf, blockDistribution));
129
130    blockDistribution.addHostsAndBlockWeight(new String[] {"h2"}, 3);
131    Assert.assertEquals(Lists.newArrayList("h2", "h1"),
132      TableSnapshotInputFormatImpl.getBestLocations(conf, blockDistribution));
133
134    blockDistribution.addHostsAndBlockWeight(new String[] {"h3"}, 6);
135    blockDistribution.addHostsAndBlockWeight(new String[] {"h4"}, 9);
136
137    Assert.assertEquals(Lists.newArrayList("h2", "h3", "h4"),
138      TableSnapshotInputFormatImpl.getBestLocations(conf, blockDistribution));
139  }
140
141  public static enum TestTableSnapshotCounters {
142    VALIDATION_ERROR
143  }
144
145  public static class TestTableSnapshotMapper
146    extends TableMapper<ImmutableBytesWritable, NullWritable> {
147    @Override
148    protected void map(ImmutableBytesWritable key, Result value,
149        Context context) throws IOException, InterruptedException {
150      // Validate a single row coming from the snapshot, and emit the row key
151      verifyRowFromMap(key, value);
152      context.write(key, NullWritable.get());
153    }
154  }
155
156  public static class TestTableSnapshotReducer
157    extends Reducer<ImmutableBytesWritable, NullWritable, NullWritable, NullWritable> {
158    HBaseTestingUtility.SeenRowTracker rowTracker =
159        new HBaseTestingUtility.SeenRowTracker(bbb, yyy);
160    @Override
161    protected void reduce(ImmutableBytesWritable key, Iterable<NullWritable> values,
162       Context context) throws IOException, InterruptedException {
163      rowTracker.addRow(key.get());
164    }
165
166    @Override
167    protected void cleanup(Context context) throws IOException,
168        InterruptedException {
169      rowTracker.validate();
170    }
171  }
172
173  @Test
174  public void testInitTableSnapshotMapperJobConfig() throws Exception {
175    setupCluster();
176    final TableName tableName = TableName.valueOf(name.getMethodName());
177    String snapshotName = "foo";
178
179    try {
180      createTableAndSnapshot(UTIL, tableName, snapshotName, getStartRow(), getEndRow(), 1);
181      Job job = new Job(UTIL.getConfiguration());
182      Path tmpTableDir = UTIL.getDataTestDirOnTestFS(snapshotName);
183
184      TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName,
185        new Scan(), TestTableSnapshotMapper.class, ImmutableBytesWritable.class,
186        NullWritable.class, job, false, tmpTableDir);
187
188      // TODO: would be better to examine directly the cache instance that results from this
189      // config. Currently this is not possible because BlockCache initialization is static.
190      Assert.assertEquals(
191        "Snapshot job should be configured for default LruBlockCache.",
192        HConstants.HFILE_BLOCK_CACHE_SIZE_DEFAULT,
193        job.getConfiguration().getFloat(HConstants.HFILE_BLOCK_CACHE_SIZE_KEY, -1), 0.01);
194      Assert.assertEquals(
195        "Snapshot job should not use BucketCache.",
196        0, job.getConfiguration().getFloat("hbase.bucketcache.size", -1), 0.01);
197    } finally {
198      UTIL.getAdmin().deleteSnapshot(snapshotName);
199      UTIL.deleteTable(tableName);
200      tearDownCluster();
201    }
202  }
203
204  @Override
205  public void testRestoreSnapshotDoesNotCreateBackRefLinksInit(TableName tableName,
206      String snapshotName, Path tmpTableDir) throws Exception {
207    Job job = new Job(UTIL.getConfiguration());
208    TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName,
209      new Scan(), TestTableSnapshotMapper.class, ImmutableBytesWritable.class,
210      NullWritable.class, job, false, tmpTableDir);
211  }
212
213  @Override
214  public void testWithMockedMapReduce(HBaseTestingUtility util, String snapshotName,
215      int numRegions, int numSplitsPerRegion, int expectedNumSplits, boolean setLocalityEnabledTo)
216      throws Exception {
217    setupCluster();
218    final TableName tableName = TableName.valueOf(name.getMethodName());
219    try {
220      createTableAndSnapshot(
221        util, tableName, snapshotName, getStartRow(), getEndRow(), numRegions);
222
223      Configuration conf = util.getConfiguration();
224      conf.setBoolean(SNAPSHOT_INPUTFORMAT_LOCALITY_ENABLED_KEY, setLocalityEnabledTo);
225      Job job = new Job(conf);
226      Path tmpTableDir = util.getDataTestDirOnTestFS(snapshotName);
227      Scan scan = new Scan(getStartRow(), getEndRow()); // limit the scan
228
229      if (numSplitsPerRegion > 1) {
230        TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName,
231                scan, TestTableSnapshotMapper.class, ImmutableBytesWritable.class,
232                NullWritable.class, job, false, tmpTableDir, new RegionSplitter.UniformSplit(),
233                numSplitsPerRegion);
234      } else {
235        TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName,
236                scan, TestTableSnapshotMapper.class, ImmutableBytesWritable.class,
237                NullWritable.class, job, false, tmpTableDir);
238      }
239
240      verifyWithMockedMapReduce(job, numRegions, expectedNumSplits, getStartRow(), getEndRow());
241
242    } finally {
243      util.getAdmin().deleteSnapshot(snapshotName);
244      util.deleteTable(tableName);
245      tearDownCluster();
246    }
247  }
248
249  @Test
250  public void testNoDuplicateResultsWhenSplitting() throws Exception {
251    setupCluster();
252    TableName tableName = TableName.valueOf("testNoDuplicateResultsWhenSplitting");
253    String snapshotName = "testSnapshotBug";
254    try {
255      if (UTIL.getAdmin().tableExists(tableName)) {
256        UTIL.deleteTable(tableName);
257      }
258
259      UTIL.createTable(tableName, FAMILIES);
260      Admin admin = UTIL.getAdmin();
261
262      // put some stuff in the table
263      Table table = UTIL.getConnection().getTable(tableName);
264      UTIL.loadTable(table, FAMILIES);
265
266      // split to 2 regions
267      admin.split(tableName, Bytes.toBytes("eee"));
268      TestTableSnapshotScanner.blockUntilSplitFinished(UTIL, tableName, 2);
269
270      Path rootDir = FSUtils.getRootDir(UTIL.getConfiguration());
271      FileSystem fs = rootDir.getFileSystem(UTIL.getConfiguration());
272
273      SnapshotTestingUtils.createSnapshotAndValidate(admin, tableName, Arrays.asList(FAMILIES),
274        null, snapshotName, rootDir, fs, true);
275
276      // load different values
277      byte[] value = Bytes.toBytes("after_snapshot_value");
278      UTIL.loadTable(table, FAMILIES, value);
279
280      // cause flush to create new files in the region
281      admin.flush(tableName);
282      table.close();
283
284      Job job = new Job(UTIL.getConfiguration());
285      Path tmpTableDir = UTIL.getDataTestDirOnTestFS(snapshotName);
286      // limit the scan
287      Scan scan = new Scan().withStartRow(getStartRow()).withStopRow(getEndRow());
288
289      TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName, scan,
290        TestTableSnapshotMapper.class, ImmutableBytesWritable.class, NullWritable.class, job, false,
291        tmpTableDir);
292
293      verifyWithMockedMapReduce(job, 2, 2, getStartRow(), getEndRow());
294    } finally {
295      UTIL.getAdmin().deleteSnapshot(snapshotName);
296      UTIL.deleteTable(tableName);
297      tearDownCluster();
298    }
299  }
300
301  private void verifyWithMockedMapReduce(Job job, int numRegions, int expectedNumSplits,
302      byte[] startRow, byte[] stopRow)
303      throws IOException, InterruptedException {
304    TableSnapshotInputFormat tsif = new TableSnapshotInputFormat();
305    List<InputSplit> splits = tsif.getSplits(job);
306
307    Assert.assertEquals(expectedNumSplits, splits.size());
308
309    HBaseTestingUtility.SeenRowTracker rowTracker =
310        new HBaseTestingUtility.SeenRowTracker(startRow, stopRow);
311
312    boolean localityEnabled =
313        job.getConfiguration().getBoolean(SNAPSHOT_INPUTFORMAT_LOCALITY_ENABLED_KEY,
314                                          SNAPSHOT_INPUTFORMAT_LOCALITY_ENABLED_DEFAULT);
315
316    for (int i = 0; i < splits.size(); i++) {
317      // validate input split
318      InputSplit split = splits.get(i);
319      Assert.assertTrue(split instanceof TableSnapshotRegionSplit);
320      if (localityEnabled) {
321        Assert.assertTrue(split.getLocations() != null && split.getLocations().length != 0);
322      } else {
323        Assert.assertTrue(split.getLocations() != null && split.getLocations().length == 0);
324      }
325
326      // validate record reader
327      TaskAttemptContext taskAttemptContext = mock(TaskAttemptContext.class);
328      when(taskAttemptContext.getConfiguration()).thenReturn(job.getConfiguration());
329      RecordReader<ImmutableBytesWritable, Result> rr =
330          tsif.createRecordReader(split, taskAttemptContext);
331      rr.initialize(split, taskAttemptContext);
332
333      // validate we can read all the data back
334      while (rr.nextKeyValue()) {
335        byte[] row = rr.getCurrentKey().get();
336        verifyRowFromMap(rr.getCurrentKey(), rr.getCurrentValue());
337        rowTracker.addRow(row);
338      }
339
340      rr.close();
341    }
342
343    // validate all rows are seen
344    rowTracker.validate();
345  }
346
347  @Override
348  protected void testWithMapReduceImpl(HBaseTestingUtility util, TableName tableName,
349      String snapshotName, Path tableDir, int numRegions, int numSplitsPerRegion,
350      int expectedNumSplits, boolean shutdownCluster) throws Exception {
351    doTestWithMapReduce(util, tableName, snapshotName, getStartRow(), getEndRow(), tableDir,
352      numRegions, numSplitsPerRegion, expectedNumSplits, shutdownCluster);
353  }
354
355  // this is also called by the IntegrationTestTableSnapshotInputFormat
356  public static void doTestWithMapReduce(HBaseTestingUtility util, TableName tableName,
357      String snapshotName, byte[] startRow, byte[] endRow, Path tableDir, int numRegions,
358      int numSplitsPerRegion, int expectedNumSplits, boolean shutdownCluster) throws Exception {
359
360    LOG.info("testing with MapReduce");
361
362    LOG.info("create the table and snapshot");
363    createTableAndSnapshot(util, tableName, snapshotName, startRow, endRow, numRegions);
364
365    if (shutdownCluster) {
366      LOG.info("shutting down hbase cluster.");
367      util.shutdownMiniHBaseCluster();
368    }
369
370    try {
371      // create the job
372      Job job = new Job(util.getConfiguration());
373      Scan scan = new Scan(startRow, endRow); // limit the scan
374
375      job.setJarByClass(util.getClass());
376      TableMapReduceUtil.addDependencyJarsForClasses(job.getConfiguration(),
377              TestTableSnapshotInputFormat.class);
378
379      if (numSplitsPerRegion > 1) {
380        TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName,
381                scan, TestTableSnapshotMapper.class, ImmutableBytesWritable.class,
382                NullWritable.class, job, true, tableDir, new RegionSplitter.UniformSplit(),
383                numSplitsPerRegion);
384      } else {
385        TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName,
386                scan, TestTableSnapshotMapper.class, ImmutableBytesWritable.class,
387                NullWritable.class, job, true, tableDir);
388      }
389
390      job.setReducerClass(TestTableSnapshotInputFormat.TestTableSnapshotReducer.class);
391      job.setNumReduceTasks(1);
392      job.setOutputFormatClass(NullOutputFormat.class);
393
394      Assert.assertTrue(job.waitForCompletion(true));
395    } finally {
396      if (!shutdownCluster) {
397        util.getAdmin().deleteSnapshot(snapshotName);
398        util.deleteTable(tableName);
399      }
400    }
401  }
402}