View Javadoc

1   /*
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  package org.apache.hadoop.hbase.io.hfile;
21  
22  import java.io.DataOutput;
23  import java.io.DataOutputStream;
24  import java.io.IOException;
25  import java.util.ArrayList;
26  import java.util.List;
27  
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  import org.apache.hadoop.hbase.classification.InterfaceAudience;
31  import org.apache.hadoop.conf.Configuration;
32  import org.apache.hadoop.fs.FSDataOutputStream;
33  import org.apache.hadoop.fs.FileSystem;
34  import org.apache.hadoop.fs.Path;
35  import org.apache.hadoop.hbase.Cell;
36  import org.apache.hadoop.hbase.KeyValue.KVComparator;
37  import org.apache.hadoop.hbase.KeyValueUtil;
38  import org.apache.hadoop.hbase.io.hfile.HFile.Writer;
39  import org.apache.hadoop.hbase.io.hfile.HFileBlock.BlockWritable;
40  import org.apache.hadoop.hbase.util.BloomFilterWriter;
41  import org.apache.hadoop.hbase.util.Bytes;
42  import org.apache.hadoop.io.Writable;
43  
44  /**
45   * Writes HFile format version 2.
46   */
47  @InterfaceAudience.Private
48  public class HFileWriterV2 extends AbstractHFileWriter {
49    static final Log LOG = LogFactory.getLog(HFileWriterV2.class);
50  
51    /** Max memstore (mvcc) timestamp in FileInfo */
52    public static final byte [] MAX_MEMSTORE_TS_KEY =
53        Bytes.toBytes("MAX_MEMSTORE_TS_KEY");
54  
55    /** KeyValue version in FileInfo */
56    public static final byte [] KEY_VALUE_VERSION =
57        Bytes.toBytes("KEY_VALUE_VERSION");
58  
59    /** Version for KeyValue which includes memstore timestamp */
60    public static final int KEY_VALUE_VER_WITH_MEMSTORE = 1;
61  
62    /** Inline block writers for multi-level block index and compound Blooms. */
63    private List<InlineBlockWriter> inlineBlockWriters =
64        new ArrayList<InlineBlockWriter>();
65  
66    /** Unified version 2 block writer */
67    protected HFileBlock.Writer fsBlockWriter;
68  
69    private HFileBlockIndex.BlockIndexWriter dataBlockIndexWriter;
70    private HFileBlockIndex.BlockIndexWriter metaBlockIndexWriter;
71  
72    /** The offset of the first data block or -1 if the file is empty. */
73    private long firstDataBlockOffset = -1;
74  
75    /** The offset of the last data block or 0 if the file is empty. */
76    protected long lastDataBlockOffset;
77  
78    /** The last(stop) Key of the previous data block. */
79    private byte[] lastKeyOfPreviousBlock = null;
80  
81    /** Additional data items to be written to the "load-on-open" section. */
82    private List<BlockWritable> additionalLoadOnOpenData =
83      new ArrayList<BlockWritable>();
84  
85    protected long maxMemstoreTS = 0;
86  
87    static class WriterFactoryV2 extends HFile.WriterFactory {
88      WriterFactoryV2(Configuration conf, CacheConfig cacheConf) {
89        super(conf, cacheConf);
90      }
91  
92      @Override
93      public Writer createWriter(FileSystem fs, Path path, 
94          FSDataOutputStream ostream,
95          KVComparator comparator, HFileContext context) throws IOException {
96        context.setIncludesTags(false);// HFile V2 does not deal with tags at all!
97        return new HFileWriterV2(conf, cacheConf, fs, path, ostream, 
98            comparator, context);
99        }
100     }
101 
102   /** Constructor that takes a path, creates and closes the output stream. */
103   public HFileWriterV2(Configuration conf, CacheConfig cacheConf,
104       FileSystem fs, Path path, FSDataOutputStream ostream, 
105       final KVComparator comparator, final HFileContext context) throws IOException {
106     super(cacheConf,
107         ostream == null ? createOutputStream(conf, fs, path, null) : ostream,
108         path, comparator, context);
109     finishInit(conf);
110   }
111 
112   /** Additional initialization steps */
113   protected void finishInit(final Configuration conf) {
114     if (fsBlockWriter != null)
115       throw new IllegalStateException("finishInit called twice");
116 
117     fsBlockWriter = new HFileBlock.Writer(blockEncoder, hFileContext);
118 
119     // Data block index writer
120     boolean cacheIndexesOnWrite = cacheConf.shouldCacheIndexesOnWrite();
121     dataBlockIndexWriter = new HFileBlockIndex.BlockIndexWriter(fsBlockWriter,
122         cacheIndexesOnWrite ? cacheConf : null,
123         cacheIndexesOnWrite ? name : null);
124     dataBlockIndexWriter.setMaxChunkSize(
125         HFileBlockIndex.getMaxChunkSize(conf));
126     inlineBlockWriters.add(dataBlockIndexWriter);
127 
128     // Meta data block index writer
129     metaBlockIndexWriter = new HFileBlockIndex.BlockIndexWriter();
130     if (LOG.isTraceEnabled()) LOG.trace("Initialized with " + cacheConf);
131   }
132 
133   /**
134    * At a block boundary, write all the inline blocks and opens new block.
135    *
136    * @throws IOException
137    */
138   protected void checkBlockBoundary() throws IOException {
139     if (fsBlockWriter.blockSizeWritten() < hFileContext.getBlocksize())
140       return;
141 
142     finishBlock();
143     writeInlineBlocks(false);
144     newBlock();
145   }
146 
147   /** Clean up the current data block */
148   private void finishBlock() throws IOException {
149     if (!fsBlockWriter.isWriting() || fsBlockWriter.blockSizeWritten() == 0)
150       return;
151 
152     // Update the first data block offset for scanning.
153     if (firstDataBlockOffset == -1) {
154       firstDataBlockOffset = outputStream.getPos();
155     }
156     // Update the last data block offset
157     lastDataBlockOffset = outputStream.getPos();
158     fsBlockWriter.writeHeaderAndData(outputStream);
159     int onDiskSize = fsBlockWriter.getOnDiskSizeWithHeader();
160 
161     byte[] indexKey = comparator.calcIndexKey(lastKeyOfPreviousBlock, firstKeyInBlock);
162     dataBlockIndexWriter.addEntry(indexKey, lastDataBlockOffset, onDiskSize);
163     totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader();
164     if (cacheConf.shouldCacheDataOnWrite()) {
165       doCacheOnWrite(lastDataBlockOffset);
166     }
167   }
168 
169   /** Gives inline block writers an opportunity to contribute blocks. */
170   private void writeInlineBlocks(boolean closing) throws IOException {
171     for (InlineBlockWriter ibw : inlineBlockWriters) {
172       while (ibw.shouldWriteBlock(closing)) {
173         long offset = outputStream.getPos();
174         boolean cacheThisBlock = ibw.getCacheOnWrite();
175         ibw.writeInlineBlock(fsBlockWriter.startWriting(
176             ibw.getInlineBlockType()));
177         fsBlockWriter.writeHeaderAndData(outputStream);
178         ibw.blockWritten(offset, fsBlockWriter.getOnDiskSizeWithHeader(),
179             fsBlockWriter.getUncompressedSizeWithoutHeader());
180         totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader();
181 
182         if (cacheThisBlock) {
183           doCacheOnWrite(offset);
184         }
185       }
186     }
187   }
188 
189   /**
190    * Caches the last written HFile block.
191    * @param offset the offset of the block we want to cache. Used to determine
192    *          the cache key.
193    */
194   private void doCacheOnWrite(long offset) {
195     HFileBlock cacheFormatBlock = fsBlockWriter.getBlockForCaching(cacheConf);
196     cacheConf.getBlockCache().cacheBlock(
197         new BlockCacheKey(name, offset), cacheFormatBlock);
198   }
199 
200   /**
201    * Ready a new block for writing.
202    *
203    * @throws IOException
204    */
205   protected void newBlock() throws IOException {
206     // This is where the next block begins.
207     fsBlockWriter.startWriting(BlockType.DATA);
208     firstKeyInBlock = null;
209     if (lastKeyLength > 0) {
210       lastKeyOfPreviousBlock = new byte[lastKeyLength];
211       KeyValueUtil.appendKeyTo(lastCell, lastKeyOfPreviousBlock, 0);
212     }
213   }
214 
215   /**
216    * Add a meta block to the end of the file. Call before close(). Metadata
217    * blocks are expensive. Fill one with a bunch of serialized data rather than
218    * do a metadata block per metadata instance. If metadata is small, consider
219    * adding to file info using {@link #appendFileInfo(byte[], byte[])}
220    *
221    * @param metaBlockName
222    *          name of the block
223    * @param content
224    *          will call readFields to get data later (DO NOT REUSE)
225    */
226   @Override
227   public void appendMetaBlock(String metaBlockName, Writable content) {
228     byte[] key = Bytes.toBytes(metaBlockName);
229     int i;
230     for (i = 0; i < metaNames.size(); ++i) {
231       // stop when the current key is greater than our own
232       byte[] cur = metaNames.get(i);
233       if (Bytes.BYTES_RAWCOMPARATOR.compare(cur, 0, cur.length, key, 0,
234           key.length) > 0) {
235         break;
236       }
237     }
238     metaNames.add(i, key);
239     metaData.add(i, content);
240   }
241 
242   /**
243    * Add key/value to file. Keys must be added in an order that agrees with the
244    * Comparator passed on construction.
245    *
246    * @param cell Cell to add. Cannot be empty nor null.
247    * @throws IOException
248    */
249   @Override
250   public void append(final Cell cell) throws IOException {
251     int klength = KeyValueUtil.keyLength(cell);
252     byte[] value = cell.getValueArray();
253     int voffset = cell.getValueOffset();
254     int vlength = cell.getValueLength();
255     // checkKey uses comparator to check we are writing in order.
256     boolean dupKey = checkKey(cell);
257     checkValue(value, voffset, vlength);
258     if (!dupKey) {
259       checkBlockBoundary();
260     }
261 
262     if (!fsBlockWriter.isWriting())
263       newBlock();
264 
265     fsBlockWriter.write(cell);
266 
267     totalKeyLength += klength;
268     totalValueLength += vlength;
269 
270     // Are we the first key in this block?
271     if (firstKeyInBlock == null) {
272       // Copy the key for use as first key in block. It is put into file index.
273       firstKeyInBlock = new byte[klength];
274       KeyValueUtil.appendKeyTo(cell, firstKeyInBlock, 0);
275     }
276 
277     lastCell = cell;
278     lastKeyLength = klength;
279     entryCount++;
280     this.maxMemstoreTS = Math.max(this.maxMemstoreTS, cell.getSequenceId());
281   }
282 
283   @Override
284   public void close() throws IOException {
285     if (outputStream == null) {
286       return;
287     }
288     // Save data block encoder metadata in the file info.
289     blockEncoder.saveMetadata(this);
290     // Write out the end of the data blocks, then write meta data blocks.
291     // followed by fileinfo, data block index and meta block index.
292 
293     finishBlock();
294     writeInlineBlocks(true);
295 
296     FixedFileTrailer trailer = new FixedFileTrailer(getMajorVersion(), getMinorVersion());
297 
298     // Write out the metadata blocks if any.
299     if (!metaNames.isEmpty()) {
300       for (int i = 0; i < metaNames.size(); ++i) {
301         // store the beginning offset
302         long offset = outputStream.getPos();
303         // write the metadata content
304         DataOutputStream dos = fsBlockWriter.startWriting(BlockType.META);
305         metaData.get(i).write(dos);
306 
307         fsBlockWriter.writeHeaderAndData(outputStream);
308         totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader();
309 
310         // Add the new meta block to the meta index.
311         metaBlockIndexWriter.addEntry(metaNames.get(i), offset,
312             fsBlockWriter.getOnDiskSizeWithHeader());
313       }
314     }
315 
316     // Load-on-open section.
317 
318     // Data block index.
319     //
320     // In version 2, this section of the file starts with the root level data
321     // block index. We call a function that writes intermediate-level blocks
322     // first, then root level, and returns the offset of the root level block
323     // index.
324 
325     long rootIndexOffset = dataBlockIndexWriter.writeIndexBlocks(outputStream);
326     trailer.setLoadOnOpenOffset(rootIndexOffset);
327 
328     // Meta block index.
329     metaBlockIndexWriter.writeSingleLevelIndex(fsBlockWriter.startWriting(
330         BlockType.ROOT_INDEX), "meta");
331     fsBlockWriter.writeHeaderAndData(outputStream);
332     totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader();
333 
334     if (this.hFileContext.isIncludesMvcc()) {
335       appendFileInfo(MAX_MEMSTORE_TS_KEY, Bytes.toBytes(maxMemstoreTS));
336       appendFileInfo(KEY_VALUE_VERSION, Bytes.toBytes(KEY_VALUE_VER_WITH_MEMSTORE));
337     }
338 
339     // File info
340     writeFileInfo(trailer, fsBlockWriter.startWriting(BlockType.FILE_INFO));
341     fsBlockWriter.writeHeaderAndData(outputStream);
342     totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader();
343 
344     // Load-on-open data supplied by higher levels, e.g. Bloom filters.
345     for (BlockWritable w : additionalLoadOnOpenData){
346       fsBlockWriter.writeBlock(w, outputStream);
347       totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader();
348     }
349 
350     // Now finish off the trailer.
351     trailer.setNumDataIndexLevels(dataBlockIndexWriter.getNumLevels());
352     trailer.setUncompressedDataIndexSize(
353         dataBlockIndexWriter.getTotalUncompressedSize());
354     trailer.setFirstDataBlockOffset(firstDataBlockOffset);
355     trailer.setLastDataBlockOffset(lastDataBlockOffset);
356     trailer.setComparatorClass(comparator.getClass());
357     trailer.setDataIndexCount(dataBlockIndexWriter.getNumRootEntries());
358 
359 
360     finishClose(trailer);
361 
362     fsBlockWriter.release();
363   }
364 
365   @Override
366   public void addInlineBlockWriter(InlineBlockWriter ibw) {
367     inlineBlockWriters.add(ibw);
368   }
369 
370   @Override
371   public void addGeneralBloomFilter(final BloomFilterWriter bfw) {
372     this.addBloomFilter(bfw, BlockType.GENERAL_BLOOM_META);
373   }
374 
375   @Override
376   public void addDeleteFamilyBloomFilter(final BloomFilterWriter bfw) {
377     this.addBloomFilter(bfw, BlockType.DELETE_FAMILY_BLOOM_META);
378   }
379 
380   private void addBloomFilter(final BloomFilterWriter bfw,
381       final BlockType blockType) {
382     if (bfw.getKeyCount() <= 0)
383       return;
384 
385     if (blockType != BlockType.GENERAL_BLOOM_META &&
386         blockType != BlockType.DELETE_FAMILY_BLOOM_META) {
387       throw new RuntimeException("Block Type: " + blockType.toString() +
388           "is not supported");
389     }
390     additionalLoadOnOpenData.add(new BlockWritable() {
391       @Override
392       public BlockType getBlockType() {
393         return blockType;
394       }
395 
396       @Override
397       public void writeToBlock(DataOutput out) throws IOException {
398         bfw.getMetaWriter().write(out);
399         Writable dataWriter = bfw.getDataWriter();
400         if (dataWriter != null)
401           dataWriter.write(out);
402       }
403     });
404   }
405 
406   protected int getMajorVersion() {
407     return 2;
408   }
409 
410   protected int getMinorVersion() {
411     return HFileReaderV2.MAX_MINOR_VERSION;
412   }
413 
414   @Override
415   public HFileContext getFileContext() {
416     return hFileContext;
417   }
418 }