1 /**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package org.apache.hadoop.hbase.regionserver.wal;
19
20 import com.google.common.annotations.VisibleForTesting;
21
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ConcurrentMap;
30
31 import org.apache.commons.logging.Log;
32 import org.apache.commons.logging.LogFactory;
33 import org.apache.hadoop.hbase.HConstants;
34 import org.apache.hadoop.hbase.HRegionInfo;
35 import org.apache.hadoop.hbase.classification.InterfaceAudience;
36 import org.apache.hadoop.hbase.util.Bytes;
37 import org.apache.hadoop.hbase.util.ImmutableByteArray;
38
39 /**
40 * Accounting of sequence ids per region and then by column family. So we can our accounting
41 * current, call startCacheFlush and then finishedCacheFlush or abortCacheFlush so this instance can
42 * keep abreast of the state of sequence id persistence. Also call update per append.
43 * <p>
44 * For the implementation, we assume that all the {@code encodedRegionName} passed in is gotten by
45 * {@link HRegionInfo#getEncodedNameAsBytes()}. So it is safe to use it as a hash key. And for
46 * family name, we use {@link ImmutableByteArray} as key. This is because hash based map is much
47 * faster than RBTree or CSLM and here we are on the critical write path. See HBASE-16278 for more
48 * details.
49 */
50 @InterfaceAudience.Private
51 class SequenceIdAccounting {
52
53 private static final Log LOG = LogFactory.getLog(SequenceIdAccounting.class);
54 /**
55 * This lock ties all operations on {@link SequenceIdAccounting#flushingSequenceIds} and
56 * {@link #lowestUnflushedSequenceIds} Maps. {@link #lowestUnflushedSequenceIds} has the
57 * lowest outstanding sequence ids EXCEPT when flushing. When we flush, the current
58 * lowest set for the region/column family are moved (atomically because of this lock) to
59 * {@link #flushingSequenceIds}.
60 *
61 * <p>The two Maps are tied by this locking object EXCEPT when we go to update the lowest
62 * entry; see {@link #lowest(byte[], Set, Long)}. In here is a putIfAbsent call on
63 * {@link #lowestUnflushedSequenceIds}. In this latter case, we will add this lowest
64 * sequence id if we find that there is no entry for the current column family. There will be no
65 * entry only if we just came up OR we have moved aside current set of lowest sequence ids
66 * because the current set are being flushed (by putting them into {@link #flushingSequenceIds}).
67 * This is how we pick up the next 'lowest' sequence id per region per column family to be used
68 * figuring what is in the next flush.
69 */
70 private final Object tieLock = new Object();
71
72 /**
73 * Map of encoded region names and family names to their OLDEST -- i.e. their first,
74 * the longest-lived, their 'earliest', the 'lowest' -- sequence id.
75 *
76 * <p>When we flush, the current lowest sequence ids get cleared and added to
77 * {@link #flushingSequenceIds}. The next append that comes in, is then added
78 * here to {@link #lowestUnflushedSequenceIds} as the next lowest sequenceid.
79 *
80 * <p>If flush fails, currently server is aborted so no need to restore previous sequence ids.
81 * <p>Needs to be concurrent Maps because we use putIfAbsent updating oldest.
82 */
83 private final ConcurrentMap<byte[], ConcurrentMap<ImmutableByteArray, Long>>
84 lowestUnflushedSequenceIds = new ConcurrentHashMap<>();
85
86 /**
87 * Map of encoded region names and family names to their lowest or OLDEST sequence/edit id
88 * currently being flushed out to hfiles. Entries are moved here from
89 * {@link #lowestUnflushedSequenceIds} while the lock {@link #tieLock} is held
90 * (so movement between the Maps is atomic).
91 */
92 private final Map<byte[], Map<ImmutableByteArray, Long>> flushingSequenceIds = new HashMap<>();
93
94 /**
95 * Map of region encoded names to the latest/highest region sequence id. Updated on each
96 * call to append.
97 * <p>
98 * This map uses byte[] as the key, and uses reference equality. It works in our use case as we
99 * use {@link HRegionInfo#getEncodedNameAsBytes()} as keys. For a given region, it always returns
100 * the same array.
101 */
102 private Map<byte[], Long> highestSequenceIds = new HashMap<>();
103
104 /**
105 * Returns the lowest unflushed sequence id for the region.
106 * @param encodedRegionName
107 * @return Lowest outstanding unflushed sequenceid for <code>encodedRegionName</code>. Will
108 * return {@link HConstants#NO_SEQNUM} when none.
109 */
110 long getLowestSequenceId(final byte[] encodedRegionName) {
111 synchronized (this.tieLock) {
112 Map<?, Long> m = this.flushingSequenceIds.get(encodedRegionName);
113 long flushingLowest = m != null ? getLowestSequenceId(m) : Long.MAX_VALUE;
114 m = this.lowestUnflushedSequenceIds.get(encodedRegionName);
115 long unflushedLowest = m != null ? getLowestSequenceId(m) : HConstants.NO_SEQNUM;
116 return Math.min(flushingLowest, unflushedLowest);
117 }
118 }
119
120 /**
121 * @param encodedRegionName
122 * @param familyName
123 * @return Lowest outstanding unflushed sequenceid for <code>encodedRegionname</code> and
124 * <code>familyName</code>. Returned sequenceid may be for an edit currently being
125 * flushed.
126 */
127 long getLowestSequenceId(final byte[] encodedRegionName, final byte[] familyName) {
128 ImmutableByteArray familyNameWrapper = ImmutableByteArray.wrap(familyName);
129 synchronized (this.tieLock) {
130 Map<ImmutableByteArray, Long> m = this.flushingSequenceIds.get(encodedRegionName);
131 if (m != null) {
132 Long lowest = m.get(familyNameWrapper);
133 if (lowest != null) {
134 return lowest;
135 }
136 }
137 m = this.lowestUnflushedSequenceIds.get(encodedRegionName);
138 if (m != null) {
139 Long lowest = m.get(familyNameWrapper);
140 if (lowest != null) {
141 return lowest;
142 }
143 }
144 }
145 return HConstants.NO_SEQNUM;
146 }
147
148 /**
149 * Reset the accounting of highest sequenceid by regionname.
150 * @return Return the previous accounting Map of regions to the last sequence id written into
151 * each.
152 */
153 Map<byte[], Long> resetHighest() {
154 Map<byte[], Long> old = this.highestSequenceIds;
155 this.highestSequenceIds = new HashMap<byte[], Long>();
156 return old;
157 }
158
159 /**
160 * We've been passed a new sequenceid for the region. Set it as highest seen for this region and
161 * if we are to record oldest, or lowest sequenceids, save it as oldest seen if nothing
162 * currently older.
163 * @param encodedRegionName
164 * @param families
165 * @param sequenceid
166 * @param lowest Whether to keep running account of oldest sequence id.
167 */
168 void update(byte[] encodedRegionName, Set<byte[]> families, long sequenceid,
169 final boolean lowest) {
170 Long l = Long.valueOf(sequenceid);
171 this.highestSequenceIds.put(encodedRegionName, l);
172 if (lowest) {
173 ConcurrentMap<ImmutableByteArray, Long> m = getOrCreateLowestSequenceIds(encodedRegionName);
174 for (byte[] familyName : families) {
175 m.putIfAbsent(ImmutableByteArray.wrap(familyName), l);
176 }
177 }
178 }
179
180 @VisibleForTesting
181 ConcurrentMap<ImmutableByteArray, Long> getOrCreateLowestSequenceIds(byte[] encodedRegionName) {
182 // Intentionally, this access is done outside of this.regionSequenceIdLock. Done per append.
183 ConcurrentMap<ImmutableByteArray, Long> m = this.lowestUnflushedSequenceIds
184 .get(encodedRegionName);
185 if (m != null) {
186 return m;
187 }
188 m = new ConcurrentHashMap<>();
189 // Another thread may have added it ahead of us.
190 ConcurrentMap<ImmutableByteArray, Long> alreadyPut = this.lowestUnflushedSequenceIds
191 .putIfAbsent(encodedRegionName, m);
192 return alreadyPut == null ? m : alreadyPut;
193 }
194
195 /**
196 * @param sequenceids Map to search for lowest value.
197 * @return Lowest value found in <code>sequenceids</code>.
198 */
199 private static long getLowestSequenceId(Map<?, Long> sequenceids) {
200 long lowest = HConstants.NO_SEQNUM;
201 for (Long sid: sequenceids.values()) {
202 if (lowest == HConstants.NO_SEQNUM || sid.longValue() < lowest) {
203 lowest = sid.longValue();
204 }
205 }
206 return lowest;
207 }
208
209 /**
210 * @param src
211 * @return New Map that has same keys as <code>src</code> but instead of a Map for a value, it
212 * instead has found the smallest sequence id and it returns that as the value instead.
213 */
214 private <T extends Map<?, Long>> Map<byte[], Long> flattenToLowestSequenceId(Map<byte[], T> src) {
215 if (src == null || src.isEmpty()) {
216 return null;
217 }
218 Map<byte[], Long> tgt = new HashMap<>();
219 for (Map.Entry<byte[], T> entry : src.entrySet()) {
220 long lowestSeqId = getLowestSequenceId(entry.getValue());
221 if (lowestSeqId != HConstants.NO_SEQNUM) {
222 tgt.put(entry.getKey(), lowestSeqId);
223 }
224 }
225 return tgt;
226 }
227
228 /**
229 * @param encodedRegionName Region to flush.
230 * @param families Families to flush. May be a subset of all families in the region.
231 * @return Returns {@link HConstants#NO_SEQNUM} if we are flushing the whole region OR if
232 * we are flushing a subset of all families but there are no edits in those families not
233 * being flushed; in other words, this is effectively same as a flush of all of the region
234 * though we were passed a subset of regions. Otherwise, it returns the sequence id of the
235 * oldest/lowest outstanding edit.
236 */
237 Long startCacheFlush(final byte[] encodedRegionName, final Set<byte[]> families) {
238 Map<ImmutableByteArray, Long> oldSequenceIds = null;
239 Long lowestUnflushedInRegion = HConstants.NO_SEQNUM;
240 synchronized (tieLock) {
241 Map<ImmutableByteArray, Long> m = this.lowestUnflushedSequenceIds.get(encodedRegionName);
242 if (m != null) {
243 // NOTE: Removal from this.lowestUnflushedSequenceIds must be done in controlled
244 // circumstance because another concurrent thread now may add sequenceids for this family
245 // (see above in getOrCreateLowestSequenceId). Make sure you are ok with this. Usually it
246 // is fine because updates are blocked when this method is called. Make sure!!!
247 for (byte[] familyName : families) {
248 ImmutableByteArray familyNameWrapper = ImmutableByteArray.wrap(familyName);
249 Long seqId = m.remove(familyNameWrapper);
250 if (seqId != null) {
251 if (oldSequenceIds == null) {
252 oldSequenceIds = new HashMap<>();
253 }
254 oldSequenceIds.put(familyNameWrapper, seqId);
255 }
256 }
257 if (oldSequenceIds != null && !oldSequenceIds.isEmpty()) {
258 if (this.flushingSequenceIds.put(encodedRegionName, oldSequenceIds) != null) {
259 LOG.warn("Flushing Map not cleaned up for " + Bytes.toString(encodedRegionName) +
260 ", sequenceid=" + oldSequenceIds);
261 }
262 }
263 if (m.isEmpty()) {
264 // Remove it otherwise it will be in oldestUnflushedStoreSequenceIds for ever
265 // even if the region is already moved to other server.
266 // Do not worry about data racing, we held write lock of region when calling
267 // startCacheFlush, so no one can add value to the map we removed.
268 this.lowestUnflushedSequenceIds.remove(encodedRegionName);
269 } else {
270 // Flushing a subset of the region families. Return the sequence id of the oldest entry.
271 lowestUnflushedInRegion = Collections.min(m.values());
272 }
273 }
274 }
275 // Do this check outside lock.
276 if (oldSequenceIds != null && oldSequenceIds.isEmpty()) {
277 // TODO: if we have no oldStoreSeqNum, and WAL is not disabled, presumably either
278 // the region is already flushing (which would make this call invalid), or there
279 // were no appends after last flush, so why are we starting flush? Maybe we should
280 // assert not empty. Less rigorous, but safer, alternative is telling the caller to stop.
281 // For now preserve old logic.
282 LOG.warn("Couldn't find oldest sequenceid for " + Bytes.toString(encodedRegionName));
283 }
284 return lowestUnflushedInRegion;
285 }
286
287 void completeCacheFlush(final byte[] encodedRegionName) {
288 synchronized (tieLock) {
289 this.flushingSequenceIds.remove(encodedRegionName);
290 }
291 }
292
293 void abortCacheFlush(final byte[] encodedRegionName) {
294 // Method is called when we are crashing down because failed write flush AND it is called
295 // if we fail prepare. The below is for the fail prepare case; we restore the old sequence ids.
296 Map<ImmutableByteArray, Long> flushing = null;
297 Map<ImmutableByteArray, Long> tmpMap = new HashMap<>();
298 // Here we are moving sequenceids from flushing back to unflushed; doing opposite of what
299 // happened in startCacheFlush. During prepare phase, we have update lock on the region so
300 // no edits should be coming in via append.
301 synchronized (tieLock) {
302 flushing = this.flushingSequenceIds.remove(encodedRegionName);
303 if (flushing != null) {
304 Map<ImmutableByteArray, Long> unflushed = getOrCreateLowestSequenceIds(encodedRegionName);
305 for (Map.Entry<ImmutableByteArray, Long> e: flushing.entrySet()) {
306 // Set into unflushed the 'old' oldest sequenceid and if any value in flushed with this
307 // value, it will now be in tmpMap.
308 tmpMap.put(e.getKey(), unflushed.put(e.getKey(), e.getValue()));
309 }
310 }
311 }
312
313 // Here we are doing some 'test' to see if edits are going in out of order. What is it for?
314 // Carried over from old code.
315 if (flushing != null) {
316 for (Map.Entry<ImmutableByteArray, Long> e : flushing.entrySet()) {
317 Long currentId = tmpMap.get(e.getKey());
318 if (currentId != null && currentId.longValue() <= e.getValue().longValue()) {
319 String errorStr = Bytes.toString(encodedRegionName) + " family "
320 + e.getKey().toStringUtf8() + " acquired edits out of order current memstore seq="
321 + currentId + ", previous oldest unflushed id=" + e.getValue();
322 LOG.error(errorStr);
323 Runtime.getRuntime().halt(1);
324 }
325 }
326 }
327 }
328
329 /**
330 * See if passed <code>sequenceids</code> are lower -- i.e. earlier -- than any outstanding
331 * sequenceids, sequenceids we are holding on to in this accounting instance.
332 * @param sequenceids Keyed by encoded region name. Cannot be null (doesn't make sense for it to
333 * be null).
334 * @return true if all sequenceids are lower, older than, the old sequenceids in this instance.
335 */
336 boolean areAllLower(Map<byte[], Long> sequenceids) {
337 Map<byte[], Long> flushing = null;
338 Map<byte[], Long> unflushed = null;
339 synchronized (this.tieLock) {
340 // Get a flattened -- only the oldest sequenceid -- copy of current flushing and unflushed
341 // data structures to use in tests below.
342 flushing = flattenToLowestSequenceId(this.flushingSequenceIds);
343 unflushed = flattenToLowestSequenceId(this.lowestUnflushedSequenceIds);
344 }
345 for (Map.Entry<byte[], Long> e : sequenceids.entrySet()) {
346 long oldestFlushing = Long.MAX_VALUE;
347 long oldestUnflushed = Long.MAX_VALUE;
348 if (flushing != null && flushing.containsKey(e.getKey())) {
349 oldestFlushing = flushing.get(e.getKey());
350 }
351 if (unflushed != null && unflushed.containsKey(e.getKey())) {
352 oldestUnflushed = unflushed.get(e.getKey());
353 }
354 long min = Math.min(oldestFlushing, oldestUnflushed);
355 if (min <= e.getValue()) {
356 return false;
357 }
358 }
359 return true;
360 }
361
362 /**
363 * Iterates over the given Map and compares sequence ids with corresponding entries in
364 * {@link #oldestUnflushedRegionSequenceIds}. If a region in
365 * {@link #oldestUnflushedRegionSequenceIds} has a sequence id less than that passed in
366 * <code>sequenceids</code> then return it.
367 * @param sequenceids Sequenceids keyed by encoded region name.
368 * @return regions found in this instance with sequence ids less than those passed in.
369 */
370 byte[][] findLower(Map<byte[], Long> sequenceids) {
371 List<byte[]> toFlush = null;
372 // Keeping the old behavior of iterating unflushedSeqNums under oldestSeqNumsLock.
373 synchronized (tieLock) {
374 for (Map.Entry<byte[], Long> e : sequenceids.entrySet()) {
375 Map<ImmutableByteArray, Long> m = this.lowestUnflushedSequenceIds.get(e.getKey());
376 if (m == null) {
377 continue;
378 }
379 // The lowest sequence id outstanding for this region.
380 long lowest = getLowestSequenceId(m);
381 if (lowest != HConstants.NO_SEQNUM && lowest <= e.getValue()) {
382 if (toFlush == null) {
383 toFlush = new ArrayList<byte[]>();
384 }
385 toFlush.add(e.getKey());
386 }
387 }
388 }
389 return toFlush == null ? null : toFlush.toArray(new byte[0][]);
390 }
391 }