View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.mapreduce;
19  
20  import java.io.IOException;
21  import java.text.MessageFormat;
22  import java.util.ArrayList;
23  import java.util.List;
24  
25  
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  import org.apache.hadoop.hbase.classification.InterfaceAudience;
29  import org.apache.hadoop.hbase.classification.InterfaceStability;
30  import org.apache.hadoop.hbase.HRegionInfo;
31  import org.apache.hadoop.hbase.HRegionLocation;
32  import org.apache.hadoop.hbase.client.HTable;
33  import org.apache.hadoop.hbase.client.Result;
34  import org.apache.hadoop.hbase.client.Scan;
35  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
36  import org.apache.hadoop.hbase.util.Bytes;
37  import org.apache.hadoop.hbase.util.Pair;
38  import org.apache.hadoop.hbase.util.RegionSizeCalculator;
39  import org.apache.hadoop.mapreduce.InputFormat;
40  import org.apache.hadoop.mapreduce.InputSplit;
41  import org.apache.hadoop.mapreduce.JobContext;
42  import org.apache.hadoop.mapreduce.RecordReader;
43  import org.apache.hadoop.mapreduce.TaskAttemptContext;
44  
45  import java.util.Map;
46  import java.util.HashMap;
47  import java.util.Iterator;
48  
49  
50  /**
51   * A base for {@link MultiTableInputFormat}s. Receives a list of
52   * {@link Scan} instances that define the input tables and
53   * filters etc. Subclasses may use other TableRecordReader implementations.
54   */
55  @InterfaceAudience.Public
56  @InterfaceStability.Evolving
57  public abstract class MultiTableInputFormatBase extends
58      InputFormat<ImmutableBytesWritable, Result> {
59  
60    final Log LOG = LogFactory.getLog(MultiTableInputFormatBase.class);
61  
62    /** Holds the set of scans used to define the input. */
63    private List<Scan> scans;
64  
65    /** The reader scanning the table, can be a custom one. */
66    private TableRecordReader tableRecordReader = null;
67  
68    /**
69     * Builds a TableRecordReader. If no TableRecordReader was provided, uses the
70     * default.
71     *
72     * @param split The split to work with.
73     * @param context The current context.
74     * @return The newly created record reader.
75     * @throws IOException When creating the reader fails.
76     * @throws InterruptedException when record reader initialization fails
77     * @see org.apache.hadoop.mapreduce.InputFormat#createRecordReader(
78     *      org.apache.hadoop.mapreduce.InputSplit,
79     *      org.apache.hadoop.mapreduce.TaskAttemptContext)
80     */
81    @Override
82    public RecordReader<ImmutableBytesWritable, Result> createRecordReader(
83        InputSplit split, TaskAttemptContext context)
84        throws IOException, InterruptedException {
85      TableSplit tSplit = (TableSplit) split;
86      LOG.info(MessageFormat.format("Input split length: {0} bytes.", tSplit.getLength()));
87  
88      if (tSplit.getTableName() == null) {
89        throw new IOException("Cannot create a record reader because of a"
90            + " previous error. Please look at the previous logs lines from"
91            + " the task's full log for more details.");
92      }
93      HTable table =
94          new HTable(context.getConfiguration(), tSplit.getTableName());
95  
96      TableRecordReader trr = this.tableRecordReader;
97  
98      try {
99        // if no table record reader was provided use default
100       if (trr == null) {
101         trr = new TableRecordReader();
102       }
103       Scan sc = tSplit.getScan();
104       sc.setStartRow(tSplit.getStartRow());
105       sc.setStopRow(tSplit.getEndRow());
106       trr.setScan(sc);
107       trr.setHTable(table);
108     } catch (IOException ioe) {
109       // If there is an exception make sure that all
110       // resources are closed and released.
111       table.close();
112       trr.close();
113       throw ioe;
114     }
115     return trr;
116   }
117 
118   /**
119    * Calculates the splits that will serve as input for the map tasks. The
120    * number of splits matches the number of regions in a table.
121    *
122    * @param context The current job context.
123    * @return The list of input splits.
124    * @throws IOException When creating the list of splits fails.
125    * @see org.apache.hadoop.mapreduce.InputFormat#getSplits(org.apache.hadoop.mapreduce.JobContext)
126    */
127   @Override
128   public List<InputSplit> getSplits(JobContext context) throws IOException {
129     if (scans.isEmpty()) {
130       throw new IOException("No scans were provided.");
131     }
132 
133     Map<String, List<Scan>> tableMaps = new HashMap<String, List<Scan>>();
134     for (Scan scan : scans) {
135       byte[] tableName = scan.getAttribute(Scan.SCAN_ATTRIBUTES_TABLE_NAME);
136       if (tableName == null)
137         throw new IOException("A scan object did not have a table name");
138 
139       String tableNameStr = Bytes.toString(tableName);
140       List<Scan> scanList = tableMaps.get(tableNameStr);
141       if (scanList == null) {
142         scanList = new ArrayList<Scan>();
143         tableMaps.put(tableNameStr, scanList);
144       }
145       scanList.add(scan);
146     }
147 
148     List<InputSplit> splits = new ArrayList<InputSplit>();
149     Iterator iter = tableMaps.entrySet().iterator();
150     while (iter.hasNext()) {
151       Map.Entry<String, List<Scan>> entry = (Map.Entry<String, List<Scan>>) iter.next();
152       String tableNameStr = entry.getKey();
153       List<Scan> scanList = entry.getValue();
154       HTable table = new HTable(context.getConfiguration(), tableNameStr);
155       Pair<byte[][], byte[][]> keys = table.getStartEndKeys();
156       RegionSizeCalculator sizeCalculator = new RegionSizeCalculator(table);
157 
158       for (Scan scan : scanList) {
159         if (keys == null || keys.getFirst() == null ||
160                 keys.getFirst().length == 0) {
161           throw new IOException("Expecting at least one region for table : "
162                   + tableNameStr);
163         }
164         int count = 0;
165         byte[] startRow = scan.getStartRow();
166         byte[] stopRow = scan.getStopRow();
167         for (int i = 0; i < keys.getFirst().length; i++) {
168           if (!includeRegionInSplit(keys.getFirst()[i], keys.getSecond()[i])) {
169             continue;
170           }
171 
172           // determine if the given start and stop keys fall into the range
173           if ((startRow.length == 0 || keys.getSecond()[i].length == 0 ||
174                   Bytes.compareTo(startRow, keys.getSecond()[i]) < 0) &&
175                   (stopRow.length == 0 || Bytes.compareTo(stopRow,
176                   keys.getFirst()[i]) > 0)) {
177             byte[] splitStart = startRow.length == 0 ||
178                     Bytes.compareTo(keys.getFirst()[i], startRow) >= 0 ?
179                     keys.getFirst()[i] : startRow;
180             byte[] splitStop = (stopRow.length == 0 ||
181                     Bytes.compareTo(keys.getSecond()[i], stopRow) <= 0) &&
182                     keys.getSecond()[i].length > 0 ?
183                     keys.getSecond()[i] : stopRow;
184             HRegionLocation hregionLocation = table.getRegionLocation(
185                     keys.getFirst()[i], false);
186             String regionHostname = hregionLocation.getHostname();
187             HRegionInfo regionInfo = hregionLocation.getRegionInfo();
188             long regionSize = sizeCalculator.getRegionSize(
189                     regionInfo.getRegionName());
190             TableSplit split = new TableSplit(table.getName(), scan, splitStart,
191                     splitStop, regionHostname, regionSize);
192             splits.add(split);
193             if (LOG.isDebugEnabled())
194               LOG.debug("getSplits: split -> " + (count++) + " -> " + split);
195           }
196         }
197       }
198       table.close();
199     }
200 
201     return splits;
202   }
203 
204   /**
205    * Test if the given region is to be included in the InputSplit while
206    * splitting the regions of a table.
207    * <p>
208    * This optimization is effective when there is a specific reasoning to
209    * exclude an entire region from the M-R job, (and hence, not contributing to
210    * the InputSplit), given the start and end keys of the same. <br>
211    * Useful when we need to remember the last-processed top record and revisit
212    * the [last, current) interval for M-R processing, continuously. In addition
213    * to reducing InputSplits, reduces the load on the region server as well, due
214    * to the ordering of the keys. <br>
215    * <br>
216    * Note: It is possible that <code>endKey.length() == 0 </code> , for the last
217    * (recent) region. <br>
218    * Override this method, if you want to bulk exclude regions altogether from
219    * M-R. By default, no region is excluded( i.e. all regions are included).
220    *
221    * @param startKey Start key of the region
222    * @param endKey End key of the region
223    * @return true, if this region needs to be included as part of the input
224    *         (default).
225    */
226   protected boolean includeRegionInSplit(final byte[] startKey,
227       final byte[] endKey) {
228     return true;
229   }
230 
231   /**
232    * Allows subclasses to get the list of {@link Scan} objects.
233    */
234   protected List<Scan> getScans() {
235     return this.scans;
236   }
237 
238   /**
239    * Allows subclasses to set the list of {@link Scan} objects.
240    *
241    * @param scans The list of {@link Scan} used to define the input
242    */
243   protected void setScans(List<Scan> scans) {
244     this.scans = scans;
245   }
246 
247   /**
248    * Allows subclasses to set the {@link TableRecordReader}.
249    *
250    * @param tableRecordReader A different {@link TableRecordReader}
251    *          implementation.
252    */
253   protected void setTableRecordReader(TableRecordReader tableRecordReader) {
254     this.tableRecordReader = tableRecordReader;
255   }
256 }