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