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.security.PrivilegedExceptionAction;
25  import java.util.ArrayList;
26  import java.util.Arrays;
27  import java.util.HashSet;
28  import java.util.List;
29  import java.util.Set;
30  import java.util.UUID;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.conf.Configurable;
35  import org.apache.hadoop.conf.Configuration;
36  import org.apache.hadoop.fs.FSDataOutputStream;
37  import org.apache.hadoop.fs.FileStatus;
38  import org.apache.hadoop.fs.FileSystem;
39  import org.apache.hadoop.fs.Path;
40  import org.apache.hadoop.hbase.Cell;
41  import org.apache.hadoop.hbase.CellUtil;
42  import org.apache.hadoop.hbase.HBaseTestingUtility;
43  import org.apache.hadoop.hbase.HConstants;
44  import org.apache.hadoop.hbase.testclassification.LargeTests;
45  import org.apache.hadoop.hbase.TableName;
46  import org.apache.hadoop.hbase.client.Admin;
47  import org.apache.hadoop.hbase.client.Delete;
48  import org.apache.hadoop.hbase.client.HBaseAdmin;
49  import org.apache.hadoop.hbase.client.HTable;
50  import org.apache.hadoop.hbase.client.Result;
51  import org.apache.hadoop.hbase.client.ResultScanner;
52  import org.apache.hadoop.hbase.client.Scan;
53  import org.apache.hadoop.hbase.client.Table;
54  import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.VisibilityLabelsResponse;
55  import org.apache.hadoop.hbase.security.User;
56  import org.apache.hadoop.hbase.security.visibility.Authorizations;
57  import org.apache.hadoop.hbase.security.visibility.CellVisibility;
58  import org.apache.hadoop.hbase.security.visibility.ScanLabelGenerator;
59  import org.apache.hadoop.hbase.security.visibility.SimpleScanLabelGenerator;
60  import org.apache.hadoop.hbase.security.visibility.VisibilityClient;
61  import org.apache.hadoop.hbase.security.visibility.VisibilityConstants;
62  import org.apache.hadoop.hbase.security.visibility.VisibilityController;
63  import org.apache.hadoop.hbase.security.visibility.VisibilityUtils;
64  import org.apache.hadoop.hbase.util.Bytes;
65  import org.apache.hadoop.mapred.Utils.OutputFileUtils.OutputFilesFilter;
66  import org.apache.hadoop.util.Tool;
67  import org.apache.hadoop.util.ToolRunner;
68  import org.junit.AfterClass;
69  import org.junit.BeforeClass;
70  import org.junit.Test;
71  import org.junit.experimental.categories.Category;
72  
73  @Category(LargeTests.class)
74  public class TestImportTSVWithVisibilityLabels implements Configurable {
75  
76    protected static final Log LOG = LogFactory.getLog(TestImportTSVWithVisibilityLabels.class);
77    protected static final String NAME = TestImportTsv.class.getSimpleName();
78    protected static HBaseTestingUtility util = new HBaseTestingUtility();
79  
80    /**
81     * Delete the tmp directory after running doMROnTableTest. Boolean. Default is
82     * false.
83     */
84    protected static final String DELETE_AFTER_LOAD_CONF = NAME + ".deleteAfterLoad";
85  
86    /**
87     * Force use of combiner in doMROnTableTest. Boolean. Default is true.
88     */
89    protected static final String FORCE_COMBINER_CONF = NAME + ".forceCombiner";
90  
91    private final String FAMILY = "FAM";
92    private final static String TOPSECRET = "topsecret";
93    private final static String PUBLIC = "public";
94    private final static String PRIVATE = "private";
95    private final static String CONFIDENTIAL = "confidential";
96    private final static String SECRET = "secret";
97    private static User SUPERUSER;
98    private static Configuration conf;
99  
100   @Override
101   public Configuration getConf() {
102     return util.getConfiguration();
103   }
104 
105   @Override
106   public void setConf(Configuration conf) {
107     throw new IllegalArgumentException("setConf not supported");
108   }
109 
110   @BeforeClass
111   public static void provisionCluster() throws Exception {
112     conf = util.getConfiguration();
113     SUPERUSER = User.createUserForTesting(conf, "admin", new String[] { "supergroup" });
114     conf.set("hbase.superuser", "admin,"+User.getCurrent().getName());
115     conf.setInt("hfile.format.version", 3);
116     conf.set("hbase.coprocessor.master.classes", VisibilityController.class.getName());
117     conf.set("hbase.coprocessor.region.classes", VisibilityController.class.getName());
118     conf.setClass(VisibilityUtils.VISIBILITY_LABEL_GENERATOR_CLASS, SimpleScanLabelGenerator.class,
119         ScanLabelGenerator.class);
120     util.startMiniCluster();
121     // Wait for the labels table to become available
122     util.waitTableEnabled(VisibilityConstants.LABELS_TABLE_NAME.getName(), 50000);
123     createLabels();
124     Admin admin = new HBaseAdmin(util.getConfiguration());
125     util.startMiniMapReduceCluster();
126   }
127 
128   private static void createLabels() throws IOException, InterruptedException {
129     PrivilegedExceptionAction<VisibilityLabelsResponse> action =
130         new PrivilegedExceptionAction<VisibilityLabelsResponse>() {
131       @Override
132       public VisibilityLabelsResponse run() throws Exception {
133         String[] labels = { SECRET, TOPSECRET, CONFIDENTIAL, PUBLIC, PRIVATE };
134         try {
135           VisibilityClient.addLabels(conf, labels);
136           LOG.info("Added labels ");
137         } catch (Throwable t) {
138           LOG.error("Error in adding labels" , t);
139           throw new IOException(t);
140         }
141         return null;
142       }
143     };
144     SUPERUSER.runAs(action);
145   }
146 
147   @AfterClass
148   public static void releaseCluster() throws Exception {
149     util.shutdownMiniMapReduceCluster();
150     util.shutdownMiniCluster();
151   }
152 
153   @Test
154   public void testMROnTable() throws Exception {
155     String tableName = "test-" + UUID.randomUUID();
156 
157     // Prepare the arguments required for the test.
158     String[] args = new String[] {
159         "-D" + ImportTsv.MAPPER_CONF_KEY
160             + "=org.apache.hadoop.hbase.mapreduce.TsvImporterMapper",
161         "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B,HBASE_CELL_VISIBILITY",
162         "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b", tableName };
163     String data = "KEY\u001bVALUE1\u001bVALUE2\u001bsecret&private\n";
164     util.createTable(TableName.valueOf(tableName), FAMILY);
165     doMROnTableTest(util, FAMILY, data, args, 1);
166     util.deleteTable(tableName);
167   }
168 
169   @Test
170   public void testMROnTableWithDeletes() throws Exception {
171     TableName tableName = TableName.valueOf("test-" + UUID.randomUUID());
172 
173     // Prepare the arguments required for the test.
174     String[] args = new String[] {
175         "-D" + ImportTsv.MAPPER_CONF_KEY + "=org.apache.hadoop.hbase.mapreduce.TsvImporterMapper",
176         "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B,HBASE_CELL_VISIBILITY",
177         "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b", tableName.getNameAsString() };
178     String data = "KEY\u001bVALUE1\u001bVALUE2\u001bsecret&private\n";
179     util.createTable(tableName, FAMILY);
180     doMROnTableTest(util, FAMILY, data, args, 1);
181     issueDeleteAndVerifyData(tableName);
182     util.deleteTable(tableName);
183   }
184 
185   private void issueDeleteAndVerifyData(TableName tableName) throws IOException {
186     LOG.debug("Validating table after delete.");
187     Table table = new HTable(conf, tableName);
188     boolean verified = false;
189     long pause = conf.getLong("hbase.client.pause", 5 * 1000);
190     int numRetries = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5);
191     for (int i = 0; i < numRetries; i++) {
192       try {
193         Delete d = new Delete(Bytes.toBytes("KEY"));
194         d.deleteFamily(Bytes.toBytes(FAMILY));
195         d.setCellVisibility(new CellVisibility("private&secret"));
196         table.delete(d);
197 
198         Scan scan = new Scan();
199         // Scan entire family.
200         scan.addFamily(Bytes.toBytes(FAMILY));
201         scan.setAuthorizations(new Authorizations("secret", "private"));
202         ResultScanner resScanner = table.getScanner(scan);
203         Result[] next = resScanner.next(5);
204         assertEquals(0, next.length);
205         verified = true;
206         break;
207       } catch (NullPointerException e) {
208         // If here, a cell was empty. Presume its because updates came in
209         // after the scanner had been opened. Wait a while and retry.
210       }
211       try {
212         Thread.sleep(pause);
213       } catch (InterruptedException e) {
214         // continue
215       }
216     }
217     table.close();
218     assertTrue(verified);
219   }
220 
221   @Test
222   public void testMROnTableWithBulkload() throws Exception {
223     String tableName = "test-" + UUID.randomUUID();
224     Path hfiles = new Path(util.getDataTestDirOnTestFS(tableName), "hfiles");
225     // Prepare the arguments required for the test.
226     String[] args = new String[] {
227         "-D" + ImportTsv.BULK_OUTPUT_CONF_KEY + "=" + hfiles.toString(),
228         "-D" + ImportTsv.COLUMNS_CONF_KEY
229             + "=HBASE_ROW_KEY,FAM:A,FAM:B,HBASE_CELL_VISIBILITY",
230         "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b", tableName };
231     String data = "KEY\u001bVALUE1\u001bVALUE2\u001bsecret&private\n";
232     util.createTable(TableName.valueOf(tableName), FAMILY);
233     doMROnTableTest(util, FAMILY, data, args, 1);
234     util.deleteTable(tableName);
235   }
236 
237   @Test
238   public void testBulkOutputWithTsvImporterTextMapper() throws Exception {
239     String table = "test-" + UUID.randomUUID();
240     String FAMILY = "FAM";
241     Path bulkOutputPath = new Path(util.getDataTestDirOnTestFS(table),"hfiles");
242     // Prepare the arguments required for the test.
243     String[] args =
244         new String[] {
245             "-D" + ImportTsv.MAPPER_CONF_KEY
246                 + "=org.apache.hadoop.hbase.mapreduce.TsvImporterTextMapper",
247             "-D" + ImportTsv.COLUMNS_CONF_KEY
248                 + "=HBASE_ROW_KEY,FAM:A,FAM:B,HBASE_CELL_VISIBILITY",
249             "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b",
250             "-D" + ImportTsv.BULK_OUTPUT_CONF_KEY + "=" + bulkOutputPath.toString(), table
251             };
252     String data = "KEY\u001bVALUE4\u001bVALUE8\u001bsecret&private\n";
253     doMROnTableTest(util, FAMILY, data, args, 4);
254     util.deleteTable(table);
255   }
256 
257   @Test
258   public void testMRWithOutputFormat() throws Exception {
259     String tableName = "test-" + UUID.randomUUID();
260     Path hfiles = new Path(util.getDataTestDirOnTestFS(tableName), "hfiles");
261     // Prepare the arguments required for the test.
262     String[] args = new String[] {
263         "-D" + ImportTsv.MAPPER_CONF_KEY
264             + "=org.apache.hadoop.hbase.mapreduce.TsvImporterMapper",
265         "-D" + ImportTsv.BULK_OUTPUT_CONF_KEY + "=" + hfiles.toString(),
266         "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B,HBASE_CELL_VISIBILITY",
267         "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b", tableName };
268     String data = "KEY\u001bVALUE4\u001bVALUE8\u001bsecret&private\n";
269     util.createTable(TableName.valueOf(tableName), FAMILY);
270     doMROnTableTest(util, FAMILY, data, args, 1);
271     util.deleteTable(tableName);
272   }
273 
274   /**
275    * Run an ImportTsv job and perform basic validation on the results. Returns
276    * the ImportTsv <code>Tool</code> instance so that other tests can inspect it
277    * for further validation as necessary. This method is static to insure
278    * non-reliance on instance's util/conf facilities.
279    *
280    * @param args
281    *          Any arguments to pass BEFORE inputFile path is appended.
282    * @return The Tool instance used to run the test.
283    */
284   protected static Tool doMROnTableTest(HBaseTestingUtility util, String family, String data,
285       String[] args, int valueMultiplier) throws Exception {
286     TableName table = TableName.valueOf(args[args.length - 1]);
287     Configuration conf = new Configuration(util.getConfiguration());
288 
289     // populate input file
290     FileSystem fs = FileSystem.get(conf);
291     Path inputPath = fs.makeQualified(new Path(util
292         .getDataTestDirOnTestFS(table.getNameAsString()), "input.dat"));
293     FSDataOutputStream op = fs.create(inputPath, true);
294     if (data == null) {
295       data = "KEY\u001bVALUE1\u001bVALUE2\n";
296     }
297     op.write(Bytes.toBytes(data));
298     op.close();
299     LOG.debug(String.format("Wrote test data to file: %s", inputPath));
300 
301     if (conf.getBoolean(FORCE_COMBINER_CONF, true)) {
302       LOG.debug("Forcing combiner.");
303       conf.setInt("mapreduce.map.combine.minspills", 1);
304     }
305 
306     // run the import
307     List<String> argv = new ArrayList<String>(Arrays.asList(args));
308     argv.add(inputPath.toString());
309     Tool tool = new ImportTsv();
310     LOG.debug("Running ImportTsv with arguments: " + argv);
311     assertEquals(0, ToolRunner.run(conf, tool, argv.toArray(args)));
312 
313     // Perform basic validation. If the input args did not include
314     // ImportTsv.BULK_OUTPUT_CONF_KEY then validate data in the table.
315     // Otherwise, validate presence of hfiles.
316     boolean createdHFiles = false;
317     String outputPath = null;
318     for (String arg : argv) {
319       if (arg.contains(ImportTsv.BULK_OUTPUT_CONF_KEY)) {
320         createdHFiles = true;
321         // split '-Dfoo=bar' on '=' and keep 'bar'
322         outputPath = arg.split("=")[1];
323         break;
324       }
325     }
326     LOG.debug("validating the table " + createdHFiles);
327     if (createdHFiles)
328      validateHFiles(fs, outputPath, family);
329     else
330       validateTable(conf, table, family, valueMultiplier);
331 
332     if (conf.getBoolean(DELETE_AFTER_LOAD_CONF, true)) {
333       LOG.debug("Deleting test subdirectory");
334       util.cleanupDataTestDirOnTestFS(table.getNameAsString());
335     }
336     return tool;
337   }
338 
339   /**
340    * Confirm ImportTsv via HFiles on fs.
341    */
342   private static void validateHFiles(FileSystem fs, String outputPath, String family)
343       throws IOException {
344 
345     // validate number and content of output columns
346     LOG.debug("Validating HFiles.");
347     Set<String> configFamilies = new HashSet<String>();
348     configFamilies.add(family);
349     Set<String> foundFamilies = new HashSet<String>();
350     for (FileStatus cfStatus : fs.listStatus(new Path(outputPath), new OutputFilesFilter())) {
351       LOG.debug("The output path has files");
352       String[] elements = cfStatus.getPath().toString().split(Path.SEPARATOR);
353       String cf = elements[elements.length - 1];
354       foundFamilies.add(cf);
355       assertTrue(String.format(
356           "HFile ouput contains a column family (%s) not present in input families (%s)", cf,
357           configFamilies), configFamilies.contains(cf));
358       for (FileStatus hfile : fs.listStatus(cfStatus.getPath())) {
359         assertTrue(String.format("HFile %s appears to contain no data.", hfile.getPath()),
360             hfile.getLen() > 0);
361       }
362     }
363   }
364 
365   /**
366    * Confirm ImportTsv via data in online table.
367    */
368   private static void validateTable(Configuration conf, TableName tableName, String family,
369       int valueMultiplier) throws IOException {
370 
371     LOG.debug("Validating table.");
372     Table table = new HTable(conf, tableName);
373     boolean verified = false;
374     long pause = conf.getLong("hbase.client.pause", 5 * 1000);
375     int numRetries = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5);
376     for (int i = 0; i < numRetries; i++) {
377       try {
378         Scan scan = new Scan();
379         // Scan entire family.
380         scan.addFamily(Bytes.toBytes(family));
381         scan.setAuthorizations(new Authorizations("secret","private"));
382         ResultScanner resScanner = table.getScanner(scan);
383         Result[] next = resScanner.next(5);
384         assertEquals(1, next.length);
385         for (Result res : resScanner) {
386           LOG.debug("Getting results " + res.size());
387           assertTrue(res.size() == 2);
388           List<Cell> kvs = res.listCells();
389           assertTrue(CellUtil.matchingRow(kvs.get(0), Bytes.toBytes("KEY")));
390           assertTrue(CellUtil.matchingRow(kvs.get(1), Bytes.toBytes("KEY")));
391           assertTrue(CellUtil.matchingValue(kvs.get(0), Bytes.toBytes("VALUE" + valueMultiplier)));
392           assertTrue(CellUtil.matchingValue(kvs.get(1),
393               Bytes.toBytes("VALUE" + 2 * valueMultiplier)));
394           // Only one result set is expected, so let it loop.
395         }
396         verified = true;
397         break;
398       } catch (NullPointerException e) {
399         // If here, a cell was empty. Presume its because updates came in
400         // after the scanner had been opened. Wait a while and retry.
401       }
402       try {
403         Thread.sleep(pause);
404       } catch (InterruptedException e) {
405         // continue
406       }
407     }
408     table.close();
409     assertTrue(verified);
410   }
411 
412 }