001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.wal;
019
020import java.io.EOFException;
021import java.io.FileNotFoundException;
022import java.io.IOException;
023import java.io.InterruptedIOException;
024import java.text.ParseException;
025import java.util.ArrayList;
026import java.util.Arrays;
027import java.util.Collections;
028import java.util.HashMap;
029import java.util.List;
030import java.util.Map;
031import java.util.NavigableSet;
032import java.util.Set;
033import java.util.TreeMap;
034import java.util.TreeSet;
035import java.util.UUID;
036import java.util.concurrent.Callable;
037import java.util.concurrent.CompletionService;
038import java.util.concurrent.ConcurrentHashMap;
039import java.util.concurrent.ExecutionException;
040import java.util.concurrent.ExecutorCompletionService;
041import java.util.concurrent.Future;
042import java.util.concurrent.ThreadFactory;
043import java.util.concurrent.ThreadPoolExecutor;
044import java.util.concurrent.TimeUnit;
045import java.util.concurrent.atomic.AtomicLong;
046import java.util.concurrent.atomic.AtomicReference;
047import java.util.regex.Matcher;
048import java.util.regex.Pattern;
049import org.apache.commons.lang3.ArrayUtils;
050import org.apache.hadoop.conf.Configuration;
051import org.apache.hadoop.fs.FileAlreadyExistsException;
052import org.apache.hadoop.fs.FileStatus;
053import org.apache.hadoop.fs.FileSystem;
054import org.apache.hadoop.fs.Path;
055import org.apache.hadoop.fs.PathFilter;
056import org.apache.hadoop.hbase.Cell;
057import org.apache.hadoop.hbase.CellScanner;
058import org.apache.hadoop.hbase.CellUtil;
059import org.apache.hadoop.hbase.HBaseConfiguration;
060import org.apache.hadoop.hbase.HConstants;
061import org.apache.hadoop.hbase.TableName;
062import org.apache.hadoop.hbase.client.Delete;
063import org.apache.hadoop.hbase.client.Durability;
064import org.apache.hadoop.hbase.client.Mutation;
065import org.apache.hadoop.hbase.client.Put;
066import org.apache.hadoop.hbase.coordination.SplitLogWorkerCoordination;
067import org.apache.hadoop.hbase.io.HeapSize;
068import org.apache.hadoop.hbase.log.HBaseMarkers;
069import org.apache.hadoop.hbase.master.SplitLogManager;
070import org.apache.hadoop.hbase.monitoring.MonitoredTask;
071import org.apache.hadoop.hbase.monitoring.TaskMonitor;
072import org.apache.hadoop.hbase.regionserver.HRegion;
073import org.apache.hadoop.hbase.regionserver.LastSequenceId;
074import org.apache.hadoop.hbase.regionserver.wal.AbstractFSWAL;
075import org.apache.hadoop.hbase.regionserver.wal.WALCellCodec;
076import org.apache.hadoop.hbase.util.Bytes;
077import org.apache.hadoop.hbase.util.CancelableProgressable;
078import org.apache.hadoop.hbase.util.ClassSize;
079import org.apache.hadoop.hbase.util.FSUtils;
080import org.apache.hadoop.hbase.util.Pair;
081import org.apache.hadoop.hbase.util.Threads;
082import org.apache.hadoop.hbase.wal.WAL.Entry;
083import org.apache.hadoop.hbase.wal.WAL.Reader;
084import org.apache.hadoop.hbase.wal.WALProvider.Writer;
085import org.apache.hadoop.hbase.zookeeper.ZKSplitLog;
086import org.apache.hadoop.io.MultipleIOException;
087import org.apache.hadoop.ipc.RemoteException;
088import org.apache.yetus.audience.InterfaceAudience;
089import org.slf4j.Logger;
090import org.slf4j.LoggerFactory;
091
092import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
093import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
094import org.apache.hbase.thirdparty.com.google.common.collect.Lists;
095import org.apache.hbase.thirdparty.com.google.protobuf.TextFormat;
096import org.apache.hbase.thirdparty.org.apache.commons.collections4.CollectionUtils;
097import org.apache.hbase.thirdparty.org.apache.commons.collections4.MapUtils;
098
099import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.WALEntry;
100import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.MutationProto.MutationType;
101import org.apache.hadoop.hbase.shaded.protobuf.generated.ClusterStatusProtos.RegionStoreSequenceIds;
102import org.apache.hadoop.hbase.shaded.protobuf.generated.ClusterStatusProtos.StoreSequenceId;
103import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos;
104/**
105 * This class is responsible for splitting up a bunch of regionserver commit log
106 * files that are no longer being written to, into new files, one per region, for
107 * recovering data on startup. Delete the old log files when finished.
108 */
109@InterfaceAudience.Private
110public class WALSplitter {
111  private static final Logger LOG = LoggerFactory.getLogger(WALSplitter.class);
112
113  /** By default we retry errors in splitting, rather than skipping. */
114  public static final boolean SPLIT_SKIP_ERRORS_DEFAULT = false;
115
116  // Parameters for split process
117  protected final Path rootDir;
118  protected final FileSystem fs;
119  protected final Configuration conf;
120
121  // Major subcomponents of the split process.
122  // These are separated into inner classes to make testing easier.
123  OutputSink outputSink;
124  private EntryBuffers entryBuffers;
125
126  private SplitLogWorkerCoordination splitLogWorkerCoordination;
127  private final WALFactory walFactory;
128
129  private MonitoredTask status;
130
131  // For checking the latest flushed sequence id
132  protected final LastSequenceId sequenceIdChecker;
133
134  // Map encodedRegionName -> lastFlushedSequenceId
135  protected Map<String, Long> lastFlushedSequenceIds = new ConcurrentHashMap<>();
136
137  // Map encodedRegionName -> maxSeqIdInStores
138  protected Map<String, Map<byte[], Long>> regionMaxSeqIdInStores = new ConcurrentHashMap<>();
139
140  // the file being split currently
141  private FileStatus fileBeingSplit;
142
143  // if we limit the number of writers opened for sinking recovered edits
144  private final boolean splitWriterCreationBounded;
145
146  public final static String SPLIT_WRITER_CREATION_BOUNDED = "hbase.split.writer.creation.bounded";
147
148
149  @VisibleForTesting
150  WALSplitter(final WALFactory factory, Configuration conf, Path rootDir,
151      FileSystem fs, LastSequenceId idChecker,
152      SplitLogWorkerCoordination splitLogWorkerCoordination) {
153    this.conf = HBaseConfiguration.create(conf);
154    String codecClassName = conf
155        .get(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, WALCellCodec.class.getName());
156    this.conf.set(HConstants.RPC_CODEC_CONF_KEY, codecClassName);
157    this.rootDir = rootDir;
158    this.fs = fs;
159    this.sequenceIdChecker = idChecker;
160    this.splitLogWorkerCoordination = splitLogWorkerCoordination;
161
162    this.walFactory = factory;
163    PipelineController controller = new PipelineController();
164
165    this.splitWriterCreationBounded = conf.getBoolean(SPLIT_WRITER_CREATION_BOUNDED, false);
166
167    entryBuffers = new EntryBuffers(controller,
168        this.conf.getInt("hbase.regionserver.hlog.splitlog.buffersize", 128 * 1024 * 1024),
169        splitWriterCreationBounded);
170
171    int numWriterThreads = this.conf.getInt("hbase.regionserver.hlog.splitlog.writer.threads", 3);
172    if(splitWriterCreationBounded){
173      outputSink = new BoundedLogWriterCreationOutputSink(
174          controller, entryBuffers, numWriterThreads);
175    }else {
176      outputSink = new LogRecoveredEditsOutputSink(controller, entryBuffers, numWriterThreads);
177    }
178  }
179
180  /**
181   * Splits a WAL file into region's recovered-edits directory.
182   * This is the main entry point for distributed log splitting from SplitLogWorker.
183   * <p>
184   * If the log file has N regions then N recovered.edits files will be produced.
185   * <p>
186   * @return false if it is interrupted by the progress-able.
187   */
188  public static boolean splitLogFile(Path rootDir, FileStatus logfile, FileSystem fs,
189      Configuration conf, CancelableProgressable reporter, LastSequenceId idChecker,
190      SplitLogWorkerCoordination splitLogWorkerCoordination, final WALFactory factory)
191      throws IOException {
192    WALSplitter s = new WALSplitter(factory, conf, rootDir, fs, idChecker,
193        splitLogWorkerCoordination);
194    return s.splitLogFile(logfile, reporter);
195  }
196
197  // A wrapper to split one log folder using the method used by distributed
198  // log splitting. Used by tools and unit tests. It should be package private.
199  // It is public only because TestWALObserver is in a different package,
200  // which uses this method to do log splitting.
201  @VisibleForTesting
202  public static List<Path> split(Path rootDir, Path logDir, Path oldLogDir,
203      FileSystem fs, Configuration conf, final WALFactory factory) throws IOException {
204    final FileStatus[] logfiles = SplitLogManager.getFileList(conf,
205        Collections.singletonList(logDir), null);
206    List<Path> splits = new ArrayList<>();
207    if (ArrayUtils.isNotEmpty(logfiles)) {
208      for (FileStatus logfile: logfiles) {
209        WALSplitter s = new WALSplitter(factory, conf, rootDir, fs, null, null);
210        if (s.splitLogFile(logfile, null)) {
211          finishSplitLogFile(rootDir, oldLogDir, logfile.getPath(), conf);
212          if (s.outputSink.splits != null) {
213            splits.addAll(s.outputSink.splits);
214          }
215        }
216      }
217    }
218    if (!fs.delete(logDir, true)) {
219      throw new IOException("Unable to delete src dir: " + logDir);
220    }
221    return splits;
222  }
223
224  /**
225   * log splitting implementation, splits one log file.
226   * @param logfile should be an actual log file.
227   */
228  @VisibleForTesting
229  boolean splitLogFile(FileStatus logfile, CancelableProgressable reporter) throws IOException {
230    Preconditions.checkState(status == null);
231    Preconditions.checkArgument(logfile.isFile(),
232        "passed in file status is for something other than a regular file.");
233    boolean isCorrupted = false;
234    boolean skipErrors = conf.getBoolean("hbase.hlog.split.skip.errors",
235      SPLIT_SKIP_ERRORS_DEFAULT);
236    int interval = conf.getInt("hbase.splitlog.report.interval.loglines", 1024);
237    Path logPath = logfile.getPath();
238    boolean outputSinkStarted = false;
239    boolean progress_failed = false;
240    int editsCount = 0;
241    int editsSkipped = 0;
242
243    status = TaskMonitor.get().createStatus(
244          "Splitting log file " + logfile.getPath() + "into a temporary staging area.");
245    Reader logFileReader = null;
246    this.fileBeingSplit = logfile;
247    try {
248      long logLength = logfile.getLen();
249      LOG.info("Splitting WAL={}, length={}", logPath, logLength);
250      status.setStatus("Opening log file");
251      if (reporter != null && !reporter.progress()) {
252        progress_failed = true;
253        return false;
254      }
255      logFileReader = getReader(logfile, skipErrors, reporter);
256      if (logFileReader == null) {
257        LOG.warn("Nothing to split in WAL={}", logPath);
258        return true;
259      }
260      int numOpenedFilesBeforeReporting = conf.getInt("hbase.splitlog.report.openedfiles", 3);
261      int numOpenedFilesLastCheck = 0;
262      outputSink.setReporter(reporter);
263      outputSink.startWriterThreads();
264      outputSinkStarted = true;
265      Entry entry;
266      Long lastFlushedSequenceId = -1L;
267      while ((entry = getNextLogLine(logFileReader, logPath, skipErrors)) != null) {
268        byte[] region = entry.getKey().getEncodedRegionName();
269        String encodedRegionNameAsStr = Bytes.toString(region);
270        lastFlushedSequenceId = lastFlushedSequenceIds.get(encodedRegionNameAsStr);
271        if (lastFlushedSequenceId == null) {
272          if (sequenceIdChecker != null) {
273            RegionStoreSequenceIds ids = sequenceIdChecker.getLastSequenceId(region);
274            Map<byte[], Long> maxSeqIdInStores = new TreeMap<>(Bytes.BYTES_COMPARATOR);
275            for (StoreSequenceId storeSeqId : ids.getStoreSequenceIdList()) {
276              maxSeqIdInStores.put(storeSeqId.getFamilyName().toByteArray(),
277                storeSeqId.getSequenceId());
278            }
279            regionMaxSeqIdInStores.put(encodedRegionNameAsStr, maxSeqIdInStores);
280            lastFlushedSequenceId = ids.getLastFlushedSequenceId();
281            if (LOG.isDebugEnabled()) {
282              LOG.debug("DLS Last flushed sequenceid for " + encodedRegionNameAsStr + ": " +
283                  TextFormat.shortDebugString(ids));
284            }
285          }
286          if (lastFlushedSequenceId == null) {
287            lastFlushedSequenceId = -1L;
288          }
289          lastFlushedSequenceIds.put(encodedRegionNameAsStr, lastFlushedSequenceId);
290        }
291        if (lastFlushedSequenceId >= entry.getKey().getSequenceId()) {
292          editsSkipped++;
293          continue;
294        }
295        // Don't send Compaction/Close/Open region events to recovered edit type sinks.
296        if (entry.getEdit().isMetaEdit() && !outputSink.keepRegionEvent(entry)) {
297          editsSkipped++;
298          continue;
299        }
300        entryBuffers.appendEntry(entry);
301        editsCount++;
302        int moreWritersFromLastCheck = this.getNumOpenWriters() - numOpenedFilesLastCheck;
303        // If sufficient edits have passed, check if we should report progress.
304        if (editsCount % interval == 0
305            || moreWritersFromLastCheck > numOpenedFilesBeforeReporting) {
306          numOpenedFilesLastCheck = this.getNumOpenWriters();
307          String countsStr = (editsCount - (editsSkipped + outputSink.getSkippedEdits()))
308              + " edits, skipped " + editsSkipped + " edits.";
309          status.setStatus("Split " + countsStr);
310          if (reporter != null && !reporter.progress()) {
311            progress_failed = true;
312            return false;
313          }
314        }
315      }
316    } catch (InterruptedException ie) {
317      IOException iie = new InterruptedIOException();
318      iie.initCause(ie);
319      throw iie;
320    } catch (CorruptedLogFileException e) {
321      LOG.warn("Could not parse, corrupted WAL={}", logPath, e);
322      if (splitLogWorkerCoordination != null) {
323        // Some tests pass in a csm of null.
324        splitLogWorkerCoordination.markCorrupted(rootDir, logfile.getPath().getName(), fs);
325      } else {
326        // for tests only
327        ZKSplitLog.markCorrupted(rootDir, logfile.getPath().getName(), fs);
328      }
329      isCorrupted = true;
330    } catch (IOException e) {
331      e = e instanceof RemoteException ? ((RemoteException) e).unwrapRemoteException() : e;
332      throw e;
333    } finally {
334      LOG.debug("Finishing writing output logs and closing down");
335      try {
336        if (null != logFileReader) {
337          logFileReader.close();
338        }
339      } catch (IOException exception) {
340        LOG.warn("Could not close WAL reader", exception);
341      }
342      try {
343        if (outputSinkStarted) {
344          // Set progress_failed to true as the immediate following statement will reset its value
345          // when finishWritingAndClose() throws exception, progress_failed has the right value
346          progress_failed = true;
347          progress_failed = outputSink.finishWritingAndClose() == null;
348        }
349      } finally {
350        String msg =
351            "Processed " + editsCount + " edits across " + outputSink.getNumberOfRecoveredRegions()
352                + " regions; edits skipped=" + editsSkipped + "; log file=" + logPath +
353                ", length=" + logfile.getLen() + // See if length got updated post lease recovery
354                ", corrupted=" + isCorrupted + ", progress failed=" + progress_failed;
355        LOG.info(msg);
356        status.markComplete(msg);
357      }
358    }
359    return !progress_failed;
360  }
361
362  /**
363   * Completes the work done by splitLogFile by archiving logs
364   * <p>
365   * It is invoked by SplitLogManager once it knows that one of the
366   * SplitLogWorkers have completed the splitLogFile() part. If the master
367   * crashes then this function might get called multiple times.
368   * <p>
369   * @param logfile
370   * @param conf
371   * @throws IOException
372   */
373  public static void finishSplitLogFile(String logfile,
374      Configuration conf)  throws IOException {
375    Path rootdir = FSUtils.getWALRootDir(conf);
376    Path oldLogDir = new Path(rootdir, HConstants.HREGION_OLDLOGDIR_NAME);
377    Path logPath;
378    if (FSUtils.isStartingWithPath(rootdir, logfile)) {
379      logPath = new Path(logfile);
380    } else {
381      logPath = new Path(rootdir, logfile);
382    }
383    finishSplitLogFile(rootdir, oldLogDir, logPath, conf);
384  }
385
386  private static void finishSplitLogFile(Path rootdir, Path oldLogDir,
387      Path logPath, Configuration conf) throws IOException {
388    List<Path> processedLogs = new ArrayList<>();
389    List<Path> corruptedLogs = new ArrayList<>();
390    FileSystem fs;
391    fs = rootdir.getFileSystem(conf);
392    if (ZKSplitLog.isCorrupted(rootdir, logPath.getName(), fs)) {
393      corruptedLogs.add(logPath);
394    } else {
395      processedLogs.add(logPath);
396    }
397    archiveLogs(corruptedLogs, processedLogs, oldLogDir, fs, conf);
398    Path stagingDir = ZKSplitLog.getSplitLogDir(rootdir, logPath.getName());
399    fs.delete(stagingDir, true);
400  }
401
402  /**
403   * Moves processed logs to a oldLogDir after successful processing Moves
404   * corrupted logs (any log that couldn't be successfully parsed to corruptDir
405   * (.corrupt) for later investigation
406   *
407   * @param corruptedLogs
408   * @param processedLogs
409   * @param oldLogDir
410   * @param fs
411   * @param conf
412   * @throws IOException
413   */
414  private static void archiveLogs(
415      final List<Path> corruptedLogs,
416      final List<Path> processedLogs, final Path oldLogDir,
417      final FileSystem fs, final Configuration conf) throws IOException {
418    final Path corruptDir = new Path(FSUtils.getWALRootDir(conf), HConstants.CORRUPT_DIR_NAME);
419    if (conf.get("hbase.regionserver.hlog.splitlog.corrupt.dir") != null) {
420      LOG.warn("hbase.regionserver.hlog.splitlog.corrupt.dir is deprecated. Default to {}",
421          corruptDir);
422    }
423    if (!fs.mkdirs(corruptDir)) {
424      LOG.info("Unable to mkdir {}", corruptDir);
425    }
426    fs.mkdirs(oldLogDir);
427
428    // this method can get restarted or called multiple times for archiving
429    // the same log files.
430    for (Path corrupted : corruptedLogs) {
431      Path p = new Path(corruptDir, corrupted.getName());
432      if (fs.exists(corrupted)) {
433        if (!fs.rename(corrupted, p)) {
434          LOG.warn("Unable to move corrupted log {} to {}", corrupted, p);
435        } else {
436          LOG.warn("Moved corrupted log {} to {}", corrupted, p);
437        }
438      }
439    }
440
441    for (Path p : processedLogs) {
442      Path newPath = AbstractFSWAL.getWALArchivePath(oldLogDir, p);
443      if (fs.exists(p)) {
444        if (!FSUtils.renameAndSetModifyTime(fs, p, newPath)) {
445          LOG.warn("Unable to move {} to {}", p, newPath);
446        } else {
447          LOG.info("Archived processed log {} to {}", p, newPath);
448        }
449      }
450    }
451  }
452
453  /**
454   * Path to a file under RECOVERED_EDITS_DIR directory of the region found in
455   * <code>logEntry</code> named for the sequenceid in the passed
456   * <code>logEntry</code>: e.g. /hbase/some_table/2323432434/recovered.edits/2332.
457   * This method also ensures existence of RECOVERED_EDITS_DIR under the region
458   * creating it if necessary.
459   * @param fs
460   * @param logEntry
461   * @param rootDir HBase root dir.
462   * @param fileNameBeingSplit the file being split currently. Used to generate tmp file name.
463   * @return Path to file into which to dump split log edits.
464   * @throws IOException
465   */
466  @SuppressWarnings("deprecation")
467  @VisibleForTesting
468  static Path getRegionSplitEditsPath(final FileSystem fs,
469      final Entry logEntry, final Path rootDir, String fileNameBeingSplit)
470  throws IOException {
471    Path tableDir = FSUtils.getTableDir(rootDir, logEntry.getKey().getTableName());
472    String encodedRegionName = Bytes.toString(logEntry.getKey().getEncodedRegionName());
473    Path regiondir = HRegion.getRegionDir(tableDir, encodedRegionName);
474    Path dir = getRegionDirRecoveredEditsDir(regiondir);
475
476    if (!fs.exists(regiondir)) {
477      LOG.info("This region's directory does not exist: {}."
478          + "It is very likely that it was already split so it is "
479          + "safe to discard those edits.", regiondir);
480      return null;
481    }
482    if (fs.exists(dir) && fs.isFile(dir)) {
483      Path tmp = new Path("/tmp");
484      if (!fs.exists(tmp)) {
485        fs.mkdirs(tmp);
486      }
487      tmp = new Path(tmp,
488        HConstants.RECOVERED_EDITS_DIR + "_" + encodedRegionName);
489      LOG.warn("Found existing old file: {}. It could be some "
490        + "leftover of an old installation. It should be a folder instead. "
491        + "So moving it to {}", dir, tmp);
492      if (!fs.rename(dir, tmp)) {
493        LOG.warn("Failed to sideline old file {}", dir);
494      }
495    }
496
497    if (!fs.exists(dir) && !fs.mkdirs(dir)) {
498      LOG.warn("mkdir failed on {}", dir);
499    }
500    // Append fileBeingSplit to prevent name conflict since we may have duplicate wal entries now.
501    // Append file name ends with RECOVERED_LOG_TMPFILE_SUFFIX to ensure
502    // region's replayRecoveredEdits will not delete it
503    String fileName = formatRecoveredEditsFileName(logEntry.getKey().getSequenceId());
504    fileName = getTmpRecoveredEditsFileName(fileName + "-" + fileNameBeingSplit);
505    return new Path(dir, fileName);
506  }
507
508  private static String getTmpRecoveredEditsFileName(String fileName) {
509    return fileName + RECOVERED_LOG_TMPFILE_SUFFIX;
510  }
511
512  /**
513   * Get the completed recovered edits file path, renaming it to be by last edit
514   * in the file from its first edit. Then we could use the name to skip
515   * recovered edits when doing {@link HRegion#replayRecoveredEditsIfAny}.
516   * @param srcPath
517   * @param maximumEditLogSeqNum
518   * @return dstPath take file's last edit log seq num as the name
519   */
520  private static Path getCompletedRecoveredEditsFilePath(Path srcPath,
521      long maximumEditLogSeqNum) {
522    String fileName = formatRecoveredEditsFileName(maximumEditLogSeqNum);
523    return new Path(srcPath.getParent(), fileName);
524  }
525
526  @VisibleForTesting
527  static String formatRecoveredEditsFileName(final long seqid) {
528    return String.format("%019d", seqid);
529  }
530
531  private static final Pattern EDITFILES_NAME_PATTERN = Pattern.compile("-?[0-9]+");
532  private static final String RECOVERED_LOG_TMPFILE_SUFFIX = ".temp";
533
534  /**
535   * @param regiondir
536   *          This regions directory in the filesystem.
537   * @return The directory that holds recovered edits files for the region
538   *         <code>regiondir</code>
539   */
540  public static Path getRegionDirRecoveredEditsDir(final Path regiondir) {
541    return new Path(regiondir, HConstants.RECOVERED_EDITS_DIR);
542  }
543
544  /**
545   * Returns sorted set of edit files made by splitter, excluding files
546   * with '.temp' suffix.
547   *
548   * @param fs
549   * @param regiondir
550   * @return Files in passed <code>regiondir</code> as a sorted set.
551   * @throws IOException
552   */
553  public static NavigableSet<Path> getSplitEditFilesSorted(final FileSystem fs,
554      final Path regiondir) throws IOException {
555    NavigableSet<Path> filesSorted = new TreeSet<>();
556    Path editsdir = getRegionDirRecoveredEditsDir(regiondir);
557    if (!fs.exists(editsdir)) {
558      return filesSorted;
559    }
560    FileStatus[] files = FSUtils.listStatus(fs, editsdir, new PathFilter() {
561      @Override
562      public boolean accept(Path p) {
563        boolean result = false;
564        try {
565          // Return files and only files that match the editfile names pattern.
566          // There can be other files in this directory other than edit files.
567          // In particular, on error, we'll move aside the bad edit file giving
568          // it a timestamp suffix. See moveAsideBadEditsFile.
569          Matcher m = EDITFILES_NAME_PATTERN.matcher(p.getName());
570          result = fs.isFile(p) && m.matches();
571          // Skip the file whose name ends with RECOVERED_LOG_TMPFILE_SUFFIX,
572          // because it means splitwal thread is writting this file.
573          if (p.getName().endsWith(RECOVERED_LOG_TMPFILE_SUFFIX)) {
574            result = false;
575          }
576          // Skip SeqId Files
577          if (isSequenceIdFile(p)) {
578            result = false;
579          }
580        } catch (IOException e) {
581          LOG.warn("Failed isFile check on {}", p, e);
582        }
583        return result;
584      }
585    });
586    if (ArrayUtils.isNotEmpty(files)) {
587      Arrays.asList(files).forEach(status -> filesSorted.add(status.getPath()));
588    }
589    return filesSorted;
590  }
591
592  /**
593   * Move aside a bad edits file.
594   *
595   * @param fs
596   * @param edits
597   *          Edits file to move aside.
598   * @return The name of the moved aside file.
599   * @throws IOException
600   */
601  public static Path moveAsideBadEditsFile(final FileSystem fs, final Path edits)
602      throws IOException {
603    Path moveAsideName = new Path(edits.getParent(), edits.getName() + "."
604        + System.currentTimeMillis());
605    if (!fs.rename(edits, moveAsideName)) {
606      LOG.warn("Rename failed from {} to {}", edits, moveAsideName);
607    }
608    return moveAsideName;
609  }
610
611  private static final String SEQUENCE_ID_FILE_SUFFIX = ".seqid";
612  private static final String OLD_SEQUENCE_ID_FILE_SUFFIX = "_seqid";
613  private static final int SEQUENCE_ID_FILE_SUFFIX_LENGTH = SEQUENCE_ID_FILE_SUFFIX.length();
614
615  /**
616   * Is the given file a region open sequence id file.
617   */
618  @VisibleForTesting
619  public static boolean isSequenceIdFile(final Path file) {
620    return file.getName().endsWith(SEQUENCE_ID_FILE_SUFFIX)
621        || file.getName().endsWith(OLD_SEQUENCE_ID_FILE_SUFFIX);
622  }
623
624  private static FileStatus[] getSequenceIdFiles(FileSystem fs, Path regionDir) throws IOException {
625    // TODO: Why are we using a method in here as part of our normal region open where
626    // there is no splitting involved? Fix. St.Ack 01/20/2017.
627    Path editsDir = WALSplitter.getRegionDirRecoveredEditsDir(regionDir);
628    try {
629      FileStatus[] files = fs.listStatus(editsDir, WALSplitter::isSequenceIdFile);
630      return files != null ? files : new FileStatus[0];
631    } catch (FileNotFoundException e) {
632      return new FileStatus[0];
633    }
634  }
635
636  private static long getMaxSequenceId(FileStatus[] files) {
637    long maxSeqId = -1L;
638    for (FileStatus file : files) {
639      String fileName = file.getPath().getName();
640      try {
641        maxSeqId = Math.max(maxSeqId, Long
642          .parseLong(fileName.substring(0, fileName.length() - SEQUENCE_ID_FILE_SUFFIX_LENGTH)));
643      } catch (NumberFormatException ex) {
644        LOG.warn("Invalid SeqId File Name={}", fileName);
645      }
646    }
647    return maxSeqId;
648  }
649
650  /**
651   * Get the max sequence id which is stored in the region directory. -1 if none.
652   */
653  public static long getMaxRegionSequenceId(FileSystem fs, Path regionDir) throws IOException {
654    return getMaxSequenceId(getSequenceIdFiles(fs, regionDir));
655  }
656
657  /**
658   * Create a file with name as region's max sequence id
659   */
660  public static void writeRegionSequenceIdFile(FileSystem fs, Path regionDir, long newMaxSeqId)
661      throws IOException {
662    FileStatus[] files = getSequenceIdFiles(fs, regionDir);
663    long maxSeqId = getMaxSequenceId(files);
664    if (maxSeqId > newMaxSeqId) {
665      throw new IOException("The new max sequence id " + newMaxSeqId +
666        " is less than the old max sequence id " + maxSeqId);
667    }
668    // write a new seqId file
669    Path newSeqIdFile = new Path(WALSplitter.getRegionDirRecoveredEditsDir(regionDir),
670      newMaxSeqId + SEQUENCE_ID_FILE_SUFFIX);
671    if (newMaxSeqId != maxSeqId) {
672      try {
673        if (!fs.createNewFile(newSeqIdFile) && !fs.exists(newSeqIdFile)) {
674          throw new IOException("Failed to create SeqId file:" + newSeqIdFile);
675        }
676        LOG.debug("Wrote file={}, newMaxSeqId={}, maxSeqId={}", newSeqIdFile, newMaxSeqId,
677          maxSeqId);
678      } catch (FileAlreadyExistsException ignored) {
679        // latest hdfs throws this exception. it's all right if newSeqIdFile already exists
680      }
681    }
682    // remove old ones
683    for (FileStatus status : files) {
684      if (!newSeqIdFile.equals(status.getPath())) {
685        fs.delete(status.getPath(), false);
686      }
687    }
688  }
689
690  /**
691   * Create a new {@link Reader} for reading logs to split.
692   *
693   * @param file
694   * @return A new Reader instance, caller should close
695   * @throws IOException
696   * @throws CorruptedLogFileException
697   */
698  protected Reader getReader(FileStatus file, boolean skipErrors, CancelableProgressable reporter)
699      throws IOException, CorruptedLogFileException {
700    Path path = file.getPath();
701    long length = file.getLen();
702    Reader in;
703
704    // Check for possibly empty file. With appends, currently Hadoop reports a
705    // zero length even if the file has been sync'd. Revisit if HDFS-376 or
706    // HDFS-878 is committed.
707    if (length <= 0) {
708      LOG.warn("File {} might be still open, length is 0", path);
709    }
710
711    try {
712      FSUtils.getInstance(fs, conf).recoverFileLease(fs, path, conf, reporter);
713      try {
714        in = getReader(path, reporter);
715      } catch (EOFException e) {
716        if (length <= 0) {
717          // TODO should we ignore an empty, not-last log file if skip.errors
718          // is false? Either way, the caller should decide what to do. E.g.
719          // ignore if this is the last log in sequence.
720          // TODO is this scenario still possible if the log has been
721          // recovered (i.e. closed)
722          LOG.warn("Could not open {} for reading. File is empty", path, e);
723        }
724        // EOFException being ignored
725        return null;
726      }
727    } catch (IOException e) {
728      if (e instanceof FileNotFoundException) {
729        // A wal file may not exist anymore. Nothing can be recovered so move on
730        LOG.warn("File {} does not exist anymore", path, e);
731        return null;
732      }
733      if (!skipErrors || e instanceof InterruptedIOException) {
734        throw e; // Don't mark the file corrupted if interrupted, or not skipErrors
735      }
736      CorruptedLogFileException t =
737        new CorruptedLogFileException("skipErrors=true Could not open wal " +
738            path + " ignoring");
739      t.initCause(e);
740      throw t;
741    }
742    return in;
743  }
744
745  static private Entry getNextLogLine(Reader in, Path path, boolean skipErrors)
746  throws CorruptedLogFileException, IOException {
747    try {
748      return in.next();
749    } catch (EOFException eof) {
750      // truncated files are expected if a RS crashes (see HBASE-2643)
751      LOG.info("EOF from wal {}. Continuing.", path);
752      return null;
753    } catch (IOException e) {
754      // If the IOE resulted from bad file format,
755      // then this problem is idempotent and retrying won't help
756      if (e.getCause() != null &&
757          (e.getCause() instanceof ParseException ||
758           e.getCause() instanceof org.apache.hadoop.fs.ChecksumException)) {
759        LOG.warn("Parse exception from wal {}. Continuing", path, e);
760        return null;
761      }
762      if (!skipErrors) {
763        throw e;
764      }
765      CorruptedLogFileException t =
766        new CorruptedLogFileException("skipErrors=true Ignoring exception" +
767            " while parsing wal " + path + ". Marking as corrupted");
768      t.initCause(e);
769      throw t;
770    }
771  }
772
773  /**
774   * Create a new {@link Writer} for writing log splits.
775   * @return a new Writer instance, caller should close
776   */
777  protected Writer createWriter(Path logfile)
778      throws IOException {
779    return walFactory.createRecoveredEditsWriter(fs, logfile);
780  }
781
782  /**
783   * Create a new {@link Reader} for reading logs to split.
784   * @return new Reader instance, caller should close
785   */
786  protected Reader getReader(Path curLogFile, CancelableProgressable reporter) throws IOException {
787    return walFactory.createReader(fs, curLogFile, reporter);
788  }
789
790  /**
791   * Get current open writers
792   */
793  private int getNumOpenWriters() {
794    int result = 0;
795    if (this.outputSink != null) {
796      result += this.outputSink.getNumOpenWriters();
797    }
798    return result;
799  }
800
801  /**
802   * Contains some methods to control WAL-entries producer / consumer interactions
803   */
804  public static class PipelineController {
805    // If an exception is thrown by one of the other threads, it will be
806    // stored here.
807    AtomicReference<Throwable> thrown = new AtomicReference<>();
808
809    // Wait/notify for when data has been produced by the writer thread,
810    // consumed by the reader thread, or an exception occurred
811    public final Object dataAvailable = new Object();
812
813    void writerThreadError(Throwable t) {
814      thrown.compareAndSet(null, t);
815    }
816
817    /**
818     * Check for errors in the writer threads. If any is found, rethrow it.
819     */
820    void checkForErrors() throws IOException {
821      Throwable thrown = this.thrown.get();
822      if (thrown == null) return;
823      if (thrown instanceof IOException) {
824        throw new IOException(thrown);
825      } else {
826        throw new RuntimeException(thrown);
827      }
828    }
829  }
830
831  /**
832   * Class which accumulates edits and separates them into a buffer per region
833   * while simultaneously accounting RAM usage. Blocks if the RAM usage crosses
834   * a predefined threshold.
835   *
836   * Writer threads then pull region-specific buffers from this class.
837   */
838  public static class EntryBuffers {
839    PipelineController controller;
840
841    Map<byte[], RegionEntryBuffer> buffers = new TreeMap<>(Bytes.BYTES_COMPARATOR);
842
843    /* Track which regions are currently in the middle of writing. We don't allow
844       an IO thread to pick up bytes from a region if we're already writing
845       data for that region in a different IO thread. */
846    Set<byte[]> currentlyWriting = new TreeSet<>(Bytes.BYTES_COMPARATOR);
847
848    long totalBuffered = 0;
849    long maxHeapUsage;
850    boolean splitWriterCreationBounded;
851
852    public EntryBuffers(PipelineController controller, long maxHeapUsage) {
853      this(controller, maxHeapUsage, false);
854    }
855
856    public EntryBuffers(PipelineController controller, long maxHeapUsage,
857        boolean splitWriterCreationBounded){
858      this.controller = controller;
859      this.maxHeapUsage = maxHeapUsage;
860      this.splitWriterCreationBounded = splitWriterCreationBounded;
861    }
862
863    /**
864     * Append a log entry into the corresponding region buffer.
865     * Blocks if the total heap usage has crossed the specified threshold.
866     *
867     * @throws InterruptedException
868     * @throws IOException
869     */
870    public void appendEntry(Entry entry) throws InterruptedException, IOException {
871      WALKey key = entry.getKey();
872
873      RegionEntryBuffer buffer;
874      long incrHeap;
875      synchronized (this) {
876        buffer = buffers.get(key.getEncodedRegionName());
877        if (buffer == null) {
878          buffer = new RegionEntryBuffer(key.getTableName(), key.getEncodedRegionName());
879          buffers.put(key.getEncodedRegionName(), buffer);
880        }
881        incrHeap= buffer.appendEntry(entry);
882      }
883
884      // If we crossed the chunk threshold, wait for more space to be available
885      synchronized (controller.dataAvailable) {
886        totalBuffered += incrHeap;
887        while (totalBuffered > maxHeapUsage && controller.thrown.get() == null) {
888          LOG.debug("Used {} bytes of buffered edits, waiting for IO threads", totalBuffered);
889          controller.dataAvailable.wait(2000);
890        }
891        controller.dataAvailable.notifyAll();
892      }
893      controller.checkForErrors();
894    }
895
896    /**
897     * @return RegionEntryBuffer a buffer of edits to be written.
898     */
899    synchronized RegionEntryBuffer getChunkToWrite() {
900      // The core part of limiting opening writers is it doesn't return chunk only if the
901      // heap size is over maxHeapUsage. Thus it doesn't need to create a writer for each
902      // region during splitting. It will flush all the logs in the buffer after splitting
903      // through a threadpool, which means the number of writers it created is under control.
904      if (splitWriterCreationBounded && totalBuffered < maxHeapUsage) {
905        return null;
906      }
907      long biggestSize = 0;
908      byte[] biggestBufferKey = null;
909
910      for (Map.Entry<byte[], RegionEntryBuffer> entry : buffers.entrySet()) {
911        long size = entry.getValue().heapSize();
912        if (size > biggestSize && (!currentlyWriting.contains(entry.getKey()))) {
913          biggestSize = size;
914          biggestBufferKey = entry.getKey();
915        }
916      }
917      if (biggestBufferKey == null) {
918        return null;
919      }
920
921      RegionEntryBuffer buffer = buffers.remove(biggestBufferKey);
922      currentlyWriting.add(biggestBufferKey);
923      return buffer;
924    }
925
926    void doneWriting(RegionEntryBuffer buffer) {
927      synchronized (this) {
928        boolean removed = currentlyWriting.remove(buffer.encodedRegionName);
929        assert removed;
930      }
931      long size = buffer.heapSize();
932
933      synchronized (controller.dataAvailable) {
934        totalBuffered -= size;
935        // We may unblock writers
936        controller.dataAvailable.notifyAll();
937      }
938    }
939
940    synchronized boolean isRegionCurrentlyWriting(byte[] region) {
941      return currentlyWriting.contains(region);
942    }
943
944    public void waitUntilDrained() {
945      synchronized (controller.dataAvailable) {
946        while (totalBuffered > 0) {
947          try {
948            controller.dataAvailable.wait(2000);
949          } catch (InterruptedException e) {
950            LOG.warn("Got interrupted while waiting for EntryBuffers is drained");
951            Thread.interrupted();
952            break;
953          }
954        }
955      }
956    }
957  }
958
959  /**
960   * A buffer of some number of edits for a given region.
961   * This accumulates edits and also provides a memory optimization in order to
962   * share a single byte array instance for the table and region name.
963   * Also tracks memory usage of the accumulated edits.
964   */
965  public static class RegionEntryBuffer implements HeapSize {
966    long heapInBuffer = 0;
967    List<Entry> entryBuffer;
968    TableName tableName;
969    byte[] encodedRegionName;
970
971    RegionEntryBuffer(TableName tableName, byte[] region) {
972      this.tableName = tableName;
973      this.encodedRegionName = region;
974      this.entryBuffer = new ArrayList<>();
975    }
976
977    long appendEntry(Entry entry) {
978      internify(entry);
979      entryBuffer.add(entry);
980      long incrHeap = entry.getEdit().heapSize() +
981        ClassSize.align(2 * ClassSize.REFERENCE) + // WALKey pointers
982        0; // TODO linkedlist entry
983      heapInBuffer += incrHeap;
984      return incrHeap;
985    }
986
987    private void internify(Entry entry) {
988      WALKeyImpl k = entry.getKey();
989      k.internTableName(this.tableName);
990      k.internEncodedRegionName(this.encodedRegionName);
991    }
992
993    @Override
994    public long heapSize() {
995      return heapInBuffer;
996    }
997
998    public byte[] getEncodedRegionName() {
999      return encodedRegionName;
1000    }
1001
1002    public List<Entry> getEntryBuffer() {
1003      return entryBuffer;
1004    }
1005
1006    public TableName getTableName() {
1007      return tableName;
1008    }
1009  }
1010
1011  public static class WriterThread extends Thread {
1012    private volatile boolean shouldStop = false;
1013    private PipelineController controller;
1014    private EntryBuffers entryBuffers;
1015    private OutputSink outputSink = null;
1016
1017    WriterThread(PipelineController controller, EntryBuffers entryBuffers, OutputSink sink, int i){
1018      super(Thread.currentThread().getName() + "-Writer-" + i);
1019      this.controller = controller;
1020      this.entryBuffers = entryBuffers;
1021      outputSink = sink;
1022    }
1023
1024    @Override
1025    public void run()  {
1026      try {
1027        doRun();
1028      } catch (Throwable t) {
1029        LOG.error("Exiting thread", t);
1030        controller.writerThreadError(t);
1031      }
1032    }
1033
1034    private void doRun() throws IOException {
1035      LOG.trace("Writer thread starting");
1036      while (true) {
1037        RegionEntryBuffer buffer = entryBuffers.getChunkToWrite();
1038        if (buffer == null) {
1039          // No data currently available, wait on some more to show up
1040          synchronized (controller.dataAvailable) {
1041            if (shouldStop && !this.outputSink.flush()) {
1042              return;
1043            }
1044            try {
1045              controller.dataAvailable.wait(500);
1046            } catch (InterruptedException ie) {
1047              if (!shouldStop) {
1048                throw new RuntimeException(ie);
1049              }
1050            }
1051          }
1052          continue;
1053        }
1054
1055        assert buffer != null;
1056        try {
1057          writeBuffer(buffer);
1058        } finally {
1059          entryBuffers.doneWriting(buffer);
1060        }
1061      }
1062    }
1063
1064    private void writeBuffer(RegionEntryBuffer buffer) throws IOException {
1065      outputSink.append(buffer);
1066    }
1067
1068    void finish() {
1069      synchronized (controller.dataAvailable) {
1070        shouldStop = true;
1071        controller.dataAvailable.notifyAll();
1072      }
1073    }
1074  }
1075
1076  /**
1077   * The following class is an abstraction class to provide a common interface to support
1078   * different ways of consuming recovered edits.
1079   */
1080  public static abstract class OutputSink {
1081
1082    protected PipelineController controller;
1083    protected EntryBuffers entryBuffers;
1084
1085    protected ConcurrentHashMap<String, SinkWriter> writers = new ConcurrentHashMap<>();
1086    protected final ConcurrentHashMap<String, Long> regionMaximumEditLogSeqNum =
1087        new ConcurrentHashMap<>();
1088
1089
1090    protected final List<WriterThread> writerThreads = Lists.newArrayList();
1091
1092    /* Set of regions which we've decided should not output edits */
1093    protected final Set<byte[]> blacklistedRegions = Collections
1094        .synchronizedSet(new TreeSet<>(Bytes.BYTES_COMPARATOR));
1095
1096    protected boolean closeAndCleanCompleted = false;
1097
1098    protected boolean writersClosed = false;
1099
1100    protected final int numThreads;
1101
1102    protected CancelableProgressable reporter = null;
1103
1104    protected AtomicLong skippedEdits = new AtomicLong();
1105
1106    protected List<Path> splits = null;
1107
1108    public OutputSink(PipelineController controller, EntryBuffers entryBuffers, int numWriters) {
1109      numThreads = numWriters;
1110      this.controller = controller;
1111      this.entryBuffers = entryBuffers;
1112    }
1113
1114    void setReporter(CancelableProgressable reporter) {
1115      this.reporter = reporter;
1116    }
1117
1118    /**
1119     * Start the threads that will pump data from the entryBuffers to the output files.
1120     */
1121    public synchronized void startWriterThreads() {
1122      for (int i = 0; i < numThreads; i++) {
1123        WriterThread t = new WriterThread(controller, entryBuffers, this, i);
1124        t.start();
1125        writerThreads.add(t);
1126      }
1127    }
1128
1129    /**
1130     *
1131     * Update region's maximum edit log SeqNum.
1132     */
1133    void updateRegionMaximumEditLogSeqNum(Entry entry) {
1134      synchronized (regionMaximumEditLogSeqNum) {
1135        String regionName = Bytes.toString(entry.getKey().getEncodedRegionName());
1136        Long currentMaxSeqNum = regionMaximumEditLogSeqNum.get(regionName);
1137        if (currentMaxSeqNum == null || entry.getKey().getSequenceId() > currentMaxSeqNum) {
1138          regionMaximumEditLogSeqNum.put(regionName, entry.getKey().getSequenceId());
1139        }
1140      }
1141    }
1142
1143    /**
1144     * @return the number of currently opened writers
1145     */
1146    int getNumOpenWriters() {
1147      return this.writers.size();
1148    }
1149
1150    long getSkippedEdits() {
1151      return this.skippedEdits.get();
1152    }
1153
1154    /**
1155     * Wait for writer threads to dump all info to the sink
1156     * @return true when there is no error
1157     * @throws IOException
1158     */
1159    protected boolean finishWriting(boolean interrupt) throws IOException {
1160      LOG.debug("Waiting for split writer threads to finish");
1161      boolean progress_failed = false;
1162      for (WriterThread t : writerThreads) {
1163        t.finish();
1164      }
1165      if (interrupt) {
1166        for (WriterThread t : writerThreads) {
1167          t.interrupt(); // interrupt the writer threads. We are stopping now.
1168        }
1169      }
1170
1171      for (WriterThread t : writerThreads) {
1172        if (!progress_failed && reporter != null && !reporter.progress()) {
1173          progress_failed = true;
1174        }
1175        try {
1176          t.join();
1177        } catch (InterruptedException ie) {
1178          IOException iie = new InterruptedIOException();
1179          iie.initCause(ie);
1180          throw iie;
1181        }
1182      }
1183      controller.checkForErrors();
1184      LOG.info("{} split writers finished; closing.", this.writerThreads.size());
1185      return (!progress_failed);
1186    }
1187
1188    public abstract List<Path> finishWritingAndClose() throws IOException;
1189
1190    /**
1191     * @return a map from encoded region ID to the number of edits written out for that region.
1192     */
1193    public abstract Map<byte[], Long> getOutputCounts();
1194
1195    /**
1196     * @return number of regions we've recovered
1197     */
1198    public abstract int getNumberOfRecoveredRegions();
1199
1200    /**
1201     * @param buffer A WAL Edit Entry
1202     * @throws IOException
1203     */
1204    public abstract void append(RegionEntryBuffer buffer) throws IOException;
1205
1206    /**
1207     * WriterThread call this function to help flush internal remaining edits in buffer before close
1208     * @return true when underlying sink has something to flush
1209     */
1210    public boolean flush() throws IOException {
1211      return false;
1212    }
1213
1214    /**
1215     * Some WALEdit's contain only KV's for account on what happened to a region.
1216     * Not all sinks will want to get all of those edits.
1217     *
1218     * @return Return true if this sink wants to accept this region-level WALEdit.
1219     */
1220    public abstract boolean keepRegionEvent(Entry entry);
1221  }
1222
1223  /**
1224   * Class that manages the output streams from the log splitting process.
1225   */
1226  class LogRecoveredEditsOutputSink extends OutputSink {
1227
1228    public LogRecoveredEditsOutputSink(PipelineController controller, EntryBuffers entryBuffers,
1229        int numWriters) {
1230      // More threads could potentially write faster at the expense
1231      // of causing more disk seeks as the logs are split.
1232      // 3. After a certain setting (probably around 3) the
1233      // process will be bound on the reader in the current
1234      // implementation anyway.
1235      super(controller, entryBuffers, numWriters);
1236    }
1237
1238    /**
1239     * @return null if failed to report progress
1240     * @throws IOException
1241     */
1242    @Override
1243    public List<Path> finishWritingAndClose() throws IOException {
1244      boolean isSuccessful = false;
1245      List<Path> result = null;
1246      try {
1247        isSuccessful = finishWriting(false);
1248      } finally {
1249        result = close();
1250        List<IOException> thrown = closeLogWriters(null);
1251        if (CollectionUtils.isNotEmpty(thrown)) {
1252          throw MultipleIOException.createIOException(thrown);
1253        }
1254      }
1255      if (isSuccessful) {
1256        splits = result;
1257      }
1258      return splits;
1259    }
1260
1261    // delete the one with fewer wal entries
1262    private void deleteOneWithFewerEntries(WriterAndPath wap, Path dst) throws IOException {
1263      long dstMinLogSeqNum = -1L;
1264      try (WAL.Reader reader = walFactory.createReader(fs, dst)) {
1265        WAL.Entry entry = reader.next();
1266        if (entry != null) {
1267          dstMinLogSeqNum = entry.getKey().getSequenceId();
1268        }
1269      } catch (EOFException e) {
1270        LOG.debug("Got EOF when reading first WAL entry from {}, an empty or broken WAL file?",
1271            dst, e);
1272      }
1273      if (wap.minLogSeqNum < dstMinLogSeqNum) {
1274        LOG.warn("Found existing old edits file. It could be the result of a previous failed"
1275            + " split attempt or we have duplicated wal entries. Deleting " + dst + ", length="
1276            + fs.getFileStatus(dst).getLen());
1277        if (!fs.delete(dst, false)) {
1278          LOG.warn("Failed deleting of old {}", dst);
1279          throw new IOException("Failed deleting of old " + dst);
1280        }
1281      } else {
1282        LOG.warn("Found existing old edits file and we have less entries. Deleting " + wap.p
1283            + ", length=" + fs.getFileStatus(wap.p).getLen());
1284        if (!fs.delete(wap.p, false)) {
1285          LOG.warn("Failed deleting of {}", wap.p);
1286          throw new IOException("Failed deleting of " + wap.p);
1287        }
1288      }
1289    }
1290
1291    /**
1292     * Close all of the output streams.
1293     * @return the list of paths written.
1294     */
1295    List<Path> close() throws IOException {
1296      Preconditions.checkState(!closeAndCleanCompleted);
1297
1298      final List<Path> paths = new ArrayList<>();
1299      final List<IOException> thrown = Lists.newArrayList();
1300      ThreadPoolExecutor closeThreadPool = Threads
1301          .getBoundedCachedThreadPool(numThreads, 30L, TimeUnit.SECONDS, new ThreadFactory() {
1302            private int count = 1;
1303
1304            @Override public Thread newThread(Runnable r) {
1305              Thread t = new Thread(r, "split-log-closeStream-" + count++);
1306              return t;
1307            }
1308          });
1309      CompletionService<Void> completionService = new ExecutorCompletionService<>(closeThreadPool);
1310      boolean progress_failed;
1311      try {
1312        progress_failed = executeCloseTask(completionService, thrown, paths);
1313      } catch (InterruptedException e) {
1314        IOException iie = new InterruptedIOException();
1315        iie.initCause(e);
1316        throw iie;
1317      } catch (ExecutionException e) {
1318        throw new IOException(e.getCause());
1319      } finally {
1320        closeThreadPool.shutdownNow();
1321      }
1322      if (!thrown.isEmpty()) {
1323        throw MultipleIOException.createIOException(thrown);
1324      }
1325      writersClosed = true;
1326      closeAndCleanCompleted = true;
1327      if (progress_failed) {
1328        return null;
1329      }
1330      return paths;
1331    }
1332
1333    /**
1334     * @param completionService threadPool to execute the closing tasks
1335     * @param thrown store the exceptions
1336     * @param paths arrayList to store the paths written
1337     * @return if close tasks executed successful
1338     */
1339    boolean executeCloseTask(CompletionService<Void> completionService,
1340        List<IOException> thrown, List<Path> paths)
1341        throws InterruptedException, ExecutionException {
1342      for (final Map.Entry<String, SinkWriter> writersEntry : writers.entrySet()) {
1343        if (LOG.isTraceEnabled()) {
1344          LOG.trace("Submitting close of " + ((WriterAndPath) writersEntry.getValue()).p);
1345        }
1346        completionService.submit(new Callable<Void>() {
1347          @Override public Void call() throws Exception {
1348            WriterAndPath wap = (WriterAndPath) writersEntry.getValue();
1349            Path dst = closeWriter(writersEntry.getKey(), wap, thrown);
1350            paths.add(dst);
1351            return null;
1352          }
1353        });
1354      }
1355      boolean progress_failed = false;
1356      for (int i = 0, n = this.writers.size(); i < n; i++) {
1357        Future<Void> future = completionService.take();
1358        future.get();
1359        if (!progress_failed && reporter != null && !reporter.progress()) {
1360          progress_failed = true;
1361        }
1362      }
1363      return progress_failed;
1364    }
1365
1366    Path closeWriter(String encodedRegionName, WriterAndPath wap,
1367        List<IOException> thrown) throws IOException{
1368      if (LOG.isTraceEnabled()) {
1369        LOG.trace("Closing " + wap.p);
1370      }
1371      try {
1372        wap.w.close();
1373      } catch (IOException ioe) {
1374        LOG.error("Couldn't close log at " + wap.p, ioe);
1375        thrown.add(ioe);
1376        return null;
1377      }
1378      if (LOG.isDebugEnabled()) {
1379        LOG.debug("Closed wap " + wap.p + " (wrote " + wap.editsWritten
1380            + " edits, skipped " + wap.editsSkipped + " edits in "
1381            + (wap.nanosSpent / 1000 / 1000) + "ms");
1382      }
1383      if (wap.editsWritten == 0) {
1384        // just remove the empty recovered.edits file
1385        if (fs.exists(wap.p) && !fs.delete(wap.p, false)) {
1386          LOG.warn("Failed deleting empty " + wap.p);
1387          throw new IOException("Failed deleting empty  " + wap.p);
1388        }
1389        return null;
1390      }
1391
1392      Path dst = getCompletedRecoveredEditsFilePath(wap.p,
1393          regionMaximumEditLogSeqNum.get(encodedRegionName));
1394      try {
1395        if (!dst.equals(wap.p) && fs.exists(dst)) {
1396          deleteOneWithFewerEntries(wap, dst);
1397        }
1398        // Skip the unit tests which create a splitter that reads and
1399        // writes the data without touching disk.
1400        // TestHLogSplit#testThreading is an example.
1401        if (fs.exists(wap.p)) {
1402          if (!fs.rename(wap.p, dst)) {
1403            throw new IOException("Failed renaming " + wap.p + " to " + dst);
1404          }
1405          LOG.info("Rename " + wap.p + " to " + dst);
1406        }
1407      } catch (IOException ioe) {
1408        LOG.error("Couldn't rename " + wap.p + " to " + dst, ioe);
1409        thrown.add(ioe);
1410        return null;
1411      }
1412      return dst;
1413    }
1414
1415    private List<IOException> closeLogWriters(List<IOException> thrown) throws IOException {
1416      if (writersClosed) {
1417        return thrown;
1418      }
1419      if (thrown == null) {
1420        thrown = Lists.newArrayList();
1421      }
1422      try {
1423        for (WriterThread t : writerThreads) {
1424          while (t.isAlive()) {
1425            t.shouldStop = true;
1426            t.interrupt();
1427            try {
1428              t.join(10);
1429            } catch (InterruptedException e) {
1430              IOException iie = new InterruptedIOException();
1431              iie.initCause(e);
1432              throw iie;
1433            }
1434          }
1435        }
1436      } finally {
1437        WriterAndPath wap = null;
1438        for (SinkWriter tmpWAP : writers.values()) {
1439          try {
1440            wap = (WriterAndPath) tmpWAP;
1441            wap.w.close();
1442          } catch (IOException ioe) {
1443            LOG.error("Couldn't close log at " + wap.p, ioe);
1444            thrown.add(ioe);
1445            continue;
1446          }
1447          LOG.info(
1448              "Closed log " + wap.p + " (wrote " + wap.editsWritten + " edits in " + (wap.nanosSpent
1449                  / 1000 / 1000) + "ms)");
1450        }
1451        writersClosed = true;
1452      }
1453
1454      return thrown;
1455    }
1456
1457    /**
1458     * Get a writer and path for a log starting at the given entry. This function is threadsafe so
1459     * long as multiple threads are always acting on different regions.
1460     * @return null if this region shouldn't output any logs
1461     */
1462    WriterAndPath getWriterAndPath(Entry entry, boolean reusable) throws IOException {
1463      byte region[] = entry.getKey().getEncodedRegionName();
1464      String regionName = Bytes.toString(region);
1465      WriterAndPath ret = (WriterAndPath) writers.get(regionName);
1466      if (ret != null) {
1467        return ret;
1468      }
1469      // If we already decided that this region doesn't get any output
1470      // we don't need to check again.
1471      if (blacklistedRegions.contains(region)) {
1472        return null;
1473      }
1474      ret = createWAP(region, entry, rootDir);
1475      if (ret == null) {
1476        blacklistedRegions.add(region);
1477        return null;
1478      }
1479      if(reusable) {
1480        writers.put(regionName, ret);
1481      }
1482      return ret;
1483    }
1484
1485    /**
1486     * @return a path with a write for that path. caller should close.
1487     */
1488    WriterAndPath createWAP(byte[] region, Entry entry, Path rootdir) throws IOException {
1489      Path regionedits = getRegionSplitEditsPath(fs, entry, rootdir, fileBeingSplit.getPath().getName());
1490      if (regionedits == null) {
1491        return null;
1492      }
1493      if (fs.exists(regionedits)) {
1494        LOG.warn("Found old edits file. It could be the "
1495            + "result of a previous failed split attempt. Deleting " + regionedits + ", length="
1496            + fs.getFileStatus(regionedits).getLen());
1497        if (!fs.delete(regionedits, false)) {
1498          LOG.warn("Failed delete of old {}", regionedits);
1499        }
1500      }
1501      Writer w = createWriter(regionedits);
1502      LOG.debug("Creating writer path={}", regionedits);
1503      return new WriterAndPath(regionedits, w, entry.getKey().getSequenceId());
1504    }
1505
1506    void filterCellByStore(Entry logEntry) {
1507      Map<byte[], Long> maxSeqIdInStores =
1508          regionMaxSeqIdInStores.get(Bytes.toString(logEntry.getKey().getEncodedRegionName()));
1509      if (MapUtils.isEmpty(maxSeqIdInStores)) {
1510        return;
1511      }
1512      // Create the array list for the cells that aren't filtered.
1513      // We make the assumption that most cells will be kept.
1514      ArrayList<Cell> keptCells = new ArrayList<>(logEntry.getEdit().getCells().size());
1515      for (Cell cell : logEntry.getEdit().getCells()) {
1516        if (CellUtil.matchingFamily(cell, WALEdit.METAFAMILY)) {
1517          keptCells.add(cell);
1518        } else {
1519          byte[] family = CellUtil.cloneFamily(cell);
1520          Long maxSeqId = maxSeqIdInStores.get(family);
1521          // Do not skip cell even if maxSeqId is null. Maybe we are in a rolling upgrade,
1522          // or the master was crashed before and we can not get the information.
1523          if (maxSeqId == null || maxSeqId.longValue() < logEntry.getKey().getSequenceId()) {
1524            keptCells.add(cell);
1525          }
1526        }
1527      }
1528
1529      // Anything in the keptCells array list is still live.
1530      // So rather than removing the cells from the array list
1531      // which would be an O(n^2) operation, we just replace the list
1532      logEntry.getEdit().setCells(keptCells);
1533    }
1534
1535    @Override
1536    public void append(RegionEntryBuffer buffer) throws IOException {
1537      appendBuffer(buffer, true);
1538    }
1539
1540    WriterAndPath appendBuffer(RegionEntryBuffer buffer, boolean reusable) throws IOException{
1541      List<Entry> entries = buffer.entryBuffer;
1542      if (entries.isEmpty()) {
1543        LOG.warn("got an empty buffer, skipping");
1544        return null;
1545      }
1546
1547      WriterAndPath wap = null;
1548
1549      long startTime = System.nanoTime();
1550      try {
1551        int editsCount = 0;
1552
1553        for (Entry logEntry : entries) {
1554          if (wap == null) {
1555            wap = getWriterAndPath(logEntry, reusable);
1556            if (wap == null) {
1557              if (LOG.isTraceEnabled()) {
1558                // This log spews the full edit. Can be massive in the log. Enable only debugging
1559                // WAL lost edit issues.
1560                LOG.trace("getWriterAndPath decided we don't need to write edits for {}", logEntry);
1561              }
1562              return null;
1563            }
1564          }
1565          filterCellByStore(logEntry);
1566          if (!logEntry.getEdit().isEmpty()) {
1567            wap.w.append(logEntry);
1568            this.updateRegionMaximumEditLogSeqNum(logEntry);
1569            editsCount++;
1570          } else {
1571            wap.incrementSkippedEdits(1);
1572          }
1573        }
1574        // Pass along summary statistics
1575        wap.incrementEdits(editsCount);
1576        wap.incrementNanoTime(System.nanoTime() - startTime);
1577      } catch (IOException e) {
1578          e = e instanceof RemoteException ?
1579                  ((RemoteException)e).unwrapRemoteException() : e;
1580        LOG.error(HBaseMarkers.FATAL, "Got while writing log entry to log", e);
1581        throw e;
1582      }
1583      return wap;
1584    }
1585
1586    @Override
1587    public boolean keepRegionEvent(Entry entry) {
1588      ArrayList<Cell> cells = entry.getEdit().getCells();
1589      for (Cell cell : cells) {
1590        if (WALEdit.isCompactionMarker(cell)) {
1591          return true;
1592        }
1593      }
1594      return false;
1595    }
1596
1597    /**
1598     * @return a map from encoded region ID to the number of edits written out for that region.
1599     */
1600    @Override
1601    public Map<byte[], Long> getOutputCounts() {
1602      TreeMap<byte[], Long> ret = new TreeMap<>(Bytes.BYTES_COMPARATOR);
1603      for (Map.Entry<String, SinkWriter> entry : writers.entrySet()) {
1604        ret.put(Bytes.toBytes(entry.getKey()), entry.getValue().editsWritten);
1605      }
1606      return ret;
1607    }
1608
1609    @Override
1610    public int getNumberOfRecoveredRegions() {
1611      return writers.size();
1612    }
1613  }
1614
1615  /**
1616   *
1617   */
1618  class BoundedLogWriterCreationOutputSink extends LogRecoveredEditsOutputSink {
1619
1620    private ConcurrentHashMap<String, Long> regionRecoverStatMap = new ConcurrentHashMap<>();
1621
1622    public BoundedLogWriterCreationOutputSink(PipelineController controller,
1623        EntryBuffers entryBuffers, int numWriters) {
1624      super(controller, entryBuffers, numWriters);
1625    }
1626
1627    @Override
1628    public List<Path> finishWritingAndClose() throws IOException {
1629      boolean isSuccessful;
1630      List<Path> result;
1631      try {
1632        isSuccessful = finishWriting(false);
1633      } finally {
1634        result = close();
1635      }
1636      if (isSuccessful) {
1637        splits = result;
1638      }
1639      return splits;
1640    }
1641
1642    @Override
1643    boolean executeCloseTask(CompletionService<Void> completionService,
1644        List<IOException> thrown, List<Path> paths)
1645        throws InterruptedException, ExecutionException {
1646      for (final Map.Entry<byte[], RegionEntryBuffer> buffer : entryBuffers.buffers.entrySet()) {
1647        LOG.info("Submitting writeThenClose of {}",
1648            Arrays.toString(buffer.getValue().encodedRegionName));
1649        completionService.submit(new Callable<Void>() {
1650          @Override
1651          public Void call() throws Exception {
1652            Path dst = writeThenClose(buffer.getValue());
1653            paths.add(dst);
1654            return null;
1655          }
1656        });
1657      }
1658      boolean progress_failed = false;
1659      for (int i = 0, n = entryBuffers.buffers.size(); i < n; i++) {
1660        Future<Void> future = completionService.take();
1661        future.get();
1662        if (!progress_failed && reporter != null && !reporter.progress()) {
1663          progress_failed = true;
1664        }
1665      }
1666
1667      return progress_failed;
1668    }
1669
1670    /**
1671     * since the splitting process may create multiple output files, we need a map
1672     * regionRecoverStatMap to track the output count of each region.
1673     * @return a map from encoded region ID to the number of edits written out for that region.
1674     */
1675    @Override
1676    public Map<byte[], Long> getOutputCounts() {
1677      Map<byte[], Long> regionRecoverStatMapResult = new HashMap<>();
1678      for(Map.Entry<String, Long> entry: regionRecoverStatMap.entrySet()){
1679        regionRecoverStatMapResult.put(Bytes.toBytes(entry.getKey()), entry.getValue());
1680      }
1681      return regionRecoverStatMapResult;
1682    }
1683
1684    /**
1685     * @return the number of recovered regions
1686     */
1687    @Override
1688    public int getNumberOfRecoveredRegions() {
1689      return regionRecoverStatMap.size();
1690    }
1691
1692    /**
1693     * Append the buffer to a new recovered edits file, then close it after all done
1694     * @param buffer contain all entries of a certain region
1695     * @throws IOException when closeWriter failed
1696     */
1697    @Override
1698    public void append(RegionEntryBuffer buffer) throws IOException {
1699      writeThenClose(buffer);
1700    }
1701
1702    private Path writeThenClose(RegionEntryBuffer buffer) throws IOException {
1703      WriterAndPath wap = appendBuffer(buffer, false);
1704      if(wap != null) {
1705        String encodedRegionName = Bytes.toString(buffer.encodedRegionName);
1706        Long value = regionRecoverStatMap.putIfAbsent(encodedRegionName, wap.editsWritten);
1707        if (value != null) {
1708          Long newValue = regionRecoverStatMap.get(encodedRegionName) + wap.editsWritten;
1709          regionRecoverStatMap.put(encodedRegionName, newValue);
1710        }
1711      }
1712
1713      Path dst = null;
1714      List<IOException> thrown = new ArrayList<>();
1715      if(wap != null){
1716        dst = closeWriter(Bytes.toString(buffer.encodedRegionName), wap, thrown);
1717      }
1718      if (!thrown.isEmpty()) {
1719        throw MultipleIOException.createIOException(thrown);
1720      }
1721      return dst;
1722    }
1723  }
1724
1725  /**
1726   * Class wraps the actual writer which writes data out and related statistics
1727   */
1728  public abstract static class SinkWriter {
1729    /* Count of edits written to this path */
1730    long editsWritten = 0;
1731    /* Count of edits skipped to this path */
1732    long editsSkipped = 0;
1733    /* Number of nanos spent writing to this log */
1734    long nanosSpent = 0;
1735
1736    void incrementEdits(int edits) {
1737      editsWritten += edits;
1738    }
1739
1740    void incrementSkippedEdits(int skipped) {
1741      editsSkipped += skipped;
1742    }
1743
1744    void incrementNanoTime(long nanos) {
1745      nanosSpent += nanos;
1746    }
1747  }
1748
1749  /**
1750   * Private data structure that wraps a Writer and its Path, also collecting statistics about the
1751   * data written to this output.
1752   */
1753  private final static class WriterAndPath extends SinkWriter {
1754    final Path p;
1755    final Writer w;
1756    final long minLogSeqNum;
1757
1758    WriterAndPath(final Path p, final Writer w, final long minLogSeqNum) {
1759      this.p = p;
1760      this.w = w;
1761      this.minLogSeqNum = minLogSeqNum;
1762    }
1763  }
1764
1765  static class CorruptedLogFileException extends Exception {
1766    private static final long serialVersionUID = 1L;
1767
1768    CorruptedLogFileException(String s) {
1769      super(s);
1770    }
1771  }
1772
1773  /** A struct used by getMutationsFromWALEntry */
1774  public static class MutationReplay implements Comparable<MutationReplay> {
1775    public MutationReplay(MutationType type, Mutation mutation, long nonceGroup, long nonce) {
1776      this.type = type;
1777      this.mutation = mutation;
1778      if(this.mutation.getDurability() != Durability.SKIP_WAL) {
1779        // using ASYNC_WAL for relay
1780        this.mutation.setDurability(Durability.ASYNC_WAL);
1781      }
1782      this.nonceGroup = nonceGroup;
1783      this.nonce = nonce;
1784    }
1785
1786    public final MutationType type;
1787    public final Mutation mutation;
1788    public final long nonceGroup;
1789    public final long nonce;
1790
1791    @Override
1792    public int compareTo(final MutationReplay d) {
1793      return this.mutation.compareTo(d.mutation);
1794    }
1795
1796    @Override
1797    public boolean equals(Object obj) {
1798      if(!(obj instanceof MutationReplay)) {
1799        return false;
1800      } else {
1801        return this.compareTo((MutationReplay)obj) == 0;
1802      }
1803    }
1804
1805    @Override
1806    public int hashCode() {
1807      return this.mutation.hashCode();
1808    }
1809  }
1810
1811  /**
1812   * This function is used to construct mutations from a WALEntry. It also
1813   * reconstructs WALKey &amp; WALEdit from the passed in WALEntry
1814   * @param entry
1815   * @param cells
1816   * @param logEntry pair of WALKey and WALEdit instance stores WALKey and WALEdit instances
1817   *          extracted from the passed in WALEntry.
1818   * @return list of Pair&lt;MutationType, Mutation&gt; to be replayed
1819   * @throws IOException
1820   */
1821  public static List<MutationReplay> getMutationsFromWALEntry(WALEntry entry, CellScanner cells,
1822      Pair<WALKey, WALEdit> logEntry, Durability durability) throws IOException {
1823    if (entry == null) {
1824      // return an empty array
1825      return Collections.emptyList();
1826    }
1827
1828    long replaySeqId = (entry.getKey().hasOrigSequenceNumber()) ?
1829      entry.getKey().getOrigSequenceNumber() : entry.getKey().getLogSequenceNumber();
1830    int count = entry.getAssociatedCellCount();
1831    List<MutationReplay> mutations = new ArrayList<>();
1832    Cell previousCell = null;
1833    Mutation m = null;
1834    WALKeyImpl key = null;
1835    WALEdit val = null;
1836    if (logEntry != null) {
1837      val = new WALEdit();
1838    }
1839
1840    for (int i = 0; i < count; i++) {
1841      // Throw index out of bounds if our cell count is off
1842      if (!cells.advance()) {
1843        throw new ArrayIndexOutOfBoundsException("Expected=" + count + ", index=" + i);
1844      }
1845      Cell cell = cells.current();
1846      if (val != null) val.add(cell);
1847
1848      boolean isNewRowOrType =
1849          previousCell == null || previousCell.getTypeByte() != cell.getTypeByte()
1850              || !CellUtil.matchingRows(previousCell, cell);
1851      if (isNewRowOrType) {
1852        // Create new mutation
1853        if (CellUtil.isDelete(cell)) {
1854          m = new Delete(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
1855          // Deletes don't have nonces.
1856          mutations.add(new MutationReplay(
1857              MutationType.DELETE, m, HConstants.NO_NONCE, HConstants.NO_NONCE));
1858        } else {
1859          m = new Put(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
1860          // Puts might come from increment or append, thus we need nonces.
1861          long nonceGroup = entry.getKey().hasNonceGroup()
1862              ? entry.getKey().getNonceGroup() : HConstants.NO_NONCE;
1863          long nonce = entry.getKey().hasNonce() ? entry.getKey().getNonce() : HConstants.NO_NONCE;
1864          mutations.add(new MutationReplay(MutationType.PUT, m, nonceGroup, nonce));
1865        }
1866      }
1867      if (CellUtil.isDelete(cell)) {
1868        ((Delete) m).add(cell);
1869      } else {
1870        ((Put) m).add(cell);
1871      }
1872      m.setDurability(durability);
1873      previousCell = cell;
1874    }
1875
1876    // reconstruct WALKey
1877    if (logEntry != null) {
1878      org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.WALKey walKeyProto =
1879          entry.getKey();
1880      List<UUID> clusterIds = new ArrayList<>(walKeyProto.getClusterIdsCount());
1881      for (HBaseProtos.UUID uuid : entry.getKey().getClusterIdsList()) {
1882        clusterIds.add(new UUID(uuid.getMostSigBits(), uuid.getLeastSigBits()));
1883      }
1884      key = new WALKeyImpl(walKeyProto.getEncodedRegionName().toByteArray(), TableName.valueOf(
1885              walKeyProto.getTableName().toByteArray()), replaySeqId, walKeyProto.getWriteTime(),
1886              clusterIds, walKeyProto.getNonceGroup(), walKeyProto.getNonce(), null);
1887      logEntry.setFirst(key);
1888      logEntry.setSecond(val);
1889    }
1890
1891    return mutations;
1892  }
1893}