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