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.client;
019
020import static org.apache.hadoop.hbase.HConstants.EMPTY_START_ROW;
021import static org.apache.hadoop.hbase.TableName.META_TABLE_NAME;
022import static org.junit.jupiter.api.Assertions.assertEquals;
023import static org.junit.jupiter.api.Assertions.assertNotEquals;
024
025import java.io.IOException;
026import java.util.concurrent.TimeUnit;
027import java.util.stream.IntStream;
028import org.apache.hadoop.conf.Configuration;
029import org.apache.hadoop.hbase.HBaseTestingUtil;
030import org.apache.hadoop.hbase.RegionLocations;
031import org.apache.hadoop.hbase.TableName;
032import org.apache.hadoop.hbase.security.User;
033import org.apache.hadoop.hbase.testclassification.ClientTests;
034import org.apache.hadoop.hbase.testclassification.MediumTests;
035import org.junit.jupiter.api.AfterAll;
036import org.junit.jupiter.api.BeforeAll;
037import org.junit.jupiter.api.Tag;
038import org.junit.jupiter.api.Test;
039import org.slf4j.Logger;
040import org.slf4j.LoggerFactory;
041
042import org.apache.hbase.thirdparty.com.google.common.io.Closeables;
043
044@Tag(MediumTests.TAG)
045@Tag(ClientTests.TAG)
046public class TestCatalogReplicaLoadBalanceSimpleSelector {
047
048  private static final Logger LOG =
049    LoggerFactory.getLogger(TestCatalogReplicaLoadBalanceSimpleSelector.class);
050
051  private static final HBaseTestingUtil TEST_UTIL = new HBaseTestingUtil();
052
053  private static final int NB_SERVERS = 4;
054  private static int numOfMetaReplica = NB_SERVERS - 1;
055
056  private static AsyncConnectionImpl CONN;
057
058  private static ConnectionRegistry registry;
059  private static Admin admin;
060
061  @BeforeAll
062  public static void setUp() throws Exception {
063    Configuration conf = TEST_UTIL.getConfiguration();
064
065    TEST_UTIL.startMiniCluster(NB_SERVERS);
066    admin = TEST_UTIL.getAdmin();
067    admin.balancerSwitch(false, true);
068
069    // Enable hbase:meta replication.
070    HBaseTestingUtil.setReplicas(admin, TableName.META_TABLE_NAME, numOfMetaReplica);
071    TEST_UTIL.waitFor(30000,
072      () -> TEST_UTIL.getMiniHBaseCluster().getRegions(TableName.META_TABLE_NAME).size()
073          >= numOfMetaReplica);
074
075    registry = ConnectionRegistryFactory.create(TEST_UTIL.getConfiguration(), User.getCurrent());
076    CONN = new AsyncConnectionImpl(conf, registry, registry.getClusterId().get(), null,
077      User.getCurrent());
078  }
079
080  @AfterAll
081  public static void tearDown() throws Exception {
082    Closeables.close(CONN, true);
083    TEST_UTIL.shutdownMiniCluster();
084  }
085
086  @Test
087  public void testMetaChangeFromReplicaNoReplica() throws IOException, InterruptedException {
088    String replicaSelectorClass =
089      CONN.getConfiguration().get(RegionLocator.LOCATOR_META_REPLICAS_MODE_LOADBALANCE_SELECTOR,
090        CatalogReplicaLoadBalanceSimpleSelector.class.getName());
091
092    CatalogReplicaLoadBalanceSelector metaSelector = CatalogReplicaLoadBalanceSelectorFactory
093      .createSelector(replicaSelectorClass, META_TABLE_NAME, CONN, () -> {
094        int numOfReplicas = CatalogReplicaLoadBalanceSelector.UNINITIALIZED_NUM_OF_REPLICAS;
095        try {
096          RegionLocations metaLocations = CONN.registry.getMetaRegionLocations()
097            .get(CONN.connConf.getMetaReadRpcTimeoutNs(), TimeUnit.NANOSECONDS);
098          numOfReplicas = metaLocations.size();
099        } catch (Exception e) {
100          LOG.error("Failed to get table {}'s region replication, ", META_TABLE_NAME, e);
101        }
102        return numOfReplicas;
103      });
104
105    // Loop for 100 times, it should cover all replica ids.
106    int[] replicaIdCount = new int[numOfMetaReplica];
107    IntStream.range(1, 100).forEach(i -> replicaIdCount[metaSelector
108      .select(TableName.valueOf("test"), EMPTY_START_ROW, RegionLocateType.CURRENT)]++);
109
110    // Make sure each replica id is returned by select() call, including primary replica id.
111    IntStream.range(0, numOfMetaReplica).forEach(i -> assertNotEquals(replicaIdCount[i], 0));
112
113    // Change to No meta replica
114    HBaseTestingUtil.setReplicas(admin, TableName.META_TABLE_NAME, 1);
115    TEST_UTIL.waitFor(30000,
116      () -> TEST_UTIL.getMiniHBaseCluster().getRegions(TableName.META_TABLE_NAME).size() == 1);
117
118    CatalogReplicaLoadBalanceSelector metaSelectorWithNoReplica =
119      CatalogReplicaLoadBalanceSelectorFactory.createSelector(replicaSelectorClass, META_TABLE_NAME,
120        CONN, () -> {
121          int numOfReplicas = CatalogReplicaLoadBalanceSelector.UNINITIALIZED_NUM_OF_REPLICAS;
122          try {
123            RegionLocations metaLocations = CONN.registry.getMetaRegionLocations()
124              .get(CONN.connConf.getMetaReadRpcTimeoutNs(), TimeUnit.NANOSECONDS);
125            numOfReplicas = metaLocations.size();
126          } catch (Exception e) {
127            LOG.error("Failed to get table {}'s region replication, ", META_TABLE_NAME, e);
128          }
129          return numOfReplicas;
130        });
131    assertEquals(metaSelectorWithNoReplica.select(TableName.valueOf("test"), EMPTY_START_ROW,
132      RegionLocateType.CURRENT), RegionReplicaUtil.DEFAULT_REPLICA_ID);
133  }
134}