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.io.InterruptedIOException;
23  import java.net.InetAddress;
24  import java.net.InetSocketAddress;
25  import java.text.MessageFormat;
26  import java.util.ArrayList;
27  import java.util.HashMap;
28  import java.util.List;
29  
30  import javax.naming.NamingException;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.classification.InterfaceAudience;
35  import org.apache.hadoop.classification.InterfaceStability;
36  import org.apache.hadoop.hbase.HConstants;
37  import org.apache.hadoop.hbase.HRegionLocation;
38  import org.apache.hadoop.hbase.client.HTable;
39  import org.apache.hadoop.hbase.client.Result;
40  import org.apache.hadoop.hbase.client.Scan;
41  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
42  import org.apache.hadoop.hbase.util.Addressing;
43  import org.apache.hadoop.hbase.util.Bytes;
44  import org.apache.hadoop.hbase.util.Pair;
45  import org.apache.hadoop.hbase.util.RegionSizeCalculator;
46  import org.apache.hadoop.hbase.util.Strings;
47  import org.apache.hadoop.mapreduce.InputFormat;
48  import org.apache.hadoop.mapreduce.InputSplit;
49  import org.apache.hadoop.mapreduce.JobContext;
50  import org.apache.hadoop.mapreduce.RecordReader;
51  import org.apache.hadoop.mapreduce.TaskAttemptContext;
52  import org.apache.hadoop.net.DNS;
53  import org.apache.hadoop.util.StringUtils;
54  
55  /**
56   * A base for {@link TableInputFormat}s. Receives a {@link HTable}, an
57   * {@link Scan} instance that defines the input columns etc. Subclasses may use
58   * other TableRecordReader implementations.
59   * <p>
60   * An example of a subclass:
61   * <pre>
62   *   class ExampleTIF extends TableInputFormatBase implements JobConfigurable {
63   *
64   *     public void configure(JobConf job) {
65   *       HTable exampleTable = new HTable(HBaseConfiguration.create(job),
66   *         Bytes.toBytes("exampleTable"));
67   *       // mandatory
68   *       setHTable(exampleTable);
69   *       Text[] inputColumns = new byte [][] { Bytes.toBytes("cf1:columnA"),
70   *         Bytes.toBytes("cf2") };
71   *       // mandatory
72   *       setInputColumns(inputColumns);
73   *       RowFilterInterface exampleFilter = new RegExpRowFilter("keyPrefix.*");
74   *       // optional
75   *       setRowFilter(exampleFilter);
76   *     }
77   *
78   *     public void validateInput(JobConf job) throws IOException {
79   *     }
80   *  }
81   * </pre>
82   */
83  @InterfaceAudience.Public
84  @InterfaceStability.Stable
85  public abstract class TableInputFormatBase
86  extends InputFormat<ImmutableBytesWritable, Result> {
87  
88    final Log LOG = LogFactory.getLog(TableInputFormatBase.class);
89  
90    /** Holds the details for the internal scanner. */
91    private Scan scan = null;
92    /** The table to scan. */
93    private HTable table = null;
94    /** The reader scanning the table, can be a custom one. */
95    private TableRecordReader tableRecordReader = null;
96  
97  
98    /** The reverse DNS lookup cache mapping: IPAddress => HostName */
99    private HashMap<InetAddress, String> reverseDNSCacheMap =
100     new HashMap<InetAddress, String>();
101   
102   /** The NameServer address */
103   private String nameServer = null;
104   
105   /**
106    * Builds a TableRecordReader. If no TableRecordReader was provided, uses
107    * the default.
108    *
109    * @param split  The split to work with.
110    * @param context  The current context.
111    * @return The newly created record reader.
112    * @throws IOException When creating the reader fails.
113    * @see org.apache.hadoop.mapreduce.InputFormat#createRecordReader(
114    *   org.apache.hadoop.mapreduce.InputSplit,
115    *   org.apache.hadoop.mapreduce.TaskAttemptContext)
116    */
117   @Override
118   public RecordReader<ImmutableBytesWritable, Result> createRecordReader(
119       InputSplit split, TaskAttemptContext context)
120   throws IOException {
121     if (table == null) {
122       throw new IOException("Cannot create a record reader because of a" +
123           " previous error. Please look at the previous logs lines from" +
124           " the task's full log for more details.");
125     }
126     TableSplit tSplit = (TableSplit) split;
127     LOG.info("Input split length: " + StringUtils.humanReadableInt(tSplit.getLength()) + " bytes.");
128     TableRecordReader trr = this.tableRecordReader;
129     // if no table record reader was provided use default
130     if (trr == null) {
131       trr = new TableRecordReader();
132     }
133     Scan sc = new Scan(this.scan);
134     sc.setStartRow(tSplit.getStartRow());
135     sc.setStopRow(tSplit.getEndRow());
136     trr.setScan(sc);
137     trr.setHTable(table);
138     return trr;
139   }
140 
141   /**
142    * Calculates the splits that will serve as input for the map tasks. The
143    * number of splits matches the number of regions in a table.
144    *
145    * @param context  The current job context.
146    * @return The list of input splits.
147    * @throws IOException When creating the list of splits fails.
148    * @see org.apache.hadoop.mapreduce.InputFormat#getSplits(
149    *   org.apache.hadoop.mapreduce.JobContext)
150    */
151   @Override
152   public List<InputSplit> getSplits(JobContext context) throws IOException {
153     if (table == null) {
154       throw new IOException("No table was provided.");
155     }
156     // Get the name server address and the default value is null.
157     this.nameServer =
158       context.getConfiguration().get("hbase.nameserver.address", null);
159 
160     RegionSizeCalculator sizeCalculator = new RegionSizeCalculator(table);
161 
162     Pair<byte[][], byte[][]> keys = table.getStartEndKeys();
163     if (keys == null || keys.getFirst() == null ||
164         keys.getFirst().length == 0) {
165       HRegionLocation regLoc = table.getRegionLocation(HConstants.EMPTY_BYTE_ARRAY, false);
166       if (null == regLoc) {
167         throw new IOException("Expecting at least one region.");
168       }
169       List<InputSplit> splits = new ArrayList<InputSplit>(1);
170       long regionSize = sizeCalculator.getRegionSize(regLoc.getRegionInfo().getRegionName());
171       TableSplit split = new TableSplit(table.getName(),
172           HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY, regLoc
173               .getHostnamePort().split(Addressing.HOSTNAME_PORT_SEPARATOR)[0], regionSize);
174       splits.add(split);
175       return splits;
176     }
177     List<InputSplit> splits = new ArrayList<InputSplit>(keys.getFirst().length);
178     for (int i = 0; i < keys.getFirst().length; i++) {
179       if ( !includeRegionInSplit(keys.getFirst()[i], keys.getSecond()[i])) {
180         continue;
181       }
182       HRegionLocation location = table.getRegionLocation(keys.getFirst()[i], false);
183       // The below InetSocketAddress creation does a name resolution.
184       InetSocketAddress isa = new InetSocketAddress(location.getHostname(), location.getPort());
185       if (isa.isUnresolved()) {
186         LOG.warn("Failed resolve " + isa);
187       }
188       InetAddress regionAddress = isa.getAddress();
189       String regionLocation;
190       try {
191         regionLocation = reverseDNS(regionAddress);
192       } catch (NamingException e) {
193         LOG.warn("Cannot resolve the host name for " + regionAddress + " because of " + e);
194         regionLocation = location.getHostname();
195       }
196 
197       byte[] startRow = scan.getStartRow();
198       byte[] stopRow = scan.getStopRow();
199       // determine if the given start an stop key fall into the region
200       if ((startRow.length == 0 || keys.getSecond()[i].length == 0 ||
201           Bytes.compareTo(startRow, keys.getSecond()[i]) < 0) &&
202           (stopRow.length == 0 ||
203            Bytes.compareTo(stopRow, keys.getFirst()[i]) > 0)) {
204         byte[] splitStart = startRow.length == 0 ||
205           Bytes.compareTo(keys.getFirst()[i], startRow) >= 0 ?
206             keys.getFirst()[i] : startRow;
207         byte[] splitStop = (stopRow.length == 0 ||
208           Bytes.compareTo(keys.getSecond()[i], stopRow) <= 0) &&
209           keys.getSecond()[i].length > 0 ?
210             keys.getSecond()[i] : stopRow;
211 
212         byte[] regionName = location.getRegionInfo().getRegionName();
213         long regionSize = sizeCalculator.getRegionSize(regionName);
214         TableSplit split = new TableSplit(table.getName(),
215           splitStart, splitStop, regionLocation, regionSize);
216         splits.add(split);
217         if (LOG.isDebugEnabled()) {
218           LOG.debug("getSplits: split -> " + i + " -> " + split);
219         }
220       }
221     }
222     return splits;
223   }
224   
225   private String reverseDNS(InetAddress ipAddress) throws NamingException {
226     String hostName = this.reverseDNSCacheMap.get(ipAddress);
227     if (hostName == null) {
228       hostName = Strings.domainNamePointerToHostName(
229         DNS.reverseDns(ipAddress, this.nameServer));
230       this.reverseDNSCacheMap.put(ipAddress, hostName);
231     }
232     return hostName;
233   }
234 
235   /**
236    *
237    *
238    * Test if the given region is to be included in the InputSplit while splitting
239    * the regions of a table.
240    * <p>
241    * This optimization is effective when there is a specific reasoning to exclude an entire region from the M-R job,
242    * (and hence, not contributing to the InputSplit), given the start and end keys of the same. <br>
243    * Useful when we need to remember the last-processed top record and revisit the [last, current) interval for M-R processing,
244    * continuously. In addition to reducing InputSplits, reduces the load on the region server as well, due to the ordering of the keys.
245    * <br>
246    * <br>
247    * Note: It is possible that <code>endKey.length() == 0 </code> , for the last (recent) region.
248    * <br>
249    * Override this method, if you want to bulk exclude regions altogether from M-R. By default, no region is excluded( i.e. all regions are included).
250    *
251    *
252    * @param startKey Start key of the region
253    * @param endKey End key of the region
254    * @return true, if this region needs to be included as part of the input (default).
255    *
256    */
257   protected boolean includeRegionInSplit(final byte[] startKey, final byte [] endKey) {
258     return true;
259   }
260 
261   /**
262    * Allows subclasses to get the {@link HTable}.
263    */
264   protected HTable getHTable() {
265     return this.table;
266   }
267 
268   /**
269    * Allows subclasses to set the {@link HTable}.
270    *
271    * @param table  The table to get the data from.
272    */
273   protected void setHTable(HTable table) {
274     this.table = table;
275   }
276 
277   /**
278    * Gets the scan defining the actual details like columns etc.
279    *
280    * @return The internal scan instance.
281    */
282   public Scan getScan() {
283     if (this.scan == null) this.scan = new Scan();
284     return scan;
285   }
286 
287   /**
288    * Sets the scan defining the actual details like columns etc.
289    *
290    * @param scan  The scan to set.
291    */
292   public void setScan(Scan scan) {
293     this.scan = scan;
294   }
295 
296   /**
297    * Allows subclasses to set the {@link TableRecordReader}.
298    *
299    * @param tableRecordReader A different {@link TableRecordReader}
300    *   implementation.
301    */
302   protected void setTableRecordReader(TableRecordReader tableRecordReader) {
303     this.tableRecordReader = tableRecordReader;
304   }
305 }