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.client;
20  
21  import java.nio.ByteBuffer;
22  import java.util.ArrayList;
23  import java.util.Arrays;
24  import java.util.HashMap;
25  import java.util.List;
26  import java.util.Map;
27  import java.util.NavigableMap;
28  import java.util.TreeMap;
29  import java.util.UUID;
30  
31  import org.apache.hadoop.classification.InterfaceAudience;
32  import org.apache.hadoop.classification.InterfaceStability;
33  import org.apache.hadoop.hbase.Cell;
34  import org.apache.hadoop.hbase.CellScannable;
35  import org.apache.hadoop.hbase.CellScanner;
36  import org.apache.hadoop.hbase.CellUtil;
37  import org.apache.hadoop.hbase.HConstants;
38  import org.apache.hadoop.hbase.KeyValue;
39  import org.apache.hadoop.hbase.KeyValueUtil;
40  import org.apache.hadoop.hbase.Tag;
41  import org.apache.hadoop.hbase.exceptions.DeserializationException;
42  import org.apache.hadoop.hbase.io.HeapSize;
43  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
44  import org.apache.hadoop.hbase.security.access.AccessControlConstants;
45  import org.apache.hadoop.hbase.security.access.Permission;
46  import org.apache.hadoop.hbase.security.visibility.CellVisibility;
47  import org.apache.hadoop.hbase.security.visibility.VisibilityConstants;
48  import org.apache.hadoop.hbase.util.Bytes;
49  import org.apache.hadoop.hbase.util.ClassSize;
50  
51  import com.google.common.collect.ArrayListMultimap;
52  import com.google.common.collect.ListMultimap;
53  import com.google.common.collect.Lists;
54  import com.google.common.io.ByteArrayDataInput;
55  import com.google.common.io.ByteArrayDataOutput;
56  import com.google.common.io.ByteStreams;
57  
58  @InterfaceAudience.Public
59  @InterfaceStability.Evolving
60  public abstract class Mutation extends OperationWithAttributes implements Row, CellScannable,
61      HeapSize {
62    public static final long MUTATION_OVERHEAD = ClassSize.align(
63        // This
64        ClassSize.OBJECT +
65        // row + OperationWithAttributes.attributes
66        2 * ClassSize.REFERENCE +
67        // Timestamp
68        1 * Bytes.SIZEOF_LONG +
69        // durability
70        ClassSize.REFERENCE +
71        // familyMap
72        ClassSize.REFERENCE +
73        // familyMap
74        ClassSize.TREEMAP);
75  
76    /**
77     * The attribute for storing the list of clusters that have consumed the change.
78     */
79    private static final String CONSUMED_CLUSTER_IDS = "_cs.id";
80  
81    protected byte [] row = null;
82    protected long ts = HConstants.LATEST_TIMESTAMP;
83    protected Durability durability = Durability.USE_DEFAULT;
84  
85    // A Map sorted by column family.
86    protected NavigableMap<byte [], List<Cell>> familyMap =
87      new TreeMap<byte [], List<Cell>>(Bytes.BYTES_COMPARATOR);
88  
89    @Override
90    public CellScanner cellScanner() {
91      return CellUtil.createCellScanner(getFamilyCellMap());
92    }
93  
94    /**
95     * Creates an empty list if one doesn't exist for the given column family
96     * or else it returns the associated list of Cell objects.
97     *
98     * @param family column family
99     * @return a list of Cell objects, returns an empty list if one doesn't exist.
100    */
101   List<Cell> getCellList(byte[] family) {
102     List<Cell> list = this.familyMap.get(family);
103     if (list == null) {
104       list = new ArrayList<Cell>();
105     }
106     return list;
107   }
108 
109   /*
110    * Create a KeyValue with this objects row key and the Put identifier.
111    *
112    * @return a KeyValue with this objects row key and the Put identifier.
113    */
114   KeyValue createPutKeyValue(byte[] family, byte[] qualifier, long ts, byte[] value) {
115     return new KeyValue(this.row, family, qualifier, ts, KeyValue.Type.Put, value);
116   }
117 
118   /**
119    * Create a KeyValue with this objects row key and the Put identifier.
120    * @param family
121    * @param qualifier
122    * @param ts
123    * @param value
124    * @param tags - Specify the Tags as an Array {@link KeyValue.Tag}
125    * @return a KeyValue with this objects row key and the Put identifier.
126    */
127   KeyValue createPutKeyValue(byte[] family, byte[] qualifier, long ts, byte[] value, Tag[] tags) {
128     KeyValue kvWithTag = new KeyValue(this.row, family, qualifier, ts, value, tags);
129     return kvWithTag;
130   }
131 
132   /*
133    * Create a KeyValue with this objects row key and the Put identifier.
134    *
135    * @return a KeyValue with this objects row key and the Put identifier.
136    */
137   KeyValue createPutKeyValue(byte[] family, ByteBuffer qualifier, long ts, ByteBuffer value,
138                              Tag[] tags) {
139     return new KeyValue(this.row, 0, this.row == null ? 0 : this.row.length,
140         family, 0, family == null ? 0 : family.length,
141         qualifier, ts, KeyValue.Type.Put, value, tags != null ? Arrays.asList(tags) : null);
142   }
143 
144   /**
145    * Compile the column family (i.e. schema) information
146    * into a Map. Useful for parsing and aggregation by debugging,
147    * logging, and administration tools.
148    * @return Map
149    */
150   @Override
151   public Map<String, Object> getFingerprint() {
152     Map<String, Object> map = new HashMap<String, Object>();
153     List<String> families = new ArrayList<String>();
154     // ideally, we would also include table information, but that information
155     // is not stored in each Operation instance.
156     map.put("families", families);
157     for (Map.Entry<byte [], List<Cell>> entry : this.familyMap.entrySet()) {
158       families.add(Bytes.toStringBinary(entry.getKey()));
159     }
160     return map;
161   }
162 
163   /**
164    * Compile the details beyond the scope of getFingerprint (row, columns,
165    * timestamps, etc.) into a Map along with the fingerprinted information.
166    * Useful for debugging, logging, and administration tools.
167    * @param maxCols a limit on the number of columns output prior to truncation
168    * @return Map
169    */
170   @Override
171   public Map<String, Object> toMap(int maxCols) {
172     // we start with the fingerprint map and build on top of it.
173     Map<String, Object> map = getFingerprint();
174     // replace the fingerprint's simple list of families with a
175     // map from column families to lists of qualifiers and kv details
176     Map<String, List<Map<String, Object>>> columns =
177       new HashMap<String, List<Map<String, Object>>>();
178     map.put("families", columns);
179     map.put("row", Bytes.toStringBinary(this.row));
180     int colCount = 0;
181     // iterate through all column families affected
182     for (Map.Entry<byte [], List<Cell>> entry : this.familyMap.entrySet()) {
183       // map from this family to details for each cell affected within the family
184       List<Map<String, Object>> qualifierDetails = new ArrayList<Map<String, Object>>();
185       columns.put(Bytes.toStringBinary(entry.getKey()), qualifierDetails);
186       colCount += entry.getValue().size();
187       if (maxCols <= 0) {
188         continue;
189       }
190       // add details for each cell
191       for (Cell cell: entry.getValue()) {
192         if (--maxCols <= 0 ) {
193           continue;
194         }
195         // KeyValue v1 expectation.  Cast for now until we go all Cell all the time.
196         KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
197         Map<String, Object> kvMap = kv.toStringMap();
198         // row and family information are already available in the bigger map
199         kvMap.remove("row");
200         kvMap.remove("family");
201         qualifierDetails.add(kvMap);
202       }
203     }
204     map.put("totalColumns", colCount);
205     // add the id if set
206     if (getId() != null) {
207       map.put("id", getId());
208     }
209     return map;
210   }
211 
212   /**
213    * @deprecated Use {@link #getDurability()} instead.
214    * @return true if edits should be applied to WAL, false if not
215    */
216   @Deprecated
217   public boolean getWriteToWAL() {
218     return this.durability == Durability.SKIP_WAL;
219   }
220 
221   /**
222    * Set whether this Delete should be written to the WAL or not.
223    * Not writing the WAL means you may lose edits on server crash.
224    * This method will reset any changes made via {@link #setDurability(Durability)}
225    * @param write true if edits should be written to WAL, false if not
226    * @deprecated Use {@link #setDurability(Durability)} instead.
227    */
228   @Deprecated
229   public Mutation setWriteToWAL(boolean write) {
230     setDurability(write ? Durability.USE_DEFAULT : Durability.SKIP_WAL);
231     return this;
232   }
233 
234   /**
235    * Set the durability for this mutation
236    * @param d
237    */
238   public Mutation setDurability(Durability d) {
239     this.durability = d;
240     return this;
241   }
242 
243   /** Get the current durability */
244   public Durability getDurability() {
245     return this.durability;
246   }
247 
248   /**
249    * Method for retrieving the put's familyMap
250    * @return familyMap
251    */
252   public NavigableMap<byte [], List<Cell>> getFamilyCellMap() {
253     return this.familyMap;
254   }
255 
256   /**
257    * Method for setting the put's familyMap
258    */
259   public Mutation setFamilyCellMap(NavigableMap<byte [], List<Cell>> map) {
260     // TODO: Shut this down or move it up to be a Constructor.  Get new object rather than change
261     // this internal data member.
262     this.familyMap = map;
263     return this;
264   }
265 
266   /**
267    * Method for retrieving the put's familyMap that is deprecated and inefficient.
268    * @return the map
269    * @deprecated use {@link #getFamilyCellMap()} instead.
270    */
271   @Deprecated
272   public NavigableMap<byte [], List<KeyValue>> getFamilyMap() {
273     TreeMap<byte[], List<KeyValue>> fm =
274         new TreeMap<byte[], List<KeyValue>>(Bytes.BYTES_COMPARATOR);
275     for (Map.Entry<byte[], List<Cell>> e : familyMap.entrySet()) {
276       List<KeyValue> kvl = new ArrayList<KeyValue>(e.getValue().size());
277       for (Cell c : e.getValue()) {
278         kvl.add(KeyValueUtil.ensureKeyValue(c));
279       }
280       fm.put(e.getKey(), kvl);
281     }
282     return fm;
283   }
284 
285   /**
286    * Method for setting the put's familyMap that is deprecated and inefficient.
287    * @deprecated use {@link #setFamilyCellMap(NavigableMap)} instead.
288    */
289   @Deprecated
290   public Mutation setFamilyMap(NavigableMap<byte [], List<KeyValue>> map) {
291     TreeMap<byte[], List<Cell>> fm = new TreeMap<byte[], List<Cell>>(Bytes.BYTES_COMPARATOR);
292     for (Map.Entry<byte[], List<KeyValue>> e : map.entrySet()) {
293       fm.put(e.getKey(), Lists.<Cell>newArrayList(e.getValue()));
294     }
295     this.familyMap = fm;
296     return this;
297   }
298 
299   /**
300    * Method to check if the familyMap is empty
301    * @return true if empty, false otherwise
302    */
303   public boolean isEmpty() {
304     return familyMap.isEmpty();
305   }
306 
307   /**
308    * Method for retrieving the delete's row
309    * @return row
310    */
311   @Override
312   public byte [] getRow() {
313     return this.row;
314   }
315 
316   @Override
317   public int compareTo(final Row d) {
318     return Bytes.compareTo(this.getRow(), d.getRow());
319   }
320 
321   /**
322    * Method for retrieving the timestamp
323    * @return timestamp
324    */
325   public long getTimeStamp() {
326     return this.ts;
327   }
328 
329   /**
330    * Marks that the clusters with the given clusterIds have consumed the mutation
331    * @param clusterIds of the clusters that have consumed the mutation
332    */
333   public Mutation setClusterIds(List<UUID> clusterIds) {
334     ByteArrayDataOutput out = ByteStreams.newDataOutput();
335     out.writeInt(clusterIds.size());
336     for (UUID clusterId : clusterIds) {
337       out.writeLong(clusterId.getMostSignificantBits());
338       out.writeLong(clusterId.getLeastSignificantBits());
339     }
340     setAttribute(CONSUMED_CLUSTER_IDS, out.toByteArray());
341     return this;
342   }
343 
344   /**
345    * @return the set of clusterIds that have consumed the mutation
346    */
347   public List<UUID> getClusterIds() {
348     List<UUID> clusterIds = new ArrayList<UUID>();
349     byte[] bytes = getAttribute(CONSUMED_CLUSTER_IDS);
350     if(bytes != null) {
351       ByteArrayDataInput in = ByteStreams.newDataInput(bytes);
352       int numClusters = in.readInt();
353       for(int i=0; i<numClusters; i++){
354         clusterIds.add(new UUID(in.readLong(), in.readLong()));
355       }
356     }
357     return clusterIds;
358   }
359 
360   /**
361    * Sets the visibility expression associated with cells in this Mutation.
362    * It is illegal to set <code>CellVisibility</code> on <code>Delete</code> mutation.
363    * @param expression
364    */
365   public Mutation setCellVisibility(CellVisibility expression) {
366     this.setAttribute(VisibilityConstants.VISIBILITY_LABELS_ATTR_KEY, ProtobufUtil
367         .toCellVisibility(expression).toByteArray());
368     return this;
369   }
370 
371   /**
372    * @return CellVisibility associated with cells in this Mutation.
373    * @throws DeserializationException
374    */
375   public CellVisibility getCellVisibility() throws DeserializationException {
376     byte[] cellVisibilityBytes = this.getAttribute(VisibilityConstants.VISIBILITY_LABELS_ATTR_KEY);
377     if (cellVisibilityBytes == null) return null;
378     return ProtobufUtil.toCellVisibility(cellVisibilityBytes);
379   }
380 
381   /**
382    * Number of KeyValues carried by this Mutation.
383    * @return the total number of KeyValues
384    */
385   public int size() {
386     int size = 0;
387     for (List<Cell> cells : this.familyMap.values()) {
388       size += cells.size();
389     }
390     return size;
391   }
392 
393   /**
394    * @return the number of different families
395    */
396   public int numFamilies() {
397     return familyMap.size();
398   }
399 
400   /**
401    * @return Calculate what Mutation adds to class heap size.
402    */
403   @Override
404   public long heapSize() {
405     long heapsize = MUTATION_OVERHEAD;
406     // Adding row
407     heapsize += ClassSize.align(ClassSize.ARRAY + this.row.length);
408 
409     // Adding map overhead
410     heapsize +=
411       ClassSize.align(this.familyMap.size() * ClassSize.MAP_ENTRY);
412     for(Map.Entry<byte [], List<Cell>> entry : this.familyMap.entrySet()) {
413       //Adding key overhead
414       heapsize +=
415         ClassSize.align(ClassSize.ARRAY + entry.getKey().length);
416 
417       //This part is kinds tricky since the JVM can reuse references if you
418       //store the same value, but have a good match with SizeOf at the moment
419       //Adding value overhead
420       heapsize += ClassSize.align(ClassSize.ARRAYLIST);
421       int size = entry.getValue().size();
422       heapsize += ClassSize.align(ClassSize.ARRAY +
423           size * ClassSize.REFERENCE);
424 
425       for(Cell cell : entry.getValue()) {
426         KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
427         heapsize += kv.heapSize();
428       }
429     }
430     heapsize += getAttributeSize();
431     heapsize += extraHeapSize();
432     return ClassSize.align(heapsize);
433   }
434 
435   /**
436    * @return The serialized ACL for this operation, or null if none
437    */
438   public byte[] getACL() {
439     return getAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL);
440   }
441 
442   /**
443    * @param user User short name
444    * @param perms Permissions for the user
445    */
446   public Mutation setACL(String user, Permission perms) {
447     setAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL,
448       ProtobufUtil.toUsersAndPermissions(user, perms).toByteArray());
449     return this;
450   }
451 
452   /**
453    * @param perms A map of permissions for a user or users
454    */
455   public Mutation setACL(Map<String, Permission> perms) {
456     ListMultimap<String, Permission> permMap = ArrayListMultimap.create();
457     for (Map.Entry<String, Permission> entry : perms.entrySet()) {
458       permMap.put(entry.getKey(), entry.getValue());
459     }
460     setAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL,
461       ProtobufUtil.toUsersAndPermissions(permMap).toByteArray());
462     return this;
463   }
464 
465   /**
466    * Subclasses should override this method to add the heap size of their own fields.
467    * @return the heap size to add (will be aligned).
468    */
469   protected long extraHeapSize(){
470     return 0L;
471   }
472 
473 
474   /**
475    * @param row Row to check
476    * @throws IllegalArgumentException Thrown if <code>row</code> is empty or null or
477    * &gt; {@link HConstants#MAX_ROW_LENGTH}
478    * @return <code>row</code>
479    */
480   static byte [] checkRow(final byte [] row) {
481     return checkRow(row, 0, row == null? 0: row.length);
482   }
483 
484   /**
485    * @param row Row to check
486    * @param offset
487    * @param length
488    * @throws IllegalArgumentException Thrown if <code>row</code> is empty or null or
489    * &gt; {@link HConstants#MAX_ROW_LENGTH}
490    * @return <code>row</code>
491    */
492   static byte [] checkRow(final byte [] row, final int offset, final int length) {
493     if (row == null) {
494       throw new IllegalArgumentException("Row buffer is null");
495     }
496     if (length == 0) {
497       throw new IllegalArgumentException("Row length is 0");
498     }
499     if (length > HConstants.MAX_ROW_LENGTH) {
500       throw new IllegalArgumentException("Row length " + length + " is > " +
501         HConstants.MAX_ROW_LENGTH);
502     }
503     return row;
504   }
505 
506   static void checkRow(ByteBuffer row) {
507     if (row == null) {
508       throw new IllegalArgumentException("Row buffer is null");
509     }
510     if (row.remaining() == 0) {
511       throw new IllegalArgumentException("Row length is 0");
512     }
513     if (row.remaining() > HConstants.MAX_ROW_LENGTH) {
514       throw new IllegalArgumentException("Row length " + row.remaining() + " is > " +
515           HConstants.MAX_ROW_LENGTH);
516     }
517   }
518 }