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