View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.master;
20  
21  import static org.apache.hadoop.hbase.SplitLogCounters.tot_mgr_wait_for_zk_delete;
22  import static org.apache.hadoop.hbase.SplitLogCounters.tot_wkr_final_transition_failed;
23  import static org.apache.hadoop.hbase.SplitLogCounters.tot_wkr_preempt_task;
24  import static org.apache.hadoop.hbase.SplitLogCounters.tot_wkr_task_acquired;
25  import static org.apache.hadoop.hbase.SplitLogCounters.tot_wkr_task_done;
26  import static org.apache.hadoop.hbase.SplitLogCounters.tot_wkr_task_err;
27  import static org.apache.hadoop.hbase.SplitLogCounters.tot_wkr_task_resigned;
28  import static org.junit.Assert.assertEquals;
29  import static org.junit.Assert.assertFalse;
30  import static org.junit.Assert.assertTrue;
31  import static org.junit.Assert.fail;
32  
33  import java.io.IOException;
34  import java.util.ArrayList;
35  import java.util.Arrays;
36  import java.util.HashSet;
37  import java.util.Iterator;
38  import java.util.LinkedList;
39  import java.util.List;
40  import java.util.NavigableSet;
41  import java.util.Set;
42  import java.util.concurrent.ExecutorService;
43  import java.util.concurrent.Executors;
44  import java.util.concurrent.Future;
45  import java.util.concurrent.TimeUnit;
46  import java.util.concurrent.TimeoutException;
47  import java.util.concurrent.atomic.AtomicLong;
48  
49  import org.apache.commons.logging.Log;
50  import org.apache.commons.logging.LogFactory;
51  import org.apache.hadoop.conf.Configuration;
52  import org.apache.hadoop.fs.FSDataOutputStream;
53  import org.apache.hadoop.fs.FileStatus;
54  import org.apache.hadoop.fs.FileSystem;
55  import org.apache.hadoop.fs.Path;
56  import org.apache.hadoop.fs.PathFilter;
57  import org.apache.hadoop.hbase.HBaseConfiguration;
58  import org.apache.hadoop.hbase.HBaseTestingUtility;
59  import org.apache.hadoop.hbase.HColumnDescriptor;
60  import org.apache.hadoop.hbase.HConstants;
61  import org.apache.hadoop.hbase.HRegionInfo;
62  import org.apache.hadoop.hbase.HTableDescriptor;
63  import org.apache.hadoop.hbase.KeyValue;
64  import org.apache.hadoop.hbase.MiniHBaseCluster;
65  import org.apache.hadoop.hbase.NamespaceDescriptor;
66  import org.apache.hadoop.hbase.ServerName;
67  import org.apache.hadoop.hbase.SplitLogCounters;
68  import org.apache.hadoop.hbase.TableName;
69  import org.apache.hadoop.hbase.Waiter;
70  import org.apache.hadoop.hbase.client.ClusterConnection;
71  import org.apache.hadoop.hbase.client.ConnectionUtils;
72  import org.apache.hadoop.hbase.client.Delete;
73  import org.apache.hadoop.hbase.client.Get;
74  import org.apache.hadoop.hbase.client.HTable;
75  import org.apache.hadoop.hbase.client.Increment;
76  import org.apache.hadoop.hbase.client.NonceGenerator;
77  import org.apache.hadoop.hbase.client.PerClientRandomNonceGenerator;
78  import org.apache.hadoop.hbase.client.Put;
79  import org.apache.hadoop.hbase.client.RegionLocator;
80  import org.apache.hadoop.hbase.client.Result;
81  import org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException;
82  import org.apache.hadoop.hbase.client.Table;
83  import org.apache.hadoop.hbase.coordination.BaseCoordinatedStateManager;
84  import org.apache.hadoop.hbase.coordination.ZKSplitLogManagerCoordination;
85  import org.apache.hadoop.hbase.exceptions.OperationConflictException;
86  import org.apache.hadoop.hbase.exceptions.RegionInRecoveryException;
87  import org.apache.hadoop.hbase.master.SplitLogManager.TaskBatch;
88  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
89  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse.CompactionState;
90  import org.apache.hadoop.hbase.regionserver.HRegion;
91  import org.apache.hadoop.hbase.regionserver.HRegionServer;
92  import org.apache.hadoop.hbase.regionserver.Region;
93  import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
94  import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
95  import org.apache.hadoop.hbase.testclassification.LargeTests;
96  import org.apache.hadoop.hbase.util.Bytes;
97  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
98  import org.apache.hadoop.hbase.util.FSUtils;
99  import org.apache.hadoop.hbase.util.JVMClusterUtil.MasterThread;
100 import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread;
101 import org.apache.hadoop.hbase.util.Threads;
102 import org.apache.hadoop.hbase.wal.DefaultWALProvider;
103 import org.apache.hadoop.hbase.wal.WAL;
104 import org.apache.hadoop.hbase.wal.WALFactory;
105 import org.apache.hadoop.hbase.wal.WALSplitter;
106 import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
107 import org.apache.hadoop.hbase.zookeeper.ZKAssign;
108 import org.apache.hadoop.hbase.zookeeper.ZKUtil;
109 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
110 import org.apache.hadoop.hdfs.MiniDFSCluster;
111 import org.apache.zookeeper.KeeperException;
112 import org.junit.After;
113 import org.junit.AfterClass;
114 import org.junit.Assert;
115 import org.junit.Before;
116 import org.junit.BeforeClass;
117 import org.junit.Test;
118 import org.junit.experimental.categories.Category;
119 
120 @Category(LargeTests.class)
121 @SuppressWarnings("deprecation")
122 public class TestDistributedLogSplitting {
123   private static final Log LOG = LogFactory.getLog(TestSplitLogManager.class);
124   static {
125     // Uncomment the following line if more verbosity is needed for
126     // debugging (see HBASE-12285 for details).
127     //Logger.getLogger("org.apache.hadoop.hbase").setLevel(Level.DEBUG);
128 
129     // test ThreeRSAbort fails under hadoop2 (2.0.2-alpha) if shortcircuit-read (scr) is on. this
130     // turns it off for this test.  TODO: Figure out why scr breaks recovery.
131     System.setProperty("hbase.tests.use.shortcircuit.reads", "false");
132 
133   }
134 
135   // Start a cluster with 2 masters and 6 regionservers
136   static final int NUM_MASTERS = 2;
137   static final int NUM_RS = 6;
138 
139   MiniHBaseCluster cluster;
140   HMaster master;
141   Configuration conf;
142   static Configuration originalConf;
143   static HBaseTestingUtility TEST_UTIL;
144   static MiniDFSCluster dfsCluster;
145   static MiniZooKeeperCluster zkCluster;
146 
147   @BeforeClass
148   public static void setup() throws Exception {
149     TEST_UTIL = new HBaseTestingUtility(HBaseConfiguration.create());
150     dfsCluster = TEST_UTIL.startMiniDFSCluster(1);
151     zkCluster = TEST_UTIL.startMiniZKCluster();
152     originalConf = TEST_UTIL.getConfiguration();
153   }
154 
155   @AfterClass
156   public static void tearDown() throws IOException {
157     TEST_UTIL.shutdownMiniZKCluster();
158     TEST_UTIL.shutdownMiniDFSCluster();
159     TEST_UTIL.shutdownMiniHBaseCluster();
160   }
161 
162   private void startCluster(int num_rs) throws Exception {
163     SplitLogCounters.resetCounters();
164     LOG.info("Starting cluster");
165     conf.getLong("hbase.splitlog.max.resubmit", 0);
166     // Make the failure test faster
167     conf.setInt("zookeeper.recovery.retry", 0);
168     conf.setInt(HConstants.REGIONSERVER_INFO_PORT, -1);
169     conf.setFloat(HConstants.LOAD_BALANCER_SLOP_KEY, (float) 100.0); // no load balancing
170     conf.setInt("hbase.regionserver.wal.max.splitters", 3);
171     conf.setInt("hbase.master.maximum.ping.server.attempts", 3);
172     conf.setInt(HConstants.REGION_SERVER_HIGH_PRIORITY_HANDLER_COUNT, 40);
173     TEST_UTIL.shutdownMiniHBaseCluster();
174     TEST_UTIL = new HBaseTestingUtility(conf);
175     TEST_UTIL.setDFSCluster(dfsCluster);
176     TEST_UTIL.setZkCluster(zkCluster);
177     TEST_UTIL.startMiniHBaseCluster(NUM_MASTERS, num_rs);
178     cluster = TEST_UTIL.getHBaseCluster();
179     LOG.info("Waiting for active/ready master");
180     cluster.waitForActiveAndReadyMaster();
181     master = cluster.getMaster();
182     while (cluster.getLiveRegionServerThreads().size() < num_rs) {
183       Threads.sleep(1);
184     }
185   }
186 
187   @Before
188   public void before() throws Exception {
189     // refresh configuration
190     conf = HBaseConfiguration.create(originalConf);
191   }
192 
193   @After
194   public void after() throws Exception {
195     try {
196       if (TEST_UTIL.getHBaseCluster() != null) {
197         for (MasterThread mt : TEST_UTIL.getHBaseCluster().getLiveMasterThreads()) {
198           mt.getMaster().abort("closing...", null);
199         }
200       }
201       TEST_UTIL.shutdownMiniHBaseCluster();
202     } finally {
203       TEST_UTIL.getTestFileSystem().delete(FSUtils.getRootDir(TEST_UTIL.getConfiguration()), true);
204       ZKUtil.deleteNodeRecursively(TEST_UTIL.getZooKeeperWatcher(), "/hbase");
205     }
206   }
207 
208   @Test (timeout=300000)
209   public void testRecoveredEdits() throws Exception {
210     LOG.info("testRecoveredEdits");
211     conf.setLong("hbase.regionserver.hlog.blocksize", 30 * 1024); // create more than one wal
212     conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, false);
213     startCluster(NUM_RS);
214 
215     final int NUM_LOG_LINES = 1000;
216     final SplitLogManager slm = master.getMasterFileSystem().splitLogManager;
217     // turn off load balancing to prevent regions from moving around otherwise
218     // they will consume recovered.edits
219     master.balanceSwitch(false);
220     FileSystem fs = master.getMasterFileSystem().getFileSystem();
221 
222     List<RegionServerThread> rsts = cluster.getLiveRegionServerThreads();
223 
224     Path rootdir = FSUtils.getRootDir(conf);
225 
226     installTable(new ZooKeeperWatcher(conf, "table-creation", null),
227         "table", "family", 40);
228     TableName table = TableName.valueOf("table");
229     List<HRegionInfo> regions = null;
230     HRegionServer hrs = null;
231     for (int i = 0; i < NUM_RS; i++) {
232       boolean foundRs = false;
233       hrs = rsts.get(i).getRegionServer();
234       regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
235       for (HRegionInfo region : regions) {
236         if (region.getTable().getNameAsString().equalsIgnoreCase("table")) {
237           foundRs = true;
238           break;
239         }
240       }
241       if (foundRs) break;
242     }
243     final Path logDir = new Path(rootdir, DefaultWALProvider.getWALDirectoryName(hrs
244         .getServerName().toString()));
245 
246     LOG.info("#regions = " + regions.size());
247     Iterator<HRegionInfo> it = regions.iterator();
248     while (it.hasNext()) {
249       HRegionInfo region = it.next();
250       if (region.getTable().getNamespaceAsString()
251           .equals(NamespaceDescriptor.SYSTEM_NAMESPACE_NAME_STR)) {
252         it.remove();
253       }
254     }
255     
256     makeWAL(hrs, regions, "table", "family", NUM_LOG_LINES, 100);
257 
258     slm.splitLogDistributed(logDir);
259 
260     int count = 0;
261     for (HRegionInfo hri : regions) {
262 
263       Path tdir = FSUtils.getTableDir(rootdir, table);
264       Path editsdir =
265         WALSplitter.getRegionDirRecoveredEditsDir(HRegion.getRegionDir(tdir, hri.getEncodedName()));
266       LOG.debug("checking edits dir " + editsdir);
267       FileStatus[] files = fs.listStatus(editsdir, new PathFilter() {
268         @Override
269         public boolean accept(Path p) {
270           if (WALSplitter.isSequenceIdFile(p)) {
271             return false;
272           }
273           return true;
274         }
275       });
276       assertTrue("edits dir should have more than a single file in it. instead has " + files.length,
277           files.length > 1);
278       for (int i = 0; i < files.length; i++) {
279         int c = countWAL(files[i].getPath(), fs, conf);
280         count += c;
281       }
282       LOG.info(count + " edits in " + files.length + " recovered edits files.");
283     }
284 
285     // check that the log file is moved
286     assertFalse(fs.exists(logDir));
287 
288     assertEquals(NUM_LOG_LINES, count);
289   }
290 
291   @Test(timeout = 300000)
292   public void testLogReplayWithNonMetaRSDown() throws Exception {
293     LOG.info("testLogReplayWithNonMetaRSDown");
294     conf.setLong("hbase.regionserver.hlog.blocksize", 30 * 1024); // create more than one wal
295     conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, true);
296     startCluster(NUM_RS);
297     final int NUM_REGIONS_TO_CREATE = 40;
298     final int NUM_LOG_LINES = 1000;
299     // turn off load balancing to prevent regions from moving around otherwise
300     // they will consume recovered.edits
301     master.balanceSwitch(false);
302 
303     final ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "table-creation", null);
304     Table ht = installTable(zkw, "table", "family", NUM_REGIONS_TO_CREATE);
305 
306     HRegionServer hrs = findRSToKill(false, "table");
307     List<HRegionInfo> regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
308     makeWAL(hrs, regions, "table", "family", NUM_LOG_LINES, 100);
309 
310     // wait for abort completes
311     this.abortRSAndVerifyRecovery(hrs, ht, zkw, NUM_REGIONS_TO_CREATE, NUM_LOG_LINES);
312     ht.close();
313     zkw.close();
314   }
315 
316   private static class NonceGeneratorWithDups extends PerClientRandomNonceGenerator {
317     private boolean isDups = false;
318     private LinkedList<Long> nonces = new LinkedList<Long>();
319 
320     public void startDups() {
321       isDups = true;
322     }
323 
324     @Override
325     public long newNonce() {
326       long nonce = isDups ? nonces.removeFirst() : super.newNonce();
327       if (!isDups) {
328         nonces.add(nonce);
329       }
330       return nonce;
331     }
332   }
333 
334   @Test(timeout = 300000)
335   public void testNonceRecovery() throws Exception {
336     LOG.info("testNonceRecovery");
337     final String TABLE_NAME = "table";
338     final String FAMILY_NAME = "family";
339     final int NUM_REGIONS_TO_CREATE = 40;
340 
341     conf.setLong("hbase.regionserver.hlog.blocksize", 100*1024);
342     conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, true);
343     startCluster(NUM_RS);
344     master.balanceSwitch(false);
345 
346     final ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "table-creation", null);
347     HTable ht = installTable(zkw, TABLE_NAME, FAMILY_NAME, NUM_REGIONS_TO_CREATE);
348     NonceGeneratorWithDups ng = new NonceGeneratorWithDups();
349     NonceGenerator oldNg =
350         ConnectionUtils.injectNonceGeneratorForTesting((ClusterConnection)ht.getConnection(), ng);
351 
352     try {
353       List<Increment> reqs = new ArrayList<Increment>();
354       for (RegionServerThread rst : cluster.getLiveRegionServerThreads()) {
355         HRegionServer hrs = rst.getRegionServer();
356         List<HRegionInfo> hris = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
357         for (HRegionInfo hri : hris) {
358           if (TABLE_NAME.equalsIgnoreCase(hri.getTable().getNameAsString())) {
359             byte[] key = hri.getStartKey();
360             if (key == null || key.length == 0) {
361               key = Bytes.copy(hri.getEndKey());
362               --(key[key.length - 1]);
363             }
364             Increment incr = new Increment(key);
365             incr.addColumn(Bytes.toBytes(FAMILY_NAME), Bytes.toBytes("q"), 1);
366             ht.increment(incr);
367             reqs.add(incr);
368           }
369         }
370       }
371 
372       HRegionServer hrs = findRSToKill(false, "table");
373       abortRSAndWaitForRecovery(hrs, zkw, NUM_REGIONS_TO_CREATE);
374       ng.startDups();
375       for (Increment incr : reqs) {
376         try {
377           ht.increment(incr);
378           fail("should have thrown");
379         } catch (OperationConflictException ope) {
380           LOG.debug("Caught as expected: " + ope.getMessage());
381         }
382       }
383     } finally {
384       ConnectionUtils.injectNonceGeneratorForTesting((ClusterConnection) ht.getConnection(), oldNg);
385       ht.close();
386       zkw.close();
387     }
388   }
389 
390   @Test(timeout = 300000)
391   public void testLogReplayWithMetaRSDown() throws Exception {
392     LOG.info("testRecoveredEditsReplayWithMetaRSDown");
393     conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, true);
394     startCluster(NUM_RS);
395     final int NUM_REGIONS_TO_CREATE = 40;
396     final int NUM_LOG_LINES = 1000;
397     // turn off load balancing to prevent regions from moving around otherwise
398     // they will consume recovered.edits
399     master.balanceSwitch(false);
400 
401     final ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "table-creation", null);
402     Table ht = installTable(zkw, "table", "family", NUM_REGIONS_TO_CREATE);
403 
404     HRegionServer hrs = findRSToKill(true, "table");
405     List<HRegionInfo> regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
406     makeWAL(hrs, regions, "table", "family", NUM_LOG_LINES, 100);
407 
408     this.abortRSAndVerifyRecovery(hrs, ht, zkw, NUM_REGIONS_TO_CREATE, NUM_LOG_LINES);
409     ht.close();
410     zkw.close();
411   }
412 
413   private void abortRSAndVerifyRecovery(HRegionServer hrs, Table ht, final ZooKeeperWatcher zkw,
414       final int numRegions, final int numofLines) throws Exception {
415 
416     abortRSAndWaitForRecovery(hrs, zkw, numRegions);
417     assertEquals(numofLines, TEST_UTIL.countRows(ht));
418   }
419 
420   private void abortRSAndWaitForRecovery(HRegionServer hrs, final ZooKeeperWatcher zkw,
421       final int numRegions) throws Exception {
422     final MiniHBaseCluster tmpCluster = this.cluster;
423 
424     // abort RS
425     LOG.info("Aborting region server: " + hrs.getServerName());
426     hrs.abort("testing");
427 
428     // wait for abort completes
429     TEST_UTIL.waitFor(120000, 200, new Waiter.Predicate<Exception>() {
430       @Override
431       public boolean evaluate() throws Exception {
432         return (tmpCluster.getLiveRegionServerThreads().size() <= (NUM_RS - 1));
433       }
434     });
435 
436     // wait for regions come online
437     TEST_UTIL.waitFor(180000, 200, new Waiter.Predicate<Exception>() {
438       @Override
439       public boolean evaluate() throws Exception {
440         return (HBaseTestingUtility.getAllOnlineRegions(tmpCluster).size()
441             >= (numRegions + 1));
442       }
443     });
444 
445     // wait for all regions are fully recovered
446     TEST_UTIL.waitFor(180000, 200, new Waiter.Predicate<Exception>() {
447       @Override
448       public boolean evaluate() throws Exception {
449         List<String> recoveringRegions = zkw.getRecoverableZooKeeper().getChildren(
450           zkw.recoveringRegionsZNode, false);
451         return (recoveringRegions != null && recoveringRegions.size() == 0);
452       }
453     });
454   }
455 
456   @Test(timeout = 300000)
457   public void testMasterStartsUpWithLogSplittingWork() throws Exception {
458     LOG.info("testMasterStartsUpWithLogSplittingWork");
459     conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, false);
460     conf.setInt(ServerManager.WAIT_ON_REGIONSERVERS_MINTOSTART, NUM_RS - 1);
461     startCluster(NUM_RS);
462 
463     final int NUM_REGIONS_TO_CREATE = 40;
464     final int NUM_LOG_LINES = 1000;
465     // turn off load balancing to prevent regions from moving around otherwise
466     // they will consume recovered.edits
467     master.balanceSwitch(false);
468 
469     final ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "table-creation", null);
470     Table ht = installTable(zkw, "table", "family", NUM_REGIONS_TO_CREATE);
471 
472     HRegionServer hrs = findRSToKill(false, "table");
473     List<HRegionInfo> regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
474     makeWAL(hrs, regions, "table", "family", NUM_LOG_LINES, 100);
475 
476     // abort master
477     abortMaster(cluster);
478 
479     // abort RS
480     LOG.info("Aborting region server: " + hrs.getServerName());
481     hrs.abort("testing");
482 
483     // wait for abort completes
484     TEST_UTIL.waitFor(120000, 200, new Waiter.Predicate<Exception>() {
485       @Override
486       public boolean evaluate() throws Exception {
487         return (cluster.getLiveRegionServerThreads().size() <= (NUM_RS - 1));
488       }
489     });
490 
491     Thread.sleep(2000);
492     LOG.info("Current Open Regions:"
493         + HBaseTestingUtility.getAllOnlineRegions(cluster).size());
494 
495     // wait for abort completes
496     TEST_UTIL.waitFor(120000, 200, new Waiter.Predicate<Exception>() {
497       @Override
498       public boolean evaluate() throws Exception {
499         return (HBaseTestingUtility.getAllOnlineRegions(cluster).size()
500           >= (NUM_REGIONS_TO_CREATE + 1));
501       }
502     });
503 
504     LOG.info("Current Open Regions After Master Node Starts Up:"
505         + HBaseTestingUtility.getAllOnlineRegions(cluster).size());
506 
507     assertEquals(NUM_LOG_LINES, TEST_UTIL.countRows(ht));
508 
509     ht.close();
510     zkw.close();
511   }
512 
513   @Test(timeout = 300000)
514   public void testMasterStartsUpWithLogReplayWork() throws Exception {
515     LOG.info("testMasterStartsUpWithLogReplayWork");
516     conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, true);
517     conf.setInt(ServerManager.WAIT_ON_REGIONSERVERS_MINTOSTART, NUM_RS - 1);
518     startCluster(NUM_RS);
519 
520     final int NUM_REGIONS_TO_CREATE = 40;
521     final int NUM_LOG_LINES = 1000;
522     // turn off load balancing to prevent regions from moving around otherwise
523     // they will consume recovered.edits
524     master.balanceSwitch(false);
525 
526     final ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "table-creation", null);
527     Table ht = installTable(zkw, "table", "family", NUM_REGIONS_TO_CREATE);
528 
529     HRegionServer hrs = findRSToKill(false, "table");
530     List<HRegionInfo> regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
531     makeWAL(hrs, regions, "table", "family", NUM_LOG_LINES, 100);
532 
533     // abort master
534     abortMaster(cluster);
535 
536     // abort RS
537     LOG.info("Aborting region server: " + hrs.getServerName());
538     hrs.abort("testing");
539 
540     // wait for the RS dies
541     TEST_UTIL.waitFor(120000, 200, new Waiter.Predicate<Exception>() {
542       @Override
543       public boolean evaluate() throws Exception {
544         return (cluster.getLiveRegionServerThreads().size() <= (NUM_RS - 1));
545       }
546     });
547 
548     Thread.sleep(2000);
549     LOG.info("Current Open Regions:" + HBaseTestingUtility.getAllOnlineRegions(cluster).size());
550 
551     // wait for all regions are fully recovered
552     TEST_UTIL.waitFor(180000, 200, new Waiter.Predicate<Exception>() {
553       @Override
554       public boolean evaluate() throws Exception {
555         List<String> recoveringRegions = zkw.getRecoverableZooKeeper().getChildren(
556           zkw.recoveringRegionsZNode, false);
557         boolean done = recoveringRegions != null && recoveringRegions.size() == 0;
558         if (!done) {
559           LOG.info("Recovering regions: " + recoveringRegions);
560         }
561         return done;
562       }
563     });
564 
565     LOG.info("Current Open Regions After Master Node Starts Up:"
566         + HBaseTestingUtility.getAllOnlineRegions(cluster).size());
567 
568     assertEquals(NUM_LOG_LINES, TEST_UTIL.countRows(ht));
569 
570     ht.close();
571     zkw.close();
572   }
573 
574 
575   @Test(timeout = 300000)
576   public void testLogReplayTwoSequentialRSDown() throws Exception {
577     LOG.info("testRecoveredEditsReplayTwoSequentialRSDown");
578     conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, true);
579     startCluster(NUM_RS);
580     final int NUM_REGIONS_TO_CREATE = 40;
581     final int NUM_LOG_LINES = 1000;
582     // turn off load balancing to prevent regions from moving around otherwise
583     // they will consume recovered.edits
584     master.balanceSwitch(false);
585 
586     List<RegionServerThread> rsts = cluster.getLiveRegionServerThreads();
587     final ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "table-creation", null);
588     Table ht = installTable(zkw, "table", "family", NUM_REGIONS_TO_CREATE);
589 
590     List<HRegionInfo> regions = null;
591     HRegionServer hrs1 = findRSToKill(false, "table");
592     regions = ProtobufUtil.getOnlineRegions(hrs1.getRSRpcServices());
593 
594     makeWAL(hrs1, regions, "table", "family", NUM_LOG_LINES, 100);
595 
596     // abort RS1
597     LOG.info("Aborting region server: " + hrs1.getServerName());
598     hrs1.abort("testing");
599 
600     // wait for abort completes
601     TEST_UTIL.waitFor(120000, 200, new Waiter.Predicate<Exception>() {
602       @Override
603       public boolean evaluate() throws Exception {
604         return (cluster.getLiveRegionServerThreads().size() <= (NUM_RS - 1));
605       }
606     });
607 
608     // wait for regions come online
609     TEST_UTIL.waitFor(180000, 200, new Waiter.Predicate<Exception>() {
610       @Override
611       public boolean evaluate() throws Exception {
612         return (HBaseTestingUtility.getAllOnlineRegions(cluster).size()
613             >= (NUM_REGIONS_TO_CREATE + 1));
614       }
615     });
616 
617     // sleep a little bit in order to interrupt recovering in the middle
618     Thread.sleep(300);
619     // abort second region server
620     rsts = cluster.getLiveRegionServerThreads();
621     HRegionServer hrs2 = rsts.get(0).getRegionServer();
622     LOG.info("Aborting one more region server: " + hrs2.getServerName());
623     hrs2.abort("testing");
624 
625     // wait for abort completes
626     TEST_UTIL.waitFor(120000, 200, new Waiter.Predicate<Exception>() {
627       @Override
628       public boolean evaluate() throws Exception {
629         return (cluster.getLiveRegionServerThreads().size() <= (NUM_RS - 2));
630       }
631     });
632 
633     // wait for regions come online
634     TEST_UTIL.waitFor(180000, 200, new Waiter.Predicate<Exception>() {
635       @Override
636       public boolean evaluate() throws Exception {
637         return (HBaseTestingUtility.getAllOnlineRegions(cluster).size()
638             >= (NUM_REGIONS_TO_CREATE + 1));
639       }
640     });
641 
642     // wait for all regions are fully recovered
643     TEST_UTIL.waitFor(180000, 200, new Waiter.Predicate<Exception>() {
644       @Override
645       public boolean evaluate() throws Exception {
646         List<String> recoveringRegions = zkw.getRecoverableZooKeeper().getChildren(
647           zkw.recoveringRegionsZNode, false);
648         return (recoveringRegions != null && recoveringRegions.size() == 0);
649       }
650     });
651 
652     assertEquals(NUM_LOG_LINES, TEST_UTIL.countRows(ht));
653     ht.close();
654     zkw.close();
655   }
656 
657   @Test(timeout = 300000)
658   public void testMarkRegionsRecoveringInZK() throws Exception {
659     LOG.info("testMarkRegionsRecoveringInZK");
660     conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, true);
661     startCluster(NUM_RS);
662     master.balanceSwitch(false);
663     List<RegionServerThread> rsts = cluster.getLiveRegionServerThreads();
664     final ZooKeeperWatcher zkw = master.getZooKeeper();
665     Table ht = installTable(zkw, "table", "family", 40);
666     final SplitLogManager slm = master.getMasterFileSystem().splitLogManager;
667 
668     Set<HRegionInfo> regionSet = new HashSet<HRegionInfo>();
669     HRegionInfo region = null;
670     HRegionServer hrs = null;
671     ServerName firstFailedServer = null;
672     ServerName secondFailedServer = null;
673     for (int i = 0; i < NUM_RS; i++) {
674       hrs = rsts.get(i).getRegionServer();
675       List<HRegionInfo> regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
676       if (regions.isEmpty()) continue;
677       region = regions.get(0);
678       regionSet.add(region);
679       firstFailedServer = hrs.getServerName();
680       secondFailedServer = rsts.get((i + 1) % NUM_RS).getRegionServer().getServerName();
681       break;
682     }
683 
684     slm.markRegionsRecovering(firstFailedServer, regionSet);
685     slm.markRegionsRecovering(secondFailedServer, regionSet);
686 
687     List<String> recoveringRegions = ZKUtil.listChildrenNoWatch(zkw,
688       ZKUtil.joinZNode(zkw.recoveringRegionsZNode, region.getEncodedName()));
689 
690     assertEquals(recoveringRegions.size(), 2);
691 
692     // wait for splitLogWorker to mark them up because there is no WAL files recorded in ZK
693     final HRegionServer tmphrs = hrs;
694     TEST_UTIL.waitFor(60000, 1000, new Waiter.Predicate<Exception>() {
695       @Override
696       public boolean evaluate() throws Exception {
697         return (tmphrs.getRecoveringRegions().size() == 0);
698       }
699     });
700     ht.close();
701   }
702 
703   @Test(timeout = 300000)
704   public void testReplayCmd() throws Exception {
705     LOG.info("testReplayCmd");
706     conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, true);
707     startCluster(NUM_RS);
708     final int NUM_REGIONS_TO_CREATE = 40;
709     // turn off load balancing to prevent regions from moving around otherwise
710     // they will consume recovered.edits
711     master.balanceSwitch(false);
712 
713     List<RegionServerThread> rsts = cluster.getLiveRegionServerThreads();
714     final ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "table-creation", null);
715     HTable ht = installTable(zkw, "table", "family", NUM_REGIONS_TO_CREATE);
716 
717     List<HRegionInfo> regions = null;
718     HRegionServer hrs = null;
719     for (int i = 0; i < NUM_RS; i++) {
720       boolean isCarryingMeta = false;
721       hrs = rsts.get(i).getRegionServer();
722       regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
723       for (HRegionInfo region : regions) {
724         if (region.isMetaRegion()) {
725           isCarryingMeta = true;
726           break;
727         }
728       }
729       if (isCarryingMeta) {
730         continue;
731       }
732       if (regions.size() > 0) break;
733     }
734 
735     this.prepareData(ht, Bytes.toBytes("family"), Bytes.toBytes("c1"));
736     String originalCheckSum = TEST_UTIL.checksumRows(ht);
737 
738     // abort RA and trigger replay
739     abortRSAndWaitForRecovery(hrs, zkw, NUM_REGIONS_TO_CREATE);
740 
741     assertEquals("Data should remain after reopening of regions", originalCheckSum,
742       TEST_UTIL.checksumRows(ht));
743 
744     ht.close();
745     zkw.close();
746   }
747 
748   @Test(timeout = 300000)
749   public void testLogReplayForDisablingTable() throws Exception {
750     LOG.info("testLogReplayForDisablingTable");
751     conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, true);
752     startCluster(NUM_RS);
753     final int NUM_REGIONS_TO_CREATE = 40;
754     final int NUM_LOG_LINES = 1000;
755 
756     List<RegionServerThread> rsts = cluster.getLiveRegionServerThreads();
757     final ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "table-creation", null);
758     Table disablingHT = installTable(zkw, "disableTable", "family", NUM_REGIONS_TO_CREATE);
759     Table ht = installTable(zkw, "table", "family", NUM_REGIONS_TO_CREATE, NUM_REGIONS_TO_CREATE);
760 
761     // turn off load balancing to prevent regions from moving around otherwise
762     // they will consume recovered.edits
763     master.balanceSwitch(false);
764 
765     List<HRegionInfo> regions = null;
766     HRegionServer hrs = null;
767     boolean hasRegionsForBothTables = false;
768     String tableName = null;
769     for (int i = 0; i < NUM_RS; i++) {
770       tableName = null;
771       hasRegionsForBothTables = false;
772       boolean isCarryingSystem = false;
773       hrs = rsts.get(i).getRegionServer();
774       regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
775       for (HRegionInfo region : regions) {
776         if (region.getTable().isSystemTable()) {
777           isCarryingSystem = true;
778           break;
779         }
780         if (tableName != null &&
781             !tableName.equalsIgnoreCase(region.getTable().getNameAsString())) {
782           // make sure that we find a RS has online regions for both "table" and "disableTable"
783           hasRegionsForBothTables = true;
784           break;
785         } else if (tableName == null) {
786           tableName = region.getTable().getNameAsString();
787         }
788       }
789       if (isCarryingSystem) {
790         continue;
791       }
792       if (hasRegionsForBothTables) {
793         break;
794       }
795     }
796 
797     // make sure we found a good RS
798     Assert.assertTrue(hasRegionsForBothTables);
799 
800     LOG.info("#regions = " + regions.size());
801     Iterator<HRegionInfo> it = regions.iterator();
802     while (it.hasNext()) {
803       HRegionInfo region = it.next();
804       if (region.isMetaTable()) {
805         it.remove();
806       }
807     }
808     makeWAL(hrs, regions, "disableTable", "family", NUM_LOG_LINES, 100, false);
809     makeWAL(hrs, regions, "table", "family", NUM_LOG_LINES, 100);
810 
811     LOG.info("Disabling table\n");
812     TEST_UTIL.getHBaseAdmin().disableTable(TableName.valueOf("disableTable"));
813 
814     // abort RS
815     LOG.info("Aborting region server: " + hrs.getServerName());
816     hrs.abort("testing");
817 
818     // wait for abort completes
819     TEST_UTIL.waitFor(120000, 200, new Waiter.Predicate<Exception>() {
820       @Override
821       public boolean evaluate() throws Exception {
822         return (cluster.getLiveRegionServerThreads().size() <= (NUM_RS - 1));
823       }
824     });
825 
826     // wait for regions come online
827     TEST_UTIL.waitFor(180000, 200, new Waiter.Predicate<Exception>() {
828       @Override
829       public boolean evaluate() throws Exception {
830         return (HBaseTestingUtility.getAllOnlineRegions(cluster).size()
831             >= (NUM_REGIONS_TO_CREATE + 1));
832       }
833     });
834 
835     // wait for all regions are fully recovered
836     TEST_UTIL.waitFor(180000, 200, new Waiter.Predicate<Exception>() {
837       @Override
838       public boolean evaluate() throws Exception {
839         List<String> recoveringRegions = zkw.getRecoverableZooKeeper().getChildren(
840           zkw.recoveringRegionsZNode, false);
841         ServerManager serverManager = master.getServerManager();
842         return (!serverManager.areDeadServersInProgress() &&
843             recoveringRegions != null && recoveringRegions.size() == 0);
844       }
845     });
846 
847     int count = 0;
848     FileSystem fs = master.getMasterFileSystem().getFileSystem();
849     Path rootdir = FSUtils.getRootDir(conf);
850     Path tdir = FSUtils.getTableDir(rootdir, TableName.valueOf("disableTable"));
851     for (HRegionInfo hri : regions) {
852       Path editsdir =
853         WALSplitter.getRegionDirRecoveredEditsDir(HRegion.getRegionDir(tdir, hri.getEncodedName()));
854       LOG.debug("checking edits dir " + editsdir);
855       if(!fs.exists(editsdir)) continue;
856       FileStatus[] files = fs.listStatus(editsdir, new PathFilter() {
857         @Override
858         public boolean accept(Path p) {
859           if (WALSplitter.isSequenceIdFile(p)) {
860             return false;
861           }
862           return true;
863         }
864       });
865       if(files != null) {
866         for(FileStatus file : files) {
867           int c = countWAL(file.getPath(), fs, conf);
868           count += c;
869           LOG.info(c + " edits in " + file.getPath());
870         }
871       }
872     }
873 
874     LOG.info("Verify edits in recovered.edits files");
875     assertEquals(NUM_LOG_LINES, count);
876     LOG.info("Verify replayed edits");
877     assertEquals(NUM_LOG_LINES, TEST_UTIL.countRows(ht));
878 
879     // clean up
880     for (HRegionInfo hri : regions) {
881       Path editsdir =
882         WALSplitter.getRegionDirRecoveredEditsDir(HRegion.getRegionDir(tdir, hri.getEncodedName()));
883       fs.delete(editsdir, true);
884     }
885     disablingHT.close();
886     ht.close();
887     zkw.close();
888   }
889 
890   @Test(timeout = 300000)
891   public void testDisallowWritesInRecovering() throws Exception {
892     LOG.info("testDisallowWritesInRecovering");
893     conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, true);
894     conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 3);
895     conf.setBoolean(HConstants.DISALLOW_WRITES_IN_RECOVERING, true);
896     startCluster(NUM_RS);
897     final int NUM_REGIONS_TO_CREATE = 40;
898     // turn off load balancing to prevent regions from moving around otherwise
899     // they will consume recovered.edits
900     master.balanceSwitch(false);
901 
902     List<RegionServerThread> rsts = cluster.getLiveRegionServerThreads();
903     final ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "table-creation", null);
904     Table ht = installTable(zkw, "table", "family", NUM_REGIONS_TO_CREATE);
905     final SplitLogManager slm = master.getMasterFileSystem().splitLogManager;
906 
907     Set<HRegionInfo> regionSet = new HashSet<HRegionInfo>();
908     HRegionInfo region = null;
909     HRegionServer hrs = null;
910     HRegionServer dstRS = null;
911     for (int i = 0; i < NUM_RS; i++) {
912       hrs = rsts.get(i).getRegionServer();
913       List<HRegionInfo> regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
914       if (regions.isEmpty()) continue;
915       region = regions.get(0);
916       if (region.isMetaRegion()) continue;
917       regionSet.add(region);
918       dstRS = rsts.get((i+1) % NUM_RS).getRegionServer();
919       break;
920     }
921 
922     slm.markRegionsRecovering(hrs.getServerName(), regionSet);
923     // move region in order for the region opened in recovering state
924     final HRegionInfo hri = region;
925     final HRegionServer tmpRS = dstRS;
926     TEST_UTIL.getHBaseAdmin().move(region.getEncodedNameAsBytes(),
927       Bytes.toBytes(dstRS.getServerName().getServerName()));
928     // wait for region move completes
929     final RegionStates regionStates =
930         TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager().getRegionStates();
931     TEST_UTIL.waitFor(45000, 200, new Waiter.Predicate<Exception>() {
932       @Override
933       public boolean evaluate() throws Exception {
934         ServerName sn = regionStates.getRegionServerOfRegion(hri);
935         return (sn != null && sn.equals(tmpRS.getServerName()));
936       }
937     });
938 
939     try {
940       byte[] key = region.getStartKey();
941       if (key == null || key.length == 0) {
942         key = new byte[] { 0, 0, 0, 0, 1 };
943       }
944       Put put = new Put(key);
945       put.add(Bytes.toBytes("family"), Bytes.toBytes("c1"), new byte[]{'b'});
946       ht.put(put);
947     } catch (IOException ioe) {
948       Assert.assertTrue(ioe instanceof RetriesExhaustedWithDetailsException);
949       RetriesExhaustedWithDetailsException re = (RetriesExhaustedWithDetailsException) ioe;
950       boolean foundRegionInRecoveryException = false;
951       for (Throwable t : re.getCauses()) {
952         if (t instanceof RegionInRecoveryException) {
953           foundRegionInRecoveryException = true;
954           break;
955         }
956       }
957       Assert.assertTrue(
958         "No RegionInRecoveryException. Following exceptions returned=" + re.getCauses(),
959         foundRegionInRecoveryException);
960     }
961 
962     ht.close();
963     zkw.close();
964   }
965 
966   /**
967    * The original intention of this test was to force an abort of a region
968    * server and to make sure that the failure path in the region servers is
969    * properly evaluated. But it is difficult to ensure that the region server
970    * doesn't finish the log splitting before it aborts. Also now, there is
971    * this code path where the master will preempt the region server when master
972    * detects that the region server has aborted.
973    * @throws Exception
974    */
975   @Test (timeout=300000)
976   public void testWorkerAbort() throws Exception {
977     LOG.info("testWorkerAbort");
978     startCluster(3);
979     final int NUM_LOG_LINES = 10000;
980     final SplitLogManager slm = master.getMasterFileSystem().splitLogManager;
981     FileSystem fs = master.getMasterFileSystem().getFileSystem();
982 
983     final List<RegionServerThread> rsts = cluster.getLiveRegionServerThreads();
984     HRegionServer hrs = findRSToKill(false, "table");
985     Path rootdir = FSUtils.getRootDir(conf);
986     final Path logDir = new Path(rootdir,
987         DefaultWALProvider.getWALDirectoryName(hrs.getServerName().toString()));
988 
989     installTable(new ZooKeeperWatcher(conf, "table-creation", null),
990         "table", "family", 40);
991 
992     makeWAL(hrs, ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices()),
993       "table", "family", NUM_LOG_LINES, 100);
994 
995     new Thread() {
996       @Override
997       public void run() {
998         waitForCounter(tot_wkr_task_acquired, 0, 1, 1000);
999         for (RegionServerThread rst : rsts) {
1000           rst.getRegionServer().abort("testing");
1001           break;
1002         }
1003       }
1004     }.start();
1005     // slm.splitLogDistributed(logDir);
1006     FileStatus[] logfiles = fs.listStatus(logDir);
1007     TaskBatch batch = new TaskBatch();
1008     slm.enqueueSplitTask(logfiles[0].getPath().toString(), batch);
1009     //waitForCounter but for one of the 2 counters
1010     long curt = System.currentTimeMillis();
1011     long waitTime = 80000;
1012     long endt = curt + waitTime;
1013     while (curt < endt) {
1014       if ((tot_wkr_task_resigned.get() + tot_wkr_task_err.get() +
1015           tot_wkr_final_transition_failed.get() + tot_wkr_task_done.get() +
1016           tot_wkr_preempt_task.get()) == 0) {
1017         Thread.yield();
1018         curt = System.currentTimeMillis();
1019       } else {
1020         assertTrue(1 <= (tot_wkr_task_resigned.get() + tot_wkr_task_err.get() +
1021             tot_wkr_final_transition_failed.get() + tot_wkr_task_done.get() +
1022             tot_wkr_preempt_task.get()));
1023         return;
1024       }
1025     }
1026     fail("none of the following counters went up in " + waitTime +
1027         " milliseconds - " +
1028         "tot_wkr_task_resigned, tot_wkr_task_err, " +
1029         "tot_wkr_final_transition_failed, tot_wkr_task_done, " +
1030         "tot_wkr_preempt_task");
1031   }
1032 
1033   @Test (timeout=300000)
1034   public void testThreeRSAbort() throws Exception {
1035     LOG.info("testThreeRSAbort");
1036     final int NUM_REGIONS_TO_CREATE = 40;
1037     final int NUM_ROWS_PER_REGION = 100;
1038 
1039     startCluster(NUM_RS); // NUM_RS=6.
1040 
1041     final ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf,
1042         "distributed log splitting test", null);
1043 
1044     Table ht = installTable(zkw, "table", "family", NUM_REGIONS_TO_CREATE);
1045     populateDataInTable(NUM_ROWS_PER_REGION, "family");
1046 
1047 
1048     List<RegionServerThread> rsts = cluster.getLiveRegionServerThreads();
1049     assertEquals(NUM_RS, rsts.size());
1050     rsts.get(0).getRegionServer().abort("testing");
1051     rsts.get(1).getRegionServer().abort("testing");
1052     rsts.get(2).getRegionServer().abort("testing");
1053 
1054     long start = EnvironmentEdgeManager.currentTime();
1055     while (cluster.getLiveRegionServerThreads().size() > (NUM_RS - 3)) {
1056       if (EnvironmentEdgeManager.currentTime() - start > 60000) {
1057         assertTrue(false);
1058       }
1059       Thread.sleep(200);
1060     }
1061 
1062     start = EnvironmentEdgeManager.currentTime();
1063     while (HBaseTestingUtility.getAllOnlineRegions(cluster).size()
1064         < (NUM_REGIONS_TO_CREATE + 1)) {
1065       if (EnvironmentEdgeManager.currentTime() - start > 60000) {
1066         assertTrue("Timedout", false);
1067       }
1068       Thread.sleep(200);
1069     }
1070 
1071     // wait for all regions are fully recovered
1072     TEST_UTIL.waitFor(180000, 200, new Waiter.Predicate<Exception>() {
1073       @Override
1074       public boolean evaluate() throws Exception {
1075         List<String> recoveringRegions = zkw.getRecoverableZooKeeper().getChildren(
1076           zkw.recoveringRegionsZNode, false);
1077         return (recoveringRegions != null && recoveringRegions.size() == 0);
1078       }
1079     });
1080 
1081     assertEquals(NUM_REGIONS_TO_CREATE * NUM_ROWS_PER_REGION,
1082         TEST_UTIL.countRows(ht));
1083     ht.close();
1084     zkw.close();
1085   }
1086 
1087 
1088 
1089   @Test(timeout=30000)
1090   public void testDelayedDeleteOnFailure() throws Exception {
1091     LOG.info("testDelayedDeleteOnFailure");
1092     startCluster(1);
1093     final SplitLogManager slm = master.getMasterFileSystem().splitLogManager;
1094     final FileSystem fs = master.getMasterFileSystem().getFileSystem();
1095     final Path logDir = new Path(FSUtils.getRootDir(conf), "x");
1096     fs.mkdirs(logDir);
1097     ExecutorService executor = null;
1098     try {
1099       final Path corruptedLogFile = new Path(logDir, "x");
1100       FSDataOutputStream out;
1101       out = fs.create(corruptedLogFile);
1102       out.write(0);
1103       out.write(Bytes.toBytes("corrupted bytes"));
1104       out.close();
1105       ZKSplitLogManagerCoordination coordination =
1106           (ZKSplitLogManagerCoordination) ((BaseCoordinatedStateManager) master
1107               .getCoordinatedStateManager()).getSplitLogManagerCoordination();
1108       coordination.setIgnoreDeleteForTesting(true);
1109       executor = Executors.newSingleThreadExecutor();
1110       Runnable runnable = new Runnable() {
1111        @Override
1112        public void run() {
1113           try {
1114             // since the logDir is a fake, corrupted one, so the split log worker
1115             // will finish it quickly with error, and this call will fail and throw
1116             // an IOException.
1117             slm.splitLogDistributed(logDir);
1118           } catch (IOException ioe) {
1119             try {
1120               assertTrue(fs.exists(corruptedLogFile));
1121               // this call will block waiting for the task to be removed from the
1122               // tasks map which is not going to happen since ignoreZKDeleteForTesting
1123               // is set to true, until it is interrupted.
1124               slm.splitLogDistributed(logDir);
1125             } catch (IOException e) {
1126               assertTrue(Thread.currentThread().isInterrupted());
1127               return;
1128             }
1129             fail("did not get the expected IOException from the 2nd call");
1130           }
1131           fail("did not get the expected IOException from the 1st call");
1132         }
1133       };
1134       Future<?> result = executor.submit(runnable);
1135       try {
1136         result.get(2000, TimeUnit.MILLISECONDS);
1137       } catch (TimeoutException te) {
1138         // it is ok, expected.
1139       }
1140       waitForCounter(tot_mgr_wait_for_zk_delete, 0, 1, 10000);
1141       executor.shutdownNow();
1142       executor = null;
1143 
1144       // make sure the runnable is finished with no exception thrown.
1145       result.get();
1146     } finally {
1147       if (executor != null) {
1148         // interrupt the thread in case the test fails in the middle.
1149         // it has no effect if the thread is already terminated.
1150         executor.shutdownNow();
1151       }
1152       fs.delete(logDir, true);
1153     }
1154   }
1155 
1156   @Test(timeout = 300000)
1157   public void testMetaRecoveryInZK() throws Exception {
1158     LOG.info("testMetaRecoveryInZK");
1159     conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, true);
1160     startCluster(NUM_RS);
1161 
1162     // turn off load balancing to prevent regions from moving around otherwise
1163     // they will consume recovered.edits
1164     master.balanceSwitch(false);
1165     final ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "table-creation", null);
1166 
1167     // only testing meta recovery in ZK operation
1168     HRegionServer hrs = findRSToKill(true, null);
1169     List<HRegionInfo> regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
1170 
1171     LOG.info("#regions = " + regions.size());
1172     Set<HRegionInfo> tmpRegions = new HashSet<HRegionInfo>();
1173     tmpRegions.add(HRegionInfo.FIRST_META_REGIONINFO);
1174     master.getMasterFileSystem().prepareLogReplay(hrs.getServerName(), tmpRegions);
1175     Set<HRegionInfo> userRegionSet = new HashSet<HRegionInfo>();
1176     userRegionSet.addAll(regions);
1177     master.getMasterFileSystem().prepareLogReplay(hrs.getServerName(), userRegionSet);
1178     boolean isMetaRegionInRecovery = false;
1179     List<String> recoveringRegions =
1180         zkw.getRecoverableZooKeeper().getChildren(zkw.recoveringRegionsZNode, false);
1181     for (String curEncodedRegionName : recoveringRegions) {
1182       if (curEncodedRegionName.equals(HRegionInfo.FIRST_META_REGIONINFO.getEncodedName())) {
1183         isMetaRegionInRecovery = true;
1184         break;
1185       }
1186     }
1187     assertTrue(isMetaRegionInRecovery);
1188 
1189     master.getMasterFileSystem().splitMetaLog(hrs.getServerName());
1190 
1191     isMetaRegionInRecovery = false;
1192     recoveringRegions =
1193         zkw.getRecoverableZooKeeper().getChildren(zkw.recoveringRegionsZNode, false);
1194     for (String curEncodedRegionName : recoveringRegions) {
1195       if (curEncodedRegionName.equals(HRegionInfo.FIRST_META_REGIONINFO.getEncodedName())) {
1196         isMetaRegionInRecovery = true;
1197         break;
1198       }
1199     }
1200     // meta region should be recovered
1201     assertFalse(isMetaRegionInRecovery);
1202     zkw.close();
1203   }
1204 
1205   @Test(timeout = 300000)
1206   public void testSameVersionUpdatesRecovery() throws Exception {
1207     LOG.info("testSameVersionUpdatesRecovery");
1208     conf.setLong("hbase.regionserver.hlog.blocksize", 15 * 1024);
1209     conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, true);
1210     startCluster(NUM_RS);
1211     final AtomicLong sequenceId = new AtomicLong(100);
1212     final int NUM_REGIONS_TO_CREATE = 40;
1213     final int NUM_LOG_LINES = 1000;
1214     // turn off load balancing to prevent regions from moving around otherwise
1215     // they will consume recovered.edits
1216     master.balanceSwitch(false);
1217 
1218     List<RegionServerThread> rsts = cluster.getLiveRegionServerThreads();
1219     final ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "table-creation", null);
1220     Table ht = installTable(zkw, "table", "family", NUM_REGIONS_TO_CREATE);
1221 
1222     List<HRegionInfo> regions = null;
1223     HRegionServer hrs = null;
1224     for (int i = 0; i < NUM_RS; i++) {
1225       boolean isCarryingMeta = false;
1226       hrs = rsts.get(i).getRegionServer();
1227       regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
1228       for (HRegionInfo region : regions) {
1229         if (region.isMetaRegion()) {
1230           isCarryingMeta = true;
1231           break;
1232         }
1233       }
1234       if (isCarryingMeta) {
1235         continue;
1236       }
1237       break;
1238     }
1239 
1240     LOG.info("#regions = " + regions.size());
1241     Iterator<HRegionInfo> it = regions.iterator();
1242     while (it.hasNext()) {
1243       HRegionInfo region = it.next();
1244       if (region.isMetaTable()
1245           || region.getEncodedName().equals(HRegionInfo.FIRST_META_REGIONINFO.getEncodedName())) {
1246         it.remove();
1247       }
1248     }
1249     if (regions.size() == 0) return;
1250     HRegionInfo curRegionInfo = regions.get(0);
1251     byte[] startRow = curRegionInfo.getStartKey();
1252     if (startRow == null || startRow.length == 0) {
1253       startRow = new byte[] { 0, 0, 0, 0, 1 };
1254     }
1255     byte[] row = Bytes.incrementBytes(startRow, 1);
1256     // use last 5 bytes because HBaseTestingUtility.createMultiRegions use 5 bytes key
1257     row = Arrays.copyOfRange(row, 3, 8);
1258     long value = 0;
1259     TableName tableName = TableName.valueOf("table");
1260     byte[] family = Bytes.toBytes("family");
1261     byte[] qualifier = Bytes.toBytes("c1");
1262     long timeStamp = System.currentTimeMillis();
1263     HTableDescriptor htd = new HTableDescriptor();
1264     htd.addFamily(new HColumnDescriptor(family));
1265     final WAL wal = hrs.getWAL(curRegionInfo);
1266     for (int i = 0; i < NUM_LOG_LINES; i += 1) {
1267       WALEdit e = new WALEdit();
1268       value++;
1269       e.add(new KeyValue(row, family, qualifier, timeStamp, Bytes.toBytes(value)));
1270       wal.append(htd, curRegionInfo,
1271           new HLogKey(curRegionInfo.getEncodedNameAsBytes(), tableName, System.currentTimeMillis()),
1272           e, sequenceId, true, null);
1273     }
1274     wal.sync();
1275     wal.shutdown();
1276 
1277     // wait for abort completes
1278     this.abortRSAndWaitForRecovery(hrs, zkw, NUM_REGIONS_TO_CREATE);
1279 
1280     // verify we got the last value
1281     LOG.info("Verification Starts...");
1282     Get g = new Get(row);
1283     Result r = ht.get(g);
1284     long theStoredVal = Bytes.toLong(r.getValue(family, qualifier));
1285     assertEquals(value, theStoredVal);
1286 
1287     // after flush
1288     LOG.info("Verification after flush...");
1289     TEST_UTIL.getHBaseAdmin().flush(tableName);
1290     r = ht.get(g);
1291     theStoredVal = Bytes.toLong(r.getValue(family, qualifier));
1292     assertEquals(value, theStoredVal);
1293     ht.close();
1294   }
1295 
1296   @Test(timeout = 300000)
1297   public void testSameVersionUpdatesRecoveryWithCompaction() throws Exception {
1298     LOG.info("testSameVersionUpdatesRecoveryWithWrites");
1299     conf.setLong("hbase.regionserver.hlog.blocksize", 15 * 1024);
1300     conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, true);
1301     conf.setInt(HConstants.HREGION_MEMSTORE_FLUSH_SIZE, 30 * 1024);
1302     conf.setInt("hbase.hstore.compactionThreshold", 3);
1303     startCluster(NUM_RS);
1304     final AtomicLong sequenceId = new AtomicLong(100);
1305     final int NUM_REGIONS_TO_CREATE = 40;
1306     final int NUM_LOG_LINES = 2000;
1307     // turn off load balancing to prevent regions from moving around otherwise
1308     // they will consume recovered.edits
1309     master.balanceSwitch(false);
1310 
1311     List<RegionServerThread> rsts = cluster.getLiveRegionServerThreads();
1312     final ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "table-creation", null);
1313     Table ht = installTable(zkw, "table", "family", NUM_REGIONS_TO_CREATE);
1314 
1315     List<HRegionInfo> regions = null;
1316     HRegionServer hrs = null;
1317     for (int i = 0; i < NUM_RS; i++) {
1318       boolean isCarryingMeta = false;
1319       hrs = rsts.get(i).getRegionServer();
1320       regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
1321       for (HRegionInfo region : regions) {
1322         if (region.isMetaRegion()) {
1323           isCarryingMeta = true;
1324           break;
1325         }
1326       }
1327       if (isCarryingMeta) {
1328         continue;
1329       }
1330       break;
1331     }
1332 
1333     LOG.info("#regions = " + regions.size());
1334     Iterator<HRegionInfo> it = regions.iterator();
1335     while (it.hasNext()) {
1336       HRegionInfo region = it.next();
1337       if (region.isMetaTable()
1338           || region.getEncodedName().equals(HRegionInfo.FIRST_META_REGIONINFO.getEncodedName())) {
1339         it.remove();
1340       }
1341     }
1342     if (regions.size() == 0) return;
1343     HRegionInfo curRegionInfo = regions.get(0);
1344     byte[] startRow = curRegionInfo.getStartKey();
1345     if (startRow == null || startRow.length == 0) {
1346       startRow = new byte[] { 0, 0, 0, 0, 1 };
1347     }
1348     byte[] row = Bytes.incrementBytes(startRow, 1);
1349     // use last 5 bytes because HBaseTestingUtility.createMultiRegions use 5 bytes key
1350     row = Arrays.copyOfRange(row, 3, 8);
1351     long value = 0;
1352     final TableName tableName = TableName.valueOf("table");
1353     byte[] family = Bytes.toBytes("family");
1354     byte[] qualifier = Bytes.toBytes("c1");
1355     long timeStamp = System.currentTimeMillis();
1356     HTableDescriptor htd = new HTableDescriptor(tableName);
1357     htd.addFamily(new HColumnDescriptor(family));
1358     final WAL wal = hrs.getWAL(curRegionInfo);
1359     for (int i = 0; i < NUM_LOG_LINES; i += 1) {
1360       WALEdit e = new WALEdit();
1361       value++;
1362       e.add(new KeyValue(row, family, qualifier, timeStamp, Bytes.toBytes(value)));
1363       wal.append(htd, curRegionInfo, new HLogKey(curRegionInfo.getEncodedNameAsBytes(),
1364           tableName, System.currentTimeMillis()), e, sequenceId, true, null);
1365     }
1366     wal.sync();
1367     wal.shutdown();
1368 
1369     // wait for abort completes
1370     this.abortRSAndWaitForRecovery(hrs, zkw, NUM_REGIONS_TO_CREATE);
1371 
1372     // verify we got the last value
1373     LOG.info("Verification Starts...");
1374     Get g = new Get(row);
1375     Result r = ht.get(g);
1376     long theStoredVal = Bytes.toLong(r.getValue(family, qualifier));
1377     assertEquals(value, theStoredVal);
1378 
1379     // after flush & compaction
1380     LOG.info("Verification after flush...");
1381     TEST_UTIL.getHBaseAdmin().flush(tableName);
1382     TEST_UTIL.getHBaseAdmin().compact(tableName);
1383 
1384     // wait for compaction completes
1385     TEST_UTIL.waitFor(30000, 200, new Waiter.Predicate<Exception>() {
1386       @Override
1387       public boolean evaluate() throws Exception {
1388         return (TEST_UTIL.getHBaseAdmin().getCompactionState(tableName) == CompactionState.NONE);
1389       }
1390     });
1391 
1392     r = ht.get(g);
1393     theStoredVal = Bytes.toLong(r.getValue(family, qualifier));
1394     assertEquals(value, theStoredVal);
1395     ht.close();
1396   }
1397 
1398   @Test(timeout = 300000)
1399   public void testReadWriteSeqIdFiles() throws Exception {
1400     LOG.info("testReadWriteSeqIdFiles");
1401     startCluster(2);
1402     final ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "table-creation", null);
1403     HTable ht = installTable(zkw, "table", "family", 10);
1404     FileSystem fs = master.getMasterFileSystem().getFileSystem();
1405     Path tableDir = FSUtils.getTableDir(FSUtils.getRootDir(conf), TableName.valueOf("table"));
1406     List<Path> regionDirs = FSUtils.getRegionDirs(fs, tableDir);
1407     long newSeqId = WALSplitter.writeRegionSequenceIdFile(fs, regionDirs.get(0), 1L, 1000L);
1408     WALSplitter.writeRegionSequenceIdFile(fs, regionDirs.get(0) , 1L, 1000L);
1409     assertEquals(newSeqId + 2000,
1410       WALSplitter.writeRegionSequenceIdFile(fs, regionDirs.get(0), 3L, 1000L));
1411     
1412     Path editsdir = WALSplitter.getRegionDirRecoveredEditsDir(regionDirs.get(0));
1413     FileStatus[] files = FSUtils.listStatus(fs, editsdir, new PathFilter() {
1414       @Override
1415       public boolean accept(Path p) {
1416         return WALSplitter.isSequenceIdFile(p);
1417       }
1418     });
1419     // only one seqid file should exist
1420     assertEquals(1, files.length);
1421 
1422     // verify all seqId files aren't treated as recovered.edits files
1423     NavigableSet<Path> recoveredEdits = WALSplitter.getSplitEditFilesSorted(fs, regionDirs.get(0));
1424     assertEquals(0, recoveredEdits.size());
1425 
1426     ht.close();
1427   }
1428 
1429   HTable installTable(ZooKeeperWatcher zkw, String tname, String fname, int nrs) throws Exception {
1430     return installTable(zkw, tname, fname, nrs, 0);
1431   }
1432 
1433   HTable installTable(ZooKeeperWatcher zkw, String tname, String fname, int nrs,
1434       int existingRegions) throws Exception {
1435     // Create a table with regions
1436     TableName table = TableName.valueOf(tname);
1437     byte [] family = Bytes.toBytes(fname);
1438     LOG.info("Creating table with " + nrs + " regions");
1439     HTable ht = TEST_UTIL.createMultiRegionTable(table, family, nrs);
1440     int numRegions = -1;
1441     try (RegionLocator r = ht.getRegionLocator()) {
1442       numRegions = r.getStartKeys().length;
1443     }
1444     assertEquals(nrs, numRegions);
1445       LOG.info("Waiting for no more RIT\n");
1446     blockUntilNoRIT(zkw, master);
1447     // disable-enable cycle to get rid of table's dead regions left behind
1448     // by createMultiRegions
1449     LOG.debug("Disabling table\n");
1450     TEST_UTIL.getHBaseAdmin().disableTable(table);
1451     LOG.debug("Waiting for no more RIT\n");
1452     blockUntilNoRIT(zkw, master);
1453     NavigableSet<String> regions = HBaseTestingUtility.getAllOnlineRegions(cluster);
1454     LOG.debug("Verifying only catalog and namespace regions are assigned\n");
1455     if (regions.size() != 2) {
1456       for (String oregion : regions)
1457         LOG.debug("Region still online: " + oregion);
1458     }
1459     assertEquals(2 + existingRegions, regions.size());
1460     LOG.debug("Enabling table\n");
1461     TEST_UTIL.getHBaseAdmin().enableTable(table);
1462     LOG.debug("Waiting for no more RIT\n");
1463     blockUntilNoRIT(zkw, master);
1464     LOG.debug("Verifying there are " + numRegions + " assigned on cluster\n");
1465     regions = HBaseTestingUtility.getAllOnlineRegions(cluster);
1466     assertEquals(numRegions + 2 + existingRegions, regions.size());
1467     return ht;
1468   }
1469 
1470   void populateDataInTable(int nrows, String fname) throws Exception {
1471     byte [] family = Bytes.toBytes(fname);
1472 
1473     List<RegionServerThread> rsts = cluster.getLiveRegionServerThreads();
1474     assertEquals(NUM_RS, rsts.size());
1475 
1476     for (RegionServerThread rst : rsts) {
1477       HRegionServer hrs = rst.getRegionServer();
1478       List<HRegionInfo> hris = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
1479       for (HRegionInfo hri : hris) {
1480         if (hri.getTable().isSystemTable()) {
1481           continue;
1482         }
1483         LOG.debug("adding data to rs = " + rst.getName() +
1484             " region = "+ hri.getRegionNameAsString());
1485         Region region = hrs.getOnlineRegion(hri.getRegionName());
1486         assertTrue(region != null);
1487         putData(region, hri.getStartKey(), nrows, Bytes.toBytes("q"), family);
1488       }
1489     }
1490   }
1491 
1492   public void makeWAL(HRegionServer hrs, List<HRegionInfo> regions, String tname, String fname,
1493       int num_edits, int edit_size) throws IOException {
1494     makeWAL(hrs, regions, tname, fname, num_edits, edit_size, true);
1495   }
1496 
1497   public void makeWAL(HRegionServer hrs, List<HRegionInfo> regions, String tname, String fname,
1498       int num_edits, int edit_size, boolean cleanShutdown) throws IOException {
1499     TableName fullTName = TableName.valueOf(tname);
1500     // remove root and meta region
1501     regions.remove(HRegionInfo.FIRST_META_REGIONINFO);
1502     // using one sequenceId for edits across all regions is ok.
1503     final AtomicLong sequenceId = new AtomicLong(10);
1504 
1505 
1506     for(Iterator<HRegionInfo> iter = regions.iterator(); iter.hasNext(); ) {
1507       HRegionInfo regionInfo = iter.next();
1508       if(regionInfo.getTable().isSystemTable()) {
1509          iter.remove();
1510       }
1511     }
1512     HTableDescriptor htd = new HTableDescriptor(fullTName);
1513     byte[] family = Bytes.toBytes(fname);
1514     htd.addFamily(new HColumnDescriptor(family));
1515     byte[] value = new byte[edit_size];
1516 
1517     List<HRegionInfo> hris = new ArrayList<HRegionInfo>();
1518     for (HRegionInfo region : regions) {
1519       if (!region.getTable().getNameAsString().equalsIgnoreCase(tname)) {
1520         continue;
1521       }
1522       hris.add(region);
1523     }
1524     LOG.info("Creating wal edits across " + hris.size() + " regions.");
1525     for (int i = 0; i < edit_size; i++) {
1526       value[i] = (byte) ('a' + (i % 26));
1527     }
1528     int n = hris.size();
1529     int[] counts = new int[n];
1530     // sync every ~30k to line up with desired wal rolls
1531     final int syncEvery = 30 * 1024 / edit_size;
1532     if (n > 0) {
1533       for (int i = 0; i < num_edits; i += 1) {
1534         WALEdit e = new WALEdit();
1535         HRegionInfo curRegionInfo = hris.get(i % n);
1536         final WAL log = hrs.getWAL(curRegionInfo);
1537         byte[] startRow = curRegionInfo.getStartKey();
1538         if (startRow == null || startRow.length == 0) {
1539           startRow = new byte[] { 0, 0, 0, 0, 1 };
1540         }
1541         byte[] row = Bytes.incrementBytes(startRow, counts[i % n]);
1542         row = Arrays.copyOfRange(row, 3, 8); // use last 5 bytes because
1543                                              // HBaseTestingUtility.createMultiRegions use 5 bytes
1544                                              // key
1545         byte[] qualifier = Bytes.toBytes("c" + Integer.toString(i));
1546         e.add(new KeyValue(row, family, qualifier, System.currentTimeMillis(), value));
1547         log.append(htd, curRegionInfo, new HLogKey(curRegionInfo.getEncodedNameAsBytes(), fullTName,
1548             System.currentTimeMillis()), e, sequenceId, true, null);
1549         if (0 == i % syncEvery) {
1550           log.sync();
1551         }
1552         counts[i % n] += 1;
1553       }
1554     }
1555     // done as two passes because the regions might share logs. shutdown is idempotent, but sync
1556     // will cause errors if done after.
1557     for (HRegionInfo info : hris) {
1558       final WAL log = hrs.getWAL(info);
1559       log.sync();
1560     }
1561     if (cleanShutdown) {
1562       for (HRegionInfo info : hris) {
1563         final WAL log = hrs.getWAL(info);
1564         log.shutdown();
1565       }
1566     }
1567     for (int i = 0; i < n; i++) {
1568       LOG.info("region " + hris.get(i).getRegionNameAsString() + " has " + counts[i] + " edits");
1569     }
1570     return;
1571   }
1572 
1573   private int countWAL(Path log, FileSystem fs, Configuration conf)
1574   throws IOException {
1575     int count = 0;
1576     WAL.Reader in = WALFactory.createReader(fs, log, conf);
1577     try {
1578       WAL.Entry e;
1579       while ((e = in.next()) != null) {
1580         if (!WALEdit.isMetaEditFamily(e.getEdit().getCells().get(0))) {
1581           count++;
1582         }
1583       }
1584     } finally {
1585       try {
1586         in.close();
1587       } catch (IOException exception) {
1588         LOG.warn("Problem closing wal: " + exception.getMessage());
1589         LOG.debug("exception details.", exception);
1590       }
1591     }
1592     return count;
1593   }
1594 
1595   private void blockUntilNoRIT(ZooKeeperWatcher zkw, HMaster master)
1596   throws KeeperException, InterruptedException {
1597     ZKAssign.blockUntilNoRIT(zkw);
1598     master.assignmentManager.waitUntilNoRegionsInTransition(60000);
1599   }
1600 
1601   private void putData(Region region, byte[] startRow, int numRows, byte [] qf,
1602       byte [] ...families)
1603   throws IOException {
1604     for(int i = 0; i < numRows; i++) {
1605       Put put = new Put(Bytes.add(startRow, Bytes.toBytes(i)));
1606       for(byte [] family : families) {
1607         put.add(family, qf, null);
1608       }
1609       region.put(put);
1610     }
1611   }
1612 
1613   /**
1614    * Load table with puts and deletes with expected values so that we can verify later
1615    */
1616   private void prepareData(final Table t, final byte[] f, final byte[] column) throws IOException {
1617     byte[] k = new byte[3];
1618 
1619     // add puts
1620     List<Put> puts = new ArrayList<>();
1621     for (byte b1 = 'a'; b1 <= 'z'; b1++) {
1622       for (byte b2 = 'a'; b2 <= 'z'; b2++) {
1623         for (byte b3 = 'a'; b3 <= 'z'; b3++) {
1624           k[0] = b1;
1625           k[1] = b2;
1626           k[2] = b3;
1627           Put put = new Put(k);
1628           put.add(f, column, k);
1629           puts.add(put);
1630         }
1631       }
1632     }
1633     t.put(puts);
1634     // add deletes
1635     for (byte b3 = 'a'; b3 <= 'z'; b3++) {
1636       k[0] = 'a';
1637       k[1] = 'a';
1638       k[2] = b3;
1639       Delete del = new Delete(k);
1640       t.delete(del);
1641     }
1642   }
1643 
1644   private void waitForCounter(AtomicLong ctr, long oldval, long newval,
1645       long timems) {
1646     long curt = System.currentTimeMillis();
1647     long endt = curt + timems;
1648     while (curt < endt) {
1649       if (ctr.get() == oldval) {
1650         Thread.yield();
1651         curt = System.currentTimeMillis();
1652       } else {
1653         assertEquals(newval, ctr.get());
1654         return;
1655       }
1656     }
1657     assertTrue(false);
1658   }
1659 
1660   private void abortMaster(MiniHBaseCluster cluster) throws InterruptedException {
1661     for (MasterThread mt : cluster.getLiveMasterThreads()) {
1662       if (mt.getMaster().isActiveMaster()) {
1663         mt.getMaster().abort("Aborting for tests", new Exception("Trace info"));
1664         mt.join();
1665         break;
1666       }
1667     }
1668     LOG.debug("Master is aborted");
1669   }
1670 
1671   /**
1672    * Find a RS that has regions of a table.
1673    * @param hasMetaRegion when true, the returned RS has hbase:meta region as well
1674    * @param tableName
1675    * @return
1676    * @throws Exception
1677    */
1678   private HRegionServer findRSToKill(boolean hasMetaRegion, String tableName) throws Exception {
1679     List<RegionServerThread> rsts = cluster.getLiveRegionServerThreads();
1680     int numOfRSs = rsts.size();
1681     List<HRegionInfo> regions = null;
1682     HRegionServer hrs = null;
1683 
1684     for (int i = 0; i < numOfRSs; i++) {
1685       boolean isCarryingMeta = false;
1686       boolean foundTableRegion = false;
1687       hrs = rsts.get(i).getRegionServer();
1688       regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
1689       for (HRegionInfo region : regions) {
1690         if (region.isMetaRegion()) {
1691           isCarryingMeta = true;
1692         }
1693         if (tableName == null || region.getTable().getNameAsString().equals(tableName)) {
1694           foundTableRegion = true;
1695         }
1696         if (foundTableRegion && (isCarryingMeta || !hasMetaRegion)) {
1697           break;
1698         }
1699       }
1700       if (isCarryingMeta && hasMetaRegion) {
1701         // clients ask for a RS with META
1702         if (!foundTableRegion) {
1703           final HRegionServer destRS = hrs;
1704           // the RS doesn't have regions of the specified table so we need move one to this RS
1705           List<HRegionInfo> tableRegions =
1706               TEST_UTIL.getHBaseAdmin().getTableRegions(TableName.valueOf(tableName));
1707           final HRegionInfo hri = tableRegions.get(0);
1708           TEST_UTIL.getHBaseAdmin().move(hri.getEncodedNameAsBytes(),
1709             Bytes.toBytes(destRS.getServerName().getServerName()));
1710           // wait for region move completes
1711           final RegionStates regionStates =
1712               TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager().getRegionStates();
1713           TEST_UTIL.waitFor(45000, 200, new Waiter.Predicate<Exception>() {
1714             @Override
1715             public boolean evaluate() throws Exception {
1716               ServerName sn = regionStates.getRegionServerOfRegion(hri);
1717               return (sn != null && sn.equals(destRS.getServerName()));
1718             }
1719           });
1720         }
1721         return hrs;
1722       } else if (hasMetaRegion || isCarryingMeta) {
1723         continue;
1724       }
1725       if (foundTableRegion) break;
1726     }
1727 
1728     return hrs;
1729   }
1730 
1731 }