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