3 """ Cleans up unassociated binary and source packages
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
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.
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.
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
26 ################################################################################
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
33 # 07:05|<Culus> elmo: Augh! <brain jumps out of skull>
35 ################################################################################
42 from datetime import datetime, timedelta
44 from daklib.config import Config
45 from daklib.dbconn import *
46 from daklib import utils
47 from daklib import daklog
49 ################################################################################
54 ################################################################################
56 def usage (exit_code=0):
57 print """Usage: dak clean-suites [OPTIONS]
58 Clean old packages from suites.
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"""
65 ################################################################################
67 def check_binaries(now_date, session):
68 Logger.log(["Checking for orphaned binary packages..."])
70 # Get the list of binary packages not in a suite and mark them for
72 # Check for any binaries which are marked for eventual deletion
73 # but are now used again.
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
84 AND s.archive_id = af.archive_id))
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
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))
97 AND af.archive_id = archive.id
98 RETURNING archive.name, f.filename, af.last_used IS NULL"""
100 res = session.execute(query, {'last_used': now_date})
104 op = "unset lastused"
105 Logger.log([op, i[0], i[1]])
107 ########################################
109 def check_sources(now_date, session):
110 Logger.log(["Checking for orphaned source packages..."])
112 # Get the list of source packages not in a suite and not used by
115 # Check for any sources which are marked for deletion but which
116 # are now used again.
118 # TODO: the UPDATE part is the same as in check_binaries. Merge?
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))
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
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
156 RETURNING archive.name, f.filename, af.last_used IS NULL
159 res = session.execute(query, {'last_used': now_date})
163 op = "unset lastused"
164 Logger.log([op, i[0], i[1]])
166 ########################################
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.
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
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})
189 utils.warn("orphaned file: {0}".format(x))
190 Logger.log(["set lastused", x[0], x[1], "ORPHANED FILE"])
192 if not Options["No-Action"]:
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).
199 # XXX: why doesn't this remove the files here as well? I don't think it
200 # buys anything keeping this separate
202 Logger.log(["Deleting from binaries table... "])
203 q = session.execute("""
204 DELETE FROM binaries b
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))
214 Logger.log(["delete binary", b[0]])
216 ########################################
218 def clean(now_date, archives, max_delete, session):
224 Logger.log(["Cleaning out packages..."])
226 morguedir = cnf.get("Dir::Morgue", os.path.join("Dir::Pool", 'morgue'))
227 morguesubdir = cnf.get("Clean-Suites::MorgueSubDir", 'pool')
229 # Build directory as morguedir/morguesubdir/year/month/day
230 dest = os.path.join(morguedir,
233 '%.2d' % now_date.month,
234 '%.2d' % now_date.day)
236 if not Options["No-Action"] and not os.path.exists(dest):
240 Logger.log(["Deleting from source table..."])
241 q = session.execute("""
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
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
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)
263 SELECT filename FROM deleted_sources""")
265 Logger.log(["delete source", s[0]])
267 if not Options["No-Action"]:
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])
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))
282 if not os.path.exists(filename):
283 Logger.log(["database referred to non-existing file", af.path])
286 Logger.log(["delete archive file", filename])
287 if os.path.isfile(filename):
288 if os.path.islink(filename):
290 Logger.log(["delete symlink", filename])
291 if not Options["No-Action"]:
294 size += os.stat(filename)[stat.ST_SIZE]
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)
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)
307 Logger.log(["removed file", filename])
310 if not Options["No-Action"]:
315 utils.fubar("%s is neither symlink nor file?!" % (filename))
318 Logger.log(["total", count, utils.size_type(size)])
320 # Delete entries in files no longer referenced by any archive
323 WHERE NOT EXISTS (SELECT 1 FROM files_archive_map af WHERE af.file_id = f.id)
325 session.execute(query)
327 if not Options["No-Action"]:
330 ################################################################################
332 def clean_maintainers(now_date, session):
333 Logger.log(["Cleaning out unused Maintainer entries..."])
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)""")
344 for i in q.fetchall():
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})
351 if not Options["No-Action"]:
355 Logger.log(["total", count])
357 ################################################################################
359 def clean_fingerprints(now_date, session):
360 Logger.log(["Cleaning out unused fingerprint entries..."])
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)""")
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})
379 if not Options["No-Action"]:
383 Logger.log(["total", count])
385 ################################################################################
387 def clean_empty_directories(session):
389 Removes empty directories from pool directories.
392 Logger.log(["Cleaning out empty directories..."])
396 cursor = session.execute(
397 """SELECT DISTINCT(path) FROM archive"""
399 bases = [x[0] for x in cursor.fetchall()]
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)
411 Logger.log(["total removed directories", count])
413 ################################################################################
415 def set_archive_delete_dates(now_date, session):
417 CREATE TEMPORARY TABLE archive_delete_date (
418 archive_id INT NOT NULL,
419 delete_date TIMESTAMP NOT NULL
423 INSERT INTO archive_delete_date
424 (archive_id, delete_date)
426 archive.id, :now_date - archive.stayofexecution
427 FROM archive""", {'now_date': now_date})
431 ################################################################################
434 global Options, Logger
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)] = ""
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")]
447 apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
448 Options = cnf.subtree("Clean-Suites::Options")
450 if cnf["Clean-Suites::Options::Maximum"] != "":
452 # Only use Maximum if it's an integer
453 max_delete = int(cnf["Clean-Suites::Options::Maximum"])
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")
464 program = "clean-suites"
465 if Options['No-Action']:
466 program = "clean-suites (no action)"
467 Logger = daklog.Logger(program, debug=Options["No-Action"])
469 session = DBConn().session()
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.')
478 now_date = datetime.now()
480 set_archive_delete_dates(now_date, session)
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)
495 ################################################################################
497 if __name__ == '__main__':