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.compactions;
019
020import static org.apache.hadoop.hbase.regionserver.StripeStoreFileManager.OPEN_KEY;
021import static org.apache.hadoop.hbase.regionserver.compactions.TestCompactor.createDummyRequest;
022import static org.junit.Assert.assertEquals;
023import static org.mockito.ArgumentMatchers.any;
024import static org.mockito.Mockito.mock;
025import static org.mockito.Mockito.when;
026
027import java.io.IOException;
028import java.util.ArrayList;
029import java.util.Arrays;
030import java.util.List;
031import org.apache.hadoop.conf.Configuration;
032import org.apache.hadoop.fs.FileSystem;
033import org.apache.hadoop.fs.Path;
034import org.apache.hadoop.hbase.CellComparatorImpl;
035import org.apache.hadoop.hbase.CellUtil;
036import org.apache.hadoop.hbase.HBaseClassTestRule;
037import org.apache.hadoop.hbase.HBaseConfiguration;
038import org.apache.hadoop.hbase.HColumnDescriptor;
039import org.apache.hadoop.hbase.KeyValue;
040import org.apache.hadoop.hbase.TableName;
041import org.apache.hadoop.hbase.client.RegionInfoBuilder;
042import org.apache.hadoop.hbase.regionserver.CreateStoreFileWriterParams;
043import org.apache.hadoop.hbase.regionserver.HStore;
044import org.apache.hadoop.hbase.regionserver.InternalScanner;
045import org.apache.hadoop.hbase.regionserver.ScanInfo;
046import org.apache.hadoop.hbase.regionserver.ScanType;
047import org.apache.hadoop.hbase.regionserver.StoreEngine;
048import org.apache.hadoop.hbase.regionserver.StoreFileScanner;
049import org.apache.hadoop.hbase.regionserver.compactions.TestCompactor.Scanner;
050import org.apache.hadoop.hbase.regionserver.compactions.TestCompactor.StoreFileWritersCapture;
051import org.apache.hadoop.hbase.regionserver.throttle.NoLimitThroughputController;
052import org.apache.hadoop.hbase.testclassification.RegionServerTests;
053import org.apache.hadoop.hbase.testclassification.SmallTests;
054import org.apache.hadoop.hbase.util.Bytes;
055import org.junit.ClassRule;
056import org.junit.Test;
057import org.junit.experimental.categories.Category;
058import org.junit.runner.RunWith;
059import org.junit.runners.Parameterized;
060import org.junit.runners.Parameterized.Parameter;
061import org.junit.runners.Parameterized.Parameters;
062
063@RunWith(Parameterized.class)
064@Category({ RegionServerTests.class, SmallTests.class })
065public class TestStripeCompactor {
066
067  @ClassRule
068  public static final HBaseClassTestRule CLASS_RULE =
069    HBaseClassTestRule.forClass(TestStripeCompactor.class);
070
071  private static final byte[] NAME_OF_THINGS = Bytes.toBytes("foo");
072  private static final TableName TABLE_NAME = TableName.valueOf(NAME_OF_THINGS, NAME_OF_THINGS);
073
074  private static final byte[] KEY_B = Bytes.toBytes("bbb");
075  private static final byte[] KEY_C = Bytes.toBytes("ccc");
076  private static final byte[] KEY_D = Bytes.toBytes("ddd");
077
078  private static final KeyValue KV_A = kvAfter(Bytes.toBytes("aaa"));
079  private static final KeyValue KV_B = kvAfter(KEY_B);
080  private static final KeyValue KV_C = kvAfter(KEY_C);
081  private static final KeyValue KV_D = kvAfter(KEY_D);
082
083  @Parameters(name = "{index}: usePrivateReaders={0}")
084  public static Iterable<Object[]> data() {
085    return Arrays.asList(new Object[] { true }, new Object[] { false });
086  }
087
088  @Parameter
089  public boolean usePrivateReaders;
090
091  private static KeyValue kvAfter(byte[] key) {
092    return new KeyValue(Arrays.copyOf(key, key.length + 1), 0L);
093  }
094
095  @SuppressWarnings("unchecked")
096  private static <T> T[] a(T... a) {
097    return a;
098  }
099
100  private static KeyValue[] e() {
101    return TestStripeCompactor.<KeyValue> a();
102  }
103
104  @Test
105  public void testBoundaryCompactions() throws Exception {
106    // General verification
107    verifyBoundaryCompaction(a(KV_A, KV_A, KV_B, KV_B, KV_C, KV_D),
108      a(OPEN_KEY, KEY_B, KEY_D, OPEN_KEY), a(a(KV_A, KV_A), a(KV_B, KV_B, KV_C), a(KV_D)));
109    verifyBoundaryCompaction(a(KV_B, KV_C), a(KEY_B, KEY_C, KEY_D), a(a(KV_B), a(KV_C)));
110    verifyBoundaryCompaction(a(KV_B, KV_C), a(KEY_B, KEY_D), new KeyValue[][] { a(KV_B, KV_C) });
111  }
112
113  @Test
114  public void testBoundaryCompactionEmptyFiles() throws Exception {
115    // No empty file if there're already files.
116    verifyBoundaryCompaction(a(KV_B), a(KEY_B, KEY_C, KEY_D, OPEN_KEY), a(a(KV_B), null, null),
117      null, null, false);
118    verifyBoundaryCompaction(a(KV_A, KV_C), a(OPEN_KEY, KEY_B, KEY_C, KEY_D),
119      a(a(KV_A), null, a(KV_C)), null, null, false);
120    // But should be created if there are no file.
121    verifyBoundaryCompaction(e(), a(OPEN_KEY, KEY_B, KEY_C, OPEN_KEY), a(null, null, e()), null,
122      null, false);
123    // In major range if there's major range.
124    verifyBoundaryCompaction(e(), a(OPEN_KEY, KEY_B, KEY_C, OPEN_KEY), a(null, e(), null), KEY_B,
125      KEY_C, false);
126    verifyBoundaryCompaction(e(), a(OPEN_KEY, KEY_B, KEY_C, OPEN_KEY), a(e(), e(), null), OPEN_KEY,
127      KEY_C, false);
128    // Major range should have files regardless of KVs.
129    verifyBoundaryCompaction(a(KV_A), a(OPEN_KEY, KEY_B, KEY_C, KEY_D, OPEN_KEY),
130      a(a(KV_A), e(), e(), null), KEY_B, KEY_D, false);
131    verifyBoundaryCompaction(a(KV_C), a(OPEN_KEY, KEY_B, KEY_C, KEY_D, OPEN_KEY),
132      a(null, null, a(KV_C), e()), KEY_C, OPEN_KEY, false);
133
134  }
135
136  private void verifyBoundaryCompaction(KeyValue[] input, byte[][] boundaries, KeyValue[][] output)
137    throws Exception {
138    verifyBoundaryCompaction(input, boundaries, output, null, null, true);
139  }
140
141  private void verifyBoundaryCompaction(KeyValue[] input, byte[][] boundaries, KeyValue[][] output,
142    byte[] majorFrom, byte[] majorTo, boolean allFiles) throws Exception {
143    StoreFileWritersCapture writers = new StoreFileWritersCapture();
144    StripeCompactor sc = createCompactor(writers, input);
145    List<Path> paths = sc.compact(createDummyRequest(), Arrays.asList(boundaries), majorFrom,
146      majorTo, NoLimitThroughputController.INSTANCE, null);
147    writers.verifyKvs(output, allFiles, true);
148    if (allFiles) {
149      assertEquals(output.length, paths.size());
150      writers.verifyBoundaries(boundaries);
151    }
152  }
153
154  @Test
155  public void testSizeCompactions() throws Exception {
156    // General verification with different sizes.
157    verifySizeCompaction(a(KV_A, KV_A, KV_B, KV_C, KV_D), 3, 2, OPEN_KEY, OPEN_KEY,
158      a(a(KV_A, KV_A), a(KV_B, KV_C), a(KV_D)));
159    verifySizeCompaction(a(KV_A, KV_B, KV_C, KV_D), 4, 1, OPEN_KEY, OPEN_KEY,
160      a(a(KV_A), a(KV_B), a(KV_C), a(KV_D)));
161    verifySizeCompaction(a(KV_B, KV_C), 2, 1, KEY_B, KEY_D, a(a(KV_B), a(KV_C)));
162    // Verify row boundaries are preserved.
163    verifySizeCompaction(a(KV_A, KV_A, KV_A, KV_C, KV_D), 3, 2, OPEN_KEY, OPEN_KEY,
164      a(a(KV_A, KV_A, KV_A), a(KV_C, KV_D)));
165    verifySizeCompaction(a(KV_A, KV_B, KV_B, KV_C), 3, 1, OPEN_KEY, OPEN_KEY,
166      a(a(KV_A), a(KV_B, KV_B), a(KV_C)));
167    // Too much data, count limits the number of files.
168    verifySizeCompaction(a(KV_A, KV_B, KV_C, KV_D), 2, 1, OPEN_KEY, OPEN_KEY,
169      a(a(KV_A), a(KV_B, KV_C, KV_D)));
170    verifySizeCompaction(a(KV_A, KV_B, KV_C), 1, Long.MAX_VALUE, OPEN_KEY, KEY_D,
171      new KeyValue[][] { a(KV_A, KV_B, KV_C) });
172    // Too little data/large count, no extra files.
173    verifySizeCompaction(a(KV_A, KV_B, KV_C, KV_D), Integer.MAX_VALUE, 2, OPEN_KEY, OPEN_KEY,
174      a(a(KV_A, KV_B), a(KV_C, KV_D)));
175  }
176
177  private void verifySizeCompaction(KeyValue[] input, int targetCount, long targetSize, byte[] left,
178    byte[] right, KeyValue[][] output) throws Exception {
179    StoreFileWritersCapture writers = new StoreFileWritersCapture();
180    StripeCompactor sc = createCompactor(writers, input);
181    List<Path> paths = sc.compact(createDummyRequest(), targetCount, targetSize, left, right, null,
182      null, NoLimitThroughputController.INSTANCE, null);
183    assertEquals(output.length, paths.size());
184    writers.verifyKvs(output, true, true);
185    List<byte[]> boundaries = new ArrayList<>(output.length + 2);
186    boundaries.add(left);
187    for (int i = 1; i < output.length; ++i) {
188      boundaries.add(CellUtil.cloneRow(output[i][0]));
189    }
190    boundaries.add(right);
191    writers.verifyBoundaries(boundaries.toArray(new byte[][] {}));
192  }
193
194  @SuppressWarnings({ "rawtypes", "unchecked" })
195  private StripeCompactor createCompactor(StoreFileWritersCapture writers, KeyValue[] input)
196    throws Exception {
197    Configuration conf = HBaseConfiguration.create();
198    conf.setBoolean("hbase.regionserver.compaction.private.readers", usePrivateReaders);
199    final Scanner scanner = new Scanner(input);
200
201    // Create store mock that is satisfactory for compactor.
202    HColumnDescriptor col = new HColumnDescriptor(NAME_OF_THINGS);
203    ScanInfo si = new ScanInfo(conf, col, Long.MAX_VALUE, 0, CellComparatorImpl.COMPARATOR);
204    HStore store = mock(HStore.class);
205    when(store.getColumnFamilyDescriptor()).thenReturn(col);
206    when(store.getScanInfo()).thenReturn(si);
207    when(store.areWritesEnabled()).thenReturn(true);
208    when(store.getFileSystem()).thenReturn(mock(FileSystem.class));
209    when(store.getRegionInfo()).thenReturn(RegionInfoBuilder.newBuilder(TABLE_NAME).build());
210    StoreEngine storeEngine = mock(StoreEngine.class);
211    when(storeEngine.createWriter(any(CreateStoreFileWriterParams.class))).thenAnswer(writers);
212    when(store.getStoreEngine()).thenReturn(storeEngine);
213    when(store.getComparator()).thenReturn(CellComparatorImpl.COMPARATOR);
214
215    return new StripeCompactor(conf, store) {
216      @Override
217      protected InternalScanner createScanner(HStore store, ScanInfo scanInfo,
218        List<StoreFileScanner> scanners, long smallestReadPoint, long earliestPutTs,
219        byte[] dropDeletesFromRow, byte[] dropDeletesToRow) throws IOException {
220        return scanner;
221      }
222
223      @Override
224      protected InternalScanner createScanner(HStore store, ScanInfo scanInfo,
225        List<StoreFileScanner> scanners, ScanType scanType, long smallestReadPoint,
226        long earliestPutTs) throws IOException {
227        return scanner;
228      }
229    };
230  }
231}