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