View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.mapreduce;
20  
21  import java.io.IOException;
22  import java.util.List;
23  import java.util.ArrayList;
24
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  import org.apache.commons.lang.StringUtils;
28  import org.apache.hadoop.hbase.HConstants;
29  import org.apache.hadoop.hbase.classification.InterfaceAudience;
30  import org.apache.hadoop.hbase.classification.InterfaceStability;
31  import org.apache.hadoop.conf.Configuration;
32  import org.apache.hadoop.conf.Configured;
33  import org.apache.hadoop.hbase.HBaseConfiguration;
34  import org.apache.hadoop.hbase.client.Result;
35  import org.apache.hadoop.hbase.client.Scan;
36  import org.apache.hadoop.hbase.filter.FilterBase;
37  import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
38  import org.apache.hadoop.hbase.filter.MultiRowRangeFilter;
39  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
40  import org.apache.hadoop.hbase.util.Bytes;
41  import org.apache.hadoop.mapreduce.Counter;
42  import org.apache.hadoop.mapreduce.Job;
43  import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
44  import org.apache.hadoop.util.Tool;
45  import org.apache.hadoop.util.ToolRunner;
46
47  /**
48   * A job with a just a map phase to count rows. Map outputs table rows IF the
49   * input row has columns that have content.
50   */
51  @InterfaceAudience.Public
52  @InterfaceStability.Stable
53  public class RowCounter extends Configured implements Tool {
54
55    private static final Log LOG = LogFactory.getLog(RowCounter.class);
56
57    /** Name of this 'program'. */
58    static final String NAME = "rowcounter";
59
60    private final static String JOB_NAME_CONF_KEY = "mapreduce.job.name";
61    private final static String EXPECTED_COUNT_KEY = RowCounter.class.getName() + ".expected_count";
62
63    /**
64     * Mapper that runs the count.
65     */
66    static class RowCounterMapper
67    extends TableMapper<ImmutableBytesWritable, Result> {
68
69      /** Counter enumeration to count the actual rows. */
70      public static enum Counters {ROWS}
71
72      /**
73       * Maps the data.
74       *
75       * @param row  The current table row key.
76       * @param values  The columns.
77       * @param context  The current context.
78       * @throws IOException When something is broken with the data.
79       * @see org.apache.hadoop.mapreduce.Mapper#map(KEYIN, VALUEIN,
80       *   org.apache.hadoop.mapreduce.Mapper.Context)
81       */
82      @Override
83      public void map(ImmutableBytesWritable row, Result values,
84        Context context)
85      throws IOException {
86        // Count every row containing data, whether it's in qualifiers or values
87        context.getCounter(Counters.ROWS).increment(1);
88      }
89    }
90
91    /**
92     * Sets up the actual job.
93     *
94     * @param conf  The current configuration.
95     * @param args  The command line parameters.
96     * @return The newly created job.
97     * @throws IOException When setting up the job fails.
98     */
99    public static Job createSubmittableJob(Configuration conf, String[] args)
100   throws IOException {
101     String tableName = args[0];
102     List<MultiRowRangeFilter.RowRange> rowRangeList = null;
103     long startTime = 0;
104     long endTime = 0;
105
106     StringBuilder sb = new StringBuilder();
107
108     final String rangeSwitch = "--range=";
109     final String startTimeArgKey = "--starttime=";
110     final String endTimeArgKey = "--endtime=";
111     final String expectedCountArg = "--expected-count=";
112
113     // First argument is table name, starting from second
114     for (int i = 1; i < args.length; i++) {
115       if (args[i].startsWith(rangeSwitch)) {
116         try {
117           rowRangeList = parseRowRangeParameter(args[i], rangeSwitch);
118         } catch (IllegalArgumentException e) {
119           return null;
120         }
121         continue;
122       }
123       if (args[i].startsWith(startTimeArgKey)) {
124         startTime = Long.parseLong(args[i].substring(startTimeArgKey.length()));
125         continue;
126       }
127       if (args[i].startsWith(endTimeArgKey)) {
128         endTime = Long.parseLong(args[i].substring(endTimeArgKey.length()));
129         continue;
130       }
131       if (args[i].startsWith(expectedCountArg)) {
132         conf.setLong(EXPECTED_COUNT_KEY,
133             Long.parseLong(args[i].substring(expectedCountArg.length())));
134         continue;
135       }
136       // if no switch, assume column names
137       sb.append(args[i]);
138       sb.append(" ");
139     }
140     if (endTime < startTime) {
141       printUsage("--endtime=" + endTime + " needs to be greater than --starttime=" + startTime);
142       return null;
143     }
144 
145     Job job = Job.getInstance(conf, conf.get(JOB_NAME_CONF_KEY, NAME + "_" + tableName));
146     job.setJarByClass(RowCounter.class);
147     Scan scan = new Scan();
148     scan.setCacheBlocks(false);
149     setScanFilter(scan, rowRangeList);
150     if (sb.length() > 0) {
151       for (String columnName : sb.toString().trim().split(" ")) {
152         String family = StringUtils.substringBefore(columnName, ":");
153         String qualifier = StringUtils.substringAfter(columnName, ":");
154
155         if (StringUtils.isBlank(qualifier)) {
156           scan.addFamily(Bytes.toBytes(family));
157         }
158         else {
159           scan.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));
160         }
161       }
162     }
163     scan.setTimeRange(startTime, endTime == 0 ? HConstants.LATEST_TIMESTAMP : endTime);
164     job.setOutputFormatClass(NullOutputFormat.class);
165     TableMapReduceUtil.initTableMapperJob(tableName, scan,
166       RowCounterMapper.class, ImmutableBytesWritable.class, Result.class, job);
167     job.setNumReduceTasks(0);
168     return job;
169   }
170
171   private static List<MultiRowRangeFilter.RowRange> parseRowRangeParameter(
172     String arg, String rangeSwitch) {
173     final String[] ranges = arg.substring(rangeSwitch.length()).split(";");
174     final List<MultiRowRangeFilter.RowRange> rangeList = new ArrayList<>();
175     for (String range : ranges) {
176       String[] startEnd = range.split(",", 2);
177       if (startEnd.length != 2 || startEnd[1].contains(",")) {
178         printUsage("Please specify range in such format as \"--range=a,b\" " +
179             "or, with only one boundary, \"--range=,b\" or \"--range=a,\"");
180         throw new IllegalArgumentException("Wrong range specification: " + range);
181       }
182       String startKey = startEnd[0];
183       String endKey = startEnd[1];
184       rangeList.add(new MultiRowRangeFilter.RowRange(
185         Bytes.toBytesBinary(startKey), true,
186         Bytes.toBytesBinary(endKey), false));
187     }
188     return rangeList;
189   }
190
191   /**
192    * Sets filter {@link FilterBase} to the {@link Scan} instance.
193    * If provided rowRangeList contains more than one element,
194    * method sets filter which is instance of {@link MultiRowRangeFilter}.
195    * Otherwise, method sets filter which is instance of {@link FirstKeyOnlyFilter}.
196    * If rowRangeList contains exactly one element, startRow and stopRow are set to the scan.
197    * @param scan
198    * @param rowRangeList
199    */
200   private static void setScanFilter(Scan scan, List<MultiRowRangeFilter.RowRange> rowRangeList) {
201     final int size = rowRangeList == null ? 0 : rowRangeList.size();
202     if (size <= 1) {
203       scan.setFilter(new FirstKeyOnlyFilter());
204     }
205     if (size == 1) {
206       MultiRowRangeFilter.RowRange range = rowRangeList.get(0);
207       scan.setStartRow(range.getStartRow()); //inclusive
208       scan.setStopRow(range.getStopRow());   //exclusive
209     } else if (size > 1) {
210       try {
211         scan.setFilter(new MultiRowRangeFilter(rowRangeList));
212       } catch (IOException e) {
213         //the IOException should never be thrown. see HBASE-16145
214         throw new RuntimeException("Cannot instantiate MultiRowRangeFilter");
215       }
216     }
217   }
218
219   /*
220    * @param errorMessage Can attach a message when error occurs.
221    */
222   private static void printUsage(String errorMessage) {
223     System.err.println("ERROR: " + errorMessage);
224     printUsage();
225   }
226
227   /**
228    * Prints usage without error message.
229    * Note that we don't document --expected-count, because it's intended for test.
230    */
231   private static void printUsage() {
232     System.err.println("Usage: RowCounter [options] <tablename> " +
233         "[--starttime=[start] --endtime=[end] " +
234         "[--range=[startKey],[endKey][;[startKey],[endKey]...]] [<column1> <column2>...]");
235     System.err.println("For performance consider the following options:\n"
236         + "-Dhbase.client.scanner.caching=100\n"
237         + "-Dmapreduce.map.speculative=false");
238   }
239
240   @Override
241   public int run(String[] args) throws Exception {
242     if (args.length < 1) {
243       printUsage("Wrong number of parameters: " + args.length);
244       return -1;
245     }
246     Job job = createSubmittableJob(getConf(), args);
247     if (job == null) {
248       return -1;
249     }
250     boolean success = job.waitForCompletion(true);
251     final long expectedCount = getConf().getLong(EXPECTED_COUNT_KEY, -1);
252     if (success && expectedCount != -1) {
253       final Counter counter = job.getCounters().findCounter(RowCounterMapper.Counters.ROWS);
254       success = expectedCount == counter.getValue();
255       if (!success) {
256         LOG.error("Failing job because count of '" + counter.getValue() +
257             "' does not match expected count of '" + expectedCount + "'");
258       }
259     }
260     return (success ? 0 : 1);
261   }
262
263   /**
264    * Main entry point.
265    * @param args The command line parameters.
266    * @throws Exception When running the job fails.
267    */
268   public static void main(String[] args) throws Exception {
269     int errCode = ToolRunner.run(HBaseConfiguration.create(), new RowCounter(), args);
270     System.exit(errCode);
271   }
272
273 }