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