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  
23  import org.apache.commons.logging.Log;
24  import org.apache.commons.logging.LogFactory;
25  import org.apache.hadoop.hbase.HConstants;
26  import org.apache.hadoop.hbase.classification.InterfaceAudience;
27  import org.apache.hadoop.hbase.classification.InterfaceStability;
28  import org.apache.hadoop.conf.Configuration;
29  import org.apache.hadoop.conf.Configured;
30  import org.apache.hadoop.fs.Path;
31  import org.apache.hadoop.hbase.Cell;
32  import org.apache.hadoop.hbase.CellUtil;
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.CompareFilter;
37  import org.apache.hadoop.hbase.filter.Filter;
38  import org.apache.hadoop.hbase.filter.PrefixFilter;
39  import org.apache.hadoop.hbase.filter.RegexStringComparator;
40  import org.apache.hadoop.hbase.filter.RowFilter;
41  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
42  import org.apache.hadoop.hbase.util.Bytes;
43  import org.apache.hadoop.io.IntWritable;
44  import org.apache.hadoop.io.Text;
45  import org.apache.hadoop.mapreduce.Job;
46  import org.apache.hadoop.mapreduce.Reducer;
47  import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
48  import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
49  import org.apache.hadoop.util.Tool;
50  import org.apache.hadoop.util.ToolRunner;
51  
52  import com.google.common.base.Preconditions;
53  
54  
55  /**
56   * A job with a a map and reduce phase to count cells in a table.
57   * The counter lists the following stats for a given table:
58   * <pre>
59   * 1. Total number of rows in the table
60   * 2. Total number of CFs across all rows
61   * 3. Total qualifiers across all rows
62   * 4. Total occurrence of each CF
63   * 5. Total occurrence  of each qualifier
64   * 6. Total number of versions of each qualifier.
65   * </pre>
66   *
67   * The cellcounter can take optional parameters to use a user
68   * supplied row/family/qualifier string to use in the report and
69   * second a regex based or prefix based row filter to restrict the
70   * count operation to a limited subset of rows from the table or a
71   * start time and/or end time to limit the count to a time range.
72   */
73  @InterfaceAudience.Public
74  @InterfaceStability.Stable
75  public class CellCounter extends Configured implements Tool {
76    private static final Log LOG =
77      LogFactory.getLog(CellCounter.class.getName());
78  
79
80    /**
81     * Name of this 'program'.
82     */
83    static final String NAME = "CellCounter";
84
85    private final static String JOB_NAME_CONF_KEY = "mapreduce.job.name";
86
87    /**
88     * Mapper that runs the count.
89     */
90    static class CellCounterMapper
91    extends TableMapper<Text, IntWritable> {
92      /**
93       * Counter enumeration to count the actual rows.
94       */
95      public static enum Counters {
96        ROWS,
97        CELLS
98      }
99
100     private Configuration conf;
101     private String separator;
102
103     // state of current row, family, column needs to persist across map() invocations
104     // in order to properly handle scanner batching, where a single qualifier may have too
105     // many versions for a single map() call
106     private byte[] lastRow;
107     private String currentRowKey;
108     byte[] currentFamily = null;
109     String currentFamilyName = null;
110     byte[] currentQualifier = null;
111     // family + qualifier
112     String currentQualifierName = null;
113     // rowkey + family + qualifier
114     String currentRowQualifierName = null;
115
116     @Override
117     protected void setup(Context context) throws IOException, InterruptedException {
118       conf = context.getConfiguration();
119       separator = conf.get("ReportSeparator",":");
120     }
121
122     /**
123      * Maps the data.
124      *
125      * @param row     The current table row key.
126      * @param values  The columns.
127      * @param context The current context.
128      * @throws IOException When something is broken with the data.
129      * @see org.apache.hadoop.mapreduce.Mapper#map(KEYIN, VALUEIN,
130      *      org.apache.hadoop.mapreduce.Mapper.Context)
131      */
132
133     @Override
134     public void map(ImmutableBytesWritable row, Result values,
135                     Context context)
136         throws IOException {
137       Preconditions.checkState(values != null,
138           "values passed to the map is null");
139
140       try {
141         byte[] currentRow = values.getRow();
142         if (lastRow == null || !Bytes.equals(lastRow, currentRow)) {
143           lastRow = currentRow;
144           currentRowKey = Bytes.toStringBinary(currentRow);
145           currentFamily = null;
146           currentQualifier = null;
147           context.getCounter(Counters.ROWS).increment(1);
148           context.write(new Text("Total ROWS"), new IntWritable(1));
149         }
150         if (!values.isEmpty()) {
151           int cellCount = 0;
152           for (Cell value : values.listCells()) {
153             cellCount++;
154             if (currentFamily == null || !CellUtil.matchingFamily(value, currentFamily)) {
155               currentFamily = CellUtil.cloneFamily(value);
156               currentFamilyName = Bytes.toStringBinary(currentFamily);
157               currentQualifier = null;
158               context.getCounter("CF", currentFamilyName).increment(1);
159               if (1 == context.getCounter("CF", currentFamilyName).getValue()) {
160                 context.write(new Text("Total Families Across all Rows"), new IntWritable(1));
161                 context.write(new Text(currentFamily), new IntWritable(1));
162               }
163             }
164             if (currentQualifier == null || !CellUtil.matchingQualifier(value, currentQualifier)) {
165               currentQualifier = CellUtil.cloneQualifier(value);
166               currentQualifierName = currentFamilyName + separator +
167                   Bytes.toStringBinary(currentQualifier);
168               currentRowQualifierName = currentRowKey + separator + currentQualifierName;
169
170               context.write(new Text("Total Qualifiers across all Rows"),
171                   new IntWritable(1));
172               context.write(new Text(currentQualifierName), new IntWritable(1));
173             }
174             // Increment versions
175             context.write(new Text(currentRowQualifierName + "_Versions"), new IntWritable(1));
176           }
177           context.getCounter(Counters.CELLS).increment(cellCount);
178         }
179       } catch (InterruptedException e) {
180         e.printStackTrace();
181       }
182     }
183   }
184
185   static class IntSumReducer<Key> extends Reducer<Key, IntWritable,
186       Key, IntWritable> {
187
188     private IntWritable result = new IntWritable();
189     public void reduce(Key key, Iterable<IntWritable> values,
190       Context context)
191     throws IOException, InterruptedException {
192       int sum = 0;
193       for (IntWritable val : values) {
194         sum += val.get();
195       }
196       result.set(sum);
197       context.write(key, result);
198     }
199   }
200
201   /**
202    * Sets up the actual job.
203    *
204    * @param conf The current configuration.
205    * @param args The command line parameters.
206    * @return The newly created job.
207    * @throws IOException When setting up the job fails.
208    */
209   public static Job createSubmittableJob(Configuration conf, String[] args)
210       throws IOException {
211     String tableName = args[0];
212     Path outputDir = new Path(args[1]);
213     String reportSeparatorString = (args.length > 2) ? args[2]: ":";
214     conf.set("ReportSeparator", reportSeparatorString);
215     Job job = Job.getInstance(conf, conf.get(JOB_NAME_CONF_KEY, NAME + "_" + tableName));
216     job.setJarByClass(CellCounter.class);
217     Scan scan = getConfiguredScanForJob(conf, args);
218     TableMapReduceUtil.initTableMapperJob(tableName, scan,
219         CellCounterMapper.class, ImmutableBytesWritable.class, Result.class, job);
220     job.setNumReduceTasks(1);
221     job.setMapOutputKeyClass(Text.class);
222     job.setMapOutputValueClass(IntWritable.class);
223     job.setOutputFormatClass(TextOutputFormat.class);
224     job.setOutputKeyClass(Text.class);
225     job.setOutputValueClass(IntWritable.class);
226     FileOutputFormat.setOutputPath(job, outputDir);
227     job.setReducerClass(IntSumReducer.class);
228     return job;
229   }
230
231   private static Scan getConfiguredScanForJob(Configuration conf, String[] args)
232       throws IOException {
233     // create scan with any properties set from TableInputFormat
234     Scan s = TableInputFormat.createScanFromConfiguration(conf);
235     // Set Scan Versions
236     if (conf.get(TableInputFormat.SCAN_MAXVERSIONS) == null) {
237       // default to all versions unless explicitly set
238       s.setMaxVersions(Integer.MAX_VALUE);
239     }
240     s.setCacheBlocks(false);
241     // Set RowFilter or Prefix Filter if applicable.
242     Filter rowFilter = getRowFilter(args);
243     if (rowFilter!= null) {
244       LOG.info("Setting Row Filter for counter.");
245       s.setFilter(rowFilter);
246     }
247     // Set TimeRange if defined
248     long timeRange[] = getTimeRange(args);
249     if (timeRange != null) {
250       LOG.info("Setting TimeRange for counter.");
251       s.setTimeRange(timeRange[0], timeRange[1]);
252     }
253     return s;
254   }
255
256
257   private static Filter getRowFilter(String[] args) {
258     Filter rowFilter = null;
259     String filterCriteria = (args.length > 3) ? args[3]: null;
260     if (filterCriteria == null) return null;
261     if (filterCriteria.startsWith("^")) {
262       String regexPattern = filterCriteria.substring(1, filterCriteria.length());
263       rowFilter = new RowFilter(CompareFilter.CompareOp.EQUAL, new RegexStringComparator(regexPattern));
264     } else {
265       rowFilter = new PrefixFilter(Bytes.toBytesBinary(filterCriteria));
266     }
267     return rowFilter;
268   }
269
270   private static long[] getTimeRange(String[] args) throws IOException {
271     final String startTimeArgKey = "--starttime=";
272     final String endTimeArgKey = "--endtime=";
273     long startTime = 0L;
274     long endTime = 0L;
275
276     for (int i = 1; i < args.length; i++) {
277       System.out.println("i:" + i + "arg[i]" + args[i]);
278       if (args[i].startsWith(startTimeArgKey)) {
279         startTime = Long.parseLong(args[i].substring(startTimeArgKey.length()));
280       }
281       if (args[i].startsWith(endTimeArgKey)) {
282         endTime = Long.parseLong(args[i].substring(endTimeArgKey.length()));
283       }
284     }
285
286     if (startTime == 0 && endTime == 0)
287       return null;
288
289     endTime = endTime == 0 ? HConstants.LATEST_TIMESTAMP : endTime;
290     return new long [] {startTime, endTime};
291   }
292
293   @Override
294   public int run(String[] args) throws Exception {
295     if (args.length < 2) {
296       System.err.println("ERROR: Wrong number of parameters: " + args.length);
297       System.err.println("Usage: CellCounter ");
298       System.err.println("       <tablename> <outputDir> <reportSeparator> [^[regex pattern] or " +
299         "[Prefix] for row filter]] --starttime=[starttime] --endtime=[endtime]");
300       System.err.println("  Note: -D properties will be applied to the conf used. ");
301       System.err.println("  Additionally, all of the SCAN properties from TableInputFormat");
302       System.err.println("  can be specified to get fine grained control on what is counted..");
303       System.err.println("   -D " + TableInputFormat.SCAN_ROW_START + "=<rowkey>");
304       System.err.println("   -D " + TableInputFormat.SCAN_ROW_STOP + "=<rowkey>");
305       System.err.println("   -D " + TableInputFormat.SCAN_COLUMNS + "=\"<col1> <col2>...\"");
306       System.err.println("   -D " + TableInputFormat.SCAN_COLUMN_FAMILY + "=<familyName>");
307       System.err.println("   -D " + TableInputFormat.SCAN_TIMESTAMP + "=<timestamp>");
308       System.err.println("   -D " + TableInputFormat.SCAN_TIMERANGE_START + "=<timestamp>");
309       System.err.println("   -D " + TableInputFormat.SCAN_TIMERANGE_END + "=<timestamp>");
310       System.err.println("   -D " + TableInputFormat.SCAN_MAXVERSIONS + "=<count>");
311       System.err.println("   -D " + TableInputFormat.SCAN_CACHEDROWS + "=<count>");
312       System.err.println("   -D " + TableInputFormat.SCAN_BATCHSIZE + "=<count>");
313       System.err.println(" <reportSeparator> parameter can be used to override the default report separator " +
314           "string : used to separate the rowId/column family name and qualifier name.");
315       System.err.println(" [^[regex pattern] or [Prefix] parameter can be used to limit the cell counter count " +
316           "operation to a limited subset of rows from the table based on regex or prefix pattern.");
317       return -1;
318     }
319     Job job = createSubmittableJob(getConf(), args);
320     return (job.waitForCompletion(true) ? 0 : 1);
321   }
322
323   /**
324    * Main entry point.
325    * @param args The command line parameters.
326    * @throws Exception When running the job fails.
327    */
328   public static void main(String[] args) throws Exception {
329     int errCode = ToolRunner.run(HBaseConfiguration.create(), new CellCounter(), args);
330     System.exit(errCode);
331   }
332
333 }