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