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.Collections;
23  import java.util.List;
24  
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  import org.apache.hadoop.conf.Configurable;
28  import org.apache.hadoop.conf.Configuration;
29  import org.apache.hadoop.hbase.KeyValue;
30  import org.apache.hadoop.hbase.TableName;
31  import org.apache.hadoop.hbase.classification.InterfaceAudience;
32  import org.apache.hadoop.hbase.classification.InterfaceStability;
33  import org.apache.hadoop.hbase.client.Connection;
34  import org.apache.hadoop.hbase.client.ConnectionFactory;
35  import org.apache.hadoop.hbase.client.RegionLocator;
36  import org.apache.hadoop.hbase.client.Scan;
37  import org.apache.hadoop.hbase.util.Bytes;
38  import org.apache.hadoop.mapreduce.InputSplit;
39  import org.apache.hadoop.mapreduce.JobContext;
40  import org.apache.hadoop.hbase.util.Pair;
41  import org.apache.hadoop.mapreduce.Job;
42  import org.apache.hadoop.util.StringUtils;
43  
44  /**
45   * Convert HBase tabular data into a format that is consumable by Map/Reduce.
46   */
47  @InterfaceAudience.Public
48  @InterfaceStability.Stable
49  public class TableInputFormat extends TableInputFormatBase
50  implements Configurable {
51  
52    @SuppressWarnings("hiding")
53    private static final Log LOG = LogFactory.getLog(TableInputFormat.class);
54  
55    /** Job parameter that specifies the input table. */
56    public static final String INPUT_TABLE = "hbase.mapreduce.inputtable";
57    /**
58     * If specified, use start keys of this table to split.
59     * This is useful when you are preparing data for bulkload.
60     */
61    private static final String SPLIT_TABLE = "hbase.mapreduce.splittable";
62    /** Base-64 encoded scanner. All other SCAN_ confs are ignored if this is specified.
63     * See {@link TableMapReduceUtil#convertScanToString(Scan)} for more details.
64     */
65    public static final String SCAN = "hbase.mapreduce.scan";
66    /** Scan start row */
67    public static final String SCAN_ROW_START = "hbase.mapreduce.scan.row.start";
68    /** Scan stop row */
69    public static final String SCAN_ROW_STOP = "hbase.mapreduce.scan.row.stop";
70    /** Column Family to Scan */
71    public static final String SCAN_COLUMN_FAMILY = "hbase.mapreduce.scan.column.family";
72    /** Space delimited list of columns and column families to scan. */
73    public static final String SCAN_COLUMNS = "hbase.mapreduce.scan.columns";
74    /** The timestamp used to filter columns with a specific timestamp. */
75    public static final String SCAN_TIMESTAMP = "hbase.mapreduce.scan.timestamp";
76    /** The starting timestamp used to filter columns with a specific range of versions. */
77    public static final String SCAN_TIMERANGE_START = "hbase.mapreduce.scan.timerange.start";
78    /** The ending timestamp used to filter columns with a specific range of versions. */
79    public static final String SCAN_TIMERANGE_END = "hbase.mapreduce.scan.timerange.end";
80    /** The maximum number of version to return. */
81    public static final String SCAN_MAXVERSIONS = "hbase.mapreduce.scan.maxversions";
82    /** Set to false to disable server-side caching of blocks for this scan. */
83    public static final String SCAN_CACHEBLOCKS = "hbase.mapreduce.scan.cacheblocks";
84    /** The number of rows for caching that will be passed to scanners. */
85    public static final String SCAN_CACHEDROWS = "hbase.mapreduce.scan.cachedrows";
86    /** Set the maximum number of values to return for each call to next(). */
87    public static final String SCAN_BATCHSIZE = "hbase.mapreduce.scan.batchsize";
88    /** Specify if we have to shuffle the map tasks. */
89    public static final String SHUFFLE_MAPS = "hbase.mapreduce.inputtable.shufflemaps";
90  
91    /** The configuration. */
92    private Configuration conf = null;
93  
94    /**
95     * Returns the current configuration.
96     *
97     * @return The current configuration.
98     * @see org.apache.hadoop.conf.Configurable#getConf()
99     */
100   @Override
101   public Configuration getConf() {
102     return conf;
103   }
104 
105   /**
106    * Sets the configuration. This is used to set the details for the table to
107    * be scanned.
108    *
109    * @param configuration  The configuration to set.
110    * @see org.apache.hadoop.conf.Configurable#setConf(
111    *   org.apache.hadoop.conf.Configuration)
112    */
113   @Override
114   public void setConf(Configuration configuration) {
115     this.conf = configuration;
116 
117     Scan scan = null;
118 
119     if (conf.get(SCAN) != null) {
120       try {
121         scan = TableMapReduceUtil.convertStringToScan(conf.get(SCAN));
122       } catch (IOException e) {
123         LOG.error("An error occurred.", e);
124       }
125     } else {
126       try {
127         scan = new Scan();
128 
129         if (conf.get(SCAN_ROW_START) != null) {
130           scan.setStartRow(Bytes.toBytes(conf.get(SCAN_ROW_START)));
131         }
132 
133         if (conf.get(SCAN_ROW_STOP) != null) {
134           scan.setStopRow(Bytes.toBytes(conf.get(SCAN_ROW_STOP)));
135         }
136 
137         if (conf.get(SCAN_COLUMNS) != null) {
138           addColumns(scan, conf.get(SCAN_COLUMNS));
139         }
140 
141         if (conf.get(SCAN_COLUMN_FAMILY) != null) {
142           scan.addFamily(Bytes.toBytes(conf.get(SCAN_COLUMN_FAMILY)));
143         }
144 
145         if (conf.get(SCAN_TIMESTAMP) != null) {
146           scan.setTimeStamp(Long.parseLong(conf.get(SCAN_TIMESTAMP)));
147         }
148 
149         if (conf.get(SCAN_TIMERANGE_START) != null && conf.get(SCAN_TIMERANGE_END) != null) {
150           scan.setTimeRange(
151               Long.parseLong(conf.get(SCAN_TIMERANGE_START)),
152               Long.parseLong(conf.get(SCAN_TIMERANGE_END)));
153         }
154 
155         if (conf.get(SCAN_MAXVERSIONS) != null) {
156           scan.setMaxVersions(Integer.parseInt(conf.get(SCAN_MAXVERSIONS)));
157         }
158 
159         if (conf.get(SCAN_CACHEDROWS) != null) {
160           scan.setCaching(Integer.parseInt(conf.get(SCAN_CACHEDROWS)));
161         }
162 
163         if (conf.get(SCAN_BATCHSIZE) != null) {
164           scan.setBatch(Integer.parseInt(conf.get(SCAN_BATCHSIZE)));
165         }
166 
167         // false by default, full table scans generate too much BC churn
168         scan.setCacheBlocks((conf.getBoolean(SCAN_CACHEBLOCKS, false)));
169       } catch (Exception e) {
170           LOG.error(StringUtils.stringifyException(e));
171       }
172     }
173 
174     setScan(scan);
175   }
176 
177   @Override
178   protected void initialize() {
179     TableName tableName = TableName.valueOf(conf.get(INPUT_TABLE));
180     try {
181       initializeTable(ConnectionFactory.createConnection(new Configuration(conf)), tableName);
182     } catch (Exception e) {
183       LOG.error(StringUtils.stringifyException(e));
184     }
185   }
186 
187   /**
188    * Parses a combined family and qualifier and adds either both or just the
189    * family in case there is no qualifier. This assumes the older colon
190    * divided notation, e.g. "family:qualifier".
191    *
192    * @param scan The Scan to update.
193    * @param familyAndQualifier family and qualifier
194    * @throws IllegalArgumentException When familyAndQualifier is invalid.
195    */
196   private static void addColumn(Scan scan, byte[] familyAndQualifier) {
197     byte [][] fq = KeyValue.parseColumn(familyAndQualifier);
198     if (fq.length == 1) {
199       scan.addFamily(fq[0]);
200     } else if (fq.length == 2) {
201       scan.addColumn(fq[0], fq[1]);
202     } else {
203       throw new IllegalArgumentException("Invalid familyAndQualifier provided.");
204     }
205   }
206 
207   /**
208    * Adds an array of columns specified using old format, family:qualifier.
209    * <p>
210    * Overrides previous calls to {@link Scan#addColumn(byte[], byte[])}for any families in the
211    * input.
212    *
213    * @param scan The Scan to update.
214    * @param columns array of columns, formatted as <code>family:qualifier</code>
215    * @see Scan#addColumn(byte[], byte[])
216    */
217   public static void addColumns(Scan scan, byte [][] columns) {
218     for (byte[] column : columns) {
219       addColumn(scan, column);
220     }
221   }
222 
223   /**
224    * Calculates the splits that will serve as input for the map tasks. The
225    * number of splits matches the number of regions in a table. Splits are shuffled if
226    * required.
227    * @param context  The current job context.
228    * @return The list of input splits.
229    * @throws IOException When creating the list of splits fails.
230    * @see org.apache.hadoop.mapreduce.InputFormat#getSplits(
231    *   org.apache.hadoop.mapreduce.JobContext)
232    */
233   @Override
234   public List<InputSplit> getSplits(JobContext context) throws IOException {
235     List<InputSplit> splits = super.getSplits(context);
236     if ((conf.get(SHUFFLE_MAPS) != null) && "true".equals(conf.get(SHUFFLE_MAPS).toLowerCase())) {
237       Collections.shuffle(splits);
238     }
239     return splits;
240   }
241 
242   /**
243    * Convenience method to parse a string representation of an array of column specifiers.
244    *
245    * @param scan The Scan to update.
246    * @param columns  The columns to parse.
247    */
248   private static void addColumns(Scan scan, String columns) {
249     String[] cols = columns.split(" ");
250     for (String col : cols) {
251       addColumn(scan, Bytes.toBytes(col));
252     }
253   }
254 
255   @Override
256   protected Pair<byte[][], byte[][]> getStartEndKeys() throws IOException {
257     if (conf.get(SPLIT_TABLE) != null) {
258       TableName splitTableName = TableName.valueOf(conf.get(SPLIT_TABLE));
259       try (Connection conn = ConnectionFactory.createConnection(getConf())) {
260         try (RegionLocator rl = conn.getRegionLocator(splitTableName)) {
261           return rl.getStartEndKeys();
262         }
263       }
264     }
265 
266     return super.getStartEndKeys();
267   }
268 
269   /**
270    * Sets split table in map-reduce job.
271    */
272   public static void configureSplitTable(Job job, TableName tableName) {
273     job.getConfiguration().set(SPLIT_TABLE, tableName.getNameAsString());
274   }
275 }