blob: f8eaeacc3124a73f6125872d021dc7b8e11f13af [file] [log] [blame]
Han Shene4b6f222013-11-22 10:02:38 -08001#!/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
Han Shena58a8242014-04-23 11:05:22 -07009import re
Han Shene4b6f222013-11-22 10:02:38 -080010import sys
11
12from utils import command_executer
13from utils import constants
14from utils import misc
15
16DIR_BY_WEEKDAY = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
17
18
19def CleanNumberedDir(s, dry_run=False):
20 """Deleted directories under each dated_dir."""
21 chromeos_dirs = [os.path.join(s, x) for x in os.listdir(s)
22 if misc.IsChromeOsTree(os.path.join(s, x))]
cmtice37828572015-02-04 17:37:43 -080023 ce = command_executer.GetCommandExecuter(log_level="none")
Han Shena58a8242014-04-23 11:05:22 -070024 all_succeeded = True
Han Shene4b6f222013-11-22 10:02:38 -080025 for cd in chromeos_dirs:
Han Shena58a8242014-04-23 11:05:22 -070026 if misc.DeleteChromeOsTree(cd, dry_run=dry_run):
27 print 'Successfully removed chromeos tree "{0}".'.format(cd)
28 else:
29 all_succeeded = False
30 print 'Failed to remove chromeos tree "{0}", please check.'.format(cd)
31
Han Shen4375f762014-04-25 10:35:29 -070032 if not all_succeeded:
33 print 'Failed to delete at least one chromeos tree, please check.'
34 return False
35
Han Shena58a8242014-04-23 11:05:22 -070036 ## Now delete the numbered dir Before forcibly removing the directory, just
Han Shen4375f762014-04-25 10:35:29 -070037 ## check 's' to make sure it is sane. A valid dir to be removed must be
38 ## '/usr/local/google/crostc/(SUN|MON|TUE...|SAT)'.
39 valid_dir_pattern = ('^' + constants.CROSTC_WORKSPACE + '/(' +
40 '|'.join(DIR_BY_WEEKDAY) + ')')
41 if not re.search(valid_dir_pattern, s):
42 print ('Trying to delete an invalid dir "{0}" (must match "{1}"), '
43 'please check.'.format(s, valid_dir_pattern))
Han Shena58a8242014-04-23 11:05:22 -070044 return False
45
Han Shene4b6f222013-11-22 10:02:38 -080046 cmd = 'rm -fr {0}'.format(s)
47 if dry_run:
48 print cmd
49 else:
Luis Lozano036c9232015-12-10 10:47:01 -080050 if ce.RunCommand(cmd, print_to_console=False, terminated_timeout=480) == 0:
Han Shena58a8242014-04-23 11:05:22 -070051 print 'Successfully removed "{0}".'.format(s)
52 else:
53 all_succeeded = False
54 print 'Failed to remove "{0}", please check.'.format(s)
55 return all_succeeded
Han Shene4b6f222013-11-22 10:02:38 -080056
57
58def CleanDatedDir(dated_dir, dry_run=False):
59 # List subdirs under dir
60 subdirs = [os.path.join(dated_dir, x) for x in os.listdir(dated_dir)
61 if os.path.isdir(os.path.join(dated_dir, x))]
Han Shena58a8242014-04-23 11:05:22 -070062 all_succeeded = True
Han Shene4b6f222013-11-22 10:02:38 -080063 for s in subdirs:
Han Shena58a8242014-04-23 11:05:22 -070064 if not CleanNumberedDir(s, dry_run):
65 all_succeeded = False
66 return all_succeeded
Han Shene4b6f222013-11-22 10:02:38 -080067
68
69def ProcessArguments(argv):
70 """Process arguments."""
71 parser = optparse.OptionParser(
72 description='Automatically delete nightly test data directories.',
Han Shena58a8242014-04-23 11:05:22 -070073 usage='auto_delete_nightly_test_data.py options')
Han Shene4b6f222013-11-22 10:02:38 -080074 parser.add_option('-d', '--dry_run', dest='dry_run',
75 default=False, action='store_true',
76 help='Only print command line, do not execute anything.')
Han Shenfdd8a5b2015-02-18 09:37:52 -080077 parser.add_option('--days_to_preserve', dest='days_to_preserve', default=3,
cmtice37828572015-02-04 17:37:43 -080078 help=('Specify the number of days (not including today), '
79 'test data generated on these days will *NOT* be '
80 'deleted. Defaults to 3.'))
Han Shene4b6f222013-11-22 10:02:38 -080081 options, _ = parser.parse_args(argv)
82 return options
83
84
Han Shenfdd8a5b2015-02-18 09:37:52 -080085def CleanChromeOsTmpAndImages():
86 """Delete temporaries, images under crostc/chromeos."""
87
88 chromeos_chroot_tmp = os.path.join(constants.CROSTC_WORKSPACE,
89 'chromeos', 'chroot', 'tmp')
90
91 ce = command_executer.GetCommandExecuter()
92 # Clean chroot/tmp/test_that_* and chroot/tmp/tmpxxxxxx, that were last
93 # accessed more than 24 hours ago.
94 cmd = (r'find {0} -maxdepth 1 -type d '
95 r'\( -name "test_that_*" -o -regex "{0}/tmp......" \) '
96 r'-amin +1440 '
97 r'-exec bash -c "echo rm -fr {{}}" \; '
98 r'-exec bash -c "rm -fr {{}}" \;').format(chromeos_chroot_tmp)
Luis Lozano036c9232015-12-10 10:47:01 -080099 rv = ce.RunCommand(cmd, print_to_console=False)
Han Shenfdd8a5b2015-02-18 09:37:52 -0800100 if rv == 0:
Luis Lozano1af92942015-11-04 17:48:32 -0800101 print ('Successfully cleaned chromeos tree tmp directory '
Han Shenfdd8a5b2015-02-18 09:37:52 -0800102 '"{0}".'.format(chromeos_chroot_tmp))
103 else:
Luis Lozano1af92942015-11-04 17:48:32 -0800104 print ('Some directories were not removed under chromeos tree '
Han Shenfdd8a5b2015-02-18 09:37:52 -0800105 'tmp directory -"{0}".'.format(chromeos_chroot_tmp))
106
107 # Clean image tar files, which were last accessed 1 hour ago and clean image
108 # bin files that were last accessed more than 24 hours ago.
109 cmd = ('find {0}/*-release -type f '
110 r'\( -name "chromiumos_test_image.tar" -amin +60 -o '
111 r' -name "chromiumos_test_image.tar.xz" -amin +60 -o '
cmtice07eb87f2015-03-11 10:10:41 -0700112 r' -name "chromiumos_test_image.bin" -amin +1440 \) '
Han Shenfdd8a5b2015-02-18 09:37:52 -0800113 r'-exec bash -c "echo rm -f {{}}" \; '
114 r'-exec bash -c "rm -f {{}}" \;').format(chromeos_chroot_tmp)
Luis Lozano036c9232015-12-10 10:47:01 -0800115 rv2 = ce.RunCommand(cmd, print_to_console=False)
Han Shenfdd8a5b2015-02-18 09:37:52 -0800116 if rv2 == 0:
Luis Lozano1af92942015-11-04 17:48:32 -0800117 print 'Successfully cleaned chromeos images.'
Han Shenfdd8a5b2015-02-18 09:37:52 -0800118 else:
Luis Lozano1af92942015-11-04 17:48:32 -0800119 print 'Some chromeos images were not removed.'
Han Shenfdd8a5b2015-02-18 09:37:52 -0800120
121 return rv + rv2
122
123
Han Shene4b6f222013-11-22 10:02:38 -0800124def Main(argv):
Han Shenfdd8a5b2015-02-18 09:37:52 -0800125 """Delete nightly test data directories, tmps and test images."""
Han Shene4b6f222013-11-22 10:02:38 -0800126 options = ProcessArguments(argv)
127 # Function 'isoweekday' returns 1(Monday) - 7 (Sunday).
128 d = datetime.datetime.today().isoweekday()
129 # We go back 1 week, delete from that day till we are
130 # options.days_to_preserve away from today.
131 s = d - 7
cmtice798a8fa2014-05-12 13:56:42 -0700132 e = d - int(options.days_to_preserve)
Han Shena58a8242014-04-23 11:05:22 -0700133 rv = 0
Han Shene4b6f222013-11-22 10:02:38 -0800134 for i in range(s + 1, e):
135 if i <= 0:
136 ## Wrap around if index is negative. 6 is from i + 7 - 1, because
137 ## DIR_BY_WEEKDAY starts from 0, while isoweekday is from 1-7.
138 dated_dir = DIR_BY_WEEKDAY[i+6]
139 else:
140 dated_dir = DIR_BY_WEEKDAY[i-1]
Han Shena58a8242014-04-23 11:05:22 -0700141 rv += 0 if CleanDatedDir(os.path.join(
142 constants.CROSTC_WORKSPACE, dated_dir), options.dry_run) else 1
Han Shenfdd8a5b2015-02-18 09:37:52 -0800143
144 ## Finally clean temporaries, images under crostc/chromeos
145 rv2 = CleanChromeOsTmpAndImages()
146
147 return rv + rv2
Han Shene4b6f222013-11-22 10:02:38 -0800148
149
150if __name__ == '__main__':
151 retval = Main(sys.argv)
152 sys.exit(retval)