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.util.ArrayList;
022import java.util.Iterator;
023import java.util.LinkedList;
024import java.util.List;
025
026import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
027import org.apache.hadoop.hbase.util.Bytes;
028import org.apache.hadoop.hbase.util.ClassSize;
029import org.apache.yetus.audience.InterfaceAudience;
030import org.slf4j.Logger;
031import org.slf4j.LoggerFactory;
032
033/**
034 * The compaction pipeline of a {@link CompactingMemStore}, is a FIFO queue of segments.
035 * It supports pushing a segment at the head of the pipeline and removing a segment from the
036 * tail when it is flushed to disk.
037 * It also supports swap method to allow the in-memory compaction swap a subset of the segments
038 * at the tail of the pipeline with a new (compacted) one. This swap succeeds only if the version
039 * number passed with the list of segments to swap is the same as the current version of the
040 * pipeline.
041 * Essentially, there are two methods which can change the structure of the pipeline: pushHead()
042 * and swap(), the later is used both by a flush to disk and by an in-memory compaction.
043 * The pipeline version is updated by swap(); it allows to identify conflicting operations at the
044 * suffix of the pipeline.
045 *
046 * The synchronization model is copy-on-write. Methods which change the structure of the
047 * pipeline (pushHead() and swap()) apply their changes in the context of a lock. They also make
048 * a read-only copy of the pipeline's list. Read methods read from a read-only copy. If a read
049 * method accesses the read-only copy more than once it makes a local copy of it
050 * to ensure it accesses the same copy.
051 *
052 * The methods getVersionedList(), getVersionedTail(), and flattenOneSegment() are also
053 * protected by a lock since they need to have a consistent (atomic) view of the pipeline list
054 * and version number.
055 */
056@InterfaceAudience.Private
057public class CompactionPipeline {
058  private static final Logger LOG = LoggerFactory.getLogger(CompactionPipeline.class);
059
060  public final static long FIXED_OVERHEAD = ClassSize
061      .align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + Bytes.SIZEOF_LONG);
062  public final static long DEEP_OVERHEAD = FIXED_OVERHEAD + (2 * ClassSize.LINKEDLIST);
063
064  private final RegionServicesForStores region;
065  private final LinkedList<ImmutableSegment> pipeline = new LinkedList<>();
066  // The list is volatile to avoid reading a new allocated reference before the c'tor is executed
067  private volatile LinkedList<ImmutableSegment> readOnlyCopy = new LinkedList<>();
068  // Version is volatile to ensure it is atomically read when not using a lock
069  private volatile long version = 0;
070
071  public CompactionPipeline(RegionServicesForStores region) {
072    this.region = region;
073  }
074
075  public boolean pushHead(MutableSegment segment) {
076    ImmutableSegment immutableSegment = SegmentFactory.instance().
077        createImmutableSegment(segment);
078    synchronized (pipeline){
079      boolean res = addFirst(immutableSegment);
080      readOnlyCopy = new LinkedList<>(pipeline);
081      return res;
082    }
083  }
084
085  public VersionedSegmentsList getVersionedList() {
086    synchronized (pipeline){
087      return new VersionedSegmentsList(readOnlyCopy, version);
088    }
089  }
090
091  public VersionedSegmentsList getVersionedTail() {
092    synchronized (pipeline){
093      List<ImmutableSegment> segmentList = new ArrayList<>();
094      if(!pipeline.isEmpty()) {
095        segmentList.add(0, pipeline.getLast());
096      }
097      return new VersionedSegmentsList(segmentList, version);
098    }
099  }
100
101  /**
102   * Swaps the versioned list at the tail of the pipeline with a new segment.
103   * Swapping only if there were no changes to the suffix of the list since the version list was
104   * created.
105   * @param versionedList suffix of the pipeline to be replaced can be tail or all the pipeline
106   * @param segment new segment to replace the suffix. Can be null if the suffix just needs to be
107   *                removed.
108   * @param closeSuffix whether to close the suffix (to release memory), as part of swapping it out
109   *        During index merge op this will be false and for compaction it will be true.
110   * @param updateRegionSize whether to update the region size. Update the region size,
111   *                         when the pipeline is swapped as part of in-memory-flush and
112   *                         further merge/compaction. Don't update the region size when the
113   *                         swap is result of the snapshot (flush-to-disk).
114   * @return true iff swapped tail with new segment
115   */
116  @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="VO_VOLATILE_INCREMENT",
117      justification="Increment is done under a synchronize block so safe")
118  public boolean swap(VersionedSegmentsList versionedList, ImmutableSegment segment,
119      boolean closeSuffix, boolean updateRegionSize) {
120    if (versionedList.getVersion() != version) {
121      return false;
122    }
123    List<ImmutableSegment> suffix;
124    synchronized (pipeline){
125      if(versionedList.getVersion() != version) {
126        return false;
127      }
128      suffix = versionedList.getStoreSegments();
129      LOG.debug("Swapping pipeline suffix; before={}, new segment={}",
130          versionedList.getStoreSegments().size(), segment);
131      swapSuffix(suffix, segment, closeSuffix);
132      readOnlyCopy = new LinkedList<>(pipeline);
133      version++;
134    }
135    if (updateRegionSize && region != null) {
136      // update the global memstore size counter
137      long suffixDataSize = getSegmentsKeySize(suffix);
138      long newDataSize = 0;
139      if(segment != null) {
140        newDataSize = segment.getDataSize();
141      }
142      long dataSizeDelta = suffixDataSize - newDataSize;
143      long suffixHeapSize = getSegmentsHeapSize(suffix);
144      long suffixOffHeapSize = getSegmentsOffHeapSize(suffix);
145      long newHeapSize = 0;
146      long newOffHeapSize = 0;
147      if(segment != null) {
148        newHeapSize = segment.getHeapSize();
149        newOffHeapSize = segment.getOffHeapSize();
150      }
151      long offHeapSizeDelta = suffixOffHeapSize - newOffHeapSize;
152      long heapSizeDelta = suffixHeapSize - newHeapSize;
153      region.addMemStoreSize(-dataSizeDelta, -heapSizeDelta, -offHeapSizeDelta);
154      LOG.debug("Suffix data size={}, new segment data size={}, "
155              + "suffix heap size={}," + "new segment heap size={}"
156              + "suffix off heap size={}," + "new segment off heap size={}"
157          , suffixDataSize
158          , newDataSize
159          , suffixHeapSize
160          , newHeapSize
161          , suffixOffHeapSize
162          , newOffHeapSize);
163    }
164    return true;
165  }
166
167  private static long getSegmentsHeapSize(List<? extends Segment> list) {
168    long res = 0;
169    for (Segment segment : list) {
170      res += segment.getHeapSize();
171    }
172    return res;
173  }
174
175  private static long getSegmentsOffHeapSize(List<? extends Segment> list) {
176    long res = 0;
177    for (Segment segment : list) {
178      res += segment.getOffHeapSize();
179    }
180    return res;
181  }
182
183  private static long getSegmentsKeySize(List<? extends Segment> list) {
184    long res = 0;
185    for (Segment segment : list) {
186      res += segment.getDataSize();
187    }
188    return res;
189  }
190
191  /**
192   * If the caller holds the current version, go over the the pipeline and try to flatten each
193   * segment. Flattening is replacing the ConcurrentSkipListMap based CellSet to CellArrayMap based.
194   * Flattening of the segment that initially is not based on ConcurrentSkipListMap has no effect.
195   * Return after one segment is successfully flatten.
196   *
197   * @return true iff a segment was successfully flattened
198   */
199  public boolean flattenOneSegment(long requesterVersion,
200      CompactingMemStore.IndexType idxType,
201      MemStoreCompactionStrategy.Action action) {
202
203    if(requesterVersion != version) {
204      LOG.warn("Segment flattening failed, because versions do not match. Requester version: "
205          + requesterVersion + ", actual version: " + version);
206      return false;
207    }
208
209    synchronized (pipeline){
210      if(requesterVersion != version) {
211        LOG.warn("Segment flattening failed, because versions do not match");
212        return false;
213      }
214      int i = 0;
215      for (ImmutableSegment s : pipeline) {
216        if ( s.canBeFlattened() ) {
217          // size to be updated
218          MemStoreSizing newMemstoreAccounting = new NonThreadSafeMemStoreSizing();
219          ImmutableSegment newS = SegmentFactory.instance().createImmutableSegmentByFlattening(
220              (CSLMImmutableSegment)s,idxType,newMemstoreAccounting,action);
221          replaceAtIndex(i,newS);
222          if(region != null) {
223            // Update the global memstore size counter upon flattening there is no change in the
224            // data size
225            MemStoreSize mss = newMemstoreAccounting.getMemStoreSize();
226            Preconditions.checkArgument(mss.getDataSize() == 0, "Not zero!");
227            region.addMemStoreSize(mss.getDataSize(), mss.getHeapSize(), mss.getOffHeapSize());
228          }
229          LOG.debug("Compaction pipeline segment {} flattened", s);
230          return true;
231        }
232        i++;
233      }
234
235    }
236    // do not update the global memstore size counter and do not increase the version,
237    // because all the cells remain in place
238    return false;
239  }
240
241  public boolean isEmpty() {
242    return readOnlyCopy.isEmpty();
243  }
244
245  public List<? extends Segment> getSegments() {
246    return readOnlyCopy;
247  }
248
249  public long size() {
250    return readOnlyCopy.size();
251  }
252
253  public long getMinSequenceId() {
254    long minSequenceId = Long.MAX_VALUE;
255    LinkedList<? extends Segment> localCopy = readOnlyCopy;
256    if (!localCopy.isEmpty()) {
257      minSequenceId = localCopy.getLast().getMinSequenceId();
258    }
259    return minSequenceId;
260  }
261
262  public MemStoreSize getTailSize() {
263    LinkedList<? extends Segment> localCopy = readOnlyCopy;
264    return localCopy.isEmpty()? new MemStoreSize(): localCopy.peekLast().getMemStoreSize();
265  }
266
267  public MemStoreSize getPipelineSize() {
268    MemStoreSizing memStoreSizing = new NonThreadSafeMemStoreSizing();
269    LinkedList<? extends Segment> localCopy = readOnlyCopy;
270    for (Segment segment : localCopy) {
271      memStoreSizing.incMemStoreSize(segment.getMemStoreSize());
272    }
273    return memStoreSizing.getMemStoreSize();
274  }
275
276  private void swapSuffix(List<? extends Segment> suffix, ImmutableSegment segment,
277      boolean closeSegmentsInSuffix) {
278    pipeline.removeAll(suffix);
279    if(segment != null) pipeline.addLast(segment);
280    // During index merge we won't be closing the segments undergoing the merge. Segment#close()
281    // will release the MSLAB chunks to pool. But in case of index merge there wont be any data copy
282    // from old MSLABs. So the new cells in new segment also refers to same chunks. In case of data
283    // compaction, we would have copied the cells data from old MSLAB chunks into a new chunk
284    // created for the result segment. So we can release the chunks associated with the compacted
285    // segments.
286    if (closeSegmentsInSuffix) {
287      for (Segment itemInSuffix : suffix) {
288        itemInSuffix.close();
289      }
290    }
291  }
292
293  // replacing one segment in the pipeline with a new one exactly at the same index
294  // need to be called only within synchronized block
295  private void replaceAtIndex(int idx, ImmutableSegment newSegment) {
296    pipeline.set(idx, newSegment);
297    readOnlyCopy = new LinkedList<>(pipeline);
298  }
299
300  public Segment getTail() {
301    List<? extends Segment> localCopy = getSegments();
302    if(localCopy.isEmpty()) {
303      return null;
304    }
305    return localCopy.get(localCopy.size() - 1);
306  }
307
308  private boolean addFirst(ImmutableSegment segment) {
309    pipeline.addFirst(segment);
310    return true;
311  }
312
313  // debug method
314  private boolean validateSuffixList(LinkedList<ImmutableSegment> suffix) {
315    if(suffix.isEmpty()) {
316      // empty suffix is always valid
317      return true;
318    }
319    Iterator<ImmutableSegment> pipelineBackwardIterator = pipeline.descendingIterator();
320    Iterator<ImmutableSegment> suffixBackwardIterator = suffix.descendingIterator();
321    ImmutableSegment suffixCurrent;
322    ImmutableSegment pipelineCurrent;
323    for( ; suffixBackwardIterator.hasNext(); ) {
324      if(!pipelineBackwardIterator.hasNext()) {
325        // a suffix longer than pipeline is invalid
326        return false;
327      }
328      suffixCurrent = suffixBackwardIterator.next();
329      pipelineCurrent = pipelineBackwardIterator.next();
330      if(suffixCurrent != pipelineCurrent) {
331        // non-matching suffix
332        return false;
333      }
334    }
335    // suffix matches pipeline suffix
336    return true;
337  }
338
339}