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.assertEquals;
21  import static org.junit.Assert.assertTrue;
22  
23  import java.io.IOException;
24  import java.util.ArrayList;
25  import java.util.Arrays;
26  import java.util.List;
27  import java.util.UUID;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.conf.Configurable;
32  import org.apache.hadoop.conf.Configuration;
33  import org.apache.hadoop.fs.FSDataOutputStream;
34  import org.apache.hadoop.fs.FileSystem;
35  import org.apache.hadoop.fs.Path;
36  import org.apache.hadoop.hbase.Cell;
37  import org.apache.hadoop.hbase.CellUtil;
38  import org.apache.hadoop.hbase.HBaseTestingUtility;
39  import org.apache.hadoop.hbase.HConstants;
40  import org.apache.hadoop.hbase.LargeTests;
41  import org.apache.hadoop.hbase.client.Durability;
42  import org.apache.hadoop.hbase.client.HBaseAdmin;
43  import org.apache.hadoop.hbase.client.HTable;
44  import org.apache.hadoop.hbase.client.Put;
45  import org.apache.hadoop.hbase.client.Result;
46  import org.apache.hadoop.hbase.client.ResultScanner;
47  import org.apache.hadoop.hbase.client.Scan;
48  import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
49  import org.apache.hadoop.hbase.coprocessor.ObserverContext;
50  import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
51  import org.apache.hadoop.hbase.regionserver.HRegion;
52  import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
53  import org.apache.hadoop.hbase.util.Bytes;
54  import org.apache.hadoop.util.Tool;
55  import org.apache.hadoop.util.ToolRunner;
56  import org.junit.AfterClass;
57  import org.junit.BeforeClass;
58  import org.junit.Test;
59  import org.junit.experimental.categories.Category;
60  
61  @Category(LargeTests.class)
62  public class TestImportTSVWithOperationAttributes implements Configurable {
63  
64    protected static final Log LOG = LogFactory.getLog(TestImportTSVWithOperationAttributes.class);
65    protected static final String NAME = TestImportTsv.class.getSimpleName();
66    protected static HBaseTestingUtility util = new HBaseTestingUtility();
67  
68    /**
69     * Delete the tmp directory after running doMROnTableTest. Boolean. Default is
70     * false.
71     */
72    protected static final String DELETE_AFTER_LOAD_CONF = NAME + ".deleteAfterLoad";
73  
74    /**
75     * Force use of combiner in doMROnTableTest. Boolean. Default is true.
76     */
77    protected static final String FORCE_COMBINER_CONF = NAME + ".forceCombiner";
78  
79    private static Configuration conf;
80  
81    private static final String TEST_ATR_KEY = "test";
82  
83    private final String FAMILY = "FAM";
84  
85    public Configuration getConf() {
86      return util.getConfiguration();
87    }
88  
89    public void setConf(Configuration conf) {
90      throw new IllegalArgumentException("setConf not supported");
91    }
92  
93    @BeforeClass
94    public static void provisionCluster() throws Exception {
95      conf = util.getConfiguration();
96      conf.set("hbase.coprocessor.master.classes", OperationAttributesTestController.class.getName());
97      conf.set("hbase.coprocessor.region.classes", OperationAttributesTestController.class.getName());
98      util.startMiniCluster();
99      HBaseAdmin admin = new HBaseAdmin(util.getConfiguration());
100     util.startMiniMapReduceCluster();
101   }
102 
103   @AfterClass
104   public static void releaseCluster() throws Exception {
105     util.shutdownMiniMapReduceCluster();
106     util.shutdownMiniCluster();
107   }
108 
109   @Test
110   public void testMROnTable() throws Exception {
111     String tableName = "test-" + UUID.randomUUID();
112 
113     // Prepare the arguments required for the test.
114     String[] args = new String[] {
115         "-D" + ImportTsv.MAPPER_CONF_KEY
116             + "=org.apache.hadoop.hbase.mapreduce.TsvImporterCustomTestMapperForOprAttr",
117         "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B,HBASE_ATTRIBUTES_KEY",
118         "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b", tableName };
119     String data = "KEY\u001bVALUE1\u001bVALUE2\u001btest=>myvalue\n";
120     util.createTable(tableName, FAMILY);
121     doMROnTableTest(util, FAMILY, data, args, 1, true);
122     util.deleteTable(tableName);
123   }
124 
125   @Test
126   public void testMROnTableWithInvalidOperationAttr() throws Exception {
127     String tableName = "test-" + UUID.randomUUID();
128 
129     // Prepare the arguments required for the test.
130     String[] args = new String[] {
131         "-D" + ImportTsv.MAPPER_CONF_KEY
132             + "=org.apache.hadoop.hbase.mapreduce.TsvImporterCustomTestMapperForOprAttr",
133         "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B,HBASE_ATTRIBUTES_KEY",
134         "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b", tableName };
135     String data = "KEY\u001bVALUE1\u001bVALUE2\u001btest1=>myvalue\n";
136     util.createTable(tableName, FAMILY);
137     doMROnTableTest(util, FAMILY, data, args, 1, false);
138     util.deleteTable(tableName);
139   }
140 
141   /**
142    * Run an ImportTsv job and perform basic validation on the results. Returns
143    * the ImportTsv <code>Tool</code> instance so that other tests can inspect it
144    * for further validation as necessary. This method is static to insure
145    * non-reliance on instance's util/conf facilities.
146    * 
147    * @param args
148    *          Any arguments to pass BEFORE inputFile path is appended.
149    * @param dataAvailable
150    * @return The Tool instance used to run the test.
151    */
152   private Tool doMROnTableTest(HBaseTestingUtility util, String family, String data, String[] args,
153       int valueMultiplier, boolean dataAvailable) throws Exception {
154     String table = args[args.length - 1];
155     Configuration conf = new Configuration(util.getConfiguration());
156 
157     // populate input file
158     FileSystem fs = FileSystem.get(conf);
159     Path inputPath = fs.makeQualified(new Path(util.getDataTestDirOnTestFS(table), "input.dat"));
160     FSDataOutputStream op = fs.create(inputPath, true);
161     op.write(Bytes.toBytes(data));
162     op.close();
163     LOG.debug(String.format("Wrote test data to file: %s", inputPath));
164 
165     if (conf.getBoolean(FORCE_COMBINER_CONF, true)) {
166       LOG.debug("Forcing combiner.");
167       conf.setInt("min.num.spills.for.combine", 1);
168     }
169 
170     // run the import
171     List<String> argv = new ArrayList<String>(Arrays.asList(args));
172     argv.add(inputPath.toString());
173     Tool tool = new ImportTsv();
174     LOG.debug("Running ImportTsv with arguments: " + argv);
175     assertEquals(0, ToolRunner.run(conf, tool, argv.toArray(args)));
176 
177     validateTable(conf, table, family, valueMultiplier, dataAvailable);
178 
179     if (conf.getBoolean(DELETE_AFTER_LOAD_CONF, true)) {
180       LOG.debug("Deleting test subdirectory");
181       util.cleanupDataTestDirOnTestFS(table);
182     }
183     return tool;
184   }
185 
186   /**
187    * Confirm ImportTsv via data in online table.
188    * 
189    * @param dataAvailable
190    */
191   private static void validateTable(Configuration conf, String tableName, String family,
192       int valueMultiplier, boolean dataAvailable) throws IOException {
193 
194     LOG.debug("Validating table.");
195     HTable table = new HTable(conf, tableName);
196     boolean verified = false;
197     long pause = conf.getLong("hbase.client.pause", 5 * 1000);
198     int numRetries = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5);
199     for (int i = 0; i < numRetries; i++) {
200       try {
201         Scan scan = new Scan();
202         // Scan entire family.
203         scan.addFamily(Bytes.toBytes(family));
204         if (dataAvailable) {
205           ResultScanner resScanner = table.getScanner(scan);
206           for (Result res : resScanner) {
207             LOG.debug("Getting results " + res.size());
208             assertTrue(res.size() == 2);
209             List<Cell> kvs = res.listCells();
210             assertTrue(CellUtil.matchingRow(kvs.get(0), Bytes.toBytes("KEY")));
211             assertTrue(CellUtil.matchingRow(kvs.get(1), Bytes.toBytes("KEY")));
212             assertTrue(CellUtil.matchingValue(kvs.get(0), Bytes.toBytes("VALUE" + valueMultiplier)));
213             assertTrue(CellUtil.matchingValue(kvs.get(1),
214                 Bytes.toBytes("VALUE" + 2 * valueMultiplier)));
215             // Only one result set is expected, so let it loop.
216             verified = true;
217           }
218         } else {
219           ResultScanner resScanner = table.getScanner(scan);
220           Result[] next = resScanner.next(2);
221           assertEquals(0, next.length);
222           verified = true;
223         }
224 
225         break;
226       } catch (NullPointerException e) {
227         // If here, a cell was empty. Presume its because updates came in
228         // after the scanner had been opened. Wait a while and retry.
229       }
230       try {
231         Thread.sleep(pause);
232       } catch (InterruptedException e) {
233         // continue
234       }
235     }
236     table.close();
237     assertTrue(verified);
238   }
239 
240   public static class OperationAttributesTestController extends BaseRegionObserver {
241 
242     @Override
243     public void prePut(ObserverContext<RegionCoprocessorEnvironment> e, Put put, WALEdit edit,
244         Durability durability) throws IOException {
245       HRegion region = e.getEnvironment().getRegion();
246       if (!region.getRegionInfo().isMetaTable()
247           && !region.getRegionInfo().getTable().isSystemTable()) {
248         if (put.getAttribute(TEST_ATR_KEY) != null) {
249           LOG.debug("allow any put to happen " + region.getRegionNameAsString());
250         } else {
251           e.bypass();
252         }
253       }
254     }
255   }
256 }