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