]> git.decadent.org.uk Git - dak.git/blob - dak/clean_suites.py
[??] sync with ftp-master/dak master
[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 import daklib.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
43 ################################################################################
44
45 def usage (exit_code=0):
46     print """Usage: dak clean-suites [OPTIONS]
47 Clean old packages from suites.
48
49   -n, --no-action            don't do anything
50   -h, --help                 show this help and exit"""
51     sys.exit(exit_code)
52
53 ################################################################################
54
55 def check_binaries():
56     global delete_date, now_date
57
58     print "Checking for orphaned binary packages..."
59
60     # Get the list of binary packages not in a suite and mark them for
61     # deletion.
62     q = projectB.query("""
63 SELECT b.file FROM binaries b, files f
64  WHERE f.last_used IS NULL AND b.file = f.id
65    AND NOT EXISTS (SELECT 1 FROM bin_associations ba WHERE ba.bin = b.id)""")
66     ql = q.getresult()
67
68     projectB.query("BEGIN WORK")
69     for i in ql:
70         file_id = i[0]
71         projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s AND last_used IS NULL" % (now_date, file_id))
72     projectB.query("COMMIT WORK")
73
74     # Check for any binaries which are marked for eventual deletion
75     # but are now used again.
76     q = projectB.query("""
77 SELECT b.file FROM binaries b, files f
78    WHERE f.last_used IS NOT NULL AND f.id = b.file
79     AND EXISTS (SELECT 1 FROM bin_associations ba WHERE ba.bin = b.id)""")
80     ql = q.getresult()
81
82     projectB.query("BEGIN WORK")
83     for i in ql:
84         file_id = i[0]
85         projectB.query("UPDATE files SET last_used = NULL WHERE id = %s" % (file_id))
86     projectB.query("COMMIT WORK")
87
88 ########################################
89
90 def check_sources():
91     global delete_date, now_date
92
93     print "Checking for orphaned source packages..."
94
95     # Get the list of source packages not in a suite and not used by
96     # any binaries.
97     q = projectB.query("""
98 SELECT s.id, s.file FROM source s, files f
99   WHERE f.last_used IS NULL AND s.file = f.id
100     AND NOT EXISTS (SELECT 1 FROM src_associations sa WHERE sa.source = s.id)
101     AND NOT EXISTS (SELECT 1 FROM binaries b WHERE b.source = s.id)""")
102
103     #### XXX: this should ignore cases where the files for the binary b
104     ####      have been marked for deletion (so the delay between bins go
105     ####      byebye and sources go byebye is 0 instead of StayOfExecution)
106
107     ql = q.getresult()
108
109     projectB.query("BEGIN WORK")
110     for i in ql:
111         source_id = i[0]
112         dsc_file_id = i[1]
113
114         # Mark the .dsc file for deletion
115         projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s AND last_used IS NULL" % (now_date, dsc_file_id))
116         # Mark all other files references by .dsc too if they're not used by anyone else
117         x = projectB.query("SELECT f.id FROM files f, dsc_files d WHERE d.source = %s AND d.file = f.id" % (source_id))
118         for j in x.getresult():
119             file_id = j[0]
120             y = projectB.query("SELECT id FROM dsc_files d WHERE d.file = %s" % (file_id))
121             if len(y.getresult()) == 1:
122                 projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s AND last_used IS NULL" % (now_date, file_id))
123     projectB.query("COMMIT WORK")
124
125     # Check for any sources which are marked for deletion but which
126     # are now used again.
127
128     q = projectB.query("""
129 SELECT f.id FROM source s, files f, dsc_files df
130   WHERE f.last_used IS NOT NULL AND s.id = df.source AND df.file = f.id
131     AND ((EXISTS (SELECT 1 FROM src_associations sa WHERE sa.source = s.id))
132       OR (EXISTS (SELECT 1 FROM binaries b WHERE b.source = s.id)))""")
133
134     #### XXX: this should also handle deleted binaries specially (ie, not
135     ####      reinstate sources because of them
136
137     ql = q.getresult()
138     # Could be done in SQL; but left this way for hysterical raisins
139     # [and freedom to innovate don'cha know?]
140     projectB.query("BEGIN WORK")
141     for i in ql:
142         file_id = i[0]
143         projectB.query("UPDATE files SET last_used = NULL WHERE id = %s" % (file_id))
144     projectB.query("COMMIT WORK")
145
146 ########################################
147
148 def check_files():
149     global delete_date, now_date
150
151     # FIXME: this is evil; nothing should ever be in this state.  if
152     # they are, it's a bug and the files should not be auto-deleted.
153
154     return
155
156     print "Checking for unused files..."
157     q = projectB.query("""
158 SELECT id FROM files f
159   WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.file = f.id)
160     AND NOT EXISTS (SELECT 1 FROM dsc_files df WHERE df.file = f.id)""")
161
162     projectB.query("BEGIN WORK")
163     for i in q.getresult():
164         file_id = i[0]
165         projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s" % (now_date, file_id))
166     projectB.query("COMMIT WORK")
167
168 def clean_binaries():
169     global delete_date, now_date
170
171     # We do this here so that the binaries we remove will have their
172     # source also removed (if possible).
173
174     # XXX: why doesn't this remove the files here as well? I don't think it
175     #      buys anything keeping this separate
176     print "Cleaning binaries from the DB..."
177     if not Options["No-Action"]:
178         before = time.time()
179         sys.stdout.write("[Deleting from binaries table... ")
180         projectB.query("DELETE FROM binaries WHERE EXISTS (SELECT 1 FROM files WHERE binaries.file = files.id AND files.last_used <= '%s')" % (delete_date))
181         sys.stdout.write("done. (%d seconds)]\n" % (int(time.time()-before)))
182
183 ########################################
184
185 def clean():
186     global delete_date, now_date
187     count = 0
188     size = 0
189
190     print "Cleaning out packages..."
191
192     date = time.strftime("%Y-%m-%d")
193     dest = Cnf["Dir::Morgue"] + '/' + Cnf["Clean-Suites::MorgueSubDir"] + '/' + date
194     if not os.path.exists(dest):
195         os.mkdir(dest)
196
197     # Delete from source
198     if not Options["No-Action"]:
199         before = time.time()
200         sys.stdout.write("[Deleting from source table... ")
201         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))
202         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))
203         projectB.query("DELETE FROM source WHERE EXISTS (SELECT 1 FROM files WHERE source.file = files.id AND files.last_used <= '%s')" % (delete_date))
204         sys.stdout.write("done. (%d seconds)]\n" % (int(time.time()-before)))
205
206     # Delete files from the pool
207     q = projectB.query("SELECT l.path, f.filename FROM location l, files f WHERE f.last_used <= '%s' AND l.id = f.location" % (delete_date))
208     for i in q.getresult():
209         filename = i[0] + i[1]
210         if not os.path.exists(filename):
211             daklib.utils.warn("can not find '%s'." % (filename))
212             continue
213         if os.path.isfile(filename):
214             if os.path.islink(filename):
215                 count += 1
216                 if Options["No-Action"]:
217                     print "Removing symlink %s..." % (filename)
218                 else:
219                     os.unlink(filename)
220             else:
221                 size += os.stat(filename)[stat.ST_SIZE]
222                 count += 1
223
224                 dest_filename = dest + '/' + os.path.basename(filename)
225                 # If the destination file exists; try to find another filename to use
226                 if os.path.exists(dest_filename):
227                     dest_filename = daklib.utils.find_next_free(dest_filename)
228
229                 if Options["No-Action"]:
230                     print "Cleaning %s -> %s ..." % (filename, dest_filename)
231                 else:
232                     daklib.utils.move(filename, dest_filename)
233         else:
234             daklib.utils.fubar("%s is neither symlink nor file?!" % (filename))
235
236     # Delete from the 'files' table
237     if not Options["No-Action"]:
238         before = time.time()
239         sys.stdout.write("[Deleting from files table... ")
240         projectB.query("DELETE FROM files WHERE last_used <= '%s'" % (delete_date))
241         sys.stdout.write("done. (%d seconds)]\n" % (int(time.time()-before)))
242     if count > 0:
243         sys.stderr.write("Cleaned %d files, %s.\n" % (count, daklib.utils.size_type(size)))
244
245 ################################################################################
246
247 def clean_maintainers():
248     print "Cleaning out unused Maintainer entries..."
249
250     q = projectB.query("""
251 SELECT m.id FROM maintainer m
252   WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.maintainer = m.id)
253     AND NOT EXISTS (SELECT 1 FROM source s WHERE s.maintainer = m.id)
254     AND NOT EXISTS (SELECT 1 FROM src_uploaders u WHERE u.maintainer = m.id)""")
255     ql = q.getresult()
256
257     count = 0
258     projectB.query("BEGIN WORK")
259     for i in ql:
260         maintainer_id = i[0]
261         if not Options["No-Action"]:
262             projectB.query("DELETE FROM maintainer WHERE id = %s" % (maintainer_id))
263             count += 1
264     projectB.query("COMMIT WORK")
265
266     if count > 0:
267         sys.stderr.write("Cleared out %d maintainer entries.\n" % (count))
268
269 ################################################################################
270
271 def clean_fingerprints():
272     print "Cleaning out unused fingerprint entries..."
273
274     q = projectB.query("""
275 SELECT f.id FROM fingerprint f
276   WHERE f.keyring IS NULL
277     AND NOT EXISTS (SELECT 1 FROM binaries b WHERE b.sig_fpr = f.id)
278     AND NOT EXISTS (SELECT 1 FROM source s WHERE s.sig_fpr = f.id)""")
279     ql = q.getresult()
280
281     count = 0
282     projectB.query("BEGIN WORK")
283     for i in ql:
284         fingerprint_id = i[0]
285         if not Options["No-Action"]:
286             projectB.query("DELETE FROM fingerprint WHERE id = %s" % (fingerprint_id))
287             count += 1
288     projectB.query("COMMIT WORK")
289
290     if count > 0:
291         sys.stderr.write("Cleared out %d fingerprint entries.\n" % (count))
292
293 ################################################################################
294
295 def clean_queue_build():
296     global now_date
297
298     if not Cnf.ValueList("Dinstall::QueueBuildSuites") or Options["No-Action"]:
299         return
300
301     print "Cleaning out queue build symlinks..."
302
303     our_delete_date = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()-int(Cnf["Clean-Suites::QueueBuildStayOfExecution"])))
304     count = 0
305
306     q = projectB.query("SELECT filename FROM queue_build WHERE last_used <= '%s'" % (our_delete_date))
307     for i in q.getresult():
308         filename = i[0]
309         if not os.path.exists(filename):
310             daklib.utils.warn("%s (from queue_build) doesn't exist." % (filename))
311             continue
312         if not Cnf.FindB("Dinstall::SecurityQueueBuild") and not os.path.islink(filename):
313             daklib.utils.fubar("%s (from queue_build) should be a symlink but isn't." % (filename))
314         os.unlink(filename)
315         count += 1
316     projectB.query("DELETE FROM queue_build WHERE last_used <= '%s'" % (our_delete_date))
317
318     if count:
319         sys.stderr.write("Cleaned %d queue_build files.\n" % (count))
320
321 ################################################################################
322
323 def main():
324     global Cnf, Options, projectB, delete_date, now_date
325
326     Cnf = daklib.utils.get_conf()
327     for i in ["Help", "No-Action" ]:
328         if not Cnf.has_key("Clean-Suites::Options::%s" % (i)):
329             Cnf["Clean-Suites::Options::%s" % (i)] = ""
330
331     Arguments = [('h',"help","Clean-Suites::Options::Help"),
332                  ('n',"no-action","Clean-Suites::Options::No-Action")]
333
334     apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
335     Options = Cnf.SubTree("Clean-Suites::Options")
336
337     if Options["Help"]:
338         usage()
339
340     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
341
342     now_date = time.strftime("%Y-%m-%d %H:%M")
343     delete_date = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()-int(Cnf["Clean-Suites::StayOfExecution"])))
344
345     check_binaries()
346     clean_binaries()
347     check_sources()
348     check_files()
349     clean()
350     clean_maintainers()
351     clean_fingerprints()
352     clean_queue_build()
353
354 ################################################################################
355
356 if __name__ == '__main__':
357     main()
358