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.regionserver;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertTrue;
022
023import java.io.IOException;
024import java.util.List;
025import java.util.Map;
026import java.util.concurrent.atomic.AtomicBoolean;
027import java.util.concurrent.atomic.AtomicReference;
028import org.apache.hadoop.conf.Configuration;
029import org.apache.hadoop.hbase.HBaseClassTestRule;
030import org.apache.hadoop.hbase.HBaseConfiguration;
031import org.apache.hadoop.hbase.HBaseTestingUtility;
032import org.apache.hadoop.hbase.LocalHBaseCluster;
033import org.apache.hadoop.hbase.MiniHBaseCluster;
034import org.apache.hadoop.hbase.ServerName;
035import org.apache.hadoop.hbase.client.RegionInfo;
036import org.apache.hadoop.hbase.master.HMaster;
037import org.apache.hadoop.hbase.master.LoadBalancer;
038import org.apache.hadoop.hbase.master.ServerListener;
039import org.apache.hadoop.hbase.master.ServerManager;
040import org.apache.hadoop.hbase.testclassification.MediumTests;
041import org.apache.hadoop.hbase.testclassification.RegionServerTests;
042import org.apache.hadoop.hbase.util.Bytes;
043import org.apache.hadoop.hbase.util.JVMClusterUtil.MasterThread;
044import org.apache.hadoop.hbase.util.Threads;
045import org.junit.ClassRule;
046import org.junit.Ignore;
047import org.junit.Rule;
048import org.junit.Test;
049import org.junit.experimental.categories.Category;
050import org.junit.rules.TestName;
051import org.slf4j.Logger;
052import org.slf4j.LoggerFactory;
053
054import org.apache.hadoop.hbase.shaded.protobuf.generated.RegionServerStatusProtos.RegionServerStartupResponse;
055
056/**
057 * Tests that a regionserver that dies after reporting for duty gets removed
058 * from list of online regions. See HBASE-9593.
059 */
060@Category({RegionServerTests.class, MediumTests.class})
061@Ignore("See HBASE-19515")
062public class TestRSKilledWhenInitializing {
063
064  @ClassRule
065  public static final HBaseClassTestRule CLASS_RULE =
066      HBaseClassTestRule.forClass(TestRSKilledWhenInitializing.class);
067
068  private static final Logger LOG = LoggerFactory.getLogger(TestRSKilledWhenInitializing.class);
069
070  @Rule
071  public TestName testName = new TestName();
072
073  // This boolean needs to be globally available. It is used below in our
074  // mocked up regionserver so it knows when to die.
075  private static AtomicBoolean masterActive = new AtomicBoolean(false);
076  // Ditto for this variable. It also is used in the mocked regionserver class.
077  private static final AtomicReference<ServerName> killedRS = new AtomicReference<ServerName>();
078
079  private static final int NUM_MASTERS = 1;
080  private static final int NUM_RS = 2;
081
082  /**
083   * Test verifies whether a region server is removed from online servers list in master if it went
084   * down after registering with master. Test will TIMEOUT if an error!!!!
085   * @throws Exception
086   */
087  @Test
088  public void testRSTerminationAfterRegisteringToMasterBeforeCreatingEphemeralNode()
089  throws Exception {
090    // Create config to use for this cluster
091    Configuration conf = HBaseConfiguration.create();
092    conf.setInt(ServerManager.WAIT_ON_REGIONSERVERS_MINTOSTART, 1);
093    // Start the cluster
094    final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(conf);
095    TEST_UTIL.startMiniDFSCluster(3);
096    TEST_UTIL.startMiniZKCluster();
097    TEST_UTIL.createRootDir();
098    final LocalHBaseCluster cluster = new LocalHBaseCluster(conf, NUM_MASTERS, NUM_RS,
099        HMaster.class, RegisterAndDieRegionServer.class);
100    final MasterThread master = startMaster(cluster.getMasters().get(0));
101    try {
102      // Master is up waiting on RegionServers to check in. Now start RegionServers.
103      for (int i = 0; i < NUM_RS; i++) {
104        cluster.getRegionServers().get(i).start();
105      }
106      // Expected total regionservers depends on whether Master can host regions or not.
107      int expectedTotalRegionServers = NUM_RS + (LoadBalancer.isTablesOnMaster(conf)? 1: 0);
108      List<ServerName> onlineServersList = null;
109      do {
110        onlineServersList = master.getMaster().getServerManager().getOnlineServersList();
111      } while (onlineServersList.size() < expectedTotalRegionServers);
112      // Wait until killedRS is set. Means RegionServer is starting to go down.
113      while (killedRS.get() == null) {
114        Threads.sleep(1);
115      }
116      // Wait on the RegionServer to fully die.
117      while (cluster.getLiveRegionServers().size() >= expectedTotalRegionServers) {
118        Threads.sleep(1);
119      }
120      // Make sure Master is fully up before progressing. Could take a while if regions
121      // being reassigned.
122      while (!master.getMaster().isInitialized()) {
123        Threads.sleep(1);
124      }
125
126      // Now in steady state. How many regions open? Master should have too many regionservers
127      // showing still. The downed RegionServer should still be showing as registered.
128      assertTrue(master.getMaster().getServerManager().isServerOnline(killedRS.get()));
129      // Find non-meta region (namespace?) and assign to the killed server. That'll trigger cleanup.
130      Map<RegionInfo, ServerName> assignments = null;
131      do {
132        assignments = master.getMaster().getAssignmentManager().getRegionStates().getRegionAssignments();
133      } while (assignments == null || assignments.size() < 2);
134      RegionInfo hri = null;
135      for (Map.Entry<RegionInfo, ServerName> e: assignments.entrySet()) {
136        if (e.getKey().isMetaRegion()) continue;
137        hri = e.getKey();
138        break;
139      }
140      // Try moving region to the killed server. It will fail. As by-product, we will
141      // remove the RS from Master online list because no corresponding znode.
142      assertEquals(expectedTotalRegionServers,
143        master.getMaster().getServerManager().getOnlineServersList().size());
144      LOG.info("Move " + hri.getEncodedName() + " to " + killedRS.get());
145      master.getMaster().move(hri.getEncodedNameAsBytes(),
146          Bytes.toBytes(killedRS.get().toString()));
147
148      // TODO: This test could do more to verify fix. It could create a table
149      // and do round-robin assign. It should fail if zombie RS. HBASE-19515.
150
151      // Wait until the RS no longer shows as registered in Master.
152      while (onlineServersList.size() > (NUM_RS + 1)) {
153        Thread.sleep(100);
154        onlineServersList = master.getMaster().getServerManager().getOnlineServersList();
155      }
156    } finally {
157      // Shutdown is messy with complaints about fs being closed. Why? TODO.
158      cluster.shutdown();
159      cluster.join();
160      TEST_UTIL.shutdownMiniDFSCluster();
161      TEST_UTIL.shutdownMiniZKCluster();
162      TEST_UTIL.cleanupTestDir();
163    }
164  }
165
166  /**
167   * Start Master. Get as far as the state where Master is waiting on
168   * RegionServers to check in, then return.
169   */
170  private MasterThread startMaster(MasterThread master) {
171    master.start();
172    // It takes a while until ServerManager creation to happen inside Master startup.
173    while (master.getMaster().getServerManager() == null) {
174      continue;
175    }
176    // Set a listener for the waiting-on-RegionServers state. We want to wait
177    // until this condition before we leave this method and start regionservers.
178    final AtomicBoolean waiting = new AtomicBoolean(false);
179    if (master.getMaster().getServerManager() == null) throw new NullPointerException("SM");
180    master.getMaster().getServerManager().registerListener(new ServerListener() {
181      @Override
182      public void waiting() {
183        waiting.set(true);
184      }
185    });
186    // Wait until the Master gets to place where it is waiting on RegionServers to check in.
187    while (!waiting.get()) {
188      continue;
189    }
190    // Set the global master-is-active; gets picked up by regionservers later.
191    masterActive.set(true);
192    return master;
193  }
194
195  /**
196   * A RegionServer that reports for duty and then immediately dies if it is the first to receive
197   * the response to a reportForDuty. When it dies, it clears its ephemeral znode which the master
198   * notices and so removes the region from its set of online regionservers.
199   */
200  static class RegisterAndDieRegionServer extends MiniHBaseCluster.MiniHBaseClusterRegionServer {
201    public RegisterAndDieRegionServer(Configuration conf)
202    throws IOException, InterruptedException {
203      super(conf);
204    }
205
206    @Override
207    protected void handleReportForDutyResponse(RegionServerStartupResponse c)
208    throws IOException {
209      if (killedRS.compareAndSet(null, getServerName())) {
210        // Make sure Master is up so it will see the removal of the ephemeral znode for this RS.
211        while (!masterActive.get()) {
212          Threads.sleep(100);
213        }
214        super.kill();
215      } else {
216        super.handleReportForDutyResponse(c);
217      }
218    }
219  }
220}