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