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)
132 (SELECT bqf.fileid FROM build_queue_files bqf)""")
134 #### XXX: this should ignore cases where the files for the binary b
135 #### have been marked for deletion (so the delay between bins go
136 #### byebye and sources go byebye is 0 instead of StayOfExecution)
138 for i in q.fetchall():
143 # Mark the .dsc file for deletion
144 Logger.log(["set lastused", dsc_fname])
145 if not Options["No-Action"]:
146 session.execute("""UPDATE files SET last_used = :last_used
147 WHERE id = :dscfileid AND last_used IS NULL""",
148 {'last_used': now_date, 'dscfileid': dsc_file_id})
150 # Mark all other files references by .dsc too if they're not used by anyone else
151 x = session.execute("""SELECT f.id, f.filename FROM files f, dsc_files d
152 WHERE d.source = :sourceid AND d.file = f.id""",
153 {'sourceid': source_id})
154 for j in x.fetchall():
157 y = session.execute("SELECT id FROM dsc_files d WHERE d.file = :fileid", {'fileid': file_id})
158 if len(y.fetchall()) == 1:
159 Logger.log(["set lastused", file_name])
160 if not Options["No-Action"]:
161 session.execute("""UPDATE files SET last_used = :lastused
162 WHERE id = :fileid AND last_used IS NULL""",
163 {'lastused': now_date, 'fileid': file_id})
165 if not Options["No-Action"]:
168 # Check for any sources which are marked for deletion but which
169 # are now used again.
170 q = session.execute("""
171 SELECT f.id, f.filename FROM source s, files f, dsc_files df
172 WHERE f.last_used IS NOT NULL AND s.id = df.source AND df.file = f.id
173 AND ((EXISTS (SELECT 1 FROM src_associations sa WHERE sa.source = s.id))
174 OR (EXISTS (SELECT 1 FROM binaries b WHERE b.source = s.id))
175 OR (EXISTS (SELECT 1 FROM build_queue_files bqf WHERE bqf.fileid = s.file)))""")
177 #### XXX: this should also handle deleted binaries specially (ie, not
178 #### reinstate sources because of them
180 for i in q.fetchall():
181 Logger.log(["unset lastused", i[1]])
182 if not Options["No-Action"]:
183 session.execute("UPDATE files SET last_used = NULL WHERE id = :fileid",
186 if not Options["No-Action"]:
189 ########################################
191 def check_files(now_date, delete_date, max_delete, session):
192 # FIXME: this is evil; nothing should ever be in this state. if
193 # they are, it's a bug.
195 # However, we've discovered it happens sometimes so we print a huge warning
196 # and then mark the file for deletion. This probably masks a bug somwhere
197 # else but is better than collecting cruft forever
199 print "Checking for unused files..."
200 q = session.execute("""
201 SELECT id, filename FROM files f
202 WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.file = f.id)
203 AND NOT EXISTS (SELECT 1 FROM dsc_files df WHERE df.file = f.id)
204 AND NOT EXISTS (SELECT 1 FROM changes_pool_files cpf WHERE cpf.fileid = f.id)
205 AND NOT EXISTS (SELECT 1 FROM build_queue_files qf WHERE qf.fileid = f.id)
206 AND last_used IS NULL
207 ORDER BY filename""")
211 utils.warn("check_files found something it shouldn't")
213 utils.warn("orphaned file: %s" % x)
214 Logger.log(["set lastused", x[1], "ORPHANED FILE"])
215 if not Options["No-Action"]:
216 session.execute("UPDATE files SET last_used = :lastused WHERE id = :fileid",
217 {'lastused': now_date, 'fileid': x[0]})
219 if not Options["No-Action"]:
222 def clean_binaries(now_date, delete_date, max_delete, session):
223 # We do this here so that the binaries we remove will have their
224 # source also removed (if possible).
226 # XXX: why doesn't this remove the files here as well? I don't think it
227 # buys anything keeping this separate
228 print "Cleaning binaries from the DB..."
229 print "Deleting from binaries table... "
230 for bin in session.query(DBBinary).join(DBBinary.poolfile).filter(PoolFile.last_used <= delete_date):
231 Logger.log(["delete binary", bin.poolfile.filename])
232 if not Options["No-Action"]:
234 if not Options["No-Action"]:
237 ########################################
239 def clean(now_date, delete_date, max_delete, session):
245 print "Cleaning out packages..."
247 cur_date = now_date.strftime("%Y-%m-%d")
248 dest = os.path.join(cnf["Dir::Morgue"], cnf["Clean-Suites::MorgueSubDir"], cur_date)
249 if not Options["No-Action"] and not os.path.exists(dest):
253 print "Deleting from source table... "
254 q = session.execute("""
255 SELECT s.id, f.filename FROM source s, files f
256 WHERE f.last_used <= :deletedate
257 AND s.file = f.id""", {'deletedate': delete_date})
258 for s in q.fetchall():
259 Logger.log(["delete source", s[1], s[0]])
260 if not Options["No-Action"]:
261 session.execute("DELETE FROM dsc_files WHERE source = :s_id", {"s_id":s[0]})
262 session.execute("DELETE FROM source WHERE id = :s_id", {"s_id":s[0]})
264 if not Options["No-Action"]:
267 # Delete files from the pool
268 old_files = session.query(PoolFile).filter(PoolFile.last_used <= delete_date)
269 if max_delete is not None:
270 old_files = old_files.limit(max_delete)
271 print "Limiting removals to %d" % max_delete
274 filename = os.path.join(pf.location.path, pf.filename)
275 if not os.path.exists(filename):
276 utils.warn("can not find '%s'." % (filename))
278 Logger.log(["delete pool file", filename])
279 if os.path.isfile(filename):
280 if os.path.islink(filename):
282 Logger.log(["delete symlink", filename])
283 if not Options["No-Action"]:
286 size += os.stat(filename)[stat.ST_SIZE]
289 dest_filename = dest + '/' + os.path.basename(filename)
290 # If the destination file exists; try to find another filename to use
291 if os.path.exists(dest_filename):
292 dest_filename = utils.find_next_free(dest_filename)
294 Logger.log(["move to morgue", filename, dest_filename])
295 if not Options["No-Action"]:
296 utils.move(filename, dest_filename)
298 if not Options["No-Action"]:
302 utils.fubar("%s is neither symlink nor file?!" % (filename))
304 if not Options["No-Action"]:
308 Logger.log(["total", count, utils.size_type(size)])
309 print "Cleaned %d files, %s." % (count, utils.size_type(size))
311 ################################################################################
313 def clean_maintainers(now_date, delete_date, max_delete, session):
314 print "Cleaning out unused Maintainer entries..."
316 # TODO Replace this whole thing with one SQL statement
317 q = session.execute("""
318 SELECT m.id, m.name FROM maintainer m
319 WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.maintainer = m.id)
320 AND NOT EXISTS (SELECT 1 FROM source s WHERE s.maintainer = m.id OR s.changedby = m.id)
321 AND NOT EXISTS (SELECT 1 FROM src_uploaders u WHERE u.maintainer = m.id)""")
325 for i in q.fetchall():
327 Logger.log(["delete maintainer", i[1]])
328 if not Options["No-Action"]:
329 session.execute("DELETE FROM maintainer WHERE id = :maint", {'maint': maintainer_id})
332 if not Options["No-Action"]:
336 Logger.log(["total", count])
337 print "Cleared out %d maintainer entries." % (count)
339 ################################################################################
341 def clean_fingerprints(now_date, delete_date, max_delete, session):
342 print "Cleaning out unused fingerprint entries..."
344 # TODO Replace this whole thing with one SQL statement
345 q = session.execute("""
346 SELECT f.id, f.fingerprint FROM fingerprint f
347 WHERE f.keyring IS NULL
348 AND NOT EXISTS (SELECT 1 FROM binaries b WHERE b.sig_fpr = f.id)
349 AND NOT EXISTS (SELECT 1 FROM source s WHERE s.sig_fpr = f.id)""")
353 for i in q.fetchall():
354 fingerprint_id = i[0]
355 Logger.log(["delete fingerprint", i[1]])
356 if not Options["No-Action"]:
357 session.execute("DELETE FROM fingerprint WHERE id = :fpr", {'fpr': fingerprint_id})
360 if not Options["No-Action"]:
364 Logger.log(["total", count])
365 print "Cleared out %d fingerprint entries." % (count)
367 ################################################################################
369 def clean_empty_directories(session):
371 Removes empty directories from pool directories.
374 print "Cleaning out empty directories..."
378 cursor = session.execute(
379 "SELECT DISTINCT(path) FROM location WHERE type = :type",
382 bases = [x[0] for x in cursor.fetchall()]
385 for dirpath, dirnames, filenames in os.walk(base, topdown=False):
386 if not filenames and not dirnames:
387 to_remove = os.path.join(base, dirpath)
388 if not Options["No-Action"]:
389 Logger.log(["removing directory", to_remove])
390 os.removedirs(to_remove)
394 Logger.log(["total removed directories", count])
396 ################################################################################
399 global Options, Logger
403 for i in ["Help", "No-Action", "Maximum" ]:
404 if not cnf.has_key("Clean-Suites::Options::%s" % (i)):
405 cnf["Clean-Suites::Options::%s" % (i)] = ""
407 Arguments = [('h',"help","Clean-Suites::Options::Help"),
408 ('n',"no-action","Clean-Suites::Options::No-Action"),
409 ('m',"maximum","Clean-Suites::Options::Maximum", "HasArg")]
411 apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
412 Options = cnf.SubTree("Clean-Suites::Options")
414 if cnf["Clean-Suites::Options::Maximum"] != "":
416 # Only use Maximum if it's an integer
417 max_delete = int(cnf["Clean-Suites::Options::Maximum"])
419 utils.fubar("If given, Maximum must be at least 1")
420 except ValueError, e:
421 utils.fubar("If given, Maximum must be an integer")
428 Logger = daklog.Logger(cnf, "clean-suites", debug=Options["No-Action"])
430 session = DBConn().session()
432 now_date = datetime.now()
433 delete_date = now_date - timedelta(seconds=int(cnf['Clean-Suites::StayOfExecution']))
435 check_binaries(now_date, delete_date, max_delete, session)
436 clean_binaries(now_date, delete_date, max_delete, session)
437 check_sources(now_date, delete_date, max_delete, session)
438 check_files(now_date, delete_date, max_delete, session)
439 clean(now_date, delete_date, max_delete, session)
440 clean_maintainers(now_date, delete_date, max_delete, session)
441 clean_fingerprints(now_date, delete_date, max_delete, session)
442 clean_empty_directories(session)
446 ################################################################################
448 if __name__ == '__main__':