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; 019 020import java.io.FileNotFoundException; 021import java.io.IOException; 022import java.util.ArrayList; 023import java.util.Date; 024import java.util.List; 025import java.util.Map; 026import java.util.NavigableSet; 027import java.util.Optional; 028import java.util.UUID; 029import java.util.concurrent.ConcurrentHashMap; 030import java.util.concurrent.atomic.AtomicLong; 031import java.util.function.Consumer; 032import org.apache.hadoop.conf.Configuration; 033import org.apache.hadoop.fs.FileSystem; 034import org.apache.hadoop.fs.Path; 035import org.apache.hadoop.hbase.ArrayBackedTag; 036import org.apache.hadoop.hbase.CellBuilderType; 037import org.apache.hadoop.hbase.CellComparator; 038import org.apache.hadoop.hbase.DoNotRetryIOException; 039import org.apache.hadoop.hbase.ExtendedCell; 040import org.apache.hadoop.hbase.ExtendedCellBuilderFactory; 041import org.apache.hadoop.hbase.HConstants; 042import org.apache.hadoop.hbase.TableName; 043import org.apache.hadoop.hbase.Tag; 044import org.apache.hadoop.hbase.TagType; 045import org.apache.hadoop.hbase.TagUtil; 046import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor; 047import org.apache.hadoop.hbase.client.Scan; 048import org.apache.hadoop.hbase.filter.Filter; 049import org.apache.hadoop.hbase.filter.FilterList; 050import org.apache.hadoop.hbase.io.compress.Compression; 051import org.apache.hadoop.hbase.io.hfile.CorruptHFileException; 052import org.apache.hadoop.hbase.mob.MobCell; 053import org.apache.hadoop.hbase.mob.MobConstants; 054import org.apache.hadoop.hbase.mob.MobFile; 055import org.apache.hadoop.hbase.mob.MobFileCache; 056import org.apache.hadoop.hbase.mob.MobFileName; 057import org.apache.hadoop.hbase.mob.MobStoreEngine; 058import org.apache.hadoop.hbase.mob.MobUtils; 059import org.apache.hadoop.hbase.regionserver.storefiletracker.StoreFileTracker; 060import org.apache.hadoop.hbase.regionserver.storefiletracker.StoreFileTrackerFactory; 061import org.apache.hadoop.hbase.util.HFileArchiveUtil; 062import org.apache.hadoop.hbase.util.IdLock; 063import org.apache.yetus.audience.InterfaceAudience; 064import org.slf4j.Logger; 065import org.slf4j.LoggerFactory; 066 067/** 068 * The store implementation to save MOBs (medium objects), it extends the HStore. When a descriptor 069 * of a column family has the value "IS_MOB", it means this column family is a mob one. When a 070 * HRegion instantiate a store for this column family, the HMobStore is created. HMobStore is almost 071 * the same with the HStore except using different types of scanners. In the method of getScanner, 072 * the MobStoreScanner and MobReversedStoreScanner are returned. In these scanners, a additional 073 * seeks in the mob files should be performed after the seek to HBase is done. The store implements 074 * how we save MOBs by extending HStore. When a descriptor of a column family has the value 075 * "IS_MOB", it means this column family is a mob one. When a HRegion instantiate a store for this 076 * column family, the HMobStore is created. HMobStore is almost the same with the HStore except 077 * using different types of scanners. In the method of getScanner, the MobStoreScanner and 078 * MobReversedStoreScanner are returned. In these scanners, a additional seeks in the mob files 079 * should be performed after the seek in HBase is done. 080 */ 081@InterfaceAudience.Private 082public class HMobStore extends HStore { 083 private static final Logger LOG = LoggerFactory.getLogger(HMobStore.class); 084 private MobFileCache mobFileCache; 085 private Path homePath; 086 private Path mobFamilyPath; 087 private AtomicLong cellsCountCompactedToMob = new AtomicLong(); 088 private AtomicLong cellsCountCompactedFromMob = new AtomicLong(); 089 private AtomicLong cellsSizeCompactedToMob = new AtomicLong(); 090 private AtomicLong cellsSizeCompactedFromMob = new AtomicLong(); 091 private AtomicLong mobFlushCount = new AtomicLong(); 092 private AtomicLong mobFlushedCellsCount = new AtomicLong(); 093 private AtomicLong mobFlushedCellsSize = new AtomicLong(); 094 private AtomicLong mobScanCellsCount = new AtomicLong(); 095 private AtomicLong mobScanCellsSize = new AtomicLong(); 096 private Map<TableName, List<Path>> map = new ConcurrentHashMap<>(); 097 private final IdLock keyLock = new IdLock(); 098 // When we add a MOB reference cell to the HFile, we will add 2 tags along with it 099 // 1. A ref tag with type TagType.MOB_REFERENCE_TAG_TYPE. This just denote this this cell is not 100 // original one but a ref to another MOB Cell. 101 // 2. Table name tag. It's very useful in cloning the snapshot. When reading from the cloning 102 // table, we need to find the original mob files by this table name. For details please see 103 // cloning snapshot for mob files. 104 private final byte[] refCellTags; 105 106 public HMobStore(final HRegion region, final ColumnFamilyDescriptor family, 107 final Configuration confParam, boolean warmup) throws IOException { 108 super(region, family, confParam, warmup); 109 this.mobFileCache = region.getMobFileCache(); 110 this.homePath = MobUtils.getMobHome(conf); 111 this.mobFamilyPath = 112 MobUtils.getMobFamilyPath(conf, this.getTableName(), getColumnFamilyName()); 113 List<Path> locations = new ArrayList<>(2); 114 locations.add(mobFamilyPath); 115 TableName tn = region.getTableDescriptor().getTableName(); 116 locations.add(HFileArchiveUtil.getStoreArchivePath(conf, tn, 117 MobUtils.getMobRegionInfo(tn).getEncodedName(), getColumnFamilyName())); 118 map.put(tn, locations); 119 List<Tag> tags = new ArrayList<>(2); 120 tags.add(MobConstants.MOB_REF_TAG); 121 Tag tableNameTag = 122 new ArrayBackedTag(TagType.MOB_TABLE_NAME_TAG_TYPE, getTableName().getName()); 123 tags.add(tableNameTag); 124 this.refCellTags = TagUtil.fromList(tags); 125 } 126 127 /** 128 * Gets current config. 129 */ 130 public Configuration getConfiguration() { 131 return this.conf; 132 } 133 134 /** 135 * Gets the MobStoreScanner or MobReversedStoreScanner. In these scanners, a additional seeks in 136 * the mob files should be performed after the seek in HBase is done. 137 */ 138 @Override 139 protected KeyValueScanner createScanner(Scan scan, ScanInfo scanInfo, 140 NavigableSet<byte[]> targetCols, long readPt) throws IOException { 141 if (MobUtils.isRefOnlyScan(scan)) { 142 Filter refOnlyFilter = new MobReferenceOnlyFilter(); 143 Filter filter = scan.getFilter(); 144 if (filter != null) { 145 scan.setFilter(new FilterList(filter, refOnlyFilter)); 146 } else { 147 scan.setFilter(refOnlyFilter); 148 } 149 } 150 return scan.isReversed() 151 ? new ReversedMobStoreScanner(this, scanInfo, scan, targetCols, readPt) 152 : new MobStoreScanner(this, scanInfo, scan, targetCols, readPt); 153 } 154 155 /** 156 * Creates the mob store engine. 157 */ 158 @Override 159 protected StoreEngine<?, ?, ?, ?> createStoreEngine(HStore store, Configuration conf, 160 CellComparator cellComparator) throws IOException { 161 MobStoreEngine engine = new MobStoreEngine(); 162 engine.createComponentsOnce(conf, store, cellComparator); 163 return engine; 164 } 165 166 /** 167 * Gets the temp directory. 168 * @return The temp directory. 169 */ 170 private Path getTempDir() { 171 return new Path(homePath, MobConstants.TEMP_DIR_NAME); 172 } 173 174 /** 175 * Creates the writer for the mob file in temp directory. 176 * @param date The latest date of written cells. 177 * @param maxKeyCount The key count. 178 * @param compression The compression algorithm. 179 * @param startKey The start key. 180 * @param isCompaction If the writer is used in compaction. 181 * @return The writer for the mob file. 182 */ 183 public StoreFileWriter createWriterInTmp(Date date, long maxKeyCount, 184 Compression.Algorithm compression, byte[] startKey, boolean isCompaction) throws IOException { 185 if (startKey == null) { 186 startKey = HConstants.EMPTY_START_ROW; 187 } 188 Path path = getTempDir(); 189 return createWriterInTmp(MobUtils.formatDate(date), path, maxKeyCount, compression, startKey, 190 isCompaction, null); 191 } 192 193 /** 194 * Creates the writer for the mob file in the mob family directory. 195 * @param date The latest date of written cells. 196 * @param maxKeyCount The key count. 197 * @param compression The compression algorithm. 198 * @param startKey The start key. 199 * @param isCompaction If the writer is used in compaction. 200 * @return The writer for the mob file. 201 */ 202 public StoreFileWriter createWriter(Date date, long maxKeyCount, 203 Compression.Algorithm compression, byte[] startKey, boolean isCompaction, 204 Consumer<Path> writerCreationTracker) throws IOException { 205 if (startKey == null) { 206 startKey = HConstants.EMPTY_START_ROW; 207 } 208 Path path = getPath(); 209 return createWriterInTmp(MobUtils.formatDate(date), path, maxKeyCount, compression, startKey, 210 isCompaction, writerCreationTracker); 211 } 212 213 /** 214 * Creates the writer for the mob file in temp directory. 215 * @param date The date string, its format is yyyymmmdd. 216 * @param basePath The basic path for a temp directory. 217 * @param maxKeyCount The key count. 218 * @param compression The compression algorithm. 219 * @param startKey The start key. 220 * @param isCompaction If the writer is used in compaction. 221 * @return The writer for the mob file. 222 */ 223 public StoreFileWriter createWriterInTmp(String date, Path basePath, long maxKeyCount, 224 Compression.Algorithm compression, byte[] startKey, boolean isCompaction, 225 Consumer<Path> writerCreationTracker) throws IOException { 226 MobFileName mobFileName = 227 MobFileName.create(startKey, date, UUID.randomUUID().toString().replaceAll("-", ""), 228 getHRegion().getRegionInfo().getEncodedName()); 229 return createWriterInTmp(mobFileName, basePath, maxKeyCount, compression, isCompaction, 230 writerCreationTracker); 231 } 232 233 /** 234 * Creates the writer for the mob file in temp directory. 235 * @param mobFileName The mob file name. 236 * @param basePath The basic path for a temp directory. 237 * @param maxKeyCount The key count. 238 * @param compression The compression algorithm. 239 * @param isCompaction If the writer is used in compaction. 240 * @return The writer for the mob file. 241 */ 242 243 public StoreFileWriter createWriterInTmp(MobFileName mobFileName, Path basePath, long maxKeyCount, 244 Compression.Algorithm compression, boolean isCompaction, Consumer<Path> writerCreationTracker) 245 throws IOException { 246 return MobUtils.createWriter(conf, getFileSystem(), getColumnFamilyDescriptor(), 247 new Path(basePath, mobFileName.getFileName()), maxKeyCount, compression, getCacheConfig(), 248 getStoreContext().getEncryptionContext(), StoreUtils.getChecksumType(conf), 249 StoreUtils.getBytesPerChecksum(conf), getStoreContext().getBlockSize(), BloomType.NONE, 250 isCompaction, writerCreationTracker); 251 } 252 253 /** 254 * Commits the mob file. 255 * @param sourceFile The source file. 256 * @param targetPath The directory path where the source file is renamed to. 257 */ 258 public void commitFile(final Path sourceFile, Path targetPath) throws IOException { 259 if (sourceFile == null) { 260 return; 261 } 262 Path dstPath = new Path(targetPath, sourceFile.getName()); 263 validateMobFile(sourceFile); 264 if (sourceFile.equals(targetPath)) { 265 LOG.info("File is already in the destination dir: {}", sourceFile); 266 return; 267 } 268 LOG.info(" FLUSH Renaming flushed file from {} to {}", sourceFile, dstPath); 269 Path parent = dstPath.getParent(); 270 if (!getFileSystem().exists(parent)) { 271 getFileSystem().mkdirs(parent); 272 } 273 if (!getFileSystem().rename(sourceFile, dstPath)) { 274 throw new IOException("Failed rename of " + sourceFile + " to " + dstPath); 275 } 276 } 277 278 /** 279 * Validates a mob file by opening and closing it. 280 * @param path the path to the mob file 281 */ 282 private void validateMobFile(Path path) throws IOException { 283 HStoreFile storeFile = null; 284 try { 285 StoreFileTracker sft = StoreFileTrackerFactory.create(conf, false, getStoreContext()); 286 storeFile = new HStoreFile(getFileSystem(), path, conf, getCacheConfig(), BloomType.NONE, 287 isPrimaryReplicaStore(), sft); 288 storeFile.initReader(); 289 } catch (IOException e) { 290 LOG.error("Fail to open mob file[" + path + "], keep it in temp directory.", e); 291 throw e; 292 } finally { 293 if (storeFile != null) { 294 storeFile.closeStoreFile(false); 295 } 296 } 297 } 298 299 /** 300 * Reads the cell from the mob file, and the read point does not count. This is used for 301 * DefaultMobStoreCompactor where we can read empty value for the missing cell. 302 * @param reference The cell found in the HBase, its value is a path to a mob file. 303 * @param cacheBlocks Whether the scanner should cache blocks. 304 * @return The cell found in the mob file. 305 */ 306 public MobCell resolve(ExtendedCell reference, boolean cacheBlocks) throws IOException { 307 return resolve(reference, cacheBlocks, -1, true); 308 } 309 310 /** 311 * Reads the cell from the mob file with readEmptyValueOnMobCellMiss 312 * @param reference The cell found in the HBase, its value is a path to a mob 313 * file. 314 * @param cacheBlocks Whether the scanner should cache blocks. 315 * @param readEmptyValueOnMobCellMiss should return empty mob cell if reference can not be 316 * resolved. 317 * @return The cell found in the mob file. 318 */ 319 public MobCell resolve(ExtendedCell reference, boolean cacheBlocks, 320 boolean readEmptyValueOnMobCellMiss) throws IOException { 321 return resolve(reference, cacheBlocks, -1, readEmptyValueOnMobCellMiss); 322 } 323 324 /** 325 * Reads the cell from the mob file. 326 * @param reference The cell found in the HBase, its value is a path to a mob 327 * file. 328 * @param cacheBlocks Whether the scanner should cache blocks. 329 * @param readPt the read point. 330 * @param readEmptyValueOnMobCellMiss Whether return null value when the mob file is missing or 331 * corrupt. 332 * @return The cell found in the mob file. 333 */ 334 public MobCell resolve(ExtendedCell reference, boolean cacheBlocks, long readPt, 335 boolean readEmptyValueOnMobCellMiss) throws IOException { 336 MobCell mobCell = null; 337 if (MobUtils.hasValidMobRefCellValue(reference)) { 338 String fileName = MobUtils.getMobFileName(reference); 339 Optional<TableName> tableName = MobUtils.getTableName(reference); 340 if (tableName.isPresent()) { 341 List<Path> locations = getLocations(tableName.get()); 342 mobCell = readCell(locations, fileName, reference, cacheBlocks, readPt, 343 readEmptyValueOnMobCellMiss); 344 } 345 } 346 if (mobCell == null) { 347 LOG.warn("The Cell result is null, assemble a new Cell with the same row,family," 348 + "qualifier,timestamp,type and tags but with an empty value to return."); 349 ExtendedCell cell = ExtendedCellBuilderFactory.create(CellBuilderType.DEEP_COPY) 350 .setRow(reference.getRowArray(), reference.getRowOffset(), reference.getRowLength()) 351 .setFamily(reference.getFamilyArray(), reference.getFamilyOffset(), 352 reference.getFamilyLength()) 353 .setQualifier(reference.getQualifierArray(), reference.getQualifierOffset(), 354 reference.getQualifierLength()) 355 .setTimestamp(reference.getTimestamp()).setType(reference.getTypeByte()) 356 .setValue(HConstants.EMPTY_BYTE_ARRAY) 357 .setTags(reference.getTagsArray(), reference.getTagsOffset(), reference.getTagsLength()) 358 .build(); 359 mobCell = new MobCell(cell); 360 } 361 return mobCell; 362 } 363 364 /** 365 * @param tableName to look up locations for, can not be null 366 * @return a list of location in order of working dir, archive dir. will not be null. 367 */ 368 public List<Path> getLocations(TableName tableName) throws IOException { 369 List<Path> locations = map.get(tableName); 370 if (locations == null) { 371 IdLock.Entry lockEntry = keyLock.getLockEntry(tableName.hashCode()); 372 try { 373 locations = map.get(tableName); 374 if (locations == null) { 375 locations = new ArrayList<>(2); 376 locations.add(MobUtils.getMobFamilyPath(conf, tableName, 377 getColumnFamilyDescriptor().getNameAsString())); 378 locations.add(HFileArchiveUtil.getStoreArchivePath(conf, tableName, 379 MobUtils.getMobRegionInfo(tableName).getEncodedName(), 380 getColumnFamilyDescriptor().getNameAsString())); 381 map.put(tableName, locations); 382 } 383 } finally { 384 keyLock.releaseLockEntry(lockEntry); 385 } 386 } 387 return locations; 388 } 389 390 /** 391 * Reads the cell from a mob file. The mob file might be located in different directories. 1. The 392 * working directory. 2. The archive directory. Reads the cell from the files located in both of 393 * the above directories. 394 * @param locations The possible locations where the mob files are saved. 395 * @param fileName The file to be read. 396 * @param search The cell to be searched. 397 * @param cacheMobBlocks Whether the scanner should cache blocks. 398 * @param readPt the read point. 399 * @param readEmptyValueOnMobCellMiss Whether return null value when the mob file is missing or 400 * corrupt. 401 * @return The found cell. Null if there's no such a cell. 402 */ 403 private MobCell readCell(List<Path> locations, String fileName, ExtendedCell search, 404 boolean cacheMobBlocks, long readPt, boolean readEmptyValueOnMobCellMiss) throws IOException { 405 FileSystem fs = getFileSystem(); 406 IOException ioe = null; 407 for (Path location : locations) { 408 MobFile file = null; 409 Path path = new Path(location, fileName); 410 try { 411 file = mobFileCache.openFile(fs, path, getCacheConfig(), this.getStoreContext()); 412 return readPt != -1 413 ? file.readCell(search, cacheMobBlocks, readPt) 414 : file.readCell(search, cacheMobBlocks); 415 } catch (IOException e) { 416 mobFileCache.evictFile(fileName); 417 ioe = e; 418 if ( 419 (e instanceof FileNotFoundException) || (e.getCause() instanceof FileNotFoundException) 420 ) { 421 LOG.debug("Fail to read the cell, the mob file " + path + " doesn't exist", e); 422 } else if (e instanceof CorruptHFileException) { 423 LOG.error("The mob file " + path + " is corrupt", e); 424 break; 425 } else { 426 throw e; 427 } 428 } finally { 429 if (file != null) { 430 mobFileCache.closeFile(file); 431 } 432 } 433 } 434 LOG.error("The mob file " + fileName + " could not be found in the locations " + locations 435 + " or it is corrupt"); 436 if (readEmptyValueOnMobCellMiss) { 437 return null; 438 } else if ( 439 (ioe instanceof FileNotFoundException) || (ioe.getCause() instanceof FileNotFoundException) 440 ) { 441 // The region is re-opened when FileNotFoundException is thrown. 442 // This is not necessary when MOB files cannot be found, because the store files 443 // in a region only contain the references to MOB files and a re-open on a region 444 // doesn't help fix the lost MOB files. 445 throw new DoNotRetryIOException(ioe); 446 } else { 447 throw ioe; 448 } 449 } 450 451 /** 452 * Gets the mob file path. 453 * @return The mob file path. 454 */ 455 public Path getPath() { 456 return mobFamilyPath; 457 } 458 459 public void updateCellsCountCompactedToMob(long count) { 460 cellsCountCompactedToMob.addAndGet(count); 461 } 462 463 public long getCellsCountCompactedToMob() { 464 return cellsCountCompactedToMob.get(); 465 } 466 467 public void updateCellsCountCompactedFromMob(long count) { 468 cellsCountCompactedFromMob.addAndGet(count); 469 } 470 471 public long getCellsCountCompactedFromMob() { 472 return cellsCountCompactedFromMob.get(); 473 } 474 475 public void updateCellsSizeCompactedToMob(long size) { 476 cellsSizeCompactedToMob.addAndGet(size); 477 } 478 479 public long getCellsSizeCompactedToMob() { 480 return cellsSizeCompactedToMob.get(); 481 } 482 483 public void updateCellsSizeCompactedFromMob(long size) { 484 cellsSizeCompactedFromMob.addAndGet(size); 485 } 486 487 public long getCellsSizeCompactedFromMob() { 488 return cellsSizeCompactedFromMob.get(); 489 } 490 491 public void updateMobFlushCount() { 492 mobFlushCount.incrementAndGet(); 493 } 494 495 public long getMobFlushCount() { 496 return mobFlushCount.get(); 497 } 498 499 public void updateMobFlushedCellsCount(long count) { 500 mobFlushedCellsCount.addAndGet(count); 501 } 502 503 public long getMobFlushedCellsCount() { 504 return mobFlushedCellsCount.get(); 505 } 506 507 public void updateMobFlushedCellsSize(long size) { 508 mobFlushedCellsSize.addAndGet(size); 509 } 510 511 public long getMobFlushedCellsSize() { 512 return mobFlushedCellsSize.get(); 513 } 514 515 public void updateMobScanCellsCount(long count) { 516 mobScanCellsCount.addAndGet(count); 517 } 518 519 public long getMobScanCellsCount() { 520 return mobScanCellsCount.get(); 521 } 522 523 public void updateMobScanCellsSize(long size) { 524 mobScanCellsSize.addAndGet(size); 525 } 526 527 public long getMobScanCellsSize() { 528 return mobScanCellsSize.get(); 529 } 530 531 public byte[] getRefCellTags() { 532 return this.refCellTags; 533 } 534 535}