]> git.decadent.org.uk Git - dak.git/blob - rhona
[aj] make SoE work. [me] don't overwrite files ever; use dated sub directories in...
[dak.git] / rhona
1 #!/usr/bin/env python
2
3 # rhona, cleans up unassociated binary and source packages
4 # Copyright (C) 2000, 2001  James Troup <james@nocrew.org>
5 # $Id: rhona,v 1.14 2001-05-31 02:19:30 troup 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, string, sys, time
33 import apt_pkg
34 import utils
35
36 ###################################################################################################
37
38 projectB = None
39 Cnf = None
40 now_date = None;     # mark newly "deleted" things as deleted "now"
41 delete_date = None;  # delete things marked "deleted" earler than this
42 overrides = {};
43
44 tried_too_hard_exc = "Tried too hard to find a free filename for %s; something's gone Pete Tong";
45
46 ###################################################################################################
47
48 def usage (exit_code):
49     print """Usage: rhona [OPTION]... [CHANGES]...
50   -D, --debug=VALUE         debug
51   -n, --no-action           don't do anything
52   -v, --verbose             be verbose
53   -V, --version             display version number and exit"""
54     sys.exit(exit_code)
55
56 ###################################################################################################
57
58 def find_next_free (dest):
59     extra = 0;
60     orig_dest = dest;
61     too_much = 100;
62     while os.path.exists(dest) and extra < too_much:
63         dest = orig_dest + '.' + repr(extra);
64         extra = extra + 1;
65     if extra >= too_much:
66         raise tried_too_hard_exc;
67     return dest;
68     
69 # FIXME: why can't we make (sane speed) UPDATEs out of these SELECTs?
70
71 def check_binaries():
72     global delete_date, now_date;
73     
74     print "Checking for orphaned binary packages..."
75
76     # Get the list of binary packages not in a suite and mark them for
77     # deletion.
78
79     q = projectB.query("""
80 SELECT b.file FROM binaries b WHERE NOT EXISTS
81         (SELECT ba.bin 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 = '%s' WHERE id = %s AND last_used IS NULL" % (now_date, file_id))
88     projectB.query("COMMIT WORK");
89
90     # Check for any binaries which are marked for eventual deletion
91     # but are now used again.
92
93     q = projectB.query("""
94 SELECT b.file FROM binaries b, files f
95    WHERE f.last_used IS NOT NULL AND f.id = b.file AND
96       EXISTS (SELECT suite FROM bin_associations ba WHERE ba.bin = b.id)""");
97     ql = q.getresult();
98     projectB.query("BEGIN WORK");
99     for i in ql:
100         file_id = i[0];
101         projectB.query("UPDATE files SET last_used = NULL WHERE id = %s" % (file_id));
102     projectB.query("COMMIT WORK");
103
104 def check_sources():
105     global delete_date, now_date;
106
107     print "Checking for orphaned source packages..."
108
109     # Get the list of source packages not in a suite and not linked to
110     # by any binary packages.
111
112     q = projectB.query("""
113 SELECT s.id, s.file FROM source s
114   WHERE NOT EXISTS
115    (SELECT sa.suite FROM src_associations sa WHERE sa.source = s.id)
116   AND NOT EXISTS (SELECT b.id FROM binaries b WHERE b.source = s.id)""");
117
118     #### XXX: this should ignore cases where the files for the binary b
119     ####      have been marked for deletion (so the delay between bins go
120     ####      byebye and sources go byebye is 0 instead of StayOfExecution)
121
122     ql = q.getresult();
123     
124     projectB.query("BEGIN WORK");
125     for i in ql:
126         source_id = i[0];
127         dsc_file_id = i[1];
128
129         # Mark the .dsc file for deletion
130         projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s AND last_used IS NULL" % (now_date, dsc_file_id))
131         # Mark all other files references by .dsc too if they're not used by anyone else
132         x = projectB.query("SELECT f.id FROM files f, dsc_files d WHERE d.source = %s AND d.file = f.id" % (source_id));
133         for j in x.getresult():
134             file_id = j[0];
135             y = projectB.query("SELECT id FROM dsc_files d WHERE d.file = %s" % (file_id));
136             if len(y.getresult()) == 1:
137                 projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s AND last_used IS NULL" % (now_date, file_id));
138     projectB.query("COMMIT WORK");
139
140     # Check for any sources which are marked for deletion but which
141     # are now used again.
142
143     q = projectB.query("""
144 SELECT f.id FROM source s, files f, dsc_files df
145   WHERE f.last_used IS NOT NULL AND s.id = df.source AND df.file = f.id
146     AND ((EXISTS (SELECT sa.suite FROM src_associations sa WHERE sa.source = s.id))
147       OR (EXISTS (SELECT b.id FROM binaries b WHERE b.source = s.id)))""");
148
149     #### XXX: this should also handle deleted binaries specially (ie, not
150     ####      reinstate sources because of them
151
152     ql = q.getresult();
153     # Could be done in SQL; but left this way for hysterical raisins
154     # [and freedom to innovate don'cha know?]
155     projectB.query("BEGIN WORK");
156     for i in ql:
157         file_id = i[0];
158         projectB.query("UPDATE files SET last_used = NULL WHERE id = %s" % (file_id));
159     projectB.query("COMMIT WORK");
160
161 def check_files():
162     global delete_date, now_date;
163
164     # FIXME: this is evil; nothing should ever be in this state.  if
165     # they are, it's a bug and the files should not be auto-deleted.
166
167     return;
168
169     print "Checking for unused files..."
170
171     q = projectB.query("""
172 SELECT id FROM files f
173   WHERE NOT EXISTS (SELECT id FROM binaries b WHERE b.file = f.id)
174     AND NOT EXISTS (SELECT id FROM dsc_files df WHERE df.file = f.id)""");
175
176     projectB.query("BEGIN WORK");
177     for i in q.getresult():
178         file_id = i[0];
179         projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s" % (now_date, file_id));
180     projectB.query("COMMIT WORK");
181     
182 def clean_binaries():
183     global delete_date, now_date;
184
185     # We do this here so that the binaries we remove will have their
186     # source also removed (if possible).
187
188     # XXX: why doesn't this remove the files here as well? I don't think it
189     #      buys anything keeping this separate
190     print "Cleaning binaries from the DB..."
191     if not Cnf["Rhona::Options::No-Action"]:
192         before = time.time();
193         sys.stdout.write("[Deleting from binaries table... ");
194         projectB.query("DELETE FROM binaries WHERE EXISTS (SELECT id FROM files WHERE binaries.file = files.id AND files.last_used <= '%s')" % (delete_date));
195         sys.stdout.write("done. (%d seconds)]\n" % (int(time.time()-before)));
196
197 def clean():
198     global delete_date, now_date;
199     count = 0;
200     size = 0;
201
202     print "Cleaning out packages..."
203
204     date = time.strftime("%Y-%m-%d", time.localtime(time.time()));
205     dest = Cnf["Dir::Morgue"] + '/' + Cnf["Rhona::MorgueSubDir"] + '/' + date;
206     if not os.path.exists(dest):
207         os.mkdir(dest);
208         
209     # Delete from source
210     if not Cnf["Rhona::Options::No-Action"]:
211         before = time.time();
212         sys.stdout.write("[Deleting from source table... ");
213         projectB.query("DELETE FROM dsc_files WHERE EXISTS (SELECT df.id 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));
214         projectB.query("DELETE FROM source WHERE EXISTS (SELECT id FROM files WHERE source.file = files.id AND files.last_used <= '%s')" % (delete_date));
215         sys.stdout.write("done. (%d seconds)]\n" % (int(time.time()-before)));
216         
217     # Delete files from the pool
218     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));
219     for i in q.getresult():
220         filename = i[0] + i[1];
221         if not os.path.exists(filename):
222             sys.stderr.write("E: can not find %s.\n" % (filename));
223             continue;
224         if os.path.isfile(filename):
225             if os.path.islink(filename):
226                 count = count + 1;
227                 if Cnf["Rhona::Options::No-Action"]:
228                     print "Removing symlink %s..." % (filename);
229                 else:
230                     os.unlink(filename);
231             else:
232                 size = size + os.stat(filename)[stat.ST_SIZE];
233                 count = count + 1;
234
235                 dest_filename = dest + '/' + os.path.basename(filename);
236                 # If the destination file exists; try to find another filename to use
237                 if os.path.exists(dest_filename):
238                     dest_filename = find_next_free(dest_filename);
239                 
240                 if Cnf["Rhona::Options::No-Action"]:
241                     print "Cleaning %s -> %s ..." % (filename, dest_filename);
242                 else:
243                     utils.move(filename, dest_filename);
244         else:
245             sys.stderr.write("%s is neither symlink nor file?!\n" % (filename));
246             sys.exit(1);
247             
248     # Delete from the 'files' table
249     if not Cnf["Rhona::Options::No-Action"]:
250         before = time.time();
251         sys.stdout.write("[Deleting from files table... ");
252         projectB.query("DELETE FROM files WHERE last_used <= '%s'" % (delete_date));
253         sys.stdout.write("done. (%d seconds)]\n" % (int(time.time()-before)));
254     if count > 0:
255         sys.stderr.write("Cleaned %d files, %s.\n" % (count, utils.size_type(size)));
256
257 def clean_maintainers():
258     print "Cleaning out unused Maintainer entries..."
259     
260     q = projectB.query("""
261 SELECT m.id FROM maintainer m
262   WHERE NOT EXISTS (SELECT id FROM binaries b WHERE b.maintainer = m.id)
263     AND NOT EXISTS (SELECT id FROM source s WHERE s.maintainer = m.id)""");
264     ql = q.getresult();
265
266     count = 0;
267     projectB.query("BEGIN WORK");
268     for i in ql:
269         maintainer_id = i[0];
270         if not Cnf["Rhona::Options::No-Action"]:
271             projectB.query("DELETE FROM maintainer WHERE id = %s" % (maintainer_id));
272             count = count + 1;
273     projectB.query("COMMIT WORK");
274
275     if count > 0:
276         sys.stderr.write("Cleared out %d maintainer entries.\n" % (count));
277
278 def main():
279     global Cnf, projectB, delete_date, now_date;
280     
281     apt_pkg.init();
282     
283     Cnf = apt_pkg.newConfiguration();
284     apt_pkg.ReadConfigFileISC(Cnf,utils.which_conf_file());
285
286     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]));
287
288     Arguments = [('D',"debug","Rhona::Options::Debug", "IntVal"),
289                  ('h',"help","Rhona::Options::Help"),
290                  ('n',"no-action","Rhona::Options::No-Action"),
291                  ('V',"version","Rhona::Options::Version")];
292     
293     apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
294     Options = Cnf.SubTree("Rhona::Options")
295
296     if Options["Help"]:
297         usage(0);
298         
299     if Options["Version"]:
300         print "rhona version 0.0000000000";
301         usage(0);
302
303     override_filename = Cnf["Dir::OverrideDir"] + Cnf["Rhona::OverrideFilename"];
304     if not os.access(override_filename, os.R_OK):
305         sys.stderr.write("W: Could not find source-only override file '%s'.\n" % (override_filename));
306
307     now_date = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()));
308     delete_date = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()-int(Cnf["Rhona::StayOfExecution"])));
309     
310     check_binaries();
311     clean_binaries();
312     check_sources();
313     check_files();
314     clean();
315     clean_maintainers();
316
317 if __name__ == '__main__':
318     main()
319