3 ### a utility to filter backups in the /db-backup area
5 # lists all files that match <prefix>-<date>-<time>.<suffix>
6 # and preserves only the following
7 # (*) more than 2 months old : one file per month
8 # (*) more than 2 weeks old : one file per week
9 # (*) recent stuff: unchanged
14 from datetime import datetime, timedelta
19 from optparse import OptionParser
21 class FileIgnored (Exception): pass
24 LEAVE_FILES_YOUNGER_THAN = 20
25 # keep that amount of (plain) months organized in weeks
26 # should not exceed 11
27 KEEP_FILES_IN_MONTH_AFTER = 2
30 # we prefer saturday as this is the end of the week
34 ## utility to parse a filename
35 datetime_pattern="(?P<datetime>[0-9]{8}\-[0-9]{4})"
37 # (bool, prefix, suffix, datetime)
39 prefix_pattern="(?P<prefix>[\w\-]+)"
40 datetime_pattern="(?P<datetime>[0-9]{8}\-[0-9]{4})"
41 suffix_pattern="(?P<suffix>[\w\.]+)"
42 filename_matcher=re.compile("\A%s[-_]%s\.%s\Z"%(prefix_pattern,datetime_pattern,suffix_pattern))
44 parsing_failed = (False, None, None, None)
46 def parse_filename (filename):
47 match=filename_matcher.match(filename)
53 dt = datetime.strptime(d['datetime'],"%Y%m%d-%H%M")
54 return (True, d['prefix'], d['suffix'], dt)
56 print "failed to parse timestamp %s from %s"%(d['datetime'],filename)
60 # one entry like this per file, managed in the Kind class
65 def __init__ (self, dir, filename, datetime, options):
67 self.filename=filename
68 self.datetime=datetime
71 self.weekday=self.datetime.weekday()
73 if self.options.verbose: print 'Filename %s is from the future - skipped'%sfilename
74 raise FileIgnored,"Filename from the future %s"%filename
75 self.group = self._group_string()
78 return "%s (%s) -- weekday %s"%(self.filename,self.datetime,self.datetime.weekday())
85 def sort_age (file1, file2):
86 # for 2.7, seems safer
88 return int((file1.datetime-file2.datetime).total_seconds())
89 # otherwise resort to days, we should be clear as our backups are daily
91 return int((file1.datetime-file2.datetime).days)
94 def sort_relevance (file1, file2):
97 if w1==PREFERRED_WEEKDAY and w2==PREFERRED_WEEKDAY:
98 return File.sort_age (file1,file2)
99 elif w1!=PREFERRED_WEEKDAY and w2!=PREFERRED_WEEKDAY:
100 return File.sort_age (file1,file2)
101 elif w1==PREFERRED_WEEKDAY and w2!=PREFERRED_WEEKDAY:
103 elif w1!=PREFERRED_WEEKDAY and w2==PREFERRED_WEEKDAY:
109 def _compute_barriers ():
110 if File.month_barrier:
112 # find the exact datetime for a month change
113 # KEEP_FILES_IN_MONTH_AFTER months ago +
117 if now.month>=KEEP_FILES_IN_MONTH_AFTER+1:
118 month -= KEEP_FILES_IN_MONTH_AFTER
121 month += (12-KEEP_FILES_IN_MONTH_AFTER)
122 File.month_barrier = datetime (year=year, month=month, day=day)
123 # find the next monday morning
124 remaining_days=(7-File.month_barrier.weekday())%7
125 File.week_barrier=File.month_barrier+timedelta(days=remaining_days)
128 def compute_month_barrier(): File._compute_barriers(); return File.month_barrier
130 def compute_week_barrier(): File._compute_barriers(); return File.week_barrier
132 # returns a key for grouping files, the cleanup then
133 # preserving one entry in the set of files with same group
134 def _group_string (self):
135 if self.age.days<=LEAVE_FILES_YOUNGER_THAN:
136 if self.options.verbose: print 'Filename %s is recent (%d d) - skipped'%\
137 (self.filename,LEAVE_FILES_YOUNGER_THAN)
138 raise FileIgnored,"Filename %s is recent"%self.filename
140 if self.datetime <= File.compute_month_barrier():
141 return self.datetime.strftime("%Y%m")
143 weeks=(self.datetime-File.compute_week_barrier()).days/7
145 return "week%02d"%weeks
147 # all files in a given timeslot (either month or week)
149 def __init__ (self, groupname):
150 self.groupname=groupname
152 def insert (self, file):
153 self.files.append(file)
155 self.files.sort (File.sort_relevance)
156 # print 20*'*','after sort'
157 # for file in self.files:
160 # all files with the same (prefix, suffix)
163 def __init__ (self, prefix, suffix, options):
167 # will contain tuples (filename, datetime)
170 # allow for basic checking to be done in File
171 def add_file (self, dir, filename, datetime):
173 self.list.append ( File (dir, filename, datetime, self.options) )
174 except FileIgnored: pass
176 print 'could not append %s'%filename
177 traceback.print_exc()
181 # sort self.list according to file age, oldest first
182 self.list.sort(File.sort_age)
183 # prepare groups according to age
185 for file in self.list:
187 if groupname not in self.groups:
188 self.groups[groupname]=Group(groupname)
189 self.groups[groupname].insert(file)
190 for group in self.groups.values():
194 print 30*'-',"%s-<date>.%s"%(self.prefix,self.suffix)
195 entries=len(self.list)
196 print " %d entries" % entries,
199 print " << %s - %s d old"%(f.filename, f.age_days()),
202 print "|| %s - %s d old >>"%(f.filename, f.age_days())
203 groupnames=self.groups.keys()
206 if self.options.extra_verbose:
207 print " Found %d groups"%len(groupnames)
210 files=self.groups[g].files
213 elif self.options.verbose:
214 print " Found %d groups"%len(groupnames),
215 for g in groupnames: print "%s->%d"%(g,len(self.groups[g].files)),
218 # sort on number of entries
220 def sort_size (k1, k2):
221 return len(k1.list)-len(k2.list)
223 # keeps an index of all files found, index by (prefix, suffix), then sorted by time
225 def __init__ (self,options):
229 def insert (self, dir, filename, prefix, suffix, datetime):
230 key= (prefix, suffix)
231 if key not in self.index:
232 self.index[key] = Kind(prefix,suffix, self.options)
233 self.index[key].add_file (dir, filename, datetime)
235 # we're done inserting, do housecleaning
237 for (key, kind) in self.index.items():
241 # sort on number of entries
242 kinds = self.index.values()
243 kinds.sort (Kind.sort_size)
247 def insert_many (self, dir, filenames):
248 for filename in filenames:
249 (b,p,s,d) = parse_filename (filename)
251 print "Filename %s does not match - skipped"%filename
253 self.insert (dir, filename, p, s, d)
255 def handle_arg (index, dir, pattern):
259 print "Cannot chdir into %s - skipped"%dir
261 filenames=glob(pattern)
262 index.insert_many (dir, filenames)
265 parser=OptionParser()
266 parser.add_option ("-v","--verbose",dest='verbose',action='store_true',default=False,
267 help="run in verbose mode")
268 parser.add_option ("-x","--extra-verbose",dest='extra_verbose',action='store_true',default=False,
269 help="run in extra verbose mode")
270 parser.add_option ("-n","--dry-run",dest='dry_run',action='store_true',default=False,
272 parser.add_option ("-o","--offset",dest='offset',action='store',type='int',default=0,
273 help="pretend we run <offset> days in the future")
274 (options, args) = parser.parse_args()
275 if options.extra_verbose: options.verbose=True
277 #options.offset=int(options.offset)
278 print 'offset=%d'%options.offset
279 if options.offset !=0:
281 now += timedelta(days=options.offset)
283 traceback.print_exc()
284 print "Offset not understood %s - expect an int. number of days"%options.offset
287 # args can be directories, or patterns, like
288 # main /db-backup /db-backup-f8/*bz2
289 # in any case we handle each arg completely separately
290 index = Index (options)
292 if os.path.isdir (arg):
293 handle_arg (index, arg, "*")
295 (dir,pattern)=os.path.split(arg)
297 handle_arg (index, dir, pattern)
301 if __name__ == '__main__':