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;
20  
21  import java.io.DataInputStream;
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.Arrays;
25  import java.util.List;
26  
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.apache.hadoop.conf.Configuration;
30  import org.apache.hadoop.hbase.KeyValue.KVComparator;
31  import org.apache.hadoop.hbase.classification.InterfaceAudience;
32  import org.apache.hadoop.hbase.classification.InterfaceStability;
33  import org.apache.hadoop.hbase.client.Result;
34  import org.apache.hadoop.hbase.exceptions.DeserializationException;
35  import org.apache.hadoop.hbase.master.RegionState;
36  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
37  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
38  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionInfo;
39  import org.apache.hadoop.hbase.util.ByteStringer;
40  import org.apache.hadoop.hbase.util.Bytes;
41  import org.apache.hadoop.hbase.util.JenkinsHash;
42  import org.apache.hadoop.hbase.util.MD5Hash;
43  import org.apache.hadoop.hbase.util.Pair;
44  import org.apache.hadoop.hbase.util.PairOfSameType;
45  import org.apache.hadoop.io.DataInputBuffer;
46  
47  import com.google.protobuf.InvalidProtocolBufferException;
48  
49  /**
50   * Information about a region. A region is a range of keys in the whole keyspace of a table, an
51   * identifier (a timestamp) for differentiating between subset ranges (after region split)
52   * and a replicaId for differentiating the instance for the same range and some status information
53   * about the region.
54   *
55   * The region has a unique name which consists of the following fields:
56   * <li> tableName   : The name of the table </li>
57   * <li> startKey    : The startKey for the region. </li>
58   * <li> regionId    : A timestamp when the region is created. </li>
59   * <li> replicaId   : An id starting from 0 to differentiate replicas of the same region range
60   * but hosted in separated servers. The same region range can be hosted in multiple locations.</li>
61   * <li> encodedName : An MD5 encoded string for the region name.</li>
62   *
63   * <br> Other than the fields in the region name, region info contains:
64   * <li> endKey      : the endKey for the region (exclusive) </li>
65   * <li> split       : Whether the region is split </li>
66   * <li> offline     : Whether the region is offline </li>
67   *
68   * In 0.98 or before, a list of table's regions would fully cover the total keyspace, and at any
69   * point in time, a row key always belongs to a single region, which is hosted in a single server.
70   * In 0.99+, a region can have multiple instances (called replicas), and thus a range (or row) can
71   * correspond to multiple HRegionInfo's. These HRI's share the same fields however except the
72   * replicaId field. If the replicaId is not set, it defaults to 0, which is compatible with the
73   * previous behavior of a range corresponding to 1 region.
74   */
75  @InterfaceAudience.Public
76  @InterfaceStability.Evolving
77  public class HRegionInfo implements Comparable<HRegionInfo> {
78  
79    private static final Log LOG = LogFactory.getLog(HRegionInfo.class);
80  
81    /**
82     * The new format for a region name contains its encodedName at the end.
83     * The encoded name also serves as the directory name for the region
84     * in the filesystem.
85     *
86     * New region name format:
87     *    &lt;tablename>,,&lt;startkey>,&lt;regionIdTimestamp>.&lt;encodedName>.
88     * where,
89     *    &lt;encodedName> is a hex version of the MD5 hash of
90     *    &lt;tablename>,&lt;startkey>,&lt;regionIdTimestamp>
91     *
92     * The old region name format:
93     *    &lt;tablename>,&lt;startkey>,&lt;regionIdTimestamp>
94     * For region names in the old format, the encoded name is a 32-bit
95     * JenkinsHash integer value (in its decimal notation, string form).
96     *<p>
97     * **NOTE**
98     *
99     * The first hbase:meta region, and regions created by an older
100    * version of HBase (0.20 or prior) will continue to use the
101    * old region name format.
102    */
103 
104   /** Separator used to demarcate the encodedName in a region name
105    * in the new format. See description on new format above.
106    */
107   private static final int ENC_SEPARATOR = '.';
108   public  static final int MD5_HEX_LENGTH   = 32;
109 
110   /** A non-capture group so that this can be embedded. */
111   public static final String ENCODED_REGION_NAME_REGEX = "(?:[a-f0-9]+)";
112 
113   // to keep appended int's sorted in string format. Only allows 2 bytes to be
114   // sorted for replicaId
115   public static final String REPLICA_ID_FORMAT = "%04X";
116 
117   public static final byte REPLICA_ID_DELIMITER = (byte)'_';
118 
119   private static final int MAX_REPLICA_ID = 0xFFFF;
120   public static final int DEFAULT_REPLICA_ID = 0;
121   /**
122    * Does region name contain its encoded name?
123    * @param regionName region name
124    * @return boolean indicating if this a new format region
125    *         name which contains its encoded name.
126    */
127   private static boolean hasEncodedName(final byte[] regionName) {
128     // check if region name ends in ENC_SEPARATOR
129     if ((regionName.length >= 1)
130         && (regionName[regionName.length - 1] == ENC_SEPARATOR)) {
131       // region name is new format. it contains the encoded name.
132       return true;
133     }
134     return false;
135   }
136 
137   /**
138    * @param regionName
139    * @return the encodedName
140    */
141   public static String encodeRegionName(final byte [] regionName) {
142     String encodedName;
143     if (hasEncodedName(regionName)) {
144       // region is in new format:
145       // <tableName>,<startKey>,<regionIdTimeStamp>/encodedName/
146       encodedName = Bytes.toString(regionName,
147           regionName.length - MD5_HEX_LENGTH - 1,
148           MD5_HEX_LENGTH);
149     } else {
150       // old format region name. First hbase:meta region also
151       // use this format.EncodedName is the JenkinsHash value.
152       int hashVal = Math.abs(JenkinsHash.getInstance().hash(regionName,
153         regionName.length, 0));
154       encodedName = String.valueOf(hashVal);
155     }
156     return encodedName;
157   }
158 
159   /**
160    * @return Return a short, printable name for this region (usually encoded name) for us logging.
161    */
162   public String getShortNameToLog() {
163     return prettyPrint(this.getEncodedName());
164   }
165 
166   /**
167    * Use logging.
168    * @param encodedRegionName The encoded regionname.
169    * @return <code>hbase:meta</code> if passed <code>1028785192</code> else returns
170    * <code>encodedRegionName</code>
171    */
172   public static String prettyPrint(final String encodedRegionName) {
173     if (encodedRegionName.equals("1028785192")) {
174       return encodedRegionName + "/hbase:meta";
175     }
176     return encodedRegionName;
177   }
178 
179   private byte [] endKey = HConstants.EMPTY_BYTE_ARRAY;
180   // This flag is in the parent of a split while the parent is still referenced
181   // by daughter regions.  We USED to set this flag when we disabled a table
182   // but now table state is kept up in zookeeper as of 0.90.0 HBase.
183   private boolean offLine = false;
184   private long regionId = -1;
185   private transient byte [] regionName = HConstants.EMPTY_BYTE_ARRAY;
186   private boolean split = false;
187   private byte [] startKey = HConstants.EMPTY_BYTE_ARRAY;
188   private int hashCode = -1;
189   //TODO: Move NO_HASH to HStoreFile which is really the only place it is used.
190   public static final String NO_HASH = null;
191   private String encodedName = null;
192   private byte [] encodedNameAsBytes = null;
193   private int replicaId = DEFAULT_REPLICA_ID;
194 
195   // Current TableName
196   private TableName tableName = null;
197   final static String DISPLAY_KEYS_KEY = "hbase.display.keys";
198   public final static byte[] HIDDEN_END_KEY = Bytes.toBytes("hidden-end-key");
199   public final static byte[] HIDDEN_START_KEY = Bytes.toBytes("hidden-start-key");
200 
201   /** HRegionInfo for first meta region */
202   public static final HRegionInfo FIRST_META_REGIONINFO =
203       new HRegionInfo(1L, TableName.META_TABLE_NAME);
204 
205   private void setHashCode() {
206     int result = Arrays.hashCode(this.regionName);
207     result ^= this.regionId;
208     result ^= Arrays.hashCode(this.startKey);
209     result ^= Arrays.hashCode(this.endKey);
210     result ^= Boolean.valueOf(this.offLine).hashCode();
211     result ^= Arrays.hashCode(this.tableName.getName());
212     result ^= this.replicaId;
213     this.hashCode = result;
214   }
215 
216 
217   /**
218    * Private constructor used constructing HRegionInfo for the
219    * first meta regions
220    */
221   private HRegionInfo(long regionId, TableName tableName) {
222     super();
223     this.regionId = regionId;
224     this.tableName = tableName;
225     // Note: First Meta regions names are still in old format
226     this.regionName = createRegionName(tableName, null,
227                                        regionId, false);
228     setHashCode();
229   }
230 
231   /** Default constructor - creates empty object
232    * @deprecated Used by Writables and Writables are going away.
233    */
234   @Deprecated
235   public HRegionInfo() {
236     super();
237   }
238 
239   public HRegionInfo(final TableName tableName) {
240     this(tableName, null, null);
241   }
242 
243   /**
244    * Construct HRegionInfo with explicit parameters
245    *
246    * @param tableName the table name
247    * @param startKey first key in region
248    * @param endKey end of key range
249    * @throws IllegalArgumentException
250    */
251   public HRegionInfo(final TableName tableName, final byte[] startKey, final byte[] endKey)
252   throws IllegalArgumentException {
253     this(tableName, startKey, endKey, false);
254   }
255 
256   /**
257    * Construct HRegionInfo with explicit parameters
258    *
259    * @param tableName the table descriptor
260    * @param startKey first key in region
261    * @param endKey end of key range
262    * @param split true if this region has split and we have daughter regions
263    * regions that may or may not hold references to this region.
264    * @throws IllegalArgumentException
265    */
266   public HRegionInfo(final TableName tableName, final byte[] startKey, final byte[] endKey,
267       final boolean split)
268   throws IllegalArgumentException {
269     this(tableName, startKey, endKey, split, System.currentTimeMillis());
270   }
271 
272   /**
273    * Construct HRegionInfo with explicit parameters
274    *
275    * @param tableName the table descriptor
276    * @param startKey first key in region
277    * @param endKey end of key range
278    * @param split true if this region has split and we have daughter regions
279    * regions that may or may not hold references to this region.
280    * @param regionid Region id to use.
281    * @throws IllegalArgumentException
282    */
283   public HRegionInfo(final TableName tableName, final byte[] startKey,
284                      final byte[] endKey, final boolean split, final long regionid)
285   throws IllegalArgumentException {
286     this(tableName, startKey, endKey, split, regionid, DEFAULT_REPLICA_ID);
287   }
288 
289   /**
290    * Construct HRegionInfo with explicit parameters
291    *
292    * @param tableName the table descriptor
293    * @param startKey first key in region
294    * @param endKey end of key range
295    * @param split true if this region has split and we have daughter regions
296    * regions that may or may not hold references to this region.
297    * @param regionid Region id to use.
298    * @param replicaId the replicaId to use
299    * @throws IllegalArgumentException
300    */
301   public HRegionInfo(final TableName tableName, final byte[] startKey,
302                      final byte[] endKey, final boolean split, final long regionid,
303                      final int replicaId)
304     throws IllegalArgumentException {
305     super();
306     if (tableName == null) {
307       throw new IllegalArgumentException("TableName cannot be null");
308     }
309     this.tableName = tableName;
310     this.offLine = false;
311     this.regionId = regionid;
312     this.replicaId = replicaId;
313     if (this.replicaId > MAX_REPLICA_ID) {
314       throw new IllegalArgumentException("ReplicaId cannot be greater than" + MAX_REPLICA_ID);
315     }
316 
317     this.regionName = createRegionName(this.tableName, startKey, regionId, replicaId, true);
318 
319     this.split = split;
320     this.endKey = endKey == null? HConstants.EMPTY_END_ROW: endKey.clone();
321     this.startKey = startKey == null?
322       HConstants.EMPTY_START_ROW: startKey.clone();
323     this.tableName = tableName;
324     setHashCode();
325   }
326 
327   /**
328    * Costruct a copy of another HRegionInfo
329    *
330    * @param other
331    */
332   public HRegionInfo(HRegionInfo other) {
333     super();
334     this.endKey = other.getEndKey();
335     this.offLine = other.isOffline();
336     this.regionId = other.getRegionId();
337     this.regionName = other.getRegionName();
338     this.split = other.isSplit();
339     this.startKey = other.getStartKey();
340     this.hashCode = other.hashCode();
341     this.encodedName = other.getEncodedName();
342     this.tableName = other.tableName;
343     this.replicaId = other.replicaId;
344   }
345 
346   public HRegionInfo(HRegionInfo other, int replicaId) {
347     this(other);
348     this.replicaId = replicaId;
349     this.setHashCode();
350   }
351 
352   /**
353    * Make a region name of passed parameters.
354    * @param tableName
355    * @param startKey Can be null
356    * @param regionid Region id (Usually timestamp from when region was created).
357    * @param newFormat should we create the region name in the new format
358    *                  (such that it contains its encoded name?).
359    * @return Region name made of passed tableName, startKey and id
360    */
361   public static byte [] createRegionName(final TableName tableName,
362       final byte [] startKey, final long regionid, boolean newFormat) {
363     return createRegionName(tableName, startKey, Long.toString(regionid), newFormat);
364   }
365 
366   /**
367    * Make a region name of passed parameters.
368    * @param tableName
369    * @param startKey Can be null
370    * @param id Region id (Usually timestamp from when region was created).
371    * @param newFormat should we create the region name in the new format
372    *                  (such that it contains its encoded name?).
373    * @return Region name made of passed tableName, startKey and id
374    */
375   public static byte [] createRegionName(final TableName tableName,
376       final byte [] startKey, final String id, boolean newFormat) {
377     return createRegionName(tableName, startKey, Bytes.toBytes(id), newFormat);
378   }
379 
380   /**
381    * Make a region name of passed parameters.
382    * @param tableName
383    * @param startKey Can be null
384    * @param regionid Region id (Usually timestamp from when region was created).
385    * @param replicaId
386    * @param newFormat should we create the region name in the new format
387    *                  (such that it contains its encoded name?).
388    * @return Region name made of passed tableName, startKey, id and replicaId
389    */
390   public static byte [] createRegionName(final TableName tableName,
391       final byte [] startKey, final long regionid, int replicaId, boolean newFormat) {
392     return createRegionName(tableName, startKey, Bytes.toBytes(Long.toString(regionid)),
393         replicaId, newFormat);
394   }
395 
396   /**
397    * Make a region name of passed parameters.
398    * @param tableName
399    * @param startKey Can be null
400    * @param id Region id (Usually timestamp from when region was created).
401    * @param newFormat should we create the region name in the new format
402    *                  (such that it contains its encoded name?).
403    * @return Region name made of passed tableName, startKey and id
404    */
405   public static byte [] createRegionName(final TableName tableName,
406       final byte [] startKey, final byte [] id, boolean newFormat) {
407     return createRegionName(tableName, startKey, id, DEFAULT_REPLICA_ID, newFormat);
408   }
409   /**
410    * Make a region name of passed parameters.
411    * @param tableName
412    * @param startKey Can be null
413    * @param id Region id (Usually timestamp from when region was created).
414    * @param replicaId
415    * @param newFormat should we create the region name in the new format
416    * @return Region name made of passed tableName, startKey, id and replicaId
417    */
418   public static byte [] createRegionName(final TableName tableName,
419       final byte [] startKey, final byte [] id, final int replicaId, boolean newFormat) {
420     int len = tableName.getName().length + 2 + id.length +
421         (startKey == null? 0: startKey.length);
422     if (newFormat) {
423       len += MD5_HEX_LENGTH + 2;
424     }
425     byte[] replicaIdBytes = null;
426     // Special casing: replicaId is only appended if replicaId is greater than
427     // 0. This is because all regions in meta would have to be migrated to the new
428     // name otherwise
429     if (replicaId > 0) {
430       // use string representation for replica id
431       replicaIdBytes = Bytes.toBytes(String.format(REPLICA_ID_FORMAT, replicaId));
432       len += 1 + replicaIdBytes.length;
433     }
434 
435     byte [] b = new byte [len];
436 
437     int offset = tableName.getName().length;
438     System.arraycopy(tableName.getName(), 0, b, 0, offset);
439     b[offset++] = HConstants.DELIMITER;
440     if (startKey != null && startKey.length > 0) {
441       System.arraycopy(startKey, 0, b, offset, startKey.length);
442       offset += startKey.length;
443     }
444     b[offset++] = HConstants.DELIMITER;
445     System.arraycopy(id, 0, b, offset, id.length);
446     offset += id.length;
447 
448     if (replicaIdBytes != null) {
449       b[offset++] = REPLICA_ID_DELIMITER;
450       System.arraycopy(replicaIdBytes, 0, b, offset, replicaIdBytes.length);
451       offset += replicaIdBytes.length;
452     }
453 
454     if (newFormat) {
455       //
456       // Encoded name should be built into the region name.
457       //
458       // Use the region name thus far (namely, <tablename>,<startKey>,<id>_<replicaId>)
459       // to compute a MD5 hash to be used as the encoded name, and append
460       // it to the byte buffer.
461       //
462       String md5Hash = MD5Hash.getMD5AsHex(b, 0, offset);
463       byte [] md5HashBytes = Bytes.toBytes(md5Hash);
464 
465       if (md5HashBytes.length != MD5_HEX_LENGTH) {
466         LOG.error("MD5-hash length mismatch: Expected=" + MD5_HEX_LENGTH +
467                   "; Got=" + md5HashBytes.length);
468       }
469 
470       // now append the bytes '.<encodedName>.' to the end
471       b[offset++] = ENC_SEPARATOR;
472       System.arraycopy(md5HashBytes, 0, b, offset, MD5_HEX_LENGTH);
473       offset += MD5_HEX_LENGTH;
474       b[offset++] = ENC_SEPARATOR;
475     }
476 
477     return b;
478   }
479 
480   /**
481    * Gets the table name from the specified region name.
482    * @param regionName
483    * @return Table name.
484    * @deprecated Since 0.96.0; use #getTable(byte[])
485    */
486   @Deprecated
487   public static byte [] getTableName(byte[] regionName) {
488     int offset = -1;
489     for (int i = 0; i < regionName.length; i++) {
490       if (regionName[i] == HConstants.DELIMITER) {
491         offset = i;
492         break;
493       }
494     }
495     byte[] buff  = new byte[offset];
496     System.arraycopy(regionName, 0, buff, 0, offset);
497     return buff;
498   }
499 
500 
501   /**
502    * Gets the table name from the specified region name.
503    * Like {@link #getTableName(byte[])} only returns a {@link TableName} rather than a byte array.
504    * @param regionName
505    * @return Table name
506    * @see #getTableName(byte[])
507    */
508   public static TableName getTable(final byte [] regionName) {
509     return TableName.valueOf(getTableName(regionName));
510   }
511 
512   /**
513    * Gets the start key from the specified region name.
514    * @param regionName
515    * @return Start key.
516    */
517   public static byte[] getStartKey(final byte[] regionName) throws IOException {
518     return parseRegionName(regionName)[1];
519   }
520 
521   /**
522    * Separate elements of a regionName.
523    * @param regionName
524    * @return Array of byte[] containing tableName, startKey and id
525    * @throws IOException
526    */
527   public static byte [][] parseRegionName(final byte [] regionName)
528   throws IOException {
529     // Region name is of the format:
530     // tablename,startkey,regionIdTimestamp[_replicaId][.encodedName.]
531     // startkey can contain the delimiter (',') so we parse from the start and end
532 
533     // parse from start
534     int offset = -1;
535     for (int i = 0; i < regionName.length; i++) {
536       if (regionName[i] == HConstants.DELIMITER) {
537         offset = i;
538         break;
539       }
540     }
541     if (offset == -1) {
542       throw new IOException("Invalid regionName format: " + Bytes.toStringBinary(regionName));
543     }
544     byte[] tableName = new byte[offset];
545     System.arraycopy(regionName, 0, tableName, 0, offset);
546     offset = -1;
547 
548     int endOffset = regionName.length;
549     // check whether regionName contains encodedName
550     if (regionName.length > MD5_HEX_LENGTH + 2
551         && regionName[regionName.length-1] == ENC_SEPARATOR
552         && regionName[regionName.length-MD5_HEX_LENGTH-2] == ENC_SEPARATOR) {
553       endOffset = endOffset - MD5_HEX_LENGTH - 2;
554     }
555 
556     // parse from end
557     byte[] replicaId = null;
558     int idEndOffset = endOffset;
559     for (int i = endOffset - 1; i > 0; i--) {
560       if (regionName[i] == REPLICA_ID_DELIMITER) { //replicaId may or may not be present
561         replicaId = new byte[endOffset - i - 1];
562         System.arraycopy(regionName, i + 1, replicaId, 0,
563           endOffset - i - 1);
564         idEndOffset = i;
565         // do not break, continue to search for id
566       }
567       if (regionName[i] == HConstants.DELIMITER) {
568         offset = i;
569         break;
570       }
571     }
572     if (offset == -1) {
573       throw new IOException("Invalid regionName format: " + Bytes.toStringBinary(regionName));
574     }
575     byte [] startKey = HConstants.EMPTY_BYTE_ARRAY;
576     if(offset != tableName.length + 1) {
577       startKey = new byte[offset - tableName.length - 1];
578       System.arraycopy(regionName, tableName.length + 1, startKey, 0,
579           offset - tableName.length - 1);
580     }
581     byte [] id = new byte[idEndOffset - offset - 1];
582     System.arraycopy(regionName, offset + 1, id, 0,
583       idEndOffset - offset - 1);
584     byte [][] elements = new byte[replicaId == null ? 3 : 4][];
585     elements[0] = tableName;
586     elements[1] = startKey;
587     elements[2] = id;
588     if (replicaId != null) {
589       elements[3] = replicaId;
590     }
591 
592     return elements;
593   }
594 
595   /** @return the regionId */
596   public long getRegionId(){
597     return regionId;
598   }
599 
600   /**
601    * @return the regionName as an array of bytes.
602    * @see #getRegionNameAsString()
603    */
604   public byte [] getRegionName(){
605     return regionName;
606   }
607 
608   /**
609    * @return Region name as a String for use in logging, etc.
610    */
611   public String getRegionNameAsString() {
612     if (hasEncodedName(this.regionName)) {
613       // new format region names already have their encoded name.
614       return Bytes.toStringBinary(this.regionName);
615     }
616 
617     // old format. regionNameStr doesn't have the region name.
618     //
619     //
620     return Bytes.toStringBinary(this.regionName) + "." + this.getEncodedName();
621   }
622 
623   /** @return the encoded region name */
624   public synchronized String getEncodedName() {
625     if (this.encodedName == null) {
626       this.encodedName = encodeRegionName(this.regionName);
627     }
628     return this.encodedName;
629   }
630 
631   public synchronized byte [] getEncodedNameAsBytes() {
632     if (this.encodedNameAsBytes == null) {
633       this.encodedNameAsBytes = Bytes.toBytes(getEncodedName());
634     }
635     return this.encodedNameAsBytes;
636   }
637 
638   /** @return the startKey */
639   public byte [] getStartKey(){
640     return startKey;
641   }
642 
643   /** @return the endKey */
644   public byte [] getEndKey(){
645     return endKey;
646   }
647 
648   /**
649    * Get current table name of the region
650    * @return byte array of table name
651    * @deprecated Since 0.96.0; use #getTable()
652    */
653   @Deprecated
654   public byte [] getTableName() {
655     return getTable().toBytes();
656   }
657 
658   /**
659    * Get current table name of the region
660    * @return TableName
661    * @see #getTableName()
662    */
663   public TableName getTable() {
664     // This method name should be getTableName but there was already a method getTableName
665     // that returned a byte array.  It is unfortunate given everwhere else, getTableName returns
666     // a TableName instance.
667     if (tableName == null || tableName.getName().length == 0) {
668       tableName = getTable(getRegionName());
669     }
670     return this.tableName;
671   }
672 
673   /**
674    * Returns true if the given inclusive range of rows is fully contained
675    * by this region. For example, if the region is foo,a,g and this is
676    * passed ["b","c"] or ["a","c"] it will return true, but if this is passed
677    * ["b","z"] it will return false.
678    * @throws IllegalArgumentException if the range passed is invalid (ie end < start)
679    */
680   public boolean containsRange(byte[] rangeStartKey, byte[] rangeEndKey) {
681     if (Bytes.compareTo(rangeStartKey, rangeEndKey) > 0) {
682       throw new IllegalArgumentException(
683       "Invalid range: " + Bytes.toStringBinary(rangeStartKey) +
684       " > " + Bytes.toStringBinary(rangeEndKey));
685     }
686 
687     boolean firstKeyInRange = Bytes.compareTo(rangeStartKey, startKey) >= 0;
688     boolean lastKeyInRange =
689       Bytes.compareTo(rangeEndKey, endKey) < 0 ||
690       Bytes.equals(endKey, HConstants.EMPTY_BYTE_ARRAY);
691     return firstKeyInRange && lastKeyInRange;
692   }
693 
694   /**
695    * Return true if the given row falls in this region.
696    */
697   public boolean containsRow(byte[] row) {
698     return Bytes.compareTo(row, startKey) >= 0 &&
699       (Bytes.compareTo(row, endKey) < 0 ||
700        Bytes.equals(endKey, HConstants.EMPTY_BYTE_ARRAY));
701   }
702 
703   /**
704    * @return true if this region is from hbase:meta
705    */
706   public boolean isMetaTable() {
707     return isMetaRegion();
708   }
709 
710   /** @return true if this region is a meta region */
711   public boolean isMetaRegion() {
712      return tableName.equals(HRegionInfo.FIRST_META_REGIONINFO.getTable());
713   }
714 
715   /**
716    * @return True if has been split and has daughters.
717    */
718   public boolean isSplit() {
719     return this.split;
720   }
721 
722   /**
723    * @param split set split status
724    */
725   public void setSplit(boolean split) {
726     this.split = split;
727   }
728 
729   /**
730    * @return True if this region is offline.
731    */
732   public boolean isOffline() {
733     return this.offLine;
734   }
735 
736   /**
737    * The parent of a region split is offline while split daughters hold
738    * references to the parent. Offlined regions are closed.
739    * @param offLine Set online/offline status.
740    */
741   public void setOffline(boolean offLine) {
742     this.offLine = offLine;
743   }
744 
745   /**
746    * @return True if this is a split parent region.
747    */
748   public boolean isSplitParent() {
749     if (!isSplit()) return false;
750     if (!isOffline()) {
751       LOG.warn("Region is split but NOT offline: " + getRegionNameAsString());
752     }
753     return true;
754   }
755 
756   /**
757    * Returns the region replica id
758    * @return returns region replica id
759    */
760   public int getReplicaId() {
761     return replicaId;
762   }
763 
764   /**
765    * @see java.lang.Object#toString()
766    */
767   @Override
768   public String toString() {
769     return "{ENCODED => " + getEncodedName() + ", " +
770       HConstants.NAME + " => '" + Bytes.toStringBinary(this.regionName)
771       + "', STARTKEY => '" +
772       Bytes.toStringBinary(this.startKey) + "', ENDKEY => '" +
773       Bytes.toStringBinary(this.endKey) + "'" +
774       (isOffline()? ", OFFLINE => true": "") +
775       (isSplit()? ", SPLIT => true": "") +
776       ((replicaId > 0)? ", REPLICA_ID => " + replicaId : "") + "}";
777   }
778 
779   /**
780    * @see java.lang.Object#equals(java.lang.Object)
781    */
782   @Override
783   public boolean equals(Object o) {
784     if (this == o) {
785       return true;
786     }
787     if (o == null) {
788       return false;
789     }
790     if (!(o instanceof HRegionInfo)) {
791       return false;
792     }
793     return this.compareTo((HRegionInfo)o) == 0;
794   }
795 
796   /**
797    * @see java.lang.Object#hashCode()
798    */
799   @Override
800   public int hashCode() {
801     return this.hashCode;
802   }
803 
804   //
805   // Comparable
806   //
807 
808   @Override
809   public int compareTo(HRegionInfo o) {
810     if (o == null) {
811       return 1;
812     }
813 
814     // Are regions of same table?
815     int result = this.tableName.compareTo(o.tableName);
816     if (result != 0) {
817       return result;
818     }
819 
820     // Compare start keys.
821     result = Bytes.compareTo(this.startKey, o.startKey);
822     if (result != 0) {
823       return result;
824     }
825 
826     // Compare end keys.
827     result = Bytes.compareTo(this.endKey, o.endKey);
828 
829     if (result != 0) {
830       if (this.getStartKey().length != 0
831               && this.getEndKey().length == 0) {
832           return 1; // this is last region
833       }
834       if (o.getStartKey().length != 0
835               && o.getEndKey().length == 0) {
836           return -1; // o is the last region
837       }
838       return result;
839     }
840 
841     // regionId is usually milli timestamp -- this defines older stamps
842     // to be "smaller" than newer stamps in sort order.
843     if (this.regionId > o.regionId) {
844       return 1;
845     } else if (this.regionId < o.regionId) {
846       return -1;
847     }
848 
849     int replicaDiff = this.getReplicaId() - o.getReplicaId();
850     if (replicaDiff != 0) return replicaDiff;
851 
852     if (this.offLine == o.offLine)
853       return 0;
854     if (this.offLine == true) return -1;
855 
856     return 1;
857   }
858 
859   /**
860    * @return Comparator to use comparing {@link KeyValue}s.
861    */
862   public KVComparator getComparator() {
863     return isMetaRegion()?
864       KeyValue.META_COMPARATOR: KeyValue.COMPARATOR;
865   }
866 
867   /**
868    * Convert a HRegionInfo to a RegionInfo
869    *
870    * @return the converted RegionInfo
871    */
872   RegionInfo convert() {
873     return convert(this);
874   }
875 
876   /**
877    * Convert a HRegionInfo to a RegionInfo
878    *
879    * @param info the HRegionInfo to convert
880    * @return the converted RegionInfo
881    */
882   public static RegionInfo convert(final HRegionInfo info) {
883     if (info == null) return null;
884     RegionInfo.Builder builder = RegionInfo.newBuilder();
885     builder.setTableName(ProtobufUtil.toProtoTableName(info.getTable()));
886     builder.setRegionId(info.getRegionId());
887     if (info.getStartKey() != null) {
888       builder.setStartKey(ByteStringer.wrap(info.getStartKey()));
889     }
890     if (info.getEndKey() != null) {
891       builder.setEndKey(ByteStringer.wrap(info.getEndKey()));
892     }
893     builder.setOffline(info.isOffline());
894     builder.setSplit(info.isSplit());
895     builder.setReplicaId(info.getReplicaId());
896     return builder.build();
897   }
898 
899   /**
900    * Convert a RegionInfo to a HRegionInfo
901    *
902    * @param proto the RegionInfo to convert
903    * @return the converted HRegionInfho
904    */
905   public static HRegionInfo convert(final RegionInfo proto) {
906     if (proto == null) return null;
907     TableName tableName =
908         ProtobufUtil.toTableName(proto.getTableName());
909     if (tableName.equals(TableName.META_TABLE_NAME)) {
910       return FIRST_META_REGIONINFO;
911     }
912     long regionId = proto.getRegionId();
913     int replicaId = proto.hasReplicaId() ? proto.getReplicaId() : DEFAULT_REPLICA_ID;
914     byte[] startKey = null;
915     byte[] endKey = null;
916     if (proto.hasStartKey()) {
917       startKey = proto.getStartKey().toByteArray();
918     }
919     if (proto.hasEndKey()) {
920       endKey = proto.getEndKey().toByteArray();
921     }
922     boolean split = false;
923     if (proto.hasSplit()) {
924       split = proto.getSplit();
925     }
926     HRegionInfo hri = new HRegionInfo(
927         tableName,
928         startKey,
929         endKey, split, regionId, replicaId);
930     if (proto.hasOffline()) {
931       hri.setOffline(proto.getOffline());
932     }
933     return hri;
934   }
935 
936   /**
937    * @return This instance serialized as protobuf w/ a magic pb prefix.
938    * @see #parseFrom(byte[])
939    */
940   public byte [] toByteArray() {
941     byte [] bytes = convert().toByteArray();
942     return ProtobufUtil.prependPBMagic(bytes);
943   }
944 
945   /**
946    * @return A deserialized {@link HRegionInfo}
947    * or null if we failed deserialize or passed bytes null
948    * @see #toByteArray()
949    */
950   public static HRegionInfo parseFromOrNull(final byte [] bytes) {
951     if (bytes == null) return null;
952     return parseFromOrNull(bytes, 0, bytes.length);
953   }
954 
955   /**
956    * @return A deserialized {@link HRegionInfo} or null
957    *  if we failed deserialize or passed bytes null
958    * @see #toByteArray()
959    */
960   public static HRegionInfo parseFromOrNull(final byte [] bytes, int offset, int len) {
961     if (bytes == null || len <= 0) return null;
962     try {
963       return parseFrom(bytes, offset, len);
964     } catch (DeserializationException e) {
965       return null;
966     }
967   }
968 
969   /**
970    * @param bytes A pb RegionInfo serialized with a pb magic prefix.
971    * @return A deserialized {@link HRegionInfo}
972    * @throws DeserializationException
973    * @see #toByteArray()
974    */
975   public static HRegionInfo parseFrom(final byte [] bytes) throws DeserializationException {
976     if (bytes == null) return null;
977     return parseFrom(bytes, 0, bytes.length);
978   }
979 
980   /**
981    * @param bytes A pb RegionInfo serialized with a pb magic prefix.
982    * @param offset starting point in the byte array
983    * @param len length to read on the byte array
984    * @return A deserialized {@link HRegionInfo}
985    * @throws DeserializationException
986    * @see #toByteArray()
987    */
988   public static HRegionInfo parseFrom(final byte [] bytes, int offset, int len)
989       throws DeserializationException {
990     if (ProtobufUtil.isPBMagicPrefix(bytes, offset, len)) {
991       int pblen = ProtobufUtil.lengthOfPBMagic();
992       try {
993         HBaseProtos.RegionInfo ri =
994             HBaseProtos.RegionInfo.newBuilder().
995                 mergeFrom(bytes, pblen + offset, len - pblen).build();
996         return convert(ri);
997       } catch (InvalidProtocolBufferException e) {
998         throw new DeserializationException(e);
999       }
1000     } else {
1001       throw new DeserializationException("PB encoded HRegionInfo expected");
1002     }
1003   }
1004 
1005   /**
1006    * Use this instead of {@link #toByteArray()} when writing to a stream and you want to use
1007    * the pb mergeDelimitedFrom (w/o the delimiter, pb reads to EOF which may not be what you want).
1008    * @return This instance serialized as a delimited protobuf w/ a magic pb prefix.
1009    * @throws IOException
1010    * @see #toByteArray()
1011    */
1012   public byte [] toDelimitedByteArray() throws IOException {
1013     return ProtobufUtil.toDelimitedByteArray(convert());
1014   }
1015 
1016   /**
1017    * Get the descriptive name as {@link RegionState} does it but with hidden
1018    * startkey optionally
1019    * @param state
1020    * @param conf
1021    * @return descriptive string
1022    */
1023   public static String getDescriptiveNameFromRegionStateForDisplay(RegionState state,
1024       Configuration conf) {
1025     if (conf.getBoolean(DISPLAY_KEYS_KEY, true)) return state.toDescriptiveString();
1026     String descriptiveStringFromState = state.toDescriptiveString();
1027     int idx = descriptiveStringFromState.lastIndexOf(" state=");
1028     String regionName = getRegionNameAsStringForDisplay(state.getRegion(), conf);
1029     return regionName + descriptiveStringFromState.substring(idx);
1030   }
1031 
1032   /**
1033    * Get the end key for display. Optionally hide the real end key. 
1034    * @param hri
1035    * @param conf
1036    * @return the endkey
1037    */
1038   public static byte[] getEndKeyForDisplay(HRegionInfo hri, Configuration conf) {
1039     boolean displayKey = conf.getBoolean(DISPLAY_KEYS_KEY, true);
1040     if (displayKey) return hri.getEndKey();
1041     return HIDDEN_END_KEY;
1042   }
1043 
1044   /**
1045    * Get the start key for display. Optionally hide the real start key. 
1046    * @param hri
1047    * @param conf
1048    * @return the startkey
1049    */
1050   public static byte[] getStartKeyForDisplay(HRegionInfo hri, Configuration conf) {
1051     boolean displayKey = conf.getBoolean(DISPLAY_KEYS_KEY, true);
1052     if (displayKey) return hri.getStartKey();
1053     return HIDDEN_START_KEY;
1054   }
1055 
1056   /**
1057    * Get the region name for display. Optionally hide the start key.
1058    * @param hri
1059    * @param conf
1060    * @return region name as String
1061    */
1062   public static String getRegionNameAsStringForDisplay(HRegionInfo hri, Configuration conf) {
1063     return Bytes.toStringBinary(getRegionNameForDisplay(hri, conf));
1064   }
1065 
1066   /**
1067    * Get the region name for display. Optionally hide the start key.
1068    * @param hri
1069    * @param conf
1070    * @return region name bytes
1071    */
1072   public static byte[] getRegionNameForDisplay(HRegionInfo hri, Configuration conf) {
1073     boolean displayKey = conf.getBoolean(DISPLAY_KEYS_KEY, true);
1074     if (displayKey || hri.getTable().equals(TableName.META_TABLE_NAME)) {
1075       return hri.getRegionName();
1076     } else {
1077       // create a modified regionname with the startkey replaced but preserving
1078       // the other parts including the encodedname.
1079       try {
1080         byte[][]regionNameParts = parseRegionName(hri.getRegionName());
1081         regionNameParts[1] = HIDDEN_START_KEY; //replace the real startkey
1082         int len = 0;
1083         // get the total length
1084         for (byte[] b : regionNameParts) {
1085           len += b.length;
1086         }
1087         byte[] encodedRegionName =
1088             Bytes.toBytes(encodeRegionName(hri.getRegionName()));
1089         len += encodedRegionName.length;
1090         //allocate some extra bytes for the delimiters and the last '.'
1091         byte[] modifiedName = new byte[len + regionNameParts.length + 1];
1092         int lengthSoFar = 0;
1093         int loopCount = 0;
1094         for (byte[] b : regionNameParts) {
1095           System.arraycopy(b, 0, modifiedName, lengthSoFar, b.length);
1096           lengthSoFar += b.length;
1097           if (loopCount++ == 2) modifiedName[lengthSoFar++] = REPLICA_ID_DELIMITER;
1098           else  modifiedName[lengthSoFar++] = HConstants.DELIMITER;
1099         }
1100         // replace the last comma with '.'
1101         modifiedName[lengthSoFar - 1] = ENC_SEPARATOR;
1102         System.arraycopy(encodedRegionName, 0, modifiedName, lengthSoFar,
1103             encodedRegionName.length);
1104         lengthSoFar += encodedRegionName.length; 
1105         modifiedName[lengthSoFar] = ENC_SEPARATOR;
1106         return modifiedName;
1107       } catch (IOException e) {
1108         //LOG.warn("Encountered exception " + e);
1109         throw new RuntimeException(e);
1110       }
1111     }
1112   }
1113 
1114   /**
1115    * Extract a HRegionInfo and ServerName from catalog table {@link Result}.
1116    * @param r Result to pull from
1117    * @return A pair of the {@link HRegionInfo} and the {@link ServerName}
1118    * (or null for server address if no address set in hbase:meta).
1119    * @throws IOException
1120    * @deprecated use MetaTableAccessor methods for interacting with meta layouts
1121    */
1122   @Deprecated
1123   public static Pair<HRegionInfo, ServerName> getHRegionInfoAndServerName(final Result r) {
1124     HRegionInfo info =
1125       getHRegionInfo(r, HConstants.REGIONINFO_QUALIFIER);
1126     ServerName sn = getServerName(r);
1127     return new Pair<HRegionInfo, ServerName>(info, sn);
1128   }
1129 
1130   /**
1131    * Returns HRegionInfo object from the column
1132    * HConstants.CATALOG_FAMILY:HConstants.REGIONINFO_QUALIFIER of the catalog
1133    * table Result.
1134    * @param data a Result object from the catalog table scan
1135    * @return HRegionInfo or null
1136    * @deprecated use MetaTableAccessor methods for interacting with meta layouts
1137    */
1138   @Deprecated
1139   public static HRegionInfo getHRegionInfo(Result data) {
1140     return getHRegionInfo(data, HConstants.REGIONINFO_QUALIFIER);
1141   }
1142 
1143   /**
1144    * Returns the daughter regions by reading the corresponding columns of the catalog table
1145    * Result.
1146    * @param data a Result object from the catalog table scan
1147    * @return a pair of HRegionInfo or PairOfSameType(null, null) if the region is not a split
1148    * parent
1149    * @deprecated use MetaTableAccessor methods for interacting with meta layouts
1150    */
1151   @Deprecated
1152   public static PairOfSameType<HRegionInfo> getDaughterRegions(Result data) throws IOException {
1153     HRegionInfo splitA = getHRegionInfo(data, HConstants.SPLITA_QUALIFIER);
1154     HRegionInfo splitB = getHRegionInfo(data, HConstants.SPLITB_QUALIFIER);
1155 
1156     return new PairOfSameType<HRegionInfo>(splitA, splitB);
1157   }
1158 
1159   /**
1160    * Returns the merge regions by reading the corresponding columns of the catalog table
1161    * Result.
1162    * @param data a Result object from the catalog table scan
1163    * @return a pair of HRegionInfo or PairOfSameType(null, null) if the region is not a split
1164    * parent
1165    * @deprecated use MetaTableAccessor methods for interacting with meta layouts
1166    */
1167   @Deprecated
1168   public static PairOfSameType<HRegionInfo> getMergeRegions(Result data) throws IOException {
1169     HRegionInfo mergeA = getHRegionInfo(data, HConstants.MERGEA_QUALIFIER);
1170     HRegionInfo mergeB = getHRegionInfo(data, HConstants.MERGEB_QUALIFIER);
1171 
1172     return new PairOfSameType<HRegionInfo>(mergeA, mergeB);
1173   }
1174 
1175   /**
1176    * Returns the HRegionInfo object from the column {@link HConstants#CATALOG_FAMILY} and
1177    * <code>qualifier</code> of the catalog table result.
1178    * @param r a Result object from the catalog table scan
1179    * @param qualifier Column family qualifier -- either
1180    * {@link HConstants#SPLITA_QUALIFIER}, {@link HConstants#SPLITB_QUALIFIER} or
1181    * {@link HConstants#REGIONINFO_QUALIFIER}.
1182    * @return An HRegionInfo instance or null.
1183    * @deprecated use MetaTableAccessor methods for interacting with meta layouts
1184    */
1185   @Deprecated
1186   public static HRegionInfo getHRegionInfo(final Result r, byte [] qualifier) {
1187     Cell cell = r.getColumnLatestCell(
1188         HConstants.CATALOG_FAMILY, qualifier);
1189     if (cell == null) return null;
1190     return parseFromOrNull(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
1191   }
1192 
1193   /**
1194    * @deprecated use MetaTableAccessor methods for interacting with meta layouts
1195    */
1196   @Deprecated
1197   public static ServerName getServerName(final Result r) {
1198     Cell cell = r.getColumnLatestCell(HConstants.CATALOG_FAMILY, HConstants.SERVER_QUALIFIER);
1199     if (cell == null || cell.getValueLength() == 0) return null;
1200     String hostAndPort = Bytes.toString(
1201         cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
1202     cell = r.getColumnLatestCell(HConstants.CATALOG_FAMILY,
1203       HConstants.STARTCODE_QUALIFIER);
1204     if (cell == null || cell.getValueLength() == 0) return null;
1205     try {
1206       return ServerName.valueOf(hostAndPort,
1207           Bytes.toLong(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
1208     } catch (IllegalArgumentException e) {
1209       LOG.error("Ignoring invalid region for server " + hostAndPort + "; cell=" + cell, e);
1210       return null;
1211     }
1212   }
1213 
1214   /**
1215    * The latest seqnum that the server writing to meta observed when opening the region.
1216    * E.g. the seqNum when the result of {@link #getServerName(Result)} was written.
1217    * @param r Result to pull the seqNum from
1218    * @return SeqNum, or HConstants.NO_SEQNUM if there's no value written.
1219    * @deprecated use MetaTableAccessor methods for interacting with meta layouts
1220    */
1221   @Deprecated
1222   public static long getSeqNumDuringOpen(final Result r) {
1223     Cell cell = r.getColumnLatestCell(HConstants.CATALOG_FAMILY, HConstants.SEQNUM_QUALIFIER);
1224     if (cell == null || cell.getValueLength() == 0) return HConstants.NO_SEQNUM;
1225     return Bytes.toLong(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
1226   }
1227 
1228   /**
1229    * Parses an HRegionInfo instance from the passed in stream.  Presumes the HRegionInfo was
1230    * serialized to the stream with {@link #toDelimitedByteArray()}
1231    * @param in
1232    * @return An instance of HRegionInfo.
1233    * @throws IOException
1234    */
1235   public static HRegionInfo parseFrom(final DataInputStream in) throws IOException {
1236     // I need to be able to move back in the stream if this is not a pb serialization so I can
1237     // do the Writable decoding instead.
1238     int pblen = ProtobufUtil.lengthOfPBMagic();
1239     byte [] pbuf = new byte[pblen];
1240     if (in.markSupported()) { //read it with mark()
1241       in.mark(pblen);
1242     }
1243     int read = in.read(pbuf); //assumption: it should be longer than pblen.
1244     if (read != pblen) throw new IOException("read=" + read + ", wanted=" + pblen);
1245     if (ProtobufUtil.isPBMagicPrefix(pbuf)) {
1246       return convert(HBaseProtos.RegionInfo.parseDelimitedFrom(in));
1247     } else {
1248       throw new IOException("PB encoded HRegionInfo expected");
1249     }
1250   }
1251 
1252   /**
1253    * Serializes given HRegionInfo's as a byte array. Use this instead of {@link #toByteArray()} when
1254    * writing to a stream and you want to use the pb mergeDelimitedFrom (w/o the delimiter, pb reads
1255    * to EOF which may not be what you want). {@link #parseDelimitedFrom(byte[], int, int)} can
1256    * be used to read back the instances.
1257    * @param infos HRegionInfo objects to serialize
1258    * @return This instance serialized as a delimited protobuf w/ a magic pb prefix.
1259    * @throws IOException
1260    * @see #toByteArray()
1261    */
1262   public static byte[] toDelimitedByteArray(HRegionInfo... infos) throws IOException {
1263     byte[][] bytes = new byte[infos.length][];
1264     int size = 0;
1265     for (int i = 0; i < infos.length; i++) {
1266       bytes[i] = infos[i].toDelimitedByteArray();
1267       size += bytes[i].length;
1268     }
1269 
1270     byte[] result = new byte[size];
1271     int offset = 0;
1272     for (byte[] b : bytes) {
1273       System.arraycopy(b, 0, result, offset, b.length);
1274       offset += b.length;
1275     }
1276     return result;
1277   }
1278 
1279   /**
1280    * Parses all the HRegionInfo instances from the passed in stream until EOF. Presumes the
1281    * HRegionInfo's were serialized to the stream with {@link #toDelimitedByteArray()}
1282    * @param bytes serialized bytes
1283    * @param offset the start offset into the byte[] buffer
1284    * @param length how far we should read into the byte[] buffer
1285    * @return All the hregioninfos that are in the byte array. Keeps reading till we hit the end.
1286    */
1287   public static List<HRegionInfo> parseDelimitedFrom(final byte[] bytes, final int offset,
1288       final int length) throws IOException {
1289     if (bytes == null) {
1290       throw new IllegalArgumentException("Can't build an object with empty bytes array");
1291     }
1292     DataInputBuffer in = new DataInputBuffer();
1293     List<HRegionInfo> hris = new ArrayList<HRegionInfo>();
1294     try {
1295       in.reset(bytes, offset, length);
1296       while (in.available() > 0) {
1297         HRegionInfo hri = parseFrom(in);
1298         hris.add(hri);
1299       }
1300     } finally {
1301       in.close();
1302     }
1303     return hris;
1304   }
1305 
1306   /**
1307    * Check whether two regions are adjacent
1308    * @param regionA
1309    * @param regionB
1310    * @return true if two regions are adjacent
1311    */
1312   public static boolean areAdjacent(HRegionInfo regionA, HRegionInfo regionB) {
1313     if (regionA == null || regionB == null) {
1314       throw new IllegalArgumentException(
1315           "Can't check whether adjacent for null region");
1316     }
1317     HRegionInfo a = regionA;
1318     HRegionInfo b = regionB;
1319     if (Bytes.compareTo(a.getStartKey(), b.getStartKey()) > 0) {
1320       a = regionB;
1321       b = regionA;
1322     }
1323     if (Bytes.compareTo(a.getEndKey(), b.getStartKey()) == 0) {
1324       return true;
1325     }
1326     return false;
1327   }
1328 }