View Javadoc

1   /**
2    * Copyright 2008 The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS,
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17   * See the License for the specific language governing permissions and
18   * limitations under the License.
19   */
20  package org.apache.hadoop.hbase.mapreduce;
21  
22  import java.io.IOException;
23  
24  import org.apache.hadoop.conf.Configuration;
25  import org.apache.hadoop.hbase.HBaseConfiguration;
26  import org.apache.hadoop.hbase.KeyValue;
27  import org.apache.hadoop.hbase.client.Result;
28  import org.apache.hadoop.hbase.client.Scan;
29  import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
30  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
31  import org.apache.hadoop.hbase.util.Bytes;
32  import org.apache.hadoop.mapreduce.Job;
33  import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
34  import org.apache.hadoop.util.GenericOptionsParser;
35  
36  /**
37   * A job with a just a map phase to count rows. Map outputs table rows IF the
38   * input row has columns that have content.
39   */
40  public class RowCounter {
41  
42    /** Name of this 'program'. */
43    static final String NAME = "rowcounter";
44  
45    /**
46     * Mapper that runs the count.
47     */
48    static class RowCounterMapper
49    extends TableMapper<ImmutableBytesWritable, Result> {
50  
51      /** Counter enumeration to count the actual rows. */
52      public static enum Counters {ROWS}
53  
54      /**
55       * Maps the data.
56       *
57       * @param row  The current table row key.
58       * @param values  The columns.
59       * @param context  The current context.
60       * @throws IOException When something is broken with the data.
61       * @see org.apache.hadoop.mapreduce.Mapper#map(KEYIN, VALUEIN,
62       *   org.apache.hadoop.mapreduce.Mapper.Context)
63       */
64      @Override
65      public void map(ImmutableBytesWritable row, Result values,
66        Context context)
67      throws IOException {
68        // Count every row containing data, whether it's in qualifiers or values
69        context.getCounter(Counters.ROWS).increment(1);
70      }
71    }
72  
73    /**
74     * Sets up the actual job.
75     *
76     * @param conf  The current configuration.
77     * @param args  The command line parameters.
78     * @return The newly created job.
79     * @throws IOException When setting up the job fails.
80     */
81    public static Job createSubmittableJob(Configuration conf, String[] args)
82    throws IOException {
83      String tableName = args[0];
84      String startKey = null;
85      String endKey = null;
86      StringBuilder sb = new StringBuilder();
87  
88      final String rangeSwitch = "--range=";
89  
90      // First argument is table name, starting from second
91      for (int i = 1; i < args.length; i++) {
92        if (args[i].startsWith(rangeSwitch)) {
93          String[] startEnd = args[i].substring(rangeSwitch.length()).split(",", 2);
94          if (startEnd.length != 2 || startEnd[1].contains(",")) {
95            printUsage("Please specify range in such format as \"--range=a,b\" " +
96                "or, with only one boundary, \"--range=,b\" or \"--range=a,\"");
97            return null;
98          }
99          startKey = startEnd[0];
100         endKey = startEnd[1];
101       }
102       else {
103         // if no switch, assume column names
104         sb.append(args[i]);
105         sb.append(" ");
106       }
107     }
108 
109     Job job = new Job(conf, NAME + "_" + tableName);
110     job.setJarByClass(RowCounter.class);
111     Scan scan = new Scan();
112     scan.setCacheBlocks(false);
113     if (startKey != null && !startKey.equals("")) {
114       scan.setStartRow(Bytes.toBytes(startKey));
115     }
116     if (endKey != null && !endKey.equals("")) {
117       scan.setStopRow(Bytes.toBytes(endKey));
118     }
119     scan.setFilter(new FirstKeyOnlyFilter());
120     if (sb.length() > 0) {
121       for (String columnName : sb.toString().trim().split(" ")) {
122         String [] fields = columnName.split(":");
123         if(fields.length == 1) {
124           scan.addFamily(Bytes.toBytes(fields[0]));
125         } else {
126           scan.addColumn(Bytes.toBytes(fields[0]), Bytes.toBytes(fields[1]));
127         }
128       }
129     }
130     job.setOutputFormatClass(NullOutputFormat.class);
131     TableMapReduceUtil.initTableMapperJob(tableName, scan,
132       RowCounterMapper.class, ImmutableBytesWritable.class, Result.class, job);
133     job.setNumReduceTasks(0);
134     return job;
135   }
136 
137   /*
138    * @param errorMessage Can attach a message when error occurs.
139    */
140   private static void printUsage(String errorMessage) {
141     System.err.println("ERROR: " + errorMessage);
142     printUsage();
143   }
144 
145   /*
146    * Prints usage without error message
147    */
148   private static void printUsage() {
149     System.err.println("Usage: RowCounter [options] <tablename> " +
150         "[--range=[startKey],[endKey]] [<column1> <column2>...]");
151     System.err.println("For performance consider the following options:\n"
152         + "-Dhbase.client.scanner.caching=100\n"
153         + "-Dmapred.map.tasks.speculative.execution=false");
154   }
155 
156   /**
157    * Main entry point.
158    *
159    * @param args  The command line parameters.
160    * @throws Exception When running the job fails.
161    */
162   public static void main(String[] args) throws Exception {
163     Configuration conf = HBaseConfiguration.create();
164     String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
165     if (otherArgs.length < 1) {
166       printUsage("Wrong number of parameters: " + args.length);
167       System.exit(-1);
168     }
169     Job job = createSubmittableJob(conf, otherArgs);
170     if (job == null) {
171       System.exit(-1);
172     }
173     System.exit(job.waitForCompletion(true) ? 0 : 1);
174   }
175 }