View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.mapreduce;
19  
20  import java.io.IOException;
21  import java.lang.reflect.Method;
22  import java.util.Map;
23  
24  import org.apache.commons.logging.Log;
25  import org.apache.commons.logging.LogFactory;
26  import org.apache.hadoop.hbase.classification.InterfaceAudience;
27  import org.apache.hadoop.hbase.classification.InterfaceStability;
28  import org.apache.hadoop.conf.Configuration;
29  import org.apache.hadoop.hbase.client.HTable;
30  import org.apache.hadoop.hbase.client.Result;
31  import org.apache.hadoop.hbase.client.ResultScanner;
32  import org.apache.hadoop.hbase.client.Scan;
33  import org.apache.hadoop.hbase.client.ScannerCallable;
34  import org.apache.hadoop.hbase.client.Table;
35  import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
36  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
37  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
38  import org.apache.hadoop.hbase.util.Bytes;
39  import org.apache.hadoop.mapreduce.Counter;
40  import org.apache.hadoop.mapreduce.InputSplit;
41  import org.apache.hadoop.mapreduce.TaskAttemptContext;
42  import org.apache.hadoop.util.StringUtils;
43  
44  /**
45   * Iterate over an HBase table data, return (ImmutableBytesWritable, Result)
46   * pairs.
47   */
48  @InterfaceAudience.Public
49  @InterfaceStability.Stable
50  public class TableRecordReaderImpl {
51    public static final String LOG_PER_ROW_COUNT
52      = "hbase.mapreduce.log.scanner.rowcount";
53  
54    static final Log LOG = LogFactory.getLog(TableRecordReaderImpl.class);
55  
56    // HBASE_COUNTER_GROUP_NAME is the name of mapreduce counter group for HBase
57    private static final String HBASE_COUNTER_GROUP_NAME =
58      "HBase Counters";
59    private ResultScanner scanner = null;
60    private Scan scan = null;
61    private Scan currentScan = null;
62    private Table htable = null;
63    private byte[] lastSuccessfulRow = null;
64    private ImmutableBytesWritable key = null;
65    private Result value = null;
66    private TaskAttemptContext context = null;
67    private Method getCounter = null;
68    private long numRestarts = 0;
69    private long numStale = 0;
70    private long timestamp;
71    private int rowcount;
72    private boolean logScannerActivity = false;
73    private int logPerRowCount = 100;
74  
75    /**
76     * Restart from survivable exceptions by creating a new scanner.
77     *
78     * @param firstRow  The first row to start at.
79     * @throws IOException When restarting fails.
80     */
81    public void restart(byte[] firstRow) throws IOException {
82      currentScan = new Scan(scan);
83      currentScan.setStartRow(firstRow);
84      currentScan.setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE,
85        Bytes.toBytes(Boolean.TRUE));
86      if (this.scanner != null) {
87        if (logScannerActivity) {
88          LOG.info("Closing the previously opened scanner object.");
89        }
90        this.scanner.close();
91      }
92      this.scanner = this.htable.getScanner(currentScan);
93      if (logScannerActivity) {
94        LOG.info("Current scan=" + currentScan.toString());
95        timestamp = System.currentTimeMillis();
96        rowcount = 0;
97      }
98    }
99  
100   /**
101    * In new mapreduce APIs, TaskAttemptContext has two getCounter methods
102    * Check if getCounter(String, String) method is available.
103    * @return The getCounter method or null if not available.
104    * @throws IOException
105    */
106   protected static Method retrieveGetCounterWithStringsParams(TaskAttemptContext context)
107   throws IOException {
108     Method m = null;
109     try {
110       m = context.getClass().getMethod("getCounter",
111         new Class [] {String.class, String.class});
112     } catch (SecurityException e) {
113       throw new IOException("Failed test for getCounter", e);
114     } catch (NoSuchMethodException e) {
115       // Ignore
116     }
117     return m;
118   }
119 
120   /**
121    * Sets the HBase table.
122    *
123    * @param htable  The {@link HTable} to scan.
124    */
125   public void setHTable(Table htable) {
126     Configuration conf = htable.getConfiguration();
127     logScannerActivity = conf.getBoolean(
128       ScannerCallable.LOG_SCANNER_ACTIVITY, false);
129     logPerRowCount = conf.getInt(LOG_PER_ROW_COUNT, 100);
130     this.htable = htable;
131   }
132 
133   /**
134    * Sets the scan defining the actual details like columns etc.
135    *
136    * @param scan  The scan to set.
137    */
138   public void setScan(Scan scan) {
139     this.scan = scan;
140   }
141 
142   /**
143    * Build the scanner. Not done in constructor to allow for extension.
144    *
145    * @throws IOException, InterruptedException
146    */
147   public void initialize(InputSplit inputsplit,
148       TaskAttemptContext context) throws IOException,
149       InterruptedException {
150     if (context != null) {
151       this.context = context;
152       getCounter = retrieveGetCounterWithStringsParams(context);
153     }
154     restart(scan.getStartRow());
155   }
156 
157   /**
158    * Closes the split.
159    *
160    *
161    */
162   public void close() {
163     this.scanner.close();
164     try {
165       this.htable.close();
166     } catch (IOException ioe) {
167       LOG.warn("Error closing table", ioe);
168     }
169   }
170 
171   /**
172    * Returns the current key.
173    *
174    * @return The current key.
175    * @throws IOException
176    * @throws InterruptedException When the job is aborted.
177    */
178   public ImmutableBytesWritable getCurrentKey() throws IOException,
179       InterruptedException {
180     return key;
181   }
182 
183   /**
184    * Returns the current value.
185    *
186    * @return The current value.
187    * @throws IOException When the value is faulty.
188    * @throws InterruptedException When the job is aborted.
189    */
190   public Result getCurrentValue() throws IOException, InterruptedException {
191     return value;
192   }
193 
194 
195   /**
196    * Positions the record reader to the next record.
197    *
198    * @return <code>true</code> if there was another record.
199    * @throws IOException When reading the record failed.
200    * @throws InterruptedException When the job was aborted.
201    */
202   public boolean nextKeyValue() throws IOException, InterruptedException {
203     if (key == null) key = new ImmutableBytesWritable();
204     if (value == null) value = new Result();
205     try {
206       try {
207         value = this.scanner.next();
208         if (value != null && value.isStale()) numStale++;
209         if (logScannerActivity) {
210           rowcount ++;
211           if (rowcount >= logPerRowCount) {
212             long now = System.currentTimeMillis();
213             LOG.info("Mapper took " + (now-timestamp)
214               + "ms to process " + rowcount + " rows");
215             timestamp = now;
216             rowcount = 0;
217           }
218         }
219       } catch (IOException e) {
220         // try to handle all IOExceptions by restarting
221         // the scanner, if the second call fails, it will be rethrown
222         LOG.info("recovered from " + StringUtils.stringifyException(e));
223         if (lastSuccessfulRow == null) {
224           LOG.warn("We are restarting the first next() invocation," +
225               " if your mapper has restarted a few other times like this" +
226               " then you should consider killing this job and investigate" +
227               " why it's taking so long.");
228         }
229         if (lastSuccessfulRow == null) {
230           restart(scan.getStartRow());
231         } else {
232           restart(lastSuccessfulRow);
233           scanner.next();    // skip presumed already mapped row
234         }
235         value = scanner.next();
236         if (value != null && value.isStale()) numStale++;
237         numRestarts++;
238       }
239       if (value != null && value.size() > 0) {
240         key.set(value.getRow());
241         lastSuccessfulRow = key.get();
242         return true;
243       }
244 
245       updateCounters();
246       return false;
247     } catch (IOException ioe) {
248       if (logScannerActivity) {
249         long now = System.currentTimeMillis();
250         LOG.info("Mapper took " + (now-timestamp)
251           + "ms to process " + rowcount + " rows");
252         LOG.info(ioe);
253         String lastRow = lastSuccessfulRow == null ?
254           "null" : Bytes.toStringBinary(lastSuccessfulRow);
255         LOG.info("lastSuccessfulRow=" + lastRow);
256       }
257       throw ioe;
258     }
259   }
260 
261   /**
262    * If hbase runs on new version of mapreduce, RecordReader has access to
263    * counters thus can update counters based on scanMetrics.
264    * If hbase runs on old version of mapreduce, it won't be able to get
265    * access to counters and TableRecorderReader can't update counter values.
266    * @throws IOException
267    */
268   private void updateCounters() throws IOException {
269     byte[] serializedMetrics = currentScan.getAttribute(
270         Scan.SCAN_ATTRIBUTES_METRICS_DATA);
271     if (serializedMetrics == null || serializedMetrics.length == 0 ) {
272       return;
273     }
274 
275     ScanMetrics scanMetrics = ProtobufUtil.toScanMetrics(serializedMetrics);
276 
277     updateCounters(scanMetrics, numRestarts, getCounter, context, numStale);
278   }
279 
280   protected static void updateCounters(ScanMetrics scanMetrics, long numScannerRestarts,
281       Method getCounter, TaskAttemptContext context, long numStale) {
282     // we can get access to counters only if hbase uses new mapreduce APIs
283     if (getCounter == null) {
284       return;
285     }
286 
287     try {
288       for (Map.Entry<String, Long> entry:scanMetrics.getMetricsMap().entrySet()) {
289         Counter ct = (Counter)getCounter.invoke(context,
290             HBASE_COUNTER_GROUP_NAME, entry.getKey());
291 
292         ct.increment(entry.getValue());
293       }
294       ((Counter) getCounter.invoke(context, HBASE_COUNTER_GROUP_NAME,
295           "NUM_SCANNER_RESTARTS")).increment(numScannerRestarts);
296       ((Counter) getCounter.invoke(context, HBASE_COUNTER_GROUP_NAME,
297           "NUM_SCAN_RESULTS_STALE")).increment(numStale);
298     } catch (Exception e) {
299       LOG.debug("can't update counter." + StringUtils.stringifyException(e));
300     }
301   }
302 
303   /**
304    * The current progress of the record reader through its data.
305    *
306    * @return A number between 0.0 and 1.0, the fraction of the data read.
307    */
308   public float getProgress() {
309     // Depends on the total number of tuples
310     return 0;
311   }
312 
313 }