]> git.decadent.org.uk Git - dak.git/blob - dak/clean_suites.py
Merge commit 'godog/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 src_uploaders WHERE EXISTS (SELECT 1 FROM source s, files f WHERE f.last_used <= '%s' AND s.file = f.id AND s.id = src_uploaders.source)" % (delete_date))
205         projectB.query("DELETE FROM source WHERE EXISTS (SELECT 1 FROM files WHERE source.file = files.id AND files.last_used <= '%s')" % (delete_date))
206         sys.stdout.write("done. (%d seconds)]\n" % (int(time.time()-before)))
207
208     # Delete files from the pool
209     query = "SELECT l.path, f.filename FROM location l, files f WHERE f.last_used <= '%s' AND l.id = f.location" % (delete_date)
210     if max_delete is not None:
211         query += " LIMIT %d" % max_delete
212         sys.stdout.write("Limiting removals to %d\n" % max_delete)
213
214     q=projectB.query(query)
215     for i in q.getresult():
216         filename = i[0] + i[1]
217         if not os.path.exists(filename):
218             utils.warn("can not find '%s'." % (filename))
219             continue
220         if os.path.isfile(filename):
221             if os.path.islink(filename):
222                 count += 1
223                 if Options["No-Action"]:
224                     print "Removing symlink %s..." % (filename)
225                 else:
226                     os.unlink(filename)
227             else:
228                 size += os.stat(filename)[stat.ST_SIZE]
229                 count += 1
230
231                 dest_filename = dest + '/' + os.path.basename(filename)
232                 # If the destination file exists; try to find another filename to use
233                 if os.path.exists(dest_filename):
234                     dest_filename = utils.find_next_free(dest_filename)
235
236                 if Options["No-Action"]:
237                     print "Cleaning %s -> %s ..." % (filename, dest_filename)
238                 else:
239                     utils.move(filename, dest_filename)
240         else:
241             utils.fubar("%s is neither symlink nor file?!" % (filename))
242
243     # Delete from the 'files' table
244     if not Options["No-Action"]:
245         before = time.time()
246         sys.stdout.write("[Deleting from files table... ")
247         projectB.query("DELETE FROM files WHERE last_used <= '%s'" % (delete_date))
248         sys.stdout.write("done. (%d seconds)]\n" % (int(time.time()-before)))
249     if count > 0:
250         sys.stderr.write("Cleaned %d files, %s.\n" % (count, utils.size_type(size)))
251
252 ################################################################################
253
254 def clean_maintainers():
255     print "Cleaning out unused Maintainer entries..."
256
257     q = projectB.query("""
258 SELECT m.id FROM maintainer m
259   WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.maintainer = m.id)
260     AND NOT EXISTS (SELECT 1 FROM source s WHERE s.maintainer = m.id OR s.changedby = m.id)
261     AND NOT EXISTS (SELECT 1 FROM src_uploaders u WHERE u.maintainer = m.id)""")
262     ql = q.getresult()
263
264     count = 0
265     projectB.query("BEGIN WORK")
266     for i in ql:
267         maintainer_id = i[0]
268         if not Options["No-Action"]:
269             projectB.query("DELETE FROM maintainer WHERE id = %s" % (maintainer_id))
270             count += 1
271     projectB.query("COMMIT WORK")
272
273     if count > 0:
274         sys.stderr.write("Cleared out %d maintainer entries.\n" % (count))
275
276 ################################################################################
277
278 def clean_fingerprints():
279     print "Cleaning out unused fingerprint entries..."
280
281     q = projectB.query("""
282 SELECT f.id FROM fingerprint f
283   WHERE f.keyring IS NULL
284     AND NOT EXISTS (SELECT 1 FROM binaries b WHERE b.sig_fpr = f.id)
285     AND NOT EXISTS (SELECT 1 FROM source s WHERE s.sig_fpr = f.id)""")
286     ql = q.getresult()
287
288     count = 0
289     projectB.query("BEGIN WORK")
290     for i in ql:
291         fingerprint_id = i[0]
292         if not Options["No-Action"]:
293             projectB.query("DELETE FROM fingerprint WHERE id = %s" % (fingerprint_id))
294             count += 1
295     projectB.query("COMMIT WORK")
296
297     if count > 0:
298         sys.stderr.write("Cleared out %d fingerprint entries.\n" % (count))
299
300 ################################################################################
301
302 def clean_queue_build():
303     global now_date
304
305     if not Cnf.ValueList("Dinstall::QueueBuildSuites") or Options["No-Action"]:
306         return
307
308     print "Cleaning out queue build symlinks..."
309
310     our_delete_date = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()-int(Cnf["Clean-Suites::QueueBuildStayOfExecution"])))
311     count = 0
312
313     q = projectB.query("SELECT filename FROM queue_build WHERE last_used <= '%s'" % (our_delete_date))
314     for i in q.getresult():
315         filename = i[0]
316         if not os.path.exists(filename):
317             utils.warn("%s (from queue_build) doesn't exist." % (filename))
318             continue
319         if not Cnf.FindB("Dinstall::SecurityQueueBuild") and not os.path.islink(filename):
320             utils.fubar("%s (from queue_build) should be a symlink but isn't." % (filename))
321         os.unlink(filename)
322         count += 1
323     projectB.query("DELETE FROM queue_build WHERE last_used <= '%s'" % (our_delete_date))
324
325     if count:
326         sys.stderr.write("Cleaned %d queue_build files.\n" % (count))
327
328 ################################################################################
329
330 def main():
331     global Cnf, Options, projectB, delete_date, now_date, max_delete
332
333     Cnf = utils.get_conf()
334     for i in ["Help", "No-Action", "Maximum" ]:
335         if not Cnf.has_key("Clean-Suites::Options::%s" % (i)):
336             Cnf["Clean-Suites::Options::%s" % (i)] = ""
337
338     Arguments = [('h',"help","Clean-Suites::Options::Help"),
339                  ('n',"no-action","Clean-Suites::Options::No-Action"),
340                  ('m',"maximum","Clean-Suites::Options::Maximum", "HasArg")]
341
342     apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
343     Options = Cnf.SubTree("Clean-Suites::Options")
344
345     if Cnf["Clean-Suites::Options::Maximum"] != "":
346         try:
347             # Only use Maximum if it's an integer
348             max_delete = int(Cnf["Clean-Suites::Options::Maximum"])
349             if max_delete < 1:
350                 utils.fubar("If given, Maximum must be at least 1")
351         except ValueError, e:
352             utils.fubar("If given, Maximum must be an integer")
353     else:
354         max_delete = None
355
356     if Options["Help"]:
357         usage()
358
359     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
360
361     now_date = time.strftime("%Y-%m-%d %H:%M")
362     delete_date = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()-int(Cnf["Clean-Suites::StayOfExecution"])))
363
364     check_binaries()
365     clean_binaries()
366     check_sources()
367     check_files()
368     clean()
369     clean_maintainers()
370     clean_fingerprints()
371     clean_queue_build()
372
373 ################################################################################
374
375 if __name__ == '__main__':
376     main()