View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.io.hfile;
19  
20  import java.io.IOException;
21  import java.security.Key;
22  import java.security.KeyException;
23  
24  import org.apache.commons.logging.Log;
25  import org.apache.commons.logging.LogFactory;
26  import org.apache.hadoop.hbase.classification.InterfaceAudience;
27  import org.apache.hadoop.conf.Configuration;
28  import org.apache.hadoop.fs.Path;
29  import org.apache.hadoop.hbase.Cell;
30  import org.apache.hadoop.hbase.CellUtil;
31  import org.apache.hadoop.hbase.HConstants;
32  import org.apache.hadoop.hbase.KeyValue;
33  import org.apache.hadoop.hbase.fs.HFileSystem;
34  import org.apache.hadoop.hbase.io.FSDataInputStreamWrapper;
35  import org.apache.hadoop.hbase.io.crypto.Cipher;
36  import org.apache.hadoop.hbase.io.crypto.Encryption;
37  import org.apache.hadoop.hbase.io.hfile.HFile.FileInfo;
38  import org.apache.hadoop.hbase.security.EncryptionUtil;
39  import org.apache.hadoop.hbase.security.User;
40  import org.apache.hadoop.hbase.util.ByteBufferUtils;
41  import org.apache.hadoop.hbase.util.Bytes;
42  import org.apache.hadoop.io.WritableUtils;
43  
44  /**
45   * {@link HFile} reader for version 3.
46   */
47  @InterfaceAudience.Private
48  public class HFileReaderV3 extends HFileReaderV2 {
49  
50    private static final Log LOG = LogFactory.getLog(HFileReaderV3.class);
51  
52    public static final int MAX_MINOR_VERSION = 0;
53  
54    /**
55     * Opens a HFile. You must load the index before you can use it by calling
56     * {@link #loadFileInfo()}.
57     * @param path
58     *          Path to HFile.
59     * @param trailer
60     *          File trailer.
61     * @param fsdis
62     *          input stream.
63     * @param size
64     *          Length of the stream.
65     * @param cacheConf
66     *          Cache configuration.
67     * @param hfs
68     *          The file system.
69     * @param conf
70     *          Configuration
71     */
72    public HFileReaderV3(final Path path, FixedFileTrailer trailer,
73        final FSDataInputStreamWrapper fsdis,
74        final long size, final CacheConfig cacheConf, final HFileSystem hfs,
75        final Configuration conf) throws IOException {
76      super(path, trailer, fsdis, size, cacheConf, hfs, conf);
77      byte[] tmp = fileInfo.get(FileInfo.MAX_TAGS_LEN);
78      // max tag length is not present in the HFile means tags were not at all written to file.
79      if (tmp != null) {
80        hfileContext.setIncludesTags(true);
81        tmp = fileInfo.get(FileInfo.TAGS_COMPRESSED);
82        if (tmp != null && Bytes.toBoolean(tmp)) {
83          hfileContext.setCompressTags(true);
84        }
85      }
86    }
87  
88    @Override
89    protected HFileContext createHFileContext(FSDataInputStreamWrapper fsdis, long fileSize,
90        HFileSystem hfs, Path path, FixedFileTrailer trailer) throws IOException {
91      trailer.expectMajorVersion(3);
92      HFileContextBuilder builder = new HFileContextBuilder()
93        .withIncludesMvcc(shouldIncludeMemstoreTS())
94        .withHBaseCheckSum(true)
95        .withCompression(this.compressAlgo);
96  
97      // Check for any key material available
98      byte[] keyBytes = trailer.getEncryptionKey();
99      if (keyBytes != null) {
100       Encryption.Context cryptoContext = Encryption.newContext(conf);
101       Key key;
102       String masterKeyName = conf.get(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY,
103         User.getCurrent().getShortName());
104       try {
105         // First try the master key
106         key = EncryptionUtil.unwrapKey(conf, masterKeyName, keyBytes);
107       } catch (KeyException e) {
108         // If the current master key fails to unwrap, try the alternate, if
109         // one is configured
110         if (LOG.isDebugEnabled()) {
111           LOG.debug("Unable to unwrap key with current master key '" + masterKeyName + "'");
112         }
113         String alternateKeyName =
114           conf.get(HConstants.CRYPTO_MASTERKEY_ALTERNATE_NAME_CONF_KEY);
115         if (alternateKeyName != null) {
116           try {
117             key = EncryptionUtil.unwrapKey(conf, alternateKeyName, keyBytes);
118           } catch (KeyException ex) {
119             throw new IOException(ex);
120           }
121         } else {
122           throw new IOException(e);
123         }
124       }
125       // Use the algorithm the key wants
126       Cipher cipher = Encryption.getCipher(conf, key.getAlgorithm());
127       if (cipher == null) {
128         throw new IOException("Cipher '" + key.getAlgorithm() + "' is not available");
129       }
130       cryptoContext.setCipher(cipher);
131       cryptoContext.setKey(key);
132       builder.withEncryptionContext(cryptoContext);
133     }
134 
135     HFileContext context = builder.build();
136 
137     if (LOG.isTraceEnabled()) {
138       LOG.trace("Reader" + (path != null ? " for " + path : "" ) +
139         " initialized with cacheConf: " + cacheConf +
140         " comparator: " + comparator.getClass().getSimpleName() +
141         " fileContext: " + context);
142     }
143 
144     return context;
145   }
146 
147   /**
148    * Create a Scanner on this file. No seeks or reads are done on creation. Call
149    * {@link HFileScanner#seekTo(byte[])} to position an start the read. There is
150    * nothing to clean up in a Scanner. Letting go of your references to the
151    * scanner is sufficient.
152    * @param cacheBlocks
153    *          True if we should cache blocks read in by this scanner.
154    * @param pread
155    *          Use positional read rather than seek+read if true (pread is better
156    *          for random reads, seek+read is better scanning).
157    * @param isCompaction
158    *          is scanner being used for a compaction?
159    * @return Scanner on this file.
160    */
161   @Override
162   public HFileScanner getScanner(boolean cacheBlocks, final boolean pread,
163       final boolean isCompaction) {
164     if (dataBlockEncoder.useEncodedScanner()) {
165       return new EncodedScannerV3(this, cacheBlocks, pread, isCompaction, this.hfileContext);
166     }
167     return new ScannerV3(this, cacheBlocks, pread, isCompaction);
168   }
169 
170   /**
171    * Implementation of {@link HFileScanner} interface.
172    */
173   protected static class ScannerV3 extends ScannerV2 {
174 
175     private HFileReaderV3 reader;
176     private int currTagsLen;
177 
178     public ScannerV3(HFileReaderV3 r, boolean cacheBlocks, final boolean pread,
179         final boolean isCompaction) {
180       super(r, cacheBlocks, pread, isCompaction);
181       this.reader = r;
182     }
183 
184     @Override
185     protected int getCellBufSize() {
186       int kvBufSize = super.getCellBufSize();
187       if (reader.hfileContext.isIncludesTags()) {
188         kvBufSize += Bytes.SIZEOF_SHORT + currTagsLen;
189       }
190       return kvBufSize;
191     }
192 
193     protected void setNonSeekedState() {
194       super.setNonSeekedState();
195       currTagsLen = 0;
196     }
197 
198     @Override
199     protected int getNextCellStartPosition() {
200       int nextKvPos = super.getNextCellStartPosition();
201       if (reader.hfileContext.isIncludesTags()) {
202         nextKvPos += Bytes.SIZEOF_SHORT + currTagsLen;
203       }
204       return nextKvPos;
205     }
206 
207     private final void checkTagsLen() {
208       if (checkLen(this.currTagsLen)) {
209         throw new IllegalStateException("Invalid currTagsLen " + this.currTagsLen +
210           ". Block offset: " + block.getOffset() + ", block length: " + this.blockBuffer.limit() +
211           ", position: " + this.blockBuffer.position() + " (without header).");
212       }
213     }
214 
215     protected final void readKeyValueLen() {
216       // TODO: METHOD (mostly) DUPLICATED IN V2!!!! FIXED in master branch by collapsing v3 and v2.
217       // This is a hot method. We go out of our way to make this method short so it can be
218       // inlined and is not too big to compile. We also manage position in ByteBuffer ourselves
219       // because it is faster than going via range-checked ByteBuffer methods or going through a
220       // byte buffer array a byte at a time.
221       int p = blockBuffer.position() + blockBuffer.arrayOffset();
222       // Get a long at a time rather than read two individual ints. In micro-benchmarking, even
223       // with the extra bit-fiddling, this is order-of-magnitude faster than getting two ints.
224       long ll = Bytes.toLong(blockBuffer.array(), p);
225       // Read top half as an int of key length and bottom int as value length
226       this.currKeyLen = (int)(ll >> Integer.SIZE);
227       this.currValueLen = (int)(Bytes.MASK_FOR_LOWER_INT_IN_LONG ^ ll);
228       checkKeyValueLen();
229       // Move position past the key and value lengths and then beyond the key and value
230       p += (Bytes.SIZEOF_LONG + currKeyLen + currValueLen);
231       if (reader.hfileContext.isIncludesTags()) {
232         // Tags length is a short.
233         this.currTagsLen = Bytes.toShort(blockBuffer.array(), p);
234         checkTagsLen();
235         p += (Bytes.SIZEOF_SHORT + currTagsLen);
236       }
237       readMvccVersion(p);
238     }
239 
240     /**
241      * Within a loaded block, seek looking for the last key that is smaller than
242      * (or equal to?) the key we are interested in.
243      * A note on the seekBefore: if you have seekBefore = true, AND the first
244      * key in the block = key, then you'll get thrown exceptions. The caller has
245      * to check for that case and load the previous block as appropriate.
246      * @param key
247      *          the key to find
248      * @param seekBefore
249      *          find the key before the given key in case of exact match.
250      * @return 0 in case of an exact key match, 1 in case of an inexact match,
251      *         -2 in case of an inexact match and furthermore, the input key
252      *         less than the first key of current block(e.g. using a faked index
253      *         key)
254      */
255     @Override
256     protected int blockSeek(Cell key, boolean seekBefore) {
257       int klen, vlen, tlen = 0;
258       long memstoreTS = 0;
259       int memstoreTSLen = 0;
260       int lastKeyValueSize = -1;
261       KeyValue.KeyOnlyKeyValue keyOnlyKv = new KeyValue.KeyOnlyKeyValue();
262       do {
263         blockBuffer.mark();
264         klen = blockBuffer.getInt();
265         vlen = blockBuffer.getInt();
266         if (klen < 0 || vlen < 0 || klen > blockBuffer.limit()
267             || vlen > blockBuffer.limit()) {
268           throw new IllegalStateException("Invalid klen " + klen + " or vlen "
269               + vlen + ". Block offset: "
270               + block.getOffset() + ", block length: " + blockBuffer.limit() + ", position: "
271               + blockBuffer.position() + " (without header).");
272         }
273         ByteBufferUtils.skip(blockBuffer, klen + vlen);
274         if (reader.hfileContext.isIncludesTags()) {
275           // Read short as unsigned, high byte first
276           tlen = ((blockBuffer.get() & 0xff) << 8) ^ (blockBuffer.get() & 0xff);
277           if (tlen < 0 || tlen > blockBuffer.limit()) {
278             throw new IllegalStateException("Invalid tlen " + tlen + ". Block offset: "
279                 + block.getOffset() + ", block length: " + blockBuffer.limit() + ", position: "
280                 + blockBuffer.position() + " (without header).");
281           }
282           ByteBufferUtils.skip(blockBuffer, tlen);
283         }
284         if (this.reader.shouldIncludeMemstoreTS()) {
285           if (this.reader.decodeMemstoreTS) {
286             memstoreTS = Bytes.readAsVLong(blockBuffer.array(), blockBuffer.arrayOffset()
287                 + blockBuffer.position());
288             memstoreTSLen = WritableUtils.getVIntSize(memstoreTS);
289           } else {
290             memstoreTS = 0;
291             memstoreTSLen = 1;
292           }
293         }
294         blockBuffer.reset();
295         int keyOffset =
296           blockBuffer.arrayOffset() + blockBuffer.position() + (Bytes.SIZEOF_INT * 2);
297         keyOnlyKv.setKey(blockBuffer.array(), keyOffset, klen);
298         int comp = reader.getComparator().compareOnlyKeyPortion(key, keyOnlyKv);
299 
300         if (comp == 0) {
301           if (seekBefore) {
302             if (lastKeyValueSize < 0) {
303               throw new IllegalStateException("blockSeek with seekBefore "
304                   + "at the first key of the block: key="
305                   + CellUtil.getCellKeyAsString(key)
306                   + ", blockOffset=" + block.getOffset() + ", onDiskSize="
307                   + block.getOnDiskSizeWithHeader());
308             }
309             blockBuffer.position(blockBuffer.position() - lastKeyValueSize);
310             readKeyValueLen();
311             return 1; // non exact match.
312           }
313           currKeyLen = klen;
314           currValueLen = vlen;
315           currTagsLen = tlen;
316           if (this.reader.shouldIncludeMemstoreTS()) {
317             currMemstoreTS = memstoreTS;
318             currMemstoreTSLen = memstoreTSLen;
319           }
320           return 0; // indicate exact match
321         } else if (comp < 0) {
322           if (lastKeyValueSize > 0)
323             blockBuffer.position(blockBuffer.position() - lastKeyValueSize);
324           readKeyValueLen();
325           if (lastKeyValueSize == -1 && blockBuffer.position() == 0) {
326             return HConstants.INDEX_KEY_MAGIC;
327           }
328           return 1;
329         }
330 
331         // The size of this key/value tuple, including key/value length fields.
332         lastKeyValueSize = klen + vlen + memstoreTSLen + KEY_VALUE_LEN_SIZE;
333         // include tag length also if tags included with KV
334         if (reader.hfileContext.isIncludesTags()) {
335           lastKeyValueSize += tlen + Bytes.SIZEOF_SHORT;
336         }
337         blockBuffer.position(blockBuffer.position() + lastKeyValueSize);
338       } while (blockBuffer.remaining() > 0);
339 
340       // Seek to the last key we successfully read. This will happen if this is
341       // the last key/value pair in the file, in which case the following call
342       // to next() has to return false.
343       blockBuffer.position(blockBuffer.position() - lastKeyValueSize);
344       readKeyValueLen();
345       return 1; // didn't exactly find it.
346     }
347   }
348 
349   /**
350    * ScannerV3 that operates on encoded data blocks.
351    */
352   protected static class EncodedScannerV3 extends EncodedScannerV2 {
353     public EncodedScannerV3(HFileReaderV3 reader, boolean cacheBlocks, boolean pread,
354         boolean isCompaction, HFileContext context) {
355       super(reader, cacheBlocks, pread, isCompaction, context);
356     }
357   }
358 
359   @Override
360   public int getMajorVersion() {
361     return 3;
362   }
363 }