1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.client.Delete;
45 import org.apache.hadoop.hbase.client.HBaseAdmin;
46 import org.apache.hadoop.hbase.client.HTable;
47 import org.apache.hadoop.hbase.client.Result;
48 import org.apache.hadoop.hbase.client.ResultScanner;
49 import org.apache.hadoop.hbase.client.Scan;
50 import org.apache.hadoop.hbase.io.hfile.CacheConfig;
51 import org.apache.hadoop.hbase.io.hfile.HFile;
52 import org.apache.hadoop.hbase.io.hfile.HFileScanner;
53 import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.VisibilityLabelsResponse;
54 import org.apache.hadoop.hbase.security.User;
55 import org.apache.hadoop.hbase.security.visibility.Authorizations;
56 import org.apache.hadoop.hbase.security.visibility.CellVisibility;
57 import org.apache.hadoop.hbase.security.visibility.ScanLabelGenerator;
58 import org.apache.hadoop.hbase.security.visibility.SimpleScanLabelGenerator;
59 import org.apache.hadoop.hbase.security.visibility.VisibilityClient;
60 import org.apache.hadoop.hbase.security.visibility.VisibilityConstants;
61 import org.apache.hadoop.hbase.security.visibility.VisibilityController;
62 import org.apache.hadoop.hbase.security.visibility.VisibilityUtils;
63 import org.apache.hadoop.hbase.testclassification.LargeTests;
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
82
83
84 protected static final String DELETE_AFTER_LOAD_CONF = NAME + ".deleteAfterLoad";
85
86
87
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
122 util.waitTableEnabled(VisibilityConstants.LABELS_TABLE_NAME.getName(), 50000);
123 createLabels();
124 HBaseAdmin 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
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, FAMILY);
165 doMROnTableTest(util, FAMILY, data, args, 1);
166 util.deleteTable(tableName);
167 }
168
169 @Test
170 public void testMROnTableWithDeletes() throws Exception {
171 String tableName = "test-" + UUID.randomUUID();
172
173
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 };
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(String tableName) throws IOException {
186 LOG.debug("Validating table after delete.");
187 HTable 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
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
209
210 }
211 try {
212 Thread.sleep(pause);
213 } catch (InterruptedException e) {
214
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
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, 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
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
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, FAMILY);
270 doMROnTableTest(util, FAMILY, data, args, 1);
271 util.deleteTable(tableName);
272 }
273
274 @Test
275 public void testBulkOutputWithInvalidLabels() throws Exception {
276 String tableName = "test-" + UUID.randomUUID();
277 Path hfiles = new Path(util.getDataTestDirOnTestFS(tableName), "hfiles");
278
279 String[] args =
280 new String[] { "-D" + ImportTsv.BULK_OUTPUT_CONF_KEY + "=" + hfiles.toString(),
281 "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B,HBASE_CELL_VISIBILITY",
282 "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b", tableName };
283
284
285 String data =
286 "KEY\u001bVALUE1\u001bVALUE2\u001bprivate\nKEY1\u001bVALUE1\u001bVALUE2\u001binvalid\n";
287 util.createTable(tableName, FAMILY);
288 doMROnTableTest(util, FAMILY, data, args, 1, 2);
289 util.deleteTable(tableName);
290 }
291
292 @Test
293 public void testBulkOutputWithTsvImporterTextMapperWithInvalidLabels() throws Exception {
294 String tableName = "test-" + UUID.randomUUID();
295 Path hfiles = new Path(util.getDataTestDirOnTestFS(tableName), "hfiles");
296
297 String[] args =
298 new String[] {
299 "-D" + ImportTsv.MAPPER_CONF_KEY
300 + "=org.apache.hadoop.hbase.mapreduce.TsvImporterTextMapper",
301 "-D" + ImportTsv.BULK_OUTPUT_CONF_KEY + "=" + hfiles.toString(),
302 "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B,HBASE_CELL_VISIBILITY",
303 "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b", tableName };
304
305
306 String data =
307 "KEY\u001bVALUE1\u001bVALUE2\u001bprivate\nKEY1\u001bVALUE1\u001bVALUE2\u001binvalid\n";
308 util.createTable(tableName, FAMILY);
309 doMROnTableTest(util, FAMILY, data, args, 1, 2);
310 util.deleteTable(tableName);
311 }
312
313 protected static Tool doMROnTableTest(HBaseTestingUtility util, String family, String data,
314 String[] args, int valueMultiplier) throws Exception {
315 return doMROnTableTest(util, family, data, args, valueMultiplier, -1);
316 }
317
318
319
320
321
322
323
324
325
326
327
328
329
330 protected static Tool doMROnTableTest(HBaseTestingUtility util, String family, String data,
331 String[] args, int valueMultiplier, int expectedKVCount) throws Exception {
332 String table = args[args.length - 1];
333 Configuration conf = new Configuration(util.getConfiguration());
334
335
336 FileSystem fs = FileSystem.get(conf);
337 Path inputPath = fs.makeQualified(new Path(util.getDataTestDirOnTestFS(table), "input.dat"));
338 FSDataOutputStream op = fs.create(inputPath, true);
339 if (data == null) {
340 data = "KEY\u001bVALUE1\u001bVALUE2\n";
341 }
342 op.write(Bytes.toBytes(data));
343 op.close();
344 LOG.debug(String.format("Wrote test data to file: %s", inputPath));
345
346 if (conf.getBoolean(FORCE_COMBINER_CONF, true)) {
347 LOG.debug("Forcing combiner.");
348 conf.setInt("min.num.spills.for.combine", 1);
349 }
350
351
352 List<String> argv = new ArrayList<String>(Arrays.asList(args));
353 argv.add(inputPath.toString());
354 Tool tool = new ImportTsv();
355 LOG.debug("Running ImportTsv with arguments: " + argv);
356 assertEquals(0, ToolRunner.run(conf, tool, argv.toArray(args)));
357
358
359
360
361 boolean createdHFiles = false;
362 String outputPath = null;
363 for (String arg : argv) {
364 if (arg.contains(ImportTsv.BULK_OUTPUT_CONF_KEY)) {
365 createdHFiles = true;
366
367 outputPath = arg.split("=")[1];
368 break;
369 }
370 }
371 LOG.debug("validating the table " + createdHFiles);
372 if (createdHFiles)
373 validateHFiles(fs, outputPath, family,expectedKVCount);
374 else
375 validateTable(conf, table, family, valueMultiplier);
376
377 if (conf.getBoolean(DELETE_AFTER_LOAD_CONF, true)) {
378 LOG.debug("Deleting test subdirectory");
379 util.cleanupDataTestDirOnTestFS(table);
380 }
381 return tool;
382 }
383
384
385
386
387 private static void validateHFiles(FileSystem fs, String outputPath, String family,
388 int expectedKVCount) throws IOException {
389
390
391 LOG.debug("Validating HFiles.");
392 Set<String> configFamilies = new HashSet<String>();
393 configFamilies.add(family);
394 Set<String> foundFamilies = new HashSet<String>();
395 int actualKVCount = 0;
396 for (FileStatus cfStatus : fs.listStatus(new Path(outputPath), new OutputFilesFilter())) {
397 LOG.debug("The output path has files");
398 String[] elements = cfStatus.getPath().toString().split(Path.SEPARATOR);
399 String cf = elements[elements.length - 1];
400 foundFamilies.add(cf);
401 assertTrue(String.format(
402 "HFile ouput contains a column family (%s) not present in input families (%s)", cf,
403 configFamilies), configFamilies.contains(cf));
404 for (FileStatus hfile : fs.listStatus(cfStatus.getPath())) {
405 assertTrue(String.format("HFile %s appears to contain no data.", hfile.getPath()),
406 hfile.getLen() > 0);
407 if (expectedKVCount > -1) {
408 actualKVCount += getKVCountFromHfile(fs, hfile.getPath());
409 }
410 }
411 }
412 if (expectedKVCount > -1) {
413 assertTrue(String.format(
414 "KV count in output hfile=<%d> doesn't match with expected KV count=<%d>", actualKVCount,
415 expectedKVCount), actualKVCount == expectedKVCount);
416 }
417 }
418
419
420
421
422
423
424
425
426 private static int getKVCountFromHfile(FileSystem fs, Path p) throws IOException {
427 Configuration conf = util.getConfiguration();
428 HFile.Reader reader = HFile.createReader(fs, p, new CacheConfig(conf), conf);
429 reader.loadFileInfo();
430 HFileScanner scanner = reader.getScanner(false, false);
431 scanner.seekTo();
432 int count = 0;
433 do {
434 count++;
435 } while (scanner.next());
436 reader.close();
437 return count;
438 }
439
440
441
442
443 private static void validateTable(Configuration conf, String tableName, String family,
444 int valueMultiplier) throws IOException {
445
446 LOG.debug("Validating table.");
447 HTable table = new HTable(conf, tableName);
448 boolean verified = false;
449 long pause = conf.getLong("hbase.client.pause", 5 * 1000);
450 int numRetries = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5);
451 for (int i = 0; i < numRetries; i++) {
452 try {
453 Scan scan = new Scan();
454
455 scan.addFamily(Bytes.toBytes(family));
456 scan.setAuthorizations(new Authorizations("secret","private"));
457 ResultScanner resScanner = table.getScanner(scan);
458 Result[] next = resScanner.next(5);
459 assertEquals(1, next.length);
460 for (Result res : resScanner) {
461 LOG.debug("Getting results " + res.size());
462 assertTrue(res.size() == 2);
463 List<Cell> kvs = res.listCells();
464 assertTrue(CellUtil.matchingRow(kvs.get(0), Bytes.toBytes("KEY")));
465 assertTrue(CellUtil.matchingRow(kvs.get(1), Bytes.toBytes("KEY")));
466 assertTrue(CellUtil.matchingValue(kvs.get(0), Bytes.toBytes("VALUE" + valueMultiplier)));
467 assertTrue(CellUtil.matchingValue(kvs.get(1),
468 Bytes.toBytes("VALUE" + 2 * valueMultiplier)));
469
470 }
471 verified = true;
472 break;
473 } catch (NullPointerException e) {
474
475
476 }
477 try {
478 Thread.sleep(pause);
479 } catch (InterruptedException e) {
480
481 }
482 }
483 table.close();
484 assertTrue(verified);
485 }
486
487 }