View Javadoc

1   /*
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
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  /** memstore test case */
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      // make sure memstore size increase won't double-count MSLAB chunk size
100     assertEquals(DefaultMemStore.heapSizeChange(kv, true), sizeChangeForFirstCell);
101     if (this.memstore.allocator != null) {
102       // make sure memstore size increased when using MSLAB
103       assertEquals(memstore.getCellLength(kv), sizeChangeForSecondCell);
104       // make sure chunk size increased even when writing the same cell, if using MSLAB
105       if (this.memstore.allocator instanceof HeapMemStoreLAB) {
106         assertEquals(2 * memstore.getCellLength(kv),
107           ((HeapMemStoreLAB) this.memstore.allocator).getCurrentChunk().getNextFreeOffset());
108       }
109     } else {
110       // make sure no memstore size change w/o MSLAB
111       assertEquals(0, sizeChangeForSecondCell);
112     }
113   }
114 
115   /**
116    * Test memstore snapshot happening while scanning.
117    * @throws IOException
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         // Row count is same as column count.
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     // Now assert can count same number even if a snapshot mid-scan.
149     s = new StoreScanner(scan, scanInfo, scanType, null, memstorescanners);
150     count = 0;
151     try {
152       while (s.next(result)) {
153         LOG.info(result);
154         // Assert the stuff is coming out in right order.
155         assertTrue(CellUtil.matchingRow(result.get(0), Bytes.toBytes(count)));
156         count++;
157         // Row count is same as column count.
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     // Assert that new values are seen in kvset as we scan.
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         // Assert the stuff is coming out in right order.
182         assertTrue(CellUtil.matchingRow(result.get(0), Bytes.toBytes(count)));
183         // Row count is same as column count.
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           // Added more rows into kvset.  But the scanner wont see these rows.
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    * A simple test which verifies the 3 possible states when scanning across snapshot.
203    * @throws IOException
204    * @throws CloneNotSupportedException 
205    */
206   public void testScanAcrossSnapshot2() throws IOException, CloneNotSupportedException {
207     // we are going to the scanning across snapshot with two kvs
208     // kv1 should always be returned before kv2
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     // use case 1: both kvs in kvset
219     this.memstore.add(kv1.clone());
220     this.memstore.add(kv2.clone());
221     verifyScanAcrossSnapshot2(kv1, kv2);
222 
223     // use case 2: both kvs in snapshot
224     this.memstore.snapshot();
225     verifyScanAcrossSnapshot2(kv1, kv2);
226 
227     // use case 3: first in snapshot second in kvset
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    * Regression test for HBASE-2616, HBASE-2670.
301    * When we insert a higher-memstoreTS version of a cell but with
302    * the same timestamp, we still need to provide consistent reads
303    * for the same scanner.
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     // INSERT 1: Write both columns val1
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     // BEFORE STARTING INSERT 2, SEE FIRST KVS
327     KeyValueScanner s = this.memstore.getScanners(mvcc.getReadPoint()).get(0);
328     assertScannerResults(s, new KeyValue[]{kv11, kv12});
329 
330     // START INSERT 2: Write both columns val2
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     // BEFORE COMPLETING INSERT 2, SEE FIRST KVS
341     s = this.memstore.getScanners(mvcc.getReadPoint()).get(0);
342     assertScannerResults(s, new KeyValue[]{kv11, kv12});
343 
344     // COMPLETE INSERT 2
345     mvcc.completeAndWait(w);
346 
347     // NOW SHOULD SEE NEW KVS IN ADDITION TO OLD KVS.
348     // See HBASE-1485 for discussion about what we should do with
349     // the duplicate-TS inserts
350     s = this.memstore.getScanners(mvcc.getReadPoint()).get(0);
351     assertScannerResults(s, new KeyValue[]{kv21, kv11, kv22, kv12});
352   }
353 
354   /**
355    * When we insert a higher-memstoreTS deletion of a cell but with
356    * the same timestamp, we still need to provide consistent reads
357    * for the same scanner.
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     // INSERT 1: Write both columns val1
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     // BEFORE STARTING INSERT 2, SEE FIRST KVS
379     KeyValueScanner s = this.memstore.getScanners(mvcc.getReadPoint()).get(0);
380     assertScannerResults(s, new KeyValue[]{kv11, kv12});
381 
382     // START DELETE: Insert delete for one of the columns
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     // BEFORE COMPLETING DELETE, SEE FIRST KVS
390     s = this.memstore.getScanners(mvcc.getReadPoint()).get(0);
391     assertScannerResults(s, new KeyValue[]{kv11, kv12});
392 
393     // COMPLETE DELETE
394     mvcc.completeAndWait(w);
395 
396     // NOW WE SHOULD SEE DELETE
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         // Insert the sequence value (i)
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         // Assert that we can read back
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    * Test memstore snapshots
486    * @throws IOException
487    */
488   public void testSnapshotting() throws IOException {
489     final int snapshotCount = 5;
490     // Add some rows, run a snapshot. Do it a few times.
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   // Get tests
520   //////////////////////////////////////////////////////////////////////////////
521 
522   /** Test getNextRow from memstore
523    * @throws InterruptedException
524    */
525   public void testGetNextRow() throws Exception {
526     addRows(this.memstore);
527     // Add more versions to make it a little more interesting.
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     //starting from each row, validate results should contain the starting row
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         // Clear out set.  Otherwise row results accumulate.
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     //Setting up memstore
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     //Creating a snapshot
588     memstore.snapshot();
589     assertEquals(3, memstore.snapshot.size());
590     //Adding value to "new" memstore
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   // Delete tests
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     // add a put to memstore
725     memstore.add(KeyValueTestUtil.create("row1", "fam", "a", 100, "dont-care"));
726 
727     // now process a specific delete:
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     // add a put to memstore
737     memstore.add(KeyValueTestUtil.create("row1", "fam", "a", 100, "dont-care"));
738 
739     // now process a specific delete:
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     // add a put to memstore
749     memstore.add(KeyValueTestUtil.create("row1", "fam", "a", 100, "dont-care"));
750 
751     // now process a specific delete:
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   //Test for timestamps
762   ////////////////////////////////////
763 
764   /**
765    * Test to ensure correctness when using Memstore with multiple timestamps
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   //Test for upsert with MSLAB
797   ////////////////////////////////////
798 
799   /**
800    * Test a pathological pattern that shows why we can't currently
801    * use the MSLAB for upsert workloads. This test inserts data
802    * in the following pattern:
803    *
804    * - row0001 through row1000 (fills up one 2M Chunk)
805    * - row0002 through row1001 (fills up another 2M chunk, leaves one reference
806    *   to the first chunk
807    * - row0003 through row1002 (another chunk, another dangling reference)
808    *
809    * This causes OOME pretty quickly if we use MSLAB for upsert
810    * since each 2M chunk is held onto by a single reference.
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   // Helpers
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    * Add keyvalues with a fixed memstoreTs, and checks that memstore size is decreased
851    * as older keyvalues are deleted from the memstore.
852    * @throws Exception
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);// readpoint is 2
868     long newSize = this.memstore.size.get();
869     assert(newSize > oldSize);
870     //The kv1 should be removed.
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     //The kv2 should be removed.
879     assert(memstore.cellSet.size() == 2);
880     //this.memstore = null;
881   }
882 
883   ////////////////////////////////////
884   // Test for periodic memstore flushes 
885   // based on time of oldest edit
886   ////////////////////////////////////
887 
888   /**
889    * Tests that the timeOfOldestEdit is updated correctly for the 
890    * various edit operations in memstore.
891    * @throws Exception
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       // test the case that the timeOfOldestEdit is updated after a KV add
902       memstore.add(KeyValueTestUtil.create("r", "f", "q", 100, "v"));
903       t = memstore.timeOfOldestEdit();
904       assertTrue(t == 1234);
905       // snapshot() will reset timeOfOldestEdit. The method will also assert the 
906       // value is reset to Long.MAX_VALUE
907       t = runSnapshot(memstore);
908 
909       // test the case that the timeOfOldestEdit is updated after a KV delete
910       memstore.delete(KeyValueTestUtil.create("r", "f", "q", 100, "v"));
911       t = memstore.timeOfOldestEdit();
912       assertTrue(t == 1234);
913       t = runSnapshot(memstore);
914 
915       // test the case that the timeOfOldestEdit is updated after a KV upsert
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    * Tests the HRegion.shouldFlush method - adds an edit in the memstore
930    * and checks that shouldFlush returns true, and another where it disables
931    * the periodic flush functionality and tests whether shouldFlush returns
932    * false. 
933    * @throws Exception
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     // test disable flush
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     // write an edit in the META and ensure the shouldFlush (that the periodic memstore
969     // flusher invokes) returns true after SYSTEM_CACHE_FLUSH_INTERVAL (even though
970     // the MEMSTORE_PERIODIC_FLUSH_INTERVAL is set to a higher value)
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    * Adds {@link #ROW_COUNT} rows and {@link #QUALIFIER_COUNT}
1011    * @param hmc Instance to add rows to.
1012    * @return How many rows we added.
1013    * @throws IOException
1014    */
1015   private int addRows(final MemStore hmc) {
1016     return addRows(hmc, HConstants.LATEST_TIMESTAMP);
1017   }
1018 
1019   /**
1020    * Adds {@link #ROW_COUNT} rows and {@link #QUALIFIER_COUNT}
1021    * @param hmc Instance to add rows to.
1022    * @return How many rows we added.
1023    * @throws IOException
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     // Save off old state.
1040     int oldHistorySize = hmc.snapshot.size();
1041     MemStoreSnapshot snapshot = hmc.snapshot();
1042     // Make some assertions about what just happened.
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       // Value is column name as bytes.  Usually result is
1057       // 100 bytes in size at least. This is the default size
1058       // for BytesWriteable.  For comparison, convert bytes to
1059       // String and trim to remove trailing null bytes.
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