001/**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019package org.apache.hadoop.hbase;
020
021import java.io.DataInputStream;
022import java.io.IOException;
023import java.util.ArrayList;
024import java.util.Arrays;
025import java.util.List;
026import java.util.stream.Collectors;
027
028import org.apache.hadoop.conf.Configuration;
029import org.apache.hadoop.hbase.KeyValue.KVComparator;
030import org.apache.hadoop.hbase.client.RegionInfo;
031import org.apache.hadoop.hbase.client.RegionInfoBuilder;
032import org.apache.hadoop.hbase.client.RegionInfoDisplay;
033import org.apache.hadoop.hbase.exceptions.DeserializationException;
034import org.apache.hadoop.hbase.master.RegionState;
035import org.apache.hadoop.hbase.util.Bytes;
036import org.apache.hadoop.io.DataInputBuffer;
037import org.apache.yetus.audience.InterfaceAudience;
038import org.slf4j.Logger;
039import org.slf4j.LoggerFactory;
040import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
041import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos;
042
043/**
044 * Information about a region. A region is a range of keys in the whole keyspace of a table, an
045 * identifier (a timestamp) for differentiating between subset ranges (after region split)
046 * and a replicaId for differentiating the instance for the same range and some status information
047 * about the region.
048 *
049 * The region has a unique name which consists of the following fields:
050 * <ul>
051 * <li> tableName   : The name of the table </li>
052 * <li> startKey    : The startKey for the region. </li>
053 * <li> regionId    : A timestamp when the region is created. </li>
054 * <li> replicaId   : An id starting from 0 to differentiate replicas of the same region range
055 * but hosted in separated servers. The same region range can be hosted in multiple locations.</li>
056 * <li> encodedName : An MD5 encoded string for the region name.</li>
057 * </ul>
058 *
059 * <br> Other than the fields in the region name, region info contains:
060 * <ul>
061 * <li> endKey      : the endKey for the region (exclusive) </li>
062 * <li> split       : Whether the region is split </li>
063 * <li> offline     : Whether the region is offline </li>
064 * </ul>
065 *
066 * In 0.98 or before, a list of table's regions would fully cover the total keyspace, and at any
067 * point in time, a row key always belongs to a single region, which is hosted in a single server.
068 * In 0.99+, a region can have multiple instances (called replicas), and thus a range (or row) can
069 * correspond to multiple HRegionInfo's. These HRI's share the same fields however except the
070 * replicaId field. If the replicaId is not set, it defaults to 0, which is compatible with the
071 * previous behavior of a range corresponding to 1 region.
072 * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0.
073 *             use {@link RegionInfoBuilder} to build {@link RegionInfo}.
074 */
075@Deprecated
076@InterfaceAudience.Public
077public class HRegionInfo implements RegionInfo, Comparable<HRegionInfo> {
078  private static final Logger LOG = LoggerFactory.getLogger(HRegionInfo.class);
079
080  /**
081   * The new format for a region name contains its encodedName at the end.
082   * The encoded name also serves as the directory name for the region
083   * in the filesystem.
084   *
085   * New region name format:
086   *    &lt;tablename>,,&lt;startkey>,&lt;regionIdTimestamp>.&lt;encodedName>.
087   * where,
088   *    &lt;encodedName> is a hex version of the MD5 hash of
089   *    &lt;tablename>,&lt;startkey>,&lt;regionIdTimestamp>
090   *
091   * The old region name format:
092   *    &lt;tablename>,&lt;startkey>,&lt;regionIdTimestamp>
093   * For region names in the old format, the encoded name is a 32-bit
094   * JenkinsHash integer value (in its decimal notation, string form).
095   *<p>
096   * **NOTE**
097   *
098   * The first hbase:meta region, and regions created by an older
099   * version of HBase (0.20 or prior) will continue to use the
100   * old region name format.
101   */
102
103  /** A non-capture group so that this can be embedded. */
104  public static final String ENCODED_REGION_NAME_REGEX = RegionInfoBuilder.ENCODED_REGION_NAME_REGEX;
105
106  private static final int MAX_REPLICA_ID = 0xFFFF;
107
108  /**
109   * @param regionName
110   * @return the encodedName
111   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
112   *             Use {@link org.apache.hadoop.hbase.client.RegionInfo#encodeRegionName(byte[])}.
113   */
114  @Deprecated
115  public static String encodeRegionName(final byte [] regionName) {
116    return RegionInfo.encodeRegionName(regionName);
117  }
118
119  /**
120   * @return Return a short, printable name for this region (usually encoded name) for us logging.
121   */
122  @Override
123  public String getShortNameToLog() {
124    return prettyPrint(this.getEncodedName());
125  }
126
127  /**
128   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
129   *             Use {@link org.apache.hadoop.hbase.client.RegionInfo#getShortNameToLog(RegionInfo...)}.
130   */
131  @Deprecated
132  public static String getShortNameToLog(HRegionInfo...hris) {
133    return RegionInfo.getShortNameToLog(Arrays.asList(hris));
134  }
135
136  /**
137   * @return Return a String of short, printable names for <code>hris</code>
138   * (usually encoded name) for us logging.
139   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
140   *             Use {@link org.apache.hadoop.hbase.client.RegionInfo#getShortNameToLog(List)})}.
141   */
142  @Deprecated
143  public static String getShortNameToLog(final List<HRegionInfo> hris) {
144    return RegionInfo.getShortNameToLog(hris.stream().collect(Collectors.toList()));
145  }
146
147  /**
148   * Use logging.
149   * @param encodedRegionName The encoded regionname.
150   * @return <code>hbase:meta</code> if passed <code>1028785192</code> else returns
151   * <code>encodedRegionName</code>
152   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
153   *             Use {@link RegionInfo#prettyPrint(String)}.
154   */
155  @Deprecated
156  @InterfaceAudience.Private
157  public static String prettyPrint(final String encodedRegionName) {
158    return RegionInfo.prettyPrint(encodedRegionName);
159  }
160
161  private byte [] endKey = HConstants.EMPTY_BYTE_ARRAY;
162  // This flag is in the parent of a split while the parent is still referenced by daughter regions.
163  // We USED to set this flag when we disabled a table but now table state is kept up in zookeeper
164  // as of 0.90.0 HBase. And now in DisableTableProcedure, finally we will create bunch of
165  // UnassignProcedures and at the last of the procedure we will set the region state to CLOSED, and
166  // will not change the offLine flag.
167  private boolean offLine = false;
168  private long regionId = -1;
169  private transient byte [] regionName = HConstants.EMPTY_BYTE_ARRAY;
170  private boolean split = false;
171  private byte [] startKey = HConstants.EMPTY_BYTE_ARRAY;
172  private int hashCode = -1;
173  //TODO: Move NO_HASH to HStoreFile which is really the only place it is used.
174  public static final String NO_HASH = null;
175  private String encodedName = null;
176  private byte [] encodedNameAsBytes = null;
177  private int replicaId = DEFAULT_REPLICA_ID;
178
179  // Current TableName
180  private TableName tableName = null;
181
182  // Duplicated over in RegionInfoDisplay
183  final static String DISPLAY_KEYS_KEY = RegionInfoDisplay.DISPLAY_KEYS_KEY;
184  public final static byte[] HIDDEN_END_KEY = RegionInfoDisplay.HIDDEN_END_KEY;
185  public final static byte[] HIDDEN_START_KEY = RegionInfoDisplay.HIDDEN_START_KEY;
186
187  /** HRegionInfo for first meta region */
188  // TODO: How come Meta regions still do not have encoded region names? Fix.
189  public static final HRegionInfo FIRST_META_REGIONINFO =
190      new HRegionInfo(1L, TableName.META_TABLE_NAME);
191
192  private void setHashCode() {
193    int result = Arrays.hashCode(this.regionName);
194    result = (int) (result ^ this.regionId);
195    result ^= Arrays.hashCode(this.startKey);
196    result ^= Arrays.hashCode(this.endKey);
197    result ^= Boolean.valueOf(this.offLine).hashCode();
198    result ^= Arrays.hashCode(this.tableName.getName());
199    result ^= this.replicaId;
200    this.hashCode = result;
201  }
202
203  /**
204   * Private constructor used constructing HRegionInfo for the
205   * first meta regions
206   */
207  private HRegionInfo(long regionId, TableName tableName) {
208    this(regionId, tableName, DEFAULT_REPLICA_ID);
209  }
210
211  public HRegionInfo(long regionId, TableName tableName, int replicaId) {
212    super();
213    this.regionId = regionId;
214    this.tableName = tableName;
215    this.replicaId = replicaId;
216    // Note: First Meta region replicas names are in old format
217    this.regionName = createRegionName(tableName, null, regionId, replicaId, false);
218    setHashCode();
219  }
220
221  public HRegionInfo(final TableName tableName) {
222    this(tableName, null, null);
223  }
224
225  /**
226   * Construct HRegionInfo with explicit parameters
227   *
228   * @param tableName the table name
229   * @param startKey first key in region
230   * @param endKey end of key range
231   * @throws IllegalArgumentException
232   */
233  public HRegionInfo(final TableName tableName, final byte[] startKey, final byte[] endKey)
234  throws IllegalArgumentException {
235    this(tableName, startKey, endKey, false);
236  }
237
238  /**
239   * Construct HRegionInfo with explicit parameters
240   *
241   * @param tableName the table descriptor
242   * @param startKey first key in region
243   * @param endKey end of key range
244   * @param split true if this region has split and we have daughter regions
245   * regions that may or may not hold references to this region.
246   * @throws IllegalArgumentException
247   */
248  public HRegionInfo(final TableName tableName, final byte[] startKey, final byte[] endKey,
249      final boolean split)
250  throws IllegalArgumentException {
251    this(tableName, startKey, endKey, split, System.currentTimeMillis());
252  }
253
254  /**
255   * Construct HRegionInfo with explicit parameters
256   *
257   * @param tableName the table descriptor
258   * @param startKey first key in region
259   * @param endKey end of key range
260   * @param split true if this region has split and we have daughter regions
261   * regions that may or may not hold references to this region.
262   * @param regionid Region id to use.
263   * @throws IllegalArgumentException
264   */
265  public HRegionInfo(final TableName tableName, final byte[] startKey,
266                     final byte[] endKey, final boolean split, final long regionid)
267  throws IllegalArgumentException {
268    this(tableName, startKey, endKey, split, regionid, DEFAULT_REPLICA_ID);
269  }
270
271  /**
272   * Construct HRegionInfo with explicit parameters
273   *
274   * @param tableName the table descriptor
275   * @param startKey first key in region
276   * @param endKey end of key range
277   * @param split true if this region has split and we have daughter regions
278   * regions that may or may not hold references to this region.
279   * @param regionid Region id to use.
280   * @param replicaId the replicaId to use
281   * @throws IllegalArgumentException
282   */
283  public HRegionInfo(final TableName tableName, final byte[] startKey,
284                     final byte[] endKey, final boolean split, final long regionid,
285                     final int replicaId)
286    throws IllegalArgumentException {
287    super();
288    if (tableName == null) {
289      throw new IllegalArgumentException("TableName cannot be null");
290    }
291    this.tableName = tableName;
292    this.offLine = false;
293    this.regionId = regionid;
294    this.replicaId = replicaId;
295    if (this.replicaId > MAX_REPLICA_ID) {
296      throw new IllegalArgumentException("ReplicaId cannot be greater than" + MAX_REPLICA_ID);
297    }
298
299    this.regionName = createRegionName(this.tableName, startKey, regionId, replicaId, true);
300
301    this.split = split;
302    this.endKey = endKey == null? HConstants.EMPTY_END_ROW: endKey.clone();
303    this.startKey = startKey == null?
304      HConstants.EMPTY_START_ROW: startKey.clone();
305    this.tableName = tableName;
306    setHashCode();
307  }
308
309  /**
310   * Costruct a copy of another HRegionInfo
311   *
312   * @param other
313   */
314  public HRegionInfo(RegionInfo other) {
315    super();
316    this.endKey = other.getEndKey();
317    this.offLine = other.isOffline();
318    this.regionId = other.getRegionId();
319    this.regionName = other.getRegionName();
320    this.split = other.isSplit();
321    this.startKey = other.getStartKey();
322    this.hashCode = other.hashCode();
323    this.encodedName = other.getEncodedName();
324    this.tableName = other.getTable();
325    this.replicaId = other.getReplicaId();
326  }
327
328  public HRegionInfo(HRegionInfo other, int replicaId) {
329    this(other);
330    this.replicaId = replicaId;
331    this.setHashCode();
332  }
333
334  /**
335   * Make a region name of passed parameters.
336   * @param tableName
337   * @param startKey Can be null
338   * @param regionid Region id (Usually timestamp from when region was created).
339   * @param newFormat should we create the region name in the new format
340   *                  (such that it contains its encoded name?).
341   * @return Region name made of passed tableName, startKey and id
342   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
343   *             Use {@link RegionInfo#createRegionName(TableName, byte[], long, boolean)}.
344   */
345  @Deprecated
346  @InterfaceAudience.Private
347  public static byte [] createRegionName(final TableName tableName,
348      final byte [] startKey, final long regionid, boolean newFormat) {
349    return RegionInfo.createRegionName(tableName, startKey, Long.toString(regionid), newFormat);
350  }
351
352  /**
353   * Make a region name of passed parameters.
354   * @param tableName
355   * @param startKey Can be null
356   * @param id Region id (Usually timestamp from when region was created).
357   * @param newFormat should we create the region name in the new format
358   *                  (such that it contains its encoded name?).
359   * @return Region name made of passed tableName, startKey and id
360   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
361   *             Use {@link RegionInfo#createRegionName(TableName, byte[], String, boolean)}.
362   */
363  @Deprecated
364  @InterfaceAudience.Private
365  public static byte [] createRegionName(final TableName tableName,
366      final byte [] startKey, final String id, boolean newFormat) {
367    return RegionInfo.createRegionName(tableName, startKey, Bytes.toBytes(id), newFormat);
368  }
369
370  /**
371   * Make a region name of passed parameters.
372   * @param tableName
373   * @param startKey Can be null
374   * @param regionid Region id (Usually timestamp from when region was created).
375   * @param replicaId
376   * @param newFormat should we create the region name in the new format
377   *                  (such that it contains its encoded name?).
378   * @return Region name made of passed tableName, startKey, id and replicaId
379   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
380   *             Use {@link RegionInfo#createRegionName(TableName, byte[], long, int, boolean)}.
381   */
382  @Deprecated
383  @InterfaceAudience.Private
384  public static byte [] createRegionName(final TableName tableName,
385      final byte [] startKey, final long regionid, int replicaId, boolean newFormat) {
386    return RegionInfo.createRegionName(tableName, startKey, Bytes.toBytes(Long.toString(regionid)),
387        replicaId, newFormat);
388  }
389
390  /**
391   * Make a region name of passed parameters.
392   * @param tableName
393   * @param startKey Can be null
394   * @param id Region id (Usually timestamp from when region was created).
395   * @param newFormat should we create the region name in the new format
396   *                  (such that it contains its encoded name?).
397   * @return Region name made of passed tableName, startKey and id
398   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
399   *             Use {@link RegionInfo#createRegionName(TableName, byte[], byte[], boolean)}.
400   */
401  @Deprecated
402  @InterfaceAudience.Private
403  public static byte [] createRegionName(final TableName tableName,
404      final byte [] startKey, final byte [] id, boolean newFormat) {
405    return RegionInfo.createRegionName(tableName, startKey, id, DEFAULT_REPLICA_ID, newFormat);
406  }
407  /**
408   * Make a region name of passed parameters.
409   * @param tableName
410   * @param startKey Can be null
411   * @param id Region id (Usually timestamp from when region was created).
412   * @param replicaId
413   * @param newFormat should we create the region name in the new format
414   * @return Region name made of passed tableName, startKey, id and replicaId
415   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
416   *             Use {@link RegionInfo#createRegionName(TableName, byte[], byte[], int, boolean)}.
417   */
418  @Deprecated
419  @InterfaceAudience.Private
420  public static byte [] createRegionName(final TableName tableName,
421      final byte [] startKey, final byte [] id, final int replicaId, boolean newFormat) {
422    return RegionInfo.createRegionName(tableName, startKey, id, replicaId, newFormat);
423  }
424
425  /**
426   * Gets the table name from the specified region name.
427   * @param regionName to extract the table name from
428   * @return Table name
429   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
430   *             Use {@link org.apache.hadoop.hbase.client.RegionInfo#getTable(byte[])}.
431   */
432  @Deprecated
433  public static TableName getTable(final byte [] regionName) {
434    return RegionInfo.getTable(regionName);
435  }
436
437  /**
438   * Gets the start key from the specified region name.
439   * @param regionName
440   * @return Start key.
441   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
442   *             Use {@link org.apache.hadoop.hbase.client.RegionInfo#getStartKey(byte[])}.
443   */
444  @Deprecated
445  public static byte[] getStartKey(final byte[] regionName) throws IOException {
446    return RegionInfo.getStartKey(regionName);
447  }
448
449  /**
450   * Separate elements of a regionName.
451   * @param regionName
452   * @return Array of byte[] containing tableName, startKey and id
453   * @throws IOException
454   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
455   *             Use {@link RegionInfo#parseRegionName(byte[])}.
456   */
457  @Deprecated
458  @InterfaceAudience.Private
459  public static byte [][] parseRegionName(final byte [] regionName) throws IOException {
460    return RegionInfo.parseRegionName(regionName);
461  }
462
463  /**
464   *
465   * @param regionName
466   * @return if region name is encoded.
467   * @throws IOException
468   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
469   *             Use {@link org.apache.hadoop.hbase.client.RegionInfo#isEncodedRegionName(byte[])}.
470   */
471  @Deprecated
472  public static boolean isEncodedRegionName(byte[] regionName) throws IOException {
473    return RegionInfo.isEncodedRegionName(regionName);
474  }
475
476  /** @return the regionId */
477  @Override
478  public long getRegionId(){
479    return regionId;
480  }
481
482  /**
483   * @return the regionName as an array of bytes.
484   * @see #getRegionNameAsString()
485   */
486  @Override
487  public byte [] getRegionName(){
488    return regionName;
489  }
490
491  /**
492   * @return Region name as a String for use in logging, etc.
493   */
494  @Override
495  public String getRegionNameAsString() {
496    if (RegionInfo.hasEncodedName(this.regionName)) {
497      // new format region names already have their encoded name.
498      return Bytes.toStringBinary(this.regionName);
499    }
500
501    // old format. regionNameStr doesn't have the region name.
502    //
503    //
504    return Bytes.toStringBinary(this.regionName) + "." + this.getEncodedName();
505  }
506
507  /**
508   * @return the encoded region name
509   */
510  @Override
511  public synchronized String getEncodedName() {
512    if (this.encodedName == null) {
513      this.encodedName = RegionInfo.encodeRegionName(this.regionName);
514    }
515    return this.encodedName;
516  }
517
518  @Override
519  public synchronized byte [] getEncodedNameAsBytes() {
520    if (this.encodedNameAsBytes == null) {
521      this.encodedNameAsBytes = Bytes.toBytes(getEncodedName());
522    }
523    return this.encodedNameAsBytes;
524  }
525
526  /**
527   * @return the startKey
528   */
529  @Override
530  public byte [] getStartKey(){
531    return startKey;
532  }
533
534  /**
535   * @return the endKey
536   */
537  @Override
538  public byte [] getEndKey(){
539    return endKey;
540  }
541
542  /**
543   * Get current table name of the region
544   * @return TableName
545   */
546  @Override
547  public TableName getTable() {
548    // This method name should be getTableName but there was already a method getTableName
549    // that returned a byte array.  It is unfortunate given everywhere else, getTableName returns
550    // a TableName instance.
551    if (tableName == null || tableName.getName().length == 0) {
552      tableName = getTable(getRegionName());
553    }
554    return this.tableName;
555  }
556
557  /**
558   * Returns true if the given inclusive range of rows is fully contained
559   * by this region. For example, if the region is foo,a,g and this is
560   * passed ["b","c"] or ["a","c"] it will return true, but if this is passed
561   * ["b","z"] it will return false.
562   * @throws IllegalArgumentException if the range passed is invalid (ie. end &lt; start)
563   */
564  @Override
565  public boolean containsRange(byte[] rangeStartKey, byte[] rangeEndKey) {
566    if (Bytes.compareTo(rangeStartKey, rangeEndKey) > 0) {
567      throw new IllegalArgumentException(
568      "Invalid range: " + Bytes.toStringBinary(rangeStartKey) +
569      " > " + Bytes.toStringBinary(rangeEndKey));
570    }
571
572    boolean firstKeyInRange = Bytes.compareTo(rangeStartKey, startKey) >= 0;
573    boolean lastKeyInRange =
574      Bytes.compareTo(rangeEndKey, endKey) < 0 ||
575      Bytes.equals(endKey, HConstants.EMPTY_BYTE_ARRAY);
576    return firstKeyInRange && lastKeyInRange;
577  }
578
579  /**
580   * @return true if the given row falls in this region.
581   */
582  @Override
583  public boolean containsRow(byte[] row) {
584    return Bytes.compareTo(row, startKey) >= 0 &&
585      (Bytes.compareTo(row, endKey) < 0 ||
586       Bytes.equals(endKey, HConstants.EMPTY_BYTE_ARRAY));
587  }
588
589  /**
590   * @return true if this region is from hbase:meta
591   */
592  public boolean isMetaTable() {
593    return isMetaRegion();
594  }
595
596  /**
597   * @return true if this region is a meta region
598   */
599  @Override
600  public boolean isMetaRegion() {
601     return tableName.equals(HRegionInfo.FIRST_META_REGIONINFO.getTable());
602  }
603
604  /**
605   * @return true if this region is from a system table
606   */
607  public boolean isSystemTable() {
608    return tableName.isSystemTable();
609  }
610
611  /**
612   * @return true if has been split and has daughters.
613   */
614  @Override
615  public boolean isSplit() {
616    return this.split;
617  }
618
619  /**
620   * @param split set split status
621   */
622  public void setSplit(boolean split) {
623    this.split = split;
624  }
625
626  /**
627   * @return true if this region is offline.
628   */
629  @Override
630  public boolean isOffline() {
631    return this.offLine;
632  }
633
634  /**
635   * The parent of a region split is offline while split daughters hold
636   * references to the parent. Offlined regions are closed.
637   * @param offLine Set online/offline status.
638   */
639  public void setOffline(boolean offLine) {
640    this.offLine = offLine;
641  }
642
643  /**
644   * @return true if this is a split parent region.
645   */
646  @Override
647  public boolean isSplitParent() {
648    if (!isSplit()) return false;
649    if (!isOffline()) {
650      LOG.warn("Region is split but NOT offline: " + getRegionNameAsString());
651    }
652    return true;
653  }
654
655  /**
656   * Returns the region replica id
657   * @return returns region replica id
658   */
659  @Override
660  public int getReplicaId() {
661    return replicaId;
662  }
663
664  /**
665   * @see java.lang.Object#toString()
666   */
667  @Override
668  public String toString() {
669    return "{ENCODED => " + getEncodedName() + ", " +
670      HConstants.NAME + " => '" + Bytes.toStringBinary(this.regionName)
671      + "', STARTKEY => '" +
672      Bytes.toStringBinary(this.startKey) + "', ENDKEY => '" +
673      Bytes.toStringBinary(this.endKey) + "'" +
674      (isOffline()? ", OFFLINE => true": "") +
675      (isSplit()? ", SPLIT => true": "") +
676      ((replicaId > 0)? ", REPLICA_ID => " + replicaId : "") + "}";
677  }
678
679  /**
680   * @see java.lang.Object#equals(java.lang.Object)
681   */
682  @Override
683  public boolean equals(Object o) {
684    if (this == o) {
685      return true;
686    }
687    if (o == null) {
688      return false;
689    }
690    if (!(o instanceof HRegionInfo)) {
691      return false;
692    }
693    return this.compareTo((HRegionInfo)o) == 0;
694  }
695
696  /**
697   * @see java.lang.Object#hashCode()
698   */
699  @Override
700  public int hashCode() {
701    return this.hashCode;
702  }
703
704  //
705  // Comparable
706  //
707
708  @Override
709  public int compareTo(HRegionInfo o) {
710    return RegionInfo.COMPARATOR.compare(this, o);
711  }
712
713  /**
714   * @return Comparator to use comparing {@link KeyValue}s.
715   * @deprecated Use Region#getCellComparator().  deprecated for hbase 2.0, remove for hbase 3.0
716   */
717  @Deprecated
718  public KVComparator getComparator() {
719    return isMetaRegion()?
720        KeyValue.META_COMPARATOR: KeyValue.COMPARATOR;
721  }
722
723  /**
724   * Convert a HRegionInfo to the protobuf RegionInfo
725   *
726   * @return the converted RegionInfo
727   */
728  HBaseProtos.RegionInfo convert() {
729    return convert(this);
730  }
731
732  /**
733   * Convert a HRegionInfo to a RegionInfo
734   *
735   * @param info the HRegionInfo to convert
736   * @return the converted RegionInfo
737   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
738   *             Use toRegionInfo(org.apache.hadoop.hbase.client.RegionInfo)
739   *             in org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil.
740   */
741  @Deprecated
742  @InterfaceAudience.Private
743  public static HBaseProtos.RegionInfo convert(final HRegionInfo info) {
744    return ProtobufUtil.toRegionInfo(info);
745  }
746
747  /**
748   * Convert a RegionInfo to a HRegionInfo
749   *
750   * @param proto the RegionInfo to convert
751   * @return the converted HRegionInfo
752   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
753   *             Use toRegionInfo(HBaseProtos.RegionInfo)
754   *             in org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil.
755   */
756  @Deprecated
757  @InterfaceAudience.Private
758  public static HRegionInfo convert(final HBaseProtos.RegionInfo proto) {
759    RegionInfo ri = ProtobufUtil.toRegionInfo(proto);
760    // This is hack of what is in RegionReplicaUtil but it is doing translation of
761    // RegionInfo into HRegionInfo which is what is wanted here.
762    HRegionInfo hri;
763    if (ri.isMetaRegion()) {
764      hri = ri.getReplicaId() == RegionInfo.DEFAULT_REPLICA_ID ?
765      HRegionInfo.FIRST_META_REGIONINFO :
766      new HRegionInfo(ri.getRegionId(), ri.getTable(), ri.getReplicaId());
767    } else {
768      hri = new HRegionInfo(
769        ri.getTable(),
770        ri.getStartKey(),
771        ri.getEndKey(),
772        ri.isSplit(),
773        ri.getRegionId(),
774        ri.getReplicaId());
775      if (proto.hasOffline()) {
776        hri.setOffline(proto.getOffline());
777      }
778    }
779    return hri;
780  }
781
782  /**
783   * @return This instance serialized as protobuf w/ a magic pb prefix.
784   * @see #parseFrom(byte[])
785   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
786   *             Use {@link org.apache.hadoop.hbase.client.RegionInfo#toByteArray(RegionInfo)}.
787   */
788  @Deprecated
789  public byte [] toByteArray() {
790    return RegionInfo.toByteArray(this);
791  }
792
793  /**
794   * @return A deserialized {@link HRegionInfo}
795   * or null if we failed deserialize or passed bytes null
796   * @see #toByteArray()
797   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
798   *             Use {@link org.apache.hadoop.hbase.client.RegionInfo#parseFromOrNull(byte[])}.
799   */
800  @Deprecated
801  public static HRegionInfo parseFromOrNull(final byte [] bytes) {
802    if (bytes == null) return null;
803    return parseFromOrNull(bytes, 0, bytes.length);
804  }
805
806  /**
807   * @return A deserialized {@link HRegionInfo} or null
808   *  if we failed deserialize or passed bytes null
809   * @see #toByteArray()
810   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
811   *             Use {@link org.apache.hadoop.hbase.client.RegionInfo#parseFromOrNull(byte[], int, int)}.
812   */
813  @Deprecated
814  public static HRegionInfo parseFromOrNull(final byte [] bytes, int offset, int len) {
815    if (bytes == null || len <= 0) return null;
816    try {
817      return parseFrom(bytes, offset, len);
818    } catch (DeserializationException e) {
819      return null;
820    }
821  }
822
823  /**
824   * @param bytes A pb RegionInfo serialized with a pb magic prefix.
825   * @return A deserialized {@link HRegionInfo}
826   * @throws DeserializationException
827   * @see #toByteArray()
828   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
829   *             Use {@link org.apache.hadoop.hbase.client.RegionInfo#parseFrom(byte[])}.
830   */
831  public static HRegionInfo parseFrom(final byte [] bytes) throws DeserializationException {
832    if (bytes == null) return null;
833    return parseFrom(bytes, 0, bytes.length);
834  }
835
836  /**
837   * @param bytes A pb RegionInfo serialized with a pb magic prefix.
838   * @param offset starting point in the byte array
839   * @param len length to read on the byte array
840   * @return A deserialized {@link HRegionInfo}
841   * @throws DeserializationException
842   * @see #toByteArray()
843   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
844   *             Use {@link org.apache.hadoop.hbase.client.RegionInfo#parseFrom(byte[], int, int)}.
845   */
846  @Deprecated
847  public static HRegionInfo parseFrom(final byte [] bytes, int offset, int len)
848      throws DeserializationException {
849    if (ProtobufUtil.isPBMagicPrefix(bytes, offset, len)) {
850      int pblen = ProtobufUtil.lengthOfPBMagic();
851      try {
852        HBaseProtos.RegionInfo.Builder builder = HBaseProtos.RegionInfo.newBuilder();
853        ProtobufUtil.mergeFrom(builder, bytes, pblen + offset, len - pblen);
854        HBaseProtos.RegionInfo ri = builder.build();
855        return convert(ri);
856      } catch (IOException e) {
857        throw new DeserializationException(e);
858      }
859    } else {
860      throw new DeserializationException("PB encoded HRegionInfo expected");
861    }
862  }
863
864  /**
865   * Use this instead of {@link #toByteArray()} when writing to a stream and you want to use
866   * the pb mergeDelimitedFrom (w/o the delimiter, pb reads to EOF which may not be what you want).
867   * @return This instance serialized as a delimited protobuf w/ a magic pb prefix.
868   * @throws IOException
869   * @see #toByteArray()
870   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
871   *             Use {@link RegionInfo#toDelimitedByteArray(RegionInfo)}.
872   */
873  @Deprecated
874  public byte [] toDelimitedByteArray() throws IOException {
875    return RegionInfo.toDelimitedByteArray(this);
876  }
877
878  /**
879   * Get the descriptive name as {@link RegionState} does it but with hidden
880   * startkey optionally
881   * @param state
882   * @param conf
883   * @return descriptive string
884   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
885   *             Use RegionInfoDisplay#getDescriptiveNameFromRegionStateForDisplay(RegionState, Configuration)
886   *             over in hbase-server module.
887   */
888  @Deprecated
889  @InterfaceAudience.Private
890  public static String getDescriptiveNameFromRegionStateForDisplay(RegionState state,
891      Configuration conf) {
892    return RegionInfoDisplay.getDescriptiveNameFromRegionStateForDisplay(state, conf);
893  }
894
895  /**
896   * Get the end key for display. Optionally hide the real end key.
897   * @param hri
898   * @param conf
899   * @return the endkey
900   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
901   *             Use RegionInfoDisplay#getEndKeyForDisplay(RegionInfo, Configuration)
902   *             over in hbase-server module.
903   */
904  @Deprecated
905  @InterfaceAudience.Private
906  public static byte[] getEndKeyForDisplay(HRegionInfo hri, Configuration conf) {
907    return RegionInfoDisplay.getEndKeyForDisplay(hri, conf);
908  }
909
910  /**
911   * Get the start key for display. Optionally hide the real start key.
912   * @param hri
913   * @param conf
914   * @return the startkey
915   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
916   *             Use RegionInfoDisplay#getStartKeyForDisplay(RegionInfo, Configuration)
917   *             over in hbase-server module.
918   */
919  @Deprecated
920  @InterfaceAudience.Private
921  public static byte[] getStartKeyForDisplay(HRegionInfo hri, Configuration conf) {
922    return RegionInfoDisplay.getStartKeyForDisplay(hri, conf);
923  }
924
925  /**
926   * Get the region name for display. Optionally hide the start key.
927   * @param hri
928   * @param conf
929   * @return region name as String
930   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
931   *             Use RegionInfoDisplay#getRegionNameAsStringForDisplay(RegionInfo, Configuration)
932   *             over in hbase-server module.
933   */
934  @Deprecated
935  @InterfaceAudience.Private
936  public static String getRegionNameAsStringForDisplay(HRegionInfo hri, Configuration conf) {
937    return RegionInfoDisplay.getRegionNameAsStringForDisplay(hri, conf);
938  }
939
940  /**
941   * Get the region name for display. Optionally hide the start key.
942   * @param hri
943   * @param conf
944   * @return region name bytes
945   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
946   *             Use RegionInfoDisplay#getRegionNameForDisplay(RegionInfo, Configuration)
947   *             over in hbase-server module.
948   */
949  @Deprecated
950  @InterfaceAudience.Private
951  public static byte[] getRegionNameForDisplay(HRegionInfo hri, Configuration conf) {
952    return RegionInfoDisplay.getRegionNameForDisplay(hri, conf);
953  }
954
955  /**
956   * Parses an HRegionInfo instance from the passed in stream.  Presumes the HRegionInfo was
957   * serialized to the stream with {@link #toDelimitedByteArray()}
958   * @param in
959   * @return An instance of HRegionInfo.
960   * @throws IOException
961   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
962   *             Use {@link RegionInfo#parseFrom(DataInputStream)}.
963   */
964  @Deprecated
965  @InterfaceAudience.Private
966  public static HRegionInfo parseFrom(final DataInputStream in) throws IOException {
967    // I need to be able to move back in the stream if this is not a pb serialization so I can
968    // do the Writable decoding instead.
969    int pblen = ProtobufUtil.lengthOfPBMagic();
970    byte [] pbuf = new byte[pblen];
971    if (in.markSupported()) { //read it with mark()
972      in.mark(pblen);
973    }
974
975    //assumption: if Writable serialization, it should be longer than pblen.
976    int read = in.read(pbuf);
977    if (read != pblen) throw new IOException("read=" + read + ", wanted=" + pblen);
978    if (ProtobufUtil.isPBMagicPrefix(pbuf)) {
979      return convert(HBaseProtos.RegionInfo.parseDelimitedFrom(in));
980    } else {
981      throw new IOException("PB encoded HRegionInfo expected");
982    }
983  }
984
985  /**
986   * Serializes given HRegionInfo's as a byte array. Use this instead of {@link #toByteArray()} when
987   * writing to a stream and you want to use the pb mergeDelimitedFrom (w/o the delimiter, pb reads
988   * to EOF which may not be what you want). {@link #parseDelimitedFrom(byte[], int, int)} can
989   * be used to read back the instances.
990   * @param infos HRegionInfo objects to serialize
991   * @return This instance serialized as a delimited protobuf w/ a magic pb prefix.
992   * @throws IOException
993   * @see #toByteArray()
994   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
995   *             Use {@link RegionInfo#toDelimitedByteArray(RegionInfo...)}.
996   */
997  @Deprecated
998  @InterfaceAudience.Private
999  public static byte[] toDelimitedByteArray(HRegionInfo... infos) throws IOException {
1000    return RegionInfo.toDelimitedByteArray(infos);
1001  }
1002
1003  /**
1004   * Parses all the HRegionInfo instances from the passed in stream until EOF. Presumes the
1005   * HRegionInfo's were serialized to the stream with {@link #toDelimitedByteArray()}
1006   * @param bytes serialized bytes
1007   * @param offset the start offset into the byte[] buffer
1008   * @param length how far we should read into the byte[] buffer
1009   * @return All the hregioninfos that are in the byte array. Keeps reading till we hit the end.
1010   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
1011   *             Use {@link RegionInfo#parseDelimitedFrom(byte[], int, int)}.
1012   */
1013  @Deprecated
1014  public static List<HRegionInfo> parseDelimitedFrom(final byte[] bytes, final int offset,
1015      final int length) throws IOException {
1016    if (bytes == null) {
1017      throw new IllegalArgumentException("Can't build an object with empty bytes array");
1018    }
1019    DataInputBuffer in = new DataInputBuffer();
1020    List<HRegionInfo> hris = new ArrayList<>();
1021    try {
1022      in.reset(bytes, offset, length);
1023      while (in.available() > 0) {
1024        HRegionInfo hri = parseFrom(in);
1025        hris.add(hri);
1026      }
1027    } finally {
1028      in.close();
1029    }
1030    return hris;
1031  }
1032
1033  /**
1034   * Check whether two regions are adjacent
1035   * @param regionA
1036   * @param regionB
1037   * @return true if two regions are adjacent
1038   * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0
1039   *             Use {@link org.apache.hadoop.hbase.client.RegionInfo#areAdjacent(RegionInfo, RegionInfo)}.
1040   */
1041  @Deprecated
1042  public static boolean areAdjacent(HRegionInfo regionA, HRegionInfo regionB) {
1043    return RegionInfo.areAdjacent(regionA, regionB);
1044  }
1045}