001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.regionserver;
019
020import static org.apache.hadoop.hbase.regionserver.StripeStoreFileManager.OPEN_KEY;
021import static org.junit.Assert.assertArrayEquals;
022import static org.junit.Assert.assertEquals;
023import static org.junit.Assert.assertFalse;
024import static org.junit.Assert.assertThrows;
025import static org.junit.Assert.assertTrue;
026
027import java.io.IOException;
028import java.util.ArrayList;
029import java.util.Arrays;
030import java.util.Collection;
031import java.util.Collections;
032import java.util.Iterator;
033import java.util.List;
034import org.apache.hadoop.conf.Configuration;
035import org.apache.hadoop.fs.FileSystem;
036import org.apache.hadoop.fs.Path;
037import org.apache.hadoop.hbase.CellComparatorImpl;
038import org.apache.hadoop.hbase.HBaseClassTestRule;
039import org.apache.hadoop.hbase.HBaseConfiguration;
040import org.apache.hadoop.hbase.HBaseTestingUtility;
041import org.apache.hadoop.hbase.HConstants;
042import org.apache.hadoop.hbase.KeyValue;
043import org.apache.hadoop.hbase.testclassification.MediumTests;
044import org.apache.hadoop.hbase.testclassification.RegionServerTests;
045import org.apache.hadoop.hbase.util.Bytes;
046import org.junit.After;
047import org.junit.Before;
048import org.junit.ClassRule;
049import org.junit.Test;
050import org.junit.experimental.categories.Category;
051import org.mockito.Mockito;
052
053@Category({ RegionServerTests.class, MediumTests.class })
054public class TestStripeStoreFileManager {
055
056  @ClassRule
057  public static final HBaseClassTestRule CLASS_RULE =
058    HBaseClassTestRule.forClass(TestStripeStoreFileManager.class);
059
060  private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
061  private static final Path BASEDIR =
062    TEST_UTIL.getDataTestDir(TestStripeStoreFileManager.class.getSimpleName());
063  private static final Path CFDIR =
064    HRegionFileSystem.getStoreHomedir(BASEDIR, "region", Bytes.toBytes("cf"));
065
066  private static final byte[] KEY_A = Bytes.toBytes("aaa");
067  private static final byte[] KEY_B = Bytes.toBytes("aab");
068  private static final byte[] KEY_C = Bytes.toBytes("aac");
069  private static final byte[] KEY_D = Bytes.toBytes("aad");
070
071  private static final KeyValue KV_A = new KeyValue(KEY_A, 0L);
072  private static final KeyValue KV_B = new KeyValue(KEY_B, 0L);
073  private static final KeyValue KV_C = new KeyValue(KEY_C, 0L);
074  private static final KeyValue KV_D = new KeyValue(KEY_D, 0L);
075
076  @Before
077  public void setUp() throws Exception {
078    FileSystem fs = TEST_UTIL.getTestFileSystem();
079    if (!fs.mkdirs(CFDIR)) {
080      throw new IOException("Cannot create test directory " + CFDIR);
081    }
082  }
083
084  @After
085  public void tearDown() throws Exception {
086    FileSystem fs = TEST_UTIL.getTestFileSystem();
087    if (fs.exists(CFDIR) && !fs.delete(CFDIR, true)) {
088      throw new IOException("Cannot delete test directory " + CFDIR);
089    }
090  }
091
092  @Test
093  public void testInsertFilesIntoL0() throws Exception {
094    StripeStoreFileManager manager = createManager();
095    MockHStoreFile sf = createFile();
096    manager.insertNewFiles(al(sf));
097    assertEquals(1, manager.getStorefileCount());
098    Collection<HStoreFile> filesForGet = manager.getFilesForScan(KEY_A, true, KEY_A, true);
099    assertEquals(1, filesForGet.size());
100    assertTrue(filesForGet.contains(sf));
101
102    // Add some stripes and make sure we get this file for every stripe.
103    manager.addCompactionResults(al(),
104      al(createFile(OPEN_KEY, KEY_B), createFile(KEY_B, OPEN_KEY)));
105    assertTrue(manager.getFilesForScan(KEY_A, true, KEY_A, true).contains(sf));
106    assertTrue(manager.getFilesForScan(KEY_C, true, KEY_C, true).contains(sf));
107  }
108
109  @Test
110  public void testClearFiles() throws Exception {
111    StripeStoreFileManager manager = createManager();
112    manager.insertNewFiles(al(createFile()));
113    manager.insertNewFiles(al(createFile()));
114    manager.addCompactionResults(al(),
115      al(createFile(OPEN_KEY, KEY_B), createFile(KEY_B, OPEN_KEY)));
116    assertEquals(4, manager.getStorefileCount());
117    Collection<HStoreFile> allFiles = manager.clearFiles();
118    assertEquals(4, allFiles.size());
119    assertEquals(0, manager.getStorefileCount());
120    assertEquals(0, manager.getStorefiles().size());
121  }
122
123  private static ArrayList<HStoreFile> dumpIterator(Iterator<HStoreFile> iter) {
124    ArrayList<HStoreFile> result = new ArrayList<>();
125    for (; iter.hasNext(); result.add(iter.next())) {
126      continue;
127    }
128    return result;
129  }
130
131  @Test
132  public void testRowKeyBefore() throws Exception {
133    StripeStoreFileManager manager = createManager();
134    HStoreFile l0File = createFile(), l0File2 = createFile();
135    manager.insertNewFiles(al(l0File));
136    manager.insertNewFiles(al(l0File2));
137    // Get candidate files.
138    Iterator<HStoreFile> sfs = manager.getCandidateFilesForRowKeyBefore(KV_B);
139    sfs.next();
140    sfs.remove();
141    // Suppose we found a candidate in this file... make sure L0 file remaining is not removed.
142    sfs = manager.updateCandidateFilesForRowKeyBefore(sfs, KV_B, KV_A);
143    assertTrue(sfs.hasNext());
144    // Now add some stripes (remove L0 file too)
145    MockHStoreFile stripe0a = createFile(0, 100, OPEN_KEY, KEY_B),
146        stripe1 = createFile(KEY_B, OPEN_KEY);
147    manager.addCompactionResults(al(l0File), al(stripe0a, stripe1));
148    manager.removeCompactedFiles(al(l0File));
149    // If we want a key <= KEY_A, we should get everything except stripe1.
150    ArrayList<HStoreFile> sfsDump = dumpIterator(manager.getCandidateFilesForRowKeyBefore(KV_A));
151    assertEquals(2, sfsDump.size());
152    assertTrue(sfsDump.contains(stripe0a));
153    assertFalse(sfsDump.contains(stripe1));
154    // If we want a key <= KEY_B, we should get everything since lower bound is inclusive.
155    sfsDump = dumpIterator(manager.getCandidateFilesForRowKeyBefore(KV_B));
156    assertEquals(3, sfsDump.size());
157    assertTrue(sfsDump.contains(stripe1));
158    // For KEY_D, we should also get everything.
159    sfsDump = dumpIterator(manager.getCandidateFilesForRowKeyBefore(KV_D));
160    assertEquals(3, sfsDump.size());
161    // Suppose in the first file we found candidate with KEY_C.
162    // Then, stripe0 no longer matters and should be removed, but stripe1 should stay.
163    sfs = manager.getCandidateFilesForRowKeyBefore(KV_D);
164    sfs.next(); // Skip L0 file.
165    sfs.remove();
166    sfs = manager.updateCandidateFilesForRowKeyBefore(sfs, KV_D, KV_C);
167    assertEquals(stripe1, sfs.next());
168    assertFalse(sfs.hasNext());
169    // Add one more, later, file to stripe0, remove the last annoying L0 file.
170    // This file should be returned in preference to older L0 file; also, after we get
171    // a candidate from the first file, the old one should not be removed.
172    HStoreFile stripe0b = createFile(0, 101, OPEN_KEY, KEY_B);
173    manager.addCompactionResults(al(l0File2), al(stripe0b));
174    manager.removeCompactedFiles(al(l0File2));
175    sfs = manager.getCandidateFilesForRowKeyBefore(KV_A);
176    assertEquals(stripe0b, sfs.next());
177    sfs.remove();
178    sfs = manager.updateCandidateFilesForRowKeyBefore(sfs, KV_A, KV_A);
179    assertEquals(stripe0a, sfs.next());
180  }
181
182  @Test
183  public void testGetSplitPointEdgeCases() throws Exception {
184    StripeStoreFileManager manager = createManager();
185    // No files => no split.
186    assertFalse(manager.getSplitPoint().isPresent());
187
188    // If there are no stripes, should pick midpoint from the biggest file in L0.
189    MockHStoreFile sf5 = createFile(5, 0);
190    sf5.splitPoint = new byte[] { 1 };
191    manager.insertNewFiles(al(sf5));
192    manager.insertNewFiles(al(createFile(1, 0)));
193    assertArrayEquals(sf5.splitPoint, manager.getSplitPoint().get());
194
195    // Same if there's one stripe but the biggest file is still in L0.
196    manager.addCompactionResults(al(), al(createFile(2, 0, OPEN_KEY, OPEN_KEY)));
197    assertArrayEquals(sf5.splitPoint, manager.getSplitPoint().get());
198
199    // If the biggest file is in the stripe, should get from it.
200    MockHStoreFile sf6 = createFile(6, 0, OPEN_KEY, OPEN_KEY);
201    sf6.splitPoint = new byte[] { 2 };
202    manager.addCompactionResults(al(), al(sf6));
203    assertArrayEquals(sf6.splitPoint, manager.getSplitPoint().get());
204  }
205
206  @Test
207  public void testGetStripeBoundarySplits() throws Exception {
208    /* First number - split must be after this stripe; further numbers - stripes */
209    verifySplitPointScenario(5, false, 0f, 2, 1, 1, 1, 1, 1, 10);
210    verifySplitPointScenario(0, false, 0f, 6, 3, 1, 1, 2);
211    verifySplitPointScenario(2, false, 0f, 1, 1, 1, 1, 2);
212    verifySplitPointScenario(0, false, 0f, 5, 4);
213    verifySplitPointScenario(2, false, 0f, 5, 2, 5, 5, 5);
214  }
215
216  @Test
217  public void testGetUnbalancedSplits() throws Exception {
218    /* First number - split must be inside/after this stripe; further numbers - stripes */
219    verifySplitPointScenario(0, false, 2.1f, 4, 4, 4); // 8/4 is less than 2.1f
220    verifySplitPointScenario(1, true, 1.5f, 4, 4, 4); // 8/4 > 6/6
221    verifySplitPointScenario(1, false, 1.1f, 3, 4, 1, 1, 2, 2); // 7/6 < 8/5
222    verifySplitPointScenario(1, false, 1.1f, 3, 6, 1, 1, 2, 2); // 9/6 == 9/6
223    verifySplitPointScenario(1, true, 1.1f, 3, 8, 1, 1, 2, 2); // 11/6 > 10/7
224    verifySplitPointScenario(3, false, 1.1f, 2, 2, 1, 1, 4, 3); // reverse order
225    verifySplitPointScenario(4, true, 1.1f, 2, 2, 1, 1, 8, 3); // reverse order
226    verifySplitPointScenario(0, true, 1.5f, 10, 4); // 10/4 > 9/5
227    verifySplitPointScenario(0, false, 1.4f, 6, 4); // 6/4 == 6/4
228    verifySplitPointScenario(1, true, 1.5f, 4, 10); // reverse just in case
229    verifySplitPointScenario(0, false, 1.4f, 4, 6); // reverse just in case
230  }
231
232  /**
233   * Verifies scenario for finding a split point.
234   * @param splitPointAfter    Stripe to expect the split point at/after.
235   * @param shouldSplitStripe  If true, the split point is expected in the middle of the above
236   *                           stripe; if false, should be at the end.
237   * @param splitRatioToVerify Maximum split imbalance ratio.
238   * @param sizes              Stripe sizes.
239   */
240  private void verifySplitPointScenario(int splitPointAfter, boolean shouldSplitStripe,
241    float splitRatioToVerify, int... sizes) throws Exception {
242    assertTrue(sizes.length > 1);
243    ArrayList<HStoreFile> sfs = new ArrayList<>();
244    for (int sizeIx = 0; sizeIx < sizes.length; ++sizeIx) {
245      byte[] startKey = (sizeIx == 0) ? OPEN_KEY : Bytes.toBytes(sizeIx - 1);
246      byte[] endKey = (sizeIx == sizes.length - 1) ? OPEN_KEY : Bytes.toBytes(sizeIx);
247      MockHStoreFile sf = createFile(sizes[sizeIx], 0, startKey, endKey);
248      sf.splitPoint = Bytes.toBytes(-sizeIx); // set split point to the negative index
249      sfs.add(sf);
250    }
251
252    Configuration conf = HBaseConfiguration.create();
253    if (splitRatioToVerify != 0) {
254      conf.setFloat(StripeStoreConfig.MAX_REGION_SPLIT_IMBALANCE_KEY, splitRatioToVerify);
255    }
256    StripeStoreFileManager manager = createManager(al(), conf);
257    manager.addCompactionResults(al(), sfs);
258    int result = Bytes.toInt(manager.getSplitPoint().get());
259    // Either end key and thus positive index, or "middle" of the file and thus negative index.
260    assertEquals(splitPointAfter * (shouldSplitStripe ? -1 : 1), result);
261  }
262
263  private static byte[] keyAfter(byte[] key) {
264    return Arrays.copyOf(key, key.length + 1);
265  }
266
267  @Test
268  public void testGetFilesForGetAndScan() throws Exception {
269    StripeStoreFileManager manager = createManager();
270    verifyGetAndScanScenario(manager, null, null);
271    verifyGetAndScanScenario(manager, KEY_B, KEY_C);
272
273    // Populate one L0 file.
274    MockHStoreFile sf0 = createFile();
275    manager.insertNewFiles(al(sf0));
276    verifyGetAndScanScenario(manager, null, null, sf0);
277    verifyGetAndScanScenario(manager, null, KEY_C, sf0);
278    verifyGetAndScanScenario(manager, KEY_B, null, sf0);
279    verifyGetAndScanScenario(manager, KEY_B, KEY_C, sf0);
280
281    // Populate a bunch of files for stripes, keep L0.
282    MockHStoreFile sfA = createFile(OPEN_KEY, KEY_A);
283    MockHStoreFile sfB = createFile(KEY_A, KEY_B);
284    MockHStoreFile sfC = createFile(KEY_B, KEY_C);
285    MockHStoreFile sfD = createFile(KEY_C, KEY_D);
286    MockHStoreFile sfE = createFile(KEY_D, OPEN_KEY);
287    manager.addCompactionResults(al(), al(sfA, sfB, sfC, sfD, sfE));
288
289    verifyGetAndScanScenario(manager, null, null, sf0, sfA, sfB, sfC, sfD, sfE);
290    verifyGetAndScanScenario(manager, keyAfter(KEY_A), null, sf0, sfB, sfC, sfD, sfE);
291    verifyGetAndScanScenario(manager, null, keyAfter(KEY_C), sf0, sfA, sfB, sfC, sfD);
292    verifyGetAndScanScenario(manager, KEY_B, null, sf0, sfC, sfD, sfE);
293    verifyGetAndScanScenario(manager, null, KEY_C, sf0, sfA, sfB, sfC, sfD);
294    verifyGetAndScanScenario(manager, KEY_B, keyAfter(KEY_B), sf0, sfC);
295    verifyGetAndScanScenario(manager, keyAfter(KEY_A), KEY_B, sf0, sfB, sfC);
296    verifyGetAndScanScenario(manager, KEY_D, KEY_D, sf0, sfE);
297    verifyGetAndScanScenario(manager, keyAfter(KEY_B), keyAfter(KEY_C), sf0, sfC, sfD);
298  }
299
300  private void verifyGetAndScanScenario(StripeStoreFileManager manager, byte[] start, byte[] end,
301    HStoreFile... results) throws Exception {
302    verifyGetOrScanScenario(manager, start, end, results);
303  }
304
305  @Test
306  @SuppressWarnings("unchecked")
307  public void testLoadFilesWithRecoverableBadFiles() throws Exception {
308    // In L0, there will be file w/o metadata (real L0, 3 files with invalid metadata, and 3
309    // files that overlap valid stripes in various ways). Note that the 4th way to overlap the
310    // stripes will cause the structure to be mostly scraped, and is tested separately.
311    ArrayList<HStoreFile> validStripeFiles = al(createFile(OPEN_KEY, KEY_B),
312      createFile(KEY_B, KEY_C), createFile(KEY_C, OPEN_KEY), createFile(KEY_C, OPEN_KEY));
313    ArrayList<HStoreFile> filesToGoToL0 = al(createFile(), createFile(null, KEY_A),
314      createFile(KEY_D, null), createFile(KEY_D, KEY_A), createFile(keyAfter(KEY_A), KEY_C),
315      createFile(OPEN_KEY, KEY_D), createFile(KEY_D, keyAfter(KEY_D)));
316    ArrayList<HStoreFile> allFilesToGo = flattenLists(validStripeFiles, filesToGoToL0);
317    Collections.shuffle(allFilesToGo);
318    StripeStoreFileManager manager = createManager(allFilesToGo);
319    List<HStoreFile> l0Files = manager.getLevel0Files();
320    assertEquals(filesToGoToL0.size(), l0Files.size());
321    for (HStoreFile sf : filesToGoToL0) {
322      assertTrue(l0Files.contains(sf));
323    }
324    verifyAllFiles(manager, allFilesToGo);
325  }
326
327  @Test
328  public void testLoadFilesWithBadStripe() throws Exception {
329    // Current "algorithm" will see the after-B key before C key, add it as valid stripe,
330    // and then fail all other stripes. So everything would end up in L0.
331    ArrayList<HStoreFile> allFilesToGo = al(createFile(OPEN_KEY, KEY_B), createFile(KEY_B, KEY_C),
332      createFile(KEY_C, OPEN_KEY), createFile(KEY_B, keyAfter(KEY_B)));
333    Collections.shuffle(allFilesToGo);
334    StripeStoreFileManager manager = createManager(allFilesToGo);
335    assertEquals(allFilesToGo.size(), manager.getLevel0Files().size());
336  }
337
338  @Test
339  public void testLoadFilesWithGaps() throws Exception {
340    // Stripes must not have gaps. If they do, everything goes to L0.
341    StripeStoreFileManager manager =
342      createManager(al(createFile(OPEN_KEY, KEY_B), createFile(KEY_C, OPEN_KEY)));
343    assertEquals(2, manager.getLevel0Files().size());
344    // Just one open stripe should be ok.
345    manager = createManager(al(createFile(OPEN_KEY, OPEN_KEY)));
346    assertEquals(0, manager.getLevel0Files().size());
347    assertEquals(1, manager.getStorefileCount());
348  }
349
350  @Test
351  public void testLoadFilesAfterSplit() throws Exception {
352    // If stripes are good but have non-open ends, they must be treated as open ends.
353    MockHStoreFile sf = createFile(KEY_B, KEY_C);
354    StripeStoreFileManager manager = createManager(al(createFile(OPEN_KEY, KEY_B), sf));
355    assertEquals(0, manager.getLevel0Files().size());
356    // Here, [B, C] is logically [B, inf), so we should be able to compact it to that only.
357    verifyInvalidCompactionScenario(manager, al(sf), al(createFile(KEY_B, KEY_C)));
358    manager.addCompactionResults(al(sf), al(createFile(KEY_B, OPEN_KEY)));
359    manager.removeCompactedFiles(al(sf));
360    // Do the same for other variants.
361    manager = createManager(al(sf, createFile(KEY_C, OPEN_KEY)));
362    verifyInvalidCompactionScenario(manager, al(sf), al(createFile(KEY_B, KEY_C)));
363    manager.addCompactionResults(al(sf), al(createFile(OPEN_KEY, KEY_C)));
364    manager.removeCompactedFiles(al(sf));
365    manager = createManager(al(sf));
366    verifyInvalidCompactionScenario(manager, al(sf), al(createFile(KEY_B, KEY_C)));
367    manager.addCompactionResults(al(sf), al(createFile(OPEN_KEY, OPEN_KEY)));
368  }
369
370  @Test
371  public void testAddingCompactionResults() throws Exception {
372    StripeStoreFileManager manager = createManager();
373    // First, add some L0 files and "compact" one with new stripe creation.
374    HStoreFile sf_L0_0a = createFile(), sf_L0_0b = createFile();
375    manager.insertNewFiles(al(sf_L0_0a, sf_L0_0b));
376
377    // Try compacting with invalid new branches (gaps, overlaps) - no effect.
378    verifyInvalidCompactionScenario(manager, al(sf_L0_0a), al(createFile(OPEN_KEY, KEY_B)));
379    verifyInvalidCompactionScenario(manager, al(sf_L0_0a),
380      al(createFile(OPEN_KEY, KEY_B), createFile(KEY_C, OPEN_KEY)));
381    verifyInvalidCompactionScenario(manager, al(sf_L0_0a),
382      al(createFile(OPEN_KEY, KEY_B), createFile(KEY_B, OPEN_KEY), createFile(KEY_A, KEY_D)));
383    verifyInvalidCompactionScenario(manager, al(sf_L0_0a),
384      al(createFile(OPEN_KEY, KEY_B), createFile(KEY_A, KEY_B), createFile(KEY_B, OPEN_KEY)));
385
386    HStoreFile sf_i2B_0 = createFile(OPEN_KEY, KEY_B);
387    HStoreFile sf_B2C_0 = createFile(KEY_B, KEY_C);
388    HStoreFile sf_C2i_0 = createFile(KEY_C, OPEN_KEY);
389    manager.addCompactionResults(al(sf_L0_0a), al(sf_i2B_0, sf_B2C_0, sf_C2i_0));
390    manager.removeCompactedFiles(al(sf_L0_0a));
391    verifyAllFiles(manager, al(sf_L0_0b, sf_i2B_0, sf_B2C_0, sf_C2i_0));
392
393    // Add another l0 file, "compact" both L0 into two stripes
394    HStoreFile sf_L0_1 = createFile();
395    HStoreFile sf_i2B_1 = createFile(OPEN_KEY, KEY_B);
396    HStoreFile sf_B2C_1 = createFile(KEY_B, KEY_C);
397    manager.insertNewFiles(al(sf_L0_1));
398    manager.addCompactionResults(al(sf_L0_0b, sf_L0_1), al(sf_i2B_1, sf_B2C_1));
399    manager.removeCompactedFiles(al(sf_L0_0b, sf_L0_1));
400    verifyAllFiles(manager, al(sf_i2B_0, sf_B2C_0, sf_C2i_0, sf_i2B_1, sf_B2C_1));
401
402    // Try compacting with invalid file (no metadata) - should add files to L0.
403    HStoreFile sf_L0_2 = createFile(null, null);
404    manager.addCompactionResults(al(), al(sf_L0_2));
405    manager.removeCompactedFiles(al());
406    verifyAllFiles(manager, al(sf_i2B_0, sf_B2C_0, sf_C2i_0, sf_i2B_1, sf_B2C_1, sf_L0_2));
407    // Remove it...
408    manager.addCompactionResults(al(sf_L0_2), al());
409    manager.removeCompactedFiles(al(sf_L0_2));
410
411    // Do regular compaction in the first stripe.
412    HStoreFile sf_i2B_3 = createFile(OPEN_KEY, KEY_B);
413    manager.addCompactionResults(al(sf_i2B_0, sf_i2B_1), al(sf_i2B_3));
414    manager.removeCompactedFiles(al(sf_i2B_0, sf_i2B_1));
415    verifyAllFiles(manager, al(sf_B2C_0, sf_C2i_0, sf_B2C_1, sf_i2B_3));
416
417    // Rebalance two stripes.
418    HStoreFile sf_B2D_4 = createFile(KEY_B, KEY_D);
419    HStoreFile sf_D2i_4 = createFile(KEY_D, OPEN_KEY);
420    manager.addCompactionResults(al(sf_B2C_0, sf_C2i_0, sf_B2C_1), al(sf_B2D_4, sf_D2i_4));
421    manager.removeCompactedFiles(al(sf_B2C_0, sf_C2i_0, sf_B2C_1));
422    verifyAllFiles(manager, al(sf_i2B_3, sf_B2D_4, sf_D2i_4));
423
424    // Split the first stripe.
425    HStoreFile sf_i2A_5 = createFile(OPEN_KEY, KEY_A);
426    HStoreFile sf_A2B_5 = createFile(KEY_A, KEY_B);
427    manager.addCompactionResults(al(sf_i2B_3), al(sf_i2A_5, sf_A2B_5));
428    manager.removeCompactedFiles(al(sf_i2B_3));
429    verifyAllFiles(manager, al(sf_B2D_4, sf_D2i_4, sf_i2A_5, sf_A2B_5));
430
431    // Split the middle stripe.
432    HStoreFile sf_B2C_6 = createFile(KEY_B, KEY_C);
433    HStoreFile sf_C2D_6 = createFile(KEY_C, KEY_D);
434    manager.addCompactionResults(al(sf_B2D_4), al(sf_B2C_6, sf_C2D_6));
435    manager.removeCompactedFiles(al(sf_B2D_4));
436    verifyAllFiles(manager, al(sf_D2i_4, sf_i2A_5, sf_A2B_5, sf_B2C_6, sf_C2D_6));
437
438    // Merge two different middle stripes.
439    HStoreFile sf_A2C_7 = createFile(KEY_A, KEY_C);
440    manager.addCompactionResults(al(sf_A2B_5, sf_B2C_6), al(sf_A2C_7));
441    manager.removeCompactedFiles(al(sf_A2B_5, sf_B2C_6));
442    verifyAllFiles(manager, al(sf_D2i_4, sf_i2A_5, sf_C2D_6, sf_A2C_7));
443
444    // Merge lower half.
445    HStoreFile sf_i2C_8 = createFile(OPEN_KEY, KEY_C);
446    manager.addCompactionResults(al(sf_i2A_5, sf_A2C_7), al(sf_i2C_8));
447    manager.removeCompactedFiles(al(sf_i2A_5, sf_A2C_7));
448    verifyAllFiles(manager, al(sf_D2i_4, sf_C2D_6, sf_i2C_8));
449
450    // Merge all.
451    HStoreFile sf_i2i_9 = createFile(OPEN_KEY, OPEN_KEY);
452    manager.addCompactionResults(al(sf_D2i_4, sf_C2D_6, sf_i2C_8), al(sf_i2i_9));
453    manager.removeCompactedFiles(al(sf_D2i_4, sf_C2D_6, sf_i2C_8));
454    verifyAllFiles(manager, al(sf_i2i_9));
455  }
456
457  @Test
458  public void testCompactionAndFlushConflict() throws Exception {
459    // Add file flush into stripes
460    StripeStoreFileManager sfm = createManager();
461    assertEquals(0, sfm.getStripeCount());
462    HStoreFile sf_i2c = createFile(OPEN_KEY, KEY_C), sf_c2i = createFile(KEY_C, OPEN_KEY);
463    sfm.insertNewFiles(al(sf_i2c, sf_c2i));
464    assertEquals(2, sfm.getStripeCount());
465    // Now try to add conflicting flush - should throw.
466    HStoreFile sf_i2d = createFile(OPEN_KEY, KEY_D), sf_d2i = createFile(KEY_D, OPEN_KEY);
467    sfm.insertNewFiles(al(sf_i2d, sf_d2i));
468    assertEquals(2, sfm.getStripeCount());
469    assertEquals(2, sfm.getLevel0Files().size());
470    verifyGetAndScanScenario(sfm, KEY_C, KEY_C, sf_i2d, sf_d2i, sf_c2i);
471    // Remove these files.
472    sfm.addCompactionResults(al(sf_i2d, sf_d2i), al());
473    sfm.removeCompactedFiles(al(sf_i2d, sf_d2i));
474    assertEquals(0, sfm.getLevel0Files().size());
475    // Add another file to stripe; then "rebalance" stripes w/o it - the file, which was
476    // presumably flushed during compaction, should go to L0.
477    HStoreFile sf_i2c_2 = createFile(OPEN_KEY, KEY_C);
478    sfm.insertNewFiles(al(sf_i2c_2));
479    sfm.addCompactionResults(al(sf_i2c, sf_c2i), al(sf_i2d, sf_d2i));
480    sfm.removeCompactedFiles(al(sf_i2c, sf_c2i));
481    assertEquals(1, sfm.getLevel0Files().size());
482    verifyGetAndScanScenario(sfm, KEY_C, KEY_C, sf_i2d, sf_i2c_2);
483  }
484
485  @Test
486  public void testEmptyResultsForStripes() throws Exception {
487    // Test that we can compact L0 into a subset of stripes.
488    StripeStoreFileManager manager = createManager();
489    HStoreFile sf0a = createFile();
490    HStoreFile sf0b = createFile();
491    manager.insertNewFiles(al(sf0a));
492    manager.insertNewFiles(al(sf0b));
493    ArrayList<HStoreFile> compacted =
494      al(createFile(OPEN_KEY, KEY_B), createFile(KEY_B, KEY_C), createFile(KEY_C, OPEN_KEY));
495    manager.addCompactionResults(al(sf0a), compacted);
496    manager.removeCompactedFiles(al(sf0a));
497    // Next L0 compaction only produces file for the first and last stripe.
498    ArrayList<HStoreFile> compacted2 = al(createFile(OPEN_KEY, KEY_B), createFile(KEY_C, OPEN_KEY));
499    manager.addCompactionResults(al(sf0b), compacted2);
500    manager.removeCompactedFiles(al(sf0b));
501    compacted.addAll(compacted2);
502    verifyAllFiles(manager, compacted);
503  }
504
505  @Test
506  public void testPriority() throws Exception {
507    // Expected priority, file limit, stripe count, files per stripe, l0 files.
508    testPriorityScenario(5, 5, 0, 0, 0);
509    testPriorityScenario(2, 5, 0, 0, 3);
510    testPriorityScenario(4, 25, 5, 1, 0); // example case.
511    testPriorityScenario(3, 25, 5, 1, 1); // L0 files counts for all stripes.
512    testPriorityScenario(3, 25, 5, 2, 0); // file to each stripe - same as one L0 file.
513    testPriorityScenario(2, 25, 5, 4, 0); // 1 is priority user, so 2 is returned.
514    testPriorityScenario(2, 25, 5, 4, 4); // don't return higher than user unless over limit.
515    testPriorityScenario(2, 25, 5, 1, 10); // same.
516    testPriorityScenario(0, 25, 5, 4, 5); // at limit.
517    testPriorityScenario(-5, 25, 5, 6, 0); // over limit!
518    testPriorityScenario(-1, 25, 0, 0, 26); // over limit with just L0
519  }
520
521  private void testPriorityScenario(int expectedPriority, int limit, int stripes, int filesInStripe,
522    int l0Files) throws Exception {
523    final byte[][] keys = { KEY_A, KEY_B, KEY_C, KEY_D };
524    assertTrue(stripes <= keys.length + 1);
525    Configuration conf = TEST_UTIL.getConfiguration();
526    conf.setInt("hbase.hstore.blockingStoreFiles", limit);
527    StripeStoreFileManager sfm = createManager(al(), conf);
528    for (int i = 0; i < l0Files; ++i) {
529      sfm.insertNewFiles(al(createFile()));
530    }
531    for (int i = 0; i < filesInStripe; ++i) {
532      ArrayList<HStoreFile> stripe = new ArrayList<>();
533      for (int j = 0; j < stripes; ++j) {
534        stripe.add(
535          createFile((j == 0) ? OPEN_KEY : keys[j - 1], (j == stripes - 1) ? OPEN_KEY : keys[j]));
536      }
537      sfm.addCompactionResults(al(), stripe);
538    }
539    assertEquals(expectedPriority, sfm.getStoreCompactionPriority());
540  }
541
542  private void verifyInvalidCompactionScenario(StripeStoreFileManager manager,
543    ArrayList<HStoreFile> filesToCompact, ArrayList<HStoreFile> filesToInsert) throws Exception {
544    Collection<HStoreFile> allFiles = manager.getStorefiles();
545    assertThrows(IllegalStateException.class,
546      () -> manager.addCompactionResults(filesToCompact, filesToInsert));
547    verifyAllFiles(manager, allFiles); // must have the same files.
548  }
549
550  private void verifyGetOrScanScenario(StripeStoreFileManager manager, byte[] start, byte[] end,
551    HStoreFile... results) throws Exception {
552    verifyGetOrScanScenario(manager, start, end, Arrays.asList(results));
553  }
554
555  private void verifyGetOrScanScenario(StripeStoreFileManager manager, byte[] start, byte[] end,
556    Collection<HStoreFile> results) throws Exception {
557    start = start != null ? start : HConstants.EMPTY_START_ROW;
558    end = end != null ? end : HConstants.EMPTY_END_ROW;
559    Collection<HStoreFile> sfs = manager.getFilesForScan(start, true, end, false);
560    assertEquals(results.size(), sfs.size());
561    for (HStoreFile result : results) {
562      assertTrue(sfs.contains(result));
563    }
564  }
565
566  private void verifyAllFiles(StripeStoreFileManager manager, Collection<HStoreFile> results)
567    throws Exception {
568    verifyGetOrScanScenario(manager, null, null, results);
569  }
570
571  // TODO: replace with Mockito?
572  private static MockHStoreFile createFile(long size, long seqNum, byte[] startKey, byte[] endKey)
573    throws Exception {
574    FileSystem fs = TEST_UTIL.getTestFileSystem();
575    Path testFilePath = StoreFileWriter.getUniqueFile(fs, CFDIR);
576    fs.create(testFilePath).close();
577    MockHStoreFile sf = new MockHStoreFile(TEST_UTIL, testFilePath, size, 0, false, seqNum);
578    if (startKey != null) {
579      sf.setMetadataValue(StripeStoreFileManager.STRIPE_START_KEY, startKey);
580    }
581    if (endKey != null) {
582      sf.setMetadataValue(StripeStoreFileManager.STRIPE_END_KEY, endKey);
583    }
584    return sf;
585  }
586
587  private static MockHStoreFile createFile(long size, long seqNum) throws Exception {
588    return createFile(size, seqNum, null, null);
589  }
590
591  private static MockHStoreFile createFile(byte[] startKey, byte[] endKey) throws Exception {
592    return createFile(0, 0, startKey, endKey);
593  }
594
595  private static MockHStoreFile createFile() throws Exception {
596    return createFile(null, null);
597  }
598
599  private static StripeStoreFileManager createManager() throws Exception {
600    return createManager(new ArrayList<>());
601  }
602
603  private static StripeStoreFileManager createManager(ArrayList<HStoreFile> sfs) throws Exception {
604    return createManager(sfs, TEST_UTIL.getConfiguration());
605  }
606
607  private static StripeStoreFileManager createManager(ArrayList<HStoreFile> sfs, Configuration conf)
608    throws Exception {
609    StripeStoreConfig config =
610      new StripeStoreConfig(conf, Mockito.mock(StoreConfigInformation.class));
611    StripeStoreFileManager result =
612      new StripeStoreFileManager(CellComparatorImpl.COMPARATOR, conf, config);
613    result.loadFiles(sfs);
614    return result;
615  }
616
617  private static ArrayList<HStoreFile> al(HStoreFile... sfs) {
618    return new ArrayList<>(Arrays.asList(sfs));
619  }
620
621  private static ArrayList<HStoreFile> flattenLists(ArrayList<HStoreFile>... sfls) {
622    ArrayList<HStoreFile> result = new ArrayList<>();
623    for (ArrayList<HStoreFile> sfl : sfls) {
624      result.addAll(sfl);
625    }
626    return result;
627  }
628}