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))
166 utils.warn("Found %s invalid .dsc files." % (count))
168 ################################################################################
170 def check_override():
172 Check for missing overrides in stable and unstable.
174 for suite in [ "stable", "unstable" ]:
178 suite_id = database.get_suite_id(suite)
179 q = projectB.query("""
180 SELECT DISTINCT b.package FROM binaries b, bin_associations ba
181 WHERE b.id = ba.bin AND ba.suite = %s AND NOT EXISTS
182 (SELECT 1 FROM override o WHERE o.suite = %s AND o.package = b.package)"""
183 % (suite_id, suite_id))
185 q = projectB.query("""
186 SELECT DISTINCT s.source FROM source s, src_associations sa
187 WHERE s.id = sa.source AND sa.suite = %s AND NOT EXISTS
188 (SELECT 1 FROM override o WHERE o.suite = %s and o.package = s.source)"""
189 % (suite_id, suite_id))
192 ################################################################################
195 def check_source_in_one_dir():
197 Ensure that the source files for any given package is all in one
198 directory so that 'apt-get source' works...
201 # Not the most enterprising method, but hey...
203 q = projectB.query("SELECT id FROM source;")
204 for i in q.getresult():
206 q2 = projectB.query("""
207 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"""
212 for j in q2.getresult():
213 filename = j[0] + j[1]
214 path = os.path.dirname(filename)
217 first_filename = filename
218 elif first_path != path:
219 symlink = path + '/' + os.path.basename(first_filename)
220 if not os.path.exists(symlink):
222 print "WOAH, we got a live one here... %s [%s] {%s}" % (filename, source_id, symlink)
225 print "Found %d source packages where the source is not all in one directory." % (broken_count)
227 ################################################################################
229 def check_checksums():
233 print "Getting file information from database..."
234 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")
237 print "Checking file checksums & sizes..."
239 filename = os.path.abspath(i[0] + i[1])
245 f = utils.open_file(filename)
247 utils.warn("can't open '%s'." % (filename))
249 md5sum = apt_pkg.md5sum(f)
250 size = os.stat(filename)[stat.ST_SIZE]
251 if md5sum != db_md5sum:
252 utils.warn("**WARNING** md5sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, md5sum, db_md5sum))
254 utils.warn("**WARNING** size mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, size, db_size))
256 sha1sum = apt_pkg.sha1sum(f)
257 if sha1sum != db_sha1sum:
258 utils.warn("**WARNING** sha1sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha1sum, db_sha1sum))
261 sha256sum = apt_pkg.sha256sum(f)
262 if sha256sum != db_sha256sum:
263 utils.warn("**WARNING** sha256sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha256sum, db_sha256sum))
267 ################################################################################
270 def Ent(Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
273 if MTime > current_time:
274 future_files[current_file] = MTime
275 print "%s: %s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % (current_file, Kind,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor)
277 def check_timestamps():
279 Check all files for timestamps in the future; common from hardware
280 (e.g. alpha) which have far-future dates as their default dates.
285 q = projectB.query("SELECT l.path, f.filename FROM files f, location l WHERE f.location = l.id AND f.filename ~ '.deb$'")
290 filename = os.path.abspath(i[0] + i[1])
291 if os.access(filename, os.R_OK):
292 f = utils.open_file(filename)
293 current_file = filename
294 sys.stderr.write("Processing %s.\n" % (filename))
295 apt_inst.debExtract(f, Ent, "control.tar.gz")
297 apt_inst.debExtract(f, Ent, "data.tar.gz")
299 print "Checked %d files (out of %d)." % (count, len(db_files.keys()))
301 ################################################################################
303 def check_missing_tar_gz_in_dsc():
305 Ensure each .dsc lists a .tar.gz file
309 print "Building list of database files..."
310 q = projectB.query("SELECT l.path, f.filename FROM files f, location l WHERE f.location = l.id AND f.filename ~ '.dsc$'")
313 print "Checking %d files..." % len(ql)
315 print "No files to check."
317 filename = os.path.abspath(i[0] + i[1])
319 # NB: don't enforce .dsc syntax
320 dsc = utils.parse_changes(filename)
322 utils.fubar("error parsing .dsc file '%s'." % (filename))
323 dsc_files = utils.build_file_list(dsc, is_a_dsc=1)
325 for f in dsc_files.keys():
326 m = re_issource.match(f)
328 utils.fubar("%s not recognised as source." % (f))
330 if ftype == "orig.tar.gz" or ftype == "tar.gz":
333 utils.warn("%s has no .tar.gz in the .dsc file." % (f))
337 utils.warn("Found %s invalid .dsc files." % (count))
340 ################################################################################
342 def validate_sources(suite, component):
344 Ensure files mentioned in Sources exist
346 filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suite, component)
347 print "Processing %s..." % (filename)
348 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
349 (fd, temp_filename) = utils.temp_filename()
350 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
352 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
354 sources = utils.open_file(temp_filename)
355 Sources = apt_pkg.ParseTagFile(sources)
356 while Sources.Step():
357 source = Sources.Section.Find('Package')
358 directory = Sources.Section.Find('Directory')
359 files = Sources.Section.Find('Files')
360 for i in files.split('\n'):
361 (md5, size, name) = i.split()
362 filename = "%s/%s/%s" % (Cnf["Dir::Root"], directory, name)
363 if not os.path.exists(filename):
364 if directory.find("potato") == -1:
365 print "W: %s missing." % (filename)
367 pool_location = utils.poolify (source, component)
368 pool_filename = "%s/%s/%s" % (Cnf["Dir::Pool"], pool_location, name)
369 if not os.path.exists(pool_filename):
370 print "E: %s missing (%s)." % (filename, pool_filename)
373 pool_filename = os.path.normpath(pool_filename)
374 filename = os.path.normpath(filename)
375 src = utils.clean_symlink(pool_filename, filename, Cnf["Dir::Root"])
376 print "Symlinking: %s -> %s" % (filename, src)
377 #os.symlink(src, filename)
379 os.unlink(temp_filename)
381 ########################################
383 def validate_packages(suite, component, architecture):
385 Ensure files mentioned in Packages exist
387 filename = "%s/dists/%s/%s/binary-%s/Packages.gz" \
388 % (Cnf["Dir::Root"], suite, component, architecture)
389 print "Processing %s..." % (filename)
390 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
391 (fd, temp_filename) = utils.temp_filename()
392 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
394 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
396 packages = utils.open_file(temp_filename)
397 Packages = apt_pkg.ParseTagFile(packages)
398 while Packages.Step():
399 filename = "%s/%s" % (Cnf["Dir::Root"], Packages.Section.Find('Filename'))
400 if not os.path.exists(filename):
401 print "W: %s missing." % (filename)
403 os.unlink(temp_filename)
405 ########################################
407 def check_indices_files_exist():
409 Ensure files mentioned in Packages & Sources exist
411 for suite in [ "stable", "testing", "unstable" ]:
412 for component in Cnf.ValueList("Suite::%s::Components" % (suite)):
413 architectures = database.get_suite_architectures(suite)
414 for arch in [ i.lower() for i in architectures ]:
416 validate_sources(suite, component)
420 validate_packages(suite, component, arch)
422 ################################################################################
424 def check_files_not_symlinks():
426 Check files in the database aren't symlinks
428 print "Building list of database files... ",
430 q = projectB.query("SELECT l.path, f.filename, f.id FROM files f, location l WHERE f.location = l.id")
431 print "done. (%d seconds)" % (int(time.time()-before))
432 q_files = q.getresult()
435 filename = os.path.normpath(i[0] + i[1])
436 if os.access(filename, os.R_OK) == 0:
437 utils.warn("%s: doesn't exist." % (filename))
439 if os.path.islink(filename):
440 utils.warn("%s: is a symlink." % (filename))
442 ################################################################################
444 def chk_bd_process_dir (unused, dirname, filenames):
445 for name in filenames:
446 if not name.endswith(".dsc"):
448 filename = os.path.abspath(dirname+'/'+name)
449 dsc = utils.parse_changes(filename)
450 for field_name in [ "build-depends", "build-depends-indep" ]:
451 field = dsc.get(field_name)
454 apt_pkg.ParseSrcDepends(field)
456 print "E: [%s] %s: %s" % (filename, field_name, field)
459 ################################################################################
461 def check_build_depends():
462 """ Validate build-dependencies of .dsc files in the archive """
463 os.path.walk(Cnf["Dir::Root"], chk_bd_process_dir, None)
465 ################################################################################
468 global Cnf, projectB, db_files, waste, excluded
470 Cnf = utils.get_conf()
471 Arguments = [('h',"help","Check-Archive::Options::Help")]
473 if not Cnf.has_key("Check-Archive::Options::%s" % (i)):
474 Cnf["Check-Archive::Options::%s" % (i)] = ""
476 args = apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
478 Options = Cnf.SubTree("Check-Archive::Options")
483 utils.warn("dak check-archive requires at least one argument")
486 utils.warn("dak check-archive accepts only one argument")
488 mode = args[0].lower()
490 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
491 database.init(Cnf, projectB)
493 if mode == "checksums":
495 elif mode == "files":
497 elif mode == "dsc-syntax":
499 elif mode == "missing-overrides":
501 elif mode == "source-in-one-dir":
502 check_source_in_one_dir()
503 elif mode == "timestamps":
505 elif mode == "tar-gz-in-dsc":
506 check_missing_tar_gz_in_dsc()
507 elif mode == "validate-indices":
508 check_indices_files_exist()
509 elif mode == "files-not-symlinks":
510 check_files_not_symlinks()
511 elif mode == "validate-builddeps":
512 check_build_depends()
514 utils.warn("unknown mode '%s'" % (mode))
517 ################################################################################
519 if __name__ == '__main__':