View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase;
19  
20  import com.google.common.annotations.VisibleForTesting;
21  import com.google.protobuf.ServiceException;
22  
23  import org.apache.commons.logging.Log;
24  import org.apache.commons.logging.LogFactory;
25  import org.apache.hadoop.conf.Configuration;
26  import org.apache.hadoop.hbase.classification.InterfaceAudience;
27  import org.apache.hadoop.hbase.client.ClusterConnection;
28  import org.apache.hadoop.hbase.client.Connection;
29  import org.apache.hadoop.hbase.client.ConnectionFactory;
30  import org.apache.hadoop.hbase.client.Delete;
31  import org.apache.hadoop.hbase.client.Get;
32  import org.apache.hadoop.hbase.client.HTable;
33  import org.apache.hadoop.hbase.client.Mutation;
34  import org.apache.hadoop.hbase.client.Put;
35  import org.apache.hadoop.hbase.client.RegionLocator;
36  import org.apache.hadoop.hbase.client.RegionReplicaUtil;
37  import org.apache.hadoop.hbase.client.Result;
38  import org.apache.hadoop.hbase.client.ResultScanner;
39  import org.apache.hadoop.hbase.client.Scan;
40  import org.apache.hadoop.hbase.client.Table;
41  import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
42  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
43  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
44  import org.apache.hadoop.hbase.protobuf.generated.MultiRowMutationProtos;
45  import org.apache.hadoop.hbase.util.Bytes;
46  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
47  import org.apache.hadoop.hbase.util.Pair;
48  import org.apache.hadoop.hbase.util.PairOfSameType;
49  import org.apache.hadoop.hbase.util.Threads;
50  import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
51  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
52  
53  import java.io.IOException;
54  import java.io.InterruptedIOException;
55  import java.util.ArrayList;
56  import java.util.List;
57  import java.util.Map;
58  import java.util.NavigableMap;
59  import java.util.Set;
60  import java.util.SortedMap;
61  import java.util.TreeMap;
62  import java.util.regex.Matcher;
63  import java.util.regex.Pattern;
64  
65  /**
66   * Read/write operations on region and assignment information store in
67   * <code>hbase:meta</code>.
68   *
69   * Some of the methods of this class take ZooKeeperWatcher as a param. The only reason
70   * for this is because when used on client-side (like from HBaseAdmin), we want to use
71   * short-living connection (opened before each operation, closed right after), while
72   * when used on HM or HRS (like in AssignmentManager) we want permanent connection.
73   */
74  @InterfaceAudience.Private
75  public class MetaTableAccessor {
76  
77    /*
78     * HBASE-10070 adds a replicaId to HRI, meaning more than one HRI can be defined for the
79     * same table range (table, startKey, endKey). For every range, there will be at least one
80     * HRI defined which is called default replica.
81     *
82     * Meta layout (as of 0.98 + HBASE-10070) is like:
83     * For each table range, there is a single row, formatted like:
84     * <tableName>,<startKey>,<regionId>,<encodedRegionName>. This row corresponds to the regionName
85     * of the default region replica.
86     * Columns are:
87     * info:regioninfo         => contains serialized HRI for the default region replica
88     * info:server             => contains hostname:port (in string form) for the server hosting
89     *                            the default regionInfo replica
90     * info:server_<replicaId> => contains hostname:port (in string form) for the server hosting the
91     *                            regionInfo replica with replicaId
92     * info:serverstartcode    => contains server start code (in binary long form) for the server
93     *                            hosting the default regionInfo replica
94     * info:serverstartcode_<replicaId> => contains server start code (in binary long form) for the
95     *                                     server hosting the regionInfo replica with replicaId
96     * info:seqnumDuringOpen    => contains seqNum (in binary long form) for the region at the time
97     *                             the server opened the region with default replicaId
98     * info:seqnumDuringOpen_<replicaId> => contains seqNum (in binary long form) for the region at
99     *                             the time the server opened the region with replicaId
100    * info:splitA              => contains a serialized HRI for the first daughter region if the
101    *                             region is split
102    * info:splitB              => contains a serialized HRI for the second daughter region if the
103    *                             region is split
104    * info:mergeA              => contains a serialized HRI for the first parent region if the
105    *                             region is the result of a merge
106    * info:mergeB              => contains a serialized HRI for the second parent region if the
107    *                             region is the result of a merge
108    *
109    * The actual layout of meta should be encapsulated inside MetaTableAccessor methods,
110    * and should not leak out of it (through Result objects, etc)
111    */
112 
113   private static final Log LOG = LogFactory.getLog(MetaTableAccessor.class);
114 
115   static final byte [] META_REGION_PREFIX;
116   static {
117     // Copy the prefix from FIRST_META_REGIONINFO into META_REGION_PREFIX.
118     // FIRST_META_REGIONINFO == 'hbase:meta,,1'.  META_REGION_PREFIX == 'hbase:meta,'
119     int len = HRegionInfo.FIRST_META_REGIONINFO.getRegionName().length - 2;
120     META_REGION_PREFIX = new byte [len];
121     System.arraycopy(HRegionInfo.FIRST_META_REGIONINFO.getRegionName(), 0,
122       META_REGION_PREFIX, 0, len);
123   }
124 
125   /** The delimiter for meta columns for replicaIds > 0 */
126   protected static final char META_REPLICA_ID_DELIMITER = '_';
127 
128   /** A regex for parsing server columns from meta. See above javadoc for meta layout */
129   private static final Pattern SERVER_COLUMN_PATTERN
130     = Pattern.compile("^server(_[0-9a-fA-F]{4})?$");
131 
132   ////////////////////////
133   // Reading operations //
134   ////////////////////////
135 
136  /**
137    * Performs a full scan of a <code>hbase:meta</code> table.
138    * @return List of {@link org.apache.hadoop.hbase.client.Result}
139    * @throws IOException
140    */
141   public static List<Result> fullScanOfMeta(Connection connection)
142   throws IOException {
143     CollectAllVisitor v = new CollectAllVisitor();
144     fullScan(connection, v, null);
145     return v.getResults();
146   }
147 
148   /**
149    * Performs a full scan of <code>hbase:meta</code>.
150    * @param connection connection we're using
151    * @param visitor Visitor invoked against each row.
152    * @throws IOException
153    */
154   public static void fullScan(Connection connection,
155       final Visitor visitor)
156   throws IOException {
157     fullScan(connection, visitor, null);
158   }
159 
160   /**
161    * Performs a full scan of <code>hbase:meta</code>.
162    * @param connection connection we're using
163    * @return List of {@link Result}
164    * @throws IOException
165    */
166   public static List<Result> fullScan(Connection connection)
167     throws IOException {
168     CollectAllVisitor v = new CollectAllVisitor();
169     fullScan(connection, v, null);
170     return v.getResults();
171   }
172 
173   /**
174    * Callers should call close on the returned {@link Table} instance.
175    * @param connection connection we're using to access Meta
176    * @return An {@link Table} for <code>hbase:meta</code>
177    * @throws IOException
178    */
179   static Table getMetaHTable(final Connection connection)
180   throws IOException {
181     // We used to pass whole CatalogTracker in here, now we just pass in Connection
182     if (connection == null) {
183       throw new NullPointerException("No connection");
184     } else if (connection.isClosed()) {
185       throw new IOException("connection is closed");
186     }
187     // If the passed in 'connection' is 'managed' -- i.e. every second test uses
188     // a Table or an HBaseAdmin with managed connections -- then doing
189     // connection.getTable will throw an exception saying you are NOT to use
190     // managed connections getting tables.  Leaving this as it is for now. Will
191     // revisit when inclined to change all tests.  User code probaby makes use of
192     // managed connections too so don't change it till post hbase 1.0.
193     //
194     // There should still be a way to use this method with an unmanaged connection.
195     if (connection instanceof ClusterConnection) {
196       if (((ClusterConnection) connection).isManaged()) {
197         return new HTable(TableName.META_TABLE_NAME, (ClusterConnection) connection);
198       }
199     }
200     return connection.getTable(TableName.META_TABLE_NAME);
201   }
202 
203   /**
204    * @param t Table to use (will be closed when done).
205    * @param g Get to run
206    * @throws IOException
207    */
208   private static Result get(final Table t, final Get g) throws IOException {
209     try {
210       return t.get(g);
211     } finally {
212       t.close();
213     }
214   }
215 
216   /**
217    * Gets the region info and assignment for the specified region.
218    * @param connection connection we're using
219    * @param regionName Region to lookup.
220    * @return Location and HRegionInfo for <code>regionName</code>
221    * @throws IOException
222    * @deprecated use {@link #getRegionLocation(Connection, byte[])} instead
223    */
224   @Deprecated
225   public static Pair<HRegionInfo, ServerName> getRegion(Connection connection, byte [] regionName)
226     throws IOException {
227     HRegionLocation location = getRegionLocation(connection, regionName);
228     return location == null
229       ? null
230       : new Pair<HRegionInfo, ServerName>(location.getRegionInfo(), location.getServerName());
231   }
232 
233   /**
234    * Returns the HRegionLocation from meta for the given region
235    * @param connection connection we're using
236    * @param regionName region we're looking for
237    * @return HRegionLocation for the given region
238    * @throws IOException
239    */
240   public static HRegionLocation getRegionLocation(Connection connection,
241                                                   byte[] regionName) throws IOException {
242     byte[] row = regionName;
243     HRegionInfo parsedInfo = null;
244     try {
245       parsedInfo = parseRegionInfoFromRegionName(regionName);
246       row = getMetaKeyForRegion(parsedInfo);
247     } catch (Exception parseEx) {
248       // Ignore. This is used with tableName passed as regionName.
249     }
250     Get get = new Get(row);
251     get.addFamily(HConstants.CATALOG_FAMILY);
252     Result r = get(getMetaHTable(connection), get);
253     RegionLocations locations = getRegionLocations(r);
254     return locations == null
255       ? null
256       : locations.getRegionLocation(parsedInfo == null ? 0 : parsedInfo.getReplicaId());
257   }
258 
259   /**
260    * Returns the HRegionLocation from meta for the given region
261    * @param connection connection we're using
262    * @param regionInfo region information
263    * @return HRegionLocation for the given region
264    * @throws IOException
265    */
266   public static HRegionLocation getRegionLocation(Connection connection,
267                                                   HRegionInfo regionInfo) throws IOException {
268     byte[] row = getMetaKeyForRegion(regionInfo);
269     Get get = new Get(row);
270     get.addFamily(HConstants.CATALOG_FAMILY);
271     Result r = get(getMetaHTable(connection), get);
272     return getRegionLocation(r, regionInfo, regionInfo.getReplicaId());
273   }
274 
275   /** Returns the row key to use for this regionInfo */
276   public static byte[] getMetaKeyForRegion(HRegionInfo regionInfo) {
277     return RegionReplicaUtil.getRegionInfoForDefaultReplica(regionInfo).getRegionName();
278   }
279 
280   /** Returns an HRI parsed from this regionName. Not all the fields of the HRI
281    * is stored in the name, so the returned object should only be used for the fields
282    * in the regionName.
283    */
284   protected static HRegionInfo parseRegionInfoFromRegionName(byte[] regionName)
285     throws IOException {
286     byte[][] fields = HRegionInfo.parseRegionName(regionName);
287     long regionId =  Long.parseLong(Bytes.toString(fields[2]));
288     int replicaId = fields.length > 3 ? Integer.parseInt(Bytes.toString(fields[3]), 16) : 0;
289     return new HRegionInfo(
290       TableName.valueOf(fields[0]), fields[1], fields[1], false, regionId, replicaId);
291   }
292 
293   /**
294    * Gets the result in hbase:meta for the specified region.
295    * @param connection connection we're using
296    * @param regionName region we're looking for
297    * @return result of the specified region
298    * @throws IOException
299    */
300   public static Result getRegionResult(Connection connection,
301       byte[] regionName) throws IOException {
302     Get get = new Get(regionName);
303     get.addFamily(HConstants.CATALOG_FAMILY);
304     return get(getMetaHTable(connection), get);
305   }
306 
307   /**
308    * Get regions from the merge qualifier of the specified merged region
309    * @return null if it doesn't contain merge qualifier, else two merge regions
310    * @throws IOException
311    */
312   public static Pair<HRegionInfo, HRegionInfo> getRegionsFromMergeQualifier(
313       Connection connection, byte[] regionName) throws IOException {
314     Result result = getRegionResult(connection, regionName);
315     HRegionInfo mergeA = getHRegionInfo(result, HConstants.MERGEA_QUALIFIER);
316     HRegionInfo mergeB = getHRegionInfo(result, HConstants.MERGEB_QUALIFIER);
317     if (mergeA == null && mergeB == null) {
318       return null;
319     }
320     return new Pair<HRegionInfo, HRegionInfo>(mergeA, mergeB);
321  }
322 
323   /**
324    * Checks if the specified table exists.  Looks at the hbase:meta table hosted on
325    * the specified server.
326    * @param connection connection we're using
327    * @param tableName table to check
328    * @return true if the table exists in meta, false if not
329    * @throws IOException
330    */
331   public static boolean tableExists(Connection connection,
332       final TableName tableName)
333   throws IOException {
334     if (tableName.equals(TableName.META_TABLE_NAME)) {
335       // Catalog tables always exist.
336       return true;
337     }
338     // Make a version of ResultCollectingVisitor that only collects the first
339     CollectingVisitor<HRegionInfo> visitor = new CollectingVisitor<HRegionInfo>() {
340       private HRegionInfo current = null;
341 
342       @Override
343       public boolean visit(Result r) throws IOException {
344         RegionLocations locations = getRegionLocations(r);
345         if (locations == null || locations.getRegionLocation().getRegionInfo() == null) {
346           LOG.warn("No serialized HRegionInfo in " + r);
347           return true;
348         }
349         this.current = locations.getRegionLocation().getRegionInfo();
350         if (this.current == null) {
351           LOG.warn("No serialized HRegionInfo in " + r);
352           return true;
353         }
354         if (!isInsideTable(this.current, tableName)) return false;
355         // Else call super and add this Result to the collection.
356         super.visit(r);
357         // Stop collecting regions from table after we get one.
358         return false;
359       }
360 
361       @Override
362       void add(Result r) {
363         // Add the current HRI.
364         this.results.add(this.current);
365       }
366     };
367     fullScan(connection, visitor, getTableStartRowForMeta(tableName));
368     // If visitor has results >= 1 then table exists.
369     return visitor.getResults().size() >= 1;
370   }
371 
372   /**
373    * Gets all of the regions of the specified table.
374    * @param zkw zookeeper connection to access meta table
375    * @param connection connection we're using
376    * @param tableName table we're looking for
377    * @return Ordered list of {@link HRegionInfo}.
378    * @throws IOException
379    */
380   public static List<HRegionInfo> getTableRegions(ZooKeeperWatcher zkw,
381       Connection connection, TableName tableName)
382   throws IOException {
383     return getTableRegions(zkw, connection, tableName, false);
384   }
385 
386   /**
387    * Gets all of the regions of the specified table.
388    * @param zkw zookeeper connection to access meta table
389    * @param connection connection we're using
390    * @param tableName table we're looking for
391    * @param excludeOfflinedSplitParents If true, do not include offlined split
392    * parents in the return.
393    * @return Ordered list of {@link HRegionInfo}.
394    * @throws IOException
395    */
396   public static List<HRegionInfo> getTableRegions(ZooKeeperWatcher zkw,
397       Connection connection, TableName tableName, final boolean excludeOfflinedSplitParents)
398         throws IOException {
399     List<Pair<HRegionInfo, ServerName>> result = null;
400       result = getTableRegionsAndLocations(zkw, connection, tableName,
401         excludeOfflinedSplitParents);
402     return getListOfHRegionInfos(result);
403   }
404 
405   static List<HRegionInfo> getListOfHRegionInfos(final List<Pair<HRegionInfo, ServerName>> pairs) {
406     if (pairs == null || pairs.isEmpty()) return null;
407     List<HRegionInfo> result = new ArrayList<HRegionInfo>(pairs.size());
408     for (Pair<HRegionInfo, ServerName> pair: pairs) {
409       result.add(pair.getFirst());
410     }
411     return result;
412   }
413 
414   /**
415    * @param current region of current table we're working with
416    * @param tableName table we're checking against
417    * @return True if <code>current</code> tablename is equal to
418    * <code>tableName</code>
419    */
420   static boolean isInsideTable(final HRegionInfo current, final TableName tableName) {
421     return tableName.equals(current.getTable());
422   }
423 
424   /**
425    * @param tableName table we're working with
426    * @return Place to start Scan in <code>hbase:meta</code> when passed a
427    * <code>tableName</code>; returns &lt;tableName&rt; &lt;,&rt; &lt;,&rt;
428    */
429   static byte [] getTableStartRowForMeta(TableName tableName) {
430     byte [] startRow = new byte[tableName.getName().length + 2];
431     System.arraycopy(tableName.getName(), 0, startRow, 0, tableName.getName().length);
432     startRow[startRow.length - 2] = HConstants.DELIMITER;
433     startRow[startRow.length - 1] = HConstants.DELIMITER;
434     return startRow;
435   }
436 
437   /**
438    * This method creates a Scan object that will only scan catalog rows that
439    * belong to the specified table. It doesn't specify any columns.
440    * This is a better alternative to just using a start row and scan until
441    * it hits a new table since that requires parsing the HRI to get the table
442    * name.
443    * @param tableName bytes of table's name
444    * @return configured Scan object
445    */
446   public static Scan getScanForTableName(TableName tableName) {
447     String strName = tableName.getNameAsString();
448     // Start key is just the table name with delimiters
449     byte[] startKey = Bytes.toBytes(strName + ",,");
450     // Stop key appends the smallest possible char to the table name
451     byte[] stopKey = Bytes.toBytes(strName + " ,,");
452 
453     Scan scan = new Scan(startKey);
454     scan.setStopRow(stopKey);
455     return scan;
456   }
457 
458   /**
459    * @param zkw zookeeper connection to access meta table
460    * @param connection connection we're using
461    * @param tableName table we're looking for
462    * @return Return list of regioninfos and server.
463    * @throws IOException
464    */
465   public static List<Pair<HRegionInfo, ServerName>>
466   getTableRegionsAndLocations(ZooKeeperWatcher zkw,
467                               Connection connection, TableName tableName)
468   throws IOException {
469     return getTableRegionsAndLocations(zkw, connection, tableName, true);
470   }
471 
472   /**
473    * @param zkw ZooKeeperWatcher instance we're using to get hbase:meta location
474    * @param connection connection we're using
475    * @param tableName table to work with
476    * @return Return list of regioninfos and server addresses.
477    * @throws IOException
478    */
479   public static List<Pair<HRegionInfo, ServerName>> getTableRegionsAndLocations(
480       ZooKeeperWatcher zkw, Connection connection, final TableName tableName,
481       final boolean excludeOfflinedSplitParents) throws IOException {
482 
483     if (tableName.equals(TableName.META_TABLE_NAME)) {
484       // If meta, do a bit of special handling.
485       ServerName serverName = new MetaTableLocator().getMetaRegionLocation(zkw);
486       List<Pair<HRegionInfo, ServerName>> list =
487         new ArrayList<Pair<HRegionInfo, ServerName>>();
488       list.add(new Pair<HRegionInfo, ServerName>(HRegionInfo.FIRST_META_REGIONINFO,
489         serverName));
490       return list;
491     }
492     // Make a version of CollectingVisitor that collects HRegionInfo and ServerAddress
493     CollectingVisitor<Pair<HRegionInfo, ServerName>> visitor =
494       new CollectingVisitor<Pair<HRegionInfo, ServerName>>() {
495         private RegionLocations current = null;
496 
497         @Override
498         public boolean visit(Result r) throws IOException {
499           current = getRegionLocations(r);
500           if (current == null || current.getRegionLocation().getRegionInfo() == null) {
501             LOG.warn("No serialized HRegionInfo in " + r);
502             return true;
503           }
504           HRegionInfo hri = current.getRegionLocation().getRegionInfo();
505           if (!isInsideTable(hri, tableName)) return false;
506           if (excludeOfflinedSplitParents && hri.isSplitParent()) return true;
507           // Else call super and add this Result to the collection.
508           return super.visit(r);
509         }
510 
511         @Override
512         void add(Result r) {
513           if (current == null) {
514             return;
515           }
516           for (HRegionLocation loc : current.getRegionLocations()) {
517             if (loc != null) {
518               this.results.add(new Pair<HRegionInfo, ServerName>(
519                 loc.getRegionInfo(), loc.getServerName()));
520             }
521           }
522         }
523       };
524     fullScan(connection, visitor, getTableStartRowForMeta(tableName));
525     return visitor.getResults();
526   }
527 
528   /**
529    * @param connection connection we're using
530    * @param serverName server whose regions we're interested in
531    * @return List of user regions installed on this server (does not include
532    * catalog regions).
533    * @throws IOException
534    */
535   public static NavigableMap<HRegionInfo, Result>
536   getServerUserRegions(Connection connection, final ServerName serverName)
537     throws IOException {
538     final NavigableMap<HRegionInfo, Result> hris = new TreeMap<HRegionInfo, Result>();
539     // Fill the above hris map with entries from hbase:meta that have the passed
540     // servername.
541     CollectingVisitor<Result> v = new CollectingVisitor<Result>() {
542       @Override
543       void add(Result r) {
544         if (r == null || r.isEmpty()) return;
545         RegionLocations locations = getRegionLocations(r);
546         if (locations == null) return;
547         for (HRegionLocation loc : locations.getRegionLocations()) {
548           if (loc != null) {
549             if (loc.getServerName() != null && loc.getServerName().equals(serverName)) {
550               hris.put(loc.getRegionInfo(), r);
551             }
552           }
553         }
554       }
555     };
556     fullScan(connection, v);
557     return hris;
558   }
559 
560   public static void fullScanMetaAndPrint(Connection connection)
561     throws IOException {
562     Visitor v = new Visitor() {
563       @Override
564       public boolean visit(Result r) throws IOException {
565         if (r ==  null || r.isEmpty()) return true;
566         LOG.info("fullScanMetaAndPrint.Current Meta Row: " + r);
567         RegionLocations locations = getRegionLocations(r);
568         if (locations == null) return true;
569         for (HRegionLocation loc : locations.getRegionLocations()) {
570           if (loc != null) {
571             LOG.info("fullScanMetaAndPrint.HRI Print= " + loc.getRegionInfo());
572           }
573         }
574         return true;
575       }
576     };
577     fullScan(connection, v);
578   }
579 
580   /**
581    * Performs a full scan of a catalog table.
582    * @param connection connection we're using
583    * @param visitor Visitor invoked against each row.
584    * @param startrow Where to start the scan. Pass null if want to begin scan
585    * at first row.
586    * <code>hbase:meta</code>, the default (pass false to scan hbase:meta)
587    * @throws IOException
588    */
589   public static void fullScan(Connection connection,
590     final Visitor visitor, final byte [] startrow)
591   throws IOException {
592     Scan scan = new Scan();
593     if (startrow != null) scan.setStartRow(startrow);
594     if (startrow == null) {
595       int caching = connection.getConfiguration()
596           .getInt(HConstants.HBASE_META_SCANNER_CACHING, 100);
597       scan.setCaching(caching);
598     }
599     scan.addFamily(HConstants.CATALOG_FAMILY);
600     Table metaTable = getMetaHTable(connection);
601     ResultScanner scanner = null;
602     try {
603       scanner = metaTable.getScanner(scan);
604       Result data;
605       while((data = scanner.next()) != null) {
606         if (data.isEmpty()) continue;
607         // Break if visit returns false.
608         if (!visitor.visit(data)) break;
609       }
610     } finally {
611       if (scanner != null) scanner.close();
612       metaTable.close();
613     }
614   }
615 
616   /**
617    * Returns the column family used for meta columns.
618    * @return HConstants.CATALOG_FAMILY.
619    */
620   protected static byte[] getFamily() {
621     return HConstants.CATALOG_FAMILY;
622   }
623 
624   /**
625    * Returns the column qualifier for serialized region info
626    * @return HConstants.REGIONINFO_QUALIFIER
627    */
628   protected static byte[] getRegionInfoColumn() {
629     return HConstants.REGIONINFO_QUALIFIER;
630   }
631 
632   /**
633    * Returns the column qualifier for server column for replicaId
634    * @param replicaId the replicaId of the region
635    * @return a byte[] for server column qualifier
636    */
637   @VisibleForTesting
638   public static byte[] getServerColumn(int replicaId) {
639     return replicaId == 0
640       ? HConstants.SERVER_QUALIFIER
641       : Bytes.toBytes(HConstants.SERVER_QUALIFIER_STR + META_REPLICA_ID_DELIMITER
642       + String.format(HRegionInfo.REPLICA_ID_FORMAT, replicaId));
643   }
644 
645   /**
646    * Returns the column qualifier for server start code column for replicaId
647    * @param replicaId the replicaId of the region
648    * @return a byte[] for server start code column qualifier
649    */
650   @VisibleForTesting
651   public static byte[] getStartCodeColumn(int replicaId) {
652     return replicaId == 0
653       ? HConstants.STARTCODE_QUALIFIER
654       : Bytes.toBytes(HConstants.STARTCODE_QUALIFIER_STR + META_REPLICA_ID_DELIMITER
655       + String.format(HRegionInfo.REPLICA_ID_FORMAT, replicaId));
656   }
657 
658   /**
659    * Returns the column qualifier for seqNum column for replicaId
660    * @param replicaId the replicaId of the region
661    * @return a byte[] for seqNum column qualifier
662    */
663   @VisibleForTesting
664   public static byte[] getSeqNumColumn(int replicaId) {
665     return replicaId == 0
666       ? HConstants.SEQNUM_QUALIFIER
667       : Bytes.toBytes(HConstants.SEQNUM_QUALIFIER_STR + META_REPLICA_ID_DELIMITER
668       + String.format(HRegionInfo.REPLICA_ID_FORMAT, replicaId));
669   }
670 
671   /**
672    * Parses the replicaId from the server column qualifier. See top of the class javadoc
673    * for the actual meta layout
674    * @param serverColumn the column qualifier
675    * @return an int for the replicaId
676    */
677   @VisibleForTesting
678   static int parseReplicaIdFromServerColumn(byte[] serverColumn) {
679     String serverStr = Bytes.toString(serverColumn);
680 
681     Matcher matcher = SERVER_COLUMN_PATTERN.matcher(serverStr);
682     if (matcher.matches() && matcher.groupCount() > 0) {
683       String group = matcher.group(1);
684       if (group != null && group.length() > 0) {
685         return Integer.parseInt(group.substring(1), 16);
686       } else {
687         return 0;
688       }
689     }
690     return -1;
691   }
692 
693   /**
694    * Returns a {@link ServerName} from catalog table {@link Result}.
695    * @param r Result to pull from
696    * @return A ServerName instance or null if necessary fields not found or empty.
697    */
698   private static ServerName getServerName(final Result r, final int replicaId) {
699     byte[] serverColumn = getServerColumn(replicaId);
700     Cell cell = r.getColumnLatestCell(getFamily(), serverColumn);
701     if (cell == null || cell.getValueLength() == 0) return null;
702     String hostAndPort = Bytes.toString(
703       cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
704     byte[] startcodeColumn = getStartCodeColumn(replicaId);
705     cell = r.getColumnLatestCell(getFamily(), startcodeColumn);
706     if (cell == null || cell.getValueLength() == 0) return null;
707     return ServerName.valueOf(hostAndPort,
708       Bytes.toLong(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
709   }
710 
711   /**
712    * The latest seqnum that the server writing to meta observed when opening the region.
713    * E.g. the seqNum when the result of {@link #getServerName(Result, int)} was written.
714    * @param r Result to pull the seqNum from
715    * @return SeqNum, or HConstants.NO_SEQNUM if there's no value written.
716    */
717   private static long getSeqNumDuringOpen(final Result r, final int replicaId) {
718     Cell cell = r.getColumnLatestCell(getFamily(), getSeqNumColumn(replicaId));
719     if (cell == null || cell.getValueLength() == 0) return HConstants.NO_SEQNUM;
720     return Bytes.toLong(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
721   }
722 
723   /**
724    * Returns an HRegionLocationList extracted from the result.
725    * @return an HRegionLocationList containing all locations for the region range or null if
726    *  we can't deserialize the result.
727    */
728   public static RegionLocations getRegionLocations(final Result r) {
729     if (r == null) return null;
730     HRegionInfo regionInfo = getHRegionInfo(r, getRegionInfoColumn());
731     if (regionInfo == null) return null;
732 
733     List<HRegionLocation> locations = new ArrayList<HRegionLocation>(1);
734     NavigableMap<byte[],NavigableMap<byte[],byte[]>> familyMap = r.getNoVersionMap();
735 
736     locations.add(getRegionLocation(r, regionInfo, 0));
737 
738     NavigableMap<byte[], byte[]> infoMap = familyMap.get(getFamily());
739     if (infoMap == null) return new RegionLocations(locations);
740 
741     // iterate until all serverName columns are seen
742     int replicaId = 0;
743     byte[] serverColumn = getServerColumn(replicaId);
744     SortedMap<byte[], byte[]> serverMap = infoMap.tailMap(serverColumn, false);
745     if (serverMap.isEmpty()) return new RegionLocations(locations);
746 
747     for (Map.Entry<byte[], byte[]> entry : serverMap.entrySet()) {
748       replicaId = parseReplicaIdFromServerColumn(entry.getKey());
749       if (replicaId < 0) {
750         break;
751       }
752       HRegionLocation location = getRegionLocation(r, regionInfo, replicaId);
753       // In case the region replica is newly created, it's location might be null. We usually do not
754       // have HRL's in RegionLocations object with null ServerName. They are handled as null HRLs.
755       if (location == null || location.getServerName() == null) {
756         locations.add(null);
757       } else {
758         locations.add(location);
759       }
760     }
761 
762     return new RegionLocations(locations);
763   }
764 
765   /**
766    * Returns the HRegionLocation parsed from the given meta row Result
767    * for the given regionInfo and replicaId. The regionInfo can be the default region info
768    * for the replica.
769    * @param r the meta row result
770    * @param regionInfo RegionInfo for default replica
771    * @param replicaId the replicaId for the HRegionLocation
772    * @return HRegionLocation parsed from the given meta row Result for the given replicaId
773    */
774   private static HRegionLocation getRegionLocation(final Result r, final HRegionInfo regionInfo,
775                                                    final int replicaId) {
776     ServerName serverName = getServerName(r, replicaId);
777     long seqNum = getSeqNumDuringOpen(r, replicaId);
778     HRegionInfo replicaInfo = RegionReplicaUtil.getRegionInfoForReplica(regionInfo, replicaId);
779     return new HRegionLocation(replicaInfo, serverName, seqNum);
780   }
781 
782   /**
783    * Returns HRegionInfo object from the column
784    * HConstants.CATALOG_FAMILY:HConstants.REGIONINFO_QUALIFIER of the catalog
785    * table Result.
786    * @param data a Result object from the catalog table scan
787    * @return HRegionInfo or null
788    */
789   public static HRegionInfo getHRegionInfo(Result data) {
790     return getHRegionInfo(data, HConstants.REGIONINFO_QUALIFIER);
791   }
792 
793   /**
794    * Returns the HRegionInfo object from the column {@link HConstants#CATALOG_FAMILY} and
795    * <code>qualifier</code> of the catalog table result.
796    * @param r a Result object from the catalog table scan
797    * @param qualifier Column family qualifier
798    * @return An HRegionInfo instance or null.
799    */
800   private static HRegionInfo getHRegionInfo(final Result r, byte [] qualifier) {
801     Cell cell = r.getColumnLatestCell(getFamily(), qualifier);
802     if (cell == null) return null;
803     return HRegionInfo.parseFromOrNull(cell.getValueArray(),
804       cell.getValueOffset(), cell.getValueLength());
805   }
806 
807   /**
808    * Returns the daughter regions by reading the corresponding columns of the catalog table
809    * Result.
810    * @param data a Result object from the catalog table scan
811    * @return a pair of HRegionInfo or PairOfSameType(null, null) if the region is not a split
812    * parent
813    */
814   public static PairOfSameType<HRegionInfo> getDaughterRegions(Result data) {
815     HRegionInfo splitA = getHRegionInfo(data, HConstants.SPLITA_QUALIFIER);
816     HRegionInfo splitB = getHRegionInfo(data, HConstants.SPLITB_QUALIFIER);
817 
818     return new PairOfSameType<HRegionInfo>(splitA, splitB);
819   }
820 
821   /**
822    * Returns the merge regions by reading the corresponding columns of the catalog table
823    * Result.
824    * @param data a Result object from the catalog table scan
825    * @return a pair of HRegionInfo or PairOfSameType(null, null) if the region is not a split
826    * parent
827    */
828   public static PairOfSameType<HRegionInfo> getMergeRegions(Result data) {
829     HRegionInfo mergeA = getHRegionInfo(data, HConstants.MERGEA_QUALIFIER);
830     HRegionInfo mergeB = getHRegionInfo(data, HConstants.MERGEB_QUALIFIER);
831 
832     return new PairOfSameType<HRegionInfo>(mergeA, mergeB);
833   }
834 
835   /**
836    * Implementations 'visit' a catalog table row.
837    */
838   public interface Visitor {
839     /**
840      * Visit the catalog table row.
841      * @param r A row from catalog table
842      * @return True if we are to proceed scanning the table, else false if
843      * we are to stop now.
844      */
845     boolean visit(final Result r) throws IOException;
846   }
847 
848   /**
849    * A {@link Visitor} that collects content out of passed {@link Result}.
850    */
851   static abstract class CollectingVisitor<T> implements Visitor {
852     final List<T> results = new ArrayList<T>();
853     @Override
854     public boolean visit(Result r) throws IOException {
855       if (r ==  null || r.isEmpty()) return true;
856       add(r);
857       return true;
858     }
859 
860     abstract void add(Result r);
861 
862     /**
863      * @return Collected results; wait till visits complete to collect all
864      * possible results
865      */
866     List<T> getResults() {
867       return this.results;
868     }
869   }
870 
871   /**
872    * Collects all returned.
873    */
874   static class CollectAllVisitor extends CollectingVisitor<Result> {
875     @Override
876     void add(Result r) {
877       this.results.add(r);
878     }
879   }
880 
881   /**
882    * Count regions in <code>hbase:meta</code> for passed table.
883    * @param c Configuration object
884    * @param tableName table name to count regions for
885    * @return Count or regions in table <code>tableName</code>
886    * @throws IOException
887    */
888   @Deprecated
889   public static int getRegionCount(final Configuration c, final String tableName)
890       throws IOException {
891     return getRegionCount(c, TableName.valueOf(tableName));
892   }
893 
894   /**
895    * Count regions in <code>hbase:meta</code> for passed table.
896    * @param c Configuration object
897    * @param tableName table name to count regions for
898    * @return Count or regions in table <code>tableName</code>
899    * @throws IOException
900    */
901   public static int getRegionCount(final Configuration c, final TableName tableName)
902   throws IOException {
903     try (Connection connection = ConnectionFactory.createConnection(c)) {
904       return getRegionCount(connection, tableName);
905     }
906   }
907 
908   /**
909    * Count regions in <code>hbase:meta</code> for passed table.
910    * @param connection Connection object
911    * @param tableName table name to count regions for
912    * @return Count or regions in table <code>tableName</code>
913    * @throws IOException
914    */
915   public static int getRegionCount(final Connection connection, final TableName tableName)
916   throws IOException {
917     try (RegionLocator locator = connection.getRegionLocator(tableName)) {
918       List<HRegionLocation> locations = locator.getAllRegionLocations();
919       return locations == null? 0: locations.size();
920     }
921   }
922 
923   ////////////////////////
924   // Editing operations //
925   ////////////////////////
926 
927   /**
928    * Generates and returns a Put containing the region into for the catalog table
929    */
930   public static Put makePutFromRegionInfo(HRegionInfo regionInfo)
931     throws IOException {
932     Put put = new Put(regionInfo.getRegionName());
933     addRegionInfo(put, regionInfo);
934     return put;
935   }
936 
937   /**
938    * Generates and returns a Delete containing the region info for the catalog
939    * table
940    */
941   public static Delete makeDeleteFromRegionInfo(HRegionInfo regionInfo) {
942     if (regionInfo == null) {
943       throw new IllegalArgumentException("Can't make a delete for null region");
944     }
945     Delete delete = new Delete(regionInfo.getRegionName());
946     return delete;
947   }
948 
949   /**
950    * Adds split daughters to the Put
951    */
952   public static Put addDaughtersToPut(Put put, HRegionInfo splitA, HRegionInfo splitB) {
953     if (splitA != null) {
954       put.addImmutable(
955         HConstants.CATALOG_FAMILY, HConstants.SPLITA_QUALIFIER, splitA.toByteArray());
956     }
957     if (splitB != null) {
958       put.addImmutable(
959         HConstants.CATALOG_FAMILY, HConstants.SPLITB_QUALIFIER, splitB.toByteArray());
960     }
961     return put;
962   }
963 
964   /**
965    * Put the passed <code>p</code> to the <code>hbase:meta</code> table.
966    * @param connection connection we're using
967    * @param p Put to add to hbase:meta
968    * @throws IOException
969    */
970   static void putToMetaTable(final Connection connection, final Put p)
971     throws IOException {
972     put(getMetaHTable(connection), p);
973   }
974 
975   /**
976    * @param t Table to use (will be closed when done).
977    * @param p put to make
978    * @throws IOException
979    */
980   private static void put(final Table t, final Put p) throws IOException {
981     try {
982       t.put(p);
983     } finally {
984       t.close();
985     }
986   }
987 
988   /**
989    * Put the passed <code>ps</code> to the <code>hbase:meta</code> table.
990    * @param connection connection we're using
991    * @param ps Put to add to hbase:meta
992    * @throws IOException
993    */
994   public static void putsToMetaTable(final Connection connection, final List<Put> ps)
995     throws IOException {
996     Table t = getMetaHTable(connection);
997     try {
998       t.put(ps);
999     } finally {
1000       t.close();
1001     }
1002   }
1003 
1004   /**
1005    * Delete the passed <code>d</code> from the <code>hbase:meta</code> table.
1006    * @param connection connection we're using
1007    * @param d Delete to add to hbase:meta
1008    * @throws IOException
1009    */
1010   static void deleteFromMetaTable(final Connection connection, final Delete d)
1011     throws IOException {
1012     List<Delete> dels = new ArrayList<Delete>(1);
1013     dels.add(d);
1014     deleteFromMetaTable(connection, dels);
1015   }
1016 
1017   /**
1018    * Delete the passed <code>deletes</code> from the <code>hbase:meta</code> table.
1019    * @param connection connection we're using
1020    * @param deletes Deletes to add to hbase:meta  This list should support #remove.
1021    * @throws IOException
1022    */
1023   public static void deleteFromMetaTable(final Connection connection, final List<Delete> deletes)
1024     throws IOException {
1025     Table t = getMetaHTable(connection);
1026     try {
1027       t.delete(deletes);
1028     } finally {
1029       t.close();
1030     }
1031   }
1032 
1033   /**
1034    * Deletes some replica columns corresponding to replicas for the passed rows
1035    * @param metaRows rows in hbase:meta
1036    * @param replicaIndexToDeleteFrom the replica ID we would start deleting from
1037    * @param numReplicasToRemove how many replicas to remove
1038    * @param connection connection we're using to access meta table
1039    * @throws IOException
1040    */
1041   public static void removeRegionReplicasFromMeta(Set<byte[]> metaRows,
1042     int replicaIndexToDeleteFrom, int numReplicasToRemove, Connection connection)
1043       throws IOException {
1044     int absoluteIndex = replicaIndexToDeleteFrom + numReplicasToRemove;
1045     for (byte[] row : metaRows) {
1046       Delete deleteReplicaLocations = new Delete(row);
1047       for (int i = replicaIndexToDeleteFrom; i < absoluteIndex; i++) {
1048         deleteReplicaLocations.deleteColumns(HConstants.CATALOG_FAMILY,
1049           getServerColumn(i));
1050         deleteReplicaLocations.deleteColumns(HConstants.CATALOG_FAMILY,
1051           getSeqNumColumn(i));
1052         deleteReplicaLocations.deleteColumns(HConstants.CATALOG_FAMILY,
1053           getStartCodeColumn(i));
1054       }
1055       deleteFromMetaTable(connection, deleteReplicaLocations);
1056     }
1057   }
1058 
1059   /**
1060    * Execute the passed <code>mutations</code> against <code>hbase:meta</code> table.
1061    * @param connection connection we're using
1062    * @param mutations Puts and Deletes to execute on hbase:meta
1063    * @throws IOException
1064    */
1065   public static void mutateMetaTable(final Connection connection,
1066                                      final List<Mutation> mutations)
1067     throws IOException {
1068     Table t = getMetaHTable(connection);
1069     try {
1070       t.batch(mutations);
1071     } catch (InterruptedException e) {
1072       InterruptedIOException ie = new InterruptedIOException(e.getMessage());
1073       ie.initCause(e);
1074       throw ie;
1075     } finally {
1076       t.close();
1077     }
1078   }
1079 
1080   /**
1081    * Adds a hbase:meta row for the specified new region.
1082    * @param connection connection we're using
1083    * @param regionInfo region information
1084    * @throws IOException if problem connecting or updating meta
1085    */
1086   public static void addRegionToMeta(Connection connection,
1087                                      HRegionInfo regionInfo)
1088     throws IOException {
1089     putToMetaTable(connection, makePutFromRegionInfo(regionInfo));
1090     LOG.info("Added " + regionInfo.getRegionNameAsString());
1091   }
1092 
1093   /**
1094    * Adds a hbase:meta row for the specified new region to the given catalog table. The
1095    * Table is not flushed or closed.
1096    * @param meta the Table for META
1097    * @param regionInfo region information
1098    * @throws IOException if problem connecting or updating meta
1099    */
1100   public static void addRegionToMeta(Table meta, HRegionInfo regionInfo) throws IOException {
1101     addRegionToMeta(meta, regionInfo, null, null);
1102   }
1103 
1104   /**
1105    * Adds a (single) hbase:meta row for the specified new region and its daughters. Note that this
1106    * does not add its daughter's as different rows, but adds information about the daughters
1107    * in the same row as the parent. Use
1108    * {@link #splitRegion(Connection, HRegionInfo, HRegionInfo, HRegionInfo, ServerName, int)}
1109    * if you want to do that.
1110    * @param meta the Table for META
1111    * @param regionInfo region information
1112    * @param splitA first split daughter of the parent regionInfo
1113    * @param splitB second split daughter of the parent regionInfo
1114    * @throws IOException if problem connecting or updating meta
1115    */
1116   public static void addRegionToMeta(Table meta, HRegionInfo regionInfo,
1117                                      HRegionInfo splitA, HRegionInfo splitB) throws IOException {
1118     Put put = makePutFromRegionInfo(regionInfo);
1119     addDaughtersToPut(put, splitA, splitB);
1120     meta.put(put);
1121     if (LOG.isDebugEnabled()) {
1122       LOG.debug("Added " + regionInfo.getRegionNameAsString());
1123     }
1124   }
1125 
1126   /**
1127    * Adds a (single) hbase:meta row for the specified new region and its daughters. Note that this
1128    * does not add its daughter's as different rows, but adds information about the daughters
1129    * in the same row as the parent. Use
1130    * {@link #splitRegion(Connection, HRegionInfo, HRegionInfo, HRegionInfo, ServerName, int)}
1131    * if you want to do that.
1132    * @param connection connection we're using
1133    * @param regionInfo region information
1134    * @param splitA first split daughter of the parent regionInfo
1135    * @param splitB second split daughter of the parent regionInfo
1136    * @throws IOException if problem connecting or updating meta
1137    */
1138   public static void addRegionToMeta(Connection connection, HRegionInfo regionInfo,
1139                                      HRegionInfo splitA, HRegionInfo splitB) throws IOException {
1140     Table meta = getMetaHTable(connection);
1141     try {
1142       addRegionToMeta(meta, regionInfo, splitA, splitB);
1143     } finally {
1144       meta.close();
1145     }
1146   }
1147 
1148   /**
1149    * Adds a hbase:meta row for each of the specified new regions.
1150    * @param connection connection we're using
1151    * @param regionInfos region information list
1152    * @throws IOException if problem connecting or updating meta
1153    */
1154   public static void addRegionsToMeta(Connection connection,
1155                                       List<HRegionInfo> regionInfos, int regionReplication)
1156     throws IOException {
1157     List<Put> puts = new ArrayList<Put>();
1158     for (HRegionInfo regionInfo : regionInfos) {
1159       if (RegionReplicaUtil.isDefaultReplica(regionInfo)) {
1160         puts.add(makePutFromRegionInfo(regionInfo));
1161         Put put = makePutFromRegionInfo(regionInfo);
1162         // Add empty locations for region replicas so that number of replicas can be cached
1163         // whenever the primary region is looked up from meta
1164         for (int i = 1; i < regionReplication; i++) {
1165           addEmptyLocation(put, i);
1166         }
1167         puts.add(put);
1168       }
1169     }
1170     putsToMetaTable(connection, puts);
1171     LOG.info("Added " + puts.size());
1172   }
1173 
1174   /**
1175    * Adds a daughter region entry to meta.
1176    * @param regionInfo the region to put
1177    * @param sn the location of the region
1178    * @param openSeqNum the latest sequence number obtained when the region was open
1179    */
1180   public static void addDaughter(final Connection connection,
1181       final HRegionInfo regionInfo, final ServerName sn, final long openSeqNum)
1182       throws NotAllMetaRegionsOnlineException, IOException {
1183     Put put = new Put(regionInfo.getRegionName());
1184     addRegionInfo(put, regionInfo);
1185     if (sn != null) {
1186       addLocation(put, sn, openSeqNum, regionInfo.getReplicaId());
1187     }
1188     putToMetaTable(connection, put);
1189     LOG.info("Added daughter " + regionInfo.getEncodedName() +
1190       (sn == null? ", serverName=null": ", serverName=" + sn.toString()));
1191   }
1192 
1193   /**
1194    * Merge the two regions into one in an atomic operation. Deletes the two
1195    * merging regions in hbase:meta and adds the merged region with the information of
1196    * two merging regions.
1197    * @param connection connection we're using
1198    * @param mergedRegion the merged region
1199    * @param regionA
1200    * @param regionB
1201    * @param sn the location of the region
1202    * @throws IOException
1203    */
1204   public static void mergeRegions(final Connection connection, HRegionInfo mergedRegion,
1205       HRegionInfo regionA, HRegionInfo regionB, ServerName sn, int regionReplication)
1206           throws IOException {
1207     Table meta = getMetaHTable(connection);
1208     try {
1209       HRegionInfo copyOfMerged = new HRegionInfo(mergedRegion);
1210 
1211       // Put for parent
1212       Put putOfMerged = makePutFromRegionInfo(copyOfMerged);
1213       putOfMerged.addImmutable(HConstants.CATALOG_FAMILY, HConstants.MERGEA_QUALIFIER,
1214         regionA.toByteArray());
1215       putOfMerged.addImmutable(HConstants.CATALOG_FAMILY, HConstants.MERGEB_QUALIFIER,
1216         regionB.toByteArray());
1217 
1218       // Deletes for merging regions
1219       Delete deleteA = makeDeleteFromRegionInfo(regionA);
1220       Delete deleteB = makeDeleteFromRegionInfo(regionB);
1221 
1222       // The merged is a new region, openSeqNum = 1 is fine.
1223       addLocation(putOfMerged, sn, 1, mergedRegion.getReplicaId());
1224 
1225       // Add empty locations for region replicas of the merged region so that number of replicas can
1226       // be cached whenever the primary region is looked up from meta
1227       for (int i = 1; i < regionReplication; i++) {
1228         addEmptyLocation(putOfMerged, i);
1229       }
1230 
1231       byte[] tableRow = Bytes.toBytes(mergedRegion.getRegionNameAsString()
1232         + HConstants.DELIMITER);
1233       multiMutate(meta, tableRow, putOfMerged, deleteA, deleteB);
1234     } finally {
1235       meta.close();
1236     }
1237   }
1238 
1239   /**
1240    * Splits the region into two in an atomic operation. Offlines the parent
1241    * region with the information that it is split into two, and also adds
1242    * the daughter regions. Does not add the location information to the daughter
1243    * regions since they are not open yet.
1244    * @param connection connection we're using
1245    * @param parent the parent region which is split
1246    * @param splitA Split daughter region A
1247    * @param splitB Split daughter region A
1248    * @param sn the location of the region
1249    */
1250   public static void splitRegion(final Connection connection,
1251                                  HRegionInfo parent, HRegionInfo splitA, HRegionInfo splitB,
1252                                  ServerName sn, int regionReplication) throws IOException {
1253     Table meta = getMetaHTable(connection);
1254     try {
1255       HRegionInfo copyOfParent = new HRegionInfo(parent);
1256       copyOfParent.setOffline(true);
1257       copyOfParent.setSplit(true);
1258 
1259       //Put for parent
1260       Put putParent = makePutFromRegionInfo(copyOfParent);
1261       addDaughtersToPut(putParent, splitA, splitB);
1262 
1263       //Puts for daughters
1264       Put putA = makePutFromRegionInfo(splitA);
1265       Put putB = makePutFromRegionInfo(splitB);
1266 
1267       addLocation(putA, sn, 1, splitA.getReplicaId()); //new regions, openSeqNum = 1 is fine.
1268       addLocation(putB, sn, 1, splitB.getReplicaId());
1269 
1270       // Add empty locations for region replicas of daughters so that number of replicas can be
1271       // cached whenever the primary region is looked up from meta
1272       for (int i = 1; i < regionReplication; i++) {
1273         addEmptyLocation(putA, i);
1274         addEmptyLocation(putB, i);
1275       }
1276 
1277       byte[] tableRow = Bytes.toBytes(parent.getRegionNameAsString() + HConstants.DELIMITER);
1278       multiMutate(meta, tableRow, putParent, putA, putB);
1279     } finally {
1280       meta.close();
1281     }
1282   }
1283 
1284   /**
1285    * Performs an atomic multi-Mutate operation against the given table.
1286    */
1287   private static void multiMutate(Table table, byte[] row, Mutation... mutations)
1288       throws IOException {
1289     CoprocessorRpcChannel channel = table.coprocessorService(row);
1290     MultiRowMutationProtos.MutateRowsRequest.Builder mmrBuilder
1291       = MultiRowMutationProtos.MutateRowsRequest.newBuilder();
1292     for (Mutation mutation : mutations) {
1293       if (mutation instanceof Put) {
1294         mmrBuilder.addMutationRequest(ProtobufUtil.toMutation(
1295           ClientProtos.MutationProto.MutationType.PUT, mutation));
1296       } else if (mutation instanceof Delete) {
1297         mmrBuilder.addMutationRequest(ProtobufUtil.toMutation(
1298           ClientProtos.MutationProto.MutationType.DELETE, mutation));
1299       } else {
1300         throw new DoNotRetryIOException("multi in MetaEditor doesn't support "
1301           + mutation.getClass().getName());
1302       }
1303     }
1304 
1305     MultiRowMutationProtos.MultiRowMutationService.BlockingInterface service =
1306       MultiRowMutationProtos.MultiRowMutationService.newBlockingStub(channel);
1307     try {
1308       service.mutateRows(null, mmrBuilder.build());
1309     } catch (ServiceException ex) {
1310       ProtobufUtil.toIOException(ex);
1311     }
1312   }
1313 
1314   /**
1315    * Updates the location of the specified region in hbase:meta to be the specified
1316    * server hostname and startcode.
1317    * <p>
1318    * Uses passed catalog tracker to get a connection to the server hosting
1319    * hbase:meta and makes edits to that region.
1320    *
1321    * @param connection connection we're using
1322    * @param regionInfo region to update location of
1323    * @param sn Server name
1324    * @throws IOException
1325    */
1326   public static void updateRegionLocation(Connection connection,
1327                                           HRegionInfo regionInfo, ServerName sn, long updateSeqNum)
1328     throws IOException {
1329     updateLocation(connection, regionInfo, sn, updateSeqNum);
1330   }
1331 
1332   /**
1333    * Updates the location of the specified region to be the specified server.
1334    * <p>
1335    * Connects to the specified server which should be hosting the specified
1336    * catalog region name to perform the edit.
1337    *
1338    * @param connection connection we're using
1339    * @param regionInfo region to update location of
1340    * @param sn Server name
1341    * @param openSeqNum the latest sequence number obtained when the region was open
1342    * @throws IOException In particular could throw {@link java.net.ConnectException}
1343    * if the server is down on other end.
1344    */
1345   private static void updateLocation(final Connection connection,
1346                                      HRegionInfo regionInfo, ServerName sn, long openSeqNum)
1347     throws IOException {
1348     // region replicas are kept in the primary region's row
1349     Put put = new Put(getMetaKeyForRegion(regionInfo));
1350     addLocation(put, sn, openSeqNum, regionInfo.getReplicaId());
1351     putToMetaTable(connection, put);
1352     LOG.info("Updated row " + regionInfo.getRegionNameAsString() +
1353       " with server=" + sn);
1354   }
1355 
1356   /**
1357    * Deletes the specified region from META.
1358    * @param connection connection we're using
1359    * @param regionInfo region to be deleted from META
1360    * @throws IOException
1361    */
1362   public static void deleteRegion(Connection connection,
1363                                   HRegionInfo regionInfo)
1364     throws IOException {
1365     Delete delete = new Delete(regionInfo.getRegionName());
1366     deleteFromMetaTable(connection, delete);
1367     LOG.info("Deleted " + regionInfo.getRegionNameAsString());
1368   }
1369 
1370   /**
1371    * Deletes the specified regions from META.
1372    * @param connection connection we're using
1373    * @param regionsInfo list of regions to be deleted from META
1374    * @throws IOException
1375    */
1376   public static void deleteRegions(Connection connection,
1377                                    List<HRegionInfo> regionsInfo) throws IOException {
1378     List<Delete> deletes = new ArrayList<Delete>(regionsInfo.size());
1379     for (HRegionInfo hri: regionsInfo) {
1380       deletes.add(new Delete(hri.getRegionName()));
1381     }
1382     deleteFromMetaTable(connection, deletes);
1383     LOG.info("Deleted " + regionsInfo);
1384   }
1385 
1386   /**
1387    * Adds and Removes the specified regions from hbase:meta
1388    * @param connection connection we're using
1389    * @param regionsToRemove list of regions to be deleted from META
1390    * @param regionsToAdd list of regions to be added to META
1391    * @throws IOException
1392    */
1393   public static void mutateRegions(Connection connection,
1394                                    final List<HRegionInfo> regionsToRemove,
1395                                    final List<HRegionInfo> regionsToAdd)
1396     throws IOException {
1397     List<Mutation> mutation = new ArrayList<Mutation>();
1398     if (regionsToRemove != null) {
1399       for (HRegionInfo hri: regionsToRemove) {
1400         mutation.add(new Delete(hri.getRegionName()));
1401       }
1402     }
1403     if (regionsToAdd != null) {
1404       for (HRegionInfo hri: regionsToAdd) {
1405         mutation.add(makePutFromRegionInfo(hri));
1406       }
1407     }
1408     mutateMetaTable(connection, mutation);
1409     if (regionsToRemove != null && regionsToRemove.size() > 0) {
1410       LOG.debug("Deleted " + regionsToRemove);
1411     }
1412     if (regionsToAdd != null && regionsToAdd.size() > 0) {
1413       LOG.debug("Added " + regionsToAdd);
1414     }
1415   }
1416 
1417   /**
1418    * Overwrites the specified regions from hbase:meta
1419    * @param connection connection we're using
1420    * @param regionInfos list of regions to be added to META
1421    * @throws IOException
1422    */
1423   public static void overwriteRegions(Connection connection,
1424       List<HRegionInfo> regionInfos, int regionReplication) throws IOException {
1425     deleteRegions(connection, regionInfos);
1426     // Why sleep? This is the easiest way to ensure that the previous deletes does not
1427     // eclipse the following puts, that might happen in the same ts from the server.
1428     // See HBASE-9906, and HBASE-9879. Once either HBASE-9879, HBASE-8770 is fixed,
1429     // or HBASE-9905 is fixed and meta uses seqIds, we do not need the sleep.
1430     Threads.sleep(20);
1431     addRegionsToMeta(connection, regionInfos, regionReplication);
1432     LOG.info("Overwritten " + regionInfos);
1433   }
1434 
1435   /**
1436    * Deletes merge qualifiers for the specified merged region.
1437    * @param connection connection we're using
1438    * @param mergedRegion
1439    * @throws IOException
1440    */
1441   public static void deleteMergeQualifiers(Connection connection,
1442                                            final HRegionInfo mergedRegion) throws IOException {
1443     Delete delete = new Delete(mergedRegion.getRegionName());
1444     delete.deleteColumns(HConstants.CATALOG_FAMILY, HConstants.MERGEA_QUALIFIER);
1445     delete.deleteColumns(HConstants.CATALOG_FAMILY, HConstants.MERGEB_QUALIFIER);
1446     deleteFromMetaTable(connection, delete);
1447     LOG.info("Deleted references in merged region "
1448       + mergedRegion.getRegionNameAsString() + ", qualifier="
1449       + Bytes.toStringBinary(HConstants.MERGEA_QUALIFIER) + " and qualifier="
1450       + Bytes.toStringBinary(HConstants.MERGEB_QUALIFIER));
1451   }
1452 
1453   private static Put addRegionInfo(final Put p, final HRegionInfo hri)
1454     throws IOException {
1455     p.addImmutable(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER,
1456       hri.toByteArray());
1457     return p;
1458   }
1459 
1460   public static Put addLocation(final Put p, final ServerName sn, long openSeqNum, int replicaId){
1461     // using regionserver's local time as the timestamp of Put.
1462     // See: HBASE-11536
1463     long now = EnvironmentEdgeManager.currentTime();
1464     p.addImmutable(HConstants.CATALOG_FAMILY, getServerColumn(replicaId), now,
1465       Bytes.toBytes(sn.getHostAndPort()));
1466     p.addImmutable(HConstants.CATALOG_FAMILY, getStartCodeColumn(replicaId), now,
1467       Bytes.toBytes(sn.getStartcode()));
1468     p.addImmutable(HConstants.CATALOG_FAMILY, getSeqNumColumn(replicaId), now,
1469       Bytes.toBytes(openSeqNum));
1470     return p;
1471   }
1472 
1473   public static Put addEmptyLocation(final Put p, int replicaId) {
1474     long now = EnvironmentEdgeManager.currentTime();
1475     p.addImmutable(HConstants.CATALOG_FAMILY, getServerColumn(replicaId), now, null);
1476     p.addImmutable(HConstants.CATALOG_FAMILY, getStartCodeColumn(replicaId), now, null);
1477     p.addImmutable(HConstants.CATALOG_FAMILY, getSeqNumColumn(replicaId), now, null);
1478     return p;
1479   }
1480 }