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 import database
42 from daklib import utils
43 from daklib.regexes import re_issource
45 ################################################################################
47 Cnf = None #: Configuration, apt_pkg.Configuration
48 projectB = None #: database connection, pgobject
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.
115 print "Building list of database files..."
116 q = projectB.query("SELECT l.path, f.filename, f.last_used FROM files f, location l WHERE f.location = l.id ORDER BY l.path, f.filename")
119 print "Missing files:"
122 filename = os.path.abspath(i[0] + i[1])
123 db_files[filename] = ""
124 if os.access(filename, os.R_OK) == 0:
126 print "(last used: %s) %s" % (i[2], filename)
128 print "%s" % (filename)
131 filename = 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] = ""
138 print "Existent files not in db:"
140 os.path.walk(Cnf["Dir::Root"]+'pool/', process_dir, None)
143 print "%s wasted..." % (utils.size_type(waste))
145 ################################################################################
149 Parse every .dsc file in the archive and check for it's validity.
153 for component in Cnf.SubTree("Component").List():
154 component = component.lower()
155 list_filename = '%s%s_%s_source.list' % (Cnf["Dir::Lists"], suite, component)
156 list_file = utils.open_file(list_filename)
157 for line in list_file.readlines():
160 utils.parse_changes(f, signing_rules=1)
161 except InvalidDscError, line:
162 utils.warn("syntax error in .dsc file '%s', line %s." % (f, line))
164 except ChangesUnicodeError:
165 utils.warn("found invalid changes file, not properly utf-8 encoded")
169 utils.warn("Found %s invalid .dsc files." % (count))
171 ################################################################################
173 def check_override():
175 Check for missing overrides in stable and unstable.
177 for suite in [ "stable", "unstable" ]:
181 suite_id = database.get_suite_id(suite)
182 q = projectB.query("""
183 SELECT DISTINCT b.package FROM binaries b, bin_associations ba
184 WHERE b.id = ba.bin AND ba.suite = %s AND NOT EXISTS
185 (SELECT 1 FROM override o WHERE o.suite = %s AND o.package = b.package)"""
186 % (suite_id, suite_id))
188 q = projectB.query("""
189 SELECT DISTINCT s.source FROM source s, src_associations sa
190 WHERE s.id = sa.source AND sa.suite = %s AND NOT EXISTS
191 (SELECT 1 FROM override o WHERE o.suite = %s and o.package = s.source)"""
192 % (suite_id, suite_id))
195 ################################################################################
198 def check_source_in_one_dir():
200 Ensure that the source files for any given package is all in one
201 directory so that 'apt-get source' works...
204 # Not the most enterprising method, but hey...
206 q = projectB.query("SELECT id FROM source;")
207 for i in q.getresult():
209 q2 = projectB.query("""
210 SELECT l.path, f.filename FROM files f, dsc_files df, location l WHERE df.source = %s AND f.id = df.file AND l.id = f.location"""
215 for j in q2.getresult():
216 filename = j[0] + j[1]
217 path = os.path.dirname(filename)
220 first_filename = filename
221 elif first_path != path:
222 symlink = path + '/' + os.path.basename(first_filename)
223 if not os.path.exists(symlink):
225 print "WOAH, we got a live one here... %s [%s] {%s}" % (filename, source_id, symlink)
228 print "Found %d source packages where the source is not all in one directory." % (broken_count)
230 ################################################################################
232 def check_checksums():
236 print "Getting file information from database..."
237 q = projectB.query("SELECT l.path, f.filename, f.md5sum, f.sha1sum, f.sha256sum, f.size FROM files f, location l WHERE f.location = l.id")
240 print "Checking file checksums & sizes..."
242 filename = os.path.abspath(i[0] + i[1])
248 f = utils.open_file(filename)
250 utils.warn("can't open '%s'." % (filename))
252 md5sum = apt_pkg.md5sum(f)
253 size = os.stat(filename)[stat.ST_SIZE]
254 if md5sum != db_md5sum:
255 utils.warn("**WARNING** md5sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, md5sum, db_md5sum))
257 utils.warn("**WARNING** size mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, size, db_size))
259 sha1sum = apt_pkg.sha1sum(f)
260 if sha1sum != db_sha1sum:
261 utils.warn("**WARNING** sha1sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha1sum, db_sha1sum))
264 sha256sum = apt_pkg.sha256sum(f)
265 if sha256sum != db_sha256sum:
266 utils.warn("**WARNING** sha256sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha256sum, db_sha256sum))
270 ################################################################################
273 def Ent(Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
276 if MTime > current_time:
277 future_files[current_file] = MTime
278 print "%s: %s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % (current_file, Kind,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor)
280 def check_timestamps():
282 Check all files for timestamps in the future; common from hardware
283 (e.g. alpha) which have far-future dates as their default dates.
288 q = projectB.query("SELECT l.path, f.filename FROM files f, location l WHERE f.location = l.id AND f.filename ~ '.deb$'")
293 filename = os.path.abspath(i[0] + i[1])
294 if os.access(filename, os.R_OK):
295 f = utils.open_file(filename)
296 current_file = filename
297 sys.stderr.write("Processing %s.\n" % (filename))
298 apt_inst.debExtract(f, Ent, "control.tar.gz")
300 apt_inst.debExtract(f, Ent, "data.tar.gz")
302 print "Checked %d files (out of %d)." % (count, len(db_files.keys()))
304 ################################################################################
306 def check_missing_tar_gz_in_dsc():
308 Ensure each .dsc lists a .tar.gz file
312 print "Building list of database files..."
313 q = projectB.query("SELECT l.path, f.filename FROM files f, location l WHERE f.location = l.id AND f.filename ~ '.dsc$'")
316 print "Checking %d files..." % len(ql)
318 print "No files to check."
320 filename = os.path.abspath(i[0] + i[1])
322 # NB: don't enforce .dsc syntax
323 dsc = utils.parse_changes(filename)
325 utils.fubar("error parsing .dsc file '%s'." % (filename))
326 dsc_files = utils.build_file_list(dsc, is_a_dsc=1)
328 for f in dsc_files.keys():
329 m = re_issource.match(f)
331 utils.fubar("%s not recognised as source." % (f))
333 if ftype == "orig.tar.gz" or ftype == "tar.gz":
336 utils.warn("%s has no .tar.gz in the .dsc file." % (f))
340 utils.warn("Found %s invalid .dsc files." % (count))
343 ################################################################################
345 def validate_sources(suite, component):
347 Ensure files mentioned in Sources exist
349 filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suite, component)
350 print "Processing %s..." % (filename)
351 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
352 (fd, temp_filename) = utils.temp_filename()
353 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
355 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
357 sources = utils.open_file(temp_filename)
358 Sources = apt_pkg.ParseTagFile(sources)
359 while Sources.Step():
360 source = Sources.Section.Find('Package')
361 directory = Sources.Section.Find('Directory')
362 files = Sources.Section.Find('Files')
363 for i in files.split('\n'):
364 (md5, size, name) = i.split()
365 filename = "%s/%s/%s" % (Cnf["Dir::Root"], directory, name)
366 if not os.path.exists(filename):
367 if directory.find("potato") == -1:
368 print "W: %s missing." % (filename)
370 pool_location = utils.poolify (source, component)
371 pool_filename = "%s/%s/%s" % (Cnf["Dir::Pool"], pool_location, name)
372 if not os.path.exists(pool_filename):
373 print "E: %s missing (%s)." % (filename, pool_filename)
376 pool_filename = os.path.normpath(pool_filename)
377 filename = os.path.normpath(filename)
378 src = utils.clean_symlink(pool_filename, filename, Cnf["Dir::Root"])
379 print "Symlinking: %s -> %s" % (filename, src)
380 #os.symlink(src, filename)
382 os.unlink(temp_filename)
384 ########################################
386 def validate_packages(suite, component, architecture):
388 Ensure files mentioned in Packages exist
390 filename = "%s/dists/%s/%s/binary-%s/Packages.gz" \
391 % (Cnf["Dir::Root"], suite, component, architecture)
392 print "Processing %s..." % (filename)
393 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
394 (fd, temp_filename) = utils.temp_filename()
395 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
397 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
399 packages = utils.open_file(temp_filename)
400 Packages = apt_pkg.ParseTagFile(packages)
401 while Packages.Step():
402 filename = "%s/%s" % (Cnf["Dir::Root"], Packages.Section.Find('Filename'))
403 if not os.path.exists(filename):
404 print "W: %s missing." % (filename)
406 os.unlink(temp_filename)
408 ########################################
410 def check_indices_files_exist():
412 Ensure files mentioned in Packages & Sources exist
414 for suite in [ "stable", "testing", "unstable" ]:
415 for component in Cnf.ValueList("Suite::%s::Components" % (suite)):
416 architectures = database.get_suite_architectures(suite)
417 for arch in [ i.lower() for i in architectures ]:
419 validate_sources(suite, component)
423 validate_packages(suite, component, arch)
425 ################################################################################
427 def check_files_not_symlinks():
429 Check files in the database aren't symlinks
431 print "Building list of database files... ",
433 q = projectB.query("SELECT l.path, f.filename, f.id FROM files f, location l WHERE f.location = l.id")
434 print "done. (%d seconds)" % (int(time.time()-before))
435 q_files = q.getresult()
438 filename = os.path.normpath(i[0] + i[1])
439 if os.access(filename, os.R_OK) == 0:
440 utils.warn("%s: doesn't exist." % (filename))
442 if os.path.islink(filename):
443 utils.warn("%s: is a symlink." % (filename))
445 ################################################################################
447 def chk_bd_process_dir (unused, dirname, filenames):
448 for name in filenames:
449 if not name.endswith(".dsc"):
451 filename = os.path.abspath(dirname+'/'+name)
452 dsc = utils.parse_changes(filename)
453 for field_name in [ "build-depends", "build-depends-indep" ]:
454 field = dsc.get(field_name)
457 apt_pkg.ParseSrcDepends(field)
459 print "E: [%s] %s: %s" % (filename, field_name, field)
462 ################################################################################
464 def check_build_depends():
465 """ Validate build-dependencies of .dsc files in the archive """
466 os.path.walk(Cnf["Dir::Root"], chk_bd_process_dir, None)
468 ################################################################################
471 global Cnf, projectB, db_files, waste, excluded
473 Cnf = utils.get_conf()
474 Arguments = [('h',"help","Check-Archive::Options::Help")]
476 if not Cnf.has_key("Check-Archive::Options::%s" % (i)):
477 Cnf["Check-Archive::Options::%s" % (i)] = ""
479 args = apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
481 Options = Cnf.SubTree("Check-Archive::Options")
486 utils.warn("dak check-archive requires at least one argument")
489 utils.warn("dak check-archive accepts only one argument")
491 mode = args[0].lower()
493 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
494 database.init(Cnf, projectB)
496 if mode == "checksums":
498 elif mode == "files":
500 elif mode == "dsc-syntax":
502 elif mode == "missing-overrides":
504 elif mode == "source-in-one-dir":
505 check_source_in_one_dir()
506 elif mode == "timestamps":
508 elif mode == "tar-gz-in-dsc":
509 check_missing_tar_gz_in_dsc()
510 elif mode == "validate-indices":
511 check_indices_files_exist()
512 elif mode == "files-not-symlinks":
513 check_files_not_symlinks()
514 elif mode == "validate-builddeps":
515 check_build_depends()
517 utils.warn("unknown mode '%s'" % (mode))
520 ################################################################################
522 if __name__ == '__main__':