1 /**
2 * Copyright 2010 The Apache Software Foundation
3 *
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 */
20
21 package org.apache.hadoop.hbase.regionserver;
22
23 import java.io.IOException;
24 import java.util.NavigableSet;
25
26 import org.apache.hadoop.hbase.HConstants;
27 import org.apache.hadoop.hbase.KeyValue;
28 import org.apache.hadoop.hbase.client.Scan;
29 import org.apache.hadoop.hbase.filter.Filter;
30 import org.apache.hadoop.hbase.filter.Filter.ReturnCode;
31 import org.apache.hadoop.hbase.io.TimeRange;
32 import org.apache.hadoop.hbase.regionserver.DeleteTracker.DeleteResult;
33 import org.apache.hadoop.hbase.util.Bytes;
34 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
35
36 /**
37 * A query matcher that is specifically designed for the scan case.
38 */
39 public class ScanQueryMatcher {
40 // Optimization so we can skip lots of compares when we decide to skip
41 // to the next row.
42 private boolean stickyNextRow;
43 private final byte[] stopRow;
44
45 private final TimeRange tr;
46
47 private final Filter filter;
48
49 /** Keeps track of deletes */
50 private final DeleteTracker deletes;
51
52 /*
53 * The following three booleans define how we deal with deletes.
54 * There are three different aspects:
55 * 1. Whether to keep delete markers. This is used in compactions.
56 * Minor compactions always keep delete markers.
57 * 2. Whether to keep deleted rows. This is also used in compactions,
58 * if the store is set to keep deleted rows. This implies keeping
59 * the delete markers as well.
60 * In this case deleted rows are subject to the normal max version
61 * and TTL/min version rules just like "normal" rows.
62 * 3. Whether a scan can do time travel queries even before deleted
63 * marker to reach deleted rows.
64 */
65 /** whether to retain delete markers */
66 private final boolean retainDeletesInOutput;
67 /** whether to return deleted rows */
68 private final boolean keepDeletedCells;
69 /** whether time range queries can see rows "behind" a delete */
70 private final boolean seePastDeleteMarkers;
71
72
73 /** Keeps track of columns and versions */
74 private final ColumnTracker columns;
75
76 /** Key to seek to in memstore and StoreFiles */
77 private final KeyValue startKey;
78
79 /** Row comparator for the region this query is for */
80 private final KeyValue.KeyComparator rowComparator;
81
82 /* row is not private for tests */
83 /** Row the query is on */
84 byte [] row;
85 int rowOffset;
86 short rowLength;
87
88 /**
89 * Oldest put in any of the involved store files
90 * Used to decide whether it is ok to delete
91 * family delete marker of this store keeps
92 * deleted KVs.
93 */
94 private final long earliestPutTs;
95
96 /** readPoint over which the KVs are unconditionally included */
97 protected long maxReadPointToTrackVersions;
98
99 /**
100 * This variable shows whether there is an null column in the query. There
101 * always exists a null column in the wildcard column query.
102 * There maybe exists a null column in the explicit column query based on the
103 * first column.
104 * */
105 private boolean hasNullColumn = true;
106
107 // By default, when hbase.hstore.time.to.purge.deletes is 0ms, a delete
108 // marker is always removed during a major compaction. If set to non-zero
109 // value then major compaction will try to keep a delete marker around for
110 // the given number of milliseconds. We want to keep the delete markers
111 // around a bit longer because old puts might appear out-of-order. For
112 // example, during log replication between two clusters.
113 //
114 // If the delete marker has lived longer than its column-family's TTL then
115 // the delete marker will be removed even if time.to.purge.deletes has not
116 // passed. This is because all the Puts that this delete marker can influence
117 // would have also expired. (Removing of delete markers on col family TTL will
118 // not happen if min-versions is set to non-zero)
119 //
120 // But, if time.to.purge.deletes has not expired then a delete
121 // marker will not be removed just because there are no Puts that it is
122 // currently influencing. This is because Puts, that this delete can
123 // influence. may appear out of order.
124 private final long timeToPurgeDeletes;
125
126 private final boolean isUserScan;
127
128 /**
129 * Construct a QueryMatcher for a scan
130 * @param scan
131 * @param scanInfo The store's immutable scan info
132 * @param columns
133 * @param scanType Type of the scan
134 * @param earliestPutTs Earliest put seen in any of the store files.
135 * @param oldestUnexpiredTS the oldest timestamp we are interested in,
136 * based on TTL
137 */
138 public ScanQueryMatcher(Scan scan, Store.ScanInfo scanInfo,
139 NavigableSet<byte[]> columns, ScanType scanType,
140 long readPointToUse, long earliestPutTs, long oldestUnexpiredTS) {
141 this.tr = scan.getTimeRange();
142 this.rowComparator = scanInfo.getComparator().getRawComparator();
143 this.deletes = new ScanDeleteTracker();
144 this.stopRow = scan.getStopRow();
145 this.startKey = KeyValue.createFirstDeleteFamilyOnRow(scan.getStartRow(),
146 scanInfo.getFamily());
147 this.filter = scan.getFilter();
148 this.earliestPutTs = earliestPutTs;
149 this.maxReadPointToTrackVersions = readPointToUse;
150 this.timeToPurgeDeletes = scanInfo.getTimeToPurgeDeletes();
151
152 /* how to deal with deletes */
153 this.isUserScan = scanType == ScanType.USER_SCAN;
154 // keep deleted cells: if compaction or raw scan
155 this.keepDeletedCells = (scanInfo.getKeepDeletedCells() && !isUserScan) || scan.isRaw();
156 // retain deletes: if minor compaction or raw scan
157 this.retainDeletesInOutput = scanType == ScanType.MINOR_COMPACT || scan.isRaw();
158 // seePastDeleteMarker: user initiated scans
159 this.seePastDeleteMarkers = scanInfo.getKeepDeletedCells() && isUserScan;
160
161 int maxVersions =
162 scan.isRaw() ? scan.getMaxVersions() : Math.min(scan.getMaxVersions(),
163 scanInfo.getMaxVersions());
164
165 // Single branch to deal with two types of reads (columns vs all in family)
166 if (columns == null || columns.size() == 0) {
167 // there is always a null column in the wildcard column query.
168 hasNullColumn = true;
169
170 // use a specialized scan for wildcard column tracker.
171 this.columns = new ScanWildcardColumnTracker(
172 scanInfo.getMinVersions(), maxVersions, oldestUnexpiredTS);
173 } else {
174 // whether there is null column in the explicit column query
175 hasNullColumn = (columns.first().length == 0);
176
177 // We can share the ExplicitColumnTracker, diff is we reset
178 // between rows, not between storefiles.
179 this.columns = new ExplicitColumnTracker(columns,
180 scanInfo.getMinVersions(), maxVersions, oldestUnexpiredTS);
181 }
182 }
183
184 /*
185 * Constructor for tests
186 */
187 ScanQueryMatcher(Scan scan, Store.ScanInfo scanInfo,
188 NavigableSet<byte[]> columns, long oldestUnexpiredTS) {
189 this(scan, scanInfo, columns, ScanType.USER_SCAN,
190 Long.MAX_VALUE, /* max Readpoint to track versions */
191 HConstants.LATEST_TIMESTAMP, oldestUnexpiredTS);
192 }
193
194 /**
195 *
196 * @return whether there is an null column in the query
197 */
198 public boolean hasNullColumnInQuery() {
199 return hasNullColumn;
200 }
201
202 /**
203 * Determines if the caller should do one of several things:
204 * - seek/skip to the next row (MatchCode.SEEK_NEXT_ROW)
205 * - seek/skip to the next column (MatchCode.SEEK_NEXT_COL)
206 * - include the current KeyValue (MatchCode.INCLUDE)
207 * - ignore the current KeyValue (MatchCode.SKIP)
208 * - got to the next row (MatchCode.DONE)
209 *
210 * @param kv KeyValue to check
211 * @return The match code instance.
212 * @throws IOException in case there is an internal consistency problem
213 * caused by a data corruption.
214 */
215 public MatchCode match(KeyValue kv) throws IOException {
216 if (filter != null && filter.filterAllRemaining()) {
217 return MatchCode.DONE_SCAN;
218 }
219
220 byte [] bytes = kv.getBuffer();
221 int offset = kv.getOffset();
222
223 int keyLength = Bytes.toInt(bytes, offset, Bytes.SIZEOF_INT);
224 offset += KeyValue.ROW_OFFSET;
225
226 int initialOffset = offset;
227
228 short rowLength = Bytes.toShort(bytes, offset, Bytes.SIZEOF_SHORT);
229 offset += Bytes.SIZEOF_SHORT;
230
231 int ret = this.rowComparator.compareRows(row, this.rowOffset, this.rowLength,
232 bytes, offset, rowLength);
233 if (ret <= -1) {
234 return MatchCode.DONE;
235 } else if (ret >= 1) {
236 // could optimize this, if necessary?
237 // Could also be called SEEK_TO_CURRENT_ROW, but this
238 // should be rare/never happens.
239 return MatchCode.SEEK_NEXT_ROW;
240 }
241
242 // optimize case.
243 if (this.stickyNextRow)
244 return MatchCode.SEEK_NEXT_ROW;
245
246 if (this.columns.done()) {
247 stickyNextRow = true;
248 return MatchCode.SEEK_NEXT_ROW;
249 }
250
251 //Passing rowLength
252 offset += rowLength;
253
254 //Skipping family
255 byte familyLength = bytes [offset];
256 offset += familyLength + 1;
257
258 int qualLength = keyLength -
259 (offset - initialOffset) - KeyValue.TIMESTAMP_TYPE_SIZE;
260
261 long timestamp = Bytes.toLong(bytes, initialOffset + keyLength - KeyValue.TIMESTAMP_TYPE_SIZE);
262 // check for early out based on timestamp alone
263 if (columns.isDone(timestamp)) {
264 return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
265 }
266
267 /*
268 * The delete logic is pretty complicated now.
269 * This is corroborated by the following:
270 * 1. The store might be instructed to keep deleted rows around.
271 * 2. A scan can optionally see past a delete marker now.
272 * 3. If deleted rows are kept, we have to find out when we can
273 * remove the delete markers.
274 * 4. Family delete markers are always first (regardless of their TS)
275 * 5. Delete markers should not be counted as version
276 * 6. Delete markers affect puts of the *same* TS
277 * 7. Delete marker need to be version counted together with puts
278 * they affect
279 */
280 byte type = bytes[initialOffset + keyLength - 1];
281 if (kv.isDelete()) {
282 if (!keepDeletedCells) {
283 // first ignore delete markers if the scanner can do so, and the
284 // range does not include the marker
285 //
286 // during flushes and compactions also ignore delete markers newer
287 // than the readpoint of any open scanner, this prevents deleted
288 // rows that could still be seen by a scanner from being collected
289 boolean includeDeleteMarker = seePastDeleteMarkers ?
290 tr.withinTimeRange(timestamp) :
291 tr.withinOrAfterTimeRange(timestamp);
292 if (includeDeleteMarker
293 && kv.getMemstoreTS() <= maxReadPointToTrackVersions) {
294 this.deletes.add(bytes, offset, qualLength, timestamp, type);
295 }
296 // Can't early out now, because DelFam come before any other keys
297 }
298 if (retainDeletesInOutput
299 || (!isUserScan && (EnvironmentEdgeManager.currentTimeMillis() - timestamp) <= timeToPurgeDeletes)
300 || kv.getMemstoreTS() > maxReadPointToTrackVersions) {
301 // always include or it is not time yet to check whether it is OK
302 // to purge deltes or not
303 if (!isUserScan) {
304 // if this is not a user scan (compaction), we can filter this deletemarker right here
305 // otherwise (i.e. a "raw" scan) we fall through to normal version and timerange checking
306 return MatchCode.INCLUDE;
307 }
308 } else if (keepDeletedCells) {
309 if (timestamp < earliestPutTs) {
310 // keeping delete rows, but there are no puts older than
311 // this delete in the store files.
312 return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
313 }
314 // else: fall through and do version counting on the
315 // delete markers
316 } else {
317 return MatchCode.SKIP;
318 }
319 // note the following next else if...
320 // delete marker are not subject to other delete markers
321 } else if (!this.deletes.isEmpty()) {
322 DeleteResult deleteResult = deletes.isDeleted(bytes, offset, qualLength,
323 timestamp);
324 switch (deleteResult) {
325 case FAMILY_DELETED:
326 case COLUMN_DELETED:
327 return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
328 case VERSION_DELETED:
329 return MatchCode.SKIP;
330 case NOT_DELETED:
331 break;
332 default:
333 throw new RuntimeException("UNEXPECTED");
334 }
335 }
336
337 int timestampComparison = tr.compare(timestamp);
338 if (timestampComparison >= 1) {
339 return MatchCode.SKIP;
340 } else if (timestampComparison <= -1) {
341 return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
342 }
343
344 // STEP 1: Check if the column is part of the requested columns
345 MatchCode colChecker = columns.checkColumn(bytes, offset, qualLength, type);
346 if (colChecker == MatchCode.INCLUDE) {
347 ReturnCode filterResponse = ReturnCode.SKIP;
348 // STEP 2: Yes, the column is part of the requested columns. Check if filter is present
349 if (filter != null) {
350 // STEP 3: Filter the key value and return if it filters out
351 filterResponse = filter.filterKeyValue(kv);
352 switch (filterResponse) {
353 case SKIP:
354 return MatchCode.SKIP;
355 case NEXT_COL:
356 return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
357 case NEXT_ROW:
358 stickyNextRow = true;
359 return MatchCode.SEEK_NEXT_ROW;
360 case SEEK_NEXT_USING_HINT:
361 return MatchCode.SEEK_NEXT_USING_HINT;
362 default:
363 //It means it is either include or include and seek next
364 break;
365 }
366 }
367 /*
368 * STEP 4: Reaching this step means the column is part of the requested columns and either
369 * the filter is null or the filter has returned INCLUDE or INCLUDE_AND_NEXT_COL response.
370 * Now check the number of versions needed. This method call returns SKIP, INCLUDE,
371 * INCLUDE_AND_SEEK_NEXT_ROW, INCLUDE_AND_SEEK_NEXT_COL.
372 *
373 * FilterResponse ColumnChecker Desired behavior
374 * INCLUDE SKIP row has already been included, SKIP.
375 * INCLUDE INCLUDE INCLUDE
376 * INCLUDE INCLUDE_AND_SEEK_NEXT_COL INCLUDE_AND_SEEK_NEXT_COL
377 * INCLUDE INCLUDE_AND_SEEK_NEXT_ROW INCLUDE_AND_SEEK_NEXT_ROW
378 * INCLUDE_AND_SEEK_NEXT_COL SKIP row has already been included, SKIP.
379 * INCLUDE_AND_SEEK_NEXT_COL INCLUDE INCLUDE_AND_SEEK_NEXT_COL
380 * INCLUDE_AND_SEEK_NEXT_COL INCLUDE_AND_SEEK_NEXT_COL INCLUDE_AND_SEEK_NEXT_COL
381 * INCLUDE_AND_SEEK_NEXT_COL INCLUDE_AND_SEEK_NEXT_ROW INCLUDE_AND_SEEK_NEXT_ROW
382 *
383 * In all the above scenarios, we return the column checker return value except for
384 * FilterResponse (INCLUDE_AND_SEEK_NEXT_COL) and ColumnChecker(INCLUDE)
385 */
386 colChecker =
387 columns.checkVersions(bytes, offset, qualLength, timestamp, type,
388 kv.getMemstoreTS() > maxReadPointToTrackVersions);
389 //Optimize with stickyNextRow
390 stickyNextRow = colChecker == MatchCode.INCLUDE_AND_SEEK_NEXT_ROW ? true : stickyNextRow;
391 return (filterResponse == ReturnCode.INCLUDE_AND_NEXT_COL &&
392 colChecker == MatchCode.INCLUDE) ? MatchCode.INCLUDE_AND_SEEK_NEXT_COL
393 : colChecker;
394 }
395 stickyNextRow = (colChecker == MatchCode.SEEK_NEXT_ROW) ? true
396 : stickyNextRow;
397 return colChecker;
398 }
399
400 public boolean moreRowsMayExistAfter(KeyValue kv) {
401 if (!Bytes.equals(stopRow , HConstants.EMPTY_END_ROW) &&
402 rowComparator.compareRows(kv.getBuffer(),kv.getRowOffset(),
403 kv.getRowLength(), stopRow, 0, stopRow.length) >= 0) {
404 // KV >= STOPROW
405 // then NO there is nothing left.
406 return false;
407 } else {
408 return true;
409 }
410 }
411
412 /**
413 * Set current row
414 * @param row
415 */
416 public void setRow(byte [] row, int offset, short length) {
417 this.row = row;
418 this.rowOffset = offset;
419 this.rowLength = length;
420 reset();
421 }
422
423 public void reset() {
424 this.deletes.reset();
425 this.columns.reset();
426
427 stickyNextRow = false;
428 }
429
430 /**
431 *
432 * @return the start key
433 */
434 public KeyValue getStartKey() {
435 return this.startKey;
436 }
437
438 /**
439 *
440 * @return the Filter
441 */
442 Filter getFilter() {
443 return this.filter;
444 }
445
446 public KeyValue getNextKeyHint(KeyValue kv) {
447 if (filter == null) {
448 return null;
449 } else {
450 return filter.getNextKeyHint(kv);
451 }
452 }
453
454 public KeyValue getKeyForNextColumn(KeyValue kv) {
455 ColumnCount nextColumn = columns.getColumnHint();
456 if (nextColumn == null) {
457 return KeyValue.createLastOnRow(
458 kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(),
459 kv.getBuffer(), kv.getFamilyOffset(), kv.getFamilyLength(),
460 kv.getBuffer(), kv.getQualifierOffset(), kv.getQualifierLength());
461 } else {
462 return KeyValue.createFirstOnRow(
463 kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(),
464 kv.getBuffer(), kv.getFamilyOffset(), kv.getFamilyLength(),
465 nextColumn.getBuffer(), nextColumn.getOffset(), nextColumn.getLength());
466 }
467 }
468
469 public KeyValue getKeyForNextRow(KeyValue kv) {
470 return KeyValue.createLastOnRow(
471 kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(),
472 null, 0, 0,
473 null, 0, 0);
474 }
475
476 // Used only for testing purposes
477 static MatchCode checkColumn(ColumnTracker columnTracker, byte[] bytes, int offset, int length,
478 long ttl, byte type, boolean ignoreCount) throws IOException {
479 MatchCode matchCode = columnTracker.checkColumn(bytes, offset, length, type);
480 if (matchCode == MatchCode.INCLUDE) {
481 return columnTracker.checkVersions(bytes, offset, length, ttl, type, ignoreCount);
482 }
483 return matchCode;
484 }
485
486 /**
487 * {@link #match} return codes. These instruct the scanner moving through
488 * memstores and StoreFiles what to do with the current KeyValue.
489 * <p>
490 * Additionally, this contains "early-out" language to tell the scanner to
491 * move on to the next File (memstore or Storefile), or to return immediately.
492 */
493 public static enum MatchCode {
494 /**
495 * Include KeyValue in the returned result
496 */
497 INCLUDE,
498
499 /**
500 * Do not include KeyValue in the returned result
501 */
502 SKIP,
503
504 /**
505 * Do not include, jump to next StoreFile or memstore (in time order)
506 */
507 NEXT,
508
509 /**
510 * Do not include, return current result
511 */
512 DONE,
513
514 /**
515 * These codes are used by the ScanQueryMatcher
516 */
517
518 /**
519 * Done with the row, seek there.
520 */
521 SEEK_NEXT_ROW,
522 /**
523 * Done with column, seek to next.
524 */
525 SEEK_NEXT_COL,
526
527 /**
528 * Done with scan, thanks to the row filter.
529 */
530 DONE_SCAN,
531
532 /*
533 * Seek to next key which is given as hint.
534 */
535 SEEK_NEXT_USING_HINT,
536
537 /**
538 * Include KeyValue and done with column, seek to next.
539 */
540 INCLUDE_AND_SEEK_NEXT_COL,
541
542 /**
543 * Include KeyValue and done with row, seek to next.
544 */
545 INCLUDE_AND_SEEK_NEXT_ROW,
546 }
547 }