]> git.decadent.org.uk Git - dak.git/blob - dak/check_archive.py
utf-8
[dak.git] / dak / check_archive.py
1 #!/usr/bin/env python
2
3 """ Various different sanity checks
4
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
8 """
9
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.
14
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.
19
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
23
24 ################################################################################
25
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*''
29 #                                                       -- aj on IRC
30
31 ################################################################################
32
33 import commands
34 import os
35 import pg
36 import stat
37 import sys
38 import time
39 import apt_pkg
40 import apt_inst
41 from daklib import database
42 from daklib import utils
43 from daklib.regexes import re_issource
44
45 ################################################################################
46
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
52 current_file = None
53 future_files = {}
54 current_time = time.time()     #: now()
55
56 ################################################################################
57
58 def usage(exit_code=0):
59     print """Usage: dak check-archive MODE
60 Run various sanity checks of the archive and/or database.
61
62   -h, --help                show this help and exit.
63
64 The following MODEs are available:
65
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
76 """
77     sys.exit(exit_code)
78
79 ################################################################################
80
81 def process_dir (unused, dirname, filenames):
82     """
83     Process a directory and output every files name which is not listed already
84     in the C{filenames} or global C{excluded} dictionaries.
85
86     @type dirname: string
87     @param dirname: the directory to look at
88
89     @type filenames: dict
90     @param filenames: Known filenames to ignore
91     """
92     global waste, db_files, excluded
93
94     if dirname.find('/disks-') != -1 or dirname.find('upgrade-') != -1:
95         return
96     # hack; can't handle .changes files
97     if dirname.find('proposed-updates') != -1:
98         return
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)
105
106 ################################################################################
107
108 def check_files():
109     """
110     Prepare the dictionary of existing filenames, then walk through the archive
111     pool/ directory to compare it.
112     """
113     global db_files
114
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")
117     ql = q.getresult()
118
119     print "Missing files:"
120     db_files.clear()
121     for i in ql:
122         filename = os.path.abspath(i[0] + i[1])
123         db_files[filename] = ""
124         if os.access(filename, os.R_OK) == 0:
125             if i[2]:
126                 print "(last used: %s) %s" % (i[2], filename)
127             else:
128                 print "%s" % (filename)
129
130
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] = ""
137
138     print "Existent files not in db:"
139
140     os.path.walk(Cnf["Dir::Root"]+'pool/', process_dir, None)
141
142     print
143     print "%s wasted..." % (utils.size_type(waste))
144
145 ################################################################################
146
147 def check_dscs():
148     """
149     Parse every .dsc file in the archive and check for it's validity.
150     """
151     count = 0
152     suite = 'unstable'
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():
158             f = line[:-1]
159             try:
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))
163                 count += 1
164             except ChangesUnicodeError:
165                 utils.warn("found invalid changes file, not properly utf-8 encoded")
166                 count += 1
167
168     if count:
169         utils.warn("Found %s invalid .dsc files." % (count))
170
171 ################################################################################
172
173 def check_override():
174     """
175     Check for missing overrides in stable and unstable.
176     """
177     for suite in [ "stable", "unstable" ]:
178         print suite
179         print "-"*len(suite)
180         print
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))
187         print q
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))
193         print q
194
195 ################################################################################
196
197
198 def check_source_in_one_dir():
199     """
200     Ensure that the source files for any given package is all in one
201     directory so that 'apt-get source' works...
202     """
203
204     # Not the most enterprising method, but hey...
205     broken_count = 0
206     q = projectB.query("SELECT id FROM source;")
207     for i in q.getresult():
208         source_id = i[0]
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"""
211                             % (source_id))
212         first_path = ""
213         first_filename = ""
214         broken = 0
215         for j in q2.getresult():
216             filename = j[0] + j[1]
217             path = os.path.dirname(filename)
218             if first_path == "":
219                 first_path = path
220                 first_filename = filename
221             elif first_path != path:
222                 symlink = path + '/' + os.path.basename(first_filename)
223                 if not os.path.exists(symlink):
224                     broken = 1
225                     print "WOAH, we got a live one here... %s [%s] {%s}" % (filename, source_id, symlink)
226         if broken:
227             broken_count += 1
228     print "Found %d source packages where the source is not all in one directory." % (broken_count)
229
230 ################################################################################
231
232 def check_checksums():
233     """
234     Validate all files
235     """
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")
238     ql = q.getresult()
239
240     print "Checking file checksums & sizes..."
241     for i in ql:
242         filename = os.path.abspath(i[0] + i[1])
243         db_md5sum = i[2]
244         db_sha1sum = i[3]
245         db_sha256sum = i[4]
246         db_size = int(i[5])
247         try:
248             f = utils.open_file(filename)
249         except:
250             utils.warn("can't open '%s'." % (filename))
251             continue
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))
256         if size != db_size:
257             utils.warn("**WARNING** size mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, size, db_size))
258         f.seek(0)
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))
262
263         f.seek(0)
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))
267
268     print "Done."
269
270 ################################################################################
271 #
272
273 def Ent(Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
274     global future_files
275
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)
279
280 def check_timestamps():
281     """
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.
284     """
285
286     global current_file
287
288     q = projectB.query("SELECT l.path, f.filename FROM files f, location l WHERE f.location = l.id AND f.filename ~ '.deb$'")
289     ql = q.getresult()
290     db_files.clear()
291     count = 0
292     for i in ql:
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")
299             f.seek(0)
300             apt_inst.debExtract(f, Ent, "data.tar.gz")
301             count += 1
302     print "Checked %d files (out of %d)." % (count, len(db_files.keys()))
303
304 ################################################################################
305
306 def check_missing_tar_gz_in_dsc():
307     """
308     Ensure each .dsc lists a .tar.gz file
309     """
310     count = 0
311
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$'")
314     ql = q.getresult()
315     if ql:
316         print "Checking %d files..." % len(ql)
317     else:
318         print "No files to check."
319     for i in ql:
320         filename = os.path.abspath(i[0] + i[1])
321         try:
322             # NB: don't enforce .dsc syntax
323             dsc = utils.parse_changes(filename)
324         except:
325             utils.fubar("error parsing .dsc file '%s'." % (filename))
326         dsc_files = utils.build_file_list(dsc, is_a_dsc=1)
327         has_tar = 0
328         for f in dsc_files.keys():
329             m = re_issource.match(f)
330             if not m:
331                 utils.fubar("%s not recognised as source." % (f))
332             ftype = m.group(3)
333             if ftype == "orig.tar.gz" or ftype == "tar.gz":
334                 has_tar = 1
335         if not has_tar:
336             utils.warn("%s has no .tar.gz in the .dsc file." % (f))
337             count += 1
338
339     if count:
340         utils.warn("Found %s invalid .dsc files." % (count))
341
342
343 ################################################################################
344
345 def validate_sources(suite, component):
346     """
347     Ensure files mentioned in Sources exist
348     """
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))
354     if (result != 0):
355         sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
356         sys.exit(result)
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)
369                 else:
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)
374                     else:
375                         # Create symlink
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)
381     sources.close()
382     os.unlink(temp_filename)
383
384 ########################################
385
386 def validate_packages(suite, component, architecture):
387     """
388     Ensure files mentioned in Packages exist
389     """
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))
396     if (result != 0):
397         sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
398         sys.exit(result)
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)
405     packages.close()
406     os.unlink(temp_filename)
407
408 ########################################
409
410 def check_indices_files_exist():
411     """
412     Ensure files mentioned in Packages & Sources exist
413     """
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 ]:
418                 if arch == "source":
419                     validate_sources(suite, component)
420                 elif arch == "all":
421                     continue
422                 else:
423                     validate_packages(suite, component, arch)
424
425 ################################################################################
426
427 def check_files_not_symlinks():
428     """
429     Check files in the database aren't symlinks
430     """
431     print "Building list of database files... ",
432     before = time.time()
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()
436
437     for i in q_files:
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))
441         else:
442             if os.path.islink(filename):
443                 utils.warn("%s: is a symlink." % (filename))
444
445 ################################################################################
446
447 def chk_bd_process_dir (unused, dirname, filenames):
448     for name in filenames:
449         if not name.endswith(".dsc"):
450             continue
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)
455             if field:
456                 try:
457                     apt_pkg.ParseSrcDepends(field)
458                 except:
459                     print "E: [%s] %s: %s" % (filename, field_name, field)
460                     pass
461
462 ################################################################################
463
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)
467
468 ################################################################################
469
470 def main ():
471     global Cnf, projectB, db_files, waste, excluded
472
473     Cnf = utils.get_conf()
474     Arguments = [('h',"help","Check-Archive::Options::Help")]
475     for i in [ "help" ]:
476         if not Cnf.has_key("Check-Archive::Options::%s" % (i)):
477             Cnf["Check-Archive::Options::%s" % (i)] = ""
478
479     args = apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
480
481     Options = Cnf.SubTree("Check-Archive::Options")
482     if Options["Help"]:
483         usage()
484
485     if len(args) < 1:
486         utils.warn("dak check-archive requires at least one argument")
487         usage(1)
488     elif len(args) > 1:
489         utils.warn("dak check-archive accepts only one argument")
490         usage(1)
491     mode = args[0].lower()
492
493     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
494     database.init(Cnf, projectB)
495
496     if mode == "checksums":
497         check_checksums()
498     elif mode == "files":
499         check_files()
500     elif mode == "dsc-syntax":
501         check_dscs()
502     elif mode == "missing-overrides":
503         check_override()
504     elif mode == "source-in-one-dir":
505         check_source_in_one_dir()
506     elif mode == "timestamps":
507         check_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()
516     else:
517         utils.warn("unknown mode '%s'" % (mode))
518         usage(1)
519
520 ################################################################################
521
522 if __name__ == '__main__':
523     main()