auto_delete_nightly_test_data.py revision e4b6f220f3cc7d3277daca7bca25f89d648dae8e
1#!/usr/bin/python 2 3"""A crontab script to delete night test data.""" 4__author__ = 'shenhan@google.com (Han Shen)' 5 6import datetime 7import optparse 8import os 9import sys 10 11from utils import command_executer 12from utils import constants 13from utils import misc 14 15DIR_BY_WEEKDAY = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') 16 17 18def CleanNumberedDir(s, dry_run=False): 19 """Deleted directories under each dated_dir.""" 20 chromeos_dirs = [os.path.join(s, x) for x in os.listdir(s) 21 if misc.IsChromeOsTree(os.path.join(s, x))] 22 ce = command_executer.GetCommandExecuter() 23 for cd in chromeos_dirs: 24 misc.DeleteChromeOsTree(cd, dry_run=dry_run) 25 ## Now delete the numbered dir 26 cmd = 'rm -fr {0}'.format(s) 27 if dry_run: 28 print cmd 29 else: 30 ce.RunCommand(cmd, return_output=True, terminated_timeout=480) 31 32 33def CleanDatedDir(dated_dir, dry_run=False): 34 # List subdirs under dir 35 subdirs = [os.path.join(dated_dir, x) for x in os.listdir(dated_dir) 36 if os.path.isdir(os.path.join(dated_dir, x))] 37 for s in subdirs: 38 CleanNumberedDir(s, dry_run) 39 40 41def ProcessArguments(argv): 42 """Process arguments.""" 43 parser = optparse.OptionParser( 44 description='Automatically delete nightly test data directories.', 45 usage='auto_delete.py options') 46 parser.add_option('-d', '--dry_run', dest='dry_run', 47 default=False, action='store_true', 48 help='Only print command line, do not execute anything.') 49 parser.add_option('--days_to_perserve', dest='days_to_preserve', default=3, 50 help=('Specify the number of days, test data generated ' 51 'on these days will *NOT* be deleted. ' 52 'Defaults to 3.')) 53 options, _ = parser.parse_args(argv) 54 return options 55 56 57def Main(argv): 58 """Delete nightly test data directories.""" 59 options = ProcessArguments(argv) 60 # Function 'isoweekday' returns 1(Monday) - 7 (Sunday). 61 d = datetime.datetime.today().isoweekday() 62 # We go back 1 week, delete from that day till we are 63 # options.days_to_preserve away from today. 64 s = d - 7 65 e = d - options.days_to_preserve 66 for i in range(s + 1, e): 67 if i <= 0: 68 ## Wrap around if index is negative. 6 is from i + 7 - 1, because 69 ## DIR_BY_WEEKDAY starts from 0, while isoweekday is from 1-7. 70 dated_dir = DIR_BY_WEEKDAY[i+6] 71 else: 72 dated_dir = DIR_BY_WEEKDAY[i-1] 73 CleanDatedDir(os.path.join( 74 constants.CROSTC_WORKSPACE, dated_dir), options.dry_run) 75 return 0 76 77 78if __name__ == '__main__': 79 retval = Main(sys.argv) 80 sys.exit(retval) 81