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