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