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.io.hfile;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertNotNull;
022import static org.junit.Assert.assertTrue;
023
024import java.io.ByteArrayInputStream;
025import java.io.DataInputStream;
026import java.io.IOException;
027import java.util.ArrayList;
028import java.util.Collection;
029import java.util.List;
030import java.util.Random;
031import org.apache.hadoop.conf.Configuration;
032import org.apache.hadoop.fs.FSDataInputStream;
033import org.apache.hadoop.fs.FileSystem;
034import org.apache.hadoop.fs.Path;
035import org.apache.hadoop.hbase.ArrayBackedTag;
036import org.apache.hadoop.hbase.Cell;
037import org.apache.hadoop.hbase.CellComparator;
038import org.apache.hadoop.hbase.HBaseClassTestRule;
039import org.apache.hadoop.hbase.HBaseCommonTestingUtility;
040import org.apache.hadoop.hbase.HBaseTestingUtility;
041import org.apache.hadoop.hbase.HConstants;
042import org.apache.hadoop.hbase.KeyValue;
043import org.apache.hadoop.hbase.Tag;
044import org.apache.hadoop.hbase.io.ByteBuffAllocator;
045import org.apache.hadoop.hbase.io.FSDataInputStreamWrapper;
046import org.apache.hadoop.hbase.io.compress.Compression;
047import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
048import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
049import org.apache.hadoop.hbase.nio.ByteBuff;
050import org.apache.hadoop.hbase.testclassification.IOTests;
051import org.apache.hadoop.hbase.testclassification.SmallTests;
052import org.apache.hadoop.hbase.util.Bytes;
053import org.apache.hadoop.hbase.util.Writables;
054import org.apache.hadoop.io.Text;
055import org.apache.hadoop.io.WritableUtils;
056import org.junit.Before;
057import org.junit.ClassRule;
058import org.junit.Test;
059import org.junit.experimental.categories.Category;
060import org.junit.runner.RunWith;
061import org.junit.runners.Parameterized;
062import org.junit.runners.Parameterized.Parameters;
063import org.slf4j.Logger;
064import org.slf4j.LoggerFactory;
065
066/**
067 * Testing writing a version 3 {@link HFile}.
068 */
069@RunWith(Parameterized.class)
070@Category({ IOTests.class, SmallTests.class })
071public class TestHFileWriterV3 {
072
073  @ClassRule
074  public static final HBaseClassTestRule CLASS_RULE =
075    HBaseClassTestRule.forClass(TestHFileWriterV3.class);
076
077  private static final Logger LOG = LoggerFactory.getLogger(TestHFileWriterV3.class);
078  private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
079  private static final Random RNG = new Random(9713312); // Just a fixed seed.
080
081  private Configuration conf;
082  private FileSystem fs;
083  private boolean useTags;
084
085  public TestHFileWriterV3(boolean useTags) {
086    this.useTags = useTags;
087  }
088
089  @Parameters
090  public static Collection<Object[]> parameters() {
091    return HBaseCommonTestingUtility.BOOLEAN_PARAMETERIZED;
092  }
093
094  @Before
095  public void setUp() throws IOException {
096    conf = TEST_UTIL.getConfiguration();
097    fs = FileSystem.get(conf);
098  }
099
100  @Test
101  public void testHFileFormatV3() throws IOException {
102    testHFileFormatV3Internals(useTags);
103  }
104
105  private void testHFileFormatV3Internals(boolean useTags) throws IOException {
106    Path hfilePath = new Path(TEST_UTIL.getDataTestDir(), "testHFileFormatV3");
107    final Compression.Algorithm compressAlgo = Compression.Algorithm.GZ;
108    final int entryCount = 10000;
109    writeDataAndReadFromHFile(hfilePath, compressAlgo, entryCount, false, useTags);
110  }
111
112  @Test
113  public void testMidKeyInHFile() throws IOException {
114    testMidKeyInHFileInternals(useTags);
115  }
116
117  private void testMidKeyInHFileInternals(boolean useTags) throws IOException {
118    Path hfilePath = new Path(TEST_UTIL.getDataTestDir(), "testMidKeyInHFile");
119    Compression.Algorithm compressAlgo = Compression.Algorithm.NONE;
120    int entryCount = 50000;
121    writeDataAndReadFromHFile(hfilePath, compressAlgo, entryCount, true, useTags);
122  }
123
124  private void writeDataAndReadFromHFile(Path hfilePath, Algorithm compressAlgo, int entryCount,
125    boolean findMidKey, boolean useTags) throws IOException {
126    HFileContext context = new HFileContextBuilder().withBlockSize(4096).withIncludesTags(useTags)
127      .withDataBlockEncoding(DataBlockEncoding.NONE).withCompression(compressAlgo).build();
128    CacheConfig cacheConfig = new CacheConfig(conf);
129    HFile.Writer writer = new HFile.WriterFactory(conf, cacheConfig).withPath(fs, hfilePath)
130      .withFileContext(context).create();
131
132    List<KeyValue> keyValues = new ArrayList<>(entryCount);
133    for (int i = 0; i < entryCount; ++i) {
134      byte[] keyBytes = RandomKeyValueUtil.randomOrderedKey(RNG, i);
135      // A random-length random value.
136      byte[] valueBytes = RandomKeyValueUtil.randomValue(RNG);
137      KeyValue keyValue = null;
138      if (useTags) {
139        ArrayList<Tag> tags = new ArrayList<>();
140        for (int j = 0; j < 1 + RNG.nextInt(4); j++) {
141          byte[] tagBytes = new byte[16];
142          RNG.nextBytes(tagBytes);
143          tags.add(new ArrayBackedTag((byte) 1, tagBytes));
144        }
145        keyValue =
146          new KeyValue(keyBytes, null, null, HConstants.LATEST_TIMESTAMP, valueBytes, tags);
147      } else {
148        keyValue = new KeyValue(keyBytes, null, null, HConstants.LATEST_TIMESTAMP, valueBytes);
149      }
150      writer.append(keyValue);
151      keyValues.add(keyValue);
152    }
153
154    // Add in an arbitrary order. They will be sorted lexicographically by
155    // the key.
156    writer.appendMetaBlock("CAPITAL_OF_USA", new Text("Washington, D.C."));
157    writer.appendMetaBlock("CAPITAL_OF_RUSSIA", new Text("Moscow"));
158    writer.appendMetaBlock("CAPITAL_OF_FRANCE", new Text("Paris"));
159
160    writer.close();
161
162    FSDataInputStream fsdis = fs.open(hfilePath);
163
164    long fileSize = fs.getFileStatus(hfilePath).getLen();
165    FixedFileTrailer trailer = FixedFileTrailer.readFromStream(fsdis, fileSize);
166
167    assertEquals(3, trailer.getMajorVersion());
168    assertEquals(entryCount, trailer.getEntryCount());
169    HFileContext meta = new HFileContextBuilder().withCompression(compressAlgo)
170      .withIncludesMvcc(false).withIncludesTags(useTags)
171      .withDataBlockEncoding(DataBlockEncoding.NONE).withHBaseCheckSum(true).build();
172    ReaderContext readerContext =
173      new ReaderContextBuilder().withInputStreamWrapper(new FSDataInputStreamWrapper(fsdis))
174        .withFilePath(hfilePath).withFileSystem(fs).withFileSize(fileSize).build();
175    HFileBlock.FSReader blockReader =
176      new HFileBlock.FSReaderImpl(readerContext, meta, ByteBuffAllocator.HEAP, conf);
177    // Comparator class name is stored in the trailer in version 3.
178    CellComparator comparator = trailer.createComparator();
179    HFileBlockIndex.BlockIndexReader dataBlockIndexReader =
180      new HFileBlockIndex.CellBasedKeyBlockIndexReader(comparator, trailer.getNumDataIndexLevels());
181    HFileBlockIndex.BlockIndexReader metaBlockIndexReader =
182      new HFileBlockIndex.ByteArrayKeyBlockIndexReader(1);
183
184    HFileBlock.BlockIterator blockIter = blockReader.blockRange(trailer.getLoadOnOpenDataOffset(),
185      fileSize - trailer.getTrailerSize());
186    // Data index. We also read statistics about the block index written after
187    // the root level.
188    dataBlockIndexReader.readMultiLevelIndexRoot(
189      blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX), trailer.getDataIndexCount());
190
191    FSDataInputStreamWrapper wrapper = new FSDataInputStreamWrapper(fs, hfilePath);
192    readerContext = new ReaderContextBuilder().withFilePath(hfilePath).withFileSize(fileSize)
193      .withFileSystem(wrapper.getHfs()).withInputStreamWrapper(wrapper).build();
194    HFileInfo hfile = new HFileInfo(readerContext, conf);
195    HFile.Reader reader = new HFilePreadReader(readerContext, hfile, cacheConfig, conf);
196    hfile.initMetaAndIndex(reader);
197    if (findMidKey) {
198      Cell midkey = dataBlockIndexReader.midkey(reader);
199      assertNotNull("Midkey should not be null", midkey);
200    }
201
202    // Meta index.
203    metaBlockIndexReader.readRootIndex(
204      blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX).getByteStream(),
205      trailer.getMetaIndexCount());
206    // File info
207    HFileInfo fileInfo = new HFileInfo();
208    fileInfo.read(blockIter.nextBlockWithBlockType(BlockType.FILE_INFO).getByteStream());
209    byte[] keyValueFormatVersion = fileInfo.get(HFileWriterImpl.KEY_VALUE_VERSION);
210    boolean includeMemstoreTS =
211      keyValueFormatVersion != null && Bytes.toInt(keyValueFormatVersion) > 0;
212
213    // Counters for the number of key/value pairs and the number of blocks
214    int entriesRead = 0;
215    int blocksRead = 0;
216    long memstoreTS = 0;
217
218    // Scan blocks the way the reader would scan them
219    fsdis.seek(0);
220    long curBlockPos = 0;
221    while (curBlockPos <= trailer.getLastDataBlockOffset()) {
222      HFileBlock block =
223        blockReader.readBlockData(curBlockPos, -1, false, false, true).unpack(context, blockReader);
224      assertEquals(BlockType.DATA, block.getBlockType());
225      ByteBuff buf = block.getBufferWithoutHeader();
226      int keyLen = -1;
227      while (buf.hasRemaining()) {
228
229        keyLen = buf.getInt();
230
231        int valueLen = buf.getInt();
232
233        byte[] key = new byte[keyLen];
234        buf.get(key);
235
236        byte[] value = new byte[valueLen];
237        buf.get(value);
238        byte[] tagValue = null;
239        if (useTags) {
240          int tagLen = ((buf.get() & 0xff) << 8) ^ (buf.get() & 0xff);
241          tagValue = new byte[tagLen];
242          buf.get(tagValue);
243        }
244
245        if (includeMemstoreTS) {
246          ByteArrayInputStream byte_input = new ByteArrayInputStream(buf.array(),
247            buf.arrayOffset() + buf.position(), buf.remaining());
248          DataInputStream data_input = new DataInputStream(byte_input);
249
250          memstoreTS = WritableUtils.readVLong(data_input);
251          buf.position(buf.position() + WritableUtils.getVIntSize(memstoreTS));
252        }
253
254        // A brute-force check to see that all keys and values are correct.
255        KeyValue kv = keyValues.get(entriesRead);
256        assertTrue(Bytes.compareTo(key, kv.getKey()) == 0);
257        assertTrue(Bytes.compareTo(value, 0, value.length, kv.getValueArray(), kv.getValueOffset(),
258          kv.getValueLength()) == 0);
259        if (useTags) {
260          assertNotNull(tagValue);
261          KeyValue tkv = kv;
262          assertEquals(tagValue.length, tkv.getTagsLength());
263          assertTrue(Bytes.compareTo(tagValue, 0, tagValue.length, tkv.getTagsArray(),
264            tkv.getTagsOffset(), tkv.getTagsLength()) == 0);
265        }
266        ++entriesRead;
267      }
268      ++blocksRead;
269      curBlockPos += block.getOnDiskSizeWithHeader();
270    }
271    LOG.info("Finished reading: entries=" + entriesRead + ", blocksRead=" + blocksRead);
272    assertEquals(entryCount, entriesRead);
273
274    // Meta blocks. We can scan until the load-on-open data offset (which is
275    // the root block index offset in version 2) because we are not testing
276    // intermediate-level index blocks here.
277
278    int metaCounter = 0;
279    while (fsdis.getPos() < trailer.getLoadOnOpenDataOffset()) {
280      LOG.info("Current offset: " + fsdis.getPos() + ", scanning until "
281        + trailer.getLoadOnOpenDataOffset());
282      HFileBlock block =
283        blockReader.readBlockData(curBlockPos, -1, false, false, true).unpack(context, blockReader);
284      assertEquals(BlockType.META, block.getBlockType());
285      Text t = new Text();
286      ByteBuff buf = block.getBufferWithoutHeader();
287      if (Writables.getWritable(buf.array(), buf.arrayOffset(), buf.limit(), t) == null) {
288        throw new IOException(
289          "Failed to deserialize block " + this + " into a " + t.getClass().getSimpleName());
290      }
291      Text expectedText = (metaCounter == 0 ? new Text("Paris")
292        : metaCounter == 1 ? new Text("Moscow")
293        : new Text("Washington, D.C."));
294      assertEquals(expectedText, t);
295      LOG.info("Read meta block data: " + t);
296      ++metaCounter;
297      curBlockPos += block.getOnDiskSizeWithHeader();
298    }
299
300    fsdis.close();
301    reader.close();
302  }
303}