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