001/**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019package org.apache.hadoop.hbase;
020
021import java.io.File;
022import java.io.IOException;
023import java.util.Arrays;
024import java.util.List;
025import java.util.UUID;
026import java.util.concurrent.ThreadLocalRandom;
027
028import org.apache.commons.io.FileUtils;
029import org.apache.hadoop.conf.Configuration;
030import org.apache.hadoop.fs.Path;
031import org.apache.hadoop.hbase.Waiter.Predicate;
032import org.apache.hadoop.hbase.io.compress.Compression;
033import org.apache.yetus.audience.InterfaceAudience;
034import org.slf4j.Logger;
035import org.slf4j.LoggerFactory;
036
037/**
038 * Common helpers for testing HBase that do not depend on specific server/etc. things.
039 * @see org.apache.hadoop.hbase.HBaseCommonTestingUtility
040 *
041 */
042@InterfaceAudience.Public
043public class HBaseCommonTestingUtility {
044  protected static final Logger LOG = LoggerFactory.getLogger(HBaseCommonTestingUtility.class);
045
046  /** Compression algorithms to use in parameterized JUnit 4 tests */
047  public static final List<Object[]> COMPRESSION_ALGORITHMS_PARAMETERIZED =
048    Arrays.asList(new Object[][] {
049      { Compression.Algorithm.NONE },
050      { Compression.Algorithm.GZ }
051    });
052
053  /** This is for unit tests parameterized with a two booleans. */
054  public static final List<Object[]> BOOLEAN_PARAMETERIZED =
055      Arrays.asList(new Object[][] {
056          {false},
057          {true}
058      });
059
060  /** Compression algorithms to use in testing */
061  public static final Compression.Algorithm[] COMPRESSION_ALGORITHMS = {
062      Compression.Algorithm.NONE, Compression.Algorithm.GZ
063  };
064
065  protected Configuration conf;
066
067  public HBaseCommonTestingUtility() {
068    this(null);
069  }
070
071  public HBaseCommonTestingUtility(Configuration conf) {
072    this.conf = (conf == null ? HBaseConfiguration.create() : conf);
073  }
074
075  /**
076   * Returns this classes's instance of {@link Configuration}.
077   *
078   * @return Instance of Configuration.
079   */
080  public Configuration getConfiguration() {
081    return this.conf;
082  }
083
084  /**
085   * System property key to get base test directory value
086   */
087  public static final String BASE_TEST_DIRECTORY_KEY =
088      "test.build.data.basedirectory";
089
090  /**
091   * Default base directory for test output.
092   */
093  public static final String DEFAULT_BASE_TEST_DIRECTORY = "target/test-data";
094
095  /**
096   * Directory where we put the data for this instance of HBaseTestingUtility
097   */
098  private File dataTestDir = null;
099
100  /**
101   * @return Where to write test data on local filesystem, specific to
102   * the test.  Useful for tests that do not use a cluster.
103   * Creates it if it does not exist already.
104   */
105  public Path getDataTestDir() {
106    if (this.dataTestDir == null) {
107      setupDataTestDir();
108    }
109    return new Path(this.dataTestDir.getAbsolutePath());
110  }
111
112  /**
113   * @param subdirName
114   * @return Path to a subdirectory named <code>subdirName</code> under
115   * {@link #getDataTestDir()}.
116   * Does *NOT* create it if it does not exist.
117   */
118  public Path getDataTestDir(final String subdirName) {
119    return new Path(getDataTestDir(), subdirName);
120  }
121
122  /**
123   * Sets up a directory for a test to use.
124   *
125   * @return New directory path, if created.
126   */
127  protected Path setupDataTestDir() {
128    if (this.dataTestDir != null) {
129      LOG.warn("Data test dir already setup in " +
130          dataTestDir.getAbsolutePath());
131      return null;
132    }
133    Path testPath = getRandomDir();
134    this.dataTestDir = new File(testPath.toString()).getAbsoluteFile();
135    // Set this property so if mapreduce jobs run, they will use this as their home dir.
136    System.setProperty("test.build.dir", this.dataTestDir.toString());
137    if (deleteOnExit()) this.dataTestDir.deleteOnExit();
138
139    createSubDir("hbase.local.dir", testPath, "hbase-local-dir");
140
141    return testPath;
142  }
143
144  /**
145   * @return A dir with a random (uuid) name under the test dir
146   * @see #getBaseTestDir()
147   */
148  public Path getRandomDir() {
149    return new Path(getBaseTestDir(), getRandomUUID().toString());
150  }
151
152  public UUID getRandomUUID() {
153    return new UUID(ThreadLocalRandom.current().nextLong(),
154                    ThreadLocalRandom.current().nextLong());
155  }
156
157
158  protected void createSubDir(String propertyName, Path parent, String subDirName) {
159    Path newPath = new Path(parent, subDirName);
160    File newDir = new File(newPath.toString()).getAbsoluteFile();
161    if (deleteOnExit()) newDir.deleteOnExit();
162    conf.set(propertyName, newDir.getAbsolutePath());
163  }
164
165  /**
166   * @return True if we should delete testing dirs on exit.
167   */
168  boolean deleteOnExit() {
169    String v = System.getProperty("hbase.testing.preserve.testdir");
170    // Let default be true, to delete on exit.
171    return v == null ? true : !Boolean.parseBoolean(v);
172  }
173
174  /**
175   * @return True if we removed the test dirs
176   * @throws IOException
177   */
178  public boolean cleanupTestDir() throws IOException {
179    if (deleteDir(this.dataTestDir)) {
180      this.dataTestDir = null;
181      return true;
182    }
183    return false;
184  }
185
186  /**
187   * @param subdir Test subdir name.
188   * @return True if we removed the test dir
189   * @throws IOException
190   */
191  boolean cleanupTestDir(final String subdir) throws IOException {
192    if (this.dataTestDir == null) {
193      return false;
194    }
195    return deleteDir(new File(this.dataTestDir, subdir));
196  }
197
198  /**
199   * @return Where to write test data on local filesystem; usually
200   * {@link #DEFAULT_BASE_TEST_DIRECTORY}
201   * Should not be used by the unit tests, hence its's private.
202   * Unit test will use a subdirectory of this directory.
203   * @see #setupDataTestDir()
204   */
205  private Path getBaseTestDir() {
206    String PathName = System.getProperty(
207        BASE_TEST_DIRECTORY_KEY, DEFAULT_BASE_TEST_DIRECTORY);
208
209    return new Path(PathName);
210  }
211
212  /**
213   * @param dir Directory to delete
214   * @return True if we deleted it.
215   * @throws IOException
216   */
217  boolean deleteDir(final File dir) throws IOException {
218    if (dir == null || !dir.exists()) {
219      return true;
220    }
221    int ntries = 0;
222    do {
223      ntries += 1;
224      try {
225        if (deleteOnExit()) FileUtils.deleteDirectory(dir);
226        return true;
227      } catch (IOException ex) {
228        LOG.warn("Failed to delete " + dir.getAbsolutePath());
229      } catch (IllegalArgumentException ex) {
230        LOG.warn("Failed to delete " + dir.getAbsolutePath(), ex);
231      }
232    } while (ntries < 30);
233
234    return false;
235  }
236
237  /**
238   * Wrapper method for {@link Waiter#waitFor(Configuration, long, Predicate)}.
239   */
240  public <E extends Exception> long waitFor(long timeout, Predicate<E> predicate)
241      throws E {
242    return Waiter.waitFor(this.conf, timeout, predicate);
243  }
244
245  /**
246   * Wrapper method for {@link Waiter#waitFor(Configuration, long, long, Predicate)}.
247   */
248  public <E extends Exception> long waitFor(long timeout, long interval, Predicate<E> predicate)
249      throws E {
250    return Waiter.waitFor(this.conf, timeout, interval, predicate);
251  }
252
253  /**
254   * Wrapper method for {@link Waiter#waitFor(Configuration, long, long, boolean, Predicate)}.
255   */
256  public <E extends Exception> long waitFor(long timeout, long interval,
257      boolean failIfTimeout, Predicate<E> predicate) throws E {
258    return Waiter.waitFor(this.conf, timeout, interval, failIfTimeout, predicate);
259  }
260}