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.hadoop.hbase.exceptions.IllegalArgumentIOException;
022import org.apache.hadoop.util.StringUtils;
023import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
024import java.io.IOException;
025import java.util.ArrayList;
026import java.util.List;
027import java.util.concurrent.ThreadPoolExecutor;
028import java.util.concurrent.atomic.AtomicBoolean;
029
030import org.apache.hadoop.conf.Configuration;
031import org.apache.hadoop.hbase.Cell;
032import org.apache.hadoop.hbase.CellComparator;
033import org.apache.hadoop.hbase.HConstants;
034import org.apache.hadoop.hbase.MemoryCompactionPolicy;
035import org.apache.yetus.audience.InterfaceAudience;
036import org.slf4j.Logger;
037import org.slf4j.LoggerFactory;
038import org.apache.hadoop.hbase.util.Bytes;
039import org.apache.hadoop.hbase.util.ClassSize;
040import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
041import org.apache.hadoop.hbase.wal.WAL;
042
043/**
044 * A memstore implementation which supports in-memory compaction.
045 * A compaction pipeline is added between the active set and the snapshot data structures;
046 * it consists of a list of segments that are subject to compaction.
047 * Like the snapshot, all pipeline segments are read-only; updates only affect the active set.
048 * To ensure this property we take advantage of the existing blocking mechanism -- the active set
049 * is pushed to the pipeline while holding the region's updatesLock in exclusive mode.
050 * Periodically, a compaction is applied in the background to all pipeline segments resulting
051 * in a single read-only component. The ``old'' segments are discarded when no scanner is reading
052 * them.
053 */
054@InterfaceAudience.Private
055public class CompactingMemStore extends AbstractMemStore {
056
057  // The external setting of the compacting MemStore behaviour
058  public static final String COMPACTING_MEMSTORE_TYPE_KEY =
059      "hbase.hregion.compacting.memstore.type";
060  public static final String COMPACTING_MEMSTORE_TYPE_DEFAULT =
061      String.valueOf(MemoryCompactionPolicy.NONE);
062  // Default fraction of in-memory-flush size w.r.t. flush-to-disk size
063  public static final String IN_MEMORY_FLUSH_THRESHOLD_FACTOR_KEY =
064      "hbase.memstore.inmemoryflush.threshold.factor";
065  private static final double IN_MEMORY_FLUSH_THRESHOLD_FACTOR_DEFAULT = 0.014;
066
067  private static final Logger LOG = LoggerFactory.getLogger(CompactingMemStore.class);
068  private HStore store;
069  private RegionServicesForStores regionServices;
070  private CompactionPipeline pipeline;
071  protected MemStoreCompactor compactor;
072
073  private long inmemoryFlushSize;       // the threshold on active size for in-memory flush
074  private final AtomicBoolean inMemoryFlushInProgress = new AtomicBoolean(false);
075
076  // inWalReplay is true while we are synchronously replaying the edits from WAL
077  private boolean inWalReplay = false;
078
079  @VisibleForTesting
080  protected final AtomicBoolean allowCompaction = new AtomicBoolean(true);
081  private boolean compositeSnapshot = true;
082
083  /**
084   * Types of indexes (part of immutable segments) to be used after flattening,
085   * compaction, or merge are applied.
086   */
087  public enum IndexType {
088    CSLM_MAP,   // ConcurrentSkipLisMap
089    ARRAY_MAP,  // CellArrayMap
090    CHUNK_MAP   // CellChunkMap
091  }
092
093  private IndexType indexType = IndexType.ARRAY_MAP;  // default implementation
094
095  public static final long DEEP_OVERHEAD = ClassSize.align( AbstractMemStore.DEEP_OVERHEAD
096      + 7 * ClassSize.REFERENCE     // Store, RegionServicesForStores, CompactionPipeline,
097                                    // MemStoreCompactor, inMemoryFlushInProgress, allowCompaction,
098                                    // indexType
099      + Bytes.SIZEOF_LONG           // inmemoryFlushSize
100      + 2 * Bytes.SIZEOF_BOOLEAN    // compositeSnapshot and inWalReplay
101      + 2 * ClassSize.ATOMIC_BOOLEAN// inMemoryFlushInProgress and allowCompaction
102      + CompactionPipeline.DEEP_OVERHEAD + MemStoreCompactor.DEEP_OVERHEAD);
103
104  public CompactingMemStore(Configuration conf, CellComparator c,
105      HStore store, RegionServicesForStores regionServices,
106      MemoryCompactionPolicy compactionPolicy) throws IOException {
107    super(conf, c);
108    this.store = store;
109    this.regionServices = regionServices;
110    this.pipeline = new CompactionPipeline(getRegionServices());
111    this.compactor = createMemStoreCompactor(compactionPolicy);
112    if (conf.getBoolean(MemStoreLAB.USEMSLAB_KEY, MemStoreLAB.USEMSLAB_DEFAULT)) {
113      // if user requested to work with MSLABs (whether on- or off-heap), then the
114      // immutable segments are going to use CellChunkMap as their index
115      indexType = IndexType.CHUNK_MAP;
116    } else {
117      indexType = IndexType.ARRAY_MAP;
118    }
119    // initialization of the flush size should happen after initialization of the index type
120    // so do not transfer the following method
121    initInmemoryFlushSize(conf);
122    LOG.info("Store={}, in-memory flush size threshold={}, immutable segments index type={}, " +
123            "compactor={}", this.store.getColumnFamilyName(),
124        StringUtils.byteDesc(this.inmemoryFlushSize), this.indexType,
125        (this.compactor == null? "NULL": this.compactor.toString()));
126  }
127
128  @VisibleForTesting
129  protected MemStoreCompactor createMemStoreCompactor(MemoryCompactionPolicy compactionPolicy)
130      throws IllegalArgumentIOException {
131    return new MemStoreCompactor(this, compactionPolicy);
132  }
133
134  private void initInmemoryFlushSize(Configuration conf) {
135    double factor = 0;
136    long memstoreFlushSize = getRegionServices().getMemStoreFlushSize();
137    int numStores = getRegionServices().getNumStores();
138    if (numStores <= 1) {
139      // Family number might also be zero in some of our unit test case
140      numStores = 1;
141    }
142    inmemoryFlushSize = memstoreFlushSize / numStores;
143    // multiply by a factor (the same factor for all index types)
144    factor = conf.getDouble(IN_MEMORY_FLUSH_THRESHOLD_FACTOR_KEY,
145          IN_MEMORY_FLUSH_THRESHOLD_FACTOR_DEFAULT);
146
147    inmemoryFlushSize = (long) (inmemoryFlushSize * factor);
148  }
149
150  /**
151   * @return Total memory occupied by this MemStore. This won't include any size occupied by the
152   *         snapshot. We assume the snapshot will get cleared soon. This is not thread safe and
153   *         the memstore may be changed while computing its size. It is the responsibility of the
154   *         caller to make sure this doesn't happen.
155   */
156  @Override
157  public MemStoreSize size() {
158    MemStoreSizing memstoreSizing = new NonThreadSafeMemStoreSizing();
159    memstoreSizing.incMemStoreSize(active.getMemStoreSize());
160    for (Segment item : pipeline.getSegments()) {
161      memstoreSizing.incMemStoreSize(item.getMemStoreSize());
162    }
163    return memstoreSizing.getMemStoreSize();
164  }
165
166  /**
167   * This method is called before the flush is executed.
168   * @return an estimation (lower bound) of the unflushed sequence id in memstore after the flush
169   * is executed. if memstore will be cleared returns {@code HConstants.NO_SEQNUM}.
170   */
171  @Override
172  public long preFlushSeqIDEstimation() {
173    if(compositeSnapshot) {
174      return HConstants.NO_SEQNUM;
175    }
176    Segment segment = getLastSegment();
177    if(segment == null) {
178      return HConstants.NO_SEQNUM;
179    }
180    return segment.getMinSequenceId();
181  }
182
183  @Override
184  public boolean isSloppy() {
185    return true;
186  }
187
188  /**
189   * Push the current active memstore segment into the pipeline
190   * and create a snapshot of the tail of current compaction pipeline
191   * Snapshot must be cleared by call to {@link #clearSnapshot}.
192   * {@link #clearSnapshot(long)}.
193   * @return {@link MemStoreSnapshot}
194   */
195  @Override
196  public MemStoreSnapshot snapshot() {
197    // If snapshot currently has entries, then flusher failed or didn't call
198    // cleanup.  Log a warning.
199    if (!this.snapshot.isEmpty()) {
200      LOG.warn("Snapshot called again without clearing previous. " +
201          "Doing nothing. Another ongoing flush or did we fail last attempt?");
202    } else {
203      LOG.debug("FLUSHING TO DISK {}, store={}",
204            getRegionServices().getRegionInfo().getEncodedName(), getFamilyName());
205      stopCompaction();
206      pushActiveToPipeline(this.active);
207      snapshotId = EnvironmentEdgeManager.currentTime();
208      // in both cases whatever is pushed to snapshot is cleared from the pipeline
209      if (compositeSnapshot) {
210        pushPipelineToSnapshot();
211      } else {
212        pushTailToSnapshot();
213      }
214      compactor.resetStats();
215    }
216    return new MemStoreSnapshot(snapshotId, this.snapshot);
217  }
218
219  @Override
220  public MemStoreSize getFlushableSize() {
221    MemStoreSize mss = getSnapshotSize();
222    if (mss.getDataSize() == 0) {
223      // if snapshot is empty the tail of the pipeline (or everything in the memstore) is flushed
224      if (compositeSnapshot) {
225        MemStoreSizing memStoreSizing = new NonThreadSafeMemStoreSizing(pipeline.getPipelineSize());
226        memStoreSizing.incMemStoreSize(this.active.getMemStoreSize());
227        mss = memStoreSizing.getMemStoreSize();
228      } else {
229        mss = pipeline.getTailSize();
230      }
231    }
232    return mss.getDataSize() > 0? mss: this.active.getMemStoreSize();
233  }
234
235  @Override
236  protected long keySize() {
237    // Need to consider dataSize/keySize of all segments in pipeline and active
238    long keySize = this.active.getDataSize();
239    for (Segment segment : this.pipeline.getSegments()) {
240      keySize += segment.getDataSize();
241    }
242    return keySize;
243  }
244
245  @Override
246  protected long heapSize() {
247    // Need to consider heapOverhead of all segments in pipeline and active
248    long h = this.active.getHeapSize();
249    for (Segment segment : this.pipeline.getSegments()) {
250      h += segment.getHeapSize();
251    }
252    return h;
253  }
254
255  @Override
256  public void updateLowestUnflushedSequenceIdInWAL(boolean onlyIfGreater) {
257    long minSequenceId = pipeline.getMinSequenceId();
258    if(minSequenceId != Long.MAX_VALUE) {
259      byte[] encodedRegionName = getRegionServices().getRegionInfo().getEncodedNameAsBytes();
260      byte[] familyName = getFamilyNameInBytes();
261      WAL WAL = getRegionServices().getWAL();
262      if (WAL != null) {
263        WAL.updateStore(encodedRegionName, familyName, minSequenceId, onlyIfGreater);
264      }
265    }
266  }
267
268  /**
269   * This message intends to inform the MemStore that next coming updates
270   * are going to be part of the replaying edits from WAL
271   */
272  @Override
273  public void startReplayingFromWAL() {
274    inWalReplay = true;
275  }
276
277  /**
278   * This message intends to inform the MemStore that the replaying edits from WAL
279   * are done
280   */
281  @Override
282  public void stopReplayingFromWAL() {
283    inWalReplay = false;
284  }
285
286  // the getSegments() method is used for tests only
287  @VisibleForTesting
288  @Override
289  protected List<Segment> getSegments() {
290    List<? extends Segment> pipelineList = pipeline.getSegments();
291    List<Segment> list = new ArrayList<>(pipelineList.size() + 2);
292    list.add(this.active);
293    list.addAll(pipelineList);
294    list.addAll(this.snapshot.getAllSegments());
295
296    return list;
297  }
298
299  // the following three methods allow to manipulate the settings of composite snapshot
300  public void setCompositeSnapshot(boolean useCompositeSnapshot) {
301    this.compositeSnapshot = useCompositeSnapshot;
302  }
303
304  public boolean swapCompactedSegments(VersionedSegmentsList versionedList, ImmutableSegment result,
305      boolean merge) {
306    // last true stands for updating the region size
307    return pipeline.swap(versionedList, result, !merge, true);
308  }
309
310  /**
311   * @param requesterVersion The caller must hold the VersionedList of the pipeline
312   *           with version taken earlier. This version must be passed as a parameter here.
313   *           The flattening happens only if versions match.
314   */
315  public void flattenOneSegment(long requesterVersion,  MemStoreCompactionStrategy.Action action) {
316    pipeline.flattenOneSegment(requesterVersion, indexType, action);
317  }
318
319  // setter is used only for testability
320  @VisibleForTesting
321  void setIndexType(IndexType type) {
322    indexType = type;
323    // Because this functionality is for testing only and tests are setting in-memory flush size
324    // according to their need, there is no setting of in-memory flush size, here.
325    // If it is needed, please change in-memory flush size explicitly
326  }
327
328  public IndexType getIndexType() {
329    return indexType;
330  }
331
332  public boolean hasImmutableSegments() {
333    return !pipeline.isEmpty();
334  }
335
336  public VersionedSegmentsList getImmutableSegments() {
337    return pipeline.getVersionedList();
338  }
339
340  public long getSmallestReadPoint() {
341    return store.getSmallestReadPoint();
342  }
343
344  public HStore getStore() {
345    return store;
346  }
347
348  public String getFamilyName() {
349    return Bytes.toString(getFamilyNameInBytes());
350  }
351
352  @Override
353  /*
354   * Scanners are ordered from 0 (oldest) to newest in increasing order.
355   */
356  public List<KeyValueScanner> getScanners(long readPt) throws IOException {
357    MutableSegment activeTmp = active;
358    List<? extends Segment> pipelineList = pipeline.getSegments();
359    List<? extends Segment> snapshotList = snapshot.getAllSegments();
360    long order = 1L + pipelineList.size() + snapshotList.size();
361    // The list of elements in pipeline + the active element + the snapshot segment
362    // The order is the Segment ordinal
363    List<KeyValueScanner> list = createList((int) order);
364    order = addToScanners(activeTmp, readPt, order, list);
365    order = addToScanners(pipelineList, readPt, order, list);
366    addToScanners(snapshotList, readPt, order, list);
367    return list;
368  }
369
370   @VisibleForTesting
371   protected List<KeyValueScanner> createList(int capacity) {
372     return new ArrayList<>(capacity);
373   }
374
375  /**
376   * Check whether anything need to be done based on the current active set size.
377   * The method is invoked upon every addition to the active set.
378   * For CompactingMemStore, flush the active set to the read-only memory if it's
379   * size is above threshold
380   */
381  @Override
382  protected void checkActiveSize() {
383    if (shouldFlushInMemory()) {
384      /* The thread is dispatched to flush-in-memory. This cannot be done
385      * on the same thread, because for flush-in-memory we require updatesLock
386      * in exclusive mode while this method (checkActiveSize) is invoked holding updatesLock
387      * in the shared mode. */
388      InMemoryFlushRunnable runnable = new InMemoryFlushRunnable();
389      if (LOG.isTraceEnabled()) {
390        LOG.trace(
391          "Dispatching the MemStore in-memory flush for store " + store.getColumnFamilyName());
392      }
393      getPool().execute(runnable);
394    }
395  }
396
397  // internally used method, externally visible only for tests
398  // when invoked directly from tests it must be verified that the caller doesn't hold updatesLock,
399  // otherwise there is a deadlock
400  @VisibleForTesting
401  void flushInMemory() throws IOException {
402    // setting the inMemoryFlushInProgress flag again for the case this method is invoked
403    // directly (only in tests) in the common path setting from true to true is idempotent
404    inMemoryFlushInProgress.set(true);
405    try {
406      // Phase I: Update the pipeline
407      getRegionServices().blockUpdates();
408      try {
409        LOG.trace("IN-MEMORY FLUSH: Pushing active segment into compaction pipeline");
410        pushActiveToPipeline(this.active);
411      } finally {
412        getRegionServices().unblockUpdates();
413      }
414
415      // Used by tests
416      if (!allowCompaction.get()) {
417        return;
418      }
419      // Phase II: Compact the pipeline
420      try {
421        // Speculative compaction execution, may be interrupted if flush is forced while
422        // compaction is in progress
423        compactor.start();
424      } catch (IOException e) {
425        LOG.warn("Unable to run in-memory compaction on {}/{}; exception={}",
426            getRegionServices().getRegionInfo().getEncodedName(), getFamilyName(), e);
427      }
428    } finally {
429      inMemoryFlushInProgress.set(false);
430      LOG.trace("IN-MEMORY FLUSH: end");
431    }
432  }
433
434  private Segment getLastSegment() {
435    Segment localActive = getActive();
436    Segment tail = pipeline.getTail();
437    return tail == null ? localActive : tail;
438  }
439
440  private byte[] getFamilyNameInBytes() {
441    return store.getColumnFamilyDescriptor().getName();
442  }
443
444  private ThreadPoolExecutor getPool() {
445    return getRegionServices().getInMemoryCompactionPool();
446  }
447
448  @VisibleForTesting
449  protected boolean shouldFlushInMemory() {
450    if (this.active.getDataSize() > inmemoryFlushSize) { // size above flush threshold
451      if (inWalReplay) {  // when replaying edits from WAL there is no need in in-memory flush
452        return false;     // regardless the size
453      }
454      // the inMemoryFlushInProgress is CASed to be true here in order to mutual exclude
455      // the insert of the active into the compaction pipeline
456      return (inMemoryFlushInProgress.compareAndSet(false,true));
457    }
458    return false;
459  }
460
461  /**
462   * The request to cancel the compaction asynchronous task (caused by in-memory flush)
463   * The compaction may still happen if the request was sent too late
464   * Non-blocking request
465   */
466  private void stopCompaction() {
467    if (inMemoryFlushInProgress.get()) {
468      compactor.stop();
469    }
470  }
471
472  protected void pushActiveToPipeline(MutableSegment active) {
473    if (!active.isEmpty()) {
474      pipeline.pushHead(active);
475      resetActive();
476    }
477  }
478
479  private void pushTailToSnapshot() {
480    VersionedSegmentsList segments = pipeline.getVersionedTail();
481    pushToSnapshot(segments.getStoreSegments());
482    // In Swap: don't close segments (they are in snapshot now) and don't update the region size
483    pipeline.swap(segments,null,false, false);
484  }
485
486  private void pushPipelineToSnapshot() {
487    int iterationsCnt = 0;
488    boolean done = false;
489    while (!done) {
490      iterationsCnt++;
491      VersionedSegmentsList segments = pipeline.getVersionedList();
492      pushToSnapshot(segments.getStoreSegments());
493      // swap can return false in case the pipeline was updated by ongoing compaction
494      // and the version increase, the chance of it happenning is very low
495      // In Swap: don't close segments (they are in snapshot now) and don't update the region size
496      done = pipeline.swap(segments, null, false, false);
497      if (iterationsCnt>2) {
498        // practically it is impossible that this loop iterates more than two times
499        // (because the compaction is stopped and none restarts it while in snapshot request),
500        // however stopping here for the case of the infinite loop causing by any error
501        LOG.warn("Multiple unsuccessful attempts to push the compaction pipeline to snapshot," +
502            " while flushing to disk.");
503        this.snapshot = SegmentFactory.instance().createImmutableSegment(getComparator());
504        break;
505      }
506    }
507  }
508
509  private void pushToSnapshot(List<ImmutableSegment> segments) {
510    if(segments.isEmpty()) return;
511    if(segments.size() == 1 && !segments.get(0).isEmpty()) {
512      this.snapshot = segments.get(0);
513      return;
514    } else { // create composite snapshot
515      this.snapshot =
516          SegmentFactory.instance().createCompositeImmutableSegment(getComparator(), segments);
517    }
518  }
519
520  private RegionServicesForStores getRegionServices() {
521    return regionServices;
522  }
523
524  /**
525  * The in-memory-flusher thread performs the flush asynchronously.
526  * There is at most one thread per memstore instance.
527  * It takes the updatesLock exclusively, pushes active into the pipeline, releases updatesLock
528  * and compacts the pipeline.
529  */
530  private class InMemoryFlushRunnable implements Runnable {
531
532    @Override
533    public void run() {
534      try {
535        flushInMemory();
536      } catch (IOException e) {
537        LOG.warn("Unable to run memstore compaction. region "
538            + getRegionServices().getRegionInfo().getRegionNameAsString()
539            + "store: "+ getFamilyName(), e);
540      }
541    }
542  }
543
544  @VisibleForTesting
545  boolean isMemStoreFlushingInMemory() {
546    return inMemoryFlushInProgress.get();
547  }
548
549  /**
550   * @param cell Find the row that comes after this one.  If null, we return the
551   *             first.
552   * @return Next row or null if none found.
553   */
554  Cell getNextRow(final Cell cell) {
555    Cell lowest = null;
556    List<Segment> segments = getSegments();
557    for (Segment segment : segments) {
558      if (lowest == null) {
559        lowest = getNextRow(cell, segment.getCellSet());
560      } else {
561        lowest = getLowest(lowest, getNextRow(cell, segment.getCellSet()));
562      }
563    }
564    return lowest;
565  }
566
567  @VisibleForTesting
568  long getInmemoryFlushSize() {
569    return inmemoryFlushSize;
570  }
571
572  // debug method
573  public void debug() {
574    String msg = "active size=" + this.active.getDataSize();
575    msg += " in-memory flush size is "+ inmemoryFlushSize;
576    msg += " allow compaction is "+ (allowCompaction.get() ? "true" : "false");
577    msg += " inMemoryFlushInProgress is "+ (inMemoryFlushInProgress.get() ? "true" : "false");
578    LOG.debug(msg);
579  }
580
581}