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 
137     // delete the archive directory, if its exists
138     if (fs.exists(archiveDir)) {
139       if (!fs.delete(archiveDir, true)) {
140         throw new IOException("Couldn't delete archive directory (" + archiveDir
141             + " for an unknown reason");
142       }
143     }
144 
145     // delete the snapshot directory, if its exists
146     if (fs.exists(snapshots)) {
147       if (!fs.delete(snapshots, true)) {
148         throw new IOException("Couldn't delete snapshots directory (" + snapshots
149             + " for an unknown reason");
150       }
151     }
152   }
153 
154   @AfterClass
155   public static void cleanupTest() throws Exception {
156     try {
157       UTIL.shutdownMiniCluster();
158     } catch (Exception e) {
159       // NOOP;
160     }
161   }
162 
163   /**
164    * Test that the contract from the master for checking on a snapshot are valid.
165    * <p>
166    * <ol>
167    * <li>If a snapshot fails with an error, we expect to get the source error.</li>
168    * <li>If there is no snapshot name supplied, we should get an error.</li>
169    * <li>If asking about a snapshot has hasn't occurred, you should get an error.</li>
170    * </ol>
171    */
172   @Test(timeout = 60000)
173   public void testIsDoneContract() throws Exception {
174 
175     String snapshotName = "asyncExpectedFailureTest";
176 
177     // check that we get an exception when looking up snapshot where one hasn't happened
178     SnapshotTestingUtils.expectSnapshotDoneException(master, new HSnapshotDescription(),
179       UnknownSnapshotException.class);
180 
181     // and that we get the same issue, even if we specify a name
182     SnapshotDescription desc = SnapshotDescription.newBuilder()
183       .setName(snapshotName).setTable(STRING_TABLE_NAME).build();
184     SnapshotTestingUtils.expectSnapshotDoneException(master, new HSnapshotDescription(desc),
185       UnknownSnapshotException.class);
186 
187     // set a mock handler to simulate a snapshot
188     DisabledTableSnapshotHandler mockHandler = Mockito.mock(DisabledTableSnapshotHandler.class);
189     Mockito.when(mockHandler.getException()).thenReturn(null);
190     Mockito.when(mockHandler.getSnapshot()).thenReturn(desc);
191     Mockito.when(mockHandler.isFinished()).thenReturn(new Boolean(true));
192     Mockito.when(mockHandler.getCompletionTimestamp())
193       .thenReturn(EnvironmentEdgeManager.currentTimeMillis());
194 
195     master.getSnapshotManagerForTesting()
196         .setSnapshotHandlerForTesting(STRING_TABLE_NAME, mockHandler);
197 
198     // if we do a lookup without a snapshot name, we should fail - you should always know your name
199     SnapshotTestingUtils.expectSnapshotDoneException(master, new HSnapshotDescription(),
200       UnknownSnapshotException.class);
201 
202     // then do the lookup for the snapshot that it is done
203     boolean isDone = master.isSnapshotDone(new HSnapshotDescription(desc));
204     assertTrue("Snapshot didn't complete when it should have.", isDone);
205 
206     // now try the case where we are looking for a snapshot we didn't take
207     desc = SnapshotDescription.newBuilder().setName("Not A Snapshot").build();
208     SnapshotTestingUtils.expectSnapshotDoneException(master, new HSnapshotDescription(desc),
209       UnknownSnapshotException.class);
210 
211     // then create a snapshot to the fs and make sure that we can find it when checking done
212     snapshotName = "completed";
213     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
214     desc = desc.toBuilder().setName(snapshotName).build();
215     SnapshotDescriptionUtils.writeSnapshotInfo(desc, snapshotDir, fs);
216 
217     isDone = master.isSnapshotDone(new HSnapshotDescription(desc));
218     assertTrue("Completed, on-disk snapshot not found", isDone);
219   }
220 
221   @Test
222   public void testGetCompletedSnapshots() throws Exception {
223     // first check when there are no snapshots
224     List<HSnapshotDescription> snapshots = master.getCompletedSnapshots();
225     assertEquals("Found unexpected number of snapshots", 0, snapshots.size());
226 
227     // write one snapshot to the fs
228     String snapshotName = "completed";
229     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
230     SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName(snapshotName).build();
231     SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, snapshotDir, fs);
232 
233     // check that we get one snapshot
234     snapshots = master.getCompletedSnapshots();
235     assertEquals("Found unexpected number of snapshots", 1, snapshots.size());
236     List<HSnapshotDescription> expected = Lists.newArrayList(new HSnapshotDescription(snapshot));
237     assertEquals("Returned snapshots don't match created snapshots", expected, snapshots);
238 
239     // write a second snapshot
240     snapshotName = "completed_two";
241     snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
242     snapshot = SnapshotDescription.newBuilder().setName(snapshotName).build();
243     SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, snapshotDir, fs);
244     expected.add(new HSnapshotDescription(snapshot));
245 
246     // check that we get one snapshot
247     snapshots = master.getCompletedSnapshots();
248     assertEquals("Found unexpected number of snapshots", 2, snapshots.size());
249     assertEquals("Returned snapshots don't match created snapshots", expected, snapshots);
250   }
251 
252   @Test
253   public void testDeleteSnapshot() throws Exception {
254 
255     String snapshotName = "completed";
256     SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName(snapshotName).build();
257 
258     try {
259       master.deleteSnapshot(new HSnapshotDescription(snapshot));
260       fail("Master didn't throw exception when attempting to delete snapshot that doesn't exist");
261     } catch (IOException e) {
262       LOG.debug("Correctly failed delete of non-existant snapshot:" + e.getMessage());
263     }
264 
265     // write one snapshot to the fs
266     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
267     SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, snapshotDir, fs);
268 
269     // then delete the existing snapshot,which shouldn't cause an exception to be thrown
270     master.deleteSnapshot(new HSnapshotDescription(snapshot));
271   }
272 
273   /**
274    * Test that the snapshot hfile archive cleaner works correctly. HFiles that are in snapshots
275    * should be retained, while those that are not in a snapshot should be deleted.
276    * @throws Exception on failure
277    */
278   @Test
279   public void testSnapshotHFileArchiving() throws Exception {
280     HBaseAdmin admin = UTIL.getHBaseAdmin();
281     // make sure we don't fail on listing snapshots
282     SnapshotTestingUtils.assertNoSnapshots(admin);
283     // load the table
284     UTIL.loadTable(new HTable(UTIL.getConfiguration(), TABLE_NAME), TEST_FAM);
285 
286     // disable the table so we can take a snapshot
287     admin.disableTable(TABLE_NAME);
288 
289     // take a snapshot of the table
290     String snapshotName = "snapshot";
291     byte[] snapshotNameBytes = Bytes.toBytes(snapshotName);
292     admin.snapshot(snapshotNameBytes, TABLE_NAME);
293 
294     Configuration conf = master.getConfiguration();
295     LOG.info("After snapshot File-System state");
296     FSUtils.logFileSystemState(fs, rootDir, LOG);
297 
298     // ensure we only have one snapshot
299     SnapshotTestingUtils.assertOneSnapshotThatMatches(admin, snapshotNameBytes, TABLE_NAME);
300 
301     // renable the table so we can compact the regions
302     admin.enableTable(TABLE_NAME);
303 
304     // compact the files so we get some archived files for the table we just snapshotted
305     List<HRegion> regions = UTIL.getHBaseCluster().getRegions(TABLE_NAME);
306     for (HRegion region : regions) {
307       region.waitForFlushesAndCompactions(); // enable can trigger a compaction, wait for it.
308       region.compactStores();
309     }
310     LOG.info("After compaction File-System state");
311     FSUtils.logFileSystemState(fs, rootDir, LOG);
312 
313     // make sure the cleaner has run
314     LOG.debug("Running hfile cleaners");
315     ensureHFileCleanersRun();
316     LOG.info("After cleaners File-System state: " + rootDir);
317     FSUtils.logFileSystemState(fs, rootDir, LOG);
318 
319     // get the snapshot files for the table
320     Path snapshotTable = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
321     FileStatus[] snapshotHFiles = SnapshotTestingUtils.listHFiles(fs, snapshotTable);
322     // check that the files in the archive contain the ones that we need for the snapshot
323     LOG.debug("Have snapshot hfiles:");
324     for (FileStatus file : snapshotHFiles) {
325       LOG.debug(file.getPath());
326     }
327     // get the archived files for the table
328     Collection<String> files = getArchivedHFiles(archiveDir, rootDir, fs, STRING_TABLE_NAME);
329 
330     // and make sure that there is a proper subset
331     for (FileStatus file : snapshotHFiles) {
332       assertTrue("Archived hfiles " + files + " is missing snapshot file:" + file.getPath(),
333         files.contains(file.getPath().getName()));
334     }
335 
336     // delete the existing snapshot
337     admin.deleteSnapshot(snapshotNameBytes);
338     SnapshotTestingUtils.assertNoSnapshots(admin);
339 
340     // make sure that we don't keep around the hfiles that aren't in a snapshot
341     // make sure we wait long enough to refresh the snapshot hfile
342     List<BaseHFileCleanerDelegate> delegates = UTIL.getMiniHBaseCluster().getMaster()
343         .getHFileCleaner().cleanersChain;
344     for (BaseHFileCleanerDelegate delegate: delegates) {
345       if (delegate instanceof SnapshotHFileCleaner) {
346         ((SnapshotHFileCleaner)delegate).getFileCacheForTesting().triggerCacheRefreshForTesting();
347       }
348     }
349     // run the cleaner again
350     LOG.debug("Running hfile cleaners");
351     ensureHFileCleanersRun();
352     LOG.info("After delete snapshot cleaners run File-System state");
353     FSUtils.logFileSystemState(fs, rootDir, LOG);
354 
355     files = getArchivedHFiles(archiveDir, rootDir, fs, STRING_TABLE_NAME);
356     assertEquals("Still have some hfiles in the archive, when their snapshot has been deleted.", 0,
357       files.size());
358   }
359 
360   /**
361    * @return all the HFiles for a given table that have been archived
362    * @throws IOException on expected failure
363    */
364   private final Collection<String> getArchivedHFiles(Path archiveDir, Path rootDir,
365       FileSystem fs, String tableName) throws IOException {
366     Path tableArchive = new Path(archiveDir, tableName);
367     FileStatus[] archivedHFiles = SnapshotTestingUtils.listHFiles(fs, tableArchive);
368     List<String> files = new ArrayList<String>(archivedHFiles.length);
369     LOG.debug("Have archived hfiles: " + tableArchive);
370     for (FileStatus file : archivedHFiles) {
371       LOG.debug(file.getPath());
372       files.add(file.getPath().getName());
373     }
374     // sort the archived files
375 
376     Collections.sort(files);
377     return files;
378   }
379 
380   /**
381    * Make sure the {@link HFileCleaner HFileCleaners} run at least once
382    */
383   private static void ensureHFileCleanersRun() {
384     UTIL.getHBaseCluster().getMaster().getHFileCleaner().chore();
385   }
386 }