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