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