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