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