]> git.decadent.org.uk Git - dak.git/blob - dak/check_archive.py
Use the database instead of Lists for check_archive
[dak.git] / dak / check_archive.py
1 #!/usr/bin/env python
2
3 """ Various different sanity checks
4
5 @contact: Debian FTP Master <ftpmaster@debian.org>
6 @copyright: (C) 2000, 2001, 2002, 2003, 2004, 2006  James Troup <james@nocrew.org>
7 @license: GNU General Public License version 2 or later
8 """
9
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
14
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19
20 # You should have received a copy of the GNU General Public License
21 # along with this program; if not, write to the Free Software
22 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
24 ################################################################################
25
26 #   And, lo, a great and menacing voice rose from the depths, and with
27 #   great wrath and vehemence it's voice boomed across the
28 #   land... ``hehehehehehe... that *tickles*''
29 #                                                       -- aj on IRC
30
31 ################################################################################
32
33 import commands
34 import os
35 import stat
36 import sys
37 import time
38 import apt_pkg
39 import apt_inst
40
41 from daklib.dbconn import *
42 from daklib import utils
43 from daklib.config import Config
44
45 ################################################################################
46
47 db_files = {}                  #: Cache of filenames as known by the database
48 waste = 0.0                    #: How many bytes are "wasted" by files not referenced in database
49 excluded = {}                  #: List of files which are excluded from files check
50 current_file = None
51 future_files = {}
52 current_time = time.time()     #: now()
53
54 ################################################################################
55
56 def usage(exit_code=0):
57     print """Usage: dak check-archive MODE
58 Run various sanity checks of the archive and/or database.
59
60   -h, --help                show this help and exit.
61
62 The following MODEs are available:
63
64   checksums          - validate the checksums stored in the database
65   files              - check files in the database against what's in the archive
66   dsc-syntax         - validate the syntax of .dsc files in the archive
67   missing-overrides  - check for missing overrides
68   source-in-one-dir  - ensure the source for each package is in one directory
69   timestamps         - check for future timestamps in .deb's
70   files-in-dsc       - ensure each .dsc references appropriate Files
71   validate-indices   - ensure files mentioned in Packages & Sources exist
72   files-not-symlinks - check files in the database aren't symlinks
73   validate-builddeps - validate build-dependencies of .dsc files in the archive
74 """
75     sys.exit(exit_code)
76
77 ################################################################################
78
79 def process_dir (unused, dirname, filenames):
80     """
81     Process a directory and output every files name which is not listed already
82     in the C{filenames} or global C{excluded} dictionaries.
83
84     @type dirname: string
85     @param dirname: the directory to look at
86
87     @type filenames: dict
88     @param filenames: Known filenames to ignore
89     """
90     global waste, db_files, excluded
91
92     if dirname.find('/disks-') != -1 or dirname.find('upgrade-') != -1:
93         return
94     # hack; can't handle .changes files
95     if dirname.find('proposed-updates') != -1:
96         return
97     for name in filenames:
98         filename = os.path.abspath(os.path.join(dirname,name))
99         if os.path.isfile(filename) and not os.path.islink(filename) and not db_files.has_key(filename) and not excluded.has_key(filename):
100             waste += os.stat(filename)[stat.ST_SIZE]
101             print "%s" % (filename)
102
103 ################################################################################
104
105 def check_files():
106     """
107     Prepare the dictionary of existing filenames, then walk through the archive
108     pool/ directory to compare it.
109     """
110     global db_files
111
112     cnf = Config()
113
114     print "Building list of database files..."
115     q = DBConn().session().query(PoolFile).join(Location).order_by('path', 'location')
116
117     print "Missing files:"
118     db_files.clear()
119
120     for f in q.all():
121         filename = os.path.abspath(os.path.join(f.location.path, f.filename))
122         db_files[filename] = ""
123         if os.access(filename, os.R_OK) == 0:
124             if f.last_used:
125                 print "(last used: %s) %s" % (f.last_used, filename)
126             else:
127                 print "%s" % (filename)
128
129
130     filename = os.path.join(cnf["Dir::Override"], 'override.unreferenced')
131     if os.path.exists(filename):
132         f = utils.open_file(filename)
133         for filename in f.readlines():
134             filename = filename[:-1]
135             excluded[filename] = ""
136
137     print "Existent files not in db:"
138
139     os.path.walk(os.path.join(cnf["Dir::Root"], 'pool/'), process_dir, None)
140
141     print
142     print "%s wasted..." % (utils.size_type(waste))
143
144 ################################################################################
145
146 def check_dscs():
147     """
148     Parse every .dsc file in the archive and check for it's validity.
149     """
150
151     count = 0
152
153     for dsc_file in DBConn().session().query(DSCFile):
154         f = dsc_file.poolfile.fullpath
155         try:
156             utils.parse_changes(f, signing_rules=1, dsc_file=1)
157         except InvalidDscError, line:
158             utils.warn("syntax error in .dsc file %s" % f)
159             count += 1
160         except ChangesUnicodeError:
161             utils.warn("found invalid dsc file (%s), not properly utf-8 encoded" % f)
162             count += 1
163
164     if count:
165         utils.warn("Found %s invalid .dsc files." % (count))
166
167 ################################################################################
168
169 def check_override():
170     """
171     Check for missing overrides in stable and unstable.
172     """
173     session = DBConn().session()
174
175     for suite_name in [ "stable", "unstable" ]:
176         print suite_name
177         print "-" * len(suite_name)
178         print
179         suite = get_suite(suite_name)
180         q = session.execute("""
181 SELECT DISTINCT b.package FROM binaries b, bin_associations ba
182  WHERE b.id = ba.bin AND ba.suite = :suiteid AND NOT EXISTS
183        (SELECT 1 FROM override o WHERE o.suite = :suiteid AND o.package = b.package)"""
184                           % {'suiteid': suite.suite_id})
185
186         for j in q.fetchall():
187             print j[0]
188
189         q = session.execute("""
190 SELECT DISTINCT s.source FROM source s, src_associations sa
191   WHERE s.id = sa.source AND sa.suite = :suiteid AND NOT EXISTS
192        (SELECT 1 FROM override o WHERE o.suite = :suiteid and o.package = s.source)"""
193                           % {'suiteid': suite.suite_id})
194         for j in q.fetchall():
195             print j[0]
196
197 ################################################################################
198
199
200 def check_source_in_one_dir():
201     """
202     Ensure that the source files for any given package is all in one
203     directory so that 'apt-get source' works...
204     """
205
206     # Not the most enterprising method, but hey...
207     broken_count = 0
208
209     session = DBConn().session()
210
211     q = session.query(DBSource)
212     for s in q.all():
213         first_path = ""
214         first_filename = ""
215         broken = False
216
217         qf = session.query(PoolFile).join(Location).join(DSCFile).filter_by(source_id=s.source_id)
218         for f in qf.all():
219             # 0: path
220             # 1: filename
221             filename = os.path.join(f.location.path, f.filename)
222             path = os.path.dirname(filename)
223
224             if first_path == "":
225                 first_path = path
226                 first_filename = filename
227             elif first_path != path:
228                 symlink = path + '/' + os.path.basename(first_filename)
229                 if not os.path.exists(symlink):
230                     broken = True
231                     print "WOAH, we got a live one here... %s [%s] {%s}" % (filename, s.source_id, symlink)
232         if broken:
233             broken_count += 1
234
235     print "Found %d source packages where the source is not all in one directory." % (broken_count)
236
237 ################################################################################
238 def check_checksums():
239     """
240     Validate all files
241     """
242     print "Getting file information from database..."
243     q = DBConn().session().query(PoolFile)
244
245     print "Checking file checksums & sizes..."
246     for f in q:
247         filename = os.path.abspath(os.path.join(f.location.path, f.filename))
248
249         try:
250             fi = utils.open_file(filename)
251         except:
252             utils.warn("can't open '%s'." % (filename))
253             continue
254
255         size = os.stat(filename)[stat.ST_SIZE]
256         if size != f.filesize:
257             utils.warn("**WARNING** size mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, size, f.filesize))
258
259         md5sum = apt_pkg.md5sum(fi)
260         if md5sum != f.md5sum:
261             utils.warn("**WARNING** md5sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, md5sum, f.md5sum))
262
263         fi.seek(0)
264         sha1sum = apt_pkg.sha1sum(fi)
265         if sha1sum != f.sha1sum:
266             utils.warn("**WARNING** sha1sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha1sum, f.sha1sum))
267
268         fi.seek(0)
269         sha256sum = apt_pkg.sha256sum(fi)
270         if sha256sum != f.sha256sum:
271             utils.warn("**WARNING** sha256sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha256sum, f.sha256sum))
272
273     print "Done."
274
275 ################################################################################
276 #
277
278 def Ent(Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
279     global future_files
280
281     if MTime > current_time:
282         future_files[current_file] = MTime
283         print "%s: %s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % (current_file, Kind,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor)
284
285 def check_timestamps():
286     """
287     Check all files for timestamps in the future; common from hardware
288     (e.g. alpha) which have far-future dates as their default dates.
289     """
290
291     global current_file
292
293     q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.deb$'))
294
295     db_files.clear()
296     count = 0
297
298     for pf in q.all():
299         filename = os.path.abspath(os.path.join(pf.location.path, pf.filename))
300         if os.access(filename, os.R_OK):
301             f = utils.open_file(filename)
302             current_file = filename
303             sys.stderr.write("Processing %s.\n" % (filename))
304             apt_inst.debExtract(f, Ent, "control.tar.gz")
305             f.seek(0)
306             apt_inst.debExtract(f, Ent, "data.tar.gz")
307             count += 1
308
309     print "Checked %d files (out of %d)." % (count, len(db_files.keys()))
310
311 ################################################################################
312
313 def check_files_in_dsc():
314     """
315     Ensure each .dsc lists appropriate files in its Files field (according
316     to the format announced in its Format field).
317     """
318     count = 0
319
320     print "Building list of database files..."
321     q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.dsc$'))
322
323     if q.count() > 0:
324         print "Checking %d files..." % len(ql)
325     else:
326         print "No files to check."
327
328     for pf in q.all():
329         filename = os.path.abspath(os.path.join(pf.location.path + pf.filename))
330
331         try:
332             # NB: don't enforce .dsc syntax
333             dsc = utils.parse_changes(filename, dsc_file=1)
334         except:
335             utils.fubar("error parsing .dsc file '%s'." % (filename))
336
337         reasons = utils.check_dsc_files(filename, dsc)
338         for r in reasons:
339             utils.warn(r)
340
341         if len(reasons) > 0:
342             count += 1
343
344     if count:
345         utils.warn("Found %s invalid .dsc files." % (count))
346
347
348 ################################################################################
349
350 def validate_sources(suite, component):
351     """
352     Ensure files mentioned in Sources exist
353     """
354     filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suite, component)
355     print "Processing %s..." % (filename)
356     # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
357     (fd, temp_filename) = utils.temp_filename()
358     (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
359     if (result != 0):
360         sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
361         sys.exit(result)
362     sources = utils.open_file(temp_filename)
363     Sources = apt_pkg.ParseTagFile(sources)
364     while Sources.Step():
365         source = Sources.Section.Find('Package')
366         directory = Sources.Section.Find('Directory')
367         files = Sources.Section.Find('Files')
368         for i in files.split('\n'):
369             (md5, size, name) = i.split()
370             filename = "%s/%s/%s" % (Cnf["Dir::Root"], directory, name)
371             if not os.path.exists(filename):
372                 if directory.find("potato") == -1:
373                     print "W: %s missing." % (filename)
374                 else:
375                     pool_location = utils.poolify (source, component)
376                     pool_filename = "%s/%s/%s" % (Cnf["Dir::Pool"], pool_location, name)
377                     if not os.path.exists(pool_filename):
378                         print "E: %s missing (%s)." % (filename, pool_filename)
379                     else:
380                         # Create symlink
381                         pool_filename = os.path.normpath(pool_filename)
382                         filename = os.path.normpath(filename)
383                         src = utils.clean_symlink(pool_filename, filename, Cnf["Dir::Root"])
384                         print "Symlinking: %s -> %s" % (filename, src)
385                         #os.symlink(src, filename)
386     sources.close()
387     os.unlink(temp_filename)
388
389 ########################################
390
391 def validate_packages(suite, component, architecture):
392     """
393     Ensure files mentioned in Packages exist
394     """
395     filename = "%s/dists/%s/%s/binary-%s/Packages.gz" \
396                % (Cnf["Dir::Root"], suite, component, architecture)
397     print "Processing %s..." % (filename)
398     # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
399     (fd, temp_filename) = utils.temp_filename()
400     (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
401     if (result != 0):
402         sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
403         sys.exit(result)
404     packages = utils.open_file(temp_filename)
405     Packages = apt_pkg.ParseTagFile(packages)
406     while Packages.Step():
407         filename = "%s/%s" % (Cnf["Dir::Root"], Packages.Section.Find('Filename'))
408         if not os.path.exists(filename):
409             print "W: %s missing." % (filename)
410     packages.close()
411     os.unlink(temp_filename)
412
413 ########################################
414
415 def check_indices_files_exist():
416     """
417     Ensure files mentioned in Packages & Sources exist
418     """
419     for suite in [ "stable", "testing", "unstable" ]:
420         for component in Cnf.ValueList("Suite::%s::Components" % (suite)):
421             architectures = get_suite_architectures(suite)
422             for arch in [ i.arch_string.lower() for i in architectures ]:
423                 if arch == "source":
424                     validate_sources(suite, component)
425                 elif arch == "all":
426                     continue
427                 else:
428                     validate_packages(suite, component, arch)
429
430 ################################################################################
431
432 def check_files_not_symlinks():
433     """
434     Check files in the database aren't symlinks
435     """
436     print "Building list of database files... ",
437     before = time.time()
438     q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.dsc$'))
439
440     for pf in q.all():
441         filename = os.path.abspath(os.path.join(pf.location.path, pf.filename))
442         if os.access(filename, os.R_OK) == 0:
443             utils.warn("%s: doesn't exist." % (filename))
444         else:
445             if os.path.islink(filename):
446                 utils.warn("%s: is a symlink." % (filename))
447
448 ################################################################################
449
450 def chk_bd_process_dir (unused, dirname, filenames):
451     for name in filenames:
452         if not name.endswith(".dsc"):
453             continue
454         filename = os.path.abspath(dirname+'/'+name)
455         dsc = utils.parse_changes(filename, dsc_file=1)
456         for field_name in [ "build-depends", "build-depends-indep" ]:
457             field = dsc.get(field_name)
458             if field:
459                 try:
460                     apt_pkg.ParseSrcDepends(field)
461                 except:
462                     print "E: [%s] %s: %s" % (filename, field_name, field)
463                     pass
464
465 ################################################################################
466
467 def check_build_depends():
468     """ Validate build-dependencies of .dsc files in the archive """
469     cnf = Config()
470     os.path.walk(cnf["Dir::Root"], chk_bd_process_dir, None)
471
472 ################################################################################
473
474 def main ():
475     global db_files, waste, excluded
476
477     cnf = Config()
478
479     Arguments = [('h',"help","Check-Archive::Options::Help")]
480     for i in [ "help" ]:
481         if not cnf.has_key("Check-Archive::Options::%s" % (i)):
482             cnf["Check-Archive::Options::%s" % (i)] = ""
483
484     args = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
485
486     Options = cnf.SubTree("Check-Archive::Options")
487     if Options["Help"]:
488         usage()
489
490     if len(args) < 1:
491         utils.warn("dak check-archive requires at least one argument")
492         usage(1)
493     elif len(args) > 1:
494         utils.warn("dak check-archive accepts only one argument")
495         usage(1)
496     mode = args[0].lower()
497
498     # Initialize DB
499     DBConn()
500
501     if mode == "checksums":
502         check_checksums()
503     elif mode == "files":
504         check_files()
505     elif mode == "dsc-syntax":
506         check_dscs()
507     elif mode == "missing-overrides":
508         check_override()
509     elif mode == "source-in-one-dir":
510         check_source_in_one_dir()
511     elif mode == "timestamps":
512         check_timestamps()
513     elif mode == "files-in-dsc":
514         check_files_in_dsc()
515     elif mode == "validate-indices":
516         check_indices_files_exist()
517     elif mode == "files-not-symlinks":
518         check_files_not_symlinks()
519     elif mode == "validate-builddeps":
520         check_build_depends()
521     else:
522         utils.warn("unknown mode '%s'" % (mode))
523         usage(1)
524
525 ################################################################################
526
527 if __name__ == '__main__':
528     main()