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;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertFalse;
022import static org.junit.Assert.assertTrue;
023
024import edu.umd.cs.findbugs.annotations.NonNull;
025import java.util.List;
026import java.util.Map;
027import org.apache.hadoop.conf.Configuration;
028import org.apache.hadoop.hbase.client.Admin;
029import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
030import org.apache.hadoop.hbase.client.Put;
031import org.apache.hadoop.hbase.client.RegionInfo;
032import org.apache.hadoop.hbase.client.ResultScanner;
033import org.apache.hadoop.hbase.client.Scan;
034import org.apache.hadoop.hbase.client.Table;
035import org.apache.hadoop.hbase.client.TableDescriptor;
036import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
037import org.apache.hadoop.hbase.coordination.ZkSplitLogWorkerCoordination;
038import org.apache.hadoop.hbase.master.HMaster;
039import org.apache.hadoop.hbase.master.LoadBalancer;
040import org.apache.hadoop.hbase.master.balancer.SimpleLoadBalancer;
041import org.apache.hadoop.hbase.testclassification.MediumTests;
042import org.apache.hadoop.hbase.testclassification.MiscTests;
043import org.apache.hadoop.hbase.util.Bytes;
044import org.apache.hadoop.hbase.util.CommonFSUtils;
045import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
046import org.apache.hadoop.hbase.zookeeper.ZKUtil;
047import org.apache.hadoop.hbase.zookeeper.ZKWatcher;
048import org.apache.zookeeper.KeeperException;
049import org.junit.After;
050import org.junit.AfterClass;
051import org.junit.Before;
052import org.junit.BeforeClass;
053import org.junit.ClassRule;
054import org.junit.Rule;
055import org.junit.Test;
056import org.junit.experimental.categories.Category;
057import org.junit.rules.TestName;
058import org.slf4j.Logger;
059import org.slf4j.LoggerFactory;
060
061@Category({ MiscTests.class, MediumTests.class })
062public class TestZooKeeper {
063
064  @ClassRule
065  public static final HBaseClassTestRule CLASS_RULE =
066    HBaseClassTestRule.forClass(TestZooKeeper.class);
067
068  private static final Logger LOG = LoggerFactory.getLogger(TestZooKeeper.class);
069
070  private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
071
072  @Rule
073  public TestName name = new TestName();
074
075  @BeforeClass
076  public static void setUpBeforeClass() throws Exception {
077    // Test we can first start the ZK cluster by itself
078    Configuration conf = TEST_UTIL.getConfiguration();
079    // A couple of tests rely on master expiring ZK session, hence killing the only master. So it
080    // makes sense only for ZK registry. Enforcing it.
081    conf.set(HConstants.CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY,
082      HConstants.ZK_CONNECTION_REGISTRY_CLASS);
083    TEST_UTIL.startMiniDFSCluster(2);
084    TEST_UTIL.startMiniZKCluster();
085    conf.setInt(HConstants.ZK_SESSION_TIMEOUT, 1000);
086    conf.setClass(HConstants.HBASE_MASTER_LOADBALANCER_CLASS, MockLoadBalancer.class,
087      LoadBalancer.class);
088    TEST_UTIL.startMiniDFSCluster(2);
089  }
090
091  @AfterClass
092  public static void tearDownAfterClass() throws Exception {
093    TEST_UTIL.shutdownMiniCluster();
094  }
095
096  @Before
097  public void setUp() throws Exception {
098    StartMiniClusterOption option =
099      StartMiniClusterOption.builder().numMasters(2).numRegionServers(2).build();
100    TEST_UTIL.startMiniHBaseCluster(option);
101  }
102
103  @After
104  public void after() throws Exception {
105    try {
106      TEST_UTIL.getHBaseCluster().waitForActiveAndReadyMaster(10000);
107      // Some regionserver could fail to delete its znode.
108      // So shutdown could hang. Let's kill them all instead.
109      TEST_UTIL.getHBaseCluster().killAll();
110
111      // Still need to clean things up
112      TEST_UTIL.shutdownMiniHBaseCluster();
113    } finally {
114      TEST_UTIL.getTestFileSystem().delete(CommonFSUtils.getRootDir(TEST_UTIL.getConfiguration()),
115        true);
116      ZKUtil.deleteNodeRecursively(TEST_UTIL.getZooKeeperWatcher(), "/hbase");
117    }
118  }
119
120  @Test
121  public void testRegionServerSessionExpired() throws Exception {
122    LOG.info("Starting " + name.getMethodName());
123    TEST_UTIL.expireRegionServerSession(0);
124    testSanity(name.getMethodName());
125  }
126
127  @Test
128  public void testMasterSessionExpired() throws Exception {
129    LOG.info("Starting " + name.getMethodName());
130    TEST_UTIL.expireMasterSession();
131    testSanity(name.getMethodName());
132  }
133
134  /**
135   * Master recovery when the znode already exists. Internally, this test differs from
136   * {@link #testMasterSessionExpired} because here the master znode will exist in ZK.
137   */
138  @Test
139  public void testMasterZKSessionRecoveryFailure() throws Exception {
140    LOG.info("Starting " + name.getMethodName());
141    MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
142    HMaster m = cluster.getMaster();
143    m.abort("Test recovery from zk session expired", new KeeperException.SessionExpiredException());
144    assertTrue(m.isStopped()); // Master doesn't recover any more
145    testSanity(name.getMethodName());
146  }
147
148  /**
149   * Make sure we can use the cluster
150   */
151  private void testSanity(final String testName) throws Exception {
152    String tableName = testName + "_" + EnvironmentEdgeManager.currentTime();
153    TableDescriptor desc = TableDescriptorBuilder.newBuilder(TableName.valueOf(tableName))
154      .setColumnFamily(ColumnFamilyDescriptorBuilder.of("fam")).build();
155    LOG.info("Creating table " + tableName);
156    Admin admin = TEST_UTIL.getAdmin();
157    try {
158      admin.createTable(desc);
159    } finally {
160      admin.close();
161    }
162
163    Table table = TEST_UTIL.getConnection().getTable(desc.getTableName());
164    Put put = new Put(Bytes.toBytes("testrow"));
165    put.addColumn(Bytes.toBytes("fam"), Bytes.toBytes("col"), Bytes.toBytes("testdata"));
166    LOG.info("Putting table " + tableName);
167    table.put(put);
168    table.close();
169  }
170
171  /**
172   * Tests that the master does not call retainAssignment after recovery from expired zookeeper
173   * session. Without the HBASE-6046 fix master always tries to assign all the user regions by
174   * calling retainAssignment.
175   */
176  @Test
177  public void testRegionAssignmentAfterMasterRecoveryDueToZKExpiry() throws Exception {
178    MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
179    cluster.startRegionServer();
180    cluster.waitForActiveAndReadyMaster(10000);
181    HMaster m = cluster.getMaster();
182    final ZKWatcher zkw = m.getZooKeeper();
183    // now the cluster is up. So assign some regions.
184    try (Admin admin = TEST_UTIL.getAdmin()) {
185      byte[][] SPLIT_KEYS = new byte[][] { Bytes.toBytes("a"), Bytes.toBytes("b"),
186        Bytes.toBytes("c"), Bytes.toBytes("d"), Bytes.toBytes("e"), Bytes.toBytes("f"),
187        Bytes.toBytes("g"), Bytes.toBytes("h"), Bytes.toBytes("i"), Bytes.toBytes("j") };
188      TableDescriptor htd =
189        TableDescriptorBuilder.newBuilder(TableName.valueOf(name.getMethodName()))
190          .setColumnFamily(ColumnFamilyDescriptorBuilder.of(HConstants.CATALOG_FAMILY)).build();
191      admin.createTable(htd, SPLIT_KEYS);
192      TEST_UTIL.waitUntilNoRegionsInTransition(60000);
193      m.getZooKeeper().close();
194      MockLoadBalancer.retainAssignCalled = false;
195      final int expectedNumOfListeners = countPermanentListeners(zkw);
196      // the master could already been aborted by some background tasks but here we call abort
197      // directly to make sure this will happen
198      m.abort("Test recovery from zk session expired",
199        new KeeperException.SessionExpiredException());
200      // it is possible that our abort call above returned earlier because of someone else has
201      // already called abort, but it is possible that it has not finished the abort call yet so the
202      // isStopped flag is still false, let's wait for sometime.
203      TEST_UTIL.waitFor(5000, () -> m.isStopped()); // Master doesn't recover any more
204
205      // The recovered master should not call retainAssignment, as it is not a
206      // clean startup.
207      assertFalse("Retain assignment should not be called", MockLoadBalancer.retainAssignCalled);
208      // number of listeners should be same as the value before master aborted
209      // wait for new master is initialized
210      cluster.waitForActiveAndReadyMaster(120000);
211      final HMaster newMaster = cluster.getMasterThread().getMaster();
212      assertEquals(expectedNumOfListeners, countPermanentListeners(newMaster.getZooKeeper()));
213    }
214  }
215
216  /**
217   * Count listeners in zkw excluding listeners, that belongs to workers or other temporary
218   * processes.
219   */
220  private int countPermanentListeners(ZKWatcher watcher) {
221    return countListeners(watcher, ZkSplitLogWorkerCoordination.class);
222  }
223
224  /**
225   * Count listeners in zkw excluding provided classes
226   */
227  private int countListeners(ZKWatcher watcher, Class<?>... exclude) {
228    int cnt = 0;
229    for (Object o : watcher.getListeners()) {
230      boolean skip = false;
231      for (Class<?> aClass : exclude) {
232        if (aClass.isAssignableFrom(o.getClass())) {
233          skip = true;
234          break;
235        }
236      }
237      if (!skip) {
238        cnt += 1;
239      }
240    }
241    return cnt;
242  }
243
244  /**
245   * Tests whether the logs are split when master recovers from a expired zookeeper session and an
246   * RS goes down.
247   */
248  @Test
249  public void testLogSplittingAfterMasterRecoveryDueToZKExpiry() throws Exception {
250    MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
251    cluster.startRegionServer();
252    TableName tableName = TableName.valueOf(name.getMethodName());
253    byte[] family = Bytes.toBytes("col");
254    try (Admin admin = TEST_UTIL.getAdmin()) {
255      byte[][] SPLIT_KEYS = new byte[][] { Bytes.toBytes("1"), Bytes.toBytes("2"),
256        Bytes.toBytes("3"), Bytes.toBytes("4"), Bytes.toBytes("5") };
257      TableDescriptor htd = TableDescriptorBuilder.newBuilder(tableName)
258        .setColumnFamily(ColumnFamilyDescriptorBuilder.of(family)).build();
259      admin.createTable(htd, SPLIT_KEYS);
260    }
261    TEST_UTIL.waitUntilNoRegionsInTransition(60000);
262    HMaster m = cluster.getMaster();
263    try (Table table = TEST_UTIL.getConnection().getTable(tableName)) {
264      int numberOfPuts;
265      for (numberOfPuts = 0; numberOfPuts < 6; numberOfPuts++) {
266        Put p = new Put(Bytes.toBytes(numberOfPuts));
267        p.addColumn(Bytes.toBytes("col"), Bytes.toBytes("ql"),
268          Bytes.toBytes("value" + numberOfPuts));
269        table.put(p);
270      }
271      m.abort("Test recovery from zk session expired",
272        new KeeperException.SessionExpiredException());
273      assertTrue(m.isStopped()); // Master doesn't recover any more
274      cluster.killRegionServer(TEST_UTIL.getRSForFirstRegionInTable(tableName).getServerName());
275      // Without patch for HBASE-6046 this test case will always timeout
276      // with patch the test case should pass.
277      int numberOfRows = 0;
278      try (ResultScanner scanner = table.getScanner(new Scan())) {
279        while (scanner.next() != null) {
280          numberOfRows++;
281        }
282      }
283      assertEquals("Number of rows should be equal to number of puts.", numberOfPuts, numberOfRows);
284    }
285  }
286
287  static class MockLoadBalancer extends SimpleLoadBalancer {
288    static boolean retainAssignCalled = false;
289
290    @Override
291    @NonNull
292    public Map<ServerName, List<RegionInfo>> retainAssignment(Map<RegionInfo, ServerName> regions,
293      List<ServerName> servers) throws HBaseIOException {
294      retainAssignCalled = true;
295      return super.retainAssignment(regions, servers);
296    }
297  }
298
299}