org.apache.flink.runtime.state.gemini.engine.fs.FileCleanerImpl Maven / Gradle / Ivy
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.state.gemini.engine.fs;
import org.apache.flink.core.fs.Path;
import org.apache.flink.runtime.state.gemini.engine.dbms.GContext;
import org.apache.flink.runtime.state.gemini.engine.metrics.FileCleanerMetrics;
import org.apache.flink.util.Preconditions;
import org.apache.flink.shaded.guava18.com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Implementation of {@link FileCleaner}.
*/
public class FileCleanerImpl implements FileCleaner {
private static final Logger LOG = LoggerFactory.getLogger(FileCleanerImpl.class);
private final GContext gContext;
private final FileCleanerStat fileCleanerStat;
private final Set registeredFileManagers;
private final Queue queue;
private final ScheduledThreadPoolExecutor fileCleanUpExecutor;
private volatile boolean closed;
public FileCleanerImpl(GContext gContext) {
this.gContext = Preconditions.checkNotNull(gContext);
this.registeredFileManagers = Collections.newSetFromMap(new ConcurrentHashMap<>());
this.queue = new ConcurrentLinkedQueue<>();
this.fileCleanerStat = new FileCleanerStat();
FileCleanerMetrics fileCleanerMetrics = gContext.getFileCleanerMetrics();
if (fileCleanerMetrics != null) {
gContext.getFileCleanerMetrics().register(fileCleanerStat);
}
this.fileCleanUpExecutor = new ScheduledThreadPoolExecutor(1,
new ThreadFactoryBuilder().setNameFormat(
gContext.getGConfiguration().getExcetorPrefixName() + "FileCleaner-%d").build());
this.fileCleanUpExecutor.setRemoveOnCancelPolicy(true);
this.fileCleanUpExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
this.fileCleanUpExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
this.closed = false;
LOG.info("FileCleaner is created.");
}
@Override
public void start() {
this.fileCleanUpExecutor.scheduleAtFixedRate(new CleanupRunner(), 0,
gContext.getGConfiguration().getFileCleanInterval(), TimeUnit.MILLISECONDS);
LOG.info("FileCleaner is started");
}
@Override
public void registerFileManager(FileManager fileManager) {
registeredFileManagers.add(fileManager);
}
@Override
public void unregisterFileManager(FileManager fileManager) {
registeredFileManagers.remove(fileManager);
}
@Override
public void triggerCleanup(FileManager fileManager) {
if (!registeredFileManagers.contains(fileManager)) {
LOG.warn("file manager {} is not registered", fileManager);
return;
}
Set files = fileManager.getMarkedDeletionFiles();
queue.addAll(files);
fileCleanerStat.addTotalReceivedFile(files.size());
}
@Override
public void close() {
synchronized (this) {
if (closed) {
LOG.warn("FileCleaner ({}) has been closed");
return;
}
closed = true;
}
fileCleanUpExecutor.shutdownNow();
while (!queue.isEmpty()) {
String filePath = queue.poll();
if (filePath == null) {
break;
}
try {
Path path = new Path(filePath);
path.getFileSystem().delete(path, false);
} catch (Exception e) {
LOG.warn("Failed to delete file {} when closing file cleaner, {}", filePath, e);
}
}
registeredFileManagers.clear();
LOG.info("FileCleaner is closed");
}
private void printStat() {
LOG.info("FileCleanerStat[ totalReceivedFiles: {}, totalDeletedFiles: {}, totalFailedDeleteFiles: {}]",
fileCleanerStat.addTotalReceivedFile(0), fileCleanerStat.addTotalDeletedFile(0),
fileCleanerStat.addTotalFailedDeletedFiles(0));
}
private class CleanupRunner implements Runnable {
@Override
public void run() {
for (FileManager fileManager : registeredFileManagers) {
if (closed) {
break;
}
Set files = fileManager.getMarkedDeletionFiles();
queue.addAll(files);
fileCleanerStat.addTotalReceivedFile(files.size());
}
while (!closed && !queue.isEmpty()) {
String filePath = queue.poll();
if (filePath == null) {
break;
}
boolean success = false;
Path path = new Path(filePath);
try {
path.getFileSystem().delete(path, false);
success = true;
fileCleanerStat.addTotalDeletedFile(1);
LOG.info("Delete file {}", filePath);
} catch (Exception e) {
fileCleanerStat.addTotalFailedDeletedFiles(1);
LOG.warn("failed to clean up file {} with Exception {}", filePath, e);
// if file cleaner is closed, try to delete the file again
if (closed) {
try {
path.getFileSystem().delete(path, false);
} catch (Exception ignore) {
// ignore the exception
}
}
}
if (success) {
try {
Thread.sleep(100);
} catch (Exception e) {
// ignore execption
}
}
}
printStat();
}
}
}