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