1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.regionserver;
20
21 import java.io.IOException;
22 import java.nio.ByteBuffer;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.TreeSet;
30
31 import org.apache.commons.logging.Log;
32 import org.apache.commons.logging.LogFactory;
33 import org.apache.hadoop.conf.Configuration;
34 import org.apache.hadoop.fs.FileSystem;
35 import org.apache.hadoop.fs.Path;
36 import org.apache.hadoop.hbase.Cell;
37 import org.apache.hadoop.hbase.HBaseTestCase;
38 import org.apache.hadoop.hbase.HBaseTestingUtility;
39 import org.apache.hadoop.hbase.HColumnDescriptor;
40 import org.apache.hadoop.hbase.HConstants;
41 import org.apache.hadoop.hbase.HRegionInfo;
42 import org.apache.hadoop.hbase.KeyValue;
43 import org.apache.hadoop.hbase.KeyValueUtil;
44 import org.apache.hadoop.hbase.testclassification.SmallTests;
45 import org.apache.hadoop.hbase.TableName;
46 import org.apache.hadoop.hbase.client.Scan;
47 import org.apache.hadoop.hbase.io.HFileLink;
48 import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
49 import org.apache.hadoop.hbase.io.hfile.BlockCache;
50 import org.apache.hadoop.hbase.io.hfile.CacheConfig;
51 import org.apache.hadoop.hbase.io.hfile.CacheStats;
52 import org.apache.hadoop.hbase.io.hfile.HFileContext;
53 import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
54 import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoder;
55 import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoderImpl;
56 import org.apache.hadoop.hbase.io.hfile.HFileScanner;
57 import org.apache.hadoop.hbase.util.BloomFilterFactory;
58 import org.apache.hadoop.hbase.util.Bytes;
59 import org.apache.hadoop.hbase.util.ChecksumType;
60 import org.apache.hadoop.hbase.util.FSUtils;
61 import org.junit.Test;
62 import org.junit.experimental.categories.Category;
63 import org.mockito.Mockito;
64
65 import com.google.common.base.Joiner;
66 import com.google.common.collect.Iterables;
67 import com.google.common.collect.Lists;
68
69 import static org.mockito.Mockito.mock;
70 import static org.mockito.Mockito.spy;
71 import static org.mockito.Mockito.when;
72
73
74
75
76 @Category(SmallTests.class)
77 public class TestStoreFile extends HBaseTestCase {
78 private static final Log LOG = LogFactory.getLog(TestStoreFile.class);
79 private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
80 private CacheConfig cacheConf = new CacheConfig(TEST_UTIL.getConfiguration());
81 private static String ROOT_DIR = TEST_UTIL.getDataTestDir("TestStoreFile").toString();
82 private static final ChecksumType CKTYPE = ChecksumType.CRC32C;
83 private static final int CKBYTES = 512;
84 private static String TEST_FAMILY = "cf";
85
86 @Override
87 public void setUp() throws Exception {
88 super.setUp();
89 }
90
91 @Override
92 public void tearDown() throws Exception {
93 super.tearDown();
94 }
95
96
97
98
99
100
101 public void testBasicHalfMapFile() throws Exception {
102 final HRegionInfo hri =
103 new HRegionInfo(TableName.valueOf("testBasicHalfMapFileTb"));
104 HRegionFileSystem regionFs = HRegionFileSystem.createRegionOnFileSystem(
105 conf, fs, new Path(this.testDir, hri.getTable().getNameAsString()), hri);
106
107 HFileContext meta = new HFileContextBuilder().withBlockSize(2*1024).build();
108 StoreFile.Writer writer = new StoreFile.WriterBuilder(conf, cacheConf, this.fs)
109 .withFilePath(regionFs.createTempName())
110 .withFileContext(meta)
111 .build();
112 writeStoreFile(writer);
113
114 Path sfPath = regionFs.commitStoreFile(TEST_FAMILY, writer.getPath());
115 StoreFile sf = new StoreFile(this.fs, sfPath, conf, cacheConf,
116 BloomType.NONE);
117 checkHalfHFile(regionFs, sf);
118 }
119
120 private void writeStoreFile(final StoreFile.Writer writer) throws IOException {
121 writeStoreFile(writer, Bytes.toBytes(getName()), Bytes.toBytes(getName()));
122 }
123
124
125 byte[] SPLITKEY = new byte[] { (LAST_CHAR + FIRST_CHAR)/2, FIRST_CHAR};
126
127
128
129
130
131
132
133 public static void writeStoreFile(final StoreFile.Writer writer, byte[] fam, byte[] qualifier)
134 throws IOException {
135 long now = System.currentTimeMillis();
136 try {
137 for (char d = FIRST_CHAR; d <= LAST_CHAR; d++) {
138 for (char e = FIRST_CHAR; e <= LAST_CHAR; e++) {
139 byte[] b = new byte[] { (byte) d, (byte) e };
140 writer.append(new KeyValue(b, fam, qualifier, now, b));
141 }
142 }
143 } finally {
144 writer.close();
145 }
146 }
147
148
149
150
151
152
153 public void testReference() throws IOException {
154 final HRegionInfo hri = new HRegionInfo(TableName.valueOf("testReferenceTb"));
155 HRegionFileSystem regionFs = HRegionFileSystem.createRegionOnFileSystem(
156 conf, fs, new Path(this.testDir, hri.getTable().getNameAsString()), hri);
157
158 HFileContext meta = new HFileContextBuilder().withBlockSize(8 * 1024).build();
159
160 StoreFile.Writer writer = new StoreFile.WriterBuilder(conf, cacheConf, this.fs)
161 .withFilePath(regionFs.createTempName())
162 .withFileContext(meta)
163 .build();
164 writeStoreFile(writer);
165
166 Path hsfPath = regionFs.commitStoreFile(TEST_FAMILY, writer.getPath());
167 StoreFile hsf = new StoreFile(this.fs, hsfPath, conf, cacheConf,
168 BloomType.NONE);
169 StoreFile.Reader reader = hsf.createReader();
170
171
172
173
174 KeyValue kv = KeyValue.createKeyValueFromKey(reader.midkey());
175 byte [] midRow = kv.getRow();
176 kv = KeyValue.createKeyValueFromKey(reader.getLastKey());
177 byte [] finalRow = kv.getRow();
178 hsf.closeReader(true);
179
180
181 HRegionInfo splitHri = new HRegionInfo(hri.getTable(), null, midRow);
182 Path refPath = splitStoreFile(regionFs, splitHri, TEST_FAMILY, hsf, midRow, true);
183 StoreFile refHsf = new StoreFile(this.fs, refPath, conf, cacheConf,
184 BloomType.NONE);
185
186
187 HFileScanner s = refHsf.createReader().getScanner(false, false);
188 for(boolean first = true; (!s.isSeeked() && s.seekTo()) || s.next();) {
189 ByteBuffer bb = s.getKey();
190 kv = KeyValue.createKeyValueFromKey(bb);
191 if (first) {
192 assertTrue(Bytes.equals(kv.getRow(), midRow));
193 first = false;
194 }
195 }
196 assertTrue(Bytes.equals(kv.getRow(), finalRow));
197 }
198
199 public void testHFileLink() throws IOException {
200 final HRegionInfo hri = new HRegionInfo(TableName.valueOf("testHFileLinkTb"));
201
202 Configuration testConf = new Configuration(this.conf);
203 FSUtils.setRootDir(testConf, this.testDir);
204 HRegionFileSystem regionFs = HRegionFileSystem.createRegionOnFileSystem(
205 testConf, fs, FSUtils.getTableDir(this.testDir, hri.getTable()), hri);
206 HFileContext meta = new HFileContextBuilder().withBlockSize(8 * 1024).build();
207
208
209 StoreFile.Writer writer = new StoreFile.WriterBuilder(conf, cacheConf, this.fs)
210 .withFilePath(regionFs.createTempName())
211 .withFileContext(meta)
212 .build();
213 writeStoreFile(writer);
214
215 Path storeFilePath = regionFs.commitStoreFile(TEST_FAMILY, writer.getPath());
216 Path dstPath = new Path(regionFs.getTableDir(), new Path("test-region", TEST_FAMILY));
217 HFileLink.create(testConf, this.fs, dstPath, hri, storeFilePath.getName());
218 Path linkFilePath = new Path(dstPath,
219 HFileLink.createHFileLinkName(hri, storeFilePath.getName()));
220
221
222 StoreFileInfo storeFileInfo = new StoreFileInfo(testConf, this.fs, linkFilePath);
223 StoreFile hsf = new StoreFile(this.fs, storeFileInfo, testConf, cacheConf,
224 BloomType.NONE);
225 assertTrue(storeFileInfo.isLink());
226
227
228 int count = 1;
229 HFileScanner s = hsf.createReader().getScanner(false, false);
230 s.seekTo();
231 while (s.next()) {
232 count++;
233 }
234 assertEquals((LAST_CHAR - FIRST_CHAR + 1) * (LAST_CHAR - FIRST_CHAR + 1), count);
235 }
236
237 @Test
238 public void testEmptyStoreFileRestrictKeyRanges() throws Exception {
239 StoreFile.Reader reader = mock(StoreFile.Reader.class);
240 Store store = mock(Store.class);
241 HColumnDescriptor hcd = mock(HColumnDescriptor.class);
242 byte[] cf = Bytes.toBytes("ty");
243 when(hcd.getName()).thenReturn(cf);
244 when(store.getFamily()).thenReturn(hcd);
245 StoreFileScanner scanner =
246 new StoreFileScanner(reader, mock(HFileScanner.class), false, false, 0, 0, false);
247 Scan scan = new Scan();
248 scan.setColumnFamilyTimeRange(cf, 0, 1);
249 assertFalse(scanner.shouldUseScanner(scan, store, 0));
250 }
251
252
253
254
255
256 public void testReferenceToHFileLink() throws IOException {
257
258 Configuration testConf = new Configuration(this.conf);
259 FSUtils.setRootDir(testConf, this.testDir);
260
261
262 HRegionInfo hri = new HRegionInfo(TableName.valueOf("_original-evil-name"));
263 HRegionFileSystem regionFs = HRegionFileSystem.createRegionOnFileSystem(
264 testConf, fs, FSUtils.getTableDir(this.testDir, hri.getTable()), hri);
265
266 HFileContext meta = new HFileContextBuilder().withBlockSize(8 * 1024).build();
267
268 StoreFile.Writer writer = new StoreFile.WriterBuilder(testConf, cacheConf, this.fs)
269 .withFilePath(regionFs.createTempName())
270 .withFileContext(meta)
271 .build();
272 writeStoreFile(writer);
273 Path storeFilePath = regionFs.commitStoreFile(TEST_FAMILY, writer.getPath());
274
275
276 HRegionInfo hriClone = new HRegionInfo(TableName.valueOf("clone"));
277 HRegionFileSystem cloneRegionFs = HRegionFileSystem.createRegionOnFileSystem(
278 testConf, fs, FSUtils.getTableDir(this.testDir, hri.getTable()),
279 hriClone);
280 Path dstPath = cloneRegionFs.getStoreDir(TEST_FAMILY);
281 HFileLink.create(testConf, this.fs, dstPath, hri, storeFilePath.getName());
282 Path linkFilePath = new Path(dstPath,
283 HFileLink.createHFileLinkName(hri, storeFilePath.getName()));
284
285
286
287
288 HRegionInfo splitHriA = new HRegionInfo(hri.getTable(), null, SPLITKEY);
289 HRegionInfo splitHriB = new HRegionInfo(hri.getTable(), SPLITKEY, null);
290 StoreFile f = new StoreFile(fs, linkFilePath, testConf, cacheConf, BloomType.NONE);
291 f.createReader();
292 Path pathA = splitStoreFile(cloneRegionFs, splitHriA, TEST_FAMILY, f, SPLITKEY, true);
293 Path pathB = splitStoreFile(cloneRegionFs, splitHriB, TEST_FAMILY, f, SPLITKEY, false);
294 f.closeReader(true);
295
296 FSUtils.logFileSystemState(fs, this.testDir, LOG);
297
298
299
300
301
302 StoreFile hsfA = new StoreFile(this.fs, pathA, testConf, cacheConf,
303 BloomType.NONE);
304
305
306 int count = 1;
307 HFileScanner s = hsfA.createReader().getScanner(false, false);
308 s.seekTo();
309 while (s.next()) {
310 count++;
311 }
312 assertTrue(count > 0);
313
314
315 StoreFile hsfB = new StoreFile(this.fs, pathB, testConf, cacheConf,
316 BloomType.NONE);
317
318
319 HFileScanner sB = hsfB.createReader().getScanner(false, false);
320 sB.seekTo();
321
322
323 count++;
324 while (sB.next()) {
325 count++;
326 }
327
328
329 assertEquals((LAST_CHAR - FIRST_CHAR + 1) * (LAST_CHAR - FIRST_CHAR + 1), count);
330 }
331
332 private void checkHalfHFile(final HRegionFileSystem regionFs, final StoreFile f)
333 throws IOException {
334 byte [] midkey = f.createReader().midkey();
335 KeyValue midKV = KeyValue.createKeyValueFromKey(midkey);
336 byte [] midRow = midKV.getRow();
337
338 HRegionInfo topHri = new HRegionInfo(regionFs.getRegionInfo().getTable(),
339 null, midRow);
340 Path topPath = splitStoreFile(regionFs, topHri, TEST_FAMILY, f, midRow, true);
341
342 HRegionInfo bottomHri = new HRegionInfo(regionFs.getRegionInfo().getTable(),
343 midRow, null);
344 Path bottomPath = splitStoreFile(regionFs, bottomHri, TEST_FAMILY, f, midRow, false);
345
346 StoreFile.Reader top = new StoreFile(
347 this.fs, topPath, conf, cacheConf, BloomType.NONE).createReader();
348 StoreFile.Reader bottom = new StoreFile(
349 this.fs, bottomPath, conf, cacheConf, BloomType.NONE).createReader();
350 ByteBuffer previous = null;
351 LOG.info("Midkey: " + midKV.toString());
352 ByteBuffer bbMidkeyBytes = ByteBuffer.wrap(midkey);
353 try {
354
355
356
357
358 boolean first = true;
359 ByteBuffer key = null;
360 HFileScanner topScanner = top.getScanner(false, false);
361 while ((!topScanner.isSeeked() && topScanner.seekTo()) ||
362 (topScanner.isSeeked() && topScanner.next())) {
363 key = topScanner.getKey();
364
365 if (topScanner.getReader().getComparator().compareFlatKey(key.array(),
366 key.arrayOffset(), key.limit(), midkey, 0, midkey.length) < 0) {
367 fail("key=" + Bytes.toStringBinary(key) + " < midkey=" +
368 Bytes.toStringBinary(midkey));
369 }
370 if (first) {
371 first = false;
372 LOG.info("First in top: " + Bytes.toString(Bytes.toBytes(key)));
373 }
374 }
375 LOG.info("Last in top: " + Bytes.toString(Bytes.toBytes(key)));
376
377 first = true;
378 HFileScanner bottomScanner = bottom.getScanner(false, false);
379 while ((!bottomScanner.isSeeked() && bottomScanner.seekTo()) ||
380 bottomScanner.next()) {
381 previous = bottomScanner.getKey();
382 key = bottomScanner.getKey();
383 if (first) {
384 first = false;
385 LOG.info("First in bottom: " +
386 Bytes.toString(Bytes.toBytes(previous)));
387 }
388 assertTrue(key.compareTo(bbMidkeyBytes) < 0);
389 }
390 if (previous != null) {
391 LOG.info("Last in bottom: " + Bytes.toString(Bytes.toBytes(previous)));
392 }
393
394 regionFs.cleanupDaughterRegion(topHri);
395 regionFs.cleanupDaughterRegion(bottomHri);
396
397
398
399
400 byte [] badmidkey = Bytes.toBytes(" .");
401 assertTrue(fs.exists(f.getPath()));
402 topPath = splitStoreFile(regionFs, topHri, TEST_FAMILY, f, badmidkey, true);
403 bottomPath = splitStoreFile(regionFs, bottomHri, TEST_FAMILY, f, badmidkey, false);
404
405 assertNull(bottomPath);
406
407 top = new StoreFile(this.fs, topPath, conf, cacheConf, BloomType.NONE).createReader();
408
409 first = true;
410 topScanner = top.getScanner(false, false);
411 while ((!topScanner.isSeeked() && topScanner.seekTo()) ||
412 topScanner.next()) {
413 key = topScanner.getKey();
414 assertTrue(topScanner.getReader().getComparator().compareFlatKey(key.array(),
415 key.arrayOffset(), key.limit(), badmidkey, 0, badmidkey.length) >= 0);
416 if (first) {
417 first = false;
418 KeyValue keyKV = KeyValue.createKeyValueFromKey(key);
419 LOG.info("First top when key < bottom: " + keyKV);
420 String tmp = Bytes.toString(keyKV.getRow());
421 for (int i = 0; i < tmp.length(); i++) {
422 assertTrue(tmp.charAt(i) == 'a');
423 }
424 }
425 }
426 KeyValue keyKV = KeyValue.createKeyValueFromKey(key);
427 LOG.info("Last top when key < bottom: " + keyKV);
428 String tmp = Bytes.toString(keyKV.getRow());
429 for (int i = 0; i < tmp.length(); i++) {
430 assertTrue(tmp.charAt(i) == 'z');
431 }
432
433 regionFs.cleanupDaughterRegion(topHri);
434 regionFs.cleanupDaughterRegion(bottomHri);
435
436
437 badmidkey = Bytes.toBytes("|||");
438 topPath = splitStoreFile(regionFs,topHri, TEST_FAMILY, f, badmidkey, true);
439 bottomPath = splitStoreFile(regionFs, bottomHri, TEST_FAMILY, f, badmidkey, false);
440 assertNull(topPath);
441 bottom = new StoreFile(this.fs, bottomPath, conf, cacheConf,
442 BloomType.NONE).createReader();
443 first = true;
444 bottomScanner = bottom.getScanner(false, false);
445 while ((!bottomScanner.isSeeked() && bottomScanner.seekTo()) ||
446 bottomScanner.next()) {
447 key = bottomScanner.getKey();
448 if (first) {
449 first = false;
450 keyKV = KeyValue.createKeyValueFromKey(key);
451 LOG.info("First bottom when key > top: " + keyKV);
452 tmp = Bytes.toString(keyKV.getRow());
453 for (int i = 0; i < tmp.length(); i++) {
454 assertTrue(tmp.charAt(i) == 'a');
455 }
456 }
457 }
458 keyKV = KeyValue.createKeyValueFromKey(key);
459 LOG.info("Last bottom when key > top: " + keyKV);
460 for (int i = 0; i < tmp.length(); i++) {
461 assertTrue(Bytes.toString(keyKV.getRow()).charAt(i) == 'z');
462 }
463 } finally {
464 if (top != null) {
465 top.close(true);
466 }
467 if (bottom != null) {
468 bottom.close(true);
469 }
470 fs.delete(f.getPath(), true);
471 }
472 }
473
474 private static StoreFileScanner getStoreFileScanner(StoreFile.Reader reader, boolean cacheBlocks,
475 boolean pread) {
476 return reader.getStoreFileScanner(cacheBlocks, pread, false, 0, 0, false);
477 }
478
479 private static final String localFormatter = "%010d";
480
481 private void bloomWriteRead(StoreFile.Writer writer, FileSystem fs) throws Exception {
482 float err = conf.getFloat(BloomFilterFactory.IO_STOREFILE_BLOOM_ERROR_RATE, 0);
483 Path f = writer.getPath();
484 long now = System.currentTimeMillis();
485 for (int i = 0; i < 2000; i += 2) {
486 String row = String.format(localFormatter, i);
487 KeyValue kv = new KeyValue(row.getBytes(), "family".getBytes(),
488 "col".getBytes(), now, "value".getBytes());
489 writer.append(kv);
490 }
491 writer.close();
492
493 StoreFile.Reader reader = new StoreFile.Reader(fs, f, cacheConf, conf);
494 reader.loadFileInfo();
495 reader.loadBloomfilter();
496 StoreFileScanner scanner = getStoreFileScanner(reader, false, false);
497
498
499 int falsePos = 0;
500 int falseNeg = 0;
501 for (int i = 0; i < 2000; i++) {
502 String row = String.format(localFormatter, i);
503 TreeSet<byte[]> columns = new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR);
504 columns.add("family:col".getBytes());
505
506 Scan scan = new Scan(row.getBytes(),row.getBytes());
507 scan.addColumn("family".getBytes(), "family:col".getBytes());
508 Store store = mock(Store.class);
509 HColumnDescriptor hcd = mock(HColumnDescriptor.class);
510 when(hcd.getName()).thenReturn(Bytes.toBytes("family"));
511 when(store.getFamily()).thenReturn(hcd);
512 boolean exists = scanner.shouldUseScanner(scan, store, Long.MIN_VALUE);
513 if (i % 2 == 0) {
514 if (!exists) falseNeg++;
515 } else {
516 if (exists) falsePos++;
517 }
518 }
519 reader.close(true);
520 fs.delete(f, true);
521 assertEquals("False negatives: " + falseNeg, 0, falseNeg);
522 int maxFalsePos = (int) (2 * 2000 * err);
523 assertTrue("Too many false positives: " + falsePos + " (err=" + err
524 + ", expected no more than " + maxFalsePos + ")",
525 falsePos <= maxFalsePos);
526 }
527
528 private static final int BLOCKSIZE_SMALL = 8192;
529
530 public void testBloomFilter() throws Exception {
531 FileSystem fs = FileSystem.getLocal(conf);
532 conf.setFloat(BloomFilterFactory.IO_STOREFILE_BLOOM_ERROR_RATE, (float) 0.01);
533 conf.setBoolean(BloomFilterFactory.IO_STOREFILE_BLOOM_ENABLED, true);
534
535
536 Path f = new Path(ROOT_DIR, getName());
537 HFileContext meta = new HFileContextBuilder().withBlockSize(BLOCKSIZE_SMALL)
538 .withChecksumType(CKTYPE)
539 .withBytesPerCheckSum(CKBYTES).build();
540
541 StoreFile.Writer writer = new StoreFile.WriterBuilder(conf, cacheConf, this.fs)
542 .withFilePath(f)
543 .withBloomType(BloomType.ROW)
544 .withMaxKeyCount(2000)
545 .withFileContext(meta)
546 .build();
547 bloomWriteRead(writer, fs);
548 }
549
550 public void testDeleteFamilyBloomFilter() throws Exception {
551 FileSystem fs = FileSystem.getLocal(conf);
552 conf.setFloat(BloomFilterFactory.IO_STOREFILE_BLOOM_ERROR_RATE, (float) 0.01);
553 conf.setBoolean(BloomFilterFactory.IO_STOREFILE_BLOOM_ENABLED, true);
554 float err = conf.getFloat(BloomFilterFactory.IO_STOREFILE_BLOOM_ERROR_RATE, 0);
555
556
557 Path f = new Path(ROOT_DIR, getName());
558
559 HFileContext meta = new HFileContextBuilder()
560 .withBlockSize(BLOCKSIZE_SMALL)
561 .withChecksumType(CKTYPE)
562 .withBytesPerCheckSum(CKBYTES).build();
563
564 StoreFile.Writer writer = new StoreFile.WriterBuilder(conf, cacheConf, this.fs)
565 .withFilePath(f)
566 .withMaxKeyCount(2000)
567 .withFileContext(meta)
568 .build();
569
570
571 long now = System.currentTimeMillis();
572 for (int i = 0; i < 2000; i += 2) {
573 String row = String.format(localFormatter, i);
574 KeyValue kv = new KeyValue(row.getBytes(), "family".getBytes(),
575 "col".getBytes(), now, KeyValue.Type.DeleteFamily, "value".getBytes());
576 writer.append(kv);
577 }
578 writer.close();
579
580 StoreFile.Reader reader = new StoreFile.Reader(fs, f, cacheConf, conf);
581 reader.loadFileInfo();
582 reader.loadBloomfilter();
583
584
585 int falsePos = 0;
586 int falseNeg = 0;
587 for (int i = 0; i < 2000; i++) {
588 String row = String.format(localFormatter, i);
589 byte[] rowKey = Bytes.toBytes(row);
590 boolean exists = reader.passesDeleteFamilyBloomFilter(rowKey, 0,
591 rowKey.length);
592 if (i % 2 == 0) {
593 if (!exists)
594 falseNeg++;
595 } else {
596 if (exists)
597 falsePos++;
598 }
599 }
600 assertEquals(1000, reader.getDeleteFamilyCnt());
601 reader.close(true);
602 fs.delete(f, true);
603 assertEquals("False negatives: " + falseNeg, 0, falseNeg);
604 int maxFalsePos = (int) (2 * 2000 * err);
605 assertTrue("Too many false positives: " + falsePos + " (err=" + err
606 + ", expected no more than " + maxFalsePos, falsePos <= maxFalsePos);
607 }
608
609
610
611
612 public void testReseek() throws Exception {
613
614 Path f = new Path(ROOT_DIR, getName());
615 HFileContext meta = new HFileContextBuilder().withBlockSize(8 * 1024).build();
616
617 StoreFile.Writer writer = new StoreFile.WriterBuilder(conf, cacheConf, this.fs)
618 .withFilePath(f)
619 .withFileContext(meta)
620 .build();
621
622 writeStoreFile(writer);
623 writer.close();
624
625 StoreFile.Reader reader = new StoreFile.Reader(fs, f, cacheConf, conf);
626
627
628
629 KeyValue k = KeyValueUtil.createFirstOnRow(HConstants.EMPTY_BYTE_ARRAY);
630 StoreFileScanner s = getStoreFileScanner(reader, false, false);
631 s.reseek(k);
632
633 assertNotNull("Intial reseek should position at the beginning of the file", s.peek());
634 }
635
636 public void testBloomTypes() throws Exception {
637 float err = (float) 0.01;
638 FileSystem fs = FileSystem.getLocal(conf);
639 conf.setFloat(BloomFilterFactory.IO_STOREFILE_BLOOM_ERROR_RATE, err);
640 conf.setBoolean(BloomFilterFactory.IO_STOREFILE_BLOOM_ENABLED, true);
641
642 int rowCount = 50;
643 int colCount = 10;
644 int versions = 2;
645
646
647 BloomType[] bt = {BloomType.ROWCOL, BloomType.ROW};
648 int[] expKeys = {rowCount*colCount, rowCount};
649
650
651
652
653 float[] expErr = {2*rowCount*colCount*err, 2*rowCount*2*colCount*err};
654
655 for (int x : new int[]{0,1}) {
656
657 Path f = new Path(ROOT_DIR, getName() + x);
658 HFileContext meta = new HFileContextBuilder().withBlockSize(BLOCKSIZE_SMALL)
659 .withChecksumType(CKTYPE)
660 .withBytesPerCheckSum(CKBYTES).build();
661
662 StoreFile.Writer writer = new StoreFile.WriterBuilder(conf, cacheConf, this.fs)
663 .withFilePath(f)
664 .withBloomType(bt[x])
665 .withMaxKeyCount(expKeys[x])
666 .withFileContext(meta)
667 .build();
668
669 long now = System.currentTimeMillis();
670 for (int i = 0; i < rowCount*2; i += 2) {
671 for (int j = 0; j < colCount*2; j += 2) {
672 String row = String.format(localFormatter, i);
673 String col = String.format(localFormatter, j);
674 for (int k= 0; k < versions; ++k) {
675 KeyValue kv = new KeyValue(row.getBytes(),
676 "family".getBytes(), ("col" + col).getBytes(),
677 now-k, Bytes.toBytes((long)-1));
678 writer.append(kv);
679 }
680 }
681 }
682 writer.close();
683
684 StoreFile.Reader reader = new StoreFile.Reader(fs, f, cacheConf, conf);
685 reader.loadFileInfo();
686 reader.loadBloomfilter();
687 StoreFileScanner scanner = getStoreFileScanner(reader, false, false);
688 assertEquals(expKeys[x], reader.generalBloomFilter.getKeyCount());
689
690 Store store = mock(Store.class);
691 HColumnDescriptor hcd = mock(HColumnDescriptor.class);
692 when(hcd.getName()).thenReturn(Bytes.toBytes("family"));
693 when(store.getFamily()).thenReturn(hcd);
694
695 int falsePos = 0;
696 int falseNeg = 0;
697 for (int i = 0; i < rowCount*2; ++i) {
698 for (int j = 0; j < colCount*2; ++j) {
699 String row = String.format(localFormatter, i);
700 String col = String.format(localFormatter, j);
701 TreeSet<byte[]> columns = new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR);
702 columns.add(("col" + col).getBytes());
703
704 Scan scan = new Scan(row.getBytes(),row.getBytes());
705 scan.addColumn("family".getBytes(), ("col"+col).getBytes());
706 boolean exists =
707 scanner.shouldUseScanner(scan, store, Long.MIN_VALUE);
708 boolean shouldRowExist = i % 2 == 0;
709 boolean shouldColExist = j % 2 == 0;
710 shouldColExist = shouldColExist || bt[x] == BloomType.ROW;
711 if (shouldRowExist && shouldColExist) {
712 if (!exists) falseNeg++;
713 } else {
714 if (exists) falsePos++;
715 }
716 }
717 }
718 reader.close(true);
719 fs.delete(f, true);
720 System.out.println(bt[x].toString());
721 System.out.println(" False negatives: " + falseNeg);
722 System.out.println(" False positives: " + falsePos);
723 assertEquals(0, falseNeg);
724 assertTrue(falsePos < 2*expErr[x]);
725 }
726 }
727
728 public void testSeqIdComparator() {
729 assertOrdering(StoreFile.Comparators.SEQ_ID, mockStoreFile(true, 100, 1000, -1, "/foo/123"),
730 mockStoreFile(true, 100, 1000, -1, "/foo/124"),
731 mockStoreFile(true, 99, 1000, -1, "/foo/126"),
732 mockStoreFile(true, 98, 2000, -1, "/foo/126"), mockStoreFile(false, 3453, -1, 1, "/foo/1"),
733 mockStoreFile(false, 2, -1, 3, "/foo/2"), mockStoreFile(false, 1000, -1, 5, "/foo/2"),
734 mockStoreFile(false, 76, -1, 5, "/foo/3"));
735 }
736
737
738
739
740
741 private void assertOrdering(Comparator<StoreFile> comparator, StoreFile ... sfs) {
742 ArrayList<StoreFile> sorted = Lists.newArrayList(sfs);
743 Collections.shuffle(sorted);
744 Collections.sort(sorted, comparator);
745 LOG.debug("sfs: " + Joiner.on(",").join(sfs));
746 LOG.debug("sorted: " + Joiner.on(",").join(sorted));
747 assertTrue(Iterables.elementsEqual(Arrays.asList(sfs), sorted));
748 }
749
750
751
752
753 private StoreFile mockStoreFile(boolean bulkLoad,
754 long size,
755 long bulkTimestamp,
756 long seqId,
757 String path) {
758 StoreFile mock = Mockito.mock(StoreFile.class);
759 StoreFile.Reader reader = Mockito.mock(StoreFile.Reader.class);
760
761 Mockito.doReturn(size).when(reader).length();
762
763 Mockito.doReturn(reader).when(mock).getReader();
764 Mockito.doReturn(bulkLoad).when(mock).isBulkLoadResult();
765 Mockito.doReturn(bulkTimestamp).when(mock).getBulkLoadTimestamp();
766 Mockito.doReturn(seqId).when(mock).getMaxSequenceId();
767 Mockito.doReturn(new Path(path)).when(mock).getPath();
768 String name = "mock storefile, bulkLoad=" + bulkLoad +
769 " bulkTimestamp=" + bulkTimestamp +
770 " seqId=" + seqId +
771 " path=" + path;
772 Mockito.doReturn(name).when(mock).toString();
773 return mock;
774 }
775
776
777
778
779
780
781
782
783
784 List<KeyValue> getKeyValueSet(long[] timestamps, int numRows,
785 byte[] qualifier, byte[] family) {
786 List<KeyValue> kvList = new ArrayList<KeyValue>();
787 for (int i=1;i<=numRows;i++) {
788 byte[] b = Bytes.toBytes(i) ;
789 LOG.info(Bytes.toString(b));
790 LOG.info(Bytes.toString(b));
791 for (long timestamp: timestamps)
792 {
793 kvList.add(new KeyValue(b, family, qualifier, timestamp, b));
794 }
795 }
796 return kvList;
797 }
798
799
800
801
802
803 public void testMultipleTimestamps() throws IOException {
804 byte[] family = Bytes.toBytes("familyname");
805 byte[] qualifier = Bytes.toBytes("qualifier");
806 int numRows = 10;
807 long[] timestamps = new long[] {20,10,5,1};
808 Scan scan = new Scan();
809
810
811 Path storedir = new Path(new Path(this.testDir, "7e0102"), "familyname");
812 Path dir = new Path(storedir, "1234567890");
813 HFileContext meta = new HFileContextBuilder().withBlockSize(8 * 1024).build();
814
815 StoreFile.Writer writer = new StoreFile.WriterBuilder(conf, cacheConf, this.fs)
816 .withOutputDir(dir)
817 .withFileContext(meta)
818 .build();
819
820 List<KeyValue> kvList = getKeyValueSet(timestamps,numRows,
821 qualifier, family);
822
823 for (KeyValue kv : kvList) {
824 writer.append(kv);
825 }
826 writer.appendMetadata(0, false);
827 writer.close();
828
829 StoreFile hsf = new StoreFile(this.fs, writer.getPath(), conf, cacheConf,
830 BloomType.NONE);
831 Store store = mock(Store.class);
832 HColumnDescriptor hcd = mock(HColumnDescriptor.class);
833 when(hcd.getName()).thenReturn(family);
834 when(store.getFamily()).thenReturn(hcd);
835 StoreFile.Reader reader = hsf.createReader();
836 StoreFileScanner scanner = getStoreFileScanner(reader, false, false);
837 TreeSet<byte[]> columns = new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR);
838 columns.add(qualifier);
839
840 scan.setTimeRange(20, 100);
841 assertTrue(scanner.shouldUseScanner(scan, store, Long.MIN_VALUE));
842
843 scan.setTimeRange(1, 2);
844
845 scan.setColumnFamilyTimeRange(family, 7, 50);
846 assertTrue(scanner.shouldUseScanner(scan, store, Long.MIN_VALUE));
847
848 scan.setTimeRange(8, 10);
849 assertTrue(scanner.shouldUseScanner(scan, store, Long.MIN_VALUE));
850
851 scan.setTimeRange(7, 50);
852 assertTrue(scanner.shouldUseScanner(scan, store, Long.MIN_VALUE));
853
854
855 scan = new Scan();
856 scan.setTimeRange(27, 50);
857 assertTrue(!scanner.shouldUseScanner(scan, store, Long.MIN_VALUE));
858
859
860 scan = new Scan();
861 scan.setTimeRange(27, 50);
862 scan.setColumnFamilyTimeRange(family, 7, 50);
863 assertTrue(scanner.shouldUseScanner(scan, store, Long.MIN_VALUE));
864
865 }
866
867 public void testCacheOnWriteEvictOnClose() throws Exception {
868 Configuration conf = this.conf;
869
870
871 Path baseDir = new Path(new Path(this.testDir, "7e0102"),"twoCOWEOC");
872
873
874 BlockCache bc = new CacheConfig(conf).getBlockCache();
875 assertNotNull(bc);
876 CacheStats cs = bc.getStats();
877 long startHit = cs.getHitCount();
878 long startMiss = cs.getMissCount();
879 long startEvicted = cs.getEvictedCount();
880
881
882 conf.setBoolean(CacheConfig.CACHE_BLOCKS_ON_WRITE_KEY, false);
883 CacheConfig cacheConf = new CacheConfig(conf);
884 Path pathCowOff = new Path(baseDir, "123456789");
885 StoreFile.Writer writer = writeStoreFile(conf, cacheConf, pathCowOff, 3);
886 StoreFile hsf = new StoreFile(this.fs, writer.getPath(), conf, cacheConf,
887 BloomType.NONE);
888 LOG.debug(hsf.getPath().toString());
889
890
891 StoreFile.Reader reader = hsf.createReader();
892 reader.loadFileInfo();
893 StoreFileScanner scanner = getStoreFileScanner(reader, true, true);
894 scanner.seek(KeyValue.LOWESTKEY);
895 while (scanner.next() != null);
896 assertEquals(startHit, cs.getHitCount());
897 assertEquals(startMiss + 3, cs.getMissCount());
898 assertEquals(startEvicted, cs.getEvictedCount());
899 startMiss += 3;
900 scanner.close();
901 reader.close(cacheConf.shouldEvictOnClose());
902
903
904 conf.setBoolean(CacheConfig.CACHE_BLOCKS_ON_WRITE_KEY, true);
905 cacheConf = new CacheConfig(conf);
906 Path pathCowOn = new Path(baseDir, "123456788");
907 writer = writeStoreFile(conf, cacheConf, pathCowOn, 3);
908 hsf = new StoreFile(this.fs, writer.getPath(), conf, cacheConf,
909 BloomType.NONE);
910
911
912 reader = hsf.createReader();
913 scanner = getStoreFileScanner(reader, true, true);
914 scanner.seek(KeyValue.LOWESTKEY);
915 while (scanner.next() != null);
916 assertEquals(startHit + 3, cs.getHitCount());
917 assertEquals(startMiss, cs.getMissCount());
918 assertEquals(startEvicted, cs.getEvictedCount());
919 startHit += 3;
920 scanner.close();
921 reader.close(cacheConf.shouldEvictOnClose());
922
923
924 hsf = new StoreFile(this.fs, pathCowOff, conf, cacheConf,
925 BloomType.NONE);
926 StoreFile.Reader readerOne = hsf.createReader();
927 readerOne.loadFileInfo();
928 StoreFileScanner scannerOne = getStoreFileScanner(readerOne, true, true);
929 scannerOne.seek(KeyValue.LOWESTKEY);
930 hsf = new StoreFile(this.fs, pathCowOn, conf, cacheConf,
931 BloomType.NONE);
932 StoreFile.Reader readerTwo = hsf.createReader();
933 readerTwo.loadFileInfo();
934 StoreFileScanner scannerTwo = getStoreFileScanner(readerTwo, true, true);
935 scannerTwo.seek(KeyValue.LOWESTKEY);
936 Cell kv1 = null;
937 Cell kv2 = null;
938 while ((kv1 = scannerOne.next()) != null) {
939 kv2 = scannerTwo.next();
940 assertTrue(kv1.equals(kv2));
941 KeyValue keyv1 = KeyValueUtil.ensureKeyValue(kv1);
942 KeyValue keyv2 = KeyValueUtil.ensureKeyValue(kv2);
943 assertTrue(Bytes.compareTo(
944 keyv1.getBuffer(), keyv1.getKeyOffset(), keyv1.getKeyLength(),
945 keyv2.getBuffer(), keyv2.getKeyOffset(), keyv2.getKeyLength()) == 0);
946 assertTrue(Bytes.compareTo(
947 kv1.getValueArray(), kv1.getValueOffset(), kv1.getValueLength(),
948 kv2.getValueArray(), kv2.getValueOffset(), kv2.getValueLength()) == 0);
949 }
950 assertNull(scannerTwo.next());
951 assertEquals(startHit + 6, cs.getHitCount());
952 assertEquals(startMiss, cs.getMissCount());
953 assertEquals(startEvicted, cs.getEvictedCount());
954 startHit += 6;
955 scannerOne.close();
956 readerOne.close(cacheConf.shouldEvictOnClose());
957 scannerTwo.close();
958 readerTwo.close(cacheConf.shouldEvictOnClose());
959
960
961 conf.setBoolean("hbase.rs.evictblocksonclose", true);
962 cacheConf = new CacheConfig(conf);
963 hsf = new StoreFile(this.fs, pathCowOff, conf, cacheConf,
964 BloomType.NONE);
965 reader = hsf.createReader();
966 reader.close(cacheConf.shouldEvictOnClose());
967
968
969 assertEquals(startHit, cs.getHitCount());
970 assertEquals(startMiss, cs.getMissCount());
971 assertEquals(startEvicted + 3, cs.getEvictedCount());
972 startEvicted += 3;
973
974
975 conf.setBoolean("hbase.rs.evictblocksonclose", false);
976 cacheConf = new CacheConfig(conf);
977 hsf = new StoreFile(this.fs, pathCowOn, conf, cacheConf,
978 BloomType.NONE);
979 reader = hsf.createReader();
980 reader.close(cacheConf.shouldEvictOnClose());
981
982
983 assertEquals(startHit, cs.getHitCount());
984 assertEquals(startMiss, cs.getMissCount());
985 assertEquals(startEvicted, cs.getEvictedCount());
986 }
987
988 private Path splitStoreFile(final HRegionFileSystem regionFs, final HRegionInfo hri,
989 final String family, final StoreFile sf, final byte[] splitKey, boolean isTopRef)
990 throws IOException {
991 FileSystem fs = regionFs.getFileSystem();
992 Path path = regionFs.splitStoreFile(hri, family, sf, splitKey, isTopRef, null);
993 if (null == path) {
994 return null;
995 }
996 Path regionDir = regionFs.commitDaughterRegion(hri);
997 return new Path(new Path(regionDir, family), path.getName());
998 }
999
1000 private StoreFile.Writer writeStoreFile(Configuration conf,
1001 CacheConfig cacheConf, Path path, int numBlocks)
1002 throws IOException {
1003
1004 int numKVs = 5 * numBlocks;
1005 List<KeyValue> kvs = new ArrayList<KeyValue>(numKVs);
1006 byte [] b = Bytes.toBytes("x");
1007 int totalSize = 0;
1008 for (int i=numKVs;i>0;i--) {
1009 KeyValue kv = new KeyValue(b, b, b, i, b);
1010 kvs.add(kv);
1011
1012 totalSize += kv.getLength() + 1;
1013 }
1014 int blockSize = totalSize / numBlocks;
1015 HFileContext meta = new HFileContextBuilder().withBlockSize(blockSize)
1016 .withChecksumType(CKTYPE)
1017 .withBytesPerCheckSum(CKBYTES)
1018 .build();
1019
1020 StoreFile.Writer writer = new StoreFile.WriterBuilder(conf, cacheConf, this.fs)
1021 .withFilePath(path)
1022 .withMaxKeyCount(2000)
1023 .withFileContext(meta)
1024 .build();
1025
1026 kvs.remove(kvs.size()-1);
1027 for (KeyValue kv : kvs) {
1028 writer.append(kv);
1029 }
1030 writer.appendMetadata(0, false);
1031 writer.close();
1032 return writer;
1033 }
1034
1035
1036
1037
1038
1039 public void testDataBlockEncodingMetaData() throws IOException {
1040
1041 Path dir = new Path(new Path(this.testDir, "7e0102"), "familyname");
1042 Path path = new Path(dir, "1234567890");
1043
1044 DataBlockEncoding dataBlockEncoderAlgo =
1045 DataBlockEncoding.FAST_DIFF;
1046 cacheConf = new CacheConfig(conf);
1047 HFileContext meta = new HFileContextBuilder().withBlockSize(BLOCKSIZE_SMALL)
1048 .withChecksumType(CKTYPE)
1049 .withBytesPerCheckSum(CKBYTES)
1050 .withDataBlockEncoding(dataBlockEncoderAlgo)
1051 .build();
1052
1053 StoreFile.Writer writer = new StoreFile.WriterBuilder(conf, cacheConf, this.fs)
1054 .withFilePath(path)
1055 .withMaxKeyCount(2000)
1056 .withFileContext(meta)
1057 .build();
1058 writer.close();
1059
1060 StoreFile storeFile = new StoreFile(fs, writer.getPath(), conf,
1061 cacheConf, BloomType.NONE);
1062 StoreFile.Reader reader = storeFile.createReader();
1063
1064 Map<byte[], byte[]> fileInfo = reader.loadFileInfo();
1065 byte[] value = fileInfo.get(HFileDataBlockEncoder.DATA_BLOCK_ENCODING);
1066 assertEquals(dataBlockEncoderAlgo.getNameInBytes(), value);
1067 }
1068 }
1069