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.mapreduce;
019
020import static org.junit.Assert.assertFalse;
021
022import java.io.IOException;
023import java.util.Arrays;
024import org.apache.hadoop.conf.Configuration;
025import org.apache.hadoop.fs.FileStatus;
026import org.apache.hadoop.fs.FileSystem;
027import org.apache.hadoop.fs.Path;
028import org.apache.hadoop.hbase.Cell;
029import org.apache.hadoop.hbase.CellScanner;
030import org.apache.hadoop.hbase.HBaseTestingUtil;
031import org.apache.hadoop.hbase.StartTestingClusterOption;
032import org.apache.hadoop.hbase.TableName;
033import org.apache.hadoop.hbase.client.Admin;
034import org.apache.hadoop.hbase.client.Result;
035import org.apache.hadoop.hbase.client.Table;
036import org.apache.hadoop.hbase.io.HFileLink;
037import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
038import org.apache.hadoop.hbase.master.snapshot.SnapshotManager;
039import org.apache.hadoop.hbase.regionserver.StoreFileInfo;
040import org.apache.hadoop.hbase.snapshot.SnapshotTestingUtils;
041import org.apache.hadoop.hbase.util.Bytes;
042import org.apache.hadoop.hbase.util.CommonFSUtils;
043import org.apache.hadoop.hbase.util.FSUtils;
044import org.apache.hadoop.hbase.util.HFileArchiveUtil;
045import org.junit.After;
046import org.junit.Assert;
047import org.junit.Before;
048import org.junit.Test;
049import org.slf4j.Logger;
050import org.slf4j.LoggerFactory;
051
052public abstract class TableSnapshotInputFormatTestBase {
053  private static final Logger LOG = LoggerFactory.getLogger(TableSnapshotInputFormatTestBase.class);
054  protected final HBaseTestingUtil UTIL = new HBaseTestingUtil();
055  protected static final int NUM_REGION_SERVERS = 2;
056  protected static final byte[][] FAMILIES = {Bytes.toBytes("f1"), Bytes.toBytes("f2")};
057
058  protected FileSystem fs;
059  protected Path rootDir;
060
061  @Before
062  public void setupCluster() throws Exception {
063    setupConf(UTIL.getConfiguration());
064    StartTestingClusterOption option = StartTestingClusterOption.builder()
065        .numRegionServers(NUM_REGION_SERVERS).numDataNodes(NUM_REGION_SERVERS)
066        .createRootDir(true).build();
067    UTIL.startMiniCluster(option);
068    rootDir = UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getRootDir();
069    fs = rootDir.getFileSystem(UTIL.getConfiguration());
070  }
071
072  @After
073  public void tearDownCluster() throws Exception {
074    UTIL.shutdownMiniCluster();
075  }
076
077  private static void setupConf(Configuration conf) {
078    // Enable snapshot
079    conf.setBoolean(SnapshotManager.HBASE_SNAPSHOT_ENABLED, true);
080  }
081
082  protected abstract void testWithMockedMapReduce(HBaseTestingUtil util, String snapshotName,
083    int numRegions, int numSplitsPerRegion, int expectedNumSplits, boolean setLocalityEnabledTo)
084    throws Exception;
085
086  protected abstract void testWithMapReduceImpl(HBaseTestingUtil util, TableName tableName,
087    String snapshotName, Path tableDir, int numRegions, int numSplitsPerRegion,
088    int expectedNumSplits, boolean shutdownCluster) throws Exception;
089
090  protected abstract byte[] getStartRow();
091
092  protected abstract byte[] getEndRow();
093
094  @Test
095  public void testWithMockedMapReduceSingleRegion() throws Exception {
096    testWithMockedMapReduce(UTIL, "testWithMockedMapReduceSingleRegion", 1, 1, 1, true);
097  }
098
099  @Test
100  public void testWithMockedMapReduceMultiRegion() throws Exception {
101    testWithMockedMapReduce(UTIL, "testWithMockedMapReduceMultiRegion", 10, 1, 8, false);
102  }
103
104  @Test
105  public void testWithMapReduceSingleRegion() throws Exception {
106    testWithMapReduce(UTIL, "testWithMapReduceSingleRegion", 1, 1, 1, false);
107  }
108
109  @Test
110  public void testWithMapReduceMultiRegion() throws Exception {
111    testWithMapReduce(UTIL, "testWithMapReduceMultiRegion", 10, 1, 8, false);
112  }
113
114  @Test
115  // run the MR job while HBase is offline
116  public void testWithMapReduceAndOfflineHBaseMultiRegion() throws Exception {
117    testWithMapReduce(UTIL, "testWithMapReduceAndOfflineHBaseMultiRegion", 10, 1, 8, true);
118  }
119
120  // Test that snapshot restore does not create back references in the HBase root dir.
121  @Test
122  public void testRestoreSnapshotDoesNotCreateBackRefLinks() throws Exception {
123    TableName tableName = TableName.valueOf("testRestoreSnapshotDoesNotCreateBackRefLinks");
124    String snapshotName = "foo";
125
126    try {
127      createTableAndSnapshot(UTIL, tableName, snapshotName, getStartRow(), getEndRow(), 1);
128
129      Path tmpTableDir = UTIL.getDataTestDirOnTestFS(snapshotName);
130
131      testRestoreSnapshotDoesNotCreateBackRefLinksInit(tableName, snapshotName,tmpTableDir);
132
133      Path rootDir = CommonFSUtils.getRootDir(UTIL.getConfiguration());
134      for (Path regionDir : FSUtils.getRegionDirs(fs,
135        CommonFSUtils.getTableDir(rootDir, tableName))) {
136        for (Path storeDir : FSUtils.getFamilyDirs(fs, regionDir)) {
137          for (FileStatus status : fs.listStatus(storeDir)) {
138            System.out.println(status.getPath());
139            if (StoreFileInfo.isValid(status)) {
140              Path archiveStoreDir = HFileArchiveUtil.getStoreArchivePath(UTIL.getConfiguration(),
141                tableName, regionDir.getName(), storeDir.getName());
142
143              Path path = HFileLink.getBackReferencesDir(storeDir, status.getPath().getName());
144              // assert back references directory is empty
145              assertFalse("There is a back reference in " + path, fs.exists(path));
146
147              path = HFileLink.getBackReferencesDir(archiveStoreDir, status.getPath().getName());
148              // assert back references directory is empty
149              assertFalse("There is a back reference in " + path, fs.exists(path));
150            }
151          }
152        }
153      }
154    } finally {
155      UTIL.getAdmin().deleteSnapshot(snapshotName);
156      UTIL.deleteTable(tableName);
157    }
158  }
159
160  public abstract void testRestoreSnapshotDoesNotCreateBackRefLinksInit(TableName tableName,
161      String snapshotName, Path tmpTableDir) throws Exception;
162
163  protected void testWithMapReduce(HBaseTestingUtil util, String snapshotName, int numRegions,
164      int numSplitsPerRegion, int expectedNumSplits, boolean shutdownCluster) throws Exception {
165    Path tableDir = util.getDataTestDirOnTestFS(snapshotName);
166    TableName tableName = TableName.valueOf("testWithMapReduce");
167    testWithMapReduceImpl(util, tableName, snapshotName, tableDir, numRegions, numSplitsPerRegion,
168      expectedNumSplits, shutdownCluster);
169  }
170
171  protected static void verifyRowFromMap(ImmutableBytesWritable key, Result result)
172    throws IOException {
173    byte[] row = key.get();
174    CellScanner scanner = result.cellScanner();
175    while (scanner.advance()) {
176      Cell cell = scanner.current();
177
178      //assert that all Cells in the Result have the same key
179      Assert.assertEquals(0, Bytes.compareTo(row, 0, row.length,
180        cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()));
181    }
182
183    for (byte[] family : FAMILIES) {
184      byte[] actual = result.getValue(family, family);
185      Assert.assertArrayEquals(
186        "Row in snapshot does not match, expected:" + Bytes.toString(row) + " ,actual:" + Bytes
187          .toString(actual), row, actual);
188    }
189  }
190
191  protected static void createTableAndSnapshot(HBaseTestingUtil util, TableName tableName,
192    String snapshotName, byte[] startRow, byte[] endRow, int numRegions)
193    throws Exception {
194    try {
195      LOG.debug("Ensuring table doesn't exist.");
196      util.deleteTable(tableName);
197    } catch(Exception ex) {
198      // ignore
199    }
200
201    LOG.info("creating table '" + tableName + "'");
202    if (numRegions > 1) {
203      util.createTable(tableName, FAMILIES, 1, startRow, endRow, numRegions);
204    } else {
205      util.createTable(tableName, FAMILIES);
206    }
207    Admin admin = util.getAdmin();
208
209    LOG.info("put some stuff in the table");
210    Table table = util.getConnection().getTable(tableName);
211    util.loadTable(table, FAMILIES);
212
213    Path rootDir = CommonFSUtils.getRootDir(util.getConfiguration());
214    FileSystem fs = rootDir.getFileSystem(util.getConfiguration());
215
216    LOG.info("snapshot");
217    SnapshotTestingUtils.createSnapshotAndValidate(admin, tableName,
218      Arrays.asList(FAMILIES), null, snapshotName, rootDir, fs, true);
219
220    LOG.info("load different values");
221    byte[] value = Bytes.toBytes("after_snapshot_value");
222    util.loadTable(table, FAMILIES, value);
223
224    LOG.info("cause flush to create new files in the region");
225    admin.flush(tableName);
226    table.close();
227  }
228}