View Javadoc

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.Collection;
26  import java.util.List;
27  import java.util.Set;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.conf.Configuration;
32  import org.apache.hadoop.fs.FileSystem;
33  import org.apache.hadoop.fs.Path;
34  import org.apache.hadoop.hbase.HBaseTestingUtility;
35  import org.apache.hadoop.hbase.HConstants;
36  import org.apache.hadoop.hbase.HTableDescriptor;
37  import org.apache.hadoop.hbase.testclassification.MediumTests;
38  import org.apache.hadoop.hbase.TableName;
39  import org.apache.hadoop.hbase.client.Admin;
40  import org.apache.hadoop.hbase.master.HMaster;
41  import org.apache.hadoop.hbase.master.snapshot.DisabledTableSnapshotHandler;
42  import org.apache.hadoop.hbase.master.snapshot.SnapshotHFileCleaner;
43  import org.apache.hadoop.hbase.master.snapshot.SnapshotManager;
44  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
45  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteSnapshotRequest;
46  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetCompletedSnapshotsRequest;
47  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetCompletedSnapshotsResponse;
48  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneRequest;
49  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneResponse;
50  import org.apache.hadoop.hbase.regionserver.CompactedHFilesDischarger;
51  import org.apache.hadoop.hbase.regionserver.ConstantSizeRegionSplitPolicy;
52  import org.apache.hadoop.hbase.regionserver.HRegion;
53  import org.apache.hadoop.hbase.regionserver.HRegionServer;
54  import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
55  import org.apache.hadoop.hbase.snapshot.SnapshotReferenceUtil;
56  import org.apache.hadoop.hbase.snapshot.SnapshotTestingUtils;
57  import org.apache.hadoop.hbase.snapshot.UnknownSnapshotException;
58  import org.apache.hadoop.hbase.util.Bytes;
59  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
60  import org.apache.hadoop.hbase.util.FSUtils;
61  import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread;
62  import org.junit.After;
63  import org.junit.AfterClass;
64  import org.junit.Before;
65  import org.junit.BeforeClass;
66  import org.junit.Test;
67  import org.junit.experimental.categories.Category;
68  import org.mockito.Mockito;
69  
70  import com.google.common.collect.Lists;
71  import com.google.protobuf.ServiceException;
72  
73  /**
74   * Test the master-related aspects of a snapshot
75   */
76  @Category(MediumTests.class)
77  public class TestSnapshotFromMaster {
78  
79    private static final Log LOG = LogFactory.getLog(TestSnapshotFromMaster.class);
80    private static final HBaseTestingUtility UTIL = new HBaseTestingUtility();
81    private static final int NUM_RS = 2;
82    private static Path rootDir;
83    private static FileSystem fs;
84    private static HMaster master;
85  
86    // for hfile archiving test.
87    private static Path archiveDir;
88    private static final byte[] TEST_FAM = Bytes.toBytes("fam");
89    private static final TableName TABLE_NAME =
90        TableName.valueOf("test");
91    // refresh the cache every 1/2 second
92    private static final long cacheRefreshPeriod = 500;
93  
94    /**
95     * Setup the config for the cluster
96     */
97    @BeforeClass
98    public static void setupCluster() throws Exception {
99      setupConf(UTIL.getConfiguration());
100     UTIL.startMiniCluster(NUM_RS);
101     fs = UTIL.getDFSCluster().getFileSystem();
102     master = UTIL.getMiniHBaseCluster().getMaster();
103     rootDir = master.getMasterFileSystem().getRootDir();
104     archiveDir = new Path(rootDir, HConstants.HFILE_ARCHIVE_DIRECTORY);
105   }
106 
107   private static void setupConf(Configuration conf) {
108     // disable the ui
109     conf.setInt("hbase.regionsever.info.port", -1);
110     // change the flush size to a small amount, regulating number of store files
111     conf.setInt("hbase.hregion.memstore.flush.size", 25000);
112     // so make sure we get a compaction when doing a load, but keep around some
113     // files in the store
114     conf.setInt("hbase.hstore.compaction.min", 2);
115     conf.setInt("hbase.hstore.compactionThreshold", 5);
116     // block writes if we get to 12 store files
117     conf.setInt("hbase.hstore.blockingStoreFiles", 12);
118     // Ensure no extra cleaners on by default (e.g. TimeToLiveHFileCleaner)
119     conf.set(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS, "");
120     conf.set(HConstants.HBASE_MASTER_LOGCLEANER_PLUGINS, "");
121     // Enable snapshot
122     conf.setBoolean(SnapshotManager.HBASE_SNAPSHOT_ENABLED, true);
123     conf.setLong(SnapshotHFileCleaner.HFILE_CACHE_REFRESH_PERIOD_CONF_KEY, cacheRefreshPeriod);
124     conf.set(HConstants.HBASE_REGION_SPLIT_POLICY_KEY,
125       ConstantSizeRegionSplitPolicy.class.getName());
126     conf.setInt("hbase.hfile.compactions.cleaner.interval", 20 * 1000);
127 
128   }
129 
130   @Before
131   public void setup() throws Exception {
132     UTIL.createTable(TABLE_NAME, TEST_FAM);
133     master.getSnapshotManager().setSnapshotHandlerForTesting(TABLE_NAME, null);
134   }
135 
136   @After
137   public void tearDown() throws Exception {
138     UTIL.deleteTable(TABLE_NAME);
139     SnapshotTestingUtils.deleteAllSnapshots(UTIL.getHBaseAdmin());
140     SnapshotTestingUtils.deleteArchiveDirectory(UTIL);
141   }
142 
143   @AfterClass
144   public static void cleanupTest() throws Exception {
145     try {
146       UTIL.shutdownMiniCluster();
147     } catch (Exception e) {
148       // NOOP;
149     }
150   }
151 
152   /**
153    * Test that the contract from the master for checking on a snapshot are valid.
154    * <p>
155    * <ol>
156    * <li>If a snapshot fails with an error, we expect to get the source error.</li>
157    * <li>If there is no snapshot name supplied, we should get an error.</li>
158    * <li>If asking about a snapshot has hasn't occurred, you should get an error.</li>
159    * </ol>
160    */
161   @Test(timeout = 300000)
162   public void testIsDoneContract() throws Exception {
163 
164     IsSnapshotDoneRequest.Builder builder = IsSnapshotDoneRequest.newBuilder();
165 
166     String snapshotName = "asyncExpectedFailureTest";
167 
168     // check that we get an exception when looking up snapshot where one hasn't happened
169     SnapshotTestingUtils.expectSnapshotDoneException(master, builder.build(),
170       UnknownSnapshotException.class);
171 
172     // and that we get the same issue, even if we specify a name
173     SnapshotDescription desc = SnapshotDescription.newBuilder()
174       .setName(snapshotName).setTable(TABLE_NAME.getNameAsString()).build();
175     builder.setSnapshot(desc);
176     SnapshotTestingUtils.expectSnapshotDoneException(master, builder.build(),
177       UnknownSnapshotException.class);
178 
179     // set a mock handler to simulate a snapshot
180     DisabledTableSnapshotHandler mockHandler = Mockito.mock(DisabledTableSnapshotHandler.class);
181     Mockito.when(mockHandler.getException()).thenReturn(null);
182     Mockito.when(mockHandler.getSnapshot()).thenReturn(desc);
183     Mockito.when(mockHandler.isFinished()).thenReturn(new Boolean(true));
184     Mockito.when(mockHandler.getCompletionTimestamp())
185       .thenReturn(EnvironmentEdgeManager.currentTime());
186 
187     master.getSnapshotManager()
188         .setSnapshotHandlerForTesting(TABLE_NAME, mockHandler);
189 
190     // if we do a lookup without a snapshot name, we should fail - you should always know your name
191     builder = IsSnapshotDoneRequest.newBuilder();
192     SnapshotTestingUtils.expectSnapshotDoneException(master, builder.build(),
193       UnknownSnapshotException.class);
194 
195     // then do the lookup for the snapshot that it is done
196     builder.setSnapshot(desc);
197     IsSnapshotDoneResponse response =
198       master.getMasterRpcServices().isSnapshotDone(null, builder.build());
199     assertTrue("Snapshot didn't complete when it should have.", response.getDone());
200 
201     // now try the case where we are looking for a snapshot we didn't take
202     builder.setSnapshot(SnapshotDescription.newBuilder().setName("Not A Snapshot").build());
203     SnapshotTestingUtils.expectSnapshotDoneException(master, builder.build(),
204       UnknownSnapshotException.class);
205 
206     // then create a snapshot to the fs and make sure that we can find it when checking done
207     snapshotName = "completed";
208     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
209     desc = desc.toBuilder().setName(snapshotName).build();
210     SnapshotDescriptionUtils.writeSnapshotInfo(desc, snapshotDir, fs);
211 
212     builder.setSnapshot(desc);
213     response = master.getMasterRpcServices().isSnapshotDone(null, builder.build());
214     assertTrue("Completed, on-disk snapshot not found", response.getDone());
215   }
216 
217   @Test(timeout = 300000)
218   public void testGetCompletedSnapshots() throws Exception {
219     // first check when there are no snapshots
220     GetCompletedSnapshotsRequest request = GetCompletedSnapshotsRequest.newBuilder().build();
221     GetCompletedSnapshotsResponse response =
222       master.getMasterRpcServices().getCompletedSnapshots(null, request);
223     assertEquals("Found unexpected number of snapshots", 0, response.getSnapshotsCount());
224 
225     // write one snapshot to the fs
226     String snapshotName = "completed";
227     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
228     SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName(snapshotName).build();
229     SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, snapshotDir, fs);
230 
231     // check that we get one snapshot
232     response = master.getMasterRpcServices().getCompletedSnapshots(null, request);
233     assertEquals("Found unexpected number of snapshots", 1, response.getSnapshotsCount());
234     List<SnapshotDescription> snapshots = response.getSnapshotsList();
235     List<SnapshotDescription> expected = Lists.newArrayList(snapshot);
236     assertEquals("Returned snapshots don't match created snapshots", expected, snapshots);
237 
238     // write a second snapshot
239     snapshotName = "completed_two";
240     snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
241     snapshot = SnapshotDescription.newBuilder().setName(snapshotName).build();
242     SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, snapshotDir, fs);
243     expected.add(snapshot);
244 
245     // check that we get one snapshot
246     response = master.getMasterRpcServices().getCompletedSnapshots(null, request);
247     assertEquals("Found unexpected number of snapshots", 2, response.getSnapshotsCount());
248     snapshots = response.getSnapshotsList();
249     assertEquals("Returned snapshots don't match created snapshots", expected, snapshots);
250   }
251 
252   @Test(timeout = 300000)
253   public void testDeleteSnapshot() throws Exception {
254 
255     String snapshotName = "completed";
256     SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName(snapshotName).build();
257 
258     DeleteSnapshotRequest request = DeleteSnapshotRequest.newBuilder().setSnapshot(snapshot)
259         .build();
260     try {
261       master.getMasterRpcServices().deleteSnapshot(null, request);
262       fail("Master didn't throw exception when attempting to delete snapshot that doesn't exist");
263     } catch (ServiceException e) {
264       LOG.debug("Correctly failed delete of non-existant snapshot:" + e.getMessage());
265     }
266 
267     // write one snapshot to the fs
268     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
269     SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, snapshotDir, fs);
270 
271     // then delete the existing snapshot,which shouldn't cause an exception to be thrown
272     master.getMasterRpcServices().deleteSnapshot(null, request);
273   }
274 
275   /**
276    * Test that the snapshot hfile archive cleaner works correctly. HFiles that are in snapshots
277    * should be retained, while those that are not in a snapshot should be deleted.
278    * @throws Exception on failure
279    */
280   @Test(timeout = 300000)
281   public void testSnapshotHFileArchiving() throws Exception {
282     Admin admin = UTIL.getHBaseAdmin();
283     // make sure we don't fail on listing snapshots
284     SnapshotTestingUtils.assertNoSnapshots(admin);
285 
286     // recreate test table with disabled compactions; otherwise compaction may happen before
287     // snapshot, the call after snapshot will be a no-op and checks will fail
288     UTIL.deleteTable(TABLE_NAME);
289     HTableDescriptor htd = new HTableDescriptor(TABLE_NAME);
290     htd.setCompactionEnabled(false);
291 
292     UTIL.createTable(htd, new byte[][] { TEST_FAM }, null);
293 
294     // load the table (creates at least 4 hfiles)
295     for ( int i = 0; i < 5; i++) {
296       UTIL.loadTable(UTIL.getConnection().getTable(TABLE_NAME), TEST_FAM);
297       UTIL.flush(TABLE_NAME);
298     }
299 
300     // disable the table so we can take a snapshot
301     admin.disableTable(TABLE_NAME);
302     htd.setCompactionEnabled(true);
303 
304     // take a snapshot of the table
305     String snapshotName = "snapshot";
306     byte[] snapshotNameBytes = Bytes.toBytes(snapshotName);
307     admin.snapshot(snapshotNameBytes, TABLE_NAME);
308 
309     LOG.info("After snapshot File-System state");
310     FSUtils.logFileSystemState(fs, rootDir, LOG);
311 
312     // ensure we only have one snapshot
313     SnapshotTestingUtils.assertOneSnapshotThatMatches(admin, snapshotNameBytes, TABLE_NAME);
314 
315     // enable compactions now
316     admin.modifyTable(TABLE_NAME, htd);
317 
318     // renable the table so we can compact the regions
319     admin.enableTable(TABLE_NAME);
320 
321     // compact the files so we get some archived files for the table we just snapshotted
322     List<HRegion> regions = UTIL.getHBaseCluster().getRegions(TABLE_NAME);
323     for (HRegion region : regions) {
324       region.waitForFlushesAndCompactions(); // enable can trigger a compaction, wait for it.
325       region.compactStores(); // min is 2 so will compact and archive
326     }
327     List<RegionServerThread> regionServerThreads = UTIL.getMiniHBaseCluster()
328         .getRegionServerThreads();
329     HRegionServer hrs = null;
330     for (RegionServerThread rs : regionServerThreads) {
331       if (!rs.getRegionServer().getOnlineRegions(TABLE_NAME).isEmpty()) {
332         hrs = rs.getRegionServer();
333         break;
334       }
335     }
336     CompactedHFilesDischarger cleaner = new CompactedHFilesDischarger(100, null, hrs, false);
337     cleaner.chore();
338     LOG.info("After compaction File-System state");
339     FSUtils.logFileSystemState(fs, rootDir, LOG);
340 
341     // make sure the cleaner has run
342     LOG.debug("Running hfile cleaners");
343     ensureHFileCleanersRun();
344     LOG.info("After cleaners File-System state: " + rootDir);
345     FSUtils.logFileSystemState(fs, rootDir, LOG);
346 
347     // get the snapshot files for the table
348     Path snapshotTable = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
349     Set<String> snapshotHFiles = SnapshotReferenceUtil.getHFileNames(
350         UTIL.getConfiguration(), fs, snapshotTable);
351     // check that the files in the archive contain the ones that we need for the snapshot
352     LOG.debug("Have snapshot hfiles:");
353     for (String fileName : snapshotHFiles) {
354       LOG.debug(fileName);
355     }
356     // get the archived files for the table
357     Collection<String> files = getArchivedHFiles(archiveDir, rootDir, fs, TABLE_NAME);
358 
359     // and make sure that there is a proper subset
360     for (String fileName : snapshotHFiles) {
361       assertTrue("Archived hfiles " + files + " is missing snapshot file:" + fileName,
362         files.contains(fileName));
363     }
364 
365     // delete the existing snapshot
366     admin.deleteSnapshot(snapshotNameBytes);
367     SnapshotTestingUtils.assertNoSnapshots(admin);
368 
369     // make sure that we don't keep around the hfiles that aren't in a snapshot
370     // make sure we wait long enough to refresh the snapshot hfile
371     List<BaseHFileCleanerDelegate> delegates = UTIL.getMiniHBaseCluster().getMaster()
372         .getHFileCleaner().cleanersChain;
373     for (BaseHFileCleanerDelegate delegate: delegates) {
374       if (delegate instanceof SnapshotHFileCleaner) {
375         ((SnapshotHFileCleaner)delegate).getFileCacheForTesting().triggerCacheRefreshForTesting();
376       }
377     }
378     // run the cleaner again
379     LOG.debug("Running hfile cleaners");
380     ensureHFileCleanersRun();
381     LOG.info("After delete snapshot cleaners run File-System state");
382     FSUtils.logFileSystemState(fs, rootDir, LOG);
383 
384     files = getArchivedHFiles(archiveDir, rootDir, fs, TABLE_NAME);
385     assertEquals("Still have some hfiles in the archive, when their snapshot has been deleted.", 0,
386       files.size());
387   }
388 
389   /**
390    * @return all the HFiles for a given table that have been archived
391    * @throws IOException on expected failure
392    */
393   private final Collection<String> getArchivedHFiles(Path archiveDir, Path rootDir,
394       FileSystem fs, TableName tableName) throws IOException {
395     Path tableArchive = FSUtils.getTableDir(archiveDir, tableName);
396     return SnapshotTestingUtils.listHFileNames(fs, tableArchive);
397   }
398 
399   /**
400    * Make sure the {@link HFileCleaner HFileCleaners} run at least once
401    */
402   private static void ensureHFileCleanersRun() {
403     UTIL.getHBaseCluster().getMaster().getHFileCleaner().chore();
404   }
405 }