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