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.regionserver;
19
20 import java.util.List;
21
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24 import org.apache.hadoop.hbase.HBaseInterfaceAudience;
25 import org.apache.hadoop.hbase.classification.InterfaceAudience;
26 import org.apache.hadoop.hbase.classification.InterfaceStability;
27 import org.apache.hadoop.hbase.client.metrics.ServerSideScanMetrics;
28
29 /**
30 * ScannerContext instances encapsulate limit tracking AND progress towards those limits during
31 * invocations of {@link InternalScanner#next(java.util.List)} and
32 * {@link RegionScanner#next(java.util.List)}.
33 * <p>
34 * A ScannerContext instance should be updated periodically throughout execution whenever progress
35 * towards a limit has been made. Each limit can be checked via the appropriate checkLimit method.
36 * <p>
37 * Once a limit has been reached, the scan will stop. The invoker of
38 * {@link InternalScanner#next(java.util.List)} or {@link RegionScanner#next(java.util.List)} can
39 * use the appropriate check*Limit methods to see exactly which limits have been reached.
40 * Alternatively, {@link #checkAnyLimitReached(LimitScope)} is provided to see if ANY limit was
41 * reached
42 * <p>
43 * {@link NoLimitScannerContext#NO_LIMIT} is an immutable static definition that can be used
44 * whenever a {@link ScannerContext} is needed but limits do not need to be enforced.
45 * <p>
46 * NOTE: It is important that this class only ever expose setter methods that can be safely skipped
47 * when limits should be NOT enforced. This is because of the necessary immutability of the class
48 * {@link NoLimitScannerContext}. If a setter cannot be safely skipped, the immutable nature of
49 * {@link NoLimitScannerContext} will lead to incorrect behavior.
50 */
51 @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.COPROC)
52 @InterfaceStability.Evolving
53 public class ScannerContext {
54 private static final Log LOG = LogFactory.getLog(ScannerContext.class);
55
56 /**
57 * Two sets of the same fields. One for the limits, another for the progress towards those limits
58 */
59 LimitFields limits;
60 LimitFields progress;
61
62 /**
63 * The state of the scanner after the invocation of {@link InternalScanner#next(java.util.List)}
64 * or {@link RegionScanner#next(java.util.List)}.
65 */
66 NextState scannerState;
67 private static final NextState DEFAULT_STATE = NextState.MORE_VALUES;
68
69 /**
70 * Used as an indication to invocations of {@link InternalScanner#next(java.util.List)} and
71 * {@link RegionScanner#next(java.util.List)} that, if true, the progress tracked within this
72 * {@link ScannerContext} instance should be considered while evaluating the limits. Useful for
73 * enforcing a set of limits across multiple calls (i.e. the limit may not be reached in a single
74 * invocation, but any progress made should be considered in future invocations)
75 * <p>
76 * Defaulting this value to false means that, by default, any tracked progress will be wiped clean
77 * on invocations to {@link InternalScanner#next(java.util.List)} and
78 * {@link RegionScanner#next(java.util.List)} and the call will be treated as though no progress
79 * has been made towards the limits so far.
80 * <p>
81 * This is an important mechanism. Users of Internal/Region scanners expect that they can define
82 * some limits and then repeatedly invoke {@link InternalScanner#next(List)} or
83 * {@link RegionScanner#next(List)} where each invocation respects these limits separately.
84 * <p>
85 * For example: <code><pre>
86 * ScannerContext context = new ScannerContext.newBuilder().setBatchLimit(5).build();
87 * RegionScanner scanner = ...
88 * List<Cell> results = new ArrayList<Cell>();
89 * while(scanner.next(results, context)) {
90 * // Do something with a batch of 5 cells
91 * }
92 * </pre></code> However, in the case of RPCs, the server wants to be able to define a set of
93 * limits for a particular RPC request and have those limits respected across multiple
94 * invocations. This means that the progress made towards the limits in earlier calls will be
95 * saved and considered in future invocations
96 */
97 boolean keepProgress;
98 private static boolean DEFAULT_KEEP_PROGRESS = false;
99
100 /**
101 * Tracks the relevant server side metrics during scans. null when metrics should not be tracked
102 */
103 final ServerSideScanMetrics metrics;
104
105 ScannerContext(boolean keepProgress, LimitFields limitsToCopy, boolean trackMetrics) {
106 this.limits = new LimitFields();
107 if (limitsToCopy != null) this.limits.copy(limitsToCopy);
108
109 // Progress fields are initialized to 0
110 progress = new LimitFields(0, LimitFields.DEFAULT_SCOPE, 0, LimitFields.DEFAULT_SCOPE, 0);
111
112 this.keepProgress = keepProgress;
113 this.scannerState = DEFAULT_STATE;
114 this.metrics = trackMetrics ? new ServerSideScanMetrics() : null;
115 }
116
117 boolean isTrackingMetrics() {
118 return this.metrics != null;
119 }
120
121 /**
122 * Get the metrics instance. Should only be called after a call to {@link #isTrackingMetrics()}
123 * has been made to confirm that metrics are indeed being tracked.
124 * @return {@link ServerSideScanMetrics} instance that is tracking metrics for this scan
125 */
126 ServerSideScanMetrics getMetrics() {
127 assert isTrackingMetrics();
128 return this.metrics;
129 }
130
131 /**
132 * @return true if the progress tracked so far in this instance will be considered during an
133 * invocation of {@link InternalScanner#next(java.util.List)} or
134 * {@link RegionScanner#next(java.util.List)}. false when the progress tracked so far
135 * should not be considered and should instead be wiped away via {@link #clearProgress()}
136 */
137 boolean getKeepProgress() {
138 return keepProgress;
139 }
140
141 void setKeepProgress(boolean keepProgress) {
142 this.keepProgress = keepProgress;
143 }
144
145 /**
146 * Progress towards the batch limit has been made. Increment internal tracking of batch progress
147 */
148 void incrementBatchProgress(int batch) {
149 int currentBatch = progress.getBatch();
150 progress.setBatch(currentBatch + batch);
151 }
152
153 /**
154 * Progress towards the size limit has been made. Increment internal tracking of size progress
155 */
156 void incrementSizeProgress(long size) {
157 long currentSize = progress.getSize();
158 progress.setSize(currentSize + size);
159 }
160
161 /**
162 * Update the time progress with {@link System#currentTimeMillis()}
163 */
164 void updateTimeProgress() {
165 progress.setTime(System.currentTimeMillis());
166 }
167
168 int getBatchProgress() {
169 return progress.getBatch();
170 }
171
172 long getSizeProgress() {
173 return progress.getSize();
174 }
175
176 long getTimeProgress() {
177 return progress.getTime();
178 }
179
180 void setProgress(int batchProgress, long sizeProgress, long timeProgress) {
181 setBatchProgress(batchProgress);
182 setSizeProgress(sizeProgress);
183 setTimeProgress(timeProgress);
184 }
185
186 void setSizeProgress(long sizeProgress) {
187 progress.setSize(sizeProgress);
188 }
189
190 void setBatchProgress(int batchProgress) {
191 progress.setBatch(batchProgress);
192 }
193
194 void setTimeProgress(long timeProgress) {
195 progress.setTime(timeProgress);
196 }
197
198 /**
199 * Clear away any progress that has been made so far. All progress fields are reset to initial
200 * values
201 */
202 void clearProgress() {
203 progress.setFields(0, LimitFields.DEFAULT_SCOPE, 0, LimitFields.DEFAULT_SCOPE, 0);
204 }
205
206 /**
207 * Note that this is not a typical setter. This setter returns the {@link NextState} that was
208 * passed in so that methods can be invoked against the new state. Furthermore, this pattern
209 * allows the {@link NoLimitScannerContext} to cleanly override this setter and simply return the
210 * new state, thus preserving the immutability of {@link NoLimitScannerContext}
211 * @param state
212 * @return The state that was passed in.
213 */
214 NextState setScannerState(NextState state) {
215 if (!NextState.isValidState(state)) {
216 throw new IllegalArgumentException("Cannot set to invalid state: " + state);
217 }
218
219 this.scannerState = state;
220 return state;
221 }
222
223 /**
224 * @return true when a partial result is formed. A partial result is formed when a limit is
225 * reached in the middle of a row.
226 */
227 boolean partialResultFormed() {
228 return scannerState == NextState.SIZE_LIMIT_REACHED_MID_ROW
229 || scannerState == NextState.TIME_LIMIT_REACHED_MID_ROW;
230 }
231
232 /**
233 * @param checkerScope
234 * @return true if the batch limit can be enforced in the checker's scope
235 */
236 boolean hasBatchLimit(LimitScope checkerScope) {
237 return limits.canEnforceBatchLimitFromScope(checkerScope) && limits.getBatch() > 0;
238 }
239
240 /**
241 * @param checkerScope
242 * @return true if the size limit can be enforced in the checker's scope
243 */
244 boolean hasSizeLimit(LimitScope checkerScope) {
245 return limits.canEnforceSizeLimitFromScope(checkerScope) && limits.getSize() > 0;
246 }
247
248 /**
249 * @param checkerScope
250 * @return true if the time limit can be enforced in the checker's scope
251 */
252 boolean hasTimeLimit(LimitScope checkerScope) {
253 return limits.canEnforceTimeLimitFromScope(checkerScope) && limits.getTime() > 0;
254 }
255
256 /**
257 * @param checkerScope
258 * @return true if any limit can be enforced within the checker's scope
259 */
260 boolean hasAnyLimit(LimitScope checkerScope) {
261 return hasBatchLimit(checkerScope) || hasSizeLimit(checkerScope) || hasTimeLimit(checkerScope);
262 }
263
264 /**
265 * @param scope The scope in which the size limit will be enforced
266 */
267 void setSizeLimitScope(LimitScope scope) {
268 limits.setSizeScope(scope);
269 }
270
271 /**
272 * @param scope The scope in which the time limit will be enforced
273 */
274 void setTimeLimitScope(LimitScope scope) {
275 limits.setTimeScope(scope);
276 }
277
278 int getBatchLimit() {
279 return limits.getBatch();
280 }
281
282 long getSizeLimit() {
283 return limits.getSize();
284 }
285
286 long getTimeLimit() {
287 return limits.getTime();
288 }
289
290 /**
291 * @param checkerScope The scope that the limit is being checked from
292 * @return true when the limit is enforceable from the checker's scope and it has been reached
293 */
294 boolean checkBatchLimit(LimitScope checkerScope) {
295 return hasBatchLimit(checkerScope) && progress.getBatch() >= limits.getBatch();
296 }
297
298 /**
299 * @param checkerScope The scope that the limit is being checked from
300 * @return true when the limit is enforceable from the checker's scope and it has been reached
301 */
302 boolean checkSizeLimit(LimitScope checkerScope) {
303 return hasSizeLimit(checkerScope) && progress.getSize() >= limits.getSize();
304 }
305
306 /**
307 * @param checkerScope The scope that the limit is being checked from. The time limit is always
308 * checked against {@link System#currentTimeMillis()}
309 * @return true when the limit is enforceable from the checker's scope and it has been reached
310 */
311 boolean checkTimeLimit(LimitScope checkerScope) {
312 return hasTimeLimit(checkerScope) && progress.getTime() >= limits.getTime();
313 }
314
315 /**
316 * @param checkerScope The scope that the limits are being checked from
317 * @return true when some limit is enforceable from the checker's scope and it has been reached
318 */
319 boolean checkAnyLimitReached(LimitScope checkerScope) {
320 return checkSizeLimit(checkerScope) || checkBatchLimit(checkerScope)
321 || checkTimeLimit(checkerScope);
322 }
323
324 @Override
325 public String toString() {
326 StringBuilder sb = new StringBuilder();
327 sb.append("{");
328
329 sb.append("limits:");
330 sb.append(limits);
331
332 sb.append(", progress:");
333 sb.append(progress);
334
335 sb.append(", keepProgress:");
336 sb.append(keepProgress);
337
338 sb.append(", state:");
339 sb.append(scannerState);
340
341 sb.append("}");
342 return sb.toString();
343 }
344
345 public static Builder newBuilder() {
346 return new Builder();
347 }
348
349 public static Builder newBuilder(boolean keepProgress) {
350 return new Builder(keepProgress);
351 }
352
353 public static final class Builder {
354 boolean keepProgress = DEFAULT_KEEP_PROGRESS;
355 boolean trackMetrics = false;
356 LimitFields limits = new LimitFields();
357
358 private Builder() {
359 }
360
361 private Builder(boolean keepProgress) {
362 this.keepProgress = keepProgress;
363 }
364
365 public Builder setKeepProgress(boolean keepProgress) {
366 this.keepProgress = keepProgress;
367 return this;
368 }
369
370 public Builder setTrackMetrics(boolean trackMetrics) {
371 this.trackMetrics = trackMetrics;
372 return this;
373 }
374
375 public Builder setSizeLimit(LimitScope sizeScope, long sizeLimit) {
376 limits.setSize(sizeLimit);
377 limits.setSizeScope(sizeScope);
378 return this;
379 }
380
381 public Builder setTimeLimit(LimitScope timeScope, long timeLimit) {
382 limits.setTime(timeLimit);
383 limits.setTimeScope(timeScope);
384 return this;
385 }
386
387 public Builder setBatchLimit(int batchLimit) {
388 limits.setBatch(batchLimit);
389 return this;
390 }
391
392 public ScannerContext build() {
393 return new ScannerContext(keepProgress, limits, trackMetrics);
394 }
395 }
396
397 /**
398 * The possible states a scanner may be in following a call to {@link InternalScanner#next(List)}
399 */
400 public enum NextState {
401 MORE_VALUES(true, false),
402 NO_MORE_VALUES(false, false),
403 SIZE_LIMIT_REACHED(true, true),
404
405 /**
406 * Special case of size limit reached to indicate that the size limit was reached in the middle
407 * of a row and thus a partial results was formed
408 */
409 SIZE_LIMIT_REACHED_MID_ROW(true, true),
410 TIME_LIMIT_REACHED(true, true),
411
412 /**
413 * Special case of time limit reached to indicate that the time limit was reached in the middle
414 * of a row and thus a partial results was formed
415 */
416 TIME_LIMIT_REACHED_MID_ROW(true, true),
417 BATCH_LIMIT_REACHED(true, true);
418
419 private boolean moreValues;
420 private boolean limitReached;
421
422 private NextState(boolean moreValues, boolean limitReached) {
423 this.moreValues = moreValues;
424 this.limitReached = limitReached;
425 }
426
427 /**
428 * @return true when the state indicates that more values may follow those that have been
429 * returned
430 */
431 public boolean hasMoreValues() {
432 return this.moreValues;
433 }
434
435 /**
436 * @return true when the state indicates that a limit has been reached and scan should stop
437 */
438 public boolean limitReached() {
439 return this.limitReached;
440 }
441
442 public static boolean isValidState(NextState state) {
443 return state != null;
444 }
445
446 public static boolean hasMoreValues(NextState state) {
447 return isValidState(state) && state.hasMoreValues();
448 }
449 }
450
451 /**
452 * The various scopes where a limit can be enforced. Used to differentiate when a limit should be
453 * enforced or not.
454 */
455 public enum LimitScope {
456 /**
457 * Enforcing a limit between rows means that the limit will not be considered until all the
458 * cells for a particular row have been retrieved
459 */
460 BETWEEN_ROWS(0),
461
462 /**
463 * Enforcing a limit between cells means that the limit will be considered after each full cell
464 * has been retrieved
465 */
466 BETWEEN_CELLS(1);
467
468 /**
469 * When enforcing a limit, we must check that the scope is appropriate for enforcement.
470 * <p>
471 * To communicate this concept, each scope has a depth. A limit will be enforced if the depth of
472 * the checker's scope is less than or equal to the limit's scope. This means that when checking
473 * limits, the checker must know their own scope (i.e. are they checking the limits between
474 * rows, between cells, etc...)
475 */
476 int depth;
477
478 LimitScope(int depth) {
479 this.depth = depth;
480 }
481
482 int depth() {
483 return depth;
484 }
485
486 /**
487 * @param checkerScope The scope in which the limit is being checked
488 * @return true when the checker is in a scope that indicates the limit can be enforced. Limits
489 * can be enforced from "higher or equal" scopes (i.e. the checker's scope is at a
490 * lesser depth than the limit)
491 */
492 boolean canEnforceLimitFromScope(LimitScope checkerScope) {
493 return checkerScope != null && checkerScope.depth() <= depth;
494 }
495 }
496
497 /**
498 * The different fields that can be used as limits in calls to
499 * {@link InternalScanner#next(java.util.List)} and {@link RegionScanner#next(java.util.List)}
500 */
501 private static class LimitFields {
502 /**
503 * Default values of the limit fields. Defined such that if a field does NOT change from its
504 * default, it will not be enforced
505 */
506 private static int DEFAULT_BATCH = -1;
507 private static long DEFAULT_SIZE = -1L;
508 private static long DEFAULT_TIME = -1L;
509
510 /**
511 * Default scope that is assigned to a limit if a scope is not specified.
512 */
513 private static final LimitScope DEFAULT_SCOPE = LimitScope.BETWEEN_ROWS;
514
515 // The batch limit will always be enforced between cells, thus, there isn't a field to hold the
516 // batch scope
517 int batch = DEFAULT_BATCH;
518
519 LimitScope sizeScope = DEFAULT_SCOPE;
520 long size = DEFAULT_SIZE;
521
522 LimitScope timeScope = DEFAULT_SCOPE;
523 long time = DEFAULT_TIME;
524
525 /**
526 * Fields keep their default values.
527 */
528 LimitFields() {
529 }
530
531 LimitFields(int batch, LimitScope sizeScope, long size, LimitScope timeScope, long time) {
532 setFields(batch, sizeScope, size, timeScope, time);
533 }
534
535 void copy(LimitFields limitsToCopy) {
536 if (limitsToCopy != null) {
537 setFields(limitsToCopy.getBatch(), limitsToCopy.getSizeScope(), limitsToCopy.getSize(),
538 limitsToCopy.getTimeScope(), limitsToCopy.getTime());
539 }
540 }
541
542 /**
543 * Set all fields together.
544 * @param batch
545 * @param sizeScope
546 * @param size
547 */
548 void setFields(int batch, LimitScope sizeScope, long size, LimitScope timeScope, long time) {
549 setBatch(batch);
550 setSizeScope(sizeScope);
551 setSize(size);
552 setTimeScope(timeScope);
553 setTime(time);
554 }
555
556 int getBatch() {
557 return this.batch;
558 }
559
560 void setBatch(int batch) {
561 this.batch = batch;
562 }
563
564 /**
565 * @param checkerScope
566 * @return true when the limit can be enforced from the scope of the checker
567 */
568 boolean canEnforceBatchLimitFromScope(LimitScope checkerScope) {
569 return LimitScope.BETWEEN_CELLS.canEnforceLimitFromScope(checkerScope);
570 }
571
572 long getSize() {
573 return this.size;
574 }
575
576 void setSize(long size) {
577 this.size = size;
578 }
579
580 /**
581 * @return {@link LimitScope} indicating scope in which the size limit is enforced
582 */
583 LimitScope getSizeScope() {
584 return this.sizeScope;
585 }
586
587 /**
588 * Change the scope in which the size limit is enforced
589 */
590 void setSizeScope(LimitScope scope) {
591 this.sizeScope = scope;
592 }
593
594 /**
595 * @param checkerScope
596 * @return true when the limit can be enforced from the scope of the checker
597 */
598 boolean canEnforceSizeLimitFromScope(LimitScope checkerScope) {
599 return this.sizeScope.canEnforceLimitFromScope(checkerScope);
600 }
601
602 long getTime() {
603 return this.time;
604 }
605
606 void setTime(long time) {
607 this.time = time;
608 }
609
610 /**
611 * @return {@link LimitScope} indicating scope in which the time limit is enforced
612 */
613 LimitScope getTimeScope() {
614 return this.timeScope;
615 }
616
617 /**
618 * Change the scope in which the time limit is enforced
619 */
620 void setTimeScope(LimitScope scope) {
621 this.timeScope = scope;
622 }
623
624 /**
625 * @param checkerScope
626 * @return true when the limit can be enforced from the scope of the checker
627 */
628 boolean canEnforceTimeLimitFromScope(LimitScope checkerScope) {
629 return this.timeScope.canEnforceLimitFromScope(checkerScope);
630 }
631
632 @Override
633 public String toString() {
634 StringBuilder sb = new StringBuilder();
635 sb.append("{");
636
637 sb.append("batch:");
638 sb.append(batch);
639
640 sb.append(", size:");
641 sb.append(size);
642
643 sb.append(", sizeScope:");
644 sb.append(sizeScope);
645
646 sb.append(", time:");
647 sb.append(time);
648
649 sb.append(", timeScope:");
650 sb.append(timeScope);
651
652 sb.append("}");
653 return sb.toString();
654 }
655 }
656 }