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