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;
20  
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertFalse;
23  import static org.junit.Assert.assertTrue;
24  import static org.mockito.Matchers.anyObject;
25  import static org.mockito.Mockito.doAnswer;
26  import static org.mockito.Mockito.doReturn;
27  import static org.mockito.Mockito.doThrow;
28  import static org.mockito.Mockito.mock;
29  import static org.mockito.Mockito.spy;
30  
31  import java.io.IOException;
32  import java.util.Arrays;
33  import java.util.Map;
34  
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  import org.apache.hadoop.hbase.*;
38  import org.apache.hadoop.hbase.client.Connection;
39  import org.apache.hadoop.hbase.client.ConnectionFactory;
40  import org.apache.hadoop.hbase.client.HTable;
41  import org.apache.hadoop.hbase.client.Put;
42  import org.apache.hadoop.hbase.client.Result;
43  import org.apache.hadoop.hbase.client.ResultScanner;
44  import org.apache.hadoop.hbase.client.Scan;
45  import org.apache.hadoop.hbase.client.Table;
46  import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
47  import org.apache.hadoop.hbase.filter.Filter;
48  import org.apache.hadoop.hbase.filter.RegexStringComparator;
49  import org.apache.hadoop.hbase.filter.RowFilter;
50  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
51  import org.apache.hadoop.hbase.testclassification.LargeTests;
52  import org.apache.hadoop.hbase.util.Bytes;
53  import org.apache.hadoop.io.NullWritable;
54  import org.apache.hadoop.mapred.JobConf;
55  import org.apache.hadoop.mapred.JobConfigurable;
56  import org.apache.hadoop.mapred.MiniMRCluster;
57  import org.apache.hadoop.mapreduce.InputFormat;
58  import org.apache.hadoop.mapreduce.Job;
59  import org.apache.hadoop.mapreduce.JobContext;
60  import org.apache.hadoop.mapreduce.Mapper.Context;
61  import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
62  import org.junit.AfterClass;
63  import org.junit.Before;
64  import org.junit.BeforeClass;
65  import org.junit.Test;
66  import org.junit.experimental.categories.Category;
67  import org.mockito.invocation.InvocationOnMock;
68  import org.mockito.stubbing.Answer;
69  
70  /**
71   * This tests the TableInputFormat and its recovery semantics
72   *
73   */
74  @Category(LargeTests.class)
75  public class TestTableInputFormat {
76  
77    private static final Log LOG = LogFactory.getLog(TestTableInputFormat.class);
78  
79    private final static HBaseTestingUtility UTIL = new HBaseTestingUtility();
80    private static MiniMRCluster mrCluster;
81    static final byte[] FAMILY = Bytes.toBytes("family");
82  
83    private static final byte[][] columns = new byte[][] { FAMILY };
84  
85    @BeforeClass
86    public static void beforeClass() throws Exception {
87      UTIL.startMiniCluster();
88      mrCluster = UTIL.startMiniMapReduceCluster();
89    }
90  
91    @AfterClass
92    public static void afterClass() throws Exception {
93      UTIL.shutdownMiniMapReduceCluster();
94      UTIL.shutdownMiniCluster();
95    }
96  
97    @Before
98    public void before() throws IOException {
99      LOG.info("before");
100     UTIL.ensureSomeRegionServersAvailable(1);
101     LOG.info("before done");
102   }
103 
104   /**
105    * Setup a table with two rows and values.
106    *
107    * @param tableName
108    * @return
109    * @throws IOException
110    */
111   public static Table createTable(byte[] tableName) throws IOException {
112     return createTable(tableName, new byte[][] { FAMILY });
113   }
114 
115   /**
116    * Setup a table with two rows and values per column family.
117    *
118    * @param tableName
119    * @return
120    * @throws IOException
121    */
122   public static Table createTable(byte[] tableName, byte[][] families) throws IOException {
123     Table table = UTIL.createTable(TableName.valueOf(tableName), families);
124     Put p = new Put("aaa".getBytes());
125     for (byte[] family : families) {
126       p.add(family, null, "value aaa".getBytes());
127     }
128     table.put(p);
129     p = new Put("bbb".getBytes());
130     for (byte[] family : families) {
131       p.add(family, null, "value bbb".getBytes());
132     }
133     table.put(p);
134     return table;
135   }
136 
137   /**
138    * Verify that the result and key have expected values.
139    *
140    * @param r
141    * @param key
142    * @param expectedKey
143    * @param expectedValue
144    * @return
145    */
146   static boolean checkResult(Result r, ImmutableBytesWritable key,
147       byte[] expectedKey, byte[] expectedValue) {
148     assertEquals(0, key.compareTo(expectedKey));
149     Map<byte[], byte[]> vals = r.getFamilyMap(FAMILY);
150     byte[] value = vals.values().iterator().next();
151     assertTrue(Arrays.equals(value, expectedValue));
152     return true; // if succeed
153   }
154 
155   /**
156    * Create table data and run tests on specified htable using the
157    * o.a.h.hbase.mapreduce API.
158    *
159    * @param table
160    * @throws IOException
161    * @throws InterruptedException
162    */
163   static void runTestMapreduce(Table table) throws IOException,
164       InterruptedException {
165     org.apache.hadoop.hbase.mapreduce.TableRecordReaderImpl trr =
166         new org.apache.hadoop.hbase.mapreduce.TableRecordReaderImpl();
167     Scan s = new Scan();
168     s.setStartRow("aaa".getBytes());
169     s.setStopRow("zzz".getBytes());
170     s.addFamily(FAMILY);
171     trr.setScan(s);
172     trr.setHTable(table);
173 
174     trr.initialize(null, null);
175     Result r = new Result();
176     ImmutableBytesWritable key = new ImmutableBytesWritable();
177 
178     boolean more = trr.nextKeyValue();
179     assertTrue(more);
180     key = trr.getCurrentKey();
181     r = trr.getCurrentValue();
182     checkResult(r, key, "aaa".getBytes(), "value aaa".getBytes());
183 
184     more = trr.nextKeyValue();
185     assertTrue(more);
186     key = trr.getCurrentKey();
187     r = trr.getCurrentValue();
188     checkResult(r, key, "bbb".getBytes(), "value bbb".getBytes());
189 
190     // no more data
191     more = trr.nextKeyValue();
192     assertFalse(more);
193   }
194 
195   /**
196    * Create a table that IOE's on first scanner next call
197    *
198    * @throws IOException
199    */
200   static Table createIOEScannerTable(byte[] name, final int failCnt)
201       throws IOException {
202     // build up a mock scanner stuff to fail the first time
203     Answer<ResultScanner> a = new Answer<ResultScanner>() {
204       int cnt = 0;
205 
206       @Override
207       public ResultScanner answer(InvocationOnMock invocation) throws Throwable {
208         // first invocation return the busted mock scanner
209         if (cnt++ < failCnt) {
210           // create mock ResultScanner that always fails.
211           Scan scan = mock(Scan.class);
212           doReturn("bogus".getBytes()).when(scan).getStartRow(); // avoid npe
213           ResultScanner scanner = mock(ResultScanner.class);
214           // simulate TimeoutException / IOException
215           doThrow(new IOException("Injected exception")).when(scanner).next();
216           return scanner;
217         }
218 
219         // otherwise return the real scanner.
220         return (ResultScanner) invocation.callRealMethod();
221       }
222     };
223 
224     Table htable = spy(createTable(name));
225     doAnswer(a).when(htable).getScanner((Scan) anyObject());
226     return htable;
227   }
228 
229   /**
230    * Create a table that throws a DoNoRetryIOException on first scanner next
231    * call
232    *
233    * @throws IOException
234    */
235   static Table createDNRIOEScannerTable(byte[] name, final int failCnt)
236       throws IOException {
237     // build up a mock scanner stuff to fail the first time
238     Answer<ResultScanner> a = new Answer<ResultScanner>() {
239       int cnt = 0;
240 
241       @Override
242       public ResultScanner answer(InvocationOnMock invocation) throws Throwable {
243         // first invocation return the busted mock scanner
244         if (cnt++ < failCnt) {
245           // create mock ResultScanner that always fails.
246           Scan scan = mock(Scan.class);
247           doReturn("bogus".getBytes()).when(scan).getStartRow(); // avoid npe
248           ResultScanner scanner = mock(ResultScanner.class);
249 
250           invocation.callRealMethod(); // simulate UnknownScannerException
251           doThrow(
252               new UnknownScannerException("Injected simulated TimeoutException"))
253               .when(scanner).next();
254           return scanner;
255         }
256 
257         // otherwise return the real scanner.
258         return (ResultScanner) invocation.callRealMethod();
259       }
260     };
261 
262     Table htable = spy(createTable(name));
263     doAnswer(a).when(htable).getScanner((Scan) anyObject());
264     return htable;
265   }
266 
267   /**
268    * Run test assuming no errors using newer mapreduce api
269    *
270    * @throws IOException
271    * @throws InterruptedException
272    */
273   @Test
274   public void testTableRecordReaderMapreduce() throws IOException,
275       InterruptedException {
276     Table table = createTable("table1-mr".getBytes());
277     runTestMapreduce(table);
278   }
279 
280   /**
281    * Run test assuming Scanner IOException failure using newer mapreduce api
282    * 
283    * @throws IOException
284    * @throws InterruptedException
285    */
286   @Test
287   public void testTableRecordReaderScannerFailMapreduce() throws IOException,
288       InterruptedException {
289     Table htable = createIOEScannerTable("table2-mr".getBytes(), 1);
290     runTestMapreduce(htable);
291   }
292 
293   /**
294    * Run test assuming Scanner IOException failure using newer mapreduce api
295    * 
296    * @throws IOException
297    * @throws InterruptedException
298    */
299   @Test(expected = IOException.class)
300   public void testTableRecordReaderScannerFailMapreduceTwice() throws IOException,
301       InterruptedException {
302     Table htable = createIOEScannerTable("table3-mr".getBytes(), 2);
303     runTestMapreduce(htable);
304   }
305 
306   /**
307    * Run test assuming UnknownScannerException (which is a type of
308    * DoNotRetryIOException) using newer mapreduce api
309    * 
310    * @throws InterruptedException
311    * @throws org.apache.hadoop.hbase.DoNotRetryIOException
312    */
313   @Test
314   public void testTableRecordReaderScannerTimeoutMapreduce()
315       throws IOException, InterruptedException {
316     Table htable = createDNRIOEScannerTable("table4-mr".getBytes(), 1);
317     runTestMapreduce(htable);
318   }
319 
320   /**
321    * Run test assuming UnknownScannerException (which is a type of
322    * DoNotRetryIOException) using newer mapreduce api
323    * 
324    * @throws InterruptedException
325    * @throws org.apache.hadoop.hbase.DoNotRetryIOException
326    */
327   @Test(expected = org.apache.hadoop.hbase.DoNotRetryIOException.class)
328   public void testTableRecordReaderScannerTimeoutMapreduceTwice()
329       throws IOException, InterruptedException {
330     Table htable = createDNRIOEScannerTable("table5-mr".getBytes(), 2);
331     runTestMapreduce(htable);
332   }
333 
334   /**
335    * Verify the example we present in javadocs on TableInputFormatBase
336    */
337   @Test
338   public void testExtensionOfTableInputFormatBase()
339       throws IOException, InterruptedException, ClassNotFoundException {
340     LOG.info("testing use of an InputFormat taht extends InputFormatBase");
341     final Table htable = createTable(Bytes.toBytes("exampleTable"),
342       new byte[][] { Bytes.toBytes("columnA"), Bytes.toBytes("columnB") });
343     testInputFormat(ExampleTIF.class);
344   }
345 
346   @Test
347   public void testJobConfigurableExtensionOfTableInputFormatBase()
348       throws IOException, InterruptedException, ClassNotFoundException {
349     LOG.info("testing use of an InputFormat taht extends InputFormatBase, " +
350         "using JobConfigurable.");
351     final Table htable = createTable(Bytes.toBytes("exampleJobConfigurableTable"),
352       new byte[][] { Bytes.toBytes("columnA"), Bytes.toBytes("columnB") });
353     testInputFormat(ExampleJobConfigurableTIF.class);
354   }
355 
356   @Test
357   public void testDeprecatedExtensionOfTableInputFormatBase()
358       throws IOException, InterruptedException, ClassNotFoundException {
359     LOG.info("testing use of an InputFormat taht extends InputFormatBase, " +
360         "using the approach documented in 0.98.");
361     final Table htable = createTable(Bytes.toBytes("exampleDeprecatedTable"),
362       new byte[][] { Bytes.toBytes("columnA"), Bytes.toBytes("columnB") });
363     testInputFormat(ExampleDeprecatedTIF.class);
364   }
365 
366   void testInputFormat(Class<? extends InputFormat> clazz)
367       throws IOException, InterruptedException, ClassNotFoundException {
368     final Job job = MapreduceTestingShim.createJob(UTIL.getConfiguration());
369     job.setInputFormatClass(clazz);
370     job.setOutputFormatClass(NullOutputFormat.class);
371     job.setMapperClass(ExampleVerifier.class);
372     job.setNumReduceTasks(0);
373 
374     LOG.debug("submitting job.");
375     assertTrue("job failed!", job.waitForCompletion(true));
376     assertEquals("Saw the wrong number of instances of the filtered-for row.", 2, job.getCounters()
377         .findCounter(TestTableInputFormat.class.getName() + ":row", "aaa").getValue());
378     assertEquals("Saw any instances of the filtered out row.", 0, job.getCounters()
379         .findCounter(TestTableInputFormat.class.getName() + ":row", "bbb").getValue());
380     assertEquals("Saw the wrong number of instances of columnA.", 1, job.getCounters()
381         .findCounter(TestTableInputFormat.class.getName() + ":family", "columnA").getValue());
382     assertEquals("Saw the wrong number of instances of columnB.", 1, job.getCounters()
383         .findCounter(TestTableInputFormat.class.getName() + ":family", "columnB").getValue());
384     assertEquals("Saw the wrong count of values for the filtered-for row.", 2, job.getCounters()
385         .findCounter(TestTableInputFormat.class.getName() + ":value", "value aaa").getValue());
386     assertEquals("Saw the wrong count of values for the filtered-out row.", 0, job.getCounters()
387         .findCounter(TestTableInputFormat.class.getName() + ":value", "value bbb").getValue());
388   }
389 
390   public static class ExampleVerifier extends TableMapper<NullWritable, NullWritable> {
391 
392     @Override
393     public void map(ImmutableBytesWritable key, Result value, Context context)
394         throws IOException {
395       for (Cell cell : value.listCells()) {
396         context.getCounter(TestTableInputFormat.class.getName() + ":row",
397             Bytes.toString(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()))
398             .increment(1l);
399         context.getCounter(TestTableInputFormat.class.getName() + ":family",
400             Bytes.toString(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength()))
401             .increment(1l);
402         context.getCounter(TestTableInputFormat.class.getName() + ":value",
403             Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()))
404             .increment(1l);
405       }
406     }
407 
408   }
409 
410   public static class ExampleDeprecatedTIF extends TableInputFormatBase implements JobConfigurable {
411 
412     @Override
413     public void configure(JobConf job) {
414       try {
415         HTable exampleTable = new HTable(HBaseConfiguration.create(job),
416           Bytes.toBytes("exampleDeprecatedTable"));
417         // mandatory
418         setHTable(exampleTable);
419         byte[][] inputColumns = new byte [][] { Bytes.toBytes("columnA"),
420           Bytes.toBytes("columnB") };
421         // optional
422         Scan scan = new Scan();
423         for (byte[] family : inputColumns) {
424           scan.addFamily(family);
425         }
426         Filter exampleFilter = new RowFilter(CompareOp.EQUAL, new RegexStringComparator("aa.*"));
427         scan.setFilter(exampleFilter);
428         setScan(scan);
429       } catch (IOException exception) {
430         throw new RuntimeException("Failed to configure for job.", exception);
431       }
432     }
433 
434   }
435 
436 
437   public static class ExampleJobConfigurableTIF extends TableInputFormatBase
438       implements JobConfigurable {
439 
440     @Override
441     public void configure(JobConf job) {
442       try {
443         Connection connection = ConnectionFactory.createConnection(HBaseConfiguration.create(job));
444         TableName tableName = TableName.valueOf("exampleJobConfigurableTable");
445         // mandatory
446         initializeTable(connection, tableName);
447         byte[][] inputColumns = new byte [][] { Bytes.toBytes("columnA"),
448           Bytes.toBytes("columnB") };
449         //optional
450         Scan scan = new Scan();
451         for (byte[] family : inputColumns) {
452           scan.addFamily(family);
453         }
454         Filter exampleFilter = new RowFilter(CompareOp.EQUAL, new RegexStringComparator("aa.*"));
455         scan.setFilter(exampleFilter);
456         setScan(scan);
457       } catch (IOException exception) {
458         throw new RuntimeException("Failed to initialize.", exception);
459       }
460     }
461   }
462 
463 
464   public static class ExampleTIF extends TableInputFormatBase {
465 
466     @Override
467     protected void initialize(JobContext job) throws IOException {
468       Connection connection = ConnectionFactory.createConnection(HBaseConfiguration.create(
469           job.getConfiguration()));
470       TableName tableName = TableName.valueOf("exampleTable");
471       // mandatory
472       initializeTable(connection, tableName);
473       byte[][] inputColumns = new byte [][] { Bytes.toBytes("columnA"),
474         Bytes.toBytes("columnB") };
475       //optional
476       Scan scan = new Scan();
477       for (byte[] family : inputColumns) {
478         scan.addFamily(family);
479       }
480       Filter exampleFilter = new RowFilter(CompareOp.EQUAL, new RegexStringComparator("aa.*"));
481       scan.setFilter(exampleFilter);
482       setScan(scan);
483     }
484 
485   }
486 }
487