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.client;
19  
20  import static org.apache.hadoop.hbase.client.ConnectionUtils.createScanResultCache;
21  
22  import com.google.common.annotations.VisibleForTesting;
23  
24  import java.io.IOException;
25  import java.io.InterruptedIOException;
26  import java.util.LinkedList;
27  import java.util.concurrent.ExecutorService;
28  
29  import org.apache.commons.lang.mutable.MutableBoolean;
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.apache.hadoop.conf.Configuration;
33  import org.apache.hadoop.hbase.Cell;
34  import org.apache.hadoop.hbase.CellUtil;
35  import org.apache.hadoop.hbase.DoNotRetryIOException;
36  import org.apache.hadoop.hbase.HBaseConfiguration;
37  import org.apache.hadoop.hbase.HConstants;
38  import org.apache.hadoop.hbase.HRegionInfo;
39  import org.apache.hadoop.hbase.NotServingRegionException;
40  import org.apache.hadoop.hbase.TableName;
41  import org.apache.hadoop.hbase.UnknownScannerException;
42  import org.apache.hadoop.hbase.classification.InterfaceAudience;
43  import org.apache.hadoop.hbase.client.ScannerCallable.MoreResults;
44  import org.apache.hadoop.hbase.exceptions.OutOfOrderScannerNextException;
45  import org.apache.hadoop.hbase.exceptions.ScannerResetException;
46  import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
47  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
48  import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException;
49  import org.apache.hadoop.hbase.util.Bytes;
50  
51  /**
52   * Implements the scanner interface for the HBase client. If there are multiple regions in a table,
53   * this scanner will iterate through them all.
54   */
55  @InterfaceAudience.Private
56  public abstract class ClientScanner extends AbstractClientScanner {
57    private static final Log LOG = LogFactory.getLog(ClientScanner.class);
58  
59    protected final Scan scan;
60    protected boolean closed = false;
61    // Current region scanner is against. Gets cleared if current region goes
62    // wonky: e.g. if it splits on us.
63    protected HRegionInfo currentRegion = null;
64    protected ScannerCallableWithReplicas callable = null;
65    protected final LinkedList<Result> cache = new LinkedList<Result>();
66    private final ScanResultCache scanResultCache;
67    protected final int caching;
68    protected long lastNext;
69    // Keep lastResult returned successfully in case we have to reset scanner.
70    protected Result lastResult = null;
71    protected final long maxScannerResultSize;
72    private final ClusterConnection connection;
73    private final TableName tableName;
74    protected final int scannerTimeout;
75    protected boolean scanMetricsPublished = false;
76    protected RpcRetryingCaller<Result[]> caller;
77    protected RpcControllerFactory rpcControllerFactory;
78    protected Configuration conf;
79    // The timeout on the primary. Applicable if there are multiple replicas for a region
80    // In that case, we will only wait for this much timeout on the primary before going
81    // to the replicas and trying the same scan. Note that the retries will still happen
82    // on each replica and the first successful results will be taken. A timeout of 0 is
83    // disallowed.
84    protected final int primaryOperationTimeout;
85    private int retries;
86    protected final ExecutorService pool;
87  
88    /**
89     * Create a new ClientScanner for the specified table Note that the passed {@link Scan}'s start
90     * row maybe changed changed.
91     * @param conf The {@link Configuration} to use.
92     * @param scan {@link Scan} to use in this scanner
93     * @param tableName The table that we wish to scan
94     * @param connection Connection identifying the cluster
95     * @throws IOException
96     */
97    public ClientScanner(final Configuration conf, final Scan scan, final TableName tableName,
98        ClusterConnection connection, RpcRetryingCallerFactory rpcFactory,
99        RpcControllerFactory controllerFactory, ExecutorService pool, int primaryOperationTimeout)
100       throws IOException {
101     if (LOG.isTraceEnabled()) {
102       LOG.trace(
103         "Scan table=" + tableName + ", startRow=" + Bytes.toStringBinary(scan.getStartRow()));
104     }
105     this.scan = scan;
106     this.tableName = tableName;
107     this.lastNext = System.currentTimeMillis();
108     this.connection = connection;
109     this.pool = pool;
110     this.primaryOperationTimeout = primaryOperationTimeout;
111     this.retries = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
112       HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
113     if (scan.getMaxResultSize() > 0) {
114       this.maxScannerResultSize = scan.getMaxResultSize();
115     } else {
116       this.maxScannerResultSize = conf.getLong(HConstants.HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE_KEY,
117         HConstants.DEFAULT_HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE);
118     }
119     this.scannerTimeout =
120         HBaseConfiguration.getInt(conf, HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD,
121           HConstants.HBASE_REGIONSERVER_LEASE_PERIOD_KEY,
122           HConstants.DEFAULT_HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD);
123 
124     // check if application wants to collect scan metrics
125     initScanMetrics(scan);
126 
127     // Use the caching from the Scan. If not set, use the default cache setting for this table.
128     if (this.scan.getCaching() > 0) {
129       this.caching = this.scan.getCaching();
130     } else {
131       this.caching = conf.getInt(HConstants.HBASE_CLIENT_SCANNER_CACHING,
132         HConstants.DEFAULT_HBASE_CLIENT_SCANNER_CACHING);
133     }
134 
135     this.caller = rpcFactory.<Result[]> newCaller();
136     this.rpcControllerFactory = controllerFactory;
137 
138     this.conf = conf;
139     this.scanResultCache = createScanResultCache(scan);
140   }
141 
142   protected ClusterConnection getConnection() {
143     return this.connection;
144   }
145 
146   /**
147    * @return Table name
148    * @deprecated As of release 0.96
149    *             (<a href="https://issues.apache.org/jira/browse/HBASE-9508">HBASE-9508</a>). This
150    *             will be removed in HBase 2.0.0. Use {@link #getTable()}.
151    */
152   @Deprecated
153   protected byte[] getTableName() {
154     return this.tableName.getName();
155   }
156 
157   protected TableName getTable() {
158     return this.tableName;
159   }
160 
161   protected int getRetries() {
162     return this.retries;
163   }
164 
165   protected int getScannerTimeout() {
166     return this.scannerTimeout;
167   }
168 
169   protected Configuration getConf() {
170     return this.conf;
171   }
172 
173   protected Scan getScan() {
174     return scan;
175   }
176 
177   protected ExecutorService getPool() {
178     return pool;
179   }
180 
181   protected int getPrimaryOperationTimeout() {
182     return primaryOperationTimeout;
183   }
184 
185   protected int getCaching() {
186     return caching;
187   }
188 
189   protected long getTimestamp() {
190     return lastNext;
191   }
192 
193   @VisibleForTesting
194   protected long getMaxResultSize() {
195     return maxScannerResultSize;
196   }
197 
198   private void closeScanner() throws IOException {
199     if (this.callable != null) {
200       this.callable.setClose();
201       call(callable, caller, scannerTimeout, false);
202       this.callable = null;
203     }
204   }
205 
206   /**
207    * Will be called in moveToNextRegion when currentRegion is null. Abstract because for normal
208    * scan, we will start next scan from the endKey of the currentRegion, and for reversed scan, we
209    * will start next scan from the startKey of the currentRegion.
210    * @return {@code false} if we have reached the stop row. Otherwise {@code true}.
211    */
212   protected abstract boolean setNewStartKey();
213 
214   /**
215    * Will be called in moveToNextRegion to create ScannerCallable. Abstract because for reversed
216    * scan we need to create a ReversedScannerCallable.
217    */
218   protected abstract ScannerCallable createScannerCallable();
219 
220   /**
221    * Close the previous scanner and create a new ScannerCallable for the next scanner.
222    * <p>
223    * Marked as protected only because TestClientScanner need to override this method.
224    * @return false if we should terminate the scan. Otherwise
225    */
226   @VisibleForTesting
227   protected boolean moveToNextRegion() {
228     // Close the previous scanner if it's open
229     try {
230       closeScanner();
231     } catch (IOException e) {
232       // not a big deal continue
233       if (LOG.isDebugEnabled()) {
234         LOG.debug("close scanner for " + currentRegion + " failed", e);
235       }
236     }
237     if (currentRegion != null) {
238       if (!setNewStartKey()) {
239         return false;
240       }
241       scan.resetMvccReadPoint();
242       if (LOG.isTraceEnabled()) {
243         LOG.trace("Finished " + this.currentRegion);
244       }
245     }
246     if (LOG.isDebugEnabled() && this.currentRegion != null) {
247       // Only worth logging if NOT first region in scan.
248       LOG.debug(
249         "Advancing internal scanner to startKey at '" + Bytes.toStringBinary(scan.getStartRow()) +
250             "', " + (scan.includeStartRow() ? "inclusive" : "exclusive"));
251     }
252     // clear the current region, we will set a new value to it after the first call of the new
253     // callable.
254     this.currentRegion = null;
255     this.callable =
256         new ScannerCallableWithReplicas(getTable(), getConnection(), createScannerCallable(), pool,
257             primaryOperationTimeout, scan, getRetries(), scannerTimeout, caching, conf, caller);
258     this.callable.setCaching(this.caching);
259     if (this.scanMetrics != null) {
260       this.scanMetrics.countOfRegions.incrementAndGet();
261     }
262     return true;
263   }
264 
265   @VisibleForTesting
266   boolean isAnyRPCcancelled() {
267     return callable.isAnyRPCcancelled();
268   }
269 
270   private Result[] call(ScannerCallableWithReplicas callable, RpcRetryingCaller<Result[]> caller,
271       int scannerTimeout, boolean updateCurrentRegion) throws IOException {
272     if (Thread.interrupted()) {
273       throw new InterruptedIOException();
274     }
275     // callWithoutRetries is at this layer. Within the ScannerCallableWithReplicas,
276     // we do a callWithRetries
277     Result[] rrs = caller.callWithoutRetries(callable, scannerTimeout);
278     if (currentRegion == null && updateCurrentRegion) {
279       currentRegion = callable.getHRegionInfo();
280     }
281     return rrs;
282   }
283 
284   /**
285    * Publish the scan metrics. For now, we use scan.setAttribute to pass the metrics back to the
286    * application or TableInputFormat.Later, we could push it to other systems. We don't use metrics
287    * framework because it doesn't support multi-instances of the same metrics on the same machine;
288    * for scan/map reduce scenarios, we will have multiple scans running at the same time. By
289    * default, scan metrics are disabled; if the application wants to collect them, this behavior can
290    * be turned on by calling calling {@link Scan#setScanMetricsEnabled(boolean)}
291    */
292   protected void writeScanMetrics() {
293     if (this.scanMetrics == null || scanMetricsPublished) {
294       return;
295     }
296     // Publish ScanMetrics to the Scan Object.
297     // As we have claimed in the comment of Scan.getScanMetrics, this relies on that user will not
298     // call ResultScanner.getScanMetrics and reset the ScanMetrics. Otherwise the metrics published
299     // to Scan will be messed up.
300     scan.setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_DATA,
301       ProtobufUtil.toScanMetrics(scanMetrics, false).toByteArray());
302     scanMetricsPublished = true;
303   }
304 
305   @Override
306   public Result next() throws IOException {
307     // If the scanner is closed and there's nothing left in the cache, next is a no-op.
308     if (cache.size() == 0 && this.closed) {
309       return null;
310     }
311     if (cache.size() == 0) {
312       loadCache();
313     }
314 
315     if (cache.size() > 0) {
316       return cache.poll();
317     }
318 
319     // if we exhausted this scanner before calling close, write out the scan metrics
320     writeScanMetrics();
321     return null;
322   }
323 
324   @VisibleForTesting
325   public int getCacheSize() {
326     return cache != null ? cache.size() : 0;
327   }
328 
329   private boolean scanExhausted(Result[] values) {
330     return callable.moreResultsForScan() == MoreResults.NO;
331   }
332 
333   private boolean regionExhausted(Result[] values) {
334     // 1. Not a heartbeat message and we get nothing, this means the region is exhausted. And in the
335     // old time we always return empty result for a open scanner operation so we add a check here to
336     // keep compatible with the old logic. Should remove the isOpenScanner in the future.
337     // 2. Server tells us that it has no more results for this region.
338     return (values.length == 0 && !callable.isHeartbeatMessage()) ||
339         callable.moreResultsInRegion() == MoreResults.NO;
340   }
341 
342   private void closeScannerIfExhausted(boolean exhausted) throws IOException {
343     if (exhausted) {
344       closeScanner();
345     }
346   }
347 
348   private void handleScanError(DoNotRetryIOException e,
349       MutableBoolean retryAfterOutOfOrderException, int retriesLeft) throws DoNotRetryIOException {
350     // An exception was thrown which makes any partial results that we were collecting
351     // invalid. The scanner will need to be reset to the beginning of a row.
352     scanResultCache.clear();
353 
354     // Unfortunately, DNRIOE is used in two different semantics.
355     // (1) The first is to close the client scanner and bubble up the exception all the way
356     // to the application. This is preferred when the exception is really un-recoverable
357     // (like CorruptHFileException, etc). Plain DoNotRetryIOException also falls into this
358     // bucket usually.
359     // (2) Second semantics is to close the current region scanner only, but continue the
360     // client scanner by overriding the exception. This is usually UnknownScannerException,
361     // OutOfOrderScannerNextException, etc where the region scanner has to be closed, but the
362     // application-level ClientScanner has to continue without bubbling up the exception to
363     // the client. See RSRpcServices to see how it throws DNRIOE's.
364     // See also: HBASE-16604, HBASE-17187
365 
366     // If exception is any but the list below throw it back to the client; else setup
367     // the scanner and retry.
368     Throwable cause = e.getCause();
369     if ((cause != null && cause instanceof NotServingRegionException) ||
370         (cause != null && cause instanceof RegionServerStoppedException) ||
371         e instanceof OutOfOrderScannerNextException || e instanceof UnknownScannerException ||
372         e instanceof ScannerResetException) {
373       // Pass. It is easier writing the if loop test as list of what is allowed rather than
374       // as a list of what is not allowed... so if in here, it means we do not throw.
375       if (retriesLeft <= 0) {
376         throw e; // no more retries
377       }
378     } else {
379       throw e;
380     }
381 
382     // Else, its signal from depths of ScannerCallable that we need to reset the scanner.
383     if (this.lastResult != null) {
384       // The region has moved. We need to open a brand new scanner at the new location.
385       // Reset the startRow to the row we've seen last so that the new scanner starts at
386       // the correct row. Otherwise we may see previously returned rows again.
387       // If the lastRow is not partial, then we should start from the next row. As now we can
388       // exclude the start row, the logic here is the same for both normal scan and reversed scan.
389       // If lastResult is partial then include it, otherwise exclude it.
390       scan.withStartRow(lastResult.getRow(), lastResult.mayHaveMoreCellsInRow());
391     }
392     if (e instanceof OutOfOrderScannerNextException) {
393       if (retryAfterOutOfOrderException.isTrue()) {
394         retryAfterOutOfOrderException.setValue(false);
395       } else {
396         // TODO: Why wrap this in a DNRIOE when it already is a DNRIOE?
397         throw new DoNotRetryIOException(
398             "Failed after retry of OutOfOrderScannerNextException: was there a rpc timeout?", e);
399       }
400     }
401     // Clear region.
402     this.currentRegion = null;
403     // Set this to zero so we don't try and do an rpc and close on remote server when
404     // the exception we got was UnknownScanner or the Server is going down.
405     callable = null;
406   }
407 
408   /**
409    * Contact the servers to load more {@link Result}s in the cache.
410    */
411   protected void loadCache() throws IOException {
412     // check if scanner was closed during previous prefetch
413     if (closed) {
414       return;
415     }
416     long remainingResultSize = maxScannerResultSize;
417     int countdown = this.caching;
418     // This is possible if we just stopped at the boundary of a region in the previous call.
419     if (callable == null) {
420       if (!moveToNextRegion()) {
421         return;
422       }
423     }
424     // This flag is set when we want to skip the result returned. We do
425     // this when we reset scanner because it split under us.
426     MutableBoolean retryAfterOutOfOrderException = new MutableBoolean(true);
427     // Even if we are retrying due to UnknownScannerException, ScannerResetException, etc. we should
428     // make sure that we are not retrying indefinitely.
429     int retriesLeft = getRetries();
430     for (;;) {
431       Result[] values;
432       try {
433         // Server returns a null values if scanning is to stop. Else,
434         // returns an empty array if scanning is to go on and we've just
435         // exhausted current region.
436         // now we will also fetch data when openScanner, so do not make a next call again if values
437         // is already non-null.
438         values = call(callable, caller, scannerTimeout, true);
439         // When the replica switch happens, we need to do certain operations again.
440         // The callable will openScanner with the right startkey but we need to pick up
441         // from there. Bypass the rest of the loop and let the catch-up happen in the beginning
442         // of the loop as it happens for the cases where we see exceptions.
443         if (callable.switchedToADifferentReplica()) {
444           // Any accumulated partial results are no longer valid since the callable will
445           // openScanner with the correct startkey and we must pick up from there
446           scanResultCache.clear();
447           this.currentRegion = callable.getHRegionInfo();
448         }
449         retryAfterOutOfOrderException.setValue(true);
450       } catch (DoNotRetryIOException e) {
451         handleScanError(e, retryAfterOutOfOrderException, retriesLeft--);
452         // reopen the scanner
453         if (!moveToNextRegion()) {
454           break;
455         }
456         continue;
457       }
458       long currentTime = System.currentTimeMillis();
459       if (this.scanMetrics != null) {
460         this.scanMetrics.sumOfMillisSecBetweenNexts.addAndGet(currentTime - lastNext);
461       }
462       lastNext = currentTime;
463       // Groom the array of Results that we received back from the server before adding that
464       // Results to the scanner's cache. If partial results are not allowed to be seen by the
465       // caller, all book keeping will be performed within this method.
466       int numberOfCompleteRowsBefore = scanResultCache.numberOfCompleteRows();
467       Result[] resultsToAddToCache =
468           scanResultCache.addAndGet(values, callable.isHeartbeatMessage());
469       int numberOfCompleteRows =
470           scanResultCache.numberOfCompleteRows() - numberOfCompleteRowsBefore;
471       if (resultsToAddToCache.length > 0) {
472         for (Result rs : resultsToAddToCache) {
473           cache.add(rs);
474           for (Cell cell : rs.rawCells()) {
475             remainingResultSize -= CellUtil.estimatedHeapSizeOf(cell);
476           }
477           countdown--;
478           this.lastResult = rs;
479         }
480       }
481 
482       if (scan.getLimit() > 0) {
483         int newLimit = scan.getLimit() - numberOfCompleteRows;
484         assert newLimit >= 0;
485         scan.setLimit(newLimit);
486       }
487       if (scanExhausted(values)) {
488         closeScanner();
489         closed = true;
490         break;
491       }
492       boolean regionExhausted = regionExhausted(values);
493       if (callable.isHeartbeatMessage()) {
494         if (!cache.isEmpty()) {
495           // Caller of this method just wants a Result. If we see a heartbeat message, it means
496           // processing of the scan is taking a long time server side. Rather than continue to
497           // loop until a limit (e.g. size or caching) is reached, break out early to avoid causing
498           // unnecesary delays to the caller
499           if (LOG.isTraceEnabled()) {
500             LOG.trace("Heartbeat message received and cache contains Results." +
501                 " Breaking out of scan loop");
502           }
503           // we know that the region has not been exhausted yet so just break without calling
504           // closeScannerIfExhausted
505           break;
506         }
507       }
508       if (cache.isEmpty() && !closed && scan.isNeedCursorResult()) {
509         if (callable.isHeartbeatMessage() && callable.getCursor() != null) {
510           // Use cursor row key from server
511           cache.add(Result.createCursorResult(callable.getCursor()));
512           break;
513         }
514         if (values.length > 0) {
515           // It is size limit exceed and we need return the last Result's row.
516           // When user setBatch and the scanner is reopened, the server may return Results that
517           // user has seen and the last Result can not be seen because the number is not enough.
518           // So the row keys of results may not be same, we must use the last one.
519           cache.add(Result.createCursorResult(new Cursor(values[values.length - 1].getRow())));
520           break;
521         }
522       }
523       if (countdown <= 0) {
524         // we have enough result.
525         closeScannerIfExhausted(regionExhausted);
526         break;
527       }
528       if (remainingResultSize <= 0) {
529         if (!cache.isEmpty()) {
530           closeScannerIfExhausted(regionExhausted);
531           break;
532         } else {
533           // we have reached the max result size but we still can not find anything to return to the
534           // user. Reset the maxResultSize and try again.
535           remainingResultSize = maxScannerResultSize;
536         }
537       }
538       // we are done with the current region
539       if (regionExhausted) {
540         if (!moveToNextRegion()) {
541           break;
542         }
543       }
544     }
545   }
546 
547   @Override
548   public void close() {
549     if (!scanMetricsPublished) writeScanMetrics();
550     if (callable != null) {
551       callable.setClose();
552       try {
553         call(callable, caller, scannerTimeout, false);
554       } catch (UnknownScannerException e) {
555         // We used to catch this error, interpret, and rethrow. However, we
556         // have since decided that it's not nice for a scanner's close to
557         // throw exceptions. Chances are it was just due to lease time out.
558       } catch (IOException e) {
559         /* An exception other than UnknownScanner is unexpected. */
560         LOG.warn("scanner failed to close. Exception follows: " + e);
561       }
562       callable = null;
563     }
564     closed = true;
565   }
566 
567   @Override
568   public boolean renewLease() {
569     if (callable != null) {
570       // do not return any rows, do not advance the scanner
571       callable.setRenew(true);
572       try {
573         this.caller.callWithoutRetries(callable, this.scannerTimeout);
574       } catch (Exception e) {
575         return false;
576       } finally {
577         callable.setRenew(false);
578       }
579       return true;
580     }
581     return false;
582   }
583 }