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