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  
23  import org.apache.commons.logging.Log;
24  import org.apache.commons.logging.LogFactory;
25  import org.apache.hadoop.conf.Configuration;
26  import org.apache.hadoop.hbase.client.HTable;
27  import org.apache.hadoop.hbase.client.Result;
28  import org.apache.hadoop.hbase.client.ResultScanner;
29  import org.apache.hadoop.hbase.client.Scan;
30  import org.apache.hadoop.hbase.client.ScannerCallable;
31  import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
32  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
33  import org.apache.hadoop.hbase.util.Bytes;
34  import org.apache.hadoop.io.DataInputBuffer;
35  import org.apache.hadoop.mapreduce.Counter;
36  import org.apache.hadoop.mapreduce.InputSplit;
37  import org.apache.hadoop.mapreduce.TaskAttemptContext;
38  import org.apache.hadoop.metrics.util.MetricsTimeVaryingLong;
39  import org.apache.hadoop.util.StringUtils;
40  
41  /**
42   * Iterate over an HBase table data, return (ImmutableBytesWritable, Result)
43   * pairs.
44   */
45  public class TableRecordReaderImpl {
46    public static final String LOG_PER_ROW_COUNT
47      = "hbase.mapreduce.log.scanner.rowcount";
48  
49    static final Log LOG = LogFactory.getLog(TableRecordReaderImpl.class);
50  
51    // HBASE_COUNTER_GROUP_NAME is the name of mapreduce counter group for HBase
52    private static final String HBASE_COUNTER_GROUP_NAME =
53      "HBase Counters";
54    private ResultScanner scanner = null;
55    private Scan scan = null;
56    private Scan currentScan = null;
57    private HTable htable = null;
58    private byte[] lastSuccessfulRow = null;
59    private ImmutableBytesWritable key = null;
60    private Result value = null;
61    private TaskAttemptContext context = null;
62    private Method getCounter = null;
63    private long numRestarts = 0;
64    private long timestamp;
65    private int rowcount;
66    private boolean logScannerActivity = false;
67    private int logPerRowCount = 100;
68  
69    /**
70     * Restart from survivable exceptions by creating a new scanner.
71     *
72     * @param firstRow  The first row to start at.
73     * @throws IOException When restarting fails.
74     */
75    public void restart(byte[] firstRow) throws IOException {
76      currentScan = new Scan(scan);
77      currentScan.setStartRow(firstRow);
78      currentScan.setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE,
79        Bytes.toBytes(Boolean.TRUE));
80      this.scanner = this.htable.getScanner(currentScan);
81      if (logScannerActivity) {
82        LOG.info("Current scan=" + currentScan.toString());
83        timestamp = System.currentTimeMillis();
84        rowcount = 0;
85      }
86    }
87  
88    /**
89     * In new mapreduce APIs, TaskAttemptContext has two getCounter methods
90     * Check if getCounter(String, String) method is available.
91     * @return The getCounter method or null if not available.
92     * @throws IOException
93     */
94    private Method retrieveGetCounterWithStringsParams(TaskAttemptContext context)
95    throws IOException {
96      Method m = null;
97      try {
98        m = context.getClass().getMethod("getCounter",
99          new Class [] {String.class, String.class});
100     } catch (SecurityException e) {
101       throw new IOException("Failed test for getCounter", e);
102     } catch (NoSuchMethodException e) {
103       // Ignore
104     }
105     return m;
106   }
107 
108   /**
109    * Sets the HBase table.
110    *
111    * @param htable  The {@link HTable} to scan.
112    */
113   public void setHTable(HTable htable) {
114     Configuration conf = htable.getConfiguration();
115     logScannerActivity = conf.getBoolean(
116       ScannerCallable.LOG_SCANNER_ACTIVITY, false);
117     logPerRowCount = conf.getInt(LOG_PER_ROW_COUNT, 100);
118     this.htable = htable;
119   }
120 
121   /**
122    * Sets the scan defining the actual details like columns etc.
123    *
124    * @param scan  The scan to set.
125    */
126   public void setScan(Scan scan) {
127     this.scan = scan;
128   }
129 
130   /**
131    * Build the scanner. Not done in constructor to allow for extension.
132    *
133    * @throws IOException, InterruptedException
134    */
135   public void initialize(InputSplit inputsplit,
136       TaskAttemptContext context) throws IOException,
137       InterruptedException {
138     if (context != null) {
139       this.context = context;
140       getCounter = retrieveGetCounterWithStringsParams(context);
141     }
142     restart(scan.getStartRow());
143   }
144 
145   /**
146    * Closes the split.
147    *
148    *
149    */
150   public void close() {
151     this.scanner.close();
152   }
153 
154   /**
155    * Returns the current key.
156    *
157    * @return The current key.
158    * @throws IOException
159    * @throws InterruptedException When the job is aborted.
160    */
161   public ImmutableBytesWritable getCurrentKey() throws IOException,
162       InterruptedException {
163     return key;
164   }
165 
166   /**
167    * Returns the current value.
168    *
169    * @return The current value.
170    * @throws IOException When the value is faulty.
171    * @throws InterruptedException When the job is aborted.
172    */
173   public Result getCurrentValue() throws IOException, InterruptedException {
174     return value;
175   }
176 
177 
178   /**
179    * Positions the record reader to the next record.
180    *
181    * @return <code>true</code> if there was another record.
182    * @throws IOException When reading the record failed.
183    * @throws InterruptedException When the job was aborted.
184    */
185   public boolean nextKeyValue() throws IOException, InterruptedException {
186     if (key == null) key = new ImmutableBytesWritable();
187     if (value == null) value = new Result();
188     try {
189       try {
190         value = this.scanner.next();
191         if (logScannerActivity) {
192           rowcount ++;
193           if (rowcount >= logPerRowCount) {
194             long now = System.currentTimeMillis();
195             LOG.info("Mapper took " + (now-timestamp)
196               + "ms to process " + rowcount + " rows");
197             timestamp = now;
198             rowcount = 0;
199           }
200         }
201       } catch (IOException e) {
202         // try to handle all IOExceptions by restarting
203         // the scanner, if the second call fails, it will be rethrown
204         LOG.info("recovered from " + StringUtils.stringifyException(e));
205         if (lastSuccessfulRow == null) {
206           LOG.warn("We are restarting the first next() invocation," +
207               " if your mapper has restarted a few other times like this" +
208               " then you should consider killing this job and investigate" +
209               " why it's taking so long.");
210         }
211         if (lastSuccessfulRow == null) {
212           restart(scan.getStartRow());
213         } else {
214           restart(lastSuccessfulRow);
215           scanner.next();    // skip presumed already mapped row
216         }
217         value = scanner.next();
218         numRestarts++;
219       }
220       if (value != null && value.size() > 0) {
221         key.set(value.getRow());
222         lastSuccessfulRow = key.get();
223         return true;
224       }
225 
226       updateCounters();
227       return false;
228     } catch (IOException ioe) {
229       if (logScannerActivity) {
230         long now = System.currentTimeMillis();
231         LOG.info("Mapper took " + (now-timestamp)
232           + "ms to process " + rowcount + " rows");
233         LOG.info(ioe);
234         String lastRow = lastSuccessfulRow == null ?
235           "null" : Bytes.toStringBinary(lastSuccessfulRow);
236         LOG.info("lastSuccessfulRow=" + lastRow);
237       }
238       throw ioe;
239     }
240   }
241 
242   /**
243    * If hbase runs on new version of mapreduce, RecordReader has access to
244    * counters thus can update counters based on scanMetrics.
245    * If hbase runs on old version of mapreduce, it won't be able to get
246    * access to counters and TableRecorderReader can't update counter values.
247    * @throws IOException
248    */
249   private void updateCounters() throws IOException {
250     // we can get access to counters only if hbase uses new mapreduce APIs
251     if (this.getCounter == null) {
252       return;
253     }
254 
255     byte[] serializedMetrics = currentScan.getAttribute(
256         Scan.SCAN_ATTRIBUTES_METRICS_DATA);
257     if (serializedMetrics == null || serializedMetrics.length == 0 ) {
258       return;
259     }
260 
261     DataInputBuffer in = new DataInputBuffer();
262     in.reset(serializedMetrics, 0, serializedMetrics.length);
263     ScanMetrics scanMetrics = new ScanMetrics();
264     scanMetrics.readFields(in);
265     MetricsTimeVaryingLong[] mlvs =
266       scanMetrics.getMetricsTimeVaryingLongArray();
267 
268     try {
269       for (MetricsTimeVaryingLong mlv : mlvs) {
270         Counter ct = (Counter)this.getCounter.invoke(context,
271           HBASE_COUNTER_GROUP_NAME, mlv.getName());
272         ct.increment(mlv.getCurrentIntervalValue());
273       }
274       ((Counter) this.getCounter.invoke(context, HBASE_COUNTER_GROUP_NAME,
275           "NUM_SCANNER_RESTARTS")).increment(numRestarts);
276     } catch (Exception e) {
277       LOG.debug("can't update counter." + StringUtils.stringifyException(e));
278     }
279   }
280 
281   /**
282    * The current progress of the record reader through its data.
283    *
284    * @return A number between 0.0 and 1.0, the fraction of the data read.
285    */
286   public float getProgress() {
287     // Depends on the total number of tuples
288     return 0;
289   }
290 
291 }