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