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 java.nio.ByteBuffer;
022import java.util.Set;
023import java.util.concurrent.BlockingQueue;
024import java.util.concurrent.ConcurrentSkipListSet;
025import java.util.concurrent.LinkedBlockingQueue;
026import java.util.concurrent.atomic.AtomicBoolean;
027import java.util.concurrent.atomic.AtomicInteger;
028import java.util.concurrent.atomic.AtomicReference;
029import java.util.concurrent.locks.ReentrantLock;
030
031import org.apache.hadoop.conf.Configuration;
032import org.apache.hadoop.hbase.Cell;
033import org.apache.hadoop.hbase.ExtendedCell;
034import org.apache.hadoop.hbase.KeyValueUtil;
035import org.apache.yetus.audience.InterfaceAudience;
036import org.slf4j.Logger;
037import org.slf4j.LoggerFactory;
038import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
039import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
040/**
041 * A memstore-local allocation buffer.
042 * <p>
043 * The MemStoreLAB is basically a bump-the-pointer allocator that allocates
044 * big (2MB) byte[] chunks from and then doles it out to threads that request
045 * slices into the array.
046 * <p>
047 * The purpose of this class is to combat heap fragmentation in the
048 * regionserver. By ensuring that all Cells in a given memstore refer
049 * only to large chunks of contiguous memory, we ensure that large blocks
050 * get freed up when the memstore is flushed.
051 * <p>
052 * Without the MSLAB, the byte array allocated during insertion end up
053 * interleaved throughout the heap, and the old generation gets progressively
054 * more fragmented until a stop-the-world compacting collection occurs.
055 * <p>
056 * TODO: we should probably benchmark whether word-aligning the allocations
057 * would provide a performance improvement - probably would speed up the
058 * Bytes.toLong/Bytes.toInt calls in KeyValue, but some of those are cached
059 * anyway.
060 * The chunks created by this MemStoreLAB can get pooled at {@link ChunkCreator}.
061 * When the Chunk comes from pool, it can be either an on heap or an off heap backed chunk. The chunks,
062 * which this MemStoreLAB creates on its own (when no chunk available from pool), those will be
063 * always on heap backed.
064 */
065@InterfaceAudience.Private
066public class MemStoreLABImpl implements MemStoreLAB {
067
068  static final Logger LOG = LoggerFactory.getLogger(MemStoreLABImpl.class);
069
070  private AtomicReference<Chunk> currChunk = new AtomicReference<>();
071  // Lock to manage multiple handlers requesting for a chunk
072  private ReentrantLock lock = new ReentrantLock();
073
074  // A set of chunks contained by this memstore LAB
075  @VisibleForTesting
076  Set<Integer> chunks = new ConcurrentSkipListSet<Integer>();
077  private final int dataChunkSize;
078  private final int maxAlloc;
079  private final ChunkCreator chunkCreator;
080  private final CompactingMemStore.IndexType idxType; // what index is used for corresponding segment
081
082  // This flag is for closing this instance, its set when clearing snapshot of
083  // memstore
084  private volatile boolean closed = false;
085  // This flag is for reclaiming chunks. Its set when putting chunks back to
086  // pool
087  private AtomicBoolean reclaimed = new AtomicBoolean(false);
088  // Current count of open scanners which reading data from this MemStoreLAB
089  private final AtomicInteger openScannerCount = new AtomicInteger();
090
091  // Used in testing
092  public MemStoreLABImpl() {
093    this(new Configuration());
094  }
095
096  public MemStoreLABImpl(Configuration conf) {
097    dataChunkSize = conf.getInt(CHUNK_SIZE_KEY, CHUNK_SIZE_DEFAULT);
098    maxAlloc = conf.getInt(MAX_ALLOC_KEY, MAX_ALLOC_DEFAULT);
099    this.chunkCreator = ChunkCreator.getInstance();
100    // if we don't exclude allocations >CHUNK_SIZE, we'd infiniteloop on one!
101    Preconditions.checkArgument(maxAlloc <= dataChunkSize,
102        MAX_ALLOC_KEY + " must be less than " + CHUNK_SIZE_KEY);
103
104    // if user requested to work with MSLABs (whether on- or off-heap), then the
105    // immutable segments are going to use CellChunkMap as their index
106    idxType = CompactingMemStore.IndexType.CHUNK_MAP;
107  }
108
109  @Override
110  public Cell copyCellInto(Cell cell) {
111    return copyCellInto(cell, maxAlloc);
112  }
113
114  /**
115   * When a cell's size is too big (bigger than maxAlloc),
116   * copyCellInto does not allocate it on MSLAB.
117   * Since the process of flattening to CellChunkMap assumes that
118   * all cells are allocated on MSLAB, during this process,
119   * the big cells are copied into MSLAB using this method.
120   */
121  @Override
122  public Cell forceCopyOfBigCellInto(Cell cell) {
123    int size = cell instanceof ExtendedCell? ((ExtendedCell)cell).getSerializedSize():
124        KeyValueUtil.length(cell);
125    size += ChunkCreator.SIZEOF_CHUNK_HEADER;
126    Preconditions.checkArgument(size >= 0, "negative size");
127    if (size <= dataChunkSize) {
128      // Using copyCellInto for cells which are bigger than the original maxAlloc
129      return copyCellInto(cell, dataChunkSize);
130    } else {
131      Chunk c = getNewExternalChunk(size);
132      int allocOffset = c.alloc(size);
133      return copyToChunkCell(cell, c.getData(), allocOffset, size);
134    }
135  }
136
137  private Cell copyCellInto(Cell cell, int maxAlloc) {
138    int size = cell instanceof ExtendedCell? ((ExtendedCell)cell).getSerializedSize():
139        KeyValueUtil.length(cell);
140    Preconditions.checkArgument(size >= 0, "negative size");
141    // Callers should satisfy large allocations directly from JVM since they
142    // don't cause fragmentation as badly.
143    if (size > maxAlloc) {
144      return null;
145    }
146    Chunk c = null;
147    int allocOffset = 0;
148    while (true) {
149      // Try to get the chunk
150      c = getOrMakeChunk();
151      // we may get null because the some other thread succeeded in getting the lock
152      // and so the current thread has to try again to make its chunk or grab the chunk
153      // that the other thread created
154      // Try to allocate from this chunk
155      if (c != null) {
156        allocOffset = c.alloc(size);
157        if (allocOffset != -1) {
158          // We succeeded - this is the common case - small alloc
159          // from a big buffer
160          break;
161        }
162        // not enough space!
163        // try to retire this chunk
164        tryRetireChunk(c);
165      }
166    }
167    return copyToChunkCell(cell, c.getData(), allocOffset, size);
168  }
169
170  /**
171   * Clone the passed cell by copying its data into the passed buf and create a cell with a chunkid
172   * out of it
173   */
174  private static Cell copyToChunkCell(Cell cell, ByteBuffer buf, int offset, int len) {
175    int tagsLen = cell.getTagsLength();
176    if (cell instanceof ExtendedCell) {
177      ((ExtendedCell) cell).write(buf, offset);
178    } else {
179      // Normally all Cell impls within Server will be of type ExtendedCell. Just considering the
180      // other case also. The data fragments within Cell is copied into buf as in KeyValue
181      // serialization format only.
182      KeyValueUtil.appendTo(cell, buf, offset, true);
183    }
184    // TODO : write the seqid here. For writing seqId we should create a new cell type so
185    // that seqId is not used as the state
186    if (tagsLen == 0) {
187      // When tagsLen is 0, make a NoTagsByteBufferKeyValue version. This is an optimized class
188      // which directly return tagsLen as 0. So we avoid parsing many length components in
189      // reading the tagLength stored in the backing buffer. The Memstore addition of every Cell
190      // call getTagsLength().
191      return new NoTagByteBufferChunkKeyValue(buf, offset, len, cell.getSequenceId());
192    } else {
193      return new ByteBufferChunkKeyValue(buf, offset, len, cell.getSequenceId());
194    }
195  }
196
197  /**
198   * Close this instance since it won't be used any more, try to put the chunks
199   * back to pool
200   */
201  @Override
202  public void close() {
203    this.closed = true;
204    // We could put back the chunks to pool for reusing only when there is no
205    // opening scanner which will read their data
206    int count  = openScannerCount.get();
207    if(count == 0) {
208      recycleChunks();
209    }
210  }
211
212  /**
213   * Called when opening a scanner on the data of this MemStoreLAB
214   */
215  @Override
216  public void incScannerCount() {
217    this.openScannerCount.incrementAndGet();
218  }
219
220  /**
221   * Called when closing a scanner on the data of this MemStoreLAB
222   */
223  @Override
224  public void decScannerCount() {
225    int count = this.openScannerCount.decrementAndGet();
226    if (this.closed && count == 0) {
227      recycleChunks();
228    }
229  }
230
231  private void recycleChunks() {
232    if (reclaimed.compareAndSet(false, true)) {
233      chunkCreator.putbackChunks(chunks);
234    }
235  }
236
237  /**
238   * Try to retire the current chunk if it is still
239   * <code>c</code>. Postcondition is that curChunk.get()
240   * != c
241   * @param c the chunk to retire
242   * @return true if we won the race to retire the chunk
243   */
244  private void tryRetireChunk(Chunk c) {
245    currChunk.compareAndSet(c, null);
246    // If the CAS succeeds, that means that we won the race
247    // to retire the chunk. We could use this opportunity to
248    // update metrics on external fragmentation.
249    //
250    // If the CAS fails, that means that someone else already
251    // retired the chunk for us.
252  }
253
254  /**
255   * Get the current chunk, or, if there is no current chunk,
256   * allocate a new one from the JVM.
257   */
258  private Chunk getOrMakeChunk() {
259    // Try to get the chunk
260    Chunk c = currChunk.get();
261    if (c != null) {
262      return c;
263    }
264    // No current chunk, so we want to allocate one. We race
265    // against other allocators to CAS in an uninitialized chunk
266    // (which is cheap to allocate)
267    if (lock.tryLock()) {
268      try {
269        // once again check inside the lock
270        c = currChunk.get();
271        if (c != null) {
272          return c;
273        }
274        c = this.chunkCreator.getChunk(idxType);
275        if (c != null) {
276          // set the curChunk. No need of CAS as only one thread will be here
277          currChunk.set(c);
278          chunks.add(c.getId());
279          return c;
280        }
281      } finally {
282        lock.unlock();
283      }
284    }
285    return null;
286  }
287
288  /* Returning a new pool chunk, without replacing current chunk,
289  ** meaning MSLABImpl does not make the returned chunk as CurChunk.
290  ** The space on this chunk will be allocated externally.
291  ** The interface is only for external callers.
292  */
293  @Override
294  public Chunk getNewExternalChunk(ChunkCreator.ChunkType chunkType) {
295    switch (chunkType) {
296      case INDEX_CHUNK:
297      case DATA_CHUNK:
298        Chunk c = this.chunkCreator.getChunk(chunkType);
299        chunks.add(c.getId());
300        return c;
301      case JUMBO_CHUNK: // a jumbo chunk doesn't have a fixed size
302      default:
303        return null;
304    }
305  }
306
307  /* Returning a new chunk, without replacing current chunk,
308  ** meaning MSLABImpl does not make the returned chunk as CurChunk.
309  ** The space on this chunk will be allocated externally.
310  ** The interface is only for external callers.
311  ** Chunks from pools are not allocated from here, since they have fixed sizes
312  */
313  @Override
314  public Chunk getNewExternalChunk(int size) {
315    int allocSize = size + ChunkCreator.getInstance().SIZEOF_CHUNK_HEADER;
316    if (allocSize <= ChunkCreator.getInstance().getChunkSize()) {
317      return getNewExternalChunk(ChunkCreator.ChunkType.DATA_CHUNK);
318    } else {
319      Chunk c = this.chunkCreator.getJumboChunk(size);
320      chunks.add(c.getId());
321      return c;
322    }
323  }
324
325  @Override
326  public boolean isOnHeap() {
327    return !isOffHeap();
328  }
329
330  @Override
331  public boolean isOffHeap() {
332    return this.chunkCreator.isOffheap();
333  }
334
335  @VisibleForTesting
336  Chunk getCurrentChunk() {
337    return currChunk.get();
338  }
339
340  @VisibleForTesting
341  BlockingQueue<Chunk> getPooledChunks() {
342    BlockingQueue<Chunk> pooledChunks = new LinkedBlockingQueue<>();
343    for (Integer id : this.chunks) {
344      Chunk chunk = chunkCreator.getChunk(id);
345      if (chunk != null && chunk.isFromPool()) {
346        pooledChunks.add(chunk);
347      }
348    }
349    return pooledChunks;
350  }
351
352  @VisibleForTesting Integer getNumOfChunksReturnedToPool() {
353    int i = 0;
354    for (Integer id : this.chunks) {
355      if (chunkCreator.isChunkInPool(id)) {
356        i++;
357      }
358    }
359    return i;
360  }
361}