View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  package org.apache.hadoop.hbase.regionserver;
21  
22  import java.lang.management.ManagementFactory;
23  import java.lang.management.RuntimeMXBean;
24  import java.util.ArrayList;
25  import java.util.Collections;
26  import java.util.Iterator;
27  import java.util.List;
28  import java.util.NavigableSet;
29  import java.util.SortedSet;
30  import java.util.concurrent.atomic.AtomicLong;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.hbase.classification.InterfaceAudience;
35  import org.apache.hadoop.conf.Configuration;
36  import org.apache.hadoop.hbase.Cell;
37  import org.apache.hadoop.hbase.CellUtil;
38  import org.apache.hadoop.hbase.HBaseConfiguration;
39  import org.apache.hadoop.hbase.HConstants;
40  import org.apache.hadoop.hbase.KeyValue;
41  import org.apache.hadoop.hbase.KeyValueUtil;
42  import org.apache.hadoop.hbase.client.Scan;
43  import org.apache.hadoop.hbase.io.TimeRange;
44  import org.apache.hadoop.hbase.util.ByteRange;
45  import org.apache.hadoop.hbase.util.Bytes;
46  import org.apache.hadoop.hbase.util.ClassSize;
47  import org.apache.hadoop.hbase.util.CollectionBackedScanner;
48  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
49  import org.apache.hadoop.hbase.util.ReflectionUtils;
50  import org.apache.htrace.Trace;
51  
52  import com.google.common.annotations.VisibleForTesting;
53  
54  /**
55   * The MemStore holds in-memory modifications to the Store.  Modifications
56   * are {@link Cell}s.  When asked to flush, current memstore is moved
57   * to snapshot and is cleared.  We continue to serve edits out of new memstore
58   * and backing snapshot until flusher reports in that the flush succeeded. At
59   * this point we let the snapshot go.
60   *  <p>
61   * The MemStore functions should not be called in parallel. Callers should hold
62   *  write and read locks. This is done in {@link HStore}.
63   *  </p>
64   *
65   * TODO: Adjust size of the memstore when we remove items because they have
66   * been deleted.
67   * TODO: With new KVSLS, need to make sure we update HeapSize with difference
68   * in KV size.
69   */
70  @InterfaceAudience.Private
71  public class DefaultMemStore implements MemStore {
72    private static final Log LOG = LogFactory.getLog(DefaultMemStore.class);
73    @VisibleForTesting
74    static final String USEMSLAB_KEY = "hbase.hregion.memstore.mslab.enabled";
75    private static final boolean USEMSLAB_DEFAULT = true;
76    private static final String MSLAB_CLASS_NAME = "hbase.regionserver.mslab.class";
77  
78    private Configuration conf;
79  
80    @VisibleForTesting
81    final KeyValue.KVComparator comparator;
82  
83    // Used to track when to flush
84    private volatile long timeOfOldestEdit = Long.MAX_VALUE;
85  
86    private volatile long snapshotId;
87    private volatile boolean tagsPresent;
88  
89    @VisibleForTesting
90    volatile Section activeSection;
91    @VisibleForTesting
92    volatile Section snapshotSection;
93  
94    /**
95     * Default constructor. Used for tests.
96     */
97    public DefaultMemStore() {
98      this(HBaseConfiguration.create(), KeyValue.COMPARATOR);
99    }
100 
101   /**
102    * Constructor.
103    * @param c Comparator
104    */
105   public DefaultMemStore(final Configuration conf,
106                   final KeyValue.KVComparator c) {
107     this.conf = conf;
108     this.comparator = c;
109     this.activeSection = Section.newActiveSection(comparator, conf);
110     this.snapshotSection = Section.newSnapshotSection(comparator);
111   }
112 
113   /**
114    * Creates a snapshot of the current memstore.
115    * Snapshot must be cleared by call to {@link #clearSnapshot(long)}
116    */
117   @Override
118   public MemStoreSnapshot snapshot() {
119     // If snapshot currently has entries, then flusher failed or didn't call
120     // cleanup.  Log a warning.
121     if (!snapshotSection.getCellSkipListSet().isEmpty()) {
122       LOG.warn("Snapshot called again without clearing previous. " +
123           "Doing nothing. Another ongoing flush or did we fail last attempt?");
124     } else {
125       this.snapshotId = EnvironmentEdgeManager.currentTime();
126       if (!activeSection.getCellSkipListSet().isEmpty()) {
127         snapshotSection = activeSection;
128         activeSection = Section.newActiveSection(comparator, conf);
129         snapshotSection.getHeapSize().addAndGet(-DEEP_OVERHEAD);
130         timeOfOldestEdit = Long.MAX_VALUE;
131       }
132     }
133     MemStoreSnapshot memStoreSnapshot = new MemStoreSnapshot(this.snapshotId,
134         snapshotSection.getCellSkipListSet().size(), snapshotSection.getHeapSize().get(),
135         snapshotSection.getTimeRangeTracker(),
136         new CollectionBackedScanner(snapshotSection.getCellSkipListSet(), this.comparator),
137         this.tagsPresent);
138     this.tagsPresent = false;
139     return memStoreSnapshot;
140   }
141 
142   /**
143    * The passed snapshot was successfully persisted; it can be let go.
144    * @param id Id of the snapshot to clean out.
145    * @throws UnexpectedStateException
146    * @see #snapshot()
147    */
148   @Override
149   public void clearSnapshot(long id) throws UnexpectedStateException {
150     if (this.snapshotId == -1) return;  // already cleared
151     if (this.snapshotId != id) {
152       throw new UnexpectedStateException("Current snapshot id is " + this.snapshotId + ",passed "
153           + id);
154     }
155     // OK. Passed in snapshot is same as current snapshot.
156     MemStoreLAB tmpAllocator = snapshotSection.getMemStoreLAB();
157     snapshotSection = Section.newSnapshotSection(comparator);
158     if (tmpAllocator != null) {
159       tmpAllocator.close();
160     }
161     this.snapshotId = -1;
162   }
163 
164   @Override
165   public long getFlushableSize() {
166     long snapshotSize = snapshotSection.getHeapSize().get();
167     return snapshotSize > 0 ? snapshotSize : keySize();
168   }
169 
170   @Override
171   public long getSnapshotSize() {
172     return snapshotSection.getHeapSize().get();
173   }
174 
175   /**
176    * Write an update
177    * @param cell
178    * @return approximate size of the passed cell.
179    */
180   @Override
181   public long add(Cell cell) {
182     Cell toAdd = maybeCloneWithAllocator(cell);
183     boolean mslabUsed = (toAdd != cell);
184     return internalAdd(toAdd, mslabUsed);
185   }
186 
187   @Override
188   public long timeOfOldestEdit() {
189     return timeOfOldestEdit;
190   }
191 
192   private boolean addToCellSet(Cell e) {
193     boolean b = this.activeSection.getCellSkipListSet().add(e);
194     // In no tags case this NoTagsKeyValue.getTagsLength() is a cheap call.
195     // When we use ACL CP or Visibility CP which deals with Tags during
196     // mutation, the TagRewriteCell.getTagsLength() is a cheaper call. We do not
197     // parse the byte[] to identify the tags length.
198     if(e.getTagsLength() > 0) {
199       tagsPresent = true;
200     }
201     setOldestEditTimeToNow();
202     return b;
203   }
204 
205   private boolean removeFromCellSet(Cell e) {
206     boolean b = this.activeSection.getCellSkipListSet().remove(e);
207     setOldestEditTimeToNow();
208     return b;
209   }
210 
211   void setOldestEditTimeToNow() {
212     if (timeOfOldestEdit == Long.MAX_VALUE) {
213       timeOfOldestEdit = EnvironmentEdgeManager.currentTime();
214     }
215   }
216 
217   /**
218    * Internal version of add() that doesn't clone Cells with the
219    * allocator, and doesn't take the lock.
220    *
221    * Callers should ensure they already have the read lock taken
222    * @param toAdd the cell to add
223    * @param mslabUsed whether using MSLAB
224    * @return the heap size change in bytes
225    */
226   private long internalAdd(final Cell toAdd, boolean mslabUsed) {
227     boolean notPresent = addToCellSet(toAdd);
228     long s = heapSizeChange(toAdd, notPresent);
229     // If there's already a same cell in the CellSet and we are using MSLAB, we must count in the
230     // MSLAB allocation size as well, or else there will be memory leak (occupied heap size larger
231     // than the counted number)
232     if (!notPresent && mslabUsed) {
233       s += getCellLength(toAdd);
234     }
235     activeSection.getTimeRangeTracker().includeTimestamp(toAdd);
236     activeSection.getHeapSize().addAndGet(s);
237     return s;
238   }
239 
240   /**
241    * Get cell length after serialized in {@link KeyValue}
242    */
243   @VisibleForTesting
244   int getCellLength(Cell cell) {
245     return KeyValueUtil.length(cell);
246   }
247 
248   private Cell maybeCloneWithAllocator(Cell cell) {
249     if (activeSection.getMemStoreLAB() == null) {
250       return cell;
251     }
252 
253     int len = getCellLength(cell);
254     ByteRange alloc = activeSection.getMemStoreLAB().allocateBytes(len);
255     if (alloc == null) {
256       // The allocation was too large, allocator decided
257       // not to do anything with it.
258       return cell;
259     }
260     assert alloc.getBytes() != null;
261     KeyValueUtil.appendToByteArray(cell, alloc.getBytes(), alloc.getOffset());
262     KeyValue newKv = new KeyValue(alloc.getBytes(), alloc.getOffset(), len);
263     newKv.setSequenceId(cell.getSequenceId());
264     return newKv;
265   }
266 
267   /**
268    * Remove n key from the memstore. Only cells that have the same key and the
269    * same memstoreTS are removed.  It is ok to not update timeRangeTracker
270    * in this call. It is possible that we can optimize this method by using
271    * tailMap/iterator, but since this method is called rarely (only for
272    * error recovery), we can leave those optimization for the future.
273    * @param cell
274    */
275   @Override
276   public void rollback(Cell cell) {
277     // If the key is in the snapshot, delete it. We should not update
278     // this.size, because that tracks the size of only the memstore and
279     // not the snapshot. The flush of this snapshot to disk has not
280     // yet started because Store.flush() waits for all rwcc transactions to
281     // commit before starting the flush to disk.
282     Cell found = snapshotSection.getCellSkipListSet().get(cell);
283     if (found != null && found.getSequenceId() == cell.getSequenceId()) {
284       snapshotSection.getCellSkipListSet().remove(cell);
285       long sz = heapSizeChange(cell, true);
286       snapshotSection.getHeapSize().addAndGet(-sz);
287     }
288     // If the key is in the memstore, delete it. Update this.size.
289     found = activeSection.getCellSkipListSet().get(cell);
290     if (found != null && found.getSequenceId() == cell.getSequenceId()) {
291       removeFromCellSet(cell);
292       long sz = heapSizeChange(found, true);
293       activeSection.getHeapSize().addAndGet(-sz);
294     }
295   }
296 
297   /**
298    * Write a delete
299    * @param deleteCell
300    * @return approximate size of the passed key and value.
301    */
302   @Override
303   public long delete(Cell deleteCell) {
304     Cell toAdd = maybeCloneWithAllocator(deleteCell);
305     boolean mslabUsed = (toAdd != deleteCell);
306     return internalAdd(toAdd, mslabUsed);
307   }
308 
309   /**
310    * @param cell Find the row that comes after this one.  If null, we return the
311    * first.
312    * @return Next row or null if none found.
313    */
314   Cell getNextRow(final Cell cell) {
315     return getLowest(getNextRow(cell, activeSection.getCellSkipListSet()),
316           getNextRow(cell, snapshotSection.getCellSkipListSet()));
317   }
318 
319   /*
320    * @param a
321    * @param b
322    * @return Return lowest of a or b or null if both a and b are null
323    */
324   private Cell getLowest(final Cell a, final Cell b) {
325     if (a == null) {
326       return b;
327     }
328     if (b == null) {
329       return a;
330     }
331     return comparator.compareRows(a, b) <= 0? a: b;
332   }
333 
334   /*
335    * @param key Find row that follows this one.  If null, return first.
336    * @param map Set to look in for a row beyond <code>row</code>.
337    * @return Next row or null if none found.  If one found, will be a new
338    * KeyValue -- can be destroyed by subsequent calls to this method.
339    */
340   private Cell getNextRow(final Cell key,
341       final NavigableSet<Cell> set) {
342     Cell result = null;
343     SortedSet<Cell> tail = key == null? set: set.tailSet(key);
344     // Iterate until we fall into the next row; i.e. move off current row
345     for (Cell cell: tail) {
346       if (comparator.compareRows(cell, key) <= 0)
347         continue;
348       // Note: Not suppressing deletes or expired cells.  Needs to be handled
349       // by higher up functions.
350       result = cell;
351       break;
352     }
353     return result;
354   }
355 
356   /**
357    * @param state column/delete tracking state
358    */
359   @Override
360   public void getRowKeyAtOrBefore(final GetClosestRowBeforeTracker state) {
361     getRowKeyAtOrBefore(activeSection.getCellSkipListSet(), state);
362     getRowKeyAtOrBefore(snapshotSection.getCellSkipListSet(), state);
363   }
364 
365   /*
366    * @param set
367    * @param state Accumulates deletes and candidates.
368    */
369   private void getRowKeyAtOrBefore(final NavigableSet<Cell> set,
370       final GetClosestRowBeforeTracker state) {
371     if (set.isEmpty()) {
372       return;
373     }
374     if (!walkForwardInSingleRow(set, state.getTargetKey(), state)) {
375       // Found nothing in row.  Try backing up.
376       getRowKeyBefore(set, state);
377     }
378   }
379 
380   /*
381    * Walk forward in a row from <code>firstOnRow</code>.  Presumption is that
382    * we have been passed the first possible key on a row.  As we walk forward
383    * we accumulate deletes until we hit a candidate on the row at which point
384    * we return.
385    * @param set
386    * @param firstOnRow First possible key on this row.
387    * @param state
388    * @return True if we found a candidate walking this row.
389    */
390   private boolean walkForwardInSingleRow(final SortedSet<Cell> set,
391       final Cell firstOnRow, final GetClosestRowBeforeTracker state) {
392     boolean foundCandidate = false;
393     SortedSet<Cell> tail = set.tailSet(firstOnRow);
394     if (tail.isEmpty()) return foundCandidate;
395     for (Iterator<Cell> i = tail.iterator(); i.hasNext();) {
396       Cell kv = i.next();
397       // Did we go beyond the target row? If so break.
398       if (state.isTooFar(kv, firstOnRow)) break;
399       if (state.isExpired(kv)) {
400         i.remove();
401         continue;
402       }
403       // If we added something, this row is a contender. break.
404       if (state.handle(kv)) {
405         foundCandidate = true;
406         break;
407       }
408     }
409     return foundCandidate;
410   }
411 
412   /*
413    * Walk backwards through the passed set a row at a time until we run out of
414    * set or until we get a candidate.
415    * @param set
416    * @param state
417    */
418   private void getRowKeyBefore(NavigableSet<Cell> set,
419       final GetClosestRowBeforeTracker state) {
420     Cell firstOnRow = state.getTargetKey();
421     for (Member p = memberOfPreviousRow(set, state, firstOnRow);
422         p != null; p = memberOfPreviousRow(p.set, state, firstOnRow)) {
423       // Make sure we don't fall out of our table.
424       if (!state.isTargetTable(p.cell)) break;
425       // Stop looking if we've exited the better candidate range.
426       if (!state.isBetterCandidate(p.cell)) break;
427       // Make into firstOnRow
428       firstOnRow = new KeyValue(p.cell.getRowArray(), p.cell.getRowOffset(), p.cell.getRowLength(),
429           HConstants.LATEST_TIMESTAMP);
430       // If we find something, break;
431       if (walkForwardInSingleRow(p.set, firstOnRow, state)) break;
432     }
433   }
434 
435   /**
436    * Only used by tests. TODO: Remove
437    *
438    * Given the specs of a column, update it, first by inserting a new record,
439    * then removing the old one.  Since there is only 1 KeyValue involved, the memstoreTS
440    * will be set to 0, thus ensuring that they instantly appear to anyone. The underlying
441    * store will ensure that the insert/delete each are atomic. A scanner/reader will either
442    * get the new value, or the old value and all readers will eventually only see the new
443    * value after the old was removed.
444    *
445    * @param row
446    * @param family
447    * @param qualifier
448    * @param newValue
449    * @param now
450    * @return  Timestamp
451    */
452   @Override
453   public long updateColumnValue(byte[] row,
454                                 byte[] family,
455                                 byte[] qualifier,
456                                 long newValue,
457                                 long now) {
458     Cell firstCell = KeyValueUtil.createFirstOnRow(row, family, qualifier);
459     // Is there a Cell in 'snapshot' with the same TS? If so, upgrade the timestamp a bit.
460     SortedSet<Cell> snSs = snapshotSection.getCellSkipListSet().tailSet(firstCell);
461     if (!snSs.isEmpty()) {
462       Cell snc = snSs.first();
463       // is there a matching Cell in the snapshot?
464       if (CellUtil.matchingRow(snc, firstCell) && CellUtil.matchingQualifier(snc, firstCell)) {
465         if (snc.getTimestamp() == now) {
466           // poop,
467           now += 1;
468         }
469       }
470     }
471 
472     // logic here: the new ts MUST be at least 'now'. But it could be larger if necessary.
473     // But the timestamp should also be max(now, mostRecentTsInMemstore)
474 
475     // so we cant add the new Cell w/o knowing what's there already, but we also
476     // want to take this chance to delete some cells. So two loops (sad)
477 
478     SortedSet<Cell> ss = activeSection.getCellSkipListSet().tailSet(firstCell);
479     for (Cell cell : ss) {
480       // if this isnt the row we are interested in, then bail:
481       if (!CellUtil.matchingColumn(cell, family, qualifier)
482           || !CellUtil.matchingRow(cell, firstCell)) {
483         break; // rows dont match, bail.
484       }
485 
486       // if the qualifier matches and it's a put, just RM it out of the cellSet.
487       if (cell.getTypeByte() == KeyValue.Type.Put.getCode() &&
488           cell.getTimestamp() > now && CellUtil.matchingQualifier(firstCell, cell)) {
489         now = cell.getTimestamp();
490       }
491     }
492 
493     // create or update (upsert) a new Cell with
494     // 'now' and a 0 memstoreTS == immediately visible
495     List<Cell> cells = new ArrayList<Cell>(1);
496     cells.add(new KeyValue(row, family, qualifier, now, Bytes.toBytes(newValue)));
497     return upsert(cells, 1L, null);
498   }
499 
500   /**
501    * Update or insert the specified KeyValues.
502    * <p>
503    * For each KeyValue, insert into MemStore.  This will atomically upsert the
504    * value for that row/family/qualifier.  If a KeyValue did already exist,
505    * it will then be removed.
506    * <p>
507    * Currently the memstoreTS is kept at 0 so as each insert happens, it will
508    * be immediately visible.  May want to change this so it is atomic across
509    * all KeyValues.
510    * <p>
511    * This is called under row lock, so Get operations will still see updates
512    * atomically.  Scans will only see each KeyValue update as atomic.
513    *
514    * @param cells
515    * @param readpoint readpoint below which we can safely remove duplicate KVs
516    * @param removedCells collect the removed cells. It can be null.
517    * @return change in memstore size
518    */
519   @Override
520   public long upsert(Iterable<Cell> cells, long readpoint, List<Cell> removedCells) {
521     long size = 0;
522     for (Cell cell : cells) {
523       size += upsert(cell, readpoint, removedCells);
524     }
525     return size;
526   }
527 
528   /**
529    * Inserts the specified KeyValue into MemStore and deletes any existing
530    * versions of the same row/family/qualifier as the specified KeyValue.
531    * <p>
532    * First, the specified KeyValue is inserted into the Memstore.
533    * <p>
534    * If there are any existing KeyValues in this MemStore with the same row,
535    * family, and qualifier, they are removed.
536    * <p>
537    * Callers must hold the read lock.
538    *
539    * @param cell
540    * @return change in size of MemStore
541    * @param removedCells collect the removed cells
542    */
543   private long upsert(Cell cell, long readpoint, List<Cell> removedCells) {
544     // Add the Cell to the MemStore
545     // Use the internalAdd method here since we (a) already have a lock
546     // and (b) cannot safely use the MSLAB here without potentially
547     // hitting OOME - see TestMemStore.testUpsertMSLAB for a
548     // test that triggers the pathological case if we don't avoid MSLAB
549     // here.
550     long addedSize = internalAdd(cell, false);
551 
552     // Get the Cells for the row/family/qualifier regardless of timestamp.
553     // For this case we want to clean up any other puts
554     Cell firstCell = KeyValueUtil.createFirstOnRow(
555         cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(),
556         cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength(),
557         cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength());
558     SortedSet<Cell> ss = activeSection.getCellSkipListSet().tailSet(firstCell);
559     Iterator<Cell> it = ss.iterator();
560     // versions visible to oldest scanner
561     int versionsVisible = 0;
562     while ( it.hasNext() ) {
563       Cell cur = it.next();
564 
565       if (cell == cur) {
566         // ignore the one just put in
567         continue;
568       }
569       // check that this is the row and column we are interested in, otherwise bail
570       if (CellUtil.matchingRow(cell, cur) && CellUtil.matchingQualifier(cell, cur)) {
571         // only remove Puts that concurrent scanners cannot possibly see
572         if (cur.getTypeByte() == KeyValue.Type.Put.getCode() &&
573             cur.getSequenceId() <= readpoint) {
574           if (versionsVisible >= 1) {
575             // if we get here we have seen at least one version visible to the oldest scanner,
576             // which means we can prove that no scanner will see this version
577 
578             // false means there was a change, so give us the size.
579             long delta = heapSizeChange(cur, true);
580             addedSize -= delta;
581             activeSection.getHeapSize().addAndGet(-delta);
582             if (removedCells != null) {
583               removedCells.add(cur);
584             }
585             it.remove();
586             setOldestEditTimeToNow();
587           } else {
588             versionsVisible++;
589           }
590         }
591       } else {
592         // past the row or column, done
593         break;
594       }
595     }
596     return addedSize;
597   }
598 
599   /*
600    * Immutable data structure to hold member found in set and the set it was
601    * found in. Include set because it is carrying context.
602    */
603   private static class Member {
604     final Cell cell;
605     final NavigableSet<Cell> set;
606     Member(final NavigableSet<Cell> s, final Cell kv) {
607       this.cell = kv;
608       this.set = s;
609     }
610   }
611 
612   /*
613    * @param set Set to walk back in.  Pass a first in row or we'll return
614    * same row (loop).
615    * @param state Utility and context.
616    * @param firstOnRow First item on the row after the one we want to find a
617    * member in.
618    * @return Null or member of row previous to <code>firstOnRow</code>
619    */
620   private Member memberOfPreviousRow(NavigableSet<Cell> set,
621       final GetClosestRowBeforeTracker state, final Cell firstOnRow) {
622     NavigableSet<Cell> head = set.headSet(firstOnRow, false);
623     if (head.isEmpty()) return null;
624     for (Iterator<Cell> i = head.descendingIterator(); i.hasNext();) {
625       Cell found = i.next();
626       if (state.isExpired(found)) {
627         i.remove();
628         continue;
629       }
630       return new Member(head, found);
631     }
632     return null;
633   }
634 
635   /**
636    * @return scanner on memstore and snapshot in this order.
637    */
638   @Override
639   public List<KeyValueScanner> getScanners(long readPt) {
640     MemStoreScanner scanner =
641       new MemStoreScanner(activeSection, snapshotSection, readPt, comparator);
642     scanner.seek(CellUtil.createCell(HConstants.EMPTY_START_ROW));
643     if (scanner.peek() == null) {
644       scanner.close();
645       return null;
646     }
647     return Collections.<KeyValueScanner> singletonList(scanner);
648   }
649 
650   /**
651    * Check if this memstore may contain the required keys
652    * @param scan scan
653    * @param store holds reference to cf
654    * @param oldestUnexpiredTS
655    * @return False if the key definitely does not exist in this Memstore
656    */
657   public boolean shouldSeek(Scan scan, Store store, long oldestUnexpiredTS) {
658     return shouldSeek(activeSection.getTimeRangeTracker(),
659         snapshotSection.getTimeRangeTracker(), scan, store, oldestUnexpiredTS);
660   }
661 
662   /**
663    * Check if this memstore may contain the required keys
664    * @param activeTimeRangeTracker the tracker of active data
665    * @param snapshotTimeRangeTracker the tracker of snapshot data
666    * @param scan scan
667    * @param store holds reference to cf
668    * @param oldestUnexpiredTS
669    * @return False if the key definitely does not exist in this Memstore
670    */
671   private static boolean shouldSeek(TimeRangeTracker activeTimeRangeTracker,
672       TimeRangeTracker snapshotTimeRangeTracker, Scan scan, Store store, long oldestUnexpiredTS) {
673     byte[] cf = store.getFamily().getName();
674     TimeRange timeRange = scan.getColumnFamilyTimeRange().get(cf);
675     if (timeRange == null) {
676       timeRange = scan.getTimeRange();
677     }
678     return (activeTimeRangeTracker.includesTimeRange(timeRange) ||
679       snapshotTimeRangeTracker.includesTimeRange(timeRange)) &&
680       (Math.max(activeTimeRangeTracker.getMax(), snapshotTimeRangeTracker.getMax()) >= oldestUnexpiredTS);
681   }
682 
683   /*
684    * MemStoreScanner implements the KeyValueScanner.
685    * It lets the caller scan the contents of a memstore -- both current
686    * map and snapshot.
687    * This behaves as if it were a real scanner but does not maintain position.
688    */
689   protected static class MemStoreScanner extends NonLazyKeyValueScanner {
690     // Next row information for either cellSet or snapshot
691     private Cell cellSetNextRow = null;
692     private Cell snapshotNextRow = null;
693 
694     // last iterated Cells for cellSet and snapshot (to restore iterator state after reseek)
695     private Cell cellSetItRow = null;
696     private Cell snapshotItRow = null;
697     
698     // iterator based scanning.
699     private Iterator<Cell> cellSetIt;
700     private Iterator<Cell> snapshotIt;
701 
702     // The cellSet and snapshot at the time of creating this scanner
703     private final Section activeAtCreation;
704     private final Section snapshotAtCreation;
705 
706     // the pre-calculated Cell to be returned by peek() or next()
707     private Cell theNext;
708 
709     // A flag represents whether could stop skipping Cells for MVCC
710     // if have encountered the next row. Only used for reversed scan
711     private boolean stopSkippingCellsIfNextRow = false;
712     // Stop skipping KeyValues for MVCC if finish this row. Only used for reversed scan
713     private Cell stopSkippingKVsRow;
714 
715     private final long readPoint;
716     private final KeyValue.KVComparator comparator;
717     /*
718     Some notes...
719 
720      So memstorescanner is fixed at creation time. this includes pointers/iterators into
721     existing kvset/snapshot.  during a snapshot creation, the kvset is null, and the
722     snapshot is moved.  since kvset is null there is no point on reseeking on both,
723       we can save us the trouble. During the snapshot->hfile transition, the memstore
724       scanner is re-created by StoreScanner#updateReaders().  StoreScanner should
725       potentially do something smarter by adjusting the existing memstore scanner.
726 
727       But there is a greater problem here, that being once a scanner has progressed
728       during a snapshot scenario, we currently iterate past the kvset then 'finish' up.
729       if a scan lasts a little while, there is a chance for new entries in kvset to
730       become available but we will never see them.  This needs to be handled at the
731       StoreScanner level with coordination with MemStoreScanner.
732 
733       Currently, this problem is only partly managed: during the small amount of time
734       when the StoreScanner has not yet created a new MemStoreScanner, we will miss
735       the adds to kvset in the MemStoreScanner.
736     */
737 
738     MemStoreScanner(Section activeSection, Section snapshotSection, long readPoint, final KeyValue.KVComparator c) {
739       this.readPoint = readPoint;
740       this.comparator = c;
741       activeAtCreation = activeSection;
742       snapshotAtCreation = snapshotSection;
743       if (activeAtCreation.getMemStoreLAB() != null) {
744         activeAtCreation.getMemStoreLAB().incScannerCount();
745       }
746       if (snapshotAtCreation.getMemStoreLAB() != null) {
747         snapshotAtCreation.getMemStoreLAB().incScannerCount();
748       }
749       if (Trace.isTracing() && Trace.currentSpan() != null) {
750         Trace.currentSpan().addTimelineAnnotation("Creating MemStoreScanner");
751       }
752     }
753 
754     /**
755      * Lock on 'this' must be held by caller.
756      * @param it
757      * @return Next Cell
758      */
759     private Cell getNext(Iterator<Cell> it) {
760       Cell v = null;
761       try {
762         while (it.hasNext()) {
763           v = it.next();
764           if (v.getSequenceId() <= this.readPoint) {
765             return v;
766           }
767           if (stopSkippingCellsIfNextRow && stopSkippingKVsRow != null
768               && comparator.compareRows(v, stopSkippingKVsRow) > 0) {
769             return null;
770           }
771         }
772 
773         return null;
774       } finally {
775         if (v != null) {
776           // in all cases, remember the last Cell iterated to
777           if (it == snapshotIt) {
778             snapshotItRow = v;
779           } else {
780             cellSetItRow = v;
781           }
782         }
783       }
784     }
785 
786     /**
787      *  Set the scanner at the seek key.
788      *  Must be called only once: there is no thread safety between the scanner
789      *   and the memStore.
790      * @param key seek value
791      * @return false if the key is null or if there is no data
792      */
793     @Override
794     public synchronized boolean seek(Cell key) {
795       if (key == null) {
796         close();
797         return false;
798       }
799       // kvset and snapshot will never be null.
800       // if tailSet can't find anything, SortedSet is empty (not null).
801       cellSetIt = activeAtCreation.getCellSkipListSet().tailSet(key).iterator();
802       snapshotIt = snapshotAtCreation.getCellSkipListSet().tailSet(key).iterator();
803       cellSetItRow = null;
804       snapshotItRow = null;
805 
806       return seekInSubLists(key);
807     }
808 
809 
810     /**
811      * (Re)initialize the iterators after a seek or a reseek.
812      */
813     private synchronized boolean seekInSubLists(Cell key){
814       cellSetNextRow = getNext(cellSetIt);
815       snapshotNextRow = getNext(snapshotIt);
816 
817       // Calculate the next value
818       theNext = getLowest(cellSetNextRow, snapshotNextRow);
819 
820       // has data
821       return (theNext != null);
822     }
823 
824 
825     /**
826      * Move forward on the sub-lists set previously by seek.
827      * @param key seek value (should be non-null)
828      * @return true if there is at least one KV to read, false otherwise
829      */
830     @Override
831     public synchronized boolean reseek(Cell key) {
832       /*
833       See HBASE-4195 & HBASE-3855 & HBASE-6591 for the background on this implementation.
834       This code is executed concurrently with flush and puts, without locks.
835       Two points must be known when working on this code:
836       1) It's not possible to use the 'kvTail' and 'snapshot'
837        variables, as they are modified during a flush.
838       2) The ideal implementation for performance would use the sub skip list
839        implicitly pointed by the iterators 'kvsetIt' and
840        'snapshotIt'. Unfortunately the Java API does not offer a method to
841        get it. So we remember the last keys we iterated to and restore
842        the reseeked set to at least that point.
843        */
844       cellSetIt = activeAtCreation.getCellSkipListSet().tailSet(getHighest(key, cellSetItRow)).iterator();
845       snapshotIt = snapshotAtCreation.getCellSkipListSet().tailSet(getHighest(key, snapshotItRow)).iterator();
846 
847       return seekInSubLists(key);
848     }
849 
850 
851     @Override
852     public synchronized Cell peek() {
853       //DebugPrint.println(" MS@" + hashCode() + " peek = " + getLowest());
854       return theNext;
855     }
856 
857     @Override
858     public synchronized Cell next() {
859       if (theNext == null) {
860           return null;
861       }
862 
863       final Cell ret = theNext;
864 
865       // Advance one of the iterators
866       if (theNext == cellSetNextRow) {
867         cellSetNextRow = getNext(cellSetIt);
868       } else {
869         snapshotNextRow = getNext(snapshotIt);
870       }
871 
872       // Calculate the next value
873       theNext = getLowest(cellSetNextRow, snapshotNextRow);
874 
875       //long readpoint = ReadWriteConsistencyControl.getThreadReadPoint();
876       //DebugPrint.println(" MS@" + hashCode() + " next: " + theNext + " next_next: " +
877       //    getLowest() + " threadpoint=" + readpoint);
878       return ret;
879     }
880 
881     /*
882      * Returns the lower of the two key values, or null if they are both null.
883      * This uses comparator.compare() to compare the KeyValue using the memstore
884      * comparator.
885      */
886     private Cell getLowest(Cell first, Cell second) {
887       if (first == null && second == null) {
888         return null;
889       }
890       if (first != null && second != null) {
891         int compare = comparator.compare(first, second);
892         return (compare <= 0 ? first : second);
893       }
894       return (first != null ? first : second);
895     }
896 
897     /*
898      * Returns the higher of the two cells, or null if they are both null.
899      * This uses comparator.compare() to compare the Cell using the memstore
900      * comparator.
901      */
902     private Cell getHighest(Cell first, Cell second) {
903       if (first == null && second == null) {
904         return null;
905       }
906       if (first != null && second != null) {
907         int compare = comparator.compare(first, second);
908         return (compare > 0 ? first : second);
909       }
910       return (first != null ? first : second);
911     }
912 
913     @Override
914     public synchronized void close() {
915       this.cellSetNextRow = null;
916       this.snapshotNextRow = null;
917 
918       this.cellSetIt = null;
919       this.snapshotIt = null;
920 
921       if (activeAtCreation != null && activeAtCreation.getMemStoreLAB() != null) {
922         activeAtCreation.getMemStoreLAB().decScannerCount();
923       }
924       if (snapshotAtCreation != null && snapshotAtCreation.getMemStoreLAB() != null) {
925         snapshotAtCreation.getMemStoreLAB().decScannerCount();
926       }
927 
928       this.cellSetItRow = null;
929       this.snapshotItRow = null;
930     }
931 
932     /**
933      * MemStoreScanner returns max value as sequence id because it will
934      * always have the latest data among all files.
935      */
936     @Override
937     public long getSequenceID() {
938       return Long.MAX_VALUE;
939     }
940 
941     @Override
942     public boolean shouldUseScanner(Scan scan, Store store, long oldestUnexpiredTS) {
943       return shouldSeek(activeAtCreation.getTimeRangeTracker(),
944         snapshotAtCreation.getTimeRangeTracker(), scan, store, oldestUnexpiredTS);
945     }
946 
947     /**
948      * Seek scanner to the given key first. If it returns false(means
949      * peek()==null) or scanner's peek row is bigger than row of given key, seek
950      * the scanner to the previous row of given key
951      */
952     @Override
953     public synchronized boolean backwardSeek(Cell key) {
954       seek(key);
955       if (peek() == null || comparator.compareRows(peek(), key) > 0) {
956         return seekToPreviousRow(key);
957       }
958       return true;
959     }
960 
961     /**
962      * Separately get the KeyValue before the specified key from kvset and
963      * snapshotset, and use the row of higher one as the previous row of
964      * specified key, then seek to the first KeyValue of previous row
965      */
966     @Override
967     public synchronized boolean seekToPreviousRow(Cell originalKey) {
968       boolean keepSeeking = false;
969       Cell key = originalKey;
970       do {
971         Cell firstKeyOnRow = KeyValueUtil.createFirstOnRow(key.getRowArray(), key.getRowOffset(),
972             key.getRowLength());
973         SortedSet<Cell> cellHead = activeAtCreation.getCellSkipListSet().headSet(firstKeyOnRow);
974         Cell cellSetBeforeRow = cellHead.isEmpty() ? null : cellHead.last();
975         SortedSet<Cell> snapshotHead = snapshotAtCreation.getCellSkipListSet()
976             .headSet(firstKeyOnRow);
977         Cell snapshotBeforeRow = snapshotHead.isEmpty() ? null : snapshotHead
978             .last();
979         Cell lastCellBeforeRow = getHighest(cellSetBeforeRow, snapshotBeforeRow);
980         if (lastCellBeforeRow == null) {
981           theNext = null;
982           return false;
983         }
984         Cell firstKeyOnPreviousRow = KeyValueUtil.createFirstOnRow(lastCellBeforeRow.getRowArray(),
985             lastCellBeforeRow.getRowOffset(), lastCellBeforeRow.getRowLength());
986         this.stopSkippingCellsIfNextRow = true;
987         this.stopSkippingKVsRow = firstKeyOnPreviousRow;
988         seek(firstKeyOnPreviousRow);
989         this.stopSkippingCellsIfNextRow = false;
990         if (peek() == null
991             || comparator.compareRows(peek(), firstKeyOnPreviousRow) > 0) {
992           keepSeeking = true;
993           key = firstKeyOnPreviousRow;
994           continue;
995         } else {
996           keepSeeking = false;
997         }
998       } while (keepSeeking);
999       return true;
1000     }
1001 
1002     @Override
1003     public synchronized boolean seekToLastRow() {
1004       Cell first = activeAtCreation.getCellSkipListSet().isEmpty() ? null
1005         : activeAtCreation.getCellSkipListSet().last();
1006       Cell second = snapshotAtCreation.getCellSkipListSet().isEmpty() ? null
1007           : snapshotAtCreation.getCellSkipListSet().last();
1008       Cell higherCell = getHighest(first, second);
1009       if (higherCell == null) {
1010         return false;
1011       }
1012       Cell firstCellOnLastRow = KeyValueUtil.createFirstOnRow(higherCell.getRowArray(),
1013           higherCell.getRowOffset(), higherCell.getRowLength());
1014       if (seek(firstCellOnLastRow)) {
1015         return true;
1016       } else {
1017         return seekToPreviousRow(higherCell);
1018       }
1019 
1020     }
1021   }
1022 
1023   public final static long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT
1024       + (4 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + Bytes.SIZEOF_BOOLEAN);
1025 
1026   public final static long DEEP_OVERHEAD = ClassSize.align(FIXED_OVERHEAD +
1027       (2 * ClassSize.ATOMIC_LONG) + (2 * ClassSize.TIMERANGE_TRACKER) +
1028       (2 * ClassSize.CELL_SKIPLIST_SET) + (2 * ClassSize.CONCURRENT_SKIPLISTMAP));
1029 
1030   /*
1031    * Calculate how the MemStore size has changed.  Includes overhead of the
1032    * backing Map.
1033    * @param cell
1034    * @param notpresent True if the cell was NOT present in the set.
1035    * @return Size
1036    */
1037   static long heapSizeChange(final Cell cell, final boolean notpresent) {
1038     return notpresent ? ClassSize.align(ClassSize.CONCURRENT_SKIPLISTMAP_ENTRY
1039         + CellUtil.estimatedHeapSizeOf(cell)) : 0;
1040   }
1041 
1042   private long keySize() {
1043     return heapSize() - DEEP_OVERHEAD;
1044   }
1045 
1046   /**
1047    * Get the entire heap usage for this MemStore not including keys in the
1048    * snapshot.
1049    */
1050   @Override
1051   public long heapSize() {
1052     return activeSection.getHeapSize().get();
1053   }
1054 
1055   @Override
1056   public long size() {
1057     return heapSize();
1058   }
1059 
1060   /**
1061    * Code to help figure if our approximation of object heap sizes is close
1062    * enough.  See hbase-900.  Fills memstores then waits so user can heap
1063    * dump and bring up resultant hprof in something like jprofiler which
1064    * allows you get 'deep size' on objects.
1065    * @param args main args
1066    */
1067   public static void main(String [] args) {
1068     RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
1069     LOG.info("vmName=" + runtime.getVmName() + ", vmVendor=" +
1070       runtime.getVmVendor() + ", vmVersion=" + runtime.getVmVersion());
1071     LOG.info("vmInputArguments=" + runtime.getInputArguments());
1072     DefaultMemStore memstore1 = new DefaultMemStore();
1073     // TODO: x32 vs x64
1074     long size = 0;
1075     final int count = 10000;
1076     byte [] fam = Bytes.toBytes("col");
1077     byte [] qf = Bytes.toBytes("umn");
1078     byte [] empty = new byte[0];
1079     for (int i = 0; i < count; i++) {
1080       // Give each its own ts
1081       size += memstore1.add(new KeyValue(Bytes.toBytes(i), fam, qf, i, empty));
1082     }
1083     LOG.info("memstore1 estimated size=" + size);
1084     for (int i = 0; i < count; i++) {
1085       size += memstore1.add(new KeyValue(Bytes.toBytes(i), fam, qf, i, empty));
1086     }
1087     LOG.info("memstore1 estimated size (2nd loading of same data)=" + size);
1088     // Make a variably sized memstore.
1089     DefaultMemStore memstore2 = new DefaultMemStore();
1090     for (int i = 0; i < count; i++) {
1091       size += memstore2.add(new KeyValue(Bytes.toBytes(i), fam, qf, i, new byte[i]));
1092     }
1093     LOG.info("memstore2 estimated size=" + size);
1094     final int seconds = 30;
1095     LOG.info("Waiting " + seconds + " seconds while heap dump is taken");
1096     for (int i = 0; i < seconds; i++) {
1097       // Thread.sleep(1000);
1098     }
1099     LOG.info("Exiting.");
1100   }
1101 
1102   /**
1103    * Contains the fields which are useful to MemStoreScanner.
1104    */
1105   @InterfaceAudience.Private
1106   @VisibleForTesting
1107   static class Section {
1108     /**
1109      * MemStore.  Use a CellSkipListSet rather than SkipListSet because of the
1110      * better semantics.  The Map will overwrite if passed a key it already had
1111      * whereas the Set will not add new Cell if key is same though value might be
1112      * different.  Value is not important -- just make sure always same reference passed.
1113      */
1114     private final CellSkipListSet cellSet;
1115     private final TimeRangeTracker tracker = new TimeRangeTracker();
1116     /**
1117      * Used to track own heapSize.
1118      */
1119     private final AtomicLong heapSize;
1120     private final MemStoreLAB allocator;
1121 
1122     static Section newSnapshotSection(final KeyValue.KVComparator c) {
1123       return new Section(c, null, 0);
1124     }
1125 
1126     static Section newActiveSection(final KeyValue.KVComparator c,
1127             final Configuration conf) {
1128       return new Section(c, conf, DEEP_OVERHEAD);
1129     }
1130 
1131     private Section(final KeyValue.KVComparator c,
1132             final Configuration conf, long initHeapSize) {
1133       this.cellSet = new CellSkipListSet(c);
1134       this.heapSize = new AtomicLong(initHeapSize);
1135       if (conf != null && conf.getBoolean(USEMSLAB_KEY, USEMSLAB_DEFAULT)) {
1136         String className = conf.get(MSLAB_CLASS_NAME, HeapMemStoreLAB.class.getName());
1137         this.allocator = ReflectionUtils.instantiateWithCustomCtor(className,
1138                 new Class[]{Configuration.class}, new Object[]{conf});
1139       } else {
1140         this.allocator = null;
1141       }
1142     }
1143 
1144     CellSkipListSet getCellSkipListSet() {
1145       return cellSet;
1146     }
1147 
1148     TimeRangeTracker getTimeRangeTracker() {
1149       return tracker;
1150     }
1151 
1152     AtomicLong getHeapSize() {
1153       return heapSize;
1154     }
1155 
1156     MemStoreLAB getMemStoreLAB() {
1157       return allocator;
1158     }
1159 
1160   }
1161 }