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 = ConnectionRegistryFactory.create(TEST_UTIL.getConfiguration(), User.getCurrent());
081    CONN = new AsyncConnectionImpl(conf, registry, registry.getClusterId().get(), null,
082      User.getCurrent());
083  }
084
085  @AfterClass
086  public static void tearDown() throws Exception {
087    Closeables.close(CONN, true);
088    TEST_UTIL.shutdownMiniCluster();
089  }
090
091  @Test
092  public void testMetaChangeFromReplicaNoReplica() throws IOException, InterruptedException {
093    String replicaSelectorClass =
094      CONN.getConfiguration().get(RegionLocator.LOCATOR_META_REPLICAS_MODE_LOADBALANCE_SELECTOR,
095        CatalogReplicaLoadBalanceSimpleSelector.class.getName());
096
097    CatalogReplicaLoadBalanceSelector metaSelector = CatalogReplicaLoadBalanceSelectorFactory
098      .createSelector(replicaSelectorClass, META_TABLE_NAME, CONN, () -> {
099        int numOfReplicas = CatalogReplicaLoadBalanceSelector.UNINITIALIZED_NUM_OF_REPLICAS;
100        try {
101          RegionLocations metaLocations = CONN.registry.getMetaRegionLocations()
102            .get(CONN.connConf.getReadRpcTimeoutNs(), TimeUnit.NANOSECONDS);
103          numOfReplicas = metaLocations.size();
104        } catch (Exception e) {
105          LOG.error("Failed to get table {}'s region replication, ", META_TABLE_NAME, e);
106        }
107        return numOfReplicas;
108      });
109
110    // Loop for 100 times, it should cover all replica ids.
111    int[] replicaIdCount = new int[numOfMetaReplica];
112    IntStream.range(1, 100).forEach(i -> replicaIdCount[metaSelector
113      .select(TableName.valueOf("test"), EMPTY_START_ROW, RegionLocateType.CURRENT)]++);
114
115    // Make sure each replica id is returned by select() call, including primary replica id.
116    IntStream.range(0, numOfMetaReplica).forEach(i -> assertNotEquals(replicaIdCount[i], 0));
117
118    // Change to No meta replica
119    HBaseTestingUtil.setReplicas(admin, TableName.META_TABLE_NAME, 1);
120    TEST_UTIL.waitFor(30000,
121      () -> TEST_UTIL.getMiniHBaseCluster().getRegions(TableName.META_TABLE_NAME).size() == 1);
122
123    CatalogReplicaLoadBalanceSelector metaSelectorWithNoReplica =
124      CatalogReplicaLoadBalanceSelectorFactory.createSelector(replicaSelectorClass, META_TABLE_NAME,
125        CONN, () -> {
126          int numOfReplicas = CatalogReplicaLoadBalanceSelector.UNINITIALIZED_NUM_OF_REPLICAS;
127          try {
128            RegionLocations metaLocations = CONN.registry.getMetaRegionLocations()
129              .get(CONN.connConf.getReadRpcTimeoutNs(), TimeUnit.NANOSECONDS);
130            numOfReplicas = metaLocations.size();
131          } catch (Exception e) {
132            LOG.error("Failed to get table {}'s region replication, ", META_TABLE_NAME, e);
133          }
134          return numOfReplicas;
135        });
136    assertEquals(metaSelectorWithNoReplica.select(TableName.valueOf("test"), EMPTY_START_ROW,
137      RegionLocateType.CURRENT), RegionReplicaUtil.DEFAULT_REPLICA_ID);
138  }
139}