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.HBaseTestingUtil;
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 HBaseTestingUtil TEST_UTIL = new HBaseTestingUtil();
061  private static final Path BASEDIR =
062      TEST_UTIL.getDataTestDir(TestStripeStoreFileManager.class.getSimpleName());
063  private static final Path CFDIR = HRegionFileSystem.getStoreHomedir(BASEDIR, "region",
064    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(), al(createFile(OPEN_KEY, KEY_B),
104        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(), al(createFile(OPEN_KEY, KEY_B),
115        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  /**
234   * Verifies scenario for finding a split point.
235   * @param splitPointAfter Stripe to expect the split point at/after.
236   * @param shouldSplitStripe If true, the split point is expected in the middle of the above
237   *                          stripe; if false, should be at the end.
238   * @param splitRatioToVerify Maximum split imbalance ratio.
239   * @param sizes Stripe sizes.
240   */
241  private void verifySplitPointScenario(int splitPointAfter, boolean shouldSplitStripe,
242      float splitRatioToVerify, int... sizes) throws Exception {
243    assertTrue(sizes.length > 1);
244    ArrayList<HStoreFile> sfs = new ArrayList<>();
245    for (int sizeIx = 0; sizeIx < sizes.length; ++sizeIx) {
246      byte[] startKey = (sizeIx == 0) ? OPEN_KEY : Bytes.toBytes(sizeIx - 1);
247      byte[] endKey = (sizeIx == sizes.length - 1) ? OPEN_KEY : Bytes.toBytes(sizeIx);
248      MockHStoreFile sf = createFile(sizes[sizeIx], 0, startKey, endKey);
249      sf.splitPoint = Bytes.toBytes(-sizeIx); // set split point to the negative index
250      sfs.add(sf);
251    }
252
253    Configuration conf = HBaseConfiguration.create();
254    if (splitRatioToVerify != 0) {
255      conf.setFloat(StripeStoreConfig.MAX_REGION_SPLIT_IMBALANCE_KEY, splitRatioToVerify);
256    }
257    StripeStoreFileManager manager = createManager(al(), conf);
258    manager.addCompactionResults(al(), sfs);
259    int result = Bytes.toInt(manager.getSplitPoint().get());
260    // Either end key and thus positive index, or "middle" of the file and thus negative index.
261    assertEquals(splitPointAfter * (shouldSplitStripe ? -1 : 1), result);
262  }
263
264  private static byte[] keyAfter(byte[] key) {
265    return Arrays.copyOf(key, key.length + 1);
266  }
267
268  @Test
269  public void testGetFilesForGetAndScan() throws Exception {
270    StripeStoreFileManager manager = createManager();
271    verifyGetAndScanScenario(manager, null, null);
272    verifyGetAndScanScenario(manager, KEY_B, KEY_C);
273
274    // Populate one L0 file.
275    MockHStoreFile sf0 = createFile();
276    manager.insertNewFiles(al(sf0));
277    verifyGetAndScanScenario(manager, null, null,   sf0);
278    verifyGetAndScanScenario(manager, null, KEY_C,  sf0);
279    verifyGetAndScanScenario(manager, KEY_B, null,  sf0);
280    verifyGetAndScanScenario(manager, KEY_B, KEY_C, sf0);
281
282    // Populate a bunch of files for stripes, keep L0.
283    MockHStoreFile sfA = createFile(OPEN_KEY, KEY_A);
284    MockHStoreFile sfB = createFile(KEY_A, KEY_B);
285    MockHStoreFile sfC = createFile(KEY_B, KEY_C);
286    MockHStoreFile sfD = createFile(KEY_C, KEY_D);
287    MockHStoreFile sfE = createFile(KEY_D, OPEN_KEY);
288    manager.addCompactionResults(al(), al(sfA, sfB, sfC, sfD, sfE));
289
290    verifyGetAndScanScenario(manager, null, null,              sf0, sfA, sfB, sfC, sfD, sfE);
291    verifyGetAndScanScenario(manager, keyAfter(KEY_A), null,   sf0, sfB, sfC, sfD, sfE);
292    verifyGetAndScanScenario(manager, null, keyAfter(KEY_C),   sf0, sfA, sfB, sfC, sfD);
293    verifyGetAndScanScenario(manager, KEY_B, null,             sf0, sfC, sfD, sfE);
294    verifyGetAndScanScenario(manager, null, KEY_C,             sf0, sfA, sfB, sfC, sfD);
295    verifyGetAndScanScenario(manager, KEY_B, keyAfter(KEY_B),  sf0, sfC);
296    verifyGetAndScanScenario(manager, keyAfter(KEY_A), KEY_B,  sf0, sfB, sfC);
297    verifyGetAndScanScenario(manager, KEY_D, KEY_D,            sf0, sfE);
298    verifyGetAndScanScenario(manager, keyAfter(KEY_B), keyAfter(KEY_C), sf0, sfC, sfD);
299  }
300
301  private void verifyGetAndScanScenario(StripeStoreFileManager manager, byte[] start, byte[] end,
302      HStoreFile... results) throws Exception {
303    verifyGetOrScanScenario(manager, start, end, results);
304  }
305
306  @Test
307  @SuppressWarnings("unchecked")
308  public void testLoadFilesWithRecoverableBadFiles() throws Exception {
309    // In L0, there will be file w/o metadata (real L0, 3 files with invalid metadata, and 3
310    // files that overlap valid stripes in various ways). Note that the 4th way to overlap the
311    // stripes will cause the structure to be mostly scraped, and is tested separately.
312    ArrayList<HStoreFile> validStripeFiles = al(createFile(OPEN_KEY, KEY_B),
313        createFile(KEY_B, KEY_C), createFile(KEY_C, OPEN_KEY),
314        createFile(KEY_C, OPEN_KEY));
315    ArrayList<HStoreFile> filesToGoToL0 = al(createFile(), createFile(null, KEY_A),
316        createFile(KEY_D, null), createFile(KEY_D, KEY_A), createFile(keyAfter(KEY_A), KEY_C),
317        createFile(OPEN_KEY, KEY_D), createFile(KEY_D, keyAfter(KEY_D)));
318    ArrayList<HStoreFile> allFilesToGo = flattenLists(validStripeFiles, filesToGoToL0);
319    Collections.shuffle(allFilesToGo);
320    StripeStoreFileManager manager = createManager(allFilesToGo);
321    List<HStoreFile> l0Files = manager.getLevel0Files();
322    assertEquals(filesToGoToL0.size(), l0Files.size());
323    for (HStoreFile sf : filesToGoToL0) {
324      assertTrue(l0Files.contains(sf));
325    }
326    verifyAllFiles(manager, allFilesToGo);
327  }
328
329  @Test
330  public void testLoadFilesWithBadStripe() throws Exception {
331    // Current "algorithm" will see the after-B key before C key, add it as valid stripe,
332    // and then fail all other stripes. So everything would end up in L0.
333    ArrayList<HStoreFile> allFilesToGo = al(createFile(OPEN_KEY, KEY_B),
334        createFile(KEY_B, KEY_C), createFile(KEY_C, OPEN_KEY),
335        createFile(KEY_B, keyAfter(KEY_B)));
336    Collections.shuffle(allFilesToGo);
337    StripeStoreFileManager manager = createManager(allFilesToGo);
338    assertEquals(allFilesToGo.size(), manager.getLevel0Files().size());
339  }
340
341  @Test
342  public void testLoadFilesWithGaps() throws Exception {
343    // Stripes must not have gaps. If they do, everything goes to L0.
344    StripeStoreFileManager manager =
345      createManager(al(createFile(OPEN_KEY, KEY_B), createFile(KEY_C, OPEN_KEY)));
346    assertEquals(2, manager.getLevel0Files().size());
347    // Just one open stripe should be ok.
348    manager = createManager(al(createFile(OPEN_KEY, OPEN_KEY)));
349    assertEquals(0, manager.getLevel0Files().size());
350    assertEquals(1, manager.getStorefileCount());
351  }
352
353  @Test
354  public void testLoadFilesAfterSplit() throws Exception {
355    // If stripes are good but have non-open ends, they must be treated as open ends.
356    MockHStoreFile sf = createFile(KEY_B, KEY_C);
357    StripeStoreFileManager manager = createManager(al(createFile(OPEN_KEY, KEY_B), sf));
358    assertEquals(0, manager.getLevel0Files().size());
359    // Here, [B, C] is logically [B, inf), so we should be able to compact it to that only.
360    verifyInvalidCompactionScenario(manager, al(sf), al(createFile(KEY_B, KEY_C)));
361    manager.addCompactionResults(al(sf), al(createFile(KEY_B, OPEN_KEY)));
362    manager.removeCompactedFiles(al(sf));
363    // Do the same for other variants.
364    manager = createManager(al(sf, createFile(KEY_C, OPEN_KEY)));
365    verifyInvalidCompactionScenario(manager, al(sf), al(createFile(KEY_B, KEY_C)));
366    manager.addCompactionResults(al(sf), al(createFile(OPEN_KEY, KEY_C)));
367    manager.removeCompactedFiles(al(sf));
368    manager = createManager(al(sf));
369    verifyInvalidCompactionScenario(manager, al(sf), al(createFile(KEY_B, KEY_C)));
370    manager.addCompactionResults(al(sf), al(createFile(OPEN_KEY, OPEN_KEY)));
371  }
372
373  @Test
374  public void testAddingCompactionResults() throws Exception {
375    StripeStoreFileManager manager = createManager();
376    // First, add some L0 files and "compact" one with new stripe creation.
377    HStoreFile sf_L0_0a = createFile(), sf_L0_0b = createFile();
378    manager.insertNewFiles(al(sf_L0_0a, sf_L0_0b));
379
380    // Try compacting with invalid new branches (gaps, overlaps) - no effect.
381    verifyInvalidCompactionScenario(manager, al(sf_L0_0a), al(createFile(OPEN_KEY, KEY_B)));
382    verifyInvalidCompactionScenario(manager, al(sf_L0_0a), al(createFile(OPEN_KEY, KEY_B),
383        createFile(KEY_C, OPEN_KEY)));
384    verifyInvalidCompactionScenario(manager, al(sf_L0_0a), al(createFile(OPEN_KEY, KEY_B),
385        createFile(KEY_B, OPEN_KEY), createFile(KEY_A, KEY_D)));
386    verifyInvalidCompactionScenario(manager, al(sf_L0_0a), al(createFile(OPEN_KEY, KEY_B),
387        createFile(KEY_A, KEY_B), createFile(KEY_B, OPEN_KEY)));
388
389    HStoreFile sf_i2B_0 = createFile(OPEN_KEY, KEY_B);
390    HStoreFile sf_B2C_0 = createFile(KEY_B, KEY_C);
391    HStoreFile sf_C2i_0 = createFile(KEY_C, OPEN_KEY);
392    manager.addCompactionResults(al(sf_L0_0a), al(sf_i2B_0, sf_B2C_0, sf_C2i_0));
393    manager.removeCompactedFiles(al(sf_L0_0a));
394    verifyAllFiles(manager, al(sf_L0_0b, sf_i2B_0, sf_B2C_0, sf_C2i_0));
395
396    // Add another l0 file, "compact" both L0 into two stripes
397    HStoreFile sf_L0_1 = createFile();
398    HStoreFile sf_i2B_1 = createFile(OPEN_KEY, KEY_B);
399    HStoreFile sf_B2C_1 = createFile(KEY_B, KEY_C);
400    manager.insertNewFiles(al(sf_L0_1));
401    manager.addCompactionResults(al(sf_L0_0b, sf_L0_1), al(sf_i2B_1, sf_B2C_1));
402    manager.removeCompactedFiles(al(sf_L0_0b, sf_L0_1));
403    verifyAllFiles(manager, al(sf_i2B_0, sf_B2C_0, sf_C2i_0, sf_i2B_1, sf_B2C_1));
404
405    // Try compacting with invalid file (no metadata) - should add files to L0.
406    HStoreFile sf_L0_2 = createFile(null, null);
407    manager.addCompactionResults(al(), al(sf_L0_2));
408    manager.removeCompactedFiles(al());
409    verifyAllFiles(manager, al(sf_i2B_0, sf_B2C_0, sf_C2i_0, sf_i2B_1, sf_B2C_1, sf_L0_2));
410    // Remove it...
411    manager.addCompactionResults(al(sf_L0_2), al());
412    manager.removeCompactedFiles(al(sf_L0_2));
413
414    // Do regular compaction in the first stripe.
415    HStoreFile sf_i2B_3 = createFile(OPEN_KEY, KEY_B);
416    manager.addCompactionResults(al(sf_i2B_0, sf_i2B_1), al(sf_i2B_3));
417    manager.removeCompactedFiles(al(sf_i2B_0, sf_i2B_1));
418    verifyAllFiles(manager, al(sf_B2C_0, sf_C2i_0, sf_B2C_1, sf_i2B_3));
419
420    // Rebalance two stripes.
421    HStoreFile sf_B2D_4 = createFile(KEY_B, KEY_D);
422    HStoreFile sf_D2i_4 = createFile(KEY_D, OPEN_KEY);
423    manager.addCompactionResults(al(sf_B2C_0, sf_C2i_0, sf_B2C_1), al(sf_B2D_4, sf_D2i_4));
424    manager.removeCompactedFiles(al(sf_B2C_0, sf_C2i_0, sf_B2C_1));
425    verifyAllFiles(manager, al(sf_i2B_3, sf_B2D_4, sf_D2i_4));
426
427    // Split the first stripe.
428    HStoreFile sf_i2A_5 = createFile(OPEN_KEY, KEY_A);
429    HStoreFile sf_A2B_5 = createFile(KEY_A, KEY_B);
430    manager.addCompactionResults(al(sf_i2B_3), al(sf_i2A_5, sf_A2B_5));
431    manager.removeCompactedFiles(al(sf_i2B_3));
432    verifyAllFiles(manager, al(sf_B2D_4, sf_D2i_4, sf_i2A_5, sf_A2B_5));
433
434    // Split the middle stripe.
435    HStoreFile sf_B2C_6 = createFile(KEY_B, KEY_C);
436    HStoreFile sf_C2D_6 = createFile(KEY_C, KEY_D);
437    manager.addCompactionResults(al(sf_B2D_4), al(sf_B2C_6, sf_C2D_6));
438    manager.removeCompactedFiles(al(sf_B2D_4));
439    verifyAllFiles(manager, al(sf_D2i_4, sf_i2A_5, sf_A2B_5, sf_B2C_6, sf_C2D_6));
440
441    // Merge two different middle stripes.
442    HStoreFile sf_A2C_7 = createFile(KEY_A, KEY_C);
443    manager.addCompactionResults(al(sf_A2B_5, sf_B2C_6), al(sf_A2C_7));
444    manager.removeCompactedFiles(al(sf_A2B_5, sf_B2C_6));
445    verifyAllFiles(manager, al(sf_D2i_4, sf_i2A_5, sf_C2D_6, sf_A2C_7));
446
447    // Merge lower half.
448    HStoreFile sf_i2C_8 = createFile(OPEN_KEY, KEY_C);
449    manager.addCompactionResults(al(sf_i2A_5, sf_A2C_7), al(sf_i2C_8));
450    manager.removeCompactedFiles(al(sf_i2A_5, sf_A2C_7));
451    verifyAllFiles(manager, al(sf_D2i_4, sf_C2D_6, sf_i2C_8));
452
453    // Merge all.
454    HStoreFile sf_i2i_9 = createFile(OPEN_KEY, OPEN_KEY);
455    manager.addCompactionResults(al(sf_D2i_4, sf_C2D_6, sf_i2C_8), al(sf_i2i_9));
456    manager.removeCompactedFiles(al(sf_D2i_4, sf_C2D_6, sf_i2C_8));
457    verifyAllFiles(manager, al(sf_i2i_9));
458  }
459
460  @Test
461  public void testCompactionAndFlushConflict() throws Exception {
462    // Add file flush into stripes
463    StripeStoreFileManager sfm = createManager();
464    assertEquals(0, sfm.getStripeCount());
465    HStoreFile sf_i2c = createFile(OPEN_KEY, KEY_C), sf_c2i = createFile(KEY_C, OPEN_KEY);
466    sfm.insertNewFiles(al(sf_i2c, sf_c2i));
467    assertEquals(2, sfm.getStripeCount());
468    // Now try to add conflicting flush - should throw.
469    HStoreFile sf_i2d = createFile(OPEN_KEY, KEY_D), sf_d2i = createFile(KEY_D, OPEN_KEY);
470    sfm.insertNewFiles(al(sf_i2d, sf_d2i));
471    assertEquals(2, sfm.getStripeCount());
472    assertEquals(2, sfm.getLevel0Files().size());
473    verifyGetAndScanScenario(sfm, KEY_C, KEY_C, sf_i2d, sf_d2i, sf_c2i);
474    // Remove these files.
475    sfm.addCompactionResults(al(sf_i2d, sf_d2i), al());
476    sfm.removeCompactedFiles(al(sf_i2d, sf_d2i));
477    assertEquals(0, sfm.getLevel0Files().size());
478    // Add another file to stripe; then "rebalance" stripes w/o it - the file, which was
479    // presumably flushed during compaction, should go to L0.
480    HStoreFile sf_i2c_2 = createFile(OPEN_KEY, KEY_C);
481    sfm.insertNewFiles(al(sf_i2c_2));
482    sfm.addCompactionResults(al(sf_i2c, sf_c2i), al(sf_i2d, sf_d2i));
483    sfm.removeCompactedFiles(al(sf_i2c, sf_c2i));
484    assertEquals(1, sfm.getLevel0Files().size());
485    verifyGetAndScanScenario(sfm, KEY_C, KEY_C, sf_i2d, sf_i2c_2);
486  }
487
488  @Test
489  public void testEmptyResultsForStripes() throws Exception {
490    // Test that we can compact L0 into a subset of stripes.
491    StripeStoreFileManager manager = createManager();
492    HStoreFile sf0a = createFile();
493    HStoreFile sf0b = createFile();
494    manager.insertNewFiles(al(sf0a));
495    manager.insertNewFiles(al(sf0b));
496    ArrayList<HStoreFile> compacted = al(createFile(OPEN_KEY, KEY_B),
497        createFile(KEY_B, KEY_C), createFile(KEY_C, OPEN_KEY));
498    manager.addCompactionResults(al(sf0a), compacted);
499    manager.removeCompactedFiles(al(sf0a));
500    // Next L0 compaction only produces file for the first and last stripe.
501    ArrayList<HStoreFile> compacted2 = al(createFile(OPEN_KEY, KEY_B), createFile(KEY_C, OPEN_KEY));
502    manager.addCompactionResults(al(sf0b), compacted2);
503    manager.removeCompactedFiles(al(sf0b));
504    compacted.addAll(compacted2);
505    verifyAllFiles(manager, compacted);
506  }
507
508  @Test
509  public void testPriority() throws Exception {
510    // Expected priority, file limit, stripe count, files per stripe, l0 files.
511    testPriorityScenario(5,    5, 0, 0, 0);
512    testPriorityScenario(2,    5, 0, 0, 3);
513    testPriorityScenario(4,   25, 5, 1, 0); // example case.
514    testPriorityScenario(3,   25, 5, 1, 1); // L0 files counts for all stripes.
515    testPriorityScenario(3,   25, 5, 2, 0); // file to each stripe - same as one L0 file.
516    testPriorityScenario(2,   25, 5, 4, 0); // 1 is priority user, so 2 is returned.
517    testPriorityScenario(2,   25, 5, 4, 4); // don't return higher than user unless over limit.
518    testPriorityScenario(2,   25, 5, 1, 10); // same.
519    testPriorityScenario(0,   25, 5, 4, 5); // at limit.
520    testPriorityScenario(-5,  25, 5, 6, 0); // over limit!
521    testPriorityScenario(-1,  25, 0, 0, 26); // over limit with just L0
522  }
523
524  private void testPriorityScenario(int expectedPriority,
525      int limit, int stripes, int filesInStripe, int l0Files) throws Exception {
526    final byte[][] keys = { KEY_A, KEY_B, KEY_C, KEY_D };
527    assertTrue(stripes <= keys.length + 1);
528    Configuration conf = TEST_UTIL.getConfiguration();
529    conf.setInt("hbase.hstore.blockingStoreFiles", limit);
530    StripeStoreFileManager sfm = createManager(al(), conf);
531    for (int i = 0; i < l0Files; ++i) {
532      sfm.insertNewFiles(al(createFile()));
533    }
534    for (int i = 0; i < filesInStripe; ++i) {
535      ArrayList<HStoreFile> stripe = new ArrayList<>();
536      for (int j = 0; j < stripes; ++j) {
537        stripe.add(createFile(
538            (j == 0) ? OPEN_KEY : keys[j - 1], (j == stripes - 1) ? OPEN_KEY : keys[j]));
539      }
540      sfm.addCompactionResults(al(), stripe);
541    }
542    assertEquals(expectedPriority, sfm.getStoreCompactionPriority());
543  }
544
545  private void verifyInvalidCompactionScenario(StripeStoreFileManager manager,
546    ArrayList<HStoreFile> filesToCompact, ArrayList<HStoreFile> filesToInsert) throws Exception {
547    Collection<HStoreFile> allFiles = manager.getStorefiles();
548    assertThrows(IllegalStateException.class,
549      () -> manager.addCompactionResults(filesToCompact, filesToInsert));
550    verifyAllFiles(manager, allFiles); // must have the same files.
551  }
552
553  private void verifyGetOrScanScenario(StripeStoreFileManager manager, byte[] start, byte[] end,
554      HStoreFile... results) throws Exception {
555    verifyGetOrScanScenario(manager, start, end, Arrays.asList(results));
556  }
557
558  private void verifyGetOrScanScenario(StripeStoreFileManager manager, byte[] start, byte[] end,
559      Collection<HStoreFile> results) throws Exception {
560    start = start != null ? start : HConstants.EMPTY_START_ROW;
561    end = end != null ? end : HConstants.EMPTY_END_ROW;
562    Collection<HStoreFile> sfs = manager.getFilesForScan(start, true, end, false);
563    assertEquals(results.size(), sfs.size());
564    for (HStoreFile result : results) {
565      assertTrue(sfs.contains(result));
566    }
567  }
568
569  private void verifyAllFiles(
570      StripeStoreFileManager manager, Collection<HStoreFile> results) throws Exception {
571    verifyGetOrScanScenario(manager, null, null, results);
572  }
573
574  // TODO: replace with Mockito?
575  private static MockHStoreFile createFile(
576      long size, long seqNum, byte[] startKey, byte[] endKey) throws Exception {
577    FileSystem fs = TEST_UTIL.getTestFileSystem();
578    Path testFilePath = StoreFileWriter.getUniqueFile(fs, CFDIR);
579    fs.create(testFilePath).close();
580    MockHStoreFile sf = new MockHStoreFile(TEST_UTIL, testFilePath, size, 0, false, seqNum);
581    if (startKey != null) {
582      sf.setMetadataValue(StripeStoreFileManager.STRIPE_START_KEY, startKey);
583    }
584    if (endKey != null) {
585      sf.setMetadataValue(StripeStoreFileManager.STRIPE_END_KEY, endKey);
586    }
587    return sf;
588  }
589
590  private static MockHStoreFile createFile(long size, long seqNum) throws Exception {
591    return createFile(size, seqNum, null, null);
592  }
593
594  private static MockHStoreFile createFile(byte[] startKey, byte[] endKey) throws Exception {
595    return createFile(0, 0, startKey, endKey);
596  }
597
598  private static MockHStoreFile createFile() throws Exception {
599    return createFile(null, null);
600  }
601
602  private static StripeStoreFileManager createManager() throws Exception {
603    return createManager(new ArrayList<>());
604  }
605
606  private static StripeStoreFileManager createManager(ArrayList<HStoreFile> sfs) throws Exception {
607    return createManager(sfs, TEST_UTIL.getConfiguration());
608  }
609
610  private static StripeStoreFileManager createManager(
611      ArrayList<HStoreFile> sfs, Configuration conf) throws Exception {
612    StripeStoreConfig config = new StripeStoreConfig(
613        conf, Mockito.mock(StoreConfigInformation.class));
614    StripeStoreFileManager result = new StripeStoreFileManager(CellComparatorImpl.COMPARATOR, conf,
615        config);
616    result.loadFiles(sfs);
617    return result;
618  }
619
620  private static ArrayList<HStoreFile> al(HStoreFile... sfs) {
621    return new ArrayList<>(Arrays.asList(sfs));
622  }
623
624  private static ArrayList<HStoreFile> flattenLists(ArrayList<HStoreFile>... sfls) {
625    ArrayList<HStoreFile> result = new ArrayList<>();
626    for (ArrayList<HStoreFile> sfl : sfls) {
627      result.addAll(sfl);
628    }
629    return result;
630  }
631}