]> 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  James Troup <james@nocrew.org>
5 # $Id: rhona,v 1.7 2001-01-10 06:08:03 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 delete_date = None;
41 overrides = {};
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 # See if a given package is in the override file.  Caches and only loads override files on demand.
56
57 def in_override_p (package):
58     global overrides;
59
60     if overrides == {}:
61         filename = Cnf["Dir::OverrideDir"] + Cnf["Rhona::OverrideFilename"];
62         try:
63             file = utils.open_file(filename, 'r');
64         except utils.cant_open_exc:
65             pass;
66         else:
67             for line in file.readlines():
68                 line = string.strip(utils.re_comments.sub('', line))
69                 if line != "":
70                     overrides[line] = 1
71             file.close()
72
73     return overrides.get(package, None);
74
75 ###################################################################################################
76
77 def check_binaries():
78     global delete_date;
79     
80     print "Checking for orphaned binary packages..."
81
82     # A nicer way to do this would be `SELECT bin FROM
83     # bin_associations EXCEPT SELECT id from binaries WHERE
84     # last_update IS NULL', but it seems postgresql can't handle that
85     # query as it hadn't return after I left it running for 20 minutes
86     # on auric.
87     
88     linked_binaries = {};
89     q = projectB.query("SELECT bin FROM bin_associations");
90     ql = q.getresult();
91     for i in ql:
92         linked_binaries[i[0]] = "";
93     
94     all_binaries = {};
95     q = projectB.query("SELECT b.id, b.file FROM binaries b, files f WHERE f.last_used IS NULL AND f.id = b.file")
96     ql = q.getresult();
97     for i in ql:
98         all_binaries[i[0]] = i[1];
99
100     projectB.query("BEGIN WORK");
101     for id in all_binaries.keys():
102         if not linked_binaries.has_key(id):
103             projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s" % (delete_date, all_binaries[id]))
104     projectB.query("COMMIT WORK");
105
106     # Check for any binaries which are marked for eventual deletion but are now used again.
107
108     all_marked_binaries = {};
109     q = projectB.query("SELECT b.id, b.file FROM binaries b, files f WHERE f.last_used IS NOT NULL AND f.id = b.file")
110     ql = q.getresult();
111     for i in ql:
112         all_marked_binaries[i[0]] = i[1];
113         
114     projectB.query("BEGIN WORK");
115     for id in all_marked_binaries.keys():
116         if linked_binaries.has_key(id):
117             # Can't imagine why this would happen, so warn about it for now.
118             print "W: %s has released %s from the target list." % (id, all_marked_binaries[id]);
119             projectB.query("UPDATE files SET last_used = NULL WHERE id = %s" % (all_marked_binaries[id]));
120     projectB.query("COMMIT WORK");
121
122 def check_sources():
123     global delete_date;
124
125     print "Checking for orphaned source packages..."
126
127     # A nicer way to do this would be using `EXCEPT', but see the
128     # comment in check_binaries().
129
130     linked_sources = {};
131     q = projectB.query("SELECT source FROM binaries WHERE source is not null");
132     ql = q.getresult();
133     for i in ql:
134         linked_sources[i[0]] = "";
135     
136     all_sources = {};
137     all_sources_package = {};
138     q = projectB.query("SELECT s.id, s.file, s.source FROM source s, files f WHERE f.last_used IS NULL AND f.id = s.file");
139     ql = q.getresult();
140     for i in ql:
141         all_sources[i[0]] = i[1];
142         all_sources_package[i[0]] = i[2];
143
144     projectB.query("BEGIN WORK");
145     for id in all_sources.keys():
146         if not linked_sources.has_key(id):
147             # Is this a known source-only package?
148             if in_override_p(all_sources_package[id]):
149                 continue;
150             # Then check to see if the source is still in any suites
151             untouchable = 0;
152             q = projectB.query("SELECT su.suite_name FROM src_associations sa, suite su WHERE sa.source = %s and su.id = sa.suite" % (id));
153             for i in q.getresult():
154                 if Cnf.Find("Suite::%s::Untouchable" % (i[0])):
155                     untouchable = 1;
156                 else:
157                     if not Cnf["Rhona::Options::No-Action"]:
158                         projectB.query("DELETE FROM src_associations WHERE source = %s" % (id));
159                     
160             # We can't delete binary-less source-only packages if
161             # they're in an untouchable suite (i.e. stable)...
162             if untouchable:
163                 continue;
164
165             projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s" % (delete_date, all_sources[id]))
166             # Delete all other files references by .dsc too if they're not used by anyone else
167             q = projectB.query("SELECT f.id FROM files f, dsc_files d WHERE d.source = %d AND d.file = f.id" % (id));
168             for i in q.getresult(): 
169                 q = projectB.query("SELECT id FROM dsc_files d WHERE file = %s" % (i[0]));
170                 ql = q.getresult();
171                 if len(ql) == 1:
172                     projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s" % (delete_date, i[0]));
173
174             # If the file is used by another source package
175             # (e.g. because it's an .orig.tar.gz) We need to delete
176             # this source package's reference to it from dsc_files.
177             # So just clear out all references to the source file in
178             # dsc_files now.
179             if not Cnf["Rhona::Options::No-Action"]:
180                 projectB.query("DELETE FROM dsc_files WHERE source = %s" % (id));
181                     
182     projectB.query("COMMIT WORK");
183
184     # Check for any sources which are marked for eventual deletion but are now used again.
185     all_marked_sources = {};
186     q = projectB.query("SELECT s.id, s.file FROM source s, files f WHERE f.last_used IS NOT NULL AND f.id = s.file");
187     ql = q.getresult();
188     for i in ql:
189         all_marked_sources[i[0]] = i[1];
190     projectB.query("BEGIN WORK");
191     for id in all_marked_sources.keys():
192         if linked_sources.has_key(id):
193             # Can't imagine why this would happen, so warn about it for now.
194             print "W: %s has released %s from the target list." % (id, all_marked_sources[id]);
195             projectB.query("UPDATE files SET last_used = NULL WHERE id = %s" % (all_marked_sources[id]));
196             # Unmark all other files references by .dsc too
197             q = projectB.query("SELECT file FROM dsc_files WHERE source = %d" % (id));
198             ql = q.getresult();
199             for i in ql:
200                     projectB.query("UPDATE files SET last_used = NULL WHERE id = %s" % (i[0]));
201     projectB.query("COMMIT WORK");
202
203     # Whee, check for any source files (i.e. non .dsc) which are
204     # marked for eventual deletion but are now used by a source
205     # package again.
206     all_marked_dsc_files = {}
207     q = projectB.query("SELECT s.id, s.file FROM source s, files f, dsc_files d WHERE f.last_used IS NOT NULL AND f.id = d.file AND d.source = s.id");
208     ql = q.getresult();
209     for i in ql:
210         all_marked_dsc_files[i[0]] = i[1];
211     projectB.query("BEGIN WORK");
212     for id in all_marked_dsc_files.keys():
213         if linked_sources.has_key(id):
214             # Can't imagine why this would happen, so warn about it for now.
215             print "W: %s has released %s from the target list." % (id, all_marked_sources[id]);
216             projectB.query("UPDATE files SET last_used = NULL WHERE id = %s" % (all_marked_sources[id]));
217             # Unmark all other files references by .dsc too
218             q = projectB.query("SELECT file FROM dsc_files WHERE source = %d" % (id));
219             ql = q.getresult();
220             for i in ql:
221                     projectB.query("UPDATE files SET last_used = NULL WHERE id = %s" % (i[0]));
222     projectB.query("COMMIT WORK");
223
224 def check_files():
225     global delete_date;
226
227     print "Checking for unused files..."
228
229     # Check for files not references in either binaries or dsc_files
230     used = {};
231     q = projectB.query("SELECT file FROM binaries");
232     for i in q.getresult():
233         used[i[0]] = "";
234     q = projectB.query("SELECT file FROM dsc_files");
235     for i in q.getresult():
236         used[i[0]] = "";
237         
238     all = {};
239     q = projectB.query("SELECT f.id, l.path, f.filename FROM files f, location l WHERE f.location = l.id;");
240     for i in q.getresult():
241         all[i[0]] = i[1] + i[2];
242
243     projectB.query("BEGIN WORK");
244     for id in all.keys():
245         if not used.has_key(id):
246             projectB.query("UPDATE files SET last_used = '%s' WHERE id = %s" % (delete_date, id));
247     projectB.query("COMMIT WORK");
248     
249 def clean_binaries():
250     global delete_date;
251
252     # We do this here so that the binaries we remove will have their
253     # source also removed (if possible).
254
255     print "Cleaning binaries from the DB..."
256     if not Cnf["Rhona::Options::No-Action"]:
257         before = time.time();
258         sys.stdout.write("[Deleting from binaries table... ");
259         projectB.query("DELETE FROM binaries WHERE EXISTS (SELECT id FROM files WHERE binaries.file = files.id AND files.last_used <= '%s')" % (delete_date));
260         sys.stdout.write("done. (%d)]\n" % (int(time.time()-before)));
261
262 def clean():
263     global delete_date;
264     count = 0;
265     size = 0;
266
267     print "Cleaning out packages..."
268
269     # Ensure destination directory exists
270     dest = Cnf["Dir::Morgue"] + '/' + Cnf["Rhona::MorgueSubDir"];
271     if not os.path.exists(dest):
272         os.mkdir(dest);
273         
274     # Delete from source (dsc_file should already be done!)
275     if not Cnf["Rhona::Options::No-Action"]:
276         before = time.time();
277         sys.stdout.write("[Deleting from source table... ");
278         projectB.query("DELETE FROM source WHERE EXISTS (SELECT id FROM files WHERE source.file = files.id AND files.last_used <= '%s')" % (delete_date));
279         sys.stdout.write("done. (%d)]\n" % (int(time.time()-before)));
280         
281     # Delete files from the pool
282     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));
283     for i in q.getresult():
284         filename = i[0] + i[1];
285         if not os.path.exists(filename):
286             sys.stderr.write("E: can not find %s.\n" % (filename));
287             continue;
288         if os.path.isfile(filename):
289             if os.path.islink(filename):
290                 count = count + 1;
291                 if Cnf["Rhona::Options::No-Action"]:
292                     print "Removing symlink %s..." % (filename);
293                 else:
294                     os.unlink(filename);
295             else:
296                 size = size + os.stat(filename)[stat.ST_SIZE];
297                 count = count + 1;
298                 if Cnf["Rhona::Options::No-Action"]:
299                     print "Cleaning %s to %s..." % (filename, dest);
300                 else:
301                     utils.move(filename, dest);
302         else:
303             sys.stderr.write("%s is neither symlink nor file?!\n" % (filename));
304             sys.exit(1);
305     # delete from files
306     if not Cnf["Rhona::Options::No-Action"]:
307         before = time.time();
308         sys.stdout.write("[Deleting from files table... ");
309         projectB.query("DELETE FROM files WHERE last_used <= '%s'" % (delete_date));
310         sys.stdout.write("done. (%d)]\n" % (int(time.time()-before)));
311     if count > 0:
312         sys.stderr.write("Cleaned %d files, %s.\n" % (count, utils.size_type(size)));
313
314 def clean_maintainers():
315     print "Cleaning out unused Maintainer entries..."
316     
317     used = {};
318     q = projectB.query("SELECT maintainer FROM binaries WHERE maintainer IS NOT NULL");
319     for i in q.getresult():
320         used[i[0]] = "";
321     q = projectB.query("SELECT maintainer FROM source WHERE maintainer IS NOT NULL");
322     for i in q.getresult():
323         used[i[0]] = "";
324
325     all = {};
326     q = projectB.query("SELECT id, name FROM maintainer");
327     for i in q.getresult():
328         all[i[0]] = i[1];
329
330     count = 0;
331     projectB.query("BEGIN WORK");
332     for id in all.keys():
333         if not used.has_key(id):
334             if not Cnf["Rhona::Options::No-Action"]:
335                 projectB.query("DELETE FROM maintainer WHERE id = %s" % (id));
336             count = count + 1;
337     projectB.query("COMMIT WORK");
338
339     if count > 0:
340         sys.stderr.write("Cleared out %d maintainer entries.\n" % (count));
341
342 def main():
343     global Cnf, projectB, delete_date;
344     
345     projectB = pg.connect('projectb', 'localhost');
346
347     apt_pkg.init();
348     
349     Cnf = apt_pkg.newConfiguration();
350     apt_pkg.ReadConfigFileISC(Cnf,utils.which_conf_file());
351
352     Arguments = [('D',"debug","Rhona::Options::Debug", "IntVal"),
353                  ('h',"help","Rhona::Options::Help"),
354                  ('n',"no-action","Rhona::Options::No-Action"),
355                  ('V',"version","Rhona::Options::Version")];
356     
357     apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
358     if Cnf["Rhona::Options::Help"]:
359         usage(0);
360         
361     if Cnf["Rhona::Options::Version"]:
362         print "rhona version 0.0000000000";
363         usage(0);
364
365     override_filename = Cnf["Dir::OverrideDir"] + Cnf["Rhona::OverrideFilename"];
366     if not os.access(override_filename, os.R_OK):
367         sys.stderr.write("W: Could not find source-only override file '%s'.\n" % (override_filename));
368
369     delete_date = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()));
370
371     check_binaries();
372     clean_binaries();
373     check_sources();
374     check_files();
375     clean();
376     clean_maintainers();
377
378 if __name__ == '__main__':
379     main()
380