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