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.assertNotNull;
23  import static org.mockito.Mockito.when;
24  
25  import java.io.IOException;
26  import java.util.Collection;
27  import java.util.Iterator;
28  import java.util.List;
29  
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.apache.hadoop.conf.Configuration;
33  import org.apache.hadoop.hbase.*;
34  import org.apache.hadoop.hbase.executor.EventHandler.EventType;
35  import org.apache.hadoop.hbase.master.AssignmentManager.RegionState;
36  import org.apache.hadoop.hbase.master.handler.OpenedRegionHandler;
37  import org.apache.hadoop.hbase.regionserver.HRegion;
38  import org.apache.hadoop.hbase.regionserver.HRegionServer;
39  import org.apache.hadoop.hbase.util.Bytes;
40  import org.apache.hadoop.hbase.util.MockServer;
41  import org.apache.hadoop.hbase.zookeeper.ZKAssign;
42  import org.apache.hadoop.hbase.zookeeper.ZKTable;
43  import org.apache.hadoop.hbase.zookeeper.ZKUtil;
44  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
45  import org.apache.zookeeper.KeeperException;
46  import org.apache.zookeeper.data.Stat;
47  import org.junit.After;
48  import org.junit.Before;
49  import org.junit.Test;
50  import org.junit.experimental.categories.Category;
51  import org.mockito.Mockito;
52  
53  @Category(MediumTests.class)
54  public class TestOpenedRegionHandler {
55  
56    private static final Log LOG = LogFactory
57        .getLog(TestOpenedRegionHandler.class);
58  
59    private HBaseTestingUtility TEST_UTIL;
60    private final int NUM_MASTERS = 1;
61    private final int NUM_RS = 1;
62    private Configuration conf;
63    private Configuration resetConf;
64    private ZooKeeperWatcher zkw;
65  
66    @Before
67    public void setUp() throws Exception {
68      conf = HBaseConfiguration.create();
69      TEST_UTIL = new HBaseTestingUtility(conf);
70    }
71    
72    @After
73    public void tearDown() throws Exception {
74      // Stop the cluster
75      TEST_UTIL.shutdownMiniCluster();
76      TEST_UTIL = new HBaseTestingUtility(resetConf);
77    }
78  
79    @Test
80    public void testOpenedRegionHandlerOnMasterRestart() throws Exception {
81      // Start the cluster
82      log("Starting cluster");
83      conf = HBaseConfiguration.create();
84      resetConf = conf;
85      conf.setInt("hbase.master.assignment.timeoutmonitor.period", 2000);
86      conf.setInt("hbase.master.assignment.timeoutmonitor.timeout", 5000);
87      TEST_UTIL = new HBaseTestingUtility(conf);
88      TEST_UTIL.startMiniCluster(NUM_MASTERS, NUM_RS);
89      String tableName = "testOpenedRegionHandlerOnMasterRestart";
90      MiniHBaseCluster cluster = createRegions(tableName);
91      abortMaster(cluster);
92  
93      HRegionServer regionServer = cluster.getRegionServer(0);
94      HRegion region = getRegionBeingServed(cluster, regionServer);
95  
96      // forcefully move a region to OPENED state in zk
97      // Create a ZKW to use in the test
98      zkw = HBaseTestingUtility.createAndForceNodeToOpenedState(TEST_UTIL,
99          region, regionServer.getServerName());
100 
101     // Start up a new master
102     log("Starting up a new master");
103     cluster.startMaster().getMaster();
104     log("Waiting for master to be ready");
105     cluster.waitForActiveAndReadyMaster();
106     log("Master is ready");
107 
108     // Failover should be completed, now wait for no RIT
109     log("Waiting for no more RIT");
110     ZKAssign.blockUntilNoRIT(zkw);
111   }
112   @Test
113   public void testShouldNotCompeleteOpenedRegionSuccessfullyIfVersionMismatches()
114       throws Exception {
115     HRegion region = null;
116     try {
117       int testIndex = 0;
118       TEST_UTIL.startMiniZKCluster();
119       final Server server = new MockServer(TEST_UTIL);
120       HTableDescriptor htd = new HTableDescriptor(
121           "testShouldNotCompeleteOpenedRegionSuccessfullyIfVersionMismatches");
122       HRegionInfo hri = new HRegionInfo(htd.getName(),
123           Bytes.toBytes(testIndex), Bytes.toBytes(testIndex + 1));
124       region = HRegion.createHRegion(hri, TEST_UTIL.getDataTestDir(), TEST_UTIL.getConfiguration(), htd);
125       assertNotNull(region);
126       AssignmentManager am = Mockito.mock(AssignmentManager.class);
127       when(am.isRegionInTransition(hri)).thenReturn(
128           new RegionState(region.getRegionInfo(), RegionState.State.OPEN,
129               System.currentTimeMillis(), server.getServerName()));
130       // create a node with OPENED state
131       zkw = HBaseTestingUtility.createAndForceNodeToOpenedState(TEST_UTIL,
132           region, server.getServerName());
133       when(am.getZKTable()).thenReturn(new ZKTable(zkw));
134       Stat stat = new Stat();
135       String nodeName = ZKAssign.getNodeName(zkw, region.getRegionInfo()
136           .getEncodedName());
137       ZKUtil.getDataAndWatch(zkw, nodeName, stat);
138 
139       // use the version for the OpenedRegionHandler
140       OpenedRegionHandler handler = new OpenedRegionHandler(server, am, region
141           .getRegionInfo(), server.getServerName(), stat.getVersion());
142       // Once again overwrite the same znode so that the version changes.
143       ZKAssign.transitionNode(zkw, region.getRegionInfo(), server
144           .getServerName(), EventType.RS_ZK_REGION_OPENED,
145           EventType.RS_ZK_REGION_OPENED, stat.getVersion());
146 
147       // Should not invoke assignmentmanager.regionOnline. If it is 
148       // invoked as per current mocking it will throw null pointer exception.
149       boolean expectedException = false;
150       try {
151         handler.process();
152       } catch (Exception e) {
153         expectedException = true;
154       }
155       assertFalse("The process method should not throw any exception.",
156           expectedException);
157       List<String> znodes = ZKUtil.listChildrenAndWatchForNewChildren(zkw,
158           zkw.assignmentZNode);
159       String regionName = znodes.get(0);
160       assertEquals("The region should not be opened successfully.", regionName,
161           region.getRegionInfo().getEncodedName());
162     } finally {
163       region.close();
164       region.getLog().closeAndDelete();
165       TEST_UTIL.shutdownMiniZKCluster();
166     }
167   }
168   private MiniHBaseCluster createRegions(String tableName)
169       throws InterruptedException, ZooKeeperConnectionException, IOException,
170       KeeperException {
171     MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
172     log("Waiting for active/ready master");
173     cluster.waitForActiveAndReadyMaster();
174     zkw = new ZooKeeperWatcher(conf, "testOpenedRegionHandler", null);
175 
176     // Create a table with regions
177     byte[] table = Bytes.toBytes(tableName);
178     byte[] family = Bytes.toBytes("family");
179     TEST_UTIL.createTable(table, family);
180 
181     //wait till the regions are online
182     log("Waiting for no more RIT");
183     ZKAssign.blockUntilNoRIT(zkw);
184 
185     return cluster;
186   }
187   private void abortMaster(MiniHBaseCluster cluster) {
188     // Stop the master
189     log("Aborting master");
190     cluster.abortMaster(0);
191     cluster.waitOnMaster(0);
192     log("Master has aborted");
193   }
194   private HRegion getRegionBeingServed(MiniHBaseCluster cluster,
195       HRegionServer regionServer) {
196     Collection<HRegion> onlineRegionsLocalContext = regionServer
197         .getOnlineRegionsLocalContext();
198     Iterator<HRegion> iterator = onlineRegionsLocalContext.iterator();
199     HRegion region = null;
200     while (iterator.hasNext()) {
201       region = iterator.next();
202       if (!region.getRegionInfo().isMetaTable()) {
203         break;
204       }
205     }
206     return region;
207   }
208   private void log(String msg) {
209     LOG.debug("\n\nTRR: " + msg + "\n");
210   }
211 
212   @org.junit.Rule
213   public org.apache.hadoop.hbase.ResourceCheckerJUnitRule cu =
214     new org.apache.hadoop.hbase.ResourceCheckerJUnitRule();
215 }
216