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.security.User;
039import org.apache.hadoop.hbase.testclassification.MasterTests;
040import org.apache.hadoop.hbase.testclassification.SmallTests;
041import org.apache.hadoop.hbase.util.JVMClusterUtil;
042import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
043import org.apache.hadoop.hbase.zookeeper.ZKUtil;
044import org.apache.hadoop.hbase.zookeeper.ZKWatcher;
045import org.apache.hadoop.hbase.zookeeper.ZNodePaths;
046import org.junit.AfterClass;
047import org.junit.BeforeClass;
048import org.junit.ClassRule;
049import org.junit.Test;
050import org.junit.experimental.categories.Category;
051
052import org.apache.hbase.thirdparty.com.google.common.io.Closeables;
053
054@Category({ SmallTests.class, MasterTests.class })
055public class TestMetaRegionLocationCache {
056  @ClassRule
057  public static final HBaseClassTestRule CLASS_RULE =
058    HBaseClassTestRule.forClass(TestMetaRegionLocationCache.class);
059
060  private static final HBaseTestingUtil TEST_UTIL = new HBaseTestingUtil();
061  private static ConnectionRegistry REGISTRY;
062
063  @BeforeClass
064  public static void setUp() throws Exception {
065    TEST_UTIL.startMiniCluster(3);
066    HBaseTestingUtil.setReplicas(TEST_UTIL.getAdmin(), TableName.META_TABLE_NAME, 3);
067    REGISTRY = ConnectionRegistryFactory.create(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().isEmpty()) {
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().size() != metaZnodes.size()
105    ) {
106      Thread.sleep(1000);
107      if (++retries == 10) {
108        break;
109      }
110    }
111    List<HRegionLocation> metaHRLs = master.getMetaRegionLocationCache().getMetaRegionLocations();
112    assertFalse(metaHRLs.isEmpty());
113    assertEquals(metaZnodes.size(), metaHRLs.size());
114    List<HRegionLocation> actualHRLs = getCurrentMetaLocations(zk);
115    Collections.sort(metaHRLs);
116    Collections.sort(actualHRLs);
117    assertEquals(actualHRLs, metaHRLs);
118  }
119
120  @Test
121  public void testInitialMetaLocations() throws Exception {
122    verifyCachedMetaLocations(TEST_UTIL.getMiniHBaseCluster().getMaster());
123  }
124
125  @Test
126  public void testStandByMetaLocations() throws Exception {
127    HMaster standBy = TEST_UTIL.getMiniHBaseCluster().startMaster().getMaster();
128    verifyCachedMetaLocations(standBy);
129  }
130
131  /*
132   * Shuffles the meta region replicas around the cluster and makes sure the cache is not stale.
133   */
134  @Test
135  public void testMetaLocationsChange() throws Exception {
136    List<HRegionLocation> currentMetaLocs =
137      getCurrentMetaLocations(TEST_UTIL.getMiniHBaseCluster().getMaster().getZooKeeper());
138    // Move these replicas to random servers.
139    for (HRegionLocation location : currentMetaLocs) {
140      RegionReplicaTestHelper.moveRegion(TEST_UTIL, location);
141    }
142    RegionReplicaTestHelper.waitUntilAllMetaReplicasAreReady(TEST_UTIL, REGISTRY);
143    for (JVMClusterUtil.MasterThread masterThread : TEST_UTIL.getMiniHBaseCluster()
144      .getMasterThreads()) {
145      verifyCachedMetaLocations(masterThread.getMaster());
146    }
147  }
148
149  /**
150   * Tests MetaRegionLocationCache's init procedure to make sure that it correctly watches the base
151   * znode for notifications.
152   */
153  @Test
154  public void testMetaRegionLocationCache() throws Exception {
155    final String parentZnodeName = "/randomznodename";
156    Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
157    conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, parentZnodeName);
158    ServerName sn = ServerName.valueOf("localhost", 1234, 5678);
159    try (ZKWatcher zkWatcher = new ZKWatcher(conf, null, null, true)) {
160      // A thread that repeatedly creates and drops an unrelated child znode. This is to simulate
161      // some ZK activity in the background.
162      MultithreadedTestUtil.TestContext ctx = new MultithreadedTestUtil.TestContext(conf);
163      ctx.addThread(new MultithreadedTestUtil.RepeatingTestThread(ctx) {
164        @Override
165        public void doAnAction() throws Exception {
166          final String testZnode = parentZnodeName + "/child";
167          ZKUtil.createNodeIfNotExistsAndWatch(zkWatcher, testZnode, testZnode.getBytes());
168          ZKUtil.deleteNode(zkWatcher, testZnode);
169        }
170      });
171      ctx.startThreads();
172      try {
173        MetaRegionLocationCache metaCache = new MetaRegionLocationCache(zkWatcher);
174        // meta znodes do not exist at this point, cache should be empty.
175        assertTrue(metaCache.getMetaRegionLocations().isEmpty());
176        // Set the meta locations for a random meta replicas, simulating an active hmaster meta
177        // assignment.
178        for (int i = 0; i < 3; i++) {
179          // Updates the meta znodes.
180          MetaTableLocator.setMetaLocation(zkWatcher, sn, i, RegionState.State.OPEN);
181        }
182        // Wait until the meta cache is populated.
183        int iters = 0;
184        while (iters++ < 10) {
185          if (metaCache.getMetaRegionLocations().size() == 3) {
186            break;
187          }
188          Thread.sleep(1000);
189        }
190        List<HRegionLocation> metaLocations = metaCache.getMetaRegionLocations();
191        assertEquals(3, metaLocations.size());
192        for (HRegionLocation location : metaLocations) {
193          assertEquals(sn, location.getServerName());
194        }
195      } finally {
196        // clean up.
197        ctx.stop();
198        ZKUtil.deleteChildrenRecursively(zkWatcher, parentZnodeName);
199      }
200    }
201  }
202}