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