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