1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.master.cleaner;
19  
20  import static org.junit.Assert.assertEquals;
21  import static org.junit.Assert.assertTrue;
22  import static org.junit.Assert.fail;
23  
24  import java.io.IOException;
25  import java.util.ArrayList;
26  import java.util.Collection;
27  import java.util.Collections;
28  import java.util.List;
29  
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.apache.hadoop.conf.Configuration;
33  import org.apache.hadoop.fs.FileStatus;
34  import org.apache.hadoop.fs.FileSystem;
35  import org.apache.hadoop.fs.Path;
36  import org.apache.hadoop.hbase.HBaseTestingUtility;
37  import org.apache.hadoop.hbase.HConstants;
38  import org.apache.hadoop.hbase.MediumTests;
39  import org.apache.hadoop.hbase.client.HBaseAdmin;
40  import org.apache.hadoop.hbase.client.HTable;
41  import org.apache.hadoop.hbase.master.HMaster;
42  import org.apache.hadoop.hbase.master.snapshot.DisabledTableSnapshotHandler;
43  import org.apache.hadoop.hbase.master.snapshot.SnapshotHFileCleaner;
44  import org.apache.hadoop.hbase.master.snapshot.SnapshotManager;
45  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
46  import org.apache.hadoop.hbase.regionserver.ConstantSizeRegionSplitPolicy;
47  import org.apache.hadoop.hbase.regionserver.HRegion;
48  import org.apache.hadoop.hbase.snapshot.HSnapshotDescription;
49  import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
50  import org.apache.hadoop.hbase.snapshot.SnapshotTestingUtils;
51  import org.apache.hadoop.hbase.snapshot.UnknownSnapshotException;
52  import org.apache.hadoop.hbase.util.Bytes;
53  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
54  import org.apache.hadoop.hbase.util.FSUtils;
55  import org.apache.hadoop.hbase.util.HFileArchiveUtil;
56  import org.junit.After;
57  import org.junit.AfterClass;
58  import org.junit.Before;
59  import org.junit.BeforeClass;
60  import org.junit.Test;
61  import org.junit.experimental.categories.Category;
62  import org.mockito.Mockito;
63  
64  import com.google.common.collect.Lists;
65  
66  /**
67   * Test the master-related aspects of a snapshot
68   */
69  @Category(MediumTests.class)
70  public class TestSnapshotFromMaster {
71  
72    private static final Log LOG = LogFactory.getLog(TestSnapshotFromMaster.class);
73    private static final HBaseTestingUtility UTIL = new HBaseTestingUtility();
74    private static final int NUM_RS = 2;
75    private static Path rootDir;
76    private static Path snapshots;
77    private static FileSystem fs;
78    private static HMaster master;
79  
80    // for hfile archiving test.
81    private static Path archiveDir;
82    private static final String STRING_TABLE_NAME = "test";
83    private static final byte[] TEST_FAM = Bytes.toBytes("fam");
84    private static final byte[] TABLE_NAME = Bytes.toBytes(STRING_TABLE_NAME);
85    // refresh the cache every 1/2 second
86    private static final long cacheRefreshPeriod = 500;
87  
88    /**
89     * Setup the config for the cluster
90     */
91    @BeforeClass
92    public static void setupCluster() throws Exception {
93      setupConf(UTIL.getConfiguration());
94      UTIL.startMiniCluster(NUM_RS);
95      fs = UTIL.getDFSCluster().getFileSystem();
96      master = UTIL.getMiniHBaseCluster().getMaster();
97      rootDir = master.getMasterFileSystem().getRootDir();
98      snapshots = SnapshotDescriptionUtils.getSnapshotsDir(rootDir);
99      archiveDir = new Path(rootDir, HConstants.HFILE_ARCHIVE_DIRECTORY);
100   }
101 
102   private static void setupConf(Configuration conf) {
103     // disable the ui
104     conf.setInt("hbase.regionsever.info.port", -1);
105     // change the flush size to a small amount, regulating number of store files
106     conf.setInt("hbase.hregion.memstore.flush.size", 25000);
107     // so make sure we get a compaction when doing a load, but keep around some
108     // files in the store
109     conf.setInt("hbase.hstore.compaction.min", 3);
110     conf.setInt("hbase.hstore.compactionThreshold", 5);
111     // block writes if we get to 12 store files
112     conf.setInt("hbase.hstore.blockingStoreFiles", 12);
113     // drop the number of attempts for the hbase admin
114     conf.setInt("hbase.client.retries.number", 1);
115     // Ensure no extra cleaners on by default (e.g. TimeToLiveHFileCleaner)
116     conf.set(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS, "");
117     conf.set(HConstants.HBASE_MASTER_LOGCLEANER_PLUGINS, "");
118     // Enable snapshot
119     conf.setBoolean(SnapshotManager.HBASE_SNAPSHOT_ENABLED, true);
120     conf.setLong(SnapshotHFileCleaner.HFILE_CACHE_REFRESH_PERIOD_CONF_KEY, cacheRefreshPeriod);
121 
122     // prevent aggressive region split
123     conf.set(HConstants.HBASE_REGION_SPLIT_POLICY_KEY,
124       ConstantSizeRegionSplitPolicy.class.getName());
125   }
126 
127   @Before
128   public void setup() throws Exception {
129     UTIL.createTable(TABLE_NAME, TEST_FAM);
130     master.getSnapshotManagerForTesting().setSnapshotHandlerForTesting(STRING_TABLE_NAME, null);
131   }
132 
133   @After
134   public void tearDown() throws Exception {
135     UTIL.deleteTable(TABLE_NAME);
136     SnapshotTestingUtils.deleteAllSnapshots(UTIL.getHBaseAdmin());
137     SnapshotTestingUtils.deleteArchiveDirectory(UTIL);
138   }
139 
140   @AfterClass
141   public static void cleanupTest() throws Exception {
142     try {
143       UTIL.shutdownMiniCluster();
144     } catch (Exception e) {
145       // NOOP;
146     }
147   }
148 
149   /**
150    * Test that the contract from the master for checking on a snapshot are valid.
151    * <p>
152    * <ol>
153    * <li>If a snapshot fails with an error, we expect to get the source error.</li>
154    * <li>If there is no snapshot name supplied, we should get an error.</li>
155    * <li>If asking about a snapshot has hasn't occurred, you should get an error.</li>
156    * </ol>
157    */
158   @Test(timeout = 60000)
159   public void testIsDoneContract() throws Exception {
160 
161     String snapshotName = "asyncExpectedFailureTest";
162 
163     // check that we get an exception when looking up snapshot where one hasn't happened
164     SnapshotTestingUtils.expectSnapshotDoneException(master, new HSnapshotDescription(),
165       UnknownSnapshotException.class);
166 
167     // and that we get the same issue, even if we specify a name
168     SnapshotDescription desc = SnapshotDescription.newBuilder()
169       .setName(snapshotName).setTable(STRING_TABLE_NAME).build();
170     SnapshotTestingUtils.expectSnapshotDoneException(master, new HSnapshotDescription(desc),
171       UnknownSnapshotException.class);
172 
173     // set a mock handler to simulate a snapshot
174     DisabledTableSnapshotHandler mockHandler = Mockito.mock(DisabledTableSnapshotHandler.class);
175     Mockito.when(mockHandler.getException()).thenReturn(null);
176     Mockito.when(mockHandler.getSnapshot()).thenReturn(desc);
177     Mockito.when(mockHandler.isFinished()).thenReturn(new Boolean(true));
178     Mockito.when(mockHandler.getCompletionTimestamp())
179       .thenReturn(EnvironmentEdgeManager.currentTimeMillis());
180 
181     master.getSnapshotManagerForTesting()
182         .setSnapshotHandlerForTesting(STRING_TABLE_NAME, mockHandler);
183 
184     // if we do a lookup without a snapshot name, we should fail - you should always know your name
185     SnapshotTestingUtils.expectSnapshotDoneException(master, new HSnapshotDescription(),
186       UnknownSnapshotException.class);
187 
188     // then do the lookup for the snapshot that it is done
189     boolean isDone = master.isSnapshotDone(new HSnapshotDescription(desc));
190     assertTrue("Snapshot didn't complete when it should have.", isDone);
191 
192     // now try the case where we are looking for a snapshot we didn't take
193     desc = SnapshotDescription.newBuilder().setName("Not A Snapshot").build();
194     SnapshotTestingUtils.expectSnapshotDoneException(master, new HSnapshotDescription(desc),
195       UnknownSnapshotException.class);
196 
197     // then create a snapshot to the fs and make sure that we can find it when checking done
198     snapshotName = "completed";
199     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
200     desc = desc.toBuilder().setName(snapshotName).build();
201     SnapshotDescriptionUtils.writeSnapshotInfo(desc, snapshotDir, fs);
202 
203     isDone = master.isSnapshotDone(new HSnapshotDescription(desc));
204     assertTrue("Completed, on-disk snapshot not found", isDone);
205   }
206 
207   @Test
208   public void testGetCompletedSnapshots() throws Exception {
209     // first check when there are no snapshots
210     List<HSnapshotDescription> snapshots = master.getCompletedSnapshots();
211     assertEquals("Found unexpected number of snapshots", 0, snapshots.size());
212 
213     // write one snapshot to the fs
214     String snapshotName = "completed";
215     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
216     SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName(snapshotName).build();
217     SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, snapshotDir, fs);
218 
219     // check that we get one snapshot
220     snapshots = master.getCompletedSnapshots();
221     assertEquals("Found unexpected number of snapshots", 1, snapshots.size());
222     List<HSnapshotDescription> expected = Lists.newArrayList(new HSnapshotDescription(snapshot));
223     assertEquals("Returned snapshots don't match created snapshots", expected, snapshots);
224 
225     // write a second snapshot
226     snapshotName = "completed_two";
227     snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
228     snapshot = SnapshotDescription.newBuilder().setName(snapshotName).build();
229     SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, snapshotDir, fs);
230     expected.add(new HSnapshotDescription(snapshot));
231 
232     // check that we get one snapshot
233     snapshots = master.getCompletedSnapshots();
234     assertEquals("Found unexpected number of snapshots", 2, snapshots.size());
235     assertEquals("Returned snapshots don't match created snapshots", expected, snapshots);
236   }
237 
238   @Test
239   public void testDeleteSnapshot() throws Exception {
240 
241     String snapshotName = "completed";
242     SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName(snapshotName).build();
243 
244     try {
245       master.deleteSnapshot(new HSnapshotDescription(snapshot));
246       fail("Master didn't throw exception when attempting to delete snapshot that doesn't exist");
247     } catch (IOException e) {
248       LOG.debug("Correctly failed delete of non-existant snapshot:" + e.getMessage());
249     }
250 
251     // write one snapshot to the fs
252     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
253     SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, snapshotDir, fs);
254 
255     // then delete the existing snapshot,which shouldn't cause an exception to be thrown
256     master.deleteSnapshot(new HSnapshotDescription(snapshot));
257   }
258 
259   /**
260    * Test that the snapshot hfile archive cleaner works correctly. HFiles that are in snapshots
261    * should be retained, while those that are not in a snapshot should be deleted.
262    * @throws Exception on failure
263    */
264   @Test
265   public void testSnapshotHFileArchiving() throws Exception {
266     HBaseAdmin admin = UTIL.getHBaseAdmin();
267     // make sure we don't fail on listing snapshots
268     SnapshotTestingUtils.assertNoSnapshots(admin);
269     // load the table
270     UTIL.loadTable(new HTable(UTIL.getConfiguration(), TABLE_NAME), TEST_FAM);
271 
272     // disable the table so we can take a snapshot
273     admin.disableTable(TABLE_NAME);
274 
275     // take a snapshot of the table
276     String snapshotName = "snapshot";
277     byte[] snapshotNameBytes = Bytes.toBytes(snapshotName);
278     admin.snapshot(snapshotNameBytes, TABLE_NAME);
279 
280     Configuration conf = master.getConfiguration();
281     LOG.info("After snapshot File-System state");
282     FSUtils.logFileSystemState(fs, rootDir, LOG);
283 
284     // ensure we only have one snapshot
285     SnapshotTestingUtils.assertOneSnapshotThatMatches(admin, snapshotNameBytes, TABLE_NAME);
286 
287     // renable the table so we can compact the regions
288     admin.enableTable(TABLE_NAME);
289 
290     // compact the files so we get some archived files for the table we just snapshotted
291     List<HRegion> regions = UTIL.getHBaseCluster().getRegions(TABLE_NAME);
292     for (HRegion region : regions) {
293       region.waitForFlushesAndCompactions(); // enable can trigger a compaction, wait for it.
294       region.compactStores();
295     }
296     LOG.info("After compaction File-System state");
297     FSUtils.logFileSystemState(fs, rootDir, LOG);
298 
299     // make sure the cleaner has run
300     LOG.debug("Running hfile cleaners");
301     ensureHFileCleanersRun();
302     LOG.info("After cleaners File-System state: " + rootDir);
303     FSUtils.logFileSystemState(fs, rootDir, LOG);
304 
305     // get the snapshot files for the table
306     Path snapshotTable = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
307     FileStatus[] snapshotHFiles = SnapshotTestingUtils.listHFiles(fs, snapshotTable);
308     // check that the files in the archive contain the ones that we need for the snapshot
309     LOG.debug("Have snapshot hfiles:");
310     for (FileStatus file : snapshotHFiles) {
311       LOG.debug(file.getPath());
312     }
313     // get the archived files for the table
314     Collection<String> files = getArchivedHFiles(archiveDir, rootDir, fs, STRING_TABLE_NAME);
315 
316     // and make sure that there is a proper subset
317     for (FileStatus file : snapshotHFiles) {
318       assertTrue("Archived hfiles " + files + " is missing snapshot file:" + file.getPath(),
319         files.contains(file.getPath().getName()));
320     }
321 
322     // delete the existing snapshot
323     admin.deleteSnapshot(snapshotNameBytes);
324     SnapshotTestingUtils.assertNoSnapshots(admin);
325 
326     // make sure that we don't keep around the hfiles that aren't in a snapshot
327     // make sure we wait long enough to refresh the snapshot hfile
328     List<BaseHFileCleanerDelegate> delegates = UTIL.getMiniHBaseCluster().getMaster()
329         .getHFileCleaner().cleanersChain;
330     for (BaseHFileCleanerDelegate delegate: delegates) {
331       if (delegate instanceof SnapshotHFileCleaner) {
332         ((SnapshotHFileCleaner)delegate).getFileCacheForTesting().triggerCacheRefreshForTesting();
333       }
334     }
335     // run the cleaner again
336     LOG.debug("Running hfile cleaners");
337     ensureHFileCleanersRun();
338     LOG.info("After delete snapshot cleaners run File-System state");
339     FSUtils.logFileSystemState(fs, rootDir, LOG);
340 
341     files = getArchivedHFiles(archiveDir, rootDir, fs, STRING_TABLE_NAME);
342     assertEquals("Still have some hfiles in the archive, when their snapshot has been deleted.", 0,
343       files.size());
344   }
345 
346   /**
347    * @return all the HFiles for a given table that have been archived
348    * @throws IOException on expected failure
349    */
350   private final Collection<String> getArchivedHFiles(Path archiveDir, Path rootDir,
351       FileSystem fs, String tableName) throws IOException {
352     Path tableArchive = new Path(archiveDir, tableName);
353     FileStatus[] archivedHFiles = SnapshotTestingUtils.listHFiles(fs, tableArchive);
354     List<String> files = new ArrayList<String>(archivedHFiles.length);
355     LOG.debug("Have archived hfiles: " + tableArchive);
356     for (FileStatus file : archivedHFiles) {
357       LOG.debug(file.getPath());
358       files.add(file.getPath().getName());
359     }
360     // sort the archived files
361 
362     Collections.sort(files);
363     return files;
364   }
365 
366   /**
367    * Make sure the {@link HFileCleaner HFileCleaners} run at least once
368    */
369   private static void ensureHFileCleanersRun() {
370     UTIL.getHBaseCluster().getMaster().getHFileCleaner().chore();
371   }
372 }