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.util;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertNull;
022
023import java.io.IOException;
024import java.util.ArrayList;
025import java.util.Arrays;
026import java.util.Collections;
027import java.util.List;
028import org.apache.hadoop.conf.Configuration;
029import org.apache.hadoop.fs.FileStatus;
030import org.apache.hadoop.fs.FileSystem;
031import org.apache.hadoop.fs.Path;
032import org.apache.hadoop.hbase.HBaseTestingUtility;
033import org.apache.hadoop.hbase.regionserver.HRegion;
034import org.apache.hadoop.hbase.regionserver.Store;
035import org.slf4j.Logger;
036import org.slf4j.LoggerFactory;
037
038/**
039 * Test helper for testing archiving of HFiles
040 */
041public class HFileArchiveTestingUtil {
042
043  private static final Logger LOG = LoggerFactory.getLogger(HFileArchiveTestingUtil.class);
044
045  private HFileArchiveTestingUtil() {
046    // NOOP private ctor since this is just a utility class
047  }
048
049  public static boolean compareArchiveToOriginal(FileStatus[] previous, FileStatus[] archived,
050      FileSystem fs, boolean hasTimedBackup) {
051
052    List<List<String>> lists = getFileLists(previous, archived);
053    List<String> original = lists.get(0);
054    Collections.sort(original);
055
056    List<String> currentFiles = lists.get(1);
057    Collections.sort(currentFiles);
058
059    List<String> backedup = lists.get(2);
060    Collections.sort(backedup);
061
062    // check the backed up files versus the current (should match up, less the
063    // backup time in the name)
064    if (!hasTimedBackup == (backedup.size() > 0)) {
065      LOG.debug("backedup files doesn't match expected.");
066      return false;
067    }
068    String msg = null;
069    if (hasTimedBackup) {
070      msg = assertArchiveEquality(original, backedup);
071      if (msg != null) {
072        LOG.debug(msg);
073        return false;
074      }
075    }
076    msg = assertArchiveEquality(original, currentFiles);
077    if (msg != null) {
078      LOG.debug(msg);
079      return false;
080    }
081    return true;
082  }
083
084  /**
085   * Compare the archived files to the files in the original directory
086   * @param expected original files that should have been archived
087   * @param actual files that were archived
088   * @param fs filessystem on which the archiving took place
089   * @throws IOException
090   */
091  public static void assertArchiveEqualToOriginal(FileStatus[] expected, FileStatus[] actual,
092      FileSystem fs) throws IOException {
093    assertArchiveEqualToOriginal(expected, actual, fs, false);
094  }
095
096  /**
097   * Compare the archived files to the files in the original directory
098   * @param expected original files that should have been archived
099   * @param actual files that were archived
100   * @param fs {@link FileSystem} on which the archiving took place
101   * @param hasTimedBackup <tt>true</tt> if we expect to find an archive backup directory with a
102   *          copy of the files in the archive directory (and the original files).
103   * @throws IOException
104   */
105  public static void assertArchiveEqualToOriginal(FileStatus[] expected, FileStatus[] actual,
106      FileSystem fs, boolean hasTimedBackup) throws IOException {
107
108    List<List<String>> lists = getFileLists(expected, actual);
109    List<String> original = lists.get(0);
110    Collections.sort(original);
111
112    List<String> currentFiles = lists.get(1);
113    Collections.sort(currentFiles);
114
115    List<String> backedup = lists.get(2);
116    Collections.sort(backedup);
117
118    // check the backed up files versus the current (should match up, less the
119    // backup time in the name)
120    assertEquals("Didn't expect any backup files, but got: " + backedup, hasTimedBackup,
121      backedup.size() > 0);
122    String msg = null;
123    if (hasTimedBackup) {
124      assertArchiveEquality(original, backedup);
125      assertNull(msg, msg);
126    }
127
128    // do the rest of the comparison
129    msg = assertArchiveEquality(original, currentFiles);
130    assertNull(msg, msg);
131  }
132
133  private static String assertArchiveEquality(List<String> expected, List<String> archived) {
134    String compare = compareFileLists(expected, archived);
135    if (!(expected.size() == archived.size())) return "Not the same number of current files\n"
136        + compare;
137    if (!expected.equals(archived)) return "Different backup files, but same amount\n" + compare;
138    return null;
139  }
140
141  /**
142   * @return &lt;expected, gotten, backup&gt;, where each is sorted
143   */
144  private static List<List<String>> getFileLists(FileStatus[] previous, FileStatus[] archived) {
145    List<List<String>> files = new ArrayList<>(3);
146
147    // copy over the original files
148    List<String> originalFileNames = convertToString(previous);
149    files.add(originalFileNames);
150
151    List<String> currentFiles = new ArrayList<>(previous.length);
152    List<FileStatus> backedupFiles = new ArrayList<>(previous.length);
153    for (FileStatus f : archived) {
154      String name = f.getPath().getName();
155      // if the file has been backed up
156      if (name.contains(".")) {
157        Path parent = f.getPath().getParent();
158        String shortName = name.split("[.]")[0];
159        Path modPath = new Path(parent, shortName);
160        FileStatus file = new FileStatus(f.getLen(), f.isDirectory(), f.getReplication(),
161            f.getBlockSize(), f.getModificationTime(), modPath);
162        backedupFiles.add(file);
163      } else {
164        // otherwise, add it to the list to compare to the original store files
165        currentFiles.add(name);
166      }
167    }
168
169    files.add(currentFiles);
170    files.add(convertToString(backedupFiles));
171    return files;
172  }
173
174  private static List<String> convertToString(FileStatus[] files) {
175    return convertToString(Arrays.asList(files));
176  }
177
178  private static List<String> convertToString(List<FileStatus> files) {
179    List<String> originalFileNames = new ArrayList<>(files.size());
180    for (FileStatus f : files) {
181      originalFileNames.add(f.getPath().getName());
182    }
183    return originalFileNames;
184  }
185
186  /* Get a pretty representation of the differences */
187  private static String compareFileLists(List<String> expected, List<String> gotten) {
188    StringBuilder sb = new StringBuilder("Expected (" + expected.size() + "): \t\t Gotten ("
189        + gotten.size() + "):\n");
190    List<String> notFound = new ArrayList<>();
191    for (String s : expected) {
192      if (gotten.contains(s)) sb.append(s + "\t\t" + s + "\n");
193      else notFound.add(s);
194    }
195    sb.append("Not Found:\n");
196    for (String s : notFound) {
197      sb.append(s + "\n");
198    }
199    sb.append("\nExtra:\n");
200    for (String s : gotten) {
201      if (!expected.contains(s)) sb.append(s + "\n");
202    }
203    return sb.toString();
204  }
205
206  /**
207   * Helper method to get the archive directory for the specified region
208   * @param conf {@link Configuration} to check for the name of the archive directory
209   * @param region region that is being archived
210   * @return {@link Path} to the archive directory for the given region
211   */
212  public static Path getRegionArchiveDir(Configuration conf, HRegion region) throws IOException {
213    return HFileArchiveUtil.getRegionArchiveDir(CommonFSUtils.getRootDir(conf),
214      region.getTableDescriptor().getTableName(), region.getRegionInfo().getEncodedName());
215  }
216
217  /**
218   * Helper method to get the store archive directory for the specified region
219   * @param conf {@link Configuration} to check for the name of the archive directory
220   * @param region region that is being archived
221   * @param store store that is archiving files
222   * @return {@link Path} to the store archive directory for the given region
223   */
224  public static Path getStoreArchivePath(Configuration conf, HRegion region, Store store)
225      throws IOException {
226    return HFileArchiveUtil.getStoreArchivePath(conf, region.getRegionInfo(),
227        region.getRegionFileSystem().getTableDir(), store.getColumnFamilyDescriptor().getName());
228  }
229
230  public static Path getStoreArchivePath(HBaseTestingUtility util, String tableName,
231      byte[] storeName) throws IOException {
232    byte[] table = Bytes.toBytes(tableName);
233    // get the RS and region serving our table
234    List<HRegion> servingRegions = util.getHBaseCluster().getRegions(table);
235    HRegion region = servingRegions.get(0);
236
237    // check that we actually have some store files that were archived
238    Store store = region.getStore(storeName);
239    return HFileArchiveTestingUtil.getStoreArchivePath(util.getConfiguration(), region, store);
240  }
241}