001/**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019package org.apache.hadoop.hbase.mapreduce;
020
021import java.io.IOException;
022
023import org.apache.hadoop.hbase.CompareOperator;
024import org.apache.hadoop.hbase.HConstants;
025import org.apache.yetus.audience.InterfaceAudience;
026import org.slf4j.Logger;
027import org.slf4j.LoggerFactory;
028import org.apache.hadoop.conf.Configuration;
029import org.apache.hadoop.conf.Configured;
030import org.apache.hadoop.fs.Path;
031import org.apache.hadoop.hbase.Cell;
032import org.apache.hadoop.hbase.CellUtil;
033import org.apache.hadoop.hbase.HBaseConfiguration;
034import org.apache.hadoop.hbase.client.Result;
035import org.apache.hadoop.hbase.client.Scan;
036import org.apache.hadoop.hbase.filter.Filter;
037import org.apache.hadoop.hbase.filter.PrefixFilter;
038import org.apache.hadoop.hbase.filter.RegexStringComparator;
039import org.apache.hadoop.hbase.filter.RowFilter;
040import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
041import org.apache.hadoop.hbase.util.Bytes;
042import org.apache.hadoop.io.IntWritable;
043import org.apache.hadoop.io.Text;
044import org.apache.hadoop.mapreduce.Job;
045import org.apache.hadoop.mapreduce.Reducer;
046import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
047import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
048import org.apache.hadoop.util.Tool;
049import org.apache.hadoop.util.ToolRunner;
050
051import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
052
053
054/**
055 * A job with a a map and reduce phase to count cells in a table.
056 * The counter lists the following stats for a given table:
057 * <pre>
058 * 1. Total number of rows in the table
059 * 2. Total number of CFs across all rows
060 * 3. Total qualifiers across all rows
061 * 4. Total occurrence of each CF
062 * 5. Total occurrence  of each qualifier
063 * 6. Total number of versions of each qualifier.
064 * </pre>
065 *
066 * The cellcounter can take optional parameters to use a user
067 * supplied row/family/qualifier string to use in the report and
068 * second a regex based or prefix based row filter to restrict the
069 * count operation to a limited subset of rows from the table or a
070 * start time and/or end time to limit the count to a time range.
071 */
072@InterfaceAudience.Public
073public class CellCounter extends Configured implements Tool {
074  private static final Logger LOG =
075    LoggerFactory.getLogger(CellCounter.class.getName());
076
077
078  /**
079   * Name of this 'program'.
080   */
081  static final String NAME = "CellCounter";
082
083  private final static String JOB_NAME_CONF_KEY = "mapreduce.job.name";
084
085  /**
086   * Mapper that runs the count.
087   */
088  static class CellCounterMapper
089  extends TableMapper<Text, IntWritable> {
090    /**
091     * Counter enumeration to count the actual rows.
092     */
093    public static enum Counters {
094      ROWS,
095      CELLS
096    }
097
098    private Configuration conf;
099    private String separator;
100
101    // state of current row, family, column needs to persist across map() invocations
102    // in order to properly handle scanner batching, where a single qualifier may have too
103    // many versions for a single map() call
104    private byte[] lastRow;
105    private String currentRowKey;
106    byte[] currentFamily = null;
107    String currentFamilyName = null;
108    byte[] currentQualifier = null;
109    // family + qualifier
110    String currentQualifierName = null;
111    // rowkey + family + qualifier
112    String currentRowQualifierName = null;
113
114    @Override
115    protected void setup(Context context) throws IOException, InterruptedException {
116      conf = context.getConfiguration();
117      separator = conf.get("ReportSeparator",":");
118    }
119
120    /**
121     * Maps the data.
122     *
123     * @param row     The current table row key.
124     * @param values  The columns.
125     * @param context The current context.
126     * @throws IOException When something is broken with the data.
127     */
128
129    @Override
130    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NP_NULL_ON_SOME_PATH",
131      justification="Findbugs is blind to the Precondition null check")
132    public void map(ImmutableBytesWritable row, Result values,
133                    Context context)
134        throws IOException {
135      Preconditions.checkState(values != null,
136          "values passed to the map is null");
137
138      try {
139        byte[] currentRow = values.getRow();
140        if (lastRow == null || !Bytes.equals(lastRow, currentRow)) {
141          lastRow = currentRow;
142          currentRowKey = Bytes.toStringBinary(currentRow);
143          currentFamily = null;
144          currentQualifier = null;
145          context.getCounter(Counters.ROWS).increment(1);
146          context.write(new Text("Total ROWS"), new IntWritable(1));
147        }
148        if (!values.isEmpty()) {
149          int cellCount = 0;
150          for (Cell value : values.listCells()) {
151            cellCount++;
152            if (currentFamily == null || !CellUtil.matchingFamily(value, currentFamily)) {
153              currentFamily = CellUtil.cloneFamily(value);
154              currentFamilyName = Bytes.toStringBinary(currentFamily);
155              currentQualifier = null;
156              context.getCounter("CF", currentFamilyName).increment(1);
157              if (1 == context.getCounter("CF", currentFamilyName).getValue()) {
158                context.write(new Text("Total Families Across all Rows"), new IntWritable(1));
159                context.write(new Text(currentFamily), new IntWritable(1));
160              }
161            }
162            if (currentQualifier == null || !CellUtil.matchingQualifier(value, currentQualifier)) {
163              currentQualifier = CellUtil.cloneQualifier(value);
164              currentQualifierName = currentFamilyName + separator +
165                  Bytes.toStringBinary(currentQualifier);
166              currentRowQualifierName = currentRowKey + separator + currentQualifierName;
167
168              context.write(new Text("Total Qualifiers across all Rows"),
169                  new IntWritable(1));
170              context.write(new Text(currentQualifierName), new IntWritable(1));
171            }
172            // Increment versions
173            context.write(new Text(currentRowQualifierName + "_Versions"), new IntWritable(1));
174          }
175          context.getCounter(Counters.CELLS).increment(cellCount);
176        }
177      } catch (InterruptedException e) {
178        e.printStackTrace();
179      }
180    }
181  }
182
183  static class IntSumReducer<Key> extends Reducer<Key, IntWritable,
184      Key, IntWritable> {
185
186    private IntWritable result = new IntWritable();
187    public void reduce(Key key, Iterable<IntWritable> values,
188      Context context)
189    throws IOException, InterruptedException {
190      int sum = 0;
191      for (IntWritable val : values) {
192        sum += val.get();
193      }
194      result.set(sum);
195      context.write(key, result);
196    }
197  }
198
199  /**
200   * Sets up the actual job.
201   *
202   * @param conf The current configuration.
203   * @param args The command line parameters.
204   * @return The newly created job.
205   * @throws IOException When setting up the job fails.
206   */
207  public static Job createSubmittableJob(Configuration conf, String[] args)
208      throws IOException {
209    String tableName = args[0];
210    Path outputDir = new Path(args[1]);
211    String reportSeparatorString = (args.length > 2) ? args[2]: ":";
212    conf.set("ReportSeparator", reportSeparatorString);
213    Job job = Job.getInstance(conf, conf.get(JOB_NAME_CONF_KEY, NAME + "_" + tableName));
214    job.setJarByClass(CellCounter.class);
215    Scan scan = getConfiguredScanForJob(conf, args);
216    TableMapReduceUtil.initTableMapperJob(tableName, scan,
217        CellCounterMapper.class, ImmutableBytesWritable.class, Result.class, job);
218    job.setNumReduceTasks(1);
219    job.setMapOutputKeyClass(Text.class);
220    job.setMapOutputValueClass(IntWritable.class);
221    job.setOutputFormatClass(TextOutputFormat.class);
222    job.setOutputKeyClass(Text.class);
223    job.setOutputValueClass(IntWritable.class);
224    FileOutputFormat.setOutputPath(job, outputDir);
225    job.setReducerClass(IntSumReducer.class);
226    return job;
227  }
228
229  private static Scan getConfiguredScanForJob(Configuration conf, String[] args)
230      throws IOException {
231    // create scan with any properties set from TableInputFormat
232    Scan s = TableInputFormat.createScanFromConfiguration(conf);
233    // Set Scan Versions
234    if (conf.get(TableInputFormat.SCAN_MAXVERSIONS) == null) {
235      // default to all versions unless explicitly set
236      s.setMaxVersions(Integer.MAX_VALUE);
237    }
238    s.setCacheBlocks(false);
239    // Set RowFilter or Prefix Filter if applicable.
240    Filter rowFilter = getRowFilter(args);
241    if (rowFilter!= null) {
242      LOG.info("Setting Row Filter for counter.");
243      s.setFilter(rowFilter);
244    }
245    // Set TimeRange if defined
246    long timeRange[] = getTimeRange(args);
247    if (timeRange != null) {
248      LOG.info("Setting TimeRange for counter.");
249      s.setTimeRange(timeRange[0], timeRange[1]);
250    }
251    return s;
252  }
253
254
255  private static Filter getRowFilter(String[] args) {
256    Filter rowFilter = null;
257    String filterCriteria = (args.length > 3) ? args[3]: null;
258    if (filterCriteria == null) return null;
259    if (filterCriteria.startsWith("^")) {
260      String regexPattern = filterCriteria.substring(1, filterCriteria.length());
261      rowFilter = new RowFilter(CompareOperator.EQUAL, new RegexStringComparator(regexPattern));
262    } else {
263      rowFilter = new PrefixFilter(Bytes.toBytesBinary(filterCriteria));
264    }
265    return rowFilter;
266  }
267
268  private static long[] getTimeRange(String[] args) throws IOException {
269    final String startTimeArgKey = "--starttime=";
270    final String endTimeArgKey = "--endtime=";
271    long startTime = 0L;
272    long endTime = 0L;
273
274    for (int i = 1; i < args.length; i++) {
275      System.out.println("i:" + i + "arg[i]" + args[i]);
276      if (args[i].startsWith(startTimeArgKey)) {
277        startTime = Long.parseLong(args[i].substring(startTimeArgKey.length()));
278      }
279      if (args[i].startsWith(endTimeArgKey)) {
280        endTime = Long.parseLong(args[i].substring(endTimeArgKey.length()));
281      }
282    }
283
284    if (startTime == 0 && endTime == 0)
285      return null;
286
287    endTime = endTime == 0 ? HConstants.LATEST_TIMESTAMP : endTime;
288    return new long [] {startTime, endTime};
289  }
290
291  @Override
292  public int run(String[] args) throws Exception {
293    if (args.length < 2) {
294      printUsage(args.length);
295      return -1;
296    }
297    Job job = createSubmittableJob(getConf(), args);
298    return (job.waitForCompletion(true) ? 0 : 1);
299  }
300
301  private void printUsage(int parameterCount) {
302    System.err.println("ERROR: Wrong number of parameters: " + parameterCount);
303    System.err.println("Usage: hbase cellcounter <tablename> <outputDir> [reportSeparator] "
304        + "[^[regex pattern] or [Prefix]] [--starttime=<starttime> --endtime=<endtime>]");
305    System.err.println("  Note: -D properties will be applied to the conf used.");
306    System.err.println("  Additionally, all of the SCAN properties from TableInputFormat can be "
307        + "specified to get fine grained control on what is counted.");
308    System.err.println("   -D" + TableInputFormat.SCAN_ROW_START + "=<rowkey>");
309    System.err.println("   -D" + TableInputFormat.SCAN_ROW_STOP + "=<rowkey>");
310    System.err.println("   -D" + TableInputFormat.SCAN_COLUMNS + "=\"<col1> <col2>...\"");
311    System.err.println("   -D" + TableInputFormat.SCAN_COLUMN_FAMILY
312        + "=<family1>,<family2>, ...");
313    System.err.println("   -D" + TableInputFormat.SCAN_TIMESTAMP + "=<timestamp>");
314    System.err.println("   -D" + TableInputFormat.SCAN_TIMERANGE_START + "=<timestamp>");
315    System.err.println("   -D" + TableInputFormat.SCAN_TIMERANGE_END + "=<timestamp>");
316    System.err.println("   -D" + TableInputFormat.SCAN_MAXVERSIONS + "=<count>");
317    System.err.println("   -D" + TableInputFormat.SCAN_CACHEDROWS + "=<count>");
318    System.err.println("   -D" + TableInputFormat.SCAN_BATCHSIZE + "=<count>");
319    System.err.println(" <reportSeparator> parameter can be used to override the default report "
320        + "separator string : used to separate the rowId/column family name and qualifier name.");
321    System.err.println(" [^[regex pattern] or [Prefix] parameter can be used to limit the cell "
322        + "counter count operation to a limited subset of rows from the table based on regex or "
323        + "prefix pattern.");
324  }
325
326  /**
327   * Main entry point.
328   * @param args The command line parameters.
329   * @throws Exception When running the job fails.
330   */
331  public static void main(String[] args) throws Exception {
332    int errCode = ToolRunner.run(HBaseConfiguration.create(), new CellCounter(), args);
333    System.exit(errCode);
334  }
335
336}