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.wal.AbstractFSWALProvider.WAL_FILE_NAME_DELIMITER; 021import static org.apache.hbase.thirdparty.com.google.common.base.Preconditions.checkArgument; 022import static org.apache.hbase.thirdparty.com.google.common.base.Preconditions.checkNotNull; 023 024import com.lmax.disruptor.RingBuffer; 025import java.io.FileNotFoundException; 026import java.io.IOException; 027import java.io.InterruptedIOException; 028import java.lang.management.MemoryType; 029import java.net.URLEncoder; 030import java.util.ArrayList; 031import java.util.Arrays; 032import java.util.Comparator; 033import java.util.List; 034import java.util.Map; 035import java.util.OptionalLong; 036import java.util.Set; 037import java.util.concurrent.ConcurrentHashMap; 038import java.util.concurrent.ConcurrentMap; 039import java.util.concurrent.ConcurrentNavigableMap; 040import java.util.concurrent.ConcurrentSkipListMap; 041import java.util.concurrent.CopyOnWriteArrayList; 042import java.util.concurrent.ExecutionException; 043import java.util.concurrent.TimeUnit; 044import java.util.concurrent.atomic.AtomicBoolean; 045import java.util.concurrent.atomic.AtomicInteger; 046import java.util.concurrent.atomic.AtomicLong; 047import java.util.concurrent.locks.ReentrantLock; 048import org.apache.commons.lang3.mutable.MutableLong; 049import org.apache.hadoop.conf.Configuration; 050import org.apache.hadoop.fs.FileStatus; 051import org.apache.hadoop.fs.FileSystem; 052import org.apache.hadoop.fs.Path; 053import org.apache.hadoop.fs.PathFilter; 054import org.apache.hadoop.hbase.Cell; 055import org.apache.hadoop.hbase.HBaseConfiguration; 056import org.apache.hadoop.hbase.HConstants; 057import org.apache.hadoop.hbase.PrivateCellUtil; 058import org.apache.hadoop.hbase.client.RegionInfo; 059import org.apache.hadoop.hbase.exceptions.TimeoutIOException; 060import org.apache.hadoop.hbase.io.util.MemorySizeUtil; 061import org.apache.hadoop.hbase.log.HBaseMarkers; 062import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl; 063import org.apache.hadoop.hbase.trace.TraceUtil; 064import org.apache.hadoop.hbase.util.Bytes; 065import org.apache.hadoop.hbase.util.CollectionUtils; 066import org.apache.hadoop.hbase.util.CommonFSUtils; 067import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; 068import org.apache.hadoop.hbase.util.FSUtils; 069import org.apache.hadoop.hbase.util.Pair; 070import org.apache.hadoop.hbase.wal.AbstractFSWALProvider; 071import org.apache.hadoop.hbase.wal.WAL; 072import org.apache.hadoop.hbase.wal.WALEdit; 073import org.apache.hadoop.hbase.wal.WALFactory; 074import org.apache.hadoop.hbase.wal.WALKeyImpl; 075import org.apache.hadoop.hbase.wal.WALPrettyPrinter; 076import org.apache.hadoop.hbase.wal.WALProvider.WriterBase; 077import org.apache.hadoop.hbase.wal.WALSplitter; 078import org.apache.hadoop.hdfs.protocol.DatanodeInfo; 079import org.apache.hadoop.util.StringUtils; 080import org.apache.htrace.core.TraceScope; 081import org.apache.yetus.audience.InterfaceAudience; 082import org.slf4j.Logger; 083import org.slf4j.LoggerFactory; 084 085import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting; 086 087/** 088 * Implementation of {@link WAL} to go against {@link FileSystem}; i.e. keep WALs in HDFS. Only one 089 * WAL is ever being written at a time. When a WAL hits a configured maximum size, it is rolled. 090 * This is done internal to the implementation. 091 * <p> 092 * As data is flushed from the MemStore to other on-disk structures (files sorted by key, hfiles), a 093 * WAL becomes obsolete. We can let go of all the log edits/entries for a given HRegion-sequence id. 094 * A bunch of work in the below is done keeping account of these region sequence ids -- what is 095 * flushed out to hfiles, and what is yet in WAL and in memory only. 096 * <p> 097 * It is only practical to delete entire files. Thus, we delete an entire on-disk file 098 * <code>F</code> when all of the edits in <code>F</code> have a log-sequence-id that's older 099 * (smaller) than the most-recent flush. 100 * <p> 101 * To read an WAL, call 102 * {@link WALFactory#createReader(org.apache.hadoop.fs.FileSystem, org.apache.hadoop.fs.Path)}. * 103 * <h2>Failure Semantic</h2> If an exception on append or sync, roll the WAL because the current WAL 104 * is now a lame duck; any more appends or syncs will fail also with the same original exception. If 105 * we have made successful appends to the WAL and we then are unable to sync them, our current 106 * semantic is to return error to the client that the appends failed but also to abort the current 107 * context, usually the hosting server. We need to replay the WALs. <br> 108 * TODO: Change this semantic. A roll of WAL may be sufficient as long as we have flagged client 109 * that the append failed. <br> 110 * TODO: replication may pick up these last edits though they have been marked as failed append 111 * (Need to keep our own file lengths, not rely on HDFS). 112 */ 113@InterfaceAudience.Private 114public abstract class AbstractFSWAL<W extends WriterBase> implements WAL { 115 116 private static final Logger LOG = LoggerFactory.getLogger(AbstractFSWAL.class); 117 118 protected static final int DEFAULT_SLOW_SYNC_TIME_MS = 100; // in ms 119 120 private static final int DEFAULT_WAL_SYNC_TIMEOUT_MS = 5 * 60 * 1000; // in ms, 5min 121 122 /** 123 * file system instance 124 */ 125 protected final FileSystem fs; 126 127 /** 128 * WAL directory, where all WAL files would be placed. 129 */ 130 protected final Path walDir; 131 132 /** 133 * dir path where old logs are kept. 134 */ 135 protected final Path walArchiveDir; 136 137 /** 138 * Matches just those wal files that belong to this wal instance. 139 */ 140 protected final PathFilter ourFiles; 141 142 /** 143 * Prefix of a WAL file, usually the region server name it is hosted on. 144 */ 145 protected final String walFilePrefix; 146 147 /** 148 * Suffix included on generated wal file names 149 */ 150 protected final String walFileSuffix; 151 152 /** 153 * Prefix used when checking for wal membership. 154 */ 155 protected final String prefixPathStr; 156 157 protected final WALCoprocessorHost coprocessorHost; 158 159 /** 160 * conf object 161 */ 162 protected final Configuration conf; 163 164 /** Listeners that are called on WAL events. */ 165 protected final List<WALActionsListener> listeners = new CopyOnWriteArrayList<>(); 166 167 /** 168 * Class that does accounting of sequenceids in WAL subsystem. Holds oldest outstanding sequence 169 * id as yet not flushed as well as the most recent edit sequence id appended to the WAL. Has 170 * facility for answering questions such as "Is it safe to GC a WAL?". 171 */ 172 protected final SequenceIdAccounting sequenceIdAccounting = new SequenceIdAccounting(); 173 174 protected final long slowSyncNs; 175 176 private final long walSyncTimeoutNs; 177 178 // If > than this size, roll the log. 179 protected final long logrollsize; 180 181 /** 182 * Block size to use writing files. 183 */ 184 protected final long blocksize; 185 186 /* 187 * If more than this many logs, force flush of oldest region to oldest edit goes to disk. If too 188 * many and we crash, then will take forever replaying. Keep the number of logs tidy. 189 */ 190 protected final int maxLogs; 191 192 /** 193 * This lock makes sure only one log roll runs at a time. Should not be taken while any other lock 194 * is held. We don't just use synchronized because that results in bogus and tedious findbugs 195 * warning when it thinks synchronized controls writer thread safety. It is held when we are 196 * actually rolling the log. It is checked when we are looking to see if we should roll the log or 197 * not. 198 */ 199 protected final ReentrantLock rollWriterLock = new ReentrantLock(true); 200 201 // The timestamp (in ms) when the log file was created. 202 protected final AtomicLong filenum = new AtomicLong(-1); 203 204 // Number of transactions in the current Wal. 205 protected final AtomicInteger numEntries = new AtomicInteger(0); 206 207 /** 208 * The highest known outstanding unsync'd WALEdit transaction id. Usually, we use a queue to pass 209 * WALEdit to background consumer thread, and the transaction id is the sequence number of the 210 * corresponding entry in queue. 211 */ 212 protected volatile long highestUnsyncedTxid = -1; 213 214 /** 215 * Updated to the transaction id of the last successful sync call. This can be less than 216 * {@link #highestUnsyncedTxid} for case where we have an append where a sync has not yet come in 217 * for it. 218 */ 219 protected final AtomicLong highestSyncedTxid = new AtomicLong(0); 220 221 /** 222 * The total size of wal 223 */ 224 protected final AtomicLong totalLogSize = new AtomicLong(0); 225 /** 226 * Current log file. 227 */ 228 volatile W writer; 229 230 // Last time to check low replication on hlog's pipeline 231 private long lastTimeCheckLowReplication = EnvironmentEdgeManager.currentTime(); 232 233 protected volatile boolean closed = false; 234 235 protected final AtomicBoolean shutdown = new AtomicBoolean(false); 236 /** 237 * WAL Comparator; it compares the timestamp (log filenum), present in the log file name. Throws 238 * an IllegalArgumentException if used to compare paths from different wals. 239 */ 240 final Comparator<Path> LOG_NAME_COMPARATOR = 241 (o1, o2) -> Long.compare(getFileNumFromFileName(o1), getFileNumFromFileName(o2)); 242 243 private static final class WalProps { 244 245 /** 246 * Map the encoded region name to the highest sequence id. Contain all the regions it has 247 * entries of 248 */ 249 public final Map<byte[], Long> encodedName2HighestSequenceId; 250 251 /** 252 * The log file size. Notice that the size may not be accurate if we do asynchronous close in 253 * sub classes. 254 */ 255 public final long logSize; 256 257 public WalProps(Map<byte[], Long> encodedName2HighestSequenceId, long logSize) { 258 this.encodedName2HighestSequenceId = encodedName2HighestSequenceId; 259 this.logSize = logSize; 260 } 261 } 262 263 /** 264 * Map of WAL log file to properties. The map is sorted by the log file creation timestamp 265 * (contained in the log file name). 266 */ 267 protected ConcurrentNavigableMap<Path, WalProps> walFile2Props = 268 new ConcurrentSkipListMap<>(LOG_NAME_COMPARATOR); 269 270 /** 271 * Map of {@link SyncFuture}s keyed by Handler objects. Used so we reuse SyncFutures. 272 * <p> 273 * TODO: Reuse FSWALEntry's rather than create them anew each time as we do SyncFutures here. 274 * <p> 275 * TODO: Add a FSWalEntry and SyncFuture as thread locals on handlers rather than have them get 276 * them from this Map? 277 */ 278 private final ConcurrentMap<Thread, SyncFuture> syncFuturesByHandler; 279 280 /** 281 * The class name of the runtime implementation, used as prefix for logging/tracing. 282 * <p> 283 * Performance testing shows getClass().getSimpleName() might be a bottleneck so we store it here, 284 * refer to HBASE-17676 for more details 285 * </p> 286 */ 287 protected final String implClassName; 288 289 public long getFilenum() { 290 return this.filenum.get(); 291 } 292 293 /** 294 * A log file has a creation timestamp (in ms) in its file name ({@link #filenum}. This helper 295 * method returns the creation timestamp from a given log file. It extracts the timestamp assuming 296 * the filename is created with the {@link #computeFilename(long filenum)} method. 297 * @return timestamp, as in the log file name. 298 */ 299 protected long getFileNumFromFileName(Path fileName) { 300 checkNotNull(fileName, "file name can't be null"); 301 if (!ourFiles.accept(fileName)) { 302 throw new IllegalArgumentException( 303 "The log file " + fileName + " doesn't belong to this WAL. (" + toString() + ")"); 304 } 305 final String fileNameString = fileName.toString(); 306 String chompedPath = fileNameString.substring(prefixPathStr.length(), 307 (fileNameString.length() - walFileSuffix.length())); 308 return Long.parseLong(chompedPath); 309 } 310 311 private int calculateMaxLogFiles(Configuration conf, long logRollSize) { 312 Pair<Long, MemoryType> globalMemstoreSize = MemorySizeUtil.getGlobalMemStoreSize(conf); 313 return (int) ((globalMemstoreSize.getFirst() * 2) / logRollSize); 314 } 315 316 // must be power of 2 317 protected final int getPreallocatedEventCount() { 318 // Preallocate objects to use on the ring buffer. The way that appends and syncs work, we will 319 // be stuck and make no progress if the buffer is filled with appends only and there is no 320 // sync. If no sync, then the handlers will be outstanding just waiting on sync completion 321 // before they return. 322 int preallocatedEventCount = 323 this.conf.getInt("hbase.regionserver.wal.disruptor.event.count", 1024 * 16); 324 checkArgument(preallocatedEventCount >= 0, 325 "hbase.regionserver.wal.disruptor.event.count must > 0"); 326 int floor = Integer.highestOneBit(preallocatedEventCount); 327 if (floor == preallocatedEventCount) { 328 return floor; 329 } 330 // max capacity is 1 << 30 331 if (floor >= 1 << 29) { 332 return 1 << 30; 333 } 334 return floor << 1; 335 } 336 337 protected AbstractFSWAL(final FileSystem fs, final Path rootDir, final String logDir, 338 final String archiveDir, final Configuration conf, final List<WALActionsListener> listeners, 339 final boolean failIfWALExists, final String prefix, final String suffix) 340 throws FailedLogCloseException, IOException { 341 this.fs = fs; 342 this.walDir = new Path(rootDir, logDir); 343 this.walArchiveDir = new Path(rootDir, archiveDir); 344 this.conf = conf; 345 346 if (!fs.exists(walDir) && !fs.mkdirs(walDir)) { 347 throw new IOException("Unable to mkdir " + walDir); 348 } 349 350 if (!fs.exists(this.walArchiveDir)) { 351 if (!fs.mkdirs(this.walArchiveDir)) { 352 throw new IOException("Unable to mkdir " + this.walArchiveDir); 353 } 354 } 355 356 // If prefix is null||empty then just name it wal 357 this.walFilePrefix = 358 prefix == null || prefix.isEmpty() ? "wal" : URLEncoder.encode(prefix, "UTF8"); 359 // we only correctly differentiate suffices when numeric ones start with '.' 360 if (suffix != null && !(suffix.isEmpty()) && !(suffix.startsWith(WAL_FILE_NAME_DELIMITER))) { 361 throw new IllegalArgumentException("WAL suffix must start with '" + WAL_FILE_NAME_DELIMITER + 362 "' but instead was '" + suffix + "'"); 363 } 364 // Now that it exists, set the storage policy for the entire directory of wal files related to 365 // this FSHLog instance 366 CommonFSUtils.setStoragePolicy(fs, conf, this.walDir, HConstants.WAL_STORAGE_POLICY, 367 HConstants.DEFAULT_WAL_STORAGE_POLICY); 368 this.walFileSuffix = (suffix == null) ? "" : URLEncoder.encode(suffix, "UTF8"); 369 this.prefixPathStr = new Path(walDir, walFilePrefix + WAL_FILE_NAME_DELIMITER).toString(); 370 371 this.ourFiles = new PathFilter() { 372 @Override 373 public boolean accept(final Path fileName) { 374 // The path should start with dir/<prefix> and end with our suffix 375 final String fileNameString = fileName.toString(); 376 if (!fileNameString.startsWith(prefixPathStr)) { 377 return false; 378 } 379 if (walFileSuffix.isEmpty()) { 380 // in the case of the null suffix, we need to ensure the filename ends with a timestamp. 381 return org.apache.commons.lang3.StringUtils 382 .isNumeric(fileNameString.substring(prefixPathStr.length())); 383 } else if (!fileNameString.endsWith(walFileSuffix)) { 384 return false; 385 } 386 return true; 387 } 388 }; 389 390 if (failIfWALExists) { 391 final FileStatus[] walFiles = CommonFSUtils.listStatus(fs, walDir, ourFiles); 392 if (null != walFiles && 0 != walFiles.length) { 393 throw new IOException("Target WAL already exists within directory " + walDir); 394 } 395 } 396 397 // Register listeners. TODO: Should this exist anymore? We have CPs? 398 if (listeners != null) { 399 for (WALActionsListener i : listeners) { 400 registerWALActionsListener(i); 401 } 402 } 403 this.coprocessorHost = new WALCoprocessorHost(this, conf); 404 405 // Schedule a WAL roll when the WAL is 50% of the HDFS block size. Scheduling at 50% of block 406 // size should make it so WAL rolls before we get to the end-of-block (Block transitions cost 407 // some latency). In hbase-1 we did this differently. We scheduled a roll when we hit 95% of 408 // the block size but experience from the field has it that this was not enough time for the 409 // roll to happen before end-of-block. So the new accounting makes WALs of about the same 410 // size as those made in hbase-1 (to prevent surprise), we now have default block size as 411 // 2 times the DFS default: i.e. 2 * DFS default block size rolling at 50% full will generally 412 // make similar size logs to 1 * DFS default block size rolling at 95% full. See HBASE-19148. 413 this.blocksize = WALUtil.getWALBlockSize(this.conf, this.fs, this.walDir); 414 float multiplier = conf.getFloat("hbase.regionserver.logroll.multiplier", 0.5f); 415 this.logrollsize = (long)(this.blocksize * multiplier); 416 417 boolean maxLogsDefined = conf.get("hbase.regionserver.maxlogs") != null; 418 if (maxLogsDefined) { 419 LOG.warn("'hbase.regionserver.maxlogs' was deprecated."); 420 } 421 this.maxLogs = conf.getInt("hbase.regionserver.maxlogs", 422 Math.max(32, calculateMaxLogFiles(conf, logrollsize))); 423 424 LOG.info("WAL configuration: blocksize=" + StringUtils.byteDesc(blocksize) + ", rollsize=" + 425 StringUtils.byteDesc(this.logrollsize) + ", prefix=" + this.walFilePrefix + ", suffix=" + 426 walFileSuffix + ", logDir=" + this.walDir + ", archiveDir=" + this.walArchiveDir); 427 this.slowSyncNs = TimeUnit.MILLISECONDS 428 .toNanos(conf.getInt("hbase.regionserver.hlog.slowsync.ms", DEFAULT_SLOW_SYNC_TIME_MS)); 429 this.walSyncTimeoutNs = TimeUnit.MILLISECONDS 430 .toNanos(conf.getLong("hbase.regionserver.hlog.sync.timeout", DEFAULT_WAL_SYNC_TIMEOUT_MS)); 431 int maxHandlersCount = conf.getInt(HConstants.REGION_SERVER_HANDLER_COUNT, 200); 432 // Presize our map of SyncFutures by handler objects. 433 this.syncFuturesByHandler = new ConcurrentHashMap<>(maxHandlersCount); 434 this.implClassName = getClass().getSimpleName(); 435 } 436 437 @Override 438 public void registerWALActionsListener(WALActionsListener listener) { 439 this.listeners.add(listener); 440 } 441 442 @Override 443 public boolean unregisterWALActionsListener(WALActionsListener listener) { 444 return this.listeners.remove(listener); 445 } 446 447 @Override 448 public WALCoprocessorHost getCoprocessorHost() { 449 return coprocessorHost; 450 } 451 452 @Override 453 public Long startCacheFlush(byte[] encodedRegionName, Set<byte[]> families) { 454 return this.sequenceIdAccounting.startCacheFlush(encodedRegionName, families); 455 } 456 457 @Override 458 public Long startCacheFlush(byte[] encodedRegionName, Map<byte[], Long> familyToSeq) { 459 return this.sequenceIdAccounting.startCacheFlush(encodedRegionName, familyToSeq); 460 } 461 462 @Override 463 public void completeCacheFlush(byte[] encodedRegionName) { 464 this.sequenceIdAccounting.completeCacheFlush(encodedRegionName); 465 } 466 467 @Override 468 public void abortCacheFlush(byte[] encodedRegionName) { 469 this.sequenceIdAccounting.abortCacheFlush(encodedRegionName); 470 } 471 472 @Override 473 public long getEarliestMemStoreSeqNum(byte[] encodedRegionName) { 474 // Used by tests. Deprecated as too subtle for general usage. 475 return this.sequenceIdAccounting.getLowestSequenceId(encodedRegionName); 476 } 477 478 @Override 479 public long getEarliestMemStoreSeqNum(byte[] encodedRegionName, byte[] familyName) { 480 // This method is used by tests and for figuring if we should flush or not because our 481 // sequenceids are too old. It is also used reporting the master our oldest sequenceid for use 482 // figuring what edits can be skipped during log recovery. getEarliestMemStoreSequenceId 483 // from this.sequenceIdAccounting is looking first in flushingOldestStoreSequenceIds, the 484 // currently flushing sequence ids, and if anything found there, it is returning these. This is 485 // the right thing to do for the reporting oldest sequenceids to master; we won't skip edits if 486 // we crash during the flush. For figuring what to flush, we might get requeued if our sequence 487 // id is old even though we are currently flushing. This may mean we do too much flushing. 488 return this.sequenceIdAccounting.getLowestSequenceId(encodedRegionName, familyName); 489 } 490 491 @Override 492 public byte[][] rollWriter() throws FailedLogCloseException, IOException { 493 return rollWriter(false); 494 } 495 496 /** 497 * This is a convenience method that computes a new filename with a given file-number. 498 * @param filenum to use 499 * @return Path 500 */ 501 protected Path computeFilename(final long filenum) { 502 if (filenum < 0) { 503 throw new RuntimeException("WAL file number can't be < 0"); 504 } 505 String child = walFilePrefix + WAL_FILE_NAME_DELIMITER + filenum + walFileSuffix; 506 return new Path(walDir, child); 507 } 508 509 /** 510 * This is a convenience method that computes a new filename with a given using the current WAL 511 * file-number 512 * @return Path 513 */ 514 public Path getCurrentFileName() { 515 return computeFilename(this.filenum.get()); 516 } 517 518 /** 519 * retrieve the next path to use for writing. Increments the internal filenum. 520 */ 521 private Path getNewPath() throws IOException { 522 this.filenum.set(System.currentTimeMillis()); 523 Path newPath = getCurrentFileName(); 524 while (fs.exists(newPath)) { 525 this.filenum.incrementAndGet(); 526 newPath = getCurrentFileName(); 527 } 528 return newPath; 529 } 530 531 @VisibleForTesting 532 Path getOldPath() { 533 long currentFilenum = this.filenum.get(); 534 Path oldPath = null; 535 if (currentFilenum > 0) { 536 // ComputeFilename will take care of meta wal filename 537 oldPath = computeFilename(currentFilenum); 538 } // I presume if currentFilenum is <= 0, this is first file and null for oldPath if fine? 539 return oldPath; 540 } 541 542 /** 543 * Tell listeners about pre log roll. 544 */ 545 private void tellListenersAboutPreLogRoll(final Path oldPath, final Path newPath) 546 throws IOException { 547 coprocessorHost.preWALRoll(oldPath, newPath); 548 549 if (!this.listeners.isEmpty()) { 550 for (WALActionsListener i : this.listeners) { 551 i.preLogRoll(oldPath, newPath); 552 } 553 } 554 } 555 556 /** 557 * Tell listeners about post log roll. 558 */ 559 private void tellListenersAboutPostLogRoll(final Path oldPath, final Path newPath) 560 throws IOException { 561 if (!this.listeners.isEmpty()) { 562 for (WALActionsListener i : this.listeners) { 563 i.postLogRoll(oldPath, newPath); 564 } 565 } 566 567 coprocessorHost.postWALRoll(oldPath, newPath); 568 } 569 570 // public only until class moves to o.a.h.h.wal 571 /** @return the number of rolled log files */ 572 public int getNumRolledLogFiles() { 573 return walFile2Props.size(); 574 } 575 576 // public only until class moves to o.a.h.h.wal 577 /** @return the number of log files in use */ 578 public int getNumLogFiles() { 579 // +1 for current use log 580 return getNumRolledLogFiles() + 1; 581 } 582 583 /** 584 * If the number of un-archived WAL files is greater than maximum allowed, check the first 585 * (oldest) WAL file, and returns those regions which should be flushed so that it can be 586 * archived. 587 * @return regions (encodedRegionNames) to flush in order to archive oldest WAL file. 588 */ 589 byte[][] findRegionsToForceFlush() throws IOException { 590 byte[][] regions = null; 591 int logCount = getNumRolledLogFiles(); 592 if (logCount > this.maxLogs && logCount > 0) { 593 Map.Entry<Path, WalProps> firstWALEntry = this.walFile2Props.firstEntry(); 594 regions = 595 this.sequenceIdAccounting.findLower(firstWALEntry.getValue().encodedName2HighestSequenceId); 596 } 597 if (regions != null) { 598 StringBuilder sb = new StringBuilder(); 599 for (int i = 0; i < regions.length; i++) { 600 if (i > 0) { 601 sb.append(", "); 602 } 603 sb.append(Bytes.toStringBinary(regions[i])); 604 } 605 LOG.info("Too many WALs; count=" + logCount + ", max=" + this.maxLogs + 606 "; forcing flush of " + regions.length + " regions(s): " + sb.toString()); 607 } 608 return regions; 609 } 610 611 /** 612 * Archive old logs. A WAL is eligible for archiving if all its WALEdits have been flushed. 613 */ 614 private void cleanOldLogs() throws IOException { 615 List<Pair<Path, Long>> logsToArchive = null; 616 // For each log file, look at its Map of regions to highest sequence id; if all sequence ids 617 // are older than what is currently in memory, the WAL can be GC'd. 618 for (Map.Entry<Path, WalProps> e : this.walFile2Props.entrySet()) { 619 Path log = e.getKey(); 620 Map<byte[], Long> sequenceNums = e.getValue().encodedName2HighestSequenceId; 621 if (this.sequenceIdAccounting.areAllLower(sequenceNums)) { 622 if (logsToArchive == null) { 623 logsToArchive = new ArrayList<>(); 624 } 625 logsToArchive.add(Pair.newPair(log, e.getValue().logSize)); 626 if (LOG.isTraceEnabled()) { 627 LOG.trace("WAL file ready for archiving " + log); 628 } 629 } 630 } 631 if (logsToArchive != null) { 632 for (Pair<Path, Long> logAndSize : logsToArchive) { 633 this.totalLogSize.addAndGet(-logAndSize.getSecond()); 634 archiveLogFile(logAndSize.getFirst()); 635 this.walFile2Props.remove(logAndSize.getFirst()); 636 } 637 } 638 } 639 640 /* 641 * only public so WALSplitter can use. 642 * @return archived location of a WAL file with the given path p 643 */ 644 public static Path getWALArchivePath(Path archiveDir, Path p) { 645 return new Path(archiveDir, p.getName()); 646 } 647 648 private void archiveLogFile(final Path p) throws IOException { 649 Path newPath = getWALArchivePath(this.walArchiveDir, p); 650 // Tell our listeners that a log is going to be archived. 651 if (!this.listeners.isEmpty()) { 652 for (WALActionsListener i : this.listeners) { 653 i.preLogArchive(p, newPath); 654 } 655 } 656 LOG.info("Archiving " + p + " to " + newPath); 657 if (!CommonFSUtils.renameAndSetModifyTime(this.fs, p, newPath)) { 658 throw new IOException("Unable to rename " + p + " to " + newPath); 659 } 660 // Tell our listeners that a log has been archived. 661 if (!this.listeners.isEmpty()) { 662 for (WALActionsListener i : this.listeners) { 663 i.postLogArchive(p, newPath); 664 } 665 } 666 } 667 668 protected final void logRollAndSetupWalProps(Path oldPath, Path newPath, long oldFileLen) { 669 int oldNumEntries = this.numEntries.getAndSet(0); 670 String newPathString = newPath != null ? CommonFSUtils.getPath(newPath) : null; 671 if (oldPath != null) { 672 this.walFile2Props.put(oldPath, 673 new WalProps(this.sequenceIdAccounting.resetHighest(), oldFileLen)); 674 this.totalLogSize.addAndGet(oldFileLen); 675 LOG.info("Rolled WAL {} with entries={}, filesize={}; new WAL {}", 676 CommonFSUtils.getPath(oldPath), oldNumEntries, StringUtils.byteDesc(oldFileLen), 677 newPathString); 678 } else { 679 LOG.info("New WAL {}", newPathString); 680 } 681 } 682 683 /** 684 * <p> 685 * Cleans up current writer closing it and then puts in place the passed in 686 * <code>nextWriter</code>. 687 * </p> 688 * <p> 689 * <ul> 690 * <li>In the case of creating a new WAL, oldPath will be null.</li> 691 * <li>In the case of rolling over from one file to the next, none of the parameters will be null. 692 * </li> 693 * <li>In the case of closing out this FSHLog with no further use newPath and nextWriter will be 694 * null.</li> 695 * </ul> 696 * </p> 697 * @param oldPath may be null 698 * @param newPath may be null 699 * @param nextWriter may be null 700 * @return the passed in <code>newPath</code> 701 * @throws IOException if there is a problem flushing or closing the underlying FS 702 */ 703 @VisibleForTesting 704 Path replaceWriter(Path oldPath, Path newPath, W nextWriter) throws IOException { 705 try (TraceScope scope = TraceUtil.createTrace("FSHFile.replaceWriter")) { 706 doReplaceWriter(oldPath, newPath, nextWriter); 707 return newPath; 708 } 709 } 710 711 protected final void blockOnSync(SyncFuture syncFuture) throws IOException { 712 // Now we have published the ringbuffer, halt the current thread until we get an answer back. 713 try { 714 if (syncFuture != null) { 715 if (closed) { 716 throw new IOException("WAL has been closed"); 717 } else { 718 syncFuture.get(walSyncTimeoutNs); 719 } 720 } 721 } catch (TimeoutIOException tioe) { 722 // SyncFuture reuse by thread, if TimeoutIOException happens, ringbuffer 723 // still refer to it, so if this thread use it next time may get a wrong 724 // result. 725 this.syncFuturesByHandler.remove(Thread.currentThread()); 726 throw tioe; 727 } catch (InterruptedException ie) { 728 LOG.warn("Interrupted", ie); 729 throw convertInterruptedExceptionToIOException(ie); 730 } catch (ExecutionException e) { 731 throw ensureIOException(e.getCause()); 732 } 733 } 734 735 private static IOException ensureIOException(final Throwable t) { 736 return (t instanceof IOException) ? (IOException) t : new IOException(t); 737 } 738 739 private IOException convertInterruptedExceptionToIOException(final InterruptedException ie) { 740 Thread.currentThread().interrupt(); 741 IOException ioe = new InterruptedIOException(); 742 ioe.initCause(ie); 743 return ioe; 744 } 745 746 @Override 747 public byte[][] rollWriter(boolean force) throws FailedLogCloseException, IOException { 748 rollWriterLock.lock(); 749 try { 750 // Return if nothing to flush. 751 if (!force && this.writer != null && this.numEntries.get() <= 0) { 752 return null; 753 } 754 byte[][] regionsToFlush = null; 755 if (this.closed) { 756 LOG.debug("WAL closed. Skipping rolling of writer"); 757 return regionsToFlush; 758 } 759 try (TraceScope scope = TraceUtil.createTrace("FSHLog.rollWriter")) { 760 Path oldPath = getOldPath(); 761 Path newPath = getNewPath(); 762 // Any exception from here on is catastrophic, non-recoverable so we currently abort. 763 W nextWriter = this.createWriterInstance(newPath); 764 tellListenersAboutPreLogRoll(oldPath, newPath); 765 // NewPath could be equal to oldPath if replaceWriter fails. 766 newPath = replaceWriter(oldPath, newPath, nextWriter); 767 tellListenersAboutPostLogRoll(oldPath, newPath); 768 if (LOG.isDebugEnabled()) { 769 LOG.debug("Create new " + implClassName + " writer with pipeline: " + 770 Arrays.toString(getPipeline())); 771 } 772 // Can we delete any of the old log files? 773 if (getNumRolledLogFiles() > 0) { 774 cleanOldLogs(); 775 regionsToFlush = findRegionsToForceFlush(); 776 } 777 } catch (CommonFSUtils.StreamLacksCapabilityException exception) { 778 // If the underlying FileSystem can't do what we ask, treat as IO failure so 779 // we'll abort. 780 throw new IOException( 781 "Underlying FileSystem can't meet stream requirements. See RS log " + "for details.", 782 exception); 783 } 784 return regionsToFlush; 785 } finally { 786 rollWriterLock.unlock(); 787 } 788 } 789 790 // public only until class moves to o.a.h.h.wal 791 /** @return the size of log files in use */ 792 public long getLogFileSize() { 793 return this.totalLogSize.get(); 794 } 795 796 // public only until class moves to o.a.h.h.wal 797 public void requestLogRoll() { 798 requestLogRoll(false); 799 } 800 801 /** 802 * Get the backing files associated with this WAL. 803 * @return may be null if there are no files. 804 */ 805 @VisibleForTesting 806 FileStatus[] getFiles() throws IOException { 807 return CommonFSUtils.listStatus(fs, walDir, ourFiles); 808 } 809 810 @Override 811 public void shutdown() throws IOException { 812 if (!shutdown.compareAndSet(false, true)) { 813 return; 814 } 815 closed = true; 816 // Tell our listeners that the log is closing 817 if (!this.listeners.isEmpty()) { 818 for (WALActionsListener i : this.listeners) { 819 i.logCloseRequested(); 820 } 821 } 822 rollWriterLock.lock(); 823 try { 824 doShutdown(); 825 } finally { 826 rollWriterLock.unlock(); 827 } 828 } 829 830 @Override 831 public void close() throws IOException { 832 shutdown(); 833 final FileStatus[] files = getFiles(); 834 if (null != files && 0 != files.length) { 835 for (FileStatus file : files) { 836 Path p = getWALArchivePath(this.walArchiveDir, file.getPath()); 837 // Tell our listeners that a log is going to be archived. 838 if (!this.listeners.isEmpty()) { 839 for (WALActionsListener i : this.listeners) { 840 i.preLogArchive(file.getPath(), p); 841 } 842 } 843 844 if (!CommonFSUtils.renameAndSetModifyTime(fs, file.getPath(), p)) { 845 throw new IOException("Unable to rename " + file.getPath() + " to " + p); 846 } 847 // Tell our listeners that a log was archived. 848 if (!this.listeners.isEmpty()) { 849 for (WALActionsListener i : this.listeners) { 850 i.postLogArchive(file.getPath(), p); 851 } 852 } 853 } 854 LOG.debug( 855 "Moved " + files.length + " WAL file(s) to " + CommonFSUtils.getPath(this.walArchiveDir)); 856 } 857 LOG.info("Closed WAL: " + toString()); 858 } 859 860 /** 861 * updates the sequence number of a specific store. depending on the flag: replaces current seq 862 * number if the given seq id is bigger, or even if it is lower than existing one 863 * @param encodedRegionName 864 * @param familyName 865 * @param sequenceid 866 * @param onlyIfGreater 867 */ 868 @Override 869 public void updateStore(byte[] encodedRegionName, byte[] familyName, Long sequenceid, 870 boolean onlyIfGreater) { 871 sequenceIdAccounting.updateStore(encodedRegionName, familyName, sequenceid, onlyIfGreater); 872 } 873 874 protected final SyncFuture getSyncFuture(long sequence) { 875 return CollectionUtils 876 .computeIfAbsent(syncFuturesByHandler, Thread.currentThread(), SyncFuture::new) 877 .reset(sequence); 878 } 879 880 protected final void requestLogRoll(boolean tooFewReplicas) { 881 if (!this.listeners.isEmpty()) { 882 for (WALActionsListener i : this.listeners) { 883 i.logRollRequested(tooFewReplicas); 884 } 885 } 886 } 887 888 long getUnflushedEntriesCount() { 889 long highestSynced = this.highestSyncedTxid.get(); 890 long highestUnsynced = this.highestUnsyncedTxid; 891 return highestSynced >= highestUnsynced ? 0 : highestUnsynced - highestSynced; 892 } 893 894 boolean isUnflushedEntries() { 895 return getUnflushedEntriesCount() > 0; 896 } 897 898 /** 899 * Exposed for testing only. Use to tricks like halt the ring buffer appending. 900 */ 901 @VisibleForTesting 902 void atHeadOfRingBufferEventHandlerAppend() { 903 // Noop 904 } 905 906 protected final boolean append(W writer, FSWALEntry entry) throws IOException { 907 // TODO: WORK ON MAKING THIS APPEND FASTER. DOING WAY TOO MUCH WORK WITH CPs, PBing, etc. 908 atHeadOfRingBufferEventHandlerAppend(); 909 long start = EnvironmentEdgeManager.currentTime(); 910 byte[] encodedRegionName = entry.getKey().getEncodedRegionName(); 911 long regionSequenceId = entry.getKey().getSequenceId(); 912 913 // Edits are empty, there is nothing to append. Maybe empty when we are looking for a 914 // region sequence id only, a region edit/sequence id that is not associated with an actual 915 // edit. It has to go through all the rigmarole to be sure we have the right ordering. 916 if (entry.getEdit().isEmpty()) { 917 return false; 918 } 919 920 // Coprocessor hook. 921 coprocessorHost.preWALWrite(entry.getRegionInfo(), entry.getKey(), entry.getEdit()); 922 if (!listeners.isEmpty()) { 923 for (WALActionsListener i : listeners) { 924 i.visitLogEntryBeforeWrite(entry.getKey(), entry.getEdit()); 925 } 926 } 927 doAppend(writer, entry); 928 assert highestUnsyncedTxid < entry.getTxid(); 929 highestUnsyncedTxid = entry.getTxid(); 930 sequenceIdAccounting.update(encodedRegionName, entry.getFamilyNames(), regionSequenceId, 931 entry.isInMemStore()); 932 coprocessorHost.postWALWrite(entry.getRegionInfo(), entry.getKey(), entry.getEdit()); 933 // Update metrics. 934 postAppend(entry, EnvironmentEdgeManager.currentTime() - start); 935 numEntries.incrementAndGet(); 936 return true; 937 } 938 939 private long postAppend(final Entry e, final long elapsedTime) throws IOException { 940 long len = 0; 941 if (!listeners.isEmpty()) { 942 for (Cell cell : e.getEdit().getCells()) { 943 len += PrivateCellUtil.estimatedSerializedSizeOf(cell); 944 } 945 for (WALActionsListener listener : listeners) { 946 listener.postAppend(len, elapsedTime, e.getKey(), e.getEdit()); 947 } 948 } 949 return len; 950 } 951 952 protected final void postSync(final long timeInNanos, final int handlerSyncs) { 953 if (timeInNanos > this.slowSyncNs) { 954 String msg = new StringBuilder().append("Slow sync cost: ").append(timeInNanos / 1000000) 955 .append(" ms, current pipeline: ").append(Arrays.toString(getPipeline())).toString(); 956 TraceUtil.addTimelineAnnotation(msg); 957 LOG.info(msg); 958 } 959 if (!listeners.isEmpty()) { 960 for (WALActionsListener listener : listeners) { 961 listener.postSync(timeInNanos, handlerSyncs); 962 } 963 } 964 } 965 966 protected final long stampSequenceIdAndPublishToRingBuffer(RegionInfo hri, WALKeyImpl key, 967 WALEdit edits, boolean inMemstore, RingBuffer<RingBufferTruck> ringBuffer) 968 throws IOException { 969 if (this.closed) { 970 throw new IOException( 971 "Cannot append; log is closed, regionName = " + hri.getRegionNameAsString()); 972 } 973 MutableLong txidHolder = new MutableLong(); 974 MultiVersionConcurrencyControl.WriteEntry we = key.getMvcc().begin(() -> { 975 txidHolder.setValue(ringBuffer.next()); 976 }); 977 long txid = txidHolder.longValue(); 978 try (TraceScope scope = TraceUtil.createTrace(implClassName + ".append")) { 979 FSWALEntry entry = new FSWALEntry(txid, key, edits, hri, inMemstore); 980 entry.stampRegionSequenceId(we); 981 ringBuffer.get(txid).load(entry); 982 } finally { 983 ringBuffer.publish(txid); 984 } 985 return txid; 986 } 987 988 @Override 989 public String toString() { 990 return implClassName + " " + walFilePrefix + ":" + walFileSuffix + "(num " + filenum + ")"; 991 } 992 993 /** 994 * if the given {@code path} is being written currently, then return its length. 995 * <p> 996 * This is used by replication to prevent replicating unacked log entries. See 997 * https://issues.apache.org/jira/browse/HBASE-14004 for more details. 998 */ 999 @Override 1000 public OptionalLong getLogFileSizeIfBeingWritten(Path path) { 1001 rollWriterLock.lock(); 1002 try { 1003 Path currentPath = getOldPath(); 1004 if (path.equals(currentPath)) { 1005 W writer = this.writer; 1006 return writer != null ? OptionalLong.of(writer.getLength()) : OptionalLong.empty(); 1007 } else { 1008 return OptionalLong.empty(); 1009 } 1010 } finally { 1011 rollWriterLock.unlock(); 1012 } 1013 } 1014 1015 /** 1016 * NOTE: This append, at a time that is usually after this call returns, starts an mvcc 1017 * transaction by calling 'begin' wherein which we assign this update a sequenceid. At assignment 1018 * time, we stamp all the passed in Cells inside WALEdit with their sequenceId. You must 1019 * 'complete' the transaction this mvcc transaction by calling 1020 * MultiVersionConcurrencyControl#complete(...) or a variant otherwise mvcc will get stuck. Do it 1021 * in the finally of a try/finally block within which this append lives and any subsequent 1022 * operations like sync or update of memstore, etc. Get the WriteEntry to pass mvcc out of the 1023 * passed in WALKey <code>walKey</code> parameter. Be warned that the WriteEntry is not 1024 * immediately available on return from this method. It WILL be available subsequent to a sync of 1025 * this append; otherwise, you will just have to wait on the WriteEntry to get filled in. 1026 */ 1027 @Override 1028 public abstract long append(RegionInfo info, WALKeyImpl key, WALEdit edits, boolean inMemstore) 1029 throws IOException; 1030 1031 protected abstract void doAppend(W writer, FSWALEntry entry) throws IOException; 1032 1033 protected abstract W createWriterInstance(Path path) 1034 throws IOException, CommonFSUtils.StreamLacksCapabilityException; 1035 1036 protected abstract void doReplaceWriter(Path oldPath, Path newPath, W nextWriter) 1037 throws IOException; 1038 1039 protected abstract void doShutdown() throws IOException; 1040 1041 protected abstract boolean doCheckLogLowReplication(); 1042 1043 public void checkLogLowReplication(long checkInterval) { 1044 long now = EnvironmentEdgeManager.currentTime(); 1045 if (now - lastTimeCheckLowReplication < checkInterval) { 1046 return; 1047 } 1048 // Will return immediately if we are in the middle of a WAL log roll currently. 1049 if (!rollWriterLock.tryLock()) { 1050 return; 1051 } 1052 try { 1053 lastTimeCheckLowReplication = now; 1054 if (doCheckLogLowReplication()) { 1055 requestLogRoll(true); 1056 } 1057 } finally { 1058 rollWriterLock.unlock(); 1059 } 1060 } 1061 1062 /** 1063 * This method gets the pipeline for the current WAL. 1064 */ 1065 @VisibleForTesting 1066 abstract DatanodeInfo[] getPipeline(); 1067 1068 /** 1069 * This method gets the datanode replication count for the current WAL. 1070 */ 1071 @VisibleForTesting 1072 abstract int getLogReplication(); 1073 1074 private static void split(final Configuration conf, final Path p) throws IOException { 1075 FileSystem fs = FSUtils.getWALFileSystem(conf); 1076 if (!fs.exists(p)) { 1077 throw new FileNotFoundException(p.toString()); 1078 } 1079 if (!fs.getFileStatus(p).isDirectory()) { 1080 throw new IOException(p + " is not a directory"); 1081 } 1082 1083 final Path baseDir = FSUtils.getWALRootDir(conf); 1084 Path archiveDir = new Path(baseDir, HConstants.HREGION_OLDLOGDIR_NAME); 1085 if (conf.getBoolean(AbstractFSWALProvider.SEPARATE_OLDLOGDIR, 1086 AbstractFSWALProvider.DEFAULT_SEPARATE_OLDLOGDIR)) { 1087 archiveDir = new Path(archiveDir, p.getName()); 1088 } 1089 WALSplitter.split(baseDir, p, archiveDir, fs, conf, WALFactory.getInstance(conf)); 1090 } 1091 1092 private static void usage() { 1093 System.err.println("Usage: AbstractFSWAL <ARGS>"); 1094 System.err.println("Arguments:"); 1095 System.err.println(" --dump Dump textual representation of passed one or more files"); 1096 System.err.println(" For example: " + 1097 "AbstractFSWAL --dump hdfs://example.com:9000/hbase/WALs/MACHINE/LOGFILE"); 1098 System.err.println(" --split Split the passed directory of WAL logs"); 1099 System.err.println( 1100 " For example: AbstractFSWAL --split hdfs://example.com:9000/hbase/WALs/DIR"); 1101 } 1102 1103 /** 1104 * Pass one or more log file names and it will either dump out a text version on 1105 * <code>stdout</code> or split the specified log files. 1106 */ 1107 public static void main(String[] args) throws IOException { 1108 if (args.length < 2) { 1109 usage(); 1110 System.exit(-1); 1111 } 1112 // either dump using the WALPrettyPrinter or split, depending on args 1113 if (args[0].compareTo("--dump") == 0) { 1114 WALPrettyPrinter.run(Arrays.copyOfRange(args, 1, args.length)); 1115 } else if (args[0].compareTo("--perf") == 0) { 1116 LOG.error(HBaseMarkers.FATAL, "Please use the WALPerformanceEvaluation tool instead. i.e.:"); 1117 LOG.error(HBaseMarkers.FATAL, 1118 "\thbase org.apache.hadoop.hbase.wal.WALPerformanceEvaluation --iterations " + args[1]); 1119 System.exit(-1); 1120 } else if (args[0].compareTo("--split") == 0) { 1121 Configuration conf = HBaseConfiguration.create(); 1122 for (int i = 1; i < args.length; i++) { 1123 try { 1124 Path logPath = new Path(args[i]); 1125 FSUtils.setFsDefault(conf, logPath); 1126 split(conf, logPath); 1127 } catch (IOException t) { 1128 t.printStackTrace(System.err); 1129 System.exit(-1); 1130 } 1131 } 1132 } else { 1133 usage(); 1134 System.exit(-1); 1135 } 1136 } 1137}