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