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