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