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