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.CellBasedKeyBlockIndexReaderV2(comparator,
181        trailer.getNumDataIndexLevels());
182    HFileBlockIndex.BlockIndexReader metaBlockIndexReader =
183      new HFileBlockIndex.ByteArrayKeyBlockIndexReader(1);
184
185    HFileBlock.BlockIterator blockIter = blockReader.blockRange(trailer.getLoadOnOpenDataOffset(),
186      fileSize - trailer.getTrailerSize());
187    // Data index. We also read statistics about the block index written after
188    // the root level.
189    dataBlockIndexReader.readMultiLevelIndexRoot(
190      blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX), trailer.getDataIndexCount());
191
192    FSDataInputStreamWrapper wrapper = new FSDataInputStreamWrapper(fs, hfilePath);
193    readerContext = new ReaderContextBuilder().withFilePath(hfilePath).withFileSize(fileSize)
194      .withFileSystem(wrapper.getHfs()).withInputStreamWrapper(wrapper).build();
195    HFileInfo hfile = new HFileInfo(readerContext, conf);
196    HFile.Reader reader = new HFilePreadReader(readerContext, hfile, cacheConfig, conf);
197    hfile.initMetaAndIndex(reader);
198    if (findMidKey) {
199      Cell midkey = dataBlockIndexReader.midkey(reader);
200      assertNotNull("Midkey should not be null", midkey);
201    }
202
203    // Meta index.
204    metaBlockIndexReader.readRootIndex(
205      blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX).getByteStream(),
206      trailer.getMetaIndexCount());
207    // File info
208    HFileInfo fileInfo = new HFileInfo();
209    fileInfo.read(blockIter.nextBlockWithBlockType(BlockType.FILE_INFO).getByteStream());
210    byte[] keyValueFormatVersion = fileInfo.get(HFileWriterImpl.KEY_VALUE_VERSION);
211    boolean includeMemstoreTS =
212      keyValueFormatVersion != null && Bytes.toInt(keyValueFormatVersion) > 0;
213
214    // Counters for the number of key/value pairs and the number of blocks
215    int entriesRead = 0;
216    int blocksRead = 0;
217    long memstoreTS = 0;
218
219    // Scan blocks the way the reader would scan them
220    fsdis.seek(0);
221    long curBlockPos = 0;
222    while (curBlockPos <= trailer.getLastDataBlockOffset()) {
223      HFileBlock block =
224        blockReader.readBlockData(curBlockPos, -1, false, false, true).unpack(context, blockReader);
225      assertEquals(BlockType.DATA, block.getBlockType());
226      ByteBuff buf = block.getBufferWithoutHeader();
227      int keyLen = -1;
228      while (buf.hasRemaining()) {
229
230        keyLen = buf.getInt();
231
232        int valueLen = buf.getInt();
233
234        byte[] key = new byte[keyLen];
235        buf.get(key);
236
237        byte[] value = new byte[valueLen];
238        buf.get(value);
239        byte[] tagValue = null;
240        if (useTags) {
241          int tagLen = ((buf.get() & 0xff) << 8) ^ (buf.get() & 0xff);
242          tagValue = new byte[tagLen];
243          buf.get(tagValue);
244        }
245
246        if (includeMemstoreTS) {
247          ByteArrayInputStream byte_input = new ByteArrayInputStream(buf.array(),
248            buf.arrayOffset() + buf.position(), buf.remaining());
249          DataInputStream data_input = new DataInputStream(byte_input);
250
251          memstoreTS = WritableUtils.readVLong(data_input);
252          buf.position(buf.position() + WritableUtils.getVIntSize(memstoreTS));
253        }
254
255        // A brute-force check to see that all keys and values are correct.
256        KeyValue kv = keyValues.get(entriesRead);
257        assertTrue(Bytes.compareTo(key, kv.getKey()) == 0);
258        assertTrue(Bytes.compareTo(value, 0, value.length, kv.getValueArray(), kv.getValueOffset(),
259          kv.getValueLength()) == 0);
260        if (useTags) {
261          assertNotNull(tagValue);
262          KeyValue tkv = kv;
263          assertEquals(tagValue.length, tkv.getTagsLength());
264          assertTrue(Bytes.compareTo(tagValue, 0, tagValue.length, tkv.getTagsArray(),
265            tkv.getTagsOffset(), tkv.getTagsLength()) == 0);
266        }
267        ++entriesRead;
268      }
269      ++blocksRead;
270      curBlockPos += block.getOnDiskSizeWithHeader();
271    }
272    LOG.info("Finished reading: entries=" + entriesRead + ", blocksRead=" + blocksRead);
273    assertEquals(entryCount, entriesRead);
274
275    // Meta blocks. We can scan until the load-on-open data offset (which is
276    // the root block index offset in version 2) because we are not testing
277    // intermediate-level index blocks here.
278
279    int metaCounter = 0;
280    while (fsdis.getPos() < trailer.getLoadOnOpenDataOffset()) {
281      LOG.info("Current offset: " + fsdis.getPos() + ", scanning until "
282        + trailer.getLoadOnOpenDataOffset());
283      HFileBlock block =
284        blockReader.readBlockData(curBlockPos, -1, false, false, true).unpack(context, blockReader);
285      assertEquals(BlockType.META, block.getBlockType());
286      Text t = new Text();
287      ByteBuff buf = block.getBufferWithoutHeader();
288      if (Writables.getWritable(buf.array(), buf.arrayOffset(), buf.limit(), t) == null) {
289        throw new IOException(
290          "Failed to deserialize block " + this + " into a " + t.getClass().getSimpleName());
291      }
292      Text expectedText = (metaCounter == 0 ? new Text("Paris")
293        : metaCounter == 1 ? new Text("Moscow")
294        : new Text("Washington, D.C."));
295      assertEquals(expectedText, t);
296      LOG.info("Read meta block data: " + t);
297      ++metaCounter;
298      curBlockPos += block.getOnDiskSizeWithHeader();
299    }
300
301    fsdis.close();
302    reader.close();
303  }
304}