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 if component == "mixed":
156 component = component.lower()
157 list_filename = '%s%s_%s_source.list' % (Cnf["Dir::Lists"], suite, component)
158 list_file = utils.open_file(list_filename)
159 for line in list_file.readlines():
162 utils.parse_changes(f, signing_rules=1)
163 except InvalidDscError, line:
164 utils.warn("syntax error in .dsc file '%s', line %s." % (f, line))
168 utils.warn("Found %s invalid .dsc files." % (count))
170 ################################################################################
172 def check_override():
174 Check for missing overrides in stable and unstable.
176 for suite in [ "stable", "unstable" ]:
180 suite_id = database.get_suite_id(suite)
181 q = projectB.query("""
182 SELECT DISTINCT b.package FROM binaries b, bin_associations ba
183 WHERE b.id = ba.bin AND ba.suite = %s AND NOT EXISTS
184 (SELECT 1 FROM override o WHERE o.suite = %s AND o.package = b.package)"""
185 % (suite_id, suite_id))
187 q = projectB.query("""
188 SELECT DISTINCT s.source FROM source s, src_associations sa
189 WHERE s.id = sa.source AND sa.suite = %s AND NOT EXISTS
190 (SELECT 1 FROM override o WHERE o.suite = %s and o.package = s.source)"""
191 % (suite_id, suite_id))
194 ################################################################################
197 def check_source_in_one_dir():
199 Ensure that the source files for any given package is all in one
200 directory so that 'apt-get source' works...
203 # Not the most enterprising method, but hey...
205 q = projectB.query("SELECT id FROM source;")
206 for i in q.getresult():
208 q2 = projectB.query("""
209 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"""
214 for j in q2.getresult():
215 filename = j[0] + j[1]
216 path = os.path.dirname(filename)
219 first_filename = filename
220 elif first_path != path:
221 symlink = path + '/' + os.path.basename(first_filename)
222 if not os.path.exists(symlink):
224 print "WOAH, we got a live one here... %s [%s] {%s}" % (filename, source_id, symlink)
227 print "Found %d source packages where the source is not all in one directory." % (broken_count)
229 ################################################################################
231 def check_checksums():
235 print "Getting file information from database..."
236 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")
239 print "Checking file checksums & sizes..."
241 filename = os.path.abspath(i[0] + i[1])
247 f = utils.open_file(filename)
249 utils.warn("can't open '%s'." % (filename))
251 md5sum = apt_pkg.md5sum(f)
252 size = os.stat(filename)[stat.ST_SIZE]
253 if md5sum != db_md5sum:
254 utils.warn("**WARNING** md5sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, md5sum, db_md5sum))
256 utils.warn("**WARNING** size mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, size, db_size))
258 sha1sum = apt_pkg.sha1sum(f)
259 if sha1sum != db_sha1sum:
260 utils.warn("**WARNING** sha1sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha1sum, db_sha1sum))
263 sha256sum = apt_pkg.sha256sum(f)
264 if sha256sum != db_sha256sum:
265 utils.warn("**WARNING** sha256sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha256sum, db_sha256sum))
269 ################################################################################
272 def Ent(Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
275 if MTime > current_time:
276 future_files[current_file] = MTime
277 print "%s: %s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % (current_file, Kind,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor)
279 def check_timestamps():
281 Check all files for timestamps in the future; common from hardware
282 (e.g. alpha) which have far-future dates as their default dates.
287 q = projectB.query("SELECT l.path, f.filename FROM files f, location l WHERE f.location = l.id AND f.filename ~ '.deb$'")
292 filename = os.path.abspath(i[0] + i[1])
293 if os.access(filename, os.R_OK):
294 f = utils.open_file(filename)
295 current_file = filename
296 sys.stderr.write("Processing %s.\n" % (filename))
297 apt_inst.debExtract(f, Ent, "control.tar.gz")
299 apt_inst.debExtract(f, Ent, "data.tar.gz")
301 print "Checked %d files (out of %d)." % (count, len(db_files.keys()))
303 ################################################################################
305 def check_missing_tar_gz_in_dsc():
307 Ensure each .dsc lists a .tar.gz file
311 print "Building list of database files..."
312 q = projectB.query("SELECT l.path, f.filename FROM files f, location l WHERE f.location = l.id AND f.filename ~ '.dsc$'")
315 print "Checking %d files..." % len(ql)
317 print "No files to check."
319 filename = os.path.abspath(i[0] + i[1])
321 # NB: don't enforce .dsc syntax
322 dsc = utils.parse_changes(filename)
324 utils.fubar("error parsing .dsc file '%s'." % (filename))
325 dsc_files = utils.build_file_list(dsc, is_a_dsc=1)
327 for f in dsc_files.keys():
328 m = re_issource.match(f)
330 utils.fubar("%s not recognised as source." % (f))
332 if ftype == "orig.tar.gz" or ftype == "tar.gz":
335 utils.warn("%s has no .tar.gz in the .dsc file." % (f))
339 utils.warn("Found %s invalid .dsc files." % (count))
342 ################################################################################
344 def validate_sources(suite, component):
346 Ensure files mentioned in Sources exist
348 filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suite, component)
349 print "Processing %s..." % (filename)
350 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
351 (fd, temp_filename) = utils.temp_filename()
352 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
354 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
356 sources = utils.open_file(temp_filename)
357 Sources = apt_pkg.ParseTagFile(sources)
358 while Sources.Step():
359 source = Sources.Section.Find('Package')
360 directory = Sources.Section.Find('Directory')
361 files = Sources.Section.Find('Files')
362 for i in files.split('\n'):
363 (md5, size, name) = i.split()
364 filename = "%s/%s/%s" % (Cnf["Dir::Root"], directory, name)
365 if not os.path.exists(filename):
366 if directory.find("potato") == -1:
367 print "W: %s missing." % (filename)
369 pool_location = utils.poolify (source, component)
370 pool_filename = "%s/%s/%s" % (Cnf["Dir::Pool"], pool_location, name)
371 if not os.path.exists(pool_filename):
372 print "E: %s missing (%s)." % (filename, pool_filename)
375 pool_filename = os.path.normpath(pool_filename)
376 filename = os.path.normpath(filename)
377 src = utils.clean_symlink(pool_filename, filename, Cnf["Dir::Root"])
378 print "Symlinking: %s -> %s" % (filename, src)
379 #os.symlink(src, filename)
381 os.unlink(temp_filename)
383 ########################################
385 def validate_packages(suite, component, architecture):
387 Ensure files mentioned in Packages exist
389 filename = "%s/dists/%s/%s/binary-%s/Packages.gz" \
390 % (Cnf["Dir::Root"], suite, component, architecture)
391 print "Processing %s..." % (filename)
392 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
393 (fd, temp_filename) = utils.temp_filename()
394 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
396 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
398 packages = utils.open_file(temp_filename)
399 Packages = apt_pkg.ParseTagFile(packages)
400 while Packages.Step():
401 filename = "%s/%s" % (Cnf["Dir::Root"], Packages.Section.Find('Filename'))
402 if not os.path.exists(filename):
403 print "W: %s missing." % (filename)
405 os.unlink(temp_filename)
407 ########################################
409 def check_indices_files_exist():
411 Ensure files mentioned in Packages & Sources exist
413 for suite in [ "stable", "testing", "unstable" ]:
414 for component in Cnf.ValueList("Suite::%s::Components" % (suite)):
415 architectures = database.get_suite_architectures(suite)
416 for arch in [ i.lower() for i in architectures ]:
418 validate_sources(suite, component)
422 validate_packages(suite, component, arch)
424 ################################################################################
426 def check_files_not_symlinks():
428 Check files in the database aren't symlinks
430 print "Building list of database files... ",
432 q = projectB.query("SELECT l.path, f.filename, f.id FROM files f, location l WHERE f.location = l.id")
433 print "done. (%d seconds)" % (int(time.time()-before))
434 q_files = q.getresult()
437 filename = os.path.normpath(i[0] + i[1])
438 if os.access(filename, os.R_OK) == 0:
439 utils.warn("%s: doesn't exist." % (filename))
441 if os.path.islink(filename):
442 utils.warn("%s: is a symlink." % (filename))
444 ################################################################################
446 def chk_bd_process_dir (unused, dirname, filenames):
447 for name in filenames:
448 if not name.endswith(".dsc"):
450 filename = os.path.abspath(dirname+'/'+name)
451 dsc = utils.parse_changes(filename)
452 for field_name in [ "build-depends", "build-depends-indep" ]:
453 field = dsc.get(field_name)
456 apt_pkg.ParseSrcDepends(field)
458 print "E: [%s] %s: %s" % (filename, field_name, field)
461 ################################################################################
463 def check_build_depends():
464 """ Validate build-dependencies of .dsc files in the archive """
465 os.path.walk(Cnf["Dir::Root"], chk_bd_process_dir, None)
467 ################################################################################
470 global Cnf, projectB, db_files, waste, excluded
472 Cnf = utils.get_conf()
473 Arguments = [('h',"help","Check-Archive::Options::Help")]
475 if not Cnf.has_key("Check-Archive::Options::%s" % (i)):
476 Cnf["Check-Archive::Options::%s" % (i)] = ""
478 args = apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
480 Options = Cnf.SubTree("Check-Archive::Options")
485 utils.warn("dak check-archive requires at least one argument")
488 utils.warn("dak check-archive accepts only one argument")
490 mode = args[0].lower()
492 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
493 database.init(Cnf, projectB)
495 if mode == "checksums":
497 elif mode == "files":
499 elif mode == "dsc-syntax":
501 elif mode == "missing-overrides":
503 elif mode == "source-in-one-dir":
504 check_source_in_one_dir()
505 elif mode == "timestamps":
507 elif mode == "tar-gz-in-dsc":
508 check_missing_tar_gz_in_dsc()
509 elif mode == "validate-indices":
510 check_indices_files_exist()
511 elif mode == "files-not-symlinks":
512 check_files_not_symlinks()
513 elif mode == "validate-builddeps":
514 check_build_depends()
516 utils.warn("unknown mode '%s'" % (mode))
519 ################################################################################
521 if __name__ == '__main__':