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.filter;
19  
20  import com.google.protobuf.InvalidProtocolBufferException;
21  
22  import java.util.ArrayList;
23  import java.util.Arrays;
24  import java.util.Comparator;
25  import java.util.Objects;
26  import java.util.TreeSet;
27  
28  import org.apache.hadoop.hbase.Cell;
29  import org.apache.hadoop.hbase.KeyValueUtil;
30  import org.apache.hadoop.hbase.classification.InterfaceAudience;
31  import org.apache.hadoop.hbase.classification.InterfaceStability;
32  import org.apache.hadoop.hbase.exceptions.DeserializationException;
33  import org.apache.hadoop.hbase.protobuf.generated.FilterProtos;
34  import org.apache.hadoop.hbase.util.ByteStringer;
35  import org.apache.hadoop.hbase.util.Bytes;
36  
37  /**
38   * This filter is used for selecting only those keys with columns that matches
39   * a particular prefix. For example, if prefix is 'an', it will pass keys will
40   * columns like 'and', 'anti' but not keys with columns like 'ball', 'act'.
41   */
42  @InterfaceAudience.Public
43  @InterfaceStability.Stable
44  public class MultipleColumnPrefixFilter extends FilterBase {
45    protected byte [] hint = null;
46    protected TreeSet<byte []> sortedPrefixes = createTreeSet();
47    private final static int MAX_LOG_PREFIXES = 5;
48  
49    public MultipleColumnPrefixFilter(final byte [][] prefixes) {
50      if (prefixes != null) {
51        for (int i = 0; i < prefixes.length; i++) {
52          if (!sortedPrefixes.add(prefixes[i]))
53            throw new IllegalArgumentException ("prefixes must be distinct");
54        }
55      }
56    }
57  
58    public byte [][] getPrefix() {
59      int count = 0;
60      byte [][] temp = new byte [sortedPrefixes.size()][];
61      for (byte [] prefixes : sortedPrefixes) {
62        temp [count++] = prefixes;
63      }
64      return temp;
65    }
66  
67    @Override
68    public ReturnCode filterKeyValue(Cell kv) {
69      if (sortedPrefixes.size() == 0 || kv.getQualifierArray() == null) {
70        return ReturnCode.INCLUDE;
71      } else {
72        return filterColumn(kv.getQualifierArray(), kv.getQualifierOffset(), kv.getQualifierLength());
73      }
74    }
75  
76    // Override here explicitly as the method in super class FilterBase might do a KeyValue recreate.
77    // See HBASE-12068
78    @Override
79    public Cell transformCell(Cell v) {
80      return v;
81    }
82  
83    public ReturnCode filterColumn(byte[] buffer, int qualifierOffset, int qualifierLength) {
84      byte [] qualifier = Arrays.copyOfRange(buffer, qualifierOffset,
85                                             qualifierLength + qualifierOffset);
86      TreeSet<byte []> lesserOrEqualPrefixes =
87        (TreeSet<byte []>) sortedPrefixes.headSet(qualifier, true);
88  
89      if (lesserOrEqualPrefixes.size() != 0) {
90        byte [] largestPrefixSmallerThanQualifier = lesserOrEqualPrefixes.last();
91        
92        if (Bytes.startsWith(qualifier, largestPrefixSmallerThanQualifier)) {
93          return ReturnCode.INCLUDE;
94        }
95        
96        if (lesserOrEqualPrefixes.size() == sortedPrefixes.size()) {
97          return ReturnCode.NEXT_ROW;
98        } else {
99          hint = sortedPrefixes.higher(largestPrefixSmallerThanQualifier);
100         return ReturnCode.SEEK_NEXT_USING_HINT;
101       }
102     } else {
103       hint = sortedPrefixes.first();
104       return ReturnCode.SEEK_NEXT_USING_HINT;
105     }
106   }
107 
108   public static Filter createFilterFromArguments(ArrayList<byte []> filterArguments) {
109     byte [][] prefixes = new byte [filterArguments.size()][];
110     for (int i = 0 ; i < filterArguments.size(); i++) {
111       byte [] columnPrefix = ParseFilter.removeQuotesFromByteArray(filterArguments.get(i));
112       prefixes[i] = columnPrefix;
113     }
114     return new MultipleColumnPrefixFilter(prefixes);
115   }
116 
117   /**
118    * @return The filter serialized using pb
119    */
120   @Override
121   public byte [] toByteArray() {
122     FilterProtos.MultipleColumnPrefixFilter.Builder builder =
123       FilterProtos.MultipleColumnPrefixFilter.newBuilder();
124     for (byte [] element : sortedPrefixes) {
125       if (element != null) builder.addSortedPrefixes(ByteStringer.wrap(element));
126     }
127     return builder.build().toByteArray();
128   }
129 
130   /**
131    * @param pbBytes A pb serialized {@link MultipleColumnPrefixFilter} instance
132    * @return An instance of {@link MultipleColumnPrefixFilter} made from <code>bytes</code>
133    * @throws DeserializationException
134    * @see #toByteArray
135    */
136   public static MultipleColumnPrefixFilter parseFrom(final byte [] pbBytes)
137   throws DeserializationException {
138     FilterProtos.MultipleColumnPrefixFilter proto;
139     try {
140       proto = FilterProtos.MultipleColumnPrefixFilter.parseFrom(pbBytes);
141     } catch (InvalidProtocolBufferException e) {
142       throw new DeserializationException(e);
143     }
144     int numPrefixes = proto.getSortedPrefixesCount();
145     byte [][] prefixes = new byte[numPrefixes][];
146     for (int i = 0; i < numPrefixes; ++i) {
147       prefixes[i] = proto.getSortedPrefixes(i).toByteArray();
148     }
149 
150     return new MultipleColumnPrefixFilter(prefixes);
151   }
152 
153   /**
154    * @param other
155    * @return true if and only if the fields of the filter that are serialized
156    * are equal to the corresponding fields in other.  Used for testing.
157    */
158   @Override
159   boolean areSerializedFieldsEqual(Filter o) {
160     if (o == this) return true;
161     if (!(o instanceof MultipleColumnPrefixFilter)) return false;
162 
163     MultipleColumnPrefixFilter other = (MultipleColumnPrefixFilter)o;
164     return this.sortedPrefixes.equals(other.sortedPrefixes);
165   }
166 
167   @Override
168   public Cell getNextCellHint(Cell kv) {
169     return KeyValueUtil.createFirstOnRow(
170       kv.getRowArray(), kv.getRowOffset(), kv.getRowLength(), kv.getFamilyArray(),
171       kv.getFamilyOffset(), kv.getFamilyLength(), hint, 0, hint.length);
172   }
173 
174   public TreeSet<byte []> createTreeSet() {
175     return new TreeSet<byte []>(new Comparator<Object>() {
176         @Override
177           public int compare (Object o1, Object o2) {
178           if (o1 == null || o2 == null)
179             throw new IllegalArgumentException ("prefixes can't be null");
180 
181           byte [] b1 = (byte []) o1;
182           byte [] b2 = (byte []) o2;
183           return Bytes.compareTo (b1, 0, b1.length, b2, 0, b2.length);
184         }
185       });
186   }
187 
188   @Override
189   public String toString() {
190     return toString(MAX_LOG_PREFIXES);
191   }
192 
193   protected String toString(int maxPrefixes) {
194     StringBuilder prefixes = new StringBuilder();
195 
196     int count = 0;
197     for (byte[] ba : this.sortedPrefixes) {
198       if (count >= maxPrefixes) {
199         break;
200       }
201       ++count;
202       prefixes.append(Bytes.toStringBinary(ba));
203       if (count < this.sortedPrefixes.size() && count < maxPrefixes) {
204         prefixes.append(", ");
205       }
206     }
207 
208     return String.format("%s (%d/%d): [%s]", this.getClass().getSimpleName(),
209         count, this.sortedPrefixes.size(), prefixes.toString());
210   }
211 
212   @Override
213   public boolean equals(Object obj) {
214     return obj instanceof Filter && areSerializedFieldsEqual((Filter) obj);
215   }
216 
217   @Override
218   public int hashCode() {
219     return Objects.hash(this.sortedPrefixes);
220   }
221 }