1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
49
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
59
60
61
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
81
82
83
84
85
86
87
88
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
106
107
108
109 static int calculatePoolSize(String poolSize) {
110 if (poolSize.matches("[1-9][0-9]*")) {
111
112
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
120
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
136
137
138
139
140 protected abstract boolean validate(Path file);
141
142
143
144
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
162
163
164
165
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
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
201
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
226
227
228
229
230 private boolean checkAndDeleteFiles(List<FileStatus> files) {
231 if (files == null) {
232 return true;
233 }
234
235
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
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
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
277
278
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
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
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
372
373
374
375
376
377
378
379
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
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
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
412 if (subDirs.isEmpty()) {
413
414 boolean deleted = allFilesDeleted;
415 if (allFilesDeleted && !root) {
416 deleted = deleteAction(curDirDeletion, "dir", dir);
417 }
418 result.set(deleted);
419 return;
420 }
421
422
423
424
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
443 for (FileStatus subDir : subDirs) {
444 final FileStatus finalSubDir = subDir;
445
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
464
465
466
467
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
478
479
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 }