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.lang.management.ManagementFactory;
23 import java.lang.management.MemoryMXBean;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.List;
27 import java.util.concurrent.atomic.AtomicLong;
28 import java.util.concurrent.atomic.AtomicReference;
29
30 import junit.framework.TestCase;
31
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34 import org.apache.hadoop.conf.Configuration;
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.HBaseConfiguration;
39 import org.apache.hadoop.hbase.HBaseTestingUtility;
40 import org.apache.hadoop.hbase.HColumnDescriptor;
41 import org.apache.hadoop.hbase.HConstants;
42 import org.apache.hadoop.hbase.HRegionInfo;
43 import org.apache.hadoop.hbase.HTableDescriptor;
44 import org.apache.hadoop.hbase.KeepDeletedCells;
45 import org.apache.hadoop.hbase.KeyValue;
46 import org.apache.hadoop.hbase.KeyValueTestUtil;
47 import org.apache.hadoop.hbase.KeyValueUtil;
48 import org.apache.hadoop.hbase.TableName;
49 import org.apache.hadoop.hbase.client.Scan;
50 import org.apache.hadoop.hbase.testclassification.MediumTests;
51 import org.apache.hadoop.hbase.util.Bytes;
52 import org.apache.hadoop.hbase.util.EnvironmentEdge;
53 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
54 import org.apache.hadoop.hbase.wal.WALFactory;
55 import org.junit.experimental.categories.Category;
56
57 import com.google.common.base.Joiner;
58 import com.google.common.collect.Iterables;
59 import com.google.common.collect.Lists;
60
61 import static org.mockito.Mockito.mock;
62 import static org.mockito.Mockito.when;
63
64
65 @Category(MediumTests.class)
66 public class TestDefaultMemStore extends TestCase {
67 private static final Log LOG = LogFactory.getLog(TestDefaultMemStore.class);
68 private DefaultMemStore memstore;
69 private static final int ROW_COUNT = 10;
70 private static final int QUALIFIER_COUNT = ROW_COUNT;
71 private static final byte [] FAMILY = Bytes.toBytes("column");
72 private MultiVersionConcurrencyControl mvcc;
73 private AtomicLong startSeqNum = new AtomicLong(0);
74
75 @Override
76 public void setUp() throws Exception {
77 super.setUp();
78 this.mvcc = new MultiVersionConcurrencyControl();
79 this.memstore = new DefaultMemStore();
80 }
81
82 public void testPutSameKey() {
83 byte [] bytes = Bytes.toBytes(getName());
84 KeyValue kv = new KeyValue(bytes, bytes, bytes, bytes);
85 this.memstore.add(kv);
86 byte [] other = Bytes.toBytes("somethingelse");
87 KeyValue samekey = new KeyValue(bytes, bytes, bytes, other);
88 this.memstore.add(samekey);
89 Cell found = this.memstore.cellSet.first();
90 assertEquals(1, this.memstore.cellSet.size());
91 assertTrue(Bytes.toString(found.getValue()), CellUtil.matchingValue(samekey, found));
92 }
93
94 public void testPutSameCell() {
95 byte[] bytes = Bytes.toBytes(getName());
96 KeyValue kv = new KeyValue(bytes, bytes, bytes, bytes);
97 long sizeChangeForFirstCell = this.memstore.add(kv);
98 long sizeChangeForSecondCell = this.memstore.add(kv);
99
100 assertEquals(DefaultMemStore.heapSizeChange(kv, true), sizeChangeForFirstCell);
101 if (this.memstore.allocator != null) {
102
103 assertEquals(memstore.getCellLength(kv), sizeChangeForSecondCell);
104
105 if (this.memstore.allocator instanceof HeapMemStoreLAB) {
106 assertEquals(2 * memstore.getCellLength(kv),
107 ((HeapMemStoreLAB) this.memstore.allocator).getCurrentChunk().getNextFreeOffset());
108 }
109 } else {
110
111 assertEquals(0, sizeChangeForSecondCell);
112 }
113 }
114
115
116
117
118
119 public void testScanAcrossSnapshot() throws IOException {
120 int rowCount = addRows(this.memstore);
121 List<KeyValueScanner> memstorescanners = this.memstore.getScanners(0);
122 Scan scan = new Scan();
123 List<Cell> result = new ArrayList<Cell>();
124 Configuration conf = HBaseConfiguration.create();
125 ScanInfo scanInfo =
126 new ScanInfo(conf, null, 0, 1, HConstants.LATEST_TIMESTAMP, KeepDeletedCells.FALSE, 0,
127 this.memstore.comparator);
128 ScanType scanType = ScanType.USER_SCAN;
129 StoreScanner s = new StoreScanner(scan, scanInfo, scanType, null, memstorescanners);
130 int count = 0;
131 try {
132 while (s.next(result)) {
133 LOG.info(result);
134 count++;
135
136 assertEquals(rowCount, result.size());
137 result.clear();
138 }
139 } finally {
140 s.close();
141 }
142 assertEquals(rowCount, count);
143 for (KeyValueScanner scanner : memstorescanners) {
144 scanner.close();
145 }
146
147 memstorescanners = this.memstore.getScanners(mvcc.getReadPoint());
148
149 s = new StoreScanner(scan, scanInfo, scanType, null, memstorescanners);
150 count = 0;
151 try {
152 while (s.next(result)) {
153 LOG.info(result);
154
155 assertTrue(CellUtil.matchingRow(result.get(0), Bytes.toBytes(count)));
156 count++;
157
158 assertEquals(rowCount, result.size());
159 if (count == 2) {
160 this.memstore.snapshot();
161 LOG.info("Snapshotted");
162 }
163 result.clear();
164 }
165 } finally {
166 s.close();
167 }
168 assertEquals(rowCount, count);
169 for (KeyValueScanner scanner : memstorescanners) {
170 scanner.close();
171 }
172 memstorescanners = this.memstore.getScanners(mvcc.getReadPoint());
173
174 long ts = System.currentTimeMillis();
175 s = new StoreScanner(scan, scanInfo, scanType, null, memstorescanners);
176 count = 0;
177 int snapshotIndex = 5;
178 try {
179 while (s.next(result)) {
180 LOG.info(result);
181
182 assertTrue(CellUtil.matchingRow(result.get(0), Bytes.toBytes(count)));
183
184 assertEquals("count=" + count + ", result=" + result, rowCount, result.size());
185 count++;
186 if (count == snapshotIndex) {
187 MemStoreSnapshot snapshot = this.memstore.snapshot();
188 this.memstore.clearSnapshot(snapshot.getId());
189
190 addRows(this.memstore, ts);
191 LOG.info("Snapshotted, cleared it and then added values (which wont be seen)");
192 }
193 result.clear();
194 }
195 } finally {
196 s.close();
197 }
198 assertEquals(rowCount, count);
199 }
200
201
202
203
204
205
206 public void testScanAcrossSnapshot2() throws IOException, CloneNotSupportedException {
207
208
209 final byte[] one = Bytes.toBytes(1);
210 final byte[] two = Bytes.toBytes(2);
211 final byte[] f = Bytes.toBytes("f");
212 final byte[] q = Bytes.toBytes("q");
213 final byte[] v = Bytes.toBytes(3);
214
215 final KeyValue kv1 = new KeyValue(one, f, q, v);
216 final KeyValue kv2 = new KeyValue(two, f, q, v);
217
218
219 this.memstore.add(kv1.clone());
220 this.memstore.add(kv2.clone());
221 verifyScanAcrossSnapshot2(kv1, kv2);
222
223
224 this.memstore.snapshot();
225 verifyScanAcrossSnapshot2(kv1, kv2);
226
227
228 this.memstore = new DefaultMemStore();
229 this.memstore.add(kv1.clone());
230 this.memstore.snapshot();
231 this.memstore.add(kv2.clone());
232 verifyScanAcrossSnapshot2(kv1, kv2);
233 }
234
235 private void verifyScanAcrossSnapshot2(KeyValue kv1, KeyValue kv2)
236 throws IOException {
237 List<KeyValueScanner> memstorescanners = this.memstore.getScanners(mvcc.getReadPoint());
238 assertEquals(1, memstorescanners.size());
239 final KeyValueScanner scanner = memstorescanners.get(0);
240 scanner.seek(KeyValueUtil.createFirstOnRow(HConstants.EMPTY_START_ROW));
241 assertEquals(kv1, scanner.next());
242 assertEquals(kv2, scanner.next());
243 assertNull(scanner.next());
244 }
245
246 private void assertScannerResults(KeyValueScanner scanner, KeyValue[] expected)
247 throws IOException {
248 scanner.seek(KeyValueUtil.createFirstOnRow(new byte[]{}));
249 List<Cell> returned = Lists.newArrayList();
250
251 while (true) {
252 Cell next = scanner.next();
253 if (next == null) break;
254 returned.add(next);
255 }
256
257 assertTrue(
258 "Got:\n" + Joiner.on("\n").join(returned) +
259 "\nExpected:\n" + Joiner.on("\n").join(expected),
260 Iterables.elementsEqual(Arrays.asList(expected), returned));
261 assertNull(scanner.peek());
262 }
263
264 public void testMemstoreConcurrentControl() throws IOException {
265 final byte[] row = Bytes.toBytes(1);
266 final byte[] f = Bytes.toBytes("family");
267 final byte[] q1 = Bytes.toBytes("q1");
268 final byte[] q2 = Bytes.toBytes("q2");
269 final byte[] v = Bytes.toBytes("value");
270
271 MultiVersionConcurrencyControl.WriteEntry w =
272 mvcc.begin();
273
274 KeyValue kv1 = new KeyValue(row, f, q1, v);
275 kv1.setSequenceId(w.getWriteNumber());
276 memstore.add(kv1);
277
278 assertTrue(this.memstore.getScanners(mvcc.getReadPoint()) == null);
279
280 mvcc.completeAndWait(w);
281
282 KeyValueScanner s = this.memstore.getScanners(mvcc.getReadPoint()).get(0);
283 assertScannerResults(s, new KeyValue[]{kv1});
284
285 w = mvcc.begin();
286 KeyValue kv2 = new KeyValue(row, f, q2, v);
287 kv2.setSequenceId(w.getWriteNumber());
288 memstore.add(kv2);
289
290 s = this.memstore.getScanners(mvcc.getReadPoint()).get(0);
291 assertScannerResults(s, new KeyValue[]{kv1});
292
293 mvcc.completeAndWait(w);
294
295 s = this.memstore.getScanners(mvcc.getReadPoint()).get(0);
296 assertScannerResults(s, new KeyValue[]{kv1, kv2});
297 }
298
299
300
301
302
303
304
305 public void testMemstoreEditsVisibilityWithSameKey() throws IOException {
306 final byte[] row = Bytes.toBytes(1);
307 final byte[] f = Bytes.toBytes("family");
308 final byte[] q1 = Bytes.toBytes("q1");
309 final byte[] q2 = Bytes.toBytes("q2");
310 final byte[] v1 = Bytes.toBytes("value1");
311 final byte[] v2 = Bytes.toBytes("value2");
312
313
314 MultiVersionConcurrencyControl.WriteEntry w =
315 mvcc.begin();
316
317 KeyValue kv11 = new KeyValue(row, f, q1, v1);
318 kv11.setSequenceId(w.getWriteNumber());
319 memstore.add(kv11);
320
321 KeyValue kv12 = new KeyValue(row, f, q2, v1);
322 kv12.setSequenceId(w.getWriteNumber());
323 memstore.add(kv12);
324 mvcc.completeAndWait(w);
325
326
327 KeyValueScanner s = this.memstore.getScanners(mvcc.getReadPoint()).get(0);
328 assertScannerResults(s, new KeyValue[]{kv11, kv12});
329
330
331 w = mvcc.begin();
332 KeyValue kv21 = new KeyValue(row, f, q1, v2);
333 kv21.setSequenceId(w.getWriteNumber());
334 memstore.add(kv21);
335
336 KeyValue kv22 = new KeyValue(row, f, q2, v2);
337 kv22.setSequenceId(w.getWriteNumber());
338 memstore.add(kv22);
339
340
341 s = this.memstore.getScanners(mvcc.getReadPoint()).get(0);
342 assertScannerResults(s, new KeyValue[]{kv11, kv12});
343
344
345 mvcc.completeAndWait(w);
346
347
348
349
350 s = this.memstore.getScanners(mvcc.getReadPoint()).get(0);
351 assertScannerResults(s, new KeyValue[]{kv21, kv11, kv22, kv12});
352 }
353
354
355
356
357
358
359 public void testMemstoreDeletesVisibilityWithSameKey() throws IOException {
360 final byte[] row = Bytes.toBytes(1);
361 final byte[] f = Bytes.toBytes("family");
362 final byte[] q1 = Bytes.toBytes("q1");
363 final byte[] q2 = Bytes.toBytes("q2");
364 final byte[] v1 = Bytes.toBytes("value1");
365
366 MultiVersionConcurrencyControl.WriteEntry w =
367 mvcc.begin();
368
369 KeyValue kv11 = new KeyValue(row, f, q1, v1);
370 kv11.setSequenceId(w.getWriteNumber());
371 memstore.add(kv11);
372
373 KeyValue kv12 = new KeyValue(row, f, q2, v1);
374 kv12.setSequenceId(w.getWriteNumber());
375 memstore.add(kv12);
376 mvcc.completeAndWait(w);
377
378
379 KeyValueScanner s = this.memstore.getScanners(mvcc.getReadPoint()).get(0);
380 assertScannerResults(s, new KeyValue[]{kv11, kv12});
381
382
383 w = mvcc.begin();
384 KeyValue kvDel = new KeyValue(row, f, q2, kv11.getTimestamp(),
385 KeyValue.Type.DeleteColumn);
386 kvDel.setSequenceId(w.getWriteNumber());
387 memstore.add(kvDel);
388
389
390 s = this.memstore.getScanners(mvcc.getReadPoint()).get(0);
391 assertScannerResults(s, new KeyValue[]{kv11, kv12});
392
393
394 mvcc.completeAndWait(w);
395
396
397 s = this.memstore.getScanners(mvcc.getReadPoint()).get(0);
398 assertScannerResults(s, new KeyValue[]{kv11, kvDel, kv12});
399 }
400
401
402 private static class ReadOwnWritesTester extends Thread {
403 static final int NUM_TRIES = 1000;
404
405 final byte[] row;
406
407 final byte[] f = Bytes.toBytes("family");
408 final byte[] q1 = Bytes.toBytes("q1");
409
410 final MultiVersionConcurrencyControl mvcc;
411 final MemStore memstore;
412 final AtomicLong startSeqNum;
413
414 AtomicReference<Throwable> caughtException;
415
416
417 public ReadOwnWritesTester(int id,
418 MemStore memstore,
419 MultiVersionConcurrencyControl mvcc,
420 AtomicReference<Throwable> caughtException,
421 AtomicLong startSeqNum)
422 {
423 this.mvcc = mvcc;
424 this.memstore = memstore;
425 this.caughtException = caughtException;
426 row = Bytes.toBytes(id);
427 this.startSeqNum = startSeqNum;
428 }
429
430 public void run() {
431 try {
432 internalRun();
433 } catch (Throwable t) {
434 caughtException.compareAndSet(null, t);
435 }
436 }
437
438 private void internalRun() throws IOException {
439 for (long i = 0; i < NUM_TRIES && caughtException.get() == null; i++) {
440 MultiVersionConcurrencyControl.WriteEntry w =
441 mvcc.begin();
442
443
444 byte[] v = Bytes.toBytes(i);
445
446 KeyValue kv = new KeyValue(row, f, q1, i, v);
447 kv.setSequenceId(w.getWriteNumber());
448 memstore.add(kv);
449 mvcc.completeAndWait(w);
450
451
452 KeyValueScanner s = this.memstore.getScanners(mvcc.getReadPoint()).get(0);
453 s.seek(kv);
454
455 Cell ret = s.next();
456 assertNotNull("Didnt find own write at all", ret);
457 assertEquals("Didnt read own writes",
458 kv.getTimestamp(), ret.getTimestamp());
459 }
460 }
461 }
462
463 public void testReadOwnWritesUnderConcurrency() throws Throwable {
464
465 int NUM_THREADS = 8;
466
467 ReadOwnWritesTester threads[] = new ReadOwnWritesTester[NUM_THREADS];
468 AtomicReference<Throwable> caught = new AtomicReference<Throwable>();
469
470 for (int i = 0; i < NUM_THREADS; i++) {
471 threads[i] = new ReadOwnWritesTester(i, memstore, mvcc, caught, this.startSeqNum);
472 threads[i].start();
473 }
474
475 for (int i = 0; i < NUM_THREADS; i++) {
476 threads[i].join();
477 }
478
479 if (caught.get() != null) {
480 throw caught.get();
481 }
482 }
483
484
485
486
487
488 public void testSnapshotting() throws IOException {
489 final int snapshotCount = 5;
490
491 for (int i = 0; i < snapshotCount; i++) {
492 addRows(this.memstore);
493 runSnapshot(this.memstore);
494 assertEquals("History not being cleared", 0, this.memstore.snapshot.size());
495 }
496 }
497
498 public void testMultipleVersionsSimple() throws Exception {
499 DefaultMemStore m = new DefaultMemStore(new Configuration(), KeyValue.COMPARATOR);
500 byte [] row = Bytes.toBytes("testRow");
501 byte [] family = Bytes.toBytes("testFamily");
502 byte [] qf = Bytes.toBytes("testQualifier");
503 long [] stamps = {1,2,3};
504 byte [][] values = {Bytes.toBytes("value0"), Bytes.toBytes("value1"),
505 Bytes.toBytes("value2")};
506 KeyValue key0 = new KeyValue(row, family, qf, stamps[0], values[0]);
507 KeyValue key1 = new KeyValue(row, family, qf, stamps[1], values[1]);
508 KeyValue key2 = new KeyValue(row, family, qf, stamps[2], values[2]);
509
510 m.add(key0);
511 m.add(key1);
512 m.add(key2);
513
514 assertTrue("Expected memstore to hold 3 values, actually has " +
515 m.cellSet.size(), m.cellSet.size() == 3);
516 }
517
518
519
520
521
522
523
524
525 public void testGetNextRow() throws Exception {
526 addRows(this.memstore);
527
528 Thread.sleep(1);
529 addRows(this.memstore);
530 Cell closestToEmpty = this.memstore.getNextRow(KeyValue.LOWESTKEY);
531 assertTrue(KeyValue.COMPARATOR.compareRows(closestToEmpty,
532 new KeyValue(Bytes.toBytes(0), System.currentTimeMillis())) == 0);
533 for (int i = 0; i < ROW_COUNT; i++) {
534 Cell nr = this.memstore.getNextRow(new KeyValue(Bytes.toBytes(i),
535 System.currentTimeMillis()));
536 if (i + 1 == ROW_COUNT) {
537 assertEquals(nr, null);
538 } else {
539 assertTrue(KeyValue.COMPARATOR.compareRows(nr,
540 new KeyValue(Bytes.toBytes(i + 1), System.currentTimeMillis())) == 0);
541 }
542 }
543
544 Configuration conf = HBaseConfiguration.create();
545 for (int startRowId = 0; startRowId < ROW_COUNT; startRowId++) {
546 ScanInfo scanInfo = new ScanInfo(conf, FAMILY, 0, 1, Integer.MAX_VALUE,
547 KeepDeletedCells.FALSE, 0, this.memstore.comparator);
548 ScanType scanType = ScanType.USER_SCAN;
549 InternalScanner scanner = new StoreScanner(new Scan(
550 Bytes.toBytes(startRowId)), scanInfo, scanType, null,
551 memstore.getScanners(0));
552 List<Cell> results = new ArrayList<Cell>();
553 for (int i = 0; scanner.next(results); i++) {
554 int rowId = startRowId + i;
555 Cell left = results.get(0);
556 byte[] row1 = Bytes.toBytes(rowId);
557 assertTrue(
558 "Row name",
559 KeyValue.COMPARATOR.compareRows(left.getRowArray(), left.getRowOffset(),
560 (int) left.getRowLength(), row1, 0, row1.length) == 0);
561 assertEquals("Count of columns", QUALIFIER_COUNT, results.size());
562 List<Cell> row = new ArrayList<Cell>();
563 for (Cell kv : results) {
564 row.add(kv);
565 }
566 isExpectedRowWithoutTimestamps(rowId, row);
567
568 results.clear();
569 }
570 }
571 }
572
573 public void testGet_memstoreAndSnapShot() throws IOException {
574 byte [] row = Bytes.toBytes("testrow");
575 byte [] fam = Bytes.toBytes("testfamily");
576 byte [] qf1 = Bytes.toBytes("testqualifier1");
577 byte [] qf2 = Bytes.toBytes("testqualifier2");
578 byte [] qf3 = Bytes.toBytes("testqualifier3");
579 byte [] qf4 = Bytes.toBytes("testqualifier4");
580 byte [] qf5 = Bytes.toBytes("testqualifier5");
581 byte [] val = Bytes.toBytes("testval");
582
583
584 memstore.add(new KeyValue(row, fam ,qf1, val));
585 memstore.add(new KeyValue(row, fam ,qf2, val));
586 memstore.add(new KeyValue(row, fam ,qf3, val));
587
588 memstore.snapshot();
589 assertEquals(3, memstore.snapshot.size());
590
591 assertEquals(0, memstore.cellSet.size());
592 memstore.add(new KeyValue(row, fam ,qf4, val));
593 memstore.add(new KeyValue(row, fam ,qf5, val));
594 assertEquals(2, memstore.cellSet.size());
595 }
596
597
598
599
600 public void testGetWithDelete() throws IOException {
601 byte [] row = Bytes.toBytes("testrow");
602 byte [] fam = Bytes.toBytes("testfamily");
603 byte [] qf1 = Bytes.toBytes("testqualifier");
604 byte [] val = Bytes.toBytes("testval");
605
606 long ts1 = System.nanoTime();
607 KeyValue put1 = new KeyValue(row, fam, qf1, ts1, val);
608 long ts2 = ts1 + 1;
609 KeyValue put2 = new KeyValue(row, fam, qf1, ts2, val);
610 long ts3 = ts2 +1;
611 KeyValue put3 = new KeyValue(row, fam, qf1, ts3, val);
612 memstore.add(put1);
613 memstore.add(put2);
614 memstore.add(put3);
615
616 assertEquals(3, memstore.cellSet.size());
617
618 KeyValue del2 = new KeyValue(row, fam, qf1, ts2, KeyValue.Type.Delete, val);
619 memstore.delete(del2);
620
621 List<Cell> expected = new ArrayList<Cell>();
622 expected.add(put3);
623 expected.add(del2);
624 expected.add(put2);
625 expected.add(put1);
626
627 assertEquals(4, memstore.cellSet.size());
628 int i = 0;
629 for(Cell cell : memstore.cellSet) {
630 assertEquals(expected.get(i++), cell);
631 }
632 }
633
634 public void testGetWithDeleteColumn() throws IOException {
635 byte [] row = Bytes.toBytes("testrow");
636 byte [] fam = Bytes.toBytes("testfamily");
637 byte [] qf1 = Bytes.toBytes("testqualifier");
638 byte [] val = Bytes.toBytes("testval");
639
640 long ts1 = System.nanoTime();
641 KeyValue put1 = new KeyValue(row, fam, qf1, ts1, val);
642 long ts2 = ts1 + 1;
643 KeyValue put2 = new KeyValue(row, fam, qf1, ts2, val);
644 long ts3 = ts2 +1;
645 KeyValue put3 = new KeyValue(row, fam, qf1, ts3, val);
646 memstore.add(put1);
647 memstore.add(put2);
648 memstore.add(put3);
649
650 assertEquals(3, memstore.cellSet.size());
651
652 KeyValue del2 =
653 new KeyValue(row, fam, qf1, ts2, KeyValue.Type.DeleteColumn, val);
654 memstore.delete(del2);
655
656 List<Cell> expected = new ArrayList<Cell>();
657 expected.add(put3);
658 expected.add(del2);
659 expected.add(put2);
660 expected.add(put1);
661
662
663 assertEquals(4, memstore.cellSet.size());
664 int i = 0;
665 for (Cell cell: memstore.cellSet) {
666 assertEquals(expected.get(i++), cell);
667 }
668 }
669
670
671 public void testGetWithDeleteFamily() throws IOException {
672 byte [] row = Bytes.toBytes("testrow");
673 byte [] fam = Bytes.toBytes("testfamily");
674 byte [] qf1 = Bytes.toBytes("testqualifier1");
675 byte [] qf2 = Bytes.toBytes("testqualifier2");
676 byte [] qf3 = Bytes.toBytes("testqualifier3");
677 byte [] val = Bytes.toBytes("testval");
678 long ts = System.nanoTime();
679
680 KeyValue put1 = new KeyValue(row, fam, qf1, ts, val);
681 KeyValue put2 = new KeyValue(row, fam, qf2, ts, val);
682 KeyValue put3 = new KeyValue(row, fam, qf3, ts, val);
683 KeyValue put4 = new KeyValue(row, fam, qf3, ts+1, val);
684
685 memstore.add(put1);
686 memstore.add(put2);
687 memstore.add(put3);
688 memstore.add(put4);
689
690 KeyValue del =
691 new KeyValue(row, fam, null, ts, KeyValue.Type.DeleteFamily, val);
692 memstore.delete(del);
693
694 List<Cell> expected = new ArrayList<Cell>();
695 expected.add(del);
696 expected.add(put1);
697 expected.add(put2);
698 expected.add(put4);
699 expected.add(put3);
700
701
702
703 assertEquals(5, memstore.cellSet.size());
704 int i = 0;
705 for (Cell cell: memstore.cellSet) {
706 assertEquals(expected.get(i++), cell);
707 }
708 }
709
710 public void testKeepDeleteInmemstore() {
711 byte [] row = Bytes.toBytes("testrow");
712 byte [] fam = Bytes.toBytes("testfamily");
713 byte [] qf = Bytes.toBytes("testqualifier");
714 byte [] val = Bytes.toBytes("testval");
715 long ts = System.nanoTime();
716 memstore.add(new KeyValue(row, fam, qf, ts, val));
717 KeyValue delete = new KeyValue(row, fam, qf, ts, KeyValue.Type.Delete, val);
718 memstore.delete(delete);
719 assertEquals(2, memstore.cellSet.size());
720 assertEquals(delete, memstore.cellSet.first());
721 }
722
723 public void testRetainsDeleteVersion() throws IOException {
724
725 memstore.add(KeyValueTestUtil.create("row1", "fam", "a", 100, "dont-care"));
726
727
728 KeyValue delete = KeyValueTestUtil.create(
729 "row1", "fam", "a", 100, KeyValue.Type.Delete, "dont-care");
730 memstore.delete(delete);
731
732 assertEquals(2, memstore.cellSet.size());
733 assertEquals(delete, memstore.cellSet.first());
734 }
735 public void testRetainsDeleteColumn() throws IOException {
736
737 memstore.add(KeyValueTestUtil.create("row1", "fam", "a", 100, "dont-care"));
738
739
740 KeyValue delete = KeyValueTestUtil.create("row1", "fam", "a", 100,
741 KeyValue.Type.DeleteColumn, "dont-care");
742 memstore.delete(delete);
743
744 assertEquals(2, memstore.cellSet.size());
745 assertEquals(delete, memstore.cellSet.first());
746 }
747 public void testRetainsDeleteFamily() throws IOException {
748
749 memstore.add(KeyValueTestUtil.create("row1", "fam", "a", 100, "dont-care"));
750
751
752 KeyValue delete = KeyValueTestUtil.create("row1", "fam", "a", 100,
753 KeyValue.Type.DeleteFamily, "dont-care");
754 memstore.delete(delete);
755
756 assertEquals(2, memstore.cellSet.size());
757 assertEquals(delete, memstore.cellSet.first());
758 }
759
760
761
762
763
764
765
766
767 public void testMultipleTimestamps() throws Exception {
768 long[] timestamps = new long[] {20,10,5,1};
769 Scan scan = new Scan();
770
771 for (long timestamp: timestamps)
772 addRows(memstore,timestamp);
773
774 byte[] fam = Bytes.toBytes("fam");
775 HColumnDescriptor hcd = mock(HColumnDescriptor.class);
776 when(hcd.getName()).thenReturn(fam);
777 Store store = mock(Store.class);
778 when(store.getFamily()).thenReturn(hcd);
779 scan.setColumnFamilyTimeRange(fam, 0, 2);
780 assertTrue(memstore.shouldSeek(scan, store, Long.MIN_VALUE));
781
782 scan.setColumnFamilyTimeRange(fam, 20, 82);
783 assertTrue(memstore.shouldSeek(scan, store, Long.MIN_VALUE));
784
785 scan.setColumnFamilyTimeRange(fam, 10, 20);
786 assertTrue(memstore.shouldSeek(scan, store, Long.MIN_VALUE));
787
788 scan.setColumnFamilyTimeRange(fam, 8, 12);
789 assertTrue(memstore.shouldSeek(scan, store, Long.MIN_VALUE));
790
791 scan.setColumnFamilyTimeRange(fam, 28, 42);
792 assertTrue(!memstore.shouldSeek(scan, store, Long.MIN_VALUE));
793 }
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812 public void testUpsertMSLAB() throws Exception {
813 Configuration conf = HBaseConfiguration.create();
814 conf.setBoolean(DefaultMemStore.USEMSLAB_KEY, true);
815 memstore = new DefaultMemStore(conf, KeyValue.COMPARATOR);
816
817 int ROW_SIZE = 2048;
818 byte[] qualifier = new byte[ROW_SIZE - 4];
819
820 MemoryMXBean bean = ManagementFactory.getMemoryMXBean();
821 for (int i = 0; i < 3; i++) { System.gc(); }
822 long usageBefore = bean.getHeapMemoryUsage().getUsed();
823
824 long size = 0;
825 long ts=0;
826
827 for (int newValue = 0; newValue < 1000; newValue++) {
828 for (int row = newValue; row < newValue + 1000; row++) {
829 byte[] rowBytes = Bytes.toBytes(row);
830 size += memstore.updateColumnValue(rowBytes, FAMILY, qualifier, newValue, ++ts);
831 }
832 }
833 System.out.println("Wrote " + ts + " vals");
834 for (int i = 0; i < 3; i++) { System.gc(); }
835 long usageAfter = bean.getHeapMemoryUsage().getUsed();
836 System.out.println("Memory used: " + (usageAfter - usageBefore)
837 + " (heapsize: " + memstore.heapSize() +
838 " size: " + size + ")");
839 }
840
841
842
843
844 private static byte [] makeQualifier(final int i1, final int i2){
845 return Bytes.toBytes(Integer.toString(i1) + ";" +
846 Integer.toString(i2));
847 }
848
849
850
851
852
853
854 public void testUpsertMemstoreSize() throws Exception {
855 Configuration conf = HBaseConfiguration.create();
856 memstore = new DefaultMemStore(conf, KeyValue.COMPARATOR);
857 long oldSize = memstore.size.get();
858
859 List<Cell> l = new ArrayList<Cell>();
860 KeyValue kv1 = KeyValueTestUtil.create("r", "f", "q", 100, "v");
861 KeyValue kv2 = KeyValueTestUtil.create("r", "f", "q", 101, "v");
862 KeyValue kv3 = KeyValueTestUtil.create("r", "f", "q", 102, "v");
863
864 kv1.setSequenceId(1); kv2.setSequenceId(1);kv3.setSequenceId(1);
865 l.add(kv1); l.add(kv2); l.add(kv3);
866
867 this.memstore.upsert(l, 2);
868 long newSize = this.memstore.size.get();
869 assert(newSize > oldSize);
870
871 assert(memstore.cellSet.size() == 2);
872
873 KeyValue kv4 = KeyValueTestUtil.create("r", "f", "q", 104, "v");
874 kv4.setSequenceId(1);
875 l.clear(); l.add(kv4);
876 this.memstore.upsert(l, 3);
877 assertEquals(newSize, this.memstore.size.get());
878
879 assert(memstore.cellSet.size() == 2);
880
881 }
882
883
884
885
886
887
888
889
890
891
892
893 public void testUpdateToTimeOfOldestEdit() throws Exception {
894 try {
895 EnvironmentEdgeForMemstoreTest edge = new EnvironmentEdgeForMemstoreTest();
896 EnvironmentEdgeManager.injectEdge(edge);
897 DefaultMemStore memstore = new DefaultMemStore();
898 long t = memstore.timeOfOldestEdit();
899 assertEquals(t, Long.MAX_VALUE);
900
901
902 memstore.add(KeyValueTestUtil.create("r", "f", "q", 100, "v"));
903 t = memstore.timeOfOldestEdit();
904 assertTrue(t == 1234);
905
906
907 t = runSnapshot(memstore);
908
909
910 memstore.delete(KeyValueTestUtil.create("r", "f", "q", 100, "v"));
911 t = memstore.timeOfOldestEdit();
912 assertTrue(t == 1234);
913 t = runSnapshot(memstore);
914
915
916 List<Cell> l = new ArrayList<Cell>();
917 KeyValue kv1 = KeyValueTestUtil.create("r", "f", "q", 100, "v");
918 kv1.setSequenceId(100);
919 l.add(kv1);
920 memstore.upsert(l, 1000);
921 t = memstore.timeOfOldestEdit();
922 assertTrue(t == 1234);
923 } finally {
924 EnvironmentEdgeManager.reset();
925 }
926 }
927
928
929
930
931
932
933
934
935 public void testShouldFlush() throws Exception {
936 Configuration conf = new Configuration();
937 conf.setInt(HRegion.MEMSTORE_PERIODIC_FLUSH_INTERVAL, 1000);
938 checkShouldFlush(conf, true);
939
940 conf.setInt(HRegion.MEMSTORE_PERIODIC_FLUSH_INTERVAL, 0);
941 checkShouldFlush(conf, false);
942 }
943
944 private void checkShouldFlush(Configuration conf, boolean expected) throws Exception {
945 try {
946 EnvironmentEdgeForMemstoreTest edge = new EnvironmentEdgeForMemstoreTest();
947 EnvironmentEdgeManager.injectEdge(edge);
948 HBaseTestingUtility hbaseUtility = HBaseTestingUtility.createLocalHTU(conf);
949 HRegion region = hbaseUtility.createTestRegion("foobar", new HColumnDescriptor("foo"));
950
951 List<Store> stores = region.getStores();
952 assertTrue(stores.size() == 1);
953
954 Store s = stores.iterator().next();
955 edge.setCurrentTimeMillis(1234);
956 s.add(KeyValueTestUtil.create("r", "f", "q", 100, "v"));
957 edge.setCurrentTimeMillis(1234 + 100);
958 StringBuffer sb = new StringBuffer();
959 assertTrue(region.shouldFlush(sb) == false);
960 edge.setCurrentTimeMillis(1234 + 10000);
961 assertTrue(region.shouldFlush(sb) == expected);
962 } finally {
963 EnvironmentEdgeManager.reset();
964 }
965 }
966
967 public void testShouldFlushMeta() throws Exception {
968
969
970
971 Configuration conf = new Configuration();
972 conf.setInt(HRegion.MEMSTORE_PERIODIC_FLUSH_INTERVAL, HRegion.SYSTEM_CACHE_FLUSH_INTERVAL * 10);
973 HBaseTestingUtility hbaseUtility = HBaseTestingUtility.createLocalHTU(conf);
974 Path testDir = hbaseUtility.getDataTestDir();
975 EnvironmentEdgeForMemstoreTest edge = new EnvironmentEdgeForMemstoreTest();
976 EnvironmentEdgeManager.injectEdge(edge);
977 edge.setCurrentTimeMillis(1234);
978 WALFactory wFactory = new WALFactory(conf, null, "1234");
979 HRegion meta = HRegion.createHRegion(HRegionInfo.FIRST_META_REGIONINFO, testDir,
980 conf, HTableDescriptor.metaTableDescriptor(conf),
981 wFactory.getMetaWAL(HRegionInfo.FIRST_META_REGIONINFO.
982 getEncodedNameAsBytes()));
983 HRegionInfo hri = new HRegionInfo(TableName.valueOf("testShouldFlushMeta"),
984 Bytes.toBytes("row_0200"), Bytes.toBytes("row_0300"));
985 HTableDescriptor desc = new HTableDescriptor(TableName.valueOf("testShouldFlushMeta"));
986 desc.addFamily(new HColumnDescriptor("foo".getBytes()));
987 HRegion r =
988 HRegion.createHRegion(hri, testDir, conf, desc,
989 wFactory.getWAL(hri.getEncodedNameAsBytes()));
990 HRegion.addRegionToMETA(meta, r);
991 edge.setCurrentTimeMillis(1234 + 100);
992 StringBuffer sb = new StringBuffer();
993 assertTrue(meta.shouldFlush(sb) == false);
994 edge.setCurrentTimeMillis(edge.currentTime() + HRegion.SYSTEM_CACHE_FLUSH_INTERVAL + 1);
995 assertTrue(meta.shouldFlush(sb) == true);
996 }
997
998 private class EnvironmentEdgeForMemstoreTest implements EnvironmentEdge {
999 long t = 1234;
1000 @Override
1001 public long currentTime() {
1002 return t;
1003 }
1004 public void setCurrentTimeMillis(long t) {
1005 this.t = t;
1006 }
1007 }
1008
1009
1010
1011
1012
1013
1014
1015 private int addRows(final MemStore hmc) {
1016 return addRows(hmc, HConstants.LATEST_TIMESTAMP);
1017 }
1018
1019
1020
1021
1022
1023
1024
1025 private int addRows(final MemStore hmc, final long ts) {
1026 for (int i = 0; i < ROW_COUNT; i++) {
1027 long timestamp = ts == HConstants.LATEST_TIMESTAMP?
1028 System.currentTimeMillis(): ts;
1029 for (int ii = 0; ii < QUALIFIER_COUNT; ii++) {
1030 byte [] row = Bytes.toBytes(i);
1031 byte [] qf = makeQualifier(i, ii);
1032 hmc.add(new KeyValue(row, FAMILY, qf, timestamp, qf));
1033 }
1034 }
1035 return ROW_COUNT;
1036 }
1037
1038 private long runSnapshot(final DefaultMemStore hmc) throws UnexpectedStateException {
1039
1040 int oldHistorySize = hmc.snapshot.size();
1041 MemStoreSnapshot snapshot = hmc.snapshot();
1042
1043 assertTrue("History size has not increased", oldHistorySize < hmc.snapshot.size());
1044 long t = memstore.timeOfOldestEdit();
1045 assertTrue("Time of oldest edit is not Long.MAX_VALUE", t == Long.MAX_VALUE);
1046 hmc.clearSnapshot(snapshot.getId());
1047 return t;
1048 }
1049
1050 private void isExpectedRowWithoutTimestamps(final int rowIndex,
1051 List<Cell> kvs) {
1052 int i = 0;
1053 for (Cell kv: kvs) {
1054 byte[] expectedColname = makeQualifier(rowIndex, i++);
1055 assertTrue("Column name", CellUtil.matchingQualifier(kv, expectedColname));
1056
1057
1058
1059
1060 assertTrue("Content", CellUtil.matchingValue(kv, expectedColname));
1061 }
1062 }
1063
1064 private static void addRows(int count, final MemStore mem) {
1065 long nanos = System.nanoTime();
1066
1067 for (int i = 0 ; i < count ; i++) {
1068 if (i % 1000 == 0) {
1069
1070 System.out.println(i + " Took for 1k usec: " + (System.nanoTime() - nanos)/1000);
1071 nanos = System.nanoTime();
1072 }
1073 long timestamp = System.currentTimeMillis();
1074
1075 for (int ii = 0; ii < QUALIFIER_COUNT ; ii++) {
1076 byte [] row = Bytes.toBytes(i);
1077 byte [] qf = makeQualifier(i, ii);
1078 mem.add(new KeyValue(row, FAMILY, qf, timestamp, qf));
1079 }
1080 }
1081 }
1082
1083
1084 static void doScan(MemStore ms, int iteration) throws IOException {
1085 long nanos = System.nanoTime();
1086 KeyValueScanner s = ms.getScanners(0).get(0);
1087 s.seek(KeyValueUtil.createFirstOnRow(new byte[]{}));
1088
1089 System.out.println(iteration + " create/seek took: " + (System.nanoTime() - nanos)/1000);
1090 int cnt=0;
1091 while(s.next() != null) ++cnt;
1092
1093 System.out.println(iteration + " took usec: " + (System.nanoTime() - nanos) / 1000 + " for: "
1094 + cnt);
1095
1096 }
1097
1098 public static void main(String [] args) throws IOException {
1099 MemStore ms = new DefaultMemStore();
1100
1101 long n1 = System.nanoTime();
1102 addRows(25000, ms);
1103 System.out.println("Took for insert: " + (System.nanoTime()-n1)/1000);
1104
1105 System.out.println("foo");
1106
1107 for (int i = 0 ; i < 50 ; i++)
1108 doScan(ms, i);
1109 }
1110 }
1111