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 java.io.IOException;
21  import java.util.ArrayList;
22  import java.util.Arrays;
23  import java.util.LinkedList;
24  import java.util.List;
25  import java.util.Map;
26  import java.util.concurrent.atomic.AtomicBoolean;
27  import java.util.concurrent.atomic.AtomicInteger;
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.FileStatus;
33  import org.apache.hadoop.fs.FileSystem;
34  import org.apache.hadoop.fs.Path;
35  import org.apache.hadoop.fs.PathIsNotEmptyDirectoryException;
36  import org.apache.hadoop.hbase.ScheduledChore;
37  import org.apache.hadoop.hbase.Stoppable;
38  import org.apache.hadoop.hbase.classification.InterfaceAudience;
39  import org.apache.hadoop.ipc.RemoteException;
40  
41  import com.google.common.annotations.VisibleForTesting;
42  import com.google.common.base.Preconditions;
43  import com.google.common.collect.ImmutableSet;
44  import com.google.common.collect.Iterables;
45  import com.google.common.collect.Lists;
46  
47  /**
48   * Abstract Cleaner that uses a chain of delegates to clean a directory of files
49   * @param <T> Cleaner delegate class that is dynamically loaded from configuration
50   */
51  @InterfaceAudience.Private
52  public abstract class CleanerChore<T extends FileCleanerDelegate> extends ScheduledChore {
53  
54    private static final Log LOG = LogFactory.getLog(CleanerChore.class.getName());
55    private static final int AVAIL_PROCESSORS = Runtime.getRuntime().availableProcessors();
56  
57    /**
58     * If it is an integer and >= 1, it would be the size;
59     * if 0.0 < size <= 1.0, size would be available processors * size.
60     * Pay attention that 1.0 is different from 1, former indicates it will use 100% of cores,
61     * while latter will use only 1 thread for chore to scan dir.
62     */
63    public static final String CHORE_POOL_SIZE = "hbase.cleaner.scan.dir.concurrent.size";
64    static final String DEFAULT_CHORE_POOL_SIZE = "0.25";
65    private final DirScanPool pool;
66  
67    protected final FileSystem fs;
68    private final Path oldFileDir;
69    private final Configuration conf;
70    protected List<T> cleanersChain;
71    protected Map<String, Object> params;
72    private AtomicBoolean enabled = new AtomicBoolean(true);
73  
74    public CleanerChore(String name, final int sleepPeriod, final Stoppable s, Configuration conf,
75      FileSystem fs, Path oldFileDir, String confKey, DirScanPool pool) {
76      this(name, sleepPeriod, s, conf, fs, oldFileDir, confKey, pool, null);
77    }
78  
79    /**
80     * @param name name of the chore being run
81     * @param sleepPeriod the period of time to sleep between each run
82     * @param s the stopper
83     * @param conf configuration to use
84     * @param fs handle to the FS
85     * @param oldFileDir the path to the archived files
86     * @param confKey configuration key for the classes to instantiate
87     * @param pool the thread pool used to scan directories
88     * @param params members could be used in cleaner
89     */
90    public CleanerChore(String name, final int sleepPeriod, final Stoppable s,
91      Configuration conf, FileSystem fs, Path oldFileDir, String confKey,
92      DirScanPool pool, Map<String, Object> params) {
93      super(name, s, sleepPeriod);
94  
95      Preconditions.checkNotNull(pool, "Chore's pool can not be null");
96      this.pool = pool;
97      this.fs = fs;
98      this.oldFileDir = oldFileDir;
99      this.conf = conf;
100     this.params = params;
101     initCleanerChain(confKey);
102   }
103 
104   /**
105    * Calculate size for cleaner pool.
106    * @param poolSize size from configuration
107    * @return size of pool after calculation
108    */
109   static int calculatePoolSize(String poolSize) {
110     if (poolSize.matches("[1-9][0-9]*")) {
111       // If poolSize is an integer, return it directly,
112       // but upmost to the number of available processors.
113       int size = Math.min(Integer.parseInt(poolSize), AVAIL_PROCESSORS);
114       if (size == AVAIL_PROCESSORS) {
115         LOG.warn("Use full core processors to scan dir, size=" + size);
116       }
117       return size;
118     } else if (poolSize.matches("0.[0-9]+|1.0")) {
119       // if poolSize is a double, return poolSize * availableProcessors;
120       // Ensure that we always return at least one.
121       int computedThreads = (int) (AVAIL_PROCESSORS * Double.valueOf(poolSize));
122       if (computedThreads < 1) {
123         LOG.debug("Computed " + computedThreads + " threads for CleanerChore, using 1 instead");
124         return 1;
125       }
126       return computedThreads;
127     } else {
128       LOG.error("Unrecognized value: " + poolSize + " for " + CHORE_POOL_SIZE +
129           ", use default config: " + DEFAULT_CHORE_POOL_SIZE + " instead.");
130       return calculatePoolSize(DEFAULT_CHORE_POOL_SIZE);
131     }
132   }
133 
134   /**
135    * Validate the file to see if it even belongs in the directory. If it is valid, then the file
136    * will go through the cleaner delegates, but otherwise the file is just deleted.
137    * @param file full {@link Path} of the file to be checked
138    * @return <tt>true</tt> if the file is valid, <tt>false</tt> otherwise
139    */
140   protected abstract boolean validate(Path file);
141 
142   /**
143    * Instantiate and initialize all the file cleaners set in the configuration
144    * @param confKey key to get the file cleaner classes from the configuration
145    */
146   private void initCleanerChain(String confKey) {
147     this.cleanersChain = new LinkedList<T>();
148     String[] logCleaners = conf.getStrings(confKey);
149     if (logCleaners != null) {
150       for (String className : logCleaners) {
151         T logCleaner = newFileCleaner(className, conf);
152         if (logCleaner != null) {
153           LOG.info("initialize cleaner=" + className);
154           this.cleanersChain.add(logCleaner);
155         }
156       }
157     }
158   }
159 
160   /**
161    * A utility method to create new instances of LogCleanerDelegate based on the class name of the
162    * LogCleanerDelegate.
163    * @param className fully qualified class name of the LogCleanerDelegate
164    * @param conf
165    * @return the new instance
166    */
167   private T newFileCleaner(String className, Configuration conf) {
168     try {
169       Class<? extends FileCleanerDelegate> c = Class.forName(className).asSubclass(
170         FileCleanerDelegate.class);
171       @SuppressWarnings("unchecked")
172       T cleaner = (T) c.getDeclaredConstructor().newInstance();
173       cleaner.setConf(conf);
174       cleaner.init(this.params);
175       return cleaner;
176     } catch (Exception e) {
177       LOG.warn("Can NOT create CleanerDelegate: " + className, e);
178       // skipping if can't instantiate
179       return null;
180     }
181   }
182 
183   @Override
184   protected void chore() {
185     if (getEnabled()) {
186       try {
187         pool.latchCountUp();
188         if (runCleaner()) {
189           if (LOG.isTraceEnabled()) {
190             LOG.trace("Cleaned all WALs under " + oldFileDir);
191           }
192         } else {
193           if (LOG.isTraceEnabled()) {
194             LOG.trace("WALs outstanding under " + oldFileDir);
195           }
196         }
197       } finally {
198         pool.latchCountDown();
199       }
200       // This cleaner is waiting for other cleaners finishing their jobs.
201       // To avoid missing next chore, only wait 0.8 * period, then shutdown.
202       pool.tryUpdatePoolSize((long) (0.8 * getTimeUnit().toMillis(getPeriod())));
203     } else {
204       LOG.trace("Cleaner chore disabled! Not cleaning.");
205     }
206   }
207 
208   public boolean runCleaner() {
209     try {
210       final AsyncResult<Boolean> result = new AsyncResult<Boolean>();
211       pool.execute(new Runnable() {
212         @Override
213         public void run() {
214           traverseAndDelete(oldFileDir, true, result);
215         }
216       });
217       return result.get();
218     } catch (Exception e) {
219       LOG.info("Failed to traverse and delete paths under the dir: " + oldFileDir, e);
220       return false;
221     }
222   }
223 
224   /**
225    * Run the given files through each of the cleaners to see if it should be deleted, deleting it if
226    * necessary.
227    * @param files List of FileStatus for the files to check (and possibly delete)
228    * @return true iff successfully deleted all files
229    */
230   private boolean checkAndDeleteFiles(List<FileStatus> files) {
231     if (files == null) {
232       return true;
233     }
234 
235     // first check to see if the path is valid
236     List<FileStatus> validFiles = Lists.newArrayListWithCapacity(files.size());
237     List<FileStatus> invalidFiles = Lists.newArrayList();
238     for (FileStatus file : files) {
239       if (validate(file.getPath())) {
240         validFiles.add(file);
241       } else {
242         LOG.warn("Found a wrongly formatted file: " + file.getPath() + " - will delete it.");
243         invalidFiles.add(file);
244       }
245     }
246 
247     Iterable<FileStatus> deletableValidFiles = validFiles;
248     // check each of the cleaners for the valid files
249     for (T cleaner : cleanersChain) {
250       if (cleaner.isStopped() || getStopper().isStopped()) {
251         LOG.warn("A file cleaner" + this.getName() + " is stopped, won't delete any more files in:"
252             + this.oldFileDir);
253         return false;
254       }
255 
256       Iterable<FileStatus> filteredFiles = cleaner.getDeletableFiles(deletableValidFiles);
257 
258       // trace which cleaner is holding on to each file
259       if (LOG.isTraceEnabled()) {
260         ImmutableSet<FileStatus> filteredFileSet = ImmutableSet.copyOf(filteredFiles);
261         for (FileStatus file : deletableValidFiles) {
262           if (!filteredFileSet.contains(file)) {
263             LOG.trace(file.getPath() + " is not deletable according to:" + cleaner);
264           }
265         }
266       }
267 
268       deletableValidFiles = filteredFiles;
269     }
270 
271     Iterable<FileStatus> filesToDelete = Iterables.concat(invalidFiles, deletableValidFiles);
272     return deleteFiles(filesToDelete) == files.size();
273   }
274 
275   /**
276    * Delete the given files
277    * @param filesToDelete files to delete
278    * @return number of deleted files
279    */
280   protected int deleteFiles(Iterable<FileStatus> filesToDelete) {
281     int deletedFileCount = 0;
282     for (FileStatus file : filesToDelete) {
283       Path filePath = file.getPath();
284       LOG.trace("Removing " + file + " from archive");
285       try {
286         boolean success = this.fs.delete(filePath, false);
287         if (success) {
288           deletedFileCount++;
289         } else {
290           LOG.warn("Attempted to delete:" + filePath
291               + ", but couldn't. Run cleaner chain and attempt to delete on next pass.");
292         }
293       } catch (IOException e) {
294         e = e instanceof RemoteException ?
295             ((RemoteException)e).unwrapRemoteException() : e;
296         LOG.warn("Error while deleting: " + filePath, e);
297       }
298     }
299     return deletedFileCount;
300   }
301 
302   @Override
303   public synchronized void cleanup() {
304     for (T lc : this.cleanersChain) {
305       try {
306         lc.stop("Exiting");
307       } catch (Throwable t) {
308         LOG.warn("Stopping", t);
309       }
310     }
311   }
312 
313   @VisibleForTesting
314   int getChorePoolSize() {
315     return pool.getSize();
316   }
317 
318   /**
319    * @param enabled
320    */
321   public boolean setEnabled(final boolean enabled) {
322     return this.enabled.getAndSet(enabled);
323   }
324 
325   public boolean getEnabled() {
326     return this.enabled.get();
327   }
328 
329   private interface Action<T> {
330     T act() throws IOException;
331   }
332 
333   private interface Callback<T> {
334     void run(T val);
335   }
336 
337   private final class AsyncResult<T> {
338 
339     private Callback<T> callback;
340     private T result;
341     private boolean resultSet = false;
342 
343     AsyncResult(Callback<T> callback) {
344       this.callback = callback;
345     }
346 
347     AsyncResult() {
348     }
349 
350     void set(T result) {
351       synchronized (this) {
352         this.result = result;
353         if (callback != null) {
354           callback.run(result);
355         }
356         // Mark the result set process finished and notify the waiting get method.
357         this.resultSet = true;
358         this.notifyAll();
359       }
360     }
361 
362     synchronized T get() throws Exception {
363       while (!resultSet) {
364         wait();
365       }
366       return result;
367     }
368   }
369 
370   /**
371    * Attempts to clean up a directory(its subdirectories, and files) in a
372    * {@link java.util.concurrent.ThreadPoolExecutor} concurrently. We can get the final result by
373    * calling result.get().
374    * @param dir means the directory we will start to traverse and delete.
375    * @param root means whether it's the root directory to traverse, if true then cannot delete it.
376    * @param result {@link AsyncResult<Boolean>} to fetch the result. True means the current
377    *          directory has been deleted successfully (for root dir we don't need that) and the
378    *          parent will try to delete its own directory if all of the children(files and
379    *          sub-directories are included) has been deleted successfully.
380    */
381   private void traverseAndDelete(final Path dir, final boolean root,
382       final AsyncResult<Boolean> result) {
383     try {
384       final Action<Boolean> curDirDeletion = new Action<Boolean>() {
385         @Override
386         public Boolean act() throws IOException {
387           return fs.delete(dir, false);
388         }
389       };
390 
391       // Step.1: List all files under the given directory.
392       List<FileStatus> allPaths = Arrays.asList(fs.listStatus(dir));
393       final List<FileStatus> subDirs = new ArrayList<>();
394       final List<FileStatus> files = new ArrayList<>();
395       for (FileStatus status : allPaths) {
396         if (status.isDirectory()) {
397           subDirs.add(status);
398         } else if (status.isFile()) {
399           files.add(status);
400         }
401       }
402 
403       // Step.2: Try to delete all the deletable files.
404       final boolean allFilesDeleted = files.isEmpty() || deleteAction(new Action<Boolean>() {
405         @Override
406         public Boolean act() throws IOException {
407           return checkAndDeleteFiles(files);
408         }
409       }, "files", dir);
410 
411       // Step.3: Start to traverse and delete the sub-directories.
412       if (subDirs.isEmpty()) {
413         // If no sub-directories, then just try to delete the current dir and finish the result.
414         boolean deleted = allFilesDeleted;
415         if (allFilesDeleted && !root) {
416           deleted = deleteAction(curDirDeletion, "dir", dir);
417         }
418         result.set(deleted);
419         return;
420       }
421 
422       // Otherwise, there should be some sub-directories. then we will register the following
423       // callback in AsyncResult of sub-directory, and once all of the sub-directories are traversed
424       // and deleted then the callback will try to delete the current dir and finish the result.
425       final AtomicInteger remain = new AtomicInteger(subDirs.size());
426       Callback<Boolean> callback = new Callback<Boolean>() {
427         private volatile boolean allSubDirDeleted = true;
428 
429         @Override
430         public void run(Boolean subDirDeleted) {
431           allSubDirDeleted &= subDirDeleted;
432           if (remain.decrementAndGet() == 0) {
433             boolean deleted = allFilesDeleted && allSubDirDeleted;
434             if (deleted && !root) {
435               deleted = deleteAction(curDirDeletion, "dir", dir);
436             }
437             result.set(deleted);
438           }
439         }
440       };
441 
442       // Submit the request of sub-directory deletion.
443       for (FileStatus subDir : subDirs) {
444         final FileStatus finalSubDir = subDir;
445         // Register the callback in AsyncResult here.
446         final AsyncResult<Boolean> asyncResult = new AsyncResult<Boolean>(callback);
447         pool.execute(new Runnable() {
448           @Override
449           public void run() {
450             traverseAndDelete(finalSubDir.getPath(), false, asyncResult);
451           }
452         });
453       }
454     } catch (Exception e) {
455       result.set(false);
456       if (LOG.isDebugEnabled()) {
457         LOG.debug("Failed to traverse and delete the path=" + dir + ", root=" + root, e);
458       }
459     }
460   }
461 
462   /**
463    * Perform a delete on a specified type.
464    * @param deletion a delete
465    * @param type possible values are 'files', 'subdirs', 'dirs'
466    * @param dir delete actions happened under the given directory.
467    * @return true if it deleted successfully, false otherwise
468    */
469   private boolean deleteAction(Action<Boolean> deletion, String type, Path dir) {
470     boolean deleted;
471     try {
472       if (LOG.isTraceEnabled()) {
473         LOG.trace("Start deleting " + type + " under " + dir);
474       }
475       deleted = deletion.act();
476     } catch (PathIsNotEmptyDirectoryException exception) {
477       // N.B. HDFS throws this exception when we try to delete a non-empty directory, but
478       // LocalFileSystem throws a bare IOException. So some test code will get the verbose
479       // message below.
480       if (LOG.isDebugEnabled()) {
481         LOG.debug("Couldn't delete '" + dir + "' yet because it isn't empty w/exception.",
482           exception);
483       }
484       deleted = false;
485     } catch (IOException ioe) {
486       LOG.info(
487         "Could not delete " + type + " under " + dir + ". might be transient; we'll retry. if it "
488             + "keeps " + "happening, use following exception when asking on mailing list.",
489         ioe);
490       deleted = false;
491     } catch (Exception e) {
492       LOG.info("unexpected exception: ", e);
493       deleted = false;
494     }
495     if (LOG.isTraceEnabled()) {
496       LOG.trace("Finish deleting " + type + " under " + dir + ", deleted=" + deleted);
497     }
498     return deleted;
499   }
500 }