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.regionserver.wal; 019 020import static org.apache.hadoop.hbase.regionserver.wal.WALActionsListener.RollRequestReason.ERROR; 021import static org.apache.hadoop.hbase.regionserver.wal.WALActionsListener.RollRequestReason.LOW_REPLICATION; 022import static org.apache.hadoop.hbase.regionserver.wal.WALActionsListener.RollRequestReason.SIZE; 023import static org.apache.hadoop.hbase.regionserver.wal.WALActionsListener.RollRequestReason.SLOW_SYNC; 024import static org.apache.hadoop.hbase.trace.HBaseSemanticAttributes.WAL_IMPL; 025import static org.apache.hadoop.hbase.util.FutureUtils.addListener; 026import static org.apache.hadoop.hbase.wal.AbstractFSWALProvider.WAL_FILE_NAME_DELIMITER; 027import static org.apache.hbase.thirdparty.com.google.common.base.Preconditions.checkArgument; 028import static org.apache.hbase.thirdparty.com.google.common.base.Preconditions.checkNotNull; 029 030import com.google.errorprone.annotations.RestrictedApi; 031import com.lmax.disruptor.RingBuffer; 032import com.lmax.disruptor.Sequence; 033import com.lmax.disruptor.Sequencer; 034import io.opentelemetry.api.trace.Span; 035import java.io.FileNotFoundException; 036import java.io.IOException; 037import java.io.InterruptedIOException; 038import java.lang.management.MemoryType; 039import java.net.URLEncoder; 040import java.nio.charset.StandardCharsets; 041import java.util.ArrayDeque; 042import java.util.ArrayList; 043import java.util.Arrays; 044import java.util.Comparator; 045import java.util.Deque; 046import java.util.Iterator; 047import java.util.List; 048import java.util.Map; 049import java.util.OptionalLong; 050import java.util.Set; 051import java.util.SortedSet; 052import java.util.TreeSet; 053import java.util.concurrent.Callable; 054import java.util.concurrent.CompletableFuture; 055import java.util.concurrent.ConcurrentHashMap; 056import java.util.concurrent.ConcurrentNavigableMap; 057import java.util.concurrent.ConcurrentSkipListMap; 058import java.util.concurrent.CopyOnWriteArrayList; 059import java.util.concurrent.ExecutionException; 060import java.util.concurrent.ExecutorService; 061import java.util.concurrent.Executors; 062import java.util.concurrent.Future; 063import java.util.concurrent.LinkedBlockingQueue; 064import java.util.concurrent.ThreadPoolExecutor; 065import java.util.concurrent.TimeUnit; 066import java.util.concurrent.TimeoutException; 067import java.util.concurrent.atomic.AtomicBoolean; 068import java.util.concurrent.atomic.AtomicInteger; 069import java.util.concurrent.atomic.AtomicLong; 070import java.util.concurrent.locks.Condition; 071import java.util.concurrent.locks.Lock; 072import java.util.concurrent.locks.ReentrantLock; 073import java.util.function.Supplier; 074import java.util.stream.Collectors; 075import org.apache.commons.lang3.mutable.MutableLong; 076import org.apache.hadoop.conf.Configuration; 077import org.apache.hadoop.fs.FileStatus; 078import org.apache.hadoop.fs.FileSystem; 079import org.apache.hadoop.fs.Path; 080import org.apache.hadoop.fs.PathFilter; 081import org.apache.hadoop.hbase.Abortable; 082import org.apache.hadoop.hbase.Cell; 083import org.apache.hadoop.hbase.HBaseConfiguration; 084import org.apache.hadoop.hbase.HConstants; 085import org.apache.hadoop.hbase.PrivateCellUtil; 086import org.apache.hadoop.hbase.client.ConnectionUtils; 087import org.apache.hadoop.hbase.client.RegionInfo; 088import org.apache.hadoop.hbase.exceptions.TimeoutIOException; 089import org.apache.hadoop.hbase.io.asyncfs.FanOutOneBlockAsyncDFSOutputHelper; 090import org.apache.hadoop.hbase.io.util.MemorySizeUtil; 091import org.apache.hadoop.hbase.ipc.RpcServer; 092import org.apache.hadoop.hbase.ipc.ServerCall; 093import org.apache.hadoop.hbase.log.HBaseMarkers; 094import org.apache.hadoop.hbase.regionserver.HRegion; 095import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl; 096import org.apache.hadoop.hbase.trace.TraceUtil; 097import org.apache.hadoop.hbase.util.Bytes; 098import org.apache.hadoop.hbase.util.CommonFSUtils; 099import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; 100import org.apache.hadoop.hbase.util.Pair; 101import org.apache.hadoop.hbase.util.RecoverLeaseFSUtils; 102import org.apache.hadoop.hbase.wal.AbstractFSWALProvider; 103import org.apache.hadoop.hbase.wal.WAL; 104import org.apache.hadoop.hbase.wal.WALEdit; 105import org.apache.hadoop.hbase.wal.WALFactory; 106import org.apache.hadoop.hbase.wal.WALKeyImpl; 107import org.apache.hadoop.hbase.wal.WALPrettyPrinter; 108import org.apache.hadoop.hbase.wal.WALProvider.WriterBase; 109import org.apache.hadoop.hbase.wal.WALSplitter; 110import org.apache.hadoop.hdfs.protocol.DatanodeInfo; 111import org.apache.hadoop.util.StringUtils; 112import org.apache.yetus.audience.InterfaceAudience; 113import org.slf4j.Logger; 114import org.slf4j.LoggerFactory; 115 116import org.apache.hbase.thirdparty.com.google.common.base.Preconditions; 117import org.apache.hbase.thirdparty.com.google.common.io.Closeables; 118import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder; 119 120/** 121 * Implementation of {@link WAL} to go against {@link FileSystem}; i.e. keep WALs in HDFS. Only one 122 * WAL is ever being written at a time. When a WAL hits a configured maximum size, it is rolled. 123 * This is done internal to the implementation. 124 * <p> 125 * As data is flushed from the MemStore to other on-disk structures (files sorted by key, hfiles), a 126 * WAL becomes obsolete. We can let go of all the log edits/entries for a given HRegion-sequence id. 127 * A bunch of work in the below is done keeping account of these region sequence ids -- what is 128 * flushed out to hfiles, and what is yet in WAL and in memory only. 129 * <p> 130 * It is only practical to delete entire files. Thus, we delete an entire on-disk file 131 * <code>F</code> when all of the edits in <code>F</code> have a log-sequence-id that's older 132 * (smaller) than the most-recent flush. 133 * <p> 134 * To read an WAL, call {@link WALFactory#createStreamReader(FileSystem, Path)} for one way read, 135 * call {@link WALFactory#createTailingReader(FileSystem, Path, Configuration, long)} for 136 * replication where we may want to tail the active WAL file. 137 * <h2>Failure Semantic</h2> If an exception on append or sync, roll the WAL because the current WAL 138 * is now a lame duck; any more appends or syncs will fail also with the same original exception. If 139 * we have made successful appends to the WAL and we then are unable to sync them, our current 140 * semantic is to return error to the client that the appends failed but also to abort the current 141 * context, usually the hosting server. We need to replay the WALs. <br> 142 * TODO: Change this semantic. A roll of WAL may be sufficient as long as we have flagged client 143 * that the append failed. <br> 144 * TODO: replication may pick up these last edits though they have been marked as failed append 145 * (Need to keep our own file lengths, not rely on HDFS). 146 */ 147@InterfaceAudience.Private 148public abstract class AbstractFSWAL<W extends WriterBase> implements WAL { 149 private static final Logger LOG = LoggerFactory.getLogger(AbstractFSWAL.class); 150 151 private static final Comparator<SyncFuture> SEQ_COMPARATOR = 152 Comparator.comparingLong(SyncFuture::getTxid).thenComparingInt(System::identityHashCode); 153 154 private static final String SURVIVED_TOO_LONG_SEC_KEY = "hbase.regionserver.wal.too.old.sec"; 155 private static final int SURVIVED_TOO_LONG_SEC_DEFAULT = 900; 156 /** Don't log blocking regions more frequently than this. */ 157 private static final long SURVIVED_TOO_LONG_LOG_INTERVAL_NS = TimeUnit.MINUTES.toNanos(5); 158 159 protected static final String SLOW_SYNC_TIME_MS = "hbase.regionserver.wal.slowsync.ms"; 160 protected static final int DEFAULT_SLOW_SYNC_TIME_MS = 100; // in ms 161 protected static final String ROLL_ON_SYNC_TIME_MS = "hbase.regionserver.wal.roll.on.sync.ms"; 162 protected static final int DEFAULT_ROLL_ON_SYNC_TIME_MS = 10000; // in ms 163 protected static final String SLOW_SYNC_ROLL_THRESHOLD = 164 "hbase.regionserver.wal.slowsync.roll.threshold"; 165 protected static final int DEFAULT_SLOW_SYNC_ROLL_THRESHOLD = 100; // 100 slow sync warnings 166 protected static final String SLOW_SYNC_ROLL_INTERVAL_MS = 167 "hbase.regionserver.wal.slowsync.roll.interval.ms"; 168 protected static final int DEFAULT_SLOW_SYNC_ROLL_INTERVAL_MS = 60 * 1000; // in ms, 1 minute 169 170 public static final String WAL_SYNC_TIMEOUT_MS = "hbase.regionserver.wal.sync.timeout"; 171 protected static final int DEFAULT_WAL_SYNC_TIMEOUT_MS = 5 * 60 * 1000; // in ms, 5min 172 173 public static final String WAL_ROLL_MULTIPLIER = "hbase.regionserver.logroll.multiplier"; 174 175 public static final String MAX_LOGS = "hbase.regionserver.maxlogs"; 176 177 public static final String RING_BUFFER_SLOT_COUNT = 178 "hbase.regionserver.wal.disruptor.event.count"; 179 180 public static final String WAL_SHUTDOWN_WAIT_TIMEOUT_MS = "hbase.wal.shutdown.wait.timeout.ms"; 181 public static final int DEFAULT_WAL_SHUTDOWN_WAIT_TIMEOUT_MS = 15 * 1000; 182 183 public static final String WAL_BATCH_SIZE = "hbase.wal.batch.size"; 184 public static final long DEFAULT_WAL_BATCH_SIZE = 64L * 1024; 185 186 public static final String WAL_AVOID_LOCAL_WRITES_KEY = 187 "hbase.regionserver.wal.avoid-local-writes"; 188 public static final boolean WAL_AVOID_LOCAL_WRITES_DEFAULT = false; 189 190 /** 191 * file system instance 192 */ 193 protected final FileSystem fs; 194 195 /** 196 * WAL directory, where all WAL files would be placed. 197 */ 198 protected final Path walDir; 199 200 private final FileSystem remoteFs; 201 202 private final Path remoteWALDir; 203 204 /** 205 * dir path where old logs are kept. 206 */ 207 protected final Path walArchiveDir; 208 209 /** 210 * Matches just those wal files that belong to this wal instance. 211 */ 212 protected final PathFilter ourFiles; 213 214 /** 215 * Prefix of a WAL file, usually the region server name it is hosted on. 216 */ 217 protected final String walFilePrefix; 218 219 /** 220 * Suffix included on generated wal file names 221 */ 222 protected final String walFileSuffix; 223 224 /** 225 * Prefix used when checking for wal membership. 226 */ 227 protected final String prefixPathStr; 228 229 protected final WALCoprocessorHost coprocessorHost; 230 231 /** 232 * conf object 233 */ 234 protected final Configuration conf; 235 236 protected final Abortable abortable; 237 238 /** Listeners that are called on WAL events. */ 239 protected final List<WALActionsListener> listeners = new CopyOnWriteArrayList<>(); 240 241 /** Tracks the logs in the process of being closed. */ 242 protected final Map<String, W> inflightWALClosures = new ConcurrentHashMap<>(); 243 244 /** 245 * Class that does accounting of sequenceids in WAL subsystem. Holds oldest outstanding sequence 246 * id as yet not flushed as well as the most recent edit sequence id appended to the WAL. Has 247 * facility for answering questions such as "Is it safe to GC a WAL?". 248 */ 249 protected final SequenceIdAccounting sequenceIdAccounting = new SequenceIdAccounting(); 250 251 /** The slow sync will be logged; the very slow sync will cause the WAL to be rolled. */ 252 protected final long slowSyncNs, rollOnSyncNs; 253 protected final int slowSyncRollThreshold; 254 protected final int slowSyncCheckInterval; 255 protected final AtomicInteger slowSyncCount = new AtomicInteger(); 256 257 private final long walSyncTimeoutNs; 258 259 private final long walTooOldNs; 260 261 // If > than this size, roll the log. 262 protected final long logrollsize; 263 264 /** 265 * Block size to use writing files. 266 */ 267 protected final long blocksize; 268 269 /* 270 * If more than this many logs, force flush of oldest region to the oldest edit goes to disk. If 271 * too many and we crash, then will take forever replaying. Keep the number of logs tidy. 272 */ 273 protected final int maxLogs; 274 275 protected final boolean useHsync; 276 277 /** 278 * This lock makes sure only one log roll runs at a time. Should not be taken while any other lock 279 * is held. We don't just use synchronized because that results in bogus and tedious findbugs 280 * warning when it thinks synchronized controls writer thread safety. It is held when we are 281 * actually rolling the log. It is checked when we are looking to see if we should roll the log or 282 * not. 283 */ 284 protected final ReentrantLock rollWriterLock = new ReentrantLock(true); 285 286 // The timestamp (in ms) when the log file was created. 287 protected final AtomicLong filenum = new AtomicLong(-1); 288 289 // Number of transactions in the current Wal. 290 protected final AtomicInteger numEntries = new AtomicInteger(0); 291 292 /** 293 * The highest known outstanding unsync'd WALEdit transaction id. Usually, we use a queue to pass 294 * WALEdit to background consumer thread, and the transaction id is the sequence number of the 295 * corresponding entry in queue. 296 */ 297 protected volatile long highestUnsyncedTxid = -1; 298 299 /** 300 * Updated to the transaction id of the last successful sync call. This can be less than 301 * {@link #highestUnsyncedTxid} for case where we have an append where a sync has not yet come in 302 * for it. 303 */ 304 protected final AtomicLong highestSyncedTxid = new AtomicLong(0); 305 306 /** 307 * The total size of wal 308 */ 309 protected final AtomicLong totalLogSize = new AtomicLong(0); 310 /** 311 * Current log file. 312 */ 313 volatile W writer; 314 315 // Last time to check low replication on hlog's pipeline 316 private volatile long lastTimeCheckLowReplication = EnvironmentEdgeManager.currentTime(); 317 318 // Last time we asked to roll the log due to a slow sync 319 private volatile long lastTimeCheckSlowSync = EnvironmentEdgeManager.currentTime(); 320 321 protected volatile boolean closed = false; 322 323 protected final AtomicBoolean shutdown = new AtomicBoolean(false); 324 325 protected final long walShutdownTimeout; 326 327 private long nextLogTooOldNs = System.nanoTime(); 328 329 /** 330 * WAL Comparator; it compares the timestamp (log filenum), present in the log file name. Throws 331 * an IllegalArgumentException if used to compare paths from different wals. 332 */ 333 final Comparator<Path> LOG_NAME_COMPARATOR = 334 (o1, o2) -> Long.compare(getFileNumFromFileName(o1), getFileNumFromFileName(o2)); 335 336 private static final class WALProps { 337 338 /** 339 * Map the encoded region name to the highest sequence id. 340 * <p/> 341 * Contains all the regions it has an entry for. 342 */ 343 private final Map<byte[], Long> encodedName2HighestSequenceId; 344 345 /** 346 * The log file size. Notice that the size may not be accurate if we do asynchronous close in 347 * subclasses. 348 */ 349 private final long logSize; 350 351 /** 352 * The nanoTime of the log rolling, used to determine the time interval that has passed since. 353 */ 354 private final long rollTimeNs; 355 356 /** 357 * If we do asynchronous close in subclasses, it is possible that when adding WALProps to the 358 * rolled map, the file is not closed yet, so in cleanOldLogs we should not archive this file, 359 * for safety. 360 */ 361 private volatile boolean closed = false; 362 363 WALProps(Map<byte[], Long> encodedName2HighestSequenceId, long logSize) { 364 this.encodedName2HighestSequenceId = encodedName2HighestSequenceId; 365 this.logSize = logSize; 366 this.rollTimeNs = System.nanoTime(); 367 } 368 } 369 370 /** 371 * Map of WAL log file to properties. The map is sorted by the log file creation timestamp 372 * (contained in the log file name). 373 */ 374 protected final ConcurrentNavigableMap<Path, WALProps> walFile2Props = 375 new ConcurrentSkipListMap<>(LOG_NAME_COMPARATOR); 376 377 /** 378 * A cache of sync futures reused by threads. 379 */ 380 protected final SyncFutureCache syncFutureCache; 381 382 /** 383 * The class name of the runtime implementation, used as prefix for logging/tracing. 384 * <p> 385 * Performance testing shows getClass().getSimpleName() might be a bottleneck so we store it here, 386 * refer to HBASE-17676 for more details 387 * </p> 388 */ 389 protected final String implClassName; 390 391 protected final AtomicBoolean rollRequested = new AtomicBoolean(false); 392 393 protected final ExecutorService closeExecutor = Executors.newCachedThreadPool( 394 new ThreadFactoryBuilder().setDaemon(true).setNameFormat("Close-WAL-Writer-%d").build()); 395 396 // Run in caller if we get reject execution exception, to avoid aborting region server when we get 397 // reject execution exception. Usually this should not happen but let's make it more robust. 398 private final ExecutorService logArchiveExecutor = 399 new ThreadPoolExecutor(1, 1, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(), 400 new ThreadFactoryBuilder().setDaemon(true).setNameFormat("WAL-Archive-%d").build(), 401 new ThreadPoolExecutor.CallerRunsPolicy()); 402 403 private final int archiveRetries; 404 405 protected ExecutorService consumeExecutor; 406 407 private final Lock consumeLock = new ReentrantLock(); 408 409 protected final Runnable consumer = this::consume; 410 411 // check if there is already a consumer task in the event loop's task queue 412 protected Supplier<Boolean> hasConsumerTask; 413 414 private static final int MAX_EPOCH = 0x3FFFFFFF; 415 // the lowest bit is waitingRoll, which means new writer is created, and we are waiting for old 416 // writer to be closed. 417 // the second-lowest bit is writerBroken which means the current writer is broken and rollWriter 418 // is needed. 419 // all other bits are the epoch number of the current writer, this is used to detect whether the 420 // writer is still the one when you issue the sync. 421 // notice that, modification to this field is only allowed under the protection of consumeLock. 422 private volatile int epochAndState; 423 424 private boolean readyForRolling; 425 426 private final Condition readyForRollingCond = consumeLock.newCondition(); 427 428 private final RingBuffer<RingBufferTruck> waitingConsumePayloads; 429 430 private final Sequence waitingConsumePayloadsGatingSequence; 431 432 private final AtomicBoolean consumerScheduled = new AtomicBoolean(false); 433 434 private final long batchSize; 435 436 protected final Deque<FSWALEntry> toWriteAppends = new ArrayDeque<>(); 437 438 protected final Deque<FSWALEntry> unackedAppends = new ArrayDeque<>(); 439 440 protected final SortedSet<SyncFuture> syncFutures = new TreeSet<>(SEQ_COMPARATOR); 441 442 // the highest txid of WAL entries being processed 443 protected long highestProcessedAppendTxid; 444 445 // file length when we issue last sync request on the writer 446 private long fileLengthAtLastSync; 447 448 private long highestProcessedAppendTxidAtLastSync; 449 450 private int waitOnShutdownInSeconds; 451 452 private String waitOnShutdownInSecondsConfigKey; 453 454 protected boolean shouldShutDownConsumeExecutorWhenClose = true; 455 456 private volatile boolean skipRemoteWAL = false; 457 458 private volatile boolean markerEditOnly = false; 459 460 public long getFilenum() { 461 return this.filenum.get(); 462 } 463 464 /** 465 * A log file has a creation timestamp (in ms) in its file name ({@link #filenum}. This helper 466 * method returns the creation timestamp from a given log file. It extracts the timestamp assuming 467 * the filename is created with the {@link #computeFilename(long filenum)} method. 468 * @return timestamp, as in the log file name. 469 */ 470 protected long getFileNumFromFileName(Path fileName) { 471 checkNotNull(fileName, "file name can't be null"); 472 if (!ourFiles.accept(fileName)) { 473 throw new IllegalArgumentException( 474 "The log file " + fileName + " doesn't belong to this WAL. (" + toString() + ")"); 475 } 476 final String fileNameString = fileName.toString(); 477 String chompedPath = fileNameString.substring(prefixPathStr.length(), 478 (fileNameString.length() - walFileSuffix.length())); 479 return Long.parseLong(chompedPath); 480 } 481 482 private int calculateMaxLogFiles(Configuration conf, long logRollSize) { 483 checkArgument(logRollSize > 0, 484 "The log roll size cannot be zero or negative when calculating max log files, " 485 + "current value is " + logRollSize); 486 Pair<Long, MemoryType> globalMemstoreSize = MemorySizeUtil.getGlobalMemStoreSize(conf); 487 return (int) ((globalMemstoreSize.getFirst() * 2) / logRollSize); 488 } 489 490 // must be power of 2 491 protected final int getPreallocatedEventCount() { 492 // Preallocate objects to use on the ring buffer. The way that appends and syncs work, we will 493 // be stuck and make no progress if the buffer is filled with appends only and there is no 494 // sync. If no sync, then the handlers will be outstanding just waiting on sync completion 495 // before they return. 496 int preallocatedEventCount = this.conf.getInt(RING_BUFFER_SLOT_COUNT, 1024 * 16); 497 checkArgument(preallocatedEventCount >= 0, RING_BUFFER_SLOT_COUNT + " must > 0"); 498 int floor = Integer.highestOneBit(preallocatedEventCount); 499 if (floor == preallocatedEventCount) { 500 return floor; 501 } 502 // max capacity is 1 << 30 503 if (floor >= 1 << 29) { 504 return 1 << 30; 505 } 506 return floor << 1; 507 } 508 509 protected final void setWaitOnShutdownInSeconds(int waitOnShutdownInSeconds, 510 String waitOnShutdownInSecondsConfigKey) { 511 this.waitOnShutdownInSeconds = waitOnShutdownInSeconds; 512 this.waitOnShutdownInSecondsConfigKey = waitOnShutdownInSecondsConfigKey; 513 } 514 515 protected final void createSingleThreadPoolConsumeExecutor(String walType, final Path rootDir, 516 final String prefix) { 517 ThreadPoolExecutor threadPool = 518 new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), 519 new ThreadFactoryBuilder().setNameFormat(walType + "-%d-" + rootDir.toString() + "-prefix:" 520 + (prefix == null ? "default" : prefix).replace("%", "%%")).setDaemon(true).build()); 521 hasConsumerTask = () -> threadPool.getQueue().peek() == consumer; 522 consumeExecutor = threadPool; 523 this.shouldShutDownConsumeExecutorWhenClose = true; 524 } 525 526 protected AbstractFSWAL(final FileSystem fs, final Abortable abortable, final Path rootDir, 527 final String logDir, final String archiveDir, final Configuration conf, 528 final List<WALActionsListener> listeners, final boolean failIfWALExists, final String prefix, 529 final String suffix, FileSystem remoteFs, Path remoteWALDir) 530 throws FailedLogCloseException, IOException { 531 this.fs = fs; 532 this.walDir = new Path(rootDir, logDir); 533 this.walArchiveDir = new Path(rootDir, archiveDir); 534 this.conf = conf; 535 this.abortable = abortable; 536 this.remoteFs = remoteFs; 537 this.remoteWALDir = remoteWALDir; 538 539 // Here we only crate archive dir, without wal dir. This is to make sure that our fencing way 540 // takes effect. See HBASE-29797 for more details. 541 if (!fs.exists(this.walArchiveDir)) { 542 if (!fs.mkdirs(this.walArchiveDir)) { 543 throw new IOException("Unable to mkdir " + this.walArchiveDir); 544 } 545 } 546 547 // If prefix is null||empty then just name it wal 548 this.walFilePrefix = prefix == null || prefix.isEmpty() 549 ? "wal" 550 : URLEncoder.encode(prefix, StandardCharsets.UTF_8.name()); 551 // we only correctly differentiate suffices when numeric ones start with '.' 552 if (suffix != null && !(suffix.isEmpty()) && !(suffix.startsWith(WAL_FILE_NAME_DELIMITER))) { 553 throw new IllegalArgumentException("WAL suffix must start with '" + WAL_FILE_NAME_DELIMITER 554 + "' but instead was '" + suffix + "'"); 555 } 556 // Now that it exists, set the storage policy for the entire directory of wal files related to 557 // this FSHLog instance 558 String storagePolicy = 559 conf.get(HConstants.WAL_STORAGE_POLICY, HConstants.DEFAULT_WAL_STORAGE_POLICY); 560 CommonFSUtils.setStoragePolicy(fs, this.walDir, storagePolicy); 561 this.walFileSuffix = (suffix == null) ? "" : URLEncoder.encode(suffix, "UTF8"); 562 this.prefixPathStr = new Path(walDir, walFilePrefix + WAL_FILE_NAME_DELIMITER).toString(); 563 564 this.ourFiles = new PathFilter() { 565 @Override 566 public boolean accept(final Path fileName) { 567 // The path should start with dir/<prefix> and end with our suffix 568 final String fileNameString = fileName.toString(); 569 if (!fileNameString.startsWith(prefixPathStr)) { 570 return false; 571 } 572 if (walFileSuffix.isEmpty()) { 573 // in the case of the null suffix, we need to ensure the filename ends with a timestamp. 574 return org.apache.commons.lang3.StringUtils 575 .isNumeric(fileNameString.substring(prefixPathStr.length())); 576 } else if (!fileNameString.endsWith(walFileSuffix)) { 577 return false; 578 } 579 return true; 580 } 581 }; 582 583 if (failIfWALExists) { 584 final FileStatus[] walFiles = CommonFSUtils.listStatus(fs, walDir, ourFiles); 585 if (null != walFiles && 0 != walFiles.length) { 586 throw new IOException("Target WAL already exists within directory " + walDir); 587 } 588 } 589 590 // Register listeners. TODO: Should this exist anymore? We have CPs? 591 if (listeners != null) { 592 for (WALActionsListener i : listeners) { 593 registerWALActionsListener(i); 594 } 595 } 596 this.coprocessorHost = new WALCoprocessorHost(this, conf); 597 598 // Schedule a WAL roll when the WAL is 50% of the HDFS block size. Scheduling at 50% of block 599 // size should make it so WAL rolls before we get to the end-of-block (Block transitions cost 600 // some latency). In hbase-1 we did this differently. We scheduled a roll when we hit 95% of 601 // the block size but experience from the field has it that this was not enough time for the 602 // roll to happen before end-of-block. So the new accounting makes WALs of about the same 603 // size as those made in hbase-1 (to prevent surprise), we now have default block size as 604 // 2 times the DFS default: i.e. 2 * DFS default block size rolling at 50% full will generally 605 // make similar size logs to 1 * DFS default block size rolling at 95% full. See HBASE-19148. 606 this.blocksize = WALUtil.getWALBlockSize(this.conf, this.fs, this.walDir); 607 float multiplier = conf.getFloat(WAL_ROLL_MULTIPLIER, 0.5f); 608 this.logrollsize = (long) (this.blocksize * multiplier); 609 this.maxLogs = conf.getInt(MAX_LOGS, Math.max(32, calculateMaxLogFiles(conf, logrollsize))); 610 611 LOG.info("WAL configuration: blocksize=" + StringUtils.byteDesc(blocksize) + ", rollsize=" 612 + StringUtils.byteDesc(this.logrollsize) + ", prefix=" + this.walFilePrefix + ", suffix=" 613 + walFileSuffix + ", logDir=" + this.walDir + ", archiveDir=" + this.walArchiveDir 614 + ", maxLogs=" + this.maxLogs); 615 this.slowSyncNs = 616 TimeUnit.MILLISECONDS.toNanos(conf.getInt(SLOW_SYNC_TIME_MS, DEFAULT_SLOW_SYNC_TIME_MS)); 617 this.rollOnSyncNs = TimeUnit.MILLISECONDS 618 .toNanos(conf.getInt(ROLL_ON_SYNC_TIME_MS, DEFAULT_ROLL_ON_SYNC_TIME_MS)); 619 this.slowSyncRollThreshold = 620 conf.getInt(SLOW_SYNC_ROLL_THRESHOLD, DEFAULT_SLOW_SYNC_ROLL_THRESHOLD); 621 this.slowSyncCheckInterval = 622 conf.getInt(SLOW_SYNC_ROLL_INTERVAL_MS, DEFAULT_SLOW_SYNC_ROLL_INTERVAL_MS); 623 this.walSyncTimeoutNs = 624 TimeUnit.MILLISECONDS.toNanos(conf.getLong(WAL_SYNC_TIMEOUT_MS, DEFAULT_WAL_SYNC_TIMEOUT_MS)); 625 this.syncFutureCache = new SyncFutureCache(conf); 626 this.implClassName = getClass().getSimpleName(); 627 this.walTooOldNs = TimeUnit.SECONDS 628 .toNanos(conf.getInt(SURVIVED_TOO_LONG_SEC_KEY, SURVIVED_TOO_LONG_SEC_DEFAULT)); 629 this.useHsync = conf.getBoolean(HRegion.WAL_HSYNC_CONF_KEY, HRegion.DEFAULT_WAL_HSYNC); 630 archiveRetries = this.conf.getInt("hbase.regionserver.walroll.archive.retries", 0); 631 this.walShutdownTimeout = 632 conf.getLong(WAL_SHUTDOWN_WAIT_TIMEOUT_MS, DEFAULT_WAL_SHUTDOWN_WAIT_TIMEOUT_MS); 633 634 int preallocatedEventCount = 635 conf.getInt("hbase.regionserver.wal.disruptor.event.count", 1024 * 16); 636 waitingConsumePayloads = 637 RingBuffer.createMultiProducer(RingBufferTruck::new, preallocatedEventCount); 638 waitingConsumePayloadsGatingSequence = new Sequence(Sequencer.INITIAL_CURSOR_VALUE); 639 waitingConsumePayloads.addGatingSequences(waitingConsumePayloadsGatingSequence); 640 641 // inrease the ringbuffer sequence so our txid is start from 1 642 waitingConsumePayloads.publish(waitingConsumePayloads.next()); 643 waitingConsumePayloadsGatingSequence.set(waitingConsumePayloads.getCursor()); 644 645 batchSize = conf.getLong(WAL_BATCH_SIZE, DEFAULT_WAL_BATCH_SIZE); 646 } 647 648 /** 649 * Used to initialize the WAL. Usually just call rollWriter to create the first log writer. 650 */ 651 @Override 652 public void init() throws IOException { 653 rollWriter(); 654 } 655 656 @Override 657 public void registerWALActionsListener(WALActionsListener listener) { 658 this.listeners.add(listener); 659 } 660 661 @Override 662 public boolean unregisterWALActionsListener(WALActionsListener listener) { 663 return this.listeners.remove(listener); 664 } 665 666 @Override 667 public WALCoprocessorHost getCoprocessorHost() { 668 return coprocessorHost; 669 } 670 671 @Override 672 public Long startCacheFlush(byte[] encodedRegionName, Set<byte[]> families) { 673 return this.sequenceIdAccounting.startCacheFlush(encodedRegionName, families); 674 } 675 676 @Override 677 public Long startCacheFlush(byte[] encodedRegionName, Map<byte[], Long> familyToSeq) { 678 return this.sequenceIdAccounting.startCacheFlush(encodedRegionName, familyToSeq); 679 } 680 681 @Override 682 public void completeCacheFlush(byte[] encodedRegionName, long maxFlushedSeqId) { 683 this.sequenceIdAccounting.completeCacheFlush(encodedRegionName, maxFlushedSeqId); 684 } 685 686 @Override 687 public void abortCacheFlush(byte[] encodedRegionName) { 688 this.sequenceIdAccounting.abortCacheFlush(encodedRegionName); 689 } 690 691 @Override 692 public long getEarliestMemStoreSeqNum(byte[] encodedRegionName, byte[] familyName) { 693 // This method is used by tests and for figuring if we should flush or not because our 694 // sequenceids are too old. It is also used reporting the master our oldest sequenceid for use 695 // figuring what edits can be skipped during log recovery. getEarliestMemStoreSequenceId 696 // from this.sequenceIdAccounting is looking first in flushingOldestStoreSequenceIds, the 697 // currently flushing sequence ids, and if anything found there, it is returning these. This is 698 // the right thing to do for the reporting oldest sequenceids to master; we won't skip edits if 699 // we crash during the flush. For figuring what to flush, we might get requeued if our sequence 700 // id is old even though we are currently flushing. This may mean we do too much flushing. 701 return this.sequenceIdAccounting.getLowestSequenceId(encodedRegionName, familyName); 702 } 703 704 @Override 705 public Map<byte[], List<byte[]>> rollWriter() throws FailedLogCloseException, IOException { 706 return rollWriter(false); 707 } 708 709 @Override 710 public final void sync() throws IOException { 711 sync(useHsync); 712 } 713 714 @Override 715 public final void sync(long txid) throws IOException { 716 sync(txid, useHsync); 717 } 718 719 @Override 720 public final void sync(boolean forceSync) throws IOException { 721 TraceUtil.trace(() -> doSync(forceSync), () -> createSpan("WAL.sync")); 722 } 723 724 @Override 725 public final void sync(long txid, boolean forceSync) throws IOException { 726 TraceUtil.trace(() -> doSync(txid, forceSync), () -> createSpan("WAL.sync")); 727 } 728 729 @RestrictedApi(explanation = "Should only be called in tests", link = "", 730 allowedOnPath = ".*/src/test/.*") 731 public SequenceIdAccounting getSequenceIdAccounting() { 732 return sequenceIdAccounting; 733 } 734 735 /** 736 * This is a convenience method that computes a new filename with a given file-number. 737 * @param filenum to use 738 */ 739 protected Path computeFilename(final long filenum) { 740 if (filenum < 0) { 741 throw new RuntimeException("WAL file number can't be < 0"); 742 } 743 String child = walFilePrefix + WAL_FILE_NAME_DELIMITER + filenum + walFileSuffix; 744 return new Path(walDir, child); 745 } 746 747 /** 748 * This is a convenience method that computes a new filename with a given using the current WAL 749 * file-number 750 */ 751 public Path getCurrentFileName() { 752 return computeFilename(this.filenum.get()); 753 } 754 755 /** 756 * retrieve the next path to use for writing. Increments the internal filenum. 757 */ 758 private Path getNewPath() throws IOException { 759 this.filenum.set(Math.max(getFilenum() + 1, EnvironmentEdgeManager.currentTime())); 760 Path newPath = getCurrentFileName(); 761 return newPath; 762 } 763 764 public Path getOldPath() { 765 long currentFilenum = this.filenum.get(); 766 Path oldPath = null; 767 if (currentFilenum > 0) { 768 // ComputeFilename will take care of meta wal filename 769 oldPath = computeFilename(currentFilenum); 770 } // I presume if currentFilenum is <= 0, this is first file and null for oldPath if fine? 771 return oldPath; 772 } 773 774 /** 775 * Tell listeners about pre log roll. 776 */ 777 private void tellListenersAboutPreLogRoll(final Path oldPath, final Path newPath) 778 throws IOException { 779 coprocessorHost.preWALRoll(oldPath, newPath); 780 781 if (!this.listeners.isEmpty()) { 782 for (WALActionsListener i : this.listeners) { 783 i.preLogRoll(oldPath, newPath); 784 } 785 } 786 } 787 788 /** 789 * Tell listeners about post log roll. 790 */ 791 private void tellListenersAboutPostLogRoll(final Path oldPath, final Path newPath) 792 throws IOException { 793 if (!this.listeners.isEmpty()) { 794 for (WALActionsListener i : this.listeners) { 795 i.postLogRoll(oldPath, newPath); 796 } 797 } 798 799 coprocessorHost.postWALRoll(oldPath, newPath); 800 } 801 802 // public only until class moves to o.a.h.h.wal 803 /** Returns the number of rolled log files */ 804 public int getNumRolledLogFiles() { 805 return walFile2Props.size(); 806 } 807 808 // public only until class moves to o.a.h.h.wal 809 /** Returns the number of log files in use */ 810 public int getNumLogFiles() { 811 // +1 for current use log 812 return getNumRolledLogFiles() + 1; 813 } 814 815 /** 816 * If the number of un-archived WAL files ('live' WALs) is greater than maximum allowed, check the 817 * first (oldest) WAL, and return those regions which should be flushed so that it can be 818 * let-go/'archived'. 819 * @return stores of regions (encodedRegionNames) to flush in order to archive the oldest WAL file 820 */ 821 Map<byte[], List<byte[]>> findRegionsToForceFlush() throws IOException { 822 Map<byte[], List<byte[]>> regions = null; 823 int logCount = getNumRolledLogFiles(); 824 if (logCount > this.maxLogs && logCount > 0) { 825 Map.Entry<Path, WALProps> firstWALEntry = this.walFile2Props.firstEntry(); 826 regions = 827 this.sequenceIdAccounting.findLower(firstWALEntry.getValue().encodedName2HighestSequenceId); 828 } 829 if (regions != null) { 830 List<String> listForPrint = new ArrayList<>(); 831 for (Map.Entry<byte[], List<byte[]>> r : regions.entrySet()) { 832 StringBuilder families = new StringBuilder(); 833 for (int i = 0; i < r.getValue().size(); i++) { 834 if (i > 0) { 835 families.append(","); 836 } 837 families.append(Bytes.toString(r.getValue().get(i))); 838 } 839 listForPrint.add(Bytes.toStringBinary(r.getKey()) + "[" + families.toString() + "]"); 840 } 841 LOG.info("Too many WALs; count=" + logCount + ", max=" + this.maxLogs 842 + "; forcing (partial) flush of " + regions.size() + " region(s): " 843 + StringUtils.join(",", listForPrint)); 844 } 845 return regions; 846 } 847 848 /** 849 * Mark this WAL file as closed and call cleanOldLogs to see if we can archive this file. 850 */ 851 private void markClosedAndClean(Path path) { 852 WALProps props = walFile2Props.get(path); 853 // typically this should not be null, but if there is no big issue if it is already null, so 854 // let's make the code more robust 855 if (props != null) { 856 props.closed = true; 857 cleanOldLogs(); 858 } 859 } 860 861 /** 862 * Archive old logs. A WAL is eligible for archiving if all its WALEdits have been flushed. 863 * <p/> 864 * Use synchronized because we may call this method in different threads, normally when replacing 865 * writer, and since now close writer may be asynchronous, we will also call this method in the 866 * closeExecutor, right after we actually close a WAL writer. 867 */ 868 private synchronized void cleanOldLogs() { 869 List<Pair<Path, Long>> logsToArchive = null; 870 long now = System.nanoTime(); 871 boolean mayLogTooOld = nextLogTooOldNs <= now; 872 ArrayList<byte[]> regionsBlockingWal = null; 873 // For each log file, look at its Map of regions to the highest sequence id; if all sequence ids 874 // are older than what is currently in memory, the WAL can be GC'd. 875 for (Map.Entry<Path, WALProps> e : this.walFile2Props.entrySet()) { 876 if (!e.getValue().closed) { 877 LOG.debug("{} is not closed yet, will try archiving it next time", e.getKey()); 878 continue; 879 } 880 Path log = e.getKey(); 881 ArrayList<byte[]> regionsBlockingThisWal = null; 882 long ageNs = now - e.getValue().rollTimeNs; 883 if (ageNs > walTooOldNs) { 884 if (mayLogTooOld && regionsBlockingWal == null) { 885 regionsBlockingWal = new ArrayList<>(); 886 } 887 regionsBlockingThisWal = regionsBlockingWal; 888 } 889 Map<byte[], Long> sequenceNums = e.getValue().encodedName2HighestSequenceId; 890 if (this.sequenceIdAccounting.areAllLower(sequenceNums, regionsBlockingThisWal)) { 891 if (logsToArchive == null) { 892 logsToArchive = new ArrayList<>(); 893 } 894 logsToArchive.add(Pair.newPair(log, e.getValue().logSize)); 895 if (LOG.isTraceEnabled()) { 896 LOG.trace("WAL file ready for archiving " + log); 897 } 898 } else if (regionsBlockingThisWal != null) { 899 StringBuilder sb = new StringBuilder(log.toString()).append(" has not been archived for ") 900 .append(TimeUnit.NANOSECONDS.toSeconds(ageNs)).append(" seconds; blocked by: "); 901 boolean isFirst = true; 902 for (byte[] region : regionsBlockingThisWal) { 903 if (!isFirst) { 904 sb.append("; "); 905 } 906 isFirst = false; 907 sb.append(Bytes.toString(region)); 908 } 909 LOG.warn(sb.toString()); 910 nextLogTooOldNs = now + SURVIVED_TOO_LONG_LOG_INTERVAL_NS; 911 regionsBlockingThisWal.clear(); 912 } 913 } 914 915 if (logsToArchive != null) { 916 final List<Pair<Path, Long>> localLogsToArchive = logsToArchive; 917 // make it async 918 for (Pair<Path, Long> log : localLogsToArchive) { 919 logArchiveExecutor.execute(() -> { 920 archive(log); 921 }); 922 this.walFile2Props.remove(log.getFirst()); 923 } 924 } 925 } 926 927 protected void archive(final Pair<Path, Long> log) { 928 totalLogSize.addAndGet(-log.getSecond()); 929 int retry = 1; 930 while (true) { 931 try { 932 archiveLogFile(log.getFirst()); 933 // successful 934 break; 935 } catch (Throwable e) { 936 if (retry > archiveRetries) { 937 LOG.error("Failed log archiving for the log {},", log.getFirst(), e); 938 if (this.abortable != null) { 939 this.abortable.abort("Failed log archiving", e); 940 break; 941 } 942 } else { 943 LOG.error("Log archiving failed for the log {} - attempt {}", log.getFirst(), retry, e); 944 } 945 retry++; 946 } 947 } 948 } 949 950 /* 951 * only public so WALSplitter can use. 952 * @return archived location of a WAL file with the given path p 953 */ 954 public static Path getWALArchivePath(Path archiveDir, Path p) { 955 return new Path(archiveDir, p.getName()); 956 } 957 958 protected void archiveLogFile(final Path p) throws IOException { 959 Path newPath = getWALArchivePath(this.walArchiveDir, p); 960 // Tell our listeners that a log is going to be archived. 961 if (!this.listeners.isEmpty()) { 962 for (WALActionsListener i : this.listeners) { 963 i.preLogArchive(p, newPath); 964 } 965 } 966 LOG.info("Archiving " + p + " to " + newPath); 967 if (!CommonFSUtils.renameAndSetModifyTime(this.fs, p, newPath)) { 968 throw new IOException("Unable to rename " + p + " to " + newPath); 969 } 970 // Tell our listeners that a log has been archived. 971 if (!this.listeners.isEmpty()) { 972 for (WALActionsListener i : this.listeners) { 973 i.postLogArchive(p, newPath); 974 } 975 } 976 } 977 978 protected final void logRollAndSetupWalProps(Path oldPath, Path newPath, long oldFileLen) { 979 int oldNumEntries = this.numEntries.getAndSet(0); 980 String newPathString = newPath != null ? CommonFSUtils.getPath(newPath) : null; 981 if (oldPath != null) { 982 this.walFile2Props.put(oldPath, 983 new WALProps(this.sequenceIdAccounting.resetHighest(), oldFileLen)); 984 this.totalLogSize.addAndGet(oldFileLen); 985 LOG.info("Rolled WAL {} with entries={}, filesize={}; new WAL {}", 986 CommonFSUtils.getPath(oldPath), oldNumEntries, StringUtils.byteDesc(oldFileLen), 987 newPathString); 988 } else { 989 LOG.info("New WAL {}", newPathString); 990 } 991 } 992 993 private Span createSpan(String name) { 994 return TraceUtil.createSpan(name).setAttribute(WAL_IMPL, implClassName); 995 } 996 997 /** 998 * Cleans up current writer closing it and then puts in place the passed in {@code nextWriter}. 999 * <p/> 1000 * <ul> 1001 * <li>In the case of creating a new WAL, oldPath will be null.</li> 1002 * <li>In the case of rolling over from one file to the next, none of the parameters will be null. 1003 * </li> 1004 * <li>In the case of closing out this FSHLog with no further use newPath and nextWriter will be 1005 * null.</li> 1006 * </ul> 1007 * @param oldPath may be null 1008 * @param newPath may be null 1009 * @param nextWriter may be null 1010 * @return the passed in <code>newPath</code> 1011 * @throws IOException if there is a problem flushing or closing the underlying FS 1012 */ 1013 Path replaceWriter(Path oldPath, Path newPath, W nextWriter) throws IOException { 1014 return TraceUtil.trace(() -> { 1015 doReplaceWriter(oldPath, newPath, nextWriter); 1016 return newPath; 1017 }, () -> createSpan("WAL.replaceWriter")); 1018 } 1019 1020 protected final void blockOnSync(SyncFuture syncFuture) throws IOException { 1021 // Now we have published the ringbuffer, halt the current thread until we get an answer back. 1022 try { 1023 if (syncFuture != null) { 1024 if (closed) { 1025 throw new IOException("WAL has been closed"); 1026 } else { 1027 syncFuture.get(walSyncTimeoutNs); 1028 } 1029 } 1030 } catch (TimeoutIOException tioe) { 1031 throw new WALSyncTimeoutIOException(tioe); 1032 } catch (InterruptedException ie) { 1033 LOG.warn("Interrupted", ie); 1034 throw convertInterruptedExceptionToIOException(ie); 1035 } catch (ExecutionException e) { 1036 throw ensureIOException(e.getCause()); 1037 } 1038 } 1039 1040 private static IOException ensureIOException(final Throwable t) { 1041 return (t instanceof IOException) ? (IOException) t : new IOException(t); 1042 } 1043 1044 private IOException convertInterruptedExceptionToIOException(final InterruptedException ie) { 1045 Thread.currentThread().interrupt(); 1046 IOException ioe = new InterruptedIOException(); 1047 ioe.initCause(ie); 1048 return ioe; 1049 } 1050 1051 private W createCombinedWriter(W localWriter, Path localPath) 1052 throws IOException, CommonFSUtils.StreamLacksCapabilityException { 1053 // retry forever if we can not create the remote writer to prevent aborting the RS due to log 1054 // rolling error, unless the skipRemoteWal is set to true. 1055 // TODO: since for now we only have one thread doing log rolling, this may block the rolling for 1056 // other wals 1057 Path remoteWAL = new Path(remoteWALDir, localPath.getName()); 1058 for (int retry = 0;; retry++) { 1059 if (skipRemoteWAL) { 1060 return localWriter; 1061 } 1062 W remoteWriter; 1063 try { 1064 remoteWriter = createWriterInstance(remoteFs, remoteWAL); 1065 } catch (IOException e) { 1066 LOG.warn("create remote writer {} failed, retry = {}", remoteWAL, retry, e); 1067 try { 1068 Thread.sleep(ConnectionUtils.getPauseTime(100, retry)); 1069 } catch (InterruptedException ie) { 1070 // restore the interrupt state 1071 Thread.currentThread().interrupt(); 1072 // must close local writer here otherwise no one will close it for us 1073 Closeables.close(localWriter, true); 1074 throw (IOException) new InterruptedIOException().initCause(ie); 1075 } 1076 continue; 1077 } 1078 return createCombinedWriter(localWriter, remoteWriter); 1079 } 1080 } 1081 1082 private Map<byte[], List<byte[]>> rollWriterInternal(boolean force) throws IOException { 1083 rollWriterLock.lock(); 1084 try { 1085 if (this.closed) { 1086 throw new WALClosedException("WAL has been closed"); 1087 } 1088 // Return if nothing to flush. 1089 if (!force && this.writer != null && this.numEntries.get() <= 0) { 1090 return null; 1091 } 1092 Map<byte[], List<byte[]>> regionsToFlush = null; 1093 try { 1094 Path oldPath = getOldPath(); 1095 Path newPath = getNewPath(); 1096 // Any exception from here on is catastrophic, non-recoverable, so we currently abort. 1097 W nextWriter = this.createWriterInstance(fs, newPath); 1098 if (remoteFs != null) { 1099 // create a remote wal if necessary 1100 nextWriter = createCombinedWriter(nextWriter, newPath); 1101 } 1102 tellListenersAboutPreLogRoll(oldPath, newPath); 1103 // NewPath could be equal to oldPath if replaceWriter fails. 1104 newPath = replaceWriter(oldPath, newPath, nextWriter); 1105 tellListenersAboutPostLogRoll(oldPath, newPath); 1106 if (LOG.isDebugEnabled()) { 1107 LOG.debug("Create new " + implClassName + " writer with pipeline: " 1108 + FanOutOneBlockAsyncDFSOutputHelper 1109 .getDataNodeInfo(Arrays.stream(getPipeline()).collect(Collectors.toList()))); 1110 } 1111 // We got a new writer, so reset the slow sync count 1112 lastTimeCheckSlowSync = EnvironmentEdgeManager.currentTime(); 1113 slowSyncCount.set(0); 1114 // Can we delete any of the old log files? 1115 if (getNumRolledLogFiles() > 0) { 1116 cleanOldLogs(); 1117 regionsToFlush = findRegionsToForceFlush(); 1118 } 1119 } catch (CommonFSUtils.StreamLacksCapabilityException exception) { 1120 // If the underlying FileSystem can't do what we ask, treat as IO failure, so 1121 // we'll abort. 1122 throw new IOException( 1123 "Underlying FileSystem can't meet stream requirements. See RS log " + "for details.", 1124 exception); 1125 } 1126 return regionsToFlush; 1127 } finally { 1128 rollWriterLock.unlock(); 1129 } 1130 } 1131 1132 @Override 1133 public Map<byte[], List<byte[]>> rollWriter(boolean force) throws IOException { 1134 return TraceUtil.trace(() -> rollWriterInternal(force), () -> createSpan("WAL.rollWriter")); 1135 } 1136 1137 // public only until class moves to o.a.h.h.wal 1138 /** Returns the size of log files in use */ 1139 public long getLogFileSize() { 1140 return this.totalLogSize.get(); 1141 } 1142 1143 // public only until class moves to o.a.h.h.wal 1144 public void requestLogRoll() { 1145 requestLogRoll(ERROR); 1146 } 1147 1148 /** 1149 * Get the backing files associated with this WAL. 1150 * @return may be null if there are no files. 1151 */ 1152 FileStatus[] getFiles() throws IOException { 1153 return CommonFSUtils.listStatus(fs, walDir, ourFiles); 1154 } 1155 1156 @Override 1157 public void shutdown() throws IOException { 1158 if (!shutdown.compareAndSet(false, true)) { 1159 return; 1160 } 1161 closed = true; 1162 // Tell our listeners that the log is closing 1163 if (!this.listeners.isEmpty()) { 1164 for (WALActionsListener i : this.listeners) { 1165 i.logCloseRequested(); 1166 } 1167 } 1168 1169 ExecutorService shutdownExecutor = Executors.newSingleThreadExecutor( 1170 new ThreadFactoryBuilder().setDaemon(true).setNameFormat("WAL-Shutdown-%d").build()); 1171 1172 Future<Void> future = shutdownExecutor.submit(new Callable<Void>() { 1173 @Override 1174 public Void call() throws Exception { 1175 if (rollWriterLock.tryLock(walShutdownTimeout, TimeUnit.SECONDS)) { 1176 try { 1177 doShutdown(); 1178 if (syncFutureCache != null) { 1179 syncFutureCache.clear(); 1180 } 1181 } finally { 1182 rollWriterLock.unlock(); 1183 } 1184 } else { 1185 throw new IOException("Waiting for rollWriterLock timeout"); 1186 } 1187 return null; 1188 } 1189 }); 1190 shutdownExecutor.shutdown(); 1191 1192 try { 1193 future.get(walShutdownTimeout, TimeUnit.MILLISECONDS); 1194 } catch (InterruptedException e) { 1195 throw new InterruptedIOException("Interrupted when waiting for shutdown WAL"); 1196 } catch (TimeoutException e) { 1197 throw new TimeoutIOException("We have waited " + walShutdownTimeout + "ms, but" 1198 + " the shutdown of WAL doesn't complete! Please check the status of underlying " 1199 + "filesystem or increase the wait time by the config \"" + WAL_SHUTDOWN_WAIT_TIMEOUT_MS 1200 + "\"", e); 1201 } catch (ExecutionException e) { 1202 if (e.getCause() instanceof IOException) { 1203 throw (IOException) e.getCause(); 1204 } else { 1205 throw new IOException(e.getCause()); 1206 } 1207 } finally { 1208 // in shutdown, we may call cleanOldLogs so shutdown this executor in the end. 1209 // In sync replication implementation, we may shut down a WAL without shutting down the whole 1210 // region server, if we shut down this executor earlier we may get reject execution exception 1211 // and abort the region server 1212 logArchiveExecutor.shutdown(); 1213 } 1214 // we also need to wait logArchive to finish if we want to a graceful shutdown as we may still 1215 // have some pending archiving tasks not finished yet, and in close we may archive all the 1216 // remaining WAL files, there could be race if we do not wait for the background archive task 1217 // finish 1218 try { 1219 if (!logArchiveExecutor.awaitTermination(walShutdownTimeout, TimeUnit.MILLISECONDS)) { 1220 throw new TimeoutIOException("We have waited " + walShutdownTimeout + "ms, but" 1221 + " the shutdown of WAL doesn't complete! Please check the status of underlying " 1222 + "filesystem or increase the wait time by the config \"" + WAL_SHUTDOWN_WAIT_TIMEOUT_MS 1223 + "\""); 1224 } 1225 } catch (InterruptedException e) { 1226 throw new InterruptedIOException("Interrupted when waiting for shutdown WAL"); 1227 } 1228 } 1229 1230 @Override 1231 public void close() throws IOException { 1232 shutdown(); 1233 final FileStatus[] files = getFiles(); 1234 if (null != files && 0 != files.length) { 1235 for (FileStatus file : files) { 1236 Path p = getWALArchivePath(this.walArchiveDir, file.getPath()); 1237 // Tell our listeners that a log is going to be archived. 1238 if (!this.listeners.isEmpty()) { 1239 for (WALActionsListener i : this.listeners) { 1240 i.preLogArchive(file.getPath(), p); 1241 } 1242 } 1243 1244 if (!CommonFSUtils.renameAndSetModifyTime(fs, file.getPath(), p)) { 1245 throw new IOException("Unable to rename " + file.getPath() + " to " + p); 1246 } 1247 // Tell our listeners that a log was archived. 1248 if (!this.listeners.isEmpty()) { 1249 for (WALActionsListener i : this.listeners) { 1250 i.postLogArchive(file.getPath(), p); 1251 } 1252 } 1253 } 1254 LOG.debug( 1255 "Moved " + files.length + " WAL file(s) to " + CommonFSUtils.getPath(this.walArchiveDir)); 1256 } 1257 LOG.info("Closed WAL: " + toString()); 1258 } 1259 1260 /** Returns number of WALs currently in the process of closing. */ 1261 public int getInflightWALCloseCount() { 1262 return inflightWALClosures.size(); 1263 } 1264 1265 /** 1266 * updates the sequence number of a specific store. depending on the flag: replaces current seq 1267 * number if the given seq id is bigger, or even if it is lower than existing one 1268 */ 1269 @Override 1270 public void updateStore(byte[] encodedRegionName, byte[] familyName, Long sequenceid, 1271 boolean onlyIfGreater) { 1272 sequenceIdAccounting.updateStore(encodedRegionName, familyName, sequenceid, onlyIfGreater); 1273 } 1274 1275 protected final SyncFuture getSyncFuture(long sequence, boolean forceSync) { 1276 return syncFutureCache.getIfPresentOrNew().reset(sequence, forceSync); 1277 } 1278 1279 protected boolean isLogRollRequested() { 1280 return rollRequested.get(); 1281 } 1282 1283 protected final void requestLogRoll(final WALActionsListener.RollRequestReason reason) { 1284 // If we have already requested a roll, don't do it again 1285 // And only set rollRequested to true when there is a registered listener 1286 if (!this.listeners.isEmpty() && rollRequested.compareAndSet(false, true)) { 1287 for (WALActionsListener i : this.listeners) { 1288 i.logRollRequested(reason); 1289 } 1290 } 1291 } 1292 1293 long getUnflushedEntriesCount() { 1294 long highestSynced = this.highestSyncedTxid.get(); 1295 long highestUnsynced = this.highestUnsyncedTxid; 1296 return highestSynced >= highestUnsynced ? 0 : highestUnsynced - highestSynced; 1297 } 1298 1299 boolean isUnflushedEntries() { 1300 return getUnflushedEntriesCount() > 0; 1301 } 1302 1303 /** 1304 * Exposed for testing only. Use to tricks like halt the ring buffer appending. 1305 */ 1306 protected void atHeadOfRingBufferEventHandlerAppend() { 1307 // Noop 1308 } 1309 1310 protected final boolean appendEntry(W writer, FSWALEntry entry) throws IOException { 1311 // TODO: WORK ON MAKING THIS APPEND FASTER. DOING WAY TOO MUCH WORK WITH CPs, PBing, etc. 1312 atHeadOfRingBufferEventHandlerAppend(); 1313 long start = EnvironmentEdgeManager.currentTime(); 1314 byte[] encodedRegionName = entry.getKey().getEncodedRegionName(); 1315 long regionSequenceId = entry.getKey().getSequenceId(); 1316 1317 // Edits are empty, there is nothing to append. Maybe empty when we are looking for a 1318 // region sequence id only, a region edit/sequence id that is not associated with an actual 1319 // edit. It has to go through all the rigmarole to be sure we have the right ordering. 1320 if (entry.getEdit().isEmpty()) { 1321 return false; 1322 } 1323 1324 // Coprocessor hook. 1325 coprocessorHost.preWALWrite(entry.getRegionInfo(), entry.getKey(), entry.getEdit()); 1326 if (!listeners.isEmpty()) { 1327 for (WALActionsListener i : listeners) { 1328 i.visitLogEntryBeforeWrite(entry.getRegionInfo(), entry.getKey(), entry.getEdit()); 1329 } 1330 } 1331 doAppend(writer, entry); 1332 assert highestUnsyncedTxid < entry.getTxid(); 1333 highestUnsyncedTxid = entry.getTxid(); 1334 if (entry.isCloseRegion()) { 1335 // let's clean all the records of this region 1336 sequenceIdAccounting.onRegionClose(encodedRegionName); 1337 } else { 1338 sequenceIdAccounting.update(encodedRegionName, entry.getFamilyNames(), regionSequenceId, 1339 entry.isInMemStore()); 1340 } 1341 coprocessorHost.postWALWrite(entry.getRegionInfo(), entry.getKey(), entry.getEdit()); 1342 // Update metrics. 1343 postAppend(entry, EnvironmentEdgeManager.currentTime() - start); 1344 numEntries.incrementAndGet(); 1345 return true; 1346 } 1347 1348 private long postAppend(final Entry e, final long elapsedTime) throws IOException { 1349 long len = 0; 1350 if (!listeners.isEmpty()) { 1351 for (Cell cell : e.getEdit().getCells()) { 1352 len += PrivateCellUtil.estimatedSerializedSizeOf(cell); 1353 } 1354 for (WALActionsListener listener : listeners) { 1355 listener.postAppend(len, elapsedTime, e.getKey(), e.getEdit()); 1356 } 1357 } 1358 return len; 1359 } 1360 1361 protected final void postSync(long timeInNanos, int handlerSyncs) { 1362 if (timeInNanos > this.slowSyncNs) { 1363 String msg = new StringBuilder().append("Slow sync cost: ") 1364 .append(TimeUnit.NANOSECONDS.toMillis(timeInNanos)).append(" ms, current pipeline: ") 1365 .append(Arrays.toString(getPipeline())).toString(); 1366 LOG.info(msg); 1367 if (timeInNanos > this.rollOnSyncNs) { 1368 // A single sync took too long. 1369 // Elsewhere in checkSlowSync, called from checkLogRoll, we will look at cumulative 1370 // effects. Here we have a single data point that indicates we should take immediate 1371 // action, so do so. 1372 LOG.warn("Requesting log roll because we exceeded slow sync threshold; time=" 1373 + TimeUnit.NANOSECONDS.toMillis(timeInNanos) + " ms, threshold=" 1374 + TimeUnit.NANOSECONDS.toMillis(rollOnSyncNs) + " ms, current pipeline: " 1375 + Arrays.toString(getPipeline())); 1376 requestLogRoll(SLOW_SYNC); 1377 } 1378 slowSyncCount.incrementAndGet(); // it's fine to unconditionally increment this 1379 } 1380 if (!listeners.isEmpty()) { 1381 for (WALActionsListener listener : listeners) { 1382 listener.postSync(timeInNanos, handlerSyncs); 1383 } 1384 } 1385 } 1386 1387 protected final long stampSequenceIdAndPublishToRingBuffer(RegionInfo hri, WALKeyImpl key, 1388 WALEdit edits, boolean inMemstore, RingBuffer<RingBufferTruck> ringBuffer) throws IOException { 1389 if (this.closed) { 1390 throw new IOException( 1391 "Cannot append; log is closed, regionName = " + hri.getRegionNameAsString()); 1392 } 1393 MutableLong txidHolder = new MutableLong(); 1394 MultiVersionConcurrencyControl.WriteEntry we = key.getMvcc().begin(() -> { 1395 txidHolder.setValue(ringBuffer.next()); 1396 }); 1397 long txid = txidHolder.longValue(); 1398 ServerCall<?> rpcCall = RpcServer.getCurrentServerCallWithCellScanner().orElse(null); 1399 try { 1400 FSWALEntry entry = new FSWALEntry(txid, key, edits, hri, inMemstore, rpcCall); 1401 entry.stampRegionSequenceId(we); 1402 ringBuffer.get(txid).load(entry); 1403 } finally { 1404 ringBuffer.publish(txid); 1405 } 1406 return txid; 1407 } 1408 1409 @Override 1410 public String toString() { 1411 return implClassName + " " + walFilePrefix + ":" + walFileSuffix + "(num " + filenum + ")"; 1412 } 1413 1414 /** 1415 * if the given {@code path} is being written currently, then return its length. 1416 * <p> 1417 * This is used by replication to prevent replicating unacked log entries. See 1418 * https://issues.apache.org/jira/browse/HBASE-14004 for more details. 1419 */ 1420 @Override 1421 public OptionalLong getLogFileSizeIfBeingWritten(Path path) { 1422 rollWriterLock.lock(); 1423 try { 1424 Path currentPath = getOldPath(); 1425 if (path.equals(currentPath)) { 1426 // Currently active path. 1427 W writer = this.writer; 1428 return writer != null ? OptionalLong.of(writer.getSyncedLength()) : OptionalLong.empty(); 1429 } else { 1430 W temp = inflightWALClosures.get(path.getName()); 1431 if (temp != null) { 1432 // In the process of being closed, trailer bytes may or may not be flushed. 1433 // Ensuring that we read all the bytes in a file is critical for correctness of tailing 1434 // use cases like replication, see HBASE-25924/HBASE-25932. 1435 return OptionalLong.of(temp.getSyncedLength()); 1436 } 1437 // Log rolled successfully. 1438 return OptionalLong.empty(); 1439 } 1440 } finally { 1441 rollWriterLock.unlock(); 1442 } 1443 } 1444 1445 @Override 1446 public long appendData(RegionInfo info, WALKeyImpl key, WALEdit edits) throws IOException { 1447 return TraceUtil.trace(() -> append(info, key, edits, true), 1448 () -> createSpan("WAL.appendData")); 1449 } 1450 1451 @Override 1452 public long appendMarker(RegionInfo info, WALKeyImpl key, WALEdit edits) throws IOException { 1453 return TraceUtil.trace(() -> append(info, key, edits, false), 1454 () -> createSpan("WAL.appendMarker")); 1455 } 1456 1457 /** 1458 * Helper that marks the future as DONE and offers it back to the cache. 1459 */ 1460 protected void markFutureDoneAndOffer(SyncFuture future, long txid, Throwable t) { 1461 future.done(txid, t); 1462 syncFutureCache.offer(future); 1463 } 1464 1465 private static boolean waitingRoll(int epochAndState) { 1466 return (epochAndState & 1) != 0; 1467 } 1468 1469 private static boolean writerBroken(int epochAndState) { 1470 return ((epochAndState >>> 1) & 1) != 0; 1471 } 1472 1473 private static int epoch(int epochAndState) { 1474 return epochAndState >>> 2; 1475 } 1476 1477 // return whether we have successfully set readyForRolling to true. 1478 private boolean trySetReadyForRolling() { 1479 // Check without holding lock first. Usually we will just return here. 1480 // waitingRoll is volatile and unacedEntries is only accessed inside event loop, so it is safe 1481 // to check them outside the consumeLock. 1482 if (!waitingRoll(epochAndState) || !unackedAppends.isEmpty()) { 1483 return false; 1484 } 1485 consumeLock.lock(); 1486 try { 1487 // 1. a roll is requested 1488 // 2. all out-going entries have been acked(we have confirmed above). 1489 if (waitingRoll(epochAndState)) { 1490 readyForRolling = true; 1491 readyForRollingCond.signalAll(); 1492 return true; 1493 } else { 1494 return false; 1495 } 1496 } finally { 1497 consumeLock.unlock(); 1498 } 1499 } 1500 1501 private void syncFailed(long epochWhenSync, Throwable error) { 1502 LOG.warn("sync failed", error); 1503 this.onException(epochWhenSync, error); 1504 } 1505 1506 private void onException(long epochWhenSync, Throwable error) { 1507 boolean shouldRequestLogRoll = true; 1508 consumeLock.lock(); 1509 try { 1510 int currentEpochAndState = epochAndState; 1511 if (epoch(currentEpochAndState) != epochWhenSync || writerBroken(currentEpochAndState)) { 1512 // this is not the previous writer which means we have already rolled the writer. 1513 // or this is still the current writer, but we have already marked it as broken and request 1514 // a roll. 1515 return; 1516 } 1517 this.epochAndState = currentEpochAndState | 0b10; 1518 if (waitingRoll(currentEpochAndState)) { 1519 readyForRolling = true; 1520 readyForRollingCond.signalAll(); 1521 // this means we have already in the middle of a rollWriter so just tell the roller thread 1522 // that you can continue without requesting an extra log roll. 1523 shouldRequestLogRoll = false; 1524 } 1525 } finally { 1526 consumeLock.unlock(); 1527 } 1528 for (Iterator<FSWALEntry> iter = unackedAppends.descendingIterator(); iter.hasNext();) { 1529 toWriteAppends.addFirst(iter.next()); 1530 } 1531 highestUnsyncedTxid = highestSyncedTxid.get(); 1532 if (shouldRequestLogRoll) { 1533 // request a roll. 1534 requestLogRoll(ERROR); 1535 } 1536 } 1537 1538 private void syncCompleted(long epochWhenSync, W writer, long processedTxid, long startTimeNs) { 1539 // Please see the last several comments on HBASE-22761, it is possible that we get a 1540 // syncCompleted which acks a previous sync request after we received a syncFailed on the same 1541 // writer. So here we will also check on the epoch and state, if the epoch has already been 1542 // changed, i.e, we have already rolled the writer, or the writer is already broken, we should 1543 // just skip here, to avoid mess up the state or accidentally release some WAL entries and 1544 // cause data corruption. 1545 // The syncCompleted call is on the critical write path, so we should try our best to make it 1546 // fast. So here we do not hold consumeLock, for increasing performance. It is safe because 1547 // there are only 3 possible situations: 1548 // 1. For normal case, the only place where we change epochAndState is when rolling the writer. 1549 // Before rolling actually happen, we will only change the state to waitingRoll which is another 1550 // bit than writerBroken, and when we actually change the epoch, we can make sure that there is 1551 // no outgoing sync request. So we will always pass the check here and there is no problem. 1552 // 2. The writer is broken, but we have not called syncFailed yet. In this case, since 1553 // syncFailed and syncCompleted are executed in the same thread, we will just face the same 1554 // situation with #1. 1555 // 3. The writer is broken, and syncFailed has been called. Then when we arrive here, there are 1556 // only 2 possible situations: 1557 // a. we arrive before we actually roll the writer, then we will find out the writer is broken 1558 // and give up. 1559 // b. we arrive after we actually roll the writer, then we will find out the epoch is changed 1560 // and give up. 1561 // For both #a and #b, we do not need to hold the consumeLock as we will always update the 1562 // epochAndState as a whole. 1563 // So in general, for all the cases above, we do not need to hold the consumeLock. 1564 int epochAndState = this.epochAndState; 1565 if (epoch(epochAndState) != epochWhenSync || writerBroken(epochAndState)) { 1566 LOG.warn("Got a sync complete call after the writer is broken, skip"); 1567 return; 1568 } 1569 1570 if (processedTxid < highestSyncedTxid.get()) { 1571 return; 1572 } 1573 highestSyncedTxid.set(processedTxid); 1574 for (Iterator<FSWALEntry> iter = unackedAppends.iterator(); iter.hasNext();) { 1575 FSWALEntry entry = iter.next(); 1576 if (entry.getTxid() <= processedTxid) { 1577 entry.release(); 1578 iter.remove(); 1579 } else { 1580 break; 1581 } 1582 } 1583 postSync(System.nanoTime() - startTimeNs, finishSync()); 1584 /** 1585 * This method is used to be compatible with the original logic of {@link FSHLog}. 1586 */ 1587 checkSlowSyncCount(); 1588 if (trySetReadyForRolling()) { 1589 // we have just finished a roll, then do not need to check for log rolling, the writer will be 1590 // closed soon. 1591 return; 1592 } 1593 // If we haven't already requested a roll, check if we have exceeded logrollsize 1594 if (!isLogRollRequested() && writer.getLength() > logrollsize) { 1595 if (LOG.isDebugEnabled()) { 1596 LOG.debug("Requesting log roll because of file size threshold; length=" + writer.getLength() 1597 + ", logrollsize=" + logrollsize); 1598 } 1599 requestLogRoll(SIZE); 1600 } 1601 } 1602 1603 // find all the sync futures between these two txids to see if we need to issue a hsync, if no 1604 // sync futures then just use the default one. 1605 private boolean isHsync(long beginTxid, long endTxid) { 1606 SortedSet<SyncFuture> futures = syncFutures.subSet(new SyncFuture().reset(beginTxid, false), 1607 new SyncFuture().reset(endTxid + 1, false)); 1608 if (futures.isEmpty()) { 1609 return useHsync; 1610 } 1611 for (SyncFuture future : futures) { 1612 if (future.isForceSync()) { 1613 return true; 1614 } 1615 } 1616 return false; 1617 } 1618 1619 private void sync(W writer) { 1620 fileLengthAtLastSync = writer.getLength(); 1621 long currentHighestProcessedAppendTxid = highestProcessedAppendTxid; 1622 boolean shouldUseHsync = 1623 isHsync(highestProcessedAppendTxidAtLastSync, currentHighestProcessedAppendTxid); 1624 highestProcessedAppendTxidAtLastSync = currentHighestProcessedAppendTxid; 1625 final long startTimeNs = System.nanoTime(); 1626 final long epoch = (long) epochAndState >>> 2L; 1627 addListener(doWriterSync(writer, shouldUseHsync, currentHighestProcessedAppendTxid), 1628 (result, error) -> { 1629 if (error != null) { 1630 syncFailed(epoch, error); 1631 } else { 1632 long syncedTxid = getSyncedTxid(currentHighestProcessedAppendTxid, result); 1633 syncCompleted(epoch, writer, syncedTxid, startTimeNs); 1634 } 1635 }, consumeExecutor); 1636 } 1637 1638 /** 1639 * This method is to adapt {@link FSHLog} and {@link AsyncFSWAL}. For {@link AsyncFSWAL}, we use 1640 * {@link AbstractFSWAL#highestProcessedAppendTxid} at the point we calling 1641 * {@link AsyncFSWAL#doWriterSync} method as successful syncedTxid. For {@link FSHLog}, because we 1642 * use multi-thread {@code SyncRunner}s, we used the result of {@link CompletableFuture} as 1643 * successful syncedTxid. 1644 */ 1645 protected long getSyncedTxid(long processedTxid, long completableFutureResult) { 1646 return processedTxid; 1647 } 1648 1649 protected abstract CompletableFuture<Long> doWriterSync(W writer, boolean shouldUseHsync, 1650 long txidWhenSyn); 1651 1652 private int finishSyncLowerThanTxid(long txid) { 1653 int finished = 0; 1654 for (Iterator<SyncFuture> iter = syncFutures.iterator(); iter.hasNext();) { 1655 SyncFuture sync = iter.next(); 1656 if (sync.getTxid() <= txid) { 1657 markFutureDoneAndOffer(sync, txid, null); 1658 iter.remove(); 1659 finished++; 1660 } else { 1661 break; 1662 } 1663 } 1664 return finished; 1665 } 1666 1667 // try advancing the highestSyncedTxid as much as possible 1668 private int finishSync() { 1669 if (unackedAppends.isEmpty()) { 1670 // All outstanding appends have been acked. 1671 if (toWriteAppends.isEmpty()) { 1672 // Also no appends that wait to be written out, then just finished all pending syncs. 1673 long maxSyncTxid = highestSyncedTxid.get(); 1674 for (SyncFuture sync : syncFutures) { 1675 maxSyncTxid = Math.max(maxSyncTxid, sync.getTxid()); 1676 markFutureDoneAndOffer(sync, maxSyncTxid, null); 1677 } 1678 highestSyncedTxid.set(maxSyncTxid); 1679 int finished = syncFutures.size(); 1680 syncFutures.clear(); 1681 return finished; 1682 } else { 1683 // There is no append between highestProcessedAppendTxid and lowestUnprocessedAppendTxid, so 1684 // if highestSyncedTxid >= highestProcessedAppendTxid, then all syncs whose txid are between 1685 // highestProcessedAppendTxid and lowestUnprocessedAppendTxid can be finished. 1686 long lowestUnprocessedAppendTxid = toWriteAppends.peek().getTxid(); 1687 assert lowestUnprocessedAppendTxid > highestProcessedAppendTxid; 1688 long doneTxid = lowestUnprocessedAppendTxid - 1; 1689 highestSyncedTxid.set(doneTxid); 1690 return finishSyncLowerThanTxid(doneTxid); 1691 } 1692 } else { 1693 // There are still unacked appends. So let's move the highestSyncedTxid to the txid of the 1694 // first unacked append minus 1. 1695 long lowestUnackedAppendTxid = unackedAppends.peek().getTxid(); 1696 long doneTxid = Math.max(lowestUnackedAppendTxid - 1, highestSyncedTxid.get()); 1697 highestSyncedTxid.set(doneTxid); 1698 return finishSyncLowerThanTxid(doneTxid); 1699 } 1700 } 1701 1702 // confirm non-empty before calling 1703 private static long getLastTxid(Deque<FSWALEntry> queue) { 1704 return queue.peekLast().getTxid(); 1705 } 1706 1707 private void appendAndSync() throws IOException { 1708 final W writer = this.writer; 1709 // maybe a sync request is not queued when we issue a sync, so check here to see if we could 1710 // finish some. 1711 finishSync(); 1712 long newHighestProcessedAppendTxid = -1L; 1713 // this is used to avoid calling peedLast every time on unackedAppends, appendAndAsync is single 1714 // threaded, this could save us some cycles 1715 boolean addedToUnackedAppends = false; 1716 for (Iterator<FSWALEntry> iter = toWriteAppends.iterator(); iter.hasNext();) { 1717 FSWALEntry entry = iter.next(); 1718 /** 1719 * For {@link FSHog},here may throw IOException,but for {@link AsyncFSWAL}, here would not 1720 * throw any IOException. 1721 */ 1722 boolean appended = appendEntry(writer, entry); 1723 newHighestProcessedAppendTxid = entry.getTxid(); 1724 iter.remove(); 1725 if (appended) { 1726 // This is possible, when we fail to sync, we will add the unackedAppends back to 1727 // toWriteAppends, so here we may get an entry which is already in the unackedAppends. 1728 if ( 1729 addedToUnackedAppends || unackedAppends.isEmpty() 1730 || getLastTxid(unackedAppends) < entry.getTxid() 1731 ) { 1732 unackedAppends.addLast(entry); 1733 addedToUnackedAppends = true; 1734 } 1735 // See HBASE-25905, here we need to make sure that, we will always write all the entries in 1736 // unackedAppends out. As the code in the consume method will assume that, the entries in 1737 // unackedAppends have all been sent out so if there is roll request and unackedAppends is 1738 // not empty, we could just return as later there will be a syncCompleted call to clear the 1739 // unackedAppends, or a syncFailed to lead us to another state. 1740 // There could be other ways to fix, such as changing the logic in the consume method, but 1741 // it will break the assumption and then (may) lead to a big refactoring. So here let's use 1742 // this way to fix first, can optimize later. 1743 if ( 1744 writer.getLength() - fileLengthAtLastSync >= batchSize 1745 && (addedToUnackedAppends || entry.getTxid() >= getLastTxid(unackedAppends)) 1746 ) { 1747 break; 1748 } 1749 } 1750 } 1751 // if we have a newer transaction id, update it. 1752 // otherwise, use the previous transaction id. 1753 if (newHighestProcessedAppendTxid > 0) { 1754 highestProcessedAppendTxid = newHighestProcessedAppendTxid; 1755 } else { 1756 newHighestProcessedAppendTxid = highestProcessedAppendTxid; 1757 } 1758 1759 if (writer.getLength() - fileLengthAtLastSync >= batchSize) { 1760 // sync because buffer size limit. 1761 sync(writer); 1762 return; 1763 } 1764 if (writer.getLength() == fileLengthAtLastSync) { 1765 // we haven't written anything out, just advance the highestSyncedSequence since we may only 1766 // stamp some region sequence id. 1767 if (unackedAppends.isEmpty()) { 1768 highestSyncedTxid.set(highestProcessedAppendTxid); 1769 finishSync(); 1770 trySetReadyForRolling(); 1771 } 1772 return; 1773 } 1774 // reach here means that we have some unsynced data but haven't reached the batch size yet, 1775 // but we will not issue a sync directly here even if there are sync requests because we may 1776 // have some new data in the ringbuffer, so let's just return here and delay the decision of 1777 // whether to issue a sync in the caller method. 1778 } 1779 1780 private void consume() { 1781 consumeLock.lock(); 1782 try { 1783 int currentEpochAndState = epochAndState; 1784 if (writerBroken(currentEpochAndState)) { 1785 return; 1786 } 1787 if (waitingRoll(currentEpochAndState)) { 1788 if (writer.getLength() > fileLengthAtLastSync) { 1789 // issue a sync 1790 sync(writer); 1791 } else { 1792 if (unackedAppends.isEmpty()) { 1793 readyForRolling = true; 1794 readyForRollingCond.signalAll(); 1795 } 1796 } 1797 return; 1798 } 1799 } finally { 1800 consumeLock.unlock(); 1801 } 1802 long nextCursor = waitingConsumePayloadsGatingSequence.get() + 1; 1803 for (long cursorBound = waitingConsumePayloads.getCursor(); nextCursor 1804 <= cursorBound; nextCursor++) { 1805 if (!waitingConsumePayloads.isPublished(nextCursor)) { 1806 break; 1807 } 1808 RingBufferTruck truck = waitingConsumePayloads.get(nextCursor); 1809 switch (truck.type()) { 1810 case APPEND: 1811 toWriteAppends.addLast(truck.unloadAppend()); 1812 break; 1813 case SYNC: 1814 syncFutures.add(truck.unloadSync()); 1815 break; 1816 default: 1817 LOG.warn("RingBufferTruck with unexpected type: " + truck.type()); 1818 break; 1819 } 1820 waitingConsumePayloadsGatingSequence.set(nextCursor); 1821 } 1822 1823 /** 1824 * This method is used to be compatible with the original logic of {@link AsyncFSWAL}. 1825 */ 1826 if (markerEditOnly) { 1827 drainNonMarkerEditsAndFailSyncs(); 1828 } 1829 try { 1830 appendAndSync(); 1831 } catch (IOException exception) { 1832 /** 1833 * For {@link FSHog},here may catch IOException,but for {@link AsyncFSWAL}, the code doesn't 1834 * go in here. 1835 */ 1836 LOG.error("appendAndSync throws IOException.", exception); 1837 onAppendEntryFailed(exception); 1838 return; 1839 } 1840 if (hasConsumerTask.get()) { 1841 return; 1842 } 1843 if (toWriteAppends.isEmpty()) { 1844 if (waitingConsumePayloadsGatingSequence.get() == waitingConsumePayloads.getCursor()) { 1845 consumerScheduled.set(false); 1846 // recheck here since in append and sync we do not hold the consumeLock. Thing may 1847 // happen like 1848 // 1. we check cursor, no new entry 1849 // 2. someone publishes a new entry to ringbuffer and the consumerScheduled is true and 1850 // give up scheduling the consumer task. 1851 // 3. we set consumerScheduled to false and also give up scheduling consumer task. 1852 if (waitingConsumePayloadsGatingSequence.get() == waitingConsumePayloads.getCursor()) { 1853 // we will give up consuming so if there are some unsynced data we need to issue a sync. 1854 if ( 1855 writer.getLength() > fileLengthAtLastSync && !syncFutures.isEmpty() 1856 && syncFutures.last().getTxid() > highestProcessedAppendTxidAtLastSync 1857 ) { 1858 // no new data in the ringbuffer and we have at least one sync request 1859 sync(writer); 1860 } 1861 return; 1862 } else { 1863 // maybe someone has grabbed this before us 1864 if (!consumerScheduled.compareAndSet(false, true)) { 1865 return; 1866 } 1867 } 1868 } 1869 } 1870 // reschedule if we still have something to write. 1871 consumeExecutor.execute(consumer); 1872 } 1873 1874 private boolean shouldScheduleConsumer() { 1875 int currentEpochAndState = epochAndState; 1876 if (writerBroken(currentEpochAndState) || waitingRoll(currentEpochAndState)) { 1877 return false; 1878 } 1879 return consumerScheduled.compareAndSet(false, true); 1880 } 1881 1882 /** 1883 * Append a set of edits to the WAL. 1884 * <p/> 1885 * The WAL is not flushed/sync'd after this transaction completes BUT on return this edit must 1886 * have its region edit/sequence id assigned else it messes up our unification of mvcc and 1887 * sequenceid. On return <code>key</code> will have the region edit/sequence id filled in. 1888 * <p/> 1889 * NOTE: This appends, at a time that is usually after this call returns, starts a mvcc 1890 * transaction by calling 'begin' wherein which we assign this update a sequenceid. At assignment 1891 * time, we stamp all the passed in Cells inside WALEdit with their sequenceId. You must 1892 * 'complete' the transaction this mvcc transaction by calling 1893 * MultiVersionConcurrencyControl#complete(...) or a variant otherwise mvcc will get stuck. Do it 1894 * in the finally of a try/finally block within which this appends lives and any subsequent 1895 * operations like sync or update of memstore, etc. Get the WriteEntry to pass mvcc out of the 1896 * passed in WALKey <code>walKey</code> parameter. Be warned that the WriteEntry is not 1897 * immediately available on return from this method. It WILL be available subsequent to a sync of 1898 * this append; otherwise, you will just have to wait on the WriteEntry to get filled in. 1899 * @param hri the regioninfo associated with append 1900 * @param key Modified by this call; we add to it this edits region edit/sequence id. 1901 * @param edits Edits to append. MAY CONTAIN NO EDITS for case where we want to get an edit 1902 * sequence id that is after all currently appended edits. 1903 * @param inMemstore Always true except for case where we are writing a region event meta marker 1904 * edit, for example, a compaction completion record into the WAL or noting a 1905 * Region Open event. In these cases the entry is just so we can finish an 1906 * unfinished compaction after a crash when the new Server reads the WAL on 1907 * recovery, etc. These transition event 'Markers' do not go via the memstore. 1908 * When memstore is false, we presume a Marker event edit. 1909 * @return Returns a 'transaction id' and <code>key</code> will have the region edit/sequence id 1910 * in it. 1911 */ 1912 protected long append(RegionInfo hri, WALKeyImpl key, WALEdit edits, boolean inMemstore) 1913 throws IOException { 1914 if (markerEditOnly && !edits.isMetaEdit()) { 1915 throw new IOException("WAL is closing, only marker edit is allowed"); 1916 } 1917 long txid = 1918 stampSequenceIdAndPublishToRingBuffer(hri, key, edits, inMemstore, waitingConsumePayloads); 1919 if (shouldScheduleConsumer()) { 1920 consumeExecutor.execute(consumer); 1921 } 1922 return txid; 1923 } 1924 1925 protected void doSync(boolean forceSync) throws IOException { 1926 long txid = waitingConsumePayloads.next(); 1927 SyncFuture future; 1928 try { 1929 future = getSyncFuture(txid, forceSync); 1930 RingBufferTruck truck = waitingConsumePayloads.get(txid); 1931 truck.load(future); 1932 } finally { 1933 waitingConsumePayloads.publish(txid); 1934 } 1935 if (shouldScheduleConsumer()) { 1936 consumeExecutor.execute(consumer); 1937 } 1938 blockOnSync(future); 1939 } 1940 1941 protected void doSync(long txid, boolean forceSync) throws IOException { 1942 if (highestSyncedTxid.get() >= txid) { 1943 return; 1944 } 1945 // here we do not use ring buffer sequence as txid 1946 long sequence = waitingConsumePayloads.next(); 1947 SyncFuture future; 1948 try { 1949 future = getSyncFuture(txid, forceSync); 1950 RingBufferTruck truck = waitingConsumePayloads.get(sequence); 1951 truck.load(future); 1952 } finally { 1953 waitingConsumePayloads.publish(sequence); 1954 } 1955 if (shouldScheduleConsumer()) { 1956 consumeExecutor.execute(consumer); 1957 } 1958 blockOnSync(future); 1959 } 1960 1961 private void drainNonMarkerEditsAndFailSyncs() { 1962 if (toWriteAppends.isEmpty()) { 1963 return; 1964 } 1965 boolean hasNonMarkerEdits = false; 1966 Iterator<FSWALEntry> iter = toWriteAppends.descendingIterator(); 1967 while (iter.hasNext()) { 1968 FSWALEntry entry = iter.next(); 1969 if (!entry.getEdit().isMetaEdit()) { 1970 entry.release(); 1971 hasNonMarkerEdits = true; 1972 break; 1973 } 1974 } 1975 if (hasNonMarkerEdits) { 1976 for (;;) { 1977 iter.remove(); 1978 if (!iter.hasNext()) { 1979 break; 1980 } 1981 iter.next().release(); 1982 } 1983 for (FSWALEntry entry : unackedAppends) { 1984 entry.release(); 1985 } 1986 unackedAppends.clear(); 1987 // fail the sync futures which are under the txid of the first remaining edit, if none, fail 1988 // all the sync futures. 1989 long txid = toWriteAppends.isEmpty() ? Long.MAX_VALUE : toWriteAppends.peek().getTxid(); 1990 IOException error = new IOException("WAL is closing, only marker edit is allowed"); 1991 for (Iterator<SyncFuture> syncIter = syncFutures.iterator(); syncIter.hasNext();) { 1992 SyncFuture future = syncIter.next(); 1993 if (future.getTxid() < txid) { 1994 markFutureDoneAndOffer(future, future.getTxid(), error); 1995 syncIter.remove(); 1996 } else { 1997 break; 1998 } 1999 } 2000 } 2001 } 2002 2003 protected abstract W createWriterInstance(FileSystem fs, Path path) 2004 throws IOException, CommonFSUtils.StreamLacksCapabilityException; 2005 2006 protected abstract W createCombinedWriter(W localWriter, W remoteWriter); 2007 2008 protected final void waitForSafePoint() { 2009 consumeLock.lock(); 2010 try { 2011 int currentEpochAndState = epochAndState; 2012 if (writerBroken(currentEpochAndState) || this.writer == null) { 2013 return; 2014 } 2015 consumerScheduled.set(true); 2016 epochAndState = currentEpochAndState | 1; 2017 readyForRolling = false; 2018 consumeExecutor.execute(consumer); 2019 while (!readyForRolling) { 2020 readyForRollingCond.awaitUninterruptibly(); 2021 } 2022 } finally { 2023 consumeLock.unlock(); 2024 } 2025 } 2026 2027 private void recoverLease(FileSystem fs, Path p, Configuration conf) { 2028 try { 2029 RecoverLeaseFSUtils.recoverFileLease(fs, p, conf, null); 2030 } catch (IOException ex) { 2031 LOG.error("Unable to recover lease after several attempts. Give up.", ex); 2032 } 2033 } 2034 2035 protected final void closeWriter(W writer, Path path) { 2036 inflightWALClosures.put(path.getName(), writer); 2037 closeExecutor.execute(() -> { 2038 try { 2039 writer.close(); 2040 } catch (IOException e) { 2041 LOG.warn("close old writer failed.", e); 2042 recoverLease(this.fs, path, conf); 2043 } finally { 2044 // call this even if the above close fails, as there is no other chance we can set closed to 2045 // true, it will not cause big problems. 2046 markClosedAndClean(path); 2047 inflightWALClosures.remove(path.getName()); 2048 } 2049 }); 2050 } 2051 2052 /** 2053 * Notice that you need to clear the {@link #rollRequested} flag in this method, as the new writer 2054 * will begin to work before returning from this method. If we clear the flag after returning from 2055 * this call, we may miss a roll request. The implementation class should choose a proper place to 2056 * clear the {@link #rollRequested} flag, so we do not miss a roll request, typically before you 2057 * start writing to the new writer. 2058 */ 2059 protected void doReplaceWriter(Path oldPath, Path newPath, W nextWriter) throws IOException { 2060 Preconditions.checkNotNull(nextWriter); 2061 waitForSafePoint(); 2062 /** 2063 * For {@link FSHLog},here would shut down {@link FSHLog.SyncRunner}. 2064 */ 2065 doCleanUpResources(); 2066 // we will call rollWriter in init method, where we want to create the first writer and 2067 // obviously the previous writer is null, so here we need this null check. And why we must call 2068 // logRollAndSetupWalProps before closeWriter is that, we will call markClosedAndClean after 2069 // closing the writer asynchronously, we need to make sure the WALProps is put into 2070 // walFile2Props before we call markClosedAndClean 2071 if (writer != null) { 2072 long oldFileLen = writer.getLength(); 2073 logRollAndSetupWalProps(oldPath, newPath, oldFileLen); 2074 closeWriter(writer, oldPath); 2075 } else { 2076 logRollAndSetupWalProps(oldPath, newPath, 0); 2077 } 2078 this.writer = nextWriter; 2079 /** 2080 * Here is used for {@link AsyncFSWAL} and {@link FSHLog} to set the under layer filesystem 2081 * output after writer is replaced. 2082 */ 2083 onWriterReplaced(nextWriter); 2084 this.fileLengthAtLastSync = nextWriter.getLength(); 2085 this.highestProcessedAppendTxidAtLastSync = 0L; 2086 consumeLock.lock(); 2087 try { 2088 consumerScheduled.set(true); 2089 int currentEpoch = epochAndState >>> 2; 2090 int nextEpoch = currentEpoch == MAX_EPOCH ? 0 : currentEpoch + 1; 2091 // set a new epoch and also clear waitingRoll and writerBroken 2092 this.epochAndState = nextEpoch << 2; 2093 // Reset rollRequested status 2094 rollRequested.set(false); 2095 consumeExecutor.execute(consumer); 2096 } finally { 2097 consumeLock.unlock(); 2098 } 2099 } 2100 2101 protected abstract void onWriterReplaced(W nextWriter); 2102 2103 protected void doShutdown() throws IOException { 2104 waitForSafePoint(); 2105 /** 2106 * For {@link FSHLog},here would shut down {@link FSHLog.SyncRunner}. 2107 */ 2108 doCleanUpResources(); 2109 if (this.writer != null) { 2110 closeWriter(this.writer, getOldPath()); 2111 this.writer = null; 2112 } 2113 closeExecutor.shutdown(); 2114 try { 2115 if (!closeExecutor.awaitTermination(waitOnShutdownInSeconds, TimeUnit.SECONDS)) { 2116 LOG.error("We have waited " + waitOnShutdownInSeconds + " seconds but" 2117 + " the close of async writer doesn't complete." 2118 + "Please check the status of underlying filesystem" 2119 + " or increase the wait time by the config \"" + this.waitOnShutdownInSecondsConfigKey 2120 + "\""); 2121 } 2122 } catch (InterruptedException e) { 2123 LOG.error("The wait for close of async writer is interrupted"); 2124 Thread.currentThread().interrupt(); 2125 } 2126 IOException error = new IOException("WAL has been closed"); 2127 long nextCursor = waitingConsumePayloadsGatingSequence.get() + 1; 2128 // drain all the pending sync requests 2129 for (long cursorBound = waitingConsumePayloads.getCursor(); nextCursor 2130 <= cursorBound; nextCursor++) { 2131 if (!waitingConsumePayloads.isPublished(nextCursor)) { 2132 break; 2133 } 2134 RingBufferTruck truck = waitingConsumePayloads.get(nextCursor); 2135 switch (truck.type()) { 2136 case SYNC: 2137 syncFutures.add(truck.unloadSync()); 2138 break; 2139 default: 2140 break; 2141 } 2142 } 2143 // and fail them 2144 syncFutures.forEach(f -> markFutureDoneAndOffer(f, f.getTxid(), error)); 2145 if (this.shouldShutDownConsumeExecutorWhenClose) { 2146 consumeExecutor.shutdown(); 2147 } 2148 } 2149 2150 protected void doCleanUpResources() { 2151 }; 2152 2153 protected abstract void doAppend(W writer, FSWALEntry entry) throws IOException; 2154 2155 /** 2156 * This method gets the pipeline for the current WAL. 2157 */ 2158 abstract DatanodeInfo[] getPipeline(); 2159 2160 /** 2161 * This method gets the datanode replication count for the current WAL. 2162 */ 2163 abstract int getLogReplication(); 2164 2165 protected abstract boolean doCheckLogLowReplication(); 2166 2167 protected boolean isWriterBroken() { 2168 return writerBroken(epochAndState); 2169 } 2170 2171 private void onAppendEntryFailed(IOException exception) { 2172 LOG.warn("append entry failed", exception); 2173 final long currentEpoch = (long) epochAndState >>> 2L; 2174 this.onException(currentEpoch, exception); 2175 } 2176 2177 protected void checkSlowSyncCount() { 2178 } 2179 2180 /** Returns true if we exceeded the slow sync roll threshold over the last check interval */ 2181 protected boolean doCheckSlowSync() { 2182 boolean result = false; 2183 long now = EnvironmentEdgeManager.currentTime(); 2184 long elapsedTime = now - lastTimeCheckSlowSync; 2185 if (elapsedTime >= slowSyncCheckInterval) { 2186 if (slowSyncCount.get() >= slowSyncRollThreshold) { 2187 if (elapsedTime >= (2 * slowSyncCheckInterval)) { 2188 // If two or more slowSyncCheckInterval have elapsed this is a corner case 2189 // where a train of slow syncs almost triggered us but then there was a long 2190 // interval from then until the one more that pushed us over. If so, we 2191 // should do nothing and let the count reset. 2192 if (LOG.isDebugEnabled()) { 2193 LOG.debug("checkSlowSync triggered but we decided to ignore it; " + "count=" 2194 + slowSyncCount.get() + ", threshold=" + slowSyncRollThreshold + ", elapsedTime=" 2195 + elapsedTime + " ms, slowSyncCheckInterval=" + slowSyncCheckInterval + " ms"); 2196 } 2197 // Fall through to count reset below 2198 } else { 2199 LOG.warn("Requesting log roll because we exceeded slow sync threshold; count=" 2200 + slowSyncCount.get() + ", threshold=" + slowSyncRollThreshold + ", current pipeline: " 2201 + Arrays.toString(getPipeline())); 2202 result = true; 2203 } 2204 } 2205 lastTimeCheckSlowSync = now; 2206 slowSyncCount.set(0); 2207 } 2208 return result; 2209 } 2210 2211 public void checkLogLowReplication(long checkInterval) { 2212 long now = EnvironmentEdgeManager.currentTime(); 2213 if (now - lastTimeCheckLowReplication < checkInterval) { 2214 return; 2215 } 2216 // Will return immediately if we are in the middle of a WAL log roll currently. 2217 if (!rollWriterLock.tryLock()) { 2218 return; 2219 } 2220 try { 2221 lastTimeCheckLowReplication = now; 2222 if (doCheckLogLowReplication()) { 2223 requestLogRoll(LOW_REPLICATION); 2224 } 2225 } finally { 2226 rollWriterLock.unlock(); 2227 } 2228 } 2229 2230 // Allow temporarily skipping the creation of remote writer. When failing to write to the remote 2231 // dfs cluster, we need to reopen the regions and switch to use the original wal writer. But we 2232 // need to write a close marker when closing a region, and if it fails, the whole rs will abort. 2233 // So here we need to skip the creation of remote writer and make it possible to write the region 2234 // close marker. 2235 // Setting markerEdit only to true is for transiting from A to S, where we need to give up writing 2236 // any pending wal entries as they will be discarded. The remote cluster will replicate the 2237 // correct data back later. We still need to allow writing marker edits such as close region event 2238 // to allow closing a region. 2239 @Override 2240 public void skipRemoteWAL(boolean markerEditOnly) { 2241 if (markerEditOnly) { 2242 this.markerEditOnly = true; 2243 } 2244 this.skipRemoteWAL = true; 2245 } 2246 2247 private static void split(final Configuration conf, final Path p) throws IOException { 2248 FileSystem fs = CommonFSUtils.getWALFileSystem(conf); 2249 if (!fs.exists(p)) { 2250 throw new FileNotFoundException(p.toString()); 2251 } 2252 if (!fs.getFileStatus(p).isDirectory()) { 2253 throw new IOException(p + " is not a directory"); 2254 } 2255 2256 final Path baseDir = CommonFSUtils.getWALRootDir(conf); 2257 Path archiveDir = new Path(baseDir, HConstants.HREGION_OLDLOGDIR_NAME); 2258 if ( 2259 conf.getBoolean(AbstractFSWALProvider.SEPARATE_OLDLOGDIR, 2260 AbstractFSWALProvider.DEFAULT_SEPARATE_OLDLOGDIR) 2261 ) { 2262 archiveDir = new Path(archiveDir, p.getName()); 2263 } 2264 WALSplitter.split(baseDir, p, archiveDir, fs, conf, WALFactory.getInstance(conf)); 2265 } 2266 2267 W getWriter() { 2268 return this.writer; 2269 } 2270 2271 private static void usage() { 2272 System.err.println("Usage: AbstractFSWAL <ARGS>"); 2273 System.err.println("Arguments:"); 2274 System.err.println(" --dump Dump textual representation of passed one or more files"); 2275 System.err.println(" For example: " 2276 + "AbstractFSWAL --dump hdfs://example.com:9000/hbase/WALs/MACHINE/LOGFILE"); 2277 System.err.println(" --split Split the passed directory of WAL logs"); 2278 System.err.println( 2279 " For example: AbstractFSWAL --split hdfs://example.com:9000/hbase/WALs/DIR"); 2280 } 2281 2282 /** 2283 * Pass one or more log file names, and it will either dump out a text version on 2284 * <code>stdout</code> or split the specified log files. 2285 */ 2286 public static void main(String[] args) throws IOException { 2287 if (args.length < 2) { 2288 usage(); 2289 System.exit(-1); 2290 } 2291 // either dump using the WALPrettyPrinter or split, depending on args 2292 if (args[0].compareTo("--dump") == 0) { 2293 WALPrettyPrinter.run(Arrays.copyOfRange(args, 1, args.length)); 2294 } else if (args[0].compareTo("--perf") == 0) { 2295 LOG.error(HBaseMarkers.FATAL, "Please use the WALPerformanceEvaluation tool instead. i.e.:"); 2296 LOG.error(HBaseMarkers.FATAL, 2297 "\thbase org.apache.hadoop.hbase.wal.WALPerformanceEvaluation --iterations " + args[1]); 2298 System.exit(-1); 2299 } else if (args[0].compareTo("--split") == 0) { 2300 Configuration conf = HBaseConfiguration.create(); 2301 for (int i = 1; i < args.length; i++) { 2302 try { 2303 Path logPath = new Path(args[i]); 2304 CommonFSUtils.setFsDefault(conf, logPath); 2305 split(conf, logPath); 2306 } catch (IOException t) { 2307 t.printStackTrace(System.err); 2308 System.exit(-1); 2309 } 2310 } 2311 } else { 2312 usage(); 2313 System.exit(-1); 2314 } 2315 } 2316}