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