1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.regionserver;
20
21 import static org.apache.hadoop.util.StringUtils.humanReadableInt;
22
23 import java.io.IOException;
24 import java.lang.Thread.UncaughtExceptionHandler;
25 import java.lang.management.MemoryUsage;
26 import java.util.ArrayList;
27 import java.util.ConcurrentModificationException;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.SortedMap;
34 import java.util.concurrent.BlockingQueue;
35 import java.util.concurrent.DelayQueue;
36 import java.util.concurrent.Delayed;
37 import java.util.concurrent.ThreadFactory;
38 import java.util.concurrent.TimeUnit;
39 import java.util.concurrent.atomic.AtomicBoolean;
40 import java.util.concurrent.locks.ReentrantReadWriteLock;
41
42 import org.apache.commons.logging.Log;
43 import org.apache.commons.logging.LogFactory;
44 import org.apache.hadoop.conf.Configuration;
45 import org.apache.hadoop.hbase.DroppedSnapshotException;
46 import org.apache.hadoop.hbase.HConstants;
47 import org.apache.hadoop.hbase.RemoteExceptionHandler;
48 import org.apache.hadoop.hbase.classification.InterfaceAudience;
49 import org.apache.hadoop.hbase.client.RegionReplicaUtil;
50 import org.apache.hadoop.hbase.io.util.HeapMemorySizeUtil;
51 import org.apache.hadoop.hbase.regionserver.Region.FlushResult;
52 import org.apache.hadoop.hbase.util.Bytes;
53 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
54 import org.apache.hadoop.hbase.util.HasThread;
55 import org.apache.hadoop.hbase.util.ServerRegionReplicaUtil;
56 import org.apache.hadoop.hbase.util.Threads;
57 import org.apache.hadoop.util.StringUtils;
58 import org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix;
59 import org.apache.htrace.Trace;
60 import org.apache.htrace.TraceScope;
61 import org.apache.hadoop.hbase.util.Counter;
62
63 import com.google.common.base.Preconditions;
64
65
66
67
68
69
70
71
72
73
74 @InterfaceAudience.Private
75 class MemStoreFlusher implements FlushRequester {
76 private static final Log LOG = LogFactory.getLog(MemStoreFlusher.class);
77
78 private Configuration conf;
79
80
81 private final BlockingQueue<FlushQueueEntry> flushQueue =
82 new DelayQueue<FlushQueueEntry>();
83 private final Map<Region, FlushRegionEntry> regionsInQueue =
84 new HashMap<Region, FlushRegionEntry>();
85 private AtomicBoolean wakeupPending = new AtomicBoolean();
86
87 private final long threadWakeFrequency;
88 private final HRegionServer server;
89 private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
90 private final Object blockSignal = new Object();
91
92 protected long globalMemStoreLimit;
93 protected float globalMemStoreLimitLowMarkPercent;
94 protected long globalMemStoreLimitLowMark;
95
96 private long blockingWaitTime;
97 private final Counter updatesBlockedMsHighWater = new Counter();
98
99 private final FlushHandler[] flushHandlers;
100 private List<FlushRequestListener> flushRequestListeners = new ArrayList<FlushRequestListener>(1);
101
102
103
104
105
106 public MemStoreFlusher(final Configuration conf,
107 final HRegionServer server) {
108 super();
109 this.conf = conf;
110 this.server = server;
111 this.threadWakeFrequency =
112 conf.getLong(HConstants.THREAD_WAKE_FREQUENCY, 10 * 1000);
113 long max = -1L;
114 final MemoryUsage usage = HeapMemorySizeUtil.safeGetHeapMemoryUsage();
115 if (usage != null) {
116 max = usage.getMax();
117 }
118 float globalMemStorePercent = HeapMemorySizeUtil.getGlobalMemStorePercent(conf, true);
119 this.globalMemStoreLimit = (long) (max * globalMemStorePercent);
120 this.globalMemStoreLimitLowMarkPercent =
121 HeapMemorySizeUtil.getGlobalMemStoreLowerMark(conf, globalMemStorePercent);
122 this.globalMemStoreLimitLowMark =
123 (long) (this.globalMemStoreLimit * this.globalMemStoreLimitLowMarkPercent);
124
125 this.blockingWaitTime = conf.getInt("hbase.hstore.blockingWaitTime",
126 90000);
127 int handlerCount = conf.getInt("hbase.hstore.flusher.count", 2);
128 this.flushHandlers = new FlushHandler[handlerCount];
129 LOG.info("globalMemStoreLimit="
130 + TraditionalBinaryPrefix.long2String(this.globalMemStoreLimit, "", 1)
131 + ", globalMemStoreLimitLowMark="
132 + TraditionalBinaryPrefix.long2String(this.globalMemStoreLimitLowMark, "", 1)
133 + ", maxHeap=" + TraditionalBinaryPrefix.long2String(max, "", 1));
134 }
135
136 public Counter getUpdatesBlockedMsHighWater() {
137 return this.updatesBlockedMsHighWater;
138 }
139
140
141
142
143
144
145
146 private boolean flushOneForGlobalPressure() {
147 SortedMap<Long, Region> regionsBySize = server.getCopyOfOnlineRegionsSortedBySize();
148 Set<Region> excludedRegions = new HashSet<Region>();
149
150 double secondaryMultiplier
151 = ServerRegionReplicaUtil.getRegionReplicaStoreFileRefreshMultiplier(conf);
152
153 boolean flushedOne = false;
154 while (!flushedOne) {
155
156
157 Region bestFlushableRegion = getBiggestMemstoreRegion(regionsBySize, excludedRegions, true);
158
159 Region bestAnyRegion = getBiggestMemstoreRegion(
160 regionsBySize, excludedRegions, false);
161
162 Region bestRegionReplica = getBiggestMemstoreOfRegionReplica(regionsBySize,
163 excludedRegions);
164
165 if (bestAnyRegion == null && bestRegionReplica == null) {
166 LOG.error("Above memory mark but there are no flushable regions!");
167 return false;
168 }
169
170 Region regionToFlush;
171 if (bestFlushableRegion != null &&
172 bestAnyRegion.getMemstoreSize() > 2 * bestFlushableRegion.getMemstoreSize()) {
173
174
175
176
177 if (LOG.isDebugEnabled()) {
178 LOG.debug("Under global heap pressure: " + "Region "
179 + bestAnyRegion.getRegionInfo().getRegionNameAsString()
180 + " has too many " + "store files, but is "
181 + TraditionalBinaryPrefix.long2String(bestAnyRegion.getMemstoreSize(), "", 1)
182 + " vs best flushable region's "
183 + TraditionalBinaryPrefix.long2String(bestFlushableRegion.getMemstoreSize(), "", 1)
184 + ". Choosing the bigger.");
185 }
186 regionToFlush = bestAnyRegion;
187 } else {
188 if (bestFlushableRegion == null) {
189 regionToFlush = bestAnyRegion;
190 } else {
191 regionToFlush = bestFlushableRegion;
192 }
193 }
194
195 Preconditions.checkState(
196 (regionToFlush != null && regionToFlush.getMemstoreSize() > 0) ||
197 (bestRegionReplica != null && bestRegionReplica.getMemstoreSize() > 0));
198
199 if (regionToFlush == null ||
200 (bestRegionReplica != null &&
201 ServerRegionReplicaUtil.isRegionReplicaStoreFileRefreshEnabled(conf) &&
202 (bestRegionReplica.getMemstoreSize()
203 > secondaryMultiplier * regionToFlush.getMemstoreSize()))) {
204 LOG.info("Refreshing storefiles of region " + bestRegionReplica +
205 " due to global heap pressure. memstore size=" + StringUtils.humanReadableInt(
206 server.getRegionServerAccounting().getGlobalMemstoreSize()));
207 flushedOne = refreshStoreFilesAndReclaimMemory(bestRegionReplica);
208 if (!flushedOne) {
209 LOG.info("Excluding secondary region " + bestRegionReplica +
210 " - trying to find a different region to refresh files.");
211 excludedRegions.add(bestRegionReplica);
212 }
213 } else {
214 LOG.info("Flush of region " + regionToFlush + " due to global heap pressure. "
215 + "Total Memstore size="
216 + humanReadableInt(server.getRegionServerAccounting().getGlobalMemstoreSize())
217 + ", Region memstore size="
218 + humanReadableInt(regionToFlush.getMemstoreSize()));
219 flushedOne = flushRegion(regionToFlush, true, false);
220
221 if (!flushedOne) {
222 LOG.info("Excluding unflushable region " + regionToFlush +
223 " - trying to find a different region to flush.");
224 excludedRegions.add(regionToFlush);
225 }
226 }
227 }
228 return true;
229 }
230
231 private class FlushHandler extends HasThread {
232
233 private FlushHandler(String name) {
234 super(name);
235 }
236
237 @Override
238 public void run() {
239 while (!server.isStopped()) {
240 FlushQueueEntry fqe = null;
241 try {
242 wakeupPending.set(false);
243 fqe = flushQueue.poll(threadWakeFrequency, TimeUnit.MILLISECONDS);
244 if (fqe == null || fqe instanceof WakeupFlushThread) {
245 if (isAboveLowWaterMark()) {
246 LOG.debug("Flush thread woke up because memory above low water="
247 + TraditionalBinaryPrefix.long2String(globalMemStoreLimitLowMark, "", 1));
248 if (!flushOneForGlobalPressure()) {
249
250
251
252
253
254 Thread.sleep(1000);
255 wakeUpIfBlocking();
256 }
257
258 wakeupFlushThread();
259 }
260 continue;
261 }
262 FlushRegionEntry fre = (FlushRegionEntry) fqe;
263 if (!flushRegion(fre)) {
264 break;
265 }
266 } catch (InterruptedException ex) {
267 continue;
268 } catch (ConcurrentModificationException ex) {
269 continue;
270 } catch (Exception ex) {
271 LOG.error("Cache flusher failed for entry " + fqe, ex);
272 if (!server.checkFileSystem()) {
273 break;
274 }
275 }
276 }
277 synchronized (regionsInQueue) {
278 regionsInQueue.clear();
279 flushQueue.clear();
280 }
281
282
283 wakeUpIfBlocking();
284 LOG.info(getName() + " exiting");
285 }
286 }
287
288
289 private void wakeupFlushThread() {
290 if (wakeupPending.compareAndSet(false, true)) {
291 flushQueue.add(new WakeupFlushThread());
292 }
293 }
294
295 private Region getBiggestMemstoreRegion(
296 SortedMap<Long, Region> regionsBySize,
297 Set<Region> excludedRegions,
298 boolean checkStoreFileCount) {
299 synchronized (regionsInQueue) {
300 for (Region region : regionsBySize.values()) {
301 if (excludedRegions.contains(region)) {
302 continue;
303 }
304
305 if (((HRegion)region).writestate.flushing ||
306 !((HRegion)region).writestate.writesEnabled) {
307 continue;
308 }
309
310 if (checkStoreFileCount && isTooManyStoreFiles(region)) {
311 continue;
312 }
313 return region;
314 }
315 }
316 return null;
317 }
318
319 private Region getBiggestMemstoreOfRegionReplica(SortedMap<Long, Region> regionsBySize,
320 Set<Region> excludedRegions) {
321 synchronized (regionsInQueue) {
322 for (Region region : regionsBySize.values()) {
323 if (excludedRegions.contains(region)) {
324 continue;
325 }
326
327 if (RegionReplicaUtil.isDefaultReplica(region.getRegionInfo())) {
328 continue;
329 }
330
331 return region;
332 }
333 }
334 return null;
335 }
336
337 private boolean refreshStoreFilesAndReclaimMemory(Region region) {
338 try {
339 return region.refreshStoreFiles();
340 } catch (IOException e) {
341 LOG.warn("Refreshing store files failed with exception", e);
342 }
343 return false;
344 }
345
346
347
348
349 private boolean isAboveHighWaterMark() {
350 return server.getRegionServerAccounting().
351 getGlobalMemstoreSize() >= globalMemStoreLimit;
352 }
353
354
355
356
357 private boolean isAboveLowWaterMark() {
358 return server.getRegionServerAccounting().
359 getGlobalMemstoreSize() >= globalMemStoreLimitLowMark;
360 }
361
362 @Override
363 public void requestFlush(Region r, boolean forceFlushAllStores) {
364 synchronized (regionsInQueue) {
365 if (!regionsInQueue.containsKey(r)) {
366
367
368 FlushRegionEntry fqe = new FlushRegionEntry(r, forceFlushAllStores);
369 this.regionsInQueue.put(r, fqe);
370 this.flushQueue.add(fqe);
371 }
372 }
373 }
374
375 @Override
376 public void requestDelayedFlush(Region r, long delay, boolean forceFlushAllStores) {
377 synchronized (regionsInQueue) {
378 if (!regionsInQueue.containsKey(r)) {
379
380 FlushRegionEntry fqe = new FlushRegionEntry(r, forceFlushAllStores);
381 fqe.requeue(delay);
382 this.regionsInQueue.put(r, fqe);
383 this.flushQueue.add(fqe);
384 }
385 }
386 }
387
388 public int getFlushQueueSize() {
389 return flushQueue.size();
390 }
391
392
393
394
395 void interruptIfNecessary() {
396 lock.writeLock().lock();
397 try {
398 for (FlushHandler flushHander : flushHandlers) {
399 if (flushHander != null) flushHander.interrupt();
400 }
401 } finally {
402 lock.writeLock().unlock();
403 }
404 }
405
406 synchronized void start(UncaughtExceptionHandler eh) {
407 ThreadFactory flusherThreadFactory = Threads.newDaemonThreadFactory(
408 server.getServerName().toShortString() + "-MemStoreFlusher", eh);
409 for (int i = 0; i < flushHandlers.length; i++) {
410 flushHandlers[i] = new FlushHandler("MemStoreFlusher." + i);
411 flusherThreadFactory.newThread(flushHandlers[i]);
412 flushHandlers[i].start();
413 }
414 }
415
416 boolean isAlive() {
417 for (FlushHandler flushHander : flushHandlers) {
418 if (flushHander != null && flushHander.isAlive()) {
419 return true;
420 }
421 }
422 return false;
423 }
424
425 void join() {
426 for (FlushHandler flushHander : flushHandlers) {
427 if (flushHander != null) {
428 Threads.shutdown(flushHander.getThread());
429 }
430 }
431 }
432
433
434
435
436
437
438
439
440
441 private boolean flushRegion(final FlushRegionEntry fqe) {
442 Region region = fqe.region;
443 if (!region.getRegionInfo().isMetaRegion() &&
444 isTooManyStoreFiles(region)) {
445 if (fqe.isMaximumWait(this.blockingWaitTime)) {
446 LOG.info("Waited " + (EnvironmentEdgeManager.currentTime() - fqe.createTime) +
447 "ms on a compaction to clean up 'too many store files'; waited " +
448 "long enough... proceeding with flush of " +
449 region.getRegionInfo().getRegionNameAsString());
450 } else {
451
452 if (fqe.getRequeueCount() <= 0) {
453
454 LOG.warn("Region " + region.getRegionInfo().getRegionNameAsString() + " has too many " +
455 "store files; delaying flush up to " + this.blockingWaitTime + "ms");
456 if (!this.server.compactSplitThread.requestSplit(region)) {
457 try {
458 this.server.compactSplitThread.requestSystemCompaction(
459 region, Thread.currentThread().getName());
460 } catch (IOException e) {
461 LOG.error("Cache flush failed for region " +
462 Bytes.toStringBinary(region.getRegionInfo().getRegionName()),
463 RemoteExceptionHandler.checkIOException(e));
464 }
465 }
466 }
467
468
469
470 this.flushQueue.add(fqe.requeue(this.blockingWaitTime / 100));
471
472 return true;
473 }
474 }
475 return flushRegion(region, false, fqe.isForceFlushAllStores());
476 }
477
478
479
480
481
482
483
484
485
486
487
488
489
490 private boolean flushRegion(final Region region, final boolean emergencyFlush,
491 boolean forceFlushAllStores) {
492 synchronized (this.regionsInQueue) {
493 FlushRegionEntry fqe = this.regionsInQueue.remove(region);
494
495 if (fqe != null && emergencyFlush) {
496
497
498 flushQueue.remove(fqe);
499 }
500 }
501
502 lock.readLock().lock();
503 try {
504 notifyFlushRequest(region, emergencyFlush);
505 FlushResult flushResult = region.flush(forceFlushAllStores);
506 boolean shouldCompact = flushResult.isCompactionNeeded();
507
508 boolean shouldSplit = ((HRegion)region).checkSplit() != null;
509 if (shouldSplit) {
510 this.server.compactSplitThread.requestSplit(region);
511 } else if (shouldCompact) {
512 server.compactSplitThread.requestSystemCompaction(
513 region, Thread.currentThread().getName());
514 }
515 } catch (DroppedSnapshotException ex) {
516
517
518
519
520
521 server.abort("Replay of WAL required. Forcing server shutdown", ex);
522 return false;
523 } catch (IOException ex) {
524 LOG.error("Cache flush failed" + (region != null ? (" for region " +
525 Bytes.toStringBinary(region.getRegionInfo().getRegionName())) : ""),
526 RemoteExceptionHandler.checkIOException(ex));
527 if (!server.checkFileSystem()) {
528 return false;
529 }
530 } finally {
531 lock.readLock().unlock();
532 wakeUpIfBlocking();
533 }
534 return true;
535 }
536
537 private void notifyFlushRequest(Region region, boolean emergencyFlush) {
538 FlushType type = FlushType.NORMAL;
539 if (emergencyFlush) {
540 type = isAboveHighWaterMark() ? FlushType.ABOVE_HIGHER_MARK : FlushType.ABOVE_LOWER_MARK;
541 }
542 for (FlushRequestListener listener : flushRequestListeners) {
543 listener.flushRequested(type, region);
544 }
545 }
546
547 private void wakeUpIfBlocking() {
548 synchronized (blockSignal) {
549 blockSignal.notifyAll();
550 }
551 }
552
553 private boolean isTooManyStoreFiles(Region region) {
554
555
556 if (!region.getTableDesc().isCompactionEnabled()) {
557 return false;
558 }
559
560 for (Store store : region.getStores()) {
561 if (store.hasTooManyStoreFiles()) {
562 return true;
563 }
564 }
565 return false;
566 }
567
568
569
570
571
572
573
574 public void reclaimMemStoreMemory() {
575 TraceScope scope = Trace.startSpan("MemStoreFluser.reclaimMemStoreMemory");
576 if (isAboveHighWaterMark()) {
577 if (Trace.isTracing()) {
578 scope.getSpan().addTimelineAnnotation("Force Flush. We're above high water mark.");
579 }
580 long start = EnvironmentEdgeManager.currentTime();
581 synchronized (this.blockSignal) {
582 boolean blocked = false;
583 long startTime = 0;
584 boolean interrupted = false;
585 try {
586 while (isAboveHighWaterMark() && !server.isStopped()) {
587 if (!blocked) {
588 startTime = EnvironmentEdgeManager.currentTime();
589 LOG.info("Blocking updates on "
590 + server.toString()
591 + ": the global memstore size "
592 + TraditionalBinaryPrefix.long2String(server.getRegionServerAccounting()
593 .getGlobalMemstoreSize(), "", 1) + " is >= than blocking "
594 + TraditionalBinaryPrefix.long2String(globalMemStoreLimit, "", 1) + " size");
595 }
596 blocked = true;
597 wakeupFlushThread();
598 try {
599
600
601 blockSignal.wait(5 * 1000);
602 } catch (InterruptedException ie) {
603 LOG.warn("Interrupted while waiting");
604 interrupted = true;
605 }
606 long took = EnvironmentEdgeManager.currentTime() - start;
607 LOG.warn("Memstore is above high water mark and block " + took + "ms");
608 }
609 } finally {
610 if (interrupted) {
611 Thread.currentThread().interrupt();
612 }
613 }
614
615 if(blocked){
616 final long totalTime = EnvironmentEdgeManager.currentTime() - startTime;
617 if(totalTime > 0){
618 this.updatesBlockedMsHighWater.add(totalTime);
619 }
620 LOG.info("Unblocking updates for server " + server.toString());
621 }
622 }
623 } else if (isAboveLowWaterMark()) {
624 wakeupFlushThread();
625 }
626 scope.close();
627 }
628 @Override
629 public String toString() {
630 return "flush_queue="
631 + flushQueue.size();
632 }
633
634 public String dumpQueue() {
635 StringBuilder queueList = new StringBuilder();
636 queueList.append("Flush Queue Queue dump:\n");
637 queueList.append(" Flush Queue:\n");
638 java.util.Iterator<FlushQueueEntry> it = flushQueue.iterator();
639
640 while(it.hasNext()){
641 queueList.append(" "+it.next().toString());
642 queueList.append("\n");
643 }
644
645 return queueList.toString();
646 }
647
648
649
650
651
652 @Override
653 public void registerFlushRequestListener(final FlushRequestListener listener) {
654 this.flushRequestListeners.add(listener);
655 }
656
657
658
659
660
661
662 @Override
663 public boolean unregisterFlushRequestListener(final FlushRequestListener listener) {
664 return this.flushRequestListeners.remove(listener);
665 }
666
667
668
669
670
671 @Override
672 public void setGlobalMemstoreLimit(long globalMemStoreSize) {
673 this.globalMemStoreLimit = globalMemStoreSize;
674 this.globalMemStoreLimitLowMark =
675 (long) (this.globalMemStoreLimitLowMarkPercent * globalMemStoreSize);
676 reclaimMemStoreMemory();
677 }
678
679 public long getMemoryLimit() {
680 return this.globalMemStoreLimit;
681 }
682
683 interface FlushQueueEntry extends Delayed {
684 }
685
686
687
688
689 static class WakeupFlushThread implements FlushQueueEntry {
690 @Override
691 public long getDelay(TimeUnit unit) {
692 return 0;
693 }
694
695 @Override
696 public int compareTo(Delayed o) {
697 return -1;
698 }
699
700 @Override
701 public boolean equals(Object obj) {
702 return (this == obj);
703 }
704 }
705
706
707
708
709
710
711
712
713
714 static class FlushRegionEntry implements FlushQueueEntry {
715 private final Region region;
716
717 private final long createTime;
718 private long whenToExpire;
719 private int requeueCount = 0;
720
721 private boolean forceFlushAllStores;
722
723 FlushRegionEntry(final Region r, boolean forceFlushAllStores) {
724 this.region = r;
725 this.createTime = EnvironmentEdgeManager.currentTime();
726 this.whenToExpire = this.createTime;
727 this.forceFlushAllStores = forceFlushAllStores;
728 }
729
730
731
732
733
734 public boolean isMaximumWait(final long maximumWait) {
735 return (EnvironmentEdgeManager.currentTime() - this.createTime) > maximumWait;
736 }
737
738
739
740
741
742 public int getRequeueCount() {
743 return this.requeueCount;
744 }
745
746
747
748
749 public boolean isForceFlushAllStores() {
750 return forceFlushAllStores;
751 }
752
753
754
755
756
757
758
759 public FlushRegionEntry requeue(final long when) {
760 this.whenToExpire = EnvironmentEdgeManager.currentTime() + when;
761 this.requeueCount++;
762 return this;
763 }
764
765 @Override
766 public long getDelay(TimeUnit unit) {
767 return unit.convert(this.whenToExpire - EnvironmentEdgeManager.currentTime(),
768 TimeUnit.MILLISECONDS);
769 }
770
771 @Override
772 public int compareTo(Delayed other) {
773
774 int ret = Long.valueOf(getDelay(TimeUnit.MILLISECONDS) -
775 other.getDelay(TimeUnit.MILLISECONDS)).intValue();
776 if (ret != 0) {
777 return ret;
778 }
779 FlushQueueEntry otherEntry = (FlushQueueEntry) other;
780 return hashCode() - otherEntry.hashCode();
781 }
782
783 @Override
784 public String toString() {
785 return "[flush region "+Bytes.toStringBinary(region.getRegionInfo().getRegionName())+"]";
786 }
787
788 @Override
789 public int hashCode() {
790 int hash = (int) getDelay(TimeUnit.MILLISECONDS);
791 return hash ^ region.hashCode();
792 }
793
794 @Override
795 public boolean equals(Object obj) {
796 if (this == obj) {
797 return true;
798 }
799 if (obj == null || getClass() != obj.getClass()) {
800 return false;
801 }
802 Delayed other = (Delayed) obj;
803 return compareTo(other) == 0;
804 }
805 }
806 }