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.Collections;
027import java.util.List;
028import java.util.Map;
029import java.util.TreeMap;
030import java.util.concurrent.ConcurrentHashMap;
031import java.util.concurrent.atomic.AtomicReference;
032import org.apache.hadoop.conf.Configuration;
033import org.apache.hadoop.fs.FileStatus;
034import org.apache.hadoop.fs.FileSystem;
035import org.apache.hadoop.fs.Path;
036import org.apache.hadoop.hbase.HBaseConfiguration;
037import org.apache.hadoop.hbase.HConstants;
038import org.apache.hadoop.hbase.TableName;
039import org.apache.hadoop.hbase.coordination.SplitLogWorkerCoordination;
040import org.apache.hadoop.hbase.master.SplitLogManager;
041import org.apache.hadoop.hbase.monitoring.MonitoredTask;
042import org.apache.hadoop.hbase.monitoring.TaskMonitor;
043import org.apache.hadoop.hbase.procedure2.util.StringUtils;
044import org.apache.hadoop.hbase.regionserver.LastSequenceId;
045import org.apache.hadoop.hbase.regionserver.RegionServerServices;
046import org.apache.hadoop.hbase.regionserver.wal.WALCellCodec;
047import org.apache.hadoop.hbase.util.Bytes;
048import org.apache.hadoop.hbase.util.CancelableProgressable;
049import org.apache.hadoop.hbase.util.CommonFSUtils;
050import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
051import org.apache.hadoop.hbase.util.RecoverLeaseFSUtils;
052import org.apache.hadoop.hbase.wal.WAL.Entry;
053import org.apache.hadoop.hbase.wal.WAL.Reader;
054import org.apache.hadoop.ipc.RemoteException;
055import org.apache.yetus.audience.InterfaceAudience;
056import org.slf4j.Logger;
057import org.slf4j.LoggerFactory;
058
059import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
060import org.apache.hbase.thirdparty.com.google.protobuf.TextFormat;
061
062import org.apache.hadoop.hbase.shaded.protobuf.generated.ClusterStatusProtos.RegionStoreSequenceIds;
063import org.apache.hadoop.hbase.shaded.protobuf.generated.ClusterStatusProtos.StoreSequenceId;
064
065/**
066 * Split RegionServer WAL files. Splits the WAL into new files, one per region, to be picked up on
067 * Region reopen. Deletes the split WAL when finished. Create an instance and call
068 * {@link #splitWAL(FileStatus, CancelableProgressable)} per file or use static helper methods.
069 */
070@InterfaceAudience.Private
071public class WALSplitter {
072  private static final Logger LOG = LoggerFactory.getLogger(WALSplitter.class);
073  public static final String SPLIT_SKIP_ERRORS_KEY = "hbase.hlog.split.skip.errors";
074
075  /**
076   * By default we retry errors in splitting, rather than skipping.
077   */
078  public static final boolean SPLIT_SKIP_ERRORS_DEFAULT = false;
079
080  // Parameters for split process
081  protected final Path walRootDir;
082  protected final FileSystem walFS;
083  protected final Configuration conf;
084  final Path rootDir;
085  final FileSystem rootFS;
086  final RegionServerServices rsServices;
087
088  // Major subcomponents of the split process.
089  // These are separated into inner classes to make testing easier.
090  OutputSink outputSink;
091  private EntryBuffers entryBuffers;
092
093  /**
094   * Coordinator for split log. Used by the zk-based log splitter. Not used by the procedure
095   * v2-based log splitter.
096   */
097  private SplitLogWorkerCoordination splitLogWorkerCoordination;
098
099  private final WALFactory walFactory;
100
101  // For checking the latest flushed sequence id
102  protected final LastSequenceId sequenceIdChecker;
103
104  // Map encodedRegionName -> lastFlushedSequenceId
105  protected Map<String, Long> lastFlushedSequenceIds = new ConcurrentHashMap<>();
106
107  // Map encodedRegionName -> maxSeqIdInStores
108  protected Map<String, Map<byte[], Long>> regionMaxSeqIdInStores = new ConcurrentHashMap<>();
109
110  // the file being split currently
111  private FileStatus fileBeingSplit;
112
113  private final String tmpDirName;
114
115  /**
116   * Split WAL directly to hfiles instead of into intermediary 'recovered.edits' files.
117   */
118  public static final String WAL_SPLIT_TO_HFILE = "hbase.wal.split.to.hfile";
119  public static final boolean DEFAULT_WAL_SPLIT_TO_HFILE = false;
120
121  /**
122   * True if we are to run with bounded amount of writers rather than let the count blossom. Default
123   * is 'false'. Does not apply if you have set 'hbase.wal.split.to.hfile' as that is always
124   * bounded. Only applies when you are doing recovery to 'recovered.edits' files (the old default).
125   * Bounded writing tends to have higher throughput.
126   */
127  public final static String SPLIT_WRITER_CREATION_BOUNDED = "hbase.split.writer.creation.bounded";
128
129  public final static String SPLIT_WAL_BUFFER_SIZE = "hbase.regionserver.hlog.splitlog.buffersize";
130  public final static String SPLIT_WAL_WRITER_THREADS =
131    "hbase.regionserver.hlog.splitlog.writer.threads";
132
133  private final int numWriterThreads;
134  private final long bufferSize;
135  private final boolean splitWriterCreationBounded;
136  private final boolean hfile;
137  private final boolean skipErrors;
138
139  WALSplitter(final WALFactory factory, Configuration conf, Path walRootDir, FileSystem walFS,
140    Path rootDir, FileSystem rootFS) {
141    this(factory, conf, walRootDir, walFS, rootDir, rootFS, null, null, null);
142  }
143
144  WALSplitter(final WALFactory factory, Configuration conf, Path walRootDir, FileSystem walFS,
145    Path rootDir, FileSystem rootFS, LastSequenceId idChecker,
146    SplitLogWorkerCoordination splitLogWorkerCoordination, RegionServerServices rsServices) {
147    this.conf = HBaseConfiguration.create(conf);
148    String codecClassName =
149      conf.get(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, WALCellCodec.class.getName());
150    this.conf.set(HConstants.RPC_CODEC_CONF_KEY, codecClassName);
151    this.walRootDir = walRootDir;
152    this.walFS = walFS;
153    this.rootDir = rootDir;
154    this.rootFS = rootFS;
155    this.sequenceIdChecker = idChecker;
156    this.splitLogWorkerCoordination = splitLogWorkerCoordination;
157    this.rsServices = rsServices;
158    this.walFactory = factory;
159    this.tmpDirName =
160      conf.get(HConstants.TEMPORARY_FS_DIRECTORY_KEY, HConstants.DEFAULT_TEMPORARY_HDFS_DIRECTORY);
161    // if we limit the number of writers opened for sinking recovered edits
162    this.splitWriterCreationBounded = conf.getBoolean(SPLIT_WRITER_CREATION_BOUNDED, false);
163    this.bufferSize = this.conf.getLong(SPLIT_WAL_BUFFER_SIZE, 128 * 1024 * 1024);
164    this.numWriterThreads = this.conf.getInt(SPLIT_WAL_WRITER_THREADS, 3);
165    this.hfile = conf.getBoolean(WAL_SPLIT_TO_HFILE, DEFAULT_WAL_SPLIT_TO_HFILE);
166    this.skipErrors = conf.getBoolean(SPLIT_SKIP_ERRORS_KEY, SPLIT_SKIP_ERRORS_DEFAULT);
167  }
168
169  WALFactory getWalFactory() {
170    return this.walFactory;
171  }
172
173  FileStatus getFileBeingSplit() {
174    return fileBeingSplit;
175  }
176
177  String getTmpDirName() {
178    return this.tmpDirName;
179  }
180
181  Map<String, Map<byte[], Long>> getRegionMaxSeqIdInStores() {
182    return regionMaxSeqIdInStores;
183  }
184
185  /**
186   * Splits a WAL file. Used by old {@link org.apache.hadoop.hbase.regionserver.SplitLogWorker} and
187   * tests. Not used by new procedure-based WAL splitter.
188   * @return false if it is interrupted by the progress-able.
189   */
190  public static boolean splitLogFile(Path walDir, FileStatus logfile, FileSystem walFS,
191    Configuration conf, CancelableProgressable reporter, LastSequenceId idChecker,
192    SplitLogWorkerCoordination splitLogWorkerCoordination, WALFactory factory,
193    RegionServerServices rsServices) throws IOException {
194    Path rootDir = CommonFSUtils.getRootDir(conf);
195    FileSystem rootFS = rootDir.getFileSystem(conf);
196    WALSplitter splitter = new WALSplitter(factory, conf, walDir, walFS, rootDir, rootFS, idChecker,
197      splitLogWorkerCoordination, rsServices);
198    // splitWAL returns a data structure with whether split is finished and if the file is corrupt.
199    // We don't need to propagate corruption flag here because it is propagated by the
200    // SplitLogWorkerCoordination.
201    return splitter.splitWAL(logfile, reporter).isFinished();
202  }
203
204  /**
205   * Split a folder of WAL files. Delete the directory when done. Used by tools and unit tests. It
206   * should be package private. It is public only because TestWALObserver is in a different package,
207   * which uses this method to do log splitting.
208   * @return List of output files created by the split.
209   */
210  public static List<Path> split(Path walRootDir, Path walsDir, Path archiveDir, FileSystem walFS,
211    Configuration conf, final WALFactory factory) throws IOException {
212    Path rootDir = CommonFSUtils.getRootDir(conf);
213    FileSystem rootFS = rootDir.getFileSystem(conf);
214    WALSplitter splitter = new WALSplitter(factory, conf, walRootDir, walFS, rootDir, rootFS);
215    final List<FileStatus> wals =
216      SplitLogManager.getFileList(conf, Collections.singletonList(walsDir), null);
217    List<Path> splits = new ArrayList<>();
218    if (!wals.isEmpty()) {
219      for (FileStatus wal : wals) {
220        SplitWALResult splitWALResult = splitter.splitWAL(wal, null);
221        if (splitWALResult.isFinished()) {
222          WALSplitUtil.archive(wal.getPath(), splitWALResult.isCorrupt(), archiveDir, walFS, conf);
223          // splitter.outputSink.splits is mark as final, do not need null check
224          splits.addAll(splitter.outputSink.splits);
225        }
226      }
227    }
228    if (!walFS.delete(walsDir, true)) {
229      throw new IOException("Unable to delete src dir " + walsDir);
230    }
231    return splits;
232  }
233
234  /**
235   * Data structure returned as result by #splitWAL(FileStatus, CancelableProgressable). Test
236   * {@link #isFinished()} to see if we are done with the WAL and {@link #isCorrupt()} for if the
237   * WAL is corrupt.
238   */
239  static final class SplitWALResult {
240    private final boolean finished;
241    private final boolean corrupt;
242
243    private SplitWALResult(boolean finished, boolean corrupt) {
244      this.finished = finished;
245      this.corrupt = corrupt;
246    }
247
248    public boolean isFinished() {
249      return finished;
250    }
251
252    public boolean isCorrupt() {
253      return corrupt;
254    }
255  }
256
257  /**
258   * Setup the output sinks and entry buffers ahead of splitting WAL.
259   */
260  private void createOutputSinkAndEntryBuffers() {
261    PipelineController controller = new PipelineController();
262    if (this.hfile) {
263      this.entryBuffers = new BoundedEntryBuffers(controller, this.bufferSize);
264      this.outputSink = new BoundedRecoveredHFilesOutputSink(this, controller, this.entryBuffers,
265        this.numWriterThreads);
266    } else if (this.splitWriterCreationBounded) {
267      this.entryBuffers = new BoundedEntryBuffers(controller, this.bufferSize);
268      this.outputSink = new BoundedRecoveredEditsOutputSink(this, controller, this.entryBuffers,
269        this.numWriterThreads);
270    } else {
271      this.entryBuffers = new EntryBuffers(controller, this.bufferSize);
272      this.outputSink =
273        new RecoveredEditsOutputSink(this, controller, this.entryBuffers, this.numWriterThreads);
274    }
275  }
276
277  /**
278   * WAL splitting implementation, splits one WAL file.
279   * @param walStatus should be for an actual WAL file.
280   */
281  SplitWALResult splitWAL(FileStatus walStatus, CancelableProgressable cancel) throws IOException {
282    Path wal = walStatus.getPath();
283    Preconditions.checkArgument(walStatus.isFile(), "Not a regular file " + wal.toString());
284    boolean corrupt = false;
285    int interval = conf.getInt("hbase.splitlog.report.interval.loglines", 1024);
286    boolean outputSinkStarted = false;
287    boolean cancelled = false;
288    int editsCount = 0;
289    int editsSkipped = 0;
290    MonitoredTask status = TaskMonitor.get()
291      .createStatus("Splitting " + wal + " to temporary staging area.", false, true);
292    Reader walReader = null;
293    this.fileBeingSplit = walStatus;
294    long startTS = EnvironmentEdgeManager.currentTime();
295    long length = walStatus.getLen();
296    String lengthStr = StringUtils.humanSize(length);
297    createOutputSinkAndEntryBuffers();
298    try {
299      String logStr = "Splitting " + wal + ", size=" + lengthStr + " (" + length + "bytes)";
300      LOG.info(logStr);
301      status.setStatus(logStr);
302      if (cancel != null && !cancel.progress()) {
303        cancelled = true;
304        return new SplitWALResult(false, corrupt);
305      }
306      walReader = getReader(walStatus, this.skipErrors, cancel);
307      if (walReader == null) {
308        LOG.warn("Nothing in {}; empty?", wal);
309        return new SplitWALResult(true, corrupt);
310      }
311      LOG.info("Open {} took {}ms", wal, EnvironmentEdgeManager.currentTime() - startTS);
312      int numOpenedFilesBeforeReporting = conf.getInt("hbase.splitlog.report.openedfiles", 3);
313      int numOpenedFilesLastCheck = 0;
314      outputSink.setReporter(cancel);
315      outputSink.setStatus(status);
316      outputSink.startWriterThreads();
317      outputSinkStarted = true;
318      Entry entry;
319      startTS = EnvironmentEdgeManager.currentTime();
320      while ((entry = getNextLogLine(walReader, wal, this.skipErrors)) != null) {
321        if (WALEdit.isReplicationMarkerEdit(entry.getEdit())) {
322          // Skip processing the replication marker edits.
323          if (LOG.isDebugEnabled()) {
324            LOG.debug("Ignoring Replication marker edits.");
325          }
326          continue;
327        }
328        byte[] region = entry.getKey().getEncodedRegionName();
329        String encodedRegionNameAsStr = Bytes.toString(region);
330        Long lastFlushedSequenceId = lastFlushedSequenceIds.get(encodedRegionNameAsStr);
331        if (lastFlushedSequenceId == null) {
332          if (
333            !(isRegionDirPresentUnderRoot(entry.getKey().getTableName(), encodedRegionNameAsStr))
334          ) {
335            // The region directory itself is not present in the FS. This indicates that
336            // the region/table is already removed. We can just skip all the edits for this
337            // region. Setting lastFlushedSequenceId as Long.MAX_VALUE so that all edits
338            // will get skipped by the seqId check below.
339            // See more details at https://issues.apache.org/jira/browse/HBASE-24189
340            LOG.info("{} no longer in filesystem; skipping all edits.", encodedRegionNameAsStr);
341            lastFlushedSequenceId = Long.MAX_VALUE;
342          } else {
343            if (sequenceIdChecker != null) {
344              RegionStoreSequenceIds ids = sequenceIdChecker.getLastSequenceId(region);
345              Map<byte[], Long> maxSeqIdInStores = new TreeMap<>(Bytes.BYTES_COMPARATOR);
346              for (StoreSequenceId storeSeqId : ids.getStoreSequenceIdList()) {
347                maxSeqIdInStores.put(storeSeqId.getFamilyName().toByteArray(),
348                  storeSeqId.getSequenceId());
349              }
350              regionMaxSeqIdInStores.put(encodedRegionNameAsStr, maxSeqIdInStores);
351              lastFlushedSequenceId = ids.getLastFlushedSequenceId();
352              if (LOG.isDebugEnabled()) {
353                LOG.debug("Last flushed sequenceid for " + encodedRegionNameAsStr + ": "
354                  + TextFormat.shortDebugString(ids));
355              }
356            }
357            if (lastFlushedSequenceId == null) {
358              lastFlushedSequenceId = -1L;
359            }
360          }
361          lastFlushedSequenceIds.put(encodedRegionNameAsStr, lastFlushedSequenceId);
362        }
363        editsCount++;
364        if (lastFlushedSequenceId >= entry.getKey().getSequenceId()) {
365          editsSkipped++;
366          continue;
367        }
368        // Don't send Compaction/Close/Open region events to recovered edit type sinks.
369        if (entry.getEdit().isMetaEdit() && !outputSink.keepRegionEvent(entry)) {
370          editsSkipped++;
371          continue;
372        }
373        entryBuffers.appendEntry(entry);
374        int moreWritersFromLastCheck = this.getNumOpenWriters() - numOpenedFilesLastCheck;
375        // If sufficient edits have passed, check if we should report progress.
376        if (
377          editsCount % interval == 0 || moreWritersFromLastCheck > numOpenedFilesBeforeReporting
378        ) {
379          numOpenedFilesLastCheck = this.getNumOpenWriters();
380          String countsStr = (editsCount - (editsSkipped + outputSink.getTotalSkippedEdits()))
381            + " edits, skipped " + editsSkipped + " edits.";
382          status.setStatus("Split " + countsStr);
383          if (cancel != null && !cancel.progress()) {
384            cancelled = true;
385            return new SplitWALResult(false, corrupt);
386          }
387        }
388      }
389    } catch (InterruptedException ie) {
390      IOException iie = new InterruptedIOException();
391      iie.initCause(ie);
392      throw iie;
393    } catch (CorruptedLogFileException e) {
394      LOG.warn("Could not parse, corrupt WAL={}", wal, e);
395      // If splitLogWorkerCoordination, then its old-school zk-coordinated splitting so update
396      // zk. Otherwise, it is the newer procedure-based WAL split which has no zk component.
397      if (this.splitLogWorkerCoordination != null) {
398        // Some tests pass in a csm of null.
399        splitLogWorkerCoordination.markCorrupted(walRootDir, wal.getName(), walFS);
400      }
401      corrupt = true;
402    } catch (IOException e) {
403      e = e instanceof RemoteException ? ((RemoteException) e).unwrapRemoteException() : e;
404      throw e;
405    } finally {
406      final String log = "Finishing writing output for " + wal + " so closing down";
407      LOG.debug(log);
408      status.setStatus(log);
409      try {
410        if (null != walReader) {
411          walReader.close();
412        }
413      } catch (IOException exception) {
414        LOG.warn("Could not close {} reader", wal, exception);
415      }
416      try {
417        if (outputSinkStarted) {
418          // Set cancelled to true as the immediate following statement will reset its value.
419          // If close() throws an exception, cancelled will have the right value
420          cancelled = true;
421          cancelled = outputSink.close() == null;
422        }
423      } finally {
424        long processCost = EnvironmentEdgeManager.currentTime() - startTS;
425        // See if length got updated post lease recovery
426        String msg = "Processed " + editsCount + " edits across "
427          + outputSink.getNumberOfRecoveredRegions() + " Regions in " + processCost
428          + " ms; skipped=" + editsSkipped + "; WAL=" + wal + ", size=" + lengthStr + ", length="
429          + length + ", corrupted=" + corrupt + ", cancelled=" + cancelled;
430        LOG.info(msg);
431        status.markComplete(msg);
432        if (LOG.isDebugEnabled()) {
433          LOG.debug("Completed split of {}, journal: {}", wal, status.prettyPrintJournal());
434        }
435      }
436    }
437    return new SplitWALResult(!cancelled, corrupt);
438  }
439
440  private boolean isRegionDirPresentUnderRoot(TableName tn, String region) throws IOException {
441    return this.rootFS.exists(CommonFSUtils.getRegionDir(this.rootDir, tn, region));
442  }
443
444  /**
445   * Create a new {@link Reader} for reading logs to split.
446   * @return Returns null if file has length zero or file can't be found.
447   */
448  protected Reader getReader(FileStatus walStatus, boolean skipErrors,
449    CancelableProgressable cancel) throws IOException, CorruptedLogFileException {
450    Path path = walStatus.getPath();
451    long length = walStatus.getLen();
452    Reader in;
453
454    // Check for possibly empty file. With appends, currently Hadoop reports a
455    // zero length even if the file has been sync'd. Revisit if HDFS-376 or
456    // HDFS-878 is committed.
457    if (length <= 0) {
458      LOG.warn("File {} might be still open, length is 0", path);
459    }
460
461    try {
462      RecoverLeaseFSUtils.recoverFileLease(walFS, path, conf, cancel);
463      try {
464        in = getReader(path, cancel);
465      } catch (EOFException e) {
466        if (length <= 0) {
467          // TODO should we ignore an empty, not-last log file if skip.errors
468          // is false? Either way, the caller should decide what to do. E.g.
469          // ignore if this is the last log in sequence.
470          // TODO is this scenario still possible if the log has been
471          // recovered (i.e. closed)
472          LOG.warn("Could not open {} for reading. File is empty", path, e);
473        }
474        // EOFException being ignored
475        return null;
476      }
477    } catch (IOException e) {
478      if (e instanceof FileNotFoundException) {
479        // A wal file may not exist anymore. Nothing can be recovered so move on
480        LOG.warn("File {} does not exist anymore", path, e);
481        return null;
482      }
483      if (!skipErrors || e instanceof InterruptedIOException) {
484        throw e; // Don't mark the file corrupted if interrupted, or not skipErrors
485      }
486      throw new CorruptedLogFileException("skipErrors=true; could not open " + path + ", skipping",
487        e);
488    }
489    return in;
490  }
491
492  private Entry getNextLogLine(Reader in, Path path, boolean skipErrors)
493    throws CorruptedLogFileException, IOException {
494    try {
495      return in.next();
496    } catch (EOFException eof) {
497      // truncated files are expected if a RS crashes (see HBASE-2643)
498      LOG.info("EOF from {}; continuing.", path);
499      return null;
500    } catch (IOException e) {
501      // If the IOE resulted from bad file format,
502      // then this problem is idempotent and retrying won't help
503      if (
504        e.getCause() != null && (e.getCause() instanceof ParseException
505          || e.getCause() instanceof org.apache.hadoop.fs.ChecksumException)
506      ) {
507        LOG.warn("Parse exception from {}; continuing", path, e);
508        return null;
509      }
510      if (!skipErrors) {
511        throw e;
512      }
513      throw new CorruptedLogFileException("skipErrors=true Ignoring exception"
514        + " while parsing wal " + path + ". Marking as corrupted", e);
515    }
516  }
517
518  /**
519   * Create a new {@link WALProvider.Writer} for writing log splits.
520   * @return a new Writer instance, caller should close
521   */
522  protected WALProvider.Writer createWriter(Path logfile) throws IOException {
523    return walFactory.createRecoveredEditsWriter(walFS, logfile);
524  }
525
526  /**
527   * Create a new {@link Reader} for reading logs to split.
528   * @return new Reader instance, caller should close
529   */
530  private Reader getReader(Path curLogFile, CancelableProgressable reporter) throws IOException {
531    return walFactory.createReader(walFS, curLogFile, reporter);
532  }
533
534  /**
535   * Get current open writers
536   */
537  private int getNumOpenWriters() {
538    int result = 0;
539    if (this.outputSink != null) {
540      result += this.outputSink.getNumOpenWriters();
541    }
542    return result;
543  }
544
545  /**
546   * Contains some methods to control WAL-entries producer / consumer interactions
547   */
548  public static class PipelineController {
549    // If an exception is thrown by one of the other threads, it will be
550    // stored here.
551    AtomicReference<Throwable> thrown = new AtomicReference<>();
552
553    // Wait/notify for when data has been produced by the writer thread,
554    // consumed by the reader thread, or an exception occurred
555    final Object dataAvailable = new Object();
556
557    void writerThreadError(Throwable t) {
558      thrown.compareAndSet(null, t);
559    }
560
561    /**
562     * Check for errors in the writer threads. If any is found, rethrow it.
563     */
564    void checkForErrors() throws IOException {
565      Throwable thrown = this.thrown.get();
566      if (thrown == null) {
567        return;
568      }
569      if (thrown instanceof IOException) {
570        throw new IOException(thrown);
571      } else {
572        throw new RuntimeException(thrown);
573      }
574    }
575  }
576
577  static class CorruptedLogFileException extends Exception {
578    private static final long serialVersionUID = 1L;
579
580    CorruptedLogFileException(String s) {
581      super(s);
582    }
583
584    /**
585     * CorruptedLogFileException with cause
586     * @param message the message for this exception
587     * @param cause   the cause for this exception
588     */
589    CorruptedLogFileException(String message, Throwable cause) {
590      super(message, cause);
591    }
592  }
593}