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 */
018package org.apache.hadoop.hbase.regionserver.wal;
019
020import static org.apache.hadoop.hbase.util.ConcurrentMapUtils.computeIfAbsent;
021
022import java.util.ArrayList;
023import java.util.Collections;
024import java.util.HashMap;
025import java.util.List;
026import java.util.Map;
027import java.util.Set;
028import java.util.TreeMap;
029import java.util.concurrent.ConcurrentHashMap;
030import java.util.concurrent.ConcurrentMap;
031import java.util.stream.Collectors;
032import org.apache.hadoop.hbase.HConstants;
033import org.apache.hadoop.hbase.util.Bytes;
034import org.apache.hadoop.hbase.util.ImmutableByteArray;
035import org.apache.yetus.audience.InterfaceAudience;
036import org.slf4j.Logger;
037import org.slf4j.LoggerFactory;
038
039/**
040 * Accounting of sequence ids per region and then by column family. So we can keep our accounting
041 * current, call startCacheFlush and then finishedCacheFlush or abortCacheFlush so this instance can
042 * keep abreast of the state of sequence id persistence. Also call update per append.
043 * <p>
044 * For the implementation, we assume that all the {@code encodedRegionName} passed in are gotten by
045 * {@link org.apache.hadoop.hbase.client.RegionInfo#getEncodedNameAsBytes()}. So it is safe to use
046 * it as a hash key. And for family name, we use {@link ImmutableByteArray} as key. This is because
047 * hash based map is much faster than RBTree or CSLM and here we are on the critical write path. See
048 * HBASE-16278 for more details.
049 * </p>
050 */
051@InterfaceAudience.Private
052class SequenceIdAccounting {
053  private static final Logger LOG = LoggerFactory.getLogger(SequenceIdAccounting.class);
054
055  /**
056   * This lock ties all operations on {@link SequenceIdAccounting#flushingSequenceIds} and
057   * {@link #lowestUnflushedSequenceIds} Maps. {@link #lowestUnflushedSequenceIds} has the lowest
058   * outstanding sequence ids EXCEPT when flushing. When we flush, the current lowest set for the
059   * region/column family are moved (atomically because of this lock) to
060   * {@link #flushingSequenceIds}.
061   * <p>
062   * The two Maps are tied by this locking object EXCEPT when we go to update the lowest entry; see
063   * {@link #lowestUnflushedSequenceIds}. In here is a putIfAbsent call on
064   * {@link #lowestUnflushedSequenceIds}. In this latter case, we will add this lowest sequence id
065   * if we find that there is no entry for the current column family. There will be no entry only if
066   * we just came up OR we have moved aside current set of lowest sequence ids because the current
067   * set are being flushed (by putting them into {@link #flushingSequenceIds}). This is how we pick
068   * up the next 'lowest' sequence id per region per column family to be used figuring what is in
069   * the next flush.
070   */
071  private final Object tieLock = new Object();
072
073  /**
074   * Map of encoded region names and family names to their OLDEST -- i.e. their first, the
075   * longest-lived, their 'earliest', the 'lowest' -- sequence id.
076   * <p>
077   * When we flush, the current lowest sequence ids get cleared and added to
078   * {@link #flushingSequenceIds}. The next append that comes in, is then added here to
079   * {@link #lowestUnflushedSequenceIds} as the next lowest sequenceid.
080   * <p>
081   * If flush fails, currently server is aborted so no need to restore previous sequence ids.
082   * <p>
083   * Needs to be concurrent Maps because we use putIfAbsent updating oldest.
084   */
085  private final ConcurrentMap<byte[],
086    ConcurrentMap<ImmutableByteArray, Long>> lowestUnflushedSequenceIds = new ConcurrentHashMap<>();
087
088  /**
089   * Map of encoded region names and family names to their lowest or OLDEST sequence/edit id
090   * currently being flushed out to hfiles. Entries are moved here from
091   * {@link #lowestUnflushedSequenceIds} while the lock {@link #tieLock} is held (so movement
092   * between the Maps is atomic).
093   */
094  private final Map<byte[], Map<ImmutableByteArray, Long>> flushingSequenceIds = new HashMap<>();
095
096  /**
097   * <p>
098   * Map of region encoded names to the latest/highest region sequence id. Updated on each call to
099   * append.
100   * </p>
101   * <p>
102   * This map uses byte[] as the key, and uses reference equality. It works in our use case as we
103   * use {@link org.apache.hadoop.hbase.client.RegionInfo#getEncodedNameAsBytes()} as keys. For a
104   * given region, it always returns the same array.
105   * </p>
106   */
107  private Map<byte[], Long> highestSequenceIds = new HashMap<>();
108
109  /**
110   * Returns the lowest unflushed sequence id for the region.
111   * @return Lowest outstanding unflushed sequenceid for <code>encodedRegionName</code>. Will return
112   *         {@link HConstants#NO_SEQNUM} when none.
113   */
114  long getLowestSequenceId(final byte[] encodedRegionName) {
115    synchronized (this.tieLock) {
116      Map<?, Long> m = this.flushingSequenceIds.get(encodedRegionName);
117      long flushingLowest = m != null ? getLowestSequenceId(m) : Long.MAX_VALUE;
118      m = this.lowestUnflushedSequenceIds.get(encodedRegionName);
119      long unflushedLowest = m != null ? getLowestSequenceId(m) : HConstants.NO_SEQNUM;
120      return Math.min(flushingLowest, unflushedLowest);
121    }
122  }
123
124  /**
125   * @return Lowest outstanding unflushed sequenceid for <code>encodedRegionname</code> and
126   *         <code>familyName</code>. Returned sequenceid may be for an edit currently being
127   *         flushed.
128   */
129  long getLowestSequenceId(final byte[] encodedRegionName, final byte[] familyName) {
130    ImmutableByteArray familyNameWrapper = ImmutableByteArray.wrap(familyName);
131    synchronized (this.tieLock) {
132      Map<ImmutableByteArray, Long> m = this.flushingSequenceIds.get(encodedRegionName);
133      if (m != null) {
134        Long lowest = m.get(familyNameWrapper);
135        if (lowest != null) {
136          return lowest;
137        }
138      }
139      m = this.lowestUnflushedSequenceIds.get(encodedRegionName);
140      if (m != null) {
141        Long lowest = m.get(familyNameWrapper);
142        if (lowest != null) {
143          return lowest;
144        }
145      }
146    }
147    return HConstants.NO_SEQNUM;
148  }
149
150  /**
151   * Reset the accounting of highest sequenceid by regionname.
152   * @return Return the previous accounting Map of regions to the last sequence id written into
153   *         each.
154   */
155  Map<byte[], Long> resetHighest() {
156    Map<byte[], Long> old = this.highestSequenceIds;
157    this.highestSequenceIds = new HashMap<>();
158    return old;
159  }
160
161  /**
162   * We've been passed a new sequenceid for the region. Set it as highest seen for this region and
163   * if we are to record oldest, or lowest sequenceids, save it as oldest seen if nothing currently
164   * older.
165   * @param lowest Whether to keep running account of oldest sequence id.
166   */
167  void update(byte[] encodedRegionName, Set<byte[]> families, long sequenceid,
168    final boolean lowest) {
169    Long l = Long.valueOf(sequenceid);
170    this.highestSequenceIds.put(encodedRegionName, l);
171    if (lowest) {
172      ConcurrentMap<ImmutableByteArray, Long> m = getOrCreateLowestSequenceIds(encodedRegionName);
173      for (byte[] familyName : families) {
174        m.putIfAbsent(ImmutableByteArray.wrap(familyName), l);
175      }
176    }
177  }
178
179  /**
180   * Clear all the records of the given region as it is going to be closed.
181   * <p/>
182   * We will call this once we get the region close marker. We need this because that, if we use
183   * Durability.ASYNC_WAL, after calling startCacheFlush, we may still get some ongoing wal entries
184   * that has not been processed yet, this will lead to orphan records in the
185   * lowestUnflushedSequenceIds and then cause too many WAL files.
186   * <p/>
187   * See HBASE-23157 for more details.
188   */
189  void onRegionClose(byte[] encodedRegionName) {
190    synchronized (tieLock) {
191      this.lowestUnflushedSequenceIds.remove(encodedRegionName);
192      Map<ImmutableByteArray, Long> flushing = this.flushingSequenceIds.remove(encodedRegionName);
193      if (flushing != null) {
194        LOG.warn("Still have flushing records when closing {}, {}",
195          Bytes.toString(encodedRegionName),
196          flushing.entrySet().stream().map(e -> e.getKey().toString() + "->" + e.getValue())
197            .collect(Collectors.joining(",", "{", "}")));
198      }
199    }
200    this.highestSequenceIds.remove(encodedRegionName);
201  }
202
203  /**
204   * Update the store sequence id, e.g., upon executing in-memory compaction
205   */
206  void updateStore(byte[] encodedRegionName, byte[] familyName, Long sequenceId,
207    boolean onlyIfGreater) {
208    if (sequenceId == null) {
209      return;
210    }
211    Long highest = this.highestSequenceIds.get(encodedRegionName);
212    if (highest == null || sequenceId > highest) {
213      this.highestSequenceIds.put(encodedRegionName, sequenceId);
214    }
215    ImmutableByteArray familyNameWrapper = ImmutableByteArray.wrap(familyName);
216    synchronized (this.tieLock) {
217      ConcurrentMap<ImmutableByteArray, Long> m = getOrCreateLowestSequenceIds(encodedRegionName);
218      boolean replaced = false;
219      while (!replaced) {
220        Long oldSeqId = m.get(familyNameWrapper);
221        if (oldSeqId == null) {
222          m.put(familyNameWrapper, sequenceId);
223          replaced = true;
224        } else if (onlyIfGreater) {
225          if (sequenceId > oldSeqId) {
226            replaced = m.replace(familyNameWrapper, oldSeqId, sequenceId);
227          } else {
228            return;
229          }
230        } else { // replace even if sequence id is not greater than oldSeqId
231          m.put(familyNameWrapper, sequenceId);
232          return;
233        }
234      }
235    }
236  }
237
238  ConcurrentMap<ImmutableByteArray, Long> getOrCreateLowestSequenceIds(byte[] encodedRegionName) {
239    // Intentionally, this access is done outside of this.regionSequenceIdLock. Done per append.
240    return computeIfAbsent(this.lowestUnflushedSequenceIds, encodedRegionName,
241      ConcurrentHashMap::new);
242  }
243
244  /**
245   * @param sequenceids Map to search for lowest value.
246   * @return Lowest value found in <code>sequenceids</code>.
247   */
248  private static long getLowestSequenceId(Map<?, Long> sequenceids) {
249    long lowest = HConstants.NO_SEQNUM;
250    for (Map.Entry<?, Long> entry : sequenceids.entrySet()) {
251      if (entry.getKey().toString().equals("METAFAMILY")) {
252        continue;
253      }
254      Long sid = entry.getValue();
255      if (lowest == HConstants.NO_SEQNUM || sid.longValue() < lowest) {
256        lowest = sid.longValue();
257      }
258    }
259    return lowest;
260  }
261
262  /**
263   * @return New Map that has same keys as <code>src</code> but instead of a Map for a value, it
264   *         instead has found the smallest sequence id and it returns that as the value instead.
265   */
266  private <T extends Map<?, Long>> Map<byte[], Long> flattenToLowestSequenceId(Map<byte[], T> src) {
267    if (src == null || src.isEmpty()) {
268      return null;
269    }
270    Map<byte[], Long> tgt = new HashMap<>();
271    for (Map.Entry<byte[], T> entry : src.entrySet()) {
272      long lowestSeqId = getLowestSequenceId(entry.getValue());
273      if (lowestSeqId != HConstants.NO_SEQNUM) {
274        tgt.put(entry.getKey(), lowestSeqId);
275      }
276    }
277    return tgt;
278  }
279
280  /**
281   * @param encodedRegionName Region to flush.
282   * @param families          Families to flush. May be a subset of all families in the region.
283   * @return Returns {@link HConstants#NO_SEQNUM} if we are flushing the whole region OR if we are
284   *         flushing a subset of all families but there are no edits in those families not being
285   *         flushed; in other words, this is effectively same as a flush of all of the region
286   *         though we were passed a subset of regions. Otherwise, it returns the sequence id of the
287   *         oldest/lowest outstanding edit.
288   */
289  Long startCacheFlush(final byte[] encodedRegionName, final Set<byte[]> families) {
290    Map<byte[], Long> familytoSeq = new HashMap<>();
291    for (byte[] familyName : families) {
292      familytoSeq.put(familyName, HConstants.NO_SEQNUM);
293    }
294    return startCacheFlush(encodedRegionName, familytoSeq);
295  }
296
297  Long startCacheFlush(final byte[] encodedRegionName, final Map<byte[], Long> familyToSeq) {
298    Map<ImmutableByteArray, Long> oldSequenceIds = null;
299    Long lowestUnflushedInRegion = HConstants.NO_SEQNUM;
300    synchronized (tieLock) {
301      Map<ImmutableByteArray, Long> m = this.lowestUnflushedSequenceIds.get(encodedRegionName);
302      if (m != null) {
303        // NOTE: Removal from this.lowestUnflushedSequenceIds must be done in controlled
304        // circumstance because another concurrent thread now may add sequenceids for this family
305        // (see above in getOrCreateLowestSequenceId). Make sure you are ok with this. Usually it
306        // is fine because updates are blocked when this method is called. Make sure!!!
307        for (Map.Entry<byte[], Long> entry : familyToSeq.entrySet()) {
308          ImmutableByteArray familyNameWrapper = ImmutableByteArray.wrap((byte[]) entry.getKey());
309          Long seqId = null;
310          if (entry.getValue() == HConstants.NO_SEQNUM) {
311            seqId = m.remove(familyNameWrapper);
312          } else {
313            seqId = m.replace(familyNameWrapper, entry.getValue());
314          }
315          if (seqId != null) {
316            if (oldSequenceIds == null) {
317              oldSequenceIds = new HashMap<>();
318            }
319            oldSequenceIds.put(familyNameWrapper, seqId);
320          }
321        }
322        if (oldSequenceIds != null && !oldSequenceIds.isEmpty()) {
323          if (this.flushingSequenceIds.put(encodedRegionName, oldSequenceIds) != null) {
324            LOG.warn("Flushing Map not cleaned up for " + Bytes.toString(encodedRegionName)
325              + ", sequenceid=" + oldSequenceIds);
326          }
327        }
328        if (m.isEmpty()) {
329          // Remove it otherwise it will be in oldestUnflushedStoreSequenceIds for ever
330          // even if the region is already moved to other server.
331          // Do not worry about data racing, we held write lock of region when calling
332          // startCacheFlush, so no one can add value to the map we removed.
333          this.lowestUnflushedSequenceIds.remove(encodedRegionName);
334        } else {
335          // Flushing a subset of the region families. Return the sequence id of the oldest entry.
336          lowestUnflushedInRegion = Collections.min(m.values());
337        }
338      }
339    }
340    // Do this check outside lock.
341    if (oldSequenceIds != null && oldSequenceIds.isEmpty()) {
342      // TODO: if we have no oldStoreSeqNum, and WAL is not disabled, presumably either
343      // the region is already flushing (which would make this call invalid), or there
344      // were no appends after last flush, so why are we starting flush? Maybe we should
345      // assert not empty. Less rigorous, but safer, alternative is telling the caller to stop.
346      // For now preserve old logic.
347      LOG.warn("Couldn't find oldest sequenceid for " + Bytes.toString(encodedRegionName));
348    }
349    return lowestUnflushedInRegion;
350  }
351
352  void completeCacheFlush(byte[] encodedRegionName, long maxFlushedSeqId) {
353    // This is a simple hack to avoid maxFlushedSeqId go backwards.
354    // The system works fine normally, but if we make use of Durability.ASYNC_WAL and we are going
355    // to flush all the stores, the maxFlushedSeqId will be next seq id of the region, but we may
356    // still have some unsynced WAL entries in the ringbuffer after we call startCacheFlush, and
357    // then it will be recorded as the lowestUnflushedSeqId by the above update method, which is
358    // less than the current maxFlushedSeqId. And if next time we only flush the family with this
359    // unusual lowestUnflushedSeqId, the maxFlushedSeqId will go backwards.
360    // This is an unexpected behavior so we should fix it, otherwise it may cause unexpected
361    // behavior in other area.
362    // The solution here is a bit hack but fine. Just replace the lowestUnflushedSeqId with
363    // maxFlushedSeqId + 1 if it is lesser. The meaning of maxFlushedSeqId is that, all edits less
364    // than or equal to it have been flushed, i.e, persistent to HFile, so set
365    // lowestUnflushedSequenceId to maxFlushedSeqId + 1 will not cause data loss.
366    // And technically, using +1 is fine here. If the maxFlushesSeqId is just the flushOpSeqId, it
367    // means we have flushed all the stores so the seq id for actual data should be at least plus 1.
368    // And if we do not flush all the stores, then the maxFlushedSeqId is calculated by
369    // lowestUnflushedSeqId - 1, so here let's plus the 1 back.
370    Long wrappedSeqId = Long.valueOf(maxFlushedSeqId + 1);
371    synchronized (tieLock) {
372      this.flushingSequenceIds.remove(encodedRegionName);
373      Map<ImmutableByteArray, Long> unflushed = lowestUnflushedSequenceIds.get(encodedRegionName);
374      if (unflushed == null) {
375        return;
376      }
377      for (Map.Entry<ImmutableByteArray, Long> e : unflushed.entrySet()) {
378        if (e.getValue().longValue() <= maxFlushedSeqId) {
379          e.setValue(wrappedSeqId);
380        }
381      }
382    }
383  }
384
385  void abortCacheFlush(final byte[] encodedRegionName) {
386    // Method is called when we are crashing down because failed write flush AND it is called
387    // if we fail prepare. The below is for the fail prepare case; we restore the old sequence ids.
388    Map<ImmutableByteArray, Long> flushing = null;
389    Map<ImmutableByteArray, Long> tmpMap = new HashMap<>();
390    // Here we are moving sequenceids from flushing back to unflushed; doing opposite of what
391    // happened in startCacheFlush. During prepare phase, we have update lock on the region so
392    // no edits should be coming in via append.
393    synchronized (tieLock) {
394      flushing = this.flushingSequenceIds.remove(encodedRegionName);
395      if (flushing != null) {
396        Map<ImmutableByteArray, Long> unflushed = getOrCreateLowestSequenceIds(encodedRegionName);
397        for (Map.Entry<ImmutableByteArray, Long> e : flushing.entrySet()) {
398          // Set into unflushed the 'old' oldest sequenceid and if any value in flushed with this
399          // value, it will now be in tmpMap.
400          tmpMap.put(e.getKey(), unflushed.put(e.getKey(), e.getValue()));
401        }
402      }
403    }
404
405    // Here we are doing some 'test' to see if edits are going in out of order. What is it for?
406    // Carried over from old code.
407    if (flushing != null) {
408      for (Map.Entry<ImmutableByteArray, Long> e : flushing.entrySet()) {
409        Long currentId = tmpMap.get(e.getKey());
410        if (currentId != null && currentId.longValue() < e.getValue().longValue()) {
411          String errorStr = Bytes.toString(encodedRegionName) + " family " + e.getKey().toString()
412            + " acquired edits out of order current memstore seq=" + currentId
413            + ", previous oldest unflushed id=" + e.getValue();
414          LOG.error(errorStr);
415          Runtime.getRuntime().halt(1);
416        }
417      }
418    }
419  }
420
421  /**
422   * See if passed <code>sequenceids</code> are lower -- i.e. earlier -- than any outstanding
423   * sequenceids, sequenceids we are holding on to in this accounting instance.
424   * @param sequenceids Keyed by encoded region name. Cannot be null (doesn't make sense for it to
425   *                    be null).
426   * @return true if all sequenceids are lower, older than, the old sequenceids in this instance.
427   */
428  boolean areAllLower(Map<byte[], Long> sequenceids) {
429    Map<byte[], Long> flushing = null;
430    Map<byte[], Long> unflushed = null;
431    synchronized (this.tieLock) {
432      // Get a flattened -- only the oldest sequenceid -- copy of current flushing and unflushed
433      // data structures to use in tests below.
434      flushing = flattenToLowestSequenceId(this.flushingSequenceIds);
435      unflushed = flattenToLowestSequenceId(this.lowestUnflushedSequenceIds);
436    }
437    for (Map.Entry<byte[], Long> e : sequenceids.entrySet()) {
438      long oldestFlushing = Long.MAX_VALUE;
439      long oldestUnflushed = Long.MAX_VALUE;
440      if (flushing != null && flushing.containsKey(e.getKey())) {
441        oldestFlushing = flushing.get(e.getKey());
442      }
443      if (unflushed != null && unflushed.containsKey(e.getKey())) {
444        oldestUnflushed = unflushed.get(e.getKey());
445      }
446      long min = Math.min(oldestFlushing, oldestUnflushed);
447      if (min <= e.getValue()) {
448        return false;
449      }
450    }
451    return true;
452  }
453
454  /**
455   * Iterates over the given Map and compares sequence ids with corresponding entries in
456   * {@link #lowestUnflushedSequenceIds}. If a region in {@link #lowestUnflushedSequenceIds} has a
457   * sequence id less than that passed in <code>sequenceids</code> then return it.
458   * @param sequenceids Sequenceids keyed by encoded region name.
459   * @return stores of regions found in this instance with sequence ids less than those passed in.
460   */
461  Map<byte[], List<byte[]>> findLower(Map<byte[], Long> sequenceids) {
462    Map<byte[], List<byte[]>> toFlush = null;
463    // Keeping the old behavior of iterating unflushedSeqNums under oldestSeqNumsLock.
464    synchronized (tieLock) {
465      for (Map.Entry<byte[], Long> e : sequenceids.entrySet()) {
466        Map<ImmutableByteArray, Long> m = this.lowestUnflushedSequenceIds.get(e.getKey());
467        if (m == null) {
468          continue;
469        }
470        for (Map.Entry<ImmutableByteArray, Long> me : m.entrySet()) {
471          if (me.getValue() <= e.getValue()) {
472            if (toFlush == null) {
473              toFlush = new TreeMap(Bytes.BYTES_COMPARATOR);
474            }
475            toFlush.computeIfAbsent(e.getKey(), k -> new ArrayList<>())
476              .add(Bytes.toBytes(me.getKey().toString()));
477          }
478        }
479      }
480    }
481    return toFlush;
482  }
483}