]> git.decadent.org.uk Git - dak.git/blob - dak/clean_suites.py
Merge commit 'mhy/master' into merge
[dak.git] / dak / clean_suites.py
1 #!/usr/bin/env python
2
3 """ Cleans up unassociated binary and source packages """
4 # Copyright (C) 2000, 2001, 2002, 2003, 2006  James Troup <james@nocrew.org>
5
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.
10
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.
15
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
19
20 ################################################################################
21
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
25 #      |       that road?
26 #
27 # 07:05|<Culus> elmo: Augh! <brain jumps out of skull>
28
29 ################################################################################
30
31 import os, pg, stat, sys, time
32 import apt_pkg
33 from daklib import utils
34
35 ################################################################################
36
37 projectB = None
38 Cnf = None
39 Options = None
40 now_date = None;     # mark newly "deleted" things as deleted "now"
41 delete_date = None;  # delete things marked "deleted" earler than this
42 max_delete = None
43
44 ################################################################################
45
46 def usage (exit_code=0):
47     print """Usage: dak clean-suites [OPTIONS]
48 Clean old packages from suites.
49
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"""
53     sys.exit(exit_code)
54
55 ################################################################################
56
57 def check_binaries():
58     global delete_date, now_date
59
60     print "Checking for orphaned binary packages..."
61
62     # Get the list of binary packages not in a suite and mark them for
63     # deletion.
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)""")
68     ql = q.getresult()
69
70     projectB.query("BEGIN WORK")
71     for i in ql:
72         file_id = i[0]
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")
75
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)""")
82     ql = q.getresult()
83
84     projectB.query("BEGIN WORK")
85     for i in ql:
86         file_id = i[0]
87         projectB.query("UPDATE files SET last_used = NULL WHERE id = %s" % (file_id))
88     projectB.query("COMMIT WORK")
89
90 ########################################
91
92 def check_sources():
93     global delete_date, now_date
94
95     print "Checking for orphaned source packages..."
96
97     # Get the list of source packages not in a suite and not used by
98     # any binaries.
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)""")
104
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)
108
109     ql = q.getresult()
110
111     projectB.query("BEGIN WORK")
112     for i in ql:
113         source_id = i[0]
114         dsc_file_id = i[1]
115
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():
121             file_id = j[0]
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")
126
127     # Check for any sources which are marked for deletion but which
128     # are now used again.
129
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)))""")
135
136     #### XXX: this should also handle deleted binaries specially (ie, not
137     ####      reinstate sources because of them
138
139     ql = q.getresult()
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")
143     for i in ql:
144         file_id = i[0]
145         projectB.query("UPDATE files SET last_used = NULL WHERE id = %s" % (file_id))
146     projectB.query("COMMIT WORK")
147
148 ########################################
149
150 def check_files():
151     global delete_date, now_date
152
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.
155
156     return
157
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)""")
163
164     projectB.query("BEGIN WORK")
165     for i in q.getresult():
166         file_id = i[0]
167         projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s" % (now_date, file_id))
168     projectB.query("COMMIT WORK")
169
170 def clean_binaries():
171     global delete_date, now_date
172
173     # We do this here so that the binaries we remove will have their
174     # source also removed (if possible).
175
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"]:
180         before = time.time()
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)))
184
185 ########################################
186
187 def clean():
188     global delete_date, now_date, max_delete
189     count = 0
190     size = 0
191
192     print "Cleaning out packages..."
193
194     date = time.strftime("%Y-%m-%d")
195     dest = Cnf["Dir::Morgue"] + '/' + Cnf["Clean-Suites::MorgueSubDir"] + '/' + date
196     if not os.path.exists(dest):
197         os.mkdir(dest)
198
199     # Delete from source
200     if not Options["No-Action"]:
201         before = time.time()
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)))
206
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)
212
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))
218             continue
219         if os.path.isfile(filename):
220             if os.path.islink(filename):
221                 count += 1
222                 if Options["No-Action"]:
223                     print "Removing symlink %s..." % (filename)
224                 else:
225                     os.unlink(filename)
226             else:
227                 size += os.stat(filename)[stat.ST_SIZE]
228                 count += 1
229
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)
234
235                 if Options["No-Action"]:
236                     print "Cleaning %s -> %s ..." % (filename, dest_filename)
237                 else:
238                     utils.move(filename, dest_filename)
239         else:
240             utils.fubar("%s is neither symlink nor file?!" % (filename))
241
242     # Delete from the 'files' table
243     if not Options["No-Action"]:
244         before = time.time()
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)))
248     if count > 0:
249         sys.stderr.write("Cleaned %d files, %s.\n" % (count, utils.size_type(size)))
250
251 ################################################################################
252
253 def clean_maintainers():
254     print "Cleaning out unused Maintainer entries..."
255
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)""")
261     ql = q.getresult()
262
263     count = 0
264     projectB.query("BEGIN WORK")
265     for i in ql:
266         maintainer_id = i[0]
267         if not Options["No-Action"]:
268             projectB.query("DELETE FROM maintainer WHERE id = %s" % (maintainer_id))
269             count += 1
270     projectB.query("COMMIT WORK")
271
272     if count > 0:
273         sys.stderr.write("Cleared out %d maintainer entries.\n" % (count))
274
275 ################################################################################
276
277 def clean_fingerprints():
278     print "Cleaning out unused fingerprint entries..."
279
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)""")
285     ql = q.getresult()
286
287     count = 0
288     projectB.query("BEGIN WORK")
289     for i in ql:
290         fingerprint_id = i[0]
291         if not Options["No-Action"]:
292             projectB.query("DELETE FROM fingerprint WHERE id = %s" % (fingerprint_id))
293             count += 1
294     projectB.query("COMMIT WORK")
295
296     if count > 0:
297         sys.stderr.write("Cleared out %d fingerprint entries.\n" % (count))
298
299 ################################################################################
300
301 def clean_queue_build():
302     global now_date
303
304     if not Cnf.ValueList("Dinstall::QueueBuildSuites") or Options["No-Action"]:
305         return
306
307     print "Cleaning out queue build symlinks..."
308
309     our_delete_date = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()-int(Cnf["Clean-Suites::QueueBuildStayOfExecution"])))
310     count = 0
311
312     q = projectB.query("SELECT filename FROM queue_build WHERE last_used <= '%s'" % (our_delete_date))
313     for i in q.getresult():
314         filename = i[0]
315         if not os.path.exists(filename):
316             utils.warn("%s (from queue_build) doesn't exist." % (filename))
317             continue
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))
320         os.unlink(filename)
321         count += 1
322     projectB.query("DELETE FROM queue_build WHERE last_used <= '%s'" % (our_delete_date))
323
324     if count:
325         sys.stderr.write("Cleaned %d queue_build files.\n" % (count))
326
327 ################################################################################
328
329 def main():
330     global Cnf, Options, projectB, delete_date, now_date, max_delete
331
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)] = ""
336
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")]
340
341     apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
342     Options = Cnf.SubTree("Clean-Suites::Options")
343
344     if Cnf["Clean-Suites::Options::Maximum"] != "":
345         try:
346             # Only use Maximum if it's an integer
347             max_delete = int(Cnf["Clean-Suites::Options::Maximum"])
348             if max_delete < 1:
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")
352     else:
353         max_delete = None
354
355     if Options["Help"]:
356         usage()
357
358     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
359
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"])))
362
363     check_binaries()
364     clean_binaries()
365     check_sources()
366     check_files()
367     clean()
368     clean_maintainers()
369     clean_fingerprints()
370     clean_queue_build()
371
372 ################################################################################
373
374 if __name__ == '__main__':
375     main()