View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.regionserver.wal;
19  
20  import 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 org.apache.commons.logging.Log;
52  import org.apache.commons.logging.LogFactory;
53  import org.apache.hadoop.conf.Configuration;
54  import org.apache.hadoop.fs.FSDataOutputStream;
55  import org.apache.hadoop.fs.FileStatus;
56  import org.apache.hadoop.fs.FileSystem;
57  import org.apache.hadoop.fs.Path;
58  import org.apache.hadoop.fs.PathFilter;
59  import org.apache.hadoop.hbase.Cell;
60  import org.apache.hadoop.hbase.CellUtil;
61  import org.apache.hadoop.hbase.HBaseConfiguration;
62  import org.apache.hadoop.hbase.HConstants;
63  import org.apache.hadoop.hbase.HRegionInfo;
64  import org.apache.hadoop.hbase.HTableDescriptor;
65  import org.apache.hadoop.hbase.classification.InterfaceAudience;
66  import org.apache.hadoop.hbase.exceptions.TimeoutIOException;
67  import org.apache.hadoop.hbase.io.util.HeapMemorySizeUtil;
68  import org.apache.hadoop.hbase.util.Bytes;
69  import org.apache.hadoop.hbase.util.ClassSize;
70  import org.apache.hadoop.hbase.util.DrainBarrier;
71  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
72  import org.apache.hadoop.hbase.util.FSUtils;
73  import org.apache.hadoop.hbase.util.HasThread;
74  import org.apache.hadoop.hbase.util.Threads;
75  import org.apache.hadoop.hbase.wal.DefaultWALProvider;
76  import org.apache.hadoop.hbase.wal.WAL;
77  import org.apache.hadoop.hbase.wal.WALFactory;
78  import org.apache.hadoop.hbase.wal.WALKey;
79  import org.apache.hadoop.hbase.wal.WALPrettyPrinter;
80  import org.apache.hadoop.hbase.wal.WALProvider.Writer;
81  import org.apache.hadoop.hbase.wal.WALSplitter;
82  import org.apache.hadoop.hdfs.DFSOutputStream;
83  import org.apache.hadoop.hdfs.client.HdfsDataOutputStream;
84  import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
85  import org.apache.hadoop.util.StringUtils;
86  import org.apache.htrace.NullScope;
87  import org.apache.htrace.Span;
88  import org.apache.htrace.Trace;
89  import org.apache.htrace.TraceScope;
90  
91  import com.google.common.annotations.VisibleForTesting;
92  import com.lmax.disruptor.BlockingWaitStrategy;
93  import com.lmax.disruptor.EventHandler;
94  import com.lmax.disruptor.ExceptionHandler;
95  import com.lmax.disruptor.LifecycleAware;
96  import com.lmax.disruptor.TimeoutException;
97  import com.lmax.disruptor.dsl.Disruptor;
98  import com.lmax.disruptor.dsl.ProducerType;
99  
100 /**
101  * Implementation of {@link WAL} to go against {@link FileSystem}; i.e. keep WALs in HDFS.
102  * Only one WAL is ever being written at a time.  When a WAL hits a configured maximum size,
103  * it is rolled.  This is done internal to the implementation.
104  *
105  * <p>As data is flushed from the MemStore to other on-disk structures (files sorted by
106  * key, hfiles), a WAL becomes obsolete. We can let go of all the log edits/entries for a given
107  * HRegion-sequence id.  A bunch of work in the below is done keeping account of these region
108  * sequence ids -- what is flushed out to hfiles, and what is yet in WAL and in memory only.
109  *
110  * <p>It is only practical to delete entire files. Thus, we delete an entire on-disk file
111  * <code>F</code> when all of the edits in <code>F</code> have a log-sequence-id that's older
112  * (smaller) than the most-recent flush.
113  *
114  * <p>To read an WAL, call {@link WALFactory#createReader(org.apache.hadoop.fs.FileSystem,
115  * org.apache.hadoop.fs.Path)}.
116  *
117  * <h2>Failure Semantic</h2>
118  * If an exception on append or sync, roll the WAL because the current WAL is now a lame duck;
119  * any more appends or syncs will fail also with the same original exception. If we have made
120  * successful appends to the WAL and we then are unable to sync them, our current semantic is to
121  * return error to the client that the appends failed but also to abort the current context,
122  * usually the hosting server. We need to replay the WALs. TODO: Change this semantic. A roll of
123  * WAL may be sufficient as long as we have flagged client that the append failed. TODO:
124  * replication may pick up these last edits though they have been marked as failed append (Need to
125  * keep our own file lengths, not rely on HDFS).
126  */
127 @InterfaceAudience.Private
128 public class FSHLog implements WAL {
129   // IMPLEMENTATION NOTES:
130   //
131   // At the core is a ring buffer.  Our ring buffer is the LMAX Disruptor.  It tries to
132   // minimize synchronizations and volatile writes when multiple contending threads as is the case
133   // here appending and syncing on a single WAL.  The Disruptor is configured to handle multiple
134   // producers but it has one consumer only (the producers in HBase are IPC Handlers calling append
135   // and then sync).  The single consumer/writer pulls the appends and syncs off the ring buffer.
136   // When a handler calls sync, it is given back a future. The producer 'blocks' on the future so
137   // it does not return until the sync completes.  The future is passed over the ring buffer from
138   // the producer/handler to the consumer thread where it does its best to batch up the producer
139   // syncs so one WAL sync actually spans multiple producer sync invocations.  How well the
140   // batching works depends on the write rate; i.e. we tend to batch more in times of
141   // high writes/syncs.
142   //
143   // Calls to append now also wait until the append has been done on the consumer side of the
144   // disruptor.  We used to not wait but it makes the implemenation easier to grok if we have
145   // the region edit/sequence id after the append returns.
146   //
147   // TODO: Handlers need to coordinate appending AND syncing.  Can we have the threads contend
148   // once only?  Probably hard given syncs take way longer than an append.
149   //
150   // The consumer threads pass the syncs off to multiple syncing threads in a round robin fashion
151   // to ensure we keep up back-to-back FS sync calls (FS sync calls are the long poll writing the
152   // WAL).  The consumer thread passes the futures to the sync threads for it to complete
153   // the futures when done.
154   //
155   // The 'sequence' in the below is the sequence of the append/sync on the ringbuffer.  It
156   // acts as a sort-of transaction id.  It is always incrementing.
157   //
158   // The RingBufferEventHandler class hosts the ring buffer consuming code.  The threads that
159   // do the actual FS sync are implementations of SyncRunner.  SafePointZigZagLatch is a
160   // synchronization class used to halt the consumer at a safe point --  just after all outstanding
161   // syncs and appends have completed -- so the log roller can swap the WAL out under it.
162 
163   private static final Log LOG = LogFactory.getLog(FSHLog.class);
164 
165   private static final int DEFAULT_SLOW_SYNC_TIME_MS = 100; // in ms
166 
167   private static final int DEFAULT_WAL_SYNC_TIMEOUT_MS = 5 * 60 * 1000; // in ms, 5min
168 
169   /**
170    * The nexus at which all incoming handlers meet.  Does appends and sync with an ordering.
171    * Appends and syncs are each put on the ring which means handlers need to
172    * smash up against the ring twice (can we make it once only? ... maybe not since time to append
173    * is so different from time to sync and sometimes we don't want to sync or we want to async
174    * the sync).  The ring is where we make sure of our ordering and it is also where we do
175    * batching up of handler sync calls.
176    */
177   private final Disruptor<RingBufferTruck> disruptor;
178 
179   /**
180    * An executorservice that runs the disruptor AppendEventHandler append executor.
181    */
182   private final ExecutorService appendExecutor;
183 
184   /**
185    * This fellow is run by the above appendExecutor service but it is all about batching up appends
186    * and syncs; it may shutdown without cleaning out the last few appends or syncs.  To guard
187    * against this, keep a reference to this handler and do explicit close on way out to make sure
188    * all flushed out before we exit.
189    */
190   private final RingBufferEventHandler ringBufferEventHandler;
191 
192   /**
193    * Map of {@link SyncFuture}s keyed by Handler objects.  Used so we reuse SyncFutures.
194    * TODO: Reus FSWALEntry's rather than create them anew each time as we do SyncFutures here.
195    * TODO: Add a FSWalEntry and SyncFuture as thread locals on handlers rather than have them
196    * get them from this Map?
197    */
198   private final Map<Thread, SyncFuture> syncFuturesByHandler;
199 
200   /**
201    * The highest known outstanding unsync'd WALEdit sequence number where sequence number is the
202    * ring buffer sequence.  Maintained by the ring buffer consumer.
203    */
204   private volatile long highestUnsyncedSequence = -1;
205 
206   /**
207    * Updated to the ring buffer sequence of the last successful sync call.  This can be less than
208    * {@link #highestUnsyncedSequence} for case where we have an append where a sync has not yet
209    * come in for it.  Maintained by the syncing threads.
210    */
211   private final AtomicLong highestSyncedSequence = new AtomicLong(0);
212 
213   /**
214    * file system instance
215    */
216   protected final FileSystem fs;
217 
218   /**
219    * WAL directory, where all WAL files would be placed.
220    */
221   private final Path fullPathLogDir;
222 
223   /**
224    * dir path where old logs are kept.
225    */
226   private final Path fullPathArchiveDir;
227 
228   /**
229    * Matches just those wal files that belong to this wal instance.
230    */
231   private final PathFilter ourFiles;
232 
233   /**
234    * Prefix of a WAL file, usually the region server name it is hosted on.
235    */
236   private final String logFilePrefix;
237 
238   /**
239    * Suffix included on generated wal file names
240    */
241   private final String logFileSuffix;
242 
243   /**
244    * Prefix used when checking for wal membership.
245    */
246   private final String prefixPathStr;
247 
248   private final WALCoprocessorHost coprocessorHost;
249 
250   /**
251    * conf object
252    */
253   protected final Configuration conf;
254 
255   /** Listeners that are called on WAL events. */
256   private final List<WALActionsListener> listeners =
257     new CopyOnWriteArrayList<WALActionsListener>();
258 
259   @Override
260   public void registerWALActionsListener(final WALActionsListener listener) {
261     this.listeners.add(listener);
262   }
263 
264   @Override
265   public boolean unregisterWALActionsListener(final WALActionsListener listener) {
266     return this.listeners.remove(listener);
267   }
268 
269   @Override
270   public WALCoprocessorHost getCoprocessorHost() {
271     return coprocessorHost;
272   }
273 
274   /**
275    * FSDataOutputStream associated with the current SequenceFile.writer
276    */
277   private FSDataOutputStream hdfs_out;
278 
279   // All about log rolling if not enough replicas outstanding.
280 
281   // Minimum tolerable replicas, if the actual value is lower than it, rollWriter will be triggered
282   private final int minTolerableReplication;
283 
284   private final int slowSyncNs;
285 
286   private final long walSyncTimeout;
287 
288   // If live datanode count is lower than the default replicas value,
289   // RollWriter will be triggered in each sync(So the RollWriter will be
290   // triggered one by one in a short time). Using it as a workaround to slow
291   // down the roll frequency triggered by checkLowReplication().
292   private final AtomicInteger consecutiveLogRolls = new AtomicInteger(0);
293 
294   private final int lowReplicationRollLimit;
295 
296   // If consecutiveLogRolls is larger than lowReplicationRollLimit,
297   // then disable the rolling in checkLowReplication().
298   // Enable it if the replications recover.
299   private volatile boolean lowReplicationRollEnabled = true;
300 
301   /**
302    * Class that does accounting of sequenceids in WAL subsystem. Holds oldest outstanding
303    * sequence id as yet not flushed as well as the most recent edit sequence id appended to the
304    * WAL. Has facility for answering questions such as "Is it safe to GC a WAL?".
305    */
306   private SequenceIdAccounting sequenceIdAccounting = new SequenceIdAccounting();
307 
308   /**
309    * Current log file.
310    */
311   volatile Writer writer;
312 
313   /** The barrier used to ensure that close() waits for all log rolls and flushes to finish. */
314   private final DrainBarrier closeBarrier = new DrainBarrier();
315 
316   /**
317    * This lock makes sure only one log roll runs at a time. Should not be taken while any other
318    * lock is held. We don't just use synchronized because that results in bogus and tedious
319    * findbugs warning when it thinks synchronized controls writer thread safety.  It is held when
320    * we are actually rolling the log.  It is checked when we are looking to see if we should roll
321    * the log or not.
322    */
323   private final ReentrantLock rollWriterLock = new ReentrantLock(true);
324 
325   private volatile boolean closed = false;
326   private final AtomicBoolean shutdown = new AtomicBoolean(false);
327 
328   // The timestamp (in ms) when the log file was created.
329   private final AtomicLong filenum = new AtomicLong(-1);
330 
331   // Number of transactions in the current Wal.
332   private final AtomicInteger numEntries = new AtomicInteger(0);
333 
334   // If > than this size, roll the log.
335   private final long logrollsize;
336 
337   /**
338    * The total size of wal
339    */
340   private AtomicLong totalLogSize = new AtomicLong(0);
341 
342   /*
343    * If more than this many logs, force flush of oldest region to oldest edit
344    * goes to disk.  If too many and we crash, then will take forever replaying.
345    * Keep the number of logs tidy.
346    */
347   private final int maxLogs;
348 
349   /** Number of log close errors tolerated before we abort */
350   private final int closeErrorsTolerated;
351 
352   private final AtomicInteger closeErrorCount = new AtomicInteger();
353 
354 
355   /**
356    * WAL Comparator; it compares the timestamp (log filenum), present in the log file name.
357    * Throws an IllegalArgumentException if used to compare paths from different wals.
358    */
359   final Comparator<Path> LOG_NAME_COMPARATOR = new Comparator<Path>() {
360     @Override
361     public int compare(Path o1, Path o2) {
362       long t1 = getFileNumFromFileName(o1);
363       long t2 = getFileNumFromFileName(o2);
364       if (t1 == t2) return 0;
365       return (t1 > t2) ? 1 : -1;
366     }
367   };
368 
369   /**
370    * Map of WAL log file to the latest sequence ids of all regions it has entries of.
371    * The map is sorted by the log file creation timestamp (contained in the log file name).
372    */
373   private NavigableMap<Path, Map<byte[], Long>> byWalRegionSequenceIds =
374     new ConcurrentSkipListMap<Path, Map<byte[], Long>>(LOG_NAME_COMPARATOR);
375 
376   /**
377    * Exception handler to pass the disruptor ringbuffer.  Same as native implementation only it
378    * logs using our logger instead of java native logger.
379    */
380   static class RingBufferExceptionHandler implements ExceptionHandler {
381     @Override
382     public void handleEventException(Throwable ex, long sequence, Object event) {
383       LOG.error("Sequence=" + sequence + ", event=" + event, ex);
384       throw new RuntimeException(ex);
385     }
386 
387     @Override
388     public void handleOnStartException(Throwable ex) {
389       LOG.error(ex);
390       throw new RuntimeException(ex);
391     }
392 
393     @Override
394     public void handleOnShutdownException(Throwable ex) {
395       LOG.error(ex);
396       throw new RuntimeException(ex);
397     }
398   }
399 
400   /**
401    * Constructor.
402    *
403    * @param fs filesystem handle
404    * @param root path for stored and archived wals
405    * @param logDir dir where wals are stored
406    * @param conf configuration to use
407    * @throws IOException
408    */
409   public FSHLog(final FileSystem fs, final Path root, final String logDir, final Configuration conf)
410       throws IOException {
411     this(fs, root, logDir, HConstants.HREGION_OLDLOGDIR_NAME, conf, null, true, null, null);
412   }
413 
414   /**
415    * Create an edit log at the given <code>dir</code> location.
416    *
417    * You should never have to load an existing log. If there is a log at
418    * startup, it should have already been processed and deleted by the time the
419    * WAL object is started up.
420    *
421    * @param fs filesystem handle
422    * @param rootDir path to where logs and oldlogs
423    * @param logDir dir where wals are stored
424    * @param archiveDir dir where wals are archived
425    * @param conf configuration to use
426    * @param listeners Listeners on WAL events. Listeners passed here will
427    * be registered before we do anything else; e.g. the
428    * Constructor {@link #rollWriter()}.
429    * @param failIfWALExists If true IOException will be thrown if files related to this wal
430    *        already exist.
431    * @param prefix should always be hostname and port in distributed env and
432    *        it will be URL encoded before being used.
433    *        If prefix is null, "wal" will be used
434    * @param suffix will be url encoded. null is treated as empty. non-empty must start with
435    *        {@link DefaultWALProvider#WAL_FILE_NAME_DELIMITER}
436    * @throws IOException
437    */
438   public FSHLog(final FileSystem fs, final Path rootDir, final String logDir,
439       final String archiveDir, final Configuration conf,
440       final List<WALActionsListener> listeners,
441       final boolean failIfWALExists, final String prefix, final String suffix)
442       throws IOException {
443     this.fs = fs;
444     this.fullPathLogDir = new Path(rootDir, logDir);
445     this.fullPathArchiveDir = new Path(rootDir, archiveDir);
446     this.conf = conf;
447 
448     if (!fs.exists(fullPathLogDir) && !fs.mkdirs(fullPathLogDir)) {
449       throw new IOException("Unable to mkdir " + fullPathLogDir);
450     }
451 
452     if (!fs.exists(this.fullPathArchiveDir)) {
453       if (!fs.mkdirs(this.fullPathArchiveDir)) {
454         throw new IOException("Unable to mkdir " + this.fullPathArchiveDir);
455       }
456     }
457 
458     // If prefix is null||empty then just name it wal
459     this.logFilePrefix =
460       prefix == null || prefix.isEmpty() ? "wal" : URLEncoder.encode(prefix, "UTF8");
461     // we only correctly differentiate suffices when numeric ones start with '.'
462     if (suffix != null && !(suffix.isEmpty()) && !(suffix.startsWith(WAL_FILE_NAME_DELIMITER))) {
463       throw new IllegalArgumentException("WAL suffix must start with '" + WAL_FILE_NAME_DELIMITER +
464           "' but instead was '" + suffix + "'");
465     }
466     // Now that it exists, set the storage policy for the entire directory of wal files related to
467     // this FSHLog instance
468     FSUtils.setStoragePolicy(fs, conf, this.fullPathLogDir, HConstants.WAL_STORAGE_POLICY,
469       HConstants.DEFAULT_WAL_STORAGE_POLICY);
470     this.logFileSuffix = (suffix == null) ? "" : URLEncoder.encode(suffix, "UTF8");
471     this.prefixPathStr = new Path(fullPathLogDir,
472         logFilePrefix + WAL_FILE_NAME_DELIMITER).toString();
473 
474     this.ourFiles = new PathFilter() {
475       @Override
476       public boolean accept(final Path fileName) {
477         // The path should start with dir/<prefix> and end with our suffix
478         final String fileNameString = fileName.toString();
479         if (!fileNameString.startsWith(prefixPathStr)) {
480           return false;
481         }
482         if (logFileSuffix.isEmpty()) {
483           // in the case of the null suffix, we need to ensure the filename ends with a timestamp.
484           return org.apache.commons.lang.StringUtils.isNumeric(
485               fileNameString.substring(prefixPathStr.length()));
486         } else if (!fileNameString.endsWith(logFileSuffix)) {
487           return false;
488         }
489         return true;
490       }
491     };
492 
493     if (failIfWALExists) {
494       final FileStatus[] walFiles = FSUtils.listStatus(fs, fullPathLogDir, ourFiles);
495       if (null != walFiles && 0 != walFiles.length) {
496         throw new IOException("Target WAL already exists within directory " + fullPathLogDir);
497       }
498     }
499 
500     // Register listeners.  TODO: Should this exist anymore?  We have CPs?
501     if (listeners != null) {
502       for (WALActionsListener i: listeners) {
503         registerWALActionsListener(i);
504       }
505     }
506     this.coprocessorHost = new WALCoprocessorHost(this, conf);
507 
508     // Get size to roll log at. Roll at 95% of HDFS block size so we avoid crossing HDFS blocks
509     // (it costs a little x'ing bocks)
510     final long blocksize = this.conf.getLong("hbase.regionserver.hlog.blocksize",
511         FSUtils.getDefaultBlockSize(this.fs, this.fullPathLogDir));
512     this.logrollsize =
513       (long)(blocksize * conf.getFloat("hbase.regionserver.logroll.multiplier", 0.95f));
514 
515     float memstoreRatio = conf.getFloat(HeapMemorySizeUtil.MEMSTORE_SIZE_KEY,
516       conf.getFloat(HeapMemorySizeUtil.MEMSTORE_SIZE_OLD_KEY,
517         HeapMemorySizeUtil.DEFAULT_MEMSTORE_SIZE));
518     boolean maxLogsDefined = conf.get("hbase.regionserver.maxlogs") != null;
519     if(maxLogsDefined){
520       LOG.warn("'hbase.regionserver.maxlogs' was deprecated.");
521     }
522     this.maxLogs = conf.getInt("hbase.regionserver.maxlogs",
523         Math.max(32, calculateMaxLogFiles(memstoreRatio, logrollsize)));
524     this.minTolerableReplication = conf.getInt("hbase.regionserver.hlog.tolerable.lowreplication",
525         FSUtils.getDefaultReplication(fs, this.fullPathLogDir));
526     this.lowReplicationRollLimit =
527       conf.getInt("hbase.regionserver.hlog.lowreplication.rolllimit", 5);
528     this.closeErrorsTolerated = conf.getInt("hbase.regionserver.logroll.errors.tolerated", 0);
529     int maxHandlersCount = conf.getInt(HConstants.REGION_SERVER_HANDLER_COUNT, 200);
530 
531     LOG.info("WAL configuration: blocksize=" + StringUtils.byteDesc(blocksize) +
532       ", rollsize=" + StringUtils.byteDesc(this.logrollsize) +
533       ", prefix=" + this.logFilePrefix + ", suffix=" + logFileSuffix + ", logDir=" +
534       this.fullPathLogDir + ", archiveDir=" + this.fullPathArchiveDir);
535 
536     // rollWriter sets this.hdfs_out if it can.
537     rollWriter();
538 
539     this.slowSyncNs =
540         1000000 * conf.getInt("hbase.regionserver.hlog.slowsync.ms",
541           DEFAULT_SLOW_SYNC_TIME_MS);
542     this.walSyncTimeout = conf.getLong("hbase.regionserver.hlog.sync.timeout",
543         DEFAULT_WAL_SYNC_TIMEOUT_MS);
544 
545     // This is the 'writer' -- a single threaded executor.  This single thread 'consumes' what is
546     // put on the ring buffer.
547     String hostingThreadName = Thread.currentThread().getName();
548     this.appendExecutor = Executors.
549       newSingleThreadExecutor(Threads.getNamedThreadFactory(hostingThreadName + ".append"));
550     // Preallocate objects to use on the ring buffer.  The way that appends and syncs work, we will
551     // be stuck and make no progress if the buffer is filled with appends only and there is no
552     // sync. If no sync, then the handlers will be outstanding just waiting on sync completion
553     // before they return.
554     final int preallocatedEventCount =
555       this.conf.getInt("hbase.regionserver.wal.disruptor.event.count", 1024 * 16);
556     // Using BlockingWaitStrategy.  Stuff that is going on here takes so long it makes no sense
557     // spinning as other strategies do.
558     this.disruptor =
559       new Disruptor<RingBufferTruck>(RingBufferTruck.EVENT_FACTORY, preallocatedEventCount,
560         this.appendExecutor, ProducerType.MULTI, new BlockingWaitStrategy());
561     // Advance the ring buffer sequence so that it starts from 1 instead of 0,
562     // because SyncFuture.NOT_DONE = 0.
563     this.disruptor.getRingBuffer().next();
564     this.ringBufferEventHandler =
565       new RingBufferEventHandler(conf.getInt("hbase.regionserver.hlog.syncer.count", 5),
566         maxHandlersCount);
567     this.disruptor.handleExceptionsWith(new RingBufferExceptionHandler());
568     this.disruptor.handleEventsWith(new RingBufferEventHandler [] {this.ringBufferEventHandler});
569     // Presize our map of SyncFutures by handler objects.
570     this.syncFuturesByHandler = new ConcurrentHashMap<Thread, SyncFuture>(maxHandlersCount);
571     // Starting up threads in constructor is a no no; Interface should have an init call.
572     this.disruptor.start();
573   }
574 
575   private int calculateMaxLogFiles(float memstoreSizeRatio, long logRollSize) {
576     long max = -1L;
577     final MemoryUsage usage = HeapMemorySizeUtil.safeGetHeapMemoryUsage();
578     if (usage != null) {
579       max = usage.getMax();
580     }
581     int maxLogs = Math.round(max * memstoreSizeRatio * 2 / logRollSize);
582     return maxLogs;
583   }
584 
585   /**
586    * Get the backing files associated with this WAL.
587    * @return may be null if there are no files.
588    */
589   protected FileStatus[] getFiles() throws IOException {
590     return FSUtils.listStatus(fs, fullPathLogDir, ourFiles);
591   }
592 
593   /**
594    * Currently, we need to expose the writer's OutputStream to tests so that they can manipulate
595    * the default behavior (such as setting the maxRecoveryErrorCount value for example (see
596    * {@link TestWALReplay#testReplayEditsWrittenIntoWAL()}). This is done using reflection on the
597    * underlying HDFS OutputStream.
598    * NOTE: This could be removed once Hadoop1 support is removed.
599    * @return null if underlying stream is not ready.
600    */
601   @VisibleForTesting
602   OutputStream getOutputStream() {
603     FSDataOutputStream fsdos = this.hdfs_out;
604     if (fsdos == null) return null;
605     return fsdos.getWrappedStream();
606   }
607 
608   @Override
609   public byte [][] rollWriter() throws FailedLogCloseException, IOException {
610     return rollWriter(false);
611   }
612 
613   /**
614    * retrieve the next path to use for writing.
615    * Increments the internal filenum.
616    */
617   private Path getNewPath() throws IOException {
618     this.filenum.set(System.currentTimeMillis());
619     Path newPath = getCurrentFileName();
620     while (fs.exists(newPath)) {
621       this.filenum.incrementAndGet();
622       newPath = getCurrentFileName();
623     }
624     return newPath;
625   }
626 
627   Path getOldPath() {
628     long currentFilenum = this.filenum.get();
629     Path oldPath = null;
630     if (currentFilenum > 0) {
631       // ComputeFilename  will take care of meta wal filename
632       oldPath = computeFilename(currentFilenum);
633     } // I presume if currentFilenum is <= 0, this is first file and null for oldPath if fine?
634     return oldPath;
635   }
636 
637   /**
638    * Tell listeners about pre log roll.
639    * @throws IOException
640    */
641   private void tellListenersAboutPreLogRoll(final Path oldPath, final Path newPath)
642   throws IOException {
643     coprocessorHost.preWALRoll(oldPath, newPath);
644 
645     if (!this.listeners.isEmpty()) {
646       for (WALActionsListener i : this.listeners) {
647         i.preLogRoll(oldPath, newPath);
648       }
649     }
650   }
651 
652   /**
653    * Tell listeners about post log roll.
654    * @throws IOException
655    */
656   private void tellListenersAboutPostLogRoll(final Path oldPath, final Path newPath)
657   throws IOException {
658     if (!this.listeners.isEmpty()) {
659       for (WALActionsListener i : this.listeners) {
660         i.postLogRoll(oldPath, newPath);
661       }
662     }
663 
664     coprocessorHost.postWALRoll(oldPath, newPath);
665   }
666 
667   /**
668    * Run a sync after opening to set up the pipeline.
669    * @param nextWriter
670    * @param startTimeNanos
671    */
672   private void preemptiveSync(final ProtobufLogWriter nextWriter) {
673     long startTimeNanos = System.nanoTime();
674     try {
675       nextWriter.sync();
676       postSync(System.nanoTime() - startTimeNanos, 0);
677     } catch (IOException e) {
678       // optimization failed, no need to abort here.
679       LOG.warn("pre-sync failed but an optimization so keep going", e);
680     }
681   }
682 
683   @Override
684   public byte [][] rollWriter(boolean force) throws FailedLogCloseException, IOException {
685     rollWriterLock.lock();
686     try {
687       // Return if nothing to flush.
688       if (!force && (this.writer != null && this.numEntries.get() <= 0)) return null;
689       byte [][] regionsToFlush = null;
690       if (this.closed) {
691         LOG.debug("WAL closed. Skipping rolling of writer");
692         return regionsToFlush;
693       }
694       if (!closeBarrier.beginOp()) {
695         LOG.debug("WAL closing. Skipping rolling of writer");
696         return regionsToFlush;
697       }
698       TraceScope scope = Trace.startSpan("FSHLog.rollWriter");
699       try {
700         Path oldPath = getOldPath();
701         Path newPath = getNewPath();
702         // Any exception from here on is catastrophic, non-recoverable so we currently abort.
703         Writer nextWriter = this.createWriterInstance(newPath);
704         FSDataOutputStream nextHdfsOut = null;
705         if (nextWriter instanceof ProtobufLogWriter) {
706           nextHdfsOut = ((ProtobufLogWriter)nextWriter).getStream();
707           // If a ProtobufLogWriter, go ahead and try and sync to force setup of pipeline.
708           // If this fails, we just keep going.... it is an optimization, not the end of the world.
709           preemptiveSync((ProtobufLogWriter)nextWriter);
710         }
711         tellListenersAboutPreLogRoll(oldPath, newPath);
712         // NewPath could be equal to oldPath if replaceWriter fails.
713         newPath = replaceWriter(oldPath, newPath, nextWriter, nextHdfsOut);
714         tellListenersAboutPostLogRoll(oldPath, newPath);
715         // Can we delete any of the old log files?
716         if (getNumRolledLogFiles() > 0) {
717           cleanOldLogs();
718           regionsToFlush = findRegionsToForceFlush();
719         }
720       } finally {
721         closeBarrier.endOp();
722         assert scope == NullScope.INSTANCE || !scope.isDetached();
723         scope.close();
724       }
725       return regionsToFlush;
726     } finally {
727       rollWriterLock.unlock();
728     }
729   }
730 
731   /**
732    * This method allows subclasses to inject different writers without having to
733    * extend other methods like rollWriter().
734    *
735    * @return Writer instance
736    */
737   protected Writer createWriterInstance(final Path path) throws IOException {
738     return DefaultWALProvider.createWriter(conf, fs, path, false);
739   }
740 
741   /**
742    * Archive old logs. A WAL is eligible for archiving if all its WALEdits have been flushed.
743    * @throws IOException
744    */
745   private void cleanOldLogs() throws IOException {
746     List<Path> logsToArchive = null;
747     // For each log file, look at its Map of regions to highest sequence id; if all sequence ids
748     // are older than what is currently in memory, the WAL can be GC'd.
749     for (Map.Entry<Path, Map<byte[], Long>> e : this.byWalRegionSequenceIds.entrySet()) {
750       Path log = e.getKey();
751       Map<byte[], Long> sequenceNums = e.getValue();
752       if (this.sequenceIdAccounting.areAllLower(sequenceNums)) {
753         if (logsToArchive == null) logsToArchive = new ArrayList<Path>();
754         logsToArchive.add(log);
755         if (LOG.isTraceEnabled()) LOG.trace("WAL file ready for archiving " + log);
756       }
757     }
758     if (logsToArchive != null) {
759       for (Path p : logsToArchive) {
760         this.totalLogSize.addAndGet(-this.fs.getFileStatus(p).getLen());
761         archiveLogFile(p);
762         this.byWalRegionSequenceIds.remove(p);
763       }
764     }
765   }
766 
767   /**
768    * If the number of un-archived WAL files is greater than maximum allowed, check the first
769    * (oldest) WAL file, and returns those regions which should be flushed so that it can
770    * be archived.
771    * @return regions (encodedRegionNames) to flush in order to archive oldest WAL file.
772    * @throws IOException
773    */
774   byte[][] findRegionsToForceFlush() throws IOException {
775     byte [][] regions = null;
776     int logCount = getNumRolledLogFiles();
777     if (logCount > this.maxLogs && logCount > 0) {
778       Map.Entry<Path, Map<byte[], Long>> firstWALEntry =
779         this.byWalRegionSequenceIds.firstEntry();
780       regions = this.sequenceIdAccounting.findLower(firstWALEntry.getValue());
781     }
782     if (regions != null) {
783       StringBuilder sb = new StringBuilder();
784       for (int i = 0; i < regions.length; i++) {
785         if (i > 0) sb.append(", ");
786         sb.append(Bytes.toStringBinary(regions[i]));
787       }
788       LOG.info("Too many WALs; count=" + logCount + ", max=" + this.maxLogs +
789         "; forcing flush of " + regions.length + " regions(s): " + sb.toString());
790     }
791     return regions;
792   }
793 
794   /**
795    * Used to manufacture race condition reliably. For testing only.
796    * @see #beforeWaitOnSafePoint()
797    */
798   @VisibleForTesting
799   protected void afterCreatingZigZagLatch() {}
800 
801   /**
802    * @see #afterCreatingZigZagLatch()
803    */
804   @VisibleForTesting
805   protected void beforeWaitOnSafePoint() {};
806 
807   /**
808    * Cleans up current writer closing it and then puts in place the passed in
809    * <code>nextWriter</code>.
810    *
811    * In the case of creating a new WAL, oldPath will be null.
812    *
813    * In the case of rolling over from one file to the next, none of the params will be null.
814    *
815    * In the case of closing out this FSHLog with no further use newPath, nextWriter, and
816    * nextHdfsOut will be null.
817    *
818    * @param oldPath may be null
819    * @param newPath may be null
820    * @param nextWriter may be null
821    * @param nextHdfsOut may be null
822    * @return the passed in <code>newPath</code>
823    * @throws IOException if there is a problem flushing or closing the underlying FS
824    */
825   Path replaceWriter(final Path oldPath, final Path newPath, Writer nextWriter,
826       final FSDataOutputStream nextHdfsOut)
827   throws IOException {
828     // Ask the ring buffer writer to pause at a safe point.  Once we do this, the writer
829     // thread will eventually pause. An error hereafter needs to release the writer thread
830     // regardless -- hence the finally block below.  Note, this method is called from the FSHLog
831     // constructor BEFORE the ring buffer is set running so it is null on first time through
832     // here; allow for that.
833     SyncFuture syncFuture = null;
834     SafePointZigZagLatch zigzagLatch = null;
835     long sequence = -1L;
836     if (this.ringBufferEventHandler != null) {
837       // Get sequence first to avoid dead lock when ring buffer is full
838       // Considering below sequence
839       // 1. replaceWriter is called and zigzagLatch is initialized
840       // 2. ringBufferEventHandler#onEvent is called and arrives at #attainSafePoint(long) then wait
841       // on safePointReleasedLatch
842       // 3. Since ring buffer is full, if we get sequence when publish sync, the replaceWriter
843       // thread will wait for the ring buffer to be consumed, but the only consumer is waiting
844       // replaceWriter thread to release safePointReleasedLatch, which causes a deadlock
845       sequence = getSequenceOnRingBuffer();
846       zigzagLatch = this.ringBufferEventHandler.attainSafePoint();
847     }
848     afterCreatingZigZagLatch();
849     TraceScope scope = Trace.startSpan("FSHFile.replaceWriter");
850     try {
851       // Wait on the safe point to be achieved.  Send in a sync in case nothing has hit the
852       // ring buffer between the above notification of writer that we want it to go to
853       // 'safe point' and then here where we are waiting on it to attain safe point.  Use
854       // 'sendSync' instead of 'sync' because we do not want this thread to block waiting on it
855       // to come back.  Cleanup this syncFuture down below after we are ready to run again.
856       try {
857         if (zigzagLatch != null) {
858           // use assert to make sure no change breaks the logic that
859           // sequence and zigzagLatch will be set together
860           assert sequence > 0L : "Failed to get sequence from ring buffer";
861           Trace.addTimelineAnnotation("awaiting safepoint");
862           syncFuture = zigzagLatch.waitSafePoint(publishSyncOnRingBuffer(sequence));
863         }
864       } catch (FailedSyncBeforeLogCloseException e) {
865         // If unflushed/unsynced entries on close, it is reason to abort.
866         if (isUnflushedEntries()) throw e;
867         LOG.warn("Failed sync-before-close but no outstanding appends; closing WAL: " +
868           e.getMessage());
869       }
870 
871       // It is at the safe point.  Swap out writer from under the blocked writer thread.
872       // TODO: This is close is inline with critical section.  Should happen in background?
873       try {
874         if (this.writer != null) {
875           Trace.addTimelineAnnotation("closing writer");
876           this.writer.close();
877           Trace.addTimelineAnnotation("writer closed");
878         }
879         this.closeErrorCount.set(0);
880       } catch (IOException ioe) {
881         int errors = closeErrorCount.incrementAndGet();
882         if (!isUnflushedEntries() && (errors <= this.closeErrorsTolerated)) {
883           LOG.warn("Riding over failed WAL close of " + oldPath + ", cause=\"" +
884             ioe.getMessage() + "\", errors=" + errors +
885             "; THIS FILE WAS NOT CLOSED BUT ALL EDITS SYNCED SO SHOULD BE OK");
886         } else {
887           throw ioe;
888         }
889       }
890       this.writer = nextWriter;
891       this.hdfs_out = nextHdfsOut;
892       int oldNumEntries = this.numEntries.get();
893       this.numEntries.set(0);
894       final String newPathString = (null == newPath ? null : FSUtils.getPath(newPath));
895       if (oldPath != null) {
896         this.byWalRegionSequenceIds.put(oldPath, this.sequenceIdAccounting.resetHighest());
897         long oldFileLen = this.fs.getFileStatus(oldPath).getLen();
898         this.totalLogSize.addAndGet(oldFileLen);
899         LOG.info("Rolled WAL " + FSUtils.getPath(oldPath) + " with entries=" + oldNumEntries +
900           ", filesize=" + StringUtils.byteDesc(oldFileLen) + "; new WAL " +
901           newPathString);
902       } else {
903         LOG.info("New WAL " + newPathString);
904       }
905     } catch (InterruptedException ie) {
906       // Perpetuate the interrupt
907       Thread.currentThread().interrupt();
908     } catch (IOException e) {
909       long count = getUnflushedEntriesCount();
910       LOG.error("Failed close of WAL writer " + oldPath + ", unflushedEntries=" + count, e);
911       throw new FailedLogCloseException(oldPath + ", unflushedEntries=" + count, e);
912     } finally {
913       try {
914         // Let the writer thread go regardless, whether error or not.
915         if (zigzagLatch != null) {
916           zigzagLatch.releaseSafePoint();
917           // syncFuture will be null if we failed our wait on safe point above. Otherwise, if
918           // latch was obtained successfully, the sync we threw in either trigger the latch or it
919           // got stamped with an exception because the WAL was damaged and we could not sync. Now
920           // the write pipeline has been opened up again by releasing the safe point, process the
921           // syncFuture we got above. This is probably a noop but it may be stale exception from
922           // when old WAL was in place. Catch it if so.
923           if (syncFuture != null) {
924             try {
925               blockOnSync(syncFuture);
926             } catch (IOException ioe) {
927               if (LOG.isTraceEnabled()) LOG.trace("Stale sync exception", ioe);
928             }
929           }
930         }
931       } finally {
932         scope.close();
933       }
934     }
935     return newPath;
936   }
937 
938   long getUnflushedEntriesCount() {
939     long highestSynced = this.highestSyncedSequence.get();
940     return highestSynced > this.highestUnsyncedSequence?
941       0: this.highestUnsyncedSequence - highestSynced;
942   }
943 
944   boolean isUnflushedEntries() {
945     return getUnflushedEntriesCount() > 0;
946   }
947 
948   /*
949    * only public so WALSplitter can use.
950    * @return archived location of a WAL file with the given path p
951    */
952   public static Path getWALArchivePath(Path archiveDir, Path p) {
953     return new Path(archiveDir, p.getName());
954   }
955 
956   private void archiveLogFile(final Path p) throws IOException {
957     Path newPath = getWALArchivePath(this.fullPathArchiveDir, p);
958     // Tell our listeners that a log is going to be archived.
959     if (!this.listeners.isEmpty()) {
960       for (WALActionsListener i : this.listeners) {
961         i.preLogArchive(p, newPath);
962       }
963     }
964     LOG.info("Archiving " + p + " to " + newPath);
965     if (!FSUtils.renameAndSetModifyTime(this.fs, p, newPath)) {
966       throw new IOException("Unable to rename " + p + " to " + newPath);
967     }
968     // Tell our listeners that a log has been archived.
969     if (!this.listeners.isEmpty()) {
970       for (WALActionsListener i : this.listeners) {
971         i.postLogArchive(p, newPath);
972       }
973     }
974   }
975 
976   /**
977    * This is a convenience method that computes a new filename with a given
978    * file-number.
979    * @param filenum to use
980    * @return Path
981    */
982   protected Path computeFilename(final long filenum) {
983     if (filenum < 0) {
984       throw new RuntimeException("WAL file number can't be < 0");
985     }
986     String child = logFilePrefix + WAL_FILE_NAME_DELIMITER + filenum + logFileSuffix;
987     return new Path(fullPathLogDir, child);
988   }
989 
990   /**
991    * This is a convenience method that computes a new filename with a given
992    * using the current WAL file-number
993    * @return Path
994    */
995   public Path getCurrentFileName() {
996     return computeFilename(this.filenum.get());
997   }
998 
999   @Override
1000   public String toString() {
1001     return "FSHLog " + logFilePrefix + ":" + logFileSuffix + "(num " + filenum + ")";
1002   }
1003 
1004 /**
1005  * A log file has a creation timestamp (in ms) in its file name ({@link #filenum}.
1006  * This helper method returns the creation timestamp from a given log file.
1007  * It extracts the timestamp assuming the filename is created with the
1008  * {@link #computeFilename(long filenum)} method.
1009  * @param fileName
1010  * @return timestamp, as in the log file name.
1011  */
1012   protected long getFileNumFromFileName(Path fileName) {
1013     if (fileName == null) throw new IllegalArgumentException("file name can't be null");
1014     if (!ourFiles.accept(fileName)) {
1015       throw new IllegalArgumentException("The log file " + fileName +
1016           " doesn't belong to this WAL. (" + toString() + ")");
1017     }
1018     final String fileNameString = fileName.toString();
1019     String chompedPath = fileNameString.substring(prefixPathStr.length(),
1020         (fileNameString.length() - logFileSuffix.length()));
1021     return Long.parseLong(chompedPath);
1022   }
1023 
1024   @Override
1025   public void close() throws IOException {
1026     shutdown();
1027     final FileStatus[] files = getFiles();
1028     if (null != files && 0 != files.length) {
1029       for (FileStatus file : files) {
1030         Path p = getWALArchivePath(this.fullPathArchiveDir, file.getPath());
1031         // Tell our listeners that a log is going to be archived.
1032         if (!this.listeners.isEmpty()) {
1033           for (WALActionsListener i : this.listeners) {
1034             i.preLogArchive(file.getPath(), p);
1035           }
1036         }
1037 
1038         if (!FSUtils.renameAndSetModifyTime(fs, file.getPath(), p)) {
1039           throw new IOException("Unable to rename " + file.getPath() + " to " + p);
1040         }
1041         // Tell our listeners that a log was archived.
1042         if (!this.listeners.isEmpty()) {
1043           for (WALActionsListener i : this.listeners) {
1044             i.postLogArchive(file.getPath(), p);
1045           }
1046         }
1047       }
1048       LOG.debug("Moved " + files.length + " WAL file(s) to " +
1049         FSUtils.getPath(this.fullPathArchiveDir));
1050     }
1051     LOG.info("Closed WAL: " + toString());
1052   }
1053 
1054   @Override
1055   public void shutdown() throws IOException {
1056     if (shutdown.compareAndSet(false, true)) {
1057       try {
1058         // Prevent all further flushing and rolling.
1059         closeBarrier.stopAndDrainOps();
1060       } catch (InterruptedException e) {
1061         LOG.error("Exception while waiting for cache flushes and log rolls", e);
1062         Thread.currentThread().interrupt();
1063       }
1064 
1065       // Shutdown the disruptor.  Will stop after all entries have been processed.  Make sure we
1066       // have stopped incoming appends before calling this else it will not shutdown.  We are
1067       // conservative below waiting a long time and if not elapsed, then halting.
1068       if (this.disruptor != null) {
1069         long timeoutms = conf.getLong("hbase.wal.disruptor.shutdown.timeout.ms", 60000);
1070         try {
1071           this.disruptor.shutdown(timeoutms, TimeUnit.MILLISECONDS);
1072         } catch (TimeoutException e) {
1073           LOG.warn("Timed out bringing down disruptor after " + timeoutms + "ms; forcing halt " +
1074             "(It is a problem if this is NOT an ABORT! -- DATALOSS!!!!)");
1075           this.disruptor.halt();
1076           this.disruptor.shutdown();
1077         }
1078       }
1079       // With disruptor down, this is safe to let go.
1080       if (this.appendExecutor !=  null) this.appendExecutor.shutdown();
1081 
1082       // Tell our listeners that the log is closing
1083       if (!this.listeners.isEmpty()) {
1084         for (WALActionsListener i : this.listeners) {
1085           i.logCloseRequested();
1086         }
1087       }
1088       this.closed = true;
1089       if (LOG.isDebugEnabled()) {
1090         LOG.debug("Closing WAL writer in " + FSUtils.getPath(fullPathLogDir));
1091       }
1092       if (this.writer != null) {
1093         this.writer.close();
1094         this.writer = null;
1095       }
1096     }
1097   }
1098 
1099   @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NP_NULL_ON_SOME_PATH_EXCEPTION",
1100       justification="Will never be null")
1101   @Override
1102   public long append(final HTableDescriptor htd, final HRegionInfo hri, final WALKey key,
1103       final WALEdit edits, final boolean inMemstore) throws IOException {
1104     if (this.closed) throw new IOException("Cannot append; log is closed");
1105     // Make a trace scope for the append.  It is closed on other side of the ring buffer by the
1106     // single consuming thread.  Don't have to worry about it.
1107     TraceScope scope = Trace.startSpan("FSHLog.append");
1108 
1109     // This is crazy how much it takes to make an edit.  Do we need all this stuff!!!!????  We need
1110     // all this to make a key and then below to append the edit, we need to carry htd, info,
1111     // etc. all over the ring buffer.
1112     FSWALEntry entry = null;
1113     long sequence = this.disruptor.getRingBuffer().next();
1114     try {
1115       RingBufferTruck truck = this.disruptor.getRingBuffer().get(sequence);
1116       // TODO: reuse FSWALEntry as we do SyncFuture rather create per append.
1117       entry = new FSWALEntry(sequence, key, edits, htd, hri, inMemstore);
1118       truck.loadPayload(entry, scope.detach());
1119     } finally {
1120       this.disruptor.getRingBuffer().publish(sequence);
1121     }
1122     return sequence;
1123   }
1124 
1125   /**
1126    * Thread to runs the hdfs sync call. This call takes a while to complete.  This is the longest
1127    * pole adding edits to the WAL and this must complete to be sure all edits persisted.  We run
1128    * multiple threads sync'ng rather than one that just syncs in series so we have better
1129    * latencies; otherwise, an edit that arrived just after a sync started, might have to wait
1130    * almost the length of two sync invocations before it is marked done.
1131    * <p>When the sync completes, it marks all the passed in futures done.  On the other end of the
1132    * sync future is a blocked thread, usually a regionserver Handler.  There may be more than one
1133    * future passed in the case where a few threads arrive at about the same time and all invoke
1134    * 'sync'.  In this case we'll batch up the invocations and run one filesystem sync only for a
1135    * batch of Handler sync invocations.  Do not confuse these Handler SyncFutures with the futures
1136    * an ExecutorService returns when you call submit. We have no use for these in this model. These
1137    * SyncFutures are 'artificial', something to hold the Handler until the filesystem sync
1138    * completes.
1139    */
1140   private class SyncRunner extends HasThread {
1141     private volatile long sequence;
1142     // Keep around last exception thrown. Clear on successful sync.
1143     private final BlockingQueue<SyncFuture> syncFutures;
1144     private volatile SyncFuture takeSyncFuture = null;
1145 
1146     /**
1147      * UPDATE!
1148      * @param syncs the batch of calls to sync that arrived as this thread was starting; when done,
1149      * we will put the result of the actual hdfs sync call as the result.
1150      * @param sequence The sequence number on the ring buffer when this thread was set running.
1151      * If this actual writer sync completes then all appends up this point have been
1152      * flushed/synced/pushed to datanodes.  If we fail, then the passed in <code>syncs</code>
1153      * futures will return the exception to their clients; some of the edits may have made it out
1154      * to data nodes but we will report all that were part of this session as failed.
1155      */
1156     SyncRunner(final String name, final int maxHandlersCount) {
1157       super(name);
1158       // LinkedBlockingQueue because of
1159       // http://www.javacodegeeks.com/2010/09/java-best-practices-queue-battle-and.html
1160       // Could use other blockingqueues here or concurrent queues.
1161       //
1162       // We could let the capacity be 'open' but bound it so we get alerted in pathological case
1163       // where we cannot sync and we have a bunch of threads all backed up waiting on their syncs
1164       // to come in.  LinkedBlockingQueue actually shrinks when you remove elements so Q should
1165       // stay neat and tidy in usual case.  Let the max size be three times the maximum handlers.
1166       // The passed in maxHandlerCount is the user-level handlers which is what we put up most of
1167       // but HBase has other handlers running too -- opening region handlers which want to write
1168       // the meta table when succesful (i.e. sync), closing handlers -- etc.  These are usually
1169       // much fewer in number than the user-space handlers so Q-size should be user handlers plus
1170       // some space for these other handlers.  Lets multiply by 3 for good-measure.
1171       this.syncFutures = new LinkedBlockingQueue<SyncFuture>(maxHandlersCount * 3);
1172     }
1173 
1174     void offer(final long sequence, final SyncFuture [] syncFutures, final int syncFutureCount) {
1175       // Set sequence first because the add to the queue will wake the thread if sleeping.
1176       this.sequence = sequence;
1177       for (int i = 0; i < syncFutureCount; ++i) {
1178         this.syncFutures.add(syncFutures[i]);
1179       }
1180     }
1181 
1182     /**
1183      * Release the passed <code>syncFuture</code>
1184      * @param syncFuture
1185      * @param currentSequence
1186      * @param t
1187      * @return Returns 1.
1188      */
1189     private int releaseSyncFuture(final SyncFuture syncFuture, final long currentSequence,
1190         final Throwable t) {
1191       if (!syncFuture.done(currentSequence, t)) throw new IllegalStateException();
1192       // This function releases one sync future only.
1193       return 1;
1194     }
1195 
1196     /**
1197      * Release all SyncFutures whose sequence is <= <code>currentSequence</code>.
1198      * @param currentSequence
1199      * @param t May be non-null if we are processing SyncFutures because an exception was thrown.
1200      * @return Count of SyncFutures we let go.
1201      */
1202     private int releaseSyncFutures(final long currentSequence, final Throwable t) {
1203       int syncCount = 0;
1204       for (SyncFuture syncFuture; (syncFuture = this.syncFutures.peek()) != null;) {
1205         if (syncFuture.getRingBufferSequence() > currentSequence) break;
1206         releaseSyncFuture(syncFuture, currentSequence, t);
1207         if (!this.syncFutures.remove(syncFuture)) {
1208           throw new IllegalStateException(syncFuture.toString());
1209         }
1210         syncCount++;
1211       }
1212       return syncCount;
1213     }
1214 
1215     /**
1216      * @param sequence The sequence we ran the filesystem sync against.
1217      * @return Current highest synced sequence.
1218      */
1219     private long updateHighestSyncedSequence(long sequence) {
1220       long currentHighestSyncedSequence;
1221       // Set the highestSyncedSequence IFF our current sequence id is the 'highest'.
1222       do {
1223         currentHighestSyncedSequence = highestSyncedSequence.get();
1224         if (currentHighestSyncedSequence >= sequence) {
1225           // Set the sync number to current highwater mark; might be able to let go more
1226           // queued sync futures
1227           sequence = currentHighestSyncedSequence;
1228           break;
1229         }
1230       } while (!highestSyncedSequence.compareAndSet(currentHighestSyncedSequence, sequence));
1231       return sequence;
1232     }
1233 
1234     boolean areSyncFuturesReleased() {
1235       // check whether there is no sync futures offered, and no in-flight sync futures that is being
1236       // processed.
1237       return syncFutures.size() <= 0
1238           && takeSyncFuture == null;
1239     }
1240 
1241     public void run() {
1242       long currentSequence;
1243       while (!isInterrupted()) {
1244         int syncCount = 0;
1245 
1246         try {
1247           while (true) {
1248             takeSyncFuture = null;
1249             // We have to process what we 'take' from the queue
1250             takeSyncFuture = this.syncFutures.take();
1251             currentSequence = this.sequence;
1252             long syncFutureSequence = takeSyncFuture.getRingBufferSequence();
1253             if (syncFutureSequence > currentSequence) {
1254               throw new IllegalStateException("currentSequence=" + syncFutureSequence +
1255                 ", syncFutureSequence=" + syncFutureSequence);
1256             }
1257             // See if we can process any syncfutures BEFORE we go sync.
1258             long currentHighestSyncedSequence = highestSyncedSequence.get();
1259             if (currentSequence < currentHighestSyncedSequence) {
1260               syncCount += releaseSyncFuture(takeSyncFuture, currentHighestSyncedSequence, null);
1261               // Done with the 'take'.  Go around again and do a new 'take'.
1262               continue;
1263             }
1264             break;
1265           }
1266           // I got something.  Lets run.  Save off current sequence number in case it changes
1267           // while we run.
1268           TraceScope scope = Trace.continueSpan(takeSyncFuture.getSpan());
1269           long start = System.nanoTime();
1270           Throwable lastException = null;
1271           try {
1272             Trace.addTimelineAnnotation("syncing writer");
1273             writer.sync();
1274             Trace.addTimelineAnnotation("writer synced");
1275             currentSequence = updateHighestSyncedSequence(currentSequence);
1276           } catch (IOException e) {
1277             LOG.error("Error syncing, request close of WAL", e);
1278             lastException = e;
1279           } catch (Exception e) {
1280             LOG.warn("UNEXPECTED", e);
1281             lastException = e;
1282           } finally {
1283             // reattach the span to the future before releasing.
1284             takeSyncFuture.setSpan(scope.detach());
1285             // First release what we 'took' from the queue.
1286             syncCount += releaseSyncFuture(takeSyncFuture, currentSequence, lastException);
1287             // Can we release other syncs?
1288             syncCount += releaseSyncFutures(currentSequence, lastException);
1289             if (lastException != null) requestLogRoll();
1290             else checkLogRoll();
1291           }
1292           postSync(System.nanoTime() - start, syncCount);
1293         } catch (InterruptedException e) {
1294           // Presume legit interrupt.
1295           Thread.currentThread().interrupt();
1296         } catch (Throwable t) {
1297           LOG.warn("UNEXPECTED, continuing", t);
1298         }
1299       }
1300     }
1301   }
1302 
1303   /**
1304    * Schedule a log roll if needed.
1305    */
1306   void checkLogRoll() {
1307     // Will return immediately if we are in the middle of a WAL log roll currently.
1308     if (!rollWriterLock.tryLock()) return;
1309     boolean lowReplication;
1310     try {
1311       lowReplication = checkLowReplication();
1312     } finally {
1313       rollWriterLock.unlock();
1314     }
1315     try {
1316       if (lowReplication || writer != null && writer.getLength() > logrollsize) {
1317         requestLogRoll(lowReplication);
1318       }
1319     } catch (IOException e) {
1320       LOG.warn("Writer.getLength() failed; continuing", e);
1321     }
1322   }
1323 
1324   /*
1325    * @return true if number of replicas for the WAL is lower than threshold
1326    */
1327   private boolean checkLowReplication() {
1328     boolean logRollNeeded = false;
1329     // if the number of replicas in HDFS has fallen below the configured
1330     // value, then roll logs.
1331     try {
1332       int numCurrentReplicas = getLogReplication();
1333       if (numCurrentReplicas != 0 && numCurrentReplicas < this.minTolerableReplication) {
1334         if (this.lowReplicationRollEnabled) {
1335           if (this.consecutiveLogRolls.get() < this.lowReplicationRollLimit) {
1336             LOG.warn("HDFS pipeline error detected. " + "Found "
1337                 + numCurrentReplicas + " replicas but expecting no less than "
1338                 + this.minTolerableReplication + " replicas. "
1339                 + " Requesting close of WAL. current pipeline: "
1340                 + Arrays.toString(getPipeLine()));
1341             logRollNeeded = true;
1342             // If rollWriter is requested, increase consecutiveLogRolls. Once it
1343             // is larger than lowReplicationRollLimit, disable the
1344             // LowReplication-Roller
1345             this.consecutiveLogRolls.getAndIncrement();
1346           } else {
1347             LOG.warn("Too many consecutive RollWriter requests, it's a sign of "
1348                 + "the total number of live datanodes is lower than the tolerable replicas.");
1349             this.consecutiveLogRolls.set(0);
1350             this.lowReplicationRollEnabled = false;
1351           }
1352         }
1353       } else if (numCurrentReplicas >= this.minTolerableReplication) {
1354         if (!this.lowReplicationRollEnabled) {
1355           // The new writer's log replicas is always the default value.
1356           // So we should not enable LowReplication-Roller. If numEntries
1357           // is lower than or equals 1, we consider it as a new writer.
1358           if (this.numEntries.get() <= 1) {
1359             return logRollNeeded;
1360           }
1361           // Once the live datanode number and the replicas return to normal,
1362           // enable the LowReplication-Roller.
1363           this.lowReplicationRollEnabled = true;
1364           LOG.info("LowReplication-Roller was enabled.");
1365         }
1366       }
1367     } catch (Exception e) {
1368       LOG.warn("DFSOutputStream.getNumCurrentReplicas failed because of " + e +
1369         ", continuing...");
1370     }
1371     return logRollNeeded;
1372   }
1373 
1374   private SyncFuture publishSyncOnRingBuffer(long sequence) {
1375     return publishSyncOnRingBuffer(sequence, null);
1376   }
1377 
1378   private long getSequenceOnRingBuffer() {
1379     return this.disruptor.getRingBuffer().next();
1380   }
1381 
1382   private SyncFuture publishSyncOnRingBuffer(Span span) {
1383     long sequence = this.disruptor.getRingBuffer().next();
1384     return publishSyncOnRingBuffer(sequence, span);
1385   }
1386 
1387   private SyncFuture publishSyncOnRingBuffer(long sequence, Span span) {
1388     SyncFuture syncFuture = getSyncFuture(sequence, span);
1389     try {
1390       RingBufferTruck truck = this.disruptor.getRingBuffer().get(sequence);
1391       truck.loadPayload(syncFuture);
1392     } finally {
1393       this.disruptor.getRingBuffer().publish(sequence);
1394     }
1395     return syncFuture;
1396   }
1397 
1398   // Sync all known transactions
1399   private Span publishSyncThenBlockOnCompletion(Span span) throws IOException {
1400     return blockOnSync(publishSyncOnRingBuffer(span));
1401   }
1402 
1403   private Span blockOnSync(final SyncFuture syncFuture) throws IOException {
1404     // Now we have published the ringbuffer, halt the current thread until we get an answer back.
1405     try {
1406       syncFuture.get(walSyncTimeout);
1407       return syncFuture.getSpan();
1408     } catch (TimeoutIOException tioe) {
1409       // SyncFuture reuse by thread, if TimeoutIOException happens, ringbuffer
1410       // still refer to it, so if this thread use it next time may get a wrong
1411       // result.
1412       this.syncFuturesByHandler.remove(Thread.currentThread());
1413       throw tioe;
1414     } catch (InterruptedException ie) {
1415       LOG.warn("Interrupted", ie);
1416       throw convertInterruptedExceptionToIOException(ie);
1417     } catch (ExecutionException e) {
1418       throw ensureIOException(e.getCause());
1419     }
1420   }
1421 
1422   private IOException convertInterruptedExceptionToIOException(final InterruptedException ie) {
1423     Thread.currentThread().interrupt();
1424     IOException ioe = new InterruptedIOException();
1425     ioe.initCause(ie);
1426     return ioe;
1427   }
1428 
1429   private SyncFuture getSyncFuture(final long sequence, Span span) {
1430     SyncFuture syncFuture = this.syncFuturesByHandler.get(Thread.currentThread());
1431     if (syncFuture == null) {
1432       syncFuture = new SyncFuture();
1433       this.syncFuturesByHandler.put(Thread.currentThread(), syncFuture);
1434     }
1435     return syncFuture.reset(sequence, span);
1436   }
1437 
1438   private void postSync(final long timeInNanos, final int handlerSyncs) {
1439     if (timeInNanos > this.slowSyncNs) {
1440       String msg =
1441           new StringBuilder().append("Slow sync cost: ")
1442               .append(timeInNanos / 1000000).append(" ms, current pipeline: ")
1443               .append(Arrays.toString(getPipeLine())).toString();
1444       Trace.addTimelineAnnotation(msg);
1445       LOG.info(msg);
1446     }
1447     if (!listeners.isEmpty()) {
1448       for (WALActionsListener listener : listeners) {
1449         listener.postSync(timeInNanos, handlerSyncs);
1450       }
1451     }
1452   }
1453 
1454   private long postAppend(final Entry e, final long elapsedTime) throws IOException {
1455     long len = 0;
1456     if (!listeners.isEmpty()) {
1457       for (Cell cell : e.getEdit().getCells()) {
1458         len += CellUtil.estimatedSerializedSizeOf(cell);
1459       }
1460       for (WALActionsListener listener : listeners) {
1461         listener.postAppend(len, elapsedTime, e.getKey(), e.getEdit());
1462       }
1463     }
1464     return len;
1465   }
1466 
1467 
1468   /**
1469    * This method gets the datanode replication count for the current WAL.
1470    *
1471    * If the pipeline isn't started yet or is empty, you will get the default
1472    * replication factor.  Therefore, if this function returns 0, it means you
1473    * are not properly running with the HDFS-826 patch.
1474    * @throws InvocationTargetException
1475    * @throws IllegalAccessException
1476    * @throws IllegalArgumentException
1477    *
1478    * @throws Exception
1479    */
1480   @VisibleForTesting
1481   int getLogReplication() {
1482     try {
1483       //in standalone mode, it will return 0
1484       if (this.hdfs_out instanceof HdfsDataOutputStream) {
1485         return ((HdfsDataOutputStream) this.hdfs_out).getCurrentBlockReplication();
1486       }
1487     } catch (IOException e) {
1488       LOG.info("", e);
1489     }
1490     return 0;
1491   }
1492 
1493   @Override
1494   public void sync() throws IOException {
1495     TraceScope scope = Trace.startSpan("FSHLog.sync");
1496     try {
1497       scope = Trace.continueSpan(publishSyncThenBlockOnCompletion(scope.detach()));
1498     } finally {
1499       assert scope == NullScope.INSTANCE || !scope.isDetached();
1500       scope.close();
1501     }
1502   }
1503 
1504   @Override
1505   public void sync(long txid) throws IOException {
1506     if (this.highestSyncedSequence.get() >= txid){
1507       // Already sync'd.
1508       return;
1509     }
1510     TraceScope scope = Trace.startSpan("FSHLog.sync");
1511     try {
1512       scope = Trace.continueSpan(publishSyncThenBlockOnCompletion(scope.detach()));
1513     } finally {
1514       assert scope == NullScope.INSTANCE || !scope.isDetached();
1515       scope.close();
1516     }
1517   }
1518 
1519   // public only until class moves to o.a.h.h.wal
1520   public void requestLogRoll() {
1521     requestLogRoll(false);
1522   }
1523 
1524   private void requestLogRoll(boolean tooFewReplicas) {
1525     if (!this.listeners.isEmpty()) {
1526       for (WALActionsListener i: this.listeners) {
1527         i.logRollRequested(tooFewReplicas);
1528       }
1529     }
1530   }
1531 
1532   // public only until class moves to o.a.h.h.wal
1533   /** @return the number of rolled log files */
1534   public int getNumRolledLogFiles() {
1535     return byWalRegionSequenceIds.size();
1536   }
1537 
1538   // public only until class moves to o.a.h.h.wal
1539   /** @return the number of log files in use */
1540   public int getNumLogFiles() {
1541     // +1 for current use log
1542     return getNumRolledLogFiles() + 1;
1543   }
1544 
1545   // public only until class moves to o.a.h.h.wal
1546   /** @return the size of log files in use */
1547   public long getLogFileSize() {
1548     return this.totalLogSize.get();
1549   }
1550 
1551   @Override
1552   public Long startCacheFlush(final byte[] encodedRegionName, Set<byte[]> families) {
1553     if (!closeBarrier.beginOp()) {
1554       LOG.info("Flush not started for " + Bytes.toString(encodedRegionName) + "; server closing.");
1555       return null;
1556     }
1557     return this.sequenceIdAccounting.startCacheFlush(encodedRegionName, families);
1558   }
1559 
1560   @Override
1561   public void completeCacheFlush(final byte [] encodedRegionName) {
1562     this.sequenceIdAccounting.completeCacheFlush(encodedRegionName);
1563     closeBarrier.endOp();
1564   }
1565 
1566   @Override
1567   public void abortCacheFlush(byte[] encodedRegionName) {
1568     this.sequenceIdAccounting.abortCacheFlush(encodedRegionName);
1569     closeBarrier.endOp();
1570   }
1571 
1572   @VisibleForTesting
1573   boolean isLowReplicationRollEnabled() {
1574       return lowReplicationRollEnabled;
1575   }
1576 
1577   public static final long FIXED_OVERHEAD = ClassSize.align(
1578     ClassSize.OBJECT + (5 * ClassSize.REFERENCE) +
1579     ClassSize.ATOMIC_INTEGER + Bytes.SIZEOF_INT + (3 * Bytes.SIZEOF_LONG));
1580 
1581   private static void split(final Configuration conf, final Path p)
1582   throws IOException {
1583     FileSystem fs = FileSystem.get(conf);
1584     if (!fs.exists(p)) {
1585       throw new FileNotFoundException(p.toString());
1586     }
1587     if (!fs.getFileStatus(p).isDirectory()) {
1588       throw new IOException(p + " is not a directory");
1589     }
1590 
1591     final Path baseDir = FSUtils.getRootDir(conf);
1592     final Path archiveDir = new Path(baseDir, HConstants.HREGION_OLDLOGDIR_NAME);
1593     WALSplitter.split(baseDir, p, archiveDir, fs, conf, WALFactory.getInstance(conf));
1594   }
1595 
1596 
1597   @Override
1598   public long getEarliestMemstoreSeqNum(byte[] encodedRegionName) {
1599     // Used by tests. Deprecated as too subtle for general usage.
1600     return this.sequenceIdAccounting.getLowestSequenceId(encodedRegionName);
1601   }
1602 
1603   @Override
1604   public long getEarliestMemstoreSeqNum(byte[] encodedRegionName, byte[] familyName) {
1605     // This method is used by tests and for figuring if we should flush or not because our
1606     // sequenceids are too old. It is also used reporting the master our oldest sequenceid for use
1607     // figuring what edits can be skipped during log recovery. getEarliestMemStoreSequenceId
1608     // from this.sequenceIdAccounting is looking first in flushingOldestStoreSequenceIds, the
1609     // currently flushing sequence ids, and if anything found there, it is returning these. This is
1610     // the right thing to do for the reporting oldest sequenceids to master; we won't skip edits if
1611     // we crash during the flush. For figuring what to flush, we might get requeued if our sequence
1612     // id is old even though we are currently flushing. This may mean we do too much flushing.
1613     return this.sequenceIdAccounting.getLowestSequenceId(encodedRegionName, familyName);
1614   }
1615 
1616   /**
1617    * This class is used coordinating two threads holding one thread at a
1618    * 'safe point' while the orchestrating thread does some work that requires the first thread
1619    * paused: e.g. holding the WAL writer while its WAL is swapped out from under it by another
1620    * thread.
1621    *
1622    * <p>Thread A signals Thread B to hold when it gets to a 'safe point'.  Thread A wait until
1623    * Thread B gets there. When the 'safe point' has been attained, Thread B signals Thread A.
1624    * Thread B then holds at the 'safe point'.  Thread A on notification that Thread B is paused,
1625    * goes ahead and does the work it needs to do while Thread B is holding.  When Thread A is done,
1626    * it flags B and then Thread A and Thread B continue along on their merry way.  Pause and
1627    * signalling 'zigzags' between the two participating threads.  We use two latches -- one the
1628    * inverse of the other -- pausing and signaling when states are achieved.
1629    *
1630    * <p>To start up the drama, Thread A creates an instance of this class each time it would do
1631    * this zigzag dance and passes it to Thread B (these classes use Latches so it is one shot
1632    * only). Thread B notices the new instance (via reading a volatile reference or how ever) and it
1633    * starts to work toward the 'safe point'.  Thread A calls {@link #waitSafePoint()} when it
1634    * cannot proceed until the Thread B 'safe point' is attained. Thread A will be held inside in
1635    * {@link #waitSafePoint()} until Thread B reaches the 'safe point'.  Once there, Thread B
1636    * frees Thread A by calling {@link #safePointAttained()}.  Thread A now knows Thread B
1637    * is at the 'safe point' and that it is holding there (When Thread B calls
1638    * {@link #safePointAttained()} it blocks here until Thread A calls {@link #releaseSafePoint()}).
1639    * Thread A proceeds to do what it needs to do while Thread B is paused.  When finished,
1640    * it lets Thread B lose by calling {@link #releaseSafePoint()} and away go both Threads again.
1641    */
1642   static class SafePointZigZagLatch {
1643     /**
1644      * Count down this latch when safe point attained.
1645      */
1646     private volatile CountDownLatch safePointAttainedLatch = new CountDownLatch(1);
1647     /**
1648      * Latch to wait on.  Will be released when we can proceed.
1649      */
1650     private volatile CountDownLatch safePointReleasedLatch = new CountDownLatch(1);
1651 
1652     private void checkIfSyncFailed(SyncFuture syncFuture) throws FailedSyncBeforeLogCloseException {
1653       if (syncFuture.isThrowable()) {
1654         throw new FailedSyncBeforeLogCloseException(syncFuture.getThrowable());
1655       }
1656     }
1657 
1658     /**
1659      * For Thread A to call when it is ready to wait on the 'safe point' to be attained. Thread A
1660      * will be held in here until Thread B calls {@link #safePointAttained()}
1661      * @param syncFuture We need this as barometer on outstanding syncs.  If it comes home with an
1662      *          exception, then something is up w/ our syncing.
1663      * @return The passed <code>syncFuture</code>
1664      */
1665     SyncFuture waitSafePoint(SyncFuture syncFuture) throws InterruptedException,
1666         FailedSyncBeforeLogCloseException {
1667       while (!this.safePointAttainedLatch.await(1, TimeUnit.MILLISECONDS)) {
1668         checkIfSyncFailed(syncFuture);
1669       }
1670       checkIfSyncFailed(syncFuture);
1671       return syncFuture;
1672     }
1673 
1674     /**
1675      * Called by Thread B when it attains the 'safe point'.  In this method, Thread B signals
1676      * Thread A it can proceed. Thread B will be held in here until {@link #releaseSafePoint()}
1677      * is called by Thread A.
1678      * @throws InterruptedException
1679      */
1680     void safePointAttained() throws InterruptedException {
1681       this.safePointAttainedLatch.countDown();
1682       this.safePointReleasedLatch.await();
1683     }
1684 
1685     /**
1686      * Called by Thread A when it is done with the work it needs to do while Thread B is
1687      * halted.  This will release the Thread B held in a call to {@link #safePointAttained()}
1688      */
1689     void releaseSafePoint() {
1690       this.safePointReleasedLatch.countDown();
1691     }
1692 
1693     /**
1694      * @return True is this is a 'cocked', fresh instance, and not one that has already fired.
1695      */
1696     boolean isCocked() {
1697       return this.safePointAttainedLatch.getCount() > 0 &&
1698         this.safePointReleasedLatch.getCount() > 0;
1699     }
1700   }
1701 
1702   /**
1703    * Handler that is run by the disruptor ringbuffer consumer. Consumer is a SINGLE
1704    * 'writer/appender' thread.  Appends edits and starts up sync runs.  Tries its best to batch up
1705    * syncs.  There is no discernible benefit batching appends so we just append as they come in
1706    * because it simplifies the below implementation.  See metrics for batching effectiveness
1707    * (In measurement, at 100 concurrent handlers writing 1k, we are batching > 10 appends and 10
1708    * handler sync invocations for every actual dfsclient sync call; at 10 concurrent handlers,
1709    * YMMV).
1710    * <p>Herein, we have an array into which we store the sync futures as they come in.  When we
1711    * have a 'batch', we'll then pass what we have collected to a SyncRunner thread to do the
1712    * filesystem sync.  When it completes, it will then call
1713    * {@link SyncFuture#done(long, Throwable)} on each of SyncFutures in the batch to release
1714    * blocked Handler threads.
1715    * <p>I've tried various effects to try and make latencies low while keeping throughput high.
1716    * I've tried keeping a single Queue of SyncFutures in this class appending to its tail as the
1717    * syncs coming and having sync runner threads poll off the head to 'finish' completed
1718    * SyncFutures.  I've tried linkedlist, and various from concurrent utils whether
1719    * LinkedBlockingQueue or ArrayBlockingQueue, etc.  The more points of synchronization, the
1720    * more 'work' (according to 'perf stats') that has to be done; small increases in stall
1721    * percentages seem to have a big impact on throughput/latencies.  The below model where we have
1722    * an array into which we stash the syncs and then hand them off to the sync thread seemed like
1723    * a decent compromise.  See HBASE-8755 for more detail.
1724    */
1725   class RingBufferEventHandler implements EventHandler<RingBufferTruck>, LifecycleAware {
1726     private final SyncRunner [] syncRunners;
1727     private final SyncFuture [] syncFutures;
1728     // Had 'interesting' issues when this was non-volatile.  On occasion, we'd not pass all
1729     // syncFutures to the next sync'ing thread.
1730     private volatile int syncFuturesCount = 0;
1731     private volatile SafePointZigZagLatch zigzagLatch;
1732     /**
1733      * Set if we get an exception appending or syncing so that all subsequence appends and syncs
1734      * on this WAL fail until WAL is replaced.
1735      */
1736     private Exception exception = null;
1737     /**
1738      * Object to block on while waiting on safe point.
1739      */
1740     private final Object safePointWaiter = new Object();
1741     private volatile boolean shutdown = false;
1742 
1743     /**
1744      * Which syncrunner to use next.
1745      */
1746     private int syncRunnerIndex;
1747 
1748     RingBufferEventHandler(final int syncRunnerCount, final int maxHandlersCount) {
1749       this.syncFutures = new SyncFuture[maxHandlersCount];
1750       this.syncRunners = new SyncRunner[syncRunnerCount];
1751       for (int i = 0; i < syncRunnerCount; i++) {
1752         this.syncRunners[i] = new SyncRunner("sync." + i, maxHandlersCount);
1753       }
1754     }
1755 
1756     private void cleanupOutstandingSyncsOnException(final long sequence, final Exception e) {
1757       // There could be handler-count syncFutures outstanding.
1758       for (int i = 0; i < this.syncFuturesCount; i++) this.syncFutures[i].done(sequence, e);
1759       this.syncFuturesCount = 0;
1760     }
1761 
1762     /**
1763      * @return True if outstanding sync futures still
1764      */
1765     private boolean isOutstandingSyncs() {
1766       // Look at SyncFutures in the EventHandler
1767       for (int i = 0; i < this.syncFuturesCount; i++) {
1768         if (!this.syncFutures[i].isDone()) return true;
1769       }
1770 
1771       return false;
1772     }
1773 
1774     private boolean isOutstandingSyncsFromRunners() {
1775       // Look at SyncFutures in the SyncRunners
1776       for (SyncRunner syncRunner: syncRunners) {
1777         if(syncRunner.isAlive() && !syncRunner.areSyncFuturesReleased()) {
1778           return true;
1779         }
1780       }
1781       return false;
1782     }
1783 
1784     @Override
1785     // We can set endOfBatch in the below method if at end of our this.syncFutures array
1786     public void onEvent(final RingBufferTruck truck, final long sequence, boolean endOfBatch)
1787     throws Exception {
1788       // Appends and syncs are coming in order off the ringbuffer.  We depend on this fact.  We'll
1789       // add appends to dfsclient as they come in.  Batching appends doesn't give any significant
1790       // benefit on measurement.  Handler sync calls we will batch up. If we get an exception
1791       // appending an edit, we fail all subsequent appends and syncs with the same exception until
1792       // the WAL is reset. It is important that we not short-circuit and exit early this method.
1793       // It is important that we always go through the attainSafePoint on the end. Another thread,
1794       // the log roller may be waiting on a signal from us here and will just hang without it.
1795 
1796       try {
1797         if (truck.hasSyncFuturePayload()) {
1798           this.syncFutures[this.syncFuturesCount++] = truck.unloadSyncFuturePayload();
1799           // Force flush of syncs if we are carrying a full complement of syncFutures.
1800           if (this.syncFuturesCount == this.syncFutures.length) endOfBatch = true;
1801         } else if (truck.hasFSWALEntryPayload()) {
1802           TraceScope scope = Trace.continueSpan(truck.unloadSpanPayload());
1803           try {
1804             FSWALEntry entry = truck.unloadFSWALEntryPayload();
1805             if (this.exception != null) {
1806               // We got an exception on an earlier attempt at append. Do not let this append
1807               // go through. Fail it but stamp the sequenceid into this append though failed.
1808               // We need to do this to close the latch held down deep in WALKey...that is waiting
1809               // on sequenceid assignment otherwise it will just hang out (The #append method
1810               // called below does this also internally).
1811               entry.stampRegionSequenceId();
1812               // Return to keep processing events coming off the ringbuffer
1813               return;
1814             }
1815             append(entry);
1816           } catch (Exception e) {
1817             // Failed append. Record the exception.
1818             this.exception = e;
1819             // invoking cleanupOutstandingSyncsOnException when append failed with exception,
1820             // it will cleanup existing sync requests recorded in syncFutures but not offered to SyncRunner yet,
1821             // so there won't be any sync future left over if no further truck published to disruptor.
1822             cleanupOutstandingSyncsOnException(sequence,
1823                 this.exception instanceof DamagedWALException ? this.exception
1824                     : new DamagedWALException("On sync", this.exception));
1825             // Return to keep processing events coming off the ringbuffer
1826             return;
1827           } finally {
1828             assert scope == NullScope.INSTANCE || !scope.isDetached();
1829             scope.close(); // append scope is complete
1830           }
1831         } else {
1832           // What is this if not an append or sync. Fail all up to this!!!
1833           cleanupOutstandingSyncsOnException(sequence,
1834             new IllegalStateException("Neither append nor sync"));
1835           // Return to keep processing.
1836           return;
1837         }
1838 
1839         // TODO: Check size and if big go ahead and call a sync if we have enough data.
1840         // This is a sync. If existing exception, fall through. Else look to see if batch.
1841         if (this.exception == null) {
1842           // If not a batch, return to consume more events from the ring buffer before proceeding;
1843           // we want to get up a batch of syncs and appends before we go do a filesystem sync.
1844           if (!endOfBatch || this.syncFuturesCount <= 0) return;
1845           // syncRunnerIndex is bound to the range [0, Integer.MAX_INT - 1] as follows:
1846           //   * The maximum value possible for syncRunners.length is Integer.MAX_INT
1847           //   * syncRunnerIndex starts at 0 and is incremented only here
1848           //   * after the increment, the value is bounded by the '%' operator to [0, syncRunners.length),
1849           //     presuming the value was positive prior to the '%' operator.
1850           //   * after being bound to [0, Integer.MAX_INT - 1], the new value is stored in syncRunnerIndex
1851           //     ensuring that it can't grow without bound and overflow.
1852           //   * note that the value after the increment must be positive, because the most it could have
1853           //     been prior was Integer.MAX_INT - 1 and we only increment by 1.
1854           this.syncRunnerIndex = (this.syncRunnerIndex + 1) % this.syncRunners.length;
1855           try {
1856             // Below expects that the offer 'transfers' responsibility for the outstanding syncs to
1857             // the syncRunner. We should never get an exception in here.
1858             this.syncRunners[this.syncRunnerIndex].offer(sequence, this.syncFutures,
1859               this.syncFuturesCount);
1860           } catch (Exception e) {
1861             // Should NEVER get here.
1862             requestLogRoll();
1863             this.exception = new DamagedWALException("Failed offering sync", e);
1864           }
1865         }
1866         // We may have picked up an exception above trying to offer sync
1867         if (this.exception != null) {
1868           cleanupOutstandingSyncsOnException(sequence,
1869             this.exception instanceof DamagedWALException?
1870               this.exception:
1871               new DamagedWALException("On sync", this.exception));
1872         }
1873         attainSafePoint(sequence);
1874         this.syncFuturesCount = 0;
1875       } catch (Throwable t) {
1876         LOG.error("UNEXPECTED!!! syncFutures.length=" + this.syncFutures.length, t);
1877       }
1878     }
1879 
1880     SafePointZigZagLatch attainSafePoint() {
1881       this.zigzagLatch = new SafePointZigZagLatch();
1882       return this.zigzagLatch;
1883     }
1884 
1885     /**
1886      * Check if we should attain safe point.  If so, go there and then wait till signalled before
1887      * we proceeding.
1888      */
1889     private void attainSafePoint(final long currentSequence) {
1890       if (this.zigzagLatch == null || !this.zigzagLatch.isCocked()) return;
1891       // If here, another thread is waiting on us to get to safe point.  Don't leave it hanging.
1892       beforeWaitOnSafePoint();
1893       try {
1894         // Wait on outstanding syncers; wait for them to finish syncing (unless we've been
1895         // shutdown or unless our latch has been thrown because we have been aborted or unless
1896         // this WAL is broken and we can't get a sync/append to complete).
1897         while ((!this.shutdown && this.zigzagLatch.isCocked()
1898             && highestSyncedSequence.get() < currentSequence &&
1899             // We could be in here and all syncs are failing or failed. Check for this. Otherwise
1900             // we'll just be stuck here for ever. In other words, ensure there syncs running.
1901             isOutstandingSyncs())
1902             // Wait for all SyncRunners to finish their work so that we can replace the writer
1903             || isOutstandingSyncsFromRunners()) {
1904           synchronized (this.safePointWaiter) {
1905             this.safePointWaiter.wait(0, 1);
1906           }
1907         }
1908         // Tell waiting thread we've attained safe point. Can clear this.throwable if set here
1909         // because we know that next event through the ringbuffer will be going to a new WAL
1910         // after we do the zigzaglatch dance.
1911         this.exception = null;
1912         this.zigzagLatch.safePointAttained();
1913       } catch (InterruptedException e) {
1914         LOG.warn("Interrupted ", e);
1915         Thread.currentThread().interrupt();
1916       }
1917     }
1918 
1919     /**
1920      * Append to the WAL.  Does all CP and WAL listener calls.
1921      * @param entry
1922      * @throws Exception
1923      */
1924     void append(final FSWALEntry entry) throws Exception {
1925       // TODO: WORK ON MAKING THIS APPEND FASTER. DOING WAY TOO MUCH WORK WITH CPs, PBing, etc.
1926       atHeadOfRingBufferEventHandlerAppend();
1927 
1928       long start = EnvironmentEdgeManager.currentTime();
1929       byte [] encodedRegionName = entry.getKey().getEncodedRegionName();
1930       long regionSequenceId = WALKey.NO_SEQUENCE_ID;
1931       try {
1932         // We are about to append this edit; update the region-scoped sequence number.  Do it
1933         // here inside this single appending/writing thread.  Events are ordered on the ringbuffer
1934         // so region sequenceids will also be in order.
1935         regionSequenceId = entry.stampRegionSequenceId();
1936         // Edits are empty, there is nothing to append.  Maybe empty when we are looking for a
1937         // region sequence id only, a region edit/sequence id that is not associated with an actual
1938         // edit. It has to go through all the rigmarole to be sure we have the right ordering.
1939         if (entry.getEdit().isEmpty()) {
1940           return;
1941         }
1942 
1943         // Coprocessor hook.
1944         if (!coprocessorHost.preWALWrite(entry.getHRegionInfo(), entry.getKey(),
1945             entry.getEdit())) {
1946           if (entry.getEdit().isReplay()) {
1947             // Set replication scope null so that this won't be replicated
1948             entry.getKey().setScopes(null);
1949           }
1950         }
1951         if (!listeners.isEmpty()) {
1952           for (WALActionsListener i: listeners) {
1953             // TODO: Why does listener take a table description and CPs take a regioninfo?  Fix.
1954             i.visitLogEntryBeforeWrite(entry.getHTableDescriptor(), entry.getKey(),
1955               entry.getEdit());
1956           }
1957         }
1958 
1959         writer.append(entry);
1960         assert highestUnsyncedSequence < entry.getSequence();
1961         highestUnsyncedSequence = entry.getSequence();
1962         sequenceIdAccounting.update(encodedRegionName, entry.getFamilyNames(), regionSequenceId,
1963           entry.isInMemstore());
1964         coprocessorHost.postWALWrite(entry.getHRegionInfo(), entry.getKey(), entry.getEdit());
1965         // Update metrics.
1966         postAppend(entry, EnvironmentEdgeManager.currentTime() - start);
1967       } catch (Exception e) {
1968         String msg = "Append sequenceId=" + regionSequenceId + ", requesting roll of WAL";
1969         LOG.warn(msg, e);
1970         requestLogRoll();
1971         throw new DamagedWALException(msg, e);
1972       }
1973       numEntries.incrementAndGet();
1974     }
1975 
1976     @Override
1977     public void onStart() {
1978       for (SyncRunner syncRunner: this.syncRunners) syncRunner.start();
1979     }
1980 
1981     @Override
1982     public void onShutdown() {
1983       for (SyncRunner syncRunner: this.syncRunners) syncRunner.interrupt();
1984     }
1985   }
1986 
1987   /**
1988    * Exposed for testing only.  Use to tricks like halt the ring buffer appending.
1989    */
1990   @VisibleForTesting
1991   void atHeadOfRingBufferEventHandlerAppend() {
1992     // Noop
1993   }
1994 
1995   private static IOException ensureIOException(final Throwable t) {
1996     return (t instanceof IOException)? (IOException)t: new IOException(t);
1997   }
1998 
1999   private static void usage() {
2000     System.err.println("Usage: FSHLog <ARGS>");
2001     System.err.println("Arguments:");
2002     System.err.println(" --dump  Dump textual representation of passed one or more files");
2003     System.err.println("         For example: " +
2004       "FSHLog --dump hdfs://example.com:9000/hbase/.logs/MACHINE/LOGFILE");
2005     System.err.println(" --split Split the passed directory of WAL logs");
2006     System.err.println("         For example: " +
2007       "FSHLog --split hdfs://example.com:9000/hbase/.logs/DIR");
2008   }
2009 
2010   /**
2011    * Pass one or more log file names and it will either dump out a text version
2012    * on <code>stdout</code> or split the specified log files.
2013    *
2014    * @param args
2015    * @throws IOException
2016    */
2017   public static void main(String[] args) throws IOException {
2018     if (args.length < 2) {
2019       usage();
2020       System.exit(-1);
2021     }
2022     // either dump using the WALPrettyPrinter or split, depending on args
2023     if (args[0].compareTo("--dump") == 0) {
2024       WALPrettyPrinter.run(Arrays.copyOfRange(args, 1, args.length));
2025     } else if (args[0].compareTo("--perf") == 0) {
2026       LOG.fatal("Please use the WALPerformanceEvaluation tool instead. i.e.:");
2027       LOG.fatal("\thbase org.apache.hadoop.hbase.wal.WALPerformanceEvaluation --iterations " +
2028           args[1]);
2029       System.exit(-1);
2030     } else if (args[0].compareTo("--split") == 0) {
2031       Configuration conf = HBaseConfiguration.create();
2032       for (int i = 1; i < args.length; i++) {
2033         try {
2034           Path logPath = new Path(args[i]);
2035           FSUtils.setFsDefault(conf, logPath);
2036           split(conf, logPath);
2037         } catch (IOException t) {
2038           t.printStackTrace(System.err);
2039           System.exit(-1);
2040         }
2041       }
2042     } else {
2043       usage();
2044       System.exit(-1);
2045     }
2046   }
2047 
2048   /**
2049    * This method gets the pipeline for the current WAL.
2050    */
2051   @VisibleForTesting
2052   DatanodeInfo[] getPipeLine() {
2053     if (this.hdfs_out != null) {
2054       if (this.hdfs_out.getWrappedStream() instanceof DFSOutputStream) {
2055         return ((DFSOutputStream) this.hdfs_out.getWrappedStream()).getPipeline();
2056       }
2057     }
2058     return new DatanodeInfo[0];
2059   }
2060 }