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