001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase;
019
020import edu.umd.cs.findbugs.annotations.NonNull;
021import edu.umd.cs.findbugs.annotations.Nullable;
022import java.io.Closeable;
023import java.io.IOException;
024import java.util.ArrayList;
025import java.util.Collections;
026import java.util.LinkedHashMap;
027import java.util.List;
028import java.util.Map;
029import java.util.Objects;
030import org.apache.hadoop.conf.Configuration;
031import org.apache.hadoop.hbase.Cell.Type;
032import org.apache.hadoop.hbase.ClientMetaTableAccessor.QueryType;
033import org.apache.hadoop.hbase.client.Connection;
034import org.apache.hadoop.hbase.client.Consistency;
035import org.apache.hadoop.hbase.client.Delete;
036import org.apache.hadoop.hbase.client.Get;
037import org.apache.hadoop.hbase.client.Mutation;
038import org.apache.hadoop.hbase.client.Put;
039import org.apache.hadoop.hbase.client.RegionInfo;
040import org.apache.hadoop.hbase.client.RegionReplicaUtil;
041import org.apache.hadoop.hbase.client.Result;
042import org.apache.hadoop.hbase.client.ResultScanner;
043import org.apache.hadoop.hbase.client.Scan;
044import org.apache.hadoop.hbase.client.Table;
045import org.apache.hadoop.hbase.client.TableState;
046import org.apache.hadoop.hbase.filter.Filter;
047import org.apache.hadoop.hbase.filter.RowFilter;
048import org.apache.hadoop.hbase.filter.SubstringComparator;
049import org.apache.hadoop.hbase.master.RegionState;
050import org.apache.hadoop.hbase.util.Bytes;
051import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
052import org.apache.hadoop.hbase.util.ExceptionUtil;
053import org.apache.hadoop.hbase.util.Pair;
054import org.apache.hadoop.hbase.util.PairOfSameType;
055import org.apache.yetus.audience.InterfaceAudience;
056import org.slf4j.Logger;
057import org.slf4j.LoggerFactory;
058
059/**
060 * Read/write operations on <code>hbase:meta</code> region as well as assignment information stored
061 * to <code>hbase:meta</code>.
062 * <p/>
063 * Some of the methods of this class take ZooKeeperWatcher as a param. The only reason for this is
064 * when this class is used on client-side (e.g. HBaseAdmin), we want to use short-lived connection
065 * (opened before each operation, closed right after), while when used on HM or HRS (like in
066 * AssignmentManager) we want permanent connection.
067 * <p/>
068 * HBASE-10070 adds a replicaId to HRI, meaning more than one HRI can be defined for the same table
069 * range (table, startKey, endKey). For every range, there will be at least one HRI defined which is
070 * called default replica.
071 * <p/>
072 * <h2>Meta layout</h2> For each table there is single row named for the table with a 'table' column
073 * family. The column family currently has one column in it, the 'state' column:
074 *
075 * <pre>
076 * table:state =&gt; contains table state
077 * </pre>
078 *
079 * For the catalog family, see the comments of {@link CatalogFamilyFormat} for more details.
080 * <p/>
081 * TODO: Add rep_barrier for serial replication explanation. See SerialReplicationChecker.
082 * <p/>
083 * The actual layout of meta should be encapsulated inside MetaTableAccessor methods, and should not
084 * leak out of it (through Result objects, etc)
085 * @see CatalogFamilyFormat
086 * @see ClientMetaTableAccessor
087 */
088@InterfaceAudience.Private
089public final class MetaTableAccessor {
090
091  private static final Logger LOG = LoggerFactory.getLogger(MetaTableAccessor.class);
092  private static final Logger METALOG = LoggerFactory.getLogger("org.apache.hadoop.hbase.META");
093
094  private MetaTableAccessor() {
095  }
096
097  ////////////////////////
098  // Reading operations //
099  ////////////////////////
100
101  /**
102   * Performs a full scan of <code>hbase:meta</code> for regions.
103   * @param connection connection we're using
104   * @param visitor    Visitor invoked against each row in regions family.
105   */
106  public static void fullScanRegions(Connection connection,
107    final ClientMetaTableAccessor.Visitor visitor) throws IOException {
108    scanMeta(connection, null, null, QueryType.REGION, visitor);
109  }
110
111  /**
112   * Performs a full scan of <code>hbase:meta</code> for regions.
113   * @param connection connection we're using
114   */
115  public static List<Result> fullScanRegions(Connection connection) throws IOException {
116    return fullScan(connection, QueryType.REGION);
117  }
118
119  /**
120   * Performs a full scan of <code>hbase:meta</code> for tables.
121   * @param connection connection we're using
122   * @param visitor    Visitor invoked against each row in tables family.
123   */
124  public static void fullScanTables(Connection connection,
125    final ClientMetaTableAccessor.Visitor visitor) throws IOException {
126    scanMeta(connection, null, null, QueryType.TABLE, visitor);
127  }
128
129  /**
130   * Performs a full scan of <code>hbase:meta</code>.
131   * @param connection connection we're using
132   * @param type       scanned part of meta
133   * @return List of {@link Result}
134   */
135  private static List<Result> fullScan(Connection connection, QueryType type) throws IOException {
136    ClientMetaTableAccessor.CollectAllVisitor v = new ClientMetaTableAccessor.CollectAllVisitor();
137    scanMeta(connection, null, null, type, v);
138    return v.getResults();
139  }
140
141  /**
142   * Callers should call close on the returned {@link Table} instance.
143   * @param connection connection we're using to access Meta
144   * @return An {@link Table} for <code>hbase:meta</code>
145   * @throws NullPointerException if {@code connection} is {@code null}
146   */
147  public static Table getMetaHTable(final Connection connection) throws IOException {
148    // We used to pass whole CatalogTracker in here, now we just pass in Connection
149    Objects.requireNonNull(connection, "Connection cannot be null");
150    if (connection.isClosed()) {
151      throw new IOException("connection is closed");
152    }
153    return connection.getTable(TableName.META_TABLE_NAME);
154  }
155
156  /**
157   * Gets the region info and assignment for the specified region.
158   * @param connection connection we're using
159   * @param regionName Region to lookup.
160   * @return Location and RegionInfo for <code>regionName</code>
161   * @deprecated use {@link #getRegionLocation(Connection, byte[])} instead
162   */
163  @Deprecated
164  public static Pair<RegionInfo, ServerName> getRegion(Connection connection, byte[] regionName)
165    throws IOException {
166    HRegionLocation location = getRegionLocation(connection, regionName);
167    return location == null ? null : new Pair<>(location.getRegion(), location.getServerName());
168  }
169
170  /**
171   * Returns the HRegionLocation from meta for the given region
172   * @param connection connection we're using
173   * @param regionName region we're looking for
174   * @return HRegionLocation for the given region
175   */
176  public static HRegionLocation getRegionLocation(Connection connection, byte[] regionName)
177    throws IOException {
178    byte[] row = regionName;
179    RegionInfo parsedInfo = null;
180    try {
181      parsedInfo = CatalogFamilyFormat.parseRegionInfoFromRegionName(regionName);
182      row = CatalogFamilyFormat.getMetaKeyForRegion(parsedInfo);
183    } catch (Exception parseEx) {
184      // Ignore. This is used with tableName passed as regionName.
185    }
186    Get get = new Get(row);
187    get.addFamily(HConstants.CATALOG_FAMILY);
188    Result r;
189    try (Table t = getMetaHTable(connection)) {
190      r = t.get(get);
191    }
192    RegionLocations locations = CatalogFamilyFormat.getRegionLocations(r);
193    return locations == null
194      ? null
195      : locations.getRegionLocation(
196        parsedInfo == null ? RegionInfo.DEFAULT_REPLICA_ID : parsedInfo.getReplicaId());
197  }
198
199  /**
200   * Returns the HRegionLocation from meta for the given region
201   * @param connection connection we're using
202   * @param regionInfo region information
203   * @return HRegionLocation for the given region
204   */
205  public static HRegionLocation getRegionLocation(Connection connection, RegionInfo regionInfo)
206    throws IOException {
207    return CatalogFamilyFormat.getRegionLocation(getCatalogFamilyRow(connection, regionInfo),
208      regionInfo, regionInfo.getReplicaId());
209  }
210
211  /** Returns Return the {@link HConstants#CATALOG_FAMILY} row from hbase:meta. */
212  public static Result getCatalogFamilyRow(Connection connection, RegionInfo ri)
213    throws IOException {
214    Get get = new Get(CatalogFamilyFormat.getMetaKeyForRegion(ri));
215    get.addFamily(HConstants.CATALOG_FAMILY);
216    try (Table t = getMetaHTable(connection)) {
217      return t.get(get);
218    }
219  }
220
221  /**
222   * Gets the result in hbase:meta for the specified region.
223   * @param connection connection we're using
224   * @param regionInfo region we're looking for
225   * @return result of the specified region
226   */
227  public static Result getRegionResult(Connection connection, RegionInfo regionInfo)
228    throws IOException {
229    Get get = new Get(CatalogFamilyFormat.getMetaKeyForRegion(regionInfo));
230    get.addFamily(HConstants.CATALOG_FAMILY);
231    try (Table t = getMetaHTable(connection)) {
232      return t.get(get);
233    }
234  }
235
236  /**
237   * Scans META table for a row whose key contains the specified <B>regionEncodedName</B>, returning
238   * a single related <code>Result</code> instance if any row is found, null otherwise.
239   * @param connection        the connection to query META table.
240   * @param regionEncodedName the region encoded name to look for at META.
241   * @return <code>Result</code> instance with the row related info in META, null otherwise.
242   * @throws IOException if any errors occur while querying META.
243   */
244  public static Result scanByRegionEncodedName(Connection connection, String regionEncodedName)
245    throws IOException {
246    RowFilter rowFilter =
247      new RowFilter(CompareOperator.EQUAL, new SubstringComparator(regionEncodedName));
248    Scan scan = getMetaScan(connection.getConfiguration(), 1);
249    scan.setFilter(rowFilter);
250    try (Table table = getMetaHTable(connection);
251      ResultScanner resultScanner = table.getScanner(scan)) {
252      return resultScanner.next();
253    }
254  }
255
256  /**
257   * Lists all of the regions currently in META.
258   * @param connection                  to connect with
259   * @param excludeOfflinedSplitParents False if we are to include offlined/splitparents regions,
260   *                                    true and we'll leave out offlined regions from returned list
261   * @return List of all user-space regions.
262   */
263  public static List<RegionInfo> getAllRegions(Connection connection,
264    boolean excludeOfflinedSplitParents) throws IOException {
265    List<Pair<RegionInfo, ServerName>> result;
266
267    result = getTableRegionsAndLocations(connection, null, excludeOfflinedSplitParents);
268
269    return getListOfRegionInfos(result);
270
271  }
272
273  /**
274   * Gets all of the regions of the specified table. Do not use this method to get meta table
275   * regions, use methods in MetaTableLocator instead.
276   * @param connection connection we're using
277   * @param tableName  table we're looking for
278   * @return Ordered list of {@link RegionInfo}.
279   */
280  public static List<RegionInfo> getTableRegions(Connection connection, TableName tableName)
281    throws IOException {
282    return getTableRegions(connection, tableName, false);
283  }
284
285  /**
286   * Gets all of the regions of the specified table. Do not use this method to get meta table
287   * regions, use methods in MetaTableLocator instead.
288   * @param connection                  connection we're using
289   * @param tableName                   table we're looking for
290   * @param excludeOfflinedSplitParents If true, do not include offlined split parents in the
291   *                                    return.
292   * @return Ordered list of {@link RegionInfo}.
293   */
294  public static List<RegionInfo> getTableRegions(Connection connection, TableName tableName,
295    final boolean excludeOfflinedSplitParents) throws IOException {
296    List<Pair<RegionInfo, ServerName>> result =
297      getTableRegionsAndLocations(connection, tableName, excludeOfflinedSplitParents);
298    return getListOfRegionInfos(result);
299  }
300
301  private static List<RegionInfo>
302    getListOfRegionInfos(final List<Pair<RegionInfo, ServerName>> pairs) {
303    if (pairs == null || pairs.isEmpty()) {
304      return Collections.emptyList();
305    }
306    List<RegionInfo> result = new ArrayList<>(pairs.size());
307    for (Pair<RegionInfo, ServerName> pair : pairs) {
308      result.add(pair.getFirst());
309    }
310    return result;
311  }
312
313  /**
314   * This method creates a Scan object that will only scan catalog rows that belong to the specified
315   * table. It doesn't specify any columns. This is a better alternative to just using a start row
316   * and scan until it hits a new table since that requires parsing the HRI to get the table name.
317   * @param tableName bytes of table's name
318   * @return configured Scan object
319   */
320  public static Scan getScanForTableName(Configuration conf, TableName tableName) {
321    // Start key is just the table name with delimiters
322    byte[] startKey = ClientMetaTableAccessor.getTableStartRowForMeta(tableName, QueryType.REGION);
323    // Stop key appends the smallest possible char to the table name
324    byte[] stopKey = ClientMetaTableAccessor.getTableStopRowForMeta(tableName, QueryType.REGION);
325
326    Scan scan = getMetaScan(conf, -1);
327    scan.withStartRow(startKey);
328    scan.withStopRow(stopKey);
329    return scan;
330  }
331
332  private static Scan getMetaScan(Configuration conf, int rowUpperLimit) {
333    Scan scan = new Scan();
334    int scannerCaching = conf.getInt(HConstants.HBASE_META_SCANNER_CACHING,
335      HConstants.DEFAULT_HBASE_META_SCANNER_CACHING);
336    if (conf.getBoolean(HConstants.USE_META_REPLICAS, HConstants.DEFAULT_USE_META_REPLICAS)) {
337      scan.setConsistency(Consistency.TIMELINE);
338    }
339    if (rowUpperLimit > 0) {
340      scan.setLimit(rowUpperLimit);
341      scan.setReadType(Scan.ReadType.PREAD);
342    }
343    scan.setCaching(scannerCaching);
344    return scan;
345  }
346
347  /**
348   * Do not use this method to get meta table regions, use methods in MetaTableLocator instead.
349   * @param connection connection we're using
350   * @param tableName  table we're looking for
351   * @return Return list of regioninfos and server.
352   */
353  public static List<Pair<RegionInfo, ServerName>>
354    getTableRegionsAndLocations(Connection connection, TableName tableName) throws IOException {
355    return getTableRegionsAndLocations(connection, tableName, true);
356  }
357
358  /**
359   * Do not use this method to get meta table regions, use methods in MetaTableLocator instead.
360   * @param connection                  connection we're using
361   * @param tableName                   table to work with, can be null for getting all regions
362   * @param excludeOfflinedSplitParents don't return split parents
363   * @return Return list of regioninfos and server addresses.
364   */
365  // What happens here when 1M regions in hbase:meta? This won't scale?
366  public static List<Pair<RegionInfo, ServerName>> getTableRegionsAndLocations(
367    Connection connection, @Nullable final TableName tableName,
368    final boolean excludeOfflinedSplitParents) throws IOException {
369    if (tableName != null && tableName.equals(TableName.META_TABLE_NAME)) {
370      throw new IOException(
371        "This method can't be used to locate meta regions;" + " use MetaTableLocator instead");
372    }
373    // Make a version of CollectingVisitor that collects RegionInfo and ServerAddress
374    ClientMetaTableAccessor.CollectRegionLocationsVisitor visitor =
375      new ClientMetaTableAccessor.CollectRegionLocationsVisitor(excludeOfflinedSplitParents);
376    scanMeta(connection,
377      ClientMetaTableAccessor.getTableStartRowForMeta(tableName, QueryType.REGION),
378      ClientMetaTableAccessor.getTableStopRowForMeta(tableName, QueryType.REGION), QueryType.REGION,
379      visitor);
380    return visitor.getResults();
381  }
382
383  public static void fullScanMetaAndPrint(Connection connection) throws IOException {
384    ClientMetaTableAccessor.Visitor v = r -> {
385      if (r == null || r.isEmpty()) {
386        return true;
387      }
388      LOG.info("fullScanMetaAndPrint.Current Meta Row: " + r);
389      TableState state = CatalogFamilyFormat.getTableState(r);
390      if (state != null) {
391        LOG.info("fullScanMetaAndPrint.Table State={}" + state);
392      } else {
393        RegionLocations locations = CatalogFamilyFormat.getRegionLocations(r);
394        if (locations == null) {
395          return true;
396        }
397        for (HRegionLocation loc : locations.getRegionLocations()) {
398          if (loc != null) {
399            LOG.info("fullScanMetaAndPrint.HRI Print={}", loc.getRegion());
400          }
401        }
402      }
403      return true;
404    };
405    scanMeta(connection, null, null, QueryType.ALL, v);
406  }
407
408  public static void scanMetaForTableRegions(Connection connection,
409    ClientMetaTableAccessor.Visitor visitor, TableName tableName) throws IOException {
410    scanMeta(connection, tableName, QueryType.REGION, Integer.MAX_VALUE, visitor);
411  }
412
413  private static void scanMeta(Connection connection, TableName table, QueryType type, int maxRows,
414    final ClientMetaTableAccessor.Visitor visitor) throws IOException {
415    scanMeta(connection, ClientMetaTableAccessor.getTableStartRowForMeta(table, type),
416      ClientMetaTableAccessor.getTableStopRowForMeta(table, type), type, maxRows, visitor);
417  }
418
419  public static void scanMeta(Connection connection, @Nullable final byte[] startRow,
420    @Nullable final byte[] stopRow, QueryType type, final ClientMetaTableAccessor.Visitor visitor)
421    throws IOException {
422    scanMeta(connection, startRow, stopRow, type, Integer.MAX_VALUE, visitor);
423  }
424
425  /**
426   * Performs a scan of META table for given table starting from given row.
427   * @param connection connection we're using
428   * @param visitor    visitor to call
429   * @param tableName  table withing we scan
430   * @param row        start scan from this row
431   * @param rowLimit   max number of rows to return
432   */
433  public static void scanMeta(Connection connection, final ClientMetaTableAccessor.Visitor visitor,
434    final TableName tableName, final byte[] row, final int rowLimit) throws IOException {
435    byte[] startRow = null;
436    byte[] stopRow = null;
437    if (tableName != null) {
438      startRow = ClientMetaTableAccessor.getTableStartRowForMeta(tableName, QueryType.REGION);
439      if (row != null) {
440        RegionInfo closestRi = getClosestRegionInfo(connection, tableName, row);
441        startRow =
442          RegionInfo.createRegionName(tableName, closestRi.getStartKey(), HConstants.ZEROES, false);
443      }
444      stopRow = ClientMetaTableAccessor.getTableStopRowForMeta(tableName, QueryType.REGION);
445    }
446    scanMeta(connection, startRow, stopRow, QueryType.REGION, rowLimit, visitor);
447  }
448
449  /**
450   * Performs a scan of META table.
451   * @param connection connection we're using
452   * @param startRow   Where to start the scan. Pass null if want to begin scan at first row.
453   * @param stopRow    Where to stop the scan. Pass null if want to scan all rows from the start one
454   * @param type       scanned part of meta
455   * @param maxRows    maximum rows to return
456   * @param visitor    Visitor invoked against each row.
457   */
458  public static void scanMeta(Connection connection, @Nullable final byte[] startRow,
459    @Nullable final byte[] stopRow, QueryType type, int maxRows,
460    final ClientMetaTableAccessor.Visitor visitor) throws IOException {
461    scanMeta(connection, startRow, stopRow, type, null, maxRows, visitor);
462  }
463
464  public static void scanMeta(Connection connection, @Nullable final byte[] startRow,
465    @Nullable final byte[] stopRow, QueryType type, @Nullable Filter filter, int maxRows,
466    final ClientMetaTableAccessor.Visitor visitor) throws IOException {
467    int rowUpperLimit = maxRows > 0 ? maxRows : Integer.MAX_VALUE;
468    Scan scan = getMetaScan(connection.getConfiguration(), rowUpperLimit);
469
470    for (byte[] family : type.getFamilies()) {
471      scan.addFamily(family);
472    }
473    if (startRow != null) {
474      scan.withStartRow(startRow);
475    }
476    if (stopRow != null) {
477      scan.withStopRow(stopRow);
478    }
479    if (filter != null) {
480      scan.setFilter(filter);
481    }
482
483    if (LOG.isTraceEnabled()) {
484      LOG.trace("Scanning META" + " starting at row=" + Bytes.toStringBinary(startRow)
485        + " stopping at row=" + Bytes.toStringBinary(stopRow) + " for max=" + rowUpperLimit
486        + " with caching=" + scan.getCaching());
487    }
488
489    int currentRow = 0;
490    try (Table metaTable = getMetaHTable(connection)) {
491      try (ResultScanner scanner = metaTable.getScanner(scan)) {
492        Result data;
493        while ((data = scanner.next()) != null) {
494          if (data.isEmpty()) {
495            continue;
496          }
497          // Break if visit returns false.
498          if (!visitor.visit(data)) {
499            break;
500          }
501          if (++currentRow >= rowUpperLimit) {
502            break;
503          }
504        }
505      }
506    }
507    if (visitor instanceof Closeable) {
508      try {
509        ((Closeable) visitor).close();
510      } catch (Throwable t) {
511        ExceptionUtil.rethrowIfInterrupt(t);
512        LOG.debug("Got exception in closing the meta scanner visitor", t);
513      }
514    }
515  }
516
517  /** Returns Get closest metatable region row to passed <code>row</code> */
518  @NonNull
519  private static RegionInfo getClosestRegionInfo(Connection connection,
520    @NonNull final TableName tableName, @NonNull final byte[] row) throws IOException {
521    byte[] searchRow = RegionInfo.createRegionName(tableName, row, HConstants.NINES, false);
522    Scan scan = getMetaScan(connection.getConfiguration(), 1);
523    scan.setReversed(true);
524    scan.withStartRow(searchRow);
525    try (ResultScanner resultScanner = getMetaHTable(connection).getScanner(scan)) {
526      Result result = resultScanner.next();
527      if (result == null) {
528        throw new TableNotFoundException("Cannot find row in META " + " for table: " + tableName
529          + ", row=" + Bytes.toStringBinary(row));
530      }
531      RegionInfo regionInfo = CatalogFamilyFormat.getRegionInfo(result);
532      if (regionInfo == null) {
533        throw new IOException("RegionInfo was null or empty in Meta for " + tableName + ", row="
534          + Bytes.toStringBinary(row));
535      }
536      return regionInfo;
537    }
538  }
539
540  /**
541   * Returns the {@link ServerName} from catalog table {@link Result} where the region is
542   * transitioning on. It should be the same as
543   * {@link CatalogFamilyFormat#getServerName(Result,int)} if the server is at OPEN state.
544   * @param r Result to pull the transitioning server name from
545   * @return A ServerName instance or {@link CatalogFamilyFormat#getServerName(Result,int)} if
546   *         necessary fields not found or empty.
547   */
548  @Nullable
549  public static ServerName getTargetServerName(final Result r, final int replicaId) {
550    final Cell cell = r.getColumnLatestCell(HConstants.CATALOG_FAMILY,
551      CatalogFamilyFormat.getServerNameColumn(replicaId));
552    if (cell == null || cell.getValueLength() == 0) {
553      RegionLocations locations = CatalogFamilyFormat.getRegionLocations(r);
554      if (locations != null) {
555        HRegionLocation location = locations.getRegionLocation(replicaId);
556        if (location != null) {
557          return location.getServerName();
558        }
559      }
560      return null;
561    }
562    return ServerName.parseServerName(
563      Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
564  }
565
566  /**
567   * Returns the daughter regions by reading the corresponding columns of the catalog table Result.
568   * @param data a Result object from the catalog table scan
569   * @return pair of RegionInfo or PairOfSameType(null, null) if region is not a split parent
570   */
571  public static PairOfSameType<RegionInfo> getDaughterRegions(Result data) {
572    RegionInfo splitA = CatalogFamilyFormat.getRegionInfo(data, HConstants.SPLITA_QUALIFIER);
573    RegionInfo splitB = CatalogFamilyFormat.getRegionInfo(data, HConstants.SPLITB_QUALIFIER);
574    return new PairOfSameType<>(splitA, splitB);
575  }
576
577  /**
578   * Fetch table state for given table from META table
579   * @param conn      connection to use
580   * @param tableName table to fetch state for
581   */
582  @Nullable
583  public static TableState getTableState(Connection conn, TableName tableName) throws IOException {
584    if (tableName.equals(TableName.META_TABLE_NAME)) {
585      return new TableState(tableName, TableState.State.ENABLED);
586    }
587    Table metaHTable = getMetaHTable(conn);
588    Get get = new Get(tableName.getName()).addColumn(HConstants.TABLE_FAMILY,
589      HConstants.TABLE_STATE_QUALIFIER);
590    Result result = metaHTable.get(get);
591    return CatalogFamilyFormat.getTableState(result);
592  }
593
594  /**
595   * Fetch table states from META table
596   * @param conn connection to use
597   * @return map {tableName -&gt; state}
598   */
599  public static Map<TableName, TableState> getTableStates(Connection conn) throws IOException {
600    final Map<TableName, TableState> states = new LinkedHashMap<>();
601    ClientMetaTableAccessor.Visitor collector = r -> {
602      TableState state = CatalogFamilyFormat.getTableState(r);
603      if (state != null) {
604        states.put(state.getTableName(), state);
605      }
606      return true;
607    };
608    fullScanTables(conn, collector);
609    return states;
610  }
611
612  /**
613   * Updates state in META Do not use. For internal use only.
614   * @param conn      connection to use
615   * @param tableName table to look for
616   */
617  public static void updateTableState(Connection conn, TableName tableName, TableState.State actual)
618    throws IOException {
619    updateTableState(conn, new TableState(tableName, actual));
620  }
621
622  ////////////////////////
623  // Editing operations //
624  ////////////////////////
625
626  /**
627   * Generates and returns a {@link Put} containing the {@link RegionInfo} for the catalog table.
628   * @throws IllegalArgumentException when the provided RegionInfo is not the default replica.
629   */
630  public static Put makePutFromRegionInfo(RegionInfo regionInfo) throws IOException {
631    return makePutFromRegionInfo(regionInfo, EnvironmentEdgeManager.currentTime());
632  }
633
634  /**
635   * Generates and returns a {@link Put} containing the {@link RegionInfo} for the catalog table.
636   * @throws IllegalArgumentException when the provided RegionInfo is not the default replica.
637   */
638  public static Put makePutFromRegionInfo(RegionInfo regionInfo, long ts) throws IOException {
639    byte[] metaKeyForRegion = CatalogFamilyFormat.getMetaKeyForRegion(regionInfo);
640    try {
641      Put put = new Put(metaKeyForRegion, ts);
642      return addRegionInfo(put, regionInfo);
643    } catch (IllegalArgumentException ex) {
644      LOG.error(
645        "Got exception while creating put for regioninfo {}." + "meta key for regioninfo is {}",
646        regionInfo.getRegionNameAsString(), metaKeyForRegion);
647      throw ex;
648    }
649  }
650
651  /**
652   * Generates and returns a Delete containing the region info for the catalog table
653   */
654  public static Delete makeDeleteFromRegionInfo(RegionInfo regionInfo, long ts) {
655    if (regionInfo == null) {
656      throw new IllegalArgumentException("Can't make a delete for null region");
657    }
658    if (regionInfo.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) {
659      throw new IllegalArgumentException(
660        "Can't make delete for a replica region. Operate on the primary");
661    }
662    Delete delete = new Delete(CatalogFamilyFormat.getMetaKeyForRegion(regionInfo));
663    delete.addFamily(HConstants.CATALOG_FAMILY, ts);
664    return delete;
665  }
666
667  /**
668   * Adds split daughters to the Put
669   */
670  public static Put addDaughtersToPut(Put put, RegionInfo splitA, RegionInfo splitB)
671    throws IOException {
672    if (splitA != null) {
673      put.add(CellBuilderFactory.create(CellBuilderType.SHALLOW_COPY).setRow(put.getRow())
674        .setFamily(HConstants.CATALOG_FAMILY).setQualifier(HConstants.SPLITA_QUALIFIER)
675        .setTimestamp(put.getTimestamp()).setType(Type.Put).setValue(RegionInfo.toByteArray(splitA))
676        .build());
677    }
678    if (splitB != null) {
679      put.add(CellBuilderFactory.create(CellBuilderType.SHALLOW_COPY).setRow(put.getRow())
680        .setFamily(HConstants.CATALOG_FAMILY).setQualifier(HConstants.SPLITB_QUALIFIER)
681        .setTimestamp(put.getTimestamp()).setType(Type.Put).setValue(RegionInfo.toByteArray(splitB))
682        .build());
683    }
684    return put;
685  }
686
687  /**
688   * Put the passed <code>p</code> to the <code>hbase:meta</code> table.
689   * @param connection connection we're using
690   * @param p          Put to add to hbase:meta
691   */
692  private static void putToMetaTable(Connection connection, Put p) throws IOException {
693    try (Table table = getMetaHTable(connection)) {
694      put(table, p);
695    }
696  }
697
698  /**
699   * @param t Table to use
700   * @param p put to make
701   */
702  private static void put(Table t, Put p) throws IOException {
703    debugLogMutation(p);
704    t.put(p);
705  }
706
707  /**
708   * Put the passed <code>ps</code> to the <code>hbase:meta</code> table.
709   * @param connection connection we're using
710   * @param ps         Put to add to hbase:meta
711   */
712  public static void putsToMetaTable(final Connection connection, final List<Put> ps)
713    throws IOException {
714    if (ps.isEmpty()) {
715      return;
716    }
717    try (Table t = getMetaHTable(connection)) {
718      debugLogMutations(ps);
719      // the implementation for putting a single Put is much simpler so here we do a check first.
720      if (ps.size() == 1) {
721        t.put(ps.get(0));
722      } else {
723        t.put(ps);
724      }
725    }
726  }
727
728  /**
729   * Delete the passed <code>d</code> from the <code>hbase:meta</code> table.
730   * @param connection connection we're using
731   * @param d          Delete to add to hbase:meta
732   */
733  private static void deleteFromMetaTable(final Connection connection, final Delete d)
734    throws IOException {
735    List<Delete> dels = new ArrayList<>(1);
736    dels.add(d);
737    deleteFromMetaTable(connection, dels);
738  }
739
740  /**
741   * Delete the passed <code>deletes</code> from the <code>hbase:meta</code> table.
742   * @param connection connection we're using
743   * @param deletes    Deletes to add to hbase:meta This list should support #remove.
744   */
745  private static void deleteFromMetaTable(final Connection connection, final List<Delete> deletes)
746    throws IOException {
747    try (Table t = getMetaHTable(connection)) {
748      debugLogMutations(deletes);
749      t.delete(deletes);
750    }
751  }
752
753  /**
754   * Set the column value corresponding to this {@code replicaId}'s {@link RegionState} to the
755   * provided {@code state}. Mutates the provided {@link Put}.
756   */
757  public static Put addRegionStateToPut(Put put, int replicaId, RegionState.State state)
758    throws IOException {
759    put.add(CellBuilderFactory.create(CellBuilderType.SHALLOW_COPY).setRow(put.getRow())
760      .setFamily(HConstants.CATALOG_FAMILY)
761      .setQualifier(CatalogFamilyFormat.getRegionStateColumn(replicaId))
762      .setTimestamp(put.getTimestamp()).setType(Cell.Type.Put).setValue(Bytes.toBytes(state.name()))
763      .build());
764    return put;
765  }
766
767  /**
768   * Update state column in hbase:meta.
769   */
770  public static void updateRegionState(Connection connection, RegionInfo ri,
771    RegionState.State state) throws IOException {
772    final Put put = makePutFromRegionInfo(ri);
773    addRegionStateToPut(put, ri.getReplicaId(), state);
774    putsToMetaTable(connection, Collections.singletonList(put));
775  }
776
777  /**
778   * Adds daughter region infos to hbase:meta row for the specified region.
779   * <p/>
780   * Note that this does not add its daughter's as different rows, but adds information about the
781   * daughters in the same row as the parent. Now only used in snapshot. Use
782   * {@link org.apache.hadoop.hbase.master.assignment.RegionStateStore} if you want to split a
783   * region.
784   * @param connection connection we're using
785   * @param regionInfo RegionInfo of parent region
786   * @param splitA     first split daughter of the parent regionInfo
787   * @param splitB     second split daughter of the parent regionInfo
788   * @throws IOException if problem connecting or updating meta
789   */
790  public static void addSplitsToParent(Connection connection, RegionInfo regionInfo,
791    RegionInfo splitA, RegionInfo splitB) throws IOException {
792    try (Table meta = getMetaHTable(connection)) {
793      Put put = makePutFromRegionInfo(regionInfo);
794      addDaughtersToPut(put, splitA, splitB);
795      meta.put(put);
796      debugLogMutation(put);
797      LOG.debug("Added region {}", regionInfo.getRegionNameAsString());
798    }
799  }
800
801  /**
802   * Adds a hbase:meta row for each of the specified new regions. Initial state for new regions is
803   * CLOSED.
804   * @param connection  connection we're using
805   * @param regionInfos region information list
806   * @throws IOException if problem connecting or updating meta
807   */
808  public static void addRegionsToMeta(Connection connection, List<RegionInfo> regionInfos,
809    int regionReplication) throws IOException {
810    addRegionsToMeta(connection, regionInfos, regionReplication,
811      EnvironmentEdgeManager.currentTime());
812  }
813
814  /**
815   * Adds a hbase:meta row for each of the specified new regions. Initial state for new regions is
816   * CLOSED.
817   * @param connection  connection we're using
818   * @param regionInfos region information list
819   * @param ts          desired timestamp
820   * @throws IOException if problem connecting or updating meta
821   */
822  public static void addRegionsToMeta(Connection connection, List<RegionInfo> regionInfos,
823    int regionReplication, long ts) throws IOException {
824    List<Put> puts = new ArrayList<>();
825    for (RegionInfo regionInfo : regionInfos) {
826      if (!RegionReplicaUtil.isDefaultReplica(regionInfo)) {
827        continue;
828      }
829      Put put = makePutFromRegionInfo(regionInfo, ts);
830      // New regions are added with initial state of CLOSED.
831      addRegionStateToPut(put, regionInfo.getReplicaId(), RegionState.State.CLOSED);
832      // Add empty locations for region replicas so that number of replicas can be cached
833      // whenever the primary region is looked up from meta
834      for (int i = 1; i < regionReplication; i++) {
835        addEmptyLocation(put, i);
836      }
837      puts.add(put);
838    }
839    putsToMetaTable(connection, puts);
840    LOG.info("Added {} regions to meta.", puts.size());
841  }
842
843  /**
844   * Update state of the table in meta.
845   * @param connection what we use for update
846   * @param state      new state
847   */
848  private static void updateTableState(Connection connection, TableState state) throws IOException {
849    Put put = makePutFromTableState(state, EnvironmentEdgeManager.currentTime());
850    putToMetaTable(connection, put);
851    LOG.info("Updated {} in hbase:meta", state);
852  }
853
854  /**
855   * Construct PUT for given state
856   * @param state new state
857   */
858  public static Put makePutFromTableState(TableState state, long ts) {
859    Put put = new Put(state.getTableName().getName(), ts);
860    put.addColumn(HConstants.TABLE_FAMILY, HConstants.TABLE_STATE_QUALIFIER,
861      state.convert().toByteArray());
862    return put;
863  }
864
865  /**
866   * Remove state for table from meta
867   * @param connection to use for deletion
868   * @param table      to delete state for
869   */
870  public static void deleteTableState(Connection connection, TableName table) throws IOException {
871    long time = EnvironmentEdgeManager.currentTime();
872    Delete delete = new Delete(table.getName());
873    delete.addColumns(HConstants.TABLE_FAMILY, HConstants.TABLE_STATE_QUALIFIER, time);
874    deleteFromMetaTable(connection, delete);
875    LOG.info("Deleted table " + table + " state from META");
876  }
877
878  /**
879   * Updates the location of the specified region in hbase:meta to be the specified server hostname
880   * and startcode.
881   * <p>
882   * Uses passed catalog tracker to get a connection to the server hosting hbase:meta and makes
883   * edits to that region.
884   * @param connection       connection we're using
885   * @param regionInfo       region to update location of
886   * @param openSeqNum       the latest sequence number obtained when the region was open
887   * @param sn               Server name
888   * @param masterSystemTime wall clock time from master if passed in the open region RPC
889   */
890  public static void updateRegionLocation(Connection connection, RegionInfo regionInfo,
891    ServerName sn, long openSeqNum, long masterSystemTime) throws IOException {
892    updateLocation(connection, regionInfo, sn, openSeqNum, masterSystemTime);
893  }
894
895  /**
896   * Updates the location of the specified region to be the specified server.
897   * <p>
898   * Connects to the specified server which should be hosting the specified catalog region name to
899   * perform the edit.
900   * @param connection       connection we're using
901   * @param regionInfo       region to update location of
902   * @param sn               Server name
903   * @param openSeqNum       the latest sequence number obtained when the region was open
904   * @param masterSystemTime wall clock time from master if passed in the open region RPC
905   * @throws IOException In particular could throw {@link java.net.ConnectException} if the server
906   *                     is down on other end.
907   */
908  private static void updateLocation(Connection connection, RegionInfo regionInfo, ServerName sn,
909    long openSeqNum, long masterSystemTime) throws IOException {
910    // region replicas are kept in the primary region's row
911    Put put = new Put(CatalogFamilyFormat.getMetaKeyForRegion(regionInfo), masterSystemTime);
912    addRegionInfo(put, regionInfo);
913    addLocation(put, sn, openSeqNum, regionInfo.getReplicaId());
914    putToMetaTable(connection, put);
915    LOG.info("Updated row {} with server=", regionInfo.getRegionNameAsString(), sn);
916  }
917
918  public static Put addRegionInfo(final Put p, final RegionInfo hri) throws IOException {
919    p.add(CellBuilderFactory.create(CellBuilderType.SHALLOW_COPY).setRow(p.getRow())
920      .setFamily(HConstants.CATALOG_FAMILY).setQualifier(HConstants.REGIONINFO_QUALIFIER)
921      .setTimestamp(p.getTimestamp()).setType(Type.Put)
922      // Serialize the Default Replica HRI otherwise scan of hbase:meta
923      // shows an info:regioninfo value with encoded name and region
924      // name that differs from that of the hbase;meta row.
925      .setValue(RegionInfo.toByteArray(RegionReplicaUtil.getRegionInfoForDefaultReplica(hri)))
926      .build());
927    return p;
928  }
929
930  public static Put addLocation(Put p, ServerName sn, long openSeqNum, int replicaId)
931    throws IOException {
932    CellBuilder builder = CellBuilderFactory.create(CellBuilderType.SHALLOW_COPY);
933    return p
934      .add(builder.clear().setRow(p.getRow()).setFamily(HConstants.CATALOG_FAMILY)
935        .setQualifier(CatalogFamilyFormat.getServerColumn(replicaId)).setTimestamp(p.getTimestamp())
936        .setType(Cell.Type.Put).setValue(Bytes.toBytes(sn.getAddress().toString())).build())
937      .add(builder.clear().setRow(p.getRow()).setFamily(HConstants.CATALOG_FAMILY)
938        .setQualifier(CatalogFamilyFormat.getStartCodeColumn(replicaId))
939        .setTimestamp(p.getTimestamp()).setType(Cell.Type.Put)
940        .setValue(Bytes.toBytes(sn.getStartcode())).build())
941      .add(builder.clear().setRow(p.getRow()).setFamily(HConstants.CATALOG_FAMILY)
942        .setQualifier(CatalogFamilyFormat.getSeqNumColumn(replicaId)).setTimestamp(p.getTimestamp())
943        .setType(Type.Put).setValue(Bytes.toBytes(openSeqNum)).build());
944  }
945
946  public static Put addEmptyLocation(Put p, int replicaId) throws IOException {
947    CellBuilder builder = CellBuilderFactory.create(CellBuilderType.SHALLOW_COPY);
948    return p
949      .add(builder.clear().setRow(p.getRow()).setFamily(HConstants.CATALOG_FAMILY)
950        .setQualifier(CatalogFamilyFormat.getServerColumn(replicaId)).setTimestamp(p.getTimestamp())
951        .setType(Type.Put).build())
952      .add(builder.clear().setRow(p.getRow()).setFamily(HConstants.CATALOG_FAMILY)
953        .setQualifier(CatalogFamilyFormat.getStartCodeColumn(replicaId))
954        .setTimestamp(p.getTimestamp()).setType(Cell.Type.Put).build())
955      .add(builder.clear().setRow(p.getRow()).setFamily(HConstants.CATALOG_FAMILY)
956        .setQualifier(CatalogFamilyFormat.getSeqNumColumn(replicaId)).setTimestamp(p.getTimestamp())
957        .setType(Cell.Type.Put).build());
958  }
959
960  private static void debugLogMutations(List<? extends Mutation> mutations) throws IOException {
961    if (!METALOG.isDebugEnabled()) {
962      return;
963    }
964    // Logging each mutation in separate line makes it easier to see diff between them visually
965    // because of common starting indentation.
966    for (Mutation mutation : mutations) {
967      debugLogMutation(mutation);
968    }
969  }
970
971  private static void debugLogMutation(Mutation p) throws IOException {
972    METALOG.debug("{} {}", p.getClass().getSimpleName(), p.toJSON());
973  }
974}