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  
23  import org.apache.commons.logging.Log;
24  import org.apache.commons.logging.LogFactory;
25  import org.apache.hadoop.conf.Configurable;
26  import org.apache.hadoop.conf.Configuration;
27  import org.apache.hadoop.hbase.KeyValue;
28  import org.apache.hadoop.hbase.TableName;
29  import org.apache.hadoop.hbase.classification.InterfaceAudience;
30  import org.apache.hadoop.hbase.classification.InterfaceStability;
31  import org.apache.hadoop.hbase.client.Connection;
32  import org.apache.hadoop.hbase.client.ConnectionFactory;
33  import org.apache.hadoop.hbase.client.RegionLocator;
34  import org.apache.hadoop.hbase.client.Scan;
35  import org.apache.hadoop.hbase.util.Bytes;
36  import org.apache.hadoop.hbase.util.Pair;
37  import org.apache.hadoop.mapreduce.Job;
38  import org.apache.hadoop.util.StringUtils;
39  
40  /**
41   * Convert HBase tabular data into a format that is consumable by Map/Reduce.
42   */
43  @InterfaceAudience.Public
44  @InterfaceStability.Stable
45  public class TableInputFormat extends TableInputFormatBase
46  implements Configurable {
47  
48    private static final Log LOG = LogFactory.getLog(TableInputFormat.class);
49  
50    /** Job parameter that specifies the input table. */
51    public static final String INPUT_TABLE = "hbase.mapreduce.inputtable";
52    /**
53     * If specified, use start keys of this table to split.
54     * This is useful when you are preparing data for bulkload.
55     */
56    private static final String SPLIT_TABLE = "hbase.mapreduce.splittable";
57    /** Base-64 encoded scanner. All other SCAN_ confs are ignored if this is specified.
58     * See {@link TableMapReduceUtil#convertScanToString(Scan)} for more details.
59     */
60    public static final String SCAN = "hbase.mapreduce.scan";
61    /** Scan start row */
62    public static final String SCAN_ROW_START = "hbase.mapreduce.scan.row.start";
63    /** Scan stop row */
64    public static final String SCAN_ROW_STOP = "hbase.mapreduce.scan.row.stop";
65    /** Column Family to Scan */
66    public static final String SCAN_COLUMN_FAMILY = "hbase.mapreduce.scan.column.family";
67    /** Space delimited list of columns and column families to scan. */
68    public static final String SCAN_COLUMNS = "hbase.mapreduce.scan.columns";
69    /** The timestamp used to filter columns with a specific timestamp. */
70    public static final String SCAN_TIMESTAMP = "hbase.mapreduce.scan.timestamp";
71    /** The starting timestamp used to filter columns with a specific range of versions. */
72    public static final String SCAN_TIMERANGE_START = "hbase.mapreduce.scan.timerange.start";
73    /** The ending timestamp used to filter columns with a specific range of versions. */
74    public static final String SCAN_TIMERANGE_END = "hbase.mapreduce.scan.timerange.end";
75    /** The maximum number of version to return. */
76    public static final String SCAN_MAXVERSIONS = "hbase.mapreduce.scan.maxversions";
77    /** Set to false to disable server-side caching of blocks for this scan. */
78    public static final String SCAN_CACHEBLOCKS = "hbase.mapreduce.scan.cacheblocks";
79    /** The number of rows for caching that will be passed to scanners. */
80    public static final String SCAN_CACHEDROWS = "hbase.mapreduce.scan.cachedrows";
81    /** Set the maximum number of values to return for each call to next(). */
82    public static final String SCAN_BATCHSIZE = "hbase.mapreduce.scan.batchsize";
83  
84    /** The configuration. */
85    private Configuration conf = null;
86  
87    /**
88     * Returns the current configuration.
89     *
90     * @return The current configuration.
91     * @see org.apache.hadoop.conf.Configurable#getConf()
92     */
93    @Override
94    public Configuration getConf() {
95      return conf;
96    }
97  
98    /**
99     * Sets the configuration. This is used to set the details for the table to
100    * be scanned.
101    *
102    * @param configuration  The configuration to set.
103    * @see org.apache.hadoop.conf.Configurable#setConf(
104    *   org.apache.hadoop.conf.Configuration)
105    */
106   @Override
107   public void setConf(Configuration configuration) {
108     this.conf = configuration;
109     TableName tableName = TableName.valueOf(conf.get(INPUT_TABLE));
110     try {
111       // NOTE: This connection doesn't currently get closed explicit1ly.
112       initializeTable(ConnectionFactory.createConnection(new Configuration(conf)), tableName);
113     } catch (Exception e) {
114       LOG.error(StringUtils.stringifyException(e));
115     }
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   /**
178    * Parses a combined family and qualifier and adds either both or just the
179    * family in case there is no qualifier. This assumes the older colon
180    * divided notation, e.g. "family:qualifier".
181    *
182    * @param scan The Scan to update.
183    * @param familyAndQualifier family and qualifier
184    * @throws IllegalArgumentException When familyAndQualifier is invalid.
185    */
186   private static void addColumn(Scan scan, byte[] familyAndQualifier) {
187     byte [][] fq = KeyValue.parseColumn(familyAndQualifier);
188     if (fq.length == 1) {
189       scan.addFamily(fq[0]);
190     } else if (fq.length == 2) {
191       scan.addColumn(fq[0], fq[1]);
192     } else {
193       throw new IllegalArgumentException("Invalid familyAndQualifier provided.");
194     }
195   }
196 
197   /**
198    * Adds an array of columns specified using old format, family:qualifier.
199    * <p>
200    * Overrides previous calls to {@link Scan#addColumn(byte[], byte[])}for any families in the
201    * input.
202    *
203    * @param scan The Scan to update.
204    * @param columns array of columns, formatted as <code>family:qualifier</code>
205    * @see Scan#addColumn(byte[], byte[])
206    */
207   public static void addColumns(Scan scan, byte [][] columns) {
208     for (byte[] column : columns) {
209       addColumn(scan, column);
210     }
211   }
212 
213   /**
214    * Convenience method to parse a string representation of an array of column specifiers.
215    *
216    * @param scan The Scan to update.
217    * @param columns  The columns to parse.
218    */
219   private static void addColumns(Scan scan, String columns) {
220     String[] cols = columns.split(" ");
221     for (String col : cols) {
222       addColumn(scan, Bytes.toBytes(col));
223     }
224   }
225 
226   @Override
227   protected Pair<byte[][], byte[][]> getStartEndKeys() throws IOException {
228     if (conf.get(SPLIT_TABLE) != null) {
229       TableName splitTableName = TableName.valueOf(conf.get(SPLIT_TABLE));
230       try (Connection conn = ConnectionFactory.createConnection(getConf());
231           RegionLocator rl = conn.getRegionLocator(splitTableName)) {
232         return rl.getStartEndKeys();
233       }
234     }
235 
236     return super.getStartEndKeys();
237   }
238   
239   /**
240    * Sets split table in map-reduce job.
241    */
242   public static void configureSplitTable(Job job, TableName tableName) {
243     job.getConfiguration().set(SPLIT_TABLE, tableName.getNameAsString());
244   }
245 }