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 java.io.IOException;
21 import java.util.Arrays;
22 import java.util.Iterator;
23 import java.util.Set;
24 import java.util.TreeSet;
25 import java.util.UUID;
26
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29 import org.apache.hadoop.conf.Configurable;
30 import org.apache.hadoop.conf.Configuration;
31 import org.apache.hadoop.fs.FSDataOutputStream;
32 import org.apache.hadoop.fs.FileSystem;
33 import org.apache.hadoop.fs.Path;
34 import org.apache.hadoop.hbase.HBaseCommonTestingUtility;
35 import org.apache.hadoop.hbase.HBaseConfiguration;
36 import org.apache.hadoop.hbase.HBaseTestingUtility;
37 import org.apache.hadoop.hbase.IntegrationTestingUtility;
38 import org.apache.hadoop.hbase.IntegrationTests;
39 import org.apache.hadoop.hbase.KeyValue;
40 import org.apache.hadoop.hbase.KeyValue.Type;
41 import org.apache.hadoop.hbase.client.HTable;
42 import org.apache.hadoop.hbase.client.Result;
43 import org.apache.hadoop.hbase.client.Scan;
44 import org.apache.hadoop.hbase.util.Bytes;
45 import org.apache.hadoop.io.LongWritable;
46 import org.apache.hadoop.io.Text;
47 import org.apache.hadoop.mapreduce.Job;
48 import org.apache.hadoop.mapreduce.JobContext;
49 import org.apache.hadoop.mapreduce.OutputCommitter;
50 import org.apache.hadoop.mapreduce.OutputFormat;
51 import org.apache.hadoop.mapreduce.RecordWriter;
52 import org.apache.hadoop.mapreduce.TaskAttemptContext;
53 import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
54 import org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter;
55 import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
56 import org.apache.hadoop.mapreduce.lib.partition.TotalOrderPartitioner;
57 import org.apache.hadoop.util.GenericOptionsParser;
58 import org.apache.hadoop.util.Tool;
59 import org.apache.hadoop.util.ToolRunner;
60 import org.junit.AfterClass;
61 import org.junit.BeforeClass;
62 import org.junit.Test;
63 import org.junit.experimental.categories.Category;
64
65 import static java.lang.String.format;
66 import static org.junit.Assert.assertEquals;
67 import static org.junit.Assert.assertFalse;
68 import static org.junit.Assert.assertTrue;
69
70
71
72
73 @Category(IntegrationTests.class)
74 public class IntegrationTestImportTsv implements Configurable, Tool {
75
76 private static final String NAME = IntegrationTestImportTsv.class.getSimpleName();
77 protected static final Log LOG = LogFactory.getLog(IntegrationTestImportTsv.class);
78
79 protected static final String simple_tsv =
80 "row1\t1\tc1\tc2\n" +
81 "row2\t1\tc1\tc2\n" +
82 "row3\t1\tc1\tc2\n" +
83 "row4\t1\tc1\tc2\n" +
84 "row5\t1\tc1\tc2\n" +
85 "row6\t1\tc1\tc2\n" +
86 "row7\t1\tc1\tc2\n" +
87 "row8\t1\tc1\tc2\n" +
88 "row9\t1\tc1\tc2\n" +
89 "row10\t1\tc1\tc2\n";
90
91 protected static final Set<KeyValue> simple_expected =
92 new TreeSet<KeyValue>(KeyValue.COMPARATOR) {
93 private static final long serialVersionUID = 1L;
94 {
95 byte[] family = Bytes.toBytes("d");
96 for (String line : simple_tsv.split("\n")) {
97 String[] row = line.split("\t");
98 byte[] key = Bytes.toBytes(row[0]);
99 long ts = Long.parseLong(row[1]);
100 byte[][] fields = { Bytes.toBytes(row[2]), Bytes.toBytes(row[3]) };
101 add(new KeyValue(key, family, fields[0], ts, Type.Put, fields[0]));
102 add(new KeyValue(key, family, fields[1], ts, Type.Put, fields[1]));
103 }
104 }
105 };
106
107
108
109 protected static IntegrationTestingUtility util = null;
110
111 public Configuration getConf() {
112 return util.getConfiguration();
113 }
114
115 public void setConf(Configuration conf) {
116 throw new IllegalArgumentException("setConf not supported");
117 }
118
119 @BeforeClass
120 public static void provisionCluster() throws Exception {
121 if (null == util) {
122 util = new IntegrationTestingUtility();
123 }
124 util.initializeCluster(1);
125 }
126
127 @AfterClass
128 public static void releaseCluster() throws Exception {
129 util.restoreCluster();
130 util = null;
131 }
132
133
134
135
136
137 protected void doLoadIncrementalHFiles(Path hfiles, String tableName)
138 throws Exception {
139
140 String[] args = { hfiles.toString(), tableName };
141 LOG.info(format("Running LoadIncrememntalHFiles with args: %s", Arrays.asList(args)));
142 assertEquals("Loading HFiles failed.",
143 0, ToolRunner.run(new LoadIncrementalHFiles(new Configuration(getConf())), args));
144
145 HTable table = null;
146 Scan scan = new Scan() {{
147 setCacheBlocks(false);
148 setCaching(1000);
149 }};
150 try {
151 table = new HTable(getConf(), tableName);
152 Iterator<Result> resultsIt = table.getScanner(scan).iterator();
153 Iterator<KeyValue> expectedIt = simple_expected.iterator();
154 while (resultsIt.hasNext() && expectedIt.hasNext()) {
155 Result r = resultsIt.next();
156 for (KeyValue actual : r.raw()) {
157 assertTrue(
158 "Ran out of expected values prematurely!",
159 expectedIt.hasNext());
160 KeyValue expected = expectedIt.next();
161 assertTrue(
162 format("Scan produced surprising result. expected: <%s>, actual: %s",
163 expected, actual),
164 KeyValue.COMPARATOR.compare(expected, actual) == 0);
165 }
166 }
167 assertFalse("Did not consume all expected values.", expectedIt.hasNext());
168 assertFalse("Did not consume all scan results.", resultsIt.hasNext());
169 } finally {
170 if (null != table) table.close();
171 }
172 }
173
174
175
176
177 protected static void validateDeletedPartitionsFile(Configuration conf) throws IOException {
178 if (!conf.getBoolean(IntegrationTestingUtility.IS_DISTRIBUTED_CLUSTER, false))
179 return;
180
181 FileSystem fs = FileSystem.get(conf);
182 Path partitionsFile = new Path(TotalOrderPartitioner.getPartitionFile(conf));
183 assertFalse("Failed to clean up partitions file.", fs.exists(partitionsFile));
184 }
185
186 @Test
187 public void testGenerateAndLoad() throws Exception {
188 LOG.info("Running test testGenerateAndLoad.");
189 String table = NAME + "-" + UUID.randomUUID();
190 String cf = "d";
191 Path hfiles = new Path(util.getDataTestDirOnTestFS(table), "hfiles");
192
193 String[] args = {
194 format("-D%s=%s", ImportTsv.BULK_OUTPUT_CONF_KEY, hfiles),
195 format("-D%s=HBASE_ROW_KEY,HBASE_TS_KEY,%s:c1,%s:c2",
196 ImportTsv.COLUMNS_CONF_KEY, cf, cf),
197
198
199 format("-D%s=false", TestImportTsv.DELETE_AFTER_LOAD_CONF),
200 table
201 };
202
203
204 util.createTable(table, cf);
205 Tool t = TestImportTsv.doMROnTableTest(util, cf, simple_tsv, args);
206 doLoadIncrementalHFiles(hfiles, table);
207
208
209 validateDeletedPartitionsFile(t.getConf());
210
211
212 util.deleteTable(table);
213 util.cleanupDataTestDirOnTestFS(table);
214 LOG.info("testGenerateAndLoad completed successfully.");
215 }
216
217
218
219
220
221
222
223
224
225 private static class JobLaunchingOuputCommitter extends FileOutputCommitter {
226
227 public JobLaunchingOuputCommitter(Path outputPath, TaskAttemptContext context)
228 throws IOException {
229 super(outputPath, context);
230 }
231
232 @Override
233 public void commitJob(JobContext context) throws IOException {
234 super.commitJob(context);
235
236
237 Configuration conf = HBaseConfiguration.create(context.getConfiguration());
238 conf.set("mapred.job.classpath.archives",
239 context.getConfiguration().get("mapred.job.classpath.archives", ""));
240 conf.set("mapreduce.job.cache.archives.visibilities",
241 context.getConfiguration().get("mapreduce.job.cache.archives.visibilities", ""));
242
243
244
245 IntegrationTestingUtility util =
246 new IntegrationTestingUtility(conf);
247
248
249
250 final String table = format("%s-%s-child", NAME, context.getJobID());
251 final String cf = "FAM";
252
253 String[] args = {
254 "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B",
255 "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b",
256 table
257 };
258
259 try {
260 util.createTable(table, cf);
261 LOG.info("testRunFromOutputCommitter: launching child job.");
262 TestImportTsv.doMROnTableTest(util, cf, null, args, 1);
263 } catch (Exception e) {
264 throw new IOException("Underlying MapReduce job failed. Aborting commit.", e);
265 } finally {
266 util.deleteTable(table);
267 }
268 }
269 }
270
271
272
273
274 public static class JobLaunchingOutputFormat extends FileOutputFormat<LongWritable, Text> {
275
276 private OutputCommitter committer = null;
277
278 @Override
279 public RecordWriter<LongWritable, Text> getRecordWriter(TaskAttemptContext job)
280 throws IOException, InterruptedException {
281 return new RecordWriter<LongWritable, Text>() {
282 @Override
283 public void write(LongWritable key, Text value) throws IOException,
284 InterruptedException {
285
286 }
287
288 @Override
289 public void close(TaskAttemptContext context) throws IOException,
290 InterruptedException {
291
292 }
293 };
294 }
295
296 @Override
297 public synchronized OutputCommitter getOutputCommitter(TaskAttemptContext context)
298 throws IOException {
299 if (committer == null) {
300 Path output = getOutputPath(context);
301 LOG.debug("Using JobLaunchingOuputCommitter.");
302 committer = new JobLaunchingOuputCommitter(output, context);
303 }
304 return committer;
305 }
306 }
307
308
309
310
311 public static void addTestDependencyJars(Configuration conf) throws IOException {
312 TableMapReduceUtil.addDependencyJars(conf,
313 org.apache.hadoop.hbase.BaseConfigurable.class,
314 HBaseTestingUtility.class,
315 HBaseCommonTestingUtility.class,
316 com.google.common.collect.ListMultimap.class,
317 org.cloudera.htrace.Trace.class);
318 }
319
320
321
322
323
324
325
326
327
328
329 @Test
330 public void testRunFromOutputCommitter() throws Exception {
331 LOG.info("Running test testRunFromOutputCommitter.");
332
333 FileSystem fs = FileSystem.get(getConf());
334 Path inputPath = new Path(util.getDataTestDirOnTestFS("parent"), "input.txt");
335 Path outputPath = new Path(util.getDataTestDirOnTestFS("parent"), "output");
336 FSDataOutputStream fout = null;
337 try {
338 fout = fs.create(inputPath, true);
339 fout.write(Bytes.toBytes("testRunFromOutputCommitter\n"));
340 LOG.debug(format("Wrote test data to file: %s", inputPath));
341 } finally {
342 fout.close();
343 }
344
345
346
347 Job job = new Job(getConf(), NAME + ".testRunFromOutputCommitter - parent");
348 job.setJarByClass(IntegrationTestImportTsv.class);
349 job.setInputFormatClass(TextInputFormat.class);
350 job.setOutputFormatClass(JobLaunchingOutputFormat.class);
351 TextInputFormat.addInputPath(job, inputPath);
352 JobLaunchingOutputFormat.setOutputPath(job, outputPath);
353 TableMapReduceUtil.addDependencyJars(job);
354 addTestDependencyJars(job.getConfiguration());
355
356
357
358 LOG.info("testRunFromOutputCommitter: launching parent job.");
359 assertTrue(job.waitForCompletion(true));
360 LOG.info("testRunFromOutputCommitter completed successfully.");
361 }
362
363 public int run(String[] args) throws Exception {
364 if (args.length != 0) {
365 System.err.println(format("%s [genericOptions]", NAME));
366 System.err.println(" Runs ImportTsv integration tests against a distributed cluster.");
367 System.err.println();
368 GenericOptionsParser.printGenericCommandUsage(System.err);
369 return 1;
370 }
371
372
373
374 provisionCluster();
375 testGenerateAndLoad();
376 testRunFromOutputCommitter();
377 releaseCluster();
378
379 return 0;
380 }
381
382 public static void main(String[] args) throws Exception {
383 Configuration conf = HBaseConfiguration.create();
384 IntegrationTestingUtility.setUseDistributedCluster(conf);
385 util = new IntegrationTestingUtility(conf);
386
387 args = new GenericOptionsParser(conf, args).getRemainingArgs();
388 int status = new IntegrationTestImportTsv().run(args);
389 System.exit(status);
390 }
391 }