View Javadoc

1   /**
2    * Copyright 2009 The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS,
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17   * See the License for the specific language governing permissions and
18   * limitations under the License.
19   */
20  package org.apache.hadoop.hbase.mapreduce;
21  
22  import java.io.IOException;
23  import java.io.InterruptedIOException;
24  import java.net.InetAddress;
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.HConstants;
34  import org.apache.hadoop.hbase.HRegionLocation;
35  import org.apache.hadoop.hbase.HServerAddress;
36  import org.apache.hadoop.hbase.client.HTable;
37  import org.apache.hadoop.hbase.client.Result;
38  import org.apache.hadoop.hbase.client.Scan;
39  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
40  import org.apache.hadoop.hbase.util.Addressing;
41  import org.apache.hadoop.hbase.util.Bytes;
42  import org.apache.hadoop.hbase.util.Pair;
43  import org.apache.hadoop.hbase.util.Strings;
44  import org.apache.hadoop.mapreduce.InputFormat;
45  import org.apache.hadoop.mapreduce.InputSplit;
46  import org.apache.hadoop.mapreduce.JobContext;
47  import org.apache.hadoop.mapreduce.RecordReader;
48  import org.apache.hadoop.mapreduce.TaskAttemptContext;
49  import org.apache.hadoop.net.DNS;
50  
51  /**
52   * A base for {@link TableInputFormat}s. Receives a {@link HTable}, an
53   * {@link Scan} instance that defines the input columns etc. Subclasses may use
54   * other TableRecordReader implementations.
55   * <p>
56   * An example of a subclass:
57   * <pre>
58   *   class ExampleTIF extends TableInputFormatBase implements JobConfigurable {
59   *
60   *     public void configure(JobConf job) {
61   *       HTable exampleTable = new HTable(HBaseConfiguration.create(job),
62   *         Bytes.toBytes("exampleTable"));
63   *       // mandatory
64   *       setHTable(exampleTable);
65   *       Text[] inputColumns = new byte [][] { Bytes.toBytes("columnA"),
66   *         Bytes.toBytes("columnB") };
67   *       // mandatory
68   *       setInputColumns(inputColumns);
69   *       RowFilterInterface exampleFilter = new RegExpRowFilter("keyPrefix.*");
70   *       // optional
71   *       setRowFilter(exampleFilter);
72   *     }
73   *
74   *     public void validateInput(JobConf job) throws IOException {
75   *     }
76   *  }
77   * </pre>
78   */
79  public abstract class TableInputFormatBase
80  extends InputFormat<ImmutableBytesWritable, Result> {
81  
82    final Log LOG = LogFactory.getLog(TableInputFormatBase.class);
83  
84    /** Holds the details for the internal scanner. */
85    private Scan scan = null;
86    /** The table to scan. */
87    private HTable table = null;
88    /** The reader scanning the table, can be a custom one. */
89    private TableRecordReader tableRecordReader = null;
90  
91  
92    /** The reverse DNS lookup cache mapping: IPAddress => HostName */
93    private HashMap<InetAddress, String> reverseDNSCacheMap =
94      new HashMap<InetAddress, String>();
95    
96    /** The NameServer address */
97    private String nameServer = null;
98    
99    /**
100    * Builds a TableRecordReader. If no TableRecordReader was provided, uses
101    * the default.
102    *
103    * @param split  The split to work with.
104    * @param context  The current context.
105    * @return The newly created record reader.
106    * @throws IOException When creating the reader fails.
107    * @see org.apache.hadoop.mapreduce.InputFormat#createRecordReader(
108    *   org.apache.hadoop.mapreduce.InputSplit,
109    *   org.apache.hadoop.mapreduce.TaskAttemptContext)
110    */
111   @Override
112   public RecordReader<ImmutableBytesWritable, Result> createRecordReader(
113       InputSplit split, TaskAttemptContext context)
114   throws IOException {
115     if (table == null) {
116       throw new IOException("Cannot create a record reader because of a" +
117           " previous error. Please look at the previous logs lines from" +
118           " the task's full log for more details.");
119     }
120     TableSplit tSplit = (TableSplit) split;
121     TableRecordReader trr = this.tableRecordReader;
122     // if no table record reader was provided use default
123     if (trr == null) {
124       trr = new TableRecordReader();
125     }
126     Scan sc = new Scan(this.scan);
127     sc.setStartRow(tSplit.getStartRow());
128     sc.setStopRow(tSplit.getEndRow());
129     trr.setScan(sc);
130     trr.setHTable(table);
131     try {
132       trr.initialize(tSplit, context);
133     } catch (InterruptedException e) {
134       throw new InterruptedIOException(e.getMessage());
135     }
136     return trr;
137   }
138 
139   /**
140    * Calculates the splits that will serve as input for the map tasks. The
141    * number of splits matches the number of regions in a table.
142    *
143    * @param context  The current job context.
144    * @return The list of input splits.
145    * @throws IOException When creating the list of splits fails.
146    * @see org.apache.hadoop.mapreduce.InputFormat#getSplits(
147    *   org.apache.hadoop.mapreduce.JobContext)
148    */
149   @Override
150   public List<InputSplit> getSplits(JobContext context) throws IOException {
151 	if (table == null) {
152 	    throw new IOException("No table was provided.");
153 	}
154     // Get the name server address and the default value is null.
155     this.nameServer =
156       context.getConfiguration().get("hbase.nameserver.address", null);
157     
158     Pair<byte[][], byte[][]> keys = table.getStartEndKeys();
159     if (keys == null || keys.getFirst() == null ||
160         keys.getFirst().length == 0) {
161       HRegionLocation regLoc = table.getRegionLocation(
162           HConstants.EMPTY_BYTE_ARRAY, false);
163       if (null == regLoc) {
164         throw new IOException("Expecting at least one region.");
165       }
166       List<InputSplit> splits = new ArrayList<InputSplit>(1);
167       InputSplit split = new TableSplit(table.getTableName(),
168           HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY, regLoc
169               .getHostnamePort().split(Addressing.HOSTNAME_PORT_SEPARATOR)[0]);
170       splits.add(split);
171       return splits;
172     }
173     List<InputSplit> splits = new ArrayList<InputSplit>(keys.getFirst().length);
174     for (int i = 0; i < keys.getFirst().length; i++) {
175       if ( !includeRegionInSplit(keys.getFirst()[i], keys.getSecond()[i])) {
176         continue;
177       }
178       HServerAddress regionServerAddress = 
179         table.getRegionLocation(keys.getFirst()[i]).getServerAddress();
180       InetAddress regionAddress =
181         regionServerAddress.getInetSocketAddress().getAddress();
182       String regionLocation;
183       try {
184         regionLocation = reverseDNS(regionAddress);
185       } catch (NamingException e) {
186         LOG.error("Cannot resolve the host name for " + regionAddress +
187             " because of " + e);
188         regionLocation = regionServerAddress.getHostname();
189       }
190 
191 			byte[] startRow = scan.getStartRow();
192 			byte[] stopRow = scan.getStopRow();
193 			// determine if the given start an stop key fall into the region
194       if ((startRow.length == 0 || keys.getSecond()[i].length == 0 ||
195 					 Bytes.compareTo(startRow, keys.getSecond()[i]) < 0) &&
196           (stopRow.length == 0 ||
197            Bytes.compareTo(stopRow, keys.getFirst()[i]) > 0)) {
198         byte[] splitStart = startRow.length == 0 ||
199           Bytes.compareTo(keys.getFirst()[i], startRow) >= 0 ?
200             keys.getFirst()[i] : startRow;
201         byte[] splitStop = (stopRow.length == 0 ||
202           Bytes.compareTo(keys.getSecond()[i], stopRow) <= 0) &&
203           keys.getSecond()[i].length > 0 ?
204             keys.getSecond()[i] : stopRow;
205         InputSplit split = new TableSplit(table.getTableName(),
206           splitStart, splitStop, regionLocation);
207         splits.add(split);
208         if (LOG.isDebugEnabled()) {
209           LOG.debug("getSplits: split -> " + i + " -> " + split);
210         }
211       }
212     }
213     return splits;
214   }
215   
216   private String reverseDNS(InetAddress ipAddress) throws NamingException {
217     String hostName = this.reverseDNSCacheMap.get(ipAddress);
218     if (hostName == null) {
219       hostName = Strings.domainNamePointerToHostName(DNS.reverseDns(ipAddress, this.nameServer));
220       this.reverseDNSCacheMap.put(ipAddress, hostName);
221     }
222     return hostName;
223   }
224 
225   /**
226    *
227    *
228    * Test if the given region is to be included in the InputSplit while splitting
229    * the regions of a table.
230    * <p>
231    * This optimization is effective when there is a specific reasoning to exclude an entire region from the M-R job,
232    * (and hence, not contributing to the InputSplit), given the start and end keys of the same. <br>
233    * Useful when we need to remember the last-processed top record and revisit the [last, current) interval for M-R processing,
234    * continuously. In addition to reducing InputSplits, reduces the load on the region server as well, due to the ordering of the keys.
235    * <br>
236    * <br>
237    * Note: It is possible that <code>endKey.length() == 0 </code> , for the last (recent) region.
238    * <br>
239    * 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).
240    *
241    *
242    * @param startKey Start key of the region
243    * @param endKey End key of the region
244    * @return true, if this region needs to be included as part of the input (default).
245    *
246    */
247   protected boolean includeRegionInSplit(final byte[] startKey, final byte [] endKey) {
248     return true;
249   }
250 
251   /**
252    * Allows subclasses to get the {@link HTable}.
253    */
254   protected HTable getHTable() {
255     return this.table;
256   }
257 
258   /**
259    * Allows subclasses to set the {@link HTable}.
260    *
261    * @param table  The table to get the data from.
262    */
263   protected void setHTable(HTable table) {
264     this.table = table;
265   }
266 
267   /**
268    * Gets the scan defining the actual details like columns etc.
269    *
270    * @return The internal scan instance.
271    */
272   public Scan getScan() {
273     if (this.scan == null) this.scan = new Scan();
274     return scan;
275   }
276 
277   /**
278    * Sets the scan defining the actual details like columns etc.
279    *
280    * @param scan  The scan to set.
281    */
282   public void setScan(Scan scan) {
283     this.scan = scan;
284   }
285 
286   /**
287    * Allows subclasses to set the {@link TableRecordReader}.
288    *
289    * @param tableRecordReader A different {@link TableRecordReader}
290    *   implementation.
291    */
292   protected void setTableRecordReader(TableRecordReader tableRecordReader) {
293     this.tableRecordReader = tableRecordReader;
294   }
295 }