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 static org.mockito.Mockito.mock; 021import static org.mockito.Mockito.when; 022 023import java.io.IOException; 024import java.nio.ByteBuffer; 025import java.util.ArrayList; 026import java.util.Arrays; 027import java.util.Collections; 028import java.util.Comparator; 029import java.util.List; 030import java.util.Map; 031import java.util.OptionalLong; 032import java.util.TreeSet; 033import java.util.concurrent.atomic.AtomicInteger; 034import org.apache.hadoop.conf.Configuration; 035import org.apache.hadoop.fs.FileSystem; 036import org.apache.hadoop.fs.Path; 037import org.apache.hadoop.hbase.Cell; 038import org.apache.hadoop.hbase.CellUtil; 039import org.apache.hadoop.hbase.HBaseClassTestRule; 040import org.apache.hadoop.hbase.HBaseTestCase; 041import org.apache.hadoop.hbase.HBaseTestingUtility; 042import org.apache.hadoop.hbase.HColumnDescriptor; 043import org.apache.hadoop.hbase.HConstants; 044import org.apache.hadoop.hbase.HRegionInfo; 045import org.apache.hadoop.hbase.KeyValue; 046import org.apache.hadoop.hbase.KeyValueUtil; 047import org.apache.hadoop.hbase.PrivateCellUtil; 048import org.apache.hadoop.hbase.TableName; 049import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor; 050import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; 051import org.apache.hadoop.hbase.client.Scan; 052import org.apache.hadoop.hbase.io.HFileLink; 053import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding; 054import org.apache.hadoop.hbase.io.hfile.BlockCache; 055import org.apache.hadoop.hbase.io.hfile.CacheConfig; 056import org.apache.hadoop.hbase.io.hfile.CacheStats; 057import org.apache.hadoop.hbase.io.hfile.HFileContext; 058import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder; 059import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoder; 060import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoderImpl; 061import org.apache.hadoop.hbase.io.hfile.HFileScanner; 062import org.apache.hadoop.hbase.testclassification.RegionServerTests; 063import org.apache.hadoop.hbase.testclassification.SmallTests; 064import org.apache.hadoop.hbase.util.BloomFilterFactory; 065import org.apache.hadoop.hbase.util.Bytes; 066import org.apache.hadoop.hbase.util.ChecksumType; 067import org.apache.hadoop.hbase.util.FSUtils; 068import org.junit.After; 069import org.junit.Before; 070import org.junit.ClassRule; 071import org.junit.Test; 072import org.junit.experimental.categories.Category; 073import org.mockito.Mockito; 074import org.slf4j.Logger; 075import org.slf4j.LoggerFactory; 076 077import org.apache.hbase.thirdparty.com.google.common.base.Joiner; 078import org.apache.hbase.thirdparty.com.google.common.collect.Iterables; 079import org.apache.hbase.thirdparty.com.google.common.collect.Lists; 080 081/** 082 * Test HStoreFile 083 */ 084@Category({RegionServerTests.class, SmallTests.class}) 085public class TestHStoreFile extends HBaseTestCase { 086 087 @ClassRule 088 public static final HBaseClassTestRule CLASS_RULE = 089 HBaseClassTestRule.forClass(TestHStoreFile.class); 090 091 private static final Logger LOG = LoggerFactory.getLogger(TestHStoreFile.class); 092 private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); 093 private CacheConfig cacheConf = new CacheConfig(TEST_UTIL.getConfiguration()); 094 private static String ROOT_DIR = TEST_UTIL.getDataTestDir("TestStoreFile").toString(); 095 private static final ChecksumType CKTYPE = ChecksumType.CRC32C; 096 private static final int CKBYTES = 512; 097 private static String TEST_FAMILY = "cf"; 098 099 @Override 100 @Before 101 public void setUp() throws Exception { 102 super.setUp(); 103 } 104 105 @Override 106 @After 107 public void tearDown() throws Exception { 108 super.tearDown(); 109 } 110 111 /** 112 * Write a file and then assert that we can read from top and bottom halves 113 * using two HalfMapFiles. 114 * @throws Exception 115 */ 116 @Test 117 public void testBasicHalfMapFile() throws Exception { 118 final HRegionInfo hri = 119 new HRegionInfo(TableName.valueOf("testBasicHalfMapFileTb")); 120 HRegionFileSystem regionFs = HRegionFileSystem.createRegionOnFileSystem( 121 conf, fs, new Path(testDir, hri.getTable().getNameAsString()), hri); 122 123 HFileContext meta = new HFileContextBuilder().withBlockSize(2*1024).build(); 124 StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs) 125 .withFilePath(regionFs.createTempName()) 126 .withFileContext(meta) 127 .build(); 128 writeStoreFile(writer); 129 130 Path sfPath = regionFs.commitStoreFile(TEST_FAMILY, writer.getPath()); 131 HStoreFile sf = new HStoreFile(this.fs, sfPath, conf, cacheConf, BloomType.NONE, true); 132 checkHalfHFile(regionFs, sf); 133 } 134 135 private void writeStoreFile(final StoreFileWriter writer) throws IOException { 136 writeStoreFile(writer, Bytes.toBytes(getName()), Bytes.toBytes(getName())); 137 } 138 139 // pick an split point (roughly halfway) 140 byte[] SPLITKEY = new byte[] { (LAST_CHAR + FIRST_CHAR)/2, FIRST_CHAR}; 141 142 /* 143 * Writes HStoreKey and ImmutableBytes data to passed writer and 144 * then closes it. 145 * @param writer 146 * @throws IOException 147 */ 148 public static void writeStoreFile(final StoreFileWriter writer, byte[] fam, byte[] qualifier) 149 throws IOException { 150 long now = System.currentTimeMillis(); 151 try { 152 for (char d = FIRST_CHAR; d <= LAST_CHAR; d++) { 153 for (char e = FIRST_CHAR; e <= LAST_CHAR; e++) { 154 byte[] b = new byte[] { (byte) d, (byte) e }; 155 writer.append(new KeyValue(b, fam, qualifier, now, b)); 156 } 157 } 158 } finally { 159 writer.close(); 160 } 161 } 162 163 /** 164 * Test that our mechanism of writing store files in one region to reference 165 * store files in other regions works. 166 * @throws IOException 167 */ 168 @Test 169 public void testReference() throws IOException { 170 final HRegionInfo hri = new HRegionInfo(TableName.valueOf("testReferenceTb")); 171 HRegionFileSystem regionFs = HRegionFileSystem.createRegionOnFileSystem( 172 conf, fs, new Path(testDir, hri.getTable().getNameAsString()), hri); 173 174 HFileContext meta = new HFileContextBuilder().withBlockSize(8 * 1024).build(); 175 // Make a store file and write data to it. 176 StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs) 177 .withFilePath(regionFs.createTempName()) 178 .withFileContext(meta) 179 .build(); 180 writeStoreFile(writer); 181 182 Path hsfPath = regionFs.commitStoreFile(TEST_FAMILY, writer.getPath()); 183 HStoreFile hsf = new HStoreFile(this.fs, hsfPath, conf, cacheConf, BloomType.NONE, true); 184 hsf.initReader(); 185 StoreFileReader reader = hsf.getReader(); 186 // Split on a row, not in middle of row. Midkey returned by reader 187 // may be in middle of row. Create new one with empty column and 188 // timestamp. 189 byte [] midRow = CellUtil.cloneRow(reader.midKey().get()); 190 byte [] finalRow = CellUtil.cloneRow(reader.getLastKey().get()); 191 hsf.closeStoreFile(true); 192 193 // Make a reference 194 HRegionInfo splitHri = new HRegionInfo(hri.getTable(), null, midRow); 195 Path refPath = splitStoreFile(regionFs, splitHri, TEST_FAMILY, hsf, midRow, true); 196 HStoreFile refHsf = new HStoreFile(this.fs, refPath, conf, cacheConf, BloomType.NONE, true); 197 refHsf.initReader(); 198 // Now confirm that I can read from the reference and that it only gets 199 // keys from top half of the file. 200 HFileScanner s = refHsf.getReader().getScanner(false, false); 201 Cell kv = null; 202 for (boolean first = true; (!s.isSeeked() && s.seekTo()) || s.next();) { 203 ByteBuffer bb = ByteBuffer.wrap(((KeyValue) s.getKey()).getKey()); 204 kv = KeyValueUtil.createKeyValueFromKey(bb); 205 if (first) { 206 assertTrue(Bytes.equals(kv.getRowArray(), kv.getRowOffset(), kv.getRowLength(), midRow, 0, 207 midRow.length)); 208 first = false; 209 } 210 } 211 assertTrue(Bytes.equals(kv.getRowArray(), kv.getRowOffset(), kv.getRowLength(), finalRow, 0, 212 finalRow.length)); 213 } 214 215 @Test 216 public void testEmptyStoreFileRestrictKeyRanges() throws Exception { 217 StoreFileReader reader = mock(StoreFileReader.class); 218 HStore store = mock(HStore.class); 219 byte[] cf = Bytes.toBytes("ty"); 220 ColumnFamilyDescriptor cfd = ColumnFamilyDescriptorBuilder.of(cf); 221 when(store.getColumnFamilyDescriptor()).thenReturn(cfd); 222 StoreFileScanner scanner = 223 new StoreFileScanner(reader, mock(HFileScanner.class), false, false, 0, 0, true); 224 Scan scan = new Scan(); 225 scan.setColumnFamilyTimeRange(cf, 0, 1); 226 assertFalse(scanner.shouldUseScanner(scan, store, 0)); 227 } 228 229 @Test 230 public void testHFileLink() throws IOException { 231 final HRegionInfo hri = new HRegionInfo(TableName.valueOf("testHFileLinkTb")); 232 // force temp data in hbase/target/test-data instead of /tmp/hbase-xxxx/ 233 Configuration testConf = new Configuration(this.conf); 234 FSUtils.setRootDir(testConf, testDir); 235 HRegionFileSystem regionFs = HRegionFileSystem.createRegionOnFileSystem( 236 testConf, fs, FSUtils.getTableDir(testDir, hri.getTable()), hri); 237 HFileContext meta = new HFileContextBuilder().withBlockSize(8 * 1024).build(); 238 239 // Make a store file and write data to it. 240 StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs) 241 .withFilePath(regionFs.createTempName()) 242 .withFileContext(meta) 243 .build(); 244 writeStoreFile(writer); 245 246 Path storeFilePath = regionFs.commitStoreFile(TEST_FAMILY, writer.getPath()); 247 Path dstPath = new Path(regionFs.getTableDir(), new Path("test-region", TEST_FAMILY)); 248 HFileLink.create(testConf, this.fs, dstPath, hri, storeFilePath.getName()); 249 Path linkFilePath = new Path(dstPath, 250 HFileLink.createHFileLinkName(hri, storeFilePath.getName())); 251 252 // Try to open store file from link 253 StoreFileInfo storeFileInfo = new StoreFileInfo(testConf, this.fs, linkFilePath); 254 HStoreFile hsf = 255 new HStoreFile(this.fs, storeFileInfo, testConf, cacheConf, BloomType.NONE, true); 256 assertTrue(storeFileInfo.isLink()); 257 hsf.initReader(); 258 259 // Now confirm that I can read from the link 260 int count = 1; 261 HFileScanner s = hsf.getReader().getScanner(false, false); 262 s.seekTo(); 263 while (s.next()) { 264 count++; 265 } 266 assertEquals((LAST_CHAR - FIRST_CHAR + 1) * (LAST_CHAR - FIRST_CHAR + 1), count); 267 } 268 269 /** 270 * This test creates an hfile and then the dir structures and files to verify that references 271 * to hfilelinks (created by snapshot clones) can be properly interpreted. 272 */ 273 @Test 274 public void testReferenceToHFileLink() throws IOException { 275 // force temp data in hbase/target/test-data instead of /tmp/hbase-xxxx/ 276 Configuration testConf = new Configuration(this.conf); 277 FSUtils.setRootDir(testConf, testDir); 278 279 // adding legal table name chars to verify regex handles it. 280 HRegionInfo hri = new HRegionInfo(TableName.valueOf("_original-evil-name")); 281 HRegionFileSystem regionFs = HRegionFileSystem.createRegionOnFileSystem( 282 testConf, fs, FSUtils.getTableDir(testDir, hri.getTable()), hri); 283 284 HFileContext meta = new HFileContextBuilder().withBlockSize(8 * 1024).build(); 285 // Make a store file and write data to it. <root>/<tablename>/<rgn>/<cf>/<file> 286 StoreFileWriter writer = new StoreFileWriter.Builder(testConf, cacheConf, this.fs) 287 .withFilePath(regionFs.createTempName()) 288 .withFileContext(meta) 289 .build(); 290 writeStoreFile(writer); 291 Path storeFilePath = regionFs.commitStoreFile(TEST_FAMILY, writer.getPath()); 292 293 // create link to store file. <root>/clone/region/<cf>/<hfile>-<region>-<table> 294 HRegionInfo hriClone = new HRegionInfo(TableName.valueOf("clone")); 295 HRegionFileSystem cloneRegionFs = HRegionFileSystem.createRegionOnFileSystem( 296 testConf, fs, FSUtils.getTableDir(testDir, hri.getTable()), 297 hriClone); 298 Path dstPath = cloneRegionFs.getStoreDir(TEST_FAMILY); 299 HFileLink.create(testConf, this.fs, dstPath, hri, storeFilePath.getName()); 300 Path linkFilePath = new Path(dstPath, 301 HFileLink.createHFileLinkName(hri, storeFilePath.getName())); 302 303 // create splits of the link. 304 // <root>/clone/splitA/<cf>/<reftohfilelink>, 305 // <root>/clone/splitB/<cf>/<reftohfilelink> 306 HRegionInfo splitHriA = new HRegionInfo(hri.getTable(), null, SPLITKEY); 307 HRegionInfo splitHriB = new HRegionInfo(hri.getTable(), SPLITKEY, null); 308 HStoreFile f = new HStoreFile(fs, linkFilePath, testConf, cacheConf, BloomType.NONE, true); 309 f.initReader(); 310 Path pathA = splitStoreFile(cloneRegionFs, splitHriA, TEST_FAMILY, f, SPLITKEY, true); // top 311 Path pathB = splitStoreFile(cloneRegionFs, splitHriB, TEST_FAMILY, f, SPLITKEY, false);// bottom 312 f.closeStoreFile(true); 313 // OK test the thing 314 FSUtils.logFileSystemState(fs, testDir, LOG); 315 316 // There is a case where a file with the hfilelink pattern is actually a daughter 317 // reference to a hfile link. This code in StoreFile that handles this case. 318 319 // Try to open store file from link 320 HStoreFile hsfA = new HStoreFile(this.fs, pathA, testConf, cacheConf, BloomType.NONE, true); 321 hsfA.initReader(); 322 323 // Now confirm that I can read from the ref to link 324 int count = 1; 325 HFileScanner s = hsfA.getReader().getScanner(false, false); 326 s.seekTo(); 327 while (s.next()) { 328 count++; 329 } 330 assertTrue(count > 0); // read some rows here 331 332 // Try to open store file from link 333 HStoreFile hsfB = new HStoreFile(this.fs, pathB, testConf, cacheConf, BloomType.NONE, true); 334 hsfB.initReader(); 335 336 // Now confirm that I can read from the ref to link 337 HFileScanner sB = hsfB.getReader().getScanner(false, false); 338 sB.seekTo(); 339 340 //count++ as seekTo() will advance the scanner 341 count++; 342 while (sB.next()) { 343 count++; 344 } 345 346 // read the rest of the rows 347 assertEquals((LAST_CHAR - FIRST_CHAR + 1) * (LAST_CHAR - FIRST_CHAR + 1), count); 348 } 349 350 private void checkHalfHFile(final HRegionFileSystem regionFs, final HStoreFile f) 351 throws IOException { 352 f.initReader(); 353 Cell midkey = f.getReader().midKey().get(); 354 KeyValue midKV = (KeyValue)midkey; 355 byte [] midRow = CellUtil.cloneRow(midKV); 356 // Create top split. 357 HRegionInfo topHri = new HRegionInfo(regionFs.getRegionInfo().getTable(), 358 null, midRow); 359 Path topPath = splitStoreFile(regionFs, topHri, TEST_FAMILY, f, midRow, true); 360 // Create bottom split. 361 HRegionInfo bottomHri = new HRegionInfo(regionFs.getRegionInfo().getTable(), 362 midRow, null); 363 Path bottomPath = splitStoreFile(regionFs, bottomHri, TEST_FAMILY, f, midRow, false); 364 // Make readers on top and bottom. 365 HStoreFile topF = new HStoreFile(this.fs, topPath, conf, cacheConf, BloomType.NONE, true); 366 topF.initReader(); 367 StoreFileReader top = topF.getReader(); 368 HStoreFile bottomF = new HStoreFile(this.fs, bottomPath, conf, cacheConf, BloomType.NONE, true); 369 bottomF.initReader(); 370 StoreFileReader bottom = bottomF.getReader(); 371 ByteBuffer previous = null; 372 LOG.info("Midkey: " + midKV.toString()); 373 ByteBuffer bbMidkeyBytes = ByteBuffer.wrap(midKV.getKey()); 374 try { 375 // Now make two HalfMapFiles and assert they can read the full backing 376 // file, one from the top and the other from the bottom. 377 // Test bottom half first. 378 // Now test reading from the top. 379 boolean first = true; 380 ByteBuffer key = null; 381 HFileScanner topScanner = top.getScanner(false, false); 382 while ((!topScanner.isSeeked() && topScanner.seekTo()) || 383 (topScanner.isSeeked() && topScanner.next())) { 384 key = ByteBuffer.wrap(((KeyValue) topScanner.getKey()).getKey()); 385 386 if ((PrivateCellUtil.compare(topScanner.getReader().getComparator(), midKV, key.array(), 387 key.arrayOffset(), key.limit())) > 0) { 388 fail("key=" + Bytes.toStringBinary(key) + " < midkey=" + 389 midkey); 390 } 391 if (first) { 392 first = false; 393 LOG.info("First in top: " + Bytes.toString(Bytes.toBytes(key))); 394 } 395 } 396 LOG.info("Last in top: " + Bytes.toString(Bytes.toBytes(key))); 397 398 first = true; 399 HFileScanner bottomScanner = bottom.getScanner(false, false); 400 while ((!bottomScanner.isSeeked() && bottomScanner.seekTo()) || 401 bottomScanner.next()) { 402 previous = ByteBuffer.wrap(((KeyValue) bottomScanner.getKey()).getKey()); 403 key = ByteBuffer.wrap(((KeyValue) bottomScanner.getKey()).getKey()); 404 if (first) { 405 first = false; 406 LOG.info("First in bottom: " + 407 Bytes.toString(Bytes.toBytes(previous))); 408 } 409 assertTrue(key.compareTo(bbMidkeyBytes) < 0); 410 } 411 if (previous != null) { 412 LOG.info("Last in bottom: " + Bytes.toString(Bytes.toBytes(previous))); 413 } 414 // Remove references. 415 regionFs.cleanupDaughterRegion(topHri); 416 regionFs.cleanupDaughterRegion(bottomHri); 417 418 // Next test using a midkey that does not exist in the file. 419 // First, do a key that is < than first key. Ensure splits behave 420 // properly. 421 byte [] badmidkey = Bytes.toBytes(" ."); 422 assertTrue(fs.exists(f.getPath())); 423 topPath = splitStoreFile(regionFs, topHri, TEST_FAMILY, f, badmidkey, true); 424 bottomPath = splitStoreFile(regionFs, bottomHri, TEST_FAMILY, f, badmidkey, false); 425 426 assertNull(bottomPath); 427 428 topF = new HStoreFile(this.fs, topPath, conf, cacheConf, BloomType.NONE, true); 429 topF.initReader(); 430 top = topF.getReader(); 431 // Now read from the top. 432 first = true; 433 topScanner = top.getScanner(false, false); 434 KeyValue.KeyOnlyKeyValue keyOnlyKV = new KeyValue.KeyOnlyKeyValue(); 435 while ((!topScanner.isSeeked() && topScanner.seekTo()) || 436 topScanner.next()) { 437 key = ByteBuffer.wrap(((KeyValue) topScanner.getKey()).getKey()); 438 keyOnlyKV.setKey(key.array(), 0 + key.arrayOffset(), key.limit()); 439 assertTrue(PrivateCellUtil.compare(topScanner.getReader().getComparator(), keyOnlyKV, 440 badmidkey, 0, badmidkey.length) >= 0); 441 if (first) { 442 first = false; 443 KeyValue keyKV = KeyValueUtil.createKeyValueFromKey(key); 444 LOG.info("First top when key < bottom: " + keyKV); 445 String tmp = 446 Bytes.toString(keyKV.getRowArray(), keyKV.getRowOffset(), keyKV.getRowLength()); 447 for (int i = 0; i < tmp.length(); i++) { 448 assertTrue(tmp.charAt(i) == 'a'); 449 } 450 } 451 } 452 KeyValue keyKV = KeyValueUtil.createKeyValueFromKey(key); 453 LOG.info("Last top when key < bottom: " + keyKV); 454 String tmp = Bytes.toString(keyKV.getRowArray(), keyKV.getRowOffset(), keyKV.getRowLength()); 455 for (int i = 0; i < tmp.length(); i++) { 456 assertTrue(tmp.charAt(i) == 'z'); 457 } 458 // Remove references. 459 regionFs.cleanupDaughterRegion(topHri); 460 regionFs.cleanupDaughterRegion(bottomHri); 461 462 // Test when badkey is > than last key in file ('||' > 'zz'). 463 badmidkey = Bytes.toBytes("|||"); 464 topPath = splitStoreFile(regionFs,topHri, TEST_FAMILY, f, badmidkey, true); 465 bottomPath = splitStoreFile(regionFs, bottomHri, TEST_FAMILY, f, badmidkey, false); 466 assertNull(topPath); 467 468 bottomF = new HStoreFile(this.fs, bottomPath, conf, cacheConf, BloomType.NONE, true); 469 bottomF.initReader(); 470 bottom = bottomF.getReader(); 471 first = true; 472 bottomScanner = bottom.getScanner(false, false); 473 while ((!bottomScanner.isSeeked() && bottomScanner.seekTo()) || 474 bottomScanner.next()) { 475 key = ByteBuffer.wrap(((KeyValue) bottomScanner.getKey()).getKey()); 476 if (first) { 477 first = false; 478 keyKV = KeyValueUtil.createKeyValueFromKey(key); 479 LOG.info("First bottom when key > top: " + keyKV); 480 tmp = Bytes.toString(keyKV.getRowArray(), keyKV.getRowOffset(), keyKV.getRowLength()); 481 for (int i = 0; i < tmp.length(); i++) { 482 assertTrue(tmp.charAt(i) == 'a'); 483 } 484 } 485 } 486 keyKV = KeyValueUtil.createKeyValueFromKey(key); 487 LOG.info("Last bottom when key > top: " + keyKV); 488 for (int i = 0; i < tmp.length(); i++) { 489 assertTrue(Bytes.toString(keyKV.getRowArray(), keyKV.getRowOffset(), keyKV.getRowLength()) 490 .charAt(i) == 'z'); 491 } 492 } finally { 493 if (top != null) { 494 top.close(true); // evict since we are about to delete the file 495 } 496 if (bottom != null) { 497 bottom.close(true); // evict since we are about to delete the file 498 } 499 fs.delete(f.getPath(), true); 500 } 501 } 502 503 private static StoreFileScanner getStoreFileScanner(StoreFileReader reader, boolean cacheBlocks, 504 boolean pread) { 505 return reader.getStoreFileScanner(cacheBlocks, pread, false, 0, 0, false); 506 } 507 508 private static final String localFormatter = "%010d"; 509 510 private void bloomWriteRead(StoreFileWriter writer, FileSystem fs) throws Exception { 511 float err = conf.getFloat(BloomFilterFactory.IO_STOREFILE_BLOOM_ERROR_RATE, 0); 512 Path f = writer.getPath(); 513 long now = System.currentTimeMillis(); 514 for (int i = 0; i < 2000; i += 2) { 515 String row = String.format(localFormatter, i); 516 KeyValue kv = new KeyValue(Bytes.toBytes(row), Bytes.toBytes("family"), 517 Bytes.toBytes("col"), now, Bytes.toBytes("value")); 518 writer.append(kv); 519 } 520 writer.close(); 521 522 StoreFileReader reader = 523 new StoreFileReader(fs, f, cacheConf, true, new AtomicInteger(0), true, conf); 524 reader.loadFileInfo(); 525 reader.loadBloomfilter(); 526 StoreFileScanner scanner = getStoreFileScanner(reader, false, false); 527 528 // check false positives rate 529 int falsePos = 0; 530 int falseNeg = 0; 531 for (int i = 0; i < 2000; i++) { 532 String row = String.format(localFormatter, i); 533 TreeSet<byte[]> columns = new TreeSet<>(Bytes.BYTES_COMPARATOR); 534 columns.add(Bytes.toBytes("family:col")); 535 536 Scan scan = new Scan(Bytes.toBytes(row),Bytes.toBytes(row)); 537 scan.addColumn(Bytes.toBytes("family"), Bytes.toBytes("family:col")); 538 HStore store = mock(HStore.class); 539 when(store.getColumnFamilyDescriptor()) 540 .thenReturn(ColumnFamilyDescriptorBuilder.of("family")); 541 boolean exists = scanner.shouldUseScanner(scan, store, Long.MIN_VALUE); 542 if (i % 2 == 0) { 543 if (!exists) falseNeg++; 544 } else { 545 if (exists) falsePos++; 546 } 547 } 548 reader.close(true); // evict because we are about to delete the file 549 fs.delete(f, true); 550 assertEquals("False negatives: " + falseNeg, 0, falseNeg); 551 int maxFalsePos = (int) (2 * 2000 * err); 552 assertTrue("Too many false positives: " + falsePos + " (err=" + err + ", expected no more than " 553 + maxFalsePos + ")", falsePos <= maxFalsePos); 554 } 555 556 private static final int BLOCKSIZE_SMALL = 8192; 557 558 @Test 559 public void testBloomFilter() throws Exception { 560 FileSystem fs = FileSystem.getLocal(conf); 561 conf.setFloat(BloomFilterFactory.IO_STOREFILE_BLOOM_ERROR_RATE, (float) 0.01); 562 conf.setBoolean(BloomFilterFactory.IO_STOREFILE_BLOOM_ENABLED, true); 563 564 // write the file 565 Path f = new Path(ROOT_DIR, getName()); 566 HFileContext meta = new HFileContextBuilder().withBlockSize(BLOCKSIZE_SMALL) 567 .withChecksumType(CKTYPE) 568 .withBytesPerCheckSum(CKBYTES).build(); 569 // Make a store file and write data to it. 570 StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs) 571 .withFilePath(f) 572 .withBloomType(BloomType.ROW) 573 .withMaxKeyCount(2000) 574 .withFileContext(meta) 575 .build(); 576 bloomWriteRead(writer, fs); 577 } 578 579 @Test 580 public void testDeleteFamilyBloomFilter() throws Exception { 581 FileSystem fs = FileSystem.getLocal(conf); 582 conf.setFloat(BloomFilterFactory.IO_STOREFILE_BLOOM_ERROR_RATE, (float) 0.01); 583 conf.setBoolean(BloomFilterFactory.IO_STOREFILE_BLOOM_ENABLED, true); 584 float err = conf.getFloat(BloomFilterFactory.IO_STOREFILE_BLOOM_ERROR_RATE, 0); 585 586 // write the file 587 Path f = new Path(ROOT_DIR, getName()); 588 589 HFileContext meta = new HFileContextBuilder() 590 .withBlockSize(BLOCKSIZE_SMALL) 591 .withChecksumType(CKTYPE) 592 .withBytesPerCheckSum(CKBYTES).build(); 593 // Make a store file and write data to it. 594 StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs) 595 .withFilePath(f) 596 .withMaxKeyCount(2000) 597 .withFileContext(meta) 598 .build(); 599 600 // add delete family 601 long now = System.currentTimeMillis(); 602 for (int i = 0; i < 2000; i += 2) { 603 String row = String.format(localFormatter, i); 604 KeyValue kv = new KeyValue(Bytes.toBytes(row), Bytes.toBytes("family"), 605 Bytes.toBytes("col"), now, KeyValue.Type.DeleteFamily, Bytes.toBytes("value")); 606 writer.append(kv); 607 } 608 writer.close(); 609 610 StoreFileReader reader = 611 new StoreFileReader(fs, f, cacheConf, true, new AtomicInteger(0), true, conf); 612 reader.loadFileInfo(); 613 reader.loadBloomfilter(); 614 615 // check false positives rate 616 int falsePos = 0; 617 int falseNeg = 0; 618 for (int i = 0; i < 2000; i++) { 619 String row = String.format(localFormatter, i); 620 byte[] rowKey = Bytes.toBytes(row); 621 boolean exists = reader.passesDeleteFamilyBloomFilter(rowKey, 0, rowKey.length); 622 if (i % 2 == 0) { 623 if (!exists) 624 falseNeg++; 625 } else { 626 if (exists) 627 falsePos++; 628 } 629 } 630 assertEquals(1000, reader.getDeleteFamilyCnt()); 631 reader.close(true); // evict because we are about to delete the file 632 fs.delete(f, true); 633 assertEquals("False negatives: " + falseNeg, 0, falseNeg); 634 int maxFalsePos = (int) (2 * 2000 * err); 635 assertTrue("Too many false positives: " + falsePos + " (err=" + err 636 + ", expected no more than " + maxFalsePos, falsePos <= maxFalsePos); 637 } 638 639 /** 640 * Test for HBASE-8012 641 */ 642 @Test 643 public void testReseek() throws Exception { 644 // write the file 645 Path f = new Path(ROOT_DIR, getName()); 646 HFileContext meta = new HFileContextBuilder().withBlockSize(8 * 1024).build(); 647 // Make a store file and write data to it. 648 StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs) 649 .withFilePath(f) 650 .withFileContext(meta) 651 .build(); 652 653 writeStoreFile(writer); 654 writer.close(); 655 656 StoreFileReader reader = 657 new StoreFileReader(fs, f, cacheConf, true, new AtomicInteger(0), true, conf); 658 659 // Now do reseek with empty KV to position to the beginning of the file 660 661 KeyValue k = KeyValueUtil.createFirstOnRow(HConstants.EMPTY_BYTE_ARRAY); 662 StoreFileScanner s = getStoreFileScanner(reader, false, false); 663 s.reseek(k); 664 665 assertNotNull("Intial reseek should position at the beginning of the file", s.peek()); 666 } 667 668 @Test 669 public void testBloomTypes() throws Exception { 670 float err = (float) 0.01; 671 FileSystem fs = FileSystem.getLocal(conf); 672 conf.setFloat(BloomFilterFactory.IO_STOREFILE_BLOOM_ERROR_RATE, err); 673 conf.setBoolean(BloomFilterFactory.IO_STOREFILE_BLOOM_ENABLED, true); 674 675 int rowCount = 50; 676 int colCount = 10; 677 int versions = 2; 678 679 // run once using columns and once using rows 680 BloomType[] bt = {BloomType.ROWCOL, BloomType.ROW}; 681 int[] expKeys = {rowCount*colCount, rowCount}; 682 // below line deserves commentary. it is expected bloom false positives 683 // column = rowCount*2*colCount inserts 684 // row-level = only rowCount*2 inserts, but failures will be magnified by 685 // 2nd for loop for every column (2*colCount) 686 float[] expErr = {2*rowCount*colCount*err, 2*rowCount*2*colCount*err}; 687 688 for (int x : new int[]{0,1}) { 689 // write the file 690 Path f = new Path(ROOT_DIR, getName() + x); 691 HFileContext meta = new HFileContextBuilder().withBlockSize(BLOCKSIZE_SMALL) 692 .withChecksumType(CKTYPE) 693 .withBytesPerCheckSum(CKBYTES).build(); 694 // Make a store file and write data to it. 695 StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs) 696 .withFilePath(f) 697 .withBloomType(bt[x]) 698 .withMaxKeyCount(expKeys[x]) 699 .withFileContext(meta) 700 .build(); 701 702 long now = System.currentTimeMillis(); 703 for (int i = 0; i < rowCount*2; i += 2) { // rows 704 for (int j = 0; j < colCount*2; j += 2) { // column qualifiers 705 String row = String.format(localFormatter, i); 706 String col = String.format(localFormatter, j); 707 for (int k= 0; k < versions; ++k) { // versions 708 KeyValue kv = new KeyValue(Bytes.toBytes(row), Bytes.toBytes("family"), 709 Bytes.toBytes("col" + col), now-k, Bytes.toBytes(-1L)); 710 writer.append(kv); 711 } 712 } 713 } 714 writer.close(); 715 716 StoreFileReader reader = 717 new StoreFileReader(fs, f, cacheConf, true, new AtomicInteger(0), true, conf); 718 reader.loadFileInfo(); 719 reader.loadBloomfilter(); 720 StoreFileScanner scanner = getStoreFileScanner(reader, false, false); 721 assertEquals(expKeys[x], reader.generalBloomFilter.getKeyCount()); 722 723 HStore store = mock(HStore.class); 724 when(store.getColumnFamilyDescriptor()) 725 .thenReturn(ColumnFamilyDescriptorBuilder.of("family")); 726 // check false positives rate 727 int falsePos = 0; 728 int falseNeg = 0; 729 for (int i = 0; i < rowCount*2; ++i) { // rows 730 for (int j = 0; j < colCount*2; ++j) { // column qualifiers 731 String row = String.format(localFormatter, i); 732 String col = String.format(localFormatter, j); 733 TreeSet<byte[]> columns = new TreeSet<>(Bytes.BYTES_COMPARATOR); 734 columns.add(Bytes.toBytes("col" + col)); 735 736 Scan scan = new Scan(Bytes.toBytes(row),Bytes.toBytes(row)); 737 scan.addColumn(Bytes.toBytes("family"), Bytes.toBytes(("col"+col))); 738 739 boolean exists = 740 scanner.shouldUseScanner(scan, store, Long.MIN_VALUE); 741 boolean shouldRowExist = i % 2 == 0; 742 boolean shouldColExist = j % 2 == 0; 743 shouldColExist = shouldColExist || bt[x] == BloomType.ROW; 744 if (shouldRowExist && shouldColExist) { 745 if (!exists) falseNeg++; 746 } else { 747 if (exists) falsePos++; 748 } 749 } 750 } 751 reader.close(true); // evict because we are about to delete the file 752 fs.delete(f, true); 753 System.out.println(bt[x].toString()); 754 System.out.println(" False negatives: " + falseNeg); 755 System.out.println(" False positives: " + falsePos); 756 assertEquals(0, falseNeg); 757 assertTrue(falsePos < 2*expErr[x]); 758 } 759 } 760 761 @Test 762 public void testSeqIdComparator() { 763 assertOrdering(StoreFileComparators.SEQ_ID, mockStoreFile(true, 100, 1000, -1, "/foo/123"), 764 mockStoreFile(true, 100, 1000, -1, "/foo/124"), 765 mockStoreFile(true, 99, 1000, -1, "/foo/126"), 766 mockStoreFile(true, 98, 2000, -1, "/foo/126"), mockStoreFile(false, 3453, -1, 1, "/foo/1"), 767 mockStoreFile(false, 2, -1, 3, "/foo/2"), mockStoreFile(false, 1000, -1, 5, "/foo/2"), 768 mockStoreFile(false, 76, -1, 5, "/foo/3")); 769 } 770 771 /** 772 * Assert that the given comparator orders the given storefiles in the 773 * same way that they're passed. 774 */ 775 private void assertOrdering(Comparator<? super HStoreFile> comparator, HStoreFile ... sfs) { 776 ArrayList<HStoreFile> sorted = Lists.newArrayList(sfs); 777 Collections.shuffle(sorted); 778 Collections.sort(sorted, comparator); 779 LOG.debug("sfs: " + Joiner.on(",").join(sfs)); 780 LOG.debug("sorted: " + Joiner.on(",").join(sorted)); 781 assertTrue(Iterables.elementsEqual(Arrays.asList(sfs), sorted)); 782 } 783 784 /** 785 * Create a mock StoreFile with the given attributes. 786 */ 787 private HStoreFile mockStoreFile(boolean bulkLoad, 788 long size, 789 long bulkTimestamp, 790 long seqId, 791 String path) { 792 HStoreFile mock = Mockito.mock(HStoreFile.class); 793 StoreFileReader reader = Mockito.mock(StoreFileReader.class); 794 795 Mockito.doReturn(size).when(reader).length(); 796 797 Mockito.doReturn(reader).when(mock).getReader(); 798 Mockito.doReturn(bulkLoad).when(mock).isBulkLoadResult(); 799 Mockito.doReturn(OptionalLong.of(bulkTimestamp)).when(mock).getBulkLoadTimestamp(); 800 Mockito.doReturn(seqId).when(mock).getMaxSequenceId(); 801 Mockito.doReturn(new Path(path)).when(mock).getPath(); 802 String name = "mock storefile, bulkLoad=" + bulkLoad + 803 " bulkTimestamp=" + bulkTimestamp + 804 " seqId=" + seqId + 805 " path=" + path; 806 Mockito.doReturn(name).when(mock).toString(); 807 return mock; 808 } 809 810 /** 811 * Generate a list of KeyValues for testing based on given parameters 812 * @param timestamps 813 * @param numRows 814 * @param qualifier 815 * @param family 816 * @return 817 */ 818 List<KeyValue> getKeyValueSet(long[] timestamps, int numRows, 819 byte[] qualifier, byte[] family) { 820 List<KeyValue> kvList = new ArrayList<>(); 821 for (int i=1;i<=numRows;i++) { 822 byte[] b = Bytes.toBytes(i) ; 823 LOG.info(Bytes.toString(b)); 824 LOG.info(Bytes.toString(b)); 825 for (long timestamp: timestamps) 826 { 827 kvList.add(new KeyValue(b, family, qualifier, timestamp, b)); 828 } 829 } 830 return kvList; 831 } 832 833 /** 834 * Test to ensure correctness when using StoreFile with multiple timestamps 835 * @throws IOException 836 */ 837 @Test 838 public void testMultipleTimestamps() throws IOException { 839 byte[] family = Bytes.toBytes("familyname"); 840 byte[] qualifier = Bytes.toBytes("qualifier"); 841 int numRows = 10; 842 long[] timestamps = new long[] {20,10,5,1}; 843 Scan scan = new Scan(); 844 845 // Make up a directory hierarchy that has a regiondir ("7e0102") and familyname. 846 Path storedir = new Path(new Path(testDir, "7e0102"), Bytes.toString(family)); 847 Path dir = new Path(storedir, "1234567890"); 848 HFileContext meta = new HFileContextBuilder().withBlockSize(8 * 1024).build(); 849 // Make a store file and write data to it. 850 StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs) 851 .withOutputDir(dir) 852 .withFileContext(meta) 853 .build(); 854 855 List<KeyValue> kvList = getKeyValueSet(timestamps,numRows, 856 qualifier, family); 857 858 for (KeyValue kv : kvList) { 859 writer.append(kv); 860 } 861 writer.appendMetadata(0, false); 862 writer.close(); 863 864 HStoreFile hsf = new HStoreFile(this.fs, writer.getPath(), conf, cacheConf, 865 BloomType.NONE, true); 866 HStore store = mock(HStore.class); 867 when(store.getColumnFamilyDescriptor()).thenReturn(ColumnFamilyDescriptorBuilder.of(family)); 868 hsf.initReader(); 869 StoreFileReader reader = hsf.getReader(); 870 StoreFileScanner scanner = getStoreFileScanner(reader, false, false); 871 TreeSet<byte[]> columns = new TreeSet<>(Bytes.BYTES_COMPARATOR); 872 columns.add(qualifier); 873 874 scan.setTimeRange(20, 100); 875 assertTrue(scanner.shouldUseScanner(scan, store, Long.MIN_VALUE)); 876 877 scan.setTimeRange(1, 2); 878 assertTrue(scanner.shouldUseScanner(scan, store, Long.MIN_VALUE)); 879 880 scan.setTimeRange(8, 10); 881 assertTrue(scanner.shouldUseScanner(scan, store, Long.MIN_VALUE)); 882 883 // lets make sure it still works with column family time ranges 884 scan.setColumnFamilyTimeRange(family, 7, 50); 885 assertTrue(scanner.shouldUseScanner(scan, store, Long.MIN_VALUE)); 886 887 // This test relies on the timestamp range optimization 888 scan = new Scan(); 889 scan.setTimeRange(27, 50); 890 assertTrue(!scanner.shouldUseScanner(scan, store, Long.MIN_VALUE)); 891 892 // should still use the scanner because we override the family time range 893 scan = new Scan(); 894 scan.setTimeRange(27, 50); 895 scan.setColumnFamilyTimeRange(family, 7, 50); 896 assertTrue(scanner.shouldUseScanner(scan, store, Long.MIN_VALUE)); 897 898 } 899 900 @Test 901 public void testCacheOnWriteEvictOnClose() throws Exception { 902 Configuration conf = this.conf; 903 904 // Find a home for our files (regiondir ("7e0102") and familyname). 905 Path baseDir = new Path(new Path(testDir, "7e0102"),"twoCOWEOC"); 906 907 // Grab the block cache and get the initial hit/miss counts 908 BlockCache bc = new CacheConfig(conf).getBlockCache(); 909 assertNotNull(bc); 910 CacheStats cs = bc.getStats(); 911 long startHit = cs.getHitCount(); 912 long startMiss = cs.getMissCount(); 913 long startEvicted = cs.getEvictedCount(); 914 915 // Let's write a StoreFile with three blocks, with cache on write off 916 conf.setBoolean(CacheConfig.CACHE_BLOCKS_ON_WRITE_KEY, false); 917 CacheConfig cacheConf = new CacheConfig(conf); 918 Path pathCowOff = new Path(baseDir, "123456789"); 919 StoreFileWriter writer = writeStoreFile(conf, cacheConf, pathCowOff, 3); 920 HStoreFile hsf = new HStoreFile(this.fs, writer.getPath(), conf, cacheConf, 921 BloomType.NONE, true); 922 LOG.debug(hsf.getPath().toString()); 923 924 // Read this file, we should see 3 misses 925 hsf.initReader(); 926 StoreFileReader reader = hsf.getReader(); 927 reader.loadFileInfo(); 928 StoreFileScanner scanner = getStoreFileScanner(reader, true, true); 929 scanner.seek(KeyValue.LOWESTKEY); 930 while (scanner.next() != null); 931 assertEquals(startHit, cs.getHitCount()); 932 assertEquals(startMiss + 3, cs.getMissCount()); 933 assertEquals(startEvicted, cs.getEvictedCount()); 934 startMiss += 3; 935 scanner.close(); 936 reader.close(cacheConf.shouldEvictOnClose()); 937 938 // Now write a StoreFile with three blocks, with cache on write on 939 conf.setBoolean(CacheConfig.CACHE_BLOCKS_ON_WRITE_KEY, true); 940 cacheConf = new CacheConfig(conf); 941 Path pathCowOn = new Path(baseDir, "123456788"); 942 writer = writeStoreFile(conf, cacheConf, pathCowOn, 3); 943 hsf = new HStoreFile(this.fs, writer.getPath(), conf, cacheConf, 944 BloomType.NONE, true); 945 946 // Read this file, we should see 3 hits 947 hsf.initReader(); 948 reader = hsf.getReader(); 949 scanner = getStoreFileScanner(reader, true, true); 950 scanner.seek(KeyValue.LOWESTKEY); 951 while (scanner.next() != null); 952 assertEquals(startHit + 3, cs.getHitCount()); 953 assertEquals(startMiss, cs.getMissCount()); 954 assertEquals(startEvicted, cs.getEvictedCount()); 955 startHit += 3; 956 scanner.close(); 957 reader.close(cacheConf.shouldEvictOnClose()); 958 959 // Let's read back the two files to ensure the blocks exactly match 960 hsf = new HStoreFile(this.fs, pathCowOff, conf, cacheConf, BloomType.NONE, true); 961 hsf.initReader(); 962 StoreFileReader readerOne = hsf.getReader(); 963 readerOne.loadFileInfo(); 964 StoreFileScanner scannerOne = getStoreFileScanner(readerOne, true, true); 965 scannerOne.seek(KeyValue.LOWESTKEY); 966 hsf = new HStoreFile(this.fs, pathCowOn, conf, cacheConf, BloomType.NONE, true); 967 hsf.initReader(); 968 StoreFileReader readerTwo = hsf.getReader(); 969 readerTwo.loadFileInfo(); 970 StoreFileScanner scannerTwo = getStoreFileScanner(readerTwo, true, true); 971 scannerTwo.seek(KeyValue.LOWESTKEY); 972 Cell kv1 = null; 973 Cell kv2 = null; 974 while ((kv1 = scannerOne.next()) != null) { 975 kv2 = scannerTwo.next(); 976 assertTrue(kv1.equals(kv2)); 977 KeyValue keyv1 = KeyValueUtil.ensureKeyValue(kv1); 978 KeyValue keyv2 = KeyValueUtil.ensureKeyValue(kv2); 979 assertTrue(Bytes.compareTo( 980 keyv1.getBuffer(), keyv1.getKeyOffset(), keyv1.getKeyLength(), 981 keyv2.getBuffer(), keyv2.getKeyOffset(), keyv2.getKeyLength()) == 0); 982 assertTrue(Bytes.compareTo( 983 kv1.getValueArray(), kv1.getValueOffset(), kv1.getValueLength(), 984 kv2.getValueArray(), kv2.getValueOffset(), kv2.getValueLength()) == 0); 985 } 986 assertNull(scannerTwo.next()); 987 assertEquals(startHit + 6, cs.getHitCount()); 988 assertEquals(startMiss, cs.getMissCount()); 989 assertEquals(startEvicted, cs.getEvictedCount()); 990 startHit += 6; 991 scannerOne.close(); 992 readerOne.close(cacheConf.shouldEvictOnClose()); 993 scannerTwo.close(); 994 readerTwo.close(cacheConf.shouldEvictOnClose()); 995 996 // Let's close the first file with evict on close turned on 997 conf.setBoolean("hbase.rs.evictblocksonclose", true); 998 cacheConf = new CacheConfig(conf); 999 hsf = new HStoreFile(this.fs, pathCowOff, conf, cacheConf, BloomType.NONE, true); 1000 hsf.initReader(); 1001 reader = hsf.getReader(); 1002 reader.close(cacheConf.shouldEvictOnClose()); 1003 1004 // We should have 3 new evictions but the evict count stat should not change. Eviction because 1005 // of HFile invalidation is not counted along with normal evictions 1006 assertEquals(startHit, cs.getHitCount()); 1007 assertEquals(startMiss, cs.getMissCount()); 1008 assertEquals(startEvicted, cs.getEvictedCount()); 1009 1010 // Let's close the second file with evict on close turned off 1011 conf.setBoolean("hbase.rs.evictblocksonclose", false); 1012 cacheConf = new CacheConfig(conf); 1013 hsf = new HStoreFile(this.fs, pathCowOn, conf, cacheConf, BloomType.NONE, true); 1014 hsf.initReader(); 1015 reader = hsf.getReader(); 1016 reader.close(cacheConf.shouldEvictOnClose()); 1017 1018 // We expect no changes 1019 assertEquals(startHit, cs.getHitCount()); 1020 assertEquals(startMiss, cs.getMissCount()); 1021 assertEquals(startEvicted, cs.getEvictedCount()); 1022 } 1023 1024 private Path splitStoreFile(final HRegionFileSystem regionFs, final HRegionInfo hri, 1025 final String family, final HStoreFile sf, final byte[] splitKey, boolean isTopRef) 1026 throws IOException { 1027 FileSystem fs = regionFs.getFileSystem(); 1028 Path path = regionFs.splitStoreFile(hri, family, sf, splitKey, isTopRef, null); 1029 if (null == path) { 1030 return null; 1031 } 1032 Path regionDir = regionFs.commitDaughterRegion(hri); 1033 return new Path(new Path(regionDir, family), path.getName()); 1034 } 1035 1036 private StoreFileWriter writeStoreFile(Configuration conf, 1037 CacheConfig cacheConf, Path path, int numBlocks) 1038 throws IOException { 1039 // Let's put ~5 small KVs in each block, so let's make 5*numBlocks KVs 1040 int numKVs = 5 * numBlocks; 1041 List<KeyValue> kvs = new ArrayList<>(numKVs); 1042 byte [] b = Bytes.toBytes("x"); 1043 int totalSize = 0; 1044 for (int i=numKVs;i>0;i--) { 1045 KeyValue kv = new KeyValue(b, b, b, i, b); 1046 kvs.add(kv); 1047 // kv has memstoreTS 0, which takes 1 byte to store. 1048 totalSize += kv.getLength() + 1; 1049 } 1050 int blockSize = totalSize / numBlocks; 1051 HFileContext meta = new HFileContextBuilder().withBlockSize(blockSize) 1052 .withChecksumType(CKTYPE) 1053 .withBytesPerCheckSum(CKBYTES) 1054 .build(); 1055 // Make a store file and write data to it. 1056 StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs) 1057 .withFilePath(path) 1058 .withMaxKeyCount(2000) 1059 .withFileContext(meta) 1060 .build(); 1061 // We'll write N-1 KVs to ensure we don't write an extra block 1062 kvs.remove(kvs.size()-1); 1063 for (KeyValue kv : kvs) { 1064 writer.append(kv); 1065 } 1066 writer.appendMetadata(0, false); 1067 writer.close(); 1068 return writer; 1069 } 1070 1071 /** 1072 * Check if data block encoding information is saved correctly in HFile's 1073 * file info. 1074 */ 1075 @Test 1076 public void testDataBlockEncodingMetaData() throws IOException { 1077 // Make up a directory hierarchy that has a regiondir ("7e0102") and familyname. 1078 Path dir = new Path(new Path(testDir, "7e0102"), "familyname"); 1079 Path path = new Path(dir, "1234567890"); 1080 1081 DataBlockEncoding dataBlockEncoderAlgo = 1082 DataBlockEncoding.FAST_DIFF; 1083 HFileDataBlockEncoder dataBlockEncoder = 1084 new HFileDataBlockEncoderImpl( 1085 dataBlockEncoderAlgo); 1086 cacheConf = new CacheConfig(conf); 1087 HFileContext meta = new HFileContextBuilder().withBlockSize(BLOCKSIZE_SMALL) 1088 .withChecksumType(CKTYPE) 1089 .withBytesPerCheckSum(CKBYTES) 1090 .withDataBlockEncoding(dataBlockEncoderAlgo) 1091 .build(); 1092 // Make a store file and write data to it. 1093 StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs) 1094 .withFilePath(path) 1095 .withMaxKeyCount(2000) 1096 .withFileContext(meta) 1097 .build(); 1098 writer.close(); 1099 1100 HStoreFile storeFile = 1101 new HStoreFile(fs, writer.getPath(), conf, cacheConf, BloomType.NONE, true); 1102 storeFile.initReader(); 1103 StoreFileReader reader = storeFile.getReader(); 1104 1105 Map<byte[], byte[]> fileInfo = reader.loadFileInfo(); 1106 byte[] value = fileInfo.get(HFileDataBlockEncoder.DATA_BLOCK_ENCODING); 1107 assertEquals(dataBlockEncoderAlgo.getNameInBytes(), value); 1108 } 1109}