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.util.ArrayList;
25  import java.util.HashMap;
26  import java.util.List;
27  
28  import javax.naming.NamingException;
29  
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.apache.hadoop.classification.InterfaceAudience;
33  import org.apache.hadoop.classification.InterfaceStability;
34  import org.apache.hadoop.hbase.HConstants;
35  import org.apache.hadoop.hbase.HRegionLocation;
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.RegionSizeCalculator;
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  import org.apache.hadoop.util.StringUtils;
52  
53  /**
54   * A base for {@link TableInputFormat}s. Receives a {@link HTable}, an
55   * {@link Scan} instance that defines the input columns etc. Subclasses may use
56   * other TableRecordReader implementations.
57   * <p>
58   * An example of a subclass:
59   * <pre>
60   *   class ExampleTIF extends TableInputFormatBase implements JobConfigurable {
61   *
62   *     public void configure(JobConf job) {
63   *       HTable exampleTable = new HTable(HBaseConfiguration.create(job),
64   *         Bytes.toBytes("exampleTable"));
65   *       // mandatory
66   *       setHTable(exampleTable);
67   *       Text[] inputColumns = new byte [][] { Bytes.toBytes("cf1:columnA"),
68   *         Bytes.toBytes("cf2") };
69   *       // mandatory
70   *       setInputColumns(inputColumns);
71   *       RowFilterInterface exampleFilter = new RegExpRowFilter("keyPrefix.*");
72   *       // optional
73   *       setRowFilter(exampleFilter);
74   *     }
75   *
76   *     public void validateInput(JobConf job) throws IOException {
77   *     }
78   *  }
79   * </pre>
80   */
81  @InterfaceAudience.Public
82  @InterfaceStability.Stable
83  public abstract class TableInputFormatBase
84  extends InputFormat<ImmutableBytesWritable, Result> {
85  
86    final Log LOG = LogFactory.getLog(TableInputFormatBase.class);
87  
88    /** Holds the details for the internal scanner. */
89    private Scan scan = null;
90    /** The table to scan. */
91    private HTable table = null;
92    /** The reader scanning the table, can be a custom one. */
93    private TableRecordReader tableRecordReader = null;
94  
95  
96    /** The reverse DNS lookup cache mapping: IPAddress => HostName */
97    private HashMap<InetAddress, String> reverseDNSCacheMap =
98      new HashMap<InetAddress, String>();
99    
100   /** The NameServer address */
101   private String nameServer = null;
102   
103   /**
104    * Builds a TableRecordReader. If no TableRecordReader was provided, uses
105    * the default.
106    *
107    * @param split  The split to work with.
108    * @param context  The current context.
109    * @return The newly created record reader.
110    * @throws IOException When creating the reader fails.
111    * @see org.apache.hadoop.mapreduce.InputFormat#createRecordReader(
112    *   org.apache.hadoop.mapreduce.InputSplit,
113    *   org.apache.hadoop.mapreduce.TaskAttemptContext)
114    */
115   @Override
116   public RecordReader<ImmutableBytesWritable, Result> createRecordReader(
117       InputSplit split, TaskAttemptContext context)
118   throws IOException {
119     if (table == null) {
120       throw new IOException("Cannot create a record reader because of a" +
121           " previous error. Please look at the previous logs lines from" +
122           " the task's full log for more details.");
123     }
124     TableSplit tSplit = (TableSplit) split;
125     LOG.info("Input split length: " + StringUtils.humanReadableInt(tSplit.getLength()) + " bytes.");
126     TableRecordReader trr = this.tableRecordReader;
127     // if no table record reader was provided use default
128     if (trr == null) {
129       trr = new TableRecordReader();
130     }
131     Scan sc = new Scan(this.scan);
132     sc.setStartRow(tSplit.getStartRow());
133     sc.setStopRow(tSplit.getEndRow());
134     trr.setScan(sc);
135     trr.setHTable(table);
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     RegionSizeCalculator sizeCalculator = new RegionSizeCalculator(table);
159 
160     Pair<byte[][], byte[][]> keys = table.getStartEndKeys();
161     if (keys == null || keys.getFirst() == null ||
162         keys.getFirst().length == 0) {
163       HRegionLocation regLoc = table.getRegionLocation(HConstants.EMPTY_BYTE_ARRAY, false);
164       if (null == regLoc) {
165         throw new IOException("Expecting at least one region.");
166       }
167       List<InputSplit> splits = new ArrayList<InputSplit>(1);
168       long regionSize = sizeCalculator.getRegionSize(regLoc.getRegionInfo().getRegionName());
169       TableSplit split = new TableSplit(table.getName(),
170           HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY, regLoc
171               .getHostnamePort().split(Addressing.HOSTNAME_PORT_SEPARATOR)[0], regionSize);
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.warn("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 
210         byte[] regionName = location.getRegionInfo().getRegionName();
211         long regionSize = sizeCalculator.getRegionSize(regionName);
212         TableSplit split = new TableSplit(table.getName(),
213           splitStart, splitStop, regionLocation, regionSize);
214         splits.add(split);
215         if (LOG.isDebugEnabled()) {
216           LOG.debug("getSplits: split -> " + i + " -> " + split);
217         }
218       }
219     }
220     return splits;
221   }
222   
223   private String reverseDNS(InetAddress ipAddress) throws NamingException {
224     String hostName = this.reverseDNSCacheMap.get(ipAddress);
225     if (hostName == null) {
226       hostName = Strings.domainNamePointerToHostName(
227         DNS.reverseDns(ipAddress, this.nameServer));
228       this.reverseDNSCacheMap.put(ipAddress, hostName);
229     }
230     return hostName;
231   }
232 
233   /**
234    *
235    *
236    * Test if the given region is to be included in the InputSplit while splitting
237    * the regions of a table.
238    * <p>
239    * This optimization is effective when there is a specific reasoning to exclude an entire region from the M-R job,
240    * (and hence, not contributing to the InputSplit), given the start and end keys of the same. <br>
241    * Useful when we need to remember the last-processed top record and revisit the [last, current) interval for M-R processing,
242    * continuously. In addition to reducing InputSplits, reduces the load on the region server as well, due to the ordering of the keys.
243    * <br>
244    * <br>
245    * Note: It is possible that <code>endKey.length() == 0 </code> , for the last (recent) region.
246    * <br>
247    * 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).
248    *
249    *
250    * @param startKey Start key of the region
251    * @param endKey End key of the region
252    * @return true, if this region needs to be included as part of the input (default).
253    *
254    */
255   protected boolean includeRegionInSplit(final byte[] startKey, final byte [] endKey) {
256     return true;
257   }
258 
259   /**
260    * Allows subclasses to get the {@link HTable}.
261    */
262   protected HTable getHTable() {
263     return this.table;
264   }
265 
266   /**
267    * Allows subclasses to set the {@link HTable}.
268    *
269    * @param table  The table to get the data from.
270    */
271   protected void setHTable(HTable table) {
272     this.table = table;
273   }
274 
275   /**
276    * Gets the scan defining the actual details like columns etc.
277    *
278    * @return The internal scan instance.
279    */
280   public Scan getScan() {
281     if (this.scan == null) this.scan = new Scan();
282     return scan;
283   }
284 
285   /**
286    * Sets the scan defining the actual details like columns etc.
287    *
288    * @param scan  The scan to set.
289    */
290   public void setScan(Scan scan) {
291     this.scan = scan;
292   }
293 
294   /**
295    * Allows subclasses to set the {@link TableRecordReader}.
296    *
297    * @param tableRecordReader A different {@link TableRecordReader}
298    *   implementation.
299    */
300   protected void setTableRecordReader(TableRecordReader tableRecordReader) {
301     this.tableRecordReader = tableRecordReader;
302   }
303 }