View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.util;
20  
21  import java.util.ArrayList;
22  import java.util.Collection;
23  import java.util.Comparator;
24  import java.util.List;
25  import java.util.Map.Entry;
26  import java.util.TreeMap;
27  import java.util.TreeSet;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.classification.InterfaceAudience;
32  import org.apache.hadoop.hbase.util.Bytes.ByteArrayComparator;
33  
34  import com.google.common.collect.ArrayListMultimap;
35  import com.google.common.collect.Multimap;
36  import com.google.common.collect.TreeMultimap;
37  
38  /**
39   * This is a generic region split calculator. It requires Ranges that provide
40   * start, end, and a comparator. It works in two phases -- the first adds ranges
41   * and rejects backwards ranges. Then one calls calcRegions to generate the
42   * multimap that has a start split key as a key and possibly multiple Ranges as
43   * members.
44   * 
45   * To traverse, one normally would get the split set, and iterate through the
46   * calcRegions. Normal regions would have only one entry, holes would have zero,
47   * and any overlaps would have multiple entries.
48   * 
49   * The interface is a bit cumbersome currently but is exposed this way so that
50   * clients can choose how to iterate through the region splits.
51   * 
52   * @param <R>
53   */
54  @InterfaceAudience.Private
55  public class RegionSplitCalculator<R extends KeyRange> {
56    final static Log LOG = LogFactory.getLog(RegionSplitCalculator.class);
57  
58    private final Comparator<R> rangeCmp;
59    /**
60     * This contains a sorted set of all the possible split points
61     * 
62     * Invariant: once populated this has 0 entries if empty or at most n+1 values
63     * where n == number of added ranges.
64     */
65    private final TreeSet<byte[]> splits = new TreeSet<byte[]>(BYTES_COMPARATOR);
66  
67    /**
68     * This is a map from start key to regions with the same start key.
69     * 
70     * Invariant: This always have n values in total
71     */
72    private final Multimap<byte[], R> starts = ArrayListMultimap.create();
73  
74    /**
75     * SPECIAL CASE
76     */
77    private final static byte[] ENDKEY = null;
78  
79    public RegionSplitCalculator(Comparator<R> cmp) {
80      rangeCmp = cmp;
81    }
82  
83    public final static Comparator<byte[]> BYTES_COMPARATOR = new ByteArrayComparator() {
84      @Override
85      public int compare(byte[] l, byte[] r) {
86        if (l == null && r == null)
87          return 0;
88        if (l == null)
89          return 1;
90        if (r == null)
91          return -1;
92        return super.compare(l, r);
93      }
94    };
95  
96    /**
97     * SPECIAL CASE wrapper for empty end key
98     * 
99     * @return ENDKEY if end key is empty, else normal endkey.
100    */
101   private static <R extends KeyRange> byte[] specialEndKey(R range) {
102     byte[] end = range.getEndKey();
103     if (end.length == 0) {
104       return ENDKEY;
105     }
106     return end;
107   }
108 
109   /**
110    * Adds an edge to the split calculator
111    * 
112    * @return true if is included, false if backwards/invalid
113    */
114   public boolean add(R range) {
115     byte[] start = range.getStartKey();
116     byte[] end = specialEndKey(range);
117 
118     if (end != ENDKEY && Bytes.compareTo(start, end) > 0) {
119       // don't allow backwards edges
120       LOG.debug("attempted to add backwards edge: " + Bytes.toString(start)
121           + " " + Bytes.toString(end));
122       return false;
123     }
124 
125     splits.add(start);
126     splits.add(end);
127     starts.put(start, range);
128     return true;
129   }
130 
131   /**
132    * Generates a coverage multimap from split key to Regions that start with the
133    * split key.
134    * 
135    * @return coverage multimap
136    */
137   public Multimap<byte[], R> calcCoverage() {
138     // This needs to be sorted to force the use of the comparator on the values,
139     // otherwise byte array comparison isn't used
140     Multimap<byte[], R> regions = TreeMultimap.create(BYTES_COMPARATOR,
141         rangeCmp);
142 
143     // march through all splits from the start points
144     for (Entry<byte[], Collection<R>> start : starts.asMap().entrySet()) {
145       byte[] key = start.getKey();
146       for (R r : start.getValue()) {
147         regions.put(key, r);
148 
149         for (byte[] coveredSplit : splits.subSet(r.getStartKey(),
150             specialEndKey(r))) {
151           regions.put(coveredSplit, r);
152         }
153       }
154     }
155     return regions;
156   }
157 
158   public TreeSet<byte[]> getSplits() {
159     return splits;
160   }
161 
162   public Multimap<byte[], R> getStarts() {
163     return starts;
164   }
165 
166   /**
167    * Find specified number of top ranges in a big overlap group.
168    * It could return less if there are not that many top ranges.
169    * Once these top ranges are excluded, the big overlap group will
170    * be broken into ranges with no overlapping, or smaller overlapped
171    * groups, and most likely some holes.
172    *
173    * @param bigOverlap a list of ranges that overlap with each other
174    * @param count the max number of ranges to find
175    * @return a list of ranges that overlap with most others
176    */
177   public static <R extends KeyRange> List<R>
178       findBigRanges(Collection<R> bigOverlap, int count) {
179     List<R> bigRanges = new ArrayList<R>();
180 
181     // The key is the count of overlaps,
182     // The value is a list of ranges that have that many overlaps
183     TreeMap<Integer, List<R>> overlapRangeMap = new TreeMap<Integer, List<R>>();
184     for (R r: bigOverlap) {
185       // Calculates the # of overlaps for each region
186       // and populates rangeOverlapMap
187       byte[] startKey = r.getStartKey();
188       byte[] endKey = specialEndKey(r);
189 
190       int overlappedRegions = 0;
191       for (R rr: bigOverlap) {
192         byte[] start = rr.getStartKey();
193         byte[] end = specialEndKey(rr);
194 
195         if (BYTES_COMPARATOR.compare(startKey, end) < 0
196             && BYTES_COMPARATOR.compare(endKey, start) > 0) {
197           overlappedRegions++;
198         }
199       }
200 
201       // One region always overlaps with itself,
202       // so overlappedRegions should be more than 1
203       // for actual overlaps.
204       if (overlappedRegions > 1) {
205         Integer key = Integer.valueOf(overlappedRegions);
206         List<R> ranges = overlapRangeMap.get(key);
207         if (ranges == null) {
208           ranges = new ArrayList<R>();
209           overlapRangeMap.put(key, ranges);
210         }
211         ranges.add(r);
212       }
213     }
214     int toBeAdded = count;
215     for (Integer key: overlapRangeMap.descendingKeySet()) {
216       List<R> chunk = overlapRangeMap.get(key);
217       int chunkSize = chunk.size();
218       if (chunkSize <= toBeAdded) {
219         bigRanges.addAll(chunk);
220         toBeAdded -= chunkSize;
221         if (toBeAdded > 0) continue;
222       } else {
223         // Try to use the middle chunk in case the overlapping is
224         // chained, for example: [a, c), [b, e), [d, g), [f h)...
225         // In such a case, sideline the middle chunk will break
226         // the group efficiently.
227         int start = (chunkSize - toBeAdded)/2;
228         int end = start + toBeAdded;
229         for (int i = start; i < end; i++) {
230           bigRanges.add(chunk.get(i));
231         }
232       }
233       break;
234     }
235     return bigRanges;
236   }
237 }