001/* 002 * 003 * Licensed to the Apache Software Foundation (ASF) under one 004 * or more contributor license agreements. See the NOTICE file 005 * distributed with this work for additional information 006 * regarding copyright ownership. The ASF licenses this file 007 * to you under the Apache License, Version 2.0 (the 008 * "License"); you may not use this file except in compliance 009 * with the License. You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 */ 019package org.apache.hadoop.hbase.regionserver; 020 021import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting; 022import java.io.IOException; 023import java.util.List; 024import java.util.NavigableSet; 025import java.util.SortedSet; 026 027import org.apache.hadoop.conf.Configuration; 028import org.apache.hadoop.hbase.Cell; 029import org.apache.hadoop.hbase.CellComparator; 030import org.apache.hadoop.hbase.ExtendedCell; 031import org.apache.yetus.audience.InterfaceAudience; 032import org.slf4j.Logger; 033import org.apache.hadoop.hbase.exceptions.UnexpectedStateException; 034import org.apache.hadoop.hbase.util.Bytes; 035import org.apache.hadoop.hbase.util.ClassSize; 036import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; 037 038/** 039 * An abstract class, which implements the behaviour shared by all concrete memstore instances. 040 */ 041@InterfaceAudience.Private 042public abstract class AbstractMemStore implements MemStore { 043 044 private static final long NO_SNAPSHOT_ID = -1; 045 046 private final Configuration conf; 047 private final CellComparator comparator; 048 049 // active segment absorbs write operations 050 protected volatile MutableSegment active; 051 // Snapshot of memstore. Made for flusher. 052 protected volatile ImmutableSegment snapshot; 053 protected volatile long snapshotId; 054 // Used to track when to flush 055 private volatile long timeOfOldestEdit; 056 057 public final static long FIXED_OVERHEAD = (long) ClassSize.OBJECT 058 + (4 * ClassSize.REFERENCE) 059 + (2 * Bytes.SIZEOF_LONG); // snapshotId, timeOfOldestEdit 060 061 public final static long DEEP_OVERHEAD = FIXED_OVERHEAD; 062 063 public static long addToScanners(List<? extends Segment> segments, long readPt, long order, 064 List<KeyValueScanner> scanners) { 065 for (Segment item : segments) { 066 order = addToScanners(item, readPt, order, scanners); 067 } 068 return order; 069 } 070 071 protected static long addToScanners(Segment segment, long readPt, long order, 072 List<KeyValueScanner> scanners) { 073 scanners.add(segment.getScanner(readPt, order)); 074 return order - 1; 075 } 076 077 protected AbstractMemStore(final Configuration conf, final CellComparator c) { 078 this.conf = conf; 079 this.comparator = c; 080 resetActive(); 081 this.snapshot = SegmentFactory.instance().createImmutableSegment(c); 082 this.snapshotId = NO_SNAPSHOT_ID; 083 } 084 085 protected void resetActive() { 086 // Reset heap to not include any keys 087 this.active = SegmentFactory.instance().createMutableSegment(conf, comparator); 088 this.timeOfOldestEdit = Long.MAX_VALUE; 089 } 090 091 /** 092 * Updates the wal with the lowest sequence id (oldest entry) that is still in memory 093 * @param onlyIfMoreRecent a flag that marks whether to update the sequence id no matter what or 094 * only if it is greater than the previous sequence id 095 */ 096 public abstract void updateLowestUnflushedSequenceIdInWAL(boolean onlyIfMoreRecent); 097 098 @Override 099 public void add(Iterable<Cell> cells, MemStoreSizing memstoreSizing) { 100 for (Cell cell : cells) { 101 add(cell, memstoreSizing); 102 } 103 } 104 105 @Override 106 public void add(Cell cell, MemStoreSizing memstoreSizing) { 107 Cell toAdd = maybeCloneWithAllocator(cell, false); 108 boolean mslabUsed = (toAdd != cell); 109 // This cell data is backed by the same byte[] where we read request in RPC(See HBASE-15180). By 110 // default MSLAB is ON and we might have copied cell to MSLAB area. If not we must do below deep 111 // copy. Or else we will keep referring to the bigger chunk of memory and prevent it from 112 // getting GCed. 113 // Copy to MSLAB would not have happened if 114 // 1. MSLAB is turned OFF. See "hbase.hregion.memstore.mslab.enabled" 115 // 2. When the size of the cell is bigger than the max size supported by MSLAB. See 116 // "hbase.hregion.memstore.mslab.max.allocation". This defaults to 256 KB 117 // 3. When cells are from Append/Increment operation. 118 if (!mslabUsed) { 119 toAdd = deepCopyIfNeeded(toAdd); 120 } 121 internalAdd(toAdd, mslabUsed, memstoreSizing); 122 } 123 124 private static Cell deepCopyIfNeeded(Cell cell) { 125 if (cell instanceof ExtendedCell) { 126 return ((ExtendedCell) cell).deepClone(); 127 } 128 return cell; 129 } 130 131 @Override 132 public void upsert(Iterable<Cell> cells, long readpoint, MemStoreSizing memstoreSizing) { 133 for (Cell cell : cells) { 134 upsert(cell, readpoint, memstoreSizing); 135 } 136 } 137 138 /** 139 * @return Oldest timestamp of all the Cells in the MemStore 140 */ 141 @Override 142 public long timeOfOldestEdit() { 143 return timeOfOldestEdit; 144 } 145 146 /** 147 * The passed snapshot was successfully persisted; it can be let go. 148 * @param id Id of the snapshot to clean out. 149 * @see MemStore#snapshot() 150 */ 151 @Override 152 public void clearSnapshot(long id) throws UnexpectedStateException { 153 if (this.snapshotId == -1) return; // already cleared 154 if (this.snapshotId != id) { 155 throw new UnexpectedStateException("Current snapshot id is " + this.snapshotId + ",passed " 156 + id); 157 } 158 // OK. Passed in snapshot is same as current snapshot. If not-empty, 159 // create a new snapshot and let the old one go. 160 Segment oldSnapshot = this.snapshot; 161 if (!this.snapshot.isEmpty()) { 162 this.snapshot = SegmentFactory.instance().createImmutableSegment(this.comparator); 163 } 164 this.snapshotId = NO_SNAPSHOT_ID; 165 oldSnapshot.close(); 166 } 167 168 @Override 169 public MemStoreSize getSnapshotSize() { 170 return this.snapshot.getMemStoreSize(); 171 } 172 173 @Override 174 public String toString() { 175 StringBuilder buf = new StringBuilder(); 176 int i = 1; 177 try { 178 for (Segment segment : getSegments()) { 179 buf.append("Segment (" + i + ") " + segment.toString() + "; "); 180 i++; 181 } 182 } catch (IOException e){ 183 return e.toString(); 184 } 185 return buf.toString(); 186 } 187 188 protected Configuration getConfiguration() { 189 return conf; 190 } 191 192 protected void dump(Logger log) { 193 active.dump(log); 194 snapshot.dump(log); 195 } 196 197 198 /* 199 * Inserts the specified Cell into MemStore and deletes any existing 200 * versions of the same row/family/qualifier as the specified Cell. 201 * <p> 202 * First, the specified Cell is inserted into the Memstore. 203 * <p> 204 * If there are any existing Cell in this MemStore with the same row, 205 * family, and qualifier, they are removed. 206 * <p> 207 * Callers must hold the read lock. 208 * 209 * @param cell the cell to be updated 210 * @param readpoint readpoint below which we can safely remove duplicate KVs 211 * @param memstoreSize 212 */ 213 private void upsert(Cell cell, long readpoint, MemStoreSizing memstoreSizing) { 214 // Add the Cell to the MemStore 215 // Use the internalAdd method here since we (a) already have a lock 216 // and (b) cannot safely use the MSLAB here without potentially 217 // hitting OOME - see TestMemStore.testUpsertMSLAB for a 218 // test that triggers the pathological case if we don't avoid MSLAB 219 // here. 220 // This cell data is backed by the same byte[] where we read request in RPC(See HBASE-15180). We 221 // must do below deep copy. Or else we will keep referring to the bigger chunk of memory and 222 // prevent it from getting GCed. 223 cell = deepCopyIfNeeded(cell); 224 this.active.upsert(cell, readpoint, memstoreSizing); 225 setOldestEditTimeToNow(); 226 checkActiveSize(); 227 } 228 229 /* 230 * @param a 231 * @param b 232 * @return Return lowest of a or b or null if both a and b are null 233 */ 234 protected Cell getLowest(final Cell a, final Cell b) { 235 if (a == null) { 236 return b; 237 } 238 if (b == null) { 239 return a; 240 } 241 return comparator.compareRows(a, b) <= 0? a: b; 242 } 243 244 /* 245 * @param key Find row that follows this one. If null, return first. 246 * @param set Set to look in for a row beyond <code>row</code>. 247 * @return Next row or null if none found. If one found, will be a new 248 * KeyValue -- can be destroyed by subsequent calls to this method. 249 */ 250 protected Cell getNextRow(final Cell key, 251 final NavigableSet<Cell> set) { 252 Cell result = null; 253 SortedSet<Cell> tail = key == null? set: set.tailSet(key); 254 // Iterate until we fall into the next row; i.e. move off current row 255 for (Cell cell: tail) { 256 if (comparator.compareRows(cell, key) <= 0) { 257 continue; 258 } 259 // Note: Not suppressing deletes or expired cells. Needs to be handled 260 // by higher up functions. 261 result = cell; 262 break; 263 } 264 return result; 265 } 266 267 /** 268 * If the segment has a memory allocator the cell is being cloned to this space, and returned; 269 * Otherwise the given cell is returned 270 * 271 * When a cell's size is too big (bigger than maxAlloc), it is not allocated on MSLAB. 272 * Since the process of flattening to CellChunkMap assumes that all cells are allocated on MSLAB, 273 * during this process, the input parameter forceCloneOfBigCell is set to 'true' 274 * and the cell is copied into MSLAB. 275 * 276 * @param cell the cell to clone 277 * @param forceCloneOfBigCell true only during the process of flattening to CellChunkMap. 278 * @return either the given cell or its clone 279 */ 280 private Cell maybeCloneWithAllocator(Cell cell, boolean forceCloneOfBigCell) { 281 return active.maybeCloneWithAllocator(cell, forceCloneOfBigCell); 282 } 283 284 /* 285 * Internal version of add() that doesn't clone Cells with the 286 * allocator, and doesn't take the lock. 287 * 288 * Callers should ensure they already have the read lock taken 289 * @param toAdd the cell to add 290 * @param mslabUsed whether using MSLAB 291 * @param memstoreSize 292 */ 293 private void internalAdd(final Cell toAdd, final boolean mslabUsed, MemStoreSizing memstoreSizing) { 294 active.add(toAdd, mslabUsed, memstoreSizing); 295 setOldestEditTimeToNow(); 296 checkActiveSize(); 297 } 298 299 private void setOldestEditTimeToNow() { 300 if (timeOfOldestEdit == Long.MAX_VALUE) { 301 timeOfOldestEdit = EnvironmentEdgeManager.currentTime(); 302 } 303 } 304 305 /** 306 * @return The total size of cells in this memstore. We will not consider cells in the snapshot 307 */ 308 protected abstract long keySize(); 309 310 /** 311 * @return The total heap size of cells in this memstore. We will not consider cells in the 312 * snapshot 313 */ 314 protected abstract long heapSize(); 315 316 protected CellComparator getComparator() { 317 return comparator; 318 } 319 320 @VisibleForTesting 321 MutableSegment getActive() { 322 return active; 323 } 324 325 @VisibleForTesting 326 ImmutableSegment getSnapshot() { 327 return snapshot; 328 } 329 330 /** 331 * Check whether anything need to be done based on the current active set size 332 */ 333 protected abstract void checkActiveSize(); 334 335 /** 336 * @return an ordered list of segments from most recent to oldest in memstore 337 */ 338 protected abstract List<Segment> getSegments() throws IOException; 339 340}