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