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