]> git.decadent.org.uk Git - dak.git/blob - dak/clean_suites.py
Merge remote-tracking branch 'nthykier/auto-decruft'
[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, session):
68     Logger.log(["Checking for orphaned binary packages..."])
69
70     # Get the list of binary packages not in a suite and mark them for
71     # deletion.
72     # Check for any binaries which are marked for eventual deletion
73     # but are now used again.
74
75     query = """
76        WITH usage AS (
77          SELECT
78            af.archive_id AS archive_id,
79            af.file_id AS file_id,
80            af.component_id AS component_id,
81            BOOL_OR(EXISTS (SELECT 1 FROM bin_associations ba
82                             JOIN suite s ON ba.suite = s.id
83                            WHERE ba.bin = b.id
84                              AND s.archive_id = af.archive_id))
85              AS in_use
86          FROM files_archive_map af
87          JOIN binaries b ON af.file_id = b.file
88          GROUP BY af.archive_id, af.file_id, af.component_id
89        )
90
91        UPDATE files_archive_map af
92           SET last_used = CASE WHEN usage.in_use THEN NULL ELSE :last_used END
93          FROM usage, files f, archive
94         WHERE af.archive_id = usage.archive_id AND af.file_id = usage.file_id AND af.component_id = usage.component_id
95           AND ((af.last_used IS NULL AND NOT usage.in_use) OR (af.last_used IS NOT NULL AND usage.in_use))
96           AND af.file_id = f.id
97           AND af.archive_id = archive.id
98        RETURNING archive.name, f.filename, af.last_used IS NULL"""
99
100     res = session.execute(query, {'last_used': now_date})
101     for i in res:
102         op = "set lastused"
103         if i[2]:
104             op = "unset lastused"
105         Logger.log([op, i[0], i[1]])
106
107 ########################################
108
109 def check_sources(now_date, session):
110     Logger.log(["Checking for orphaned source packages..."])
111
112     # Get the list of source packages not in a suite and not used by
113     # any binaries.
114
115     # Check for any sources which are marked for deletion but which
116     # are now used again.
117
118     # TODO: the UPDATE part is the same as in check_binaries. Merge?
119
120     query = """
121     WITH usage AS (
122       SELECT
123         af.archive_id AS archive_id,
124         af.file_id AS file_id,
125         af.component_id AS component_id,
126         BOOL_OR(EXISTS (SELECT 1 FROM src_associations sa
127                          JOIN suite s ON sa.suite = s.id
128                         WHERE sa.source = df.source
129                           AND s.archive_id = af.archive_id)
130           OR EXISTS (SELECT 1 FROM files_archive_map af_bin
131                               JOIN binaries b ON af_bin.file_id = b.file
132                              WHERE b.source = df.source
133                                AND af_bin.archive_id = af.archive_id
134                                AND (af_bin.last_used IS NULL OR af_bin.last_used > ad.delete_date))
135           OR EXISTS (SELECT 1 FROM extra_src_references esr
136                          JOIN bin_associations ba ON esr.bin_id = ba.bin
137                          JOIN binaries b ON ba.bin = b.id
138                          JOIN suite s ON ba.suite = s.id
139                         WHERE esr.src_id = df.source
140                           AND s.archive_id = af.archive_id))
141           AS in_use
142       FROM files_archive_map af
143       JOIN dsc_files df ON af.file_id = df.file
144       JOIN archive_delete_date ad ON af.archive_id = ad.archive_id
145       GROUP BY af.archive_id, af.file_id, af.component_id
146     )
147
148     UPDATE files_archive_map af
149        SET last_used = CASE WHEN usage.in_use THEN NULL ELSE :last_used END
150       FROM usage, files f, archive
151      WHERE af.archive_id = usage.archive_id AND af.file_id = usage.file_id AND af.component_id = usage.component_id
152        AND ((af.last_used IS NULL AND NOT usage.in_use) OR (af.last_used IS NOT NULL AND usage.in_use))
153        AND af.file_id = f.id
154        AND af.archive_id = archive.id
155
156     RETURNING archive.name, f.filename, af.last_used IS NULL
157     """
158
159     res = session.execute(query, {'last_used': now_date})
160     for i in res:
161         op = "set lastused"
162         if i[2]:
163             op = "unset lastused"
164         Logger.log([op, i[0], i[1]])
165
166 ########################################
167
168 def check_files(now_date, session):
169     # FIXME: this is evil; nothing should ever be in this state.  if
170     # they are, it's a bug.
171
172     # However, we've discovered it happens sometimes so we print a huge warning
173     # and then mark the file for deletion.  This probably masks a bug somwhere
174     # else but is better than collecting cruft forever
175
176     Logger.log(["Checking for unused files..."])
177     q = session.execute("""
178     UPDATE files_archive_map af
179        SET last_used = :last_used
180       FROM files f, archive
181      WHERE af.file_id = f.id
182        AND af.archive_id = archive.id
183        AND NOT EXISTS (SELECT 1 FROM binaries b WHERE b.file = af.file_id)
184        AND NOT EXISTS (SELECT 1 FROM dsc_files df WHERE df.file = af.file_id)
185        AND af.last_used IS NULL
186     RETURNING archive.name, f.filename""", {'last_used': now_date})
187
188     for x in q:
189         utils.warn("orphaned file: {0}".format(x))
190         Logger.log(["set lastused", x[0], x[1], "ORPHANED FILE"])
191
192     if not Options["No-Action"]:
193         session.commit()
194
195 def clean_binaries(now_date, 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
202     Logger.log(["Deleting from binaries table... "])
203     q = session.execute("""
204       DELETE FROM binaries b
205        USING files f
206        WHERE f.id = b.file
207          AND NOT EXISTS (SELECT 1 FROM files_archive_map af
208                                   JOIN archive_delete_date ad ON af.archive_id = ad.archive_id
209                                  WHERE af.file_id = b.file
210                                    AND (af.last_used IS NULL OR af.last_used > ad.delete_date))
211       RETURNING f.filename
212     """)
213     for b in q:
214         Logger.log(["delete binary", b[0]])
215
216 ########################################
217
218 def clean(now_date, archives, max_delete, session):
219     cnf = Config()
220
221     count = 0
222     size = 0
223
224     Logger.log(["Cleaning out packages..."])
225
226     morguedir = cnf.get("Dir::Morgue", os.path.join("Dir::Pool", 'morgue'))
227     morguesubdir = cnf.get("Clean-Suites::MorgueSubDir", 'pool')
228
229     # Build directory as morguedir/morguesubdir/year/month/day
230     dest = os.path.join(morguedir,
231                         morguesubdir,
232                         str(now_date.year),
233                         '%.2d' % now_date.month,
234                         '%.2d' % now_date.day)
235
236     if not Options["No-Action"] and not os.path.exists(dest):
237         os.makedirs(dest)
238
239     # Delete from source
240     Logger.log(["Deleting from source table..."])
241     q = session.execute("""
242       WITH
243       deleted_sources AS (
244         DELETE FROM source
245          USING files f
246          WHERE source.file = f.id
247            AND NOT EXISTS (SELECT 1 FROM files_archive_map af
248                                     JOIN archive_delete_date ad ON af.archive_id = ad.archive_id
249                                    WHERE af.file_id = source.file
250                                      AND (af.last_used IS NULL OR af.last_used > ad.delete_date))
251         RETURNING source.id AS id, f.filename AS filename
252       ),
253       deleted_dsc_files AS (
254         DELETE FROM dsc_files df WHERE df.source IN (SELECT id FROM deleted_sources)
255         RETURNING df.file AS file_id
256       ),
257       now_unused_source_files AS (
258         UPDATE files_archive_map af
259            SET last_used = '1977-03-13 13:37:42' -- Kill it now. We waited long enough before removing the .dsc.
260          WHERE af.file_id IN (SELECT file_id FROM deleted_dsc_files)
261            AND NOT EXISTS (SELECT 1 FROM dsc_files df WHERE df.file = af.file_id)
262       )
263       SELECT filename FROM deleted_sources""")
264     for s in q:
265         Logger.log(["delete source", s[0]])
266
267     if not Options["No-Action"]:
268         session.commit()
269
270     # Delete files from the pool
271     old_files = session.query(ArchiveFile).filter('files_archive_map.last_used <= (SELECT delete_date FROM archive_delete_date ad WHERE ad.archive_id = files_archive_map.archive_id)').join(Archive)
272     if max_delete is not None:
273         old_files = old_files.limit(max_delete)
274         Logger.log(["Limiting removals to %d" % max_delete])
275
276     if archives is not None:
277         archive_ids = [ a.archive_id for a in archives ]
278         old_files = old_files.filter(ArchiveFile.archive_id.in_(archive_ids))
279
280     for af in old_files:
281         filename = af.path
282         if not os.path.exists(filename):
283             Logger.log(["database referred to non-existing file", af.path])
284             session.delete(af)
285             continue
286         Logger.log(["delete archive file", filename])
287         if os.path.isfile(filename):
288             if os.path.islink(filename):
289                 count += 1
290                 Logger.log(["delete symlink", filename])
291                 if not Options["No-Action"]:
292                     os.unlink(filename)
293             else:
294                 size += os.stat(filename)[stat.ST_SIZE]
295                 count += 1
296
297                 dest_filename = dest + '/' + os.path.basename(filename)
298                 # If the destination file exists; try to find another filename to use
299                 if os.path.lexists(dest_filename):
300                     dest_filename = utils.find_next_free(dest_filename)
301
302                 if not Options["No-Action"]:
303                     if af.archive.use_morgue:
304                         Logger.log(["move to morgue", filename, dest_filename])
305                         utils.move(filename, dest_filename)
306                     else:
307                         Logger.log(["removed file", filename])
308                         os.unlink(filename)
309
310             if not Options["No-Action"]:
311                 session.delete(af)
312                 session.commit()
313
314         else:
315             utils.fubar("%s is neither symlink nor file?!" % (filename))
316
317     if count > 0:
318         Logger.log(["total", count, utils.size_type(size)])
319
320     # Delete entries in files no longer referenced by any archive
321     query = """
322        DELETE FROM files f
323         WHERE NOT EXISTS (SELECT 1 FROM files_archive_map af WHERE af.file_id = f.id)
324     """
325     session.execute(query)
326
327     if not Options["No-Action"]:
328         session.commit()
329
330 ################################################################################
331
332 def clean_maintainers(now_date, session):
333     Logger.log(["Cleaning out unused Maintainer entries..."])
334
335     # TODO Replace this whole thing with one SQL statement
336     q = session.execute("""
337 SELECT m.id, m.name FROM maintainer m
338   WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.maintainer = m.id)
339     AND NOT EXISTS (SELECT 1 FROM source s WHERE s.maintainer = m.id OR s.changedby = m.id)
340     AND NOT EXISTS (SELECT 1 FROM src_uploaders u WHERE u.maintainer = m.id)""")
341
342     count = 0
343
344     for i in q.fetchall():
345         maintainer_id = i[0]
346         Logger.log(["delete maintainer", i[1]])
347         if not Options["No-Action"]:
348             session.execute("DELETE FROM maintainer WHERE id = :maint", {'maint': maintainer_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
357 ################################################################################
358
359 def clean_fingerprints(now_date, session):
360     Logger.log(["Cleaning out unused fingerprint entries..."])
361
362     # TODO Replace this whole thing with one SQL statement
363     q = session.execute("""
364 SELECT f.id, f.fingerprint FROM fingerprint f
365   WHERE f.keyring IS NULL
366     AND NOT EXISTS (SELECT 1 FROM binaries b WHERE b.sig_fpr = f.id)
367     AND NOT EXISTS (SELECT 1 FROM source s WHERE s.sig_fpr = f.id)
368     AND NOT EXISTS (SELECT 1 FROM acl_per_source aps WHERE aps.created_by_id = f.id)""")
369
370     count = 0
371
372     for i in q.fetchall():
373         fingerprint_id = i[0]
374         Logger.log(["delete fingerprint", i[1]])
375         if not Options["No-Action"]:
376             session.execute("DELETE FROM fingerprint WHERE id = :fpr", {'fpr': fingerprint_id})
377         count += 1
378
379     if not Options["No-Action"]:
380         session.commit()
381
382     if count > 0:
383         Logger.log(["total", count])
384
385 ################################################################################
386
387 def clean_empty_directories(session):
388     """
389     Removes empty directories from pool directories.
390     """
391
392     Logger.log(["Cleaning out empty directories..."])
393
394     count = 0
395
396     cursor = session.execute(
397         """SELECT DISTINCT(path) FROM archive"""
398     )
399     bases = [x[0] for x in cursor.fetchall()]
400
401     for base in bases:
402         for dirpath, dirnames, filenames in os.walk(base, topdown=False):
403             if not filenames and not dirnames:
404                 to_remove = os.path.join(base, dirpath)
405                 if not Options["No-Action"]:
406                     Logger.log(["removing directory", to_remove])
407                     os.removedirs(to_remove)
408                 count += 1
409
410     if count:
411         Logger.log(["total removed directories", count])
412
413 ################################################################################
414
415 def set_archive_delete_dates(now_date, session):
416     session.execute("""
417         CREATE TEMPORARY TABLE archive_delete_date (
418           archive_id INT NOT NULL,
419           delete_date TIMESTAMP NOT NULL
420         )""")
421
422     session.execute("""
423         INSERT INTO archive_delete_date
424           (archive_id, delete_date)
425         SELECT
426           archive.id, :now_date - archive.stayofexecution
427         FROM archive""", {'now_date': now_date})
428
429     session.flush()
430
431 ################################################################################
432
433 def main():
434     global Options, Logger
435
436     cnf = Config()
437
438     for i in ["Help", "No-Action", "Maximum" ]:
439         if not cnf.has_key("Clean-Suites::Options::%s" % (i)):
440             cnf["Clean-Suites::Options::%s" % (i)] = ""
441
442     Arguments = [('h',"help","Clean-Suites::Options::Help"),
443                  ('a','archive','Clean-Suites::Options::Archive','HasArg'),
444                  ('n',"no-action","Clean-Suites::Options::No-Action"),
445                  ('m',"maximum","Clean-Suites::Options::Maximum", "HasArg")]
446
447     apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
448     Options = cnf.subtree("Clean-Suites::Options")
449
450     if cnf["Clean-Suites::Options::Maximum"] != "":
451         try:
452             # Only use Maximum if it's an integer
453             max_delete = int(cnf["Clean-Suites::Options::Maximum"])
454             if max_delete < 1:
455                 utils.fubar("If given, Maximum must be at least 1")
456         except ValueError as e:
457             utils.fubar("If given, Maximum must be an integer")
458     else:
459         max_delete = None
460
461     if Options["Help"]:
462         usage()
463
464     program = "clean-suites"
465     if Options['No-Action']:
466         program = "clean-suites (no action)"
467     Logger = daklog.Logger(program, debug=Options["No-Action"])
468
469     session = DBConn().session()
470
471     archives = None
472     if 'Archive' in Options:
473         archive_names = Options['Archive'].split(',')
474         archives = session.query(Archive).filter(Archive.archive_name.in_(archive_names)).all()
475         if len(archives) == 0:
476             utils.fubar('Unknown archive.')
477
478     now_date = datetime.now()
479
480     set_archive_delete_dates(now_date, session)
481
482     check_binaries(now_date, session)
483     clean_binaries(now_date, session)
484     check_sources(now_date, session)
485     check_files(now_date, session)
486     clean(now_date, archives, max_delete, session)
487     clean_maintainers(now_date, session)
488     clean_fingerprints(now_date, session)
489     clean_empty_directories(session)
490
491     session.rollback()
492
493     Logger.close()
494
495 ################################################################################
496
497 if __name__ == '__main__':
498     main()