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