]> git.decadent.org.uk Git - dak.git/blob - dak/clean_suites.py
honour No-Action in clean suites
[dak.git] / dak / clean_suites.py
1 #!/usr/bin/env python
2
3 """ Cleans up unassociated binary and source packages """
4 # Copyright (C) 2000, 2001, 2002, 2003, 2006  James Troup <james@nocrew.org>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20 ################################################################################
21
22 # 07:05|<elmo> well.. *shrug*.. no, probably not.. but to fix it,
23 #      |       we're going to have to implement reference counting
24 #      |       through dependencies.. do we really want to go down
25 #      |       that road?
26 #
27 # 07:05|<Culus> elmo: Augh! <brain jumps out of skull>
28
29 ################################################################################
30
31 import os, stat, sys, time
32 import apt_pkg
33 from datetime import datetime, timedelta
34
35 from daklib.config import Config
36 from daklib.dbconn import *
37 from daklib import utils
38 from daklib import daklog
39
40 ################################################################################
41
42 Options = None
43 Logger = None
44
45 ################################################################################
46
47 def usage (exit_code=0):
48     print """Usage: dak clean-suites [OPTIONS]
49 Clean old packages from suites.
50
51   -n, --no-action            don't do anything
52   -h, --help                 show this help and exit
53   -m, --maximum              maximum number of files to remove"""
54     sys.exit(exit_code)
55
56 ################################################################################
57
58 def check_binaries(now_date, delete_date, max_delete, session):
59     print "Checking for orphaned binary packages..."
60
61     # Get the list of binary packages not in a suite and mark them for
62     # deletion.
63
64     q = session.execute("""
65 SELECT b.file, f.filename FROM binaries b, files f
66  WHERE f.last_used IS NULL AND b.file = f.id
67    AND NOT EXISTS (SELECT 1 FROM bin_associations ba WHERE ba.bin = b.id)""")
68
69     for i in q.fetchall():
70         Logger.log(["set lastused", i[1]])
71         if not Options["No-Action"]:
72             session.execute("UPDATE files SET last_used = :lastused WHERE id = :fileid AND last_used IS NULL",
73                             {'lastused': now_date, 'fileid': i[0]})
74
75     if not Options["No-Action"]:
76         session.commit()
77
78     # Check for any binaries which are marked for eventual deletion
79     # but are now used again.
80
81     q = session.execute("""
82 SELECT b.file, f.filename FROM binaries b, files f
83    WHERE f.last_used IS NOT NULL AND f.id = b.file
84     AND EXISTS (SELECT 1 FROM bin_associations ba WHERE ba.bin = b.id)""")
85
86     for i in q.fetchall():
87         Logger.log(["unset lastused", i[1]])
88         if not Options["No-Action"]:
89             session.execute("UPDATE files SET last_used = NULL WHERE id = :fileid", {'fileid': i[0]})
90
91     if not Options["No-Action"]:
92         session.commit()
93
94 ########################################
95
96 def check_sources(now_date, delete_date, max_delete, session):
97     print "Checking for orphaned source packages..."
98
99     # Get the list of source packages not in a suite and not used by
100     # any binaries.
101     q = session.execute("""
102 SELECT s.id, s.file, f.filename FROM source s, files f
103   WHERE f.last_used IS NULL AND s.file = f.id
104     AND NOT EXISTS (SELECT 1 FROM src_associations sa WHERE sa.source = s.id)
105     AND NOT EXISTS (SELECT 1 FROM binaries b WHERE b.source = s.id)""")
106
107     #### XXX: this should ignore cases where the files for the binary b
108     ####      have been marked for deletion (so the delay between bins go
109     ####      byebye and sources go byebye is 0 instead of StayOfExecution)
110
111     for i in q.fetchall():
112         source_id = i[0]
113         dsc_file_id = i[1]
114         dsc_fname = i[2]
115
116         # Mark the .dsc file for deletion
117         Logger.log(["set lastused", dsc_fname])
118         if not Options["No-Action"]:
119             session.execute("""UPDATE files SET last_used = :last_used
120                                 WHERE id = :dscfileid AND last_used IS NULL""",
121                             {'last_used': now_date, 'dscfileid': dsc_file_id})
122
123         # Mark all other files references by .dsc too if they're not used by anyone else
124         x = session.execute("""SELECT f.id, f.filename FROM files f, dsc_files d
125                               WHERE d.source = :sourceid AND d.file = f.id""",
126                              {'sourceid': source_id})
127         for j in x.fetchall():
128             file_id = j[0]
129             file_name = j[1]
130             y = session.execute("SELECT id FROM dsc_files d WHERE d.file = :fileid", {'fileid': file_id})
131             if len(y.fetchall()) == 1:
132                 Logger.log(["set lastused", file_name])
133                 if not Options["No-Action"]:
134                     session.execute("""UPDATE files SET last_used = :lastused
135                                        WHERE id = :fileid AND last_used IS NULL""",
136                                     {'lastused': now_date, 'fileid': file_id})
137
138     if not Options["No-Action"]:
139         session.commit()
140
141     # Check for any sources which are marked for deletion but which
142     # are now used again.
143
144     q = session.execute("""
145 SELECT f.id, f.filename FROM source s, files f, dsc_files df
146   WHERE f.last_used IS NOT NULL AND s.id = df.source AND df.file = f.id
147     AND ((EXISTS (SELECT 1 FROM src_associations sa WHERE sa.source = s.id))
148       OR (EXISTS (SELECT 1 FROM binaries b WHERE b.source = s.id)))""")
149
150     #### XXX: this should also handle deleted binaries specially (ie, not
151     ####      reinstate sources because of them
152
153     for i in q.fetchall():
154         Logger.log(["unset lastused", i[1]])
155         if not Options["No-Action"]:
156             session.execute("UPDATE files SET last_used = NULL WHERE id = :fileid",
157                             {'fileid': i[0]})
158
159     if not Options["No-Action"]:
160         session.commit()
161
162 ########################################
163
164 def check_files(now_date, delete_date, max_delete, session):
165     # FIXME: this is evil; nothing should ever be in this state.  if
166     # they are, it's a bug.
167
168     # However, we've discovered it happens sometimes so we print a huge warning
169     # and then mark the file for deletion.  This probably masks a bug somwhere
170     # else but is better than collecting cruft forever
171
172     print "Checking for unused files..."
173     q = session.execute("""
174 SELECT id, filename FROM files f
175   WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.file = f.id)
176     AND NOT EXISTS (SELECT 1 FROM dsc_files df WHERE df.file = f.id)
177     AND NOT EXISTS (SELECT 1 FROM changes_pool_files cpf WHERE cpf.fileid = f.id)
178     AND NOT EXISTS (SELECT 1 FROM queue_files qf WHERE qf.id = f.id)
179     AND last_used IS NULL
180     ORDER BY filename""")
181
182     ql = q.fetchall()
183     if len(ql) > 0:
184         utils.warn("check_files found something it shouldn't")
185         for x in ql:
186             utils.warn("orphaned file: %s" % x)
187             Logger.log(["set lastused", x[1], "ORPHANED FILE"])
188             if not Options["No-Action"]:
189                  session.execute("UPDATE files SET last_used = :lastused WHERE id = :fileid",
190                                  {'lastused': now_date, 'fileid': x[0]})
191
192         if not Options["No-Action"]:
193             session.commit()
194
195 def clean_binaries(now_date, delete_date, max_delete, session):
196     # We do this here so that the binaries we remove will have their
197     # source also removed (if possible).
198
199     # XXX: why doesn't this remove the files here as well? I don't think it
200     #      buys anything keeping this separate
201     print "Cleaning binaries from the DB..."
202     print "Deleting from binaries table... "
203     for bin in session.query(DBBinary).join(DBBinary.poolfile).filter(PoolFile.last_used <= delete_date):
204         Logger.log(["delete binary", bin.poolfile.filename])
205         if not Options["No-Action"]:
206             session.delete(bin)
207     if not Options["No-Action"]:
208         session.commit()
209
210 ########################################
211
212 def clean(now_date, delete_date, max_delete, session):
213     cnf = Config()
214
215     count = 0
216     size = 0
217
218     print "Cleaning out packages..."
219
220     cur_date = now_date.strftime("%Y-%m-%d")
221     dest = os.path.join(cnf["Dir::Morgue"], cnf["Clean-Suites::MorgueSubDir"], cur_date)
222     if not os.path.exists(dest):
223         os.mkdir(dest)
224
225     # Delete from source
226     print "Deleting from source table... "
227     q = session.execute("""
228 SELECT s.id, f.filename FROM source s, files f
229   WHERE f.last_used <= :deletedate
230         AND s.file = f.id""", {'deletedate': delete_date})
231     for s in q.fetchall():
232         Logger.log(["delete source", s[1], s[0]])
233         if not Options["No-Action"]:
234             session.execute("DELETE FROM dsc_files WHERE source = :s_id", {"s_id":s[0]})
235             session.execute("DELETE FROM source WHERE id = :s_id", {"s_id":s[0]})
236
237     if not Options["No-Action"]:
238         session.commit()
239
240     # Delete files from the pool
241     old_files = session.query(PoolFile).filter(PoolFile.last_used <= delete_date)
242     if max_delete is not None:
243         old_files = old_files.limit(max_delete)
244         print "Limiting removals to %d" % max_delete
245
246     for pf in old_files:
247         filename = os.path.join(pf.location.path, pf.filename)
248         if not os.path.exists(filename):
249             utils.warn("can not find '%s'." % (filename))
250             continue
251         Logger.log(["delete pool file", filename])
252         if os.path.isfile(filename):
253             if os.path.islink(filename):
254                 count += 1
255                 Logger.log(["delete symlink", filename])
256                 if not Options["No-Action"]:
257                     os.unlink(filename)
258             else:
259                 size += os.stat(filename)[stat.ST_SIZE]
260                 count += 1
261
262                 dest_filename = dest + '/' + os.path.basename(filename)
263                 # If the destination file exists; try to find another filename to use
264                 if os.path.exists(dest_filename):
265                     dest_filename = utils.find_next_free(dest_filename)
266
267                 Logger.log(["move to morgue", filename, dest_filename])
268                 if not Options["No-Action"]:
269                     utils.move(filename, dest_filename)
270
271             if not Options["No-Action"]:
272                 session.delete(pf)
273
274         else:
275             utils.fubar("%s is neither symlink nor file?!" % (filename))
276
277     if not Options["No-Action"]:
278         session.commit()
279
280     if count > 0:
281         Logger.log(["total", count, utils.size_type(size)])
282         print "Cleaned %d files, %s." % (count, utils.size_type(size))
283
284 ################################################################################
285
286 def clean_maintainers(now_date, delete_date, max_delete, session):
287     print "Cleaning out unused Maintainer entries..."
288
289     # TODO Replace this whole thing with one SQL statement
290     q = session.execute("""
291 SELECT m.id, m.name FROM maintainer m
292   WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.maintainer = m.id)
293     AND NOT EXISTS (SELECT 1 FROM source s WHERE s.maintainer = m.id OR s.changedby = m.id)
294     AND NOT EXISTS (SELECT 1 FROM src_uploaders u WHERE u.maintainer = m.id)""")
295
296     count = 0
297
298     for i in q.fetchall():
299         maintainer_id = i[0]
300         Logger.log(["delete maintainer", i[1]])
301         if not Options["No-Action"]:
302             session.execute("DELETE FROM maintainer WHERE id = :maint", {'maint': maintainer_id})
303         count += 1
304
305     if not Options["No-Action"]:
306         session.commit()
307
308     if count > 0:
309         Logger.log(["total", count])
310         print "Cleared out %d maintainer entries." % (count)
311
312 ################################################################################
313
314 def clean_fingerprints(now_date, delete_date, max_delete, session):
315     print "Cleaning out unused fingerprint entries..."
316
317     # TODO Replace this whole thing with one SQL statement
318     q = session.execute("""
319 SELECT f.id, f.fingerprint FROM fingerprint f
320   WHERE f.keyring IS NULL
321     AND NOT EXISTS (SELECT 1 FROM binaries b WHERE b.sig_fpr = f.id)
322     AND NOT EXISTS (SELECT 1 FROM source s WHERE s.sig_fpr = f.id)""")
323
324     count = 0
325
326     for i in q.fetchall():
327         fingerprint_id = i[0]
328         Logger.log(["delete fingerprint", i[1]])
329         if not Options["No-Action"]:
330             session.execute("DELETE FROM fingerprint WHERE id = :fpr", {'fpr': fingerprint_id})
331         count += 1
332
333     if not Options["No-Action"]:
334         session.commit()
335
336     if count > 0:
337         Logger.log(["total", count])
338         print "Cleared out %d fingerprint entries." % (count)
339
340 ################################################################################
341
342 def clean_queue_build(now_date, delete_date, max_delete, session):
343
344     cnf = Config()
345
346     if not cnf.ValueList("Dinstall::QueueBuildSuites") or Options["No-Action"]:
347         return
348
349     print "Cleaning out queue build symlinks..."
350
351     our_delete_date = now_date - timedelta(seconds = int(cnf["Clean-Suites::QueueBuildStayOfExecution"]))
352     count = 0
353
354     for qf in session.query(BuildQueueFile).filter(BuildQueueFile.last_used <= our_delete_date):
355         if not os.path.exists(qf.filename):
356             utils.warn("%s (from queue_build) doesn't exist." % (qf.filename))
357             continue
358
359         if not cnf.FindB("Dinstall::SecurityQueueBuild") and not os.path.islink(qf.filename):
360             utils.fubar("%s (from queue_build) should be a symlink but isn't." % (qf.filename))
361
362         Logger.log(["delete queue build", qf.filename])
363         if not Options["No-Action"]:
364             os.unlink(qf.filename)
365             session.delete(qf)
366         count += 1
367
368     if not Options["No-Action"]:
369         session.commit()
370
371     if count:
372         Logger.log(["total", count])
373         print "Cleaned %d queue_build files." % (count)
374
375 ################################################################################
376
377 def clean_empty_directories(session):
378     """
379     Removes empty directories from pool directories.
380     """
381
382     count = 0
383
384     cursor = session.execute(
385         "SELECT DISTINCT(path) FROM location WHERE type = :type",
386         {'type': 'pool'},
387     )
388     bases = [x[0] for x in cursor.fetchall()]
389
390     for base in bases:
391         for dirpath, dirnames, filenames in os.walk(base, topdown=False):
392             if not filenames and not dirnames:
393                 to_remove = os.path.join(base, dirpath)
394                 if not Options["No-Action"]:
395                     Logger.log(["removing directory", to_remove])
396                     os.removedirs(to_remove)
397                 count += 1
398
399     if count:
400         Logger.log(["total removed directories", count])
401
402 ################################################################################
403
404 def main():
405     global Options, Logger
406
407     cnf = Config()
408
409     for i in ["Help", "No-Action", "Maximum" ]:
410         if not cnf.has_key("Clean-Suites::Options::%s" % (i)):
411             cnf["Clean-Suites::Options::%s" % (i)] = ""
412
413     Arguments = [('h',"help","Clean-Suites::Options::Help"),
414                  ('n',"no-action","Clean-Suites::Options::No-Action"),
415                  ('m',"maximum","Clean-Suites::Options::Maximum", "HasArg")]
416
417     apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
418     Options = cnf.SubTree("Clean-Suites::Options")
419
420     if cnf["Clean-Suites::Options::Maximum"] != "":
421         try:
422             # Only use Maximum if it's an integer
423             max_delete = int(cnf["Clean-Suites::Options::Maximum"])
424             if max_delete < 1:
425                 utils.fubar("If given, Maximum must be at least 1")
426         except ValueError, e:
427             utils.fubar("If given, Maximum must be an integer")
428     else:
429         max_delete = None
430
431     if Options["Help"]:
432         usage()
433
434     Logger = daklog.Logger(cnf, "clean-suites", debug=Options["No-Action"])
435
436     session = DBConn().session()
437
438     now_date = datetime.now()
439     delete_date = now_date - timedelta(seconds=int(cnf['Clean-Suites::StayOfExecution']))
440
441     check_binaries(now_date, delete_date, max_delete, session)
442     clean_binaries(now_date, delete_date, max_delete, session)
443     check_sources(now_date, delete_date, max_delete, session)
444     check_files(now_date, delete_date, max_delete, session)
445     clean(now_date, delete_date, max_delete, session)
446     clean_maintainers(now_date, delete_date, max_delete, session)
447     clean_fingerprints(now_date, delete_date, max_delete, session)
448     clean_queue_build(now_date, delete_date, max_delete, session)
449     clean_empty_directories(session)
450
451     Logger.close()
452
453 ################################################################################
454
455 if __name__ == '__main__':
456     main()