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  
19  package org.apache.hadoop.hbase;
20  
21  import java.io.IOException;
22  import java.io.OutputStream;
23  import java.nio.ByteBuffer;
24  import java.util.ArrayList;
25  import java.util.List;
26  
27  import org.apache.hadoop.classification.InterfaceAudience;
28  import org.apache.hadoop.hbase.KeyValue.Type;
29  import org.apache.hadoop.hbase.io.util.StreamUtils;
30  import org.apache.hadoop.hbase.util.ByteBufferUtils;
31  import org.apache.hadoop.hbase.util.Bytes;
32  import org.apache.hadoop.hbase.util.IterableUtils;
33  import org.apache.hadoop.hbase.util.SimpleMutableByteRange;
34  import org.apache.hadoop.io.WritableUtils;
35  
36  import com.google.common.base.Function;
37  import com.google.common.collect.Lists;
38  
39  /**
40   * static convenience methods for dealing with KeyValues and collections of KeyValues
41   */
42  @InterfaceAudience.Private
43  public class KeyValueUtil {
44  
45    /**************** length *********************/
46  
47    /**
48     * Returns number of bytes this cell would have been used if serialized as in {@link KeyValue}
49     * @param cell
50     * @return the length
51     */
52    public static int length(final Cell cell) {
53      return length(cell.getRowLength(), cell.getFamilyLength(), cell.getQualifierLength(),
54          cell.getValueLength(), cell.getTagsLength(), true);
55    }
56  
57    private static int length(short rlen, byte flen, int qlen, int vlen, int tlen, boolean withTags) {
58      if (withTags) {
59        return (int) (KeyValue.getKeyValueDataStructureSize(rlen, flen, qlen, vlen, tlen));
60      }
61      return (int) (KeyValue.getKeyValueDataStructureSize(rlen, flen, qlen, vlen));
62    }
63  
64    /**
65     * Returns number of bytes this cell's key part would have been used if serialized as in
66     * {@link KeyValue}. Key includes rowkey, family, qualifier, timestamp and type.
67     * @param cell
68     * @return the key length
69     */
70    public static int keyLength(final Cell cell) {
71      return keyLength(cell.getRowLength(), cell.getFamilyLength(), cell.getQualifierLength());
72    }
73  
74    private static int keyLength(short rlen, byte flen, int qlen) {
75      return (int) KeyValue.getKeyDataStructureSize(rlen, flen, qlen);
76    }
77  
78    public static int lengthWithMvccVersion(final KeyValue kv, final boolean includeMvccVersion) {
79      int length = kv.getLength();
80      if (includeMvccVersion) {
81        length += WritableUtils.getVIntSize(kv.getMvccVersion());
82      }
83      return length;
84    }
85  
86    public static int totalLengthWithMvccVersion(final Iterable<? extends KeyValue> kvs,
87        final boolean includeMvccVersion) {
88      int length = 0;
89      for (KeyValue kv : IterableUtils.nullSafe(kvs)) {
90        length += lengthWithMvccVersion(kv, includeMvccVersion);
91      }
92      return length;
93    }
94  
95  
96    /**************** copy key only *********************/
97  
98    public static KeyValue copyToNewKeyValue(final Cell cell) {
99      byte[] bytes = copyToNewByteArray(cell);
100     KeyValue kvCell = new KeyValue(bytes, 0, bytes.length);
101     kvCell.setSequenceId(cell.getMvccVersion());
102     return kvCell;
103   }
104 
105   public static ByteBuffer copyKeyToNewByteBuffer(final Cell cell) {
106     byte[] bytes = new byte[keyLength(cell)];
107     appendKeyTo(cell, bytes, 0);
108     ByteBuffer buffer = ByteBuffer.wrap(bytes);
109     buffer.position(buffer.limit());//make it look as if each field were appended
110     return buffer;
111   }
112 
113   public static byte[] copyToNewByteArray(final Cell cell) {
114     int v1Length = length(cell);
115     byte[] backingBytes = new byte[v1Length];
116     appendToByteArray(cell, backingBytes, 0);
117     return backingBytes;
118   }
119 
120   public static int appendKeyTo(final Cell cell, final byte[] output,
121       final int offset) {
122     int nextOffset = offset;
123     nextOffset = Bytes.putShort(output, nextOffset, cell.getRowLength());
124     nextOffset = CellUtil.copyRowTo(cell, output, nextOffset);
125     nextOffset = Bytes.putByte(output, nextOffset, cell.getFamilyLength());
126     nextOffset = CellUtil.copyFamilyTo(cell, output, nextOffset);
127     nextOffset = CellUtil.copyQualifierTo(cell, output, nextOffset);
128     nextOffset = Bytes.putLong(output, nextOffset, cell.getTimestamp());
129     nextOffset = Bytes.putByte(output, nextOffset, cell.getTypeByte());
130     return nextOffset;
131   }
132 
133 
134   /**************** copy key and value *********************/
135 
136   public static int appendToByteArray(final Cell cell, final byte[] output, final int offset) {
137     int pos = offset;
138     pos = Bytes.putInt(output, pos, keyLength(cell));
139     pos = Bytes.putInt(output, pos, cell.getValueLength());
140     pos = appendKeyTo(cell, output, pos);
141     pos = CellUtil.copyValueTo(cell, output, pos);
142     if ((cell.getTagsLength() > 0)) {
143       pos = Bytes.putAsShort(output, pos, cell.getTagsLength());
144       pos = CellUtil.copyTagTo(cell, output, pos);
145     }
146     return pos;
147   }
148 
149   public static ByteBuffer copyToNewByteBuffer(final Cell cell) {
150     byte[] bytes = new byte[length(cell)];
151     appendToByteArray(cell, bytes, 0);
152     ByteBuffer buffer = ByteBuffer.wrap(bytes);
153     buffer.position(buffer.limit());//make it look as if each field were appended
154     return buffer;
155   }
156 
157   public static void appendToByteBuffer(final ByteBuffer bb, final KeyValue kv,
158       final boolean includeMvccVersion) {
159     // keep pushing the limit out. assume enough capacity
160     bb.limit(bb.position() + kv.getLength());
161     bb.put(kv.getBuffer(), kv.getOffset(), kv.getLength());
162     if (includeMvccVersion) {
163       int numMvccVersionBytes = WritableUtils.getVIntSize(kv.getMvccVersion());
164       ByteBufferUtils.extendLimit(bb, numMvccVersionBytes);
165       ByteBufferUtils.writeVLong(bb, kv.getMvccVersion());
166     }
167   }
168 
169 
170   /**************** iterating *******************************/
171 
172   /**
173    * Creates a new KeyValue object positioned in the supplied ByteBuffer and sets the ByteBuffer's
174    * position to the start of the next KeyValue. Does not allocate a new array or copy data.
175    * @param bb
176    * @param includesMvccVersion
177    * @param includesTags 
178    */
179   public static KeyValue nextShallowCopy(final ByteBuffer bb, final boolean includesMvccVersion,
180       boolean includesTags) {
181     if (bb.isDirect()) {
182       throw new IllegalArgumentException("only supports heap buffers");
183     }
184     if (bb.remaining() < 1) {
185       return null;
186     }
187     KeyValue keyValue = null;
188     int underlyingArrayOffset = bb.arrayOffset() + bb.position();
189     int keyLength = bb.getInt();
190     int valueLength = bb.getInt();
191     ByteBufferUtils.skip(bb, keyLength + valueLength);
192     int tagsLength = 0;
193     if (includesTags) {
194       // Read short as unsigned, high byte first
195       tagsLength = ((bb.get() & 0xff) << 8) ^ (bb.get() & 0xff);
196       ByteBufferUtils.skip(bb, tagsLength);
197     }
198     int kvLength = (int) KeyValue.getKeyValueDataStructureSize(keyLength, valueLength, tagsLength);
199     keyValue = new KeyValue(bb.array(), underlyingArrayOffset, kvLength);
200     if (includesMvccVersion) {
201       long mvccVersion = ByteBufferUtils.readVLong(bb);
202       keyValue.setSequenceId(mvccVersion);
203     }
204     return keyValue;
205   }
206 
207 
208   /*************** next/previous **********************************/
209 
210   /**
211    * Append single byte 0x00 to the end of the input row key
212    */
213   public static KeyValue createFirstKeyInNextRow(final Cell in){
214     byte[] nextRow = new byte[in.getRowLength() + 1];
215     System.arraycopy(in.getRowArray(), in.getRowOffset(), nextRow, 0, in.getRowLength());
216     nextRow[nextRow.length - 1] = 0;//maybe not necessary
217     return createFirstOnRow(nextRow);
218   }
219 
220   /**
221    * Increment the row bytes and clear the other fields
222    */
223   public static KeyValue createFirstKeyInIncrementedRow(final Cell in){
224     byte[] thisRow = new SimpleMutableByteRange(in.getRowArray(), in.getRowOffset(),
225         in.getRowLength()).deepCopyToNewArray();
226     byte[] nextRow = Bytes.unsignedCopyAndIncrement(thisRow);
227     return createFirstOnRow(nextRow);
228   }
229 
230   /**
231    * Decrement the timestamp.  For tests (currently wasteful)
232    *
233    * Remember timestamps are sorted reverse chronologically.
234    * @param in
235    * @return previous key
236    */
237   public static KeyValue previousKey(final KeyValue in) {
238     return createFirstOnRow(CellUtil.cloneRow(in), CellUtil.cloneFamily(in),
239       CellUtil.cloneQualifier(in), in.getTimestamp() - 1);
240   }
241   
242 
243   /**
244    * Create a KeyValue for the specified row, family and qualifier that would be
245    * larger than or equal to all other possible KeyValues that have the same
246    * row, family, qualifier. Used for reseeking.
247    *
248    * @param row
249    *          row key
250    * @param roffset
251    *         row offset
252    * @param rlength
253    *         row length
254    * @param family
255    *         family name
256    * @param foffset
257    *         family offset
258    * @param flength
259    *         family length
260    * @param qualifier
261    *        column qualifier
262    * @param qoffset
263    *        qualifier offset
264    * @param qlength
265    *        qualifier length
266    * @return Last possible key on passed row, family, qualifier.
267    */
268   public static KeyValue createLastOnRow(final byte[] row, final int roffset, final int rlength,
269       final byte[] family, final int foffset, final int flength, final byte[] qualifier,
270       final int qoffset, final int qlength) {
271     return new KeyValue(row, roffset, rlength, family, foffset, flength, qualifier, qoffset,
272         qlength, HConstants.OLDEST_TIMESTAMP, Type.Minimum, null, 0, 0);
273   }
274   
275   /**
276    * Creates a keyValue for the specified keyvalue larger than or equal to all other possible
277    * KeyValues that have the same row, family, qualifer.  Used for reseeking
278    * @param kv
279    * @return KeyValue
280    */
281   public static KeyValue createLastOnRow(Cell kv) {
282     return createLastOnRow(kv.getRowArray(), kv.getRowOffset(), kv.getRowLength(), null, 0, 0,
283         null, 0, 0);
284   }
285 
286   /**
287    * Similar to
288    * {@link #createLastOnRow(byte[], int, int, byte[], int, int, byte[], int, int)}
289    * but creates the last key on the row/column of this KV (the value part of
290    * the returned KV is always empty). Used in creating "fake keys" for the
291    * multi-column Bloom filter optimization to skip the row/column we already
292    * know is not in the file.
293    * 
294    * @param kv - cell
295    * @return the last key on the row/column of the given key-value pair
296    */
297   public static KeyValue createLastOnRowCol(Cell kv) {
298     return new KeyValue(kv.getRowArray(), kv.getRowOffset(), kv.getRowLength(),
299         kv.getFamilyArray(), kv.getFamilyOffset(), kv.getFamilyLength(), kv.getQualifierArray(),
300         kv.getQualifierOffset(), kv.getQualifierLength(), HConstants.OLDEST_TIMESTAMP,
301         Type.Minimum, null, 0, 0);
302   }
303 
304   /**
305    * Creates the first KV with the row/family/qualifier of this KV and the given
306    * timestamp. Uses the "maximum" KV type that guarantees that the new KV is
307    * the lowest possible for this combination of row, family, qualifier, and
308    * timestamp. This KV's own timestamp is ignored. While this function copies
309    * the value from this KV, it is normally used on key-only KVs.
310    * 
311    * @param kv - cell
312    * @param ts
313    */
314   public static KeyValue createFirstOnRowColTS(Cell kv, long ts) {
315     return new KeyValue(kv.getRowArray(), kv.getRowOffset(), kv.getRowLength(),
316         kv.getFamilyArray(), kv.getFamilyOffset(), kv.getFamilyLength(), kv.getQualifierArray(),
317         kv.getQualifierOffset(), kv.getQualifierLength(), ts, Type.Maximum, kv.getValueArray(),
318         kv.getValueOffset(), kv.getValueLength());
319   }
320   
321   /**
322    * Create a KeyValue that is smaller than all other possible KeyValues
323    * for the given row. That is any (valid) KeyValue on 'row' would sort
324    * _after_ the result.
325    *
326    * @param row - row key (arbitrary byte array)
327    * @return First possible KeyValue on passed <code>row</code>
328    */
329   public static KeyValue createFirstOnRow(final byte [] row, int roffset, short rlength) {
330     return new KeyValue(row, roffset, rlength,
331         null, 0, 0, null, 0, 0, HConstants.LATEST_TIMESTAMP, Type.Maximum, null, 0, 0);
332   }
333   
334 
335   /**
336    * Creates a KeyValue that is last on the specified row id. That is,
337    * every other possible KeyValue for the given row would compareTo()
338    * less than the result of this call.
339    * @param row row key
340    * @return Last possible KeyValue on passed <code>row</code>
341    */
342   public static KeyValue createLastOnRow(final byte[] row) {
343     return new KeyValue(row, null, null, HConstants.LATEST_TIMESTAMP, Type.Minimum);
344   }
345 
346   /**
347    * Create a KeyValue that is smaller than all other possible KeyValues
348    * for the given row. That is any (valid) KeyValue on 'row' would sort
349    * _after_ the result.
350    *
351    * @param row - row key (arbitrary byte array)
352    * @return First possible KeyValue on passed <code>row</code>
353    */
354   public static KeyValue createFirstOnRow(final byte [] row) {
355     return createFirstOnRow(row, HConstants.LATEST_TIMESTAMP);
356   }
357 
358   /**
359    * Creates a KeyValue that is smaller than all other KeyValues that
360    * are older than the passed timestamp.
361    * @param row - row key (arbitrary byte array)
362    * @param ts - timestamp
363    * @return First possible key on passed <code>row</code> and timestamp.
364    */
365   public static KeyValue createFirstOnRow(final byte [] row,
366       final long ts) {
367     return new KeyValue(row, null, null, ts, Type.Maximum);
368   }
369 
370   /**
371    * Create a KeyValue for the specified row, family and qualifier that would be
372    * smaller than all other possible KeyValues that have the same row,family,qualifier.
373    * Used for seeking.
374    * @param row - row key (arbitrary byte array)
375    * @param family - family name
376    * @param qualifier - column qualifier
377    * @return First possible key on passed <code>row</code>, and column.
378    */
379   public static KeyValue createFirstOnRow(final byte [] row, final byte [] family,
380       final byte [] qualifier) {
381     return new KeyValue(row, family, qualifier, HConstants.LATEST_TIMESTAMP, Type.Maximum);
382   }
383 
384   /**
385    * Create a Delete Family KeyValue for the specified row and family that would
386    * be smaller than all other possible Delete Family KeyValues that have the
387    * same row and family.
388    * Used for seeking.
389    * @param row - row key (arbitrary byte array)
390    * @param family - family name
391    * @return First Delete Family possible key on passed <code>row</code>.
392    */
393   public static KeyValue createFirstDeleteFamilyOnRow(final byte [] row,
394       final byte [] family) {
395     return new KeyValue(row, family, null, HConstants.LATEST_TIMESTAMP,
396         Type.DeleteFamily);
397   }
398 
399   /**
400    * @param row - row key (arbitrary byte array)
401    * @param f - family name
402    * @param q - column qualifier
403    * @param ts - timestamp
404    * @return First possible key on passed <code>row</code>, column and timestamp
405    */
406   public static KeyValue createFirstOnRow(final byte [] row, final byte [] f,
407       final byte [] q, final long ts) {
408     return new KeyValue(row, f, q, ts, Type.Maximum);
409   }
410 
411   /**
412    * Create a KeyValue for the specified row, family and qualifier that would be
413    * smaller than all other possible KeyValues that have the same row,
414    * family, qualifier.
415    * Used for seeking.
416    * @param row row key
417    * @param roffset row offset
418    * @param rlength row length
419    * @param family family name
420    * @param foffset family offset
421    * @param flength family length
422    * @param qualifier column qualifier
423    * @param qoffset qualifier offset
424    * @param qlength qualifier length
425    * @return First possible key on passed Row, Family, Qualifier.
426    */
427   public static KeyValue createFirstOnRow(final byte [] row,
428       final int roffset, final int rlength, final byte [] family,
429       final int foffset, final int flength, final byte [] qualifier,
430       final int qoffset, final int qlength) {
431     return new KeyValue(row, roffset, rlength, family,
432         foffset, flength, qualifier, qoffset, qlength,
433         HConstants.LATEST_TIMESTAMP, Type.Maximum, null, 0, 0);
434   }
435 
436   /**
437    * Create a KeyValue for the specified row, family and qualifier that would be
438    * smaller than all other possible KeyValues that have the same row,
439    * family, qualifier.
440    * Used for seeking.
441    *
442    * @param buffer the buffer to use for the new <code>KeyValue</code> object
443    * @param row the value key
444    * @param family family name
445    * @param qualifier column qualifier
446    *
447    * @return First possible key on passed Row, Family, Qualifier.
448    *
449    * @throws IllegalArgumentException The resulting <code>KeyValue</code> object would be larger
450    * than the provided buffer or than <code>Integer.MAX_VALUE</code>
451    */
452   public static KeyValue createFirstOnRow(byte [] buffer, final byte [] row,
453       final byte [] family, final byte [] qualifier)
454           throws IllegalArgumentException {
455     return createFirstOnRow(buffer, 0, row, 0, row.length,
456         family, 0, family.length,
457         qualifier, 0, qualifier.length);
458   }
459 
460   /**
461    * Create a KeyValue for the specified row, family and qualifier that would be
462    * smaller than all other possible KeyValues that have the same row,
463    * family, qualifier.
464    * Used for seeking.
465    *
466    * @param buffer the buffer to use for the new <code>KeyValue</code> object
467    * @param boffset buffer offset
468    * @param row the value key
469    * @param roffset row offset
470    * @param rlength row length
471    * @param family family name
472    * @param foffset family offset
473    * @param flength family length
474    * @param qualifier column qualifier
475    * @param qoffset qualifier offset
476    * @param qlength qualifier length
477    *
478    * @return First possible key on passed Row, Family, Qualifier.
479    *
480    * @throws IllegalArgumentException The resulting <code>KeyValue</code> object would be larger
481    * than the provided buffer or than <code>Integer.MAX_VALUE</code>
482    */
483   public static KeyValue createFirstOnRow(byte[] buffer, final int boffset, final byte[] row,
484       final int roffset, final int rlength, final byte[] family, final int foffset,
485       final int flength, final byte[] qualifier, final int qoffset, final int qlength)
486       throws IllegalArgumentException {
487 
488     long lLength = KeyValue.getKeyValueDataStructureSize(rlength, flength, qlength, 0);
489 
490     if (lLength > Integer.MAX_VALUE) {
491       throw new IllegalArgumentException("KeyValue length " + lLength + " > " + Integer.MAX_VALUE);
492     }
493     int iLength = (int) lLength;
494     if (buffer.length - boffset < iLength) {
495       throw new IllegalArgumentException("Buffer size " + (buffer.length - boffset) + " < "
496           + iLength);
497     }
498 
499     int len = KeyValue.writeByteArray(buffer, boffset, row, roffset, rlength, family, foffset,
500         flength, qualifier, qoffset, qlength, HConstants.LATEST_TIMESTAMP, KeyValue.Type.Maximum,
501         null, 0, 0, null);
502     return new KeyValue(buffer, boffset, len);
503   }
504 
505   /**
506    * Creates the first KV with the row/family/qualifier of this KV and the
507    * given timestamp. Uses the "maximum" KV type that guarantees that the new
508    * KV is the lowest possible for this combination of row, family, qualifier,
509    * and timestamp. This KV's own timestamp is ignored. While this function
510    * copies the value from this KV, it is normally used on key-only KVs.
511    */
512   public static KeyValue createFirstOnRowColTS(KeyValue kv, long ts) {
513     return new KeyValue(
514         kv.getRowArray(), kv.getRowOffset(), kv.getRowLength(),
515         kv.getFamilyArray(), kv.getFamilyOffset(), kv.getFamilyLength(),
516         kv.getQualifierArray(), kv.getQualifierOffset(), kv.getQualifierLength(),
517         ts, Type.Maximum, kv.getValueArray(), kv.getValueOffset(), kv.getValueLength());
518   }
519 
520   /*************** misc **********************************/
521   /**
522    * @param cell
523    * @return <code>cell<code> if it is an instance of {@link KeyValue} else we will return a
524    * new {@link KeyValue} instance made from <code>cell</code>
525    */
526   public static KeyValue ensureKeyValue(final Cell cell) {
527     if (cell == null) return null;
528     return cell instanceof KeyValue? (KeyValue)cell: copyToNewKeyValue(cell);
529   }
530 
531   public static List<KeyValue> ensureKeyValues(List<Cell> cells) {
532     List<KeyValue> lazyList = Lists.transform(cells, new Function<Cell, KeyValue>() {
533       public KeyValue apply(Cell arg0) {
534         return KeyValueUtil.ensureKeyValue(arg0);
535       }
536     });
537     return new ArrayList<KeyValue>(lazyList);
538   }
539 
540   public static void oswrite(final Cell cell, final OutputStream out, final boolean withTags)
541       throws IOException {
542     if (cell instanceof KeyValue) {
543       KeyValue.oswrite((KeyValue) cell, out, withTags);
544     } else {
545       short rlen = cell.getRowLength();
546       byte flen = cell.getFamilyLength();
547       int qlen = cell.getQualifierLength();
548       int vlen = cell.getValueLength();
549       int tlen = cell.getTagsLength();
550 
551       // write total length
552       StreamUtils.writeInt(out, length(rlen, flen, qlen, vlen, tlen, withTags));
553       // write key length
554       StreamUtils.writeInt(out, keyLength(rlen, flen, qlen));
555       // write value length
556       StreamUtils.writeInt(out, vlen);
557       // Write rowkey - 2 bytes rk length followed by rowkey bytes
558       StreamUtils.writeShort(out, rlen);
559       out.write(cell.getRowArray(), cell.getRowOffset(), rlen);
560       // Write cf - 1 byte of cf length followed by the family bytes
561       out.write(flen);
562       out.write(cell.getFamilyArray(), cell.getFamilyOffset(), flen);
563       // write qualifier
564       out.write(cell.getQualifierArray(), cell.getQualifierOffset(), qlen);
565       // write timestamp
566       StreamUtils.writeLong(out, cell.getTimestamp());
567       // write the type
568       out.write(cell.getTypeByte());
569       // write value
570       out.write(cell.getValueArray(), cell.getValueOffset(), vlen);
571       // write tags if we have to
572       if (withTags) {
573         // 2 bytes tags length followed by tags bytes
574         // tags length is serialized with 2 bytes only(short way) even if the type is int. As this
575         // is non -ve numbers, we save the sign bit. See HBASE-11437
576         out.write((byte) (0xff & (tlen >> 8)));
577         out.write((byte) (0xff & tlen));
578         out.write(cell.getTagsArray(), cell.getTagsOffset(), tlen);
579       }
580     }
581   }
582 }