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