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  // run the MR job while HBase is offline
108  public void testWithMapReduceAndOfflineHBaseMultiRegion() throws Exception {
109    testWithMapReduce(UTIL, "testWithMapReduceAndOfflineHBaseMultiRegion", 10, 1, 8, true);
110  }
111
112  // Test that snapshot restore does not create back references in the HBase root dir.
113  @Test
114  public void testRestoreSnapshotDoesNotCreateBackRefLinks() throws Exception {
115    setupCluster();
116    TableName tableName = TableName.valueOf("testRestoreSnapshotDoesNotCreateBackRefLinks");
117    String snapshotName = "foo";
118
119    try {
120      createTableAndSnapshot(UTIL, tableName, snapshotName, getStartRow(), getEndRow(), 1);
121
122      Path tmpTableDir = UTIL.getDataTestDirOnTestFS(snapshotName);
123
124      testRestoreSnapshotDoesNotCreateBackRefLinksInit(tableName, snapshotName,tmpTableDir);
125
126      Path rootDir = FSUtils.getRootDir(UTIL.getConfiguration());
127      for (Path regionDir : FSUtils.getRegionDirs(fs, FSUtils.getTableDir(rootDir, tableName))) {
128        for (Path storeDir : FSUtils.getFamilyDirs(fs, regionDir)) {
129          for (FileStatus status : fs.listStatus(storeDir)) {
130            System.out.println(status.getPath());
131            if (StoreFileInfo.isValid(status)) {
132              Path archiveStoreDir = HFileArchiveUtil.getStoreArchivePath(UTIL.getConfiguration(),
133                tableName, regionDir.getName(), storeDir.getName());
134
135              Path path = HFileLink.getBackReferencesDir(storeDir, status.getPath().getName());
136              // assert back references directory is empty
137              assertFalse("There is a back reference in " + path, fs.exists(path));
138
139              path = HFileLink.getBackReferencesDir(archiveStoreDir, status.getPath().getName());
140              // assert back references directory is empty
141              assertFalse("There is a back reference in " + path, fs.exists(path));
142            }
143          }
144        }
145      }
146    } finally {
147      UTIL.getAdmin().deleteSnapshot(snapshotName);
148      UTIL.deleteTable(tableName);
149      tearDownCluster();
150    }
151  }
152
153  public abstract void testRestoreSnapshotDoesNotCreateBackRefLinksInit(TableName tableName,
154      String snapshotName, Path tmpTableDir) throws Exception;
155
156  protected void testWithMapReduce(HBaseTestingUtility util, String snapshotName,
157      int numRegions, int numSplitsPerRegion, int expectedNumSplits, boolean shutdownCluster) throws Exception {
158    setupCluster();
159    try {
160      Path tableDir = util.getDataTestDirOnTestFS(snapshotName);
161      TableName tableName = TableName.valueOf("testWithMapReduce");
162      testWithMapReduceImpl(util, tableName, snapshotName, tableDir, numRegions,
163              numSplitsPerRegion, expectedNumSplits, shutdownCluster);
164    } finally {
165      tearDownCluster();
166    }
167  }
168
169  protected static void verifyRowFromMap(ImmutableBytesWritable key, Result result)
170    throws IOException {
171    byte[] row = key.get();
172    CellScanner scanner = result.cellScanner();
173    while (scanner.advance()) {
174      Cell cell = scanner.current();
175
176      //assert that all Cells in the Result have the same key
177      Assert.assertEquals(0, Bytes.compareTo(row, 0, row.length,
178        cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()));
179    }
180
181    for (int j = 0; j < FAMILIES.length; j++) {
182      byte[] actual = result.getValue(FAMILIES[j], FAMILIES[j]);
183      Assert.assertArrayEquals("Row in snapshot does not match, expected:" + Bytes.toString(row)
184        + " ,actual:" + Bytes.toString(actual), row, actual);
185    }
186  }
187
188  protected static void createTableAndSnapshot(HBaseTestingUtility util, TableName tableName,
189    String snapshotName, byte[] startRow, byte[] endRow, int numRegions)
190    throws Exception {
191    try {
192      LOG.debug("Ensuring table doesn't exist.");
193      util.deleteTable(tableName);
194    } catch(Exception ex) {
195      // ignore
196    }
197
198    LOG.info("creating table '" + tableName + "'");
199    if (numRegions > 1) {
200      util.createTable(tableName, FAMILIES, 1, startRow, endRow, numRegions);
201    } else {
202      util.createTable(tableName, FAMILIES);
203    }
204    Admin admin = util.getAdmin();
205
206    LOG.info("put some stuff in the table");
207    Table table = util.getConnection().getTable(tableName);
208    util.loadTable(table, FAMILIES);
209
210    Path rootDir = FSUtils.getRootDir(util.getConfiguration());
211    FileSystem fs = rootDir.getFileSystem(util.getConfiguration());
212
213    LOG.info("snapshot");
214    SnapshotTestingUtils.createSnapshotAndValidate(admin, tableName,
215      Arrays.asList(FAMILIES), null, snapshotName, rootDir, fs, true);
216
217    LOG.info("load different values");
218    byte[] value = Bytes.toBytes("after_snapshot_value");
219    util.loadTable(table, FAMILIES, value);
220
221    LOG.info("cause flush to create new files in the region");
222    admin.flush(tableName);
223    table.close();
224  }
225
226}