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