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