1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
53
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
62
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
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
80
81
82
83
84 protected final int primaryOperationTimeout;
85 private int retries;
86 protected final ExecutorService pool;
87
88
89
90
91
92
93
94
95
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
125 initScanMetrics(scan);
126
127
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
148
149
150
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
208
209
210
211
212 protected abstract boolean setNewStartKey();
213
214
215
216
217
218 protected abstract ScannerCallable createScannerCallable();
219
220
221
222
223
224
225
226 @VisibleForTesting
227 protected boolean moveToNextRegion() {
228
229 try {
230 closeScanner();
231 } catch (IOException e) {
232
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
248 LOG.debug(
249 "Advancing internal scanner to startKey at '" + Bytes.toStringBinary(scan.getStartRow()) +
250 "', " + (scan.includeStartRow() ? "inclusive" : "exclusive"));
251 }
252
253
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
276
277 Result[] rrs = caller.callWithoutRetries(callable, scannerTimeout);
278 if (currentRegion == null && updateCurrentRegion) {
279 currentRegion = callable.getHRegionInfo();
280 }
281 return rrs;
282 }
283
284
285
286
287
288
289
290
291
292 protected void writeScanMetrics() {
293 if (this.scanMetrics == null || scanMetricsPublished) {
294 return;
295 }
296
297
298
299
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
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
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
335
336
337
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
351
352 scanResultCache.clear();
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
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
374
375 if (retriesLeft <= 0) {
376 throw e;
377 }
378 } else {
379 throw e;
380 }
381
382
383 if (this.lastResult != null) {
384
385
386
387
388
389
390 scan.withStartRow(lastResult.getRow(), lastResult.mayHaveMoreCellsInRow());
391 }
392 if (e instanceof OutOfOrderScannerNextException) {
393 if (retryAfterOutOfOrderException.isTrue()) {
394 retryAfterOutOfOrderException.setValue(false);
395 } else {
396
397 throw new DoNotRetryIOException(
398 "Failed after retry of OutOfOrderScannerNextException: was there a rpc timeout?", e);
399 }
400 }
401
402 this.currentRegion = null;
403
404
405 callable = null;
406 }
407
408
409
410
411 protected void loadCache() throws IOException {
412
413 if (closed) {
414 return;
415 }
416 long remainingResultSize = maxScannerResultSize;
417 int countdown = this.caching;
418
419 if (callable == null) {
420 if (!moveToNextRegion()) {
421 return;
422 }
423 }
424
425
426 MutableBoolean retryAfterOutOfOrderException = new MutableBoolean(true);
427
428
429 int retriesLeft = getRetries();
430 for (;;) {
431 Result[] values;
432 try {
433
434
435
436
437
438 values = call(callable, caller, scannerTimeout, true);
439
440
441
442
443 if (callable.switchedToADifferentReplica()) {
444
445
446 scanResultCache.clear();
447 this.currentRegion = callable.getHRegionInfo();
448 }
449 retryAfterOutOfOrderException.setValue(true);
450 } catch (DoNotRetryIOException e) {
451 handleScanError(e, retryAfterOutOfOrderException, retriesLeft--);
452
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
464
465
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
496
497
498
499 if (LOG.isTraceEnabled()) {
500 LOG.trace("Heartbeat message received and cache contains Results." +
501 " Breaking out of scan loop");
502 }
503
504
505 break;
506 }
507 }
508 if (cache.isEmpty() && !closed && scan.isNeedCursorResult()) {
509 if (callable.isHeartbeatMessage() && callable.getCursor() != null) {
510
511 cache.add(Result.createCursorResult(callable.getCursor()));
512 break;
513 }
514 if (values.length > 0) {
515
516
517
518
519 cache.add(Result.createCursorResult(new Cursor(values[values.length - 1].getRow())));
520 break;
521 }
522 }
523 if (countdown <= 0) {
524
525 closeScannerIfExhausted(regionExhausted);
526 break;
527 }
528 if (remainingResultSize <= 0) {
529 if (!cache.isEmpty()) {
530 closeScannerIfExhausted(regionExhausted);
531 break;
532 } else {
533
534
535 remainingResultSize = maxScannerResultSize;
536 }
537 }
538
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
556
557
558 } catch (IOException e) {
559
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
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 }