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