HBASE-26724 Backport the UT changes in HBASE-24510 to branch-2.x (#4081)

Signed-off-by: Xin Sun <ddupgs@gmail.com>
This commit is contained in:
Duo Zhang 2022-02-09 21:45:52 +08:00 committed by GitHub
parent 0bc8671cec
commit cbbb1a0542
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 522 additions and 440 deletions

View File

@ -16,16 +16,21 @@
*/
package org.apache.hadoop.hbase;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.Collections;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.regionserver.Region;
import org.apache.hadoop.hbase.regionserver.RegionAsTable;
import org.apache.hadoop.hbase.util.Bytes;
/**
* Similar to {@link HConstants} but for tests. Also provides some simple
* static utility functions to generate test data.
* Similar to {@link HConstants} but for tests. Also provides some simple static utility functions
* to generate test data.
*/
public class HTestConst {
@ -34,15 +39,13 @@ public class HTestConst {
public static final String DEFAULT_TABLE_STR = "MyTestTable";
public static final byte[] DEFAULT_TABLE_BYTES = Bytes.toBytes(DEFAULT_TABLE_STR);
public static final TableName DEFAULT_TABLE =
TableName.valueOf(DEFAULT_TABLE_BYTES);
public static final TableName DEFAULT_TABLE = TableName.valueOf(DEFAULT_TABLE_BYTES);
public static final String DEFAULT_CF_STR = "MyDefaultCF";
public static final byte[] DEFAULT_CF_BYTES = Bytes.toBytes(DEFAULT_CF_STR);
public static final Set<String> DEFAULT_CF_STR_SET =
Collections.unmodifiableSet(new HashSet<>(
Arrays.asList(new String[] { DEFAULT_CF_STR })));
Collections.unmodifiableSet(new HashSet<>(Arrays.asList(new String[] { DEFAULT_CF_STR })));
public static final String DEFAULT_ROW_STR = "MyTestRow";
public static final byte[] DEFAULT_ROW_BYTES = Bytes.toBytes(DEFAULT_ROW_STR);
@ -53,9 +56,13 @@ public class HTestConst {
public static String DEFAULT_VALUE_STR = "MyTestValue";
public static byte[] DEFAULT_VALUE_BYTES = Bytes.toBytes(DEFAULT_VALUE_STR);
private static final char FIRST_CHAR = 'a';
private static final char LAST_CHAR = 'z';
private static final byte[] START_KEY_BYTES = { FIRST_CHAR, FIRST_CHAR, FIRST_CHAR };
/**
* Generate the given number of unique byte sequences by appending numeric
* suffixes (ASCII representations of decimal numbers).
* Generate the given number of unique byte sequences by appending numeric suffixes (ASCII
* representations of decimal numbers).
*/
public static byte[][] makeNAscii(byte[] base, int n) {
byte[][] ret = new byte[n][];
@ -66,4 +73,112 @@ public class HTestConst {
return ret;
}
/**
* Add content to region <code>r</code> on the passed column <code>column</code>. Adds data of the
* from 'aaa', 'aab', etc where key and value are the same.
* @return count of what we added.
*/
public static long addContent(final Region r, final byte[] columnFamily, final byte[] column)
throws IOException {
byte[] startKey = r.getRegionInfo().getStartKey();
byte[] endKey = r.getRegionInfo().getEndKey();
byte[] startKeyBytes = startKey;
if (startKeyBytes == null || startKeyBytes.length == 0) {
startKeyBytes = START_KEY_BYTES;
}
return addContent(new RegionAsTable(r), Bytes.toString(columnFamily), Bytes.toString(column),
startKeyBytes, endKey, -1);
}
public static long addContent(final Region r, final byte[] columnFamily) throws IOException {
return addContent(r, columnFamily, null);
}
/**
* Add content to region <code>r</code> on the passed column <code>column</code>. Adds data of the
* from 'aaa', 'aab', etc where key and value are the same.
* @return count of what we added.
*/
public static long addContent(Table updater, String columnFamily) throws IOException {
return addContent(updater, columnFamily, START_KEY_BYTES, null);
}
public static long addContent(Table updater, String family, String column) throws IOException {
return addContent(updater, family, column, START_KEY_BYTES, null);
}
/**
* Add content to region <code>r</code> on the passed column <code>column</code>. Adds data of the
* from 'aaa', 'aab', etc where key and value are the same.
* @return count of what we added.
*/
public static long addContent(Table updater, String columnFamily, byte[] startKeyBytes,
byte[] endKey) throws IOException {
return addContent(updater, columnFamily, null, startKeyBytes, endKey, -1);
}
public static long addContent(Table updater, String family, String column, byte[] startKeyBytes,
byte[] endKey) throws IOException {
return addContent(updater, family, column, startKeyBytes, endKey, -1);
}
/**
* Add content to region <code>r</code> on the passed column <code>column</code>. Adds data of the
* from 'aaa', 'aab', etc where key and value are the same.
* @return count of what we added.
*/
public static long addContent(Table updater, String columnFamily, String column,
byte[] startKeyBytes, byte[] endKey, long ts) throws IOException {
long count = 0;
// Add rows of three characters. The first character starts with the
// 'a' character and runs up to 'z'. Per first character, we run the
// second character over same range. And same for the third so rows
// (and values) look like this: 'aaa', 'aab', 'aac', etc.
char secondCharStart = (char) startKeyBytes[1];
char thirdCharStart = (char) startKeyBytes[2];
EXIT: for (char c = (char) startKeyBytes[0]; c <= LAST_CHAR; c++) {
for (char d = secondCharStart; d <= LAST_CHAR; d++) {
for (char e = thirdCharStart; e <= LAST_CHAR; e++) {
byte[] t = new byte[] { (byte) c, (byte) d, (byte) e };
if (endKey != null && endKey.length > 0 && Bytes.compareTo(endKey, t) <= 0) {
break EXIT;
}
Put put;
if (ts != -1) {
put = new Put(t, ts);
} else {
put = new Put(t);
}
StringBuilder sb = new StringBuilder();
if (column != null && column.contains(":")) {
sb.append(column);
} else {
if (columnFamily != null) {
sb.append(columnFamily);
if (!columnFamily.endsWith(":")) {
sb.append(":");
}
if (column != null) {
sb.append(column);
}
}
}
byte[][] split = CellUtil.parseColumn(Bytes.toBytes(sb.toString()));
if (split.length == 1) {
byte[] qualifier = new byte[0];
put.addColumn(split[0], qualifier, t);
} else {
put.addColumn(split[0], split[1], t);
}
put.setDurability(Durability.SKIP_WAL);
updater.put(put);
count++;
}
// Set start character back to FIRST_CHAR after we've done first loop.
thirdCharStart = FIRST_CHAR;
}
secondCharStart = FIRST_CHAR;
}
return count;
}
}

View File

@ -17,11 +17,11 @@
*/
package org.apache.hadoop.hbase.client;
import static org.apache.hadoop.hbase.HBaseTestCase.assertByteEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertArrayEquals;
import java.io.IOException;
import java.nio.ByteBuffer;
@ -168,7 +168,7 @@ public class TestResult extends TestCase {
for (int i = 0; i < 100; ++i) {
final byte[] qf = Bytes.toBytes(i);
assertByteEquals(Bytes.add(value, Bytes.toBytes(i)), r.getValue(family, qf));
assertArrayEquals(Bytes.add(value, Bytes.toBytes(i)), r.getValue(family, qf));
assertTrue(r.containsColumn(family, qf));
}
}
@ -187,7 +187,7 @@ public class TestResult extends TestCase {
for (int i = 0; i < 100; ++i) {
final byte[] qf = Bytes.toBytes(i);
assertByteEquals(Bytes.add(value, Bytes.toBytes(i)), r.getValue(family, qf));
assertArrayEquals(Bytes.add(value, Bytes.toBytes(i)), r.getValue(family, qf));
assertTrue(r.containsColumn(family, qf));
}
}

View File

@ -38,11 +38,11 @@ import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.Coprocessor;
import org.apache.hadoop.hbase.CoprocessorEnvironment;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestCase;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.HTestConst;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.RegionInfo;
@ -292,7 +292,7 @@ public class TestCoprocessorInterface {
HRegion region = initHRegion(tableName, name.getMethodName(), hc, new Class<?>[]{}, families);
for (int i = 0; i < 3; i++) {
HBaseTestCase.addContent(region, fam3);
HTestConst.addContent(region, fam3);
region.flush(true);
}
@ -354,7 +354,7 @@ public class TestCoprocessorInterface {
HRegion region = initHRegion(tableName, name.getMethodName(), hc,
new Class<?>[]{CoprocessorImpl.class}, families);
for (int i = 0; i < 3; i++) {
HBaseTestCase.addContent(region, fam3);
HTestConst.addContent(region, fam3);
region.flush(true);
}

View File

@ -17,12 +17,11 @@
*/
package org.apache.hadoop.hbase.regionserver;
import static org.apache.hadoop.hbase.HBaseTestCase.addContent;
import static org.apache.hadoop.hbase.HTestConst.addContent;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;

View File

@ -28,7 +28,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
@ -50,11 +50,11 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.ChoreService;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HBaseTestCase;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.HTestConst;
import org.apache.hadoop.hbase.Waiter;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Durability;
@ -175,7 +175,7 @@ public class TestCompaction {
for (int j = 0; j < jmax; j++) {
p.addColumn(COLUMN_FAMILY, Bytes.toBytes(j), pad);
}
HBaseTestCase.addContent(loader, Bytes.toString(COLUMN_FAMILY));
HTestConst.addContent(loader, Bytes.toString(COLUMN_FAMILY));
loader.put(p);
r.flush(true);
}
@ -251,7 +251,7 @@ public class TestCompaction {
for (int j = 0; j < jmax; j++) {
p.addColumn(COLUMN_FAMILY, Bytes.toBytes(j), pad);
}
HBaseTestCase.addContent(loader, Bytes.toString(COLUMN_FAMILY));
HTestConst.addContent(loader, Bytes.toString(COLUMN_FAMILY));
loader.put(p);
r.flush(true);
}
@ -330,7 +330,7 @@ public class TestCompaction {
private void createStoreFile(final HRegion region, String family) throws IOException {
Table loader = new RegionAsTable(region);
HBaseTestCase.addContent(loader, family);
HTestConst.addContent(loader, family);
region.flush(true);
}
@ -494,7 +494,7 @@ public class TestCompaction {
for (int j = 0; j < jmax; j++) {
p.addColumn(COLUMN_FAMILY, Bytes.toBytes(j), pad);
}
HBaseTestCase.addContent(loader, Bytes.toString(COLUMN_FAMILY));
HTestConst.addContent(loader, Bytes.toString(COLUMN_FAMILY));
loader.put(p);
r.flush(true);
}

View File

@ -17,6 +17,13 @@
*/
package org.apache.hadoop.hbase.regionserver;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@ -38,7 +45,6 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestCase;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
@ -64,7 +70,6 @@ import org.apache.hadoop.hbase.io.hfile.CacheStats;
import org.apache.hadoop.hbase.io.hfile.HFileContext;
import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoder;
import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoderImpl;
import org.apache.hadoop.hbase.io.hfile.HFileInfo;
import org.apache.hadoop.hbase.io.hfile.HFileScanner;
import org.apache.hadoop.hbase.io.hfile.ReaderContext;
@ -78,11 +83,13 @@ import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.ChecksumType;
import org.apache.hadoop.hbase.util.CommonFSUtils;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -95,7 +102,7 @@ import org.apache.hbase.thirdparty.com.google.common.collect.Lists;
* Test HStoreFile
*/
@Category({ RegionServerTests.class, MediumTests.class })
public class TestHStoreFile extends HBaseTestCase {
public class TestHStoreFile {
@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
@ -108,22 +115,35 @@ public class TestHStoreFile extends HBaseTestCase {
private static final ChecksumType CKTYPE = ChecksumType.CRC32C;
private static final int CKBYTES = 512;
private static String TEST_FAMILY = "cf";
private static final char FIRST_CHAR = 'a';
private static final char LAST_CHAR = 'z';
@Rule
public TestName name = new TestName();
private Configuration conf;
private Path testDir;
private FileSystem fs;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
public void setUp() throws IOException {
conf = TEST_UTIL.getConfiguration();
testDir = TEST_UTIL.getDataTestDir(name.getMethodName());
fs = testDir.getFileSystem(conf);
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
@AfterClass
public static void tearDownAfterClass() {
TEST_UTIL.cleanupTestDir();
}
/**
* Write a file and then assert that we can read from top and bottom halves using two
<<<<<<< HEAD
* HalfMapFiles, as well as one HalfMapFile and one HFileLink file.
=======
* HalfMapFiles.
>>>>>>> 16116fa35e... HBASE-24510 Remove HBaseTestCase and GenericTestUtils (#1859)
*/
@Test
public void testBasicHalfAndHFileLinkMapFile() throws Exception {
@ -137,9 +157,7 @@ public class TestHStoreFile extends HBaseTestCase {
HFileContext meta = new HFileContextBuilder().withBlockSize(2 * 1024).build();
StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs)
.withFilePath(regionFs.createTempName())
.withFileContext(meta)
.build();
.withFilePath(regionFs.createTempName()).withFileContext(meta).build();
writeStoreFile(writer);
Path sfPath = regionFs.commitStoreFile(TEST_FAMILY, writer.getPath());
@ -148,15 +166,15 @@ public class TestHStoreFile extends HBaseTestCase {
}
private void writeStoreFile(final StoreFileWriter writer) throws IOException {
writeStoreFile(writer, Bytes.toBytes(getName()), Bytes.toBytes(getName()));
writeStoreFile(writer, Bytes.toBytes(name.getMethodName()),
Bytes.toBytes(name.getMethodName()));
}
// pick an split point (roughly halfway)
byte[] SPLITKEY = new byte[] { (LAST_CHAR + FIRST_CHAR) / 2, FIRST_CHAR };
/*
* Writes HStoreKey and ImmutableBytes data to passed writer and
* then closes it.
* Writes HStoreKey and ImmutableBytes data to passed writer and then closes it.
* @param writer
* @throws IOException
*/
@ -176,8 +194,8 @@ public class TestHStoreFile extends HBaseTestCase {
}
/**
* Test that our mechanism of writing store files in one region to reference
* store files in other regions works.
* Test that our mechanism of writing store files in one region to reference store files in other
* regions works.
*/
@Test
public void testReference() throws IOException {
@ -188,9 +206,7 @@ public class TestHStoreFile extends HBaseTestCase {
HFileContext meta = new HFileContextBuilder().withBlockSize(8 * 1024).build();
// Make a store file and write data to it.
StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs)
.withFilePath(regionFs.createTempName())
.withFileContext(meta)
.build();
.withFilePath(regionFs.createTempName()).withFileContext(meta).build();
writeStoreFile(writer);
Path hsfPath = regionFs.commitStoreFile(TEST_FAMILY, writer.getPath());
@ -262,12 +278,13 @@ public class TestHStoreFile extends HBaseTestCase {
byte[] cf = Bytes.toBytes("ty");
ColumnFamilyDescriptor cfd = ColumnFamilyDescriptorBuilder.of(cf);
when(store.getColumnFamilyDescriptor()).thenReturn(cfd);
StoreFileScanner scanner =
new StoreFileScanner(reader, mock(HFileScanner.class), false, false, 0, 0, true);
try (StoreFileScanner scanner =
new StoreFileScanner(reader, mock(HFileScanner.class), false, false, 0, 0, true)) {
Scan scan = new Scan();
scan.setColumnFamilyTimeRange(cf, 0, 1);
assertFalse(scanner.shouldUseScanner(scan, store, 0));
}
}
@Test
public void testHFileLink() throws IOException {
@ -275,22 +292,20 @@ public class TestHStoreFile extends HBaseTestCase {
// force temp data in hbase/target/test-data instead of /tmp/hbase-xxxx/
Configuration testConf = new Configuration(this.conf);
CommonFSUtils.setRootDir(testConf, testDir);
HRegionFileSystem regionFs = HRegionFileSystem.createRegionOnFileSystem(
testConf, fs, CommonFSUtils.getTableDir(testDir, hri.getTable()), hri);
HRegionFileSystem regionFs = HRegionFileSystem.createRegionOnFileSystem(testConf, fs,
CommonFSUtils.getTableDir(testDir, hri.getTable()), hri);
HFileContext meta = new HFileContextBuilder().withBlockSize(8 * 1024).build();
// Make a store file and write data to it.
StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs)
.withFilePath(regionFs.createTempName())
.withFileContext(meta)
.build();
.withFilePath(regionFs.createTempName()).withFileContext(meta).build();
writeStoreFile(writer);
Path storeFilePath = regionFs.commitStoreFile(TEST_FAMILY, writer.getPath());
Path dstPath = new Path(regionFs.getTableDir(), new Path("test-region", TEST_FAMILY));
HFileLink.create(testConf, this.fs, dstPath, hri, storeFilePath.getName());
Path linkFilePath = new Path(dstPath,
HFileLink.createHFileLinkName(hri, storeFilePath.getName()));
Path linkFilePath =
new Path(dstPath, HFileLink.createHFileLinkName(hri, storeFilePath.getName()));
// Try to open store file from link
StoreFileInfo storeFileInfo = new StoreFileInfo(testConf, this.fs, linkFilePath, true);
@ -309,8 +324,8 @@ public class TestHStoreFile extends HBaseTestCase {
}
/**
* This test creates an hfile and then the dir structures and files to verify that references
* to hfilelinks (created by snapshot clones) can be properly interpreted.
* This test creates an hfile and then the dir structures and files to verify that references to
* hfilelinks (created by snapshot clones) can be properly interpreted.
*/
@Test
public void testReferenceToHFileLink() throws IOException {
@ -326,21 +341,18 @@ public class TestHStoreFile extends HBaseTestCase {
HFileContext meta = new HFileContextBuilder().withBlockSize(8 * 1024).build();
// Make a store file and write data to it. <root>/<tablename>/<rgn>/<cf>/<file>
StoreFileWriter writer = new StoreFileWriter.Builder(testConf, cacheConf, this.fs)
.withFilePath(regionFs.createTempName())
.withFileContext(meta)
.build();
.withFilePath(regionFs.createTempName()).withFileContext(meta).build();
writeStoreFile(writer);
Path storeFilePath = regionFs.commitStoreFile(TEST_FAMILY, writer.getPath());
// create link to store file. <root>/clone/region/<cf>/<hfile>-<region>-<table>
HRegionInfo hriClone = new HRegionInfo(TableName.valueOf("clone"));
HRegionFileSystem cloneRegionFs = HRegionFileSystem.createRegionOnFileSystem(
testConf, fs, CommonFSUtils.getTableDir(testDir, hri.getTable()),
hriClone);
RegionInfo hriClone = RegionInfoBuilder.newBuilder(TableName.valueOf("clone")).build();
HRegionFileSystem cloneRegionFs = HRegionFileSystem.createRegionOnFileSystem(testConf, fs,
CommonFSUtils.getTableDir(testDir, hri.getTable()), hriClone);
Path dstPath = cloneRegionFs.getStoreDir(TEST_FAMILY);
HFileLink.create(testConf, this.fs, dstPath, hri, storeFilePath.getName());
Path linkFilePath = new Path(dstPath,
HFileLink.createHFileLinkName(hri, storeFilePath.getName()));
Path linkFilePath =
new Path(dstPath, HFileLink.createHFileLinkName(hri, storeFilePath.getName()));
// create splits of the link.
// <root>/clone/splitA/<cf>/<reftohfilelink>,
@ -428,8 +440,7 @@ public class TestHStoreFile extends HBaseTestCase {
if ((PrivateCellUtil.compare(topScanner.getReader().getComparator(), midKV, key.array(),
key.arrayOffset(), key.limit())) > 0) {
fail("key=" + Bytes.toStringBinary(key) + " < midkey=" +
midkey);
fail("key=" + Bytes.toStringBinary(key) + " < midkey=" + midkey);
}
if (first) {
first = false;
@ -440,14 +451,12 @@ public class TestHStoreFile extends HBaseTestCase {
first = true;
HFileScanner bottomScanner = bottom.getScanner(false, false);
while ((!bottomScanner.isSeeked() && bottomScanner.seekTo()) ||
bottomScanner.next()) {
while ((!bottomScanner.isSeeked() && bottomScanner.seekTo()) || bottomScanner.next()) {
previous = ByteBuffer.wrap(((KeyValue) bottomScanner.getKey()).getKey());
key = ByteBuffer.wrap(((KeyValue) bottomScanner.getKey()).getKey());
if (first) {
first = false;
LOG.info("First in bottom: " +
Bytes.toString(Bytes.toBytes(previous)));
LOG.info("First in bottom: " + Bytes.toString(Bytes.toBytes(previous)));
}
assertTrue(key.compareTo(bbMidkeyBytes) < 0);
}
@ -475,8 +484,7 @@ public class TestHStoreFile extends HBaseTestCase {
first = true;
topScanner = top.getScanner(false, false);
KeyValue.KeyOnlyKeyValue keyOnlyKV = new KeyValue.KeyOnlyKeyValue();
while ((!topScanner.isSeeked() && topScanner.seekTo()) ||
topScanner.next()) {
while ((!topScanner.isSeeked() && topScanner.seekTo()) || topScanner.next()) {
key = ByteBuffer.wrap(((KeyValue) topScanner.getKey()).getKey());
keyOnlyKV.setKey(key.array(), 0 + key.arrayOffset(), key.limit());
assertTrue(PrivateCellUtil.compare(topScanner.getReader().getComparator(), keyOnlyKV,
@ -513,8 +521,7 @@ public class TestHStoreFile extends HBaseTestCase {
bottom = bottomF.getReader();
first = true;
bottomScanner = bottom.getScanner(false, false);
while ((!bottomScanner.isSeeked() && bottomScanner.seekTo()) ||
bottomScanner.next()) {
while ((!bottomScanner.isSeeked() && bottomScanner.seekTo()) || bottomScanner.next()) {
key = ByteBuffer.wrap(((KeyValue) bottomScanner.getKey()).getKey());
if (first) {
first = false;
@ -556,8 +563,8 @@ public class TestHStoreFile extends HBaseTestCase {
long now = EnvironmentEdgeManager.currentTime();
for (int i = 0; i < 2000; i += 2) {
String row = String.format(localFormatter, i);
KeyValue kv = new KeyValue(Bytes.toBytes(row), Bytes.toBytes("family"),
Bytes.toBytes("col"), now, Bytes.toBytes("value"));
KeyValue kv = new KeyValue(Bytes.toBytes(row), Bytes.toBytes("family"), Bytes.toBytes("col"),
now, Bytes.toBytes("value"));
writer.append(kv);
}
writer.close();
@ -579,7 +586,7 @@ public class TestHStoreFile extends HBaseTestCase {
TreeSet<byte[]> columns = new TreeSet<>(Bytes.BYTES_COMPARATOR);
columns.add(Bytes.toBytes("family:col"));
Scan scan = new Scan(Bytes.toBytes(row),Bytes.toBytes(row));
Scan scan = new Scan().withStartRow(Bytes.toBytes(row)).withStopRow(Bytes.toBytes(row), true);
scan.addColumn(Bytes.toBytes("family"), Bytes.toBytes("family:col"));
HStore store = mock(HStore.class);
when(store.getColumnFamilyDescriptor())
@ -599,60 +606,48 @@ public class TestHStoreFile extends HBaseTestCase {
fs.delete(f, true);
assertEquals("False negatives: " + falseNeg, 0, falseNeg);
int maxFalsePos = (int) (2 * 2000 * err);
assertTrue("Too many false positives: " + falsePos + " (err=" + err + ", expected no more than "
+ maxFalsePos + ")", falsePos <= maxFalsePos);
assertTrue("Too many false positives: " + falsePos + " (err=" + err +
", expected no more than " + maxFalsePos + ")", falsePos <= maxFalsePos);
}
private static final int BLOCKSIZE_SMALL = 8192;
@Test
public void testBloomFilter() throws Exception {
FileSystem fs = FileSystem.getLocal(conf);
conf.setFloat(BloomFilterFactory.IO_STOREFILE_BLOOM_ERROR_RATE, (float) 0.01);
conf.setBoolean(BloomFilterFactory.IO_STOREFILE_BLOOM_ENABLED, true);
// write the file
Path f = new Path(ROOT_DIR, getName());
Path f = new Path(ROOT_DIR, name.getMethodName());
HFileContext meta = new HFileContextBuilder().withBlockSize(BLOCKSIZE_SMALL)
.withChecksumType(CKTYPE)
.withBytesPerCheckSum(CKBYTES).build();
.withChecksumType(CKTYPE).withBytesPerCheckSum(CKBYTES).build();
// Make a store file and write data to it.
StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs)
.withFilePath(f)
.withBloomType(BloomType.ROW)
.withMaxKeyCount(2000)
.withFileContext(meta)
.build();
StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs).withFilePath(f)
.withBloomType(BloomType.ROW).withMaxKeyCount(2000).withFileContext(meta).build();
bloomWriteRead(writer, fs);
}
@Test
public void testDeleteFamilyBloomFilter() throws Exception {
FileSystem fs = FileSystem.getLocal(conf);
conf.setFloat(BloomFilterFactory.IO_STOREFILE_BLOOM_ERROR_RATE, (float) 0.01);
conf.setBoolean(BloomFilterFactory.IO_STOREFILE_BLOOM_ENABLED, true);
float err = conf.getFloat(BloomFilterFactory.IO_STOREFILE_BLOOM_ERROR_RATE, 0);
// write the file
Path f = new Path(ROOT_DIR, getName());
Path f = new Path(ROOT_DIR, name.getMethodName());
HFileContext meta = new HFileContextBuilder()
.withBlockSize(BLOCKSIZE_SMALL)
.withChecksumType(CKTYPE)
.withBytesPerCheckSum(CKBYTES).build();
HFileContext meta = new HFileContextBuilder().withBlockSize(BLOCKSIZE_SMALL)
.withChecksumType(CKTYPE).withBytesPerCheckSum(CKBYTES).build();
// Make a store file and write data to it.
StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs)
.withFilePath(f)
.withMaxKeyCount(2000)
.withFileContext(meta)
.build();
StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs).withFilePath(f)
.withMaxKeyCount(2000).withFileContext(meta).build();
// add delete family
long now = EnvironmentEdgeManager.currentTime();
for (int i = 0; i < 2000; i += 2) {
String row = String.format(localFormatter, i);
KeyValue kv = new KeyValue(Bytes.toBytes(row), Bytes.toBytes("family"),
Bytes.toBytes("col"), now, KeyValue.Type.DeleteFamily, Bytes.toBytes("value"));
KeyValue kv = new KeyValue(Bytes.toBytes(row), Bytes.toBytes("family"), Bytes.toBytes("col"),
now, KeyValue.Type.DeleteFamily, Bytes.toBytes("value"));
writer.append(kv);
}
writer.close();
@ -687,8 +682,8 @@ public class TestHStoreFile extends HBaseTestCase {
fs.delete(f, true);
assertEquals("False negatives: " + falseNeg, 0, falseNeg);
int maxFalsePos = (int) (2 * 2000 * err);
assertTrue("Too many false positives: " + falsePos + " (err=" + err
+ ", expected no more than " + maxFalsePos, falsePos <= maxFalsePos);
assertTrue("Too many false positives: " + falsePos + " (err=" + err +
", expected no more than " + maxFalsePos, falsePos <= maxFalsePos);
}
/**
@ -697,13 +692,11 @@ public class TestHStoreFile extends HBaseTestCase {
@Test
public void testReseek() throws Exception {
// write the file
Path f = new Path(ROOT_DIR, getName());
Path f = new Path(ROOT_DIR, name.getMethodName());
HFileContext meta = new HFileContextBuilder().withBlockSize(8 * 1024).build();
// Make a store file and write data to it.
StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs)
.withFilePath(f)
.withFileContext(meta)
.build();
StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs).withFilePath(f)
.withFileContext(meta).build();
writeStoreFile(writer);
writer.close();
@ -745,17 +738,12 @@ public class TestHStoreFile extends HBaseTestCase {
for (int x : new int[] { 0, 1 }) {
// write the file
Path f = new Path(ROOT_DIR, getName() + x);
Path f = new Path(ROOT_DIR, name.getMethodName() + x);
HFileContext meta = new HFileContextBuilder().withBlockSize(BLOCKSIZE_SMALL)
.withChecksumType(CKTYPE)
.withBytesPerCheckSum(CKBYTES).build();
.withChecksumType(CKTYPE).withBytesPerCheckSum(CKBYTES).build();
// Make a store file and write data to it.
StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs)
.withFilePath(f)
.withBloomType(bt[x])
.withMaxKeyCount(expKeys[x])
.withFileContext(meta)
.build();
StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs).withFilePath(f)
.withBloomType(bt[x]).withMaxKeyCount(expKeys[x]).withFileContext(meta).build();
long now = EnvironmentEdgeManager.currentTime();
for (int i = 0; i < rowCount * 2; i += 2) { // rows
@ -771,12 +759,9 @@ public class TestHStoreFile extends HBaseTestCase {
}
writer.close();
ReaderContext context = new ReaderContextBuilder()
.withFilePath(f)
.withFileSize(fs.getFileStatus(f).getLen())
.withFileSystem(fs)
.withInputStreamWrapper(new FSDataInputStreamWrapper(fs, f))
.build();
ReaderContext context =
new ReaderContextBuilder().withFilePath(f).withFileSize(fs.getFileStatus(f).getLen())
.withFileSystem(fs).withInputStreamWrapper(new FSDataInputStreamWrapper(fs, f)).build();
HFileInfo fileInfo = new HFileInfo(context, conf);
StoreFileReader reader =
new StoreFileReader(context, fileInfo, cacheConf, new AtomicInteger(0), conf);
@ -799,11 +784,11 @@ public class TestHStoreFile extends HBaseTestCase {
TreeSet<byte[]> columns = new TreeSet<>(Bytes.BYTES_COMPARATOR);
columns.add(Bytes.toBytes("col" + col));
Scan scan = new Scan(Bytes.toBytes(row),Bytes.toBytes(row));
Scan scan =
new Scan().withStartRow(Bytes.toBytes(row)).withStopRow(Bytes.toBytes(row), true);
scan.addColumn(Bytes.toBytes("family"), Bytes.toBytes(("col" + col)));
boolean exists =
scanner.shouldUseScanner(scan, store, Long.MIN_VALUE);
boolean exists = scanner.shouldUseScanner(scan, store, Long.MIN_VALUE);
boolean shouldRowExist = i % 2 == 0;
boolean shouldColExist = j % 2 == 0;
shouldColExist = shouldColExist || bt[x] == BloomType.ROW;
@ -831,16 +816,15 @@ public class TestHStoreFile extends HBaseTestCase {
@Test
public void testSeqIdComparator() {
assertOrdering(StoreFileComparators.SEQ_ID, mockStoreFile(true, 100, 1000, -1, "/foo/123"),
mockStoreFile(true, 100, 1000, -1, "/foo/124"),
mockStoreFile(true, 99, 1000, -1, "/foo/126"),
mockStoreFile(true, 100, 1000, -1, "/foo/124"), mockStoreFile(true, 99, 1000, -1, "/foo/126"),
mockStoreFile(true, 98, 2000, -1, "/foo/126"), mockStoreFile(false, 3453, -1, 1, "/foo/1"),
mockStoreFile(false, 2, -1, 3, "/foo/2"), mockStoreFile(false, 1000, -1, 5, "/foo/2"),
mockStoreFile(false, 76, -1, 5, "/foo/3"));
}
/**
* Assert that the given comparator orders the given storefiles in the
* same way that they're passed.
* Assert that the given comparator orders the given storefiles in the same way that they're
* passed.
*/
private void assertOrdering(Comparator<? super HStoreFile> comparator, HStoreFile... sfs) {
ArrayList<HStoreFile> sorted = Lists.newArrayList(sfs);
@ -854,10 +838,7 @@ public class TestHStoreFile extends HBaseTestCase {
/**
* Create a mock StoreFile with the given attributes.
*/
private HStoreFile mockStoreFile(boolean bulkLoad,
long size,
long bulkTimestamp,
long seqId,
private HStoreFile mockStoreFile(boolean bulkLoad, long size, long bulkTimestamp, long seqId,
String path) {
HStoreFile mock = Mockito.mock(HStoreFile.class);
StoreFileReader reader = Mockito.mock(StoreFileReader.class);
@ -869,10 +850,8 @@ public class TestHStoreFile extends HBaseTestCase {
Mockito.doReturn(OptionalLong.of(bulkTimestamp)).when(mock).getBulkLoadTimestamp();
Mockito.doReturn(seqId).when(mock).getMaxSequenceId();
Mockito.doReturn(new Path(path)).when(mock).getPath();
String name = "mock storefile, bulkLoad=" + bulkLoad +
" bulkTimestamp=" + bulkTimestamp +
" seqId=" + seqId +
" path=" + path;
String name = "mock storefile, bulkLoad=" + bulkLoad + " bulkTimestamp=" + bulkTimestamp +
" seqId=" + seqId + " path=" + path;
Mockito.doReturn(name).when(mock).toString();
return mock;
}
@ -881,8 +860,7 @@ public class TestHStoreFile extends HBaseTestCase {
* Generate a list of KeyValues for testing based on given parameters
* @return the rows key-value list
*/
List<KeyValue> getKeyValueSet(long[] timestamps, int numRows,
byte[] qualifier, byte[] family) {
List<KeyValue> getKeyValueSet(long[] timestamps, int numRows, byte[] qualifier, byte[] family) {
List<KeyValue> kvList = new ArrayList<>();
for (int i = 1; i <= numRows; i++) {
byte[] b = Bytes.toBytes(i);
@ -912,12 +890,9 @@ public class TestHStoreFile extends HBaseTestCase {
HFileContext meta = new HFileContextBuilder().withBlockSize(8 * 1024).build();
// Make a store file and write data to it.
StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs)
.withOutputDir(dir)
.withFileContext(meta)
.build();
.withOutputDir(dir).withFileContext(meta).build();
List<KeyValue> kvList = getKeyValueSet(timestamps,numRows,
qualifier, family);
List<KeyValue> kvList = getKeyValueSet(timestamps, numRows, qualifier, family);
for (KeyValue kv : kvList) {
writer.append(kv);
@ -925,8 +900,8 @@ public class TestHStoreFile extends HBaseTestCase {
writer.appendMetadata(0, false);
writer.close();
HStoreFile hsf = new HStoreFile(this.fs, writer.getPath(), conf, cacheConf,
BloomType.NONE, true);
HStoreFile hsf =
new HStoreFile(this.fs, writer.getPath(), conf, cacheConf, BloomType.NONE, true);
HStore store = mock(HStore.class);
when(store.getColumnFamilyDescriptor()).thenReturn(ColumnFamilyDescriptorBuilder.of(family));
hsf.initReader();
@ -980,8 +955,8 @@ public class TestHStoreFile extends HBaseTestCase {
CacheConfig cacheConf = new CacheConfig(conf, bc);
Path pathCowOff = new Path(baseDir, "123456789");
StoreFileWriter writer = writeStoreFile(conf, cacheConf, pathCowOff, 3);
HStoreFile hsf = new HStoreFile(this.fs, writer.getPath(), conf, cacheConf,
BloomType.NONE, true);
HStoreFile hsf =
new HStoreFile(this.fs, writer.getPath(), conf, cacheConf, BloomType.NONE, true);
LOG.debug(hsf.getPath().toString());
// Read this file, we should see 3 misses
@ -1005,8 +980,7 @@ public class TestHStoreFile extends HBaseTestCase {
cacheConf = new CacheConfig(conf, bc);
Path pathCowOn = new Path(baseDir, "123456788");
writer = writeStoreFile(conf, cacheConf, pathCowOn, 3);
hsf = new HStoreFile(this.fs, writer.getPath(), conf, cacheConf,
BloomType.NONE, true);
hsf = new HStoreFile(this.fs, writer.getPath(), conf, cacheConf, BloomType.NONE, true);
// Read this file, we should see 3 hits
hsf.initReader();
@ -1043,11 +1017,9 @@ public class TestHStoreFile extends HBaseTestCase {
assertTrue(kv1.equals(kv2));
KeyValue keyv1 = KeyValueUtil.ensureKeyValue(kv1);
KeyValue keyv2 = KeyValueUtil.ensureKeyValue(kv2);
assertTrue(Bytes.compareTo(
keyv1.getBuffer(), keyv1.getKeyOffset(), keyv1.getKeyLength(),
assertTrue(Bytes.compareTo(keyv1.getBuffer(), keyv1.getKeyOffset(), keyv1.getKeyLength(),
keyv2.getBuffer(), keyv2.getKeyOffset(), keyv2.getKeyLength()) == 0);
assertTrue(Bytes.compareTo(
kv1.getValueArray(), kv1.getValueOffset(), kv1.getValueLength(),
assertTrue(Bytes.compareTo(kv1.getValueArray(), kv1.getValueOffset(), kv1.getValueLength(),
kv2.getValueArray(), kv2.getValueOffset(), kv2.getValueLength()) == 0);
}
assertNull(scannerTwo.next());
@ -1088,10 +1060,9 @@ public class TestHStoreFile extends HBaseTestCase {
assertEquals(startEvicted, cs.getEvictedCount());
}
private Path splitStoreFile(final HRegionFileSystem regionFs, final HRegionInfo hri,
private Path splitStoreFile(final HRegionFileSystem regionFs, final RegionInfo hri,
final String family, final HStoreFile sf, final byte[] splitKey, boolean isTopRef)
throws IOException {
FileSystem fs = regionFs.getFileSystem();
Path path = regionFs.splitStoreFile(hri, family, sf, splitKey, isTopRef, null);
if (null == path) {
return null;
@ -1125,16 +1096,11 @@ public class TestHStoreFile extends HBaseTestCase {
totalSize += kv.getLength() + 1;
}
int blockSize = totalSize / numBlocks;
HFileContext meta = new HFileContextBuilder().withBlockSize(blockSize)
.withChecksumType(CKTYPE)
.withBytesPerCheckSum(CKBYTES)
.build();
HFileContext meta = new HFileContextBuilder().withBlockSize(blockSize).withChecksumType(CKTYPE)
.withBytesPerCheckSum(CKBYTES).build();
// Make a store file and write data to it.
StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs)
.withFilePath(path)
.withMaxKeyCount(2000)
.withFileContext(meta)
.build();
.withFilePath(path).withMaxKeyCount(2000).withFileContext(meta).build();
// We'll write N-1 KVs to ensure we don't write an extra block
kvs.remove(kvs.size() - 1);
for (KeyValue kv : kvs) {
@ -1146,8 +1112,7 @@ public class TestHStoreFile extends HBaseTestCase {
}
/**
* Check if data block encoding information is saved correctly in HFile's
* file info.
* Check if data block encoding information is saved correctly in HFile's file info.
*/
@Test
public void testDataBlockEncodingMetaData() throws IOException {
@ -1155,23 +1120,14 @@ public class TestHStoreFile extends HBaseTestCase {
Path dir = new Path(new Path(testDir, "7e0102"), "familyname");
Path path = new Path(dir, "1234567890");
DataBlockEncoding dataBlockEncoderAlgo =
DataBlockEncoding.FAST_DIFF;
HFileDataBlockEncoder dataBlockEncoder =
new HFileDataBlockEncoderImpl(
dataBlockEncoderAlgo);
DataBlockEncoding dataBlockEncoderAlgo = DataBlockEncoding.FAST_DIFF;
cacheConf = new CacheConfig(conf);
HFileContext meta = new HFileContextBuilder().withBlockSize(BLOCKSIZE_SMALL)
.withChecksumType(CKTYPE)
.withBytesPerCheckSum(CKBYTES)
.withDataBlockEncoding(dataBlockEncoderAlgo)
.build();
HFileContext meta =
new HFileContextBuilder().withBlockSize(BLOCKSIZE_SMALL).withChecksumType(CKTYPE)
.withBytesPerCheckSum(CKBYTES).withDataBlockEncoding(dataBlockEncoderAlgo).build();
// Make a store file and write data to it.
StoreFileWriter writer = new StoreFileWriter.Builder(conf, cacheConf, this.fs)
.withFilePath(path)
.withMaxKeyCount(2000)
.withFileContext(meta)
.build();
.withFilePath(path).withMaxKeyCount(2000).withFileContext(meta).build();
writer.close();
HStoreFile storeFile =
@ -1181,6 +1137,6 @@ public class TestHStoreFile extends HBaseTestCase {
Map<byte[], byte[]> fileInfo = reader.loadFileInfo();
byte[] value = fileInfo.get(HFileDataBlockEncoder.DATA_BLOCK_ENCODING);
assertEquals(dataBlockEncoderAlgo.getNameInBytes(), value);
assertArrayEquals(dataBlockEncoderAlgo.getNameInBytes(), value);
}
}

View File

@ -17,6 +17,10 @@
*/
package org.apache.hadoop.hbase.regionserver;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@ -24,19 +28,17 @@ import java.util.List;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellComparatorImpl;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestCase;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.testclassification.RegionServerTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.CollectionBackedScanner;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category({ RegionServerTests.class, SmallTests.class })
public class TestKeyValueHeap extends HBaseTestCase {
public class TestKeyValueHeap {
@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
@ -74,15 +76,14 @@ public class TestKeyValueHeap extends HBaseTestCase {
List<KeyValueScanner> scanners = new ArrayList<>(Arrays.asList(s1, s2, s3));
/*
* Uses {@code scanners} to build a KeyValueHeap, iterates over it and asserts that returned
* Cells are same as {@code expected}.
* Uses {@code scanners} to build a KeyValueHeap, iterates over it and asserts that returned Cells
* are same as {@code expected}.
* @return List of Cells returned from scanners.
*/
public List<Cell> assertCells(List<Cell> expected, List<KeyValueScanner> scanners)
throws IOException {
// Creating KeyValueHeap
KeyValueHeap kvh = new KeyValueHeap(scanners, CellComparatorImpl.COMPARATOR);
try (KeyValueHeap kvh = new KeyValueHeap(scanners, CellComparatorImpl.COMPARATOR)) {
List<Cell> actual = new ArrayList<>();
while (kvh.peek() != null) {
actual.add(kvh.next());
@ -91,11 +92,6 @@ public class TestKeyValueHeap extends HBaseTestCase {
assertEquals(expected, actual);
return actual;
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
}
@Test
@ -104,8 +100,8 @@ public class TestKeyValueHeap extends HBaseTestCase {
// 1. The "smallest" Cell is in the same scanners as current
// 2. Current scanner gets empty
List<Cell> expected = Arrays.asList(
kv111, kv112, kv113, kv114, kv115, kv121, kv122, kv211, kv212, kv213);
List<Cell> expected =
Arrays.asList(kv111, kv112, kv113, kv114, kv115, kv121, kv122, kv211, kv212, kv213);
List<Cell> actual = assertCells(expected, scanners);
@ -121,20 +117,18 @@ public class TestKeyValueHeap extends HBaseTestCase {
// Cases:
// 1. Seek Cell that is not in scanner
// 2. Check that smallest that is returned from a seek is correct
List<Cell> expected = Arrays.asList(kv211);
// Creating KeyValueHeap
KeyValueHeap kvh =
new KeyValueHeap(scanners, CellComparatorImpl.COMPARATOR);
try (KeyValueHeap kvh = new KeyValueHeap(scanners, CellComparatorImpl.COMPARATOR)) {
Cell seekKv = new KeyValue(row2, fam1, null, null);
kvh.seek(seekKv);
List<Cell> actual = Arrays.asList(kvh.peek());
assertEquals("Expected = " + Arrays.toString(expected.toArray())
+ "\n Actual = " + Arrays.toString(actual.toArray()), expected, actual);
assertEquals("Expected = " + Arrays.toString(expected.toArray()) + "\n Actual = " +
Arrays.toString(actual.toArray()), expected, actual);
}
}
@Test
@ -145,17 +139,22 @@ public class TestKeyValueHeap extends HBaseTestCase {
scanners.add(s4);
// Creating KeyValueHeap
KeyValueHeap kvh = new KeyValueHeap(scanners, CellComparatorImpl.COMPARATOR);
while(kvh.next() != null);
try (KeyValueHeap kvh = new KeyValueHeap(scanners, CellComparatorImpl.COMPARATOR)) {
for (;;) {
if (kvh.next() == null) {
break;
}
}
// Once the internal scanners go out of Cells, those will be removed from KVHeap's priority
// queue and added to a Set for lazy close. The actual close will happen only on KVHeap#close()
// queue and added to a Set for lazy close. The actual close will happen only on
// KVHeap#close()
assertEquals(4, kvh.scannersForDelayedClose.size());
assertTrue(kvh.scannersForDelayedClose.contains(s1));
assertTrue(kvh.scannersForDelayedClose.contains(s2));
assertTrue(kvh.scannersForDelayedClose.contains(s3));
assertTrue(kvh.scannersForDelayedClose.contains(s4));
kvh.close();
}
for (KeyValueScanner scanner : scanners) {
assertTrue(((TestScanner) scanner).isClosed());
}
@ -173,19 +172,19 @@ public class TestKeyValueHeap extends HBaseTestCase {
List<KeyValueScanner> scanners = new ArrayList<>(Arrays.asList(s1, s2, s3, s4));
// Creating KeyValueHeap
KeyValueHeap kvh = new KeyValueHeap(scanners, CellComparatorImpl.COMPARATOR);
try {
try (KeyValueHeap kvh = new KeyValueHeap(scanners, CellComparatorImpl.COMPARATOR)) {
for (KeyValueScanner scanner : scanners) {
((SeekTestScanner) scanner).setRealSeekDone(false);
}
while (kvh.next() != null);
// The pollRealKV should throw IOE.
assertTrue(false);
} catch (IOException ioe) {
kvh.close();
assertThrows(IOException.class, () -> {
for (;;) {
if (kvh.next() == null) {
break;
}
}
});
}
// It implies there is no NPE thrown from kvh.close() if getting here
for (KeyValueScanner scanner : scanners) {
// Verify that close is called and only called once for each scanner
@ -198,18 +197,15 @@ public class TestKeyValueHeap extends HBaseTestCase {
public void testPriorityId() throws IOException {
Cell kv113A = new KeyValue(row1, fam1, col3, Bytes.toBytes("aaa"));
Cell kv113B = new KeyValue(row1, fam1, col3, Bytes.toBytes("bbb"));
{
TestScanner scan1 = new TestScanner(Arrays.asList(kv111, kv112, kv113A), 1);
TestScanner scan2 = new TestScanner(Arrays.asList(kv113B), 2);
List<Cell> expected = Arrays.asList(kv111, kv112, kv113B, kv113A);
assertCells(expected, new ArrayList<>(Arrays.asList(scan1, scan2)));
}
{
TestScanner scan1 = new TestScanner(Arrays.asList(kv111, kv112, kv113A), 2);
TestScanner scan2 = new TestScanner(Arrays.asList(kv113B), 1);
List<Cell> expected = Arrays.asList(kv111, kv112, kv113A, kv113B);
assertCells(expected, new ArrayList<>(Arrays.asList(scan1, scan2)));
}
assertCells(expected, Arrays.asList(scan1, scan2));
scan1 = new TestScanner(Arrays.asList(kv111, kv112, kv113A), 2);
scan2 = new TestScanner(Arrays.asList(kv113B), 1);
expected = Arrays.asList(kv111, kv112, kv113A, kv113B);
assertCells(expected, Arrays.asList(scan1, scan2));
}
private static class TestScanner extends CollectionBackedScanner {

View File

@ -37,11 +37,13 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestCase;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.HTestConst;
import org.apache.hadoop.hbase.KeepDeletedCells;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Result;
@ -87,7 +89,9 @@ public class TestMajorCompaction {
public static Object[] data() {
return new Object[] { "NONE", "BASIC", "EAGER" };
}
@Rule public TestName name;
@Rule
public TestName name;
private static final Logger LOG = LoggerFactory.getLogger(TestMajorCompaction.class.getName());
private static final HBaseTestingUtility UTIL = HBaseTestingUtility.createLocalHTU();
protected Configuration conf = UTIL.getConfiguration();
@ -121,7 +125,10 @@ public class TestMajorCompaction {
@Before
public void setUp() throws Exception {
this.htd = UTIL.createTableDescriptor(name.getMethodName().replace('[','i').replace(']','i'));
this.htd = UTIL.createTableDescriptor(
TableName.valueOf(name.getMethodName().replace('[', 'i').replace(']', 'i')),
ColumnFamilyDescriptorBuilder.DEFAULT_MIN_VERSIONS, 3, HConstants.FOREVER,
ColumnFamilyDescriptorBuilder.DEFAULT_KEEP_DELETED);
this.r = UTIL.createLocalHRegion(htd, null, null);
}
@ -133,9 +140,9 @@ public class TestMajorCompaction {
}
/**
* Test that on a major compaction, if all cells are expired or deleted, then
* we'll end up with no product. Make sure scanner over region returns
* right answer in this case - and that it just basically works.
* Test that on a major compaction, if all cells are expired or deleted, then we'll end up with no
* product. Make sure scanner over region returns right answer in this case - and that it just
* basically works.
* @throws IOException exception encountered
*/
@Test
@ -153,8 +160,7 @@ public class TestMajorCompaction {
}
/**
* Run compaction and flushing memstore
* Assert deletes get cleaned up.
* Run compaction and flushing memstore Assert deletes get cleaned up.
* @throws Exception
*/
@Test
@ -172,15 +178,13 @@ public class TestMajorCompaction {
majorCompactionWithDataBlockEncoding(false);
}
public void majorCompactionWithDataBlockEncoding(boolean inCacheOnly)
throws Exception {
public void majorCompactionWithDataBlockEncoding(boolean inCacheOnly) throws Exception {
Map<HStore, HFileDataBlockEncoder> replaceBlockCache = new HashMap<>();
for (HStore store : r.getStores()) {
HFileDataBlockEncoder blockEncoder = store.getDataBlockEncoder();
replaceBlockCache.put(store, blockEncoder);
final DataBlockEncoding inCache = DataBlockEncoding.PREFIX;
final DataBlockEncoding onDisk = inCacheOnly ? DataBlockEncoding.NONE :
inCache;
final DataBlockEncoding onDisk = inCacheOnly ? DataBlockEncoding.NONE : inCache;
((HStore) store).setDataBlockEncoderInTest(new HFileDataBlockEncoderImpl(onDisk));
}
@ -198,7 +202,7 @@ public class TestMajorCompaction {
createStoreFile(r);
}
// Add more content.
HBaseTestCase.addContent(new RegionAsTable(r), Bytes.toString(COLUMN_FAMILY));
HTestConst.addContent(new RegionAsTable(r), Bytes.toString(COLUMN_FAMILY));
// Now there are about 5 versions of each column.
// Default is that there only 3 (MAXVERSIONS) versions allowed per column.
@ -234,11 +238,10 @@ public class TestMajorCompaction {
// Always 3 versions if that is what max versions is.
result = r.get(new Get(secondRowBytes).addFamily(COLUMN_FAMILY_TEXT).readVersions(100));
LOG.debug("Row " + Bytes.toStringBinary(secondRowBytes) + " after " +
"initial compaction: " + result);
assertEquals("Invalid number of versions of row "
+ Bytes.toStringBinary(secondRowBytes) + ".", compactionThreshold,
result.size());
LOG.debug(
"Row " + Bytes.toStringBinary(secondRowBytes) + " after " + "initial compaction: " + result);
assertEquals("Invalid number of versions of row " + Bytes.toStringBinary(secondRowBytes) + ".",
compactionThreshold, result.size());
// Now add deletes to memstore and then flush it.
// That will put us over
@ -315,8 +318,8 @@ public class TestMajorCompaction {
assertEquals(2, s.getStorefilesCount());
// ensure that major compaction time is deterministic
RatioBasedCompactionPolicy
c = (RatioBasedCompactionPolicy)s.storeEngine.getCompactionPolicy();
RatioBasedCompactionPolicy c =
(RatioBasedCompactionPolicy) s.storeEngine.getCompactionPolicy();
Collection<HStoreFile> storeFiles = s.getStorefiles();
long mcTime = c.getNextMajorCompactTime(storeFiles);
for (int i = 0; i < 10; ++i) {
@ -363,7 +366,6 @@ public class TestMajorCompaction {
assertEquals(countRow2, count2);
}
private int count() throws IOException {
int count = 0;
for (HStoreFile f : r.getStore(COLUMN_FAMILY_TEXT).getStorefiles()) {
@ -384,14 +386,13 @@ public class TestMajorCompaction {
private void createStoreFile(final HRegion region, String family) throws IOException {
Table loader = new RegionAsTable(region);
HBaseTestCase.addContent(loader, family);
HTestConst.addContent(loader, family);
region.flush(true);
}
private void createSmallerStoreFile(final HRegion region) throws IOException {
Table loader = new RegionAsTable(region);
HBaseTestCase.addContent(loader, Bytes.toString(COLUMN_FAMILY), Bytes.toBytes("" +
"bbb"), null);
HTestConst.addContent(loader, Bytes.toString(COLUMN_FAMILY), Bytes.toBytes("" + "bbb"), null);
region.flush(true);
}
@ -410,8 +411,7 @@ public class TestMajorCompaction {
CompactionRequestImpl request = store.requestCompaction().get().getRequest();
assertNotNull("Expected to receive a compaction request", request);
assertEquals(
"System-requested major compaction should not occur if there are too many store files",
false,
"System-requested major compaction should not occur if there are too many store files", false,
request.isMajor());
}
@ -426,14 +426,12 @@ public class TestMajorCompaction {
createStoreFile(r);
}
store.triggerMajorCompaction();
CompactionRequestImpl request =
store.requestCompaction(PRIORITY_USER, CompactionLifeCycleTracker.DUMMY, null).get()
.getRequest();
CompactionRequestImpl request = store
.requestCompaction(PRIORITY_USER, CompactionLifeCycleTracker.DUMMY, null).get().getRequest();
assertNotNull("Expected to receive a compaction request", request);
assertEquals(
"User-requested major compaction should always occur, even if there are too many store files",
true,
request.isMajor());
true, request.isMajor());
}
/**

View File

@ -30,9 +30,9 @@ import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestCase;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTestConst;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Result;
@ -195,13 +195,13 @@ public class TestMinorCompaction {
throws Exception {
Table loader = new RegionAsTable(r);
for (int i = 0; i < COMPACTION_THRESHOLD + 1; i++) {
HBaseTestCase.addContent(loader, Bytes.toString(fam1), Bytes.toString(COL1), FIRST_ROW_BYTES,
HTestConst.addContent(loader, Bytes.toString(fam1), Bytes.toString(COL1), FIRST_ROW_BYTES,
THIRD_ROW_BYTES, i);
HBaseTestCase.addContent(loader, Bytes.toString(fam1), Bytes.toString(COL2), FIRST_ROW_BYTES,
HTestConst.addContent(loader, Bytes.toString(fam1), Bytes.toString(COL2), FIRST_ROW_BYTES,
THIRD_ROW_BYTES, i);
HBaseTestCase.addContent(loader, Bytes.toString(fam2), Bytes.toString(COL1), FIRST_ROW_BYTES,
HTestConst.addContent(loader, Bytes.toString(fam2), Bytes.toString(COL1), FIRST_ROW_BYTES,
THIRD_ROW_BYTES, i);
HBaseTestCase.addContent(loader, Bytes.toString(fam2), Bytes.toString(COL2), FIRST_ROW_BYTES,
HTestConst.addContent(loader, Bytes.toString(fam2), Bytes.toString(COL2), FIRST_ROW_BYTES,
THIRD_ROW_BYTES, i);
r.flush(true);
}

View File

@ -31,12 +31,12 @@ import java.util.List;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestCase;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.HTestConst;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.UnknownScannerException;
import org.apache.hadoop.hbase.client.Delete;
@ -132,7 +132,7 @@ public class TestScanner {
byte [] stoprow = Bytes.toBytes("ccc");
try {
this.region = TEST_UTIL.createLocalHRegion(TESTTABLEDESC, null, null);
HBaseTestCase.addContent(this.region, HConstants.CATALOG_FAMILY);
HTestConst.addContent(this.region, HConstants.CATALOG_FAMILY);
List<Cell> results = new ArrayList<>();
// Do simple test of getting one row only first.
Scan scan = new Scan(Bytes.toBytes("abc"), Bytes.toBytes("abd"));
@ -205,7 +205,7 @@ public class TestScanner {
public void testFilters() throws IOException {
try {
this.region = TEST_UTIL.createLocalHRegion(TESTTABLEDESC, null, null);
HBaseTestCase.addContent(this.region, HConstants.CATALOG_FAMILY);
HTestConst.addContent(this.region, HConstants.CATALOG_FAMILY);
byte [] prefix = Bytes.toBytes("ab");
Filter newFilter = new PrefixFilter(prefix);
Scan scan = new Scan();
@ -231,7 +231,7 @@ public class TestScanner {
public void testRaceBetweenClientAndTimeout() throws Exception {
try {
this.region = TEST_UTIL.createLocalHRegion(TESTTABLEDESC, null, null);
HBaseTestCase.addContent(this.region, HConstants.CATALOG_FAMILY);
HTestConst.addContent(this.region, HConstants.CATALOG_FAMILY);
Scan scan = new Scan();
InternalScanner s = region.getScanner(scan);
List<Cell> results = new ArrayList<>();
@ -463,7 +463,7 @@ public class TestScanner {
Table hri = new RegionAsTable(region);
try {
LOG.info("Added: " +
HBaseTestCase.addContent(hri, Bytes.toString(HConstants.CATALOG_FAMILY),
HTestConst.addContent(hri, Bytes.toString(HConstants.CATALOG_FAMILY),
Bytes.toString(HConstants.REGIONINFO_QUALIFIER)));
int count = count(hri, -1, false);
assertEquals(count, count(hri, 100, false)); // do a sync flush.
@ -485,7 +485,7 @@ public class TestScanner {
Table hri = new RegionAsTable(region);
try {
LOG.info("Added: " +
HBaseTestCase.addContent(hri, Bytes.toString(HConstants.CATALOG_FAMILY),
HTestConst.addContent(hri, Bytes.toString(HConstants.CATALOG_FAMILY),
Bytes.toString(HConstants.REGIONINFO_QUALIFIER)));
int count = count(hri, -1, false);
assertEquals(count, count(hri, 100, true)); // do a true concurrent background thread flush
@ -509,9 +509,9 @@ public class TestScanner {
Table hri = new RegionAsTable(region);
try {
HBaseTestCase.addContent(hri, Bytes.toString(fam1), Bytes.toString(col1),
HTestConst.addContent(hri, Bytes.toString(fam1), Bytes.toString(col1),
firstRowBytes, secondRowBytes);
HBaseTestCase.addContent(hri, Bytes.toString(fam2), Bytes.toString(col1),
HTestConst.addContent(hri, Bytes.toString(fam2), Bytes.toString(col1),
firstRowBytes, secondRowBytes);
Delete dc = new Delete(firstRowBytes);
@ -520,9 +520,9 @@ public class TestScanner {
region.delete(dc);
region.flush(true);
HBaseTestCase.addContent(hri, Bytes.toString(fam1), Bytes.toString(col1),
HTestConst.addContent(hri, Bytes.toString(fam1), Bytes.toString(col1),
secondRowBytes, thirdRowBytes);
HBaseTestCase.addContent(hri, Bytes.toString(fam2), Bytes.toString(col1),
HTestConst.addContent(hri, Bytes.toString(fam2), Bytes.toString(col1),
secondRowBytes, thirdRowBytes);
region.flush(true);

View File

@ -17,27 +17,35 @@
*/
package org.apache.hadoop.hbase.regionserver;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestCase;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.RegionInfoBuilder;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.testclassification.RegionServerTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@ -45,33 +53,52 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Category({ RegionServerTests.class, SmallTests.class })
public class TestWideScanner extends HBaseTestCase {
public class TestWideScanner {
@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
HBaseClassTestRule.forClass(TestWideScanner.class);
private static final HBaseTestingUtility UTIL = new HBaseTestingUtility();
private static final Logger LOG = LoggerFactory.getLogger(TestWideScanner.class);
static final byte[] A = Bytes.toBytes("A");
static final byte[] B = Bytes.toBytes("B");
static final byte[] C = Bytes.toBytes("C");
static byte[][] COLUMNS = { A, B, C };
static final Random rng = new Random();
static final HTableDescriptor TESTTABLEDESC =
new HTableDescriptor(TableName.valueOf("testwidescan"));
private static final byte[] A = Bytes.toBytes("A");
private static final byte[] B = Bytes.toBytes("B");
private static final byte[] C = Bytes.toBytes("C");
private static byte[][] COLUMNS = { A, B, C };
private static final TableDescriptor TESTTABLEDESC;
static {
TableDescriptorBuilder builder =
TableDescriptorBuilder.newBuilder(TableName.valueOf("testwidescan"));
for (byte[] cfName : new byte[][] { A, B, C }) {
TESTTABLEDESC.addFamily(new HColumnDescriptor(cfName)
// Keep versions to help debugging.
.setMaxVersions(100)
.setBlocksize(8 * 1024)
);
builder.setColumnFamily(ColumnFamilyDescriptorBuilder.newBuilder(cfName).setMaxVersions(100)
.setBlocksize(8 * 1024).build());
}
TESTTABLEDESC = builder.build();
}
/** HRegionInfo for root region */
HRegion r;
private static HRegion REGION;
@BeforeClass
public static void setUp() throws IOException {
Path testDir = UTIL.getDataTestDir();
RegionInfo hri = RegionInfoBuilder.newBuilder(TESTTABLEDESC.getTableName()).build();
REGION =
HBaseTestingUtility.createRegionAndWAL(hri, testDir, UTIL.getConfiguration(), TESTTABLEDESC);
}
@AfterClass
public static void tearDown() throws IOException {
if (REGION != null) {
HBaseTestingUtility.closeRegionAndWAL(REGION);
REGION = null;
}
UTIL.cleanupTestDir();
}
private int addWideContent(HRegion region) throws IOException {
int count = 0;
@ -85,7 +112,7 @@ public class TestWideScanner extends HBaseTestCase {
Put put = new Put(row);
put.setDurability(Durability.SKIP_WAL);
long ts1 = ++ts;
put.addColumn(COLUMNS[rng.nextInt(COLUMNS.length)], b, ts1, b);
put.addColumn(COLUMNS[ThreadLocalRandom.current().nextInt(COLUMNS.length)], b, ts1, b);
region.put(put);
count++;
}
@ -97,17 +124,15 @@ public class TestWideScanner extends HBaseTestCase {
@Test
public void testWideScanBatching() throws IOException {
final int batch = 256;
try {
this.r = createNewHRegion(TESTTABLEDESC, null, null);
int inserted = addWideContent(this.r);
int inserted = addWideContent(REGION);
List<Cell> results = new ArrayList<>();
Scan scan = new Scan();
scan.addFamily(A);
scan.addFamily(B);
scan.addFamily(C);
scan.setMaxVersions(100);
scan.readVersions(100);
scan.setBatch(batch);
InternalScanner s = r.getScanner(scan);
try (InternalScanner s = REGION.getScanner(scan)) {
int total = 0;
int i = 0;
boolean more;
@ -132,23 +157,16 @@ public class TestWideScanner extends HBaseTestCase {
results.clear();
// trigger ChangedReadersObservers
Iterator<KeyValueScanner> scanners =
((RegionScannerImpl) s).storeHeap.getHeap().iterator();
Iterator<KeyValueScanner> scanners = ((RegionScannerImpl) s).storeHeap.getHeap().iterator();
while (scanners.hasNext()) {
StoreScanner ss = (StoreScanner) scanners.next();
ss.updateReaders(Collections.EMPTY_LIST, Collections.EMPTY_LIST);
ss.updateReaders(Collections.emptyList(), Collections.emptyList());
}
} while (more);
// assert that the scanner returned all values
LOG.info("inserted " + inserted + ", scanned " + total);
assertEquals(total, inserted);
s.close();
} finally {
HBaseTestingUtility.closeRegionAndWAL(this.r);
}
}
}