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   *   public static class ExampleTIF extends TableInputFormatBase implements JobConfigurable {
62   *  
63   *     @Override
64   *     public void configure(JobConf job) {
65   *       try {
66   *         HTable exampleTable = new HTable(HBaseConfiguration.create(job),
67   *           Bytes.toBytes("exampleTable"));
68   *         // mandatory
69   *         setHTable(exampleTable);
70   *         byte[][] inputColumns = new byte [][] { Bytes.toBytes("columnA"),
71   *           Bytes.toBytes("columnB") };
72   *         // optional
73   *         Scan scan = new Scan();
74   *         for (byte[] family : inputColumns) {
75   *           scan.addFamily(family);
76   *         }
77   *         Filter exampleFilter = new RowFilter(CompareOp.EQUAL, new RegexStringComparator("aa.*"));
78   *         scan.setFilter(exampleFilter);
79   *         setScan(scan);
80   *       } catch (IOException exception) {
81   *         throw new RuntimeException("Failed to configure for job.", exception);
82   *       }
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    private Scan scan = null;
96    /** The table to scan. */
97    private HTable table = null;
98    /** The reader scanning the table, can be a custom one. */
99    private TableRecordReader tableRecordReader = null;
100   
101   /** The reverse DNS lookup cache mapping: IPAddress => HostName */
102   private HashMap<InetAddress, String> reverseDNSCacheMap =
103     new HashMap<InetAddress, String>();
104   
105   /** The NameServer address */
106   private String nameServer = null;
107   
108   /**
109    * Builds a TableRecordReader. If no TableRecordReader was provided, uses
110    * the default.
111    *
112    * @param split  The split to work with.
113    * @param context  The current context.
114    * @return The newly created record reader.
115    * @throws IOException When creating the reader fails.
116    * @see org.apache.hadoop.mapreduce.InputFormat#createRecordReader(
117    *   org.apache.hadoop.mapreduce.InputSplit,
118    *   org.apache.hadoop.mapreduce.TaskAttemptContext)
119    */
120   @Override
121   public RecordReader<ImmutableBytesWritable, Result> createRecordReader(
122       InputSplit split, TaskAttemptContext context)
123   throws IOException {
124     if (table == null) {
125       throw new IOException("Cannot create a record reader because of a" +
126           " previous error. Please look at the previous logs lines from" +
127           " the task's full log for more details.");
128     }
129     TableSplit tSplit = (TableSplit) split;
130     LOG.info("Input split length: " + StringUtils.humanReadableInt(tSplit.getLength()) + " bytes.");
131     TableRecordReader trr = this.tableRecordReader;
132     // if no table record reader was provided use default
133     if (trr == null) {
134       trr = new TableRecordReader();
135     }
136     Scan sc = new Scan(this.scan);
137     sc.setStartRow(tSplit.getStartRow());
138     sc.setStopRow(tSplit.getEndRow());
139     trr.setScan(sc);
140     trr.setHTable(table);
141     return trr;
142   }
143   
144   protected Pair<byte[][],byte[][]> getStartEndKeys() throws IOException {
145     return table.getStartEndKeys();
146   }
147 
148   /**
149    * Calculates the splits that will serve as input for the map tasks. The
150    * number of splits matches the number of regions in a table.
151    *
152    * @param context  The current job context.
153    * @return The list of input splits.
154    * @throws IOException When creating the list of splits fails.
155    * @see org.apache.hadoop.mapreduce.InputFormat#getSplits(
156    *   org.apache.hadoop.mapreduce.JobContext)
157    */
158   @Override
159   public List<InputSplit> getSplits(JobContext context) throws IOException {
160     if (table == null) {
161       throw new IOException("No table was provided.");
162     }
163     // Get the name server address and the default value is null.
164     this.nameServer =
165       context.getConfiguration().get("hbase.nameserver.address", null);
166 
167     RegionSizeCalculator sizeCalculator = new RegionSizeCalculator(table);
168 
169     
170     Pair<byte[][], byte[][]> keys = getStartEndKeys();
171     if (keys == null || keys.getFirst() == null ||
172         keys.getFirst().length == 0) {
173       HRegionLocation regLoc = table.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 = table.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   protected HTable getHTable() {
282     return this.table;
283   }
284 
285   /**
286    * Allows subclasses to set the {@link HTable}.
287    *
288    * @param table  The table to get the data from.
289    */
290   protected void setHTable(HTable table) {
291     this.table = 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 }