View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with this
4    * work for additional information regarding copyright ownership. The ASF
5    * licenses this file to you under the Apache License, Version 2.0 (the
6    * "License"); you may not use this file except in compliance with the License.
7    * You may obtain a copy of the License at
8    *
9    * http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14   * License for the specific language governing permissions and limitations
15   * under the License.
16   */
17  package org.apache.hadoop.hbase.io.encoding;
18  
19  import java.io.DataInputStream;
20  import java.io.DataOutputStream;
21  import java.io.IOException;
22  import java.nio.ByteBuffer;
23  
24  import org.apache.hadoop.hbase.Cell;
25  import org.apache.hadoop.hbase.CellComparator;
26  import org.apache.hadoop.hbase.CellUtil;
27  import org.apache.hadoop.hbase.KeyValue;
28  import org.apache.hadoop.hbase.KeyValueUtil;
29  import org.apache.hadoop.hbase.classification.InterfaceAudience;
30  import org.apache.hadoop.hbase.nio.ByteBuff;
31  import org.apache.hadoop.hbase.util.ByteBufferUtils;
32  import org.apache.hadoop.hbase.util.Bytes;
33  
34  /**
35   * Compress key by storing size of common prefix with previous KeyValue
36   * and storing raw size of rest.
37   *
38   * Format:
39   * 1-5 bytes: compressed key length minus prefix (7-bit encoding)
40   * 1-5 bytes: compressed value length (7-bit encoding)
41   * 1-3 bytes: compressed length of common key prefix
42   * ... bytes: rest of key (including timestamp)
43   * ... bytes: value
44   *
45   * In a worst case compressed KeyValue will be three bytes longer than original.
46   *
47   */
48  @InterfaceAudience.Private
49  public class PrefixKeyDeltaEncoder extends BufferedDataBlockEncoder {
50  
51    @Override
52    public int internalEncode(Cell cell, HFileBlockDefaultEncodingContext encodingContext,
53        DataOutputStream out) throws IOException {
54      int klength = KeyValueUtil.keyLength(cell);
55      int vlength = cell.getValueLength();
56      EncodingState state = encodingContext.getEncodingState();
57      if (state.prevCell == null) {
58        // copy the key, there is no common prefix with none
59        ByteBufferUtils.putCompressedInt(out, klength);
60        ByteBufferUtils.putCompressedInt(out, vlength);
61        ByteBufferUtils.putCompressedInt(out, 0);
62        CellUtil.writeFlatKey(cell, out);
63      } else {
64        // find a common prefix and skip it
65        int common = CellUtil.findCommonPrefixInFlatKey(cell, state.prevCell, true, true);
66        ByteBufferUtils.putCompressedInt(out, klength - common);
67        ByteBufferUtils.putCompressedInt(out, vlength);
68        ByteBufferUtils.putCompressedInt(out, common);
69        writeKeyExcludingCommon(cell, common, out);
70      }
71      // Write the value part
72      CellUtil.writeValue(out, cell, vlength);
73      int size = klength + vlength + KeyValue.KEYVALUE_INFRASTRUCTURE_SIZE;
74      size += afterEncodingKeyValue(cell, out, encodingContext);
75      state.prevCell = cell;
76      return size;
77    }
78  
79    private void writeKeyExcludingCommon(Cell cell, int commonPrefix, DataOutputStream out)
80        throws IOException {
81      short rLen = cell.getRowLength();
82      if (commonPrefix < rLen + KeyValue.ROW_LENGTH_SIZE) {
83        // Previous and current rows are different. Need to write the differing part followed by
84        // cf,q,ts and type
85        CellUtil.writeRowKeyExcludingCommon(cell, rLen, commonPrefix, out);
86        byte fLen = cell.getFamilyLength();
87        out.writeByte(fLen);
88        CellUtil.writeFamily(out, cell, fLen);
89        CellUtil.writeQualifier(out, cell, cell.getQualifierLength());
90        out.writeLong(cell.getTimestamp());
91        out.writeByte(cell.getTypeByte());
92      } else {
93        // The full row key part is common. CF part will be common for sure as we deal with Cells in
94        // same family. Just need write the differing part in q, ts and type
95        commonPrefix = commonPrefix - (rLen + KeyValue.ROW_LENGTH_SIZE)
96            - (cell.getFamilyLength() + KeyValue.FAMILY_LENGTH_SIZE);
97        int qLen = cell.getQualifierLength();
98        int commonQualPrefix = Math.min(commonPrefix, qLen);
99        int qualPartLenToWrite = qLen - commonQualPrefix;
100       if (qualPartLenToWrite > 0) {
101         CellUtil.writeQualifierSkippingBytes(out, cell, qLen, commonQualPrefix);
102       }
103       commonPrefix -= commonQualPrefix;
104       // Common part in TS also?
105       if (commonPrefix > 0) {
106         int commonTimestampPrefix = Math.min(commonPrefix, KeyValue.TIMESTAMP_SIZE);
107         if (commonTimestampPrefix < KeyValue.TIMESTAMP_SIZE) {
108           byte[] curTsBuf = Bytes.toBytes(cell.getTimestamp());
109           out.write(curTsBuf, commonTimestampPrefix, KeyValue.TIMESTAMP_SIZE
110               - commonTimestampPrefix);
111         }
112         commonPrefix -= commonTimestampPrefix;
113         if (commonPrefix == 0) {
114           out.writeByte(cell.getTypeByte());
115         }
116       } else {
117         out.writeLong(cell.getTimestamp());
118         out.writeByte(cell.getTypeByte());
119       }
120     }
121   }
122 
123   @Override
124   protected ByteBuffer internalDecodeKeyValues(DataInputStream source, int allocateHeaderLength,
125       int skipLastBytes, HFileBlockDefaultDecodingContext decodingCtx) throws IOException {
126     int decompressedSize = source.readInt();
127     ByteBuffer buffer = ByteBuffer.allocate(decompressedSize +
128         allocateHeaderLength);
129     buffer.position(allocateHeaderLength);
130     int prevKeyOffset = 0;
131 
132     while (source.available() > skipLastBytes) {
133       prevKeyOffset = decodeKeyValue(source, buffer, prevKeyOffset);
134       afterDecodingKeyValue(source, buffer, decodingCtx);
135     }
136 
137     if (source.available() != skipLastBytes) {
138       throw new IllegalStateException("Read too many bytes.");
139     }
140 
141     buffer.limit(buffer.position());
142     return buffer;
143   }
144 
145   private int decodeKeyValue(DataInputStream source, ByteBuffer buffer,
146       int prevKeyOffset)
147           throws IOException, EncoderBufferTooSmallException {
148     int keyLength = ByteBufferUtils.readCompressedInt(source);
149     int valueLength = ByteBufferUtils.readCompressedInt(source);
150     int commonLength = ByteBufferUtils.readCompressedInt(source);
151     int keyOffset;
152     keyLength += commonLength;
153 
154     ensureSpace(buffer, keyLength + valueLength + KeyValue.ROW_OFFSET);
155 
156     buffer.putInt(keyLength);
157     buffer.putInt(valueLength);
158 
159     // copy the prefix
160     if (commonLength > 0) {
161       keyOffset = buffer.position();
162       ByteBufferUtils.copyFromBufferToBuffer(buffer, buffer, prevKeyOffset,
163           commonLength);
164     } else {
165       keyOffset = buffer.position();
166     }
167 
168     // copy rest of the key and value
169     int len = keyLength - commonLength + valueLength;
170     ByteBufferUtils.copyFromStreamToBuffer(buffer, source, len);
171     return keyOffset;
172   }
173 
174   @Override
175   public Cell getFirstKeyCellInBlock(ByteBuff block) {
176     block.mark();
177     block.position(Bytes.SIZEOF_INT);
178     int keyLength = ByteBuff.readCompressedInt(block);
179     // TODO : See if we can avoid these reads as the read values are not getting used
180     ByteBuff.readCompressedInt(block);
181     int commonLength = ByteBuff.readCompressedInt(block);
182     if (commonLength != 0) {
183       throw new AssertionError("Nonzero common length in the first key in "
184           + "block: " + commonLength);
185     }
186     ByteBuffer key = block.asSubByteBuffer(keyLength).duplicate();
187     block.reset();
188     return createFirstKeyCell(key, keyLength);
189   }
190 
191   @Override
192   public String toString() {
193     return PrefixKeyDeltaEncoder.class.getSimpleName();
194   }
195 
196   @Override
197   public EncodedSeeker createSeeker(CellComparator comparator,
198       final HFileBlockDecodingContext decodingCtx) {
199     return new BufferedEncodedSeeker<SeekerState>(comparator, decodingCtx) {
200       @Override
201       protected void decodeNext() {
202         current.keyLength = ByteBuff.readCompressedInt(currentBuffer);
203         current.valueLength = ByteBuff.readCompressedInt(currentBuffer);
204         current.lastCommonPrefix = ByteBuff.readCompressedInt(currentBuffer);
205         current.keyLength += current.lastCommonPrefix;
206         current.ensureSpaceForKey();
207         currentBuffer.get(current.keyBuffer, current.lastCommonPrefix,
208             current.keyLength - current.lastCommonPrefix);
209         current.valueOffset = currentBuffer.position();
210         currentBuffer.skip(current.valueLength);
211         if (includesTags()) {
212           decodeTags();
213         }
214         if (includesMvcc()) {
215           current.memstoreTS = ByteBuff.readVLong(currentBuffer);
216         } else {
217           current.memstoreTS = 0;
218         }
219         current.nextKvOffset = currentBuffer.position();
220       }
221 
222       @Override
223       protected void decodeFirst() {
224         currentBuffer.skip(Bytes.SIZEOF_INT);
225         decodeNext();
226       }
227     };
228   }
229 }