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 java.lang.String.format;
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertFalse;
23  import static org.junit.Assert.assertTrue;
24  
25  import java.io.IOException;
26  import java.util.Arrays;
27  import java.util.Iterator;
28  import java.util.Set;
29  import java.util.TreeSet;
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.FileSystem;
37  import org.apache.hadoop.fs.Path;
38  import org.apache.hadoop.hbase.Cell;
39  import org.apache.hadoop.hbase.HBaseConfiguration;
40  import org.apache.hadoop.hbase.IntegrationTestingUtility;
41  import org.apache.hadoop.hbase.testclassification.IntegrationTests;
42  import org.apache.hadoop.hbase.KeyValue;
43  import org.apache.hadoop.hbase.KeyValue.Type;
44  import org.apache.hadoop.hbase.TableName;
45  import org.apache.hadoop.hbase.client.HTable;
46  import org.apache.hadoop.hbase.client.Result;
47  import org.apache.hadoop.hbase.client.Scan;
48  import org.apache.hadoop.hbase.client.Table;
49  import org.apache.hadoop.hbase.util.Bytes;
50  import org.apache.hadoop.mapreduce.lib.partition.TotalOrderPartitioner;
51  import org.apache.hadoop.util.GenericOptionsParser;
52  import org.apache.hadoop.util.Tool;
53  import org.apache.hadoop.util.ToolRunner;
54  import org.junit.AfterClass;
55  import org.junit.BeforeClass;
56  import org.junit.Test;
57  import org.junit.experimental.categories.Category;
58  
59  /**
60   * Validate ImportTsv + LoadIncrementalHFiles on a distributed cluster.
61   */
62  @Category(IntegrationTests.class)
63  public class IntegrationTestImportTsv implements Configurable, Tool {
64  
65    private static final String NAME = IntegrationTestImportTsv.class.getSimpleName();
66    private static final Log LOG = LogFactory.getLog(IntegrationTestImportTsv.class);
67  
68    protected static final String simple_tsv =
69        "row1\t1\tc1\tc2\n" +
70        "row2\t1\tc1\tc2\n" +
71        "row3\t1\tc1\tc2\n" +
72        "row4\t1\tc1\tc2\n" +
73        "row5\t1\tc1\tc2\n" +
74        "row6\t1\tc1\tc2\n" +
75        "row7\t1\tc1\tc2\n" +
76        "row8\t1\tc1\tc2\n" +
77        "row9\t1\tc1\tc2\n" +
78        "row10\t1\tc1\tc2\n";
79  
80    protected static final Set<KeyValue> simple_expected =
81        new TreeSet<KeyValue>(KeyValue.COMPARATOR) {
82      private static final long serialVersionUID = 1L;
83      {
84        byte[] family = Bytes.toBytes("d");
85        for (String line : simple_tsv.split("\n")) {
86          String[] row = line.split("\t");
87          byte[] key = Bytes.toBytes(row[0]);
88          long ts = Long.parseLong(row[1]);
89          byte[][] fields = { Bytes.toBytes(row[2]), Bytes.toBytes(row[3]) };
90          add(new KeyValue(key, family, fields[0], ts, Type.Put, fields[0]));
91          add(new KeyValue(key, family, fields[1], ts, Type.Put, fields[1]));
92        }
93      }
94    };
95  
96    // this instance is initialized on first access when the test is run from
97    // JUnit/Maven or by main when run from the CLI.
98    protected static IntegrationTestingUtility util = null;
99  
100   public Configuration getConf() {
101     return util.getConfiguration();
102   }
103 
104   public void setConf(Configuration conf) {
105     throw new IllegalArgumentException("setConf not supported");
106   }
107 
108   @BeforeClass
109   public static void provisionCluster() throws Exception {
110     if (null == util) {
111       util = new IntegrationTestingUtility();
112     }
113     util.initializeCluster(1);
114     if (!util.isDistributedCluster()) {
115       // also need MR when running without a real cluster
116       util.startMiniMapReduceCluster();
117     }
118   }
119 
120   @AfterClass
121   public static void releaseCluster() throws Exception {
122     util.restoreCluster();
123     if (!util.isDistributedCluster()) {
124       util.shutdownMiniMapReduceCluster();
125     }
126     util = null;
127   }
128 
129   /**
130    * Verify the data described by <code>simple_tsv</code> matches
131    * <code>simple_expected</code>.
132    */
133   protected void doLoadIncrementalHFiles(Path hfiles, TableName tableName)
134       throws Exception {
135 
136     String[] args = { hfiles.toString(), tableName.getNameAsString() };
137     LOG.info(format("Running LoadIncrememntalHFiles with args: %s", Arrays.asList(args)));
138     assertEquals("Loading HFiles failed.",
139       0, ToolRunner.run(new LoadIncrementalHFiles(new Configuration(getConf())), args));
140 
141     Table table = null;
142     Scan scan = new Scan() {{
143       setCacheBlocks(false);
144       setCaching(1000);
145     }};
146     try {
147       table = new HTable(getConf(), tableName);
148       Iterator<Result> resultsIt = table.getScanner(scan).iterator();
149       Iterator<KeyValue> expectedIt = simple_expected.iterator();
150       while (resultsIt.hasNext() && expectedIt.hasNext()) {
151         Result r = resultsIt.next();
152         for (Cell actual : r.rawCells()) {
153           assertTrue(
154             "Ran out of expected values prematurely!",
155             expectedIt.hasNext());
156           KeyValue expected = expectedIt.next();
157           assertTrue(
158             format("Scan produced surprising result. expected: <%s>, actual: %s",
159               expected, actual),
160             KeyValue.COMPARATOR.compare(expected, actual) == 0);
161         }
162       }
163       assertFalse("Did not consume all expected values.", expectedIt.hasNext());
164       assertFalse("Did not consume all scan results.", resultsIt.hasNext());
165     } finally {
166       if (null != table) table.close();
167     }
168   }
169 
170   /**
171    * Confirm the absence of the {@link TotalOrderPartitioner} partitions file.
172    */
173   protected static void validateDeletedPartitionsFile(Configuration conf) throws IOException {
174     if (!conf.getBoolean(IntegrationTestingUtility.IS_DISTRIBUTED_CLUSTER, false))
175       return;
176 
177     FileSystem fs = FileSystem.get(conf);
178     Path partitionsFile = new Path(TotalOrderPartitioner.getPartitionFile(conf));
179     assertFalse("Failed to clean up partitions file.", fs.exists(partitionsFile));
180   }
181 
182   @Test
183   public void testGenerateAndLoad() throws Exception {
184     LOG.info("Running test testGenerateAndLoad.");
185     TableName table = TableName.valueOf(NAME + "-" + UUID.randomUUID());
186     String cf = "d";
187     Path hfiles = new Path(
188         util.getDataTestDirOnTestFS(table.getNameAsString()), "hfiles");
189 
190     String[] args = {
191         format("-D%s=%s", ImportTsv.BULK_OUTPUT_CONF_KEY, hfiles),
192         format("-D%s=HBASE_ROW_KEY,HBASE_TS_KEY,%s:c1,%s:c2",
193           ImportTsv.COLUMNS_CONF_KEY, cf, cf),
194         // configure the test harness to NOT delete the HFiles after they're
195         // generated. We need those for doLoadIncrementalHFiles
196         format("-D%s=false", TestImportTsv.DELETE_AFTER_LOAD_CONF),
197         table.getNameAsString()
198     };
199 
200     // run the job, complete the load.
201     util.createTable(table, new String[]{cf});
202     Tool t = TestImportTsv.doMROnTableTest(util, cf, simple_tsv, args);
203     doLoadIncrementalHFiles(hfiles, table);
204 
205     // validate post-conditions
206     validateDeletedPartitionsFile(t.getConf());
207 
208     // clean up after ourselves.
209     util.deleteTable(table);
210     util.cleanupDataTestDirOnTestFS(table.getNameAsString());
211     LOG.info("testGenerateAndLoad completed successfully.");
212   }
213 
214   public int run(String[] args) throws Exception {
215     if (args.length != 0) {
216       System.err.println(format("%s [genericOptions]", NAME));
217       System.err.println("  Runs ImportTsv integration tests against a distributed cluster.");
218       System.err.println();
219       GenericOptionsParser.printGenericCommandUsage(System.err);
220       return 1;
221     }
222 
223     // adding more test methods? Don't forget to add them here... or consider doing what
224     // IntegrationTestsDriver does.
225     provisionCluster();
226     testGenerateAndLoad();
227     releaseCluster();
228 
229     return 0;
230   }
231 
232   public static void main(String[] args) throws Exception {
233     Configuration conf = HBaseConfiguration.create();
234     IntegrationTestingUtility.setUseDistributedCluster(conf);
235     util = new IntegrationTestingUtility(conf);
236     // not using ToolRunner to avoid unnecessary call to setConf()
237     args = new GenericOptionsParser(conf, args).getRemainingArgs();
238     int status = new IntegrationTestImportTsv().run(args);
239     System.exit(status);
240   }
241 }