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 java.io.IOException;
21  import java.io.InterruptedIOException;
22  import java.util.LinkedList;
23  import java.util.concurrent.ExecutorService;
24  
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  import org.apache.hadoop.classification.InterfaceAudience;
28  import org.apache.hadoop.conf.Configuration;
29  import org.apache.hadoop.hbase.Cell;
30  import org.apache.hadoop.hbase.DoNotRetryIOException;
31  import org.apache.hadoop.hbase.HBaseConfiguration;
32  import org.apache.hadoop.hbase.HConstants;
33  import org.apache.hadoop.hbase.HRegionInfo;
34  import org.apache.hadoop.hbase.KeyValueUtil;
35  import org.apache.hadoop.hbase.NotServingRegionException;
36  import org.apache.hadoop.hbase.TableName;
37  import org.apache.hadoop.hbase.UnknownScannerException;
38  import org.apache.hadoop.hbase.client.RpcRetryingCallerFactory;
39  import org.apache.hadoop.hbase.exceptions.OutOfOrderScannerNextException;
40  import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
41  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
42  import org.apache.hadoop.hbase.protobuf.generated.MapReduceProtos;
43  import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException;
44  import org.apache.hadoop.hbase.util.Bytes;
45  
46  /**
47   * Implements the scanner interface for the HBase client.
48   * If there are multiple regions in a table, this scanner will iterate
49   * through them all.
50   */
51  @InterfaceAudience.Private
52  public class ClientScanner extends AbstractClientScanner {
53      private final Log LOG = LogFactory.getLog(this.getClass());
54      protected Scan scan;
55      protected boolean closed = false;
56      // Current region scanner is against.  Gets cleared if current region goes
57      // wonky: e.g. if it splits on us.
58      protected HRegionInfo currentRegion = null;
59      protected ScannerCallableWithReplicas callable = null;
60      protected final LinkedList<Result> cache = new LinkedList<Result>();
61      protected final int caching;
62      protected long lastNext;
63      // Keep lastResult returned successfully in case we have to reset scanner.
64      protected Result lastResult = null;
65      protected final long maxScannerResultSize;
66      private final ClusterConnection connection;
67      private final TableName tableName;
68      protected final int scannerTimeout;
69      protected boolean scanMetricsPublished = false;
70      protected RpcRetryingCaller<Result []> caller;
71      protected RpcControllerFactory rpcControllerFactory;
72      protected Configuration conf;
73      //The timeout on the primary. Applicable if there are multiple replicas for a region
74      //In that case, we will only wait for this much timeout on the primary before going
75      //to the replicas and trying the same scan. Note that the retries will still happen
76      //on each replica and the first successful results will be taken. A timeout of 0 is
77      //disallowed.
78      protected final int primaryOperationTimeout;
79      private int retries;
80      protected final ExecutorService pool;
81  
82    /**
83     * Create a new ClientScanner for the specified table Note that the passed {@link Scan}'s start
84     * row maybe changed changed.
85     * @param conf The {@link Configuration} to use.
86     * @param scan {@link Scan} to use in this scanner
87     * @param tableName The table that we wish to scan
88     * @param connection Connection identifying the cluster
89     * @throws IOException
90     */
91    public ClientScanner(final Configuration conf, final Scan scan, final TableName tableName,
92        ClusterConnection connection, RpcRetryingCallerFactory rpcFactory,
93        RpcControllerFactory controllerFactory, ExecutorService pool, int primaryOperationTimeout) throws IOException {
94        if (LOG.isTraceEnabled()) {
95          LOG.trace("Scan table=" + tableName
96              + ", startRow=" + Bytes.toStringBinary(scan.getStartRow()));
97        }
98        this.scan = scan;
99        this.tableName = tableName;
100       this.lastNext = System.currentTimeMillis();
101       this.connection = connection;
102       this.pool = pool;
103       this.primaryOperationTimeout = primaryOperationTimeout;
104       this.retries = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
105           HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
106       if (scan.getMaxResultSize() > 0) {
107         this.maxScannerResultSize = scan.getMaxResultSize();
108       } else {
109         this.maxScannerResultSize = conf.getLong(
110           HConstants.HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE_KEY,
111           HConstants.DEFAULT_HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE);
112       }
113       this.scannerTimeout = HBaseConfiguration.getInt(conf,
114         HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD,
115         HConstants.HBASE_REGIONSERVER_LEASE_PERIOD_KEY,
116         HConstants.DEFAULT_HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD);
117 
118       // check if application wants to collect scan metrics
119       initScanMetrics(scan);
120 
121       // Use the caching from the Scan.  If not set, use the default cache setting for this table.
122       if (this.scan.getCaching() > 0) {
123         this.caching = this.scan.getCaching();
124       } else {
125         this.caching = conf.getInt(
126             HConstants.HBASE_CLIENT_SCANNER_CACHING,
127             HConstants.DEFAULT_HBASE_CLIENT_SCANNER_CACHING);
128       }
129 
130       this.caller = rpcFactory.<Result[]> newCaller();
131       this.rpcControllerFactory = controllerFactory;
132 
133       this.conf = conf;
134       initializeScannerInConstruction();
135     }
136 
137     protected void initializeScannerInConstruction() throws IOException{
138       // initialize the scanner
139       nextScanner(this.caching, false);
140     }
141 
142     protected ClusterConnection getConnection() {
143       return this.connection;
144     }
145 
146     /**
147      * @return Table name
148      * @deprecated Since 0.96.0; use {@link #getTable()}
149      */
150     @Deprecated
151     protected byte [] getTableName() {
152       return this.tableName.getName();
153     }
154 
155     protected TableName getTable() {
156       return this.tableName;
157     }
158 
159     protected int getRetries() {
160       return this.retries;
161     }
162 
163     protected int getScannerTimeout() {
164       return this.scannerTimeout;
165     }
166 
167     protected Configuration getConf() {
168       return this.conf;
169     }
170 
171     protected Scan getScan() {
172       return scan;
173     }
174 
175     protected ExecutorService getPool() {
176       return pool;
177     }
178 
179     protected int getPrimaryOperationTimeout() {
180       return primaryOperationTimeout;
181     }
182 
183     protected int getCaching() {
184       return caching;
185     }
186 
187     protected long getTimestamp() {
188       return lastNext;
189     }
190 
191     // returns true if the passed region endKey
192     protected boolean checkScanStopRow(final byte [] endKey) {
193       if (this.scan.getStopRow().length > 0) {
194         // there is a stop row, check to see if we are past it.
195         byte [] stopRow = scan.getStopRow();
196         int cmp = Bytes.compareTo(stopRow, 0, stopRow.length,
197           endKey, 0, endKey.length);
198         if (cmp <= 0) {
199           // stopRow <= endKey (endKey is equals to or larger than stopRow)
200           // This is a stop.
201           return true;
202         }
203       }
204       return false; //unlikely.
205     }
206 
207     private boolean possiblyNextScanner(int nbRows, final boolean done) throws IOException {
208       // If we have just switched replica, don't go to the next scanner yet. Rather, try
209       // the scanner operations on the new replica, from the right point in the scan
210       // Note that when we switched to a different replica we left it at a point
211       // where we just did the "openScanner" with the appropriate startrow
212       if (callable != null && callable.switchedToADifferentReplica()) return true;
213       return nextScanner(nbRows, done);
214     }
215 
216     /*
217      * Gets a scanner for the next region.  If this.currentRegion != null, then
218      * we will move to the endrow of this.currentRegion.  Else we will get
219      * scanner at the scan.getStartRow().  We will go no further, just tidy
220      * up outstanding scanners, if <code>currentRegion != null</code> and
221      * <code>done</code> is true.
222      * @param nbRows
223      * @param done Server-side says we're done scanning.
224      */
225   protected boolean nextScanner(int nbRows, final boolean done)
226     throws IOException {
227       // Close the previous scanner if it's open
228       if (this.callable != null) {
229         this.callable.setClose();
230         call(scan, callable, caller, scannerTimeout);
231         this.callable = null;
232       }
233 
234       // Where to start the next scanner
235       byte [] localStartKey;
236 
237       // if we're at end of table, close and return false to stop iterating
238       if (this.currentRegion != null) {
239         byte [] endKey = this.currentRegion.getEndKey();
240         if (endKey == null ||
241             Bytes.equals(endKey, HConstants.EMPTY_BYTE_ARRAY) ||
242             checkScanStopRow(endKey) ||
243             done) {
244           close();
245           if (LOG.isTraceEnabled()) {
246             LOG.trace("Finished " + this.currentRegion);
247           }
248           return false;
249         }
250         localStartKey = endKey;
251         if (LOG.isTraceEnabled()) {
252           LOG.trace("Finished " + this.currentRegion);
253         }
254       } else {
255         localStartKey = this.scan.getStartRow();
256       }
257 
258       if (LOG.isDebugEnabled() && this.currentRegion != null) {
259         // Only worth logging if NOT first region in scan.
260         LOG.debug("Advancing internal scanner to startKey at '" +
261           Bytes.toStringBinary(localStartKey) + "'");
262       }
263       try {
264         callable = getScannerCallable(localStartKey, nbRows);
265         // Open a scanner on the region server starting at the
266         // beginning of the region
267         call(scan, callable, caller, scannerTimeout);
268         this.currentRegion = callable.getHRegionInfo();
269         if (this.scanMetrics != null) {
270           this.scanMetrics.countOfRegions.incrementAndGet();
271         }
272       } catch (IOException e) {
273         close();
274         throw e;
275       }
276       return true;
277     }
278 
279   static Result[] call(Scan scan, ScannerCallableWithReplicas callable,
280       RpcRetryingCaller<Result[]> caller, int scannerTimeout)
281       throws IOException, RuntimeException {
282     if (Thread.interrupted()) {
283       throw new InterruptedIOException();
284     }
285     // callWithoutRetries is at this layer. Within the ScannerCallableWithReplicas,
286     // we do a callWithRetries
287     return caller.callWithoutRetries(callable, scannerTimeout);
288   }
289 
290     @InterfaceAudience.Private
291     protected ScannerCallableWithReplicas getScannerCallable(byte [] localStartKey,
292         int nbRows) {
293       scan.setStartRow(localStartKey);
294       ScannerCallable s =
295           new ScannerCallable(getConnection(), getTable(), scan, this.scanMetrics,
296               this.rpcControllerFactory);
297       s.setCaching(nbRows);
298       ScannerCallableWithReplicas sr = new ScannerCallableWithReplicas(tableName, getConnection(),
299        s, pool, primaryOperationTimeout, scan,
300        retries, scannerTimeout, caching, conf, caller);
301       return sr;
302     }
303 
304     /**
305      * Publish the scan metrics. For now, we use scan.setAttribute to pass the metrics back to the
306      * application or TableInputFormat.Later, we could push it to other systems. We don't use metrics
307      * framework because it doesn't support multi-instances of the same metrics on the same machine;
308      * for scan/map reduce scenarios, we will have multiple scans running at the same time.
309      *
310      * By default, scan metrics are disabled; if the application wants to collect them, this behavior
311      * can be turned on by calling calling:
312      *
313      * scan.setAttribute(SCAN_ATTRIBUTES_METRICS_ENABLE, Bytes.toBytes(Boolean.TRUE))
314      */
315     protected void writeScanMetrics() {
316       if (this.scanMetrics == null || scanMetricsPublished) {
317         return;
318       }
319       MapReduceProtos.ScanMetrics pScanMetrics = ProtobufUtil.toScanMetrics(scanMetrics);
320       scan.setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_DATA, pScanMetrics.toByteArray());
321       scanMetricsPublished = true;
322     }
323 
324     @Override
325     public Result next() throws IOException {
326       // If the scanner is closed and there's nothing left in the cache, next is a no-op.
327       if (cache.size() == 0 && this.closed) {
328         return null;
329       }
330       if (cache.size() == 0) {
331         Result [] values = null;
332         long remainingResultSize = maxScannerResultSize;
333         int countdown = this.caching;
334         // We need to reset it if it's a new callable that was created
335         // with a countdown in nextScanner
336         callable.setCaching(this.caching);
337         // This flag is set when we want to skip the result returned.  We do
338         // this when we reset scanner because it split under us.
339         boolean skipFirst = false;
340         boolean retryAfterOutOfOrderException  = true;
341         do {
342           try {
343             if (skipFirst) {
344               // Skip only the first row (which was the last row of the last
345               // already-processed batch).
346               callable.setCaching(1);
347               values = call(scan, callable, caller, scannerTimeout);
348               // When the replica switch happens, we need to do certain operations
349               // again. The scannercallable will openScanner with the right startkey
350               // but we need to pick up from there. Bypass the rest of the loop
351               // and let the catch-up happen in the beginning of the loop as it
352               // happens for the cases where we see exceptions. Since only openScanner
353               // would have happened, values would be null
354               if (values == null && callable.switchedToADifferentReplica()) {
355                 if (this.lastResult != null) { //only skip if there was something read earlier
356                   skipFirst = true;
357                 }
358                 this.currentRegion = callable.getHRegionInfo();
359                 continue;
360               }
361               callable.setCaching(this.caching);
362               skipFirst = false;
363             }
364             // Server returns a null values if scanning is to stop.  Else,
365             // returns an empty array if scanning is to go on and we've just
366             // exhausted current region.
367             values = call(scan, callable, caller, scannerTimeout);
368             if (skipFirst && values != null && values.length == 1) {
369               skipFirst = false; // Already skipped, unset it before scanning again
370               values = call(scan, callable, caller, scannerTimeout);
371             }
372             // When the replica switch happens, we need to do certain operations
373             // again. The callable will openScanner with the right startkey
374             // but we need to pick up from there. Bypass the rest of the loop
375             // and let the catch-up happen in the beginning of the loop as it
376             // happens for the cases where we see exceptions. Since only openScanner
377             // would have happened, values would be null
378             if (values == null && callable.switchedToADifferentReplica()) {
379               if (this.lastResult != null) { //only skip if there was something read earlier
380                 skipFirst = true;
381               }
382               this.currentRegion = callable.getHRegionInfo();
383               continue;
384             }
385             retryAfterOutOfOrderException  = true;
386           } catch (DoNotRetryIOException e) {
387             // DNRIOEs are thrown to make us break out of retries.  Some types of DNRIOEs want us
388             // to reset the scanner and come back in again.
389             if (e instanceof UnknownScannerException) {
390               long timeout = lastNext + scannerTimeout;
391               // If we are over the timeout, throw this exception to the client wrapped in
392               // a ScannerTimeoutException. Else, it's because the region moved and we used the old
393               // id against the new region server; reset the scanner.
394               if (timeout < System.currentTimeMillis()) {
395                 long elapsed = System.currentTimeMillis() - lastNext;
396                 ScannerTimeoutException ex = new ScannerTimeoutException(
397                     elapsed + "ms passed since the last invocation, " +
398                         "timeout is currently set to " + scannerTimeout);
399                 ex.initCause(e);
400                 throw ex;
401               }
402             } else {
403               // If exception is any but the list below throw it back to the client; else setup
404               // the scanner and retry.
405               Throwable cause = e.getCause();
406               if ((cause != null && cause instanceof NotServingRegionException) ||
407                 (cause != null && cause instanceof RegionServerStoppedException) ||
408                 e instanceof OutOfOrderScannerNextException) {
409                 // Pass
410                 // It is easier writing the if loop test as list of what is allowed rather than
411                 // as a list of what is not allowed... so if in here, it means we do not throw.
412               } else {
413                 throw e;
414               }
415             }
416             // Else, its signal from depths of ScannerCallable that we need to reset the scanner.
417             if (this.lastResult != null) {
418               this.scan.setStartRow(this.lastResult.getRow());
419               // Skip first row returned.  We already let it out on previous
420               // invocation.
421               skipFirst = true;
422             }
423             if (e instanceof OutOfOrderScannerNextException) {
424               if (retryAfterOutOfOrderException) {
425                 retryAfterOutOfOrderException = false;
426               } else {
427                 // TODO: Why wrap this in a DNRIOE when it already is a DNRIOE?
428                 throw new DoNotRetryIOException("Failed after retry of " +
429                   "OutOfOrderScannerNextException: was there a rpc timeout?", e);
430               }
431             }
432             // Clear region.
433             this.currentRegion = null;
434             // Set this to zero so we don't try and do an rpc and close on remote server when
435             // the exception we got was UnknownScanner or the Server is going down.
436             callable = null;
437             // This continue will take us to while at end of loop where we will set up new scanner.
438             continue;
439           }
440           long currentTime = System.currentTimeMillis();
441           if (this.scanMetrics != null ) {
442             this.scanMetrics.sumOfMillisSecBetweenNexts.addAndGet(currentTime-lastNext);
443           }
444           lastNext = currentTime;
445           if (values != null && values.length > 0) {
446             for (Result rs : values) {
447               cache.add(rs);
448               for (Cell kv : rs.rawCells()) {
449                 // TODO make method in Cell or CellUtil
450                 remainingResultSize -= KeyValueUtil.ensureKeyValue(kv).heapSize();
451               }
452               countdown--;
453               this.lastResult = rs;
454             }
455           }
456           // Values == null means server-side filter has determined we must STOP
457         } while (remainingResultSize > 0 && countdown > 0 &&
458             possiblyNextScanner(countdown, values == null));
459       }
460 
461       if (cache.size() > 0) {
462         return cache.poll();
463       }
464 
465       // if we exhausted this scanner before calling close, write out the scan metrics
466       writeScanMetrics();
467       return null;
468     }
469 
470     @Override
471     public void close() {
472       if (!scanMetricsPublished) writeScanMetrics();
473       if (callable != null) {
474         callable.setClose();
475         try {
476           call(scan, callable, caller, scannerTimeout);
477         } catch (UnknownScannerException e) {
478            // We used to catch this error, interpret, and rethrow. However, we
479            // have since decided that it's not nice for a scanner's close to
480            // throw exceptions. Chances are it was just due to lease time out.
481         } catch (IOException e) {
482            /* An exception other than UnknownScanner is unexpected. */
483            LOG.warn("scanner failed to close. Exception follows: " + e);
484         }
485         callable = null;
486       }
487       closed = true;
488     }
489 }