1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase.regionserver.wal;
19
20 import static org.apache.hadoop.hbase.wal.DefaultWALProvider.WAL_FILE_NAME_DELIMITER;
21
22 import java.io.FileNotFoundException;
23 import java.io.IOException;
24 import java.io.InterruptedIOException;
25 import java.io.OutputStream;
26 import java.lang.management.MemoryUsage;
27 import java.lang.reflect.InvocationTargetException;
28 import java.net.URLEncoder;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.Comparator;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.NavigableMap;
35 import java.util.Set;
36 import java.util.concurrent.BlockingQueue;
37 import java.util.concurrent.ConcurrentHashMap;
38 import java.util.concurrent.ConcurrentSkipListMap;
39 import java.util.concurrent.CopyOnWriteArrayList;
40 import java.util.concurrent.CountDownLatch;
41 import java.util.concurrent.ExecutionException;
42 import java.util.concurrent.ExecutorService;
43 import java.util.concurrent.Executors;
44 import java.util.concurrent.LinkedBlockingQueue;
45 import java.util.concurrent.TimeUnit;
46 import java.util.concurrent.atomic.AtomicBoolean;
47 import java.util.concurrent.atomic.AtomicInteger;
48 import java.util.concurrent.atomic.AtomicLong;
49 import java.util.concurrent.locks.ReentrantLock;
50
51 import com.lmax.disruptor.*;
52 import org.apache.commons.lang.mutable.MutableLong;
53 import org.apache.commons.logging.Log;
54 import org.apache.commons.logging.LogFactory;
55 import org.apache.hadoop.conf.Configuration;
56 import org.apache.hadoop.fs.FSDataOutputStream;
57 import org.apache.hadoop.fs.FileStatus;
58 import org.apache.hadoop.fs.FileSystem;
59 import org.apache.hadoop.fs.Path;
60 import org.apache.hadoop.fs.PathFilter;
61 import org.apache.hadoop.hbase.Cell;
62 import org.apache.hadoop.hbase.CellUtil;
63 import org.apache.hadoop.hbase.HBaseConfiguration;
64 import org.apache.hadoop.hbase.HConstants;
65 import org.apache.hadoop.hbase.HRegionInfo;
66 import org.apache.hadoop.hbase.HTableDescriptor;
67 import org.apache.hadoop.hbase.classification.InterfaceAudience;
68 import org.apache.hadoop.hbase.exceptions.TimeoutIOException;
69 import org.apache.hadoop.hbase.io.util.HeapMemorySizeUtil;
70 import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl;
71 import org.apache.hadoop.hbase.util.Bytes;
72 import org.apache.hadoop.hbase.util.ClassSize;
73 import org.apache.hadoop.hbase.util.DrainBarrier;
74 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
75 import org.apache.hadoop.hbase.util.FSUtils;
76 import org.apache.hadoop.hbase.util.HasThread;
77 import org.apache.hadoop.hbase.util.Threads;
78 import org.apache.hadoop.hbase.wal.DefaultWALProvider;
79 import org.apache.hadoop.hbase.wal.WAL;
80 import org.apache.hadoop.hbase.wal.WALFactory;
81 import org.apache.hadoop.hbase.wal.WALKey;
82 import org.apache.hadoop.hbase.wal.WALPrettyPrinter;
83 import org.apache.hadoop.hbase.wal.WALProvider.Writer;
84 import org.apache.hadoop.hbase.wal.WALSplitter;
85 import org.apache.hadoop.hdfs.DFSOutputStream;
86 import org.apache.hadoop.hdfs.client.HdfsDataOutputStream;
87 import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
88 import org.apache.hadoop.util.StringUtils;
89 import org.apache.htrace.NullScope;
90 import org.apache.htrace.Span;
91 import org.apache.htrace.Trace;
92 import org.apache.htrace.TraceScope;
93
94 import com.google.common.annotations.VisibleForTesting;
95 import com.lmax.disruptor.dsl.Disruptor;
96 import com.lmax.disruptor.dsl.ProducerType;
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125 @InterfaceAudience.Private
126 public class FSHLog implements WAL {
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161 private static final Log LOG = LogFactory.getLog(FSHLog.class);
162
163 private static final int DEFAULT_SLOW_SYNC_TIME_MS = 100;
164
165 private static final int DEFAULT_WAL_SYNC_TIMEOUT_MS = 5 * 60 * 1000;
166
167
168
169
170
171
172
173
174
175 private final Disruptor<RingBufferTruck> disruptor;
176
177
178
179
180 private final ExecutorService appendExecutor;
181
182
183
184
185
186
187
188 private final RingBufferEventHandler ringBufferEventHandler;
189
190
191
192
193
194
195
196 private final Map<Thread, SyncFuture> syncFuturesByHandler;
197
198
199
200
201
202 private volatile long highestUnsyncedSequence = -1;
203
204
205
206
207
208
209 private final AtomicLong highestSyncedSequence = new AtomicLong(0);
210
211
212
213
214 protected final FileSystem fs;
215
216
217
218
219 private final Path fullPathLogDir;
220
221
222
223
224 private final Path fullPathArchiveDir;
225
226
227
228
229 private final PathFilter ourFiles;
230
231
232
233
234 private final String logFilePrefix;
235
236
237
238
239 private final String logFileSuffix;
240
241
242
243
244 private final String prefixPathStr;
245
246 private final WALCoprocessorHost coprocessorHost;
247
248
249
250
251 protected final Configuration conf;
252
253
254 private final List<WALActionsListener> listeners =
255 new CopyOnWriteArrayList<WALActionsListener>();
256
257 @Override
258 public void registerWALActionsListener(final WALActionsListener listener) {
259 this.listeners.add(listener);
260 }
261
262 @Override
263 public boolean unregisterWALActionsListener(final WALActionsListener listener) {
264 return this.listeners.remove(listener);
265 }
266
267 @Override
268 public WALCoprocessorHost getCoprocessorHost() {
269 return coprocessorHost;
270 }
271
272
273
274
275 private FSDataOutputStream hdfs_out;
276
277
278
279
280 private final int minTolerableReplication;
281
282 private final int slowSyncNs;
283
284 private final long walSyncTimeout;
285
286
287
288
289
290 private final AtomicInteger consecutiveLogRolls = new AtomicInteger(0);
291
292 private final int lowReplicationRollLimit;
293
294
295
296
297 private volatile boolean lowReplicationRollEnabled = true;
298
299
300
301
302
303
304 private SequenceIdAccounting sequenceIdAccounting = new SequenceIdAccounting();
305
306
307
308
309 volatile Writer writer;
310
311
312 private final DrainBarrier closeBarrier = new DrainBarrier();
313
314
315
316
317
318
319
320
321 private final ReentrantLock rollWriterLock = new ReentrantLock(true);
322
323 private volatile boolean closed = false;
324 private final AtomicBoolean shutdown = new AtomicBoolean(false);
325
326
327 private final AtomicLong filenum = new AtomicLong(-1);
328
329
330 private final AtomicInteger numEntries = new AtomicInteger(0);
331
332
333 private final long logrollsize;
334
335
336
337
338 private AtomicLong totalLogSize = new AtomicLong(0);
339
340
341
342
343
344
345 private final int maxLogs;
346
347
348 private final int closeErrorsTolerated;
349
350 private final AtomicInteger closeErrorCount = new AtomicInteger();
351
352
353 private volatile long lastTimeCheckLowReplication = EnvironmentEdgeManager.currentTime();
354
355
356
357
358
359
360 final Comparator<Path> LOG_NAME_COMPARATOR = new Comparator<Path>() {
361 @Override
362 public int compare(Path o1, Path o2) {
363 long t1 = getFileNumFromFileName(o1);
364 long t2 = getFileNumFromFileName(o2);
365 if (t1 == t2) return 0;
366 return (t1 > t2) ? 1 : -1;
367 }
368 };
369
370
371
372
373
374 private NavigableMap<Path, Map<byte[], Long>> byWalRegionSequenceIds =
375 new ConcurrentSkipListMap<Path, Map<byte[], Long>>(LOG_NAME_COMPARATOR);
376
377
378
379
380
381 static class RingBufferExceptionHandler implements ExceptionHandler {
382 @Override
383 public void handleEventException(Throwable ex, long sequence, Object event) {
384 LOG.error("Sequence=" + sequence + ", event=" + event, ex);
385 throw new RuntimeException(ex);
386 }
387
388 @Override
389 public void handleOnStartException(Throwable ex) {
390 LOG.error(ex);
391 throw new RuntimeException(ex);
392 }
393
394 @Override
395 public void handleOnShutdownException(Throwable ex) {
396 LOG.error(ex);
397 throw new RuntimeException(ex);
398 }
399 }
400
401
402
403
404
405
406
407
408
409
410 public FSHLog(final FileSystem fs, final Path root, final String logDir, final Configuration conf)
411 throws IOException {
412 this(fs, root, logDir, HConstants.HREGION_OLDLOGDIR_NAME, conf, null, true, null, null);
413 }
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439 public FSHLog(final FileSystem fs, final Path rootDir, final String logDir,
440 final String archiveDir, final Configuration conf,
441 final List<WALActionsListener> listeners,
442 final boolean failIfWALExists, final String prefix, final String suffix)
443 throws IOException {
444 this.fs = fs;
445 this.fullPathLogDir = new Path(rootDir, logDir);
446 this.fullPathArchiveDir = new Path(rootDir, archiveDir);
447 this.conf = conf;
448
449 if (!fs.exists(fullPathLogDir) && !fs.mkdirs(fullPathLogDir)) {
450 throw new IOException("Unable to mkdir " + fullPathLogDir);
451 }
452
453 if (!fs.exists(this.fullPathArchiveDir)) {
454 if (!fs.mkdirs(this.fullPathArchiveDir)) {
455 throw new IOException("Unable to mkdir " + this.fullPathArchiveDir);
456 }
457 }
458
459
460 this.logFilePrefix =
461 prefix == null || prefix.isEmpty() ? "wal" : URLEncoder.encode(prefix, "UTF8");
462
463 if (suffix != null && !(suffix.isEmpty()) && !(suffix.startsWith(WAL_FILE_NAME_DELIMITER))) {
464 throw new IllegalArgumentException("WAL suffix must start with '" + WAL_FILE_NAME_DELIMITER +
465 "' but instead was '" + suffix + "'");
466 }
467
468
469 FSUtils.setStoragePolicy(fs, conf, this.fullPathLogDir, HConstants.WAL_STORAGE_POLICY,
470 HConstants.DEFAULT_WAL_STORAGE_POLICY);
471 this.logFileSuffix = (suffix == null) ? "" : URLEncoder.encode(suffix, "UTF8");
472 this.prefixPathStr = new Path(fullPathLogDir,
473 logFilePrefix + WAL_FILE_NAME_DELIMITER).toString();
474
475 this.ourFiles = new PathFilter() {
476 @Override
477 public boolean accept(final Path fileName) {
478
479 final String fileNameString = fileName.toString();
480 if (!fileNameString.startsWith(prefixPathStr)) {
481 return false;
482 }
483 if (logFileSuffix.isEmpty()) {
484
485 return org.apache.commons.lang.StringUtils.isNumeric(
486 fileNameString.substring(prefixPathStr.length()));
487 } else if (!fileNameString.endsWith(logFileSuffix)) {
488 return false;
489 }
490 return true;
491 }
492 };
493
494 if (failIfWALExists) {
495 final FileStatus[] walFiles = FSUtils.listStatus(fs, fullPathLogDir, ourFiles);
496 if (null != walFiles && 0 != walFiles.length) {
497 throw new IOException("Target WAL already exists within directory " + fullPathLogDir);
498 }
499 }
500
501
502 if (listeners != null) {
503 for (WALActionsListener i: listeners) {
504 registerWALActionsListener(i);
505 }
506 }
507 this.coprocessorHost = new WALCoprocessorHost(this, conf);
508
509
510
511 final long blocksize = this.conf.getLong("hbase.regionserver.hlog.blocksize",
512 FSUtils.getDefaultBlockSize(this.fs, this.fullPathLogDir));
513 this.logrollsize =
514 (long)(blocksize * conf.getFloat("hbase.regionserver.logroll.multiplier", 0.95f));
515
516 float memstoreRatio = conf.getFloat(HeapMemorySizeUtil.MEMSTORE_SIZE_KEY,
517 conf.getFloat(HeapMemorySizeUtil.MEMSTORE_SIZE_OLD_KEY,
518 HeapMemorySizeUtil.DEFAULT_MEMSTORE_SIZE));
519 boolean maxLogsDefined = conf.get("hbase.regionserver.maxlogs") != null;
520 if(maxLogsDefined){
521 LOG.warn("'hbase.regionserver.maxlogs' was deprecated.");
522 }
523 this.maxLogs = conf.getInt("hbase.regionserver.maxlogs",
524 Math.max(32, calculateMaxLogFiles(memstoreRatio, logrollsize)));
525 this.minTolerableReplication = conf.getInt("hbase.regionserver.hlog.tolerable.lowreplication",
526 FSUtils.getDefaultReplication(fs, this.fullPathLogDir));
527 this.lowReplicationRollLimit =
528 conf.getInt("hbase.regionserver.hlog.lowreplication.rolllimit", 5);
529 this.closeErrorsTolerated = conf.getInt("hbase.regionserver.logroll.errors.tolerated", 0);
530 int maxHandlersCount = conf.getInt(HConstants.REGION_SERVER_HANDLER_COUNT, 200);
531
532 LOG.info("WAL configuration: blocksize=" + StringUtils.byteDesc(blocksize) +
533 ", rollsize=" + StringUtils.byteDesc(this.logrollsize) +
534 ", prefix=" + this.logFilePrefix + ", suffix=" + logFileSuffix + ", logDir=" +
535 this.fullPathLogDir + ", archiveDir=" + this.fullPathArchiveDir);
536
537
538 rollWriter();
539
540 this.slowSyncNs =
541 1000000 * conf.getInt("hbase.regionserver.hlog.slowsync.ms",
542 DEFAULT_SLOW_SYNC_TIME_MS);
543 this.walSyncTimeout = conf.getLong("hbase.regionserver.hlog.sync.timeout",
544 DEFAULT_WAL_SYNC_TIMEOUT_MS);
545
546
547
548 String hostingThreadName = Thread.currentThread().getName();
549 this.appendExecutor = Executors.
550 newSingleThreadExecutor(Threads.getNamedThreadFactory(hostingThreadName + ".append"));
551
552
553
554
555 final int preallocatedEventCount =
556 this.conf.getInt("hbase.regionserver.wal.disruptor.event.count", 1024 * 16);
557
558
559 this.disruptor =
560 new Disruptor<RingBufferTruck>(RingBufferTruck.EVENT_FACTORY, preallocatedEventCount,
561 this.appendExecutor, ProducerType.MULTI, new BlockingWaitStrategy());
562
563
564 this.disruptor.getRingBuffer().next();
565 this.ringBufferEventHandler =
566 new RingBufferEventHandler(conf.getInt("hbase.regionserver.hlog.syncer.count", 5),
567 maxHandlersCount);
568 this.disruptor.handleExceptionsWith(new RingBufferExceptionHandler());
569 this.disruptor.handleEventsWith(new RingBufferEventHandler [] {this.ringBufferEventHandler});
570
571 this.syncFuturesByHandler = new ConcurrentHashMap<Thread, SyncFuture>(maxHandlersCount);
572
573 this.disruptor.start();
574 }
575
576 private int calculateMaxLogFiles(float memstoreSizeRatio, long logRollSize) {
577 long max = -1L;
578 final MemoryUsage usage = HeapMemorySizeUtil.safeGetHeapMemoryUsage();
579 if (usage != null) {
580 max = usage.getMax();
581 }
582 int maxLogs = Math.round(max * memstoreSizeRatio * 2 / logRollSize);
583 return maxLogs;
584 }
585
586
587
588
589
590 protected FileStatus[] getFiles() throws IOException {
591 return FSUtils.listStatus(fs, fullPathLogDir, ourFiles);
592 }
593
594
595
596
597
598
599
600
601
602 @VisibleForTesting
603 OutputStream getOutputStream() {
604 FSDataOutputStream fsdos = this.hdfs_out;
605 if (fsdos == null) return null;
606 return fsdos.getWrappedStream();
607 }
608
609 @Override
610 public byte [][] rollWriter() throws FailedLogCloseException, IOException {
611 return rollWriter(false);
612 }
613
614
615
616
617
618 private Path getNewPath() throws IOException {
619 this.filenum.set(System.currentTimeMillis());
620 Path newPath = getCurrentFileName();
621 while (fs.exists(newPath)) {
622 this.filenum.incrementAndGet();
623 newPath = getCurrentFileName();
624 }
625 return newPath;
626 }
627
628 Path getOldPath() {
629 long currentFilenum = this.filenum.get();
630 Path oldPath = null;
631 if (currentFilenum > 0) {
632
633 oldPath = computeFilename(currentFilenum);
634 }
635 return oldPath;
636 }
637
638
639
640
641
642 private void tellListenersAboutPreLogRoll(final Path oldPath, final Path newPath)
643 throws IOException {
644 coprocessorHost.preWALRoll(oldPath, newPath);
645
646 if (!this.listeners.isEmpty()) {
647 for (WALActionsListener i : this.listeners) {
648 i.preLogRoll(oldPath, newPath);
649 }
650 }
651 }
652
653
654
655
656
657 private void tellListenersAboutPostLogRoll(final Path oldPath, final Path newPath)
658 throws IOException {
659 if (!this.listeners.isEmpty()) {
660 for (WALActionsListener i : this.listeners) {
661 i.postLogRoll(oldPath, newPath);
662 }
663 }
664
665 coprocessorHost.postWALRoll(oldPath, newPath);
666 }
667
668
669
670
671
672
673 private void preemptiveSync(final ProtobufLogWriter nextWriter) {
674 long startTimeNanos = System.nanoTime();
675 try {
676 nextWriter.sync();
677 postSync(System.nanoTime() - startTimeNanos, 0);
678 } catch (IOException e) {
679
680 LOG.warn("pre-sync failed but an optimization so keep going", e);
681 }
682 }
683
684 @Override
685 public byte [][] rollWriter(boolean force) throws FailedLogCloseException, IOException {
686 rollWriterLock.lock();
687 try {
688
689 if (!force && (this.writer != null && this.numEntries.get() <= 0)) return null;
690 byte [][] regionsToFlush = null;
691 if (this.closed) {
692 LOG.debug("WAL closed. Skipping rolling of writer");
693 return regionsToFlush;
694 }
695 if (!closeBarrier.beginOp()) {
696 LOG.debug("WAL closing. Skipping rolling of writer");
697 return regionsToFlush;
698 }
699 TraceScope scope = Trace.startSpan("FSHLog.rollWriter");
700 try {
701 Path oldPath = getOldPath();
702 Path newPath = getNewPath();
703
704 Writer nextWriter = this.createWriterInstance(newPath);
705 FSDataOutputStream nextHdfsOut = null;
706 if (nextWriter instanceof ProtobufLogWriter) {
707 nextHdfsOut = ((ProtobufLogWriter)nextWriter).getStream();
708
709
710 preemptiveSync((ProtobufLogWriter)nextWriter);
711 }
712 tellListenersAboutPreLogRoll(oldPath, newPath);
713
714 newPath = replaceWriter(oldPath, newPath, nextWriter, nextHdfsOut);
715 tellListenersAboutPostLogRoll(oldPath, newPath);
716
717 if (getNumRolledLogFiles() > 0) {
718 cleanOldLogs();
719 regionsToFlush = findRegionsToForceFlush();
720 }
721 } finally {
722 closeBarrier.endOp();
723 assert scope == NullScope.INSTANCE || !scope.isDetached();
724 scope.close();
725 }
726 return regionsToFlush;
727 } finally {
728 rollWriterLock.unlock();
729 }
730 }
731
732
733
734
735
736
737
738 protected Writer createWriterInstance(final Path path) throws IOException {
739 return DefaultWALProvider.createWriter(conf, fs, path, false);
740 }
741
742
743
744
745
746 private void cleanOldLogs() throws IOException {
747 List<Path> logsToArchive = null;
748
749
750 for (Map.Entry<Path, Map<byte[], Long>> e : this.byWalRegionSequenceIds.entrySet()) {
751 Path log = e.getKey();
752 Map<byte[], Long> sequenceNums = e.getValue();
753 if (this.sequenceIdAccounting.areAllLower(sequenceNums)) {
754 if (logsToArchive == null) logsToArchive = new ArrayList<Path>();
755 logsToArchive.add(log);
756 if (LOG.isTraceEnabled()) LOG.trace("WAL file ready for archiving " + log);
757 }
758 }
759 if (logsToArchive != null) {
760 for (Path p : logsToArchive) {
761 this.totalLogSize.addAndGet(-this.fs.getFileStatus(p).getLen());
762 archiveLogFile(p);
763 this.byWalRegionSequenceIds.remove(p);
764 }
765 }
766 }
767
768
769
770
771
772
773
774
775 byte[][] findRegionsToForceFlush() throws IOException {
776 byte [][] regions = null;
777 int logCount = getNumRolledLogFiles();
778 if (logCount > this.maxLogs && logCount > 0) {
779 Map.Entry<Path, Map<byte[], Long>> firstWALEntry =
780 this.byWalRegionSequenceIds.firstEntry();
781 regions = this.sequenceIdAccounting.findLower(firstWALEntry.getValue());
782 }
783 if (regions != null) {
784 StringBuilder sb = new StringBuilder();
785 for (int i = 0; i < regions.length; i++) {
786 if (i > 0) sb.append(", ");
787 sb.append(Bytes.toStringBinary(regions[i]));
788 }
789 LOG.info("Too many WALs; count=" + logCount + ", max=" + this.maxLogs +
790 "; forcing flush of " + regions.length + " regions(s): " + sb.toString());
791 }
792 return regions;
793 }
794
795
796
797
798
799 @VisibleForTesting
800 protected void afterCreatingZigZagLatch() {}
801
802
803
804
805 @VisibleForTesting
806 protected void beforeWaitOnSafePoint() {};
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826 Path replaceWriter(final Path oldPath, final Path newPath, Writer nextWriter,
827 final FSDataOutputStream nextHdfsOut)
828 throws IOException {
829
830
831
832
833
834 SyncFuture syncFuture = null;
835 SafePointZigZagLatch zigzagLatch = null;
836 long sequence = -1L;
837 if (this.ringBufferEventHandler != null) {
838
839
840
841
842
843
844
845
846 sequence = getSequenceOnRingBuffer();
847 zigzagLatch = this.ringBufferEventHandler.attainSafePoint();
848 }
849 afterCreatingZigZagLatch();
850 TraceScope scope = Trace.startSpan("FSHFile.replaceWriter");
851 try {
852
853
854
855
856
857 try {
858 if (zigzagLatch != null) {
859
860
861 assert sequence > 0L : "Failed to get sequence from ring buffer";
862 Trace.addTimelineAnnotation("awaiting safepoint");
863 syncFuture = zigzagLatch.waitSafePoint(publishSyncOnRingBuffer(sequence));
864 }
865 } catch (FailedSyncBeforeLogCloseException e) {
866
867 if (isUnflushedEntries()) throw e;
868 LOG.warn("Failed sync-before-close but no outstanding appends; closing WAL: " +
869 e.getMessage());
870 }
871
872
873
874 try {
875 if (this.writer != null) {
876 Trace.addTimelineAnnotation("closing writer");
877 this.writer.close();
878 Trace.addTimelineAnnotation("writer closed");
879 }
880 this.closeErrorCount.set(0);
881 } catch (IOException ioe) {
882 int errors = closeErrorCount.incrementAndGet();
883 if (!isUnflushedEntries() && (errors <= this.closeErrorsTolerated)) {
884 LOG.warn("Riding over failed WAL close of " + oldPath + ", cause=\"" +
885 ioe.getMessage() + "\", errors=" + errors +
886 "; THIS FILE WAS NOT CLOSED BUT ALL EDITS SYNCED SO SHOULD BE OK");
887 } else {
888 throw ioe;
889 }
890 }
891 this.writer = nextWriter;
892 this.hdfs_out = nextHdfsOut;
893 int oldNumEntries = this.numEntries.get();
894 this.numEntries.set(0);
895 final String newPathString = (null == newPath ? null : FSUtils.getPath(newPath));
896 if (oldPath != null) {
897 this.byWalRegionSequenceIds.put(oldPath, this.sequenceIdAccounting.resetHighest());
898 long oldFileLen = this.fs.getFileStatus(oldPath).getLen();
899 this.totalLogSize.addAndGet(oldFileLen);
900 LOG.info("Rolled WAL " + FSUtils.getPath(oldPath) + " with entries=" + oldNumEntries +
901 ", filesize=" + StringUtils.byteDesc(oldFileLen) + "; new WAL " +
902 newPathString);
903 } else {
904 LOG.info("New WAL " + newPathString);
905 }
906 } catch (InterruptedException ie) {
907
908 Thread.currentThread().interrupt();
909 } catch (IOException e) {
910 long count = getUnflushedEntriesCount();
911 LOG.error("Failed close of WAL writer " + oldPath + ", unflushedEntries=" + count, e);
912 throw new FailedLogCloseException(oldPath + ", unflushedEntries=" + count, e);
913 } finally {
914 try {
915
916 if (zigzagLatch != null) {
917 zigzagLatch.releaseSafePoint();
918
919
920
921
922
923
924 if (syncFuture != null) {
925 try {
926 blockOnSync(syncFuture);
927 } catch (IOException ioe) {
928 if (LOG.isTraceEnabled()) LOG.trace("Stale sync exception", ioe);
929 }
930 }
931 }
932 } finally {
933 scope.close();
934 }
935 }
936 return newPath;
937 }
938
939 long getUnflushedEntriesCount() {
940 long highestSynced = this.highestSyncedSequence.get();
941 return highestSynced > this.highestUnsyncedSequence?
942 0: this.highestUnsyncedSequence - highestSynced;
943 }
944
945 boolean isUnflushedEntries() {
946 return getUnflushedEntriesCount() > 0;
947 }
948
949
950
951
952
953 public static Path getWALArchivePath(Path archiveDir, Path p) {
954 return new Path(archiveDir, p.getName());
955 }
956
957 private void archiveLogFile(final Path p) throws IOException {
958 Path newPath = getWALArchivePath(this.fullPathArchiveDir, p);
959
960 if (!this.listeners.isEmpty()) {
961 for (WALActionsListener i : this.listeners) {
962 i.preLogArchive(p, newPath);
963 }
964 }
965 LOG.info("Archiving " + p + " to " + newPath);
966 if (!FSUtils.renameAndSetModifyTime(this.fs, p, newPath)) {
967 throw new IOException("Unable to rename " + p + " to " + newPath);
968 }
969
970 if (!this.listeners.isEmpty()) {
971 for (WALActionsListener i : this.listeners) {
972 i.postLogArchive(p, newPath);
973 }
974 }
975 }
976
977
978
979
980
981
982
983 protected Path computeFilename(final long filenum) {
984 if (filenum < 0) {
985 throw new RuntimeException("WAL file number can't be < 0");
986 }
987 String child = logFilePrefix + WAL_FILE_NAME_DELIMITER + filenum + logFileSuffix;
988 return new Path(fullPathLogDir, child);
989 }
990
991
992
993
994
995
996 public Path getCurrentFileName() {
997 return computeFilename(this.filenum.get());
998 }
999
1000
1001
1002
1003 public long getFilenum() {
1004 return filenum.get();
1005 }
1006
1007 @Override
1008 public String toString() {
1009 return "FSHLog " + logFilePrefix + ":" + logFileSuffix + "(num " + filenum + ")";
1010 }
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020 protected long getFileNumFromFileName(Path fileName) {
1021 if (fileName == null) throw new IllegalArgumentException("file name can't be null");
1022 if (!ourFiles.accept(fileName)) {
1023 throw new IllegalArgumentException("The log file " + fileName +
1024 " doesn't belong to this WAL. (" + toString() + ")");
1025 }
1026 final String fileNameString = fileName.toString();
1027 String chompedPath = fileNameString.substring(prefixPathStr.length(),
1028 (fileNameString.length() - logFileSuffix.length()));
1029 return Long.parseLong(chompedPath);
1030 }
1031
1032 @Override
1033 public void close() throws IOException {
1034 shutdown();
1035 final FileStatus[] files = getFiles();
1036 if (null != files && 0 != files.length) {
1037 for (FileStatus file : files) {
1038 Path p = getWALArchivePath(this.fullPathArchiveDir, file.getPath());
1039
1040 if (!this.listeners.isEmpty()) {
1041 for (WALActionsListener i : this.listeners) {
1042 i.preLogArchive(file.getPath(), p);
1043 }
1044 }
1045
1046 if (!FSUtils.renameAndSetModifyTime(fs, file.getPath(), p)) {
1047 throw new IOException("Unable to rename " + file.getPath() + " to " + p);
1048 }
1049
1050 if (!this.listeners.isEmpty()) {
1051 for (WALActionsListener i : this.listeners) {
1052 i.postLogArchive(file.getPath(), p);
1053 }
1054 }
1055 }
1056 LOG.debug("Moved " + files.length + " WAL file(s) to " +
1057 FSUtils.getPath(this.fullPathArchiveDir));
1058 }
1059 LOG.info("Closed WAL: " + toString());
1060 }
1061
1062 @Override
1063 public void shutdown() throws IOException {
1064 if (shutdown.compareAndSet(false, true)) {
1065 try {
1066
1067 closeBarrier.stopAndDrainOps();
1068 } catch (InterruptedException e) {
1069 LOG.error("Exception while waiting for cache flushes and log rolls", e);
1070 Thread.currentThread().interrupt();
1071 }
1072
1073
1074
1075
1076 if (this.disruptor != null) {
1077 long timeoutms = conf.getLong("hbase.wal.disruptor.shutdown.timeout.ms", 60000);
1078 try {
1079 this.disruptor.shutdown(timeoutms, TimeUnit.MILLISECONDS);
1080 } catch (TimeoutException e) {
1081 LOG.warn("Timed out bringing down disruptor after " + timeoutms + "ms; forcing halt " +
1082 "(It is a problem if this is NOT an ABORT! -- DATALOSS!!!!)");
1083 this.disruptor.halt();
1084 this.disruptor.shutdown();
1085 }
1086 }
1087
1088 if (this.appendExecutor != null) this.appendExecutor.shutdown();
1089
1090
1091 if (!this.listeners.isEmpty()) {
1092 for (WALActionsListener i : this.listeners) {
1093 i.logCloseRequested();
1094 }
1095 }
1096 this.closed = true;
1097 if (LOG.isDebugEnabled()) {
1098 LOG.debug("Closing WAL writer in " + FSUtils.getPath(fullPathLogDir));
1099 }
1100 if (this.writer != null) {
1101 this.writer.close();
1102 this.writer = null;
1103 }
1104 }
1105 }
1106
1107 @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NP_NULL_ON_SOME_PATH_EXCEPTION",
1108 justification="Will never be null")
1109 @Override
1110 public long append(final HTableDescriptor htd, final HRegionInfo hri, final WALKey key,
1111 final WALEdit edits, final boolean inMemstore) throws IOException {
1112 if (this.closed) throw new IOException("Cannot append; log is closed");
1113
1114
1115 TraceScope scope = Trace.startSpan("FSHLog.append");
1116 final MutableLong txidHolder = new MutableLong();
1117 final RingBuffer<RingBufferTruck> ringBuffer = disruptor.getRingBuffer();
1118 MultiVersionConcurrencyControl.WriteEntry we = key.getMvcc().begin(new Runnable() {
1119 @Override public void run() {
1120 txidHolder.setValue(ringBuffer.next());
1121 }
1122 });
1123 long txid = txidHolder.longValue();
1124 try {
1125 FSWALEntry entry = new FSWALEntry(txid, key, edits, htd, hri, inMemstore);
1126 entry.stampRegionSequenceId(we);
1127 ringBuffer.get(txid).loadPayload(entry, scope.detach());
1128 } finally {
1129 ringBuffer.publish(txid);
1130 }
1131 return txid;
1132 }
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149 private class SyncRunner extends HasThread {
1150 private volatile long sequence;
1151
1152 private final BlockingQueue<SyncFuture> syncFutures;
1153 private volatile SyncFuture takeSyncFuture = null;
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165 SyncRunner(final String name, final int maxHandlersCount) {
1166 super(name);
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180 this.syncFutures = new LinkedBlockingQueue<SyncFuture>(maxHandlersCount * 3);
1181 }
1182
1183 void offer(final long sequence, final SyncFuture [] syncFutures, final int syncFutureCount) {
1184
1185 this.sequence = sequence;
1186 for (int i = 0; i < syncFutureCount; ++i) {
1187 this.syncFutures.add(syncFutures[i]);
1188 }
1189 }
1190
1191
1192
1193
1194
1195
1196
1197
1198 private int releaseSyncFuture(final SyncFuture syncFuture, final long currentSequence,
1199 final Throwable t) {
1200 if (!syncFuture.done(currentSequence, t)) throw new IllegalStateException();
1201
1202 return 1;
1203 }
1204
1205
1206
1207
1208
1209
1210
1211 private int releaseSyncFutures(final long currentSequence, final Throwable t) {
1212 int syncCount = 0;
1213 for (SyncFuture syncFuture; (syncFuture = this.syncFutures.peek()) != null;) {
1214 if (syncFuture.getRingBufferSequence() > currentSequence) break;
1215 releaseSyncFuture(syncFuture, currentSequence, t);
1216 if (!this.syncFutures.remove(syncFuture)) {
1217 throw new IllegalStateException(syncFuture.toString());
1218 }
1219 syncCount++;
1220 }
1221 return syncCount;
1222 }
1223
1224
1225
1226
1227
1228 private long updateHighestSyncedSequence(long sequence) {
1229 long currentHighestSyncedSequence;
1230
1231 do {
1232 currentHighestSyncedSequence = highestSyncedSequence.get();
1233 if (currentHighestSyncedSequence >= sequence) {
1234
1235
1236 sequence = currentHighestSyncedSequence;
1237 break;
1238 }
1239 } while (!highestSyncedSequence.compareAndSet(currentHighestSyncedSequence, sequence));
1240 return sequence;
1241 }
1242
1243 boolean areSyncFuturesReleased() {
1244
1245
1246 return syncFutures.size() <= 0
1247 && takeSyncFuture == null;
1248 }
1249
1250 @Override
1251 public void run() {
1252 long currentSequence;
1253 while (!isInterrupted()) {
1254 int syncCount = 0;
1255
1256 try {
1257 while (true) {
1258 takeSyncFuture = null;
1259
1260 takeSyncFuture = this.syncFutures.take();
1261 currentSequence = this.sequence;
1262 long syncFutureSequence = takeSyncFuture.getRingBufferSequence();
1263 if (syncFutureSequence > currentSequence) {
1264 throw new IllegalStateException("currentSequence=" + currentSequence +
1265 ", syncFutureSequence=" + syncFutureSequence);
1266 }
1267
1268 long currentHighestSyncedSequence = highestSyncedSequence.get();
1269 if (currentSequence < currentHighestSyncedSequence) {
1270 syncCount += releaseSyncFuture(takeSyncFuture, currentHighestSyncedSequence, null);
1271
1272 continue;
1273 }
1274 break;
1275 }
1276
1277
1278 TraceScope scope = Trace.continueSpan(takeSyncFuture.getSpan());
1279 long start = System.nanoTime();
1280 Throwable lastException = null;
1281 try {
1282 Trace.addTimelineAnnotation("syncing writer");
1283 writer.sync();
1284 Trace.addTimelineAnnotation("writer synced");
1285 currentSequence = updateHighestSyncedSequence(currentSequence);
1286 } catch (IOException e) {
1287 LOG.error("Error syncing, request close of WAL", e);
1288 lastException = e;
1289 } catch (Exception e) {
1290 LOG.warn("UNEXPECTED", e);
1291 lastException = e;
1292 } finally {
1293
1294 takeSyncFuture.setSpan(scope.detach());
1295
1296 syncCount += releaseSyncFuture(takeSyncFuture, currentSequence, lastException);
1297
1298 syncCount += releaseSyncFutures(currentSequence, lastException);
1299 if (lastException != null) requestLogRoll();
1300 else checkLogRoll();
1301 }
1302 postSync(System.nanoTime() - start, syncCount);
1303 } catch (InterruptedException e) {
1304
1305 Thread.currentThread().interrupt();
1306 } catch (Throwable t) {
1307 LOG.warn("UNEXPECTED, continuing", t);
1308 }
1309 }
1310 }
1311 }
1312
1313
1314
1315
1316 public void checkLogRoll() {
1317
1318 if (!rollWriterLock.tryLock()) return;
1319 boolean lowReplication;
1320 try {
1321 lowReplication = checkLowReplication();
1322 } finally {
1323 rollWriterLock.unlock();
1324 }
1325 try {
1326 if (lowReplication || (writer != null && writer.getLength() > logrollsize)) {
1327 requestLogRoll(lowReplication);
1328 }
1329 } catch (IOException e) {
1330 LOG.warn("Writer.getLength() failed; continuing", e);
1331 }
1332 }
1333
1334
1335
1336
1337 private boolean checkLowReplication() {
1338 boolean logRollNeeded = false;
1339 this.lastTimeCheckLowReplication = EnvironmentEdgeManager.currentTime();
1340
1341
1342 try {
1343 int numCurrentReplicas = getLogReplication();
1344 if (numCurrentReplicas != 0 && numCurrentReplicas < this.minTolerableReplication) {
1345 if (this.lowReplicationRollEnabled) {
1346 if (this.consecutiveLogRolls.get() < this.lowReplicationRollLimit) {
1347 LOG.warn("HDFS pipeline error detected. " + "Found "
1348 + numCurrentReplicas + " replicas but expecting no less than "
1349 + this.minTolerableReplication + " replicas. "
1350 + " Requesting close of WAL. current pipeline: "
1351 + Arrays.toString(getPipeLine()));
1352 logRollNeeded = true;
1353
1354
1355
1356 this.consecutiveLogRolls.getAndIncrement();
1357 } else {
1358 LOG.warn("Too many consecutive RollWriter requests, it's a sign of "
1359 + "the total number of live datanodes is lower than the tolerable replicas.");
1360 this.consecutiveLogRolls.set(0);
1361 this.lowReplicationRollEnabled = false;
1362 }
1363 }
1364 } else if (numCurrentReplicas >= this.minTolerableReplication) {
1365 if (!this.lowReplicationRollEnabled) {
1366
1367
1368
1369 if (this.numEntries.get() <= 1) {
1370 return logRollNeeded;
1371 }
1372
1373
1374 this.lowReplicationRollEnabled = true;
1375 LOG.info("LowReplication-Roller was enabled.");
1376 }
1377 }
1378 } catch (Exception e) {
1379 LOG.warn("DFSOutputStream.getNumCurrentReplicas failed because of " + e +
1380 ", continuing...");
1381 }
1382 return logRollNeeded;
1383 }
1384
1385 private SyncFuture publishSyncOnRingBuffer(long sequence) {
1386 return publishSyncOnRingBuffer(sequence, null);
1387 }
1388
1389 private long getSequenceOnRingBuffer() {
1390 return this.disruptor.getRingBuffer().next();
1391 }
1392
1393 private SyncFuture publishSyncOnRingBuffer(Span span) {
1394 long sequence = this.disruptor.getRingBuffer().next();
1395 return publishSyncOnRingBuffer(sequence, span);
1396 }
1397
1398 private SyncFuture publishSyncOnRingBuffer(long sequence, Span span) {
1399 SyncFuture syncFuture = getSyncFuture(sequence, span);
1400 try {
1401 RingBufferTruck truck = this.disruptor.getRingBuffer().get(sequence);
1402 truck.loadPayload(syncFuture);
1403 } finally {
1404 this.disruptor.getRingBuffer().publish(sequence);
1405 }
1406 return syncFuture;
1407 }
1408
1409
1410 private Span publishSyncThenBlockOnCompletion(Span span) throws IOException {
1411 return blockOnSync(publishSyncOnRingBuffer(span));
1412 }
1413
1414 private Span blockOnSync(final SyncFuture syncFuture) throws IOException {
1415
1416 try {
1417 syncFuture.get(walSyncTimeout);
1418 return syncFuture.getSpan();
1419 } catch (TimeoutIOException tioe) {
1420
1421
1422
1423 this.syncFuturesByHandler.remove(Thread.currentThread());
1424 throw tioe;
1425 } catch (InterruptedException ie) {
1426 LOG.warn("Interrupted", ie);
1427 throw convertInterruptedExceptionToIOException(ie);
1428 } catch (ExecutionException e) {
1429 throw ensureIOException(e.getCause());
1430 }
1431 }
1432
1433 private IOException convertInterruptedExceptionToIOException(final InterruptedException ie) {
1434 Thread.currentThread().interrupt();
1435 IOException ioe = new InterruptedIOException();
1436 ioe.initCause(ie);
1437 return ioe;
1438 }
1439
1440 private SyncFuture getSyncFuture(final long sequence, Span span) {
1441 SyncFuture syncFuture = this.syncFuturesByHandler.get(Thread.currentThread());
1442 if (syncFuture == null) {
1443 syncFuture = new SyncFuture();
1444 this.syncFuturesByHandler.put(Thread.currentThread(), syncFuture);
1445 }
1446 return syncFuture.reset(sequence, span);
1447 }
1448
1449 private void postSync(final long timeInNanos, final int handlerSyncs) {
1450 if (timeInNanos > this.slowSyncNs) {
1451 String msg =
1452 new StringBuilder().append("Slow sync cost: ")
1453 .append(timeInNanos / 1000000).append(" ms, current pipeline: ")
1454 .append(Arrays.toString(getPipeLine())).toString();
1455 Trace.addTimelineAnnotation(msg);
1456 LOG.info(msg);
1457 }
1458 if (!listeners.isEmpty()) {
1459 for (WALActionsListener listener : listeners) {
1460 listener.postSync(timeInNanos, handlerSyncs);
1461 }
1462 }
1463 }
1464
1465 private long postAppend(final Entry e, final long elapsedTime) throws IOException {
1466 long len = 0;
1467 if (!listeners.isEmpty()) {
1468 for (Cell cell : e.getEdit().getCells()) {
1469 len += CellUtil.estimatedSerializedSizeOf(cell);
1470 }
1471 for (WALActionsListener listener : listeners) {
1472 listener.postAppend(len, elapsedTime, e.getKey(), e.getEdit());
1473 }
1474 }
1475 return len;
1476 }
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491 @VisibleForTesting
1492 int getLogReplication() {
1493 try {
1494
1495 if (this.hdfs_out instanceof HdfsDataOutputStream) {
1496 return ((HdfsDataOutputStream) this.hdfs_out).getCurrentBlockReplication();
1497 }
1498 } catch (IOException e) {
1499 LOG.info("", e);
1500 }
1501 return 0;
1502 }
1503
1504 @Override
1505 public void sync() throws IOException {
1506 TraceScope scope = Trace.startSpan("FSHLog.sync");
1507 try {
1508 scope = Trace.continueSpan(publishSyncThenBlockOnCompletion(scope.detach()));
1509 } finally {
1510 assert scope == NullScope.INSTANCE || !scope.isDetached();
1511 scope.close();
1512 }
1513 }
1514
1515 @Override
1516 public void sync(long txid) throws IOException {
1517 if (this.highestSyncedSequence.get() >= txid){
1518
1519 return;
1520 }
1521 TraceScope scope = Trace.startSpan("FSHLog.sync");
1522 try {
1523 scope = Trace.continueSpan(publishSyncThenBlockOnCompletion(scope.detach()));
1524 } finally {
1525 assert scope == NullScope.INSTANCE || !scope.isDetached();
1526 scope.close();
1527 }
1528 }
1529
1530
1531 public void requestLogRoll() {
1532 requestLogRoll(false);
1533 }
1534
1535 private void requestLogRoll(boolean tooFewReplicas) {
1536 if (!this.listeners.isEmpty()) {
1537 for (WALActionsListener i: this.listeners) {
1538 i.logRollRequested(tooFewReplicas);
1539 }
1540 }
1541 }
1542
1543
1544
1545 public int getNumRolledLogFiles() {
1546 return byWalRegionSequenceIds.size();
1547 }
1548
1549
1550
1551 public int getNumLogFiles() {
1552
1553 return getNumRolledLogFiles() + 1;
1554 }
1555
1556
1557
1558 public long getLogFileSize() {
1559 return this.totalLogSize.get();
1560 }
1561
1562 @Override
1563 public Long startCacheFlush(final byte[] encodedRegionName, Set<byte[]> families) {
1564 if (!closeBarrier.beginOp()) {
1565 LOG.info("Flush not started for " + Bytes.toString(encodedRegionName) + "; server closing.");
1566 return null;
1567 }
1568 return this.sequenceIdAccounting.startCacheFlush(encodedRegionName, families);
1569 }
1570
1571 @Override
1572 public void completeCacheFlush(final byte [] encodedRegionName) {
1573 this.sequenceIdAccounting.completeCacheFlush(encodedRegionName);
1574 closeBarrier.endOp();
1575 }
1576
1577 @Override
1578 public void abortCacheFlush(byte[] encodedRegionName) {
1579 this.sequenceIdAccounting.abortCacheFlush(encodedRegionName);
1580 closeBarrier.endOp();
1581 }
1582
1583 @VisibleForTesting
1584 boolean isLowReplicationRollEnabled() {
1585 return lowReplicationRollEnabled;
1586 }
1587
1588 public static final long FIXED_OVERHEAD = ClassSize.align(
1589 ClassSize.OBJECT + (5 * ClassSize.REFERENCE) +
1590 ClassSize.ATOMIC_INTEGER + Bytes.SIZEOF_INT + (3 * Bytes.SIZEOF_LONG));
1591
1592
1593 private static void split(final Configuration conf, final Path p) throws IOException {
1594 FileSystem fs = FSUtils.getWALFileSystem(conf);
1595 if (!fs.exists(p)) {
1596 throw new FileNotFoundException(p.toString());
1597 }
1598 if (!fs.getFileStatus(p).isDirectory()) {
1599 throw new IOException(p + " is not a directory");
1600 }
1601
1602 final Path baseDir = FSUtils.getWALRootDir(conf);
1603 final Path archiveDir = new Path(baseDir, HConstants.HREGION_OLDLOGDIR_NAME);
1604 WALSplitter.split(baseDir, p, archiveDir, fs, conf, WALFactory.getInstance(conf));
1605 }
1606
1607
1608 @Override
1609 public long getEarliestMemstoreSeqNum(byte[] encodedRegionName) {
1610
1611 return this.sequenceIdAccounting.getLowestSequenceId(encodedRegionName);
1612 }
1613
1614 @Override
1615 public long getEarliestMemstoreSeqNum(byte[] encodedRegionName, byte[] familyName) {
1616
1617
1618
1619
1620
1621
1622
1623
1624 return this.sequenceIdAccounting.getLowestSequenceId(encodedRegionName, familyName);
1625 }
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653 static class SafePointZigZagLatch {
1654
1655
1656
1657 private volatile CountDownLatch safePointAttainedLatch = new CountDownLatch(1);
1658
1659
1660
1661 private volatile CountDownLatch safePointReleasedLatch = new CountDownLatch(1);
1662
1663 private void checkIfSyncFailed(SyncFuture syncFuture) throws FailedSyncBeforeLogCloseException {
1664 if (syncFuture.isThrowable()) {
1665 throw new FailedSyncBeforeLogCloseException(syncFuture.getThrowable());
1666 }
1667 }
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679 SyncFuture waitSafePoint(SyncFuture syncFuture) throws InterruptedException,
1680 FailedSyncBeforeLogCloseException {
1681 while (!this.safePointAttainedLatch.await(1, TimeUnit.MILLISECONDS)) {
1682 checkIfSyncFailed(syncFuture);
1683 }
1684 checkIfSyncFailed(syncFuture);
1685 return syncFuture;
1686 }
1687
1688
1689
1690
1691
1692
1693
1694 void safePointAttained() throws InterruptedException {
1695 this.safePointAttainedLatch.countDown();
1696 this.safePointReleasedLatch.await();
1697 }
1698
1699
1700
1701
1702
1703 void releaseSafePoint() {
1704 this.safePointReleasedLatch.countDown();
1705 }
1706
1707
1708
1709
1710 boolean isCocked() {
1711 return this.safePointAttainedLatch.getCount() > 0 &&
1712 this.safePointReleasedLatch.getCount() > 0;
1713 }
1714 }
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739 class RingBufferEventHandler implements EventHandler<RingBufferTruck>, LifecycleAware {
1740 private final SyncRunner [] syncRunners;
1741 private final SyncFuture [] syncFutures;
1742
1743
1744 private volatile int syncFuturesCount = 0;
1745 private volatile SafePointZigZagLatch zigzagLatch;
1746
1747
1748
1749
1750 private Exception exception = null;
1751
1752
1753
1754 private final Object safePointWaiter = new Object();
1755 private volatile boolean shutdown = false;
1756
1757
1758
1759
1760 private int syncRunnerIndex;
1761
1762 RingBufferEventHandler(final int syncRunnerCount, final int maxHandlersCount) {
1763 this.syncFutures = new SyncFuture[maxHandlersCount];
1764 this.syncRunners = new SyncRunner[syncRunnerCount];
1765 for (int i = 0; i < syncRunnerCount; i++) {
1766 this.syncRunners[i] = new SyncRunner("sync." + i, maxHandlersCount);
1767 }
1768 }
1769
1770 private void cleanupOutstandingSyncsOnException(final long sequence, final Exception e) {
1771
1772 for (int i = 0; i < this.syncFuturesCount; i++) this.syncFutures[i].done(sequence, e);
1773 this.syncFuturesCount = 0;
1774 }
1775
1776
1777
1778
1779 private boolean isOutstandingSyncs() {
1780
1781 for (int i = 0; i < this.syncFuturesCount; i++) {
1782 if (!this.syncFutures[i].isDone()) return true;
1783 }
1784
1785 return false;
1786 }
1787
1788 private boolean isOutstandingSyncsFromRunners() {
1789
1790 for (SyncRunner syncRunner: syncRunners) {
1791 if(syncRunner.isAlive() && !syncRunner.areSyncFuturesReleased()) {
1792 return true;
1793 }
1794 }
1795 return false;
1796 }
1797
1798 @Override
1799
1800 public void onEvent(final RingBufferTruck truck, final long sequence, boolean endOfBatch)
1801 throws Exception {
1802
1803
1804
1805
1806
1807
1808
1809
1810 try {
1811 if (truck.hasSyncFuturePayload()) {
1812 this.syncFutures[this.syncFuturesCount++] = truck.unloadSyncFuturePayload();
1813
1814 if (this.syncFuturesCount == this.syncFutures.length) endOfBatch = true;
1815 } else if (truck.hasFSWALEntryPayload()) {
1816 TraceScope scope = Trace.continueSpan(truck.unloadSpanPayload());
1817 try {
1818 FSWALEntry entry = truck.unloadFSWALEntryPayload();
1819 if (this.exception != null) {
1820
1821 return;
1822 }
1823 append(entry);
1824 } catch (Exception e) {
1825
1826 this.exception = e;
1827
1828
1829
1830 cleanupOutstandingSyncsOnException(sequence,
1831 this.exception instanceof DamagedWALException ? this.exception
1832 : new DamagedWALException("On sync", this.exception));
1833
1834 return;
1835 } finally {
1836 assert scope == NullScope.INSTANCE || !scope.isDetached();
1837 scope.close();
1838 }
1839 } else {
1840
1841 cleanupOutstandingSyncsOnException(sequence,
1842 new IllegalStateException("Neither append nor sync"));
1843
1844 return;
1845 }
1846
1847
1848
1849 if (this.exception == null) {
1850
1851
1852 if (!endOfBatch || this.syncFuturesCount <= 0) return;
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862 this.syncRunnerIndex = (this.syncRunnerIndex + 1) % this.syncRunners.length;
1863 try {
1864
1865
1866 this.syncRunners[this.syncRunnerIndex].offer(sequence, this.syncFutures,
1867 this.syncFuturesCount);
1868 } catch (Exception e) {
1869
1870 requestLogRoll();
1871 this.exception = new DamagedWALException("Failed offering sync", e);
1872 }
1873 }
1874
1875 if (this.exception != null) {
1876 cleanupOutstandingSyncsOnException(sequence,
1877 this.exception instanceof DamagedWALException?
1878 this.exception:
1879 new DamagedWALException("On sync", this.exception));
1880 }
1881 attainSafePoint(sequence);
1882 this.syncFuturesCount = 0;
1883 } catch (Throwable t) {
1884 LOG.error("UNEXPECTED!!! syncFutures.length=" + this.syncFutures.length, t);
1885 }
1886 }
1887
1888 SafePointZigZagLatch attainSafePoint() {
1889 this.zigzagLatch = new SafePointZigZagLatch();
1890 return this.zigzagLatch;
1891 }
1892
1893
1894
1895
1896
1897 private void attainSafePoint(final long currentSequence) {
1898 if (this.zigzagLatch == null || !this.zigzagLatch.isCocked()) return;
1899
1900 beforeWaitOnSafePoint();
1901 try {
1902
1903
1904
1905 while ((!this.shutdown && this.zigzagLatch.isCocked()
1906 && highestSyncedSequence.get() < currentSequence &&
1907
1908
1909 isOutstandingSyncs())
1910
1911 || isOutstandingSyncsFromRunners()) {
1912 synchronized (this.safePointWaiter) {
1913 this.safePointWaiter.wait(0, 1);
1914 }
1915 }
1916
1917
1918
1919 this.exception = null;
1920 this.zigzagLatch.safePointAttained();
1921 } catch (InterruptedException e) {
1922 LOG.warn("Interrupted ", e);
1923 Thread.currentThread().interrupt();
1924 }
1925 }
1926
1927
1928
1929
1930
1931
1932 void append(final FSWALEntry entry) throws Exception {
1933
1934 atHeadOfRingBufferEventHandlerAppend();
1935
1936 long start = EnvironmentEdgeManager.currentTime();
1937 byte [] encodedRegionName = entry.getKey().getEncodedRegionName();
1938 long regionSequenceId = WALKey.NO_SEQUENCE_ID;
1939 try {
1940
1941 regionSequenceId = entry.getKey().getSequenceId();
1942
1943
1944
1945 if (entry.getEdit().isEmpty()) {
1946 return;
1947 }
1948
1949
1950 if (!coprocessorHost.preWALWrite(entry.getHRegionInfo(), entry.getKey(),
1951 entry.getEdit())) {
1952 if (entry.getEdit().isReplay()) {
1953
1954 entry.getKey().setScopes(null);
1955 }
1956 }
1957 if (!listeners.isEmpty()) {
1958 for (WALActionsListener i: listeners) {
1959
1960 i.visitLogEntryBeforeWrite(entry.getHTableDescriptor(), entry.getKey(),
1961 entry.getEdit());
1962 }
1963 }
1964
1965 writer.append(entry);
1966 assert highestUnsyncedSequence < entry.getSequence();
1967 highestUnsyncedSequence = entry.getSequence();
1968 sequenceIdAccounting.update(encodedRegionName, entry.getFamilyNames(), regionSequenceId,
1969 entry.isInMemstore());
1970 coprocessorHost.postWALWrite(entry.getHRegionInfo(), entry.getKey(), entry.getEdit());
1971
1972 postAppend(entry, EnvironmentEdgeManager.currentTime() - start);
1973 } catch (Exception e) {
1974 String msg = "Append sequenceId=" + regionSequenceId + ", requesting roll of WAL";
1975 LOG.warn(msg, e);
1976 requestLogRoll();
1977 throw new DamagedWALException(msg, e);
1978 }
1979 numEntries.incrementAndGet();
1980 }
1981
1982 @Override
1983 public void onStart() {
1984 for (SyncRunner syncRunner: this.syncRunners) syncRunner.start();
1985 }
1986
1987 @Override
1988 public void onShutdown() {
1989 for (SyncRunner syncRunner: this.syncRunners) syncRunner.interrupt();
1990 }
1991 }
1992
1993
1994
1995
1996 @VisibleForTesting
1997 void atHeadOfRingBufferEventHandlerAppend() {
1998
1999 }
2000
2001 private static IOException ensureIOException(final Throwable t) {
2002 return (t instanceof IOException)? (IOException)t: new IOException(t);
2003 }
2004
2005 private static void usage() {
2006 System.err.println("Usage: FSHLog <ARGS>");
2007 System.err.println("Arguments:");
2008 System.err.println(" --dump Dump textual representation of passed one or more files");
2009 System.err.println(" For example: " +
2010 "FSHLog --dump hdfs://example.com:9000/hbase/.logs/MACHINE/LOGFILE");
2011 System.err.println(" --split Split the passed directory of WAL logs");
2012 System.err.println(" For example: " +
2013 "FSHLog --split hdfs://example.com:9000/hbase/.logs/DIR");
2014 }
2015
2016
2017
2018
2019
2020
2021
2022
2023 public static void main(String[] args) throws IOException {
2024 if (args.length < 2) {
2025 usage();
2026 System.exit(-1);
2027 }
2028
2029 if (args[0].compareTo("--dump") == 0) {
2030 WALPrettyPrinter.run(Arrays.copyOfRange(args, 1, args.length));
2031 } else if (args[0].compareTo("--perf") == 0) {
2032 LOG.fatal("Please use the WALPerformanceEvaluation tool instead. i.e.:");
2033 LOG.fatal("\thbase org.apache.hadoop.hbase.wal.WALPerformanceEvaluation --iterations " +
2034 args[1]);
2035 System.exit(-1);
2036 } else if (args[0].compareTo("--split") == 0) {
2037 Configuration conf = HBaseConfiguration.create();
2038 for (int i = 1; i < args.length; i++) {
2039 try {
2040 Path logPath = new Path(args[i]);
2041 FSUtils.setFsDefault(conf, logPath);
2042 split(conf, logPath);
2043 } catch (IOException t) {
2044 t.printStackTrace(System.err);
2045 System.exit(-1);
2046 }
2047 }
2048 } else {
2049 usage();
2050 System.exit(-1);
2051 }
2052 }
2053
2054
2055
2056
2057 @VisibleForTesting
2058 DatanodeInfo[] getPipeLine() {
2059 if (this.hdfs_out != null) {
2060 if (this.hdfs_out.getWrappedStream() instanceof DFSOutputStream) {
2061 return ((DFSOutputStream) this.hdfs_out.getWrappedStream()).getPipeline();
2062 }
2063 }
2064 return new DatanodeInfo[0];
2065 }
2066
2067
2068
2069
2070
2071 public long getLastTimeCheckLowReplication() {
2072 return this.lastTimeCheckLowReplication;
2073 }
2074 }