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