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, pg, stat, sys, time
33 from daklib import utils
35 ################################################################################
40 now_date = None; # mark newly "deleted" things as deleted "now"
41 delete_date = None; # delete things marked "deleted" earler than this
44 ################################################################################
46 def usage (exit_code=0):
47 print """Usage: dak clean-suites [OPTIONS]
48 Clean old packages from suites.
50 -n, --no-action don't do anything
51 -h, --help show this help and exit
52 -m, --maximum maximum number of files to remove"""
55 ################################################################################
58 global delete_date, now_date
60 print "Checking for orphaned binary packages..."
62 # Get the list of binary packages not in a suite and mark them for
64 q = projectB.query("""
65 SELECT b.file FROM binaries b, files f
66 WHERE f.last_used IS NULL AND b.file = f.id
67 AND NOT EXISTS (SELECT 1 FROM bin_associations ba WHERE ba.bin = b.id)""")
70 projectB.query("BEGIN WORK")
73 projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s AND last_used IS NULL" % (now_date, file_id))
74 projectB.query("COMMIT WORK")
76 # Check for any binaries which are marked for eventual deletion
77 # but are now used again.
78 q = projectB.query("""
79 SELECT b.file FROM binaries b, files f
80 WHERE f.last_used IS NOT NULL AND f.id = b.file
81 AND EXISTS (SELECT 1 FROM bin_associations ba WHERE ba.bin = b.id)""")
84 projectB.query("BEGIN WORK")
87 projectB.query("UPDATE files SET last_used = NULL WHERE id = %s" % (file_id))
88 projectB.query("COMMIT WORK")
90 ########################################
93 global delete_date, now_date
95 print "Checking for orphaned source packages..."
97 # Get the list of source packages not in a suite and not used by
99 q = projectB.query("""
100 SELECT s.id, s.file FROM source s, files f
101 WHERE f.last_used IS NULL AND s.file = f.id
102 AND NOT EXISTS (SELECT 1 FROM src_associations sa WHERE sa.source = s.id)
103 AND NOT EXISTS (SELECT 1 FROM binaries b WHERE b.source = s.id)""")
105 #### XXX: this should ignore cases where the files for the binary b
106 #### have been marked for deletion (so the delay between bins go
107 #### byebye and sources go byebye is 0 instead of StayOfExecution)
111 projectB.query("BEGIN WORK")
116 # Mark the .dsc file for deletion
117 projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s AND last_used IS NULL" % (now_date, dsc_file_id))
118 # Mark all other files references by .dsc too if they're not used by anyone else
119 x = projectB.query("SELECT f.id FROM files f, dsc_files d WHERE d.source = %s AND d.file = f.id" % (source_id))
120 for j in x.getresult():
122 y = projectB.query("SELECT id FROM dsc_files d WHERE d.file = %s" % (file_id))
123 if len(y.getresult()) == 1:
124 projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s AND last_used IS NULL" % (now_date, file_id))
125 projectB.query("COMMIT WORK")
127 # Check for any sources which are marked for deletion but which
128 # are now used again.
130 q = projectB.query("""
131 SELECT f.id FROM source s, files f, dsc_files df
132 WHERE f.last_used IS NOT NULL AND s.id = df.source AND df.file = f.id
133 AND ((EXISTS (SELECT 1 FROM src_associations sa WHERE sa.source = s.id))
134 OR (EXISTS (SELECT 1 FROM binaries b WHERE b.source = s.id)))""")
136 #### XXX: this should also handle deleted binaries specially (ie, not
137 #### reinstate sources because of them
140 # Could be done in SQL; but left this way for hysterical raisins
141 # [and freedom to innovate don'cha know?]
142 projectB.query("BEGIN WORK")
145 projectB.query("UPDATE files SET last_used = NULL WHERE id = %s" % (file_id))
146 projectB.query("COMMIT WORK")
148 ########################################
151 global delete_date, now_date
153 # FIXME: this is evil; nothing should ever be in this state. if
154 # they are, it's a bug and the files should not be auto-deleted.
158 print "Checking for unused files..."
159 q = projectB.query("""
160 SELECT id FROM files f
161 WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.file = f.id)
162 AND NOT EXISTS (SELECT 1 FROM dsc_files df WHERE df.file = f.id)""")
164 projectB.query("BEGIN WORK")
165 for i in q.getresult():
167 projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s" % (now_date, file_id))
168 projectB.query("COMMIT WORK")
170 def clean_binaries():
171 global delete_date, now_date
173 # We do this here so that the binaries we remove will have their
174 # source also removed (if possible).
176 # XXX: why doesn't this remove the files here as well? I don't think it
177 # buys anything keeping this separate
178 print "Cleaning binaries from the DB..."
179 if not Options["No-Action"]:
181 sys.stdout.write("[Deleting from binaries table... ")
182 projectB.query("DELETE FROM binaries WHERE EXISTS (SELECT 1 FROM files WHERE binaries.file = files.id AND files.last_used <= '%s')" % (delete_date))
183 sys.stdout.write("done. (%d seconds)]\n" % (int(time.time()-before)))
185 ########################################
188 global delete_date, now_date, max_delete
192 print "Cleaning out packages..."
194 date = time.strftime("%Y-%m-%d")
195 dest = Cnf["Dir::Morgue"] + '/' + Cnf["Clean-Suites::MorgueSubDir"] + '/' + date
196 if not os.path.exists(dest):
200 if not Options["No-Action"]:
202 sys.stdout.write("[Deleting from source table... ")
203 projectB.query("DELETE FROM dsc_files WHERE EXISTS (SELECT 1 FROM source s, files f, dsc_files df WHERE f.last_used <= '%s' AND s.file = f.id AND s.id = df.source AND df.id = dsc_files.id)" % (delete_date))
204 projectB.query("DELETE FROM source WHERE EXISTS (SELECT 1 FROM files WHERE source.file = files.id AND files.last_used <= '%s')" % (delete_date))
205 sys.stdout.write("done. (%d seconds)]\n" % (int(time.time()-before)))
207 # Delete files from the pool
208 query = "SELECT l.path, f.filename FROM location l, files f WHERE f.last_used <= '%s' AND l.id = f.location" % (delete_date)
209 if max_delete is not None:
210 query += " LIMIT %d" % max_delete
211 sys.stdout.write("Limiting removals to %d\n" % max_delete)
213 q=projectB.query(query)
214 for i in q.getresult():
215 filename = i[0] + i[1]
216 if not os.path.exists(filename):
217 utils.warn("can not find '%s'." % (filename))
219 if os.path.isfile(filename):
220 if os.path.islink(filename):
222 if Options["No-Action"]:
223 print "Removing symlink %s..." % (filename)
227 size += os.stat(filename)[stat.ST_SIZE]
230 dest_filename = dest + '/' + os.path.basename(filename)
231 # If the destination file exists; try to find another filename to use
232 if os.path.exists(dest_filename):
233 dest_filename = utils.find_next_free(dest_filename)
235 if Options["No-Action"]:
236 print "Cleaning %s -> %s ..." % (filename, dest_filename)
238 utils.move(filename, dest_filename)
240 utils.fubar("%s is neither symlink nor file?!" % (filename))
242 # Delete from the 'files' table
243 if not Options["No-Action"]:
245 sys.stdout.write("[Deleting from files table... ")
246 projectB.query("DELETE FROM files WHERE last_used <= '%s'" % (delete_date))
247 sys.stdout.write("done. (%d seconds)]\n" % (int(time.time()-before)))
249 sys.stderr.write("Cleaned %d files, %s.\n" % (count, utils.size_type(size)))
251 ################################################################################
253 def clean_maintainers():
254 print "Cleaning out unused Maintainer entries..."
256 q = projectB.query("""
257 SELECT m.id FROM maintainer m
258 WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.maintainer = m.id)
259 AND NOT EXISTS (SELECT 1 FROM source s WHERE s.maintainer = m.id OR s.changedby = m.id)
260 AND NOT EXISTS (SELECT 1 FROM src_uploaders u WHERE u.maintainer = m.id)""")
264 projectB.query("BEGIN WORK")
267 if not Options["No-Action"]:
268 projectB.query("DELETE FROM maintainer WHERE id = %s" % (maintainer_id))
270 projectB.query("COMMIT WORK")
273 sys.stderr.write("Cleared out %d maintainer entries.\n" % (count))
275 ################################################################################
277 def clean_fingerprints():
278 print "Cleaning out unused fingerprint entries..."
280 q = projectB.query("""
281 SELECT f.id FROM fingerprint f
282 WHERE f.keyring IS NULL
283 AND NOT EXISTS (SELECT 1 FROM binaries b WHERE b.sig_fpr = f.id)
284 AND NOT EXISTS (SELECT 1 FROM source s WHERE s.sig_fpr = f.id)""")
288 projectB.query("BEGIN WORK")
290 fingerprint_id = i[0]
291 if not Options["No-Action"]:
292 projectB.query("DELETE FROM fingerprint WHERE id = %s" % (fingerprint_id))
294 projectB.query("COMMIT WORK")
297 sys.stderr.write("Cleared out %d fingerprint entries.\n" % (count))
299 ################################################################################
301 def clean_queue_build():
304 if not Cnf.ValueList("Dinstall::QueueBuildSuites") or Options["No-Action"]:
307 print "Cleaning out queue build symlinks..."
309 our_delete_date = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()-int(Cnf["Clean-Suites::QueueBuildStayOfExecution"])))
312 q = projectB.query("SELECT filename FROM queue_build WHERE last_used <= '%s'" % (our_delete_date))
313 for i in q.getresult():
315 if not os.path.exists(filename):
316 utils.warn("%s (from queue_build) doesn't exist." % (filename))
318 if not Cnf.FindB("Dinstall::SecurityQueueBuild") and not os.path.islink(filename):
319 utils.fubar("%s (from queue_build) should be a symlink but isn't." % (filename))
322 projectB.query("DELETE FROM queue_build WHERE last_used <= '%s'" % (our_delete_date))
325 sys.stderr.write("Cleaned %d queue_build files.\n" % (count))
327 ################################################################################
330 global Cnf, Options, projectB, delete_date, now_date, max_delete
332 Cnf = utils.get_conf()
333 for i in ["Help", "No-Action", "Maximum" ]:
334 if not Cnf.has_key("Clean-Suites::Options::%s" % (i)):
335 Cnf["Clean-Suites::Options::%s" % (i)] = ""
337 Arguments = [('h',"help","Clean-Suites::Options::Help"),
338 ('n',"no-action","Clean-Suites::Options::No-Action"),
339 ('m',"maximum","Clean-Suites::Options::Maximum", "HasArg")]
341 apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
342 Options = Cnf.SubTree("Clean-Suites::Options")
344 if Cnf["Clean-Suites::Options::Maximum"] != "":
346 # Only use Maximum if it's an integer
347 max_delete = int(Cnf["Clean-Suites::Options::Maximum"])
349 utils.fubar("If given, Maximum must be at least 1")
350 except ValueError, e:
351 utils.fubar("If given, Maximum must be an integer")
358 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
360 now_date = time.strftime("%Y-%m-%d %H:%M")
361 delete_date = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()-int(Cnf["Clean-Suites::StayOfExecution"])))
372 ################################################################################
374 if __name__ == '__main__':