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.conf.Configuration;
35  import org.apache.hadoop.hbase.classification.InterfaceAudience;
36  import org.apache.hadoop.hbase.classification.InterfaceStability;
37  import org.apache.hadoop.hbase.HConstants;
38  import org.apache.hadoop.hbase.HRegionLocation;
39  import org.apache.hadoop.hbase.TableName;
40  import org.apache.hadoop.hbase.client.Admin;
41  import org.apache.hadoop.hbase.client.Connection;
42  import org.apache.hadoop.hbase.client.HTable;
43  import org.apache.hadoop.hbase.client.RegionLocator;
44  import org.apache.hadoop.hbase.client.Result;
45  import org.apache.hadoop.hbase.client.Scan;
46  import org.apache.hadoop.hbase.client.Table;
47  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
48  import org.apache.hadoop.hbase.util.Addressing;
49  import org.apache.hadoop.hbase.util.Bytes;
50  import org.apache.hadoop.hbase.util.Pair;
51  import org.apache.hadoop.hbase.util.RegionSizeCalculator;
52  import org.apache.hadoop.hbase.util.Strings;
53  import org.apache.hadoop.mapreduce.InputFormat;
54  import org.apache.hadoop.mapreduce.InputSplit;
55  import org.apache.hadoop.mapreduce.JobContext;
56  import org.apache.hadoop.mapreduce.RecordReader;
57  import org.apache.hadoop.mapreduce.TaskAttemptContext;
58  import org.apache.hadoop.net.DNS;
59  import org.apache.hadoop.util.StringUtils;
60  
61  /**
62   * A base for {@link TableInputFormat}s. Receives a {@link Connection}, a {@link TableName},
63   * an {@link Scan} instance that defines the input columns etc. Subclasses may use
64   * other TableRecordReader implementations.
65   *
66   * Subclasses MUST ensure initializeTable(Connection, TableName) is called for an instance to
67   * function properly. Each of the entry points to this class used by the MapReduce framework,
68   * {@link #createRecordReader(InputSplit, TaskAttemptContext)} and {@link #getSplits(JobContext)},
69   * will call {@link #initialize(JobContext)} as a convenient centralized location to handle
70   * retrieving the necessary configuration information. If your subclass overrides either of these
71   * methods, either call the parent version or call initialize yourself.
72   *
73   * <p>
74   * An example of a subclass:
75   * <pre>
76   *   class ExampleTIF extends TableInputFormatBase {
77   *
78   *     {@literal @}Override
79   *     protected void initialize(JobContext context) throws IOException {
80   *       // We are responsible for the lifecycle of this connection until we hand it over in
81   *       // initializeTable.
82   *       Connection connection = ConnectionFactory.createConnection(HBaseConfiguration.create(
83   *              job.getConfiguration()));
84   *       TableName tableName = TableName.valueOf("exampleTable");
85   *       // mandatory. once passed here, TableInputFormatBase will handle closing the connection.
86   *       initializeTable(connection, tableName);
87   *       byte[][] inputColumns = new byte [][] { Bytes.toBytes("columnA"),
88   *         Bytes.toBytes("columnB") };
89   *       // optional, by default we'll get everything for the table.
90   *       Scan scan = new Scan();
91   *       for (byte[] family : inputColumns) {
92   *         scan.addFamily(family);
93   *       }
94   *       Filter exampleFilter = new RowFilter(CompareOp.EQUAL, new RegexStringComparator("aa.*"));
95   *       scan.setFilter(exampleFilter);
96   *       setScan(scan);
97   *     }
98   *   }
99   * </pre>
100  */
101 @InterfaceAudience.Public
102 @InterfaceStability.Stable
103 public abstract class TableInputFormatBase
104 extends InputFormat<ImmutableBytesWritable, Result> {
105 
106   /** Specify if we enable auto-balance for input in M/R jobs.*/
107   public static final String MAPREDUCE_INPUT_AUTOBALANCE = "hbase.mapreduce.input.autobalance";
108   /** Specify if ratio for data skew in M/R jobs, it goes well with the enabling hbase.mapreduce
109    * .input.autobalance property.*/
110   public static final String INPUT_AUTOBALANCE_MAXSKEWRATIO = "hbase.mapreduce.input.autobalance" +
111           ".maxskewratio";
112   /** Specify if the row key in table is text (ASCII between 32~126),
113    * default is true. False means the table is using binary row key*/
114   public static final String TABLE_ROW_TEXTKEY = "hbase.table.row.textkey";
115 
116   private static final Log LOG = LogFactory.getLog(TableInputFormatBase.class);
117 
118   private static final String NOT_INITIALIZED = "The input format instance has not been properly " +
119       "initialized. Ensure you call initializeTable either in your constructor or initialize " +
120       "method";
121   private static final String INITIALIZATION_ERROR = "Cannot create a record reader because of a" +
122             " previous error. Please look at the previous logs lines from" +
123             " the task's full log for more details.";
124 
125   /** Holds the details for the internal scanner.
126    *
127    * @see Scan */
128   private Scan scan = null;
129   /** The {@link Admin}. */
130   private Admin admin;
131   /** The {@link Table} to scan. */
132   private Table table;
133   /** The {@link RegionLocator} of the table. */
134   private RegionLocator regionLocator;
135   /** The reader scanning the table, can be a custom one. */
136   private TableRecordReader tableRecordReader = null;
137   /** The underlying {@link Connection} of the table. */
138   private Connection connection;
139 
140   
141   /** The reverse DNS lookup cache mapping: IPAddress => HostName */
142   private HashMap<InetAddress, String> reverseDNSCacheMap =
143     new HashMap<InetAddress, String>();
144 
145   /**
146    * Builds a {@link TableRecordReader}. If no {@link TableRecordReader} was provided, uses
147    * the default.
148    *
149    * @param split  The split to work with.
150    * @param context  The current context.
151    * @return The newly created record reader.
152    * @throws IOException When creating the reader fails.
153    * @see org.apache.hadoop.mapreduce.InputFormat#createRecordReader(
154    *   org.apache.hadoop.mapreduce.InputSplit,
155    *   org.apache.hadoop.mapreduce.TaskAttemptContext)
156    */
157   @Override
158   public RecordReader<ImmutableBytesWritable, Result> createRecordReader(
159       InputSplit split, TaskAttemptContext context)
160   throws IOException {
161     // Just in case a subclass is relying on JobConfigurable magic.
162     if (table == null) {
163       initialize(context);
164     }
165     // null check in case our child overrides getTable to not throw.
166     try {
167       if (getTable() == null) {
168         // initialize() must not have been implemented in the subclass.
169         throw new IOException(INITIALIZATION_ERROR);
170       }
171     } catch (IllegalStateException exception) {
172       throw new IOException(INITIALIZATION_ERROR, exception);
173     }
174     TableSplit tSplit = (TableSplit) split;
175     LOG.info("Input split length: " + StringUtils.humanReadableInt(tSplit.getLength()) + " bytes.");
176     final TableRecordReader trr =
177         this.tableRecordReader != null ? this.tableRecordReader : new TableRecordReader();
178     Scan sc = new Scan(this.scan);
179     sc.setStartRow(tSplit.getStartRow());
180     sc.setStopRow(tSplit.getEndRow());
181     trr.setScan(sc);
182     trr.setTable(getTable());
183     return new RecordReader<ImmutableBytesWritable, Result>() {
184 
185       @Override
186       public void close() throws IOException {
187         trr.close();
188         closeTable();
189       }
190 
191       @Override
192       public ImmutableBytesWritable getCurrentKey() throws IOException, InterruptedException {
193         return trr.getCurrentKey();
194       }
195 
196       @Override
197       public Result getCurrentValue() throws IOException, InterruptedException {
198         return trr.getCurrentValue();
199       }
200 
201       @Override
202       public float getProgress() throws IOException, InterruptedException {
203         return trr.getProgress();
204       }
205 
206       @Override
207       public void initialize(InputSplit inputsplit, TaskAttemptContext context) throws IOException,
208           InterruptedException {
209         trr.initialize(inputsplit, context);
210       }
211 
212       @Override
213       public boolean nextKeyValue() throws IOException, InterruptedException {
214         return trr.nextKeyValue();
215       }
216     };
217   }
218 
219   protected Pair<byte[][],byte[][]> getStartEndKeys() throws IOException {
220     return getRegionLocator().getStartEndKeys();
221   }
222 
223   /**
224    * Calculates the splits that will serve as input for the map tasks. The
225    * number of splits matches the number of regions in a table.
226    *
227    * @param context  The current job context.
228    * @return The list of input splits.
229    * @throws IOException When creating the list of splits fails.
230    * @see org.apache.hadoop.mapreduce.InputFormat#getSplits(
231    *   org.apache.hadoop.mapreduce.JobContext)
232    */
233   @Override
234   public List<InputSplit> getSplits(JobContext context) throws IOException {
235     boolean closeOnFinish = false;
236 
237     // Just in case a subclass is relying on JobConfigurable magic.
238     if (table == null) {
239       initialize(context);
240       closeOnFinish = true;
241     }
242 
243     // null check in case our child overrides getTable to not throw.
244     try {
245       if (getTable() == null) {
246         // initialize() must not have been implemented in the subclass.
247         throw new IOException(INITIALIZATION_ERROR);
248       }
249     } catch (IllegalStateException exception) {
250       throw new IOException(INITIALIZATION_ERROR, exception);
251     }
252 
253     try {
254       RegionSizeCalculator sizeCalculator =
255           new RegionSizeCalculator(getRegionLocator(), getAdmin());
256       
257       TableName tableName = getTable().getName();
258   
259       Pair<byte[][], byte[][]> keys = getStartEndKeys();
260       if (keys == null || keys.getFirst() == null ||
261           keys.getFirst().length == 0) {
262         HRegionLocation regLoc =
263             getRegionLocator().getRegionLocation(HConstants.EMPTY_BYTE_ARRAY, false);
264         if (null == regLoc) {
265           throw new IOException("Expecting at least one region.");
266         }
267         List<InputSplit> splits = new ArrayList<InputSplit>(1);
268         long regionSize = sizeCalculator.getRegionSize(regLoc.getRegionInfo().getRegionName());
269         TableSplit split = new TableSplit(tableName, scan,
270             HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY, regLoc
271                 .getHostnamePort().split(Addressing.HOSTNAME_PORT_SEPARATOR)[0], regionSize);
272         splits.add(split);
273         return splits;
274       }
275       List<InputSplit> splits = new ArrayList<InputSplit>(keys.getFirst().length);
276       for (int i = 0; i < keys.getFirst().length; i++) {
277         if (!includeRegionInSplit(keys.getFirst()[i], keys.getSecond()[i])) {
278           continue;
279         }
280         HRegionLocation location = getRegionLocator().getRegionLocation(keys.getFirst()[i], false);
281         // The below InetSocketAddress creation does a name resolution.
282         InetSocketAddress isa = new InetSocketAddress(location.getHostname(), location.getPort());
283         if (isa.isUnresolved()) {
284           LOG.warn("Failed resolve " + isa);
285         }
286         InetAddress regionAddress = isa.getAddress();
287         String regionLocation;
288         try {
289           regionLocation = reverseDNS(regionAddress);
290         } catch (NamingException e) {
291           LOG.warn("Cannot resolve the host name for " + regionAddress + " because of " + e);
292           regionLocation = location.getHostname();
293         }
294   
295         byte[] startRow = scan.getStartRow();
296         byte[] stopRow = scan.getStopRow();
297         // determine if the given start an stop key fall into the region
298         if ((startRow.length == 0 || keys.getSecond()[i].length == 0 ||
299             Bytes.compareTo(startRow, keys.getSecond()[i]) < 0) &&
300             (stopRow.length == 0 ||
301              Bytes.compareTo(stopRow, keys.getFirst()[i]) > 0)) {
302           byte[] splitStart = startRow.length == 0 ||
303             Bytes.compareTo(keys.getFirst()[i], startRow) >= 0 ?
304               keys.getFirst()[i] : startRow;
305           byte[] splitStop = (stopRow.length == 0 ||
306             Bytes.compareTo(keys.getSecond()[i], stopRow) <= 0) &&
307             keys.getSecond()[i].length > 0 ?
308               keys.getSecond()[i] : stopRow;
309   
310           byte[] regionName = location.getRegionInfo().getRegionName();
311           long regionSize = sizeCalculator.getRegionSize(regionName);
312           TableSplit split = new TableSplit(tableName, scan,
313             splitStart, splitStop, regionLocation, regionSize);
314           splits.add(split);
315           if (LOG.isDebugEnabled()) {
316             LOG.debug("getSplits: split -> " + i + " -> " + split);
317           }
318         }
319       }
320       //The default value of "hbase.mapreduce.input.autobalance" is false, which means not enabled.
321       boolean enableAutoBalance = context.getConfiguration()
322         .getBoolean(MAPREDUCE_INPUT_AUTOBALANCE, false);
323       if (enableAutoBalance) {
324         long totalRegionSize=0;
325         for (int i = 0; i < splits.size(); i++){
326           TableSplit ts = (TableSplit)splits.get(i);
327           totalRegionSize += ts.getLength();
328         }
329         long averageRegionSize = totalRegionSize / splits.size();
330         // the averageRegionSize must be positive.
331         if (averageRegionSize <= 0) {
332             LOG.warn("The averageRegionSize is not positive: "+ averageRegionSize + ", " +
333                     "set it to 1.");
334             averageRegionSize = 1;
335         }
336         return calculateRebalancedSplits(splits, context, averageRegionSize);
337       } else {
338         return splits;
339       }
340     } finally {
341       if (closeOnFinish) {
342         closeTable();
343       }
344     }
345   }
346 
347   String reverseDNS(InetAddress ipAddress) throws NamingException, UnknownHostException {
348     String hostName = this.reverseDNSCacheMap.get(ipAddress);
349     if (hostName == null) {
350       String ipAddressString = null;
351       try {
352         ipAddressString = DNS.reverseDns(ipAddress, null);
353       } catch (Exception e) {
354         // We can use InetAddress in case the jndi failed to pull up the reverse DNS entry from the
355         // name service. Also, in case of ipv6, we need to use the InetAddress since resolving
356         // reverse DNS using jndi doesn't work well with ipv6 addresses.
357         ipAddressString = InetAddress.getByName(ipAddress.getHostAddress()).getHostName();
358       }
359       if (ipAddressString == null) throw new UnknownHostException("No host found for " + ipAddress);
360       hostName = Strings.domainNamePointerToHostName(ipAddressString);
361       this.reverseDNSCacheMap.put(ipAddress, hostName);
362     }
363     return hostName;
364   }
365 
366   /**
367    * Calculates the number of MapReduce input splits for the map tasks. The number of
368    * MapReduce input splits depends on the average region size and the "data skew ratio" user set in
369    * configuration.
370    *
371    * @param list  The list of input splits before balance.
372    * @param context  The current job context.
373    * @param average  The average size of all regions .
374    * @return The list of input splits.
375    * @throws IOException When creating the list of splits fails.
376    * @see org.apache.hadoop.mapreduce.InputFormat#getSplits(
377    *   org.apache.hadoop.mapreduce.JobContext)
378    */
379   private List<InputSplit> calculateRebalancedSplits(List<InputSplit> list, JobContext context,
380                                                long average) throws IOException {
381     List<InputSplit> resultList = new ArrayList<InputSplit>();
382     Configuration conf = context.getConfiguration();
383     //The default data skew ratio is 3
384     long dataSkewRatio = conf.getLong(INPUT_AUTOBALANCE_MAXSKEWRATIO, 3);
385     //It determines which mode to use: text key mode or binary key mode. The default is text mode.
386     boolean isTextKey = context.getConfiguration().getBoolean(TABLE_ROW_TEXTKEY, true);
387     long dataSkewThreshold = dataSkewRatio * average;
388     int count = 0;
389     while (count < list.size()) {
390       TableSplit ts = (TableSplit)list.get(count);
391       TableName tableName = ts.getTable();
392       String regionLocation = ts.getRegionLocation();
393       long regionSize = ts.getLength();
394       if (regionSize >= dataSkewThreshold) {
395         // if the current region size is large than the data skew threshold,
396         // split the region into two MapReduce input splits.
397         byte[] splitKey = getSplitKey(ts.getStartRow(), ts.getEndRow(), isTextKey);
398          //Set the size of child TableSplit as 1/2 of the region size. The exact size of the
399          // MapReduce input splits is not far off.
400         TableSplit t1 = new TableSplit(tableName, scan, ts.getStartRow(), splitKey, regionLocation,
401                 regionSize / 2);
402         TableSplit t2 = new TableSplit(tableName, scan, splitKey, ts.getEndRow(), regionLocation,
403                 regionSize - regionSize / 2);
404         resultList.add(t1);
405         resultList.add(t2);
406         count++;
407       } else if (regionSize >= average) {
408         // if the region size between average size and data skew threshold size,
409         // make this region as one MapReduce input split.
410         resultList.add(ts);
411         count++;
412       } else {
413         // if the total size of several small continuous regions less than the average region size,
414         // combine them into one MapReduce input split.
415         long totalSize = regionSize;
416         byte[] splitStartKey = ts.getStartRow();
417         byte[] splitEndKey = ts.getEndRow();
418         count++;
419         for (; count < list.size(); count++) {
420           TableSplit nextRegion = (TableSplit)list.get(count);
421           long nextRegionSize = nextRegion.getLength();
422           if (totalSize + nextRegionSize <= dataSkewThreshold) {
423             totalSize = totalSize + nextRegionSize;
424             splitEndKey = nextRegion.getEndRow();
425           } else {
426             break;
427           }
428         }
429         TableSplit t = new TableSplit(tableName, scan, splitStartKey, splitEndKey,
430                 regionLocation, totalSize);
431         resultList.add(t);
432       }
433     }
434     return resultList;
435   }
436 
437   /**
438    * select a split point in the region. The selection of the split point is based on an uniform
439    * distribution assumption for the keys in a region.
440    * Here are some examples:
441    * startKey: aaabcdefg  endKey: aaafff    split point: aaad
442    * startKey: 111000  endKey: 1125790    split point: 111b
443    * startKey: 1110  endKey: 1120    split point: 111_
444    * startKey: binary key { 13, -19, 126, 127 }, endKey: binary key { 13, -19, 127, 0 },
445    * split point: binary key { 13, -19, 127, -64 }
446    * Set this function as "public static", make it easier for test.
447    *
448    * @param start Start key of the region
449    * @param end End key of the region
450    * @param isText It determines to use text key mode or binary key mode
451    * @return The split point in the region.
452    */
453   @InterfaceAudience.Private
454   public static byte[] getSplitKey(byte[] start, byte[] end, boolean isText) {
455     byte upperLimitByte;
456     byte lowerLimitByte;
457     //Use text mode or binary mode.
458     if (isText) {
459       //The range of text char set in ASCII is [32,126], the lower limit is space and the upper
460       // limit is '~'.
461       upperLimitByte = '~';
462       lowerLimitByte = ' ';
463     } else {
464       upperLimitByte = Byte.MAX_VALUE;
465       lowerLimitByte = Byte.MIN_VALUE;
466     }
467     // For special case
468     // Example 1 : startkey=null, endkey="hhhqqqwww", splitKey="h"
469     // Example 2 (text key mode): startKey="ffffaaa", endKey=null, splitkey="f~~~~~~"
470     if (start.length == 0 && end.length == 0){
471       return new byte[]{(byte) ((lowerLimitByte + upperLimitByte) / 2)};
472     }
473     if (start.length == 0 && end.length != 0){
474       return new byte[]{ end[0] };
475     }
476     if (start.length != 0 && end.length == 0){
477       byte[] result =new byte[start.length];
478       result[0]=start[0];
479       for (int k = 1; k < start.length; k++){
480           result[k] = upperLimitByte;
481       }
482       return result;
483     }
484     // A list to store bytes in split key
485     List resultBytesList = new ArrayList();
486     int maxLength = start.length > end.length ? start.length : end.length;
487     for (int i = 0; i < maxLength; i++) {
488       //calculate the midpoint byte between the first difference
489       //for example: "11ae" and "11chw", the midpoint is "11b"
490       //another example: "11ae" and "11bhw", the first different byte is 'a' and 'b',
491       // there is no midpoint between 'a' and 'b', so we need to check the next byte.
492       if (start[i] == end[i]) {
493         resultBytesList.add(start[i]);
494         //For special case like: startKey="aaa", endKey="aaaz", splitKey="aaaM"
495         if (i + 1 == start.length) {
496           resultBytesList.add((byte) ((lowerLimitByte + end[i + 1]) / 2));
497           break;
498         }
499       } else {
500         //if the two bytes differ by 1, like ['a','b'], We need to check the next byte to find
501         // the midpoint.
502         if ((int)end[i] - (int)start[i] == 1) {
503           //get next byte after the first difference
504           byte startNextByte = (i + 1 < start.length) ? start[i + 1] : lowerLimitByte;
505           byte endNextByte = (i + 1 < end.length) ? end[i + 1] : lowerLimitByte;
506           int byteRange = (upperLimitByte - startNextByte) + (endNextByte - lowerLimitByte) + 1;
507           int halfRange = byteRange / 2;
508           if ((int)startNextByte + halfRange > (int)upperLimitByte) {
509             resultBytesList.add(end[i]);
510             resultBytesList.add((byte) (startNextByte + halfRange - upperLimitByte +
511                     lowerLimitByte));
512           } else {
513             resultBytesList.add(start[i]);
514             resultBytesList.add((byte) (startNextByte + halfRange));
515           }
516         } else {
517           //calculate the midpoint key by the fist different byte (normal case),
518           // like "11ae" and "11chw", the midpoint is "11b"
519           resultBytesList.add((byte) ((start[i] + end[i]) / 2));
520         }
521         break;
522       }
523     }
524     //transform the List of bytes to byte[]
525     byte[] result = new byte[resultBytesList.size()];
526     for (int k = 0; k < resultBytesList.size(); k++) {
527       result[k] = (byte) resultBytesList.get(k);
528     }
529     return result;
530   }
531 
532   /**
533    * Test if the given region is to be included in the InputSplit while splitting
534    * the regions of a table.
535    * <p>
536    * This optimization is effective when there is a specific reasoning to exclude an entire region from the M-R job,
537    * (and hence, not contributing to the InputSplit), given the start and end keys of the same. <br>
538    * Useful when we need to remember the last-processed top record and revisit the [last, current) interval for M-R processing,
539    * continuously. In addition to reducing InputSplits, reduces the load on the region server as well, due to the ordering of the keys.
540    * <br>
541    * <br>
542    * Note: It is possible that <code>endKey.length() == 0 </code> , for the last (recent) region.
543    * <br>
544    * 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).
545    *
546    *
547    * @param startKey Start key of the region
548    * @param endKey End key of the region
549    * @return true, if this region needs to be included as part of the input (default).
550    *
551    */
552   protected boolean includeRegionInSplit(final byte[] startKey, final byte [] endKey) {
553     return true;
554   }
555 
556   /**
557    * Allows subclasses to get the {@link RegionLocator}.
558    */
559   protected RegionLocator getRegionLocator() {
560     if (regionLocator == null) {
561       throw new IllegalStateException(NOT_INITIALIZED);
562     }
563     return regionLocator;
564   }
565   
566   /**
567    * Allows subclasses to get the {@link Table}.
568    */
569   protected Table getTable() {
570     if (table == null) {
571       throw new IllegalStateException(NOT_INITIALIZED);
572     }
573     return table;
574   }
575 
576   /**
577    * Allows subclasses to get the {@link Admin}.
578    */
579   protected Admin getAdmin() {
580     if (admin == null) {
581       throw new IllegalStateException(NOT_INITIALIZED);
582     }
583     return admin;
584   }
585 
586   /**
587    * Allows subclasses to initialize the table information.
588    *
589    * @param connection  The Connection to the HBase cluster. MUST be unmanaged. We will close.
590    * @param tableName  The {@link TableName} of the table to process. 
591    * @throws IOException 
592    */
593   protected void initializeTable(Connection connection, TableName tableName) throws IOException {
594     if (this.table != null || this.connection != null) {
595       LOG.warn("initializeTable called multiple times. Overwriting connection and table " +
596           "reference; TableInputFormatBase will not close these old references when done.");
597     }
598     this.table = connection.getTable(tableName);
599     this.regionLocator = connection.getRegionLocator(tableName);
600     this.admin = connection.getAdmin();
601     this.connection = connection;
602   }
603 
604   /**
605    * Gets the scan defining the actual details like columns etc.
606    *
607    * @return The internal scan instance.
608    */
609   public Scan getScan() {
610     if (this.scan == null) this.scan = new Scan();
611     return scan;
612   }
613 
614   /**
615    * Sets the scan defining the actual details like columns etc.
616    *
617    * @param scan  The scan to set.
618    */
619   public void setScan(Scan scan) {
620     this.scan = scan;
621   }
622 
623   /**
624    * Allows subclasses to set the {@link TableRecordReader}.
625    *
626    * @param tableRecordReader A different {@link TableRecordReader}
627    *   implementation.
628    */
629   protected void setTableRecordReader(TableRecordReader tableRecordReader) {
630     this.tableRecordReader = tableRecordReader;
631   }
632   
633   /**
634    * Handle subclass specific set up.
635    * Each of the entry points used by the MapReduce framework,
636    * {@link #createRecordReader(InputSplit, TaskAttemptContext)} and {@link #getSplits(JobContext)},
637    * will call {@link #initialize(JobContext)} as a convenient centralized location to handle
638    * retrieving the necessary configuration information and calling
639    * {@link #initializeTable(Connection, TableName)}.
640    *
641    * Subclasses should implement their initialize call such that it is safe to call multiple times.
642    * The current TableInputFormatBase implementation relies on a non-null table reference to decide
643    * if an initialize call is needed, but this behavior may change in the future. In particular,
644    * it is critical that initializeTable not be called multiple times since this will leak
645    * Connection instances.
646    *
647    */
648   protected void initialize(JobContext context) throws IOException {
649   }
650 
651   /**
652    * Close the Table and related objects that were initialized via
653    * {@link #initializeTable(Connection, TableName)}.
654    *
655    * @throws IOException
656    */
657   protected void closeTable() throws IOException {
658     close(admin, table, regionLocator, connection);
659     admin = null;
660     table = null;
661     regionLocator = null;
662     connection = null;
663   }
664 
665   private void close(Closeable... closables) throws IOException {
666     for (Closeable c : closables) {
667       if(c != null) { c.close(); }
668     }
669   }
670 
671 }