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