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, delete_date, max_delete, session):
68 print "Checking for orphaned binary packages..."
70 # Get the list of binary packages not in a suite and mark them for
73 q = session.execute("""
74 SELECT b.file, f.filename
78 WHERE f.last_used IS NULL
80 (SELECT ba.bin FROM bin_associations ba)
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]})
89 if not Options["No-Action"]:
92 # Check for any binaries which are marked for eventual deletion
93 # but are now used again.
95 q = session.execute("""
96 SELECT b.file, f.filename
100 WHERE f.last_used IS NOT NULL
102 (SELECT ba.bin FROM bin_associations ba)
104 (SELECT bqf.fileid FROM build_queue_files bqf))""")
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]})
111 if not Options["No-Action"]:
114 ########################################
116 def check_sources(now_date, delete_date, max_delete, session):
117 print "Checking for orphaned source packages..."
119 # Get the list of source packages not in a suite and not used by
121 q = session.execute("""
122 SELECT s.id, s.file, f.filename
126 WHERE f.last_used IS NULL
128 (SELECT sa.source FROM src_associations sa)
130 (SELECT b.source FROM binaries b)
131 AND s.id NOT IN (SELECT esr.src_id FROM extra_src_references esr)
133 (SELECT bqf.fileid FROM build_queue_files bqf)""")
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)
139 for i in q.fetchall():
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})
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():
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})
166 if not Options["No-Action"]:
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)))""")
179 #### XXX: this should also handle deleted binaries specially (ie, not
180 #### reinstate sources because of them
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",
188 if not Options["No-Action"]:
191 ########################################
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.
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
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""")
213 utils.warn("check_files found something it shouldn't")
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]})
221 if not Options["No-Action"]:
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).
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"]:
236 if not Options["No-Action"]:
239 ########################################
241 def clean(now_date, delete_date, max_delete, session):
247 print "Cleaning out packages..."
249 morguedir = cnf.get("Dir::Morgue", os.path.join("Dir::Pool", 'morgue'))
250 morguesubdir = cnf.get("Clean-Suites::MorgueSubDir", 'pool')
252 # Build directory as morguedir/morguesubdir/year/month/day
253 dest = os.path.join(morguedir,
256 '%.2d' % now_date.month,
257 '%.2d' % now_date.day)
259 if not Options["No-Action"] and not os.path.exists(dest):
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
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]})
275 if not Options["No-Action"]:
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
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))
289 Logger.log(["delete pool file", filename])
290 if os.path.isfile(filename):
291 if os.path.islink(filename):
293 Logger.log(["delete symlink", filename])
294 if not Options["No-Action"]:
297 size += os.stat(filename)[stat.ST_SIZE]
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)
305 Logger.log(["move to morgue", filename, dest_filename])
306 if not Options["No-Action"]:
307 utils.move(filename, dest_filename)
309 if not Options["No-Action"]:
314 utils.fubar("%s is neither symlink nor file?!" % (filename))
317 Logger.log(["total", count, utils.size_type(size)])
318 print "Cleaned %d files, %s." % (count, utils.size_type(size))
320 ################################################################################
322 def clean_maintainers(now_date, delete_date, max_delete, session):
323 print "Cleaning out unused Maintainer entries..."
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)""")
334 for i in q.fetchall():
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})
341 if not Options["No-Action"]:
345 Logger.log(["total", count])
346 print "Cleared out %d maintainer entries." % (count)
348 ################################################################################
350 def clean_fingerprints(now_date, delete_date, max_delete, session):
351 print "Cleaning out unused fingerprint entries..."
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)""")
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})
369 if not Options["No-Action"]:
373 Logger.log(["total", count])
374 print "Cleared out %d fingerprint entries." % (count)
376 ################################################################################
378 def clean_empty_directories(session):
380 Removes empty directories from pool directories.
383 print "Cleaning out empty directories..."
387 cursor = session.execute(
388 "SELECT DISTINCT(path) FROM location WHERE type = :type",
391 bases = [x[0] for x in cursor.fetchall()]
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)
403 Logger.log(["total removed directories", count])
405 ################################################################################
408 global Options, Logger
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)] = ""
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")]
420 apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
421 Options = cnf.SubTree("Clean-Suites::Options")
423 if cnf["Clean-Suites::Options::Maximum"] != "":
425 # Only use Maximum if it's an integer
426 max_delete = int(cnf["Clean-Suites::Options::Maximum"])
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")
437 Logger = daklog.Logger("clean-suites", debug=Options["No-Action"])
439 session = DBConn().session()
441 now_date = datetime.now()
443 # Stay of execution; default to 1.5 days
444 soe = int(cnf.get('Clean-Suites::StayOfExecution', '129600'))
446 delete_date = now_date - timedelta(seconds=soe)
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)
459 ################################################################################
461 if __name__ == '__main__':