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
258 AND s.id NOT IN (SELECT src_id FROM extra_src_references)""", {'deletedate': delete_date})
259 for s in q.fetchall():
260 Logger.log(["delete source", s[1], s[0]])
261 if not Options["No-Action"]:
262 session.execute("DELETE FROM dsc_files WHERE source = :s_id", {"s_id":s[0]})
263 session.execute("DELETE FROM source WHERE id = :s_id", {"s_id":s[0]})
265 if not Options["No-Action"]:
268 # Delete files from the pool
269 old_files = session.query(PoolFile).filter(PoolFile.last_used <= delete_date)
270 if max_delete is not None:
271 old_files = old_files.limit(max_delete)
272 print "Limiting removals to %d" % max_delete
275 filename = os.path.join(pf.location.path, pf.filename)
276 if not os.path.exists(filename):
277 utils.warn("can not find '%s'." % (filename))
279 Logger.log(["delete pool file", filename])
280 if os.path.isfile(filename):
281 if os.path.islink(filename):
283 Logger.log(["delete symlink", filename])
284 if not Options["No-Action"]:
287 size += os.stat(filename)[stat.ST_SIZE]
290 dest_filename = dest + '/' + os.path.basename(filename)
291 # If the destination file exists; try to find another filename to use
292 if os.path.exists(dest_filename):
293 dest_filename = utils.find_next_free(dest_filename)
295 Logger.log(["move to morgue", filename, dest_filename])
296 if not Options["No-Action"]:
297 utils.move(filename, dest_filename)
299 if not Options["No-Action"]:
303 utils.fubar("%s is neither symlink nor file?!" % (filename))
305 if not Options["No-Action"]:
309 Logger.log(["total", count, utils.size_type(size)])
310 print "Cleaned %d files, %s." % (count, utils.size_type(size))
312 ################################################################################
314 def clean_maintainers(now_date, delete_date, max_delete, session):
315 print "Cleaning out unused Maintainer entries..."
317 # TODO Replace this whole thing with one SQL statement
318 q = session.execute("""
319 SELECT m.id, m.name FROM maintainer m
320 WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.maintainer = m.id)
321 AND NOT EXISTS (SELECT 1 FROM source s WHERE s.maintainer = m.id OR s.changedby = m.id)
322 AND NOT EXISTS (SELECT 1 FROM src_uploaders u WHERE u.maintainer = m.id)""")
326 for i in q.fetchall():
328 Logger.log(["delete maintainer", i[1]])
329 if not Options["No-Action"]:
330 session.execute("DELETE FROM maintainer WHERE id = :maint", {'maint': maintainer_id})
333 if not Options["No-Action"]:
337 Logger.log(["total", count])
338 print "Cleared out %d maintainer entries." % (count)
340 ################################################################################
342 def clean_fingerprints(now_date, delete_date, max_delete, session):
343 print "Cleaning out unused fingerprint entries..."
345 # TODO Replace this whole thing with one SQL statement
346 q = session.execute("""
347 SELECT f.id, f.fingerprint FROM fingerprint f
348 WHERE f.keyring IS NULL
349 AND NOT EXISTS (SELECT 1 FROM binaries b WHERE b.sig_fpr = f.id)
350 AND NOT EXISTS (SELECT 1 FROM source s WHERE s.sig_fpr = f.id)""")
354 for i in q.fetchall():
355 fingerprint_id = i[0]
356 Logger.log(["delete fingerprint", i[1]])
357 if not Options["No-Action"]:
358 session.execute("DELETE FROM fingerprint WHERE id = :fpr", {'fpr': fingerprint_id})
361 if not Options["No-Action"]:
365 Logger.log(["total", count])
366 print "Cleared out %d fingerprint entries." % (count)
368 ################################################################################
370 def clean_empty_directories(session):
372 Removes empty directories from pool directories.
375 print "Cleaning out empty directories..."
379 cursor = session.execute(
380 "SELECT DISTINCT(path) FROM location WHERE type = :type",
383 bases = [x[0] for x in cursor.fetchall()]
386 for dirpath, dirnames, filenames in os.walk(base, topdown=False):
387 if not filenames and not dirnames:
388 to_remove = os.path.join(base, dirpath)
389 if not Options["No-Action"]:
390 Logger.log(["removing directory", to_remove])
391 os.removedirs(to_remove)
395 Logger.log(["total removed directories", count])
397 ################################################################################
400 global Options, Logger
404 for i in ["Help", "No-Action", "Maximum" ]:
405 if not cnf.has_key("Clean-Suites::Options::%s" % (i)):
406 cnf["Clean-Suites::Options::%s" % (i)] = ""
408 Arguments = [('h',"help","Clean-Suites::Options::Help"),
409 ('n',"no-action","Clean-Suites::Options::No-Action"),
410 ('m',"maximum","Clean-Suites::Options::Maximum", "HasArg")]
412 apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
413 Options = cnf.SubTree("Clean-Suites::Options")
415 if cnf["Clean-Suites::Options::Maximum"] != "":
417 # Only use Maximum if it's an integer
418 max_delete = int(cnf["Clean-Suites::Options::Maximum"])
420 utils.fubar("If given, Maximum must be at least 1")
421 except ValueError, e:
422 utils.fubar("If given, Maximum must be an integer")
429 Logger = daklog.Logger(cnf, "clean-suites", debug=Options["No-Action"])
431 session = DBConn().session()
433 now_date = datetime.now()
434 delete_date = now_date - timedelta(seconds=int(cnf['Clean-Suites::StayOfExecution']))
436 check_binaries(now_date, delete_date, max_delete, session)
437 clean_binaries(now_date, delete_date, max_delete, session)
438 check_sources(now_date, delete_date, max_delete, session)
439 check_files(now_date, delete_date, max_delete, session)
440 clean(now_date, delete_date, max_delete, session)
441 clean_maintainers(now_date, delete_date, max_delete, session)
442 clean_fingerprints(now_date, delete_date, max_delete, session)
443 clean_empty_directories(session)
447 ################################################################################
449 if __name__ == '__main__':