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  
19  package org.apache.hadoop.hbase.master.procedure;
20  
21  import java.util.concurrent.CountDownLatch;
22  
23  import org.apache.commons.logging.Log;
24  import org.apache.commons.logging.LogFactory;
25  import org.apache.hadoop.conf.Configuration;
26  import org.apache.hadoop.fs.FileSystem;
27  import org.apache.hadoop.fs.Path;
28  import org.apache.hadoop.hbase.HBaseTestingUtility;
29  import org.apache.hadoop.hbase.HRegionInfo;
30  import org.apache.hadoop.hbase.HTableDescriptor;
31  import org.apache.hadoop.hbase.MiniHBaseCluster;
32  import org.apache.hadoop.hbase.TableName;
33  import org.apache.hadoop.hbase.master.HMaster;
34  import org.apache.hadoop.hbase.procedure2.ProcedureExecutor;
35  import org.apache.hadoop.hbase.procedure2.ProcedureTestingUtility;
36  import org.apache.hadoop.hbase.procedure2.store.ProcedureStore;
37  import org.apache.hadoop.hbase.procedure2.store.wal.WALProcedureStore;
38  import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos.CreateTableState;
39  import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos.DeleteTableState;
40  import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos.DisableTableState;
41  import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos.EnableTableState;
42  import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos.TruncateTableState;
43  import org.apache.hadoop.hbase.testclassification.LargeTests;
44  import org.apache.hadoop.hbase.util.Bytes;
45  import org.apache.hadoop.hbase.util.FSUtils;
46  import org.apache.hadoop.hbase.util.ModifyRegionUtils;
47  
48  import org.junit.After;
49  import org.junit.Before;
50  import org.junit.Test;
51  import org.junit.experimental.categories.Category;
52  import org.mockito.Mockito;
53  
54  import static org.junit.Assert.assertEquals;
55  import static org.junit.Assert.assertFalse;
56  import static org.junit.Assert.assertTrue;
57  import static org.junit.Assert.fail;
58  
59  @Category(LargeTests.class)
60  public class TestMasterFailoverWithProcedures {
61    private static final Log LOG = LogFactory.getLog(TestMasterFailoverWithProcedures.class);
62  
63    protected static final HBaseTestingUtility UTIL = new HBaseTestingUtility();
64  
65    private static void setupConf(Configuration conf) {
66    }
67  
68    @Before
69    public void setup() throws Exception {
70      setupConf(UTIL.getConfiguration());
71      UTIL.startMiniCluster(2, 1);
72  
73      final ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
74      ProcedureTestingUtility.setToggleKillBeforeStoreUpdate(procExec, false);
75      ProcedureTestingUtility.setKillBeforeStoreUpdate(procExec, false);
76    }
77  
78    @After
79    public void tearDown() throws Exception {
80      try {
81        UTIL.shutdownMiniCluster();
82      } catch (Exception e) {
83        LOG.warn("failure shutting down cluster", e);
84      }
85    }
86  
87    @Test(timeout=60000)
88    public void testWalRecoverLease() throws Exception {
89      final ProcedureStore masterStore = getMasterProcedureExecutor().getStore();
90      assertTrue("expected WALStore for this test", masterStore instanceof WALProcedureStore);
91  
92      HMaster firstMaster = UTIL.getHBaseCluster().getMaster();
93      // Abort Latch for the master store
94      final CountDownLatch masterStoreAbort = new CountDownLatch(1);
95      masterStore.registerListener(new ProcedureStore.ProcedureStoreListener() {
96        @Override
97        public void abortProcess() {
98          LOG.debug("Abort store of Master");
99          masterStoreAbort.countDown();
100       }
101     });
102 
103     // startup a fake master the new WAL store will take the lease
104     // and the active master should abort.
105     HMaster backupMaster3 = Mockito.mock(HMaster.class);
106     Mockito.doReturn(firstMaster.getConfiguration()).when(backupMaster3).getConfiguration();
107     Mockito.doReturn(true).when(backupMaster3).isActiveMaster();
108     final WALProcedureStore backupStore3 = new WALProcedureStore(firstMaster.getConfiguration(),
109         firstMaster.getMasterFileSystem().getFileSystem(),
110         ((WALProcedureStore)masterStore).getLogDir(),
111         new MasterProcedureEnv.WALStoreLeaseRecovery(backupMaster3));
112     // Abort Latch for the test store
113     final CountDownLatch backupStore3Abort = new CountDownLatch(1);
114     backupStore3.registerListener(new ProcedureStore.ProcedureStoreListener() {
115       @Override
116       public void abortProcess() {
117         LOG.debug("Abort store of backupMaster3");
118         backupStore3Abort.countDown();
119         backupStore3.stop(true);
120       }
121     });
122     backupStore3.start(1);
123     backupStore3.recoverLease();
124 
125     // Try to trigger a command on the master (WAL lease expired on the active one)
126     HTableDescriptor htd = MasterProcedureTestingUtility.createHTD(TableName.valueOf("mtb"), "f");
127     HRegionInfo[] regions = ModifyRegionUtils.createHRegionInfos(htd, null);
128     LOG.debug("submit proc");
129     getMasterProcedureExecutor().submitProcedure(
130       new CreateTableProcedure(getMasterProcedureExecutor().getEnvironment(), htd, regions));
131     LOG.debug("wait master store abort");
132     masterStoreAbort.await();
133 
134     // Now the real backup master should start up
135     LOG.debug("wait backup master to startup");
136     waitBackupMaster(UTIL, firstMaster);
137     assertEquals(true, firstMaster.isStopped());
138 
139     // wait the store in here to abort (the test will fail due to timeout if it doesn't)
140     LOG.debug("wait the store to abort");
141     backupStore3.getStoreTracker().setDeleted(1, false);
142     backupStore3.delete(1);
143     backupStore3Abort.await();
144   }
145 
146   // ==========================================================================
147   //  Test Create Table
148   // ==========================================================================
149   @Test(timeout=60000)
150   public void testCreateWithFailover() throws Exception {
151     // TODO: Should we try every step? (master failover takes long time)
152     // It is already covered by TestCreateTableProcedure
153     // but without the master restart, only the executor/store is restarted.
154     // Without Master restart we may not find bug in the procedure code
155     // like missing "wait" for resources to be available (e.g. RS)
156     testCreateWithFailoverAtStep(CreateTableState.CREATE_TABLE_ASSIGN_REGIONS.ordinal());
157   }
158 
159   private void testCreateWithFailoverAtStep(final int step) throws Exception {
160     final TableName tableName = TableName.valueOf("testCreateWithFailoverAtStep" + step);
161 
162     // create the table
163     ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
164     ProcedureTestingUtility.setKillBeforeStoreUpdate(procExec, true);
165     ProcedureTestingUtility.setToggleKillBeforeStoreUpdate(procExec, true);
166 
167     // Start the Create procedure && kill the executor
168     byte[][] splitKeys = null;
169     HTableDescriptor htd = MasterProcedureTestingUtility.createHTD(tableName, "f1", "f2");
170     HRegionInfo[] regions = ModifyRegionUtils.createHRegionInfos(htd, splitKeys);
171     long procId = procExec.submitProcedure(
172       new CreateTableProcedure(procExec.getEnvironment(), htd, regions));
173     testRecoveryAndDoubleExecution(UTIL, procId, step, CreateTableState.values());
174 
175     MasterProcedureTestingUtility.validateTableCreation(
176       UTIL.getHBaseCluster().getMaster(), tableName, regions, "f1", "f2");
177   }
178 
179   // ==========================================================================
180   //  Test Delete Table
181   // ==========================================================================
182   @Test(timeout=60000)
183   public void testDeleteWithFailover() throws Exception {
184     // TODO: Should we try every step? (master failover takes long time)
185     // It is already covered by TestDeleteTableProcedure
186     // but without the master restart, only the executor/store is restarted.
187     // Without Master restart we may not find bug in the procedure code
188     // like missing "wait" for resources to be available (e.g. RS)
189     testDeleteWithFailoverAtStep(DeleteTableState.DELETE_TABLE_UNASSIGN_REGIONS.ordinal());
190   }
191 
192   private void testDeleteWithFailoverAtStep(final int step) throws Exception {
193     final TableName tableName = TableName.valueOf("testDeleteWithFailoverAtStep" + step);
194 
195     // create the table
196     byte[][] splitKeys = null;
197     HRegionInfo[] regions = MasterProcedureTestingUtility.createTable(
198       getMasterProcedureExecutor(), tableName, splitKeys, "f1", "f2");
199     Path tableDir = FSUtils.getTableDir(getRootDir(), tableName);
200     MasterProcedureTestingUtility.validateTableCreation(
201       UTIL.getHBaseCluster().getMaster(), tableName, regions, "f1", "f2");
202     UTIL.getHBaseAdmin().disableTable(tableName);
203 
204     ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
205     ProcedureTestingUtility.setKillBeforeStoreUpdate(procExec, true);
206     ProcedureTestingUtility.setToggleKillBeforeStoreUpdate(procExec, true);
207 
208     // Start the Delete procedure && kill the executor
209     long procId = procExec.submitProcedure(
210       new DeleteTableProcedure(procExec.getEnvironment(), tableName));
211     testRecoveryAndDoubleExecution(UTIL, procId, step, DeleteTableState.values());
212 
213     MasterProcedureTestingUtility.validateTableDeletion(
214       UTIL.getHBaseCluster().getMaster(), tableName, regions, "f1", "f2");
215   }
216 
217   // ==========================================================================
218   //  Test Truncate Table
219   // ==========================================================================
220   @Test(timeout=90000)
221   public void testTruncateWithFailover() throws Exception {
222     // TODO: Should we try every step? (master failover takes long time)
223     // It is already covered by TestTruncateTableProcedure
224     // but without the master restart, only the executor/store is restarted.
225     // Without Master restart we may not find bug in the procedure code
226     // like missing "wait" for resources to be available (e.g. RS)
227     testTruncateWithFailoverAtStep(true, TruncateTableState.TRUNCATE_TABLE_ADD_TO_META.ordinal());
228   }
229 
230   private void testTruncateWithFailoverAtStep(final boolean preserveSplits, final int step)
231       throws Exception {
232     final TableName tableName = TableName.valueOf("testTruncateWithFailoverAtStep" + step);
233 
234     // create the table
235     final String[] families = new String[] { "f1", "f2" };
236     final byte[][] splitKeys = new byte[][] {
237       Bytes.toBytes("a"), Bytes.toBytes("b"), Bytes.toBytes("c")
238     };
239     HRegionInfo[] regions = MasterProcedureTestingUtility.createTable(
240       getMasterProcedureExecutor(), tableName, splitKeys, families);
241     // load and verify that there are rows in the table
242     MasterProcedureTestingUtility.loadData(
243       UTIL.getConnection(), tableName, 100, splitKeys, families);
244     assertEquals(100, UTIL.countRows(tableName));
245     // disable the table
246     UTIL.getHBaseAdmin().disableTable(tableName);
247 
248     ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
249     ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExec, true);
250 
251     // Start the Truncate procedure && kill the executor
252     long procId = procExec.submitProcedure(
253       new TruncateTableProcedure(procExec.getEnvironment(), tableName, preserveSplits));
254     testRecoveryAndDoubleExecution(UTIL, procId, step, TruncateTableState.values());
255 
256     ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExec, false);
257     UTIL.waitUntilAllRegionsAssigned(tableName);
258 
259     // validate the table regions and layout
260     if (preserveSplits) {
261       assertEquals(1 + splitKeys.length, UTIL.getHBaseAdmin().getTableRegions(tableName).size());
262     } else {
263       regions = UTIL.getHBaseAdmin().getTableRegions(tableName).toArray(new HRegionInfo[1]);
264       assertEquals(1, regions.length);
265     }
266     MasterProcedureTestingUtility.validateTableCreation(
267       UTIL.getHBaseCluster().getMaster(), tableName, regions, families);
268 
269     // verify that there are no rows in the table
270     assertEquals(0, UTIL.countRows(tableName));
271 
272     // verify that the table is read/writable
273     MasterProcedureTestingUtility.loadData(
274       UTIL.getConnection(), tableName, 50, splitKeys, families);
275     assertEquals(50, UTIL.countRows(tableName));
276   }
277 
278   // ==========================================================================
279   //  Test Disable Table
280   // ==========================================================================
281   @Test(timeout=60000)
282   public void testDisableTableWithFailover() throws Exception {
283     // TODO: Should we try every step? (master failover takes long time)
284     // It is already covered by TestDisableTableProcedure
285     // but without the master restart, only the executor/store is restarted.
286     // Without Master restart we may not find bug in the procedure code
287     // like missing "wait" for resources to be available (e.g. RS)
288     testDisableTableWithFailoverAtStep(
289       DisableTableState.DISABLE_TABLE_MARK_REGIONS_OFFLINE.ordinal());
290   }
291 
292   private void testDisableTableWithFailoverAtStep(final int step) throws Exception {
293     final TableName tableName = TableName.valueOf("testDisableTableWithFailoverAtStep" + step);
294 
295     // create the table
296     final byte[][] splitKeys = new byte[][] {
297       Bytes.toBytes("a"), Bytes.toBytes("b"), Bytes.toBytes("c")
298     };
299     MasterProcedureTestingUtility.createTable(
300       getMasterProcedureExecutor(), tableName, splitKeys, "f1", "f2");
301 
302     ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
303     ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExec, true);
304 
305     // Start the Delete procedure && kill the executor
306     long procId = procExec.submitProcedure(
307       new DisableTableProcedure(procExec.getEnvironment(), tableName, false));
308     testRecoveryAndDoubleExecution(UTIL, procId, step, DisableTableState.values());
309 
310     MasterProcedureTestingUtility.validateTableIsDisabled(
311       UTIL.getHBaseCluster().getMaster(), tableName);
312   }
313 
314   // ==========================================================================
315   //  Test Enable Table
316   // ==========================================================================
317   @Test(timeout=60000)
318   public void testEnableTableWithFailover() throws Exception {
319     // TODO: Should we try every step? (master failover takes long time)
320     // It is already covered by TestEnableTableProcedure
321     // but without the master restart, only the executor/store is restarted.
322     // Without Master restart we may not find bug in the procedure code
323     // like missing "wait" for resources to be available (e.g. RS)
324     testEnableTableWithFailoverAtStep(
325       EnableTableState.ENABLE_TABLE_MARK_REGIONS_ONLINE.ordinal());
326   }
327 
328   private void testEnableTableWithFailoverAtStep(final int step) throws Exception {
329     final TableName tableName = TableName.valueOf("testEnableTableWithFailoverAtStep" + step);
330 
331     // create the table
332     final byte[][] splitKeys = new byte[][] {
333       Bytes.toBytes("a"), Bytes.toBytes("b"), Bytes.toBytes("c")
334     };
335     MasterProcedureTestingUtility.createTable(
336       getMasterProcedureExecutor(), tableName, splitKeys, "f1", "f2");
337     UTIL.getHBaseAdmin().disableTable(tableName);
338 
339     ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
340     ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExec, true);
341 
342     // Start the Delete procedure && kill the executor
343     long procId = procExec.submitProcedure(
344       new EnableTableProcedure(procExec.getEnvironment(), tableName, false));
345     testRecoveryAndDoubleExecution(UTIL, procId, step, EnableTableState.values());
346 
347     MasterProcedureTestingUtility.validateTableIsEnabled(
348       UTIL.getHBaseCluster().getMaster(), tableName);
349   }
350 
351   // ==========================================================================
352   //  Test Helpers
353   // ==========================================================================
354   public static <TState> void testRecoveryAndDoubleExecution(final HBaseTestingUtility testUtil,
355       final long procId, final int lastStepBeforeFailover, TState[] states) throws Exception {
356     ProcedureExecutor<MasterProcedureEnv> procExec =
357       testUtil.getHBaseCluster().getMaster().getMasterProcedureExecutor();
358     ProcedureTestingUtility.waitProcedure(procExec, procId);
359 
360     for (int i = 0; i < lastStepBeforeFailover; ++i) {
361       LOG.info("Restart "+ i +" exec state: " + states[i]);
362       ProcedureTestingUtility.assertProcNotYetCompleted(procExec, procId);
363       ProcedureTestingUtility.restart(procExec);
364       ProcedureTestingUtility.waitProcedure(procExec, procId);
365     }
366     ProcedureTestingUtility.assertProcNotYetCompleted(procExec, procId);
367 
368     LOG.info("Trigger master failover");
369     masterFailover(testUtil);
370 
371     procExec = testUtil.getHBaseCluster().getMaster().getMasterProcedureExecutor();
372     ProcedureTestingUtility.waitProcedure(procExec, procId);
373     ProcedureTestingUtility.assertProcNotFailed(procExec, procId);
374   }
375 
376   // ==========================================================================
377   //  Master failover utils
378   // ==========================================================================
379   public static void masterFailover(final HBaseTestingUtility testUtil)
380       throws Exception {
381     MiniHBaseCluster cluster = testUtil.getMiniHBaseCluster();
382 
383     // Kill the master
384     HMaster oldMaster = cluster.getMaster();
385     cluster.killMaster(cluster.getMaster().getServerName());
386 
387     // Wait the secondary
388     waitBackupMaster(testUtil, oldMaster);
389   }
390 
391   public static void waitBackupMaster(final HBaseTestingUtility testUtil,
392       final HMaster oldMaster) throws Exception {
393     MiniHBaseCluster cluster = testUtil.getMiniHBaseCluster();
394 
395     HMaster newMaster = cluster.getMaster();
396     while (newMaster == null || newMaster == oldMaster) {
397       Thread.sleep(250);
398       newMaster = cluster.getMaster();
399     }
400 
401     while (!(newMaster.isActiveMaster() && newMaster.isInitialized())) {
402       Thread.sleep(250);
403     }
404   }
405 
406   // ==========================================================================
407   //  Helpers
408   // ==========================================================================
409   private MasterProcedureEnv getMasterProcedureEnv() {
410     return getMasterProcedureExecutor().getEnvironment();
411   }
412 
413   private ProcedureExecutor<MasterProcedureEnv> getMasterProcedureExecutor() {
414     return UTIL.getHBaseCluster().getMaster().getMasterProcedureExecutor();
415   }
416 
417   private FileSystem getFileSystem() {
418     return UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getFileSystem();
419   }
420 
421   private Path getRootDir() {
422     return UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getRootDir();
423   }
424 
425   private Path getTempDir() {
426     return UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getTempDir();
427   }
428 }