]> git.decadent.org.uk Git - dak.git/blob - dak/clean_suites.py
Convert exception handling to Python3 syntax.
[dak.git] / dak / clean_suites.py
1 #!/usr/bin/env python
2
3 """ Cleans up unassociated binary and source packages
4
5 @contact: Debian FTPMaster <ftpmaster@debian.org>
6 @copyright: 2000, 2001, 2002, 2003, 2006  James Troup <james@nocrew.org>
7 @copyright: 2009  Mark Hymers <mhy@debian.org>
8 @copyright: 2010  Joerg Jaspert <joerg@debian.org>
9 @license: GNU General Public License version 2 or later
10 """
11
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2 of the License, or
15 # (at your option) any later version.
16
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 # GNU General Public License for more details.
21
22 # You should have received a copy of the GNU General Public License
23 # along with this program; if not, write to the Free Software
24 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
26 ################################################################################
27
28 # 07:05|<elmo> well.. *shrug*.. no, probably not.. but to fix it,
29 #      |       we're going to have to implement reference counting
30 #      |       through dependencies.. do we really want to go down
31 #      |       that road?
32 #
33 # 07:05|<Culus> elmo: Augh! <brain jumps out of skull>
34
35 ################################################################################
36
37 import os
38 import stat
39 import sys
40 import time
41 import apt_pkg
42 from datetime import datetime, timedelta
43
44 from daklib.config import Config
45 from daklib.dbconn import *
46 from daklib import utils
47 from daklib import daklog
48
49 ################################################################################
50
51 Options = None
52 Logger = None
53
54 ################################################################################
55
56 def usage (exit_code=0):
57     print """Usage: dak clean-suites [OPTIONS]
58 Clean old packages from suites.
59
60   -n, --no-action            don't do anything
61   -h, --help                 show this help and exit
62   -m, --maximum              maximum number of files to remove"""
63     sys.exit(exit_code)
64
65 ################################################################################
66
67 def check_binaries(now_date, delete_date, max_delete, session):
68     print "Checking for orphaned binary packages..."
69
70     # Get the list of binary packages not in a suite and mark them for
71     # deletion.
72
73     q = session.execute("""
74 SELECT b.file, f.filename
75          FROM binaries b
76     LEFT JOIN files f
77       ON (b.file = f.id)
78    WHERE f.last_used IS NULL
79      AND b.id NOT IN
80          (SELECT ba.bin FROM bin_associations ba)
81      AND f.id NOT IN
82          (SELECT bqf.fileid FROM build_queue_files bqf)""")
83     for i in q.fetchall():
84         Logger.log(["set lastused", i[1]])
85         if not Options["No-Action"]:
86             session.execute("UPDATE files SET last_used = :lastused WHERE id = :fileid AND last_used IS NULL",
87                             {'lastused': now_date, 'fileid': i[0]})
88
89     if not Options["No-Action"]:
90         session.commit()
91
92     # Check for any binaries which are marked for eventual deletion
93     # but are now used again.
94
95     q = session.execute("""
96 SELECT b.file, f.filename
97          FROM binaries b
98     LEFT JOIN files f
99       ON (b.file = f.id)
100    WHERE f.last_used IS NOT NULL
101      AND (b.id IN
102           (SELECT ba.bin FROM bin_associations ba)
103           OR f.id IN
104           (SELECT bqf.fileid FROM build_queue_files bqf))""")
105
106     for i in q.fetchall():
107         Logger.log(["unset lastused", i[1]])
108         if not Options["No-Action"]:
109             session.execute("UPDATE files SET last_used = NULL WHERE id = :fileid", {'fileid': i[0]})
110
111     if not Options["No-Action"]:
112         session.commit()
113
114 ########################################
115
116 def check_sources(now_date, delete_date, max_delete, session):
117     print "Checking for orphaned source packages..."
118
119     # Get the list of source packages not in a suite and not used by
120     # any binaries.
121     q = session.execute("""
122 SELECT s.id, s.file, f.filename
123        FROM source s
124   LEFT JOIN files f
125     ON (s.file = f.id)
126   WHERE f.last_used IS NULL
127    AND s.id NOT IN
128         (SELECT sa.source FROM src_associations sa)
129    AND s.id NOT IN
130         (SELECT b.source FROM binaries b)
131    AND f.id NOT IN
132         (SELECT bqf.fileid FROM build_queue_files bqf)""")
133
134     #### XXX: this should ignore cases where the files for the binary b
135     ####      have been marked for deletion (so the delay between bins go
136     ####      byebye and sources go byebye is 0 instead of StayOfExecution)
137
138     for i in q.fetchall():
139         source_id = i[0]
140         dsc_file_id = i[1]
141         dsc_fname = i[2]
142
143         # Mark the .dsc file for deletion
144         Logger.log(["set lastused", dsc_fname])
145         if not Options["No-Action"]:
146             session.execute("""UPDATE files SET last_used = :last_used
147                                 WHERE id = :dscfileid AND last_used IS NULL""",
148                             {'last_used': now_date, 'dscfileid': dsc_file_id})
149
150         # Mark all other files references by .dsc too if they're not used by anyone else
151         x = session.execute("""SELECT f.id, f.filename FROM files f, dsc_files d
152                               WHERE d.source = :sourceid AND d.file = f.id""",
153                              {'sourceid': source_id})
154         for j in x.fetchall():
155             file_id = j[0]
156             file_name = j[1]
157             y = session.execute("SELECT id FROM dsc_files d WHERE d.file = :fileid", {'fileid': file_id})
158             if len(y.fetchall()) == 1:
159                 Logger.log(["set lastused", file_name])
160                 if not Options["No-Action"]:
161                     session.execute("""UPDATE files SET last_used = :lastused
162                                        WHERE id = :fileid AND last_used IS NULL""",
163                                     {'lastused': now_date, 'fileid': file_id})
164
165     if not Options["No-Action"]:
166         session.commit()
167
168     # Check for any sources which are marked for deletion but which
169     # are now used again.
170     q = session.execute("""
171 SELECT f.id, f.filename FROM source s, files f, dsc_files df
172   WHERE f.last_used IS NOT NULL AND s.id = df.source AND df.file = f.id
173     AND ((EXISTS (SELECT 1 FROM src_associations sa WHERE sa.source = s.id))
174       OR (EXISTS (SELECT 1 FROM binaries b WHERE b.source = s.id))
175       OR (EXISTS (SELECT 1 FROM build_queue_files bqf WHERE bqf.fileid = s.file)))""")
176
177     #### XXX: this should also handle deleted binaries specially (ie, not
178     ####      reinstate sources because of them
179
180     for i in q.fetchall():
181         Logger.log(["unset lastused", i[1]])
182         if not Options["No-Action"]:
183             session.execute("UPDATE files SET last_used = NULL WHERE id = :fileid",
184                             {'fileid': i[0]})
185
186     if not Options["No-Action"]:
187         session.commit()
188
189 ########################################
190
191 def check_files(now_date, delete_date, max_delete, session):
192     # FIXME: this is evil; nothing should ever be in this state.  if
193     # they are, it's a bug.
194
195     # However, we've discovered it happens sometimes so we print a huge warning
196     # and then mark the file for deletion.  This probably masks a bug somwhere
197     # else but is better than collecting cruft forever
198
199     print "Checking for unused files..."
200     q = session.execute("""
201 SELECT id, filename FROM files f
202   WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.file = f.id)
203     AND NOT EXISTS (SELECT 1 FROM dsc_files df WHERE df.file = f.id)
204     AND NOT EXISTS (SELECT 1 FROM changes_pool_files cpf WHERE cpf.fileid = f.id)
205     AND NOT EXISTS (SELECT 1 FROM build_queue_files qf WHERE qf.fileid = f.id)
206     AND last_used IS NULL
207     ORDER BY filename""")
208
209     ql = q.fetchall()
210     if len(ql) > 0:
211         utils.warn("check_files found something it shouldn't")
212         for x in ql:
213             utils.warn("orphaned file: %s" % x)
214             Logger.log(["set lastused", x[1], "ORPHANED FILE"])
215             if not Options["No-Action"]:
216                  session.execute("UPDATE files SET last_used = :lastused WHERE id = :fileid",
217                                  {'lastused': now_date, 'fileid': x[0]})
218
219         if not Options["No-Action"]:
220             session.commit()
221
222 def clean_binaries(now_date, delete_date, max_delete, session):
223     # We do this here so that the binaries we remove will have their
224     # source also removed (if possible).
225
226     # XXX: why doesn't this remove the files here as well? I don't think it
227     #      buys anything keeping this separate
228     print "Cleaning binaries from the DB..."
229     print "Deleting from binaries table... "
230     for bin in session.query(DBBinary).join(DBBinary.poolfile).filter(PoolFile.last_used <= delete_date):
231         Logger.log(["delete binary", bin.poolfile.filename])
232         if not Options["No-Action"]:
233             session.delete(bin)
234     if not Options["No-Action"]:
235         session.commit()
236
237 ########################################
238
239 def clean(now_date, delete_date, max_delete, session):
240     cnf = Config()
241
242     count = 0
243     size = 0
244
245     print "Cleaning out packages..."
246
247     morguedir = cnf.get("Dir::Morgue", os.path.join("Dir::Pool", 'morgue'))
248     morguesubdir = cnf.get("Clean-Suites::MorgueSubDir", 'pool')
249
250     # Build directory as morguedir/morguesubdir/year/month/day
251     dest = os.path.join(morguedir,
252                         morguesubdir,
253                         str(now_date.year),
254                         '%.2d' % now_date.month,
255                         '%.2d' % now_date.day)
256
257     if not Options["No-Action"] and not os.path.exists(dest):
258         os.makedirs(dest)
259
260     # Delete from source
261     print "Deleting from source table... "
262     q = session.execute("""
263 SELECT s.id, f.filename FROM source s, files f
264   WHERE f.last_used <= :deletedate
265         AND s.file = f.id
266         AND s.id NOT IN (SELECT src_id FROM extra_src_references)""", {'deletedate': delete_date})
267     for s in q.fetchall():
268         Logger.log(["delete source", s[1], s[0]])
269         if not Options["No-Action"]:
270             session.execute("DELETE FROM dsc_files WHERE source = :s_id", {"s_id":s[0]})
271             session.execute("DELETE FROM source WHERE id = :s_id", {"s_id":s[0]})
272
273     if not Options["No-Action"]:
274         session.commit()
275
276     # Delete files from the pool
277     old_files = session.query(PoolFile).filter(PoolFile.last_used <= delete_date)
278     if max_delete is not None:
279         old_files = old_files.limit(max_delete)
280         print "Limiting removals to %d" % max_delete
281
282     for pf in old_files:
283         filename = os.path.join(pf.location.path, pf.filename)
284         if not os.path.exists(filename):
285             utils.warn("can not find '%s'." % (filename))
286             continue
287         Logger.log(["delete pool file", filename])
288         if os.path.isfile(filename):
289             if os.path.islink(filename):
290                 count += 1
291                 Logger.log(["delete symlink", filename])
292                 if not Options["No-Action"]:
293                     os.unlink(filename)
294             else:
295                 size += os.stat(filename)[stat.ST_SIZE]
296                 count += 1
297
298                 dest_filename = dest + '/' + os.path.basename(filename)
299                 # If the destination file exists; try to find another filename to use
300                 if os.path.exists(dest_filename):
301                     dest_filename = utils.find_next_free(dest_filename)
302
303                 Logger.log(["move to morgue", filename, dest_filename])
304                 if not Options["No-Action"]:
305                     utils.move(filename, dest_filename)
306
307             if not Options["No-Action"]:
308                 session.delete(pf)
309                 session.commit()
310
311         else:
312             utils.fubar("%s is neither symlink nor file?!" % (filename))
313
314     if count > 0:
315         Logger.log(["total", count, utils.size_type(size)])
316         print "Cleaned %d files, %s." % (count, utils.size_type(size))
317
318 ################################################################################
319
320 def clean_maintainers(now_date, delete_date, max_delete, session):
321     print "Cleaning out unused Maintainer entries..."
322
323     # TODO Replace this whole thing with one SQL statement
324     q = session.execute("""
325 SELECT m.id, m.name FROM maintainer m
326   WHERE NOT EXISTS (SELECT 1 FROM binaries b WHERE b.maintainer = m.id)
327     AND NOT EXISTS (SELECT 1 FROM source s WHERE s.maintainer = m.id OR s.changedby = m.id)
328     AND NOT EXISTS (SELECT 1 FROM src_uploaders u WHERE u.maintainer = m.id)""")
329
330     count = 0
331
332     for i in q.fetchall():
333         maintainer_id = i[0]
334         Logger.log(["delete maintainer", i[1]])
335         if not Options["No-Action"]:
336             session.execute("DELETE FROM maintainer WHERE id = :maint", {'maint': maintainer_id})
337         count += 1
338
339     if not Options["No-Action"]:
340         session.commit()
341
342     if count > 0:
343         Logger.log(["total", count])
344         print "Cleared out %d maintainer entries." % (count)
345
346 ################################################################################
347
348 def clean_fingerprints(now_date, delete_date, max_delete, session):
349     print "Cleaning out unused fingerprint entries..."
350
351     # TODO Replace this whole thing with one SQL statement
352     q = session.execute("""
353 SELECT f.id, f.fingerprint FROM fingerprint f
354   WHERE f.keyring IS NULL
355     AND NOT EXISTS (SELECT 1 FROM binaries b WHERE b.sig_fpr = f.id)
356     AND NOT EXISTS (SELECT 1 FROM source s WHERE s.sig_fpr = f.id)""")
357
358     count = 0
359
360     for i in q.fetchall():
361         fingerprint_id = i[0]
362         Logger.log(["delete fingerprint", i[1]])
363         if not Options["No-Action"]:
364             session.execute("DELETE FROM fingerprint WHERE id = :fpr", {'fpr': fingerprint_id})
365         count += 1
366
367     if not Options["No-Action"]:
368         session.commit()
369
370     if count > 0:
371         Logger.log(["total", count])
372         print "Cleared out %d fingerprint entries." % (count)
373
374 ################################################################################
375
376 def clean_empty_directories(session):
377     """
378     Removes empty directories from pool directories.
379     """
380
381     print "Cleaning out empty directories..."
382
383     count = 0
384
385     cursor = session.execute(
386         "SELECT DISTINCT(path) FROM location WHERE type = :type",
387         {'type': 'pool'},
388     )
389     bases = [x[0] for x in cursor.fetchall()]
390
391     for base in bases:
392         for dirpath, dirnames, filenames in os.walk(base, topdown=False):
393             if not filenames and not dirnames:
394                 to_remove = os.path.join(base, dirpath)
395                 if not Options["No-Action"]:
396                     Logger.log(["removing directory", to_remove])
397                     os.removedirs(to_remove)
398                 count += 1
399
400     if count:
401         Logger.log(["total removed directories", count])
402
403 ################################################################################
404
405 def main():
406     global Options, Logger
407
408     cnf = Config()
409
410     for i in ["Help", "No-Action", "Maximum" ]:
411         if not cnf.has_key("Clean-Suites::Options::%s" % (i)):
412             cnf["Clean-Suites::Options::%s" % (i)] = ""
413
414     Arguments = [('h',"help","Clean-Suites::Options::Help"),
415                  ('n',"no-action","Clean-Suites::Options::No-Action"),
416                  ('m',"maximum","Clean-Suites::Options::Maximum", "HasArg")]
417
418     apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
419     Options = cnf.SubTree("Clean-Suites::Options")
420
421     if cnf["Clean-Suites::Options::Maximum"] != "":
422         try:
423             # Only use Maximum if it's an integer
424             max_delete = int(cnf["Clean-Suites::Options::Maximum"])
425             if max_delete < 1:
426                 utils.fubar("If given, Maximum must be at least 1")
427         except ValueError as e:
428             utils.fubar("If given, Maximum must be an integer")
429     else:
430         max_delete = None
431
432     if Options["Help"]:
433         usage()
434
435     Logger = daklog.Logger("clean-suites", debug=Options["No-Action"])
436
437     session = DBConn().session()
438
439     now_date = datetime.now()
440
441     # Stay of execution; default to 1.5 days
442     soe = int(cnf.get('Clean-Suites::StayOfExecution', '129600'))
443
444     delete_date = now_date - timedelta(seconds=soe)
445
446     check_binaries(now_date, delete_date, max_delete, session)
447     clean_binaries(now_date, delete_date, max_delete, session)
448     check_sources(now_date, delete_date, max_delete, session)
449     check_files(now_date, delete_date, max_delete, session)
450     clean(now_date, delete_date, max_delete, session)
451     clean_maintainers(now_date, delete_date, max_delete, session)
452     clean_fingerprints(now_date, delete_date, max_delete, session)
453     clean_empty_directories(session)
454
455     Logger.close()
456
457 ################################################################################
458
459 if __name__ == '__main__':
460     main()