3 # Various different sanity checks
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006 James Troup <james@nocrew.org>
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 ################################################################################
22 # And, lo, a great and menacing voice rose from the depths, and with
23 # great wrath and vehemence it's voice boomed across the
24 # land... ``hehehehehehe... that *tickles*''
27 ################################################################################
29 import commands, os, pg, stat, sys, time
30 import apt_pkg, apt_inst
31 from daklib import database
32 from daklib import utils
34 ################################################################################
43 current_time = time.time()
45 ################################################################################
47 def usage(exit_code=0):
48 print """Usage: dak check-archive MODE
49 Run various sanity checks of the archive and/or database.
51 -h, --help show this help and exit.
53 The following MODEs are available:
55 checksums - validate the checksums stored in the database
56 files - check files in the database against what's in the archive
57 dsc-syntax - validate the syntax of .dsc files in the archive
58 missing-overrides - check for missing overrides
59 source-in-one-dir - ensure the source for each package is in one directory
60 timestamps - check for future timestamps in .deb's
61 tar-gz-in-dsc - ensure each .dsc lists a .tar.gz file
62 validate-indices - ensure files mentioned in Packages & Sources exist
63 files-not-symlinks - check files in the database aren't symlinks
64 validate-builddeps - validate build-dependencies of .dsc files in the archive
68 ################################################################################
70 def process_dir (unused, dirname, filenames):
71 global waste, db_files, excluded
73 if dirname.find('/disks-') != -1 or dirname.find('upgrade-') != -1:
75 # hack; can't handle .changes files
76 if dirname.find('proposed-updates') != -1:
78 for name in filenames:
79 filename = os.path.abspath(dirname+'/'+name)
80 filename = filename.replace('potato-proposed-updates', 'proposed-updates')
81 if os.path.isfile(filename) and not os.path.islink(filename) and not db_files.has_key(filename) and not excluded.has_key(filename):
82 waste += os.stat(filename)[stat.ST_SIZE]
83 print "%s" % (filename)
85 ################################################################################
90 print "Building list of database files..."
91 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")
94 print "Missing files:"
97 filename = os.path.abspath(i[0] + i[1])
98 db_files[filename] = ""
99 if os.access(filename, os.R_OK) == 0:
101 print "(last used: %s) %s" % (i[2], filename)
103 print "%s" % (filename)
106 filename = Cnf["Dir::Override"]+'override.unreferenced'
107 if os.path.exists(filename):
108 f = utils.open_file(filename)
109 for filename in f.readlines():
110 filename = filename[:-1]
111 excluded[filename] = ""
113 print "Existent files not in db:"
115 os.path.walk(Cnf["Dir::Root"]+'pool/', process_dir, None)
118 print "%s wasted..." % (utils.size_type(waste))
120 ################################################################################
125 for component in Cnf.SubTree("Component").List():
126 if component == "mixed":
128 component = component.lower()
129 list_filename = '%s%s_%s_source.list' % (Cnf["Dir::Lists"], suite, component)
130 list_file = utils.open_file(list_filename)
131 for line in list_file.readlines():
134 utils.parse_changes(f, signing_rules=1)
135 except InvalidDscError, line:
136 utils.warn("syntax error in .dsc file '%s', line %s." % (f, line))
140 utils.warn("Found %s invalid .dsc files." % (count))
142 ################################################################################
144 def check_override():
145 for suite in [ "stable", "unstable" ]:
149 suite_id = database.get_suite_id(suite)
150 q = projectB.query("""
151 SELECT DISTINCT b.package FROM binaries b, bin_associations ba
152 WHERE b.id = ba.bin AND ba.suite = %s AND NOT EXISTS
153 (SELECT 1 FROM override o WHERE o.suite = %s AND o.package = b.package)"""
154 % (suite_id, suite_id))
156 q = projectB.query("""
157 SELECT DISTINCT s.source FROM source s, src_associations sa
158 WHERE s.id = sa.source AND sa.suite = %s AND NOT EXISTS
159 (SELECT 1 FROM override o WHERE o.suite = %s and o.package = s.source)"""
160 % (suite_id, suite_id))
163 ################################################################################
165 # Ensure that the source files for any given package is all in one
166 # directory so that 'apt-get source' works...
168 def check_source_in_one_dir():
169 # Not the most enterprising method, but hey...
171 q = projectB.query("SELECT id FROM source;")
172 for i in q.getresult():
174 q2 = projectB.query("""
175 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"""
180 for j in q2.getresult():
181 filename = j[0] + j[1]
182 path = os.path.dirname(filename)
185 first_filename = filename
186 elif first_path != path:
187 symlink = path + '/' + os.path.basename(first_filename)
188 if not os.path.exists(symlink):
190 print "WOAH, we got a live one here... %s [%s] {%s}" % (filename, source_id, symlink)
193 print "Found %d source packages where the source is not all in one directory." % (broken_count)
195 ################################################################################
197 def check_checksums():
198 print "Getting file information from database..."
199 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")
202 print "Checking file checksums & sizes..."
204 filename = os.path.abspath(i[0] + i[1])
210 f = utils.open_file(filename)
212 utils.warn("can't open '%s'." % (filename))
214 md5sum = apt_pkg.md5sum(f)
215 size = os.stat(filename)[stat.ST_SIZE]
216 if md5sum != db_md5sum:
217 utils.warn("**WARNING** md5sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, md5sum, db_md5sum))
219 utils.warn("**WARNING** size mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, size, db_size))
220 # Until the main database is filled, we need to not spit 500,000 warnings
221 # every time we scan the archive. Yet another hack (TM) which can go away
222 # once this is all working
223 if db_sha1sum is not None and db_sha1sum != '':
225 sha1sum = apt_pkg.sha1sum(f)
226 if sha1sum != db_sha1sum:
227 utils.warn("**WARNING** sha1sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha1sum, db_sha1sum))
229 if db_sha256sum is not None and db_sha256sum != '':
231 sha256sum = apt_pkg.sha256sum(f)
232 if sha256sum != db_sha256sum:
233 utils.warn("**WARNING** sha256sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha256sum, db_sha256sum))
237 ################################################################################
239 # Check all files for timestamps in the future; common from hardware
240 # (e.g. alpha) which have far-future dates as their default dates.
242 def Ent(Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
245 if MTime > current_time:
246 future_files[current_file] = MTime
247 print "%s: %s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % (current_file, Kind,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor)
249 def check_timestamps():
252 q = projectB.query("SELECT l.path, f.filename FROM files f, location l WHERE f.location = l.id AND f.filename ~ '.deb$'")
257 filename = os.path.abspath(i[0] + i[1])
258 if os.access(filename, os.R_OK):
259 f = utils.open_file(filename)
260 current_file = filename
261 sys.stderr.write("Processing %s.\n" % (filename))
262 apt_inst.debExtract(f, Ent, "control.tar.gz")
264 apt_inst.debExtract(f, Ent, "data.tar.gz")
266 print "Checked %d files (out of %d)." % (count, len(db_files.keys()))
268 ################################################################################
270 def check_missing_tar_gz_in_dsc():
273 print "Building list of database files..."
274 q = projectB.query("SELECT l.path, f.filename FROM files f, location l WHERE f.location = l.id AND f.filename ~ '.dsc$'")
277 print "Checking %d files..." % len(ql)
279 print "No files to check."
281 filename = os.path.abspath(i[0] + i[1])
283 # NB: don't enforce .dsc syntax
284 dsc = utils.parse_changes(filename)
286 utils.fubar("error parsing .dsc file '%s'." % (filename))
287 dsc_files = utils.build_file_list(dsc, is_a_dsc=1)
289 for f in dsc_files.keys():
290 m = utils.re_issource.match(f)
292 utils.fubar("%s not recognised as source." % (f))
294 if ftype == "orig.tar.gz" or ftype == "tar.gz":
297 utils.warn("%s has no .tar.gz in the .dsc file." % (f))
301 utils.warn("Found %s invalid .dsc files." % (count))
304 ################################################################################
306 def validate_sources(suite, component):
307 filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suite, component)
308 print "Processing %s..." % (filename)
309 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
310 temp_filename = utils.temp_filename()
311 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
313 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
315 sources = utils.open_file(temp_filename)
316 Sources = apt_pkg.ParseTagFile(sources)
317 while Sources.Step():
318 source = Sources.Section.Find('Package')
319 directory = Sources.Section.Find('Directory')
320 files = Sources.Section.Find('Files')
321 for i in files.split('\n'):
322 (md5, size, name) = i.split()
323 filename = "%s/%s/%s" % (Cnf["Dir::Root"], directory, name)
324 if not os.path.exists(filename):
325 if directory.find("potato") == -1:
326 print "W: %s missing." % (filename)
328 pool_location = utils.poolify (source, component)
329 pool_filename = "%s/%s/%s" % (Cnf["Dir::Pool"], pool_location, name)
330 if not os.path.exists(pool_filename):
331 print "E: %s missing (%s)." % (filename, pool_filename)
334 pool_filename = os.path.normpath(pool_filename)
335 filename = os.path.normpath(filename)
336 src = utils.clean_symlink(pool_filename, filename, Cnf["Dir::Root"])
337 print "Symlinking: %s -> %s" % (filename, src)
338 #os.symlink(src, filename)
340 os.unlink(temp_filename)
342 ########################################
344 def validate_packages(suite, component, architecture):
345 filename = "%s/dists/%s/%s/binary-%s/Packages.gz" \
346 % (Cnf["Dir::Root"], suite, component, architecture)
347 print "Processing %s..." % (filename)
348 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
349 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 packages = utils.open_file(temp_filename)
355 Packages = apt_pkg.ParseTagFile(packages)
356 while Packages.Step():
357 filename = "%s/%s" % (Cnf["Dir::Root"], Packages.Section.Find('Filename'))
358 if not os.path.exists(filename):
359 print "W: %s missing." % (filename)
361 os.unlink(temp_filename)
363 ########################################
365 def check_indices_files_exist():
366 for suite in [ "stable", "testing", "unstable" ]:
367 for component in Cnf.ValueList("Suite::%s::Components" % (suite)):
368 architectures = Cnf.ValueList("Suite::%s::Architectures" % (suite))
369 for arch in [ i.lower() for i in architectures ]:
371 validate_sources(suite, component)
375 validate_packages(suite, component, arch)
377 ################################################################################
379 def check_files_not_symlinks():
380 print "Building list of database files... ",
382 q = projectB.query("SELECT l.path, f.filename, f.id FROM files f, location l WHERE f.location = l.id")
383 print "done. (%d seconds)" % (int(time.time()-before))
384 q_files = q.getresult()
387 filename = os.path.normpath(i[0] + i[1])
388 if os.access(filename, os.R_OK) == 0:
389 utils.warn("%s: doesn't exist." % (filename))
391 if os.path.islink(filename):
392 utils.warn("%s: is a symlink." % (filename))
394 ################################################################################
396 def chk_bd_process_dir (unused, dirname, filenames):
397 for name in filenames:
398 if not name.endswith(".dsc"):
400 filename = os.path.abspath(dirname+'/'+name)
401 dsc = utils.parse_changes(filename)
402 for field_name in [ "build-depends", "build-depends-indep" ]:
403 field = dsc.get(field_name)
406 apt_pkg.ParseSrcDepends(field)
408 print "E: [%s] %s: %s" % (filename, field_name, field)
411 ################################################################################
413 def check_build_depends():
414 os.path.walk(Cnf["Dir::Root"], chk_bd_process_dir, None)
416 ################################################################################
419 global Cnf, projectB, db_files, waste, excluded
421 Cnf = utils.get_conf()
422 Arguments = [('h',"help","Check-Archive::Options::Help")]
424 if not Cnf.has_key("Check-Archive::Options::%s" % (i)):
425 Cnf["Check-Archive::Options::%s" % (i)] = ""
427 args = apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
429 Options = Cnf.SubTree("Check-Archive::Options")
434 utils.warn("dak check-archive requires at least one argument")
437 utils.warn("dak check-archive accepts only one argument")
439 mode = args[0].lower()
441 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
442 database.init(Cnf, projectB)
444 if mode == "checksums":
446 elif mode == "files":
448 elif mode == "dsc-syntax":
450 elif mode == "missing-overrides":
452 elif mode == "source-in-one-dir":
453 check_source_in_one_dir()
454 elif mode == "timestamps":
456 elif mode == "tar-gz-in-dsc":
457 check_missing_tar_gz_in_dsc()
458 elif mode == "validate-indices":
459 check_indices_files_exist()
460 elif mode == "files-not-symlinks":
461 check_files_not_symlinks()
462 elif mode == "validate-builddeps":
463 check_build_depends()
465 utils.warn("unknown mode '%s'" % (mode))
468 ################################################################################
470 if __name__ == '__main__':