]> git.decadent.org.uk Git - dak.git/blob - dak/check_archive.py
merge from ftp-master
[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(dirname+'/'+name)
99         filename = filename.replace('potato-proposed-updates', 'proposed-updates')
100         if os.path.isfile(filename) and not os.path.islink(filename) and not db_files.has_key(filename) and not excluded.has_key(filename):
101             waste += os.stat(filename)[stat.ST_SIZE]
102             print "%s" % (filename)
103
104 ################################################################################
105
106 def check_files():
107     """
108     Prepare the dictionary of existing filenames, then walk through the archive
109     pool/ directory to compare it.
110     """
111     global db_files
112
113     cnf = Config()
114
115     print "Building list of database files..."
116     q = DBConn().session().query(PoolFile).join(Location).order_by('path', 'location')
117
118     print "Missing files:"
119     db_files.clear()
120
121     for f in q.all():
122         filename = os.path.abspath(f.location.path, f.filename)
123         db_files[filename] = ""
124         if os.access(filename, os.R_OK) == 0:
125             if f.last_used:
126                 print "(last used: %s) %s" % (f.last_used, filename)
127             else:
128                 print "%s" % (filename)
129
130
131     filename = os.path.join(cnf["Dir::Override"], 'override.unreferenced')
132     if os.path.exists(filename):
133         f = utils.open_file(filename)
134         for filename in f.readlines():
135             filename = filename[:-1]
136             excluded[filename] = ""
137
138     print "Existent files not in db:"
139
140     os.path.walk(cnf["Dir::Root"] + 'pool/', process_dir, None)
141
142     print
143     print "%s wasted..." % (utils.size_type(waste))
144
145 ################################################################################
146
147 def check_dscs():
148     """
149     Parse every .dsc file in the archive and check for it's validity.
150     """
151
152     cnf = Config()
153
154     count = 0
155     suite = 'unstable'
156
157     for component in cnf.SubTree("Component").List():
158         component = component.lower()
159         list_filename = '%s%s_%s_source.list' % (cnf["Dir::Lists"], suite, component)
160         list_file = utils.open_file(list_filename)
161
162         for line in list_file.readlines():
163             f = line[:-1]
164             try:
165                 utils.parse_changes(f, signing_rules=1)
166             except InvalidDscError, line:
167                 utils.warn("syntax error in .dsc file '%s', line %s." % (f, line))
168                 count += 1
169             except ChangesUnicodeError:
170                 utils.warn("found invalid changes file, not properly utf-8 encoded")
171                 count += 1
172
173     if count:
174         utils.warn("Found %s invalid .dsc files." % (count))
175
176 ################################################################################
177
178 def check_override():
179     """
180     Check for missing overrides in stable and unstable.
181     """
182     session = DBConn().session()
183
184     for suite_name in [ "stable", "unstable" ]:
185         print suite_name
186         print "-" * len(suite_name)
187         print
188         suite = get_suite(suite_name)
189         q = session.execute("""
190 SELECT DISTINCT b.package FROM binaries b, bin_associations ba
191  WHERE b.id = ba.bin AND ba.suite = :suiteid AND NOT EXISTS
192        (SELECT 1 FROM override o WHERE o.suite = :suiteid AND o.package = b.package)"""
193                           % {'suiteid': suite.suite_id})
194
195         for j in q.fetchall():
196             print j[0]
197
198         q = session.execute("""
199 SELECT DISTINCT s.source FROM source s, src_associations sa
200   WHERE s.id = sa.source AND sa.suite = :suiteid AND NOT EXISTS
201        (SELECT 1 FROM override o WHERE o.suite = :suiteid and o.package = s.source)"""
202                           % {'suiteid': suite.suite_id})
203         for j in q.fetchall():
204             print j[0]
205
206 ################################################################################
207
208
209 def check_source_in_one_dir():
210     """
211     Ensure that the source files for any given package is all in one
212     directory so that 'apt-get source' works...
213     """
214
215     # Not the most enterprising method, but hey...
216     broken_count = 0
217
218     session = DBConn().session()
219
220     q = session.query(DBSource)
221     for s in q.all():
222         first_path = ""
223         first_filename = ""
224         broken = False
225
226         qf = session.query(PoolFile).join(Location).join(DSCFile).filter_by(source_id=s.source_id)
227         for f in qf.all():
228             # 0: path
229             # 1: filename
230             filename = os.path.join(f.location.path, f.filename)
231             path = os.path.dirname(filename)
232
233             if first_path == "":
234                 first_path = path
235                 first_filename = filename
236             elif first_path != path:
237                 symlink = path + '/' + os.path.basename(first_filename)
238                 if not os.path.exists(symlink):
239                     broken = True
240                     print "WOAH, we got a live one here... %s [%s] {%s}" % (filename, s.source_id, symlink)
241         if broken:
242             broken_count += 1
243
244     print "Found %d source packages where the source is not all in one directory." % (broken_count)
245
246 ################################################################################
247 def check_checksums():
248     """
249     Validate all files
250     """
251     print "Getting file information from database..."
252     q = DBConn().session().query(PoolFile)
253
254     print "Checking file checksums & sizes..."
255     for f in q:
256         filename = os.path.abspath(os.path.join(f.location.path, f.filename))
257
258         try:
259             fi = utils.open_file(filename)
260         except:
261             utils.warn("can't open '%s'." % (filename))
262             continue
263
264         size = os.stat(filename)[stat.ST_SIZE]
265         if size != f.filesize:
266             utils.warn("**WARNING** size mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, size, f.filesize))
267
268         md5sum = apt_pkg.md5sum(fi)
269         if md5sum != f.md5sum:
270             utils.warn("**WARNING** md5sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, md5sum, f.md5sum))
271
272         fi.seek(0)
273         sha1sum = apt_pkg.sha1sum(fi)
274         if sha1sum != f.sha1sum:
275             utils.warn("**WARNING** sha1sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha1sum, f.sha1sum))
276
277         fi.seek(0)
278         sha256sum = apt_pkg.sha256sum(fi)
279         if sha256sum != f.sha256sum:
280             utils.warn("**WARNING** sha256sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha256sum, f.sha256sum))
281
282     print "Done."
283
284 ################################################################################
285 #
286
287 def Ent(Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
288     global future_files
289
290     if MTime > current_time:
291         future_files[current_file] = MTime
292         print "%s: %s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % (current_file, Kind,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor)
293
294 def check_timestamps():
295     """
296     Check all files for timestamps in the future; common from hardware
297     (e.g. alpha) which have far-future dates as their default dates.
298     """
299
300     global current_file
301
302     q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.deb$'))
303
304     db_files.clear()
305     count = 0
306
307     for pf in q.all():
308         filename = os.path.abspath(os.path.join(pf.location.path, pf.filename))
309         if os.access(filename, os.R_OK):
310             f = utils.open_file(filename)
311             current_file = filename
312             sys.stderr.write("Processing %s.\n" % (filename))
313             apt_inst.debExtract(f, Ent, "control.tar.gz")
314             f.seek(0)
315             apt_inst.debExtract(f, Ent, "data.tar.gz")
316             count += 1
317
318     print "Checked %d files (out of %d)." % (count, len(db_files.keys()))
319
320 ################################################################################
321
322 def check_files_in_dsc():
323     """
324     Ensure each .dsc lists appropriate files in its Files field (according
325     to the format announced in its Format field).
326     """
327     count = 0
328
329     print "Building list of database files..."
330     q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.dsc$'))
331
332     if q.count() > 0:
333         print "Checking %d files..." % len(ql)
334     else:
335         print "No files to check."
336
337     for pf in q.all():
338         filename = os.path.abspath(os.path.join(pf.location.path + pf.filename))
339
340         try:
341             # NB: don't enforce .dsc syntax
342             dsc = utils.parse_changes(filename)
343         except:
344             utils.fubar("error parsing .dsc file '%s'." % (filename))
345
346         reasons = utils.check_dsc_files(filename, dsc)
347         for r in reasons:
348             utils.warn(r)
349
350         if len(reasons) > 0:
351             count += 1
352
353     if count:
354         utils.warn("Found %s invalid .dsc files." % (count))
355
356
357 ################################################################################
358
359 def validate_sources(suite, component):
360     """
361     Ensure files mentioned in Sources exist
362     """
363     filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suite, component)
364     print "Processing %s..." % (filename)
365     # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
366     (fd, temp_filename) = utils.temp_filename()
367     (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
368     if (result != 0):
369         sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
370         sys.exit(result)
371     sources = utils.open_file(temp_filename)
372     Sources = apt_pkg.ParseTagFile(sources)
373     while Sources.Step():
374         source = Sources.Section.Find('Package')
375         directory = Sources.Section.Find('Directory')
376         files = Sources.Section.Find('Files')
377         for i in files.split('\n'):
378             (md5, size, name) = i.split()
379             filename = "%s/%s/%s" % (Cnf["Dir::Root"], directory, name)
380             if not os.path.exists(filename):
381                 if directory.find("potato") == -1:
382                     print "W: %s missing." % (filename)
383                 else:
384                     pool_location = utils.poolify (source, component)
385                     pool_filename = "%s/%s/%s" % (Cnf["Dir::Pool"], pool_location, name)
386                     if not os.path.exists(pool_filename):
387                         print "E: %s missing (%s)." % (filename, pool_filename)
388                     else:
389                         # Create symlink
390                         pool_filename = os.path.normpath(pool_filename)
391                         filename = os.path.normpath(filename)
392                         src = utils.clean_symlink(pool_filename, filename, Cnf["Dir::Root"])
393                         print "Symlinking: %s -> %s" % (filename, src)
394                         #os.symlink(src, filename)
395     sources.close()
396     os.unlink(temp_filename)
397
398 ########################################
399
400 def validate_packages(suite, component, architecture):
401     """
402     Ensure files mentioned in Packages exist
403     """
404     filename = "%s/dists/%s/%s/binary-%s/Packages.gz" \
405                % (Cnf["Dir::Root"], suite, component, architecture)
406     print "Processing %s..." % (filename)
407     # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
408     (fd, temp_filename) = utils.temp_filename()
409     (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
410     if (result != 0):
411         sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
412         sys.exit(result)
413     packages = utils.open_file(temp_filename)
414     Packages = apt_pkg.ParseTagFile(packages)
415     while Packages.Step():
416         filename = "%s/%s" % (Cnf["Dir::Root"], Packages.Section.Find('Filename'))
417         if not os.path.exists(filename):
418             print "W: %s missing." % (filename)
419     packages.close()
420     os.unlink(temp_filename)
421
422 ########################################
423
424 def check_indices_files_exist():
425     """
426     Ensure files mentioned in Packages & Sources exist
427     """
428     for suite in [ "stable", "testing", "unstable" ]:
429         for component in Cnf.ValueList("Suite::%s::Components" % (suite)):
430             architectures = get_suite_architectures(suite)
431             for arch in [ i.arch_string.lower() for i in architectures ]:
432                 if arch == "source":
433                     validate_sources(suite, component)
434                 elif arch == "all":
435                     continue
436                 else:
437                     validate_packages(suite, component, arch)
438
439 ################################################################################
440
441 def check_files_not_symlinks():
442     """
443     Check files in the database aren't symlinks
444     """
445     print "Building list of database files... ",
446     before = time.time()
447     q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.dsc$'))
448
449     for pf in q.all():
450         filename = os.path.abspath(os.path.join(pf.location.path, pf.filename))
451         if os.access(filename, os.R_OK) == 0:
452             utils.warn("%s: doesn't exist." % (filename))
453         else:
454             if os.path.islink(filename):
455                 utils.warn("%s: is a symlink." % (filename))
456
457 ################################################################################
458
459 def chk_bd_process_dir (unused, dirname, filenames):
460     for name in filenames:
461         if not name.endswith(".dsc"):
462             continue
463         filename = os.path.abspath(dirname+'/'+name)
464         dsc = utils.parse_changes(filename)
465         for field_name in [ "build-depends", "build-depends-indep" ]:
466             field = dsc.get(field_name)
467             if field:
468                 try:
469                     apt_pkg.ParseSrcDepends(field)
470                 except:
471                     print "E: [%s] %s: %s" % (filename, field_name, field)
472                     pass
473
474 ################################################################################
475
476 def check_build_depends():
477     """ Validate build-dependencies of .dsc files in the archive """
478     cnf = Config()
479     os.path.walk(cnf["Dir::Root"], chk_bd_process_dir, None)
480
481 ################################################################################
482
483 def main ():
484     global db_files, waste, excluded
485
486     cnf = Config()
487
488     Arguments = [('h',"help","Check-Archive::Options::Help")]
489     for i in [ "help" ]:
490         if not cnf.has_key("Check-Archive::Options::%s" % (i)):
491             cnf["Check-Archive::Options::%s" % (i)] = ""
492
493     args = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
494
495     Options = cnf.SubTree("Check-Archive::Options")
496     if Options["Help"]:
497         usage()
498
499     if len(args) < 1:
500         utils.warn("dak check-archive requires at least one argument")
501         usage(1)
502     elif len(args) > 1:
503         utils.warn("dak check-archive accepts only one argument")
504         usage(1)
505     mode = args[0].lower()
506
507     # Initialize DB
508     DBConn()
509
510     if mode == "checksums":
511         check_checksums()
512     elif mode == "files":
513         check_files()
514     elif mode == "dsc-syntax":
515         check_dscs()
516     elif mode == "missing-overrides":
517         check_override()
518     elif mode == "source-in-one-dir":
519         check_source_in_one_dir()
520     elif mode == "timestamps":
521         check_timestamps()
522     elif mode == "files-in-dsc":
523         check_files_in_dsc()
524     elif mode == "validate-indices":
525         check_indices_files_exist()
526     elif mode == "files-not-symlinks":
527         check_files_not_symlinks()
528     elif mode == "validate-builddeps":
529         check_build_depends()
530     else:
531         utils.warn("unknown mode '%s'" % (mode))
532         usage(1)
533
534 ################################################################################
535
536 if __name__ == '__main__':
537     main()