View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.master;
19  
20  import static org.junit.Assert.assertEquals;
21  import static org.junit.Assert.assertFalse;
22  import static org.junit.Assert.assertNotSame;
23  import static org.junit.Assert.assertTrue;
24  import static org.junit.Assert.fail;
25  
26  import java.io.IOException;
27  import java.util.ArrayList;
28  import java.util.HashMap;
29  import java.util.List;
30  import java.util.Map;
31  import java.util.concurrent.atomic.AtomicBoolean;
32  
33  import org.apache.hadoop.conf.Configuration;
34  import org.apache.hadoop.hbase.CellScannable;
35  import org.apache.hadoop.hbase.CellUtil;
36  import org.apache.hadoop.hbase.CoordinatedStateException;
37  import org.apache.hadoop.hbase.CoordinatedStateManager;
38  import org.apache.hadoop.hbase.CoordinatedStateManagerFactory;
39  import org.apache.hadoop.hbase.DoNotRetryIOException;
40  import org.apache.hadoop.hbase.HBaseConfiguration;
41  import org.apache.hadoop.hbase.HBaseTestingUtility;
42  import org.apache.hadoop.hbase.HConstants;
43  import org.apache.hadoop.hbase.HRegionInfo;
44  import org.apache.hadoop.hbase.MetaMockingUtil;
45  import org.apache.hadoop.hbase.RegionException;
46  import org.apache.hadoop.hbase.RegionTransition;
47  import org.apache.hadoop.hbase.Server;
48  import org.apache.hadoop.hbase.ServerLoad;
49  import org.apache.hadoop.hbase.ServerName;
50  import org.apache.hadoop.hbase.TableName;
51  import org.apache.hadoop.hbase.ZooKeeperConnectionException;
52  import org.apache.hadoop.hbase.client.ClusterConnection;
53  import org.apache.hadoop.hbase.client.HConnectionTestingUtility;
54  import org.apache.hadoop.hbase.client.Result;
55  import org.apache.hadoop.hbase.coordination.BaseCoordinatedStateManager;
56  import org.apache.hadoop.hbase.coordination.OpenRegionCoordination;
57  import org.apache.hadoop.hbase.coordination.ZkCoordinatedStateManager;
58  import org.apache.hadoop.hbase.coordination.ZkOpenRegionCoordination;
59  import org.apache.hadoop.hbase.exceptions.DeserializationException;
60  import org.apache.hadoop.hbase.executor.EventType;
61  import org.apache.hadoop.hbase.executor.ExecutorService;
62  import org.apache.hadoop.hbase.executor.ExecutorType;
63  import org.apache.hadoop.hbase.ipc.PayloadCarryingRpcController;
64  import org.apache.hadoop.hbase.master.RegionState.State;
65  import org.apache.hadoop.hbase.master.TableLockManager.NullTableLockManager;
66  import org.apache.hadoop.hbase.master.balancer.LoadBalancerFactory;
67  import org.apache.hadoop.hbase.master.balancer.SimpleLoadBalancer;
68  import org.apache.hadoop.hbase.master.handler.EnableTableHandler;
69  import org.apache.hadoop.hbase.master.handler.ServerShutdownHandler;
70  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
71  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
72  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetRequest;
73  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetResponse;
74  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
75  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanResponse;
76  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.SplitLogTask.RecoveryMode;
77  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.Table;
78  import org.apache.hadoop.hbase.regionserver.RegionOpeningState;
79  import org.apache.hadoop.hbase.testclassification.MediumTests;
80  import org.apache.hadoop.hbase.util.Bytes;
81  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
82  import org.apache.hadoop.hbase.util.Threads;
83  import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
84  import org.apache.hadoop.hbase.zookeeper.RecoverableZooKeeper;
85  import org.apache.hadoop.hbase.zookeeper.ZKAssign;
86  import org.apache.hadoop.hbase.zookeeper.ZKUtil;
87  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
88  import org.apache.zookeeper.KeeperException;
89  import org.apache.zookeeper.KeeperException.NodeExistsException;
90  import org.apache.zookeeper.Watcher;
91  import org.junit.After;
92  import org.junit.AfterClass;
93  import org.junit.Before;
94  import org.junit.BeforeClass;
95  import org.junit.Test;
96  import org.junit.experimental.categories.Category;
97  import org.mockito.Mockito;
98  import org.mockito.internal.util.reflection.Whitebox;
99  import org.mockito.invocation.InvocationOnMock;
100 import org.mockito.stubbing.Answer;
101 
102 import com.google.protobuf.RpcController;
103 import com.google.protobuf.ServiceException;
104 
105 
106 /**
107  * Test {@link AssignmentManager}
108  */
109 @Category(MediumTests.class)
110 public class TestAssignmentManager {
111   private static final HBaseTestingUtility HTU = new HBaseTestingUtility();
112   private static final ServerName SERVERNAME_A =
113       ServerName.valueOf("example.org", 1234, 5678);
114   private static final ServerName SERVERNAME_B =
115       ServerName.valueOf("example.org", 0, 5678);
116   private static final HRegionInfo REGIONINFO =
117     new HRegionInfo(TableName.valueOf("t"),
118       HConstants.EMPTY_START_ROW, HConstants.EMPTY_START_ROW);
119   private static int assignmentCount;
120   private static boolean enabling = false;
121 
122   // Mocked objects or; get redone for each test.
123   private Server server;
124   private ServerManager serverManager;
125   private ZooKeeperWatcher watcher;
126   private CoordinatedStateManager cp;
127   private MetaTableLocator mtl;
128   private LoadBalancer balancer;
129   private HMaster master;
130   private ClusterConnection connection;
131 
132   @BeforeClass
133   public static void beforeClass() throws Exception {
134     HTU.getConfiguration().setBoolean("hbase.assignment.usezk", true);
135     HTU.startMiniZKCluster();
136   }
137 
138   @AfterClass
139   public static void afterClass() throws IOException {
140     HTU.shutdownMiniZKCluster();
141   }
142 
143   @Before
144   public void before() throws ZooKeeperConnectionException, IOException {
145     // TODO: Make generic versions of what we do below and put up in a mocking
146     // utility class or move up into HBaseTestingUtility.
147 
148     // Mock a Server.  Have it return a legit Configuration and ZooKeeperWatcher.
149     // If abort is called, be sure to fail the test (don't just swallow it
150     // silently as is mockito default).
151     this.server = Mockito.mock(Server.class);
152     Mockito.when(server.getServerName()).thenReturn(ServerName.valueOf("master,1,1"));
153     Mockito.when(server.getConfiguration()).thenReturn(HTU.getConfiguration());
154     this.watcher =
155       new ZooKeeperWatcher(HTU.getConfiguration(), "mockedServer", this.server, true);
156     Mockito.when(server.getZooKeeper()).thenReturn(this.watcher);
157     Mockito.doThrow(new RuntimeException("Aborted")).
158       when(server).abort(Mockito.anyString(), (Throwable)Mockito.anyObject());
159 
160     cp = new ZkCoordinatedStateManager();
161     cp.initialize(this.server);
162     cp.start();
163 
164     mtl = Mockito.mock(MetaTableLocator.class);
165 
166     Mockito.when(server.getCoordinatedStateManager()).thenReturn(cp);
167     Mockito.when(server.getMetaTableLocator()).thenReturn(mtl);
168 
169     // Get a connection w/ mocked up common methods.
170     this.connection =
171       (ClusterConnection)HConnectionTestingUtility.getMockedConnection(HTU.getConfiguration());
172 
173     // Make it so we can get a catalogtracker from servermanager.. .needed
174     // down in guts of server shutdown handler.
175     Mockito.when(server.getConnection()).thenReturn(connection);
176 
177     // Mock a ServerManager.  Say server SERVERNAME_{A,B} are online.  Also
178     // make it so if close or open, we return 'success'.
179     this.serverManager = Mockito.mock(ServerManager.class);
180     Mockito.when(this.serverManager.isServerOnline(SERVERNAME_A)).thenReturn(true);
181     Mockito.when(this.serverManager.isServerOnline(SERVERNAME_B)).thenReturn(true);
182     Mockito.when(this.serverManager.getDeadServers()).thenReturn(new DeadServer());
183     final Map<ServerName, ServerLoad> onlineServers = new HashMap<ServerName, ServerLoad>();
184     onlineServers.put(SERVERNAME_B, ServerLoad.EMPTY_SERVERLOAD);
185     onlineServers.put(SERVERNAME_A, ServerLoad.EMPTY_SERVERLOAD);
186     Mockito.when(this.serverManager.getOnlineServersList()).thenReturn(
187         new ArrayList<ServerName>(onlineServers.keySet()));
188     Mockito.when(this.serverManager.getOnlineServers()).thenReturn(onlineServers);
189 
190     List<ServerName> avServers = new ArrayList<ServerName>();
191     avServers.addAll(onlineServers.keySet());
192     Mockito.when(this.serverManager.createDestinationServersList()).thenReturn(avServers);
193     Mockito.when(this.serverManager.createDestinationServersList(null)).thenReturn(avServers);
194 
195     Mockito.when(this.serverManager.sendRegionClose(SERVERNAME_A, REGIONINFO, -1)).
196       thenReturn(true);
197     Mockito.when(this.serverManager.sendRegionClose(SERVERNAME_B, REGIONINFO, -1)).
198       thenReturn(true);
199     // Ditto on open.
200     Mockito.when(this.serverManager.sendRegionOpen(SERVERNAME_A, REGIONINFO, -1, null)).
201       thenReturn(RegionOpeningState.OPENED);
202     Mockito.when(this.serverManager.sendRegionOpen(SERVERNAME_B, REGIONINFO, -1, null)).
203       thenReturn(RegionOpeningState.OPENED);
204     this.master = Mockito.mock(HMaster.class);
205 
206     Mockito.when(this.master.getServerManager()).thenReturn(serverManager);
207   }
208 
209   @After public void after() throws KeeperException, IOException {
210     if (this.watcher != null) {
211       // Clean up all znodes
212       ZKAssign.deleteAllNodes(this.watcher);
213       this.watcher.close();
214       this.cp.stop();
215     }
216     if (this.connection != null) this.connection.close();
217   }
218 
219   /**
220    * Test a balance going on at same time as a master failover
221    *
222    * @throws IOException
223    * @throws KeeperException
224    * @throws InterruptedException
225    * @throws DeserializationException
226    */
227   @Test(timeout = 60000)
228   public void testBalanceOnMasterFailoverScenarioWithOpenedNode()
229       throws IOException, KeeperException, InterruptedException, ServiceException,
230       DeserializationException, CoordinatedStateException {
231     AssignmentManagerWithExtrasForTesting am =
232       setUpMockedAssignmentManager(this.server, this.serverManager);
233     try {
234       createRegionPlanAndBalance(am, SERVERNAME_A, SERVERNAME_B, REGIONINFO);
235       startFakeFailedOverMasterAssignmentManager(am, this.watcher);
236       while (!am.processRITInvoked) Thread.sleep(1);
237       // As part of the failover cleanup, the balancing region plan is removed.
238       // So a random server will be used to open the region. For testing purpose,
239       // let's assume it is going to open on server b:
240       am.addPlan(REGIONINFO.getEncodedName(), new RegionPlan(REGIONINFO, null, SERVERNAME_B));
241 
242       Mocking.waitForRegionFailedToCloseAndSetToPendingClose(am, REGIONINFO);
243 
244       // Now fake the region closing successfully over on the regionserver; the
245       // regionserver will have set the region in CLOSED state. This will
246       // trigger callback into AM. The below zk close call is from the RS close
247       // region handler duplicated here because its down deep in a private
248       // method hard to expose.
249       int versionid =
250         ZKAssign.transitionNodeClosed(this.watcher, REGIONINFO, SERVERNAME_A, -1);
251       assertNotSame(versionid, -1);
252       Mocking.waitForRegionPendingOpenInRIT(am, REGIONINFO.getEncodedName());
253 
254       // Get current versionid else will fail on transition from OFFLINE to
255       // OPENING below
256       versionid = ZKAssign.getVersion(this.watcher, REGIONINFO);
257       assertNotSame(-1, versionid);
258       // This uglyness below is what the openregionhandler on RS side does.
259       versionid = ZKAssign.transitionNode(server.getZooKeeper(), REGIONINFO,
260         SERVERNAME_B, EventType.M_ZK_REGION_OFFLINE,
261         EventType.RS_ZK_REGION_OPENING, versionid);
262       assertNotSame(-1, versionid);
263       // Move znode from OPENING to OPENED as RS does on successful open.
264       versionid = ZKAssign.transitionNodeOpened(this.watcher, REGIONINFO,
265         SERVERNAME_B, versionid);
266       assertNotSame(-1, versionid);
267       am.gate.set(false);
268       // Block here until our znode is cleared or until this test times out.
269       ZKAssign.blockUntilNoRIT(watcher);
270     } finally {
271       am.getExecutorService().shutdown();
272       am.shutdown();
273     }
274   }
275 
276   @Test(timeout = 60000)
277   public void testBalanceOnMasterFailoverScenarioWithClosedNode()
278       throws IOException, KeeperException, InterruptedException, ServiceException,
279         DeserializationException, CoordinatedStateException {
280     AssignmentManagerWithExtrasForTesting am =
281       setUpMockedAssignmentManager(this.server, this.serverManager);
282     try {
283       createRegionPlanAndBalance(am, SERVERNAME_A, SERVERNAME_B, REGIONINFO);
284       startFakeFailedOverMasterAssignmentManager(am, this.watcher);
285       while (!am.processRITInvoked) Thread.sleep(1);
286       // As part of the failover cleanup, the balancing region plan is removed.
287       // So a random server will be used to open the region. For testing purpose,
288       // let's assume it is going to open on server b:
289       am.addPlan(REGIONINFO.getEncodedName(), new RegionPlan(REGIONINFO, null, SERVERNAME_B));
290 
291       Mocking.waitForRegionFailedToCloseAndSetToPendingClose(am, REGIONINFO);
292 
293       // Now fake the region closing successfully over on the regionserver; the
294       // regionserver will have set the region in CLOSED state. This will
295       // trigger callback into AM. The below zk close call is from the RS close
296       // region handler duplicated here because its down deep in a private
297       // method hard to expose.
298       int versionid =
299         ZKAssign.transitionNodeClosed(this.watcher, REGIONINFO, SERVERNAME_A, -1);
300       assertNotSame(versionid, -1);
301       am.gate.set(false);
302       Mocking.waitForRegionPendingOpenInRIT(am, REGIONINFO.getEncodedName());
303 
304       // Get current versionid else will fail on transition from OFFLINE to
305       // OPENING below
306       versionid = ZKAssign.getVersion(this.watcher, REGIONINFO);
307       assertNotSame(-1, versionid);
308       // This uglyness below is what the openregionhandler on RS side does.
309       versionid = ZKAssign.transitionNode(server.getZooKeeper(), REGIONINFO,
310           SERVERNAME_B, EventType.M_ZK_REGION_OFFLINE,
311           EventType.RS_ZK_REGION_OPENING, versionid);
312       assertNotSame(-1, versionid);
313       // Move znode from OPENING to OPENED as RS does on successful open.
314       versionid = ZKAssign.transitionNodeOpened(this.watcher, REGIONINFO,
315           SERVERNAME_B, versionid);
316       assertNotSame(-1, versionid);
317 
318       // Block here until our znode is cleared or until this test timesout.
319       ZKAssign.blockUntilNoRIT(watcher);
320     } finally {
321       am.getExecutorService().shutdown();
322       am.shutdown();
323     }
324   }
325 
326   @Test(timeout = 60000)
327   public void testBalanceOnMasterFailoverScenarioWithOfflineNode()
328       throws IOException, KeeperException, InterruptedException, ServiceException,
329       DeserializationException, CoordinatedStateException {
330     AssignmentManagerWithExtrasForTesting am =
331       setUpMockedAssignmentManager(this.server, this.serverManager);
332     try {
333       createRegionPlanAndBalance(am, SERVERNAME_A, SERVERNAME_B, REGIONINFO);
334       startFakeFailedOverMasterAssignmentManager(am, this.watcher);
335       while (!am.processRITInvoked) Thread.sleep(1);
336       // As part of the failover cleanup, the balancing region plan is removed.
337       // So a random server will be used to open the region. For testing purpose,
338       // let's assume it is going to open on server b:
339       am.addPlan(REGIONINFO.getEncodedName(), new RegionPlan(REGIONINFO, null, SERVERNAME_B));
340 
341       Mocking.waitForRegionFailedToCloseAndSetToPendingClose(am, REGIONINFO);
342 
343       // Now fake the region closing successfully over on the regionserver; the
344       // regionserver will have set the region in CLOSED state. This will
345       // trigger callback into AM. The below zk close call is from the RS close
346       // region handler duplicated here because its down deep in a private
347       // method hard to expose.
348       int versionid =
349         ZKAssign.transitionNodeClosed(this.watcher, REGIONINFO, SERVERNAME_A, -1);
350       assertNotSame(versionid, -1);
351       Mocking.waitForRegionPendingOpenInRIT(am, REGIONINFO.getEncodedName());
352 
353       am.gate.set(false);
354       // Get current versionid else will fail on transition from OFFLINE to
355       // OPENING below
356       versionid = ZKAssign.getVersion(this.watcher, REGIONINFO);
357       assertNotSame(-1, versionid);
358       // This uglyness below is what the openregionhandler on RS side does.
359       versionid = ZKAssign.transitionNode(server.getZooKeeper(), REGIONINFO,
360           SERVERNAME_B, EventType.M_ZK_REGION_OFFLINE,
361           EventType.RS_ZK_REGION_OPENING, versionid);
362       assertNotSame(-1, versionid);
363       // Move znode from OPENING to OPENED as RS does on successful open.
364       versionid = ZKAssign.transitionNodeOpened(this.watcher, REGIONINFO,
365           SERVERNAME_B, versionid);
366       assertNotSame(-1, versionid);
367       // Block here until our znode is cleared or until this test timesout.
368       ZKAssign.blockUntilNoRIT(watcher);
369     } finally {
370       am.getExecutorService().shutdown();
371       am.shutdown();
372     }
373   }
374 
375   private void createRegionPlanAndBalance(
376       final AssignmentManager am, final ServerName from,
377       final ServerName to, final HRegionInfo hri) throws RegionException {
378     // Call the balance function but fake the region being online first at
379     // servername from.
380     am.regionOnline(hri, from);
381     // Balance region from 'from' to 'to'. It calls unassign setting CLOSING state
382     // up in zk.  Create a plan and balance
383     am.balance(new RegionPlan(hri, from, to));
384   }
385 
386   /**
387    * Tests AssignmentManager balance function.  Runs a balance moving a region
388    * from one server to another mocking regionserver responding over zk.
389    * @throws IOException
390    * @throws KeeperException
391    * @throws DeserializationException
392    */
393   @Test (timeout=180000)
394   public void testBalance() throws IOException, KeeperException, DeserializationException,
395       InterruptedException, CoordinatedStateException {
396     // Create and startup an executor.  This is used by AssignmentManager
397     // handling zk callbacks.
398     ExecutorService executor = startupMasterExecutor("testBalanceExecutor");
399 
400     // We need a mocked catalog tracker.
401     LoadBalancer balancer = LoadBalancerFactory.getLoadBalancer(server
402         .getConfiguration());
403     // Create an AM.
404     AssignmentManager am = new AssignmentManager(this.server,
405       this.serverManager, balancer, executor, null, master.getTableLockManager());
406     am.failoverCleanupDone.set(true);
407     try {
408       // Make sure our new AM gets callbacks; once registered, can't unregister.
409       // Thats ok because we make a new zk watcher for each test.
410       this.watcher.registerListenerFirst(am);
411       // Call the balance function but fake the region being online first at
412       // SERVERNAME_A.  Create a balance plan.
413       am.regionOnline(REGIONINFO, SERVERNAME_A);
414       // Balance region from A to B.
415       RegionPlan plan = new RegionPlan(REGIONINFO, SERVERNAME_A, SERVERNAME_B);
416       am.balance(plan);
417 
418       RegionStates regionStates = am.getRegionStates();
419       // Must be failed to close since the server is fake
420       assertTrue(regionStates.isRegionInTransition(REGIONINFO)
421         && regionStates.isRegionInState(REGIONINFO, State.FAILED_CLOSE));
422       // Move it back to pending_close
423       regionStates.updateRegionState(REGIONINFO, State.PENDING_CLOSE);
424 
425       // Now fake the region closing successfully over on the regionserver; the
426       // regionserver will have set the region in CLOSED state.  This will
427       // trigger callback into AM. The below zk close call is from the RS close
428       // region handler duplicated here because its down deep in a private
429       // method hard to expose.
430       int versionid =
431         ZKAssign.transitionNodeClosed(this.watcher, REGIONINFO, SERVERNAME_A, -1);
432       assertNotSame(versionid, -1);
433       // AM is going to notice above CLOSED and queue up a new assign.  The
434       // assign will go to open the region in the new location set by the
435       // balancer.  The zk node will be OFFLINE waiting for regionserver to
436       // transition it through OPENING, OPENED.  Wait till we see the OFFLINE
437       // zk node before we proceed.
438       Mocking.waitForRegionPendingOpenInRIT(am, REGIONINFO.getEncodedName());
439 
440       // Get current versionid else will fail on transition from OFFLINE to OPENING below
441       versionid = ZKAssign.getVersion(this.watcher, REGIONINFO);
442       assertNotSame(-1, versionid);
443       // This uglyness below is what the openregionhandler on RS side does.
444       versionid = ZKAssign.transitionNode(server.getZooKeeper(), REGIONINFO,
445         SERVERNAME_B, EventType.M_ZK_REGION_OFFLINE,
446         EventType.RS_ZK_REGION_OPENING, versionid);
447       assertNotSame(-1, versionid);
448       // Move znode from OPENING to OPENED as RS does on successful open.
449       versionid =
450         ZKAssign.transitionNodeOpened(this.watcher, REGIONINFO, SERVERNAME_B, versionid);
451       assertNotSame(-1, versionid);
452       // Wait on the handler removing the OPENED znode.
453       while(regionStates.isRegionInTransition(REGIONINFO)) Threads.sleep(1);
454     } finally {
455       executor.shutdown();
456       am.shutdown();
457       // Clean up all znodes
458       ZKAssign.deleteAllNodes(this.watcher);
459     }
460   }
461 
462   /**
463    * Run a simple server shutdown handler.
464    * @throws KeeperException
465    * @throws IOException
466    */
467   @Test (timeout=180000)
468   public void testShutdownHandler()
469       throws KeeperException, IOException, CoordinatedStateException, ServiceException {
470     // Create and startup an executor.  This is used by AssignmentManager
471     // handling zk callbacks.
472     ExecutorService executor = startupMasterExecutor("testShutdownHandler");
473 
474     // Create an AM.
475     AssignmentManagerWithExtrasForTesting am = setUpMockedAssignmentManager(
476         this.server, this.serverManager);
477     try {
478       processServerShutdownHandler(am, false);
479     } finally {
480       executor.shutdown();
481       am.shutdown();
482       // Clean up all znodes
483       ZKAssign.deleteAllNodes(this.watcher);
484     }
485   }
486 
487   /**
488    * To test closed region handler to remove rit and delete corresponding znode
489    * if region in pending close or closing while processing shutdown of a region
490    * server.(HBASE-5927).
491    *
492    * @throws KeeperException
493    * @throws IOException
494    * @throws ServiceException
495    */
496   @Test (timeout=180000)
497   public void testSSHWhenDisableTableInProgress() throws KeeperException, IOException,
498     CoordinatedStateException, ServiceException {
499     testCaseWithPartiallyDisabledState(Table.State.DISABLING);
500     testCaseWithPartiallyDisabledState(Table.State.DISABLED);
501   }
502 
503 
504   /**
505    * To test if the split region is removed from RIT if the region was in SPLITTING state but the RS
506    * has actually completed the splitting in hbase:meta but went down. See HBASE-6070 and also HBASE-5806
507    *
508    * @throws KeeperException
509    * @throws IOException
510    */
511   @Test (timeout=180000)
512   public void testSSHWhenSplitRegionInProgress() throws KeeperException, IOException, Exception {
513     // true indicates the region is split but still in RIT
514     testCaseWithSplitRegionPartial(true);
515     // false indicate the region is not split
516     testCaseWithSplitRegionPartial(false);
517   }
518 
519   private void testCaseWithSplitRegionPartial(boolean regionSplitDone) throws KeeperException,
520       IOException, InterruptedException,
521     CoordinatedStateException, ServiceException {
522     // Create and startup an executor. This is used by AssignmentManager
523     // handling zk callbacks.
524     ExecutorService executor = startupMasterExecutor("testSSHWhenSplitRegionInProgress");
525     // We need a mocked catalog tracker.
526     ZKAssign.deleteAllNodes(this.watcher);
527 
528     // Create an AM.
529     AssignmentManagerWithExtrasForTesting am = setUpMockedAssignmentManager(
530       this.server, this.serverManager);
531     // adding region to regions and servers maps.
532     am.regionOnline(REGIONINFO, SERVERNAME_A);
533     // adding region in pending close.
534     am.getRegionStates().updateRegionState(
535       REGIONINFO, State.SPLITTING, SERVERNAME_A);
536     am.getTableStateManager().setTableState(REGIONINFO.getTable(),
537       Table.State.ENABLED);
538     RegionTransition data = RegionTransition.createRegionTransition(EventType.RS_ZK_REGION_SPLITTING,
539         REGIONINFO.getRegionName(), SERVERNAME_A);
540     String node = ZKAssign.getNodeName(this.watcher, REGIONINFO.getEncodedName());
541     // create znode in M_ZK_REGION_CLOSING state.
542     ZKUtil.createAndWatch(this.watcher, node, data.toByteArray());
543 
544     try {
545       processServerShutdownHandler(am, regionSplitDone);
546       // check znode deleted or not.
547       // In both cases the znode should be deleted.
548 
549       if (regionSplitDone) {
550         assertFalse("Region state of region in SPLITTING should be removed from rit.",
551             am.getRegionStates().isRegionsInTransition());
552       } else {
553         while (!am.assignInvoked) {
554           Thread.sleep(1);
555         }
556         assertTrue("Assign should be invoked.", am.assignInvoked);
557       }
558     } finally {
559       REGIONINFO.setOffline(false);
560       REGIONINFO.setSplit(false);
561       executor.shutdown();
562       am.shutdown();
563       // Clean up all znodes
564       ZKAssign.deleteAllNodes(this.watcher);
565     }
566   }
567 
568   private void testCaseWithPartiallyDisabledState(Table.State state) throws KeeperException,
569       IOException, CoordinatedStateException, ServiceException {
570     // Create and startup an executor. This is used by AssignmentManager
571     // handling zk callbacks.
572     ExecutorService executor = startupMasterExecutor("testSSHWhenDisableTableInProgress");
573     LoadBalancer balancer = LoadBalancerFactory.getLoadBalancer(server.getConfiguration());
574     ZKAssign.deleteAllNodes(this.watcher);
575 
576     // Create an AM.
577     AssignmentManager am = new AssignmentManager(this.server,
578       this.serverManager, balancer, executor, null, master.getTableLockManager());
579     // adding region to regions and servers maps.
580     am.regionOnline(REGIONINFO, SERVERNAME_A);
581     // adding region in pending close.
582     am.getRegionStates().updateRegionState(REGIONINFO, State.PENDING_CLOSE);
583     if (state == Table.State.DISABLING) {
584       am.getTableStateManager().setTableState(REGIONINFO.getTable(),
585         Table.State.DISABLING);
586     } else {
587       am.getTableStateManager().setTableState(REGIONINFO.getTable(),
588         Table.State.DISABLED);
589     }
590     RegionTransition data = RegionTransition.createRegionTransition(EventType.M_ZK_REGION_CLOSING,
591         REGIONINFO.getRegionName(), SERVERNAME_A);
592     // RegionTransitionData data = new
593     // RegionTransitionData(EventType.M_ZK_REGION_CLOSING,
594     // REGIONINFO.getRegionName(), SERVERNAME_A);
595     String node = ZKAssign.getNodeName(this.watcher, REGIONINFO.getEncodedName());
596     // create znode in M_ZK_REGION_CLOSING state.
597     ZKUtil.createAndWatch(this.watcher, node, data.toByteArray());
598 
599     try {
600       processServerShutdownHandler(am, false);
601       // check znode deleted or not.
602       // In both cases the znode should be deleted.
603       assertTrue("The znode should be deleted.", ZKUtil.checkExists(this.watcher, node) == -1);
604       // check whether in rit or not. In the DISABLING case also the below
605       // assert will be true but the piece of code added for HBASE-5927 will not
606       // do that.
607       if (state == Table.State.DISABLED) {
608         assertFalse("Region state of region in pending close should be removed from rit.",
609             am.getRegionStates().isRegionsInTransition());
610       }
611     } finally {
612       am.setEnabledTable(REGIONINFO.getTable());
613       executor.shutdown();
614       am.shutdown();
615       // Clean up all znodes
616       ZKAssign.deleteAllNodes(this.watcher);
617     }
618   }
619 
620   private void processServerShutdownHandler(AssignmentManager am, boolean splitRegion)
621       throws IOException, ServiceException {
622     // Make sure our new AM gets callbacks; once registered, can't unregister.
623     // Thats ok because we make a new zk watcher for each test.
624     this.watcher.registerListenerFirst(am);
625 
626     // Need to set up a fake scan of meta for the servershutdown handler
627     // Make an RS Interface implementation.  Make it so a scanner can go against it.
628     ClientProtos.ClientService.BlockingInterface implementation =
629       Mockito.mock(ClientProtos.ClientService.BlockingInterface.class);
630     // Get a meta row result that has region up on SERVERNAME_A
631 
632     Result r;
633     if (splitRegion) {
634       r = MetaMockingUtil.getMetaTableRowResultAsSplitRegion(REGIONINFO, SERVERNAME_A);
635     } else {
636       r = MetaMockingUtil.getMetaTableRowResult(REGIONINFO, SERVERNAME_A);
637     }
638 
639     final ScanResponse.Builder builder = ScanResponse.newBuilder();
640     builder.setMoreResults(true);
641     builder.addCellsPerResult(r.size());
642     final List<CellScannable> cellScannables = new ArrayList<CellScannable>(1);
643     cellScannables.add(r);
644     Mockito.when(implementation.scan(
645       (RpcController)Mockito.any(), (ScanRequest)Mockito.any())).
646       thenAnswer(new Answer<ScanResponse>() {
647           @Override
648           public ScanResponse answer(InvocationOnMock invocation) throws Throwable {
649             PayloadCarryingRpcController controller = (PayloadCarryingRpcController) invocation
650                 .getArguments()[0];
651             if (controller != null) {
652               controller.setCellScanner(CellUtil.createCellScanner(cellScannables));
653             }
654             return builder.build();
655           }
656       });
657 
658     // Get a connection w/ mocked up common methods.
659     ClusterConnection connection =
660       HConnectionTestingUtility.getMockedConnectionAndDecorate(HTU.getConfiguration(),
661         null, implementation, SERVERNAME_B, REGIONINFO);
662     // These mocks were done up when all connections were managed.  World is different now we
663     // moved to unmanaged connections.  It messes up the intercepts done in these tests.
664     // Just mark connections as marked and then down in MetaTableAccessor, it will go the path
665     // that picks up the above mocked up 'implementation' so 'scans' of meta return the expected
666     // result.  Redo in new realm of unmanaged connections.
667     Mockito.when(connection.isManaged()).thenReturn(true);
668     try {
669       // Make it so we can get a catalogtracker from servermanager.. .needed
670       // down in guts of server shutdown handler.
671       Mockito.when(this.server.getConnection()).thenReturn(connection);
672 
673       // Now make a server shutdown handler instance and invoke process.
674       // Have it that SERVERNAME_A died.
675       DeadServer deadServers = new DeadServer();
676       deadServers.add(SERVERNAME_A);
677       // I need a services instance that will return the AM
678       MasterFileSystem fs = Mockito.mock(MasterFileSystem.class);
679       Mockito.doNothing().when(fs).setLogRecoveryMode();
680       Mockito.when(fs.getLogRecoveryMode()).thenReturn(RecoveryMode.LOG_REPLAY);
681       MasterServices services = Mockito.mock(MasterServices.class);
682       Mockito.when(services.getAssignmentManager()).thenReturn(am);
683       Mockito.when(services.getServerManager()).thenReturn(this.serverManager);
684       Mockito.when(services.getZooKeeper()).thenReturn(this.watcher);
685       Mockito.when(services.getMasterFileSystem()).thenReturn(fs);
686       Mockito.when(services.getConnection()).thenReturn(connection);
687       Configuration conf = server.getConfiguration();
688       Mockito.when(services.getConfiguration()).thenReturn(conf);
689       ServerShutdownHandler handler = new ServerShutdownHandler(this.server,
690           services, deadServers, SERVERNAME_A, false);
691       am.failoverCleanupDone.set(true);
692       handler.process();
693       // The region in r will have been assigned.  It'll be up in zk as unassigned.
694     } finally {
695       if (connection != null) connection.close();
696     }
697   }
698 
699   /**
700    * Create and startup executor pools. Start same set as master does (just
701    * run a few less).
702    * @param name Name to give our executor
703    * @return Created executor (be sure to call shutdown when done).
704    */
705   private ExecutorService startupMasterExecutor(final String name) {
706     // TODO: Move up into HBaseTestingUtility?  Generally useful.
707     ExecutorService executor = new ExecutorService(name);
708     executor.startExecutorService(ExecutorType.MASTER_OPEN_REGION, 3);
709     executor.startExecutorService(ExecutorType.MASTER_CLOSE_REGION, 3);
710     executor.startExecutorService(ExecutorType.MASTER_SERVER_OPERATIONS, 3);
711     executor.startExecutorService(ExecutorType.MASTER_META_SERVER_OPERATIONS, 3);
712     return executor;
713   }
714 
715   @Test (timeout=180000)
716   public void testUnassignWithSplitAtSameTime() throws KeeperException,
717       IOException, CoordinatedStateException {
718     // Region to use in test.
719     final HRegionInfo hri = HRegionInfo.FIRST_META_REGIONINFO;
720     // First amend the servermanager mock so that when we do send close of the
721     // first meta region on SERVERNAME_A, it will return true rather than
722     // default null.
723     Mockito.when(this.serverManager.sendRegionClose(SERVERNAME_A, hri, -1)).thenReturn(true);
724     // Need a mocked catalog tracker.
725     LoadBalancer balancer = LoadBalancerFactory.getLoadBalancer(server
726         .getConfiguration());
727     // Create an AM.
728     AssignmentManager am = new AssignmentManager(this.server,
729       this.serverManager, balancer, null, null, master.getTableLockManager());
730     try {
731       // First make sure my mock up basically works.  Unassign a region.
732       unassign(am, SERVERNAME_A, hri);
733       // This delete will fail if the previous unassign did wrong thing.
734       ZKAssign.deleteClosingNode(this.watcher, hri, SERVERNAME_A);
735       // Now put a SPLITTING region in the way.  I don't have to assert it
736       // go put in place.  This method puts it in place then asserts it still
737       // owns it by moving state from SPLITTING to SPLITTING.
738       int version = createNodeSplitting(this.watcher, hri, SERVERNAME_A);
739       // Now, retry the unassign with the SPLTTING in place.  It should just
740       // complete without fail; a sort of 'silent' recognition that the
741       // region to unassign has been split and no longer exists: TOOD: what if
742       // the split fails and the parent region comes back to life?
743       unassign(am, SERVERNAME_A, hri);
744       // This transition should fail if the znode has been messed with.
745       ZKAssign.transitionNode(this.watcher, hri, SERVERNAME_A,
746         EventType.RS_ZK_REGION_SPLITTING, EventType.RS_ZK_REGION_SPLITTING, version);
747       assertFalse(am.getRegionStates().isRegionInTransition(hri));
748     } finally {
749       am.shutdown();
750     }
751   }
752 
753   /**
754    * Tests the processDeadServersAndRegionsInTransition should not fail with NPE
755    * when it failed to get the children. Let's abort the system in this
756    * situation
757    * @throws ServiceException
758    */
759   @Test(timeout = 60000)
760   public void testProcessDeadServersAndRegionsInTransitionShouldNotFailWithNPE()
761       throws IOException, KeeperException, CoordinatedStateException,
762       InterruptedException, ServiceException {
763     final RecoverableZooKeeper recoverableZk = Mockito
764         .mock(RecoverableZooKeeper.class);
765     AssignmentManagerWithExtrasForTesting am = setUpMockedAssignmentManager(
766       this.server, this.serverManager);
767     Watcher zkw = new ZooKeeperWatcher(HBaseConfiguration.create(), "unittest",
768         null) {
769       @Override
770       public RecoverableZooKeeper getRecoverableZooKeeper() {
771         return recoverableZk;
772       }
773     };
774     ((ZooKeeperWatcher) zkw).registerListener(am);
775     Mockito.doThrow(new InterruptedException()).when(recoverableZk)
776         .getChildren("/hbase/region-in-transition", null);
777     am.setWatcher((ZooKeeperWatcher) zkw);
778     try {
779       am.processDeadServersAndRegionsInTransition(null);
780       fail("Expected to abort");
781     } catch (NullPointerException e) {
782       fail("Should not throw NPE");
783     } catch (RuntimeException e) {
784       assertEquals("Aborted", e.getLocalizedMessage());
785     } finally {
786       am.shutdown();
787     }
788   }
789   /**
790    * TestCase verifies that the regionPlan is updated whenever a region fails to open
791    * and the master tries to process RS_ZK_FAILED_OPEN state.(HBASE-5546).
792    */
793   @Test(timeout = 60000)
794   public void testRegionPlanIsUpdatedWhenRegionFailsToOpen() throws IOException, KeeperException,
795       ServiceException, InterruptedException, CoordinatedStateException {
796     this.server.getConfiguration().setClass(
797       HConstants.HBASE_MASTER_LOADBALANCER_CLASS, MockedLoadBalancer.class,
798       LoadBalancer.class);
799     AssignmentManagerWithExtrasForTesting am = setUpMockedAssignmentManager(
800       this.server, this.serverManager);
801     try {
802       // Boolean variable used for waiting until randomAssignment is called and
803       // new
804       // plan is generated.
805       AtomicBoolean gate = new AtomicBoolean(false);
806       if (balancer instanceof MockedLoadBalancer) {
807         ((MockedLoadBalancer) balancer).setGateVariable(gate);
808       }
809       ZKAssign.createNodeOffline(this.watcher, REGIONINFO, SERVERNAME_A);
810       int v = ZKAssign.getVersion(this.watcher, REGIONINFO);
811       ZKAssign.transitionNode(this.watcher, REGIONINFO, SERVERNAME_A,
812           EventType.M_ZK_REGION_OFFLINE, EventType.RS_ZK_REGION_FAILED_OPEN, v);
813       String path = ZKAssign.getNodeName(this.watcher, REGIONINFO
814           .getEncodedName());
815       am.getRegionStates().updateRegionState(
816         REGIONINFO, State.OPENING, SERVERNAME_A);
817       // a dummy plan inserted into the regionPlans. This plan is cleared and
818       // new one is formed
819       am.regionPlans.put(REGIONINFO.getEncodedName(), new RegionPlan(
820           REGIONINFO, null, SERVERNAME_A));
821       RegionPlan regionPlan = am.regionPlans.get(REGIONINFO.getEncodedName());
822       List<ServerName> serverList = new ArrayList<ServerName>(2);
823       serverList.add(SERVERNAME_B);
824       Mockito.when(
825           this.serverManager.createDestinationServersList(SERVERNAME_A))
826           .thenReturn(serverList);
827       am.nodeDataChanged(path);
828       // here we are waiting until the random assignment in the load balancer is
829       // called.
830       while (!gate.get()) {
831         Thread.sleep(10);
832       }
833       // new region plan may take some time to get updated after random
834       // assignment is called and
835       // gate is set to true.
836       RegionPlan newRegionPlan = am.regionPlans
837           .get(REGIONINFO.getEncodedName());
838       while (newRegionPlan == null) {
839         Thread.sleep(10);
840         newRegionPlan = am.regionPlans.get(REGIONINFO.getEncodedName());
841       }
842       // the new region plan created may contain the same RS as destination but
843       // it should
844       // be new plan.
845       assertNotSame("Same region plan should not come", regionPlan,
846           newRegionPlan);
847       assertTrue("Destination servers should be different.", !(regionPlan
848           .getDestination().equals(newRegionPlan.getDestination())));
849 
850       Mocking.waitForRegionPendingOpenInRIT(am, REGIONINFO.getEncodedName());
851     } finally {
852       this.server.getConfiguration().setClass(
853           HConstants.HBASE_MASTER_LOADBALANCER_CLASS, SimpleLoadBalancer.class,
854           LoadBalancer.class);
855       am.getExecutorService().shutdown();
856       am.shutdown();
857     }
858   }
859 
860   /**
861    * Mocked load balancer class used in the testcase to make sure that the testcase waits until
862    * random assignment is called and the gate variable is set to true.
863    */
864   public static class MockedLoadBalancer extends SimpleLoadBalancer {
865     private AtomicBoolean gate;
866 
867     public void setGateVariable(AtomicBoolean gate) {
868       this.gate = gate;
869     }
870 
871     @Override
872     public ServerName randomAssignment(HRegionInfo regionInfo, List<ServerName> servers) {
873       ServerName randomServerName = super.randomAssignment(regionInfo, servers);
874       this.gate.set(true);
875       return randomServerName;
876     }
877 
878     @Override
879     public Map<ServerName, List<HRegionInfo>> retainAssignment(
880         Map<HRegionInfo, ServerName> regions, List<ServerName> servers) {
881       this.gate.set(true);
882       return super.retainAssignment(regions, servers);
883     }
884   }
885 
886   /**
887    * Test the scenario when the master is in failover and trying to process a
888    * region which is in Opening state on a dead RS. Master will force offline the
889    * region and put it in transition. AM relies on SSH to reassign it.
890    */
891   @Test(timeout = 60000)
892   public void testRegionInOpeningStateOnDeadRSWhileMasterFailover() throws IOException,
893       KeeperException, ServiceException, CoordinatedStateException, InterruptedException {
894     AssignmentManagerWithExtrasForTesting am = setUpMockedAssignmentManager(
895       this.server, this.serverManager);
896     ZKAssign.createNodeOffline(this.watcher, REGIONINFO, SERVERNAME_A);
897     int version = ZKAssign.getVersion(this.watcher, REGIONINFO);
898     ZKAssign.transitionNode(this.watcher, REGIONINFO, SERVERNAME_A, EventType.M_ZK_REGION_OFFLINE,
899         EventType.RS_ZK_REGION_OPENING, version);
900     RegionTransition rt = RegionTransition.createRegionTransition(EventType.RS_ZK_REGION_OPENING,
901         REGIONINFO.getRegionName(), SERVERNAME_A, HConstants.EMPTY_BYTE_ARRAY);
902     version = ZKAssign.getVersion(this.watcher, REGIONINFO);
903     Mockito.when(this.serverManager.isServerOnline(SERVERNAME_A)).thenReturn(false);
904     am.getRegionStates().logSplit(SERVERNAME_A); // Assume log splitting is done
905     am.getRegionStates().createRegionState(REGIONINFO);
906     am.gate.set(false);
907 
908     BaseCoordinatedStateManager cp = new ZkCoordinatedStateManager();
909     cp.initialize(server);
910     cp.start();
911 
912     OpenRegionCoordination orc = cp.getOpenRegionCoordination();
913     ZkOpenRegionCoordination.ZkOpenRegionDetails zkOrd =
914       new ZkOpenRegionCoordination.ZkOpenRegionDetails();
915     zkOrd.setServerName(server.getServerName());
916     zkOrd.setVersion(version);
917 
918     assertFalse(am.processRegionsInTransition(rt, REGIONINFO, orc, zkOrd));
919     am.getTableStateManager().setTableState(REGIONINFO.getTable(), Table.State.ENABLED);
920     processServerShutdownHandler(am, false);
921     // Waiting for the assignment to get completed.
922     while (!am.gate.get()) {
923       Thread.sleep(10);
924     }
925     assertTrue("The region should be assigned immediately.", null != am.regionPlans.get(REGIONINFO
926         .getEncodedName()));
927     am.shutdown();
928   }
929 
930   /**
931    * Test verifies whether assignment is skipped for regions of tables in DISABLING state during
932    * clean cluster startup. See HBASE-6281.
933    *
934    * @throws KeeperException
935    * @throws IOException
936    * @throws Exception
937    */
938   @Test(timeout = 60000)
939   public void testDisablingTableRegionsAssignmentDuringCleanClusterStartup()
940       throws KeeperException, IOException, Exception {
941     this.server.getConfiguration().setClass(HConstants.HBASE_MASTER_LOADBALANCER_CLASS,
942         MockedLoadBalancer.class, LoadBalancer.class);
943     Mockito.when(this.serverManager.getOnlineServers()).thenReturn(
944         new HashMap<ServerName, ServerLoad>(0));
945     List<ServerName> destServers = new ArrayList<ServerName>(1);
946     destServers.add(SERVERNAME_A);
947     Mockito.when(this.serverManager.createDestinationServersList()).thenReturn(destServers);
948     // To avoid cast exception in DisableTableHandler process.
949     HTU.getConfiguration().setInt(HConstants.MASTER_PORT, 0);
950 
951     CoordinatedStateManager csm = CoordinatedStateManagerFactory.getCoordinatedStateManager(
952       HTU.getConfiguration());
953     Server server = new HMaster(HTU.getConfiguration(), csm);
954     AssignmentManagerWithExtrasForTesting am = setUpMockedAssignmentManager(server,
955         this.serverManager);
956 
957     Whitebox.setInternalState(server, "metaTableLocator", Mockito.mock(MetaTableLocator.class));
958 
959     // Make it so we can get a catalogtracker from servermanager.. .needed
960     // down in guts of server shutdown handler.
961     Whitebox.setInternalState(server, "clusterConnection", am.getConnection());
962 
963     AtomicBoolean gate = new AtomicBoolean(false);
964     if (balancer instanceof MockedLoadBalancer) {
965       ((MockedLoadBalancer) balancer).setGateVariable(gate);
966     }
967     try{
968       // set table in disabling state.
969       am.getTableStateManager().setTableState(REGIONINFO.getTable(),
970         Table.State.DISABLING);
971       am.joinCluster();
972       // should not call retainAssignment if we get empty regions in assignAllUserRegions.
973       assertFalse(
974           "Assign should not be invoked for disabling table regions during clean cluster startup.",
975           gate.get());
976       // need to change table state from disabling to disabled.
977       assertTrue("Table should be disabled.",
978           am.getTableStateManager().isTableState(REGIONINFO.getTable(),
979             Table.State.DISABLED));
980     } finally {
981       this.server.getConfiguration().setClass(
982         HConstants.HBASE_MASTER_LOADBALANCER_CLASS, SimpleLoadBalancer.class,
983         LoadBalancer.class);
984       am.getTableStateManager().setTableState(REGIONINFO.getTable(),
985         Table.State.ENABLED);
986       am.shutdown();
987     }
988   }
989 
990   /**
991    * Test verifies whether all the enabling table regions assigned only once during master startup.
992    *
993    * @throws KeeperException
994    * @throws IOException
995    * @throws Exception
996    */
997   @Test (timeout=180000)
998   public void testMasterRestartWhenTableInEnabling() throws KeeperException, IOException, Exception {
999     enabling = true;
1000     List<ServerName> destServers = new ArrayList<ServerName>(1);
1001     destServers.add(SERVERNAME_A);
1002     Mockito.when(this.serverManager.createDestinationServersList()).thenReturn(destServers);
1003     Mockito.when(this.serverManager.isServerOnline(SERVERNAME_A)).thenReturn(true);
1004     HTU.getConfiguration().setInt(HConstants.MASTER_PORT, 0);
1005     CoordinatedStateManager csm = CoordinatedStateManagerFactory.getCoordinatedStateManager(
1006       HTU.getConfiguration());
1007     Server server = new HMaster(HTU.getConfiguration(), csm);
1008     Whitebox.setInternalState(server, "serverManager", this.serverManager);
1009     AssignmentManagerWithExtrasForTesting am = setUpMockedAssignmentManager(server,
1010         this.serverManager);
1011 
1012     Whitebox.setInternalState(server, "metaTableLocator", Mockito.mock(MetaTableLocator.class));
1013 
1014     // Make it so we can get a catalogtracker from servermanager.. .needed
1015     // down in guts of server shutdown handler.
1016     Whitebox.setInternalState(server, "clusterConnection", am.getConnection());
1017 
1018     try {
1019       // set table in enabling state.
1020       am.getTableStateManager().setTableState(REGIONINFO.getTable(),
1021         Table.State.ENABLING);
1022       new EnableTableHandler(server, REGIONINFO.getTable(),
1023           am, new NullTableLockManager(), true).prepare()
1024           .process();
1025       assertEquals("Number of assignments should be 1.", 1, assignmentCount);
1026       assertTrue("Table should be enabled.",
1027           am.getTableStateManager().isTableState(REGIONINFO.getTable(),
1028             Table.State.ENABLED));
1029     } finally {
1030       enabling = false;
1031       assignmentCount = 0;
1032       am.getTableStateManager().setTableState(REGIONINFO.getTable(),
1033         Table.State.ENABLED);
1034       am.shutdown();
1035       ZKAssign.deleteAllNodes(this.watcher);
1036     }
1037   }
1038 
1039   /**
1040    * Test verifies whether stale znodes of unknown tables as for the hbase:meta will be removed or
1041    * not.
1042    * @throws KeeperException
1043    * @throws IOException
1044    * @throws Exception
1045    */
1046   @Test (timeout=180000)
1047   public void testMasterRestartShouldRemoveStaleZnodesOfUnknownTableAsForMeta()
1048       throws Exception {
1049     List<ServerName> destServers = new ArrayList<ServerName>(1);
1050     destServers.add(SERVERNAME_A);
1051     Mockito.when(this.serverManager.createDestinationServersList()).thenReturn(destServers);
1052     Mockito.when(this.serverManager.isServerOnline(SERVERNAME_A)).thenReturn(true);
1053     HTU.getConfiguration().setInt(HConstants.MASTER_PORT, 0);
1054     CoordinatedStateManager csm = CoordinatedStateManagerFactory.getCoordinatedStateManager(
1055       HTU.getConfiguration());
1056     Server server = new HMaster(HTU.getConfiguration(), csm);
1057     Whitebox.setInternalState(server, "serverManager", this.serverManager);
1058     AssignmentManagerWithExtrasForTesting am = setUpMockedAssignmentManager(server,
1059         this.serverManager);
1060 
1061     Whitebox.setInternalState(server, "metaTableLocator", Mockito.mock(MetaTableLocator.class));
1062 
1063     // Make it so we can get a catalogtracker from servermanager.. .needed
1064     // down in guts of server shutdown handler.
1065     Whitebox.setInternalState(server, "clusterConnection", am.getConnection());
1066 
1067     try {
1068       TableName tableName = TableName.valueOf("dummyTable");
1069       // set table in enabling state.
1070       am.getTableStateManager().setTableState(tableName,
1071         Table.State.ENABLING);
1072       am.joinCluster();
1073       assertFalse("Table should not be present in zookeeper.",
1074         am.getTableStateManager().isTablePresent(tableName));
1075     } finally {
1076       am.shutdown();
1077     }
1078   }
1079   /**
1080    * When a region is in transition, if the region server opening the region goes down,
1081    * the region assignment takes a long time normally (waiting for timeout monitor to trigger assign).
1082    * This test is to make sure SSH reassigns it right away.
1083    */
1084   @Test (timeout=180000)
1085   public void testSSHTimesOutOpeningRegionTransition()
1086       throws KeeperException, IOException, CoordinatedStateException, ServiceException {
1087     // Create an AM.
1088     AssignmentManagerWithExtrasForTesting am =
1089       setUpMockedAssignmentManager(this.server, this.serverManager);
1090     // adding region in pending open.
1091     RegionState state = new RegionState(REGIONINFO,
1092       State.OPENING, System.currentTimeMillis(), SERVERNAME_A);
1093     am.getRegionStates().regionOnline(REGIONINFO, SERVERNAME_B);
1094     am.getRegionStates().regionsInTransition.put(REGIONINFO.getEncodedName(), state);
1095     // adding region plan
1096     am.regionPlans.put(REGIONINFO.getEncodedName(),
1097       new RegionPlan(REGIONINFO, SERVERNAME_B, SERVERNAME_A));
1098     am.getTableStateManager().setTableState(REGIONINFO.getTable(),
1099       Table.State.ENABLED);
1100 
1101     try {
1102       am.assignInvoked = false;
1103       processServerShutdownHandler(am, false);
1104       assertTrue(am.assignInvoked);
1105     } finally {
1106       am.getRegionStates().regionsInTransition.remove(REGIONINFO.getEncodedName());
1107       am.regionPlans.remove(REGIONINFO.getEncodedName());
1108       am.shutdown();
1109     }
1110   }
1111 
1112   /**
1113    * Scenario:<ul>
1114    *  <li> master starts a close, and creates a znode</li>
1115    *  <li> it fails just at this moment, before contacting the RS</li>
1116    *  <li> while the second master is coming up, the targeted RS dies. But it's before ZK timeout so
1117    *    we don't know, and we have an exception.</li>
1118    *  <li> the master must handle this nicely and reassign.
1119    *  </ul>
1120    */
1121   @Test (timeout=180000)
1122   public void testClosingFailureDuringRecovery() throws Exception {
1123 
1124     AssignmentManagerWithExtrasForTesting am =
1125         setUpMockedAssignmentManager(this.server, this.serverManager);
1126     ZKAssign.createNodeClosing(this.watcher, REGIONINFO, SERVERNAME_A);
1127     try {
1128       am.getRegionStates().createRegionState(REGIONINFO);
1129 
1130       assertFalse( am.getRegionStates().isRegionsInTransition() );
1131 
1132       am.processRegionInTransition(REGIONINFO.getEncodedName(), REGIONINFO);
1133 
1134       assertTrue( am.getRegionStates().isRegionsInTransition() );
1135     } finally {
1136       am.shutdown();
1137     }
1138   }
1139 
1140   /**
1141    * Creates a new ephemeral node in the SPLITTING state for the specified region.
1142    * Create it ephemeral in case regionserver dies mid-split.
1143    *
1144    * <p>Does not transition nodes from other states.  If a node already exists
1145    * for this region, a {@link NodeExistsException} will be thrown.
1146    *
1147    * @param zkw zk reference
1148    * @param region region to be created as offline
1149    * @param serverName server event originates from
1150    * @return Version of znode created.
1151    * @throws KeeperException
1152    * @throws IOException
1153    */
1154   // Copied from SplitTransaction rather than open the method over there in
1155   // the regionserver package.
1156   private static int createNodeSplitting(final ZooKeeperWatcher zkw,
1157       final HRegionInfo region, final ServerName serverName)
1158   throws KeeperException, IOException {
1159     RegionTransition rt =
1160       RegionTransition.createRegionTransition(EventType.RS_ZK_REGION_SPLITTING,
1161         region.getRegionName(), serverName);
1162 
1163     String node = ZKAssign.getNodeName(zkw, region.getEncodedName());
1164     if (!ZKUtil.createEphemeralNodeAndWatch(zkw, node, rt.toByteArray())) {
1165       throw new IOException("Failed create of ephemeral " + node);
1166     }
1167     // Transition node from SPLITTING to SPLITTING and pick up version so we
1168     // can be sure this znode is ours; version is needed deleting.
1169     return transitionNodeSplitting(zkw, region, serverName, -1);
1170   }
1171 
1172   // Copied from SplitTransaction rather than open the method over there in
1173   // the regionserver package.
1174   private static int transitionNodeSplitting(final ZooKeeperWatcher zkw,
1175       final HRegionInfo parent,
1176       final ServerName serverName, final int version)
1177   throws KeeperException, IOException {
1178     return ZKAssign.transitionNode(zkw, parent, serverName,
1179       EventType.RS_ZK_REGION_SPLITTING, EventType.RS_ZK_REGION_SPLITTING, version);
1180   }
1181 
1182   private void unassign(final AssignmentManager am, final ServerName sn,
1183       final HRegionInfo hri) throws RegionException {
1184     // Before I can unassign a region, I need to set it online.
1185     am.regionOnline(hri, sn);
1186     // Unassign region.
1187     am.unassign(hri);
1188   }
1189 
1190   /**
1191    * Create an {@link AssignmentManagerWithExtrasForTesting} that has mocked
1192    * {@link CatalogTracker} etc.
1193    * @param server
1194    * @param manager
1195    * @return An AssignmentManagerWithExtras with mock connections, etc.
1196    * @throws IOException
1197    * @throws KeeperException
1198    */
1199   private AssignmentManagerWithExtrasForTesting setUpMockedAssignmentManager(final Server server,
1200       final ServerManager manager) throws IOException, KeeperException,
1201         ServiceException, CoordinatedStateException {
1202     // Make an RS Interface implementation. Make it so a scanner can go against
1203     // it and a get to return the single region, REGIONINFO, this test is
1204     // messing with. Needed when "new master" joins cluster. AM will try and
1205     // rebuild its list of user regions and it will also get the HRI that goes
1206     // with an encoded name by doing a Get on hbase:meta
1207     ClientProtos.ClientService.BlockingInterface ri =
1208       Mockito.mock(ClientProtos.ClientService.BlockingInterface.class);
1209     // Get a meta row result that has region up on SERVERNAME_A for REGIONINFO
1210     Result r = MetaMockingUtil.getMetaTableRowResult(REGIONINFO, SERVERNAME_A);
1211     final ScanResponse.Builder builder = ScanResponse.newBuilder();
1212     builder.setMoreResults(true);
1213     builder.addCellsPerResult(r.size());
1214     final List<CellScannable> rows = new ArrayList<CellScannable>(1);
1215     rows.add(r);
1216     Answer<ScanResponse> ans = new Answer<ClientProtos.ScanResponse>() {
1217       @Override
1218       public ScanResponse answer(InvocationOnMock invocation) throws Throwable {
1219         PayloadCarryingRpcController controller = (PayloadCarryingRpcController) invocation
1220             .getArguments()[0];
1221         if (controller != null) {
1222           controller.setCellScanner(CellUtil.createCellScanner(rows));
1223         }
1224         return builder.build();
1225       }
1226     };
1227     if (enabling) {
1228       Mockito.when(ri.scan((RpcController) Mockito.any(), (ScanRequest) Mockito.any()))
1229           .thenAnswer(ans).thenAnswer(ans).thenAnswer(ans).thenAnswer(ans).thenAnswer(ans)
1230           .thenReturn(ScanResponse.newBuilder().setMoreResults(false).build());
1231     } else {
1232       Mockito.when(ri.scan((RpcController) Mockito.any(), (ScanRequest) Mockito.any())).thenAnswer(
1233           ans);
1234     }
1235     // If a get, return the above result too for REGIONINFO
1236     GetResponse.Builder getBuilder = GetResponse.newBuilder();
1237     getBuilder.setResult(ProtobufUtil.toResult(r));
1238     Mockito.when(ri.get((RpcController)Mockito.any(), (GetRequest) Mockito.any())).
1239       thenReturn(getBuilder.build());
1240     // Get a connection w/ mocked up common methods.
1241     ClusterConnection connection = (ClusterConnection)HConnectionTestingUtility.
1242       getMockedConnectionAndDecorate(HTU.getConfiguration(), null,
1243         ri, SERVERNAME_B, REGIONINFO);
1244     // These mocks were done up when all connections were managed.  World is different now we
1245     // moved to unmanaged connections.  It messes up the intercepts done in these tests.
1246     // Just mark connections as marked and then down in MetaTableAccessor, it will go the path
1247     // that picks up the above mocked up 'implementation' so 'scans' of meta return the expected
1248     // result.  Redo in new realm of unmanaged connections.
1249     Mockito.when(connection.isManaged()).thenReturn(true);
1250     // Make it so we can get the connection from our mocked catalogtracker
1251     // Create and startup an executor. Used by AM handling zk callbacks.
1252     ExecutorService executor = startupMasterExecutor("mockedAMExecutor");
1253     this.balancer = LoadBalancerFactory.getLoadBalancer(server.getConfiguration());
1254     AssignmentManagerWithExtrasForTesting am = new AssignmentManagerWithExtrasForTesting(
1255       server, connection, manager, this.balancer, executor, new NullTableLockManager());
1256     return am;
1257   }
1258 
1259   /**
1260    * An {@link AssignmentManager} with some extra facility used testing
1261    */
1262   class AssignmentManagerWithExtrasForTesting extends AssignmentManager {
1263     // Keep a reference so can give it out below in {@link #getExecutorService}
1264     private final ExecutorService es;
1265     boolean processRITInvoked = false;
1266     boolean assignInvoked = false;
1267     AtomicBoolean gate = new AtomicBoolean(true);
1268     private ClusterConnection connection;
1269 
1270     public AssignmentManagerWithExtrasForTesting(
1271         final Server master, ClusterConnection connection, final ServerManager serverManager,
1272         final LoadBalancer balancer,
1273         final ExecutorService service, final TableLockManager tableLockManager)
1274             throws KeeperException, IOException, CoordinatedStateException {
1275       super(master, serverManager, balancer, service, null, tableLockManager);
1276       this.es = service;
1277       this.connection = connection;
1278     }
1279 
1280     @Override
1281     boolean processRegionInTransition(String encodedRegionName,
1282         HRegionInfo regionInfo) throws KeeperException, IOException {
1283       this.processRITInvoked = true;
1284       return super.processRegionInTransition(encodedRegionName, regionInfo);
1285     }
1286 
1287     @Override
1288     public void assign(HRegionInfo region, boolean setOfflineInZK, boolean forceNewPlan) {
1289       if (enabling) {
1290         assignmentCount++;
1291         this.regionOnline(region, SERVERNAME_A);
1292       } else {
1293         super.assign(region, setOfflineInZK, forceNewPlan);
1294         this.gate.set(true);
1295       }
1296     }
1297 
1298     @Override
1299     boolean assign(ServerName destination, List<HRegionInfo> regions)
1300         throws InterruptedException {
1301       if (enabling) {
1302         for (HRegionInfo region : regions) {
1303           assignmentCount++;
1304           this.regionOnline(region, SERVERNAME_A);
1305         }
1306         return true;
1307       }
1308       return super.assign(destination, regions);
1309     }
1310 
1311     @Override
1312     public void assign(List<HRegionInfo> regions)
1313         throws IOException, InterruptedException {
1314       assignInvoked = (regions != null && regions.size() > 0);
1315       super.assign(regions);
1316       this.gate.set(true);
1317     }
1318 
1319     /** reset the watcher */
1320     void setWatcher(ZooKeeperWatcher watcher) {
1321       this.watcher = watcher;
1322     }
1323 
1324     /**
1325      * @return ExecutorService used by this instance.
1326      */
1327     ExecutorService getExecutorService() {
1328       return this.es;
1329     }
1330 
1331     /*
1332      * Convenient method to retrieve mocked up connection
1333      */
1334     ClusterConnection getConnection() {
1335       return this.connection;
1336     }
1337 
1338     @Override
1339     public void shutdown() {
1340       super.shutdown();
1341       if (this.connection != null)
1342         try {
1343           this.connection.close();
1344         } catch (IOException e) {
1345           fail("Failed to close connection");
1346         }
1347     }
1348   }
1349 
1350   /**
1351    * Call joinCluster on the passed AssignmentManager.  Do it in a thread
1352    * so it runs independent of what all else is going on.  Try to simulate
1353    * an AM running insided a failed over master by clearing all in-memory
1354    * AM state first.
1355   */
1356   private void startFakeFailedOverMasterAssignmentManager(final AssignmentManager am,
1357       final ZooKeeperWatcher watcher) {
1358     // Make sure our new AM gets callbacks; once registered, we can't unregister.
1359     // Thats ok because we make a new zk watcher for each test.
1360     watcher.registerListenerFirst(am);
1361     Thread t = new Thread("RunAmJoinCluster") {
1362       @Override
1363       public void run() {
1364         // Call the joinCluster function as though we were doing a master
1365         // failover at this point. It will stall just before we go to add
1366         // the RIT region to our RIT Map in AM at processRegionsInTransition.
1367         // First clear any inmemory state from AM so it acts like a new master
1368         // coming on line.
1369         am.getRegionStates().regionsInTransition.clear();
1370         am.regionPlans.clear();
1371         try {
1372           am.joinCluster();
1373         } catch (IOException e) {
1374           throw new RuntimeException(e);
1375         } catch (KeeperException e) {
1376           throw new RuntimeException(e);
1377         } catch (InterruptedException e) {
1378           throw new RuntimeException(e);
1379         } catch (CoordinatedStateException e) {
1380           throw new RuntimeException(e);
1381         }
1382       }
1383     };
1384     t.start();
1385     while (!t.isAlive()) Threads.sleep(1);
1386   }
1387 
1388   @Test (timeout=180000)
1389   public void testForceAssignMergingRegion() throws Exception {
1390     // Region to use in test.
1391     final HRegionInfo hri = HRegionInfo.FIRST_META_REGIONINFO;
1392     // Need a mocked catalog tracker.
1393     LoadBalancer balancer = LoadBalancerFactory.getLoadBalancer(
1394       server.getConfiguration());
1395     // Create an AM.
1396     AssignmentManager am = new AssignmentManager(this.server,
1397       this.serverManager, balancer, null, null, master.getTableLockManager());
1398     RegionStates regionStates = am.getRegionStates();
1399     try {
1400       // First set the state of the region to merging
1401       regionStates.updateRegionState(hri, RegionState.State.MERGING);
1402       // Now, try to assign it with force new plan
1403       am.assign(hri, true, true);
1404       assertEquals("The region should be still in merging state",
1405         RegionState.State.MERGING, regionStates.getRegionState(hri).getState());
1406     } finally {
1407       am.shutdown();
1408     }
1409   }
1410 
1411   /**
1412    * Test assignment related ZK events are ignored by AM if the region is not known
1413    * by AM to be in transition. During normal operation, all assignments are started
1414    * by AM (not considering split/merge), if an event is received but the region
1415    * is not in transition, the event must be a very late one. So it can be ignored.
1416    * During master failover, since AM watches assignment znodes after failover cleanup
1417    * is completed, when an event comes in, AM should already have the region in transition
1418    * if ZK is used during the assignment action (only hbck doesn't use ZK for region
1419    * assignment). So during master failover, we can ignored such events too.
1420    */
1421   @Test (timeout=180000)
1422   public void testAssignmentEventIgnoredIfNotExpected() throws KeeperException, IOException,
1423       CoordinatedStateException {
1424     // Region to use in test.
1425     final HRegionInfo hri = HRegionInfo.FIRST_META_REGIONINFO;
1426     LoadBalancer balancer = LoadBalancerFactory.getLoadBalancer(
1427       server.getConfiguration());
1428     final AtomicBoolean zkEventProcessed = new AtomicBoolean(false);
1429     // Create an AM.
1430     AssignmentManager am = new AssignmentManager(this.server,
1431       this.serverManager, balancer, null, null, master.getTableLockManager()) {
1432 
1433       @Override
1434       void handleRegion(final RegionTransition rt, OpenRegionCoordination coordination,
1435                         OpenRegionCoordination.OpenRegionDetails ord) {
1436         super.handleRegion(rt, coordination, ord);
1437         if (rt != null && Bytes.equals(hri.getRegionName(),
1438           rt.getRegionName()) && rt.getEventType() == EventType.RS_ZK_REGION_OPENING) {
1439           zkEventProcessed.set(true);
1440         }
1441       }
1442     };
1443     try {
1444       // First make sure the region is not in transition
1445       am.getRegionStates().regionOffline(hri);
1446       zkEventProcessed.set(false); // Reset it before faking zk transition
1447       this.watcher.registerListenerFirst(am);
1448       assertFalse("The region should not be in transition",
1449         am.getRegionStates().isRegionInTransition(hri));
1450       ZKAssign.createNodeOffline(this.watcher, hri, SERVERNAME_A);
1451       // Trigger a transition event
1452       ZKAssign.transitionNodeOpening(this.watcher, hri, SERVERNAME_A);
1453       long startTime = EnvironmentEdgeManager.currentTime();
1454       while (!zkEventProcessed.get()) {
1455         assertTrue("Timed out in waiting for ZK event to be processed",
1456           EnvironmentEdgeManager.currentTime() - startTime < 30000);
1457         Threads.sleepWithoutInterrupt(100);
1458       }
1459       assertFalse(am.getRegionStates().isRegionInTransition(hri));
1460     } finally {
1461       am.shutdown();
1462     }
1463   }
1464 
1465   /**
1466    * If a table is deleted, we should not be able to balance it anymore.
1467    * Otherwise, the region will be brought back.
1468    * @throws Exception
1469    */
1470   @Test (timeout=180000)
1471   public void testBalanceRegionOfDeletedTable() throws Exception {
1472     AssignmentManager am = new AssignmentManager(this.server, this.serverManager,
1473       balancer, null, null, master.getTableLockManager());
1474     RegionStates regionStates = am.getRegionStates();
1475     HRegionInfo hri = REGIONINFO;
1476     regionStates.createRegionState(hri);
1477     assertFalse(regionStates.isRegionInTransition(hri));
1478     RegionPlan plan = new RegionPlan(hri, SERVERNAME_A, SERVERNAME_B);
1479     // Fake table is deleted
1480     regionStates.tableDeleted(hri.getTable());
1481     am.balance(plan);
1482     assertFalse("The region should not in transition",
1483       regionStates.isRegionInTransition(hri));
1484     am.shutdown();
1485   }
1486 
1487   /**
1488    * Tests an on-the-fly RPC that was scheduled for the earlier RS on the same port
1489    * for openRegion. AM should assign this somewhere else. (HBASE-9721)
1490    */
1491   @SuppressWarnings("unchecked")
1492   @Test (timeout=180000)
1493   public void testOpenCloseRegionRPCIntendedForPreviousServer() throws Exception {
1494     Mockito.when(this.serverManager.sendRegionOpen(Mockito.eq(SERVERNAME_B), Mockito.eq(REGIONINFO),
1495       Mockito.anyInt(), (List<ServerName>)Mockito.any()))
1496       .thenThrow(new DoNotRetryIOException());
1497     this.server.getConfiguration().setInt("hbase.assignment.maximum.attempts", 100);
1498 
1499     HRegionInfo hri = REGIONINFO;
1500     LoadBalancer balancer = LoadBalancerFactory.getLoadBalancer(
1501       server.getConfiguration());
1502     // Create an AM.
1503     AssignmentManager am = new AssignmentManager(this.server,
1504       this.serverManager, balancer, null, null, master.getTableLockManager());
1505     RegionStates regionStates = am.getRegionStates();
1506     try {
1507       am.regionPlans.put(REGIONINFO.getEncodedName(),
1508         new RegionPlan(REGIONINFO, null, SERVERNAME_B));
1509 
1510       // Should fail once, but succeed on the second attempt for the SERVERNAME_A
1511       am.assign(hri, true, false);
1512     } finally {
1513       assertEquals(SERVERNAME_A, regionStates.getRegionState(REGIONINFO).getServerName());
1514       am.shutdown();
1515     }
1516   }
1517 }