]> git.decadent.org.uk Git - dak.git/blob - dak/clean_suites.py
Stop using silly names, and migrate to a saner directory structure.
[dak.git] / dak / clean_suites.py
1 #!/usr/bin/env python
2
3 # rhona, cleans up unassociated binary and source packages
4 # Copyright (C) 2000, 2001, 2002, 2003  James Troup <james@nocrew.org>
5 # $Id: rhona,v 1.29 2005-11-25 06:59:45 ajt Exp $
6
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
21 ################################################################################
22
23 # 07:05|<elmo> well.. *shrug*.. no, probably not.. but to fix it,
24 #      |       we're going to have to implement reference counting
25 #      |       through dependencies.. do we really want to go down
26 #      |       that road?
27 #
28 # 07:05|<Culus> elmo: Augh! <brain jumps out of skull>
29
30 ################################################################################
31
32 import os, pg, stat, sys, time
33 import apt_pkg
34 import utils
35
36 ################################################################################
37
38 projectB = None;
39 Cnf = None;
40 Options = None;
41 now_date = None;     # mark newly "deleted" things as deleted "now"
42 delete_date = None;  # delete things marked "deleted" earler than this
43
44 ################################################################################
45
46 def usage (exit_code=0):
47     print """Usage: rhona [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     sys.exit(exit_code)
53
54 ################################################################################
55
56 def check_binaries():
57     global delete_date, now_date;
58
59     print "Checking for orphaned binary packages..."
60
61     # Get the list of binary packages not in a suite and mark them for
62     # deletion.
63     q = projectB.query("""
64 SELECT b.file FROM binaries b, files f
65  WHERE f.last_used IS NULL AND b.file = f.id
66    AND NOT EXISTS (SELECT 1 FROM bin_associations ba WHERE ba.bin = b.id)""");
67     ql = q.getresult();
68
69     projectB.query("BEGIN WORK");
70     for i in ql:
71         file_id = i[0];
72         projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s AND last_used IS NULL" % (now_date, file_id))
73     projectB.query("COMMIT WORK");
74
75     # Check for any binaries which are marked for eventual deletion
76     # but are now used again.
77     q = projectB.query("""
78 SELECT b.file FROM binaries b, files f
79    WHERE f.last_used IS NOT NULL AND f.id = b.file
80     AND EXISTS (SELECT 1 FROM bin_associations ba WHERE ba.bin = b.id)""");
81     ql = q.getresult();
82
83     projectB.query("BEGIN WORK");
84     for i in ql:
85         file_id = i[0];
86         projectB.query("UPDATE files SET last_used = NULL WHERE id = %s" % (file_id));
87     projectB.query("COMMIT WORK");
88
89 ########################################
90
91 def check_sources():
92     global delete_date, now_date;
93
94     print "Checking for orphaned source packages..."
95
96     # Get the list of source packages not in a suite and not used by
97     # any binaries.
98     q = projectB.query("""
99 SELECT s.id, s.file FROM source s, files f
100   WHERE f.last_used IS NULL AND s.file = f.id
101     AND NOT EXISTS (SELECT 1 FROM src_associations sa WHERE sa.source = s.id)
102     AND NOT EXISTS (SELECT 1 FROM binaries b WHERE b.source = s.id)""");
103
104     #### XXX: this should ignore cases where the files for the binary b
105     ####      have been marked for deletion (so the delay between bins go
106     ####      byebye and sources go byebye is 0 instead of StayOfExecution)
107
108     ql = q.getresult();
109
110     projectB.query("BEGIN WORK");
111     for i in ql:
112         source_id = i[0];
113         dsc_file_id = i[1];
114
115         # Mark the .dsc file for deletion
116         projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s AND last_used IS NULL" % (now_date, dsc_file_id))
117         # Mark all other files references by .dsc too if they're not used by anyone else
118         x = projectB.query("SELECT f.id FROM files f, dsc_files d WHERE d.source = %s AND d.file = f.id" % (source_id));
119         for j in x.getresult():
120             file_id = j[0];
121             y = projectB.query("SELECT id FROM dsc_files d WHERE d.file = %s" % (file_id));
122             if len(y.getresult()) == 1:
123                 projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s AND last_used IS NULL" % (now_date, file_id));
124     projectB.query("COMMIT WORK");
125
126     # Check for any sources which are marked for deletion but which
127     # are now used again.
128
129     q = projectB.query("""
130 SELECT f.id FROM source s, files f, dsc_files df
131   WHERE f.last_used IS NOT NULL AND s.id = df.source AND df.file = f.id
132     AND ((EXISTS (SELECT 1 FROM src_associations sa WHERE sa.source = s.id))
133       OR (EXISTS (SELECT 1 FROM binaries b WHERE b.source = s.id)))""");
134
135     #### XXX: this should also handle deleted binaries specially (ie, not
136     ####      reinstate sources because of them
137
138     ql = q.getresult();
139     # Could be done in SQL; but left this way for hysterical raisins
140     # [and freedom to innovate don'cha know?]
141     projectB.query("BEGIN WORK");
142     for i in ql:
143         file_id = i[0];
144         projectB.query("UPDATE files SET last_used = NULL WHERE id = %s" % (file_id));
145     projectB.query("COMMIT WORK");
146
147 ########################################
148
149 def check_files():
150     global delete_date, now_date;
151
152     # FIXME: this is evil; nothing should ever be in this state.  if
153     # they are, it's a bug and the files should not be auto-deleted.
154
155     return;
156
157     print "Checking for unused files..."
158     q = projectB.query("""
159 SELECT id FROM files f
160   WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.file = f.id)
161     AND NOT EXISTS (SELECT 1 FROM dsc_files df WHERE df.file = f.id)""");
162
163     projectB.query("BEGIN WORK");
164     for i in q.getresult():
165         file_id = i[0];
166         projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s" % (now_date, file_id));
167     projectB.query("COMMIT WORK");
168
169 def clean_binaries():
170     global delete_date, now_date;
171
172     # We do this here so that the binaries we remove will have their
173     # source also removed (if possible).
174
175     # XXX: why doesn't this remove the files here as well? I don't think it
176     #      buys anything keeping this separate
177     print "Cleaning binaries from the DB..."
178     if not Options["No-Action"]:
179         before = time.time();
180         sys.stdout.write("[Deleting from binaries table... ");
181         sys.stderr.write("DELETE FROM binaries WHERE EXISTS (SELECT 1 FROM files WHERE binaries.file = files.id AND files.last_used <= '%s')\n" % (delete_date));
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;
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["Rhona::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     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));
209     for i in q.getresult():
210         filename = i[0] + i[1];
211         if not os.path.exists(filename):
212             utils.warn("can not find '%s'." % (filename));
213             continue;
214         if os.path.isfile(filename):
215             if os.path.islink(filename):
216                 count += 1;
217                 if Options["No-Action"]:
218                     print "Removing symlink %s..." % (filename);
219                 else:
220                     os.unlink(filename);
221             else:
222                 size += os.stat(filename)[stat.ST_SIZE];
223                 count += 1;
224
225                 dest_filename = dest + '/' + os.path.basename(filename);
226                 # If the destination file exists; try to find another filename to use
227                 if os.path.exists(dest_filename):
228                     dest_filename = utils.find_next_free(dest_filename);
229
230                 if Options["No-Action"]:
231                     print "Cleaning %s -> %s ..." % (filename, dest_filename);
232                 else:
233                     utils.move(filename, dest_filename);
234         else:
235             utils.fubar("%s is neither symlink nor file?!" % (filename));
236
237     # Delete from the 'files' table
238     if not Options["No-Action"]:
239         before = time.time();
240         sys.stdout.write("[Deleting from files table... ");
241         projectB.query("DELETE FROM files WHERE last_used <= '%s'" % (delete_date));
242         sys.stdout.write("done. (%d seconds)]\n" % (int(time.time()-before)));
243     if count > 0:
244         sys.stderr.write("Cleaned %d files, %s.\n" % (count, utils.size_type(size)));
245
246 ################################################################################
247
248 def clean_maintainers():
249     print "Cleaning out unused Maintainer entries..."
250
251     q = projectB.query("""
252 SELECT m.id FROM maintainer m
253   WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.maintainer = m.id)
254     AND NOT EXISTS (SELECT 1 FROM source s WHERE s.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 NOT EXISTS (SELECT 1 FROM binaries b WHERE b.sig_fpr = f.id)
277     AND NOT EXISTS (SELECT 1 FROM source s WHERE s.sig_fpr = f.id)""");
278     ql = q.getresult();
279
280     count = 0;
281     projectB.query("BEGIN WORK");
282     for i in ql:
283         fingerprint_id = i[0];
284         if not Options["No-Action"]:
285             projectB.query("DELETE FROM fingerprint WHERE id = %s" % (fingerprint_id));
286             count += 1;
287     projectB.query("COMMIT WORK");
288
289     if count > 0:
290         sys.stderr.write("Cleared out %d fingerprint entries.\n" % (count));
291
292 ################################################################################
293
294 def clean_queue_build():
295     global now_date;
296
297     if not Cnf.ValueList("Dinstall::QueueBuildSuites") or Options["No-Action"]:
298         return;
299
300     print "Cleaning out queue build symlinks..."
301
302     our_delete_date = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()-int(Cnf["Rhona::QueueBuildStayOfExecution"])));
303     count = 0;
304
305     q = projectB.query("SELECT filename FROM queue_build WHERE last_used <= '%s'" % (our_delete_date));
306     for i in q.getresult():
307         filename = i[0];
308         if not os.path.exists(filename):
309             utils.warn("%s (from queue_build) doesn't exist." % (filename));
310             continue;
311         if not Cnf.FindB("Dinstall::SecurityQueueBuild") and not os.path.islink(filename):
312             utils.fubar("%s (from queue_build) should be a symlink but isn't." % (filename));
313         os.unlink(filename);
314         count += 1;
315     projectB.query("DELETE FROM queue_build WHERE last_used <= '%s'" % (our_delete_date));
316
317     if count:
318         sys.stderr.write("Cleaned %d queue_build files.\n" % (count));
319
320 ################################################################################
321
322 def main():
323     global Cnf, Options, projectB, delete_date, now_date;
324
325     Cnf = utils.get_conf()
326     for i in ["Help", "No-Action" ]:
327         if not Cnf.has_key("Rhona::Options::%s" % (i)):
328             Cnf["Rhona::Options::%s" % (i)] = "";
329
330     Arguments = [('h',"help","Rhona::Options::Help"),
331                  ('n',"no-action","Rhona::Options::No-Action")];
332
333     apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
334     Options = Cnf.SubTree("Rhona::Options")
335
336     if Options["Help"]:
337         usage();
338
339     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]));
340
341     now_date = time.strftime("%Y-%m-%d %H:%M");
342     delete_date = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()-int(Cnf["Rhona::StayOfExecution"])));
343
344     check_binaries();
345     clean_binaries();
346     check_sources();
347     check_files();
348     clean();
349     clean_maintainers();
350     clean_fingerprints();
351     clean_queue_build();
352
353 ################################################################################
354
355 if __name__ == '__main__':
356     main()
357