2023-05-15 17:07:19 +02:00
|
|
|
import os
|
|
|
|
import signal
|
|
|
|
import sys
|
|
|
|
import time
|
|
|
|
|
2023-05-15 18:50:30 +02:00
|
|
|
# Keep files for 72 hours (3 days)
|
|
|
|
try:
|
|
|
|
MAX_FILE_AGE_SECONDS = int(os.environ.get('NP_MAX_FILE_AGE_HOURS', "72")) * 60 * 60
|
|
|
|
except err:
|
|
|
|
print("Error: ")
|
|
|
|
print(err)
|
|
|
|
print("Using 72 hours instead !")
|
|
|
|
MAX_FILE_AGE_SECONDS = 72 * 60 * 60
|
2023-05-15 17:07:19 +02:00
|
|
|
|
|
|
|
# Once done cleaning, sleep for 5 minutes
|
|
|
|
SLEEP_TIME_SECONDS = 5 * 60
|
|
|
|
|
|
|
|
# Handling shutdown signals
|
|
|
|
def signal_handler(sig, frame):
|
|
|
|
sys.exit(0)
|
|
|
|
|
|
|
|
signal.signal(signal.SIGTERM, signal_handler)
|
|
|
|
|
|
|
|
def delete_old_files(directory, current_time):
|
|
|
|
deletion_count = 0
|
|
|
|
|
|
|
|
for filename in os.listdir(directory):
|
|
|
|
filepath = os.path.join(directory, filename)
|
|
|
|
|
|
|
|
if os.path.isfile(filepath):
|
|
|
|
file_creation_time = os.path.getctime(filepath)
|
|
|
|
|
|
|
|
if (current_time - file_creation_time) > (MAX_FILE_AGE_SECONDS):
|
|
|
|
os.remove(filepath)
|
|
|
|
deletion_count = deletion_count + 1
|
|
|
|
|
|
|
|
return deletion_count
|
|
|
|
|
|
|
|
print("Deleting old files...")
|
|
|
|
|
|
|
|
start_time = time.time()
|
|
|
|
|
|
|
|
file_deleted_count = 0
|
|
|
|
|
|
|
|
for item in os.listdir("/data/"):
|
2023-05-15 18:50:30 +02:00
|
|
|
item_path = os.path.join("/data/", item)
|
2023-05-15 17:07:19 +02:00
|
|
|
|
|
|
|
if os.path.isdir(item_path):
|
|
|
|
file_deleted_count = file_deleted_count + delete_old_files(item_path, start_time)
|
|
|
|
else:
|
|
|
|
# Ignoring files
|
|
|
|
continue
|
|
|
|
|
|
|
|
end_time = time.time()
|
|
|
|
|
|
|
|
print("Took {} second(s) to delete {} file(s)".format(round(end_time - start_time, 2), file_deleted_count))
|
|
|
|
|
|
|
|
time.sleep(SLEEP_TIME_SECONDS)
|