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