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  package org.apache.hadoop.hbase.mapreduce;
19  
20  import static org.junit.Assert.assertTrue;
21  import static org.junit.Assert.fail;
22  
23  import java.io.File;
24  import java.io.IOException;
25  import java.util.Iterator;
26  import java.util.Map;
27  import java.util.NavigableMap;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.conf.Configuration;
32  import org.apache.hadoop.fs.FileUtil;
33  import org.apache.hadoop.fs.Path;
34  import org.apache.hadoop.hbase.HConstants;
35  import org.apache.hadoop.hbase.Cell;
36  import org.apache.hadoop.hbase.CellUtil;
37  import org.apache.hadoop.hbase.HBaseTestingUtility;
38  import org.apache.hadoop.hbase.HConstants;
39  import org.apache.hadoop.hbase.TableName;
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.io.ImmutableBytesWritable;
47  import org.apache.hadoop.hbase.testclassification.LargeTests;
48  import org.apache.hadoop.hbase.util.Bytes;
49  import org.apache.hadoop.mapreduce.Job;
50  import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
51  import org.junit.AfterClass;
52  import org.junit.BeforeClass;
53  import org.junit.Test;
54  import org.junit.experimental.categories.Category;
55  
56  /**
57   * Test Map/Reduce job over HBase tables. The map/reduce process we're testing
58   * on our tables is simple - take every row in the table, reverse the value of
59   * a particular cell, and write it back to the table.
60   */
61  @Category(LargeTests.class)
62  public class TestMultithreadedTableMapper {
63    private static final Log LOG = LogFactory.getLog(TestMultithreadedTableMapper.class);
64    private static final HBaseTestingUtility UTIL =
65        new HBaseTestingUtility();
66    static final TableName MULTI_REGION_TABLE_NAME = TableName.valueOf("mrtest");
67    static final byte[] INPUT_FAMILY = Bytes.toBytes("contents");
68    static final byte[] OUTPUT_FAMILY = Bytes.toBytes("text");
69    static final int    NUMBER_OF_THREADS = 10;
70  
71    @BeforeClass
72    public static void beforeClass() throws Exception {
73      // Up the handlers; this test needs more than usual.
74      UTIL.getConfiguration().setInt(HConstants.REGION_SERVER_HIGH_PRIORITY_HANDLER_COUNT, 10);
75      UTIL.setJobWithoutMRCluster();
76      UTIL.startMiniCluster();
77      HTable table =
78          UTIL.createMultiRegionTable(MULTI_REGION_TABLE_NAME, new byte[][] { INPUT_FAMILY,
79              OUTPUT_FAMILY });
80      UTIL.loadTable(table, INPUT_FAMILY, false);
81      UTIL.waitUntilAllRegionsAssigned(MULTI_REGION_TABLE_NAME);
82    }
83  
84    @AfterClass
85    public static void afterClass() throws Exception {
86      UTIL.shutdownMiniCluster();
87    }
88  
89    /**
90     * Pass the given key and processed record reduce
91     */
92    public static class ProcessContentsMapper
93    extends TableMapper<ImmutableBytesWritable, Put> {
94  
95      /**
96       * Pass the key, and reversed value to reduce
97       *
98       * @param key
99       * @param value
100      * @param context
101      * @throws IOException
102      */
103     @Override
104     public void map(ImmutableBytesWritable key, Result value,
105         Context context)
106             throws IOException, InterruptedException {
107       if (value.size() != 1) {
108         throw new IOException("There should only be one input column");
109       }
110       Map<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>>
111       cf = value.getMap();
112       if(!cf.containsKey(INPUT_FAMILY)) {
113         throw new IOException("Wrong input columns. Missing: '" +
114             Bytes.toString(INPUT_FAMILY) + "'.");
115       }
116       // Get the original value and reverse it
117       String originalValue = Bytes.toString(value.getValue(INPUT_FAMILY, INPUT_FAMILY));
118       StringBuilder newValue = new StringBuilder(originalValue);
119       newValue.reverse();
120       // Now set the value to be collected
121       Put outval = new Put(key.get());
122       outval.add(OUTPUT_FAMILY, null, Bytes.toBytes(newValue.toString()));
123       context.write(key, outval);
124     }
125   }
126 
127   /**
128    * Test multithreadedTableMappper map/reduce against a multi-region table
129    * @throws IOException
130    * @throws ClassNotFoundException
131    * @throws InterruptedException
132    */
133   @Test
134   public void testMultithreadedTableMapper()
135       throws IOException, InterruptedException, ClassNotFoundException {
136     runTestOnTable(new HTable(new Configuration(UTIL.getConfiguration()),
137         MULTI_REGION_TABLE_NAME));
138   }
139 
140   private void runTestOnTable(HTable table)
141       throws IOException, InterruptedException, ClassNotFoundException {
142     Job job = null;
143     try {
144       LOG.info("Before map/reduce startup");
145       job = new Job(table.getConfiguration(), "process column contents");
146       job.setNumReduceTasks(1);
147       Scan scan = new Scan();
148       scan.addFamily(INPUT_FAMILY);
149       TableMapReduceUtil.initTableMapperJob(
150           table.getTableName(), scan,
151           MultithreadedTableMapper.class, ImmutableBytesWritable.class,
152           Put.class, job);
153       MultithreadedTableMapper.setMapperClass(job, ProcessContentsMapper.class);
154       MultithreadedTableMapper.setNumberOfThreads(job, NUMBER_OF_THREADS);
155       TableMapReduceUtil.initTableReducerJob(
156           Bytes.toString(table.getTableName()),
157           IdentityTableReducer.class, job);
158       FileOutputFormat.setOutputPath(job, new Path("test"));
159       LOG.info("Started " + table.getName().getNameAsString());
160       assertTrue(job.waitForCompletion(true));
161       LOG.info("After map/reduce completion");
162       // verify map-reduce results
163       verify(table.getName());
164     } finally {
165       table.close();
166       if (job != null) {
167         FileUtil.fullyDelete(
168             new File(job.getConfiguration().get("hadoop.tmp.dir")));
169       }
170     }
171   }
172 
173   private void verify(TableName tableName) throws IOException {
174     Table table = new HTable(new Configuration(UTIL.getConfiguration()), tableName);
175     boolean verified = false;
176     long pause = UTIL.getConfiguration().getLong("hbase.client.pause", 5 * 1000);
177     int numRetries = UTIL.getConfiguration().getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5);
178     for (int i = 0; i < numRetries; i++) {
179       try {
180         LOG.info("Verification attempt #" + i);
181         verifyAttempt(table);
182         verified = true;
183         break;
184       } catch (NullPointerException e) {
185         // If here, a cell was empty.  Presume its because updates came in
186         // after the scanner had been opened.  Wait a while and retry.
187         LOG.debug("Verification attempt failed: " + e.getMessage());
188       }
189       try {
190         Thread.sleep(pause);
191       } catch (InterruptedException e) {
192         // continue
193       }
194     }
195     assertTrue(verified);
196     table.close();
197   }
198 
199   /**
200    * Looks at every value of the mapreduce output and verifies that indeed
201    * the values have been reversed.
202    *
203    * @param table Table to scan.
204    * @throws IOException
205    * @throws NullPointerException if we failed to find a cell value
206    */
207   private void verifyAttempt(final Table table)
208       throws IOException, NullPointerException {
209     Scan scan = new Scan();
210     scan.addFamily(INPUT_FAMILY);
211     scan.addFamily(OUTPUT_FAMILY);
212     ResultScanner scanner = table.getScanner(scan);
213     try {
214       Iterator<Result> itr = scanner.iterator();
215       assertTrue(itr.hasNext());
216       while(itr.hasNext()) {
217         Result r = itr.next();
218         if (LOG.isDebugEnabled()) {
219           if (r.size() > 2 ) {
220             throw new IOException("Too many results, expected 2 got " +
221                 r.size());
222           }
223         }
224         byte[] firstValue = null;
225         byte[] secondValue = null;
226         int count = 0;
227         for(Cell kv : r.listCells()) {
228           if (count == 0) {
229             firstValue = CellUtil.cloneValue(kv);
230           }else if (count == 1) {
231             secondValue = CellUtil.cloneValue(kv);
232           }else if (count == 2) {
233             break;
234           }
235           count++;
236         }
237         String first = "";
238         if (firstValue == null) {
239           throw new NullPointerException(Bytes.toString(r.getRow()) +
240               ": first value is null");
241         }
242         first = Bytes.toString(firstValue);
243         String second = "";
244         if (secondValue == null) {
245           throw new NullPointerException(Bytes.toString(r.getRow()) +
246               ": second value is null");
247         }
248         byte[] secondReversed = new byte[secondValue.length];
249         for (int i = 0, j = secondValue.length - 1; j >= 0; j--, i++) {
250           secondReversed[i] = secondValue[j];
251         }
252         second = Bytes.toString(secondReversed);
253         if (first.compareTo(second) != 0) {
254           if (LOG.isDebugEnabled()) {
255             LOG.debug("second key is not the reverse of first. row=" +
256                 Bytes.toStringBinary(r.getRow()) + ", first value=" + first +
257                 ", second value=" + second);
258           }
259           fail();
260         }
261       }
262     } finally {
263       scanner.close();
264     }
265   }
266 
267 }
268