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.junit.Assert.assertEquals;
021import static org.junit.Assert.assertFalse;
022import static org.junit.Assert.assertTrue;
023
024import java.util.ArrayList;
025import java.util.Collections;
026import java.util.List;
027import org.apache.hadoop.conf.Configuration;
028import org.apache.hadoop.hbase.HBaseClassTestRule;
029import org.apache.hadoop.hbase.HBaseTestingUtil;
030import org.apache.hadoop.hbase.HConstants;
031import org.apache.hadoop.hbase.HRegionLocation;
032import org.apache.hadoop.hbase.MetaRegionLocationCache;
033import org.apache.hadoop.hbase.MultithreadedTestUtil;
034import org.apache.hadoop.hbase.ServerName;
035import org.apache.hadoop.hbase.TableName;
036import org.apache.hadoop.hbase.master.HMaster;
037import org.apache.hadoop.hbase.master.RegionState;
038import org.apache.hadoop.hbase.testclassification.MasterTests;
039import org.apache.hadoop.hbase.testclassification.SmallTests;
040import org.apache.hadoop.hbase.util.JVMClusterUtil;
041import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
042import org.apache.hadoop.hbase.zookeeper.ZKUtil;
043import org.apache.hadoop.hbase.zookeeper.ZKWatcher;
044import org.apache.hadoop.hbase.zookeeper.ZNodePaths;
045import org.junit.AfterClass;
046import org.junit.BeforeClass;
047import org.junit.ClassRule;
048import org.junit.Test;
049import org.junit.experimental.categories.Category;
050
051import org.apache.hbase.thirdparty.com.google.common.io.Closeables;
052
053@Category({SmallTests.class, MasterTests.class })
054public class TestMetaRegionLocationCache {
055  @ClassRule
056  public static final HBaseClassTestRule CLASS_RULE =
057      HBaseClassTestRule.forClass(TestMetaRegionLocationCache.class);
058
059  private static final HBaseTestingUtil TEST_UTIL = new HBaseTestingUtil();
060  private static ConnectionRegistry REGISTRY;
061
062  @BeforeClass
063  public static void setUp() throws Exception {
064    TEST_UTIL.startMiniCluster(3);
065    HBaseTestingUtil.setReplicas(TEST_UTIL.getAdmin(), TableName.META_TABLE_NAME, 3);
066    REGISTRY = ConnectionRegistryFactory.getRegistry(TEST_UTIL.getConfiguration());
067    RegionReplicaTestHelper.waitUntilAllMetaReplicasAreReady(TEST_UTIL, REGISTRY);
068    TEST_UTIL.getAdmin().balancerSwitch(false, true);
069  }
070
071  @AfterClass
072  public static void cleanUp() throws Exception {
073    Closeables.close(REGISTRY, true);
074    TEST_UTIL.shutdownMiniCluster();
075  }
076
077  private List<HRegionLocation> getCurrentMetaLocations(ZKWatcher zk) throws Exception {
078    List<HRegionLocation> result = new ArrayList<>();
079    for (String znode: zk.getMetaReplicaNodes()) {
080      String path = ZNodePaths.joinZNode(zk.getZNodePaths().baseZNode, znode);
081      int replicaId = zk.getZNodePaths().getMetaReplicaIdFromPath(path);
082      RegionState state = MetaTableLocator.getMetaRegionState(zk, replicaId);
083      result.add(new HRegionLocation(state.getRegion(), state.getServerName()));
084    }
085    return result;
086  }
087
088  // Verifies that the cached meta locations in the given master are in sync with what is in ZK.
089  private void verifyCachedMetaLocations(HMaster master) throws Exception {
090    // Wait until initial meta locations are loaded.
091    int retries = 0;
092    while (master.getMetaRegionLocationCache().getMetaRegionLocations().isEmpty()) {
093      Thread.sleep(1000);
094      if (++retries == 10) {
095        break;
096      }
097    }
098    ZKWatcher zk = master.getZooKeeper();
099    List<String> metaZnodes = zk.getMetaReplicaNodes();
100    // Wait till all replicas available.
101    retries = 0;
102    while (master.getMetaRegionLocationCache().getMetaRegionLocations().size() != metaZnodes
103      .size()) {
104      Thread.sleep(1000);
105      if (++retries == 10) {
106        break;
107      }
108    }
109    List<HRegionLocation> metaHRLs = master.getMetaRegionLocationCache().getMetaRegionLocations();
110    assertFalse(metaHRLs.isEmpty());
111    assertEquals(metaZnodes.size(), metaHRLs.size());
112    List<HRegionLocation> actualHRLs = getCurrentMetaLocations(zk);
113    Collections.sort(metaHRLs);
114    Collections.sort(actualHRLs);
115    assertEquals(actualHRLs, metaHRLs);
116  }
117
118  @Test
119  public void testInitialMetaLocations() throws Exception {
120    verifyCachedMetaLocations(TEST_UTIL.getMiniHBaseCluster().getMaster());
121  }
122
123  @Test
124  public void testStandByMetaLocations() throws Exception {
125    HMaster standBy = TEST_UTIL.getMiniHBaseCluster().startMaster().getMaster();
126    verifyCachedMetaLocations(standBy);
127  }
128
129  /*
130   * Shuffles the meta region replicas around the cluster and makes sure the cache is not stale.
131   */
132  @Test public void testMetaLocationsChange() throws Exception {
133    List<HRegionLocation> currentMetaLocs =
134        getCurrentMetaLocations(TEST_UTIL.getMiniHBaseCluster().getMaster().getZooKeeper());
135    // Move these replicas to random servers.
136    for (HRegionLocation location: currentMetaLocs) {
137      RegionReplicaTestHelper.moveRegion(TEST_UTIL, location);
138    }
139    RegionReplicaTestHelper.waitUntilAllMetaReplicasAreReady(TEST_UTIL, REGISTRY);
140    for (JVMClusterUtil.MasterThread masterThread:
141        TEST_UTIL.getMiniHBaseCluster().getMasterThreads()) {
142      verifyCachedMetaLocations(masterThread.getMaster());
143    }
144  }
145
146  /**
147   * Tests MetaRegionLocationCache's init procedure to make sure that it correctly watches the base
148   * znode for notifications.
149   */
150  @Test public void testMetaRegionLocationCache() throws Exception {
151    final String parentZnodeName = "/randomznodename";
152    Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
153    conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, parentZnodeName);
154    ServerName sn = ServerName.valueOf("localhost", 1234, 5678);
155    try (ZKWatcher zkWatcher = new ZKWatcher(conf, null, null, true)) {
156      // A thread that repeatedly creates and drops an unrelated child znode. This is to simulate
157      // some ZK activity in the background.
158      MultithreadedTestUtil.TestContext ctx = new MultithreadedTestUtil.TestContext(conf);
159      ctx.addThread(new MultithreadedTestUtil.RepeatingTestThread(ctx) {
160        @Override public void doAnAction() throws Exception {
161          final String testZnode = parentZnodeName + "/child";
162          ZKUtil.createNodeIfNotExistsAndWatch(zkWatcher, testZnode, testZnode.getBytes());
163          ZKUtil.deleteNode(zkWatcher, testZnode);
164        }
165      });
166      ctx.startThreads();
167      try {
168        MetaRegionLocationCache metaCache = new MetaRegionLocationCache(zkWatcher);
169        // meta znodes do not exist at this point, cache should be empty.
170        assertTrue(metaCache.getMetaRegionLocations().isEmpty());
171        // Set the meta locations for a random meta replicas, simulating an active hmaster meta
172        // assignment.
173        for (int i = 0; i < 3; i++) {
174          // Updates the meta znodes.
175          MetaTableLocator.setMetaLocation(zkWatcher, sn, i, RegionState.State.OPEN);
176        }
177        // Wait until the meta cache is populated.
178        int iters = 0;
179        while (iters++ < 10) {
180          if (metaCache.getMetaRegionLocations().size() == 3) {
181            break;
182          }
183          Thread.sleep(1000);
184        }
185        List<HRegionLocation> metaLocations = metaCache.getMetaRegionLocations();
186        assertEquals(3, metaLocations.size());
187        for (HRegionLocation location : metaLocations) {
188          assertEquals(sn, location.getServerName());
189        }
190      } finally {
191        // clean up.
192        ctx.stop();
193        ZKUtil.deleteChildrenRecursively(zkWatcher, parentZnodeName);
194      }
195    }
196  }
197}