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 int initialOffset = offset;
223
224 int keyLength = Bytes.toInt(bytes, offset, Bytes.SIZEOF_INT);
225 offset += KeyValue.ROW_OFFSET;
226
227 short rowLength = Bytes.toShort(bytes, offset, Bytes.SIZEOF_SHORT);
228 offset += Bytes.SIZEOF_SHORT;
229
230 int ret = this.rowComparator.compareRows(row, this.rowOffset, this.rowLength,
231 bytes, offset, rowLength);
232 if (ret <= -1) {
233 return MatchCode.DONE;
234 } else if (ret >= 1) {
235 // could optimize this, if necessary?
236 // Could also be called SEEK_TO_CURRENT_ROW, but this
237 // should be rare/never happens.
238 return MatchCode.SEEK_NEXT_ROW;
239 }
240
241 // optimize case.
242 if (this.stickyNextRow)
243 return MatchCode.SEEK_NEXT_ROW;
244
245 if (this.columns.done()) {
246 stickyNextRow = true;
247 return MatchCode.SEEK_NEXT_ROW;
248 }
249
250 //Passing rowLength
251 offset += rowLength;
252
253 //Skipping family
254 byte familyLength = bytes [offset];
255 offset += familyLength + 1;
256
257 int qualLength = keyLength + KeyValue.ROW_OFFSET -
258 (offset - initialOffset) - KeyValue.TIMESTAMP_TYPE_SIZE;
259
260 long timestamp = kv.getTimestamp();
261 // check for early out based on timestamp alone
262 if (columns.isDone(timestamp)) {
263 return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
264 }
265
266 /*
267 * The delete logic is pretty complicated now.
268 * This is corroborated by the following:
269 * 1. The store might be instructed to keep deleted rows around.
270 * 2. A scan can optionally see past a delete marker now.
271 * 3. If deleted rows are kept, we have to find out when we can
272 * remove the delete markers.
273 * 4. Family delete markers are always first (regardless of their TS)
274 * 5. Delete markers should not be counted as version
275 * 6. Delete markers affect puts of the *same* TS
276 * 7. Delete marker need to be version counted together with puts
277 * they affect
278 */
279 byte type = kv.getType();
280 if (kv.isDelete()) {
281 if (!keepDeletedCells) {
282 // first ignore delete markers if the scanner can do so, and the
283 // range does not include the marker
284 //
285 // during flushes and compactions also ignore delete markers newer
286 // than the readpoint of any open scanner, this prevents deleted
287 // rows that could still be seen by a scanner from being collected
288 boolean includeDeleteMarker = seePastDeleteMarkers ?
289 tr.withinTimeRange(timestamp) :
290 tr.withinOrAfterTimeRange(timestamp);
291 if (includeDeleteMarker
292 && kv.getMemstoreTS() <= maxReadPointToTrackVersions) {
293 this.deletes.add(bytes, offset, qualLength, timestamp, type);
294 }
295 // Can't early out now, because DelFam come before any other keys
296 }
297 if (retainDeletesInOutput
298 || (!isUserScan && (EnvironmentEdgeManager.currentTimeMillis() - timestamp) <= timeToPurgeDeletes)
299 || kv.getMemstoreTS() > maxReadPointToTrackVersions) {
300 // always include or it is not time yet to check whether it is OK
301 // to purge deltes or not
302 if (!isUserScan) {
303 // if this is not a user scan (compaction), we can filter this deletemarker right here
304 // otherwise (i.e. a "raw" scan) we fall through to normal version and timerange checking
305 return MatchCode.INCLUDE;
306 }
307 } else if (keepDeletedCells) {
308 if (timestamp < earliestPutTs) {
309 // keeping delete rows, but there are no puts older than
310 // this delete in the store files.
311 return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
312 }
313 // else: fall through and do version counting on the
314 // delete markers
315 } else {
316 return MatchCode.SKIP;
317 }
318 // note the following next else if...
319 // delete marker are not subject to other delete markers
320 } else if (!this.deletes.isEmpty()) {
321 DeleteResult deleteResult = deletes.isDeleted(bytes, offset, qualLength,
322 timestamp);
323 switch (deleteResult) {
324 case FAMILY_DELETED:
325 case COLUMN_DELETED:
326 return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
327 case VERSION_DELETED:
328 return MatchCode.SKIP;
329 case NOT_DELETED:
330 break;
331 default:
332 throw new RuntimeException("UNEXPECTED");
333 }
334 }
335
336 int timestampComparison = tr.compare(timestamp);
337 if (timestampComparison >= 1) {
338 return MatchCode.SKIP;
339 } else if (timestampComparison <= -1) {
340 return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
341 }
342
343 /**
344 * Filters should be checked before checking column trackers. If we do
345 * otherwise, as was previously being done, ColumnTracker may increment its
346 * counter for even that KV which may be discarded later on by Filter. This
347 * would lead to incorrect results in certain cases.
348 */
349 ReturnCode filterResponse = ReturnCode.SKIP;
350 if (filter != null) {
351 filterResponse = filter.filterKeyValue(kv);
352 if (filterResponse == ReturnCode.SKIP) {
353 return MatchCode.SKIP;
354 } else if (filterResponse == ReturnCode.NEXT_COL) {
355 return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
356 } else if (filterResponse == ReturnCode.NEXT_ROW) {
357 stickyNextRow = true;
358 return MatchCode.SEEK_NEXT_ROW;
359 } else if (filterResponse == ReturnCode.SEEK_NEXT_USING_HINT) {
360 return MatchCode.SEEK_NEXT_USING_HINT;
361 }
362 }
363
364 MatchCode colChecker = columns.checkColumn(bytes, offset, qualLength,
365 timestamp, type, kv.getMemstoreTS() > maxReadPointToTrackVersions);
366 /*
367 * According to current implementation, colChecker can only be
368 * SEEK_NEXT_COL, SEEK_NEXT_ROW, SKIP or INCLUDE. Therefore, always return
369 * the MatchCode. If it is SEEK_NEXT_ROW, also set stickyNextRow.
370 */
371 if (colChecker == MatchCode.SEEK_NEXT_ROW) {
372 stickyNextRow = true;
373 } else if (filter != null && colChecker == MatchCode.INCLUDE &&
374 filterResponse == ReturnCode.INCLUDE_AND_NEXT_COL) {
375 return MatchCode.INCLUDE_AND_SEEK_NEXT_COL;
376 }
377 return colChecker;
378
379 }
380
381 public boolean moreRowsMayExistAfter(KeyValue kv) {
382 if (!Bytes.equals(stopRow , HConstants.EMPTY_END_ROW) &&
383 rowComparator.compareRows(kv.getBuffer(),kv.getRowOffset(),
384 kv.getRowLength(), stopRow, 0, stopRow.length) >= 0) {
385 // KV >= STOPROW
386 // then NO there is nothing left.
387 return false;
388 } else {
389 return true;
390 }
391 }
392
393 /**
394 * Set current row
395 * @param row
396 */
397 public void setRow(byte [] row, int offset, short length) {
398 this.row = row;
399 this.rowOffset = offset;
400 this.rowLength = length;
401 reset();
402 }
403
404 public void reset() {
405 this.deletes.reset();
406 this.columns.reset();
407
408 stickyNextRow = false;
409 }
410
411 /**
412 *
413 * @return the start key
414 */
415 public KeyValue getStartKey() {
416 return this.startKey;
417 }
418
419 /**
420 *
421 * @return the Filter
422 */
423 Filter getFilter() {
424 return this.filter;
425 }
426
427 public KeyValue getNextKeyHint(KeyValue kv) {
428 if (filter == null) {
429 return null;
430 } else {
431 return filter.getNextKeyHint(kv);
432 }
433 }
434
435 public KeyValue getKeyForNextColumn(KeyValue kv) {
436 ColumnCount nextColumn = columns.getColumnHint();
437 if (nextColumn == null) {
438 return KeyValue.createLastOnRow(
439 kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(),
440 kv.getBuffer(), kv.getFamilyOffset(), kv.getFamilyLength(),
441 kv.getBuffer(), kv.getQualifierOffset(), kv.getQualifierLength());
442 } else {
443 return KeyValue.createFirstOnRow(
444 kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(),
445 kv.getBuffer(), kv.getFamilyOffset(), kv.getFamilyLength(),
446 nextColumn.getBuffer(), nextColumn.getOffset(), nextColumn.getLength());
447 }
448 }
449
450 public KeyValue getKeyForNextRow(KeyValue kv) {
451 return KeyValue.createLastOnRow(
452 kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(),
453 null, 0, 0,
454 null, 0, 0);
455 }
456
457 /**
458 * {@link #match} return codes. These instruct the scanner moving through
459 * memstores and StoreFiles what to do with the current KeyValue.
460 * <p>
461 * Additionally, this contains "early-out" language to tell the scanner to
462 * move on to the next File (memstore or Storefile), or to return immediately.
463 */
464 public static enum MatchCode {
465 /**
466 * Include KeyValue in the returned result
467 */
468 INCLUDE,
469
470 /**
471 * Do not include KeyValue in the returned result
472 */
473 SKIP,
474
475 /**
476 * Do not include, jump to next StoreFile or memstore (in time order)
477 */
478 NEXT,
479
480 /**
481 * Do not include, return current result
482 */
483 DONE,
484
485 /**
486 * These codes are used by the ScanQueryMatcher
487 */
488
489 /**
490 * Done with the row, seek there.
491 */
492 SEEK_NEXT_ROW,
493 /**
494 * Done with column, seek to next.
495 */
496 SEEK_NEXT_COL,
497
498 /**
499 * Done with scan, thanks to the row filter.
500 */
501 DONE_SCAN,
502
503 /*
504 * Seek to next key which is given as hint.
505 */
506 SEEK_NEXT_USING_HINT,
507
508 /**
509 * Include KeyValue and done with column, seek to next.
510 */
511 INCLUDE_AND_SEEK_NEXT_COL,
512
513 /**
514 * Include KeyValue and done with row, seek to next.
515 */
516 INCLUDE_AND_SEEK_NEXT_ROW,
517 }
518 }