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