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  
20  package org.apache.hadoop.hbase.regionserver;
21  
22  import static org.junit.Assert.assertNull;
23  import static org.mockito.Matchers.any;
24  import static org.mockito.Mockito.spy;
25  import static org.mockito.Mockito.times;
26  import static org.mockito.Mockito.verify;
27  
28  import java.io.IOException;
29  import java.lang.ref.SoftReference;
30  import java.security.PrivilegedExceptionAction;
31  import java.util.ArrayList;
32  import java.util.Collection;
33  import java.util.Collections;
34  import java.util.Iterator;
35  import java.util.List;
36  import java.util.ListIterator;
37  import java.util.NavigableSet;
38  import java.util.TreeSet;
39  import java.util.concurrent.ConcurrentSkipListSet;
40  import java.util.concurrent.ExecutorService;
41  import java.util.concurrent.Executors;
42  import java.util.concurrent.TimeUnit;
43  import java.util.concurrent.atomic.AtomicBoolean;
44  import org.apache.commons.logging.Log;
45  import org.apache.commons.logging.LogFactory;
46  import org.apache.hadoop.conf.Configuration;
47  import org.apache.hadoop.fs.FSDataOutputStream;
48  import org.apache.hadoop.fs.FileStatus;
49  import org.apache.hadoop.fs.FileSystem;
50  import org.apache.hadoop.fs.FilterFileSystem;
51  import org.apache.hadoop.fs.LocalFileSystem;
52  import org.apache.hadoop.fs.Path;
53  import org.apache.hadoop.fs.permission.FsPermission;
54  import org.apache.hadoop.hbase.Cell;
55  import org.apache.hadoop.hbase.CellUtil;
56  import org.apache.hadoop.hbase.HBaseConfiguration;
57  import org.apache.hadoop.hbase.HBaseTestingUtility;
58  import org.apache.hadoop.hbase.HColumnDescriptor;
59  import org.apache.hadoop.hbase.HRegionInfo;
60  import org.apache.hadoop.hbase.HTableDescriptor;
61  import org.apache.hadoop.hbase.KeyValue;
62  import org.apache.hadoop.hbase.KeyValue.KVComparator;
63  import org.apache.hadoop.hbase.KeyValueUtil;
64  import org.apache.hadoop.hbase.TableName;
65  import org.apache.hadoop.hbase.client.Get;
66  import org.apache.hadoop.hbase.client.Scan;
67  import org.apache.hadoop.hbase.io.compress.Compression;
68  import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
69  import org.apache.hadoop.hbase.io.hfile.CacheConfig;
70  import org.apache.hadoop.hbase.io.hfile.HFile;
71  import org.apache.hadoop.hbase.io.hfile.HFileContext;
72  import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
73  import org.apache.hadoop.hbase.monitoring.MonitoredTask;
74  import static org.apache.hadoop.hbase.regionserver.MemStoreChunkPool.CHUNK_POOL_MAXSIZE_KEY;
75  import org.apache.hadoop.hbase.regionserver.compactions.CompactionConfiguration;
76  import org.apache.hadoop.hbase.regionserver.compactions.DefaultCompactor;
77  import org.apache.hadoop.hbase.regionserver.throttle.NoLimitThroughputController;
78  import org.apache.hadoop.hbase.security.User;
79  import org.apache.hadoop.hbase.testclassification.MediumTests;
80  import org.apache.hadoop.hbase.util.Bytes;
81  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
82  import org.apache.hadoop.hbase.util.EnvironmentEdgeManagerTestHelper;
83  import org.apache.hadoop.hbase.util.FSUtils;
84  import org.apache.hadoop.hbase.util.IncrementingEnvironmentEdge;
85  import org.apache.hadoop.hbase.util.ManualEnvironmentEdge;
86  import org.apache.hadoop.hbase.wal.DefaultWALProvider;
87  import org.apache.hadoop.hbase.wal.WALFactory;
88  import org.apache.hadoop.util.Progressable;
89  import org.junit.After;
90  import org.junit.Assert;
91  import org.junit.Before;
92  import org.junit.Rule;
93  import org.junit.Test;
94  import org.junit.experimental.categories.Category;
95  import org.junit.rules.TestName;
96  import org.mockito.Mockito;
97  
98  import com.google.common.collect.Lists;
99  import org.apache.hadoop.hbase.filter.Filter;
100 import org.apache.hadoop.hbase.filter.FilterBase;
101 import static org.junit.Assert.assertEquals;
102 import static org.junit.Assert.assertTrue;
103 
104 /**
105  * Test class for the Store
106  */
107 @Category(MediumTests.class)
108 public class TestStore {
109   private static final Log LOG = LogFactory.getLog(TestStore.class);
110   @Rule public TestName name = new TestName();
111 
112   HStore store;
113   byte [] table = Bytes.toBytes("table");
114   byte [] family = Bytes.toBytes("family");
115 
116   byte [] row = Bytes.toBytes("row");
117   byte [] row2 = Bytes.toBytes("row2");
118   byte [] qf1 = Bytes.toBytes("qf1");
119   byte [] qf2 = Bytes.toBytes("qf2");
120   byte [] qf3 = Bytes.toBytes("qf3");
121   byte [] qf4 = Bytes.toBytes("qf4");
122   byte [] qf5 = Bytes.toBytes("qf5");
123   byte [] qf6 = Bytes.toBytes("qf6");
124 
125   NavigableSet<byte[]> qualifiers =
126     new ConcurrentSkipListSet<byte[]>(Bytes.BYTES_COMPARATOR);
127 
128   List<Cell> expected = new ArrayList<Cell>();
129   List<Cell> result = new ArrayList<Cell>();
130 
131   long id = System.currentTimeMillis();
132   Get get = new Get(row);
133 
134   private HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
135   private final String DIR = TEST_UTIL.getDataTestDir("TestStore").toString();
136 
137 
138   /**
139    * Setup
140    * @throws IOException
141    */
142   @Before
143   public void setUp() throws IOException {
144     qualifiers.add(qf1);
145     qualifiers.add(qf3);
146     qualifiers.add(qf5);
147 
148     Iterator<byte[]> iter = qualifiers.iterator();
149     while(iter.hasNext()){
150       byte [] next = iter.next();
151       expected.add(new KeyValue(row, family, next, 1, (byte[])null));
152       get.addColumn(family, next);
153     }
154   }
155 
156   private void init(String methodName) throws IOException {
157     init(methodName, TEST_UTIL.getConfiguration());
158   }
159 
160   private void init(String methodName, Configuration conf)
161   throws IOException {
162     HColumnDescriptor hcd = new HColumnDescriptor(family);
163     // some of the tests write 4 versions and then flush
164     // (with HBASE-4241, lower versions are collected on flush)
165     hcd.setMaxVersions(4);
166     init(methodName, conf, hcd);
167   }
168 
169   private void init(String methodName, Configuration conf,
170       HColumnDescriptor hcd) throws IOException {
171     HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(table));
172     init(methodName, conf, htd, hcd);
173   }
174 
175   private Store init(String methodName, Configuration conf, HTableDescriptor htd,
176       HColumnDescriptor hcd) throws IOException {
177     return init(methodName, conf, htd, hcd, null);
178   }
179 
180   @SuppressWarnings("deprecation")
181   private Store init(String methodName, Configuration conf, HTableDescriptor htd,
182       HColumnDescriptor hcd, MyStoreHook hook) throws IOException {
183     //Setting up a Store
184     Path basedir = new Path(DIR+methodName);
185     Path tableDir = FSUtils.getTableDir(basedir, htd.getTableName());
186     final Path logdir = new Path(basedir, DefaultWALProvider.getWALDirectoryName(methodName));
187 
188     FileSystem fs = FileSystem.get(conf);
189 
190     fs.delete(logdir, true);
191 
192     if (htd.hasFamily(hcd.getName())) {
193       htd.modifyFamily(hcd);
194     } else {
195       htd.addFamily(hcd);
196     }
197     HRegionInfo info = new HRegionInfo(htd.getTableName(), null, null, false);
198     final Configuration walConf = new Configuration(conf);
199     FSUtils.setRootDir(walConf, basedir);
200     final WALFactory wals = new WALFactory(walConf, null, methodName);
201     HRegion region = new HRegion(tableDir, wals.getWAL(info.getEncodedNameAsBytes(),
202             info.getTable().getNamespace()), fs, conf, info, htd, null);
203     if (hook == null) {
204       store = new HStore(region, hcd, conf);
205     } else {
206       store = new MyStore(region, hcd, conf, hook);
207     }
208     return store;
209   }
210 
211   /**
212    * Test we do not lose data if we fail a flush and then close.
213    * Part of HBase-10466
214    * @throws Exception
215    */
216   @Test
217   public void testFlushSizeAccounting() throws Exception {
218     LOG.info("Setting up a faulty file system that cannot write in " +
219       this.name.getMethodName());
220     final Configuration conf = HBaseConfiguration.create();
221     // Only retry once.
222     conf.setInt("hbase.hstore.flush.retries.number", 1);
223     User user = User.createUserForTesting(conf, this.name.getMethodName(),
224       new String[]{"foo"});
225     // Inject our faulty LocalFileSystem
226     conf.setClass("fs.file.impl", FaultyFileSystem.class, FileSystem.class);
227     user.runAs(new PrivilegedExceptionAction<Object>() {
228       @Override
229       public Object run() throws Exception {
230         // Make sure it worked (above is sensitive to caching details in hadoop core)
231         FileSystem fs = FileSystem.get(conf);
232         Assert.assertEquals(FaultyFileSystem.class, fs.getClass());
233         FaultyFileSystem ffs = (FaultyFileSystem)fs;
234 
235         // Initialize region
236         init(name.getMethodName(), conf);
237 
238         long size = store.memstore.getFlushableSize();
239         Assert.assertEquals(0, size);
240         LOG.info("Adding some data");
241         long kvSize = store.add(new KeyValue(row, family, qf1, 1, (byte[])null));
242         size = store.memstore.getFlushableSize();
243         Assert.assertEquals(kvSize, size);
244         // Flush.  Bug #1 from HBASE-10466.  Make sure size calculation on failed flush is right.
245         try {
246           LOG.info("Flushing");
247           flushStore(store, id++);
248           Assert.fail("Didn't bubble up IOE!");
249         } catch (IOException ioe) {
250           Assert.assertTrue(ioe.getMessage().contains("Fault injected"));
251         }
252         size = store.memstore.getFlushableSize();
253         Assert.assertEquals(kvSize, size);
254         store.add(new KeyValue(row, family, qf2, 2, (byte[])null));
255         // Even though we add a new kv, we expect the flushable size to be 'same' since we have
256         // not yet cleared the snapshot -- the above flush failed.
257         Assert.assertEquals(kvSize, size);
258         ffs.fault.set(false);
259         flushStore(store, id++);
260         size = store.memstore.getFlushableSize();
261         // Size should be the foreground kv size.
262         Assert.assertEquals(kvSize, size);
263         flushStore(store, id++);
264         size = store.memstore.getFlushableSize();
265         Assert.assertEquals(0, size);
266         return null;
267       }
268     });
269   }
270 
271   /**
272    * Verify that compression and data block encoding are respected by the
273    * Store.createWriterInTmp() method, used on store flush.
274    */
275   @Test
276   public void testCreateWriter() throws Exception {
277     Configuration conf = HBaseConfiguration.create();
278     FileSystem fs = FileSystem.get(conf);
279 
280     HColumnDescriptor hcd = new HColumnDescriptor(family);
281     hcd.setCompressionType(Compression.Algorithm.GZ);
282     hcd.setDataBlockEncoding(DataBlockEncoding.DIFF);
283     init(name.getMethodName(), conf, hcd);
284 
285     // Test createWriterInTmp()
286     StoreFile.Writer writer = store.createWriterInTmp(4, hcd.getCompression(), false, true, false);
287     Path path = writer.getPath();
288     writer.append(new KeyValue(row, family, qf1, Bytes.toBytes(1)));
289     writer.append(new KeyValue(row, family, qf2, Bytes.toBytes(2)));
290     writer.append(new KeyValue(row2, family, qf1, Bytes.toBytes(3)));
291     writer.append(new KeyValue(row2, family, qf2, Bytes.toBytes(4)));
292     writer.close();
293 
294     // Verify that compression and encoding settings are respected
295     HFile.Reader reader = HFile.createReader(fs, path, new CacheConfig(conf), conf);
296     Assert.assertEquals(hcd.getCompressionType(), reader.getCompressionAlgorithm());
297     Assert.assertEquals(hcd.getDataBlockEncoding(), reader.getDataBlockEncoding());
298     reader.close();
299   }
300 
301   @Test
302   public void testDeleteExpiredStoreFiles() throws Exception {
303     testDeleteExpiredStoreFiles(0);
304     testDeleteExpiredStoreFiles(1);
305   }
306 
307   /*
308    * @param minVersions the MIN_VERSIONS for the column family
309    */
310   public void testDeleteExpiredStoreFiles(int minVersions) throws Exception {
311     int storeFileNum = 4;
312     int ttl = 4;
313     IncrementingEnvironmentEdge edge = new IncrementingEnvironmentEdge();
314     EnvironmentEdgeManagerTestHelper.injectEdge(edge);
315 
316     Configuration conf = HBaseConfiguration.create();
317     // Enable the expired store file deletion
318     conf.setBoolean("hbase.store.delete.expired.storefile", true);
319     // Set the compaction threshold higher to avoid normal compactions.
320     conf.setInt(CompactionConfiguration.HBASE_HSTORE_COMPACTION_MIN_KEY, 5);
321 
322     HColumnDescriptor hcd = new HColumnDescriptor(family);
323     hcd.setMinVersions(minVersions);
324     hcd.setTimeToLive(ttl);
325     init(name.getMethodName() + "-" + minVersions, conf, hcd);
326 
327     long storeTtl = this.store.getScanInfo().getTtl();
328     long sleepTime = storeTtl / storeFileNum;
329     long timeStamp;
330     // There are 4 store files and the max time stamp difference among these
331     // store files will be (this.store.ttl / storeFileNum)
332     for (int i = 1; i <= storeFileNum; i++) {
333       LOG.info("Adding some data for the store file #" + i);
334       timeStamp = EnvironmentEdgeManager.currentTime();
335       this.store.add(new KeyValue(row, family, qf1, timeStamp, (byte[]) null));
336       this.store.add(new KeyValue(row, family, qf2, timeStamp, (byte[]) null));
337       this.store.add(new KeyValue(row, family, qf3, timeStamp, (byte[]) null));
338       flush(i);
339       edge.incrementTime(sleepTime);
340     }
341 
342     // Verify the total number of store files
343     Assert.assertEquals(storeFileNum, this.store.getStorefiles().size());
344 
345      // Each call will find one expired store file and delete it before compaction happens.
346      // There will be no compaction due to threshold above. Last file will not be replaced.
347     for (int i = 1; i <= storeFileNum - 1; i++) {
348       // verify the expired store file.
349       assertNull(this.store.requestCompaction());
350       Collection<StoreFile> sfs = this.store.getStorefiles();
351       // Ensure i files are gone.
352       if (minVersions == 0) {
353         assertEquals(storeFileNum - i, sfs.size());
354         // Ensure only non-expired files remain.
355         for (StoreFile sf : sfs) {
356           assertTrue(sf.getReader().getMaxTimestamp() >= (edge.currentTime() - storeTtl));
357         }
358       } else {
359         assertEquals(storeFileNum, sfs.size());
360       }
361       // Let the next store file expired.
362       edge.incrementTime(sleepTime);
363     }
364     assertNull(this.store.requestCompaction());
365 
366     Collection<StoreFile> sfs = this.store.getStorefiles();
367     // Assert the last expired file is not removed.
368     if (minVersions == 0) {
369       assertEquals(1, sfs.size());
370     }
371     long ts = sfs.iterator().next().getReader().getMaxTimestamp();
372     assertTrue(ts < (edge.currentTime() - storeTtl));
373 
374     for (StoreFile sf : sfs) {
375       sf.closeReader(true);
376     }
377   }
378 
379   @Test
380   public void testLowestModificationTime() throws Exception {
381     Configuration conf = HBaseConfiguration.create();
382     FileSystem fs = FileSystem.get(conf);
383     // Initialize region
384     init(name.getMethodName(), conf);
385 
386     int storeFileNum = 4;
387     for (int i = 1; i <= storeFileNum; i++) {
388       LOG.info("Adding some data for the store file #"+i);
389       this.store.add(new KeyValue(row, family, qf1, i, (byte[])null));
390       this.store.add(new KeyValue(row, family, qf2, i, (byte[])null));
391       this.store.add(new KeyValue(row, family, qf3, i, (byte[])null));
392       flush(i);
393     }
394     // after flush; check the lowest time stamp
395     long lowestTimeStampFromManager = StoreUtils.getLowestTimestamp(store.getStorefiles());
396     long lowestTimeStampFromFS = getLowestTimeStampFromFS(fs, store.getStorefiles());
397     Assert.assertEquals(lowestTimeStampFromManager,lowestTimeStampFromFS);
398 
399     // after compact; check the lowest time stamp
400     store.compact(store.requestCompaction(), NoLimitThroughputController.INSTANCE);
401     lowestTimeStampFromManager = StoreUtils.getLowestTimestamp(store.getStorefiles());
402     lowestTimeStampFromFS = getLowestTimeStampFromFS(fs, store.getStorefiles());
403     Assert.assertEquals(lowestTimeStampFromManager, lowestTimeStampFromFS);
404   }
405 
406   private static long getLowestTimeStampFromFS(FileSystem fs,
407       final Collection<StoreFile> candidates) throws IOException {
408     long minTs = Long.MAX_VALUE;
409     if (candidates.isEmpty()) {
410       return minTs;
411     }
412     Path[] p = new Path[candidates.size()];
413     int i = 0;
414     for (StoreFile sf : candidates) {
415       p[i] = sf.getPath();
416       ++i;
417     }
418 
419     FileStatus[] stats = fs.listStatus(p);
420     if (stats == null || stats.length == 0) {
421       return minTs;
422     }
423     for (FileStatus s : stats) {
424       minTs = Math.min(minTs, s.getModificationTime());
425     }
426     return minTs;
427   }
428 
429   //////////////////////////////////////////////////////////////////////////////
430   // Get tests
431   //////////////////////////////////////////////////////////////////////////////
432 
433   private static final int BLOCKSIZE_SMALL = 8192;
434   /**
435    * Test for hbase-1686.
436    * @throws IOException
437    */
438   @Test
439   public void testEmptyStoreFile() throws IOException {
440     init(this.name.getMethodName());
441     // Write a store file.
442     this.store.add(new KeyValue(row, family, qf1, 1, (byte[])null));
443     this.store.add(new KeyValue(row, family, qf2, 1, (byte[])null));
444     flush(1);
445     // Now put in place an empty store file.  Its a little tricky.  Have to
446     // do manually with hacked in sequence id.
447     StoreFile f = this.store.getStorefiles().iterator().next();
448     Path storedir = f.getPath().getParent();
449     long seqid = f.getMaxSequenceId();
450     Configuration c = HBaseConfiguration.create();
451     FileSystem fs = FileSystem.get(c);
452     HFileContext meta = new HFileContextBuilder().withBlockSize(BLOCKSIZE_SMALL).build();
453     StoreFile.Writer w = new StoreFile.WriterBuilder(c, new CacheConfig(c),
454         fs)
455             .withOutputDir(storedir)
456             .withFileContext(meta)
457             .build();
458     w.appendMetadata(seqid + 1, false);
459     w.close();
460     this.store.close();
461     // Reopen it... should pick up two files
462     this.store = new HStore(this.store.getHRegion(), this.store.getFamily(), c);
463     Assert.assertEquals(2, this.store.getStorefilesCount());
464 
465     result = HBaseTestingUtility.getFromStoreFile(store,
466         get.getRow(),
467         qualifiers);
468     Assert.assertEquals(1, result.size());
469   }
470 
471   /**
472    * Getting data from memstore only
473    * @throws IOException
474    */
475   @Test
476   public void testGet_FromMemStoreOnly() throws IOException {
477     init(this.name.getMethodName());
478 
479     //Put data in memstore
480     this.store.add(new KeyValue(row, family, qf1, 1, (byte[])null));
481     this.store.add(new KeyValue(row, family, qf2, 1, (byte[])null));
482     this.store.add(new KeyValue(row, family, qf3, 1, (byte[])null));
483     this.store.add(new KeyValue(row, family, qf4, 1, (byte[])null));
484     this.store.add(new KeyValue(row, family, qf5, 1, (byte[])null));
485     this.store.add(new KeyValue(row, family, qf6, 1, (byte[])null));
486 
487     //Get
488     result = HBaseTestingUtility.getFromStoreFile(store,
489         get.getRow(), qualifiers);
490 
491     //Compare
492     assertCheck();
493   }
494 
495   /**
496    * Getting data from files only
497    * @throws IOException
498    */
499   @Test
500   public void testGet_FromFilesOnly() throws IOException {
501     init(this.name.getMethodName());
502 
503     //Put data in memstore
504     this.store.add(new KeyValue(row, family, qf1, 1, (byte[])null));
505     this.store.add(new KeyValue(row, family, qf2, 1, (byte[])null));
506     //flush
507     flush(1);
508 
509     //Add more data
510     this.store.add(new KeyValue(row, family, qf3, 1, (byte[])null));
511     this.store.add(new KeyValue(row, family, qf4, 1, (byte[])null));
512     //flush
513     flush(2);
514 
515     //Add more data
516     this.store.add(new KeyValue(row, family, qf5, 1, (byte[])null));
517     this.store.add(new KeyValue(row, family, qf6, 1, (byte[])null));
518     //flush
519     flush(3);
520 
521     //Get
522     result = HBaseTestingUtility.getFromStoreFile(store,
523         get.getRow(),
524         qualifiers);
525     //this.store.get(get, qualifiers, result);
526 
527     //Need to sort the result since multiple files
528     Collections.sort(result, KeyValue.COMPARATOR);
529 
530     //Compare
531     assertCheck();
532   }
533 
534   /**
535    * Getting data from memstore and files
536    * @throws IOException
537    */
538   @Test
539   public void testGet_FromMemStoreAndFiles() throws IOException {
540     init(this.name.getMethodName());
541 
542     //Put data in memstore
543     this.store.add(new KeyValue(row, family, qf1, 1, (byte[])null));
544     this.store.add(new KeyValue(row, family, qf2, 1, (byte[])null));
545     //flush
546     flush(1);
547 
548     //Add more data
549     this.store.add(new KeyValue(row, family, qf3, 1, (byte[])null));
550     this.store.add(new KeyValue(row, family, qf4, 1, (byte[])null));
551     //flush
552     flush(2);
553 
554     //Add more data
555     this.store.add(new KeyValue(row, family, qf5, 1, (byte[])null));
556     this.store.add(new KeyValue(row, family, qf6, 1, (byte[])null));
557 
558     //Get
559     result = HBaseTestingUtility.getFromStoreFile(store,
560         get.getRow(), qualifiers);
561 
562     //Need to sort the result since multiple files
563     Collections.sort(result, KeyValue.COMPARATOR);
564 
565     //Compare
566     assertCheck();
567   }
568 
569   private void flush(int storeFilessize) throws IOException{
570     this.store.snapshot();
571     flushStore(store, id++);
572     Assert.assertEquals(storeFilessize, this.store.getStorefiles().size());
573     Assert.assertEquals(0, ((DefaultMemStore)this.store.memstore).activeSection.getCellSkipListSet().size());
574   }
575 
576   private void assertCheck() {
577     Assert.assertEquals(expected.size(), result.size());
578     for(int i=0; i<expected.size(); i++) {
579       Assert.assertEquals(expected.get(i), result.get(i));
580     }
581   }
582 
583   //////////////////////////////////////////////////////////////////////////////
584   // IncrementColumnValue tests
585   //////////////////////////////////////////////////////////////////////////////
586   /*
587    * test the internal details of how ICV works, especially during a flush scenario.
588    */
589   @Test
590   public void testIncrementColumnValue_ICVDuringFlush()
591       throws IOException, InterruptedException {
592     init(this.name.getMethodName());
593 
594     long oldValue = 1L;
595     long newValue = 3L;
596     this.store.add(new KeyValue(row, family, qf1,
597         System.currentTimeMillis(),
598         Bytes.toBytes(oldValue)));
599 
600     // snapshot the store.
601     this.store.snapshot();
602 
603     // add other things:
604     this.store.add(new KeyValue(row, family, qf2,
605         System.currentTimeMillis(),
606         Bytes.toBytes(oldValue)));
607 
608     // update during the snapshot.
609     long ret = this.store.updateColumnValue(row, family, qf1, newValue);
610 
611     // memstore should have grown by some amount.
612     Assert.assertTrue(ret > 0);
613 
614     // then flush.
615     flushStore(store, id++);
616     Assert.assertEquals(1, this.store.getStorefiles().size());
617     // from the one we inserted up there, and a new one
618     Assert.assertEquals(2, ((DefaultMemStore)this.store.memstore).activeSection.getCellSkipListSet().size());
619 
620     // how many key/values for this row are there?
621     Get get = new Get(row);
622     get.addColumn(family, qf1);
623     get.setMaxVersions(); // all versions.
624     List<Cell> results = new ArrayList<Cell>();
625 
626     results = HBaseTestingUtility.getFromStoreFile(store, get);
627     Assert.assertEquals(2, results.size());
628 
629     long ts1 = results.get(0).getTimestamp();
630     long ts2 = results.get(1).getTimestamp();
631 
632     Assert.assertTrue(ts1 > ts2);
633 
634     Assert.assertEquals(newValue, Bytes.toLong(CellUtil.cloneValue(results.get(0))));
635     Assert.assertEquals(oldValue, Bytes.toLong(CellUtil.cloneValue(results.get(1))));
636   }
637 
638   @After
639   public void tearDown() throws Exception {
640     EnvironmentEdgeManagerTestHelper.reset();
641   }
642 
643   @Test
644   public void testICV_negMemstoreSize()  throws IOException {
645       init(this.name.getMethodName());
646 
647     long time = 100;
648     ManualEnvironmentEdge ee = new ManualEnvironmentEdge();
649     ee.setValue(time);
650     EnvironmentEdgeManagerTestHelper.injectEdge(ee);
651     long newValue = 3L;
652     long size = 0;
653 
654 
655     size += this.store.add(new KeyValue(Bytes.toBytes("200909091000"), family, qf1,
656         System.currentTimeMillis(), Bytes.toBytes(newValue)));
657     size += this.store.add(new KeyValue(Bytes.toBytes("200909091200"), family, qf1,
658         System.currentTimeMillis(), Bytes.toBytes(newValue)));
659     size += this.store.add(new KeyValue(Bytes.toBytes("200909091300"), family, qf1,
660         System.currentTimeMillis(), Bytes.toBytes(newValue)));
661     size += this.store.add(new KeyValue(Bytes.toBytes("200909091400"), family, qf1,
662         System.currentTimeMillis(), Bytes.toBytes(newValue)));
663     size += this.store.add(new KeyValue(Bytes.toBytes("200909091500"), family, qf1,
664         System.currentTimeMillis(), Bytes.toBytes(newValue)));
665 
666 
667     for ( int i = 0 ; i < 10000 ; ++i) {
668       newValue++;
669 
670       long ret = this.store.updateColumnValue(row, family, qf1, newValue);
671       long ret2 = this.store.updateColumnValue(row2, family, qf1, newValue);
672 
673       if (ret != 0) System.out.println("ret: " + ret);
674       if (ret2 != 0) System.out.println("ret2: " + ret2);
675 
676       Assert.assertTrue("ret: " + ret, ret >= 0);
677       size += ret;
678       Assert.assertTrue("ret2: " + ret2, ret2 >= 0);
679       size += ret2;
680 
681 
682       if (i % 1000 == 0)
683         ee.setValue(++time);
684     }
685 
686     long computedSize=0;
687     for (Cell cell : ((DefaultMemStore)this.store.memstore).activeSection.getCellSkipListSet()) {
688       long kvsize = DefaultMemStore.heapSizeChange(cell, true);
689       //System.out.println(kv + " size= " + kvsize + " kvsize= " + kv.heapSize());
690       computedSize += kvsize;
691     }
692     Assert.assertEquals(computedSize, size);
693   }
694 
695   @Test
696   public void testIncrementColumnValue_SnapshotFlushCombo() throws Exception {
697     ManualEnvironmentEdge mee = new ManualEnvironmentEdge();
698     EnvironmentEdgeManagerTestHelper.injectEdge(mee);
699     init(this.name.getMethodName());
700 
701     long oldValue = 1L;
702     long newValue = 3L;
703     this.store.add(new KeyValue(row, family, qf1,
704         EnvironmentEdgeManager.currentTime(),
705         Bytes.toBytes(oldValue)));
706 
707     // snapshot the store.
708     this.store.snapshot();
709 
710     // update during the snapshot, the exact same TS as the Put (lololol)
711     long ret = this.store.updateColumnValue(row, family, qf1, newValue);
712 
713     // memstore should have grown by some amount.
714     Assert.assertTrue(ret > 0);
715 
716     // then flush.
717     flushStore(store, id++);
718     Assert.assertEquals(1, this.store.getStorefiles().size());
719     Assert.assertEquals(1, ((DefaultMemStore)this.store.memstore).activeSection.getCellSkipListSet().size());
720 
721     // now increment again:
722     newValue += 1;
723     this.store.updateColumnValue(row, family, qf1, newValue);
724 
725     // at this point we have a TS=1 in snapshot, and a TS=2 in kvset, so increment again:
726     newValue += 1;
727     this.store.updateColumnValue(row, family, qf1, newValue);
728 
729     // the second TS should be TS=2 or higher., even though 'time=1' right now.
730 
731 
732     // how many key/values for this row are there?
733     Get get = new Get(row);
734     get.addColumn(family, qf1);
735     get.setMaxVersions(); // all versions.
736     List<Cell> results = new ArrayList<Cell>();
737 
738     results = HBaseTestingUtility.getFromStoreFile(store, get);
739     Assert.assertEquals(2, results.size());
740 
741     long ts1 = results.get(0).getTimestamp();
742     long ts2 = results.get(1).getTimestamp();
743 
744     Assert.assertTrue(ts1 > ts2);
745     Assert.assertEquals(newValue, Bytes.toLong(CellUtil.cloneValue(results.get(0))));
746     Assert.assertEquals(oldValue, Bytes.toLong(CellUtil.cloneValue(results.get(1))));
747 
748     mee.setValue(2); // time goes up slightly
749     newValue += 1;
750     this.store.updateColumnValue(row, family, qf1, newValue);
751 
752     results = HBaseTestingUtility.getFromStoreFile(store, get);
753     Assert.assertEquals(2, results.size());
754 
755     ts1 = results.get(0).getTimestamp();
756     ts2 = results.get(1).getTimestamp();
757 
758     Assert.assertTrue(ts1 > ts2);
759     Assert.assertEquals(newValue, Bytes.toLong(CellUtil.cloneValue(results.get(0))));
760     Assert.assertEquals(oldValue, Bytes.toLong(CellUtil.cloneValue(results.get(1))));
761   }
762 
763   @Test
764   public void testHandleErrorsInFlush() throws Exception {
765     LOG.info("Setting up a faulty file system that cannot write");
766 
767     final Configuration conf = HBaseConfiguration.create();
768     User user = User.createUserForTesting(conf,
769         "testhandleerrorsinflush", new String[]{"foo"});
770     // Inject our faulty LocalFileSystem
771     conf.setClass("fs.file.impl", FaultyFileSystem.class,
772         FileSystem.class);
773     user.runAs(new PrivilegedExceptionAction<Object>() {
774       @Override
775       public Object run() throws Exception {
776         // Make sure it worked (above is sensitive to caching details in hadoop core)
777         FileSystem fs = FileSystem.get(conf);
778         Assert.assertEquals(FaultyFileSystem.class, fs.getClass());
779 
780         // Initialize region
781         init(name.getMethodName(), conf);
782 
783         LOG.info("Adding some data");
784         store.add(new KeyValue(row, family, qf1, 1, (byte[])null));
785         store.add(new KeyValue(row, family, qf2, 1, (byte[])null));
786         store.add(new KeyValue(row, family, qf3, 1, (byte[])null));
787 
788         LOG.info("Before flush, we should have no files");
789 
790         Collection<StoreFileInfo> files =
791           store.getRegionFileSystem().getStoreFiles(store.getColumnFamilyName());
792         Assert.assertEquals(0, files != null ? files.size() : 0);
793 
794         //flush
795         try {
796           LOG.info("Flushing");
797           flush(1);
798           Assert.fail("Didn't bubble up IOE!");
799         } catch (IOException ioe) {
800           Assert.assertTrue(ioe.getMessage().contains("Fault injected"));
801         }
802 
803         LOG.info("After failed flush, we should still have no files!");
804         files = store.getRegionFileSystem().getStoreFiles(store.getColumnFamilyName());
805         Assert.assertEquals(0, files != null ? files.size() : 0);
806         store.getHRegion().getWAL().close();
807         return null;
808       }
809     });
810     FileSystem.closeAllForUGI(user.getUGI());
811   }
812 
813   /**
814    * Faulty file system that will fail if you write past its fault position the FIRST TIME
815    * only; thereafter it will succeed.  Used by {@link TestHRegion} too.
816    */
817   static class FaultyFileSystem extends FilterFileSystem {
818     List<SoftReference<FaultyOutputStream>> outStreams =
819       new ArrayList<SoftReference<FaultyOutputStream>>();
820     private long faultPos = 200;
821     AtomicBoolean fault = new AtomicBoolean(true);
822 
823     public FaultyFileSystem() {
824       super(new LocalFileSystem());
825       System.err.println("Creating faulty!");
826     }
827 
828     @Override
829     public FSDataOutputStream create(Path p) throws IOException {
830       return new FaultyOutputStream(super.create(p), faultPos, fault);
831     }
832 
833     @Override
834     public FSDataOutputStream create(Path f, FsPermission permission,
835         boolean overwrite, int bufferSize, short replication, long blockSize,
836         Progressable progress) throws IOException {
837       return new FaultyOutputStream(super.create(f, permission,
838           overwrite, bufferSize, replication, blockSize, progress), faultPos, fault);
839     }
840 
841     @Override
842     public FSDataOutputStream createNonRecursive(Path f, boolean overwrite,
843         int bufferSize, short replication, long blockSize, Progressable progress)
844     throws IOException {
845       // Fake it.  Call create instead.  The default implementation throws an IOE
846       // that this is not supported.
847       return create(f, overwrite, bufferSize, replication, blockSize, progress);
848     }
849   }
850 
851   static class FaultyOutputStream extends FSDataOutputStream {
852     volatile long faultPos = Long.MAX_VALUE;
853     private final AtomicBoolean fault;
854 
855     public FaultyOutputStream(FSDataOutputStream out, long faultPos, final AtomicBoolean fault)
856     throws IOException {
857       super(out, null);
858       this.faultPos = faultPos;
859       this.fault = fault;
860     }
861 
862     @Override
863     public void write(byte[] buf, int offset, int length) throws IOException {
864       System.err.println("faulty stream write at pos " + getPos());
865       injectFault();
866       super.write(buf, offset, length);
867     }
868 
869     private void injectFault() throws IOException {
870       if (this.fault.get() && getPos() >= faultPos) {
871         throw new IOException("Fault injected");
872       }
873     }
874   }
875 
876   private static void flushStore(HStore store, long id) throws IOException {
877     StoreFlushContext storeFlushCtx = store.createFlushContext(id);
878     storeFlushCtx.prepare();
879     storeFlushCtx.flushCache(Mockito.mock(MonitoredTask.class));
880     storeFlushCtx.commit(Mockito.mock(MonitoredTask.class));
881   }
882 
883   /**
884    * Generate a list of KeyValues for testing based on given parameters
885    * @param timestamps
886    * @param numRows
887    * @param qualifier
888    * @param family
889    * @return
890    */
891   List<Cell> getKeyValueSet(long[] timestamps, int numRows,
892       byte[] qualifier, byte[] family) {
893     List<Cell> kvList = new ArrayList<Cell>();
894     for (int i=1;i<=numRows;i++) {
895       byte[] b = Bytes.toBytes(i);
896       for (long timestamp: timestamps) {
897         kvList.add(new KeyValue(b, family, qualifier, timestamp, b));
898       }
899     }
900     return kvList;
901   }
902 
903   /**
904    * Test to ensure correctness when using Stores with multiple timestamps
905    * @throws IOException
906    */
907   @Test
908   public void testMultipleTimestamps() throws IOException {
909     int numRows = 1;
910     long[] timestamps1 = new long[] {1,5,10,20};
911     long[] timestamps2 = new long[] {30,80};
912 
913     init(this.name.getMethodName());
914 
915     List<Cell> kvList1 = getKeyValueSet(timestamps1,numRows, qf1, family);
916     for (Cell kv : kvList1) {
917       this.store.add(KeyValueUtil.ensureKeyValue(kv));
918     }
919 
920     this.store.snapshot();
921     flushStore(store, id++);
922 
923     List<Cell> kvList2 = getKeyValueSet(timestamps2,numRows, qf1, family);
924     for(Cell kv : kvList2) {
925       this.store.add(KeyValueUtil.ensureKeyValue(kv));
926     }
927 
928     List<Cell> result;
929     Get get = new Get(Bytes.toBytes(1));
930     get.addColumn(family,qf1);
931 
932     get.setTimeRange(0,15);
933     result = HBaseTestingUtility.getFromStoreFile(store, get);
934     Assert.assertTrue(result.size()>0);
935 
936     get.setTimeRange(40,90);
937     result = HBaseTestingUtility.getFromStoreFile(store, get);
938     Assert.assertTrue(result.size()>0);
939 
940     get.setTimeRange(10,45);
941     result = HBaseTestingUtility.getFromStoreFile(store, get);
942     Assert.assertTrue(result.size()>0);
943 
944     get.setTimeRange(80,145);
945     result = HBaseTestingUtility.getFromStoreFile(store, get);
946     Assert.assertTrue(result.size()>0);
947 
948     get.setTimeRange(1,2);
949     result = HBaseTestingUtility.getFromStoreFile(store, get);
950     Assert.assertTrue(result.size()>0);
951 
952     get.setTimeRange(90,200);
953     result = HBaseTestingUtility.getFromStoreFile(store, get);
954     Assert.assertTrue(result.size()==0);
955   }
956 
957   /**
958    * Test for HBASE-3492 - Test split on empty colfam (no store files).
959    *
960    * @throws IOException When the IO operations fail.
961    */
962   @Test
963   public void testSplitWithEmptyColFam() throws IOException {
964     init(this.name.getMethodName());
965     Assert.assertNull(store.getSplitPoint());
966     store.getHRegion().forceSplit(null);
967     Assert.assertNull(store.getSplitPoint());
968     store.getHRegion().clearSplit();
969   }
970 
971   @Test
972   public void testStoreUsesConfigurationFromHcdAndHtd() throws Exception {
973     final String CONFIG_KEY = "hbase.regionserver.thread.compaction.throttle";
974     long anyValue = 10;
975 
976     // We'll check that it uses correct config and propagates it appropriately by going thru
977     // the simplest "real" path I can find - "throttleCompaction", which just checks whether
978     // a number we pass in is higher than some config value, inside compactionPolicy.
979     Configuration conf = HBaseConfiguration.create();
980     conf.setLong(CONFIG_KEY, anyValue);
981     init(name.getMethodName() + "-xml", conf);
982     Assert.assertTrue(store.throttleCompaction(anyValue + 1));
983     Assert.assertFalse(store.throttleCompaction(anyValue));
984 
985     // HTD overrides XML.
986     --anyValue;
987     HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(table));
988     HColumnDescriptor hcd = new HColumnDescriptor(family);
989     htd.setConfiguration(CONFIG_KEY, Long.toString(anyValue));
990     init(name.getMethodName() + "-htd", conf, htd, hcd);
991     Assert.assertTrue(store.throttleCompaction(anyValue + 1));
992     Assert.assertFalse(store.throttleCompaction(anyValue));
993 
994     // HCD overrides them both.
995     --anyValue;
996     hcd.setConfiguration(CONFIG_KEY, Long.toString(anyValue));
997     init(name.getMethodName() + "-hcd", conf, htd, hcd);
998     Assert.assertTrue(store.throttleCompaction(anyValue + 1));
999     Assert.assertFalse(store.throttleCompaction(anyValue));
1000   }
1001 
1002   public static class DummyStoreEngine extends DefaultStoreEngine {
1003     public static DefaultCompactor lastCreatedCompactor = null;
1004     @Override
1005     protected void createComponents(
1006         Configuration conf, Store store, KVComparator comparator) throws IOException {
1007       super.createComponents(conf, store, comparator);
1008       lastCreatedCompactor = this.compactor;
1009     }
1010   }
1011 
1012   @Test
1013   public void testStoreUsesSearchEngineOverride() throws Exception {
1014     Configuration conf = HBaseConfiguration.create();
1015     conf.set(StoreEngine.STORE_ENGINE_CLASS_KEY, DummyStoreEngine.class.getName());
1016     init(this.name.getMethodName(), conf);
1017     Assert.assertEquals(DummyStoreEngine.lastCreatedCompactor,
1018       this.store.storeEngine.getCompactor());
1019   }
1020 
1021   private void addStoreFile() throws IOException {
1022     StoreFile f = this.store.getStorefiles().iterator().next();
1023     Path storedir = f.getPath().getParent();
1024     long seqid = this.store.getMaxSequenceId();
1025     Configuration c = TEST_UTIL.getConfiguration();
1026     FileSystem fs = FileSystem.get(c);
1027     HFileContext fileContext = new HFileContextBuilder().withBlockSize(BLOCKSIZE_SMALL).build();
1028     StoreFile.Writer w = new StoreFile.WriterBuilder(c, new CacheConfig(c),
1029         fs)
1030             .withOutputDir(storedir)
1031             .withFileContext(fileContext)
1032             .build();
1033     w.appendMetadata(seqid + 1, false);
1034     w.close();
1035     LOG.info("Added store file:" + w.getPath());
1036   }
1037 
1038   private void archiveStoreFile(int index) throws IOException {
1039     Collection<StoreFile> files = this.store.getStorefiles();
1040     StoreFile sf = null;
1041     Iterator<StoreFile> it = files.iterator();
1042     for (int i = 0; i <= index; i++) {
1043       sf = it.next();
1044     }
1045     store.getRegionFileSystem().removeStoreFiles(store.getColumnFamilyName(), Lists.newArrayList(sf));
1046   }
1047 
1048   private void closeCompactedFile(int index) throws IOException {
1049     Collection<StoreFile> files =
1050         this.store.getStoreEngine().getStoreFileManager().getCompactedfiles();
1051     StoreFile sf = null;
1052     Iterator<StoreFile> it = files.iterator();
1053     for (int i = 0; i <= index; i++) {
1054       sf = it.next();
1055     }
1056     sf.closeReader(true);
1057     store.getStoreEngine().getStoreFileManager().removeCompactedFiles(Lists.newArrayList(sf));
1058   }
1059 
1060   @Test
1061   public void testRefreshStoreFiles() throws Exception {
1062     init(name.getMethodName());
1063 
1064     assertEquals(0, this.store.getStorefilesCount());
1065 
1066     // Test refreshing store files when no store files are there
1067     store.refreshStoreFiles();
1068     assertEquals(0, this.store.getStorefilesCount());
1069 
1070     // add some data, flush
1071     this.store.add(new KeyValue(row, family, qf1, 1, (byte[])null));
1072     flush(1);
1073     assertEquals(1, this.store.getStorefilesCount());
1074 
1075     // add one more file
1076     addStoreFile();
1077 
1078     assertEquals(1, this.store.getStorefilesCount());
1079     store.refreshStoreFiles();
1080     assertEquals(2, this.store.getStorefilesCount());
1081 
1082     // add three more files
1083     addStoreFile();
1084     addStoreFile();
1085     addStoreFile();
1086 
1087     assertEquals(2, this.store.getStorefilesCount());
1088     store.refreshStoreFiles();
1089     assertEquals(5, this.store.getStorefilesCount());
1090 
1091     closeCompactedFile(0);
1092     archiveStoreFile(0);
1093 
1094     assertEquals(5, this.store.getStorefilesCount());
1095     store.refreshStoreFiles();
1096     assertEquals(4, this.store.getStorefilesCount());
1097 
1098     archiveStoreFile(0);
1099     archiveStoreFile(1);
1100     archiveStoreFile(2);
1101 
1102     assertEquals(4, this.store.getStorefilesCount());
1103     store.refreshStoreFiles();
1104     assertEquals(1, this.store.getStorefilesCount());
1105 
1106     archiveStoreFile(0);
1107     store.refreshStoreFiles();
1108     assertEquals(0, this.store.getStorefilesCount());
1109   }
1110 
1111   @SuppressWarnings("unchecked")
1112   @Test
1113   public void testRefreshStoreFilesNotChanged() throws IOException {
1114     init(name.getMethodName());
1115 
1116     assertEquals(0, this.store.getStorefilesCount());
1117 
1118     // add some data, flush
1119     this.store.add(new KeyValue(row, family, qf1, 1, (byte[])null));
1120     flush(1);
1121     // add one more file
1122     addStoreFile();
1123 
1124     HStore spiedStore = spy(store);
1125 
1126     // call first time after files changed
1127     spiedStore.refreshStoreFiles();
1128     assertEquals(2, this.store.getStorefilesCount());
1129     verify(spiedStore, times(1)).replaceStoreFiles(any(Collection.class), any(Collection.class));
1130 
1131     // call second time
1132     spiedStore.refreshStoreFiles();
1133 
1134     //ensure that replaceStoreFiles is not called if files are not refreshed
1135     verify(spiedStore, times(0)).replaceStoreFiles(null, null);
1136   }
1137 
1138   private Cell createCell(byte[] qualifier, long ts, long sequenceId, byte[] value) throws IOException {
1139     return createCell(row, qualifier, ts, sequenceId, value);
1140   }
1141 
1142   private Cell createCell(byte[] row, byte[] qualifier, long ts, long sequenceId, byte[] value) throws IOException {
1143     Cell c = CellUtil.createCell(row, family, qualifier, ts, KeyValue.Type.Put.getCode(), value);
1144     CellUtil.setSequenceId(c, sequenceId);
1145     return c;
1146   }
1147 
1148   @Test
1149   public void testScanWithDoubleFlush() throws IOException {
1150     Configuration conf = HBaseConfiguration.create();
1151     // Initialize region
1152     MyStore myStore = initMyStore(name.getMethodName(), conf, new MyStoreHook() {
1153       @Override
1154       public void getScanners(final MyStore store) throws IOException {
1155         final long tmpId = id++;
1156         ExecutorService s = Executors.newSingleThreadExecutor();
1157         s.submit(new Runnable() {
1158           @Override
1159           public void run() {
1160             try {
1161               // flush the store before storescanner updates the scanners from store.
1162               // The current data will be flushed into files and the memstore will
1163               // be clear.
1164               // -- phase (4/4)
1165               flushStore(store, tmpId);
1166             } catch (IOException ex) {
1167               throw new RuntimeException(ex);
1168             }
1169           }
1170         });
1171         s.shutdown();
1172         try {
1173           // wait for the flush, the thread will be blocked in HStore#notifyChangedReadersObservers.
1174           s.awaitTermination(500, TimeUnit.MILLISECONDS);
1175         } catch (InterruptedException ex) {
1176         }
1177       }
1178     });
1179     byte[] oldValue = Bytes.toBytes("oldValue");
1180     byte[] currentValue = Bytes.toBytes("currentValue");
1181     long ts = EnvironmentEdgeManager.currentTime();
1182     long seqId = 100;
1183     // older data whihc shouldn't be "seen" by client
1184     myStore.add(createCell(qf1, ts, seqId, oldValue));
1185     myStore.add(createCell(qf2, ts, seqId, oldValue));
1186     myStore.add(createCell(qf3, ts, seqId, oldValue));
1187     long snapshotId = id++;
1188     // push older data into snapshot -- phase (1/4)
1189     StoreFlushContext storeFlushCtx = store.createFlushContext(snapshotId);
1190     storeFlushCtx.prepare();
1191 
1192     // insert current data into active -- phase (2/4)
1193     myStore.add(createCell(qf1, ts + 1, seqId + 1, currentValue));
1194     myStore.add(createCell(qf2, ts + 1, seqId + 1, currentValue));
1195     myStore.add(createCell(qf3, ts + 1, seqId + 1, currentValue));
1196     TreeSet<byte[]> quals = new TreeSet<>(Bytes.BYTES_COMPARATOR);
1197     quals.add(qf1);
1198     quals.add(qf2);
1199     quals.add(qf3);
1200     try (InternalScanner scanner = (InternalScanner) myStore.getScanner(
1201             new Scan(new Get(row)), quals, seqId + 1)) {
1202       // complete the flush -- phase (3/4)
1203       storeFlushCtx.flushCache(Mockito.mock(MonitoredTask.class));
1204       storeFlushCtx.commit(Mockito.mock(MonitoredTask.class));
1205 
1206       List<Cell> results = new ArrayList<>();
1207       scanner.next(results);
1208       assertEquals(3, results.size());
1209       for (Cell c : results) {
1210         byte[] actualValue = CellUtil.cloneValue(c);
1211         assertTrue("expected:" + Bytes.toStringBinary(currentValue)
1212                 + ", actual:" + Bytes.toStringBinary(actualValue),
1213                  Bytes.equals(actualValue, currentValue));
1214       }
1215     }
1216 
1217   }
1218 
1219   @Test
1220   public void testFlushBeforeCompletingScanWoFilter() throws IOException, InterruptedException {
1221     final AtomicBoolean timeToGoNextRow = new AtomicBoolean(false);
1222     testFlushBeforeCompletingScan(new MyListHook() {
1223       @Override
1224       public void hook(int currentSize) {
1225         if (currentSize == 2) {
1226           try {
1227             flushStore(store, id++);
1228             timeToGoNextRow.set(true);
1229           } catch (IOException e) {
1230             throw new RuntimeException(e);
1231           }
1232         }
1233       }
1234     }, new FilterBase() {
1235       @Override
1236       public Filter.ReturnCode filterKeyValue(Cell v) throws IOException {
1237         return Filter.ReturnCode.INCLUDE;
1238       }
1239     });
1240   }
1241 
1242   @Test
1243   public void testFlushBeforeCompletingScanWithFilter() throws IOException, InterruptedException {
1244     final AtomicBoolean timeToGoNextRow = new AtomicBoolean(false);
1245     testFlushBeforeCompletingScan(new MyListHook() {
1246       @Override
1247       public void hook(int currentSize) {
1248         if (currentSize == 2) {
1249           try {
1250             flushStore(store, id++);
1251             timeToGoNextRow.set(true);
1252           } catch (IOException e) {
1253             throw new RuntimeException(e);
1254           }
1255         }
1256       }
1257     }, new FilterBase() {
1258       @Override
1259       public Filter.ReturnCode filterKeyValue(Cell v) throws IOException {
1260         if (timeToGoNextRow.get()) {
1261           timeToGoNextRow.set(false);
1262           return Filter.ReturnCode.NEXT_ROW;
1263         } else {
1264           return Filter.ReturnCode.INCLUDE;
1265         }
1266       }
1267     });
1268   }
1269 
1270   @Test
1271   public void testFlushBeforeCompletingScanWithFilterHint() throws IOException, InterruptedException {
1272     final AtomicBoolean timeToGetHint = new AtomicBoolean(false);
1273     testFlushBeforeCompletingScan(new MyListHook() {
1274       @Override
1275       public void hook(int currentSize) {
1276         if (currentSize == 2) {
1277           try {
1278             flushStore(store, id++);
1279             timeToGetHint.set(true);
1280           } catch (IOException e) {
1281             throw new RuntimeException(e);
1282           }
1283         }
1284       }
1285     }, new FilterBase() {
1286       @Override
1287       public Filter.ReturnCode filterKeyValue(Cell v) throws IOException {
1288         if (timeToGetHint.get()) {
1289           timeToGetHint.set(false);
1290           return Filter.ReturnCode.SEEK_NEXT_USING_HINT;
1291         } else {
1292           return Filter.ReturnCode.INCLUDE;
1293         }
1294       }
1295       @Override
1296       public Cell getNextCellHint(Cell currentCell) throws IOException {
1297         return currentCell;
1298       }
1299     });
1300   }
1301 
1302   private void testFlushBeforeCompletingScan(MyListHook hook, Filter filter)
1303           throws IOException, InterruptedException {
1304     Configuration conf = HBaseConfiguration.create();
1305     HColumnDescriptor hcd = new HColumnDescriptor(family);
1306     hcd.setMaxVersions(1);
1307     byte[] r0 = Bytes.toBytes("row0");
1308     byte[] r1 = Bytes.toBytes("row1");
1309     byte[] r2 = Bytes.toBytes("row2");
1310     byte[] value0 = Bytes.toBytes("value0");
1311     byte[] value1 = Bytes.toBytes("value1");
1312     byte[] value2 = Bytes.toBytes("value2");
1313     long ts = EnvironmentEdgeManager.currentTime();
1314     final long seqId = 100;
1315     init(name.getMethodName(), conf, new HTableDescriptor(TableName.valueOf(table)), hcd, new MyStoreHook() {
1316       @Override
1317       public long getSmallestReadPoint(HStore store) {
1318         return seqId + 3;
1319       }
1320     });
1321     // The cells having the value0 won't be flushed to disk because the value of max version is 1
1322     store.add(createCell(r0, qf1, ts, seqId, value0));
1323     store.add(createCell(r0, qf2, ts, seqId, value0));
1324     store.add(createCell(r0, qf3, ts, seqId, value0));
1325     store.add(createCell(r1, qf1, ts + 1, seqId + 1, value1));
1326     store.add(createCell(r1, qf2, ts + 1, seqId + 1, value1));
1327     store.add(createCell(r1, qf3, ts + 1, seqId + 1, value1));
1328     store.add(createCell(r2, qf1, ts + 2, seqId + 2, value2));
1329     store.add(createCell(r2, qf2, ts + 2, seqId + 2, value2));
1330     store.add(createCell(r2, qf3, ts + 2, seqId + 2, value2));
1331     store.add(createCell(r1, qf1, ts + 3, seqId + 3, value1));
1332     store.add(createCell(r1, qf2, ts + 3, seqId + 3, value1));
1333     store.add(createCell(r1, qf3, ts + 3, seqId + 3, value1));
1334     List<Cell> myList = new MyList<>(hook);
1335     Scan scan = new Scan(r1)
1336             .setFilter(filter);
1337     try (InternalScanner scanner = (InternalScanner) store.getScanner(
1338           scan, null, seqId + 3)){
1339       // r1
1340       scanner.next(myList);
1341       assertEquals(3, myList.size());
1342       for (Cell c : myList) {
1343         byte[] actualValue = CellUtil.cloneValue(c);
1344         assertTrue("expected:" + Bytes.toStringBinary(value1)
1345           + ", actual:" + Bytes.toStringBinary(actualValue)
1346           , Bytes.equals(actualValue, value1));
1347       }
1348       List<Cell> normalList = new ArrayList<>(3);
1349       // r2
1350       scanner.next(normalList);
1351       assertEquals(3, normalList.size());
1352       for (Cell c : normalList) {
1353         byte[] actualValue = CellUtil.cloneValue(c);
1354         assertTrue("expected:" + Bytes.toStringBinary(value2)
1355           + ", actual:" + Bytes.toStringBinary(actualValue)
1356           , Bytes.equals(actualValue, value2));
1357       }
1358     }
1359   }
1360 
1361   @Test
1362   public void testReclaimChunkWhenScaning() throws IOException {
1363     Configuration conf = HBaseConfiguration.create();
1364     conf.setFloat(CHUNK_POOL_MAXSIZE_KEY, 1);
1365     init("testReclaimChunkWhenScaning", conf);
1366     final long ts = EnvironmentEdgeManager.currentTime();
1367     final long seqId = 100;
1368     byte[] value = Bytes.toBytes("value");
1369     // older data whihc shouldn't be "seen" by client
1370     store.add(createCell(qf1, ts, seqId, value));
1371     store.add(createCell(qf2, ts, seqId, value));
1372     store.add(createCell(qf3, ts, seqId, value));
1373     TreeSet<byte[]> quals = new TreeSet<>(Bytes.BYTES_COMPARATOR);
1374     quals.add(qf1);
1375     quals.add(qf2);
1376     quals.add(qf3);
1377     try (InternalScanner scanner = (InternalScanner) store.getScanner(
1378         new Scan(new Get(row)), quals, seqId)) {
1379       List<Cell> results = new MyList<>(new MyListHook() {
1380         @Override
1381         public void hook(int size) {
1382           switch (size) {
1383             // 1) we get the first cell (qf1)
1384             // 2) flush the data to have StoreScanner update inner scanners
1385             // 3) the chunk will be reclaimed after updaing
1386             case 1:
1387               try {
1388                 flushStore(store, id++);
1389               } catch (IOException e) {
1390                 throw new RuntimeException(e);
1391               }
1392               break;
1393             // 1) we get the second cell (qf2)
1394             // 2) add some cell to fill some byte into the chunk (we have only one chunk)
1395             case 2:
1396               try {
1397                 byte[] newValue = Bytes.toBytes("newValue");
1398                 // older data whihc shouldn't be "seen" by client
1399                 store.add(createCell(qf1, ts + 1, seqId + 1, newValue));
1400                 store.add(createCell(qf2, ts + 1, seqId + 1, newValue));
1401                 store.add(createCell(qf3, ts + 1, seqId + 1, newValue));
1402               } catch (IOException e) {
1403                 throw new RuntimeException(e);
1404               }
1405               break;
1406             default:
1407               break;
1408           }
1409         }
1410       });
1411       scanner.next(results);
1412       assertEquals(3, results.size());
1413       for (Cell c : results) {
1414         byte[] actualValue = CellUtil.cloneValue(c);
1415         assertTrue("expected:" + Bytes.toStringBinary(value)
1416           + ", actual:" + Bytes.toStringBinary(actualValue)
1417           , Bytes.equals(actualValue, value));
1418       }
1419     }
1420   }
1421 
1422   private MyStore initMyStore(String methodName, Configuration conf, MyStoreHook hook) throws IOException {
1423     HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(table));
1424     HColumnDescriptor hcd = new HColumnDescriptor(family);
1425     hcd.setMaxVersions(5);
1426     return (MyStore) init(methodName, conf, htd, hcd, hook);
1427   }
1428 
1429   private static class MyStore extends HStore {
1430 
1431     private final MyStoreHook hook;
1432 
1433     MyStore(final HRegion region, final HColumnDescriptor family,
1434             final Configuration confParam, MyStoreHook hook) throws IOException {
1435       super(region, family, confParam);
1436       this.hook = hook;
1437     }
1438 
1439     @Override
1440     public List<KeyValueScanner> getScanners(List<StoreFile> files, boolean cacheBlocks,
1441             boolean isGet, boolean usePread, boolean isCompaction, ScanQueryMatcher matcher,
1442             byte[] startRow, byte[] stopRow, long readPt, boolean includeMemstoreScanner) throws IOException {
1443       hook.getScanners(this);
1444       return super.getScanners(files, cacheBlocks, isGet, usePread,
1445               isCompaction, matcher, startRow, stopRow, readPt, includeMemstoreScanner);
1446     }
1447 
1448     @Override
1449     public long getSmallestReadPoint() {
1450       return hook.getSmallestReadPoint(this);
1451     }
1452   }
1453 
1454   private abstract class MyStoreHook {
1455     void getScanners(MyStore store) throws IOException {
1456     }
1457     long getSmallestReadPoint(HStore store) {
1458       return store.getHRegion().getSmallestReadPoint();
1459     }
1460   }
1461 
1462   interface MyListHook {
1463     void hook(int currentSize);
1464   }
1465 
1466   private static class MyList<T> implements List<T> {
1467     private final List<T> delegatee = new ArrayList<>();
1468     private final MyListHook hookAtAdd;
1469     MyList(final MyListHook hookAtAdd) {
1470       this.hookAtAdd = hookAtAdd;
1471     }
1472     @Override
1473     public int size() {return delegatee.size();}
1474 
1475     @Override
1476     public boolean isEmpty() {return delegatee.isEmpty();}
1477 
1478     @Override
1479     public boolean contains(Object o) {return delegatee.contains(o);}
1480 
1481     @Override
1482     public Iterator<T> iterator() {return delegatee.iterator();}
1483 
1484     @Override
1485     public Object[] toArray() {return delegatee.toArray();}
1486 
1487     @Override
1488     public <T> T[] toArray(T[] a) {return delegatee.toArray(a);}
1489 
1490     @Override
1491     public boolean add(T e) {
1492       hookAtAdd.hook(size());
1493       return delegatee.add(e);
1494     }
1495 
1496     @Override
1497     public boolean remove(Object o) {return delegatee.remove(o);}
1498 
1499     @Override
1500     public boolean containsAll(Collection<?> c) {return delegatee.containsAll(c);}
1501 
1502     @Override
1503     public boolean addAll(Collection<? extends T> c) {return delegatee.addAll(c);}
1504 
1505     @Override
1506     public boolean addAll(int index, Collection<? extends T> c) {return delegatee.addAll(index, c);}
1507 
1508     @Override
1509     public boolean removeAll(Collection<?> c) {return delegatee.removeAll(c);}
1510 
1511     @Override
1512     public boolean retainAll(Collection<?> c) {return delegatee.retainAll(c);}
1513 
1514     @Override
1515     public void clear() {delegatee.clear();}
1516 
1517     @Override
1518     public T get(int index) {return delegatee.get(index);}
1519 
1520     @Override
1521     public T set(int index, T element) {return delegatee.set(index, element);}
1522 
1523     @Override
1524     public void add(int index, T element) {delegatee.add(index, element);}
1525 
1526     @Override
1527     public T remove(int index) {return delegatee.remove(index);}
1528 
1529     @Override
1530     public int indexOf(Object o) {return delegatee.indexOf(o);}
1531 
1532     @Override
1533     public int lastIndexOf(Object o) {return delegatee.lastIndexOf(o);}
1534 
1535     @Override
1536     public ListIterator<T> listIterator() {return delegatee.listIterator();}
1537 
1538     @Override
1539     public ListIterator<T> listIterator(int index) {return delegatee.listIterator(index);}
1540 
1541     @Override
1542     public List<T> subList(int fromIndex, int toIndex) {return delegatee.subList(fromIndex, toIndex);}
1543   }
1544 }