]> git.decadent.org.uk Git - dak.git/blob - dak/clean_suites.py
move build queue cleaning to manage-build-queues
[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
66          FROM binaries b
67     LEFT JOIN files f
68       ON (b.file = f.id)
69    WHERE f.last_used IS NULL
70      AND b.id NOT IN
71          (SELECT ba.bin FROM bin_associations ba)
72      AND f.id NOT IN
73          (SELECT bqf.fileid FROM build_queue_files bqf)""")
74     for i in q.fetchall():
75         Logger.log(["set lastused", i[1]])
76         if not Options["No-Action"]:
77             session.execute("UPDATE files SET last_used = :lastused WHERE id = :fileid AND last_used IS NULL",
78                             {'lastused': now_date, 'fileid': i[0]})
79
80     if not Options["No-Action"]:
81         session.commit()
82
83     # Check for any binaries which are marked for eventual deletion
84     # but are now used again.
85
86     q = session.execute("""
87 SELECT b.file, f.filename
88          FROM binaries b
89     LEFT JOIN files f
90       ON (b.file = f.id)
91    WHERE f.last_used IS NOT NULL
92      AND (b.id IN
93           (SELECT ba.bin FROM bin_associations ba)
94           OR f.id IN
95           (SELECT bqf.fileid FROM build_queue_files bqf))""")
96
97     for i in q.fetchall():
98         Logger.log(["unset lastused", i[1]])
99         if not Options["No-Action"]:
100             session.execute("UPDATE files SET last_used = NULL WHERE id = :fileid", {'fileid': i[0]})
101
102     if not Options["No-Action"]:
103         session.commit()
104
105 ########################################
106
107 def check_sources(now_date, delete_date, max_delete, session):
108     print "Checking for orphaned source packages..."
109
110     # Get the list of source packages not in a suite and not used by
111     # any binaries.
112     q = session.execute("""
113 SELECT s.id, s.file, f.filename
114        FROM source s
115   LEFT JOIN files f
116     ON (s.file = f.id)
117   WHERE f.last_used IS NULL
118    AND s.id NOT IN
119         (SELECT sa.source FROM src_associations sa)
120    AND s.id NOT IN
121         (SELECT b.source FROM binaries b)
122    AND f.id NOT IN
123         (SELECT bqf.fileid FROM build_queue_files bqf)""")
124
125     #### XXX: this should ignore cases where the files for the binary b
126     ####      have been marked for deletion (so the delay between bins go
127     ####      byebye and sources go byebye is 0 instead of StayOfExecution)
128
129     for i in q.fetchall():
130         source_id = i[0]
131         dsc_file_id = i[1]
132         dsc_fname = i[2]
133
134         # Mark the .dsc file for deletion
135         Logger.log(["set lastused", dsc_fname])
136         if not Options["No-Action"]:
137             session.execute("""UPDATE files SET last_used = :last_used
138                                 WHERE id = :dscfileid AND last_used IS NULL""",
139                             {'last_used': now_date, 'dscfileid': dsc_file_id})
140
141         # Mark all other files references by .dsc too if they're not used by anyone else
142         x = session.execute("""SELECT f.id, f.filename FROM files f, dsc_files d
143                               WHERE d.source = :sourceid AND d.file = f.id""",
144                              {'sourceid': source_id})
145         for j in x.fetchall():
146             file_id = j[0]
147             file_name = j[1]
148             y = session.execute("SELECT id FROM dsc_files d WHERE d.file = :fileid", {'fileid': file_id})
149             if len(y.fetchall()) == 1:
150                 Logger.log(["set lastused", file_name])
151                 if not Options["No-Action"]:
152                     session.execute("""UPDATE files SET last_used = :lastused
153                                        WHERE id = :fileid AND last_used IS NULL""",
154                                     {'lastused': now_date, 'fileid': file_id})
155
156     if not Options["No-Action"]:
157         session.commit()
158
159     # Check for any sources which are marked for deletion but which
160     # are now used again.
161     q = session.execute("""
162 SELECT f.id, f.filename FROM source s, files f, dsc_files df
163   WHERE f.last_used IS NOT NULL AND s.id = df.source AND df.file = f.id
164     AND ((EXISTS (SELECT 1 FROM src_associations sa WHERE sa.source = s.id))
165       OR (EXISTS (SELECT 1 FROM binaries b WHERE b.source = s.id))
166       OR (EXISTS (SELECT 1 FROM build_queue_files bqf WHERE bqf.fileid = s.file)))""")
167
168     #### XXX: this should also handle deleted binaries specially (ie, not
169     ####      reinstate sources because of them
170
171     for i in q.fetchall():
172         Logger.log(["unset lastused", i[1]])
173         if not Options["No-Action"]:
174             session.execute("UPDATE files SET last_used = NULL WHERE id = :fileid",
175                             {'fileid': i[0]})
176
177     if not Options["No-Action"]:
178         session.commit()
179
180 ########################################
181
182 def check_files(now_date, delete_date, max_delete, session):
183     # FIXME: this is evil; nothing should ever be in this state.  if
184     # they are, it's a bug.
185
186     # However, we've discovered it happens sometimes so we print a huge warning
187     # and then mark the file for deletion.  This probably masks a bug somwhere
188     # else but is better than collecting cruft forever
189
190     print "Checking for unused files..."
191     q = session.execute("""
192 SELECT id, filename FROM files f
193   WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.file = f.id)
194     AND NOT EXISTS (SELECT 1 FROM dsc_files df WHERE df.file = f.id)
195     AND NOT EXISTS (SELECT 1 FROM changes_pool_files cpf WHERE cpf.fileid = f.id)
196     AND NOT EXISTS (SELECT 1 FROM build_queue_files qf WHERE qf.fileid = f.id)
197     AND last_used IS NULL
198     ORDER BY filename""")
199
200     ql = q.fetchall()
201     if len(ql) > 0:
202         utils.warn("check_files found something it shouldn't")
203         for x in ql:
204             utils.warn("orphaned file: %s" % x)
205             Logger.log(["set lastused", x[1], "ORPHANED FILE"])
206             if not Options["No-Action"]:
207                  session.execute("UPDATE files SET last_used = :lastused WHERE id = :fileid",
208                                  {'lastused': now_date, 'fileid': x[0]})
209
210         if not Options["No-Action"]:
211             session.commit()
212
213 def clean_binaries(now_date, delete_date, max_delete, session):
214     # We do this here so that the binaries we remove will have their
215     # source also removed (if possible).
216
217     # XXX: why doesn't this remove the files here as well? I don't think it
218     #      buys anything keeping this separate
219     print "Cleaning binaries from the DB..."
220     print "Deleting from binaries table... "
221     for bin in session.query(DBBinary).join(DBBinary.poolfile).filter(PoolFile.last_used <= delete_date):
222         Logger.log(["delete binary", bin.poolfile.filename])
223         if not Options["No-Action"]:
224             session.delete(bin)
225     if not Options["No-Action"]:
226         session.commit()
227
228 ########################################
229
230 def clean(now_date, delete_date, max_delete, session):
231     cnf = Config()
232
233     count = 0
234     size = 0
235
236     print "Cleaning out packages..."
237
238     cur_date = now_date.strftime("%Y-%m-%d")
239     dest = os.path.join(cnf["Dir::Morgue"], cnf["Clean-Suites::MorgueSubDir"], cur_date)
240     if not os.path.exists(dest):
241         os.mkdir(dest)
242
243     # Delete from source
244     print "Deleting from source table... "
245     q = session.execute("""
246 SELECT s.id, f.filename FROM source s, files f
247   WHERE f.last_used <= :deletedate
248         AND s.file = f.id""", {'deletedate': delete_date})
249     for s in q.fetchall():
250         Logger.log(["delete source", s[1], s[0]])
251         if not Options["No-Action"]:
252             session.execute("DELETE FROM dsc_files WHERE source = :s_id", {"s_id":s[0]})
253             session.execute("DELETE FROM source WHERE id = :s_id", {"s_id":s[0]})
254
255     if not Options["No-Action"]:
256         session.commit()
257
258     # Delete files from the pool
259     old_files = session.query(PoolFile).filter(PoolFile.last_used <= delete_date)
260     if max_delete is not None:
261         old_files = old_files.limit(max_delete)
262         print "Limiting removals to %d" % max_delete
263
264     for pf in old_files:
265         filename = os.path.join(pf.location.path, pf.filename)
266         if not os.path.exists(filename):
267             utils.warn("can not find '%s'." % (filename))
268             continue
269         Logger.log(["delete pool file", filename])
270         if os.path.isfile(filename):
271             if os.path.islink(filename):
272                 count += 1
273                 Logger.log(["delete symlink", filename])
274                 if not Options["No-Action"]:
275                     os.unlink(filename)
276             else:
277                 size += os.stat(filename)[stat.ST_SIZE]
278                 count += 1
279
280                 dest_filename = dest + '/' + os.path.basename(filename)
281                 # If the destination file exists; try to find another filename to use
282                 if os.path.exists(dest_filename):
283                     dest_filename = utils.find_next_free(dest_filename)
284
285                 Logger.log(["move to morgue", filename, dest_filename])
286                 if not Options["No-Action"]:
287                     utils.move(filename, dest_filename)
288
289             if not Options["No-Action"]:
290                 session.delete(pf)
291
292         else:
293             utils.fubar("%s is neither symlink nor file?!" % (filename))
294
295     if not Options["No-Action"]:
296         session.commit()
297
298     if count > 0:
299         Logger.log(["total", count, utils.size_type(size)])
300         print "Cleaned %d files, %s." % (count, utils.size_type(size))
301
302 ################################################################################
303
304 def clean_maintainers(now_date, delete_date, max_delete, session):
305     print "Cleaning out unused Maintainer entries..."
306
307     # TODO Replace this whole thing with one SQL statement
308     q = session.execute("""
309 SELECT m.id, m.name FROM maintainer m
310   WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.maintainer = m.id)
311     AND NOT EXISTS (SELECT 1 FROM source s WHERE s.maintainer = m.id OR s.changedby = m.id)
312     AND NOT EXISTS (SELECT 1 FROM src_uploaders u WHERE u.maintainer = m.id)""")
313
314     count = 0
315
316     for i in q.fetchall():
317         maintainer_id = i[0]
318         Logger.log(["delete maintainer", i[1]])
319         if not Options["No-Action"]:
320             session.execute("DELETE FROM maintainer WHERE id = :maint", {'maint': maintainer_id})
321         count += 1
322
323     if not Options["No-Action"]:
324         session.commit()
325
326     if count > 0:
327         Logger.log(["total", count])
328         print "Cleared out %d maintainer entries." % (count)
329
330 ################################################################################
331
332 def clean_fingerprints(now_date, delete_date, max_delete, session):
333     print "Cleaning out unused fingerprint entries..."
334
335     # TODO Replace this whole thing with one SQL statement
336     q = session.execute("""
337 SELECT f.id, f.fingerprint FROM fingerprint f
338   WHERE f.keyring IS NULL
339     AND NOT EXISTS (SELECT 1 FROM binaries b WHERE b.sig_fpr = f.id)
340     AND NOT EXISTS (SELECT 1 FROM source s WHERE s.sig_fpr = f.id)""")
341
342     count = 0
343
344     for i in q.fetchall():
345         fingerprint_id = i[0]
346         Logger.log(["delete fingerprint", i[1]])
347         if not Options["No-Action"]:
348             session.execute("DELETE FROM fingerprint WHERE id = :fpr", {'fpr': fingerprint_id})
349         count += 1
350
351     if not Options["No-Action"]:
352         session.commit()
353
354     if count > 0:
355         Logger.log(["total", count])
356         print "Cleared out %d fingerprint entries." % (count)
357
358 ################################################################################
359
360 def clean_empty_directories(session):
361     """
362     Removes empty directories from pool directories.
363     """
364
365     count = 0
366
367     cursor = session.execute(
368         "SELECT DISTINCT(path) FROM location WHERE type = :type",
369         {'type': 'pool'},
370     )
371     bases = [x[0] for x in cursor.fetchall()]
372
373     for base in bases:
374         for dirpath, dirnames, filenames in os.walk(base, topdown=False):
375             if not filenames and not dirnames:
376                 to_remove = os.path.join(base, dirpath)
377                 if not Options["No-Action"]:
378                     Logger.log(["removing directory", to_remove])
379                     os.removedirs(to_remove)
380                 count += 1
381
382     if count:
383         Logger.log(["total removed directories", count])
384
385 ################################################################################
386
387 def main():
388     global Options, Logger
389
390     cnf = Config()
391
392     for i in ["Help", "No-Action", "Maximum" ]:
393         if not cnf.has_key("Clean-Suites::Options::%s" % (i)):
394             cnf["Clean-Suites::Options::%s" % (i)] = ""
395
396     Arguments = [('h',"help","Clean-Suites::Options::Help"),
397                  ('n',"no-action","Clean-Suites::Options::No-Action"),
398                  ('m',"maximum","Clean-Suites::Options::Maximum", "HasArg")]
399
400     apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
401     Options = cnf.SubTree("Clean-Suites::Options")
402
403     if cnf["Clean-Suites::Options::Maximum"] != "":
404         try:
405             # Only use Maximum if it's an integer
406             max_delete = int(cnf["Clean-Suites::Options::Maximum"])
407             if max_delete < 1:
408                 utils.fubar("If given, Maximum must be at least 1")
409         except ValueError, e:
410             utils.fubar("If given, Maximum must be an integer")
411     else:
412         max_delete = None
413
414     if Options["Help"]:
415         usage()
416
417     Logger = daklog.Logger(cnf, "clean-suites", debug=Options["No-Action"])
418
419     session = DBConn().session()
420
421     now_date = datetime.now()
422     delete_date = now_date - timedelta(seconds=int(cnf['Clean-Suites::StayOfExecution']))
423
424     check_binaries(now_date, delete_date, max_delete, session)
425     clean_binaries(now_date, delete_date, max_delete, session)
426     check_sources(now_date, delete_date, max_delete, session)
427     check_files(now_date, delete_date, max_delete, session)
428     clean(now_date, delete_date, max_delete, session)
429     clean_maintainers(now_date, delete_date, max_delete, session)
430     clean_fingerprints(now_date, delete_date, max_delete, session)
431     clean_empty_directories(session)
432
433     Logger.close()
434
435 ################################################################################
436
437 if __name__ == '__main__':
438     main()