3 """ Various different sanity checks
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
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.
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.
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
24 ################################################################################
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*''
31 ################################################################################
41 from daklib.dbconn import *
42 from daklib import utils
43 from daklib.regexes import re_issource
44 from daklib.config import Config
46 ################################################################################
48 db_files = {} #: Cache of filenames as known by the database
49 waste = 0.0 #: How many bytes are "wasted" by files not referenced in database
50 excluded = {} #: List of files which are excluded from files check
53 current_time = time.time() #: now()
55 ################################################################################
57 def usage(exit_code=0):
58 print """Usage: dak check-archive MODE
59 Run various sanity checks of the archive and/or database.
61 -h, --help show this help and exit.
63 The following MODEs are available:
65 checksums - validate the checksums stored in the database
66 files - check files in the database against what's in the archive
67 dsc-syntax - validate the syntax of .dsc files in the archive
68 missing-overrides - check for missing overrides
69 source-in-one-dir - ensure the source for each package is in one directory
70 timestamps - check for future timestamps in .deb's
71 files-in-dsc - ensure each .dsc references appropriate Files
72 validate-indices - ensure files mentioned in Packages & Sources exist
73 files-not-symlinks - check files in the database aren't symlinks
74 validate-builddeps - validate build-dependencies of .dsc files in the archive
78 ################################################################################
80 def process_dir (unused, dirname, filenames):
82 Process a directory and output every files name which is not listed already
83 in the C{filenames} or global C{excluded} dictionaries.
86 @param dirname: the directory to look at
89 @param filenames: Known filenames to ignore
91 global waste, db_files, excluded
93 if dirname.find('/disks-') != -1 or dirname.find('upgrade-') != -1:
95 # hack; can't handle .changes files
96 if dirname.find('proposed-updates') != -1:
98 for name in filenames:
99 filename = os.path.abspath(dirname+'/'+name)
100 filename = filename.replace('potato-proposed-updates', 'proposed-updates')
101 if os.path.isfile(filename) and not os.path.islink(filename) and not db_files.has_key(filename) and not excluded.has_key(filename):
102 waste += os.stat(filename)[stat.ST_SIZE]
103 print "%s" % (filename)
105 ################################################################################
109 Prepare the dictionary of existing filenames, then walk through the archive
110 pool/ directory to compare it.
116 print "Building list of database files..."
117 q = DBConn().session().query(PoolFile).join(Location).order_by('path', 'location')
119 print "Missing files:"
123 filename = os.path.abspath(f.location.path, f.filename)
124 db_files[filename] = ""
125 if os.access(filename, os.R_OK) == 0:
127 print "(last used: %s) %s" % (f.last_used, filename)
129 print "%s" % (filename)
132 filename = os.path.join(cnf["Dir::Override"], 'override.unreferenced')
133 if os.path.exists(filename):
134 f = utils.open_file(filename)
135 for filename in f.readlines():
136 filename = filename[:-1]
137 excluded[filename] = ""
139 print "Existent files not in db:"
141 os.path.walk(cnf["Dir::Root"] + 'pool/', process_dir, None)
144 print "%s wasted..." % (utils.size_type(waste))
146 ################################################################################
150 Parse every .dsc file in the archive and check for it's validity.
158 for component in cnf.SubTree("Component").List():
159 component = component.lower()
160 list_filename = '%s%s_%s_source.list' % (cnf["Dir::Lists"], suite, component)
161 list_file = utils.open_file(list_filename)
163 for line in list_file.readlines():
166 utils.parse_changes(f, signing_rules=1)
167 except InvalidDscError, line:
168 utils.warn("syntax error in .dsc file '%s', line %s." % (f, line))
170 except ChangesUnicodeError:
171 utils.warn("found invalid changes file, not properly utf-8 encoded")
175 utils.warn("Found %s invalid .dsc files." % (count))
177 ################################################################################
179 def check_override():
181 Check for missing overrides in stable and unstable.
183 session = DBConn().session()
185 for suite_name in [ "stable", "unstable" ]:
187 print "-" * len(suite_name)
189 suite = get_suite(suite)
191 SELECT DISTINCT b.package FROM binaries b, bin_associations ba
192 WHERE b.id = ba.bin AND ba.suite = :suiteid AND NOT EXISTS
193 (SELECT 1 FROM override o WHERE o.suite = :suiteid AND o.package = b.package)"""
194 % {'suiteid': suite.suite_id})
196 for j in q.fetchall():
200 SELECT DISTINCT s.source FROM source s, src_associations sa
201 WHERE s.id = sa.source AND sa.suite = :suiteid AND NOT EXISTS
202 (SELECT 1 FROM override o WHERE o.suite = :suiteid and o.package = s.source)"""
203 % {'suiteid': suite.suite_id})
204 for j in q.fetchall():
207 ################################################################################
210 def check_source_in_one_dir():
212 Ensure that the source files for any given package is all in one
213 directory so that 'apt-get source' works...
216 # Not the most enterprising method, but hey...
219 session = DBConn().session()
221 q = session.query(DBSource)
227 qf = session.query(PoolFile).join(Location).join(DSCFile).filter_by(source_id=s.source_id)
231 filename = os.path.join(f.location.path, f.filename)
232 path = os.path.dirname(filename)
236 first_filename = filename
237 elif first_path != path:
238 symlink = path + '/' + os.path.basename(first_filename)
239 if not os.path.exists(symlink):
241 print "WOAH, we got a live one here... %s [%s] {%s}" % (filename, s.source_id, symlink)
245 print "Found %d source packages where the source is not all in one directory." % (broken_count)
247 ################################################################################
248 def check_checksums():
252 print "Getting file information from database..."
253 q = DBConn().session().query(PoolFile)
255 print "Checking file checksums & sizes..."
257 filename = os.path.abspath(os.path.join(f.location.path, f.filename))
260 fi = utils.open_file(filename)
262 utils.warn("can't open '%s'." % (filename))
265 size = os.stat(filename)[stat.ST_SIZE]
266 if size != f.filesize:
267 utils.warn("**WARNING** size mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, size, f.filesize))
269 md5sum = apt_pkg.md5sum(fi)
270 if md5sum != f.md5sum:
271 utils.warn("**WARNING** md5sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, md5sum, f.md5sum))
274 sha1sum = apt_pkg.sha1sum(fi)
275 if sha1sum != f.sha1sum:
276 utils.warn("**WARNING** sha1sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha1sum, f.sha1sum))
279 sha256sum = apt_pkg.sha256sum(fi)
280 if sha256sum != f.sha256sum:
281 utils.warn("**WARNING** sha256sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha256sum, f.sha256sum))
285 ################################################################################
288 def Ent(Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
291 if MTime > current_time:
292 future_files[current_file] = MTime
293 print "%s: %s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % (current_file, Kind,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor)
295 def check_timestamps():
297 Check all files for timestamps in the future; common from hardware
298 (e.g. alpha) which have far-future dates as their default dates.
303 q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.deb$'))
309 filename = os.path.abspath(os.path.join(pf.location.path, pf.filename))
310 if os.access(filename, os.R_OK):
311 f = utils.open_file(filename)
312 current_file = filename
313 sys.stderr.write("Processing %s.\n" % (filename))
314 apt_inst.debExtract(f, Ent, "control.tar.gz")
316 apt_inst.debExtract(f, Ent, "data.tar.gz")
319 print "Checked %d files (out of %d)." % (count, len(db_files.keys()))
321 ################################################################################
323 def check_files_in_dsc():
325 Ensure each .dsc lists appropriate files in its Files field (according
326 to the format announced in its Format field).
330 print "Building list of database files..."
331 q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.dsc$'))
334 print "Checking %d files..." % len(ql)
336 print "No files to check."
339 filename = os.path.abspath(os.path.join(pf.location.path + pf.filename))
342 # NB: don't enforce .dsc syntax
343 dsc = utils.parse_changes(filename)
345 utils.fubar("error parsing .dsc file '%s'." % (filename))
347 reasons = utils.check_dsc_files(filename, dsc)
355 utils.warn("Found %s invalid .dsc files." % (count))
358 ################################################################################
360 def validate_sources(suite, component):
362 Ensure files mentioned in Sources exist
364 filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suite, component)
365 print "Processing %s..." % (filename)
366 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
367 (fd, temp_filename) = utils.temp_filename()
368 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
370 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
372 sources = utils.open_file(temp_filename)
373 Sources = apt_pkg.ParseTagFile(sources)
374 while Sources.Step():
375 source = Sources.Section.Find('Package')
376 directory = Sources.Section.Find('Directory')
377 files = Sources.Section.Find('Files')
378 for i in files.split('\n'):
379 (md5, size, name) = i.split()
380 filename = "%s/%s/%s" % (Cnf["Dir::Root"], directory, name)
381 if not os.path.exists(filename):
382 if directory.find("potato") == -1:
383 print "W: %s missing." % (filename)
385 pool_location = utils.poolify (source, component)
386 pool_filename = "%s/%s/%s" % (Cnf["Dir::Pool"], pool_location, name)
387 if not os.path.exists(pool_filename):
388 print "E: %s missing (%s)." % (filename, pool_filename)
391 pool_filename = os.path.normpath(pool_filename)
392 filename = os.path.normpath(filename)
393 src = utils.clean_symlink(pool_filename, filename, Cnf["Dir::Root"])
394 print "Symlinking: %s -> %s" % (filename, src)
395 #os.symlink(src, filename)
397 os.unlink(temp_filename)
399 ########################################
401 def validate_packages(suite, component, architecture):
403 Ensure files mentioned in Packages exist
405 filename = "%s/dists/%s/%s/binary-%s/Packages.gz" \
406 % (Cnf["Dir::Root"], suite, component, architecture)
407 print "Processing %s..." % (filename)
408 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
409 (fd, temp_filename) = utils.temp_filename()
410 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
412 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
414 packages = utils.open_file(temp_filename)
415 Packages = apt_pkg.ParseTagFile(packages)
416 while Packages.Step():
417 filename = "%s/%s" % (Cnf["Dir::Root"], Packages.Section.Find('Filename'))
418 if not os.path.exists(filename):
419 print "W: %s missing." % (filename)
421 os.unlink(temp_filename)
423 ########################################
425 def check_indices_files_exist():
427 Ensure files mentioned in Packages & Sources exist
429 for suite in [ "stable", "testing", "unstable" ]:
430 for component in Cnf.ValueList("Suite::%s::Components" % (suite)):
431 architectures = database.get_suite_architectures(suite)
432 for arch in [ i.lower() for i in architectures ]:
434 validate_sources(suite, component)
438 validate_packages(suite, component, arch)
440 ################################################################################
442 def check_files_not_symlinks():
444 Check files in the database aren't symlinks
446 print "Building list of database files... ",
448 q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.dsc$'))
451 filename = os.path.abspath(os.path.join(pf.location.path, pf.filename))
452 if os.access(filename, os.R_OK) == 0:
453 utils.warn("%s: doesn't exist." % (filename))
455 if os.path.islink(filename):
456 utils.warn("%s: is a symlink." % (filename))
458 ################################################################################
460 def chk_bd_process_dir (unused, dirname, filenames):
461 for name in filenames:
462 if not name.endswith(".dsc"):
464 filename = os.path.abspath(dirname+'/'+name)
465 dsc = utils.parse_changes(filename)
466 for field_name in [ "build-depends", "build-depends-indep" ]:
467 field = dsc.get(field_name)
470 apt_pkg.ParseSrcDepends(field)
472 print "E: [%s] %s: %s" % (filename, field_name, field)
475 ################################################################################
477 def check_build_depends():
478 """ Validate build-dependencies of .dsc files in the archive """
479 os.path.walk(cnf["Dir::Root"], chk_bd_process_dir, None)
481 ################################################################################
484 global db_files, waste, excluded
488 Arguments = [('h',"help","Check-Archive::Options::Help")]
490 if not cnf.has_key("Check-Archive::Options::%s" % (i)):
491 cnf["Check-Archive::Options::%s" % (i)] = ""
493 args = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
495 Options = cnf.SubTree("Check-Archive::Options")
500 utils.warn("dak check-archive requires at least one argument")
503 utils.warn("dak check-archive accepts only one argument")
505 mode = args[0].lower()
510 if mode == "checksums":
512 elif mode == "files":
514 elif mode == "dsc-syntax":
516 elif mode == "missing-overrides":
518 elif mode == "source-in-one-dir":
519 check_source_in_one_dir()
520 elif mode == "timestamps":
522 elif mode == "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()
531 utils.warn("unknown mode '%s'" % (mode))
534 ################################################################################
536 if __name__ == '__main__':