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  import java.util.Set;
23  import java.util.TreeSet;
24  
25  import org.apache.commons.lang.StringUtils;
26  import org.apache.hadoop.classification.InterfaceAudience;
27  import org.apache.hadoop.classification.InterfaceStability;
28  import org.apache.hadoop.conf.Configuration;
29  import org.apache.hadoop.conf.Configured;
30  import org.apache.hadoop.hbase.HBaseConfiguration;
31  import org.apache.hadoop.hbase.client.Result;
32  import org.apache.hadoop.hbase.client.Scan;
33  import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
34  import org.apache.hadoop.hbase.filter.FirstKeyValueMatchingQualifiersFilter;
35  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
36  import org.apache.hadoop.hbase.util.Bytes;
37  import org.apache.hadoop.mapreduce.Job;
38  import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
39  import org.apache.hadoop.util.GenericOptionsParser;
40  import org.apache.hadoop.util.Tool;
41  import org.apache.hadoop.util.ToolRunner;
42  
43  /**
44   * A job with a just a map phase to count rows. Map outputs table rows IF the
45   * input row has columns that have content.
46   */
47  @InterfaceAudience.Public
48  @InterfaceStability.Stable
49  public class RowCounter extends Configured implements Tool {
50  
51    /** Name of this 'program'. */
52    static final String NAME = "rowcounter";
53  
54    /**
55     * Mapper that runs the count.
56     */
57    static class RowCounterMapper
58    extends TableMapper<ImmutableBytesWritable, Result> {
59  
60      /** Counter enumeration to count the actual rows. */
61      public static enum Counters {ROWS}
62  
63      /**
64       * Maps the data.
65       *
66       * @param row  The current table row key.
67       * @param values  The columns.
68       * @param context  The current context.
69       * @throws IOException When something is broken with the data.
70       * @see org.apache.hadoop.mapreduce.Mapper#map(KEYIN, VALUEIN,
71       *   org.apache.hadoop.mapreduce.Mapper.Context)
72       */
73      @Override
74      public void map(ImmutableBytesWritable row, Result values,
75        Context context)
76      throws IOException {
77        // Count every row containing data, whether it's in qualifiers or values
78        context.getCounter(Counters.ROWS).increment(1);
79      }
80    }
81  
82    /**
83     * Sets up the actual job.
84     *
85     * @param conf  The current configuration.
86     * @param args  The command line parameters.
87     * @return The newly created job.
88     * @throws IOException When setting up the job fails.
89     */
90    public static Job createSubmittableJob(Configuration conf, String[] args)
91    throws IOException {
92      String tableName = args[0];
93      String startKey = null;
94      String endKey = null;
95      StringBuilder sb = new StringBuilder();
96  
97      final String rangeSwitch = "--range=";
98  
99      // First argument is table name, starting from second
100     for (int i = 1; i < args.length; i++) {
101       if (args[i].startsWith(rangeSwitch)) {
102         String[] startEnd = args[i].substring(rangeSwitch.length()).split(",", 2);
103         if (startEnd.length != 2 || startEnd[1].contains(",")) {
104           printUsage("Please specify range in such format as \"--range=a,b\" " +
105               "or, with only one boundary, \"--range=,b\" or \"--range=a,\"");
106           return null;
107         }
108         startKey = startEnd[0];
109         endKey = startEnd[1];
110       }
111       else {
112         // if no switch, assume column names
113         sb.append(args[i]);
114         sb.append(" ");
115       }
116     }
117 
118     Job job = Job.getInstance(conf, NAME + "_" + tableName);
119     job.setJarByClass(RowCounter.class);
120     Scan scan = new Scan();
121     scan.setCacheBlocks(false);
122     Set<byte []> qualifiers = new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR);
123     if (startKey != null && !startKey.equals("")) {
124       scan.setStartRow(Bytes.toBytes(startKey));
125     }
126     if (endKey != null && !endKey.equals("")) {
127       scan.setStopRow(Bytes.toBytes(endKey));
128     }
129     if (sb.length() > 0) {
130       for (String columnName : sb.toString().trim().split(" ")) {
131         String family = StringUtils.substringBefore(columnName, ":");
132         String qualifier = StringUtils.substringAfter(columnName, ":");
133 
134         if (StringUtils.isBlank(qualifier)) {
135           scan.addFamily(Bytes.toBytes(family));
136         }
137         else {
138           scan.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));
139         }
140       }
141     }
142     // specified column may or may not be part of first key value for the row.
143     // Hence do not use FirstKeyOnlyFilter if scan has columns, instead use
144     // FirstKeyValueMatchingQualifiersFilter.
145     if (qualifiers.size() == 0) {
146       scan.setFilter(new FirstKeyOnlyFilter());
147     } else {
148       scan.setFilter(new FirstKeyValueMatchingQualifiersFilter(qualifiers));
149     }
150     job.setOutputFormatClass(NullOutputFormat.class);
151     TableMapReduceUtil.initTableMapperJob(tableName, scan,
152       RowCounterMapper.class, ImmutableBytesWritable.class, Result.class, job);
153     job.setNumReduceTasks(0);
154     return job;
155   }
156 
157   /*
158    * @param errorMessage Can attach a message when error occurs.
159    */
160   private static void printUsage(String errorMessage) {
161     System.err.println("ERROR: " + errorMessage);
162     printUsage();
163   }
164 
165   /*
166    * Prints usage without error message
167    */
168   private static void printUsage() {
169     System.err.println("Usage: RowCounter [options] <tablename> " +
170         "[--range=[startKey],[endKey]] [<column1> <column2>...]");
171     System.err.println("For performance consider the following options:\n"
172         + "-Dhbase.client.scanner.caching=100\n"
173         + "-Dmapreduce.map.speculative=false");
174   }
175 
176   @Override
177   public int run(String[] args) throws Exception {
178     String[] otherArgs = new GenericOptionsParser(getConf(), args).getRemainingArgs();
179     if (otherArgs.length < 1) {
180       printUsage("Wrong number of parameters: " + args.length);
181       return -1;
182     }
183     Job job = createSubmittableJob(getConf(), otherArgs);
184     if (job == null) {
185       return -1;
186     }
187     return (job.waitForCompletion(true) ? 0 : 1);
188   }
189 
190   /**
191    * Main entry point.
192    * @param args The command line parameters.
193    * @throws Exception When running the job fails.
194    */
195   public static void main(String[] args) throws Exception {
196     int errCode = ToolRunner.run(HBaseConfiguration.create(), new RowCounter(), args);
197     System.exit(errCode);
198   }
199 
200 }