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