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 ################################################################################
42 from daklib.dbconn import *
43 from daklib import utils
44 from daklib.regexes import re_issource
45 from daklib.config import Config
47 ################################################################################
49 db_files = {} #: Cache of filenames as known by the database
50 waste = 0.0 #: How many bytes are "wasted" by files not referenced in database
51 excluded = {} #: List of files which are excluded from files check
54 current_time = time.time() #: now()
56 ################################################################################
58 def usage(exit_code=0):
59 print """Usage: dak check-archive MODE
60 Run various sanity checks of the archive and/or database.
62 -h, --help show this help and exit.
64 The following MODEs are available:
66 checksums - validate the checksums stored in the database
67 files - check files in the database against what's in the archive
68 dsc-syntax - validate the syntax of .dsc files in the archive
69 missing-overrides - check for missing overrides
70 source-in-one-dir - ensure the source for each package is in one directory
71 timestamps - check for future timestamps in .deb's
72 tar-gz-in-dsc - ensure each .dsc lists a .tar.gz file
73 validate-indices - ensure files mentioned in Packages & Sources exist
74 files-not-symlinks - check files in the database aren't symlinks
75 validate-builddeps - validate build-dependencies of .dsc files in the archive
79 ################################################################################
81 def process_dir (unused, dirname, filenames):
83 Process a directory and output every files name which is not listed already
84 in the C{filenames} or global C{excluded} dictionaries.
87 @param dirname: the directory to look at
90 @param filenames: Known filenames to ignore
92 global waste, db_files, excluded
94 if dirname.find('/disks-') != -1 or dirname.find('upgrade-') != -1:
96 # hack; can't handle .changes files
97 if dirname.find('proposed-updates') != -1:
99 for name in filenames:
100 filename = os.path.abspath(dirname+'/'+name)
101 filename = filename.replace('potato-proposed-updates', 'proposed-updates')
102 if os.path.isfile(filename) and not os.path.islink(filename) and not db_files.has_key(filename) and not excluded.has_key(filename):
103 waste += os.stat(filename)[stat.ST_SIZE]
104 print "%s" % (filename)
106 ################################################################################
110 Prepare the dictionary of existing filenames, then walk through the archive
111 pool/ directory to compare it.
117 print "Building list of database files..."
118 q = DBConn().session().query(PoolFile).join(Location).order_by('path', 'location')
120 print "Missing files:"
124 filename = os.path.abspath(f.location.path, f.filename)
125 db_files[filename] = ""
126 if os.access(filename, os.R_OK) == 0:
128 print "(last used: %s) %s" % (f.last_used, filename)
130 print "%s" % (filename)
133 filename = os.path.join(cnf["Dir::Override"], 'override.unreferenced')
134 if os.path.exists(filename):
135 f = utils.open_file(filename)
136 for filename in f.readlines():
137 filename = filename[:-1]
138 excluded[filename] = ""
140 print "Existent files not in db:"
142 os.path.walk(cnf["Dir::Root"] + 'pool/', process_dir, None)
145 print "%s wasted..." % (utils.size_type(waste))
147 ################################################################################
151 Parse every .dsc file in the archive and check for it's validity.
159 for component in cnf.SubTree("Component").List():
160 component = component.lower()
161 list_filename = '%s%s_%s_source.list' % (cnf["Dir::Lists"], suite, component)
162 list_file = utils.open_file(list_filename)
164 for line in list_file.readlines():
167 utils.parse_changes(f, signing_rules=1)
168 except InvalidDscError, line:
169 utils.warn("syntax error in .dsc file '%s', line %s." % (f, line))
171 except ChangesUnicodeError:
172 utils.warn("found invalid changes file, not properly utf-8 encoded")
176 utils.warn("Found %s invalid .dsc files." % (count))
178 ################################################################################
180 def check_override():
182 Check for missing overrides in stable and unstable.
184 session = DBConn().session()
186 for suite_name in [ "stable", "unstable" ]:
188 print "-" * len(suite_name)
190 suite = get_suite(suite)
192 SELECT DISTINCT b.package FROM binaries b, bin_associations ba
193 WHERE b.id = ba.bin AND ba.suite = :suiteid AND NOT EXISTS
194 (SELECT 1 FROM override o WHERE o.suite = :suiteid AND o.package = b.package)"""
195 % {'suiteid': suite.suite_id})
201 SELECT DISTINCT s.source FROM source s, src_associations sa
202 WHERE s.id = sa.source AND sa.suite = :suiteid AND NOT EXISTS
203 (SELECT 1 FROM override o WHERE o.suite = :suiteid and o.package = s.source)"""
204 % {'suiteid': suite.suite_id})
208 ################################################################################
211 def check_source_in_one_dir():
213 Ensure that the source files for any given package is all in one
214 directory so that 'apt-get source' works...
217 # Not the most enterprising method, but hey...
220 session = DBConn().session()
222 q = session.query(DBSource)
228 qf = session.query(PoolFile).join(Location).join(DSCFile).filter_by(source_id=s.source_id)
232 filename = os.path.join(f.location.path, f.filename)
233 path = os.path.dirname(filename)
237 first_filename = filename
238 elif first_path != path:
239 symlink = path + '/' + os.path.basename(first_filename)
240 if not os.path.exists(symlink):
242 print "WOAH, we got a live one here... %s [%s] {%s}" % (filename, s.source_id, symlink)
246 print "Found %d source packages where the source is not all in one directory." % (broken_count)
248 ################################################################################
249 def check_checksums():
253 print "Getting file information from database..."
254 q = DBConn().session().query(PoolFile)
256 print "Checking file checksums & sizes..."
258 filename = os.path.abspath(os.path.join(f.location.path, f.filename))
261 fi = utils.open_file(filename)
263 utils.warn("can't open '%s'." % (filename))
266 size = os.stat(filename)[stat.ST_SIZE]
267 if size != f.filesize:
268 utils.warn("**WARNING** size mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, size, f.filesize))
270 md5sum = apt_pkg.md5sum(fi)
271 if md5sum != f.md5sum:
272 utils.warn("**WARNING** md5sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, md5sum, f.md5sum))
275 sha1sum = apt_pkg.sha1sum(fi)
276 if sha1sum != f.sha1sum:
277 utils.warn("**WARNING** sha1sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha1sum, f.sha1sum))
280 sha256sum = apt_pkg.sha256sum(fi)
281 if sha256sum != f.sha256sum:
282 utils.warn("**WARNING** sha256sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha256sum, f.sha256sum))
286 ################################################################################
289 def Ent(Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
292 if MTime > current_time:
293 future_files[current_file] = MTime
294 print "%s: %s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % (current_file, Kind,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor)
296 def check_timestamps():
298 Check all files for timestamps in the future; common from hardware
299 (e.g. alpha) which have far-future dates as their default dates.
304 q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.deb$'))
310 filename = os.path.abspath(os.path.join(pf.location.path, pf.filename))
311 if os.access(filename, os.R_OK):
312 f = utils.open_file(filename)
313 current_file = filename
314 sys.stderr.write("Processing %s.\n" % (filename))
315 apt_inst.debExtract(f, Ent, "control.tar.gz")
317 apt_inst.debExtract(f, Ent, "data.tar.gz")
320 print "Checked %d files (out of %d)." % (count, len(db_files.keys()))
322 ################################################################################
324 def check_missing_tar_gz_in_dsc():
326 Ensure each .dsc lists a .tar.gz file
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 dsc_files = utils.build_file_list(dsc, is_a_dsc=1)
350 for f in dsc_files.keys():
351 m = re_issource.match(f)
353 utils.fubar("%s not recognised as source." % (f))
355 if ftype == "orig.tar.gz" or ftype == "tar.gz":
359 utils.warn("%s has no .tar.gz in the .dsc file." % (f))
363 utils.warn("Found %s invalid .dsc files." % (count))
366 ################################################################################
368 def validate_sources(suite, component):
370 Ensure files mentioned in Sources exist
372 filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suite, component)
373 print "Processing %s..." % (filename)
374 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
375 (fd, temp_filename) = utils.temp_filename()
376 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
378 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
380 sources = utils.open_file(temp_filename)
381 Sources = apt_pkg.ParseTagFile(sources)
382 while Sources.Step():
383 source = Sources.Section.Find('Package')
384 directory = Sources.Section.Find('Directory')
385 files = Sources.Section.Find('Files')
386 for i in files.split('\n'):
387 (md5, size, name) = i.split()
388 filename = "%s/%s/%s" % (Cnf["Dir::Root"], directory, name)
389 if not os.path.exists(filename):
390 if directory.find("potato") == -1:
391 print "W: %s missing." % (filename)
393 pool_location = utils.poolify (source, component)
394 pool_filename = "%s/%s/%s" % (Cnf["Dir::Pool"], pool_location, name)
395 if not os.path.exists(pool_filename):
396 print "E: %s missing (%s)." % (filename, pool_filename)
399 pool_filename = os.path.normpath(pool_filename)
400 filename = os.path.normpath(filename)
401 src = utils.clean_symlink(pool_filename, filename, Cnf["Dir::Root"])
402 print "Symlinking: %s -> %s" % (filename, src)
403 #os.symlink(src, filename)
405 os.unlink(temp_filename)
407 ########################################
409 def validate_packages(suite, component, architecture):
411 Ensure files mentioned in Packages exist
413 filename = "%s/dists/%s/%s/binary-%s/Packages.gz" \
414 % (Cnf["Dir::Root"], suite, component, architecture)
415 print "Processing %s..." % (filename)
416 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
417 (fd, temp_filename) = utils.temp_filename()
418 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
420 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
422 packages = utils.open_file(temp_filename)
423 Packages = apt_pkg.ParseTagFile(packages)
424 while Packages.Step():
425 filename = "%s/%s" % (Cnf["Dir::Root"], Packages.Section.Find('Filename'))
426 if not os.path.exists(filename):
427 print "W: %s missing." % (filename)
429 os.unlink(temp_filename)
431 ########################################
433 def check_indices_files_exist():
435 Ensure files mentioned in Packages & Sources exist
437 for suite in [ "stable", "testing", "unstable" ]:
438 for component in Cnf.ValueList("Suite::%s::Components" % (suite)):
439 architectures = database.get_suite_architectures(suite)
440 for arch in [ i.lower() for i in architectures ]:
442 validate_sources(suite, component)
446 validate_packages(suite, component, arch)
448 ################################################################################
450 def check_files_not_symlinks():
452 Check files in the database aren't symlinks
454 print "Building list of database files... ",
456 q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.dsc$'))
459 filename = os.path.abspath(os.path.join(pf.location.path, pf.filename))
460 if os.access(filename, os.R_OK) == 0:
461 utils.warn("%s: doesn't exist." % (filename))
463 if os.path.islink(filename):
464 utils.warn("%s: is a symlink." % (filename))
466 ################################################################################
468 def chk_bd_process_dir (unused, dirname, filenames):
469 for name in filenames:
470 if not name.endswith(".dsc"):
472 filename = os.path.abspath(dirname+'/'+name)
473 dsc = utils.parse_changes(filename)
474 for field_name in [ "build-depends", "build-depends-indep" ]:
475 field = dsc.get(field_name)
478 apt_pkg.ParseSrcDepends(field)
480 print "E: [%s] %s: %s" % (filename, field_name, field)
483 ################################################################################
485 def check_build_depends():
486 """ Validate build-dependencies of .dsc files in the archive """
487 os.path.walk(cnf["Dir::Root"], chk_bd_process_dir, None)
489 ################################################################################
492 global db_files, waste, excluded
496 Arguments = [('h',"help","Check-Archive::Options::Help")]
498 if not cnf.has_key("Check-Archive::Options::%s" % (i)):
499 cnf["Check-Archive::Options::%s" % (i)] = ""
501 args = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
503 Options = cnf.SubTree("Check-Archive::Options")
508 utils.warn("dak check-archive requires at least one argument")
511 utils.warn("dak check-archive accepts only one argument")
513 mode = args[0].lower()
518 if mode == "checksums":
520 elif mode == "files":
522 elif mode == "dsc-syntax":
524 elif mode == "missing-overrides":
526 elif mode == "source-in-one-dir":
527 check_source_in_one_dir()
528 elif mode == "timestamps":
530 elif mode == "tar-gz-in-dsc":
531 check_missing_tar_gz_in_dsc()
532 elif mode == "validate-indices":
533 check_indices_files_exist()
534 elif mode == "files-not-symlinks":
535 check_files_not_symlinks()
536 elif mode == "validate-builddeps":
537 check_build_depends()
539 utils.warn("unknown mode '%s'" % (mode))
542 ################################################################################
544 if __name__ == '__main__':