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.snapshot;
19  
20  import java.io.IOException;
21  import java.util.Collection;
22  import java.util.HashMap;
23  import java.util.HashSet;
24  import java.util.List;
25  import java.util.Map;
26  import java.util.Set;
27  import java.util.Timer;
28  import java.util.TimerTask;
29  import java.util.concurrent.locks.Lock;
30  
31  import com.google.common.collect.Lists;
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.fs.PathFilter;
35  import org.apache.hadoop.hbase.classification.InterfaceAudience;
36  import org.apache.hadoop.hbase.classification.InterfaceStability;
37  import org.apache.hadoop.conf.Configuration;
38  import org.apache.hadoop.fs.FileStatus;
39  import org.apache.hadoop.fs.FileSystem;
40  import org.apache.hadoop.fs.Path;
41  import org.apache.hadoop.hbase.Stoppable;
42  import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
43  import org.apache.hadoop.hbase.util.ArrayUtils;
44  import org.apache.hadoop.hbase.util.FSUtils;
45  
46  /**
47   * Intelligently keep track of all the files for all the snapshots.
48   * <p>
49   * A cache of files is kept to avoid querying the {@link FileSystem} frequently. If there is a cache
50   * miss the directory modification time is used to ensure that we don't rescan directories that we
51   * already have in cache. We only check the modification times of the snapshot directories
52   * (/hbase/.snapshot/[snapshot_name]) to determine if the files need to be loaded into the cache.
53   * <p>
54   * New snapshots will be added to the cache and deleted snapshots will be removed when we refresh
55   * the cache. If the files underneath a snapshot directory are changed, but not the snapshot itself,
56   * we will ignore updates to that snapshot's files.
57   * <p>
58   * This is sufficient because each snapshot has its own directory and is added via an atomic rename
59   * <i>once</i>, when the snapshot is created. We don't need to worry about the data in the snapshot
60   * being run.
61   * <p>
62   * Further, the cache is periodically refreshed ensure that files in snapshots that were deleted are
63   * also removed from the cache.
64   * <p>
65   * A {@link SnapshotFileCache.SnapshotFileInspector} must be passed when creating <tt>this</tt> to
66   * allow extraction of files under /hbase/.snapshot/[snapshot name] directory, for each snapshot.
67   * This allows you to only cache files under, for instance, all the logs in the .logs directory or
68   * all the files under all the regions.
69   * <p>
70   * <tt>this</tt> also considers all running snapshots (those under /hbase/.snapshot/.tmp) as valid
71   * snapshots and will attempt to cache files from those snapshots as well.
72   * <p>
73   * Queries about a given file are thread-safe with respect to multiple queries and cache refreshes.
74   */
75  @InterfaceAudience.Private
76  @InterfaceStability.Evolving
77  public class SnapshotFileCache implements Stoppable {
78    interface SnapshotFileInspector {
79      /**
80       * Returns a collection of file names needed by the snapshot.
81       * @param snapshotDir {@link Path} to the snapshot directory to scan.
82       * @return the collection of file names needed by the snapshot.
83       */
84      Collection<String> filesUnderSnapshot(final Path snapshotDir) throws IOException;
85    }
86  
87    private static final Log LOG = LogFactory.getLog(SnapshotFileCache.class);
88    private volatile boolean stop = false;
89    private final FileSystem fs;
90    private final SnapshotFileInspector fileInspector;
91    private final Path snapshotDir;
92    private final Set<String> cache = new HashSet<String>();
93    /**
94     * This is a helper map of information about the snapshot directories so we don't need to rescan
95     * them if they haven't changed since the last time we looked.
96     */
97    private final Map<String, SnapshotDirectoryInfo> snapshots =
98        new HashMap<String, SnapshotDirectoryInfo>();
99    private final Timer refreshTimer;
100 
101   /**
102    * Create a snapshot file cache for all snapshots under the specified [root]/.snapshot on the
103    * filesystem.
104    * <p>
105    * Immediately loads the file cache.
106    * @param conf to extract the configured {@link FileSystem} where the snapshots are stored and
107    *          hbase root directory
108    * @param cacheRefreshPeriod frequency (ms) with which the cache should be refreshed
109    * @param refreshThreadName name of the cache refresh thread
110    * @param inspectSnapshotFiles Filter to apply to each snapshot to extract the files.
111    * @throws IOException if the {@link FileSystem} or root directory cannot be loaded
112    */
113   public SnapshotFileCache(Configuration conf, long cacheRefreshPeriod, String refreshThreadName,
114       SnapshotFileInspector inspectSnapshotFiles) throws IOException {
115     this(FSUtils.getCurrentFileSystem(conf), FSUtils.getRootDir(conf), 0, cacheRefreshPeriod,
116       refreshThreadName, inspectSnapshotFiles);
117   }
118 
119   /**
120    * Create a snapshot file cache for all snapshots under the specified [root]/.snapshot on the
121    * filesystem
122    * @param fs {@link FileSystem} where the snapshots are stored
123    * @param rootDir hbase root directory
124    * @param cacheRefreshPeriod period (ms) with which the cache should be refreshed
125    * @param cacheRefreshDelay amount of time to wait for the cache to be refreshed
126    * @param refreshThreadName name of the cache refresh thread
127    * @param inspectSnapshotFiles Filter to apply to each snapshot to extract the files.
128    */
129   public SnapshotFileCache(FileSystem fs, Path rootDir, long cacheRefreshPeriod,
130       long cacheRefreshDelay, String refreshThreadName,
131       SnapshotFileInspector inspectSnapshotFiles) {
132     this.fs = fs;
133     this.fileInspector = inspectSnapshotFiles;
134     this.snapshotDir = SnapshotDescriptionUtils.getSnapshotsDir(rootDir);
135     // periodically refresh the file cache to make sure we aren't superfluously saving files.
136     this.refreshTimer = new Timer(refreshThreadName, true);
137     this.refreshTimer.scheduleAtFixedRate(new RefreshCacheTask(), cacheRefreshDelay,
138       cacheRefreshPeriod);
139   }
140 
141   /**
142    * Trigger a cache refresh, even if its before the next cache refresh. Does not affect pending
143    * cache refreshes.
144    * <p/>
145    * Blocks until the cache is refreshed.
146    * <p/>
147    * Exposed for TESTING.
148    */
149   public synchronized void triggerCacheRefreshForTesting() {
150     try {
151       refreshCache();
152     } catch (IOException e) {
153       LOG.warn("Failed to refresh snapshot hfile cache!", e);
154     }
155     LOG.debug("Current cache:" + cache);
156   }
157 
158   /**
159    * Check to see if any of the passed file names is contained in any of the snapshots. First checks
160    * an in-memory cache of the files to keep. If its not in the cache, then the cache is refreshed
161    * and the cache checked again for that file. This ensures that we never return files that exist.
162    * <p>
163    * Note this may lead to periodic false positives for the file being referenced. Periodically, the
164    * cache is refreshed even if there are no requests to ensure that the false negatives get removed
165    * eventually. For instance, suppose you have a file in the snapshot and it gets loaded into the
166    * cache. Then at some point later that snapshot is deleted. If the cache has not been refreshed
167    * at that point, cache will still think the file system contains that file and return
168    * <tt>true</tt>, even if it is no longer present (false positive). However, if the file never was
169    * on the filesystem, we will never find it and always return <tt>false</tt>.
170    * @param files file to check, NOTE: Relies that files are loaded from hdfs before method is
171    *          called (NOT LAZY)
172    * @return <tt>unReferencedFiles</tt> the collection of files that do not have snapshot references
173    * @throws IOException if there is an unexpected error reaching the filesystem.
174    */
175   // XXX this is inefficient to synchronize on the method, when what we really need to guard against
176   // is an illegal access to the cache. Really we could do a mutex-guarded pointer swap on the
177   // cache, but that seems overkill at the moment and isn't necessarily a bottleneck.
178   public synchronized Iterable<FileStatus> getUnreferencedFiles(Iterable<FileStatus> files,
179       final SnapshotManager snapshotManager) throws IOException {
180     List<FileStatus> unReferencedFiles = Lists.newArrayList();
181     boolean refreshed = false;
182     Lock lock = null;
183     if (snapshotManager != null) {
184       lock = snapshotManager.getTakingSnapshotLock().writeLock();
185     }
186     if (lock == null || lock.tryLock()) {
187       try {
188         if (snapshotManager != null && snapshotManager.isTakingAnySnapshot()) {
189           LOG.warn("Not checking unreferenced files since snapshot is running, it will " +
190             "skip to clean the HFiles this time");
191           return unReferencedFiles;
192         }
193         for (FileStatus file : files) {
194           String fileName = file.getPath().getName();
195           if (!refreshed && !cache.contains(fileName)) {
196             refreshCache();
197             refreshed = true;
198           }
199           if (cache.contains(fileName)) {
200             continue;
201           }
202           unReferencedFiles.add(file);
203         }
204       } finally {
205         if (lock != null) {
206           lock.unlock();
207         }
208       }
209     }
210     return unReferencedFiles;
211   }
212 
213   private void refreshCache() throws IOException {
214     // just list the snapshot directory directly, do not check the modification time for the root
215     // snapshot directory, as some file system implementations do not modify the parent directory's
216     // modTime when there are new sub items, for example, S3.
217     FileStatus[] snapshotDirs = FSUtils.listStatus(fs, snapshotDir, new PathFilter() {
218       @Override
219       public boolean accept(Path path) {
220         return !path.getName().equals(SnapshotDescriptionUtils.SNAPSHOT_TMP_DIR_NAME);
221       }
222     });
223     // clear the cache, as in the below code, either we will also clear the snapshots, or we will
224     // refill the file name cache again.
225     this.cache.clear();
226     if (ArrayUtils.isEmpty(snapshotDirs)) {
227       // remove all the remembered snapshots because we don't have any left
228       if (LOG.isDebugEnabled() && this.snapshots.size() > 0) {
229         LOG.debug("No snapshots on-disk, clear cache");
230       }
231       this.snapshots.clear();
232       return;
233     }
234 
235     // iterate over all the cached snapshots and see if we need to update some, it is not an
236     // expensive operation if we do not reload the manifest of snapshots.
237     Map<String, SnapshotDirectoryInfo> newSnapshots = new HashMap<>();
238     for (FileStatus snapshotDir : snapshotDirs) {
239       String name = snapshotDir.getPath().getName();
240       SnapshotDirectoryInfo files = this.snapshots.remove(name);
241       // if we don't know about the snapshot or its been modified, we need to update the
242       // files the latter could occur where I create a snapshot, then delete it, and then make a
243       // new snapshot with the same name. We will need to update the cache the information from
244       // that new snapshot, even though it has the same name as the files referenced have
245       // probably changed.
246       if (files == null || files.hasBeenModified(snapshotDir.getModificationTime())) {
247         Collection<String> storedFiles = fileInspector.filesUnderSnapshot(snapshotDir.getPath());
248         files = new SnapshotDirectoryInfo(snapshotDir.getModificationTime(), storedFiles);
249       }
250       // add all the files to cache
251       this.cache.addAll(files.getFiles());
252       newSnapshots.put(name, files);
253     }
254     // set the snapshots we are tracking
255     this.snapshots.clear();
256     this.snapshots.putAll(newSnapshots);
257   }
258 
259   /**
260    * Simple helper task that just periodically attempts to refresh the cache
261    */
262   public class RefreshCacheTask extends TimerTask {
263     @Override
264     public void run() {
265       synchronized (SnapshotFileCache.this) {
266         try {
267           SnapshotFileCache.this.refreshCache();
268         } catch (IOException e) {
269           LOG.warn("Failed to refresh snapshot hfile cache!", e);
270           // clear all the cached entries if we meet an error
271           cache.clear();
272           snapshots.clear();
273         }
274       }
275 
276     }
277   }
278 
279   @Override
280   public void stop(String why) {
281     if (!this.stop) {
282       this.stop = true;
283       this.refreshTimer.cancel();
284     }
285 
286   }
287 
288   @Override
289   public boolean isStopped() {
290     return this.stop;
291   }
292 
293   /**
294    * Information about a snapshot directory
295    */
296   private static class SnapshotDirectoryInfo {
297     long lastModified;
298     Collection<String> files;
299 
300     public SnapshotDirectoryInfo(long mtime, Collection<String> files) {
301       this.lastModified = mtime;
302       this.files = files;
303     }
304 
305     /**
306      * @return the hfiles in the snapshot when <tt>this</tt> was made.
307      */
308     public Collection<String> getFiles() {
309       return this.files;
310     }
311 
312     /**
313      * Check if the snapshot directory has been modified
314      * @param mtime current modification time of the directory
315      * @return <tt>true</tt> if it the modification time of the directory is newer time when we
316      *         created <tt>this</tt>
317      */
318     public boolean hasBeenModified(long mtime) {
319       return this.lastModified < mtime;
320     }
321   }
322 }