View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.wal;
20  
21  import java.io.EOFException;
22  import java.io.FileNotFoundException;
23  import java.io.IOException;
24  import java.io.InterruptedIOException;
25  import java.text.ParseException;
26  import java.util.ArrayList;
27  import java.util.Collections;
28  import java.util.HashMap;
29  import java.util.HashSet;
30  import java.util.LinkedList;
31  import java.util.List;
32  import java.util.Map;
33  import java.util.NavigableSet;
34  import java.util.Set;
35  import java.util.TreeMap;
36  import java.util.TreeSet;
37  import java.util.UUID;
38  import java.util.concurrent.Callable;
39  import java.util.concurrent.CompletionService;
40  import java.util.concurrent.ConcurrentHashMap;
41  import java.util.concurrent.ExecutionException;
42  import java.util.concurrent.ExecutorCompletionService;
43  import java.util.concurrent.Future;
44  import java.util.concurrent.ThreadFactory;
45  import java.util.concurrent.ThreadPoolExecutor;
46  import java.util.concurrent.TimeUnit;
47  import java.util.concurrent.atomic.AtomicBoolean;
48  import java.util.concurrent.atomic.AtomicLong;
49  import java.util.concurrent.atomic.AtomicReference;
50  import java.util.regex.Matcher;
51  import java.util.regex.Pattern;
52  
53  import org.apache.commons.logging.Log;
54  import org.apache.commons.logging.LogFactory;
55  import org.apache.hadoop.conf.Configuration;
56  import org.apache.hadoop.fs.FileAlreadyExistsException;
57  import org.apache.hadoop.fs.FileStatus;
58  import org.apache.hadoop.fs.FileSystem;
59  import org.apache.hadoop.fs.Path;
60  import org.apache.hadoop.fs.PathFilter;
61  import org.apache.hadoop.hbase.Cell;
62  import org.apache.hadoop.hbase.CellScanner;
63  import org.apache.hadoop.hbase.CellUtil;
64  import org.apache.hadoop.hbase.CoordinatedStateException;
65  import org.apache.hadoop.hbase.CoordinatedStateManager;
66  import org.apache.hadoop.hbase.HBaseConfiguration;
67  import org.apache.hadoop.hbase.HConstants;
68  import org.apache.hadoop.hbase.HRegionInfo;
69  import org.apache.hadoop.hbase.HRegionLocation;
70  import org.apache.hadoop.hbase.RemoteExceptionHandler;
71  import org.apache.hadoop.hbase.ServerName;
72  import org.apache.hadoop.hbase.TableName;
73  import org.apache.hadoop.hbase.TableNotFoundException;
74  import org.apache.hadoop.hbase.TableStateManager;
75  import org.apache.hadoop.hbase.classification.InterfaceAudience;
76  import org.apache.hadoop.hbase.client.ConnectionUtils;
77  import org.apache.hadoop.hbase.client.Delete;
78  import org.apache.hadoop.hbase.client.Durability;
79  import org.apache.hadoop.hbase.client.HConnection;
80  import org.apache.hadoop.hbase.client.HConnectionManager;
81  import org.apache.hadoop.hbase.client.Mutation;
82  import org.apache.hadoop.hbase.client.Put;
83  import org.apache.hadoop.hbase.coordination.BaseCoordinatedStateManager;
84  import org.apache.hadoop.hbase.coordination.ZKSplitLogManagerCoordination;
85  import org.apache.hadoop.hbase.exceptions.RegionOpeningException;
86  import org.apache.hadoop.hbase.io.HeapSize;
87  import org.apache.hadoop.hbase.master.SplitLogManager;
88  import org.apache.hadoop.hbase.monitoring.MonitoredTask;
89  import org.apache.hadoop.hbase.monitoring.TaskMonitor;
90  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
91  import org.apache.hadoop.hbase.protobuf.RequestConverter;
92  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService.BlockingInterface;
93  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoRequest;
94  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse;
95  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.WALEntry;
96  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.MutationType;
97  import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.RegionStoreSequenceIds;
98  import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.StoreSequenceId;
99  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
100 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor;
101 import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
102 import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.SplitLogTask.RecoveryMode;
103 import org.apache.hadoop.hbase.regionserver.HRegion;
104 import org.apache.hadoop.hbase.regionserver.LastSequenceId;
105 // imports for things that haven't moved from regionserver.wal yet.
106 import org.apache.hadoop.hbase.regionserver.wal.FSHLog;
107 import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
108 import org.apache.hadoop.hbase.regionserver.wal.WALCellCodec;
109 import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
110 import org.apache.hadoop.hbase.regionserver.wal.WALEditsReplaySink;
111 import org.apache.hadoop.hbase.util.Bytes;
112 import org.apache.hadoop.hbase.util.CancelableProgressable;
113 import org.apache.hadoop.hbase.util.ClassSize;
114 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
115 import org.apache.hadoop.hbase.util.FSUtils;
116 import org.apache.hadoop.hbase.util.Pair;
117 import org.apache.hadoop.hbase.util.Threads;
118 import org.apache.hadoop.hbase.wal.WAL.Entry;
119 import org.apache.hadoop.hbase.wal.WAL.Reader;
120 import org.apache.hadoop.hbase.wal.WALProvider.Writer;
121 import org.apache.hadoop.hbase.zookeeper.ZKSplitLog;
122 import org.apache.hadoop.io.MultipleIOException;
123 
124 import com.google.common.annotations.VisibleForTesting;
125 import com.google.common.base.Preconditions;
126 import com.google.common.collect.Lists;
127 import com.google.protobuf.ServiceException;
128 import com.google.protobuf.TextFormat;
129 
130 /**
131  * This class is responsible for splitting up a bunch of regionserver commit log
132  * files that are no longer being written to, into new files, one per region for
133  * region to replay on startup. Delete the old log files when finished.
134  */
135 @InterfaceAudience.Private
136 @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="JLM_JSR166_UTILCONCURRENT_MONITORENTER",
137   justification="Synchronization on concurrent map is intended")
138 public class WALSplitter {
139   private static final Log LOG = LogFactory.getLog(WALSplitter.class);
140 
141   /** By default we retry errors in splitting, rather than skipping. */
142   public static final boolean SPLIT_SKIP_ERRORS_DEFAULT = false;
143 
144   // Parameters for split process
145   protected final Path walDir;
146   protected final FileSystem fs;
147   protected final Configuration conf;
148 
149   // Major subcomponents of the split process.
150   // These are separated into inner classes to make testing easier.
151   PipelineController controller;
152   OutputSink outputSink;
153   EntryBuffers entryBuffers;
154 
155   private Set<TableName> disablingOrDisabledTables =
156       new HashSet<TableName>();
157   private BaseCoordinatedStateManager csm;
158   private final WALFactory walFactory;
159 
160   private MonitoredTask status;
161 
162   // For checking the latest flushed sequence id
163   protected final LastSequenceId sequenceIdChecker;
164 
165   protected boolean distributedLogReplay;
166 
167   private final boolean splitWriterCreationBounded;
168 
169 
170   // Map encodedRegionName -> lastFlushedSequenceId
171   protected Map<String, Long> lastFlushedSequenceIds = new ConcurrentHashMap<String, Long>();
172 
173   // Map encodedRegionName -> maxSeqIdInStores
174   protected Map<String, Map<byte[], Long>> regionMaxSeqIdInStores =
175       new ConcurrentHashMap<String, Map<byte[], Long>>();
176 
177   // Failed region server that the wal file being split belongs to
178   protected String failedServerName = "";
179 
180   // Number of writer threads
181   private final int numWriterThreads;
182 
183   // Min batch size when replay WAL edits
184   private final int minBatchSize;
185 
186   // the file being split currently
187   private FileStatus fileBeingSplit;
188 
189   public final static String SPLIT_WRITER_CREATION_BOUNDED = "hbase.split.writer.creation.bounded";
190 
191   @VisibleForTesting
192   WALSplitter(final WALFactory factory, Configuration conf, Path walDir,
193       FileSystem fs, LastSequenceId idChecker,
194       CoordinatedStateManager csm, RecoveryMode mode) {
195     this.conf = HBaseConfiguration.create(conf);
196     String codecClassName = conf
197         .get(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, WALCellCodec.class.getName());
198     this.conf.set(HConstants.RPC_CODEC_CONF_KEY, codecClassName);
199     this.walDir = walDir;
200     this.fs = fs;
201     this.sequenceIdChecker = idChecker;
202     this.csm = (BaseCoordinatedStateManager)csm;
203     this.walFactory = factory;
204     this.controller = new PipelineController();
205     this.splitWriterCreationBounded = conf.getBoolean(SPLIT_WRITER_CREATION_BOUNDED, false);
206     entryBuffers = new EntryBuffers(controller,
207         this.conf.getInt("hbase.regionserver.hlog.splitlog.buffersize",
208             128*1024*1024), splitWriterCreationBounded);
209 
210     // a larger minBatchSize may slow down recovery because replay writer has to wait for
211     // enough edits before replaying them
212     this.minBatchSize = this.conf.getInt("hbase.regionserver.wal.logreplay.batch.size", 64);
213     this.distributedLogReplay = (RecoveryMode.LOG_REPLAY == mode);
214 
215     this.numWriterThreads = this.conf.getInt("hbase.regionserver.hlog.splitlog.writer.threads", 3);
216     if (csm != null && this.distributedLogReplay) {
217       outputSink = new LogReplayOutputSink(controller, entryBuffers, numWriterThreads);
218     } else {
219       if (this.distributedLogReplay) {
220         LOG.info("ZooKeeperWatcher is passed in as NULL so disable distrubitedLogRepaly.");
221       }
222       this.distributedLogReplay = false;
223       if(splitWriterCreationBounded){
224         outputSink = new BoundedLogWriterCreationOutputSink(controller,
225             entryBuffers, numWriterThreads);
226       }else {
227         outputSink = new LogRecoveredEditsOutputSink(controller, entryBuffers, numWriterThreads);
228       }
229     }
230 
231   }
232 
233   /**
234    * Splits a WAL file into region's recovered-edits directory.
235    * This is the main entry point for distributed log splitting from SplitLogWorker.
236    * <p>
237    * If the log file has N regions then N recovered.edits files will be produced.
238    * <p>
239    * @param rootDir
240    * @param logfile
241    * @param fs
242    * @param conf
243    * @param reporter
244    * @param idChecker
245    * @param cp coordination state manager
246    * @return false if it is interrupted by the progress-able.
247    * @throws IOException
248    */
249   public static boolean splitLogFile(Path walDir, FileStatus logfile, FileSystem fs,
250       Configuration conf, CancelableProgressable reporter, LastSequenceId idChecker,
251       CoordinatedStateManager cp, RecoveryMode mode, final WALFactory factory) throws IOException {
252     WALSplitter s = new WALSplitter(factory, conf, walDir, fs, idChecker, cp, mode);
253     return s.splitLogFile(logfile, reporter);
254   }
255 
256   // A wrapper to split one log folder using the method used by distributed
257   // log splitting. Used by tools and unit tests. It should be package private.
258   // It is public only because UpgradeTo96 and TestWALObserver are in different packages,
259   // which uses this method to do log splitting.
260   public static List<Path> split(Path walRootDir, Path logDir, Path oldLogDir,
261       FileSystem walFs, Configuration conf, final WALFactory factory) throws IOException {
262     final FileStatus[] logfiles = SplitLogManager.getFileList(conf,
263         Collections.singletonList(logDir), null);
264     List<Path> splits = new ArrayList<Path>();
265     if (logfiles != null && logfiles.length > 0) {
266       for (FileStatus logfile: logfiles) {
267         WALSplitter s = new WALSplitter(factory, conf, walRootDir, walFs, null, null,
268             RecoveryMode.LOG_SPLITTING);
269         if (s.splitLogFile(logfile, null)) {
270           finishSplitLogFile(walRootDir, oldLogDir, logfile.getPath(), conf);
271           if (s.outputSink.splits != null) {
272             splits.addAll(s.outputSink.splits);
273           }
274         }
275       }
276     }
277     if (!walFs.delete(logDir, true)) {
278       throw new IOException("Unable to delete src dir: " + logDir);
279     }
280     return splits;
281   }
282 
283   /**
284    * log splitting implementation, splits one log file.
285    * @param logfile should be an actual log file.
286    */
287   @VisibleForTesting
288   boolean splitLogFile(FileStatus logfile, CancelableProgressable reporter) throws IOException {
289     Preconditions.checkState(status == null);
290     Preconditions.checkArgument(logfile.isFile(),
291         "passed in file status is for something other than a regular file.");
292     boolean isCorrupted = false;
293     boolean skipErrors = conf.getBoolean("hbase.hlog.split.skip.errors",
294       SPLIT_SKIP_ERRORS_DEFAULT);
295     int interval = conf.getInt("hbase.splitlog.report.interval.loglines", 1024);
296     Path logPath = logfile.getPath();
297     boolean outputSinkStarted = false;
298     boolean progress_failed = false;
299     int editsCount = 0;
300     int editsSkipped = 0;
301 
302     status =
303         TaskMonitor.get().createStatus(
304           "Splitting log file " + logfile.getPath() + "into a temporary staging area.");
305     Reader in = null;
306     this.fileBeingSplit = logfile;
307     try {
308       long logLength = logfile.getLen();
309       LOG.info("Splitting wal: " + logPath + ", length=" + logLength);
310       LOG.info("DistributedLogReplay = " + this.distributedLogReplay);
311       status.setStatus("Opening log file");
312       if (reporter != null && !reporter.progress()) {
313         progress_failed = true;
314         return false;
315       }
316       try {
317         in = getReader(logfile, skipErrors, reporter);
318       } catch (CorruptedLogFileException e) {
319         LOG.warn("Could not get reader, corrupted log file " + logPath, e);
320         ZKSplitLog.markCorrupted(walDir, logfile.getPath().getName(), fs);
321         isCorrupted = true;
322       }
323       if (in == null) {
324         LOG.warn("Nothing to split in log file " + logPath);
325         return true;
326       }
327       if (csm != null) {
328         try {
329           TableStateManager tsm = csm.getTableStateManager();
330           disablingOrDisabledTables = tsm.getTablesInStates(
331           ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING);
332         } catch (CoordinatedStateException e) {
333           throw new IOException("Can't get disabling/disabled tables", e);
334         }
335       }
336       int numOpenedFilesBeforeReporting = conf.getInt("hbase.splitlog.report.openedfiles", 3);
337       int numOpenedFilesLastCheck = 0;
338       outputSink.setReporter(reporter);
339       outputSink.startWriterThreads();
340       outputSinkStarted = true;
341       Entry entry;
342       Long lastFlushedSequenceId = -1L;
343       ServerName serverName = DefaultWALProvider.getServerNameFromWALDirectoryName(logPath);
344       failedServerName = (serverName == null) ? "" : serverName.getServerName();
345       while ((entry = getNextLogLine(in, logPath, skipErrors)) != null) {
346         byte[] region = entry.getKey().getEncodedRegionName();
347         String encodedRegionNameAsStr = Bytes.toString(region);
348         lastFlushedSequenceId = lastFlushedSequenceIds.get(encodedRegionNameAsStr);
349         if (lastFlushedSequenceId == null) {
350           if (this.distributedLogReplay) {
351             RegionStoreSequenceIds ids =
352                 csm.getSplitLogWorkerCoordination().getRegionFlushedSequenceId(failedServerName,
353                   encodedRegionNameAsStr);
354             if (ids != null) {
355               lastFlushedSequenceId = ids.getLastFlushedSequenceId();
356               if (LOG.isDebugEnabled()) {
357                 LOG.debug("DLR Last flushed sequenceid for " + encodedRegionNameAsStr + ": " +
358                   TextFormat.shortDebugString(ids));
359               }
360             }
361           } else if (sequenceIdChecker != null) {
362             RegionStoreSequenceIds ids = sequenceIdChecker.getLastSequenceId(region);
363             Map<byte[], Long> maxSeqIdInStores = new TreeMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
364             for (StoreSequenceId storeSeqId : ids.getStoreSequenceIdList()) {
365               maxSeqIdInStores.put(storeSeqId.getFamilyName().toByteArray(),
366                 storeSeqId.getSequenceId());
367             }
368             regionMaxSeqIdInStores.put(encodedRegionNameAsStr, maxSeqIdInStores);
369             lastFlushedSequenceId = ids.getLastFlushedSequenceId();
370             if (LOG.isDebugEnabled()) {
371               LOG.debug("DLS Last flushed sequenceid for " + encodedRegionNameAsStr + ": " +
372                   TextFormat.shortDebugString(ids));
373             }
374           }
375           if (lastFlushedSequenceId == null) {
376             lastFlushedSequenceId = -1L;
377           }
378           lastFlushedSequenceIds.put(encodedRegionNameAsStr, lastFlushedSequenceId);
379         }
380         if (lastFlushedSequenceId >= entry.getKey().getLogSeqNum()) {
381           editsSkipped++;
382           continue;
383         }
384         // Don't send Compaction/Close/Open region events to recovered edit type sinks.
385         if (entry.getEdit().isMetaEdit() && !outputSink.keepRegionEvent(entry)) {
386           editsSkipped++;
387           continue;
388         }
389         entryBuffers.appendEntry(entry);
390         editsCount++;
391         int moreWritersFromLastCheck = this.getNumOpenWriters() - numOpenedFilesLastCheck;
392         // If sufficient edits have passed, check if we should report progress.
393         if (editsCount % interval == 0
394             || moreWritersFromLastCheck > numOpenedFilesBeforeReporting) {
395           numOpenedFilesLastCheck = this.getNumOpenWriters();
396           String countsStr = (editsCount - (editsSkipped + outputSink.getSkippedEdits()))
397               + " edits, skipped " + editsSkipped + " edits.";
398           status.setStatus("Split " + countsStr);
399           if (reporter != null && !reporter.progress()) {
400             progress_failed = true;
401             return false;
402           }
403         }
404       }
405     } catch (InterruptedException ie) {
406       IOException iie = new InterruptedIOException();
407       iie.initCause(ie);
408       throw iie;
409     } catch (CorruptedLogFileException e) {
410       LOG.warn("Could not parse, corrupted log file " + logPath, e);
411       csm.getSplitLogWorkerCoordination().markCorrupted(walDir,
412         logfile.getPath().getName(), fs);
413       isCorrupted = true;
414     } catch (IOException e) {
415       e = RemoteExceptionHandler.checkIOException(e);
416       throw e;
417     } finally {
418       LOG.debug("Finishing writing output logs and closing down.");
419       try {
420         if (null != in) {
421           in.close();
422         }
423       } catch (IOException exception) {
424         LOG.warn("Could not close wal reader: " + exception.getMessage());
425         LOG.debug("exception details", exception);
426       }
427       try {
428         if (outputSinkStarted) {
429           // Set progress_failed to true as the immediate following statement will reset its value
430           // when finishWritingAndClose() throws exception, progress_failed has the right value
431           progress_failed = true;
432           progress_failed = outputSink.finishWritingAndClose() == null;
433         }
434       } finally {
435         String msg =
436             "Processed " + editsCount + " edits across " + outputSink.getNumberOfRecoveredRegions()
437                 + " regions; edits skipped=" + editsSkipped + "; log file=" + logPath +
438                 ", length=" + logfile.getLen() + // See if length got updated post lease recovery
439                 ", corrupted=" + isCorrupted + ", progress failed=" + progress_failed;
440         LOG.info(msg);
441         status.markComplete(msg);
442       }
443     }
444     return !progress_failed;
445   }
446 
447   /**
448    * Completes the work done by splitLogFile by archiving logs
449    * <p>
450    * It is invoked by SplitLogManager once it knows that one of the
451    * SplitLogWorkers have completed the splitLogFile() part. If the master
452    * crashes then this function might get called multiple times.
453    * <p>
454    * @param logfile
455    * @param conf
456    * @throws IOException
457    */
458   public static void finishSplitLogFile(String logfile,
459       Configuration conf)  throws IOException {
460     Path rootdir = FSUtils.getWALRootDir(conf);
461     Path oldLogDir = new Path(rootdir, HConstants.HREGION_OLDLOGDIR_NAME);
462     Path logPath;
463     if (FSUtils.isStartingWithPath(rootdir, logfile)) {
464       logPath = new Path(logfile);
465     } else {
466       logPath = new Path(rootdir, logfile);
467     }
468     finishSplitLogFile(rootdir, oldLogDir, logPath, conf);
469   }
470 
471   private static void finishSplitLogFile(Path rootdir, Path oldLogDir,
472       Path logPath, Configuration conf) throws IOException {
473     List<Path> processedLogs = new ArrayList<Path>();
474     List<Path> corruptedLogs = new ArrayList<Path>();
475     FileSystem fs;
476     fs = rootdir.getFileSystem(conf);
477     if (ZKSplitLog.isCorrupted(rootdir, logPath.getName(), fs)) {
478       corruptedLogs.add(logPath);
479     } else {
480       processedLogs.add(logPath);
481     }
482     archiveLogs(corruptedLogs, processedLogs, oldLogDir, fs, conf);
483     Path stagingDir = ZKSplitLog.getSplitLogDir(rootdir, logPath.getName());
484     fs.delete(stagingDir, true);
485   }
486 
487   /**
488    * Moves processed logs to a oldLogDir after successful processing Moves
489    * corrupted logs (any log that couldn't be successfully parsed to corruptDir
490    * (.corrupt) for later investigation
491    *
492    * @param corruptedLogs
493    * @param processedLogs
494    * @param oldLogDir
495    * @param fs
496    * @param conf
497    * @throws IOException
498    */
499   private static void archiveLogs(
500       final List<Path> corruptedLogs,
501       final List<Path> processedLogs, final Path oldLogDir,
502       final FileSystem fs, final Configuration conf) throws IOException {
503     final Path corruptDir = new Path(FSUtils.getWALRootDir(conf), conf.get(
504         "hbase.regionserver.hlog.splitlog.corrupt.dir",  HConstants.CORRUPT_DIR_NAME));
505 
506     if (!fs.mkdirs(corruptDir)) {
507       LOG.info("Unable to mkdir " + corruptDir);
508     }
509     fs.mkdirs(oldLogDir);
510 
511     // this method can get restarted or called multiple times for archiving
512     // the same log files.
513     for (Path corrupted : corruptedLogs) {
514       Path p = new Path(corruptDir, corrupted.getName());
515       if (fs.exists(corrupted)) {
516         if (!fs.rename(corrupted, p)) {
517           LOG.warn("Unable to move corrupted log " + corrupted + " to " + p);
518         } else {
519           LOG.warn("Moved corrupted log " + corrupted + " to " + p);
520         }
521       }
522     }
523 
524     for (Path p : processedLogs) {
525       Path newPath = FSHLog.getWALArchivePath(oldLogDir, p);
526       if (fs.exists(p)) {
527         if (!FSUtils.renameAndSetModifyTime(fs, p, newPath)) {
528           LOG.warn("Unable to move  " + p + " to " + newPath);
529         } else {
530           LOG.info("Archived processed log " + p + " to " + newPath);
531         }
532       }
533     }
534   }
535 
536   /**
537    * Path to a file under RECOVERED_EDITS_DIR directory of the region found in
538    * <code>logEntry</code> named for the sequenceid in the passed
539    * <code>logEntry</code>: e.g. /hbase/some_table/2323432434/recovered.edits/2332.
540    * This method also ensures existence of RECOVERED_EDITS_DIR under the region
541    * creating it if necessary.
542    * @param logEntry
543    * @param fileNameBeingSplit the file being split currently. Used to generate tmp file name.
544    * @param conf
545    * @return Path to file into which to dump split log edits.
546    * @throws IOException
547    */
548   @SuppressWarnings("deprecation")
549   @VisibleForTesting
550   static Path getRegionSplitEditsPath(final Entry logEntry, String fileNameBeingSplit,
551       Configuration conf)
552   throws IOException {
553     FileSystem fs = FileSystem.get(conf);
554     Path rootDir = FSUtils.getRootDir(conf);
555     Path tableDir = FSUtils.getTableDir(rootDir, logEntry.getKey().getTablename());
556     String encodedRegionName = Bytes.toString(logEntry.getKey().getEncodedRegionName());
557     Path regiondir = HRegion.getRegionDir(tableDir, encodedRegionName);
558     Path dir = getRegionDirRecoveredEditsDir(regiondir);
559 
560     if (!fs.exists(regiondir)) {
561       LOG.info("This region's directory doesn't exist: "
562           + regiondir.toString() + ". It is very likely that it was" +
563           " already split so it's safe to discard those edits.");
564       return null;
565     }
566     if (fs.exists(dir) && fs.isFile(dir)) {
567       Path tmp = new Path("/tmp");
568       if (!fs.exists(tmp)) {
569         fs.mkdirs(tmp);
570       }
571       tmp = new Path(tmp,
572         HConstants.RECOVERED_EDITS_DIR + "_" + encodedRegionName);
573       LOG.warn("Found existing old file: " + dir + ". It could be some "
574         + "leftover of an old installation. It should be a folder instead. "
575         + "So moving it to " + tmp);
576       if (!fs.rename(dir, tmp)) {
577         LOG.warn("Failed to sideline old file " + dir);
578       }
579     }
580 
581     if (!fs.exists(dir) && !fs.mkdirs(dir)) {
582       LOG.warn("mkdir failed on " + dir);
583     }
584     // Append fileBeingSplit to prevent name conflict since we may have duplicate wal entries now.
585     // Append file name ends with RECOVERED_LOG_TMPFILE_SUFFIX to ensure
586     // region's replayRecoveredEdits will not delete it
587     String fileName = formatRecoveredEditsFileName(logEntry.getKey().getLogSeqNum());
588     fileName = getTmpRecoveredEditsFileName(fileName + "-" + fileNameBeingSplit);
589     return new Path(dir, fileName);
590   }
591 
592   private static String getTmpRecoveredEditsFileName(String fileName) {
593     return fileName + RECOVERED_LOG_TMPFILE_SUFFIX;
594   }
595 
596   /**
597    * Get the completed recovered edits file path, renaming it to be by last edit
598    * in the file from its first edit. Then we could use the name to skip
599    * recovered edits when doing {@link HRegion#replayRecoveredEditsIfAny}.
600    * @param srcPath
601    * @param maximumEditLogSeqNum
602    * @return dstPath take file's last edit log seq num as the name
603    */
604   private static Path getCompletedRecoveredEditsFilePath(Path srcPath,
605       long maximumEditLogSeqNum) {
606     String fileName = formatRecoveredEditsFileName(maximumEditLogSeqNum);
607     return new Path(srcPath.getParent(), fileName);
608   }
609 
610   @VisibleForTesting
611   static String formatRecoveredEditsFileName(final long seqid) {
612     return String.format("%019d", seqid);
613   }
614 
615   private static final Pattern EDITFILES_NAME_PATTERN = Pattern.compile("-?[0-9]+");
616   private static final String RECOVERED_LOG_TMPFILE_SUFFIX = ".temp";
617 
618   /**
619    * @param regiondir
620    *          This regions directory in the filesystem.
621    * @return The directory that holds recovered edits files for the region
622    *         <code>regiondir</code>
623    */
624   public static Path getRegionDirRecoveredEditsDir(final Path regiondir) {
625     return new Path(regiondir, HConstants.RECOVERED_EDITS_DIR);
626   }
627 
628   /**
629    * Returns sorted set of edit files made by splitter, excluding files
630    * with '.temp' suffix.
631    *
632    * @param fs
633    * @param regiondir
634    * @return Files in passed <code>regiondir</code> as a sorted set.
635    * @throws IOException
636    */
637   public static NavigableSet<Path> getSplitEditFilesSorted(final FileSystem fs,
638       final Path regiondir) throws IOException {
639     NavigableSet<Path> filesSorted = new TreeSet<Path>();
640     Path editsdir = getRegionDirRecoveredEditsDir(regiondir);
641     if (!fs.exists(editsdir))
642       return filesSorted;
643     FileStatus[] files = FSUtils.listStatus(fs, editsdir, new PathFilter() {
644       @Override
645       public boolean accept(Path p) {
646         boolean result = false;
647         try {
648           // Return files and only files that match the editfile names pattern.
649           // There can be other files in this directory other than edit files.
650           // In particular, on error, we'll move aside the bad edit file giving
651           // it a timestamp suffix. See moveAsideBadEditsFile.
652           Matcher m = EDITFILES_NAME_PATTERN.matcher(p.getName());
653           result = fs.isFile(p) && m.matches();
654           // Skip the file whose name ends with RECOVERED_LOG_TMPFILE_SUFFIX,
655           // because it means splitwal thread is writting this file.
656           if (p.getName().endsWith(RECOVERED_LOG_TMPFILE_SUFFIX)) {
657             result = false;
658           }
659           // Skip SeqId Files
660           if (isSequenceIdFile(p)) {
661             result = false;
662           }
663         } catch (IOException e) {
664           LOG.warn("Failed isFile check on " + p);
665         }
666         return result;
667       }
668     });
669     if (files == null) {
670       return filesSorted;
671     }
672     for (FileStatus status : files) {
673       filesSorted.add(status.getPath());
674     }
675     return filesSorted;
676   }
677 
678   /**
679    * Move aside a bad edits file.
680    *
681    * @param fs
682    * @param edits
683    *          Edits file to move aside.
684    * @return The name of the moved aside file.
685    * @throws IOException
686    */
687   public static Path moveAsideBadEditsFile(final FileSystem fs, final Path edits)
688       throws IOException {
689     Path moveAsideName = new Path(edits.getParent(), edits.getName() + "."
690         + System.currentTimeMillis());
691     if (!fs.rename(edits, moveAsideName)) {
692       LOG.warn("Rename failed from " + edits + " to " + moveAsideName);
693     }
694     return moveAsideName;
695   }
696 
697   private static final String SEQUENCE_ID_FILE_SUFFIX = ".seqid";
698   private static final String OLD_SEQUENCE_ID_FILE_SUFFIX = "_seqid";
699   private static final int SEQUENCE_ID_FILE_SUFFIX_LENGTH = SEQUENCE_ID_FILE_SUFFIX.length();
700 
701   /**
702    * Is the given file a region open sequence id file.
703    */
704   @VisibleForTesting
705   public static boolean isSequenceIdFile(final Path file) {
706     return file.getName().endsWith(SEQUENCE_ID_FILE_SUFFIX)
707         || file.getName().endsWith(OLD_SEQUENCE_ID_FILE_SUFFIX);
708   }
709 
710   /**
711    * Create a file with name as region open sequence id
712    * @param fs
713    * @param regiondir
714    * @param newSeqId
715    * @param saftyBumper
716    * @return long new sequence Id value
717    * @throws IOException
718    */
719   public static long writeRegionSequenceIdFile(final FileSystem fs, final Path regiondir,
720       long newSeqId, long saftyBumper) throws IOException {
721 
722     Path editsdir = WALSplitter.getRegionDirRecoveredEditsDir(regiondir);
723     long maxSeqId = 0;
724     FileStatus[] files = null;
725     if (fs.exists(editsdir)) {
726       files = FSUtils.listStatus(fs, editsdir, new PathFilter() {
727         @Override
728         public boolean accept(Path p) {
729           return isSequenceIdFile(p);
730         }
731       });
732       if (files != null) {
733         for (FileStatus status : files) {
734           String fileName = status.getPath().getName();
735           try {
736             Long tmpSeqId = Long.parseLong(fileName.substring(0, fileName.length()
737                 - SEQUENCE_ID_FILE_SUFFIX_LENGTH));
738             maxSeqId = Math.max(tmpSeqId, maxSeqId);
739           } catch (NumberFormatException ex) {
740             LOG.warn("Invalid SeqId File Name=" + fileName);
741           }
742         }
743       }
744     }
745     if (maxSeqId > newSeqId) {
746       newSeqId = maxSeqId;
747     }
748     newSeqId += saftyBumper; // bump up SeqId
749 
750     // write a new seqId file
751     Path newSeqIdFile = new Path(editsdir, newSeqId + SEQUENCE_ID_FILE_SUFFIX);
752     if (newSeqId != maxSeqId) {
753       try {
754         if (!fs.createNewFile(newSeqIdFile) && !fs.exists(newSeqIdFile)) {
755           throw new IOException("Failed to create SeqId file:" + newSeqIdFile);
756         }
757         if (LOG.isDebugEnabled()) {
758           LOG.debug("Wrote region seqId=" + newSeqIdFile + " to file, newSeqId=" + newSeqId
759               + ", maxSeqId=" + maxSeqId);
760         }
761       } catch (FileAlreadyExistsException ignored) {
762         // latest hdfs throws this exception. it's all right if newSeqIdFile already exists
763       }
764     }
765     // remove old ones
766     if (files != null) {
767       for (FileStatus status : files) {
768         if (newSeqIdFile.equals(status.getPath())) {
769           continue;
770         }
771         fs.delete(status.getPath(), false);
772       }
773     }
774     return newSeqId;
775   }
776 
777   /**
778    * Create a new {@link Reader} for reading logs to split.
779    *
780    * @param file
781    * @return A new Reader instance, caller should close
782    * @throws IOException
783    * @throws CorruptedLogFileException
784    */
785   protected Reader getReader(FileStatus file, boolean skipErrors, CancelableProgressable reporter)
786       throws IOException, CorruptedLogFileException {
787     Path path = file.getPath();
788     long length = file.getLen();
789     Reader in;
790 
791     // Check for possibly empty file. With appends, currently Hadoop reports a
792     // zero length even if the file has been sync'd. Revisit if HDFS-376 or
793     // HDFS-878 is committed.
794     if (length <= 0) {
795       LOG.warn("File " + path + " might be still open, length is 0");
796     }
797 
798     try {
799       FSUtils.getInstance(fs, conf).recoverFileLease(fs, path, conf, reporter);
800       try {
801         in = getReader(path, reporter);
802       } catch (EOFException e) {
803         if (length <= 0) {
804           // TODO should we ignore an empty, not-last log file if skip.errors
805           // is false? Either way, the caller should decide what to do. E.g.
806           // ignore if this is the last log in sequence.
807           // TODO is this scenario still possible if the log has been
808           // recovered (i.e. closed)
809           LOG.warn("Could not open " + path + " for reading. File is empty", e);
810           return null;
811         } else {
812           // EOFException being ignored
813           return null;
814         }
815       }
816     } catch (IOException e) {
817       if (e instanceof FileNotFoundException) {
818         // A wal file may not exist anymore. Nothing can be recovered so move on
819         LOG.warn("File " + path + " doesn't exist anymore.", e);
820         return null;
821       }
822       if (!skipErrors || e instanceof InterruptedIOException) {
823         throw e; // Don't mark the file corrupted if interrupted, or not skipErrors
824       }
825       CorruptedLogFileException t =
826         new CorruptedLogFileException("skipErrors=true Could not open wal " +
827             path + " ignoring");
828       t.initCause(e);
829       throw t;
830     }
831     return in;
832   }
833 
834   static private Entry getNextLogLine(Reader in, Path path, boolean skipErrors)
835   throws CorruptedLogFileException, IOException {
836     try {
837       return in.next();
838     } catch (EOFException eof) {
839       // truncated files are expected if a RS crashes (see HBASE-2643)
840       LOG.info("EOF from wal " + path + ".  continuing");
841       return null;
842     } catch (IOException e) {
843       // If the IOE resulted from bad file format,
844       // then this problem is idempotent and retrying won't help
845       if (e.getCause() != null &&
846           (e.getCause() instanceof ParseException ||
847            e.getCause() instanceof org.apache.hadoop.fs.ChecksumException)) {
848         LOG.warn("Parse exception " + e.getCause().toString() + " from wal "
849            + path + ".  continuing");
850         return null;
851       }
852       if (!skipErrors) {
853         throw e;
854       }
855       CorruptedLogFileException t =
856         new CorruptedLogFileException("skipErrors=true Ignoring exception" +
857             " while parsing wal " + path + ". Marking as corrupted");
858       t.initCause(e);
859       throw t;
860     }
861   }
862 
863   /**
864    * Create a new {@link Writer} for writing log splits.
865    * @return a new Writer instance, caller should close
866    */
867   protected Writer createWriter(Path logfile)
868       throws IOException {
869     return walFactory.createRecoveredEditsWriter(fs, logfile);
870   }
871 
872   /**
873    * Create a new {@link Reader} for reading logs to split.
874    * @return new Reader instance, caller should close
875    */
876   protected Reader getReader(Path curLogFile, CancelableProgressable reporter) throws IOException {
877     return walFactory.createReader(fs, curLogFile, reporter);
878   }
879 
880   /**
881    * Get current open writers
882    */
883   private int getNumOpenWriters() {
884     int result = 0;
885     if (this.outputSink != null) {
886       result += this.outputSink.getNumOpenWriters();
887     }
888     return result;
889   }
890 
891   /**
892    * Contains some methods to control WAL-entries producer / consumer interactions
893    */
894   public static class PipelineController {
895     // If an exception is thrown by one of the other threads, it will be
896     // stored here.
897     AtomicReference<Throwable> thrown = new AtomicReference<Throwable>();
898 
899     // Wait/notify for when data has been produced by the writer thread,
900     // consumed by the reader thread, or an exception occurred
901     public final Object dataAvailable = new Object();
902 
903     void writerThreadError(Throwable t) {
904       thrown.compareAndSet(null, t);
905     }
906 
907     /**
908      * Check for errors in the writer threads. If any is found, rethrow it.
909      */
910     void checkForErrors() throws IOException {
911       Throwable thrown = this.thrown.get();
912       if (thrown == null) return;
913       if (thrown instanceof IOException) {
914         throw new IOException(thrown);
915       } else {
916         throw new RuntimeException(thrown);
917       }
918     }
919   }
920 
921   /**
922    * Class which accumulates edits and separates them into a buffer per region
923    * while simultaneously accounting RAM usage. Blocks if the RAM usage crosses
924    * a predefined threshold.
925    *
926    * Writer threads then pull region-specific buffers from this class.
927    */
928   public static class EntryBuffers {
929     PipelineController controller;
930 
931     Map<byte[], RegionEntryBuffer> buffers =
932       new TreeMap<byte[], RegionEntryBuffer>(Bytes.BYTES_COMPARATOR);
933 
934     /* Track which regions are currently in the middle of writing. We don't allow
935        an IO thread to pick up bytes from a region if we're already writing
936        data for that region in a different IO thread. */
937     Set<byte[]> currentlyWriting = new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR);
938 
939     long totalBuffered = 0;
940     final long maxHeapUsage;
941     boolean splitWriterCreationBounded;
942 
943 
944     public EntryBuffers(PipelineController controller, long maxHeapUsage) {
945       this(controller, maxHeapUsage, false);
946     }
947 
948     public EntryBuffers(PipelineController controller, long maxHeapUsage,
949         boolean splitWriterCreationBounded) {
950       this.controller = controller;
951       this.maxHeapUsage = maxHeapUsage;
952       this.splitWriterCreationBounded = splitWriterCreationBounded;
953     }
954 
955     /**
956      * Append a log entry into the corresponding region buffer.
957      * Blocks if the total heap usage has crossed the specified threshold.
958      *
959      * @throws InterruptedException
960      * @throws IOException
961      */
962     public void appendEntry(Entry entry) throws InterruptedException, IOException {
963       WALKey key = entry.getKey();
964 
965       RegionEntryBuffer buffer;
966       long incrHeap;
967       synchronized (this) {
968         buffer = buffers.get(key.getEncodedRegionName());
969         if (buffer == null) {
970           buffer = new RegionEntryBuffer(key.getTablename(), key.getEncodedRegionName());
971           buffers.put(key.getEncodedRegionName(), buffer);
972         }
973         incrHeap= buffer.appendEntry(entry);
974       }
975 
976       // If we crossed the chunk threshold, wait for more space to be available
977       synchronized (controller.dataAvailable) {
978         totalBuffered += incrHeap;
979         while (totalBuffered > maxHeapUsage && controller.thrown.get() == null) {
980           LOG.debug("Used " + totalBuffered + " bytes of buffered edits, waiting for IO threads...");
981           controller.dataAvailable.wait(2000);
982         }
983         controller.dataAvailable.notifyAll();
984       }
985       controller.checkForErrors();
986     }
987 
988     /**
989      * @return RegionEntryBuffer a buffer of edits to be written or replayed.
990      */
991     synchronized RegionEntryBuffer getChunkToWrite() {
992       // The core part of limiting opening writers is it doesn't return chunk only if the heap size
993       // is over maxHeapUsage. Thus it doesn't need to create a writer for each region
994       // during splitting. It will flush all the logs in the buffer after splitting through a
995       // threadpool, which means the number of writers it created is under control
996       if(splitWriterCreationBounded && totalBuffered < maxHeapUsage){
997         return null;
998       }
999 
1000       long biggestSize = 0;
1001       byte[] biggestBufferKey = null;
1002 
1003       for (Map.Entry<byte[], RegionEntryBuffer> entry : buffers.entrySet()) {
1004         long size = entry.getValue().heapSize();
1005         if (size > biggestSize && (!currentlyWriting.contains(entry.getKey()))) {
1006           biggestSize = size;
1007           biggestBufferKey = entry.getKey();
1008         }
1009       }
1010       if (biggestBufferKey == null) {
1011         return null;
1012       }
1013 
1014       RegionEntryBuffer buffer = buffers.remove(biggestBufferKey);
1015       currentlyWriting.add(biggestBufferKey);
1016       return buffer;
1017     }
1018 
1019     void doneWriting(RegionEntryBuffer buffer) {
1020       synchronized (this) {
1021         boolean removed = currentlyWriting.remove(buffer.encodedRegionName);
1022         assert removed;
1023       }
1024       long size = buffer.heapSize();
1025 
1026       synchronized (controller.dataAvailable) {
1027         totalBuffered -= size;
1028         // We may unblock writers
1029         controller.dataAvailable.notifyAll();
1030       }
1031     }
1032 
1033     synchronized boolean isRegionCurrentlyWriting(byte[] region) {
1034       return currentlyWriting.contains(region);
1035     }
1036 
1037     public void waitUntilDrained() {
1038       synchronized (controller.dataAvailable) {
1039         while (totalBuffered > 0) {
1040           try {
1041             controller.dataAvailable.wait(2000);
1042           } catch (InterruptedException e) {
1043             LOG.warn("Got interrupted while waiting for EntryBuffers is drained");
1044             Thread.interrupted();
1045             break;
1046           }
1047         }
1048       }
1049     }
1050   }
1051 
1052   /**
1053    * A buffer of some number of edits for a given region.
1054    * This accumulates edits and also provides a memory optimization in order to
1055    * share a single byte array instance for the table and region name.
1056    * Also tracks memory usage of the accumulated edits.
1057    */
1058   public static class RegionEntryBuffer implements HeapSize {
1059     long heapInBuffer = 0;
1060     List<Entry> entryBuffer;
1061     TableName tableName;
1062     byte[] encodedRegionName;
1063 
1064     RegionEntryBuffer(TableName tableName, byte[] region) {
1065       this.tableName = tableName;
1066       this.encodedRegionName = region;
1067       this.entryBuffer = new LinkedList<Entry>();
1068     }
1069 
1070     long appendEntry(Entry entry) {
1071       internify(entry);
1072       entryBuffer.add(entry);
1073       long incrHeap = entry.getEdit().heapSize() +
1074         ClassSize.align(2 * ClassSize.REFERENCE) + // WALKey pointers
1075         0; // TODO linkedlist entry
1076       heapInBuffer += incrHeap;
1077       return incrHeap;
1078     }
1079 
1080     private void internify(Entry entry) {
1081       WALKey k = entry.getKey();
1082       k.internTableName(this.tableName);
1083       k.internEncodedRegionName(this.encodedRegionName);
1084     }
1085 
1086     @Override
1087     public long heapSize() {
1088       return heapInBuffer;
1089     }
1090 
1091     public byte[] getEncodedRegionName() {
1092       return encodedRegionName;
1093     }
1094 
1095     public List<Entry> getEntryBuffer() {
1096       return entryBuffer;
1097     }
1098 
1099     public TableName getTableName() {
1100       return tableName;
1101     }
1102   }
1103 
1104   public static class WriterThread extends Thread {
1105     private volatile boolean shouldStop = false;
1106     private PipelineController controller;
1107     private EntryBuffers entryBuffers;
1108     private OutputSink outputSink = null;
1109 
1110     WriterThread(PipelineController controller, EntryBuffers entryBuffers, OutputSink sink, int i){
1111       super(Thread.currentThread().getName() + "-Writer-" + i);
1112       this.controller = controller;
1113       this.entryBuffers = entryBuffers;
1114       outputSink = sink;
1115     }
1116 
1117     @Override
1118     public void run()  {
1119       try {
1120         doRun();
1121       } catch (Throwable t) {
1122         LOG.error("Exiting thread", t);
1123         controller.writerThreadError(t);
1124       }
1125     }
1126 
1127     private void doRun() throws IOException {
1128       if (LOG.isTraceEnabled()) LOG.trace("Writer thread starting");
1129       while (true) {
1130         RegionEntryBuffer buffer = entryBuffers.getChunkToWrite();
1131         if (buffer == null) {
1132           // No data currently available, wait on some more to show up
1133           synchronized (controller.dataAvailable) {
1134             if (shouldStop && !this.outputSink.flush()) {
1135               return;
1136             }
1137             try {
1138               controller.dataAvailable.wait(500);
1139             } catch (InterruptedException ie) {
1140               if (!shouldStop) {
1141                 throw new RuntimeException(ie);
1142               }
1143             }
1144           }
1145           continue;
1146         }
1147 
1148         assert buffer != null;
1149         try {
1150           writeBuffer(buffer);
1151         } finally {
1152           entryBuffers.doneWriting(buffer);
1153         }
1154       }
1155     }
1156 
1157     private void writeBuffer(RegionEntryBuffer buffer) throws IOException {
1158       outputSink.append(buffer);
1159     }
1160 
1161     void finish() {
1162       synchronized (controller.dataAvailable) {
1163         shouldStop = true;
1164         controller.dataAvailable.notifyAll();
1165       }
1166     }
1167   }
1168 
1169   /**
1170    * The following class is an abstraction class to provide a common interface to support both
1171    * existing recovered edits file sink and region server WAL edits replay sink
1172    */
1173   public static abstract class OutputSink {
1174 
1175     protected PipelineController controller;
1176     protected EntryBuffers entryBuffers;
1177 
1178     protected ConcurrentHashMap<String, SinkWriter> writers = new ConcurrentHashMap<>();
1179     protected ConcurrentHashMap<String, Long> regionMaximumEditLogSeqNum =
1180         new ConcurrentHashMap<>();
1181 
1182     protected final List<WriterThread> writerThreads = Lists.newArrayList();
1183 
1184     /* Set of regions which we've decided should not output edits */
1185     protected final Set<byte[]> blacklistedRegions = Collections
1186         .synchronizedSet(new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR));
1187 
1188     protected boolean closeAndCleanCompleted = false;
1189 
1190     protected boolean writersClosed = false;
1191 
1192     protected final int numThreads;
1193 
1194     protected CancelableProgressable reporter = null;
1195 
1196     protected AtomicLong skippedEdits = new AtomicLong();
1197 
1198     protected List<Path> splits = null;
1199 
1200     public OutputSink(PipelineController controller, EntryBuffers entryBuffers, int numWriters) {
1201       numThreads = numWriters;
1202       this.controller = controller;
1203       this.entryBuffers = entryBuffers;
1204     }
1205 
1206     void setReporter(CancelableProgressable reporter) {
1207       this.reporter = reporter;
1208     }
1209 
1210     /**
1211      * Start the threads that will pump data from the entryBuffers to the output files.
1212      */
1213     public synchronized void startWriterThreads() {
1214       for (int i = 0; i < numThreads; i++) {
1215         WriterThread t = new WriterThread(controller, entryBuffers, this, i);
1216         t.start();
1217         writerThreads.add(t);
1218       }
1219     }
1220 
1221     /**
1222      *
1223      * Update region's maximum edit log SeqNum.
1224      */
1225     void updateRegionMaximumEditLogSeqNum(Entry entry) {
1226 
1227       synchronized (regionMaximumEditLogSeqNum) {
1228         String encodedRegionName = Bytes.toString(entry.getKey().getEncodedRegionName());
1229         Long currentMaxSeqNum = regionMaximumEditLogSeqNum.get(encodedRegionName);
1230         if (currentMaxSeqNum == null || entry.getKey().getLogSeqNum() > currentMaxSeqNum) {
1231           regionMaximumEditLogSeqNum.put(encodedRegionName, entry.getKey()
1232               .getLogSeqNum());
1233         }
1234       }
1235     }
1236 
1237     Long getRegionMaximumEditLogSeqNum(byte[] region) {
1238       return regionMaximumEditLogSeqNum.get(Bytes.toString(region));
1239     }
1240 
1241     /**
1242      * @return the number of currently opened writers
1243      */
1244     int getNumOpenWriters() {
1245       return this.writers.size();
1246     }
1247 
1248     long getSkippedEdits() {
1249       return this.skippedEdits.get();
1250     }
1251 
1252     /**
1253      * Wait for writer threads to dump all info to the sink
1254      * @return true when there is no error
1255      * @throws IOException
1256      */
1257     protected boolean finishWriting(boolean interrupt) throws IOException {
1258       LOG.debug("Waiting for split writer threads to finish");
1259       boolean progress_failed = false;
1260       for (WriterThread t : writerThreads) {
1261         t.finish();
1262       }
1263       if (interrupt) {
1264         for (WriterThread t : writerThreads) {
1265           t.interrupt(); // interrupt the writer threads. We are stopping now.
1266         }
1267       }
1268 
1269       for (WriterThread t : writerThreads) {
1270         if (!progress_failed && reporter != null && !reporter.progress()) {
1271           progress_failed = true;
1272         }
1273         try {
1274           t.join();
1275         } catch (InterruptedException ie) {
1276           IOException iie = new InterruptedIOException();
1277           iie.initCause(ie);
1278           throw iie;
1279         }
1280       }
1281       controller.checkForErrors();
1282       LOG.info(this.writerThreads.size() + " split writers finished; closing...");
1283       return (!progress_failed);
1284     }
1285 
1286     public abstract List<Path> finishWritingAndClose() throws IOException;
1287 
1288     /**
1289      * @return a map from encoded region ID to the number of edits written out for that region.
1290      */
1291     public abstract Map<byte[], Long> getOutputCounts();
1292 
1293     /**
1294      * @return number of regions we've recovered
1295      */
1296     public abstract int getNumberOfRecoveredRegions();
1297 
1298     /**
1299      * @param buffer A WAL Edit Entry
1300      * @throws IOException
1301      */
1302     public abstract void append(RegionEntryBuffer buffer) throws IOException;
1303 
1304     /**
1305      * WriterThread call this function to help flush internal remaining edits in buffer before close
1306      * @return true when underlying sink has something to flush
1307      */
1308     public boolean flush() throws IOException {
1309       return false;
1310     }
1311 
1312     /**
1313      * Some WALEdit's contain only KV's for account on what happened to a region.
1314      * Not all sinks will want to get all of those edits.
1315      *
1316      * @return Return true if this sink wants to accept this region-level WALEdit.
1317      */
1318     public abstract boolean keepRegionEvent(Entry entry);
1319   }
1320 
1321   /**
1322    * Class that manages the output streams from the log splitting process.
1323    */
1324   class LogRecoveredEditsOutputSink extends OutputSink {
1325 
1326     public LogRecoveredEditsOutputSink(PipelineController controller, EntryBuffers entryBuffers,
1327         int numWriters) {
1328       // More threads could potentially write faster at the expense
1329       // of causing more disk seeks as the logs are split.
1330       // 3. After a certain setting (probably around 3) the
1331       // process will be bound on the reader in the current
1332       // implementation anyway.
1333       super(controller, entryBuffers, numWriters);
1334     }
1335 
1336     /**
1337      * @return null if failed to report progress
1338      * @throws IOException
1339      */
1340     @Override
1341     public List<Path> finishWritingAndClose() throws IOException {
1342       boolean isSuccessful = false;
1343       List<Path> result = null;
1344       try {
1345         isSuccessful = finishWriting(false);
1346       } finally {
1347         result = close();
1348         List<IOException> thrown = closeLogWriters(null);
1349         if (thrown != null && !thrown.isEmpty()) {
1350           throw MultipleIOException.createIOException(thrown);
1351         }
1352       }
1353       if (isSuccessful) {
1354         splits = result;
1355       }
1356       return splits;
1357     }
1358 
1359     // delete the one with fewer wal entries
1360     void deleteOneWithFewerEntries(FileSystem rootFs, WriterAndPath wap, Path dst)
1361         throws IOException {
1362       long dstMinLogSeqNum = -1L;
1363       try (WAL.Reader reader = walFactory.createReader(fs, dst)) {
1364         WAL.Entry entry = reader.next();
1365         if (entry != null) {
1366           dstMinLogSeqNum = entry.getKey().getLogSeqNum();
1367         }
1368       } catch (EOFException e) {
1369         if (LOG.isDebugEnabled()) {
1370           LOG.debug(
1371             "Got EOF when reading first WAL entry from " + dst + ", an empty or broken WAL file?",
1372             e);
1373         }
1374       }
1375       if (wap.minLogSeqNum < dstMinLogSeqNum) {
1376         LOG.warn("Found existing old edits file. It could be the result of a previous failed"
1377             + " split attempt or we have duplicated wal entries. Deleting " + dst + ", length="
1378             + fs.getFileStatus(dst).getLen());
1379         if (!fs.delete(dst, false)) {
1380           LOG.warn("Failed deleting of old " + dst);
1381           throw new IOException("Failed deleting of old " + dst);
1382         }
1383       } else {
1384         LOG.warn("Found existing old edits file and we have less entries. Deleting " + wap.p
1385             + ", length=" + rootFs.getFileStatus(wap.p).getLen());
1386         if (!rootFs.delete(wap.p, false)) {
1387           LOG.warn("Failed deleting of " + wap.p);
1388           throw new IOException("Failed deleting of " + wap.p);
1389         }
1390       }
1391     }
1392 
1393     /**
1394      * Close all of the output streams.
1395      * @return the list of paths written.
1396      */
1397     List<Path> close() throws IOException {
1398       Preconditions.checkState(!closeAndCleanCompleted);
1399 
1400       final List<Path> paths = new ArrayList<Path>();
1401       final List<IOException> thrown = Lists.newArrayList();
1402       ThreadPoolExecutor closeThreadPool = Threads.getBoundedCachedThreadPool(numThreads, 30L,
1403         TimeUnit.SECONDS, new ThreadFactory() {
1404           private int count = 1;
1405 
1406           @Override
1407           public Thread newThread(Runnable r) {
1408             Thread t = new Thread(r, "split-log-closeStream-" + count++);
1409             return t;
1410           }
1411         });
1412       CompletionService<Void> completionService =
1413         new ExecutorCompletionService<Void>(closeThreadPool);
1414       boolean progress_failed;
1415       try{
1416         progress_failed = executeCloseTask(completionService, thrown, paths);
1417       } catch (InterruptedException e) {
1418         IOException iie = new InterruptedIOException();
1419         iie.initCause(e);
1420         throw iie;
1421       } catch (ExecutionException e) {
1422         throw new IOException(e.getCause());
1423       } finally {
1424         closeThreadPool.shutdownNow();
1425       }
1426 
1427       if (!thrown.isEmpty()) {
1428         throw MultipleIOException.createIOException(thrown);
1429       }
1430       writersClosed = true;
1431       closeAndCleanCompleted = true;
1432       if (progress_failed) {
1433         return null;
1434       }
1435       return paths;
1436     }
1437 
1438     boolean executeCloseTask(CompletionService<Void> completionService,
1439         final List<IOException> thrown, final List<Path> paths)
1440         throws InterruptedException, ExecutionException {
1441       for (final Map.Entry<String, SinkWriter> writersEntry : writers.entrySet()) {
1442         if (LOG.isTraceEnabled()) {
1443           LOG.trace("Submitting close of " + ((WriterAndPath) writersEntry.getValue()).p);
1444         }
1445         completionService.submit(new Callable<Void>() {
1446           @Override public Void call() throws Exception {
1447             WriterAndPath wap = (WriterAndPath) writersEntry.getValue();
1448             Path dst = closeWriter(writersEntry.getKey(), wap, thrown);
1449             paths.add(dst);
1450             return null;
1451           }
1452         });
1453       }
1454       boolean progress_failed = false;
1455       for (int i = 0, n = this.writers.size(); i < n; i++) {
1456         Future<Void> future = completionService.take();
1457         future.get();
1458         if (!progress_failed && reporter != null && !reporter.progress()) {
1459           progress_failed = true;
1460         }
1461       }
1462       return progress_failed;
1463     }
1464 
1465     Path closeWriter(String encodedRegionName, WriterAndPath wap, List<IOException> thrown)
1466         throws IOException {
1467       if (LOG.isTraceEnabled()) {
1468         LOG.trace("Closing " + wap.p);
1469       }
1470       FileSystem rootFs = FileSystem.get(conf);
1471       try {
1472         wap.w.close();
1473       } catch (IOException ioe) {
1474         LOG.error("Couldn't close log at " + wap.p, ioe);
1475         thrown.add(ioe);
1476         return null;
1477       }
1478       if (LOG.isDebugEnabled()) {
1479         LOG.debug("Closed wap " + wap.p + " (wrote " + wap.editsWritten
1480             + " edits, skipped " + wap.editsSkipped + " edits in "
1481             + (wap.nanosSpent / 1000 / 1000) + "ms");
1482       }
1483       if (wap.editsWritten == 0) {
1484         // just remove the empty recovered.edits file
1485         if (rootFs.exists(wap.p) && !rootFs.delete(wap.p, false)) {
1486           LOG.warn("Failed deleting empty " + wap.p);
1487           throw new IOException("Failed deleting empty  " + wap.p);
1488         }
1489         return null;
1490       }
1491 
1492       Path dst = getCompletedRecoveredEditsFilePath(wap.p,
1493           regionMaximumEditLogSeqNum.get(encodedRegionName));
1494       try {
1495         if (!dst.equals(wap.p) && rootFs.exists(dst)) {
1496           deleteOneWithFewerEntries(rootFs, wap, dst);
1497         }
1498         // Skip the unit tests which create a splitter that reads and
1499         // writes the data without touching disk.
1500         // TestHLogSplit#testThreading is an example.
1501         if (rootFs.exists(wap.p)) {
1502           if (!rootFs.rename(wap.p, dst)) {
1503             throw new IOException("Failed renaming " + wap.p + " to " + dst);
1504           }
1505           LOG.info("Rename " + wap.p + " to " + dst);
1506         }
1507       } catch (IOException ioe) {
1508         LOG.error("Couldn't rename " + wap.p + " to " + dst, ioe);
1509         thrown.add(ioe);
1510         return null;
1511       }
1512       return dst;
1513     }
1514 
1515 
1516     private List<IOException> closeLogWriters(List<IOException> thrown) throws IOException {
1517       if (writersClosed) {
1518         return thrown;
1519       }
1520 
1521       if (thrown == null) {
1522         thrown = Lists.newArrayList();
1523       }
1524       try {
1525         for (WriterThread t : writerThreads) {
1526           while (t.isAlive()) {
1527             t.shouldStop = true;
1528             t.interrupt();
1529             try {
1530               t.join(10);
1531             } catch (InterruptedException e) {
1532               IOException iie = new InterruptedIOException();
1533               iie.initCause(e);
1534               throw iie;
1535             }
1536           }
1537         }
1538       } finally {
1539         WriterAndPath wap = null;
1540         for (SinkWriter tmpWAP : writers.values()) {
1541           try {
1542             wap = (WriterAndPath) tmpWAP;
1543             wap.w.close();
1544           } catch (IOException ioe) {
1545             LOG.error("Couldn't close log at " + wap.p, ioe);
1546             thrown.add(ioe);
1547             continue;
1548           }
1549           LOG.info(
1550               "Closed log " + wap.p + " (wrote " + wap.editsWritten + " edits in " + (wap.nanosSpent
1551                   / 1000 / 1000) + "ms)");
1552         }
1553         writersClosed = true;
1554       }
1555 
1556       return thrown;
1557     }
1558 
1559     /**
1560      * Get a writer and path for a log starting at the given entry. This function is threadsafe so
1561      * long as multiple threads are always acting on different regions.
1562      * @return null if this region shouldn't output any logs
1563      */
1564     WriterAndPath getWriterAndPath(Entry entry, boolean reusable) throws IOException {
1565       byte region[] = entry.getKey().getEncodedRegionName();
1566       String regionName = Bytes.toString(region);
1567       WriterAndPath ret = (WriterAndPath) writers.get(regionName);
1568       if (ret != null) {
1569         return ret;
1570       }
1571       // If we already decided that this region doesn't get any output
1572       // we don't need to check again.
1573       if (blacklistedRegions.contains(region)) {
1574         return null;
1575       }
1576       ret = createWAP(region, entry);
1577       if (ret == null) {
1578         blacklistedRegions.add(region);
1579         return null;
1580       }
1581 
1582       if(reusable) {
1583         writers.put(regionName, ret);
1584       }
1585       return ret;
1586     }
1587 
1588     /**
1589      * @return a path with a write for that path. caller should close.
1590      */
1591     WriterAndPath createWAP(byte[] region, Entry entry) throws IOException {
1592       Path regionedits = getRegionSplitEditsPath(entry,
1593           fileBeingSplit.getPath().getName(), conf);
1594       if (regionedits == null) {
1595         return null;
1596       }
1597       FileSystem rootFs = FileSystem.get(conf);
1598       if (rootFs.exists(regionedits)) {
1599         LOG.warn("Found old edits file. It could be the "
1600             + "result of a previous failed split attempt. Deleting " + regionedits + ", length="
1601             + rootFs.getFileStatus(regionedits).getLen());
1602         if (!rootFs.delete(regionedits, false)) {
1603           LOG.warn("Failed delete of old " + regionedits);
1604         }
1605       }
1606       Writer w = createWriter(regionedits);
1607       LOG.debug("Creating writer path=" + regionedits);
1608       return new WriterAndPath(regionedits, w, entry.getKey().getLogSeqNum());
1609     }
1610 
1611     void filterCellByStore(Entry logEntry) {
1612       Map<byte[], Long> maxSeqIdInStores =
1613           regionMaxSeqIdInStores.get(Bytes.toString(logEntry.getKey().getEncodedRegionName()));
1614       if (maxSeqIdInStores == null || maxSeqIdInStores.isEmpty()) {
1615         return;
1616       }
1617       // Create the array list for the cells that aren't filtered.
1618       // We make the assumption that most cells will be kept.
1619       ArrayList<Cell> keptCells = new ArrayList<Cell>(logEntry.getEdit().getCells().size());
1620       for (Cell cell : logEntry.getEdit().getCells()) {
1621         if (CellUtil.matchingFamily(cell, WALEdit.METAFAMILY)) {
1622           keptCells.add(cell);
1623         } else {
1624           byte[] family = CellUtil.cloneFamily(cell);
1625           Long maxSeqId = maxSeqIdInStores.get(family);
1626           // Do not skip cell even if maxSeqId is null. Maybe we are in a rolling upgrade,
1627           // or the master was crashed before and we can not get the information.
1628           if (maxSeqId == null || maxSeqId.longValue() < logEntry.getKey().getLogSeqNum()) {
1629             keptCells.add(cell);
1630           }
1631         }
1632       }
1633 
1634       // Anything in the keptCells array list is still live.
1635       // So rather than removing the cells from the array list
1636       // which would be an O(n^2) operation, we just replace the list
1637       logEntry.getEdit().setCells(keptCells);
1638     }
1639 
1640     @Override
1641     public void append(RegionEntryBuffer buffer) throws IOException {
1642       appendBuffer(buffer, true);
1643     }
1644 
1645 
1646     WriterAndPath appendBuffer(RegionEntryBuffer buffer, boolean reusable) throws IOException{
1647       List<Entry> entries = buffer.entryBuffer;
1648       if (entries.isEmpty()) {
1649         LOG.warn("got an empty buffer, skipping");
1650         return null;
1651       }
1652       WriterAndPath wap = null;
1653 
1654       long startTime = System.nanoTime();
1655       try {
1656         int editsCount = 0;
1657 
1658         for (Entry logEntry : entries) {
1659           if (wap == null) {
1660             wap = getWriterAndPath(logEntry, reusable);
1661             if (wap == null) {
1662               if (LOG.isDebugEnabled()) {
1663                 LOG.debug("getWriterAndPath decided we don't need to write edits for " + logEntry);
1664               }
1665               return null;
1666             }
1667           }
1668           filterCellByStore(logEntry);
1669           if (!logEntry.getEdit().isEmpty()) {
1670             wap.w.append(logEntry);
1671             this.updateRegionMaximumEditLogSeqNum(logEntry);
1672             editsCount++;
1673           } else {
1674             wap.incrementSkippedEdits(1);
1675           }
1676         }
1677         // Pass along summary statistics
1678         wap.incrementEdits(editsCount);
1679         wap.incrementNanoTime(System.nanoTime() - startTime);
1680       } catch (IOException e) {
1681         e = RemoteExceptionHandler.checkIOException(e);
1682         LOG.fatal(" Got while writing log entry to log", e);
1683         throw e;
1684       }
1685       return wap;
1686     }
1687 
1688     @Override
1689     public boolean keepRegionEvent(Entry entry) {
1690       ArrayList<Cell> cells = entry.getEdit().getCells();
1691       for (int i = 0; i < cells.size(); i++) {
1692         if (WALEdit.isCompactionMarker(cells.get(i))) {
1693           return true;
1694         }
1695       }
1696       return false;
1697     }
1698 
1699     /**
1700      * @return a map from encoded region ID to the number of edits written out for that region.
1701      */
1702     @Override
1703     public Map<byte[], Long> getOutputCounts() {
1704       TreeMap<byte[], Long> ret = new TreeMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
1705       synchronized (writers) {
1706         for (Map.Entry<String, SinkWriter> entry : writers.entrySet()) {
1707           ret.put(Bytes.toBytes(entry.getKey()), entry.getValue().editsWritten);
1708         }
1709       }
1710       return ret;
1711     }
1712 
1713     @Override
1714     public int getNumberOfRecoveredRegions() {
1715       return writers.size();
1716     }
1717   }
1718 
1719   /**
1720    * Class that will limit the number of hdfs writers we create to split the logs
1721    */
1722   class BoundedLogWriterCreationOutputSink extends LogRecoveredEditsOutputSink{
1723 
1724     ConcurrentHashMap<String, Long> regionRecoverStatMap = new ConcurrentHashMap<>();
1725 
1726 
1727     public BoundedLogWriterCreationOutputSink(PipelineController controller,
1728         EntryBuffers entryBuffers, int numWriters){
1729       super(controller, entryBuffers, numWriters);
1730     }
1731 
1732     @Override
1733     public List<Path> finishWritingAndClose() throws IOException {
1734       boolean isSuccessful;
1735       List<Path> result;
1736       try {
1737         isSuccessful = finishWriting(false);
1738       } finally {
1739         result = close();
1740       }
1741       if (isSuccessful) {
1742         splits = result;
1743       }
1744       return splits;
1745     }
1746 
1747     @Override
1748     boolean executeCloseTask(CompletionService<Void> closeCompletionService,
1749         final List<IOException> thrown, final List<Path> paths)
1750         throws InterruptedException, ExecutionException {
1751       for (final Map.Entry<byte[], RegionEntryBuffer> buffer : entryBuffers.buffers.entrySet()) {
1752         LOG.info("Submitting write then close of " +
1753             Bytes.toString(buffer.getValue().encodedRegionName));
1754         closeCompletionService.submit(new Callable<Void>() {
1755           public Void call() throws Exception {
1756             Path dst = writeThenClose(buffer.getValue());
1757             paths.add(dst);
1758             return null;
1759           }
1760         });
1761       }
1762 
1763       boolean progress_failed = false;
1764       for (int i = 0, n = entryBuffers.buffers.size(); i < n; i++) {
1765         Future<Void> future = closeCompletionService.take();
1766         future.get();
1767         if (!progress_failed && reporter != null && !reporter.progress()) {
1768           progress_failed = true;
1769         }
1770       }
1771       return progress_failed;
1772     }
1773 
1774     @Override
1775     public Map<byte[], Long> getOutputCounts() {
1776       Map<byte[], Long> regionRecoverStatMapResult = new HashMap<>();
1777       for(Map.Entry<String, Long> entry: regionRecoverStatMap.entrySet()){
1778         regionRecoverStatMapResult.put(Bytes.toBytes(entry.getKey()), entry.getValue());
1779       }
1780       return regionRecoverStatMapResult;
1781     }
1782 
1783     @Override
1784     public int getNumberOfRecoveredRegions() {
1785       return regionRecoverStatMap.size();
1786     }
1787 
1788     @Override
1789     public void append(RegionEntryBuffer buffer) throws IOException {
1790       writeThenClose(buffer);
1791     }
1792 
1793     private Path writeThenClose(RegionEntryBuffer buffer) throws IOException {
1794       WriterAndPath wap = appendBuffer(buffer, false);
1795       Path dst = null;
1796       if(wap != null){
1797         String encodedRegionName = Bytes.toString(buffer.encodedRegionName);
1798         Long value = regionRecoverStatMap.putIfAbsent(encodedRegionName, wap.editsWritten);
1799         if(value != null){
1800           Long newValue = regionRecoverStatMap.get(encodedRegionName) + wap.editsWritten;
1801           regionRecoverStatMap.put(encodedRegionName, newValue);
1802         }
1803       }
1804 
1805       List<IOException> thrown = new ArrayList<>();
1806       if(wap != null) {
1807         dst = closeWriter(Bytes.toString(buffer.encodedRegionName), wap, thrown);
1808       }
1809 
1810       if(!thrown.isEmpty()){
1811         throw MultipleIOException.createIOException(thrown);
1812       }
1813       return dst;
1814     }
1815   }
1816 
1817 
1818   /**
1819    * Class wraps the actual writer which writes data out and related statistics
1820    */
1821   public abstract static class SinkWriter {
1822     /* Count of edits written to this path */
1823     long editsWritten = 0;
1824     /* Count of edits skipped to this path */
1825     long editsSkipped = 0;
1826     /* Number of nanos spent writing to this log */
1827     long nanosSpent = 0;
1828 
1829     void incrementEdits(int edits) {
1830       editsWritten += edits;
1831     }
1832 
1833     void incrementSkippedEdits(int skipped) {
1834       editsSkipped += skipped;
1835     }
1836 
1837     void incrementNanoTime(long nanos) {
1838       nanosSpent += nanos;
1839     }
1840   }
1841 
1842   /**
1843    * Private data structure that wraps a Writer and its Path, also collecting statistics about the
1844    * data written to this output.
1845    */
1846   private final static class WriterAndPath extends SinkWriter {
1847     final Path p;
1848     final Writer w;
1849     final long minLogSeqNum;
1850 
1851     WriterAndPath(final Path p, final Writer w, final long minLogSeqNum) {
1852       this.p = p;
1853       this.w = w;
1854       this.minLogSeqNum = minLogSeqNum;
1855     }
1856   }
1857 
1858   /**
1859    * Class that manages to replay edits from WAL files directly to assigned fail over region servers
1860    */
1861   class LogReplayOutputSink extends OutputSink {
1862     private static final double BUFFER_THRESHOLD = 0.35;
1863     private static final String KEY_DELIMITER = "#";
1864 
1865     private long waitRegionOnlineTimeOut;
1866     private final Set<String> recoveredRegions = Collections.synchronizedSet(new HashSet<String>());
1867     private final Map<String, RegionServerWriter> rsWriters =
1868         new ConcurrentHashMap<String, RegionServerWriter>();
1869     // online encoded region name -> region location map
1870     private final Map<String, HRegionLocation> onlineRegions =
1871         new ConcurrentHashMap<String, HRegionLocation>();
1872 
1873     private final Map<TableName, HConnection> tableNameToHConnectionMap = Collections
1874         .synchronizedMap(new TreeMap<TableName, HConnection>());
1875     /**
1876      * Map key -> value layout
1877      * servername:table name -> Queue(Row)
1878      */
1879     private final Map<String, List<Pair<HRegionLocation, Entry>>> serverToBufferQueueMap =
1880         new ConcurrentHashMap<String, List<Pair<HRegionLocation, Entry>>>();
1881     private final List<Throwable> thrown = new ArrayList<Throwable>();
1882 
1883     // The following sink is used in distrubitedLogReplay mode for entries of regions in a disabling
1884     // table. It's a limitation of distributedLogReplay. Because log replay needs a region is
1885     // assigned and online before it can replay wal edits while regions of disabling/disabled table
1886     // won't be assigned by AM. We can retire this code after HBASE-8234.
1887     private LogRecoveredEditsOutputSink logRecoveredEditsOutputSink;
1888     private boolean hasEditsInDisablingOrDisabledTables = false;
1889 
1890     public LogReplayOutputSink(PipelineController controller, EntryBuffers entryBuffers,
1891         int numWriters) {
1892       super(controller, entryBuffers, numWriters);
1893       this.waitRegionOnlineTimeOut = conf.getInt(HConstants.HBASE_SPLITLOG_MANAGER_TIMEOUT,
1894           ZKSplitLogManagerCoordination.DEFAULT_TIMEOUT);
1895       this.logRecoveredEditsOutputSink = new LogRecoveredEditsOutputSink(controller,
1896         entryBuffers, numWriters);
1897       this.logRecoveredEditsOutputSink.setReporter(reporter);
1898     }
1899 
1900     @Override
1901     public void append(RegionEntryBuffer buffer) throws IOException {
1902       List<Entry> entries = buffer.entryBuffer;
1903       if (entries.isEmpty()) {
1904         LOG.warn("got an empty buffer, skipping");
1905         return;
1906       }
1907 
1908       // check if current region in a disabling or disabled table
1909       if (disablingOrDisabledTables.contains(buffer.tableName)) {
1910         // need fall back to old way
1911         logRecoveredEditsOutputSink.append(buffer);
1912         hasEditsInDisablingOrDisabledTables = true;
1913         // store regions we have recovered so far
1914         addToRecoveredRegions(Bytes.toString(buffer.encodedRegionName));
1915         return;
1916       }
1917 
1918       // group entries by region servers
1919       groupEditsByServer(entries);
1920 
1921       // process workitems
1922       String maxLocKey = null;
1923       int maxSize = 0;
1924       List<Pair<HRegionLocation, Entry>> maxQueue = null;
1925       synchronized (this.serverToBufferQueueMap) {
1926         for (Map.Entry<String, List<Pair<HRegionLocation, Entry>>> entry:
1927               serverToBufferQueueMap.entrySet()) {
1928           List<Pair<HRegionLocation, Entry>> curQueue = entry.getValue();
1929           if (curQueue.size() > maxSize) {
1930             maxSize = curQueue.size();
1931             maxQueue = curQueue;
1932             maxLocKey = entry.getKey();
1933           }
1934         }
1935         if (maxSize < minBatchSize
1936             && entryBuffers.totalBuffered < BUFFER_THRESHOLD * entryBuffers.maxHeapUsage) {
1937           // buffer more to process
1938           return;
1939         } else if (maxSize > 0) {
1940           this.serverToBufferQueueMap.remove(maxLocKey);
1941         }
1942       }
1943 
1944       if (maxSize > 0) {
1945         processWorkItems(maxLocKey, maxQueue);
1946       }
1947     }
1948 
1949     private void addToRecoveredRegions(String encodedRegionName) {
1950       if (!recoveredRegions.contains(encodedRegionName)) {
1951         recoveredRegions.add(encodedRegionName);
1952       }
1953     }
1954 
1955     /**
1956      * Helper function to group WALEntries to individual region servers
1957      * @throws IOException
1958      */
1959     private void groupEditsByServer(List<Entry> entries) throws IOException {
1960       Set<TableName> nonExistentTables = null;
1961       Long cachedLastFlushedSequenceId = -1l;
1962       for (Entry entry : entries) {
1963         WALEdit edit = entry.getEdit();
1964         TableName table = entry.getKey().getTablename();
1965         // clear scopes which isn't needed for recovery
1966         entry.getKey().setScopes(null);
1967         String encodeRegionNameStr = Bytes.toString(entry.getKey().getEncodedRegionName());
1968         // skip edits of non-existent tables
1969         if (nonExistentTables != null && nonExistentTables.contains(table)) {
1970           this.skippedEdits.incrementAndGet();
1971           continue;
1972         }
1973 
1974         Map<byte[], Long> maxStoreSequenceIds = null;
1975         boolean needSkip = false;
1976         HRegionLocation loc = null;
1977         String locKey = null;
1978         List<Cell> cells = edit.getCells();
1979         List<Cell> skippedCells = new ArrayList<Cell>();
1980         HConnection hconn = this.getConnectionByTableName(table);
1981 
1982         for (Cell cell : cells) {
1983           byte[] row = CellUtil.cloneRow(cell);
1984           byte[] family = CellUtil.cloneFamily(cell);
1985           boolean isCompactionEntry = false;
1986           if (CellUtil.matchingFamily(cell, WALEdit.METAFAMILY)) {
1987             CompactionDescriptor compaction = WALEdit.getCompaction(cell);
1988             if (compaction != null && compaction.hasRegionName()) {
1989               try {
1990                 byte[][] regionName = HRegionInfo.parseRegionName(compaction.getRegionName()
1991                   .toByteArray());
1992                 row = regionName[1]; // startKey of the region
1993                 family = compaction.getFamilyName().toByteArray();
1994                 isCompactionEntry = true;
1995               } catch (Exception ex) {
1996                 LOG.warn("Unexpected exception received, ignoring " + ex);
1997                 skippedCells.add(cell);
1998                 continue;
1999               }
2000             } else {
2001               skippedCells.add(cell);
2002               continue;
2003             }
2004           }
2005 
2006           try {
2007             loc =
2008                 locateRegionAndRefreshLastFlushedSequenceId(hconn, table, row,
2009                   encodeRegionNameStr);
2010             // skip replaying the compaction if the region is gone
2011             if (isCompactionEntry && !encodeRegionNameStr.equalsIgnoreCase(
2012               loc.getRegionInfo().getEncodedName())) {
2013               LOG.info("Not replaying a compaction marker for an older region: "
2014                   + encodeRegionNameStr);
2015               needSkip = true;
2016             }
2017           } catch (TableNotFoundException ex) {
2018             // table has been deleted so skip edits of the table
2019             LOG.info("Table " + table + " doesn't exist. Skip log replay for region "
2020                 + encodeRegionNameStr);
2021             lastFlushedSequenceIds.put(encodeRegionNameStr, Long.MAX_VALUE);
2022             if (nonExistentTables == null) {
2023               nonExistentTables = new TreeSet<TableName>();
2024             }
2025             nonExistentTables.add(table);
2026             this.skippedEdits.incrementAndGet();
2027             needSkip = true;
2028             break;
2029           }
2030 
2031           cachedLastFlushedSequenceId =
2032               lastFlushedSequenceIds.get(loc.getRegionInfo().getEncodedName());
2033           if (cachedLastFlushedSequenceId != null
2034               && cachedLastFlushedSequenceId >= entry.getKey().getLogSeqNum()) {
2035             // skip the whole WAL entry
2036             this.skippedEdits.incrementAndGet();
2037             needSkip = true;
2038             break;
2039           } else {
2040             if (maxStoreSequenceIds == null) {
2041               maxStoreSequenceIds =
2042                   regionMaxSeqIdInStores.get(loc.getRegionInfo().getEncodedName());
2043             }
2044             if (maxStoreSequenceIds != null) {
2045               Long maxStoreSeqId = maxStoreSequenceIds.get(family);
2046               if (maxStoreSeqId == null || maxStoreSeqId >= entry.getKey().getLogSeqNum()) {
2047                 // skip current kv if column family doesn't exist anymore or already flushed
2048                 skippedCells.add(cell);
2049                 continue;
2050               }
2051             }
2052           }
2053         }
2054 
2055         // skip the edit
2056         if (loc == null || needSkip) continue;
2057 
2058         if (!skippedCells.isEmpty()) {
2059           cells.removeAll(skippedCells);
2060         }
2061 
2062         synchronized (serverToBufferQueueMap) {
2063           locKey = loc.getHostnamePort() + KEY_DELIMITER + table;
2064           List<Pair<HRegionLocation, Entry>> queue = serverToBufferQueueMap.get(locKey);
2065           if (queue == null) {
2066             queue =
2067                 Collections.synchronizedList(new ArrayList<Pair<HRegionLocation, Entry>>());
2068             serverToBufferQueueMap.put(locKey, queue);
2069           }
2070           queue.add(new Pair<HRegionLocation, Entry>(loc, entry));
2071         }
2072         // store regions we have recovered so far
2073         addToRecoveredRegions(loc.getRegionInfo().getEncodedName());
2074       }
2075     }
2076 
2077     /**
2078      * Locate destination region based on table name & row. This function also makes sure the
2079      * destination region is online for replay.
2080      * @throws IOException
2081      */
2082     private HRegionLocation locateRegionAndRefreshLastFlushedSequenceId(HConnection hconn,
2083         TableName table, byte[] row, String originalEncodedRegionName) throws IOException {
2084       // fetch location from cache
2085       HRegionLocation loc = onlineRegions.get(originalEncodedRegionName);
2086       if(loc != null) return loc;
2087       // fetch location from hbase:meta directly without using cache to avoid hit old dead server
2088       loc = hconn.getRegionLocation(table, row, true);
2089       if (loc == null) {
2090         throw new IOException("Can't locate location for row:" + Bytes.toString(row)
2091             + " of table:" + table);
2092       }
2093       // check if current row moves to a different region due to region merge/split
2094       if (!originalEncodedRegionName.equalsIgnoreCase(loc.getRegionInfo().getEncodedName())) {
2095         // originalEncodedRegionName should have already flushed
2096         lastFlushedSequenceIds.put(originalEncodedRegionName, Long.MAX_VALUE);
2097         HRegionLocation tmpLoc = onlineRegions.get(loc.getRegionInfo().getEncodedName());
2098         if (tmpLoc != null) return tmpLoc;
2099       }
2100 
2101       Long lastFlushedSequenceId = -1l;
2102       AtomicBoolean isRecovering = new AtomicBoolean(true);
2103       loc = waitUntilRegionOnline(loc, row, this.waitRegionOnlineTimeOut, isRecovering);
2104       if (!isRecovering.get()) {
2105         // region isn't in recovering at all because WAL file may contain a region that has
2106         // been moved to somewhere before hosting RS fails
2107         lastFlushedSequenceIds.put(loc.getRegionInfo().getEncodedName(), Long.MAX_VALUE);
2108         LOG.info("logReplay skip region: " + loc.getRegionInfo().getEncodedName()
2109             + " because it's not in recovering.");
2110       } else {
2111         Long cachedLastFlushedSequenceId =
2112             lastFlushedSequenceIds.get(loc.getRegionInfo().getEncodedName());
2113 
2114         // retrieve last flushed sequence Id from ZK. Because region postOpenDeployTasks will
2115         // update the value for the region
2116         RegionStoreSequenceIds ids =
2117             csm.getSplitLogWorkerCoordination().getRegionFlushedSequenceId(failedServerName,
2118               loc.getRegionInfo().getEncodedName());
2119         if (ids != null) {
2120           lastFlushedSequenceId = ids.getLastFlushedSequenceId();
2121           Map<byte[], Long> storeIds = new TreeMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
2122           List<StoreSequenceId> maxSeqIdInStores = ids.getStoreSequenceIdList();
2123           for (StoreSequenceId id : maxSeqIdInStores) {
2124             storeIds.put(id.getFamilyName().toByteArray(), id.getSequenceId());
2125           }
2126           regionMaxSeqIdInStores.put(loc.getRegionInfo().getEncodedName(), storeIds);
2127         }
2128 
2129         if (cachedLastFlushedSequenceId == null
2130             || lastFlushedSequenceId > cachedLastFlushedSequenceId) {
2131           lastFlushedSequenceIds.put(loc.getRegionInfo().getEncodedName(), lastFlushedSequenceId);
2132         }
2133       }
2134 
2135       onlineRegions.put(loc.getRegionInfo().getEncodedName(), loc);
2136       return loc;
2137     }
2138 
2139     private void processWorkItems(String key, List<Pair<HRegionLocation, Entry>> actions)
2140         throws IOException {
2141       RegionServerWriter rsw = null;
2142 
2143       long startTime = System.nanoTime();
2144       try {
2145         rsw = getRegionServerWriter(key);
2146         rsw.sink.replayEntries(actions);
2147 
2148         // Pass along summary statistics
2149         rsw.incrementEdits(actions.size());
2150         rsw.incrementNanoTime(System.nanoTime() - startTime);
2151       } catch (IOException e) {
2152         e = RemoteExceptionHandler.checkIOException(e);
2153         LOG.fatal(" Got while writing log entry to log", e);
2154         throw e;
2155       }
2156     }
2157 
2158     /**
2159      * Wait until region is online on the destination region server
2160      * @param loc
2161      * @param row
2162      * @param timeout How long to wait
2163      * @param isRecovering Recovering state of the region interested on destination region server.
2164      * @return True when region is online on the destination region server
2165      * @throws InterruptedException
2166      */
2167     private HRegionLocation waitUntilRegionOnline(HRegionLocation loc, byte[] row,
2168         final long timeout, AtomicBoolean isRecovering)
2169         throws IOException {
2170       final long endTime = EnvironmentEdgeManager.currentTime() + timeout;
2171       final long pause = conf.getLong(HConstants.HBASE_CLIENT_PAUSE,
2172         HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
2173       boolean reloadLocation = false;
2174       TableName tableName = loc.getRegionInfo().getTable();
2175       int tries = 0;
2176       Throwable cause = null;
2177       while (endTime > EnvironmentEdgeManager.currentTime()) {
2178         try {
2179           // Try and get regioninfo from the hosting server.
2180           HConnection hconn = getConnectionByTableName(tableName);
2181           if(reloadLocation) {
2182             loc = hconn.getRegionLocation(tableName, row, true);
2183           }
2184           BlockingInterface remoteSvr = hconn.getAdmin(loc.getServerName());
2185           HRegionInfo region = loc.getRegionInfo();
2186           try {
2187             GetRegionInfoRequest request =
2188                 RequestConverter.buildGetRegionInfoRequest(region.getRegionName());
2189             GetRegionInfoResponse response = remoteSvr.getRegionInfo(null, request);
2190             if (HRegionInfo.convert(response.getRegionInfo()) != null) {
2191               isRecovering.set((response.hasIsRecovering()) ? response.getIsRecovering() : true);
2192               return loc;
2193             }
2194           } catch (ServiceException se) {
2195             throw ProtobufUtil.getRemoteException(se);
2196           }
2197         } catch (IOException e) {
2198           cause = e.getCause();
2199           if(!(cause instanceof RegionOpeningException)) {
2200             reloadLocation = true;
2201           }
2202         }
2203         long expectedSleep = ConnectionUtils.getPauseTime(pause, tries);
2204         try {
2205           Thread.sleep(expectedSleep);
2206         } catch (InterruptedException e) {
2207           throw new IOException("Interrupted when waiting region " +
2208               loc.getRegionInfo().getEncodedName() + " online.", e);
2209         }
2210         tries++;
2211       }
2212 
2213       throw new IOException("Timeout when waiting region " + loc.getRegionInfo().getEncodedName() +
2214         " online for " + timeout + " milliseconds.", cause);
2215     }
2216 
2217     @Override
2218     public boolean flush() throws IOException {
2219       String curLoc = null;
2220       int curSize = 0;
2221       List<Pair<HRegionLocation, Entry>> curQueue = null;
2222       synchronized (this.serverToBufferQueueMap) {
2223         for (Map.Entry<String, List<Pair<HRegionLocation, Entry>>> entry :
2224                 serverToBufferQueueMap.entrySet()) {
2225           String locationKey = entry.getKey();
2226           curQueue = entry.getValue();
2227           if (!curQueue.isEmpty()) {
2228             curSize = curQueue.size();
2229             curLoc = locationKey;
2230             break;
2231           }
2232         }
2233         if (curSize > 0) {
2234           this.serverToBufferQueueMap.remove(curLoc);
2235         }
2236       }
2237 
2238       if (curSize > 0) {
2239         this.processWorkItems(curLoc, curQueue);
2240         // We should already have control of the monitor; ensure this is the case.
2241         synchronized(controller.dataAvailable) {
2242           controller.dataAvailable.notifyAll();
2243         }
2244         return true;
2245       }
2246       return false;
2247     }
2248 
2249     @Override
2250     public boolean keepRegionEvent(Entry entry) {
2251       return true;
2252     }
2253 
2254     void addWriterError(Throwable t) {
2255       thrown.add(t);
2256     }
2257 
2258     @Override
2259     public List<Path> finishWritingAndClose() throws IOException {
2260       try {
2261         if (!finishWriting(false)) {
2262           return null;
2263         }
2264         if (hasEditsInDisablingOrDisabledTables) {
2265           splits = logRecoveredEditsOutputSink.finishWritingAndClose();
2266         } else {
2267           splits = new ArrayList<Path>();
2268         }
2269         // returns an empty array in order to keep interface same as old way
2270         return splits;
2271       } finally {
2272         List<IOException> thrown = closeRegionServerWriters();
2273         if (thrown != null && !thrown.isEmpty()) {
2274           throw MultipleIOException.createIOException(thrown);
2275         }
2276       }
2277     }
2278 
2279     @Override
2280     int getNumOpenWriters() {
2281       return this.rsWriters.size() + this.logRecoveredEditsOutputSink.getNumOpenWriters();
2282     }
2283 
2284     private List<IOException> closeRegionServerWriters() throws IOException {
2285       List<IOException> result = null;
2286       if (!writersClosed) {
2287         result = Lists.newArrayList();
2288         try {
2289           for (WriterThread t : writerThreads) {
2290             while (t.isAlive()) {
2291               t.shouldStop = true;
2292               t.interrupt();
2293               try {
2294                 t.join(10);
2295               } catch (InterruptedException e) {
2296                 IOException iie = new InterruptedIOException();
2297                 iie.initCause(e);
2298                 throw iie;
2299               }
2300             }
2301           }
2302         } finally {
2303           synchronized (rsWriters) {
2304             for (Map.Entry<String, RegionServerWriter> entry : rsWriters.entrySet()) {
2305               String locationKey = entry.getKey();
2306               RegionServerWriter tmpW = entry.getValue();
2307               try {
2308                 tmpW.close();
2309               } catch (IOException ioe) {
2310                 LOG.error("Couldn't close writer for region server:" + locationKey, ioe);
2311                 result.add(ioe);
2312               }
2313             }
2314           }
2315 
2316           // close connections
2317           synchronized (this.tableNameToHConnectionMap) {
2318             for (Map.Entry<TableName, HConnection> entry :
2319                   tableNameToHConnectionMap.entrySet()) {
2320               TableName tableName = entry.getKey();
2321               HConnection hconn = entry.getValue();
2322               try {
2323                 hconn.clearRegionCache();
2324                 hconn.close();
2325               } catch (IOException ioe) {
2326                 result.add(ioe);
2327               }
2328             }
2329           }
2330           writersClosed = true;
2331         }
2332       }
2333       return result;
2334     }
2335 
2336     @Override
2337     public Map<byte[], Long> getOutputCounts() {
2338       TreeMap<byte[], Long> ret = new TreeMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
2339       synchronized (rsWriters) {
2340         for (Map.Entry<String, RegionServerWriter> entry : rsWriters.entrySet()) {
2341           ret.put(Bytes.toBytes(entry.getKey()), entry.getValue().editsWritten);
2342         }
2343       }
2344       return ret;
2345     }
2346 
2347     @Override
2348     public int getNumberOfRecoveredRegions() {
2349       return this.recoveredRegions.size();
2350     }
2351 
2352     /**
2353      * Get a writer and path for a log starting at the given entry. This function is threadsafe so
2354      * long as multiple threads are always acting on different regions.
2355      * @return null if this region shouldn't output any logs
2356      */
2357     private RegionServerWriter getRegionServerWriter(String loc) throws IOException {
2358       RegionServerWriter ret = rsWriters.get(loc);
2359       if (ret != null) {
2360         return ret;
2361       }
2362 
2363       TableName tableName = getTableFromLocationStr(loc);
2364       if(tableName == null){
2365         throw new IOException("Invalid location string:" + loc + " found. Replay aborted.");
2366       }
2367 
2368       HConnection hconn = getConnectionByTableName(tableName);
2369       synchronized (rsWriters) {
2370         ret = rsWriters.get(loc);
2371         if (ret == null) {
2372           ret = new RegionServerWriter(conf, tableName, hconn);
2373           rsWriters.put(loc, ret);
2374         }
2375       }
2376       return ret;
2377     }
2378 
2379     private HConnection getConnectionByTableName(final TableName tableName) throws IOException {
2380       HConnection hconn = this.tableNameToHConnectionMap.get(tableName);
2381       if (hconn == null) {
2382         synchronized (this.tableNameToHConnectionMap) {
2383           hconn = this.tableNameToHConnectionMap.get(tableName);
2384           if (hconn == null) {
2385             hconn = HConnectionManager.getConnection(conf);
2386             this.tableNameToHConnectionMap.put(tableName, hconn);
2387           }
2388         }
2389       }
2390       return hconn;
2391     }
2392     private TableName getTableFromLocationStr(String loc) {
2393       /**
2394        * location key is in format <server name:port>#<table name>
2395        */
2396       String[] splits = loc.split(KEY_DELIMITER);
2397       if (splits.length != 2) {
2398         return null;
2399       }
2400       return TableName.valueOf(splits[1]);
2401     }
2402   }
2403 
2404   /**
2405    * Private data structure that wraps a receiving RS and collecting statistics about the data
2406    * written to this newly assigned RS.
2407    */
2408   private final static class RegionServerWriter extends SinkWriter {
2409     final WALEditsReplaySink sink;
2410 
2411     RegionServerWriter(final Configuration conf, final TableName tableName, final HConnection conn)
2412         throws IOException {
2413       this.sink = new WALEditsReplaySink(conf, tableName, conn);
2414     }
2415 
2416     void close() throws IOException {
2417     }
2418   }
2419 
2420   static class CorruptedLogFileException extends Exception {
2421     private static final long serialVersionUID = 1L;
2422 
2423     CorruptedLogFileException(String s) {
2424       super(s);
2425     }
2426   }
2427 
2428   /** A struct used by getMutationsFromWALEntry */
2429   public static class MutationReplay implements Comparable<MutationReplay> {
2430     public MutationReplay(MutationType type, Mutation mutation, long nonceGroup, long nonce) {
2431       this.type = type;
2432       this.mutation = mutation;
2433       if(this.mutation.getDurability() != Durability.SKIP_WAL) {
2434         // using ASYNC_WAL for relay
2435         this.mutation.setDurability(Durability.ASYNC_WAL);
2436       }
2437       this.nonceGroup = nonceGroup;
2438       this.nonce = nonce;
2439     }
2440 
2441     public final MutationType type;
2442     public final Mutation mutation;
2443     public final long nonceGroup;
2444     public final long nonce;
2445 
2446     @Override
2447     public int compareTo(final MutationReplay d) {
2448       return this.mutation.compareTo(d.mutation);
2449     }
2450 
2451     @Override
2452     public boolean equals(Object obj) {
2453       if(!(obj instanceof MutationReplay)) {
2454         return false;
2455       } else {
2456         return this.compareTo((MutationReplay)obj) == 0;
2457       }
2458     }
2459 
2460     @Override
2461     public int hashCode() {
2462       return this.mutation.hashCode();
2463     }
2464   }
2465 
2466   /**
2467    * This function is used to construct mutations from a WALEntry. It also
2468    * reconstructs WALKey &amp; WALEdit from the passed in WALEntry
2469    * @param entry
2470    * @param cells
2471    * @param logEntry pair of WALKey and WALEdit instance stores WALKey and WALEdit instances
2472    *          extracted from the passed in WALEntry.
2473    * @param durability
2474    * @return list of Pair&lt;MutationType, Mutation&gt; to be replayed
2475    * @throws IOException
2476    */
2477   public static List<MutationReplay> getMutationsFromWALEntry(WALEntry entry, CellScanner cells,
2478       Pair<WALKey, WALEdit> logEntry, Durability durability)
2479           throws IOException {
2480     if (entry == null) {
2481       // return an empty array
2482       return new ArrayList<MutationReplay>();
2483     }
2484 
2485     long replaySeqId = (entry.getKey().hasOrigSequenceNumber()) ?
2486       entry.getKey().getOrigSequenceNumber() : entry.getKey().getLogSequenceNumber();
2487     int count = entry.getAssociatedCellCount();
2488     List<MutationReplay> mutations = new ArrayList<MutationReplay>();
2489     Cell previousCell = null;
2490     Mutation m = null;
2491     WALKey key = null;
2492     WALEdit val = null;
2493     if (logEntry != null) val = new WALEdit();
2494 
2495     for (int i = 0; i < count; i++) {
2496       // Throw index out of bounds if our cell count is off
2497       if (!cells.advance()) {
2498         throw new ArrayIndexOutOfBoundsException("Expected=" + count + ", index=" + i);
2499       }
2500       Cell cell = cells.current();
2501       if (val != null) val.add(cell);
2502 
2503       boolean isNewRowOrType =
2504           previousCell == null || previousCell.getTypeByte() != cell.getTypeByte()
2505               || !CellUtil.matchingRow(previousCell, cell);
2506       if (isNewRowOrType) {
2507         // Create new mutation
2508         if (CellUtil.isDelete(cell)) {
2509           m = new Delete(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
2510           // Deletes don't have nonces.
2511           mutations.add(new MutationReplay(
2512               MutationType.DELETE, m, HConstants.NO_NONCE, HConstants.NO_NONCE));
2513         } else {
2514           m = new Put(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
2515           // Puts might come from increment or append, thus we need nonces.
2516           long nonceGroup = entry.getKey().hasNonceGroup()
2517               ? entry.getKey().getNonceGroup() : HConstants.NO_NONCE;
2518           long nonce = entry.getKey().hasNonce() ? entry.getKey().getNonce() : HConstants.NO_NONCE;
2519           mutations.add(new MutationReplay(MutationType.PUT, m, nonceGroup, nonce));
2520         }
2521       }
2522       if (CellUtil.isDelete(cell)) {
2523         ((Delete) m).addDeleteMarker(cell);
2524       } else {
2525         ((Put) m).add(cell);
2526       }
2527       m.setDurability(durability);
2528       previousCell = cell;
2529     }
2530 
2531     // reconstruct WALKey
2532     if (logEntry != null) {
2533       org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey walKeyProto = entry.getKey();
2534       List<UUID> clusterIds = new ArrayList<UUID>(walKeyProto.getClusterIdsCount());
2535       for (HBaseProtos.UUID uuid : entry.getKey().getClusterIdsList()) {
2536         clusterIds.add(new UUID(uuid.getMostSigBits(), uuid.getLeastSigBits()));
2537       }
2538       // we use HLogKey here instead of WALKey directly to support legacy coprocessors.
2539       key = new HLogKey(walKeyProto.getEncodedRegionName().toByteArray(), TableName.valueOf(
2540               walKeyProto.getTableName().toByteArray()), replaySeqId, walKeyProto.getWriteTime(),
2541               clusterIds, walKeyProto.getNonceGroup(), walKeyProto.getNonce(), null);
2542       logEntry.setFirst(key);
2543       logEntry.setSecond(val);
2544     }
2545 
2546     return mutations;
2547   }
2548 }