85 lines
3.2 KiB
Python
85 lines
3.2 KiB
Python
import os
|
|
import subprocess
|
|
from constant import WHITE_LIST, KEEP_FILES, DATE, MAIL_MSG, MOVE_MSG
|
|
|
|
class Cleaner():
|
|
def __init__(self, user_dir, mailer=None):
|
|
self.user_dir = user_dir
|
|
self.mailer = mailer
|
|
|
|
def run(self, test=True, notify_stage=True):
|
|
'''
|
|
notify_stage=1, test=1: 不會刪,不會寄信(只寄給開發人員)
|
|
notify_stage=1, test=0: 不會刪,會寄信 (提醒階段)
|
|
notify_stage=0, test=1: 不會刪,不會寄信(確認)
|
|
notify_stage=0, test=0: 會刪除,不會寄信(刪除階段)
|
|
'''
|
|
username = self.user_dir.split('/')[-1]
|
|
if username in WHITE_LIST:
|
|
print(f' WHITE LIST: {username}')
|
|
return
|
|
|
|
remove_objs = []
|
|
for obj in sorted(os.listdir(self.user_dir)):
|
|
if obj in KEEP_FILES:
|
|
continue
|
|
|
|
obj = obj.replace(' ', '\ ')
|
|
|
|
# stat {file or dir}:
|
|
# get Create, modified information
|
|
# grep Modify:
|
|
# get Modified time
|
|
# awk:
|
|
# -F ' ': use space to split the data
|
|
# print $2: column 2 (get date)
|
|
modify_date = subprocess.getoutput(f"stat {self.user_dir}/{obj} | grep Modify | awk -F ' ' '{{print $2}}'" )
|
|
|
|
if modify_date < DATE:
|
|
remove_objs.append((obj, modify_date))
|
|
print(f' {modify_date} {obj}')
|
|
|
|
if notify_stage and len(remove_objs) != 0:
|
|
self.notify(username, test, remove_objs)
|
|
|
|
elif not notify_stage and len(remove_objs) != 0:
|
|
# delete files
|
|
remove_obj_names = [ name for name, date in remove_objs ]
|
|
if test:
|
|
command = 'rm -rf {}'.format(" ".join(remove_obj_names))
|
|
print(f' we will run:\n {command}')
|
|
else:
|
|
if not os.path.isdir(f'/volume1/cmlabhome/home_backup/{username}'):
|
|
os.mkdir(f'/volume1/cmlabhome/home_backup/{username}')
|
|
|
|
msg = ""
|
|
for name, date in remove_objs:
|
|
if name[0] != '.' and 'conda' not in name:
|
|
command = f'mv {self.user_dir}/{name} /volume1/cmlabhome/home_backup/{username}/{name}'
|
|
else:
|
|
command = f'rm -rf {self.user_dir}/{name}'
|
|
print(command)
|
|
subprocess.getoutput(command)
|
|
msg += f" - {name}\n"
|
|
msg = MOVE_MSG.format(msg)
|
|
|
|
with open(f'{self.user_dir}/PLEASE_READ_ME', 'w') as fp:
|
|
fp.write(msg)
|
|
|
|
def notify(self, username, test, remove_objs):
|
|
if self.mailer == None:
|
|
return
|
|
|
|
if test:
|
|
receiver = 'snsd0805@cmlab.csie.ntu.edu.tw'
|
|
else:
|
|
receiver = f'{username}@cmlab.csie.ntu.edu.tw'
|
|
sender = 'unix_manager@cmlab.csie.ntu.edu.tw'
|
|
subject = f'[網管通知] CML Server 清理預計被移除的內容({username})'
|
|
msg = ''
|
|
for obj, date in remove_objs:
|
|
msg += f'<li>{date} - {obj}</li>'
|
|
msg = MAIL_MSG.format(username, msg)
|
|
|
|
self.mailer.send(sender, receiver, subject, msg)
|