001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.hadoop.hbase.regionserver;
020
021import java.io.IOException;
022import java.lang.management.ManagementFactory;
023import java.lang.management.RuntimeMXBean;
024import java.util.ArrayList;
025import java.util.List;
026
027import org.apache.hadoop.conf.Configuration;
028import org.apache.hadoop.hbase.Cell;
029import org.apache.hadoop.hbase.CellComparator;
030import org.apache.hadoop.hbase.HBaseConfiguration;
031import org.apache.hadoop.hbase.HConstants;
032import org.apache.hadoop.hbase.KeyValue;
033import org.apache.yetus.audience.InterfaceAudience;
034import org.slf4j.Logger;
035import org.slf4j.LoggerFactory;
036import org.apache.hadoop.hbase.util.Bytes;
037import org.apache.hadoop.hbase.util.ClassSize;
038import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
039
040/**
041 * The MemStore holds in-memory modifications to the Store.  Modifications
042 * are {@link Cell}s.  When asked to flush, current memstore is moved
043 * to snapshot and is cleared.  We continue to serve edits out of new memstore
044 * and backing snapshot until flusher reports in that the flush succeeded. At
045 * this point we let the snapshot go.
046 *  <p>
047 * The MemStore functions should not be called in parallel. Callers should hold
048 *  write and read locks. This is done in {@link HStore}.
049 *  </p>
050 *
051 * TODO: Adjust size of the memstore when we remove items because they have
052 * been deleted.
053 * TODO: With new KVSLS, need to make sure we update HeapSize with difference
054 * in KV size.
055 */
056@InterfaceAudience.Private
057public class DefaultMemStore extends AbstractMemStore {
058  private static final Logger LOG = LoggerFactory.getLogger(DefaultMemStore.class);
059
060  public final static long DEEP_OVERHEAD = ClassSize.align(AbstractMemStore.DEEP_OVERHEAD);
061  public final static long FIXED_OVERHEAD = ClassSize.align(AbstractMemStore.FIXED_OVERHEAD);
062  /**
063   * Default constructor. Used for tests.
064   */
065  public DefaultMemStore() {
066    this(HBaseConfiguration.create(), CellComparator.getInstance());
067  }
068
069  /**
070   * Constructor.
071   * @param c Comparator
072   */
073  public DefaultMemStore(final Configuration conf, final CellComparator c) {
074    super(conf, c);
075  }
076
077  /**
078   * Creates a snapshot of the current memstore.
079   * Snapshot must be cleared by call to {@link #clearSnapshot(long)}
080   */
081  @Override
082  public MemStoreSnapshot snapshot() {
083    // If snapshot currently has entries, then flusher failed or didn't call
084    // cleanup.  Log a warning.
085    if (!this.snapshot.isEmpty()) {
086      LOG.warn("Snapshot called again without clearing previous. " +
087          "Doing nothing. Another ongoing flush or did we fail last attempt?");
088    } else {
089      this.snapshotId = EnvironmentEdgeManager.currentTime();
090      if (!this.active.isEmpty()) {
091        ImmutableSegment immutableSegment = SegmentFactory.instance().
092            createImmutableSegment(this.active);
093        this.snapshot = immutableSegment;
094        resetActive();
095      }
096    }
097    return new MemStoreSnapshot(this.snapshotId, this.snapshot);
098  }
099
100  @Override
101  public MemStoreSize getFlushableSize() {
102    MemStoreSize mss = getSnapshotSize();
103    return mss.getDataSize() > 0? mss: this.active.getMemStoreSize();
104  }
105
106  @Override
107  protected long keySize() {
108    return this.active.getDataSize();
109  }
110
111  @Override
112  protected long heapSize() {
113    return this.active.getHeapSize();
114  }
115
116  @Override
117  /*
118   * Scanners are ordered from 0 (oldest) to newest in increasing order.
119   */
120  public List<KeyValueScanner> getScanners(long readPt) throws IOException {
121    List<KeyValueScanner> list = new ArrayList<>();
122    long order = snapshot.getNumOfSegments();
123    order = addToScanners(active, readPt, order, list);
124    addToScanners(snapshot.getAllSegments(), readPt, order, list);
125    return list;
126  }
127
128  @Override
129  protected List<Segment> getSegments() throws IOException {
130    List<Segment> list = new ArrayList<>(2);
131    list.add(this.active);
132    list.add(this.snapshot);
133    return list;
134  }
135
136  /**
137   * @param cell Find the row that comes after this one.  If null, we return the
138   * first.
139   * @return Next row or null if none found.
140   */
141  Cell getNextRow(final Cell cell) {
142    return getLowest(
143        getNextRow(cell, this.active.getCellSet()),
144        getNextRow(cell, this.snapshot.getCellSet()));
145  }
146
147  @Override public void updateLowestUnflushedSequenceIdInWAL(boolean onlyIfMoreRecent) {
148  }
149
150  @Override
151  public MemStoreSize size() {
152    return active.getMemStoreSize();
153  }
154
155  /**
156   * Check whether anything need to be done based on the current active set size
157   * Nothing need to be done for the DefaultMemStore
158   */
159  @Override
160  protected void checkActiveSize() {
161    return;
162  }
163
164  @Override
165  public long preFlushSeqIDEstimation() {
166    return HConstants.NO_SEQNUM;
167  }
168
169  @Override public boolean isSloppy() {
170    return false;
171  }
172
173  /**
174   * Code to help figure if our approximation of object heap sizes is close
175   * enough.  See hbase-900.  Fills memstores then waits so user can heap
176   * dump and bring up resultant hprof in something like jprofiler which
177   * allows you get 'deep size' on objects.
178   * @param args main args
179   */
180  public static void main(String [] args) {
181    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
182    LOG.info("vmName=" + runtime.getVmName() + ", vmVendor=" +
183      runtime.getVmVendor() + ", vmVersion=" + runtime.getVmVersion());
184    LOG.info("vmInputArguments=" + runtime.getInputArguments());
185    DefaultMemStore memstore1 = new DefaultMemStore();
186    // TODO: x32 vs x64
187    final int count = 10000;
188    byte [] fam = Bytes.toBytes("col");
189    byte [] qf = Bytes.toBytes("umn");
190    byte [] empty = new byte[0];
191    MemStoreSizing memStoreSizing = new NonThreadSafeMemStoreSizing();
192    for (int i = 0; i < count; i++) {
193      // Give each its own ts
194      memstore1.add(new KeyValue(Bytes.toBytes(i), fam, qf, i, empty), memStoreSizing);
195    }
196    LOG.info("memstore1 estimated size={}", memStoreSizing.getMemStoreSize().getDataSize() +
197        memStoreSizing.getMemStoreSize().getHeapSize());
198    for (int i = 0; i < count; i++) {
199      memstore1.add(new KeyValue(Bytes.toBytes(i), fam, qf, i, empty), memStoreSizing);
200    }
201    LOG.info("memstore1 estimated size (2nd loading of same data)={}",
202        memStoreSizing.getMemStoreSize().getDataSize() +
203            memStoreSizing.getMemStoreSize().getHeapSize());
204    // Make a variably sized memstore.
205    DefaultMemStore memstore2 = new DefaultMemStore();
206    memStoreSizing = new NonThreadSafeMemStoreSizing();
207    for (int i = 0; i < count; i++) {
208      memstore2.add(new KeyValue(Bytes.toBytes(i), fam, qf, i, new byte[i]), memStoreSizing);
209    }
210    LOG.info("memstore2 estimated size={}", memStoreSizing.getMemStoreSize().getDataSize() +
211        memStoreSizing.getMemStoreSize().getHeapSize());
212    final int seconds = 30;
213    LOG.info("Waiting " + seconds + " seconds while heap dump is taken");
214    LOG.info("Exiting.");
215  }
216}