View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase;
19  
20  import java.io.File;
21  import java.io.IOException;
22  import java.io.OutputStream;
23  import java.lang.reflect.Field;
24  import java.lang.reflect.Modifier;
25  import java.net.BindException;
26  import java.net.InetAddress;
27  import java.net.ServerSocket;
28  import java.net.Socket;
29  import java.net.UnknownHostException;
30  import java.security.MessageDigest;
31  import java.util.ArrayList;
32  import java.util.Arrays;
33  import java.util.Collection;
34  import java.util.Collections;
35  import java.util.HashSet;
36  import java.util.List;
37  import java.util.Map;
38  import java.util.NavigableSet;
39  import java.util.Properties;
40  import java.util.Random;
41  import java.util.Set;
42  import java.util.TreeSet;
43  import java.util.UUID;
44  import java.util.concurrent.TimeUnit;
45  
46  import org.apache.commons.io.FileUtils;
47  import org.apache.commons.lang.RandomStringUtils;
48  import org.apache.commons.logging.Log;
49  import org.apache.commons.logging.LogFactory;
50  import org.apache.commons.logging.impl.Jdk14Logger;
51  import org.apache.commons.logging.impl.Log4JLogger;
52  import org.apache.hadoop.conf.Configuration;
53  import org.apache.hadoop.fs.FileSystem;
54  import org.apache.hadoop.fs.Path;
55  import org.apache.hadoop.hbase.Waiter.ExplainingPredicate;
56  import org.apache.hadoop.hbase.Waiter.Predicate;
57  import org.apache.hadoop.hbase.classification.InterfaceAudience;
58  import org.apache.hadoop.hbase.classification.InterfaceStability;
59  import org.apache.hadoop.hbase.client.Admin;
60  import org.apache.hadoop.hbase.client.Connection;
61  import org.apache.hadoop.hbase.client.ConnectionFactory;
62  import org.apache.hadoop.hbase.client.Consistency;
63  import org.apache.hadoop.hbase.client.Delete;
64  import org.apache.hadoop.hbase.client.Durability;
65  import org.apache.hadoop.hbase.client.Get;
66  import org.apache.hadoop.hbase.client.HBaseAdmin;
67  import org.apache.hadoop.hbase.client.HConnection;
68  import org.apache.hadoop.hbase.client.HTable;
69  import org.apache.hadoop.hbase.client.Put;
70  import org.apache.hadoop.hbase.client.RegionLocator;
71  import org.apache.hadoop.hbase.client.Result;
72  import org.apache.hadoop.hbase.client.ResultScanner;
73  import org.apache.hadoop.hbase.client.Scan;
74  import org.apache.hadoop.hbase.client.Table;
75  import org.apache.hadoop.hbase.fs.HFileSystem;
76  import org.apache.hadoop.hbase.io.compress.Compression;
77  import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
78  import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
79  import org.apache.hadoop.hbase.io.hfile.ChecksumUtil;
80  import org.apache.hadoop.hbase.io.hfile.HFile;
81  import org.apache.hadoop.hbase.ipc.RpcServerInterface;
82  import org.apache.hadoop.hbase.ipc.ServerNotRunningYetException;
83  import org.apache.hadoop.hbase.mapreduce.MapreduceTestingShim;
84  import org.apache.hadoop.hbase.master.HMaster;
85  import org.apache.hadoop.hbase.master.AssignmentManager;
86  import org.apache.hadoop.hbase.master.RegionStates;
87  import org.apache.hadoop.hbase.master.ServerManager;
88  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
89  import org.apache.hadoop.hbase.regionserver.BloomType;
90  import org.apache.hadoop.hbase.regionserver.HRegion;
91  import org.apache.hadoop.hbase.regionserver.HRegionServer;
92  import org.apache.hadoop.hbase.regionserver.HStore;
93  import org.apache.hadoop.hbase.regionserver.InternalScanner;
94  import org.apache.hadoop.hbase.regionserver.Region;
95  import org.apache.hadoop.hbase.regionserver.RegionServerServices;
96  import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException;
97  import org.apache.hadoop.hbase.regionserver.wal.MetricsWAL;
98  import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
99  import org.apache.hadoop.hbase.security.HBaseKerberosUtils;
100 import org.apache.hadoop.hbase.security.User;
101 import org.apache.hadoop.hbase.security.visibility.VisibilityLabelsCache;
102 import org.apache.hadoop.hbase.tool.Canary;
103 import org.apache.hadoop.hbase.util.Bytes;
104 import org.apache.hadoop.hbase.util.FSTableDescriptors;
105 import org.apache.hadoop.hbase.util.FSUtils;
106 import org.apache.hadoop.hbase.util.JVMClusterUtil;
107 import org.apache.hadoop.hbase.util.JVMClusterUtil.MasterThread;
108 import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread;
109 import org.apache.hadoop.hbase.util.Pair;
110 import org.apache.hadoop.hbase.util.RegionSplitter;
111 import org.apache.hadoop.hbase.util.RetryCounter;
112 import org.apache.hadoop.hbase.util.Threads;
113 import org.apache.hadoop.hbase.wal.WAL;
114 import org.apache.hadoop.hbase.wal.WALFactory;
115 import org.apache.hadoop.hbase.zookeeper.EmptyWatcher;
116 import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
117 import org.apache.hadoop.hbase.zookeeper.ZKAssign;
118 import org.apache.hadoop.hbase.zookeeper.ZKConfig;
119 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
120 import org.apache.hadoop.hdfs.DFSClient;
121 import org.apache.hadoop.hdfs.DistributedFileSystem;
122 import org.apache.hadoop.hdfs.MiniDFSCluster;
123 import org.apache.hadoop.hdfs.server.namenode.EditLogFileOutputStream;
124 import org.apache.hadoop.mapred.JobConf;
125 import org.apache.hadoop.mapred.MiniMRCluster;
126 import org.apache.hadoop.mapred.TaskLog;
127 import org.apache.hadoop.minikdc.MiniKdc;
128 import org.apache.zookeeper.KeeperException;
129 import org.apache.zookeeper.KeeperException.NodeExistsException;
130 import org.apache.zookeeper.WatchedEvent;
131 import org.apache.zookeeper.ZooKeeper;
132 import org.apache.zookeeper.ZooKeeper.States;
133 
134 import static org.junit.Assert.assertEquals;
135 import static org.junit.Assert.assertTrue;
136 import static org.junit.Assert.fail;
137 
138 /**
139  * Facility for testing HBase. Replacement for
140  * old HBaseTestCase and HBaseClusterTestCase functionality.
141  * Create an instance and keep it around testing HBase.  This class is
142  * meant to be your one-stop shop for anything you might need testing.  Manages
143  * one cluster at a time only. Managed cluster can be an in-process
144  * {@link MiniHBaseCluster}, or a deployed cluster of type {@link HBaseCluster}.
145  * Not all methods work with the real cluster.
146  * Depends on log4j being on classpath and
147  * hbase-site.xml for logging and test-run configuration.  It does not set
148  * logging levels nor make changes to configuration parameters.
149  * <p>To preserve test data directories, pass the system property "hbase.testing.preserve.testdir"
150  * setting it to true.
151  */
152 @InterfaceAudience.Public
153 @InterfaceStability.Evolving
154 @SuppressWarnings("deprecation")
155 public class HBaseTestingUtility extends HBaseCommonTestingUtility {
156    private MiniZooKeeperCluster zkCluster = null;
157 
158   public static final String REGIONS_PER_SERVER_KEY = "hbase.test.regions-per-server";
159   /**
160    * The default number of regions per regionserver when creating a pre-split
161    * table.
162    */
163   public static final int DEFAULT_REGIONS_PER_SERVER = 3;
164 
165 
166   public static final String PRESPLIT_TEST_TABLE_KEY = "hbase.test.pre-split-table";
167   public static final boolean PRESPLIT_TEST_TABLE = true;
168 
169   public static final String USE_LOCAL_FILESYSTEM = "hbase.test.local.fileSystem";
170   /**
171    * Set if we were passed a zkCluster.  If so, we won't shutdown zk as
172    * part of general shutdown.
173    */
174   private boolean passedZkCluster = false;
175   private MiniDFSCluster dfsCluster = null;
176 
177   private volatile HBaseCluster hbaseCluster = null;
178   private MiniMRCluster mrCluster = null;
179 
180   /** If there is a mini cluster running for this testing utility instance. */
181   private volatile boolean miniClusterRunning;
182 
183   private String hadoopLogDir;
184 
185   /** Directory (a subdirectory of dataTestDir) used by the dfs cluster if any */
186   private File clusterTestDir = null;
187 
188   /** Directory on test filesystem where we put the data for this instance of
189     * HBaseTestingUtility*/
190   private Path dataTestDirOnTestFS = null;
191 
192   /**
193    * Shared cluster connection.
194    */
195   private volatile Connection connection;
196 
197   /**
198    * System property key to get test directory value.
199    * Name is as it is because mini dfs has hard-codings to put test data here.
200    * It should NOT be used directly in HBase, as it's a property used in
201    *  mini dfs.
202    *  @deprecated can be used only with mini dfs
203    */
204   @Deprecated
205   private static final String TEST_DIRECTORY_KEY = "test.build.data";
206 
207   /** Filesystem URI used for map-reduce mini-cluster setup */
208   private static String FS_URI;
209 
210   /** A set of ports that have been claimed using {@link #randomFreePort()}. */
211   private static final Set<Integer> takenRandomPorts = new HashSet<Integer>();
212 
213   /** Compression algorithms to use in parameterized JUnit 4 tests */
214   public static final List<Object[]> COMPRESSION_ALGORITHMS_PARAMETERIZED =
215     Arrays.asList(new Object[][] {
216       { Compression.Algorithm.NONE },
217       { Compression.Algorithm.GZ }
218     });
219 
220   /** This is for unit tests parameterized with a two booleans. */
221   public static final List<Object[]> BOOLEAN_PARAMETERIZED =
222       Arrays.asList(new Object[][] {
223           { new Boolean(false) },
224           { new Boolean(true) }
225       });
226 
227   /** This is for unit tests parameterized with a single boolean. */
228   public static final List<Object[]> MEMSTORETS_TAGS_PARAMETRIZED = memStoreTSAndTagsCombination()  ;
229   /** Compression algorithms to use in testing */
230   public static final Compression.Algorithm[] COMPRESSION_ALGORITHMS ={
231       Compression.Algorithm.NONE, Compression.Algorithm.GZ
232     };
233 
234   /**
235    * Create all combinations of Bloom filters and compression algorithms for
236    * testing.
237    */
238   private static List<Object[]> bloomAndCompressionCombinations() {
239     List<Object[]> configurations = new ArrayList<Object[]>();
240     for (Compression.Algorithm comprAlgo :
241          HBaseTestingUtility.COMPRESSION_ALGORITHMS) {
242       for (BloomType bloomType : BloomType.values()) {
243         configurations.add(new Object[] { comprAlgo, bloomType });
244       }
245     }
246     return Collections.unmodifiableList(configurations);
247   }
248 
249   /**
250    * Create combination of memstoreTS and tags
251    */
252   private static List<Object[]> memStoreTSAndTagsCombination() {
253     List<Object[]> configurations = new ArrayList<Object[]>();
254     configurations.add(new Object[] { false, false });
255     configurations.add(new Object[] { false, true });
256     configurations.add(new Object[] { true, false });
257     configurations.add(new Object[] { true, true });
258     return Collections.unmodifiableList(configurations);
259   }
260 
261   public static final Collection<Object[]> BLOOM_AND_COMPRESSION_COMBINATIONS =
262       bloomAndCompressionCombinations();
263 
264   public HBaseTestingUtility() {
265     this(HBaseConfiguration.create());
266   }
267 
268   public HBaseTestingUtility(Configuration conf) {
269     super(conf);
270 
271     // a hbase checksum verification failure will cause unit tests to fail
272     ChecksumUtil.generateExceptionForChecksumFailureForTest(true);
273   }
274 
275   /**
276    * Create an HBaseTestingUtility where all tmp files are written to the local test data dir.
277    * It is needed to properly base FSUtil.getRootDirs so that they drop temp files in the proper
278    * test dir.  Use this when you aren't using an Mini HDFS cluster.
279    * @return HBaseTestingUtility that use local fs for temp files.
280    */
281   public static HBaseTestingUtility createLocalHTU() {
282     Configuration c = HBaseConfiguration.create();
283     return createLocalHTU(c);
284   }
285 
286   /**
287    * Create an HBaseTestingUtility where all tmp files are written to the local test data dir.
288    * It is needed to properly base FSUtil.getRootDirs so that they drop temp files in the proper
289    * test dir.  Use this when you aren't using an Mini HDFS cluster.
290    * @param c Configuration (will be modified)
291    * @return HBaseTestingUtility that use local fs for temp files.
292    */
293   public static HBaseTestingUtility createLocalHTU(Configuration c) {
294     HBaseTestingUtility htu = new HBaseTestingUtility(c);
295     String dataTestDir = htu.getDataTestDir().toString();
296     htu.getConfiguration().set(HConstants.HBASE_DIR, dataTestDir);
297     LOG.debug("Setting " + HConstants.HBASE_DIR + " to " + dataTestDir);
298     return htu;
299   }
300 
301  /**
302   * Close the Region {@code r}. For use in tests.
303   */
304  public static void closeRegion(final Region r) throws IOException {
305    if (r != null) {
306      ((HRegion)r).close();
307    }
308  }
309 
310   /**
311    * Returns this classes's instance of {@link Configuration}.  Be careful how
312    * you use the returned Configuration since {@link HConnection} instances
313    * can be shared.  The Map of HConnections is keyed by the Configuration.  If
314    * say, a Connection was being used against a cluster that had been shutdown,
315    * see {@link #shutdownMiniCluster()}, then the Connection will no longer
316    * be wholesome.  Rather than use the return direct, its usually best to
317    * make a copy and use that.  Do
318    * <code>Configuration c = new Configuration(INSTANCE.getConfiguration());</code>
319    * @return Instance of Configuration.
320    */
321   @Override
322   public Configuration getConfiguration() {
323     return super.getConfiguration();
324   }
325 
326   public void setHBaseCluster(HBaseCluster hbaseCluster) {
327     this.hbaseCluster = hbaseCluster;
328   }
329 
330   /**
331    * Home our data in a dir under {@link #DEFAULT_BASE_TEST_DIRECTORY}.
332    * Give it a random name so can have many concurrent tests running if
333    * we need to.  It needs to amend the {@link #TEST_DIRECTORY_KEY}
334    * System property, as it's what minidfscluster bases
335    * it data dir on.  Moding a System property is not the way to do concurrent
336    * instances -- another instance could grab the temporary
337    * value unintentionally -- but not anything can do about it at moment;
338    * single instance only is how the minidfscluster works.
339    *
340    * We also create the underlying directory for
341    *  hadoop.log.dir, mapreduce.cluster.local.dir and hadoop.tmp.dir, and set the values
342    *  in the conf, and as a system property for hadoop.tmp.dir
343    *
344    * @return The calculated data test build directory, if newly-created.
345    */
346   @Override
347   protected Path setupDataTestDir() {
348     Path testPath = super.setupDataTestDir();
349     if (null == testPath) {
350       return null;
351     }
352 
353     createSubDirAndSystemProperty(
354       "hadoop.log.dir",
355       testPath, "hadoop-log-dir");
356 
357     // This is defaulted in core-default.xml to /tmp/hadoop-${user.name}, but
358     //  we want our own value to ensure uniqueness on the same machine
359     createSubDirAndSystemProperty(
360       "hadoop.tmp.dir",
361       testPath, "hadoop-tmp-dir");
362 
363     // Read and modified in org.apache.hadoop.mapred.MiniMRCluster
364     createSubDir(
365       "mapreduce.cluster.local.dir",
366       testPath, "mapred-local-dir");
367 
368     return testPath;
369   }
370 
371   public void setJobWithoutMRCluster() throws IOException {
372     conf.set("hbase.fs.tmp.dir", getDataTestDirOnTestFS("hbase-staging").toString());
373     conf.setBoolean(HBaseTestingUtility.USE_LOCAL_FILESYSTEM, true);
374   }
375 
376   private void createSubDirAndSystemProperty(
377     String propertyName, Path parent, String subDirName){
378 
379     String sysValue = System.getProperty(propertyName);
380 
381     if (sysValue != null) {
382       // There is already a value set. So we do nothing but hope
383       //  that there will be no conflicts
384       LOG.info("System.getProperty(\""+propertyName+"\") already set to: "+
385         sysValue + " so I do NOT create it in " + parent);
386       String confValue = conf.get(propertyName);
387       if (confValue != null && !confValue.endsWith(sysValue)){
388        LOG.warn(
389          propertyName + " property value differs in configuration and system: "+
390          "Configuration="+confValue+" while System="+sysValue+
391          " Erasing configuration value by system value."
392        );
393       }
394       conf.set(propertyName, sysValue);
395     } else {
396       // Ok, it's not set, so we create it as a subdirectory
397       createSubDir(propertyName, parent, subDirName);
398       System.setProperty(propertyName, conf.get(propertyName));
399     }
400   }
401 
402   /**
403    * @return Where to write test data on the test filesystem; Returns working directory
404    * for the test filesystem by default
405    * @see #setupDataTestDirOnTestFS()
406    * @see #getTestFileSystem()
407    */
408   private Path getBaseTestDirOnTestFS() throws IOException {
409     FileSystem fs = getTestFileSystem();
410     return new Path(fs.getWorkingDirectory(), "test-data");
411   }
412 
413   /**
414    * @return META table descriptor
415    */
416   public HTableDescriptor getMetaTableDescriptor() {
417     try {
418       return new FSTableDescriptors(conf).get(TableName.META_TABLE_NAME);
419     } catch (IOException e) {
420       throw new RuntimeException("Unable to create META table descriptor", e);
421     }
422   }
423 
424   /**
425    * @return Where the DFS cluster will write data on the local subsystem.
426    * Creates it if it does not exist already.  A subdir of {@link #getBaseTestDir()}
427    * @see #getTestFileSystem()
428    */
429   Path getClusterTestDir() {
430     if (clusterTestDir == null){
431       setupClusterTestDir();
432     }
433     return new Path(clusterTestDir.getAbsolutePath());
434   }
435 
436   /**
437    * Creates a directory for the DFS cluster, under the test data
438    */
439   private void setupClusterTestDir() {
440     if (clusterTestDir != null) {
441       return;
442     }
443 
444     // Using randomUUID ensures that multiple clusters can be launched by
445     //  a same test, if it stops & starts them
446     Path testDir = getDataTestDir("dfscluster_" + UUID.randomUUID().toString());
447     clusterTestDir = new File(testDir.toString()).getAbsoluteFile();
448     // Have it cleaned up on exit
449     boolean b = deleteOnExit();
450     if (b) clusterTestDir.deleteOnExit();
451     conf.set(TEST_DIRECTORY_KEY, clusterTestDir.getPath());
452     LOG.info("Created new mini-cluster data directory: " + clusterTestDir + ", deleteOnExit=" + b);
453   }
454 
455   /**
456    * Returns a Path in the test filesystem, obtained from {@link #getTestFileSystem()}
457    * to write temporary test data. Call this method after setting up the mini dfs cluster
458    * if the test relies on it.
459    * @return a unique path in the test filesystem
460    */
461   public Path getDataTestDirOnTestFS() throws IOException {
462     if (dataTestDirOnTestFS == null) {
463       setupDataTestDirOnTestFS();
464     }
465 
466     return dataTestDirOnTestFS;
467   }
468 
469   /**
470    * Returns a Path in the test filesystem, obtained from {@link #getTestFileSystem()}
471    * to write temporary test data. Call this method after setting up the mini dfs cluster
472    * if the test relies on it.
473    * @return a unique path in the test filesystem
474    * @param subdirName name of the subdir to create under the base test dir
475    */
476   public Path getDataTestDirOnTestFS(final String subdirName) throws IOException {
477     return new Path(getDataTestDirOnTestFS(), subdirName);
478   }
479 
480   /**
481    * Sets up a path in test filesystem to be used by tests.
482    * Creates a new directory if not already setup.
483    */
484   private void setupDataTestDirOnTestFS() throws IOException {
485     if (dataTestDirOnTestFS != null) {
486       LOG.warn("Data test on test fs dir already setup in "
487           + dataTestDirOnTestFS.toString());
488       return;
489     }
490     dataTestDirOnTestFS = getNewDataTestDirOnTestFS();
491   }
492 
493   /**
494    * Sets up a new path in test filesystem to be used by tests.
495    */
496   private Path getNewDataTestDirOnTestFS() throws IOException {
497     //The file system can be either local, mini dfs, or if the configuration
498     //is supplied externally, it can be an external cluster FS. If it is a local
499     //file system, the tests should use getBaseTestDir, otherwise, we can use
500     //the working directory, and create a unique sub dir there
501     FileSystem fs = getTestFileSystem();
502     Path newDataTestDir = null;
503     if (fs.getUri().getScheme().equals(FileSystem.getLocal(conf).getUri().getScheme())) {
504       File dataTestDir = new File(getDataTestDir().toString());
505       if (deleteOnExit()) dataTestDir.deleteOnExit();
506       newDataTestDir = new Path(dataTestDir.getAbsolutePath());
507     } else {
508       Path base = getBaseTestDirOnTestFS();
509       String randomStr = UUID.randomUUID().toString();
510       newDataTestDir = new Path(base, randomStr);
511       if (deleteOnExit()) fs.deleteOnExit(newDataTestDir);
512     }
513     return newDataTestDir;
514   }
515 
516   /**
517    * Cleans the test data directory on the test filesystem.
518    * @return True if we removed the test dirs
519    * @throws IOException
520    */
521   public boolean cleanupDataTestDirOnTestFS() throws IOException {
522     boolean ret = getTestFileSystem().delete(dataTestDirOnTestFS, true);
523     if (ret)
524       dataTestDirOnTestFS = null;
525     return ret;
526   }
527 
528   /**
529    * Cleans a subdirectory under the test data directory on the test filesystem.
530    * @return True if we removed child
531    * @throws IOException
532    */
533   public boolean cleanupDataTestDirOnTestFS(String subdirName) throws IOException {
534     Path cpath = getDataTestDirOnTestFS(subdirName);
535     return getTestFileSystem().delete(cpath, true);
536   }
537 
538   /**
539    * Start a minidfscluster.
540    * @param servers How many DNs to start.
541    * @throws Exception
542    * @see {@link #shutdownMiniDFSCluster()}
543    * @return The mini dfs cluster created.
544    */
545   public MiniDFSCluster startMiniDFSCluster(int servers) throws Exception {
546     return startMiniDFSCluster(servers, null);
547   }
548 
549   /**
550    * Start a minidfscluster.
551    * This is useful if you want to run datanode on distinct hosts for things
552    * like HDFS block location verification.
553    * If you start MiniDFSCluster without host names, all instances of the
554    * datanodes will have the same host name.
555    * @param hosts hostnames DNs to run on.
556    * @throws Exception
557    * @see {@link #shutdownMiniDFSCluster()}
558    * @return The mini dfs cluster created.
559    */
560   public MiniDFSCluster startMiniDFSCluster(final String hosts[])
561   throws Exception {
562     if ( hosts != null && hosts.length != 0) {
563       return startMiniDFSCluster(hosts.length, hosts);
564     } else {
565       return startMiniDFSCluster(1, null);
566     }
567   }
568 
569   /**
570    * Start a minidfscluster.
571    * Can only create one.
572    * @param servers How many DNs to start.
573    * @param hosts hostnames DNs to run on.
574    * @throws Exception
575    * @see {@link #shutdownMiniDFSCluster()}
576    * @return The mini dfs cluster created.
577    */
578   public MiniDFSCluster startMiniDFSCluster(int servers, final String hosts[])
579   throws Exception {
580     createDirsAndSetProperties();
581     EditLogFileOutputStream.setShouldSkipFsyncForTesting(true);
582 
583     // Error level to skip some warnings specific to the minicluster. See HBASE-4709
584     org.apache.log4j.Logger.getLogger(org.apache.hadoop.metrics2.util.MBeans.class).
585         setLevel(org.apache.log4j.Level.ERROR);
586     org.apache.log4j.Logger.getLogger(org.apache.hadoop.metrics2.impl.MetricsSystemImpl.class).
587         setLevel(org.apache.log4j.Level.ERROR);
588 
589 
590     this.dfsCluster = new MiniDFSCluster(0, this.conf, servers, true, true,
591       true, null, null, hosts, null);
592 
593     // Set this just-started cluster as our filesystem.
594     setFs();
595 
596     // Wait for the cluster to be totally up
597     this.dfsCluster.waitClusterUp();
598 
599     //reset the test directory for test file system
600     dataTestDirOnTestFS = null;
601 
602     return this.dfsCluster;
603   }
604 
605   private void setFs() throws IOException {
606     if(this.dfsCluster == null){
607       LOG.info("Skipping setting fs because dfsCluster is null");
608       return;
609     }
610     FileSystem fs = this.dfsCluster.getFileSystem();
611     FSUtils.setFsDefault(this.conf, new Path(fs.getUri()));
612     if (this.conf.getBoolean(USE_LOCAL_FILESYSTEM, false)) {
613       FSUtils.setFsDefault(this.conf, new Path("file:///"));
614     }
615   }
616 
617   public MiniDFSCluster startMiniDFSCluster(int servers, final  String racks[], String hosts[])
618       throws Exception {
619     createDirsAndSetProperties();
620     this.dfsCluster = new MiniDFSCluster(0, this.conf, servers, true, true,
621         true, null, racks, hosts, null);
622 
623     // Set this just-started cluster as our filesystem.
624     FileSystem fs = this.dfsCluster.getFileSystem();
625     FSUtils.setFsDefault(this.conf, new Path(fs.getUri()));
626 
627     // Wait for the cluster to be totally up
628     this.dfsCluster.waitClusterUp();
629 
630     //reset the test directory for test file system
631     dataTestDirOnTestFS = null;
632 
633     return this.dfsCluster;
634   }
635 
636   public MiniDFSCluster startMiniDFSClusterForTestWAL(int namenodePort) throws IOException {
637     createDirsAndSetProperties();
638     dfsCluster = new MiniDFSCluster(namenodePort, conf, 5, false, true, true, null,
639         null, null, null);
640     return dfsCluster;
641   }
642 
643   /** This is used before starting HDFS and map-reduce mini-clusters */
644   private void createDirsAndSetProperties() throws IOException {
645     setupClusterTestDir();
646     System.setProperty(TEST_DIRECTORY_KEY, clusterTestDir.getPath());
647     createDirAndSetProperty("cache_data", "test.cache.data");
648     createDirAndSetProperty("hadoop_tmp", "hadoop.tmp.dir");
649     hadoopLogDir = createDirAndSetProperty("hadoop_logs", "hadoop.log.dir");
650     createDirAndSetProperty("mapred_local", "mapreduce.cluster.local.dir");
651     createDirAndSetProperty("mapred_temp", "mapreduce.cluster.temp.dir");
652     enableShortCircuit();
653 
654     Path root = getDataTestDirOnTestFS("hadoop");
655     conf.set(MapreduceTestingShim.getMROutputDirProp(),
656       new Path(root, "mapred-output-dir").toString());
657     conf.set("mapreduce.jobtracker.system.dir", new Path(root, "mapred-system-dir").toString());
658     conf.set("mapreduce.jobtracker.staging.root.dir",
659       new Path(root, "mapreduce-jobtracker-staging-root-dir").toString());
660     conf.set("mapreduce.job.working.dir", new Path(root, "mapred-working-dir").toString());
661   }
662 
663 
664   /**
665    *  Get the HBase setting for dfs.client.read.shortcircuit from the conf or a system property.
666    *  This allows to specify this parameter on the command line.
667    *   If not set, default is true.
668    */
669   public boolean isReadShortCircuitOn(){
670     final String propName = "hbase.tests.use.shortcircuit.reads";
671     String readOnProp = System.getProperty(propName);
672     if (readOnProp != null){
673       return  Boolean.parseBoolean(readOnProp);
674     } else {
675       return conf.getBoolean(propName, false);
676     }
677   }
678 
679   /** Enable the short circuit read, unless configured differently.
680    * Set both HBase and HDFS settings, including skipping the hdfs checksum checks.
681    */
682   private void enableShortCircuit() {
683     if (isReadShortCircuitOn()) {
684       String curUser = System.getProperty("user.name");
685       LOG.info("read short circuit is ON for user " + curUser);
686       // read short circuit, for hdfs
687       conf.set("dfs.block.local-path-access.user", curUser);
688       // read short circuit, for hbase
689       conf.setBoolean("dfs.client.read.shortcircuit", true);
690       // Skip checking checksum, for the hdfs client and the datanode
691       conf.setBoolean("dfs.client.read.shortcircuit.skip.checksum", true);
692     } else {
693       LOG.info("read short circuit is OFF");
694     }
695   }
696 
697   private String createDirAndSetProperty(final String relPath, String property) {
698     String path = getDataTestDir(relPath).toString();
699     System.setProperty(property, path);
700     conf.set(property, path);
701     new File(path).mkdirs();
702     LOG.info("Setting " + property + " to " + path + " in system properties and HBase conf");
703     return path;
704   }
705 
706   /**
707    * Shuts down instance created by call to {@link #startMiniDFSCluster(int)}
708    * or does nothing.
709    * @throws IOException
710    */
711   public void shutdownMiniDFSCluster() throws IOException {
712     if (this.dfsCluster != null) {
713       // The below throws an exception per dn, AsynchronousCloseException.
714       this.dfsCluster.shutdown();
715       dfsCluster = null;
716       dataTestDirOnTestFS = null;
717       FSUtils.setFsDefault(this.conf, new Path("file:///"));
718     }
719   }
720 
721   /**
722    * Call this if you only want a zk cluster.
723    * @see #startMiniZKCluster() if you want zk + dfs + hbase mini cluster.
724    * @throws Exception
725    * @see #shutdownMiniZKCluster()
726    * @return zk cluster started.
727    */
728   public MiniZooKeeperCluster startMiniZKCluster() throws Exception {
729     return startMiniZKCluster(1);
730   }
731 
732   /**
733    * Call this if you only want a zk cluster.
734    * @param zooKeeperServerNum
735    * @see #startMiniZKCluster() if you want zk + dfs + hbase mini cluster.
736    * @throws Exception
737    * @see #shutdownMiniZKCluster()
738    * @return zk cluster started.
739    */
740   public MiniZooKeeperCluster startMiniZKCluster(
741       final int zooKeeperServerNum,
742       final int ... clientPortList)
743       throws Exception {
744     setupClusterTestDir();
745     return startMiniZKCluster(clusterTestDir, zooKeeperServerNum, clientPortList);
746   }
747 
748   private MiniZooKeeperCluster startMiniZKCluster(final File dir)
749     throws Exception {
750     return startMiniZKCluster(dir, 1, null);
751   }
752 
753   /**
754    * Start a mini ZK cluster. If the property "test.hbase.zookeeper.property.clientPort" is set
755    *  the port mentionned is used as the default port for ZooKeeper.
756    */
757   private MiniZooKeeperCluster startMiniZKCluster(final File dir,
758       final int zooKeeperServerNum,
759       final int [] clientPortList)
760   throws Exception {
761     if (this.zkCluster != null) {
762       throw new IOException("Cluster already running at " + dir);
763     }
764     this.passedZkCluster = false;
765     this.zkCluster = new MiniZooKeeperCluster(this.getConfiguration());
766     final int defPort = this.conf.getInt("test.hbase.zookeeper.property.clientPort", 0);
767     if (defPort > 0){
768       // If there is a port in the config file, we use it.
769       this.zkCluster.setDefaultClientPort(defPort);
770     }
771 
772     if (clientPortList != null) {
773       // Ignore extra client ports
774       int clientPortListSize = (clientPortList.length <= zooKeeperServerNum) ?
775           clientPortList.length : zooKeeperServerNum;
776       for (int i=0; i < clientPortListSize; i++) {
777         this.zkCluster.addClientPort(clientPortList[i]);
778       }
779     }
780     int clientPort =   this.zkCluster.startup(dir,zooKeeperServerNum);
781     this.conf.set(HConstants.ZOOKEEPER_CLIENT_PORT,
782       Integer.toString(clientPort));
783     return this.zkCluster;
784   }
785 
786   /**
787    * Shuts down zk cluster created by call to {@link #startMiniZKCluster(File)}
788    * or does nothing.
789    * @throws IOException
790    * @see #startMiniZKCluster()
791    */
792   public void shutdownMiniZKCluster() throws IOException {
793     if (this.zkCluster != null) {
794       this.zkCluster.shutdown();
795       this.zkCluster = null;
796     }
797   }
798 
799   /**
800    * Start up a minicluster of hbase, dfs, and zookeeper.
801    * @throws Exception
802    * @return Mini hbase cluster instance created.
803    * @see {@link #shutdownMiniDFSCluster()}
804    */
805   public MiniHBaseCluster startMiniCluster() throws Exception {
806     return startMiniCluster(1, 1);
807   }
808 
809   /**
810    * Start up a minicluster of hbase, dfs, and zookeeper.
811    * Set the <code>create</code> flag to create root or data directory path or not
812    * (will overwrite if dir already exists)
813    * @throws Exception
814    * @return Mini hbase cluster instance created.
815    * @see {@link #shutdownMiniDFSCluster()}
816    */
817   public MiniHBaseCluster startMiniCluster(final int numSlaves, boolean create)
818   throws Exception {
819     return startMiniCluster(1, numSlaves, create);
820   }
821 
822   /**
823    * Start up a minicluster of hbase, optionally dfs, and zookeeper.
824    * Modifies Configuration.  Homes the cluster data directory under a random
825    * subdirectory in a directory under System property test.build.data.
826    * Directory is cleaned up on exit.
827    * @param numSlaves Number of slaves to start up.  We'll start this many
828    * datanodes and regionservers.  If numSlaves is > 1, then make sure
829    * hbase.regionserver.info.port is -1 (i.e. no ui per regionserver) otherwise
830    * bind errors.
831    * @throws Exception
832    * @see {@link #shutdownMiniCluster()}
833    * @return Mini hbase cluster instance created.
834    */
835   public MiniHBaseCluster startMiniCluster(final int numSlaves)
836   throws Exception {
837     return startMiniCluster(1, numSlaves, false);
838   }
839 
840   /**
841    * Start minicluster. Whether to create a new root or data dir path even if such a path
842    * has been created earlier is decided based on flag <code>create</code>
843    * @throws Exception
844    * @see {@link #shutdownMiniCluster()}
845    * @return Mini hbase cluster instance created.
846    */
847   public MiniHBaseCluster startMiniCluster(final int numMasters,
848       final int numSlaves, boolean create)
849     throws Exception {
850       return startMiniCluster(numMasters, numSlaves, null, create);
851   }
852 
853   /**
854    * start minicluster
855    * @throws Exception
856    * @see {@link #shutdownMiniCluster()}
857    * @return Mini hbase cluster instance created.
858    */
859   public MiniHBaseCluster startMiniCluster(final int numMasters,
860     final int numSlaves)
861   throws Exception {
862     return startMiniCluster(numMasters, numSlaves, null, false);
863   }
864 
865   public MiniHBaseCluster startMiniCluster(final int numMasters,
866       final int numSlaves, final String[] dataNodeHosts, boolean create)
867       throws Exception {
868     return startMiniCluster(numMasters, numSlaves, numSlaves, dataNodeHosts,
869         null, null, create);
870   }
871 
872   /**
873    * Start up a minicluster of hbase, optionally dfs, and zookeeper.
874    * Modifies Configuration.  Homes the cluster data directory under a random
875    * subdirectory in a directory under System property test.build.data.
876    * Directory is cleaned up on exit.
877    * @param numMasters Number of masters to start up.  We'll start this many
878    * hbase masters.  If numMasters > 1, you can find the active/primary master
879    * with {@link MiniHBaseCluster#getMaster()}.
880    * @param numSlaves Number of slaves to start up.  We'll start this many
881    * regionservers. If dataNodeHosts == null, this also indicates the number of
882    * datanodes to start. If dataNodeHosts != null, the number of datanodes is
883    * based on dataNodeHosts.length.
884    * If numSlaves is > 1, then make sure
885    * hbase.regionserver.info.port is -1 (i.e. no ui per regionserver) otherwise
886    * bind errors.
887    * @param dataNodeHosts hostnames DNs to run on.
888    * This is useful if you want to run datanode on distinct hosts for things
889    * like HDFS block location verification.
890    * If you start MiniDFSCluster without host names,
891    * all instances of the datanodes will have the same host name.
892    * @throws Exception
893    * @see {@link #shutdownMiniCluster()}
894    * @return Mini hbase cluster instance created.
895    */
896   public MiniHBaseCluster startMiniCluster(final int numMasters,
897       final int numSlaves, final String[] dataNodeHosts) throws Exception {
898     return startMiniCluster(numMasters, numSlaves, numSlaves, dataNodeHosts,
899         null, null);
900   }
901 
902   /**
903    * Same as {@link #startMiniCluster(int, int)}, but with custom number of datanodes.
904    * @param numDataNodes Number of data nodes.
905    */
906   public MiniHBaseCluster startMiniCluster(final int numMasters,
907       final int numSlaves, final int numDataNodes) throws Exception {
908     return startMiniCluster(numMasters, numSlaves, numDataNodes, null, null, null);
909   }
910 
911   /**
912    * Start up a minicluster of hbase, optionally dfs, and zookeeper.
913    * Modifies Configuration.  Homes the cluster data directory under a random
914    * subdirectory in a directory under System property test.build.data.
915    * Directory is cleaned up on exit.
916    * @param numMasters Number of masters to start up.  We'll start this many
917    * hbase masters.  If numMasters > 1, you can find the active/primary master
918    * with {@link MiniHBaseCluster#getMaster()}.
919    * @param numSlaves Number of slaves to start up.  We'll start this many
920    * regionservers. If dataNodeHosts == null, this also indicates the number of
921    * datanodes to start. If dataNodeHosts != null, the number of datanodes is
922    * based on dataNodeHosts.length.
923    * If numSlaves is > 1, then make sure
924    * hbase.regionserver.info.port is -1 (i.e. no ui per regionserver) otherwise
925    * bind errors.
926    * @param dataNodeHosts hostnames DNs to run on.
927    * This is useful if you want to run datanode on distinct hosts for things
928    * like HDFS block location verification.
929    * If you start MiniDFSCluster without host names,
930    * all instances of the datanodes will have the same host name.
931    * @param masterClass The class to use as HMaster, or null for default
932    * @param regionserverClass The class to use as HRegionServer, or null for
933    * default
934    * @throws Exception
935    * @see {@link #shutdownMiniCluster()}
936    * @return Mini hbase cluster instance created.
937    */
938   public MiniHBaseCluster startMiniCluster(final int numMasters,
939       final int numSlaves, final String[] dataNodeHosts, Class<? extends HMaster> masterClass,
940       Class<? extends MiniHBaseCluster.MiniHBaseClusterRegionServer> regionserverClass)
941           throws Exception {
942     return startMiniCluster(
943         numMasters, numSlaves, numSlaves, dataNodeHosts, masterClass, regionserverClass);
944   }
945 
946   public MiniHBaseCluster startMiniCluster(final int numMasters,
947       final int numSlaves, int numDataNodes, final String[] dataNodeHosts,
948       Class<? extends HMaster> masterClass,
949       Class<? extends MiniHBaseCluster.MiniHBaseClusterRegionServer> regionserverClass)
950     throws Exception {
951     return startMiniCluster(numMasters, numSlaves, numDataNodes, dataNodeHosts,
952         masterClass, regionserverClass, false);
953   }
954 
955   /**
956    * Same as {@link #startMiniCluster(int, int, String[], Class, Class)}, but with custom
957    * number of datanodes.
958    * @param numDataNodes Number of data nodes.
959    * @param create Set this flag to create a new
960    * root or data directory path or not (will overwrite if exists already).
961    */
962   public MiniHBaseCluster startMiniCluster(final int numMasters,
963     final int numSlaves, int numDataNodes, final String[] dataNodeHosts,
964     Class<? extends HMaster> masterClass,
965     Class<? extends MiniHBaseCluster.MiniHBaseClusterRegionServer> regionserverClass,
966     boolean create)
967   throws Exception {
968     if (dataNodeHosts != null && dataNodeHosts.length != 0) {
969       numDataNodes = dataNodeHosts.length;
970     }
971 
972     LOG.info("Starting up minicluster with " + numMasters + " master(s) and " +
973         numSlaves + " regionserver(s) and " + numDataNodes + " datanode(s)");
974 
975     // If we already put up a cluster, fail.
976     if (miniClusterRunning) {
977       throw new IllegalStateException("A mini-cluster is already running");
978     }
979     miniClusterRunning = true;
980 
981     setupClusterTestDir();
982     System.setProperty(TEST_DIRECTORY_KEY, this.clusterTestDir.getPath());
983 
984     // Bring up mini dfs cluster. This spews a bunch of warnings about missing
985     // scheme. Complaints are 'Scheme is undefined for build/test/data/dfs/name1'.
986     if(this.dfsCluster == null) {
987       dfsCluster = startMiniDFSCluster(numDataNodes, dataNodeHosts);
988     }
989 
990     // Start up a zk cluster.
991     if (this.zkCluster == null) {
992       startMiniZKCluster(clusterTestDir);
993     }
994 
995     // Start the MiniHBaseCluster
996     return startMiniHBaseCluster(numMasters, numSlaves, masterClass,
997       regionserverClass, create);
998   }
999 
1000   public MiniHBaseCluster startMiniHBaseCluster(final int numMasters, final int numSlaves)
1001       throws IOException, InterruptedException{
1002     return startMiniHBaseCluster(numMasters, numSlaves, null, null, false);
1003   }
1004 
1005   /**
1006    * Starts up mini hbase cluster.  Usually used after call to
1007    * {@link #startMiniCluster(int, int)} when doing stepped startup of clusters.
1008    * Usually you won't want this.  You'll usually want {@link #startMiniCluster()}.
1009    * @param numMasters
1010    * @param numSlaves
1011    * @param create Whether to create a
1012    * root or data directory path or not; will overwrite if exists already.
1013    * @return Reference to the hbase mini hbase cluster.
1014    * @throws IOException
1015    * @throws InterruptedException
1016    * @see {@link #startMiniCluster()}
1017    */
1018   public MiniHBaseCluster startMiniHBaseCluster(final int numMasters,
1019         final int numSlaves, Class<? extends HMaster> masterClass,
1020         Class<? extends MiniHBaseCluster.MiniHBaseClusterRegionServer> regionserverClass,
1021         boolean create)
1022   throws IOException, InterruptedException {
1023     // Now do the mini hbase cluster.  Set the hbase.rootdir in config.
1024     createRootDir(create);
1025 
1026     // These settings will make the server waits until this exact number of
1027     // regions servers are connected.
1028     if (conf.getInt(ServerManager.WAIT_ON_REGIONSERVERS_MINTOSTART, -1) == -1) {
1029       conf.setInt(ServerManager.WAIT_ON_REGIONSERVERS_MINTOSTART, numSlaves);
1030     }
1031     if (conf.getInt(ServerManager.WAIT_ON_REGIONSERVERS_MAXTOSTART, -1) == -1) {
1032       conf.setInt(ServerManager.WAIT_ON_REGIONSERVERS_MAXTOSTART, numSlaves);
1033     }
1034 
1035     Configuration c = new Configuration(this.conf);
1036     this.hbaseCluster =
1037         new MiniHBaseCluster(c, numMasters, numSlaves, masterClass, regionserverClass);
1038     // Don't leave here till we've done a successful scan of the hbase:meta
1039     Table t = new HTable(c, TableName.META_TABLE_NAME);
1040     ResultScanner s = t.getScanner(new Scan());
1041     while (s.next() != null) {
1042       continue;
1043     }
1044     s.close();
1045     t.close();
1046 
1047     getHBaseAdmin(); // create immediately the hbaseAdmin
1048     LOG.info("Minicluster is up");
1049 
1050     // Set the hbase.fs.tmp.dir config to make sure that we have some default value. This is
1051     // for tests that do not read hbase-defaults.xml
1052     setHBaseFsTmpDir();
1053 
1054     return (MiniHBaseCluster)this.hbaseCluster;
1055   }
1056 
1057   /**
1058    * Starts the hbase cluster up again after shutting it down previously in a
1059    * test.  Use this if you want to keep dfs/zk up and just stop/start hbase.
1060    * @param servers number of region servers
1061    * @throws IOException
1062    */
1063   public void restartHBaseCluster(int servers) throws IOException, InterruptedException {
1064     this.hbaseCluster = new MiniHBaseCluster(this.conf, servers);
1065     // Don't leave here till we've done a successful scan of the hbase:meta
1066     Table t = new HTable(new Configuration(this.conf), TableName.META_TABLE_NAME);
1067     ResultScanner s = t.getScanner(new Scan());
1068     while (s.next() != null) {
1069       // do nothing
1070     }
1071     LOG.info("HBase has been restarted");
1072     s.close();
1073     t.close();
1074   }
1075 
1076   /**
1077    * @return Current mini hbase cluster. Only has something in it after a call
1078    * to {@link #startMiniCluster()}.
1079    * @see #startMiniCluster()
1080    */
1081   public MiniHBaseCluster getMiniHBaseCluster() {
1082     if (this.hbaseCluster == null || this.hbaseCluster instanceof MiniHBaseCluster) {
1083       return (MiniHBaseCluster)this.hbaseCluster;
1084     }
1085     throw new RuntimeException(hbaseCluster + " not an instance of " +
1086                                MiniHBaseCluster.class.getName());
1087   }
1088 
1089   /**
1090    * Stops mini hbase, zk, and hdfs clusters.
1091    * @throws IOException
1092    * @see {@link #startMiniCluster(int)}
1093    */
1094   public void shutdownMiniCluster() throws Exception {
1095     LOG.info("Shutting down minicluster");
1096     if (this.connection != null && !this.connection.isClosed()) {
1097       this.connection.close();
1098       this.connection = null;
1099     }
1100     shutdownMiniHBaseCluster();
1101     if (!this.passedZkCluster){
1102       shutdownMiniZKCluster();
1103     }
1104     shutdownMiniDFSCluster();
1105 
1106     cleanupTestDir();
1107     miniClusterRunning = false;
1108     LOG.info("Minicluster is down");
1109   }
1110 
1111   /**
1112    * @return True if we removed the test dirs
1113    * @throws IOException
1114    */
1115   @Override
1116   public boolean cleanupTestDir() throws IOException {
1117     boolean ret = super.cleanupTestDir();
1118     if (deleteDir(this.clusterTestDir)) {
1119       this.clusterTestDir = null;
1120       return ret & true;
1121     }
1122     return false;
1123   }
1124 
1125   /**
1126    * Shutdown HBase mini cluster.  Does not shutdown zk or dfs if running.
1127    * @throws IOException
1128    */
1129   public void shutdownMiniHBaseCluster() throws IOException {
1130     if (hbaseAdmin != null) {
1131       hbaseAdmin.close0();
1132       hbaseAdmin = null;
1133     }
1134 
1135     // unset the configuration for MIN and MAX RS to start
1136     conf.setInt(ServerManager.WAIT_ON_REGIONSERVERS_MINTOSTART, -1);
1137     conf.setInt(ServerManager.WAIT_ON_REGIONSERVERS_MAXTOSTART, -1);
1138     if (this.hbaseCluster != null) {
1139       this.hbaseCluster.shutdown();
1140       // Wait till hbase is down before going on to shutdown zk.
1141       this.hbaseCluster.waitUntilShutDown();
1142       this.hbaseCluster = null;
1143     }
1144 
1145     if (zooKeeperWatcher != null) {
1146       zooKeeperWatcher.close();
1147       zooKeeperWatcher = null;
1148     }
1149   }
1150 
1151   /**
1152    * Returns the path to the default root dir the minicluster uses. If <code>create</code>
1153    * is true, a new root directory path is fetched irrespective of whether it has been fetched
1154    * before or not. If false, previous path is used.
1155    * Note: this does not cause the root dir to be created.
1156    * @return Fully qualified path for the default hbase root dir
1157    * @throws IOException
1158    */
1159   public Path getDefaultRootDirPath(boolean create) throws IOException {
1160     if (!create) {
1161       return getDataTestDirOnTestFS();
1162     } else {
1163       return getNewDataTestDirOnTestFS();
1164     }
1165   }
1166 
1167   /**
1168    * Same as {{@link HBaseTestingUtility#getDefaultRootDirPath(boolean create)}
1169    * except that <code>create</code> flag is false.
1170    * Note: this does not cause the root dir to be created.
1171    * @return Fully qualified path for the default hbase root dir
1172    * @throws IOException
1173    */
1174   public Path getDefaultRootDirPath() throws IOException {
1175     return getDefaultRootDirPath(false);
1176   }
1177 
1178   /**
1179    * Creates an hbase rootdir in user home directory.  Also creates hbase
1180    * version file.  Normally you won't make use of this method.  Root hbasedir
1181    * is created for you as part of mini cluster startup.  You'd only use this
1182    * method if you were doing manual operation.
1183    * @param create This flag decides whether to get a new
1184    * root or data directory path or not, if it has been fetched already.
1185    * Note : Directory will be made irrespective of whether path has been fetched or not.
1186    * If directory already exists, it will be overwritten
1187    * @return Fully qualified path to hbase root dir
1188    * @throws IOException
1189    */
1190   public Path createRootDir(boolean create) throws IOException {
1191     FileSystem fs = FileSystem.get(this.conf);
1192     Path hbaseRootdir = getDefaultRootDirPath(create);
1193     FSUtils.setRootDir(this.conf, hbaseRootdir);
1194     fs.mkdirs(hbaseRootdir);
1195     FSUtils.setVersion(fs, hbaseRootdir);
1196     return hbaseRootdir;
1197   }
1198 
1199   /**
1200    * Same as {@link HBaseTestingUtility#createRootDir(boolean create)}
1201    * except that <code>create</code> flag is false.
1202    * @return Fully qualified path to hbase root dir
1203    * @throws IOException
1204    */
1205   public Path createRootDir() throws IOException {
1206     return createRootDir(false);
1207   }
1208 
1209 
1210   private void setHBaseFsTmpDir() throws IOException {
1211     String hbaseFsTmpDirInString = this.conf.get("hbase.fs.tmp.dir");
1212     if (hbaseFsTmpDirInString == null) {
1213       this.conf.set("hbase.fs.tmp.dir",  getDataTestDirOnTestFS("hbase-staging").toString());
1214       LOG.info("Setting hbase.fs.tmp.dir to " + this.conf.get("hbase.fs.tmp.dir"));
1215     } else {
1216       LOG.info("The hbase.fs.tmp.dir is set to " + hbaseFsTmpDirInString);
1217     }
1218   }
1219 
1220   /**
1221    * Flushes all caches in the mini hbase cluster
1222    * @throws IOException
1223    */
1224   public void flush() throws IOException {
1225     getMiniHBaseCluster().flushcache();
1226   }
1227 
1228   /**
1229    * Flushes all caches in the mini hbase cluster
1230    * @throws IOException
1231    */
1232   public void flush(TableName tableName) throws IOException {
1233     getMiniHBaseCluster().flushcache(tableName);
1234   }
1235 
1236   /**
1237    * Compact all regions in the mini hbase cluster
1238    * @throws IOException
1239    */
1240   public void compact(boolean major) throws IOException {
1241     getMiniHBaseCluster().compact(major);
1242   }
1243 
1244   /**
1245    * Compact all of a table's reagion in the mini hbase cluster
1246    * @throws IOException
1247    */
1248   public void compact(TableName tableName, boolean major) throws IOException {
1249     getMiniHBaseCluster().compact(tableName, major);
1250   }
1251 
1252   /**
1253    * Create a table.
1254    * @param tableName
1255    * @param family
1256    * @return An HTable instance for the created table.
1257    * @throws IOException
1258    */
1259   public Table createTable(TableName tableName, String family)
1260   throws IOException{
1261     return createTable(tableName, new String[]{family});
1262   }
1263 
1264   /**
1265    * Create a table.
1266    * @param tableName
1267    * @param family
1268    * @return An HTable instance for the created table.
1269    * @throws IOException
1270    */
1271   public HTable createTable(byte[] tableName, byte[] family)
1272   throws IOException{
1273     return createTable(TableName.valueOf(tableName), new byte[][]{family});
1274   }
1275 
1276   /**
1277    * Create a table.
1278    * @param tableName
1279    * @param families
1280    * @return An HTable instance for the created table.
1281    * @throws IOException
1282    */
1283   public Table createTable(TableName tableName, String[] families)
1284   throws IOException {
1285     List<byte[]> fams = new ArrayList<byte[]>(families.length);
1286     for (String family : families) {
1287       fams.add(Bytes.toBytes(family));
1288     }
1289     return createTable(tableName, fams.toArray(new byte[0][]));
1290   }
1291 
1292   /**
1293    * Create a table.
1294    * @param tableName
1295    * @param family
1296    * @return An HTable instance for the created table.
1297    * @throws IOException
1298    */
1299   public HTable createTable(TableName tableName, byte[] family)
1300   throws IOException{
1301     return createTable(tableName, new byte[][]{family});
1302   }
1303 
1304   /**
1305    * Create a table with multiple regions.
1306    * @param tableName
1307    * @param family
1308    * @param numRegions
1309    * @return An HTable instance for the created table.
1310    * @throws IOException
1311    */
1312   public HTable createMultiRegionTable(TableName tableName, byte[] family, int numRegions)
1313       throws IOException {
1314     if (numRegions < 3) throw new IOException("Must create at least 3 regions");
1315     byte[] startKey = Bytes.toBytes("aaaaa");
1316     byte[] endKey = Bytes.toBytes("zzzzz");
1317     byte[][] splitKeys = Bytes.split(startKey, endKey, numRegions - 3);
1318 
1319     return createTable(tableName, new byte[][] { family }, splitKeys);
1320   }
1321 
1322 
1323   /**
1324    * Create a table.
1325    * @param tableName
1326    * @param families
1327    * @return An HTable instance for the created table.
1328    * @throws IOException
1329    */
1330   public HTable createTable(byte[] tableName, byte[][] families)
1331   throws IOException {
1332     return createTable(tableName, families,
1333         new Configuration(getConfiguration()));
1334   }
1335 
1336   /**
1337    * Create a table.
1338    * @param tableName
1339    * @param families
1340    * @return An HTable instance for the created table.
1341    * @throws IOException
1342    */
1343   public HTable createTable(TableName tableName, byte[][] families)
1344   throws IOException {
1345     return createTable(tableName, families, (byte[][]) null);
1346   }
1347 
1348   /**
1349    * Create a table with multiple regions.
1350    * @param tableName
1351    * @param families
1352    * @return An HTable instance for the created table.
1353    * @throws IOException
1354    */
1355   public HTable createMultiRegionTable(TableName tableName, byte[][] families) throws IOException {
1356     return createTable(tableName, families, KEYS_FOR_HBA_CREATE_TABLE);
1357   }
1358 
1359   /**
1360    * Create a table.
1361    * @param tableName
1362    * @param families
1363    * @param splitKeys
1364    * @return An HTable instance for the created table.
1365    * @throws IOException
1366    */
1367   public HTable createTable(TableName tableName, byte[][] families, byte[][] splitKeys)
1368       throws IOException {
1369     return createTable(tableName, families, splitKeys, new Configuration(getConfiguration()));
1370   }
1371 
1372   public HTable createTable(byte[] tableName, byte[][] families,
1373       int numVersions, byte[] startKey, byte[] endKey, int numRegions) throws IOException {
1374     return createTable(TableName.valueOf(tableName), families, numVersions,
1375         startKey, endKey, numRegions);
1376   }
1377 
1378   public HTable createTable(String tableName, byte[][] families,
1379       int numVersions, byte[] startKey, byte[] endKey, int numRegions) throws IOException {
1380     return createTable(TableName.valueOf(tableName), families, numVersions,
1381         startKey, endKey, numRegions);
1382   }
1383 
1384   public HTable createTable(TableName tableName, byte[][] families,
1385       int numVersions, byte[] startKey, byte[] endKey, int numRegions)
1386   throws IOException{
1387     HTableDescriptor desc = new HTableDescriptor(tableName);
1388     for (byte[] family : families) {
1389       HColumnDescriptor hcd = new HColumnDescriptor(family)
1390           .setMaxVersions(numVersions);
1391       desc.addFamily(hcd);
1392     }
1393     getHBaseAdmin().createTable(desc, startKey, endKey, numRegions);
1394     // HBaseAdmin only waits for regions to appear in hbase:meta we should wait until they are assigned
1395     waitUntilAllRegionsAssigned(tableName);
1396     return new HTable(getConfiguration(), tableName);
1397   }
1398 
1399   /**
1400    * Create a table.
1401    * @param htd
1402    * @param families
1403    * @param c Configuration to use
1404    * @return An HTable instance for the created table.
1405    * @throws IOException
1406    */
1407   public HTable createTable(HTableDescriptor htd, byte[][] families, Configuration c)
1408   throws IOException {
1409     return createTable(htd, families, (byte[][]) null, c);
1410   }
1411 
1412   /**
1413    * Create a table.
1414    * @param htd
1415    * @param families
1416    * @param splitKeys
1417    * @param c Configuration to use
1418    * @return An HTable instance for the created table.
1419    * @throws IOException
1420    */
1421   public HTable createTable(HTableDescriptor htd, byte[][] families, byte[][] splitKeys,
1422       Configuration c) throws IOException {
1423     for (byte[] family : families) {
1424       HColumnDescriptor hcd = new HColumnDescriptor(family);
1425       // Disable blooms (they are on by default as of 0.95) but we disable them here because
1426       // tests have hard coded counts of what to expect in block cache, etc., and blooms being
1427       // on is interfering.
1428       hcd.setBloomFilterType(BloomType.NONE);
1429       htd.addFamily(hcd);
1430     }
1431     getHBaseAdmin().createTable(htd, splitKeys);
1432     // HBaseAdmin only waits for regions to appear in hbase:meta we should wait until they are
1433     // assigned
1434     waitUntilAllRegionsAssigned(htd.getTableName());
1435     return (HTable) getConnection().getTable(htd.getTableName());
1436   }
1437 
1438   /**
1439    * Create a table.
1440    * @param htd
1441    * @param splitRows
1442    * @return An HTable instance for the created table.
1443    * @throws IOException
1444    */
1445   public HTable createTable(HTableDescriptor htd, byte[][] splitRows)
1446       throws IOException {
1447     getHBaseAdmin().createTable(htd, splitRows);
1448     // HBaseAdmin only waits for regions to appear in hbase:meta we should wait until they are assigned
1449     waitUntilAllRegionsAssigned(htd.getTableName());
1450     return new HTable(getConfiguration(), htd.getTableName());
1451   }
1452 
1453   /**
1454    * Create a table.
1455    * @param tableName
1456    * @param families
1457    * @param c Configuration to use
1458    * @return An HTable instance for the created table.
1459    * @throws IOException
1460    */
1461   public HTable createTable(TableName tableName, byte[][] families,
1462       final Configuration c)
1463   throws IOException {
1464     return createTable(tableName, families, (byte[][]) null, c);
1465   }
1466 
1467   /**
1468    * Create a table.
1469    * @param tableName
1470    * @param families
1471    * @param splitKeys
1472    * @param c Configuration to use
1473    * @return An HTable instance for the created table.
1474    * @throws IOException
1475    */
1476   public HTable createTable(TableName tableName, byte[][] families, byte[][] splitKeys,
1477       final Configuration c) throws IOException {
1478     return createTable(new HTableDescriptor(tableName), families, splitKeys, c);
1479   }
1480 
1481   /**
1482    * Create a table.
1483    * @param tableName
1484    * @param families
1485    * @param c Configuration to use
1486    * @return An HTable instance for the created table.
1487    * @throws IOException
1488    */
1489   public HTable createTable(byte[] tableName, byte[][] families,
1490       final Configuration c)
1491   throws IOException {
1492     HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
1493     for(byte[] family : families) {
1494       HColumnDescriptor hcd = new HColumnDescriptor(family);
1495       // Disable blooms (they are on by default as of 0.95) but we disable them here because
1496       // tests have hard coded counts of what to expect in block cache, etc., and blooms being
1497       // on is interfering.
1498       hcd.setBloomFilterType(BloomType.NONE);
1499       desc.addFamily(hcd);
1500     }
1501     getHBaseAdmin().createTable(desc);
1502     return new HTable(c, desc.getTableName());
1503   }
1504 
1505   /**
1506    * Create a table.
1507    * @param tableName
1508    * @param families
1509    * @param c Configuration to use
1510    * @param numVersions
1511    * @return An HTable instance for the created table.
1512    * @throws IOException
1513    */
1514   public HTable createTable(TableName tableName, byte[][] families,
1515       final Configuration c, int numVersions)
1516   throws IOException {
1517     HTableDescriptor desc = new HTableDescriptor(tableName);
1518     for(byte[] family : families) {
1519       HColumnDescriptor hcd = new HColumnDescriptor(family)
1520           .setMaxVersions(numVersions);
1521       desc.addFamily(hcd);
1522     }
1523     getHBaseAdmin().createTable(desc);
1524     // HBaseAdmin only waits for regions to appear in hbase:meta we should wait until they are assigned
1525     waitUntilAllRegionsAssigned(tableName);
1526     return new HTable(c, tableName);
1527   }
1528 
1529   /**
1530    * Create a table.
1531    * @param tableName
1532    * @param families
1533    * @param c Configuration to use
1534    * @param numVersions
1535    * @return An HTable instance for the created table.
1536    * @throws IOException
1537    */
1538   public HTable createTable(byte[] tableName, byte[][] families,
1539       final Configuration c, int numVersions)
1540   throws IOException {
1541     HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
1542     for(byte[] family : families) {
1543       HColumnDescriptor hcd = new HColumnDescriptor(family)
1544           .setMaxVersions(numVersions);
1545       desc.addFamily(hcd);
1546     }
1547     getHBaseAdmin().createTable(desc);
1548     return new HTable(c, desc.getTableName());
1549   }
1550 
1551   /**
1552    * Create a table.
1553    * @param tableName
1554    * @param family
1555    * @param numVersions
1556    * @return An HTable instance for the created table.
1557    * @throws IOException
1558    */
1559   public HTable createTable(byte[] tableName, byte[] family, int numVersions)
1560   throws IOException {
1561     return createTable(tableName, new byte[][]{family}, numVersions);
1562   }
1563 
1564   /**
1565    * Create a table.
1566    * @param tableName
1567    * @param family
1568    * @param numVersions
1569    * @return An HTable instance for the created table.
1570    * @throws IOException
1571    */
1572   public HTable createTable(TableName tableName, byte[] family, int numVersions)
1573   throws IOException {
1574     return createTable(tableName, new byte[][]{family}, numVersions);
1575   }
1576 
1577   /**
1578    * Create a table.
1579    * @param tableName
1580    * @param families
1581    * @param numVersions
1582    * @return An HTable instance for the created table.
1583    * @throws IOException
1584    */
1585   public HTable createTable(byte[] tableName, byte[][] families,
1586       int numVersions)
1587   throws IOException {
1588     return createTable(TableName.valueOf(tableName), families, numVersions);
1589   }
1590 
1591   /**
1592    * Create a table.
1593    * @param tableName
1594    * @param families
1595    * @param numVersions
1596    * @return An HTable instance for the created table.
1597    * @throws IOException
1598    */
1599   public HTable createTable(TableName tableName, byte[][] families,
1600       int numVersions)
1601   throws IOException {
1602     return createTable(tableName, families, numVersions, (byte[][]) null);
1603   }
1604 
1605   /**
1606    * Create a table.
1607    * @param tableName
1608    * @param families
1609    * @param numVersions
1610    * @param splitKeys
1611    * @return An HTable instance for the created table.
1612    * @throws IOException
1613    */
1614   public HTable createTable(TableName tableName, byte[][] families, int numVersions,
1615       byte[][] splitKeys) throws IOException {
1616     HTableDescriptor desc = new HTableDescriptor(tableName);
1617     for (byte[] family : families) {
1618       HColumnDescriptor hcd = new HColumnDescriptor(family).setMaxVersions(numVersions);
1619       desc.addFamily(hcd);
1620     }
1621     getHBaseAdmin().createTable(desc, splitKeys);
1622     // HBaseAdmin only waits for regions to appear in hbase:meta we should wait until they are assigned
1623     waitUntilAllRegionsAssigned(tableName);
1624     return new HTable(new Configuration(getConfiguration()), tableName);
1625   }
1626 
1627   /**
1628    * Create a table with multiple regions.
1629    * @param tableName
1630    * @param families
1631    * @param numVersions
1632    * @return An HTable instance for the created table.
1633    * @throws IOException
1634    */
1635   public HTable createMultiRegionTable(TableName tableName, byte[][] families, int numVersions)
1636       throws IOException {
1637     return createTable(tableName, families, numVersions, KEYS_FOR_HBA_CREATE_TABLE);
1638   }
1639 
1640   /**
1641    * Create a table.
1642    * @param tableName
1643    * @param families
1644    * @param numVersions
1645    * @param blockSize
1646    * @return An HTable instance for the created table.
1647    * @throws IOException
1648    */
1649   public HTable createTable(byte[] tableName, byte[][] families,
1650     int numVersions, int blockSize) throws IOException {
1651     return createTable(TableName.valueOf(tableName),
1652         families, numVersions, blockSize);
1653   }
1654 
1655   /**
1656    * Create a table.
1657    * @param tableName
1658    * @param families
1659    * @param numVersions
1660    * @param blockSize
1661    * @return An HTable instance for the created table.
1662    * @throws IOException
1663    */
1664   public HTable createTable(TableName tableName, byte[][] families,
1665     int numVersions, int blockSize) throws IOException {
1666     HTableDescriptor desc = new HTableDescriptor(tableName);
1667     for (byte[] family : families) {
1668       HColumnDescriptor hcd = new HColumnDescriptor(family)
1669           .setMaxVersions(numVersions)
1670           .setBlocksize(blockSize);
1671       desc.addFamily(hcd);
1672     }
1673     getHBaseAdmin().createTable(desc);
1674     // HBaseAdmin only waits for regions to appear in hbase:meta we should wait until they are assigned
1675     waitUntilAllRegionsAssigned(tableName);
1676     return new HTable(new Configuration(getConfiguration()), tableName);
1677   }
1678 
1679   /**
1680    * Create a table.
1681    * @param tableName
1682    * @param families
1683    * @param numVersions
1684    * @return An HTable instance for the created table.
1685    * @throws IOException
1686    */
1687   public HTable createTable(byte[] tableName, byte[][] families,
1688       int[] numVersions)
1689   throws IOException {
1690     return createTable(TableName.valueOf(tableName), families, numVersions);
1691   }
1692 
1693   /**
1694    * Create a table.
1695    * @param tableName
1696    * @param families
1697    * @param numVersions
1698    * @return An HTable instance for the created table.
1699    * @throws IOException
1700    */
1701   public HTable createTable(TableName tableName, byte[][] families,
1702       int[] numVersions)
1703   throws IOException {
1704     HTableDescriptor desc = new HTableDescriptor(tableName);
1705     int i = 0;
1706     for (byte[] family : families) {
1707       HColumnDescriptor hcd = new HColumnDescriptor(family)
1708           .setMaxVersions(numVersions[i]);
1709       desc.addFamily(hcd);
1710       i++;
1711     }
1712     getHBaseAdmin().createTable(desc);
1713     // HBaseAdmin only waits for regions to appear in hbase:meta we should wait until they are assigned
1714     waitUntilAllRegionsAssigned(tableName);
1715     return new HTable(new Configuration(getConfiguration()), tableName);
1716   }
1717 
1718   /**
1719    * Create a table.
1720    * @param tableName
1721    * @param family
1722    * @param splitRows
1723    * @return An HTable instance for the created table.
1724    * @throws IOException
1725    */
1726   public HTable createTable(byte[] tableName, byte[] family, byte[][] splitRows)
1727     throws IOException{
1728     return createTable(TableName.valueOf(tableName), family, splitRows);
1729   }
1730 
1731   /**
1732    * Create a table.
1733    * @param tableName
1734    * @param family
1735    * @param splitRows
1736    * @return An HTable instance for the created table.
1737    * @throws IOException
1738    */
1739   public HTable createTable(TableName tableName, byte[] family, byte[][] splitRows)
1740       throws IOException {
1741     HTableDescriptor desc = new HTableDescriptor(tableName);
1742     HColumnDescriptor hcd = new HColumnDescriptor(family);
1743     desc.addFamily(hcd);
1744     getHBaseAdmin().createTable(desc, splitRows);
1745     // HBaseAdmin only waits for regions to appear in hbase:meta we should wait until they are assigned
1746     waitUntilAllRegionsAssigned(tableName);
1747     return new HTable(getConfiguration(), tableName);
1748   }
1749 
1750   /**
1751    * Create a table with multiple regions.
1752    * @param tableName
1753    * @param family
1754    * @return An HTable instance for the created table.
1755    * @throws IOException
1756    */
1757   public HTable createMultiRegionTable(TableName tableName, byte[] family) throws IOException {
1758     return createTable(tableName, family, KEYS_FOR_HBA_CREATE_TABLE);
1759   }
1760 
1761   /**
1762    * Create a table.
1763    * @param tableName
1764    * @param families
1765    * @param splitRows
1766    * @return An HTable instance for the created table.
1767    * @throws IOException
1768    */
1769   public HTable createTable(byte[] tableName, byte[][] families, byte[][] splitRows)
1770       throws IOException {
1771     HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
1772     for(byte[] family:families) {
1773       HColumnDescriptor hcd = new HColumnDescriptor(family);
1774       desc.addFamily(hcd);
1775     }
1776     getHBaseAdmin().createTable(desc, splitRows);
1777     // HBaseAdmin only waits for regions to appear in hbase:meta we should wait until they are assigned
1778     waitUntilAllRegionsAssigned(desc.getTableName());
1779     return new HTable(getConfiguration(), desc.getTableName());
1780   }
1781 
1782   /**
1783    * Create an unmanaged WAL. Be sure to close it when you're through.
1784    */
1785   public static WAL createWal(final Configuration conf, final Path rootDir, final HRegionInfo hri)
1786       throws IOException {
1787     // The WAL subsystem will use the default rootDir rather than the passed in rootDir
1788     // unless I pass along via the conf.
1789     Configuration confForWAL = new Configuration(conf);
1790     confForWAL.set(HConstants.HBASE_DIR, rootDir.toString());
1791     return (new WALFactory(confForWAL,
1792         Collections.<WALActionsListener>singletonList(new MetricsWAL()),
1793         "hregion-" + RandomStringUtils.randomNumeric(8))).
1794         getWAL(hri.getEncodedNameAsBytes());
1795   }
1796 
1797   /**
1798    * Create a region with it's own WAL. Be sure to call
1799    * {@link HBaseTestingUtility#closeRegionAndWAL(HRegion)} to clean up all resources.
1800    */
1801   public static HRegion createRegionAndWAL(final HRegionInfo info, final Path rootDir,
1802       final Configuration conf, final HTableDescriptor htd) throws IOException {
1803     return createRegionAndWAL(info, rootDir, conf, htd, true);
1804   }
1805 
1806   /**
1807    * Create a region with it's own WAL. Be sure to call
1808    * {@link HBaseTestingUtility#closeRegionAndWAL(HRegion)} to clean up all resources.
1809    */
1810   public static HRegion createRegionAndWAL(final HRegionInfo info, final Path rootDir,
1811       final Configuration conf, final HTableDescriptor htd, boolean initialize)
1812       throws IOException {
1813     WAL wal = createWal(conf, rootDir, info);
1814     return HRegion.createHRegion(info, rootDir, conf, htd, wal, initialize);
1815   }
1816 
1817   /**
1818    * Close both the region {@code r} and it's underlying WAL. For use in tests.
1819    */
1820   public static void closeRegionAndWAL(final Region r) throws IOException {
1821     closeRegionAndWAL((HRegion)r);
1822   }
1823 
1824   /**
1825    * Close both the HRegion {@code r} and it's underlying WAL. For use in tests.
1826    */
1827   public static void closeRegionAndWAL(final HRegion r) throws IOException {
1828     if (r == null) return;
1829     r.close();
1830     if (r.getWAL() == null) return;
1831     r.getWAL().close();
1832   }
1833 
1834   /**
1835    * Modify a table, synchronous. Waiting logic similar to that of {@code admin.rb#alter_status}.
1836    */
1837   @SuppressWarnings("serial")
1838   public static void modifyTableSync(Admin admin, HTableDescriptor desc)
1839       throws IOException, InterruptedException {
1840     admin.modifyTable(desc.getTableName(), desc);
1841     Pair<Integer, Integer> status = new Pair<Integer, Integer>() {{
1842       setFirst(0);
1843       setSecond(0);
1844     }};
1845     int i = 0;
1846     do {
1847       status = admin.getAlterStatus(desc.getTableName());
1848       if (status.getSecond() != 0) {
1849         LOG.debug(status.getSecond() - status.getFirst() + "/" + status.getSecond()
1850           + " regions updated.");
1851         Thread.sleep(1 * 1000l);
1852       } else {
1853         LOG.debug("All regions updated.");
1854         break;
1855       }
1856     } while (status.getFirst() != 0 && i++ < 500);
1857     if (status.getFirst() != 0) {
1858       throw new IOException("Failed to update all regions even after 500 seconds.");
1859     }
1860   }
1861 
1862   /**
1863    * Set the number of Region replicas.
1864    */
1865   public static void setReplicas(Admin admin, TableName table, int replicaCount)
1866       throws IOException, InterruptedException {
1867     admin.disableTable(table);
1868     HTableDescriptor desc = admin.getTableDescriptor(table);
1869     desc.setRegionReplication(replicaCount);
1870     admin.modifyTable(desc.getTableName(), desc);
1871     admin.enableTable(table);
1872   }
1873 
1874   /**
1875    * Drop an existing table
1876    * @param tableName existing table
1877    */
1878   public void deleteTable(String tableName) throws IOException {
1879     deleteTable(TableName.valueOf(tableName));
1880   }
1881 
1882   /**
1883    * Drop an existing table
1884    * @param tableName existing table
1885    */
1886   public void deleteTable(byte[] tableName) throws IOException {
1887     deleteTable(TableName.valueOf(tableName));
1888   }
1889 
1890   /**
1891    * Drop an existing table
1892    * @param tableName existing table
1893    */
1894   public void deleteTable(TableName tableName) throws IOException {
1895     try {
1896       getHBaseAdmin().disableTable(tableName);
1897     } catch (TableNotEnabledException e) {
1898       LOG.debug("Table: " + tableName + " already disabled, so just deleting it.");
1899     }
1900     getHBaseAdmin().deleteTable(tableName);
1901   }
1902 
1903   /**
1904    * Drop an existing table
1905    * @param tableName existing table
1906    */
1907   public void deleteTableIfAny(TableName tableName) throws IOException {
1908     try {
1909       deleteTable(tableName);
1910     } catch (TableNotFoundException e) {
1911       // ignore
1912     }
1913   }
1914 
1915   // ==========================================================================
1916   // Canned table and table descriptor creation
1917   // TODO replace HBaseTestCase
1918 
1919   public final static byte [] fam1 = Bytes.toBytes("colfamily11");
1920   public final static byte [] fam2 = Bytes.toBytes("colfamily21");
1921   public final static byte [] fam3 = Bytes.toBytes("colfamily31");
1922   public static final byte[][] COLUMNS = {fam1, fam2, fam3};
1923   private static final int MAXVERSIONS = 3;
1924 
1925   public static final char FIRST_CHAR = 'a';
1926   public static final char LAST_CHAR = 'z';
1927   public static final byte [] START_KEY_BYTES = {FIRST_CHAR, FIRST_CHAR, FIRST_CHAR};
1928   public static final String START_KEY = new String(START_KEY_BYTES, HConstants.UTF8_CHARSET);
1929 
1930   /**
1931    * Create a table of name <code>name</code> with {@link COLUMNS} for
1932    * families.
1933    * @param name Name to give table.
1934    * @param versions How many versions to allow per column.
1935    * @return Column descriptor.
1936    */
1937   public HTableDescriptor createTableDescriptor(final String name,
1938       final int minVersions, final int versions, final int ttl, KeepDeletedCells keepDeleted) {
1939     HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(name));
1940     for (byte[] cfName : new byte[][]{ fam1, fam2, fam3 }) {
1941       htd.addFamily(new HColumnDescriptor(cfName)
1942           .setMinVersions(minVersions)
1943           .setMaxVersions(versions)
1944           .setKeepDeletedCells(keepDeleted)
1945           .setBlockCacheEnabled(false)
1946           .setTimeToLive(ttl)
1947       );
1948     }
1949     return htd;
1950   }
1951 
1952   /**
1953    * Create a table of name <code>name</code> with {@link COLUMNS} for
1954    * families.
1955    * @param name Name to give table.
1956    * @return Column descriptor.
1957    */
1958   public HTableDescriptor createTableDescriptor(final String name) {
1959     return createTableDescriptor(name,  HColumnDescriptor.DEFAULT_MIN_VERSIONS,
1960         MAXVERSIONS, HConstants.FOREVER, HColumnDescriptor.DEFAULT_KEEP_DELETED);
1961   }
1962 
1963   /**
1964    * Create an HRegion. Be sure to call {@link HBaseTestingUtility#closeRegion(Region)}
1965    * when you're finished with it.
1966    */
1967   public HRegion createHRegion(
1968       final HRegionInfo info,
1969       final Path rootDir,
1970       final Configuration conf,
1971       final HTableDescriptor htd) throws IOException {
1972     return HRegion.createHRegion(info, rootDir, conf, htd);
1973   }
1974 
1975   public HTableDescriptor createTableDescriptor(final TableName tableName,
1976       byte[] family) {
1977     return createTableDescriptor(tableName, new byte[][] {family}, 1);
1978   }
1979 
1980   public HTableDescriptor createTableDescriptor(final TableName tableName,
1981       byte[][] families, int maxVersions) {
1982     HTableDescriptor desc = new HTableDescriptor(tableName);
1983     for (byte[] family : families) {
1984       HColumnDescriptor hcd = new HColumnDescriptor(family)
1985           .setMaxVersions(maxVersions);
1986       desc.addFamily(hcd);
1987     }
1988     return desc;
1989   }
1990 
1991   /**
1992    * Create an HRegion that writes to the local tmp dirs
1993    * @param desc
1994    * @param startKey
1995    * @param endKey
1996    * @return
1997    * @throws IOException
1998    */
1999   public HRegion createLocalHRegion(HTableDescriptor desc, byte [] startKey,
2000       byte [] endKey)
2001   throws IOException {
2002     HRegionInfo hri = new HRegionInfo(desc.getTableName(), startKey, endKey);
2003     return createLocalHRegion(hri, desc);
2004   }
2005 
2006   /**
2007    * Create an HRegion that writes to the local tmp dirs
2008    * @param info
2009    * @param desc
2010    * @return
2011    * @throws IOException
2012    */
2013   public HRegion createLocalHRegion(HRegionInfo info, HTableDescriptor desc) throws IOException {
2014     return HRegion.createHRegion(info, getDataTestDir(), getConfiguration(), desc);
2015   }
2016 
2017   /**
2018    * Create an HRegion that writes to the local tmp dirs with specified wal
2019    * @param info regioninfo
2020    * @param desc table descriptor
2021    * @param wal wal for this region.
2022    * @return created hregion
2023    * @throws IOException
2024    */
2025   public HRegion createLocalHRegion(HRegionInfo info, HTableDescriptor desc, WAL wal)
2026       throws IOException {
2027     return HRegion.createHRegion(info, getDataTestDir(), getConfiguration(), desc, wal);
2028   }
2029 
2030   /**
2031    * @param tableName
2032    * @param startKey
2033    * @param stopKey
2034    * @param callingMethod
2035    * @param conf
2036    * @param isReadOnly
2037    * @param families
2038    * @throws IOException
2039    * @return A region on which you must call
2040    *         {@link HRegion#closeHRegion(HRegion)} when done.
2041    */
2042   public HRegion createLocalHRegion(byte[] tableName, byte[] startKey, byte[] stopKey,
2043       String callingMethod, Configuration conf, boolean isReadOnly, Durability durability,
2044       WAL wal, byte[]... families) throws IOException {
2045     HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(tableName));
2046     htd.setReadOnly(isReadOnly);
2047     for (byte[] family : families) {
2048       HColumnDescriptor hcd = new HColumnDescriptor(family);
2049       // Set default to be three versions.
2050       hcd.setMaxVersions(Integer.MAX_VALUE);
2051       htd.addFamily(hcd);
2052     }
2053     htd.setDurability(durability);
2054     HRegionInfo info = new HRegionInfo(htd.getTableName(), startKey, stopKey, false);
2055     return createLocalHRegion(info, htd, wal);
2056   }
2057   //
2058   // ==========================================================================
2059 
2060   /**
2061    * Provide an existing table name to truncate.
2062    * Scans the table and issues a delete for each row read.
2063    * @param tableName existing table
2064    * @return HTable to that new table
2065    * @throws IOException
2066    */
2067   public HTable deleteTableData(byte[] tableName) throws IOException {
2068     return deleteTableData(TableName.valueOf(tableName));
2069   }
2070 
2071   /**
2072    * Provide an existing table name to truncate.
2073    * Scans the table and issues a delete for each row read.
2074    * @param tableName existing table
2075    * @return HTable to that new table
2076    * @throws IOException
2077    */
2078   public HTable deleteTableData(TableName tableName) throws IOException {
2079     HTable table = new HTable(getConfiguration(), tableName);
2080     Scan scan = new Scan();
2081     ResultScanner resScan = table.getScanner(scan);
2082     for(Result res : resScan) {
2083       Delete del = new Delete(res.getRow());
2084       table.delete(del);
2085     }
2086     resScan = table.getScanner(scan);
2087     resScan.close();
2088     return table;
2089   }
2090 
2091   /**
2092    * Truncate a table using the admin command.
2093    * Effectively disables, deletes, and recreates the table.
2094    * @param tableName table which must exist.
2095    * @param preserveRegions keep the existing split points
2096    * @return HTable for the new table
2097    */
2098   public HTable truncateTable(final TableName tableName, final boolean preserveRegions)
2099       throws IOException {
2100     Admin admin = getHBaseAdmin();
2101     if (!admin.isTableDisabled(tableName)) {
2102       admin.disableTable(tableName);
2103     }
2104     admin.truncateTable(tableName, preserveRegions);
2105     return new HTable(getConfiguration(), tableName);
2106   }
2107 
2108   /**
2109    * Truncate a table using the admin command.
2110    * Effectively disables, deletes, and recreates the table.
2111    * For previous behavior of issuing row deletes, see
2112    * deleteTableData.
2113    * Expressly does not preserve regions of existing table.
2114    * @param tableName table which must exist.
2115    * @return HTable for the new table
2116    */
2117   public HTable truncateTable(final TableName tableName) throws IOException {
2118     return truncateTable(tableName, false);
2119   }
2120 
2121   /**
2122    * Truncate a table using the admin command.
2123    * Effectively disables, deletes, and recreates the table.
2124    * @param tableName table which must exist.
2125    * @param preserveRegions keep the existing split points
2126    * @return HTable for the new table
2127    */
2128   public HTable truncateTable(final byte[] tableName, final boolean preserveRegions)
2129       throws IOException {
2130     return truncateTable(TableName.valueOf(tableName), preserveRegions);
2131   }
2132 
2133   /**
2134    * Truncate a table using the admin command.
2135    * Effectively disables, deletes, and recreates the table.
2136    * For previous behavior of issuing row deletes, see
2137    * deleteTableData.
2138    * Expressly does not preserve regions of existing table.
2139    * @param tableName table which must exist.
2140    * @return HTable for the new table
2141    */
2142   public HTable truncateTable(final byte[] tableName) throws IOException {
2143     return truncateTable(tableName, false);
2144   }
2145 
2146   /**
2147    * Load table with rows from 'aaa' to 'zzz'.
2148    * @param t Table
2149    * @param f Family
2150    * @return Count of rows loaded.
2151    * @throws IOException
2152    */
2153   public int loadTable(final Table t, final byte[] f) throws IOException {
2154     return loadTable(t, new byte[][] {f});
2155   }
2156 
2157   /**
2158    * Load table with rows from 'aaa' to 'zzz'.
2159    * @param t Table
2160    * @param f Family
2161    * @return Count of rows loaded.
2162    * @throws IOException
2163    */
2164   public int loadTable(final Table t, final byte[] f, boolean writeToWAL) throws IOException {
2165     return loadTable(t, new byte[][] {f}, null, writeToWAL);
2166   }
2167 
2168   /**
2169    * Load table of multiple column families with rows from 'aaa' to 'zzz'.
2170    * @param t Table
2171    * @param f Array of Families to load
2172    * @return Count of rows loaded.
2173    * @throws IOException
2174    */
2175   public int loadTable(final Table t, final byte[][] f) throws IOException {
2176     return loadTable(t, f, null);
2177   }
2178 
2179   /**
2180    * Load table of multiple column families with rows from 'aaa' to 'zzz'.
2181    * @param t Table
2182    * @param f Array of Families to load
2183    * @param value the values of the cells. If null is passed, the row key is used as value
2184    * @return Count of rows loaded.
2185    * @throws IOException
2186    */
2187   public int loadTable(final Table t, final byte[][] f, byte[] value) throws IOException {
2188     return loadTable(t, f, value, true);
2189   }
2190 
2191   /**
2192    * Load table of multiple column families with rows from 'aaa' to 'zzz'.
2193    * @param t Table
2194    * @param f Array of Families to load
2195    * @param value the values of the cells. If null is passed, the row key is used as value
2196    * @return Count of rows loaded.
2197    * @throws IOException
2198    */
2199   public int loadTable(final Table t, final byte[][] f, byte[] value, boolean writeToWAL) throws IOException {
2200     List<Put> puts = new ArrayList<>();
2201     for (byte[] row : HBaseTestingUtility.ROWS) {
2202       Put put = new Put(row);
2203       put.setDurability(writeToWAL ? Durability.USE_DEFAULT : Durability.SKIP_WAL);
2204       for (int i = 0; i < f.length; i++) {
2205         put.add(f[i], f[i], value != null ? value : row);
2206       }
2207       puts.add(put);
2208     }
2209     t.put(puts);
2210     return puts.size();
2211   }
2212 
2213   /** A tracker for tracking and validating table rows
2214    * generated with {@link HBaseTestingUtility#loadTable(HTable, byte[])}
2215    */
2216   public static class SeenRowTracker {
2217     int dim = 'z' - 'a' + 1;
2218     int[][][] seenRows = new int[dim][dim][dim]; //count of how many times the row is seen
2219     byte[] startRow;
2220     byte[] stopRow;
2221 
2222     public SeenRowTracker(byte[] startRow, byte[] stopRow) {
2223       this.startRow = startRow;
2224       this.stopRow = stopRow;
2225     }
2226 
2227     void reset() {
2228       for (byte[] row : ROWS) {
2229         seenRows[i(row[0])][i(row[1])][i(row[2])] = 0;
2230       }
2231     }
2232 
2233     int i(byte b) {
2234       return b - 'a';
2235     }
2236 
2237     public void addRow(byte[] row) {
2238       seenRows[i(row[0])][i(row[1])][i(row[2])]++;
2239     }
2240 
2241     /** Validate that all the rows between startRow and stopRow are seen exactly once, and
2242      * all other rows none
2243      */
2244     public void validate() {
2245       for (byte b1 = 'a'; b1 <= 'z'; b1++) {
2246         for (byte b2 = 'a'; b2 <= 'z'; b2++) {
2247           for (byte b3 = 'a'; b3 <= 'z'; b3++) {
2248             int count = seenRows[i(b1)][i(b2)][i(b3)];
2249             int expectedCount = 0;
2250             if (Bytes.compareTo(new byte[] {b1,b2,b3}, startRow) >= 0
2251                 && Bytes.compareTo(new byte[] {b1,b2,b3}, stopRow) < 0) {
2252               expectedCount = 1;
2253             }
2254             if (count != expectedCount) {
2255               String row = new String(new byte[] {b1,b2,b3});
2256               throw new RuntimeException("Row:" + row + " has a seen count of " + count + " instead of " + expectedCount);
2257             }
2258           }
2259         }
2260       }
2261     }
2262   }
2263 
2264   public int loadRegion(final HRegion r, final byte[] f) throws IOException {
2265     return loadRegion(r, f, false);
2266   }
2267 
2268   public int loadRegion(final Region r, final byte[] f) throws IOException {
2269     return loadRegion((HRegion)r, f);
2270   }
2271 
2272   /**
2273    * Load region with rows from 'aaa' to 'zzz'.
2274    * @param r Region
2275    * @param f Family
2276    * @param flush flush the cache if true
2277    * @return Count of rows loaded.
2278    * @throws IOException
2279    */
2280   public int loadRegion(final HRegion r, final byte[] f, final boolean flush)
2281   throws IOException {
2282     byte[] k = new byte[3];
2283     int rowCount = 0;
2284     for (byte b1 = 'a'; b1 <= 'z'; b1++) {
2285       for (byte b2 = 'a'; b2 <= 'z'; b2++) {
2286         for (byte b3 = 'a'; b3 <= 'z'; b3++) {
2287           k[0] = b1;
2288           k[1] = b2;
2289           k[2] = b3;
2290           Put put = new Put(k);
2291           put.setDurability(Durability.SKIP_WAL);
2292           put.add(f, null, k);
2293           if (r.getWAL() == null) {
2294             put.setDurability(Durability.SKIP_WAL);
2295           }
2296           int preRowCount = rowCount;
2297           int pause = 10;
2298           int maxPause = 1000;
2299           while (rowCount == preRowCount) {
2300             try {
2301               r.put(put);
2302               rowCount++;
2303             } catch (RegionTooBusyException e) {
2304               pause = (pause * 2 >= maxPause) ? maxPause : pause * 2;
2305               Threads.sleep(pause);
2306             }
2307           }
2308         }
2309       }
2310       if (flush) {
2311         r.flush(true);
2312       }
2313     }
2314     return rowCount;
2315   }
2316 
2317   public void loadNumericRows(final Table t, final byte[] f, int startRow, int endRow)
2318       throws IOException {
2319     for (int i = startRow; i < endRow; i++) {
2320       byte[] data = Bytes.toBytes(String.valueOf(i));
2321       Put put = new Put(data);
2322       put.add(f, null, data);
2323       t.put(put);
2324     }
2325   }
2326 
2327   public void verifyNumericRows(Table table, final byte[] f, int startRow, int endRow,
2328       int replicaId)
2329       throws IOException {
2330     for (int i = startRow; i < endRow; i++) {
2331       String failMsg = "Failed verification of row :" + i;
2332       byte[] data = Bytes.toBytes(String.valueOf(i));
2333       Get get = new Get(data);
2334       get.setReplicaId(replicaId);
2335       get.setConsistency(Consistency.TIMELINE);
2336       Result result = table.get(get);
2337       assertTrue(failMsg, result.containsColumn(f, null));
2338       assertEquals(failMsg, result.getColumnCells(f, null).size(), 1);
2339       Cell cell = result.getColumnLatestCell(f, null);
2340       assertTrue(failMsg,
2341         Bytes.equals(data, 0, data.length, cell.getValueArray(), cell.getValueOffset(),
2342           cell.getValueLength()));
2343     }
2344   }
2345 
2346   public void verifyNumericRows(Region region, final byte[] f, int startRow, int endRow)
2347       throws IOException {
2348     verifyNumericRows((HRegion)region, f, startRow, endRow);
2349   }
2350 
2351   public void verifyNumericRows(HRegion region, final byte[] f, int startRow, int endRow)
2352       throws IOException {
2353     verifyNumericRows(region, f, startRow, endRow, true);
2354   }
2355 
2356   public void verifyNumericRows(Region region, final byte[] f, int startRow, int endRow,
2357       final boolean present) throws IOException {
2358     verifyNumericRows((HRegion)region, f, startRow, endRow, present);
2359   }
2360 
2361   public void verifyNumericRows(HRegion region, final byte[] f, int startRow, int endRow,
2362       final boolean present) throws IOException {
2363     for (int i = startRow; i < endRow; i++) {
2364       String failMsg = "Failed verification of row :" + i;
2365       byte[] data = Bytes.toBytes(String.valueOf(i));
2366       Result result = region.get(new Get(data));
2367 
2368       boolean hasResult = result != null && !result.isEmpty();
2369       assertEquals(failMsg + result, present, hasResult);
2370       if (!present) continue;
2371 
2372       assertTrue(failMsg, result.containsColumn(f, null));
2373       assertEquals(failMsg, result.getColumnCells(f, null).size(), 1);
2374       Cell cell = result.getColumnLatestCell(f, null);
2375       assertTrue(failMsg,
2376         Bytes.equals(data, 0, data.length, cell.getValueArray(), cell.getValueOffset(),
2377           cell.getValueLength()));
2378     }
2379   }
2380 
2381   public void deleteNumericRows(final HTable t, final byte[] f, int startRow, int endRow)
2382       throws IOException {
2383     for (int i = startRow; i < endRow; i++) {
2384       byte[] data = Bytes.toBytes(String.valueOf(i));
2385       Delete delete = new Delete(data);
2386       delete.deleteFamily(f);
2387       t.delete(delete);
2388     }
2389   }
2390 
2391   /**
2392    * Return the number of rows in the given table.
2393    */
2394   public int countRows(final Table table) throws IOException {
2395     Scan scan = new Scan();
2396     ResultScanner results = table.getScanner(scan);
2397     int count = 0;
2398     for (@SuppressWarnings("unused") Result res : results) {
2399       count++;
2400     }
2401     results.close();
2402     return count;
2403   }
2404 
2405   public int countRows(final Table table, final byte[]... families) throws IOException {
2406     Scan scan = new Scan();
2407     for (byte[] family: families) {
2408       scan.addFamily(family);
2409     }
2410     ResultScanner results = table.getScanner(scan);
2411     int count = 0;
2412     for (@SuppressWarnings("unused") Result res : results) {
2413       count++;
2414     }
2415     results.close();
2416     return count;
2417   }
2418 
2419   /**
2420    * Return the number of rows in the given table.
2421    */
2422   public int countRows(final TableName tableName) throws IOException {
2423     Table table = getConnection().getTable(tableName);
2424     try {
2425       return countRows(table);
2426     } finally {
2427       table.close();
2428     }
2429   }
2430 
2431   /**
2432    * Return an md5 digest of the entire contents of a table.
2433    */
2434   public String checksumRows(final Table table) throws Exception {
2435     Scan scan = new Scan();
2436     ResultScanner results = table.getScanner(scan);
2437     MessageDigest digest = MessageDigest.getInstance("MD5");
2438     for (Result res : results) {
2439       digest.update(res.getRow());
2440     }
2441     results.close();
2442     return digest.toString();
2443   }
2444 
2445   /** All the row values for the data loaded by {@link #loadTable(HTable, byte[])} */
2446   public static final byte[][] ROWS = new byte[(int) Math.pow('z' - 'a' + 1, 3)][3]; // ~52KB
2447   static {
2448     int i = 0;
2449     for (byte b1 = 'a'; b1 <= 'z'; b1++) {
2450       for (byte b2 = 'a'; b2 <= 'z'; b2++) {
2451         for (byte b3 = 'a'; b3 <= 'z'; b3++) {
2452           ROWS[i][0] = b1;
2453           ROWS[i][1] = b2;
2454           ROWS[i][2] = b3;
2455           i++;
2456         }
2457       }
2458     }
2459   }
2460 
2461   public static final byte[][] KEYS = {
2462     HConstants.EMPTY_BYTE_ARRAY, Bytes.toBytes("bbb"),
2463     Bytes.toBytes("ccc"), Bytes.toBytes("ddd"), Bytes.toBytes("eee"),
2464     Bytes.toBytes("fff"), Bytes.toBytes("ggg"), Bytes.toBytes("hhh"),
2465     Bytes.toBytes("iii"), Bytes.toBytes("jjj"), Bytes.toBytes("kkk"),
2466     Bytes.toBytes("lll"), Bytes.toBytes("mmm"), Bytes.toBytes("nnn"),
2467     Bytes.toBytes("ooo"), Bytes.toBytes("ppp"), Bytes.toBytes("qqq"),
2468     Bytes.toBytes("rrr"), Bytes.toBytes("sss"), Bytes.toBytes("ttt"),
2469     Bytes.toBytes("uuu"), Bytes.toBytes("vvv"), Bytes.toBytes("www"),
2470     Bytes.toBytes("xxx"), Bytes.toBytes("yyy")
2471   };
2472 
2473   public static final byte[][] KEYS_FOR_HBA_CREATE_TABLE = {
2474       Bytes.toBytes("bbb"),
2475       Bytes.toBytes("ccc"), Bytes.toBytes("ddd"), Bytes.toBytes("eee"),
2476       Bytes.toBytes("fff"), Bytes.toBytes("ggg"), Bytes.toBytes("hhh"),
2477       Bytes.toBytes("iii"), Bytes.toBytes("jjj"), Bytes.toBytes("kkk"),
2478       Bytes.toBytes("lll"), Bytes.toBytes("mmm"), Bytes.toBytes("nnn"),
2479       Bytes.toBytes("ooo"), Bytes.toBytes("ppp"), Bytes.toBytes("qqq"),
2480       Bytes.toBytes("rrr"), Bytes.toBytes("sss"), Bytes.toBytes("ttt"),
2481       Bytes.toBytes("uuu"), Bytes.toBytes("vvv"), Bytes.toBytes("www"),
2482       Bytes.toBytes("xxx"), Bytes.toBytes("yyy"), Bytes.toBytes("zzz")
2483   };
2484 
2485   /**
2486    * Create rows in hbase:meta for regions of the specified table with the specified
2487    * start keys.  The first startKey should be a 0 length byte array if you
2488    * want to form a proper range of regions.
2489    * @param conf
2490    * @param htd
2491    * @param startKeys
2492    * @return list of region info for regions added to meta
2493    * @throws IOException
2494    */
2495   public List<HRegionInfo> createMultiRegionsInMeta(final Configuration conf,
2496       final HTableDescriptor htd, byte [][] startKeys)
2497   throws IOException {
2498     Table meta = new HTable(conf, TableName.META_TABLE_NAME);
2499     Arrays.sort(startKeys, Bytes.BYTES_COMPARATOR);
2500     List<HRegionInfo> newRegions = new ArrayList<HRegionInfo>(startKeys.length);
2501     // add custom ones
2502     for (int i = 0; i < startKeys.length; i++) {
2503       int j = (i + 1) % startKeys.length;
2504       HRegionInfo hri = new HRegionInfo(htd.getTableName(), startKeys[i],
2505           startKeys[j]);
2506       MetaTableAccessor.addRegionToMeta(meta, hri);
2507       newRegions.add(hri);
2508     }
2509 
2510     meta.close();
2511     return newRegions;
2512   }
2513 
2514   /**
2515    * Returns all rows from the hbase:meta table.
2516    *
2517    * @throws IOException When reading the rows fails.
2518    */
2519   public List<byte[]> getMetaTableRows() throws IOException {
2520     // TODO: Redo using MetaTableAccessor class
2521     Table t = new HTable(new Configuration(this.conf), TableName.META_TABLE_NAME);
2522     List<byte[]> rows = new ArrayList<byte[]>();
2523     ResultScanner s = t.getScanner(new Scan());
2524     for (Result result : s) {
2525       LOG.info("getMetaTableRows: row -> " +
2526         Bytes.toStringBinary(result.getRow()));
2527       rows.add(result.getRow());
2528     }
2529     s.close();
2530     t.close();
2531     return rows;
2532   }
2533 
2534   /**
2535    * Returns all rows from the hbase:meta table for a given user table
2536    *
2537    * @throws IOException When reading the rows fails.
2538    */
2539   public List<byte[]> getMetaTableRows(TableName tableName) throws IOException {
2540     // TODO: Redo using MetaTableAccessor.
2541     Table t = new HTable(new Configuration(this.conf), TableName.META_TABLE_NAME);
2542     List<byte[]> rows = new ArrayList<byte[]>();
2543     ResultScanner s = t.getScanner(new Scan());
2544     for (Result result : s) {
2545       HRegionInfo info = HRegionInfo.getHRegionInfo(result);
2546       if (info == null) {
2547         LOG.error("No region info for row " + Bytes.toString(result.getRow()));
2548         // TODO figure out what to do for this new hosed case.
2549         continue;
2550       }
2551 
2552       if (info.getTable().equals(tableName)) {
2553         LOG.info("getMetaTableRows: row -> " +
2554             Bytes.toStringBinary(result.getRow()) + info);
2555         rows.add(result.getRow());
2556       }
2557     }
2558     s.close();
2559     t.close();
2560     return rows;
2561   }
2562 
2563   /**
2564    * Tool to get the reference to the region server object that holds the
2565    * region of the specified user table.
2566    * It first searches for the meta rows that contain the region of the
2567    * specified table, then gets the index of that RS, and finally retrieves
2568    * the RS's reference.
2569    * @param tableName user table to lookup in hbase:meta
2570    * @return region server that holds it, null if the row doesn't exist
2571    * @throws IOException
2572    * @throws InterruptedException
2573    */
2574   public HRegionServer getRSForFirstRegionInTable(TableName tableName)
2575       throws IOException, InterruptedException {
2576     List<byte[]> metaRows = getMetaTableRows(tableName);
2577     if (metaRows == null || metaRows.isEmpty()) {
2578       return null;
2579     }
2580     LOG.debug("Found " + metaRows.size() + " rows for table " +
2581       tableName);
2582     byte [] firstrow = metaRows.get(0);
2583     LOG.debug("FirstRow=" + Bytes.toString(firstrow));
2584     long pause = getConfiguration().getLong(HConstants.HBASE_CLIENT_PAUSE,
2585       HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
2586     int numRetries = getConfiguration().getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
2587       HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
2588     RetryCounter retrier = new RetryCounter(numRetries+1, (int)pause, TimeUnit.MICROSECONDS);
2589     while(retrier.shouldRetry()) {
2590       int index = getMiniHBaseCluster().getServerWith(firstrow);
2591       if (index != -1) {
2592         return getMiniHBaseCluster().getRegionServerThreads().get(index).getRegionServer();
2593       }
2594       // Came back -1.  Region may not be online yet.  Sleep a while.
2595       retrier.sleepUntilNextRetry();
2596     }
2597     return null;
2598   }
2599 
2600   /**
2601    * Starts a <code>MiniMRCluster</code> with a default number of
2602    * <code>TaskTracker</code>'s.
2603    *
2604    * @throws IOException When starting the cluster fails.
2605    */
2606   public MiniMRCluster startMiniMapReduceCluster() throws IOException {
2607     startMiniMapReduceCluster(2);
2608     return mrCluster;
2609   }
2610 
2611   /**
2612    * Tasktracker has a bug where changing the hadoop.log.dir system property
2613    * will not change its internal static LOG_DIR variable.
2614    */
2615   private void forceChangeTaskLogDir() {
2616     Field logDirField;
2617     try {
2618       logDirField = TaskLog.class.getDeclaredField("LOG_DIR");
2619       logDirField.setAccessible(true);
2620 
2621       Field modifiersField = Field.class.getDeclaredField("modifiers");
2622       modifiersField.setAccessible(true);
2623       modifiersField.setInt(logDirField, logDirField.getModifiers() & ~Modifier.FINAL);
2624 
2625       logDirField.set(null, new File(hadoopLogDir, "userlogs"));
2626     } catch (SecurityException e) {
2627       throw new RuntimeException(e);
2628     } catch (NoSuchFieldException e) {
2629       // TODO Auto-generated catch block
2630       throw new RuntimeException(e);
2631     } catch (IllegalArgumentException e) {
2632       throw new RuntimeException(e);
2633     } catch (IllegalAccessException e) {
2634       throw new RuntimeException(e);
2635     }
2636   }
2637 
2638   /**
2639    * Starts a <code>MiniMRCluster</code>. Call {@link #setFileSystemURI(String)} to use a different
2640    * filesystem.
2641    * @param servers  The number of <code>TaskTracker</code>'s to start.
2642    * @throws IOException When starting the cluster fails.
2643    */
2644   private void startMiniMapReduceCluster(final int servers) throws IOException {
2645     if (mrCluster != null) {
2646       throw new IllegalStateException("MiniMRCluster is already running");
2647     }
2648     LOG.info("Starting mini mapreduce cluster...");
2649     setupClusterTestDir();
2650     createDirsAndSetProperties();
2651 
2652     forceChangeTaskLogDir();
2653 
2654     //// hadoop2 specific settings
2655     // Tests were failing because this process used 6GB of virtual memory and was getting killed.
2656     // we up the VM usable so that processes don't get killed.
2657     conf.setFloat("yarn.nodemanager.vmem-pmem-ratio", 8.0f);
2658 
2659     // Tests were failing due to MAPREDUCE-4880 / MAPREDUCE-4607 against hadoop 2.0.2-alpha and
2660     // this avoids the problem by disabling speculative task execution in tests.
2661     conf.setBoolean("mapreduce.map.speculative", false);
2662     conf.setBoolean("mapreduce.reduce.speculative", false);
2663     ////
2664 
2665     // Allow the user to override FS URI for this map-reduce cluster to use.
2666     mrCluster = new MiniMRCluster(servers,
2667       FS_URI != null ? FS_URI : FileSystem.get(conf).getUri().toString(), 1,
2668       null, null, new JobConf(this.conf));
2669     JobConf jobConf = MapreduceTestingShim.getJobConf(mrCluster);
2670     if (jobConf == null) {
2671       jobConf = mrCluster.createJobConf();
2672     }
2673 
2674     jobConf.set("mapreduce.cluster.local.dir",
2675       conf.get("mapreduce.cluster.local.dir")); //Hadoop MiniMR overwrites this while it should not
2676     LOG.info("Mini mapreduce cluster started");
2677 
2678     // In hadoop2, YARN/MR2 starts a mini cluster with its own conf instance and updates settings.
2679     // Our HBase MR jobs need several of these settings in order to properly run.  So we copy the
2680     // necessary config properties here.  YARN-129 required adding a few properties.
2681     conf.set("mapreduce.jobtracker.address", jobConf.get("mapreduce.jobtracker.address"));
2682     // this for mrv2 support; mr1 ignores this
2683     conf.set("mapreduce.framework.name", "yarn");
2684     conf.setBoolean("yarn.is.minicluster", true);
2685     String rmAddress = jobConf.get("yarn.resourcemanager.address");
2686     if (rmAddress != null) {
2687       conf.set("yarn.resourcemanager.address", rmAddress);
2688     }
2689     String historyAddress = jobConf.get("mapreduce.jobhistory.address");
2690     if (historyAddress != null) {
2691       conf.set("mapreduce.jobhistory.address", historyAddress);
2692     }
2693     String schedulerAddress =
2694       jobConf.get("yarn.resourcemanager.scheduler.address");
2695     if (schedulerAddress != null) {
2696       conf.set("yarn.resourcemanager.scheduler.address", schedulerAddress);
2697     }
2698     String mrJobHistoryWebappAddress =
2699       jobConf.get("mapreduce.jobhistory.webapp.address");
2700     if (mrJobHistoryWebappAddress != null) {
2701       conf.set("mapreduce.jobhistory.webapp.address", mrJobHistoryWebappAddress);
2702     }
2703     String yarnRMWebappAddress =
2704       jobConf.get("yarn.resourcemanager.webapp.address");
2705     if (yarnRMWebappAddress != null) {
2706       conf.set("yarn.resourcemanager.webapp.address", yarnRMWebappAddress);
2707     }
2708   }
2709 
2710   /**
2711    * Stops the previously started <code>MiniMRCluster</code>.
2712    */
2713   public void shutdownMiniMapReduceCluster() {
2714     if (mrCluster != null) {
2715       LOG.info("Stopping mini mapreduce cluster...");
2716       mrCluster.shutdown();
2717       mrCluster = null;
2718       LOG.info("Mini mapreduce cluster stopped");
2719     }
2720     // Restore configuration to point to local jobtracker
2721     conf.set("mapreduce.jobtracker.address", "local");
2722   }
2723 
2724   /**
2725    * Create a stubbed out RegionServerService, mainly for getting FS.
2726    */
2727   public RegionServerServices createMockRegionServerService() throws IOException {
2728     return createMockRegionServerService((ServerName)null);
2729   }
2730 
2731   /**
2732    * Create a stubbed out RegionServerService, mainly for getting FS.
2733    * This version is used by TestTokenAuthentication
2734    */
2735   public RegionServerServices createMockRegionServerService(RpcServerInterface rpc) throws IOException {
2736     final MockRegionServerServices rss = new MockRegionServerServices(getZooKeeperWatcher());
2737     rss.setFileSystem(getTestFileSystem());
2738     rss.setRpcServer(rpc);
2739     return rss;
2740   }
2741 
2742   /**
2743    * Create a stubbed out RegionServerService, mainly for getting FS.
2744    * This version is used by TestOpenRegionHandler
2745    */
2746   public RegionServerServices createMockRegionServerService(ServerName name) throws IOException {
2747     final MockRegionServerServices rss = new MockRegionServerServices(getZooKeeperWatcher(), name);
2748     rss.setFileSystem(getTestFileSystem());
2749     return rss;
2750   }
2751 
2752   /**
2753    * Switches the logger for the given class to DEBUG level.
2754    *
2755    * @param clazz  The class for which to switch to debug logging.
2756    */
2757   public void enableDebug(Class<?> clazz) {
2758     Log l = LogFactory.getLog(clazz);
2759     if (l instanceof Log4JLogger) {
2760       ((Log4JLogger) l).getLogger().setLevel(org.apache.log4j.Level.DEBUG);
2761     } else if (l instanceof Jdk14Logger) {
2762       ((Jdk14Logger) l).getLogger().setLevel(java.util.logging.Level.ALL);
2763     }
2764   }
2765 
2766   /**
2767    * Expire the Master's session
2768    * @throws Exception
2769    */
2770   public void expireMasterSession() throws Exception {
2771     HMaster master = getMiniHBaseCluster().getMaster();
2772     expireSession(master.getZooKeeper(), false);
2773   }
2774 
2775   /**
2776    * Expire a region server's session
2777    * @param index which RS
2778    * @throws Exception
2779    */
2780   public void expireRegionServerSession(int index) throws Exception {
2781     HRegionServer rs = getMiniHBaseCluster().getRegionServer(index);
2782     expireSession(rs.getZooKeeper(), false);
2783     decrementMinRegionServerCount();
2784   }
2785 
2786   private void decrementMinRegionServerCount() {
2787     // decrement the count for this.conf, for newly spwaned master
2788     // this.hbaseCluster shares this configuration too
2789     decrementMinRegionServerCount(getConfiguration());
2790 
2791     // each master thread keeps a copy of configuration
2792     for (MasterThread master : getHBaseCluster().getMasterThreads()) {
2793       decrementMinRegionServerCount(master.getMaster().getConfiguration());
2794     }
2795   }
2796 
2797   private void decrementMinRegionServerCount(Configuration conf) {
2798     int currentCount = conf.getInt(
2799         ServerManager.WAIT_ON_REGIONSERVERS_MINTOSTART, -1);
2800     if (currentCount != -1) {
2801       conf.setInt(ServerManager.WAIT_ON_REGIONSERVERS_MINTOSTART,
2802           Math.max(currentCount - 1, 1));
2803     }
2804   }
2805 
2806   public void expireSession(ZooKeeperWatcher nodeZK) throws Exception {
2807    expireSession(nodeZK, false);
2808   }
2809 
2810   @Deprecated
2811   public void expireSession(ZooKeeperWatcher nodeZK, Server server)
2812     throws Exception {
2813     expireSession(nodeZK, false);
2814   }
2815 
2816   /**
2817    * Expire a ZooKeeper session as recommended in ZooKeeper documentation
2818    * http://wiki.apache.org/hadoop/ZooKeeper/FAQ#A4
2819    * There are issues when doing this:
2820    * [1] http://www.mail-archive.com/dev@zookeeper.apache.org/msg01942.html
2821    * [2] https://issues.apache.org/jira/browse/ZOOKEEPER-1105
2822    *
2823    * @param nodeZK - the ZK watcher to expire
2824    * @param checkStatus - true to check if we can create an HTable with the
2825    *                    current configuration.
2826    */
2827   public void expireSession(ZooKeeperWatcher nodeZK, boolean checkStatus)
2828     throws Exception {
2829     Configuration c = new Configuration(this.conf);
2830     String quorumServers = ZKConfig.getZKQuorumServersString(c);
2831     ZooKeeper zk = nodeZK.getRecoverableZooKeeper().getZooKeeper();
2832     byte[] password = zk.getSessionPasswd();
2833     long sessionID = zk.getSessionId();
2834 
2835     // Expiry seems to be asynchronous (see comment from P. Hunt in [1]),
2836     //  so we create a first watcher to be sure that the
2837     //  event was sent. We expect that if our watcher receives the event
2838     //  other watchers on the same machine will get is as well.
2839     // When we ask to close the connection, ZK does not close it before
2840     //  we receive all the events, so don't have to capture the event, just
2841     //  closing the connection should be enough.
2842     ZooKeeper monitor = new ZooKeeper(quorumServers,
2843       1000, new org.apache.zookeeper.Watcher(){
2844       @Override
2845       public void process(WatchedEvent watchedEvent) {
2846         LOG.info("Monitor ZKW received event="+watchedEvent);
2847       }
2848     } , sessionID, password);
2849 
2850     // Making it expire
2851     ZooKeeper newZK = new ZooKeeper(quorumServers,
2852         1000, EmptyWatcher.instance, sessionID, password);
2853 
2854     //ensure that we have connection to the server before closing down, otherwise
2855     //the close session event will be eaten out before we start CONNECTING state
2856     long start = System.currentTimeMillis();
2857     while (newZK.getState() != States.CONNECTED
2858          && System.currentTimeMillis() - start < 1000) {
2859        Thread.sleep(1);
2860     }
2861     newZK.close();
2862     LOG.info("ZK Closed Session 0x" + Long.toHexString(sessionID));
2863 
2864     // Now closing & waiting to be sure that the clients get it.
2865     monitor.close();
2866 
2867     if (checkStatus) {
2868       new HTable(new Configuration(conf), TableName.META_TABLE_NAME).close();
2869     }
2870   }
2871 
2872   /**
2873    * Get the Mini HBase cluster.
2874    *
2875    * @return hbase cluster
2876    * @see #getHBaseClusterInterface()
2877    */
2878   public MiniHBaseCluster getHBaseCluster() {
2879     return getMiniHBaseCluster();
2880   }
2881 
2882   /**
2883    * Returns the HBaseCluster instance.
2884    * <p>Returned object can be any of the subclasses of HBaseCluster, and the
2885    * tests referring this should not assume that the cluster is a mini cluster or a
2886    * distributed one. If the test only works on a mini cluster, then specific
2887    * method {@link #getMiniHBaseCluster()} can be used instead w/o the
2888    * need to type-cast.
2889    */
2890   public HBaseCluster getHBaseClusterInterface() {
2891     //implementation note: we should rename this method as #getHBaseCluster(),
2892     //but this would require refactoring 90+ calls.
2893     return hbaseCluster;
2894   }
2895 
2896   /**
2897    * Get a Connection to the cluster.
2898    * Not thread-safe (This class needs a lot of work to make it thread-safe).
2899    * @return A Connection that can be shared. Don't close. Will be closed on shutdown of cluster.
2900    * @throws IOException
2901    */
2902   public Connection getConnection() throws IOException {
2903     if (this.connection == null) {
2904       this.connection = ConnectionFactory.createConnection(this.conf);
2905     }
2906     return this.connection;
2907   }
2908 
2909   /**
2910    * Returns a Admin instance.
2911    * This instance is shared between HBaseTestingUtility instance users.
2912    * Closing it has no effect, it will be closed automatically when the
2913    * cluster shutdowns
2914    *
2915    * @return An Admin instance.
2916    * @throws IOException
2917    */
2918   public synchronized HBaseAdmin getHBaseAdmin()
2919   throws IOException {
2920     if (hbaseAdmin == null){
2921       this.hbaseAdmin = new HBaseAdminForTests(getConnection());
2922     }
2923     return hbaseAdmin;
2924   }
2925 
2926   private HBaseAdminForTests hbaseAdmin = null;
2927   private static class HBaseAdminForTests extends HBaseAdmin {
2928     public HBaseAdminForTests(Connection connection) throws MasterNotRunningException,
2929         ZooKeeperConnectionException, IOException {
2930       super(connection);
2931     }
2932 
2933     @Override
2934     public synchronized void close() throws IOException {
2935       LOG.warn("close() called on HBaseAdmin instance returned from " +
2936         "HBaseTestingUtility.getHBaseAdmin()");
2937     }
2938 
2939     private synchronized void close0() throws IOException {
2940       super.close();
2941     }
2942   }
2943 
2944   /**
2945    * Returns a ZooKeeperWatcher instance.
2946    * This instance is shared between HBaseTestingUtility instance users.
2947    * Don't close it, it will be closed automatically when the
2948    * cluster shutdowns
2949    *
2950    * @return The ZooKeeperWatcher instance.
2951    * @throws IOException
2952    */
2953   public synchronized ZooKeeperWatcher getZooKeeperWatcher()
2954     throws IOException {
2955     if (zooKeeperWatcher == null) {
2956       zooKeeperWatcher = new ZooKeeperWatcher(conf, "testing utility",
2957         new Abortable() {
2958         @Override public void abort(String why, Throwable e) {
2959           throw new RuntimeException("Unexpected abort in HBaseTestingUtility:"+why, e);
2960         }
2961         @Override public boolean isAborted() {return false;}
2962       });
2963     }
2964     return zooKeeperWatcher;
2965   }
2966   private ZooKeeperWatcher zooKeeperWatcher;
2967 
2968 
2969 
2970   /**
2971    * Closes the named region.
2972    *
2973    * @param regionName  The region to close.
2974    * @throws IOException
2975    */
2976   public void closeRegion(String regionName) throws IOException {
2977     closeRegion(Bytes.toBytes(regionName));
2978   }
2979 
2980   /**
2981    * Closes the named region.
2982    *
2983    * @param regionName  The region to close.
2984    * @throws IOException
2985    */
2986   public void closeRegion(byte[] regionName) throws IOException {
2987     getHBaseAdmin().closeRegion(regionName, null);
2988   }
2989 
2990   /**
2991    * Closes the region containing the given row.
2992    *
2993    * @param row  The row to find the containing region.
2994    * @param table  The table to find the region.
2995    * @throws IOException
2996    */
2997   public void closeRegionByRow(String row, RegionLocator table) throws IOException {
2998     closeRegionByRow(Bytes.toBytes(row), table);
2999   }
3000 
3001   /**
3002    * Closes the region containing the given row.
3003    *
3004    * @param row  The row to find the containing region.
3005    * @param table  The table to find the region.
3006    * @throws IOException
3007    */
3008   public void closeRegionByRow(byte[] row, RegionLocator table) throws IOException {
3009     HRegionLocation hrl = table.getRegionLocation(row);
3010     closeRegion(hrl.getRegionInfo().getRegionName());
3011   }
3012 
3013   /*
3014    * Retrieves a splittable region randomly from tableName
3015    *
3016    * @param tableName name of table
3017    * @param maxAttempts maximum number of attempts, unlimited for value of -1
3018    * @return the HRegion chosen, null if none was found within limit of maxAttempts
3019    */
3020   public HRegion getSplittableRegion(TableName tableName, int maxAttempts) {
3021     List<HRegion> regions = getHBaseCluster().getRegions(tableName);
3022     int regCount = regions.size();
3023     Set<Integer> attempted = new HashSet<Integer>();
3024     int idx;
3025     int attempts = 0;
3026     do {
3027       regions = getHBaseCluster().getRegions(tableName);
3028       if (regCount != regions.size()) {
3029         // if there was region movement, clear attempted Set
3030         attempted.clear();
3031       }
3032       regCount = regions.size();
3033       // There are chances that before we get the region for the table from an RS the region may
3034       // be going for CLOSE.  This may be because online schema change is enabled
3035       if (regCount > 0) {
3036         idx = random.nextInt(regCount);
3037         // if we have just tried this region, there is no need to try again
3038         if (attempted.contains(idx))
3039           continue;
3040         try {
3041           regions.get(idx).checkSplit();
3042           return regions.get(idx);
3043         } catch (Exception ex) {
3044           LOG.warn("Caught exception", ex);
3045           attempted.add(idx);
3046         }
3047       }
3048       attempts++;
3049     } while (maxAttempts == -1 || attempts < maxAttempts);
3050     return null;
3051   }
3052 
3053   public MiniZooKeeperCluster getZkCluster() {
3054     return zkCluster;
3055   }
3056 
3057   public void setZkCluster(MiniZooKeeperCluster zkCluster) {
3058     this.passedZkCluster = true;
3059     this.zkCluster = zkCluster;
3060     conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, zkCluster.getClientPort());
3061   }
3062 
3063   public MiniDFSCluster getDFSCluster() {
3064     return dfsCluster;
3065   }
3066 
3067   public void setDFSCluster(MiniDFSCluster cluster) throws IllegalStateException, IOException {
3068     setDFSCluster(cluster, true);
3069   }
3070 
3071   /**
3072    * Set the MiniDFSCluster
3073    * @param cluster cluster to use
3074    * @param requireDown require the that cluster not be "up" (MiniDFSCluster#isClusterUp) before
3075    * it is set.
3076    * @throws IllegalStateException if the passed cluster is up when it is required to be down
3077    * @throws IOException if the FileSystem could not be set from the passed dfs cluster
3078    */
3079   public void setDFSCluster(MiniDFSCluster cluster, boolean requireDown)
3080       throws IllegalStateException, IOException {
3081     if (dfsCluster != null && requireDown && dfsCluster.isClusterUp()) {
3082       throw new IllegalStateException("DFSCluster is already running! Shut it down first.");
3083     }
3084     this.dfsCluster = cluster;
3085     this.setFs();
3086   }
3087 
3088   public FileSystem getTestFileSystem() throws IOException {
3089     return HFileSystem.get(conf);
3090   }
3091 
3092   /**
3093    * Wait until all regions in a table have been assigned.  Waits default timeout before giving up
3094    * (30 seconds).
3095    * @param table Table to wait on.
3096    * @throws InterruptedException
3097    * @throws IOException
3098    */
3099   public void waitTableAvailable(TableName table)
3100       throws InterruptedException, IOException {
3101     waitTableAvailable(table.getName(), 30000);
3102   }
3103 
3104   public void waitTableAvailable(TableName table, long timeoutMillis)
3105       throws InterruptedException, IOException {
3106     waitFor(timeoutMillis, predicateTableAvailable(table));
3107   }
3108 
3109   public String explainTableAvailability(TableName tableName) throws IOException {
3110     String msg = explainTableState(tableName) + ",";
3111     if (getHBaseCluster().getMaster().isAlive()) {
3112       Map<HRegionInfo, ServerName> assignments =
3113           getHBaseCluster().getMaster().getAssignmentManager().getRegionStates()
3114               .getRegionAssignments();
3115       final List<Pair<HRegionInfo, ServerName>> metaLocations =
3116           MetaTableAccessor
3117               .getTableRegionsAndLocations(getZooKeeperWatcher(), connection, tableName);
3118       for (Pair<HRegionInfo, ServerName> metaLocation : metaLocations) {
3119         HRegionInfo hri = metaLocation.getFirst();
3120         ServerName sn = metaLocation.getSecond();
3121         if (!assignments.containsKey(hri)) {
3122           msg += ", region " + hri
3123               + " not assigned, but found in meta, it expected to be on " + sn;
3124 
3125         } else if (sn == null) {
3126           msg += ",  region " + hri
3127               + " assigned,  but has no server in meta";
3128         } else if (!sn.equals(assignments.get(hri))) {
3129           msg += ",  region " + hri
3130               + " assigned,  but has different servers in meta and AM ( " +
3131               sn + " <> " + assignments.get(hri);
3132         }
3133       }
3134     }
3135     return msg;
3136   }
3137 
3138   public String explainTableState(TableName tableName) throws IOException {
3139     try {
3140       if (getHBaseAdmin().isTableEnabled(tableName))
3141         return "table enabled in zk";
3142       else if (getHBaseAdmin().isTableDisabled(tableName))
3143         return "table disabled in zk";
3144       else
3145         return "table in uknown state";
3146     } catch (TableNotFoundException e) {
3147       return "table not exists";
3148     }
3149   }
3150 
3151   /**
3152    * Wait until all regions in a table have been assigned
3153    * @param table Table to wait on.
3154    * @param timeoutMillis Timeout.
3155    * @throws InterruptedException
3156    * @throws IOException
3157    */
3158   public void waitTableAvailable(byte[] table, long timeoutMillis)
3159   throws InterruptedException, IOException {
3160     waitTableAvailable(getHBaseAdmin(), table, timeoutMillis);
3161   }
3162 
3163   public void waitTableAvailable(Admin admin, byte[] table, long timeoutMillis)
3164   throws InterruptedException, IOException {
3165     long startWait = System.currentTimeMillis();
3166     while (!admin.isTableAvailable(TableName.valueOf(table))) {
3167       assertTrue("Timed out waiting for table to become available " +
3168         Bytes.toStringBinary(table),
3169         System.currentTimeMillis() - startWait < timeoutMillis);
3170       Thread.sleep(200);
3171     }
3172   }
3173 
3174   /**
3175    * Waits for a table to be 'enabled'.  Enabled means that table is set as 'enabled' and the
3176    * regions have been all assigned.  Will timeout after default period (30 seconds)
3177    * @see #waitTableAvailable(byte[])
3178    * @param table Table to wait on.
3179    * @param table
3180    * @throws InterruptedException
3181    * @throws IOException
3182    */
3183   public void waitTableEnabled(TableName table)
3184       throws InterruptedException, IOException {
3185     waitTableEnabled(table, 30000);
3186   }
3187 
3188   /**
3189    * Waits for a table to be 'enabled'.  Enabled means that table is set as 'enabled' and the
3190    * regions have been all assigned.
3191    * @see #waitTableAvailable(byte[])
3192    * @param table Table to wait on.
3193    * @param timeoutMillis Time to wait on it being marked enabled.
3194    * @throws InterruptedException
3195    * @throws IOException
3196    */
3197   public void waitTableEnabled(byte[] table, long timeoutMillis)
3198   throws InterruptedException, IOException {
3199     waitTableEnabled(TableName.valueOf(table), timeoutMillis);
3200   }
3201 
3202   public void waitTableEnabled(TableName table, long timeoutMillis)
3203       throws IOException {
3204     waitFor(timeoutMillis, predicateTableEnabled(table));
3205   }
3206 
3207   /**
3208    * Waits for a table to be 'disabled'.  Disabled means that table is set as 'disabled'
3209    * Will timeout after default period (30 seconds)
3210    * @param table Table to wait on.
3211    * @throws InterruptedException
3212    * @throws IOException
3213    */
3214   public void waitTableDisabled(byte[] table)
3215       throws InterruptedException, IOException {
3216     waitTableDisabled(getHBaseAdmin(), table, 30000);
3217   }
3218 
3219   public void waitTableDisabled(Admin admin, byte[] table)
3220       throws InterruptedException, IOException {
3221     waitTableDisabled(admin, table, 30000);
3222   }
3223 
3224   /**
3225    * Waits for a table to be 'disabled'.  Disabled means that table is set as 'disabled'
3226    * @param table Table to wait on.
3227    * @param timeoutMillis Time to wait on it being marked disabled.
3228    * @throws InterruptedException
3229    * @throws IOException
3230    */
3231   public void waitTableDisabled(byte[] table, long timeoutMillis)
3232       throws InterruptedException, IOException {
3233     waitTableDisabled(getHBaseAdmin(), table, timeoutMillis);
3234   }
3235 
3236   public void waitTableDisabled(Admin admin, byte[] table, long timeoutMillis)
3237       throws InterruptedException, IOException {
3238     TableName tableName = TableName.valueOf(table);
3239     long startWait = System.currentTimeMillis();
3240     while (!admin.isTableDisabled(tableName)) {
3241       assertTrue("Timed out waiting for table to become disabled " +
3242               Bytes.toStringBinary(table),
3243           System.currentTimeMillis() - startWait < timeoutMillis);
3244       Thread.sleep(200);
3245     }
3246   }
3247 
3248   /**
3249    * Make sure that at least the specified number of region servers
3250    * are running
3251    * @param num minimum number of region servers that should be running
3252    * @return true if we started some servers
3253    * @throws IOException
3254    */
3255   public boolean ensureSomeRegionServersAvailable(final int num)
3256       throws IOException {
3257     boolean startedServer = false;
3258     MiniHBaseCluster hbaseCluster = getMiniHBaseCluster();
3259     for (int i=hbaseCluster.getLiveRegionServerThreads().size(); i<num; ++i) {
3260       LOG.info("Started new server=" + hbaseCluster.startRegionServer());
3261       startedServer = true;
3262     }
3263 
3264     return startedServer;
3265   }
3266 
3267 
3268   /**
3269    * Make sure that at least the specified number of region servers
3270    * are running. We don't count the ones that are currently stopping or are
3271    * stopped.
3272    * @param num minimum number of region servers that should be running
3273    * @return true if we started some servers
3274    * @throws IOException
3275    */
3276   public boolean ensureSomeNonStoppedRegionServersAvailable(final int num)
3277     throws IOException {
3278     boolean startedServer = ensureSomeRegionServersAvailable(num);
3279 
3280     int nonStoppedServers = 0;
3281     for (JVMClusterUtil.RegionServerThread rst :
3282       getMiniHBaseCluster().getRegionServerThreads()) {
3283 
3284       HRegionServer hrs = rst.getRegionServer();
3285       if (hrs.isStopping() || hrs.isStopped()) {
3286         LOG.info("A region server is stopped or stopping:"+hrs);
3287       } else {
3288         nonStoppedServers++;
3289       }
3290     }
3291     for (int i=nonStoppedServers; i<num; ++i) {
3292       LOG.info("Started new server=" + getMiniHBaseCluster().startRegionServer());
3293       startedServer = true;
3294     }
3295     return startedServer;
3296   }
3297 
3298 
3299   /**
3300    * This method clones the passed <code>c</code> configuration setting a new
3301    * user into the clone.  Use it getting new instances of FileSystem.  Only
3302    * works for DistributedFileSystem w/o Kerberos.
3303    * @param c Initial configuration
3304    * @param differentiatingSuffix Suffix to differentiate this user from others.
3305    * @return A new configuration instance with a different user set into it.
3306    * @throws IOException
3307    */
3308   public static User getDifferentUser(final Configuration c,
3309     final String differentiatingSuffix)
3310   throws IOException {
3311     FileSystem currentfs = FileSystem.get(c);
3312     if (!(currentfs instanceof DistributedFileSystem) || User.isHBaseSecurityEnabled(c)) {
3313       return User.getCurrent();
3314     }
3315     // Else distributed filesystem.  Make a new instance per daemon.  Below
3316     // code is taken from the AppendTestUtil over in hdfs.
3317     String username = User.getCurrent().getName() +
3318       differentiatingSuffix;
3319     User user = User.createUserForTesting(c, username,
3320         new String[]{"supergroup"});
3321     return user;
3322   }
3323 
3324   public static NavigableSet<String> getAllOnlineRegions(MiniHBaseCluster cluster)
3325       throws IOException {
3326     NavigableSet<String> online = new TreeSet<String>();
3327     for (RegionServerThread rst : cluster.getLiveRegionServerThreads()) {
3328       try {
3329         for (HRegionInfo region :
3330             ProtobufUtil.getOnlineRegions(rst.getRegionServer().getRSRpcServices())) {
3331           online.add(region.getRegionNameAsString());
3332         }
3333       } catch (RegionServerStoppedException e) {
3334         // That's fine.
3335       }
3336     }
3337     for (MasterThread mt : cluster.getLiveMasterThreads()) {
3338       try {
3339         for (HRegionInfo region :
3340             ProtobufUtil.getOnlineRegions(mt.getMaster().getRSRpcServices())) {
3341           online.add(region.getRegionNameAsString());
3342         }
3343       } catch (RegionServerStoppedException e) {
3344         // That's fine.
3345       } catch (ServerNotRunningYetException e) {
3346         // That's fine.
3347       }
3348     }
3349     return online;
3350   }
3351 
3352   /**
3353    * Set maxRecoveryErrorCount in DFSClient.  In 0.20 pre-append its hard-coded to 5 and
3354    * makes tests linger.  Here is the exception you'll see:
3355    * <pre>
3356    * 2010-06-15 11:52:28,511 WARN  [DataStreamer for file /hbase/.logs/wal.1276627923013 block blk_928005470262850423_1021] hdfs.DFSClient$DFSOutputStream(2657): Error Recovery for block blk_928005470262850423_1021 failed  because recovery from primary datanode 127.0.0.1:53683 failed 4 times.  Pipeline was 127.0.0.1:53687, 127.0.0.1:53683. Will retry...
3357    * </pre>
3358    * @param stream A DFSClient.DFSOutputStream.
3359    * @param max
3360    * @throws NoSuchFieldException
3361    * @throws SecurityException
3362    * @throws IllegalAccessException
3363    * @throws IllegalArgumentException
3364    */
3365   public static void setMaxRecoveryErrorCount(final OutputStream stream,
3366       final int max) {
3367     try {
3368       Class<?> [] clazzes = DFSClient.class.getDeclaredClasses();
3369       for (Class<?> clazz: clazzes) {
3370         String className = clazz.getSimpleName();
3371         if (className.equals("DFSOutputStream")) {
3372           if (clazz.isInstance(stream)) {
3373             Field maxRecoveryErrorCountField =
3374               stream.getClass().getDeclaredField("maxRecoveryErrorCount");
3375             maxRecoveryErrorCountField.setAccessible(true);
3376             maxRecoveryErrorCountField.setInt(stream, max);
3377             break;
3378           }
3379         }
3380       }
3381     } catch (Exception e) {
3382       LOG.info("Could not set max recovery field", e);
3383     }
3384   }
3385 
3386   /**
3387    * Wait until all regions for a table in hbase:meta have a non-empty
3388    * info:server, up to a configuable timeout value (default is 60 seconds)
3389    * This means all regions have been deployed,
3390    * master has been informed and updated hbase:meta with the regions deployed
3391    * server.
3392    * @param tableName the table name
3393    * @throws IOException
3394    */
3395   public void waitUntilAllRegionsAssigned(final TableName tableName) throws IOException {
3396     waitUntilAllRegionsAssigned(
3397       tableName,
3398       this.conf.getLong("hbase.client.sync.wait.timeout.msec", 60000));
3399   }
3400 
3401   /**
3402    * Wait until all regions for a table in hbase:meta have a non-empty
3403    * info:server, or until timeout.  This means all regions have been deployed,
3404    * master has been informed and updated hbase:meta with the regions deployed
3405    * server.
3406    * @param tableName the table name
3407    * @param timeout timeout, in milliseconds
3408    * @throws IOException
3409    */
3410   public void waitUntilAllRegionsAssigned(final TableName tableName, final long timeout)
3411       throws IOException {
3412     final Table meta = new HTable(getConfiguration(), TableName.META_TABLE_NAME);
3413     try {
3414       waitFor(timeout, 200, true, new Predicate<IOException>() {
3415         @Override
3416         public boolean evaluate() throws IOException {
3417           boolean allRegionsAssigned = true;
3418           Scan scan = new Scan();
3419           scan.addFamily(HConstants.CATALOG_FAMILY);
3420           ResultScanner s = meta.getScanner(scan);
3421           try {
3422             Result r;
3423             while ((r = s.next()) != null) {
3424               byte[] b = r.getValue(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER);
3425               HRegionInfo info = HRegionInfo.parseFromOrNull(b);
3426               if (info != null && info.getTable().equals(tableName)) {
3427                 b = r.getValue(HConstants.CATALOG_FAMILY, HConstants.SERVER_QUALIFIER);
3428                 allRegionsAssigned &= (b != null);
3429               }
3430             }
3431           } finally {
3432             s.close();
3433           }
3434           return allRegionsAssigned;
3435         }
3436       });
3437     } finally {
3438       meta.close();
3439     }
3440 
3441     // check from the master state if we are using a mini cluster
3442     if (!getHBaseClusterInterface().isDistributedCluster()) {
3443       // So, all regions are in the meta table but make sure master knows of the assignments before
3444       // returing -- sometimes this can lag.
3445       HMaster master = getHBaseCluster().getMaster();
3446       final RegionStates states = master.getAssignmentManager().getRegionStates();
3447       waitFor(timeout, 200, new ExplainingPredicate<IOException>() {
3448         @Override
3449         public String explainFailure() throws IOException {
3450           return explainTableAvailability(tableName);
3451         }
3452 
3453         @Override
3454         public boolean evaluate() throws IOException {
3455           List<HRegionInfo> hris = states.getRegionsOfTable(tableName);
3456           return hris != null && !hris.isEmpty();
3457         }
3458       });
3459     }
3460   }
3461 
3462   /**
3463    * Do a small get/scan against one store. This is required because store
3464    * has no actual methods of querying itself, and relies on StoreScanner.
3465    */
3466   public static List<Cell> getFromStoreFile(HStore store,
3467                                                 Get get) throws IOException {
3468     Scan scan = new Scan(get);
3469     InternalScanner scanner = (InternalScanner) store.getScanner(scan,
3470         scan.getFamilyMap().get(store.getFamily().getName()),
3471         // originally MultiVersionConcurrencyControl.resetThreadReadPoint() was called to set
3472         // readpoint 0.
3473         0);
3474 
3475     List<Cell> result = new ArrayList<Cell>();
3476     scanner.next(result);
3477     if (!result.isEmpty()) {
3478       // verify that we are on the row we want:
3479       Cell kv = result.get(0);
3480       if (!CellUtil.matchingRow(kv, get.getRow())) {
3481         result.clear();
3482       }
3483     }
3484     scanner.close();
3485     return result;
3486   }
3487 
3488   /**
3489    * Create region split keys between startkey and endKey
3490    *
3491    * @param startKey
3492    * @param endKey
3493    * @param numRegions the number of regions to be created. it has to be greater than 3.
3494    * @return
3495    */
3496   public byte[][] getRegionSplitStartKeys(byte[] startKey, byte[] endKey, int numRegions){
3497     assertTrue(numRegions>3);
3498     byte [][] tmpSplitKeys = Bytes.split(startKey, endKey, numRegions - 3);
3499     byte [][] result = new byte[tmpSplitKeys.length+1][];
3500     System.arraycopy(tmpSplitKeys, 0, result, 1, tmpSplitKeys.length);
3501     result[0] = HConstants.EMPTY_BYTE_ARRAY;
3502     return result;
3503   }
3504 
3505   /**
3506    * Do a small get/scan against one store. This is required because store
3507    * has no actual methods of querying itself, and relies on StoreScanner.
3508    */
3509   public static List<Cell> getFromStoreFile(HStore store,
3510                                                 byte [] row,
3511                                                 NavigableSet<byte[]> columns
3512                                                 ) throws IOException {
3513     Get get = new Get(row);
3514     Map<byte[], NavigableSet<byte[]>> s = get.getFamilyMap();
3515     s.put(store.getFamily().getName(), columns);
3516 
3517     return getFromStoreFile(store,get);
3518   }
3519 
3520   /**
3521    * Gets a ZooKeeperWatcher.
3522    * @param TEST_UTIL
3523    */
3524   public static ZooKeeperWatcher getZooKeeperWatcher(
3525       HBaseTestingUtility TEST_UTIL) throws ZooKeeperConnectionException,
3526       IOException {
3527     ZooKeeperWatcher zkw = new ZooKeeperWatcher(TEST_UTIL.getConfiguration(),
3528         "unittest", new Abortable() {
3529           boolean aborted = false;
3530 
3531           @Override
3532           public void abort(String why, Throwable e) {
3533             aborted = true;
3534             throw new RuntimeException("Fatal ZK error, why=" + why, e);
3535           }
3536 
3537           @Override
3538           public boolean isAborted() {
3539             return aborted;
3540           }
3541         });
3542     return zkw;
3543   }
3544 
3545   /**
3546    * Creates a znode with OPENED state.
3547    * @param TEST_UTIL
3548    * @param region
3549    * @param serverName
3550    * @return
3551    * @throws IOException
3552    * @throws org.apache.hadoop.hbase.ZooKeeperConnectionException
3553    * @throws KeeperException
3554    * @throws NodeExistsException
3555    */
3556   public static ZooKeeperWatcher createAndForceNodeToOpenedState(
3557       HBaseTestingUtility TEST_UTIL, Region region,
3558       ServerName serverName) throws ZooKeeperConnectionException,
3559       IOException, KeeperException, NodeExistsException {
3560     return createAndForceNodeToOpenedState(TEST_UTIL, (HRegion)region, serverName);
3561   }
3562 
3563   /**
3564    * Creates a znode with OPENED state.
3565    * @param TEST_UTIL
3566    * @param region
3567    * @param serverName
3568    * @return
3569    * @throws IOException
3570    * @throws org.apache.hadoop.hbase.ZooKeeperConnectionException
3571    * @throws KeeperException
3572    * @throws NodeExistsException
3573    */
3574   public static ZooKeeperWatcher createAndForceNodeToOpenedState(
3575       HBaseTestingUtility TEST_UTIL, HRegion region,
3576       ServerName serverName) throws ZooKeeperConnectionException,
3577       IOException, KeeperException, NodeExistsException {
3578     ZooKeeperWatcher zkw = getZooKeeperWatcher(TEST_UTIL);
3579     ZKAssign.createNodeOffline(zkw, region.getRegionInfo(), serverName);
3580     int version = ZKAssign.transitionNodeOpening(zkw, region
3581         .getRegionInfo(), serverName);
3582     ZKAssign.transitionNodeOpened(zkw, region.getRegionInfo(), serverName,
3583         version);
3584     return zkw;
3585   }
3586 
3587   public static void assertKVListsEqual(String additionalMsg,
3588       final List<? extends Cell> expected,
3589       final List<? extends Cell> actual) {
3590     final int eLen = expected.size();
3591     final int aLen = actual.size();
3592     final int minLen = Math.min(eLen, aLen);
3593 
3594     int i;
3595     for (i = 0; i < minLen
3596         && KeyValue.COMPARATOR.compare(expected.get(i), actual.get(i)) == 0;
3597         ++i) {}
3598 
3599     if (additionalMsg == null) {
3600       additionalMsg = "";
3601     }
3602     if (!additionalMsg.isEmpty()) {
3603       additionalMsg = ". " + additionalMsg;
3604     }
3605 
3606     if (eLen != aLen || i != minLen) {
3607       throw new AssertionError(
3608           "Expected and actual KV arrays differ at position " + i + ": " +
3609           safeGetAsStr(expected, i) + " (length " + eLen +") vs. " +
3610           safeGetAsStr(actual, i) + " (length " + aLen + ")" + additionalMsg);
3611     }
3612   }
3613 
3614   public static <T> String safeGetAsStr(List<T> lst, int i) {
3615     if (0 <= i && i < lst.size()) {
3616       return lst.get(i).toString();
3617     } else {
3618       return "<out_of_range>";
3619     }
3620   }
3621 
3622   public String getClusterKey() {
3623     return conf.get(HConstants.ZOOKEEPER_QUORUM) + ":"
3624         + conf.get(HConstants.ZOOKEEPER_CLIENT_PORT) + ":"
3625         + conf.get(HConstants.ZOOKEEPER_ZNODE_PARENT,
3626             HConstants.DEFAULT_ZOOKEEPER_ZNODE_PARENT);
3627   }
3628 
3629   /** Creates a random table with the given parameters */
3630   public HTable createRandomTable(String tableName,
3631       final Collection<String> families,
3632       final int maxVersions,
3633       final int numColsPerRow,
3634       final int numFlushes,
3635       final int numRegions,
3636       final int numRowsPerFlush)
3637       throws IOException, InterruptedException {
3638 
3639     LOG.info("\n\nCreating random table " + tableName + " with " + numRegions +
3640         " regions, " + numFlushes + " storefiles per region, " +
3641         numRowsPerFlush + " rows per flush, maxVersions=" +  maxVersions +
3642         "\n");
3643 
3644     final Random rand = new Random(tableName.hashCode() * 17L + 12938197137L);
3645     final int numCF = families.size();
3646     final byte[][] cfBytes = new byte[numCF][];
3647     {
3648       int cfIndex = 0;
3649       for (String cf : families) {
3650         cfBytes[cfIndex++] = Bytes.toBytes(cf);
3651       }
3652     }
3653 
3654     final int actualStartKey = 0;
3655     final int actualEndKey = Integer.MAX_VALUE;
3656     final int keysPerRegion = (actualEndKey - actualStartKey) / numRegions;
3657     final int splitStartKey = actualStartKey + keysPerRegion;
3658     final int splitEndKey = actualEndKey - keysPerRegion;
3659     final String keyFormat = "%08x";
3660     final HTable table = createTable(tableName, cfBytes,
3661         maxVersions,
3662         Bytes.toBytes(String.format(keyFormat, splitStartKey)),
3663         Bytes.toBytes(String.format(keyFormat, splitEndKey)),
3664         numRegions);
3665 
3666     if (hbaseCluster != null) {
3667       getMiniHBaseCluster().flushcache(TableName.META_TABLE_NAME);
3668     }
3669 
3670     for (int iFlush = 0; iFlush < numFlushes; ++iFlush) {
3671       for (int iRow = 0; iRow < numRowsPerFlush; ++iRow) {
3672         final byte[] row = Bytes.toBytes(String.format(keyFormat,
3673             actualStartKey + rand.nextInt(actualEndKey - actualStartKey)));
3674 
3675         Put put = new Put(row);
3676         Delete del = new Delete(row);
3677         for (int iCol = 0; iCol < numColsPerRow; ++iCol) {
3678           final byte[] cf = cfBytes[rand.nextInt(numCF)];
3679           final long ts = rand.nextInt();
3680           final byte[] qual = Bytes.toBytes("col" + iCol);
3681           if (rand.nextBoolean()) {
3682             final byte[] value = Bytes.toBytes("value_for_row_" + iRow +
3683                 "_cf_" + Bytes.toStringBinary(cf) + "_col_" + iCol + "_ts_" +
3684                 ts + "_random_" + rand.nextLong());
3685             put.add(cf, qual, ts, value);
3686           } else if (rand.nextDouble() < 0.8) {
3687             del.deleteColumn(cf, qual, ts);
3688           } else {
3689             del.deleteColumns(cf, qual, ts);
3690           }
3691         }
3692 
3693         if (!put.isEmpty()) {
3694           table.put(put);
3695         }
3696 
3697         if (!del.isEmpty()) {
3698           table.delete(del);
3699         }
3700       }
3701       LOG.info("Initiating flush #" + iFlush + " for table " + tableName);
3702       table.flushCommits();
3703       if (hbaseCluster != null) {
3704         getMiniHBaseCluster().flushcache(table.getName());
3705       }
3706     }
3707 
3708     return table;
3709   }
3710 
3711   private static final int MIN_RANDOM_PORT = 0xc000;
3712   private static final int MAX_RANDOM_PORT = 0xfffe;
3713   private static Random random = new Random();
3714 
3715   /**
3716    * Returns a random port. These ports cannot be registered with IANA and are
3717    * intended for dynamic allocation (see http://bit.ly/dynports).
3718    */
3719   public static int randomPort() {
3720     return MIN_RANDOM_PORT
3721         + random.nextInt(MAX_RANDOM_PORT - MIN_RANDOM_PORT);
3722   }
3723 
3724   /**
3725    * Returns a random free port and marks that port as taken. Not thread-safe. Expected to be
3726    * called from single-threaded test setup code/
3727    */
3728   public static int randomFreePort() {
3729     int port = 0;
3730     do {
3731       port = randomPort();
3732       if (takenRandomPorts.contains(port)) {
3733         port = 0;
3734         continue;
3735       }
3736       takenRandomPorts.add(port);
3737 
3738       try {
3739         ServerSocket sock = new ServerSocket(port);
3740         sock.close();
3741       } catch (IOException ex) {
3742         port = 0;
3743       }
3744     } while (port == 0);
3745     return port;
3746   }
3747 
3748 
3749   public static String randomMultiCastAddress() {
3750     return "226.1.1." + random.nextInt(254);
3751   }
3752 
3753 
3754 
3755   public static void waitForHostPort(String host, int port)
3756       throws IOException {
3757     final int maxTimeMs = 10000;
3758     final int maxNumAttempts = maxTimeMs / HConstants.SOCKET_RETRY_WAIT_MS;
3759     IOException savedException = null;
3760     LOG.info("Waiting for server at " + host + ":" + port);
3761     for (int attempt = 0; attempt < maxNumAttempts; ++attempt) {
3762       try {
3763         Socket sock = new Socket(InetAddress.getByName(host), port);
3764         sock.close();
3765         savedException = null;
3766         LOG.info("Server at " + host + ":" + port + " is available");
3767         break;
3768       } catch (UnknownHostException e) {
3769         throw new IOException("Failed to look up " + host, e);
3770       } catch (IOException e) {
3771         savedException = e;
3772       }
3773       Threads.sleepWithoutInterrupt(HConstants.SOCKET_RETRY_WAIT_MS);
3774     }
3775 
3776     if (savedException != null) {
3777       throw savedException;
3778     }
3779   }
3780 
3781   /**
3782    * Creates a pre-split table for load testing. If the table already exists,
3783    * logs a warning and continues.
3784    * @return the number of regions the table was split into
3785    */
3786   public static int createPreSplitLoadTestTable(Configuration conf,
3787       TableName tableName, byte[] columnFamily, Algorithm compression,
3788       DataBlockEncoding dataBlockEncoding) throws IOException {
3789     return createPreSplitLoadTestTable(conf, tableName,
3790       columnFamily, compression, dataBlockEncoding, DEFAULT_REGIONS_PER_SERVER, 1,
3791       Durability.USE_DEFAULT);
3792   }
3793   /**
3794    * Creates a pre-split table for load testing. If the table already exists,
3795    * logs a warning and continues.
3796    * @return the number of regions the table was split into
3797    */
3798   public static int createPreSplitLoadTestTable(Configuration conf,
3799       TableName tableName, byte[] columnFamily, Algorithm compression,
3800       DataBlockEncoding dataBlockEncoding, int numRegionsPerServer, int regionReplication,
3801       Durability durability)
3802           throws IOException {
3803     HTableDescriptor desc = new HTableDescriptor(tableName);
3804     desc.setDurability(durability);
3805     desc.setRegionReplication(regionReplication);
3806     HColumnDescriptor hcd = new HColumnDescriptor(columnFamily);
3807     hcd.setDataBlockEncoding(dataBlockEncoding);
3808     hcd.setCompressionType(compression);
3809     return createPreSplitLoadTestTable(conf, desc, hcd, numRegionsPerServer);
3810   }
3811 
3812   /**
3813    * Creates a pre-split table for load testing. If the table already exists,
3814    * logs a warning and continues.
3815    * @return the number of regions the table was split into
3816    */
3817   public static int createPreSplitLoadTestTable(Configuration conf,
3818       TableName tableName, byte[][] columnFamilies, Algorithm compression,
3819       DataBlockEncoding dataBlockEncoding, int numRegionsPerServer, int regionReplication,
3820       Durability durability)
3821           throws IOException {
3822     HTableDescriptor desc = new HTableDescriptor(tableName);
3823     desc.setDurability(durability);
3824     desc.setRegionReplication(regionReplication);
3825     HColumnDescriptor[] hcds = new HColumnDescriptor[columnFamilies.length];
3826     for (int i = 0; i < columnFamilies.length; i++) {
3827       HColumnDescriptor hcd = new HColumnDescriptor(columnFamilies[i]);
3828       hcd.setDataBlockEncoding(dataBlockEncoding);
3829       hcd.setCompressionType(compression);
3830       hcds[i] = hcd;
3831     }
3832     return createPreSplitLoadTestTable(conf, desc, hcds, numRegionsPerServer);
3833   }
3834 
3835   /**
3836    * Creates a pre-split table for load testing. If the table already exists,
3837    * logs a warning and continues.
3838    * @return the number of regions the table was split into
3839    */
3840   public static int createPreSplitLoadTestTable(Configuration conf,
3841       HTableDescriptor desc, HColumnDescriptor hcd) throws IOException {
3842     return createPreSplitLoadTestTable(conf, desc, hcd, DEFAULT_REGIONS_PER_SERVER);
3843   }
3844 
3845   /**
3846    * Creates a pre-split table for load testing. If the table already exists,
3847    * logs a warning and continues.
3848    * @return the number of regions the table was split into
3849    */
3850   public static int createPreSplitLoadTestTable(Configuration conf,
3851       HTableDescriptor desc, HColumnDescriptor hcd, int numRegionsPerServer) throws IOException {
3852     return createPreSplitLoadTestTable(conf, desc, new HColumnDescriptor[] {hcd},
3853         numRegionsPerServer);
3854   }
3855 
3856   /**
3857    * Creates a pre-split table for load testing. If the table already exists,
3858    * logs a warning and continues.
3859    * @return the number of regions the table was split into
3860    */
3861   public static int createPreSplitLoadTestTable(Configuration conf,
3862       HTableDescriptor desc, HColumnDescriptor[] hcds, int numRegionsPerServer) throws IOException {
3863     for (HColumnDescriptor hcd : hcds) {
3864       if (!desc.hasFamily(hcd.getName())) {
3865         desc.addFamily(hcd);
3866       }
3867     }
3868 
3869     int totalNumberOfRegions = 0;
3870     Connection unmanagedConnection = ConnectionFactory.createConnection(conf);
3871     Admin admin = unmanagedConnection.getAdmin();
3872 
3873     try {
3874       // create a table a pre-splits regions.
3875       // The number of splits is set as:
3876       //    region servers * regions per region server).
3877       int numberOfServers = admin.getClusterStatus().getServers().size();
3878       if (numberOfServers == 0) {
3879         throw new IllegalStateException("No live regionservers");
3880       }
3881 
3882       totalNumberOfRegions = numberOfServers * numRegionsPerServer;
3883       LOG.info("Number of live regionservers: " + numberOfServers + ", " +
3884           "pre-splitting table into " + totalNumberOfRegions + " regions " +
3885           "(regions per server: " + numRegionsPerServer + ")");
3886 
3887       byte[][] splits = new RegionSplitter.HexStringSplit().split(
3888           totalNumberOfRegions);
3889 
3890       admin.createTable(desc, splits);
3891     } catch (MasterNotRunningException e) {
3892       LOG.error("Master not running", e);
3893       throw new IOException(e);
3894     } catch (TableExistsException e) {
3895       LOG.warn("Table " + desc.getTableName() +
3896           " already exists, continuing");
3897     } finally {
3898       admin.close();
3899       unmanagedConnection.close();
3900     }
3901     return totalNumberOfRegions;
3902   }
3903 
3904   public static int getMetaRSPort(Configuration conf) throws IOException {
3905     try (Connection c = ConnectionFactory.createConnection();
3906         RegionLocator locator = c.getRegionLocator(TableName.META_TABLE_NAME)) {
3907       return locator.getRegionLocation(Bytes.toBytes("")).getPort();
3908     }
3909   }
3910 
3911   /**
3912    *  Due to async racing issue, a region may not be in
3913    *  the online region list of a region server yet, after
3914    *  the assignment znode is deleted and the new assignment
3915    *  is recorded in master.
3916    */
3917   public void assertRegionOnServer(
3918       final HRegionInfo hri, final ServerName server,
3919       final long timeout) throws IOException, InterruptedException {
3920     long timeoutTime = System.currentTimeMillis() + timeout;
3921     while (true) {
3922       List<HRegionInfo> regions = getHBaseAdmin().getOnlineRegions(server);
3923       if (regions.contains(hri)) return;
3924       long now = System.currentTimeMillis();
3925       if (now > timeoutTime) break;
3926       Thread.sleep(10);
3927     }
3928     fail("Could not find region " + hri.getRegionNameAsString()
3929       + " on server " + server);
3930   }
3931 
3932   /**
3933    * Check to make sure the region is open on the specified
3934    * region server, but not on any other one.
3935    */
3936   public void assertRegionOnlyOnServer(
3937       final HRegionInfo hri, final ServerName server,
3938       final long timeout) throws IOException, InterruptedException {
3939     long timeoutTime = System.currentTimeMillis() + timeout;
3940     while (true) {
3941       List<HRegionInfo> regions = getHBaseAdmin().getOnlineRegions(server);
3942       if (regions.contains(hri)) {
3943         List<JVMClusterUtil.RegionServerThread> rsThreads =
3944           getHBaseCluster().getLiveRegionServerThreads();
3945         for (JVMClusterUtil.RegionServerThread rsThread: rsThreads) {
3946           HRegionServer rs = rsThread.getRegionServer();
3947           if (server.equals(rs.getServerName())) {
3948             continue;
3949           }
3950           Collection<Region> hrs = rs.getOnlineRegionsLocalContext();
3951           for (Region r: hrs) {
3952             assertTrue("Region should not be double assigned",
3953               r.getRegionInfo().getRegionId() != hri.getRegionId());
3954           }
3955         }
3956         return; // good, we are happy
3957       }
3958       long now = System.currentTimeMillis();
3959       if (now > timeoutTime) break;
3960       Thread.sleep(10);
3961     }
3962     fail("Could not find region " + hri.getRegionNameAsString()
3963       + " on server " + server);
3964   }
3965 
3966   public HRegion createTestRegion(String tableName, HColumnDescriptor hcd)
3967       throws IOException {
3968     HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(tableName));
3969     htd.addFamily(hcd);
3970     HRegionInfo info =
3971         new HRegionInfo(TableName.valueOf(tableName), null, null, false);
3972     HRegion region =
3973         HRegion.createHRegion(info, getDataTestDir(), getConfiguration(), htd);
3974     return region;
3975   }
3976 
3977   public void setFileSystemURI(String fsURI) {
3978     FS_URI = fsURI;
3979   }
3980 
3981   /**
3982    * Wrapper method for {@link Waiter#waitFor(Configuration, long, Predicate)}.
3983    */
3984   public <E extends Exception> long waitFor(long timeout, Predicate<E> predicate)
3985       throws E {
3986     return Waiter.waitFor(this.conf, timeout, predicate);
3987   }
3988 
3989   /**
3990    * Wrapper method for {@link Waiter#waitFor(Configuration, long, long, Predicate)}.
3991    */
3992   public <E extends Exception> long waitFor(long timeout, long interval, Predicate<E> predicate)
3993       throws E {
3994     return Waiter.waitFor(this.conf, timeout, interval, predicate);
3995   }
3996 
3997   /**
3998    * Wrapper method for {@link Waiter#waitFor(Configuration, long, long, boolean, Predicate)}.
3999    */
4000   public <E extends Exception> long waitFor(long timeout, long interval,
4001       boolean failIfTimeout, Predicate<E> predicate) throws E {
4002     return Waiter.waitFor(this.conf, timeout, interval, failIfTimeout, predicate);
4003   }
4004 
4005   /**
4006    * Returns a {@link Predicate} for checking that there are no regions in transition in master
4007    */
4008   public ExplainingPredicate<IOException> predicateNoRegionsInTransition() {
4009     return new ExplainingPredicate<IOException>() {
4010       @Override
4011       public String explainFailure() throws IOException {
4012         final RegionStates regionStates = getMiniHBaseCluster().getMaster()
4013             .getAssignmentManager().getRegionStates();
4014         return "found in transition: " + regionStates.getRegionsInTransition().toString();
4015       }
4016 
4017       @Override
4018       public boolean evaluate() throws IOException {
4019         HMaster master = getMiniHBaseCluster().getMaster();
4020         if (master == null) return false;
4021         AssignmentManager am = master.getAssignmentManager();
4022         if (am == null) return false;
4023         final RegionStates regionStates = am.getRegionStates();
4024         return !regionStates.isRegionsInTransition();
4025       }
4026     };
4027   }
4028 
4029   /**
4030    * Returns a {@link Predicate} for checking that table is enabled
4031    */
4032   public Waiter.Predicate<IOException> predicateTableEnabled(final TableName tableName) {
4033     return new ExplainingPredicate<IOException>() {
4034       @Override
4035       public String explainFailure() throws IOException {
4036         return explainTableState(tableName);
4037       }
4038 
4039       @Override
4040       public boolean evaluate() throws IOException {
4041         return getHBaseAdmin().tableExists(tableName) && getHBaseAdmin().isTableEnabled(tableName);
4042       }
4043     };
4044   }
4045 
4046   /**
4047    * Returns a {@link Predicate} for checking that table is enabled
4048    */
4049   public Waiter.Predicate<IOException> predicateTableDisabled(final TableName tableName) {
4050     return new ExplainingPredicate<IOException>() {
4051       @Override
4052       public String explainFailure() throws IOException {
4053         return explainTableState(tableName);
4054       }
4055 
4056       @Override
4057       public boolean evaluate() throws IOException {
4058         return getHBaseAdmin().isTableDisabled(tableName);
4059       }
4060     };
4061   }
4062 
4063   /**
4064    * Returns a {@link Predicate} for checking that table is enabled
4065    */
4066   public Waiter.Predicate<IOException> predicateTableAvailable(final TableName tableName) {
4067     return new ExplainingPredicate<IOException>() {
4068       @Override
4069       public String explainFailure() throws IOException {
4070         return explainTableAvailability(tableName);
4071       }
4072 
4073       @Override
4074       public boolean evaluate() throws IOException {
4075         boolean tableAvailable = getHBaseAdmin().isTableAvailable(tableName);
4076         if (tableAvailable) {
4077           try {
4078             Canary.sniff(getHBaseAdmin(), tableName);
4079           } catch (Exception e) {
4080             throw new IOException("Canary sniff failed for table " + tableName, e);
4081           }
4082         }
4083         return tableAvailable;
4084       }
4085     };
4086   }
4087 
4088   /**
4089    * Wait until no regions in transition.
4090    * @param timeout How long to wait.
4091    * @throws Exception
4092    */
4093   public void waitUntilNoRegionsInTransition(
4094       final long timeout) throws Exception {
4095     waitFor(timeout, predicateNoRegionsInTransition());
4096   }
4097 
4098   /**
4099    * Wait until labels is ready in VisibilityLabelsCache.
4100    * @param timeoutMillis
4101    * @param labels
4102    */
4103   public void waitLabelAvailable(long timeoutMillis, final String... labels) {
4104     final VisibilityLabelsCache labelsCache = VisibilityLabelsCache.get();
4105     waitFor(timeoutMillis, new Waiter.ExplainingPredicate<RuntimeException>() {
4106 
4107       @Override
4108       public boolean evaluate() {
4109         for (String label : labels) {
4110           if (labelsCache.getLabelOrdinal(label) == 0) {
4111             return false;
4112           }
4113         }
4114         return true;
4115       }
4116 
4117       @Override
4118       public String explainFailure() {
4119         for (String label : labels) {
4120           if (labelsCache.getLabelOrdinal(label) == 0) {
4121             return label + " is not available yet";
4122           }
4123         }
4124         return "";
4125       }
4126     });
4127   }
4128 
4129   /**
4130    * Create a set of column descriptors with the combination of compression,
4131    * encoding, bloom codecs available.
4132    * @return the list of column descriptors
4133    */
4134   public static List<HColumnDescriptor> generateColumnDescriptors() {
4135     return generateColumnDescriptors("");
4136   }
4137 
4138   /**
4139    * Create a set of column descriptors with the combination of compression,
4140    * encoding, bloom codecs available.
4141    * @param prefix family names prefix
4142    * @return the list of column descriptors
4143    */
4144   public static List<HColumnDescriptor> generateColumnDescriptors(final String prefix) {
4145     List<HColumnDescriptor> htds = new ArrayList<HColumnDescriptor>();
4146     long familyId = 0;
4147     for (Compression.Algorithm compressionType: getSupportedCompressionAlgorithms()) {
4148       for (DataBlockEncoding encodingType: DataBlockEncoding.values()) {
4149         for (BloomType bloomType: BloomType.values()) {
4150           String name = String.format("%s-cf-!@#&-%d!@#", prefix, familyId);
4151           HColumnDescriptor htd = new HColumnDescriptor(name);
4152           htd.setCompressionType(compressionType);
4153           htd.setDataBlockEncoding(encodingType);
4154           htd.setBloomFilterType(bloomType);
4155           htds.add(htd);
4156           familyId++;
4157         }
4158       }
4159     }
4160     return htds;
4161   }
4162 
4163   /**
4164    * Get supported compression algorithms.
4165    * @return supported compression algorithms.
4166    */
4167   public static Compression.Algorithm[] getSupportedCompressionAlgorithms() {
4168     String[] allAlgos = HFile.getSupportedCompressionAlgorithms();
4169     List<Compression.Algorithm> supportedAlgos = new ArrayList<Compression.Algorithm>();
4170     for (String algoName : allAlgos) {
4171       try {
4172         Compression.Algorithm algo = Compression.getCompressionAlgorithmByName(algoName);
4173         algo.getCompressor();
4174         supportedAlgos.add(algo);
4175       } catch (Throwable t) {
4176         // this algo is not available
4177       }
4178     }
4179     return supportedAlgos.toArray(new Algorithm[supportedAlgos.size()]);
4180   }
4181 
4182 
4183   /**
4184    * Sets up {@link MiniKdc} for testing security.
4185    * Uses {@link HBaseKerberosUtils} to set the given keytab file as
4186    * {@link HBaseKerberosUtils#KRB_KEYTAB_FILE}.
4187    */
4188   public MiniKdc setupMiniKdc(File keytabFile) throws Exception {
4189     Properties conf = MiniKdc.createConf();
4190     conf.put(MiniKdc.DEBUG, true);
4191     MiniKdc kdc = null;
4192     File dir = null;
4193     // There is time lag between selecting a port and trying to bind with it. It's possible that
4194     // another service captures the port in between which'll result in BindException.
4195     boolean bindException;
4196     int numTries = 0;
4197     do {
4198       try {
4199         bindException = false;
4200         dir = new File(getDataTestDir("kdc").toUri().getPath());
4201         kdc = new MiniKdc(conf, dir);
4202         kdc.start();
4203       } catch (BindException e) {
4204         FileUtils.deleteDirectory(dir);  // clean directory
4205         numTries++;
4206         if (numTries == 3) {
4207           LOG.error("Failed setting up MiniKDC. Tried " + numTries + " times.");
4208           throw e;
4209         }
4210         LOG.error("BindException encountered when setting up MiniKdc. Trying again.");
4211         bindException = true;
4212       }
4213     } while (bindException);
4214     HBaseKerberosUtils.setKeytabFileForTesting(keytabFile.getAbsolutePath());
4215     return kdc;
4216   }
4217 }