3 """ Cleans up unassociated binary and source packages """
4 # Copyright (C) 2000, 2001, 2002, 2003, 2006 James Troup <james@nocrew.org>
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 ################################################################################
22 # 07:05|<elmo> well.. *shrug*.. no, probably not.. but to fix it,
23 # | we're going to have to implement reference counting
24 # | through dependencies.. do we really want to go down
27 # 07:05|<Culus> elmo: Augh! <brain jumps out of skull>
29 ################################################################################
31 import os, stat, sys, time
33 from datetime import datetime, timedelta
35 from daklib.config import Config
36 from daklib.dbconn import *
37 from daklib import utils
38 from daklib import daklog
40 ################################################################################
45 ################################################################################
47 def usage (exit_code=0):
48 print """Usage: dak clean-suites [OPTIONS]
49 Clean old packages from suites.
51 -n, --no-action don't do anything
52 -h, --help show this help and exit
53 -m, --maximum maximum number of files to remove"""
56 ################################################################################
58 def check_binaries(now_date, delete_date, max_delete, session):
59 print "Checking for orphaned binary packages..."
61 # Get the list of binary packages not in a suite and mark them for
64 q = session.execute("""
65 SELECT b.file, f.filename
69 WHERE f.last_used IS NULL
71 (SELECT ba.bin FROM bin_associations ba)
73 (SELECT bqf.fileid FROM build_queue_files bqf)""")
74 for i in q.fetchall():
75 Logger.log(["set lastused", i[1]])
76 if not Options["No-Action"]:
77 session.execute("UPDATE files SET last_used = :lastused WHERE id = :fileid AND last_used IS NULL",
78 {'lastused': now_date, 'fileid': i[0]})
80 if not Options["No-Action"]:
83 # Check for any binaries which are marked for eventual deletion
84 # but are now used again.
86 q = session.execute("""
87 SELECT b.file, f.filename
91 WHERE f.last_used IS NOT NULL
93 (SELECT ba.bin FROM bin_associations ba)
95 (SELECT bqf.fileid FROM build_queue_files bqf))""")
97 for i in q.fetchall():
98 Logger.log(["unset lastused", i[1]])
99 if not Options["No-Action"]:
100 session.execute("UPDATE files SET last_used = NULL WHERE id = :fileid", {'fileid': i[0]})
102 if not Options["No-Action"]:
105 ########################################
107 def check_sources(now_date, delete_date, max_delete, session):
108 print "Checking for orphaned source packages..."
110 # Get the list of source packages not in a suite and not used by
112 q = session.execute("""
113 SELECT s.id, s.file, f.filename
117 WHERE f.last_used IS NULL
119 (SELECT sa.source FROM src_associations sa)
121 (SELECT b.source FROM binaries b)
123 (SELECT bqf.fileid FROM build_queue_files bqf)""")
125 #### XXX: this should ignore cases where the files for the binary b
126 #### have been marked for deletion (so the delay between bins go
127 #### byebye and sources go byebye is 0 instead of StayOfExecution)
129 for i in q.fetchall():
134 # Mark the .dsc file for deletion
135 Logger.log(["set lastused", dsc_fname])
136 if not Options["No-Action"]:
137 session.execute("""UPDATE files SET last_used = :last_used
138 WHERE id = :dscfileid AND last_used IS NULL""",
139 {'last_used': now_date, 'dscfileid': dsc_file_id})
141 # Mark all other files references by .dsc too if they're not used by anyone else
142 x = session.execute("""SELECT f.id, f.filename FROM files f, dsc_files d
143 WHERE d.source = :sourceid AND d.file = f.id""",
144 {'sourceid': source_id})
145 for j in x.fetchall():
148 y = session.execute("SELECT id FROM dsc_files d WHERE d.file = :fileid", {'fileid': file_id})
149 if len(y.fetchall()) == 1:
150 Logger.log(["set lastused", file_name])
151 if not Options["No-Action"]:
152 session.execute("""UPDATE files SET last_used = :lastused
153 WHERE id = :fileid AND last_used IS NULL""",
154 {'lastused': now_date, 'fileid': file_id})
156 if not Options["No-Action"]:
159 # Check for any sources which are marked for deletion but which
160 # are now used again.
161 q = session.execute("""
162 SELECT f.id, f.filename FROM source s, files f, dsc_files df
163 WHERE f.last_used IS NOT NULL AND s.id = df.source AND df.file = f.id
164 AND ((EXISTS (SELECT 1 FROM src_associations sa WHERE sa.source = s.id))
165 OR (EXISTS (SELECT 1 FROM binaries b WHERE b.source = s.id))
166 OR (EXISTS (SELECT 1 FROM build_queue_files bqf WHERE bqf.fileid = s.file)))""")
168 #### XXX: this should also handle deleted binaries specially (ie, not
169 #### reinstate sources because of them
171 for i in q.fetchall():
172 Logger.log(["unset lastused", i[1]])
173 if not Options["No-Action"]:
174 session.execute("UPDATE files SET last_used = NULL WHERE id = :fileid",
177 if not Options["No-Action"]:
180 ########################################
182 def check_files(now_date, delete_date, max_delete, session):
183 # FIXME: this is evil; nothing should ever be in this state. if
184 # they are, it's a bug.
186 # However, we've discovered it happens sometimes so we print a huge warning
187 # and then mark the file for deletion. This probably masks a bug somwhere
188 # else but is better than collecting cruft forever
190 print "Checking for unused files..."
191 q = session.execute("""
192 SELECT id, filename FROM files f
193 WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.file = f.id)
194 AND NOT EXISTS (SELECT 1 FROM dsc_files df WHERE df.file = f.id)
195 AND NOT EXISTS (SELECT 1 FROM changes_pool_files cpf WHERE cpf.fileid = f.id)
196 AND NOT EXISTS (SELECT 1 FROM build_queue_files qf WHERE qf.fileid = f.id)
197 AND last_used IS NULL
198 ORDER BY filename""")
202 utils.warn("check_files found something it shouldn't")
204 utils.warn("orphaned file: %s" % x)
205 Logger.log(["set lastused", x[1], "ORPHANED FILE"])
206 if not Options["No-Action"]:
207 session.execute("UPDATE files SET last_used = :lastused WHERE id = :fileid",
208 {'lastused': now_date, 'fileid': x[0]})
210 if not Options["No-Action"]:
213 def clean_binaries(now_date, delete_date, max_delete, session):
214 # We do this here so that the binaries we remove will have their
215 # source also removed (if possible).
217 # XXX: why doesn't this remove the files here as well? I don't think it
218 # buys anything keeping this separate
219 print "Cleaning binaries from the DB..."
220 print "Deleting from binaries table... "
221 for bin in session.query(DBBinary).join(DBBinary.poolfile).filter(PoolFile.last_used <= delete_date):
222 Logger.log(["delete binary", bin.poolfile.filename])
223 if not Options["No-Action"]:
225 if not Options["No-Action"]:
228 ########################################
230 def clean(now_date, delete_date, max_delete, session):
236 print "Cleaning out packages..."
238 cur_date = now_date.strftime("%Y-%m-%d")
239 dest = os.path.join(cnf["Dir::Morgue"], cnf["Clean-Suites::MorgueSubDir"], cur_date)
240 if not Options["No-Action"] and not os.path.exists(dest):
244 print "Deleting from source table... "
245 q = session.execute("""
246 SELECT s.id, f.filename FROM source s, files f
247 WHERE f.last_used <= :deletedate
248 AND s.file = f.id""", {'deletedate': delete_date})
249 for s in q.fetchall():
250 Logger.log(["delete source", s[1], s[0]])
251 if not Options["No-Action"]:
252 session.execute("DELETE FROM dsc_files WHERE source = :s_id", {"s_id":s[0]})
253 session.execute("DELETE FROM source WHERE id = :s_id", {"s_id":s[0]})
255 if not Options["No-Action"]:
258 # Delete files from the pool
259 old_files = session.query(PoolFile).filter(PoolFile.last_used <= delete_date)
260 if max_delete is not None:
261 old_files = old_files.limit(max_delete)
262 print "Limiting removals to %d" % max_delete
265 filename = os.path.join(pf.location.path, pf.filename)
266 if not os.path.exists(filename):
267 utils.warn("can not find '%s'." % (filename))
269 Logger.log(["delete pool file", filename])
270 if os.path.isfile(filename):
271 if os.path.islink(filename):
273 Logger.log(["delete symlink", filename])
274 if not Options["No-Action"]:
277 size += os.stat(filename)[stat.ST_SIZE]
280 dest_filename = dest + '/' + os.path.basename(filename)
281 # If the destination file exists; try to find another filename to use
282 if os.path.exists(dest_filename):
283 dest_filename = utils.find_next_free(dest_filename)
285 Logger.log(["move to morgue", filename, dest_filename])
286 if not Options["No-Action"]:
287 utils.move(filename, dest_filename)
289 if not Options["No-Action"]:
293 utils.fubar("%s is neither symlink nor file?!" % (filename))
295 if not Options["No-Action"]:
299 Logger.log(["total", count, utils.size_type(size)])
300 print "Cleaned %d files, %s." % (count, utils.size_type(size))
302 ################################################################################
304 def clean_maintainers(now_date, delete_date, max_delete, session):
305 print "Cleaning out unused Maintainer entries..."
307 # TODO Replace this whole thing with one SQL statement
308 q = session.execute("""
309 SELECT m.id, m.name FROM maintainer m
310 WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.maintainer = m.id)
311 AND NOT EXISTS (SELECT 1 FROM source s WHERE s.maintainer = m.id OR s.changedby = m.id)
312 AND NOT EXISTS (SELECT 1 FROM src_uploaders u WHERE u.maintainer = m.id)""")
316 for i in q.fetchall():
318 Logger.log(["delete maintainer", i[1]])
319 if not Options["No-Action"]:
320 session.execute("DELETE FROM maintainer WHERE id = :maint", {'maint': maintainer_id})
323 if not Options["No-Action"]:
327 Logger.log(["total", count])
328 print "Cleared out %d maintainer entries." % (count)
330 ################################################################################
332 def clean_fingerprints(now_date, delete_date, max_delete, session):
333 print "Cleaning out unused fingerprint entries..."
335 # TODO Replace this whole thing with one SQL statement
336 q = session.execute("""
337 SELECT f.id, f.fingerprint FROM fingerprint f
338 WHERE f.keyring IS NULL
339 AND NOT EXISTS (SELECT 1 FROM binaries b WHERE b.sig_fpr = f.id)
340 AND NOT EXISTS (SELECT 1 FROM source s WHERE s.sig_fpr = f.id)""")
344 for i in q.fetchall():
345 fingerprint_id = i[0]
346 Logger.log(["delete fingerprint", i[1]])
347 if not Options["No-Action"]:
348 session.execute("DELETE FROM fingerprint WHERE id = :fpr", {'fpr': fingerprint_id})
351 if not Options["No-Action"]:
355 Logger.log(["total", count])
356 print "Cleared out %d fingerprint entries." % (count)
358 ################################################################################
360 def clean_empty_directories(session):
362 Removes empty directories from pool directories.
365 print "Cleaning out empty directories..."
369 cursor = session.execute(
370 "SELECT DISTINCT(path) FROM location WHERE type = :type",
373 bases = [x[0] for x in cursor.fetchall()]
376 for dirpath, dirnames, filenames in os.walk(base, topdown=False):
377 if not filenames and not dirnames:
378 to_remove = os.path.join(base, dirpath)
379 if not Options["No-Action"]:
380 Logger.log(["removing directory", to_remove])
381 os.removedirs(to_remove)
385 Logger.log(["total removed directories", count])
387 ################################################################################
390 global Options, Logger
394 for i in ["Help", "No-Action", "Maximum" ]:
395 if not cnf.has_key("Clean-Suites::Options::%s" % (i)):
396 cnf["Clean-Suites::Options::%s" % (i)] = ""
398 Arguments = [('h',"help","Clean-Suites::Options::Help"),
399 ('n',"no-action","Clean-Suites::Options::No-Action"),
400 ('m',"maximum","Clean-Suites::Options::Maximum", "HasArg")]
402 apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
403 Options = cnf.SubTree("Clean-Suites::Options")
405 if cnf["Clean-Suites::Options::Maximum"] != "":
407 # Only use Maximum if it's an integer
408 max_delete = int(cnf["Clean-Suites::Options::Maximum"])
410 utils.fubar("If given, Maximum must be at least 1")
411 except ValueError, e:
412 utils.fubar("If given, Maximum must be an integer")
419 Logger = daklog.Logger(cnf, "clean-suites", debug=Options["No-Action"])
421 session = DBConn().session()
423 now_date = datetime.now()
424 delete_date = now_date - timedelta(seconds=int(cnf['Clean-Suites::StayOfExecution']))
426 check_binaries(now_date, delete_date, max_delete, session)
427 clean_binaries(now_date, delete_date, max_delete, session)
428 check_sources(now_date, delete_date, max_delete, session)
429 check_files(now_date, delete_date, max_delete, session)
430 clean(now_date, delete_date, max_delete, session)
431 clean_maintainers(now_date, delete_date, max_delete, session)
432 clean_fingerprints(now_date, delete_date, max_delete, session)
433 clean_empty_directories(session)
437 ################################################################################
439 if __name__ == '__main__':