]> git.decadent.org.uk Git - dak.git/blob - dak/check_archive.py
docstrings fun
[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 filename: dict
90     @param filename: 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         if component == "mixed":
155             continue
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():
160             f = line[:-1]
161             try:
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))
165                 count += 1
166
167     if count:
168         utils.warn("Found %s invalid .dsc files." % (count))
169
170 ################################################################################
171
172 def check_override():
173     """
174     Check for missing overrides in stable and unstable.
175     """
176     for suite in [ "stable", "unstable" ]:
177         print suite
178         print "-"*len(suite)
179         print
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))
186         print q
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))
192         print q
193
194 ################################################################################
195
196
197 def check_source_in_one_dir():
198     """
199     Ensure that the source files for any given package is all in one
200     directory so that 'apt-get source' works...
201     """
202
203     # Not the most enterprising method, but hey...
204     broken_count = 0
205     q = projectB.query("SELECT id FROM source;")
206     for i in q.getresult():
207         source_id = i[0]
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"""
210                             % (source_id))
211         first_path = ""
212         first_filename = ""
213         broken = 0
214         for j in q2.getresult():
215             filename = j[0] + j[1]
216             path = os.path.dirname(filename)
217             if first_path == "":
218                 first_path = path
219                 first_filename = filename
220             elif first_path != path:
221                 symlink = path + '/' + os.path.basename(first_filename)
222                 if not os.path.exists(symlink):
223                     broken = 1
224                     print "WOAH, we got a live one here... %s [%s] {%s}" % (filename, source_id, symlink)
225         if broken:
226             broken_count += 1
227     print "Found %d source packages where the source is not all in one directory." % (broken_count)
228
229 ################################################################################
230
231 def check_checksums():
232     """
233     Validate all files
234     """
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")
237     ql = q.getresult()
238
239     print "Checking file checksums & sizes..."
240     for i in ql:
241         filename = os.path.abspath(i[0] + i[1])
242         db_md5sum = i[2]
243         db_sha1sum = i[3]
244         db_sha256sum = i[4]
245         db_size = int(i[5])
246         try:
247             f = utils.open_file(filename)
248         except:
249             utils.warn("can't open '%s'." % (filename))
250             continue
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))
255         if size != db_size:
256             utils.warn("**WARNING** size mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, size, db_size))
257         f.seek(0)
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))
261
262         f.seek(0)
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))
266
267     print "Done."
268
269 ################################################################################
270 #
271
272 def Ent(Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
273     global future_files
274
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)
278
279 def check_timestamps():
280     """
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.
283     """
284
285     global current_file
286
287     q = projectB.query("SELECT l.path, f.filename FROM files f, location l WHERE f.location = l.id AND f.filename ~ '.deb$'")
288     ql = q.getresult()
289     db_files.clear()
290     count = 0
291     for i in ql:
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")
298             f.seek(0)
299             apt_inst.debExtract(f, Ent, "data.tar.gz")
300             count += 1
301     print "Checked %d files (out of %d)." % (count, len(db_files.keys()))
302
303 ################################################################################
304
305 def check_missing_tar_gz_in_dsc():
306     """
307     Ensure each .dsc lists a .tar.gz file
308     """
309     count = 0
310
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$'")
313     ql = q.getresult()
314     if ql:
315         print "Checking %d files..." % len(ql)
316     else:
317         print "No files to check."
318     for i in ql:
319         filename = os.path.abspath(i[0] + i[1])
320         try:
321             # NB: don't enforce .dsc syntax
322             dsc = utils.parse_changes(filename)
323         except:
324             utils.fubar("error parsing .dsc file '%s'." % (filename))
325         dsc_files = utils.build_file_list(dsc, is_a_dsc=1)
326         has_tar = 0
327         for f in dsc_files.keys():
328             m = re_issource.match(f)
329             if not m:
330                 utils.fubar("%s not recognised as source." % (f))
331             ftype = m.group(3)
332             if ftype == "orig.tar.gz" or ftype == "tar.gz":
333                 has_tar = 1
334         if not has_tar:
335             utils.warn("%s has no .tar.gz in the .dsc file." % (f))
336             count += 1
337
338     if count:
339         utils.warn("Found %s invalid .dsc files." % (count))
340
341
342 ################################################################################
343
344 def validate_sources(suite, component):
345     """
346     Ensure files mentioned in Sources exist
347     """
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))
353     if (result != 0):
354         sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
355         sys.exit(result)
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)
368                 else:
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)
373                     else:
374                         # Create symlink
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)
380     sources.close()
381     os.unlink(temp_filename)
382
383 ########################################
384
385 def validate_packages(suite, component, architecture):
386     """
387     Ensure files mentioned in Packages exist
388     """
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))
395     if (result != 0):
396         sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
397         sys.exit(result)
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)
404     packages.close()
405     os.unlink(temp_filename)
406
407 ########################################
408
409 def check_indices_files_exist():
410     """
411     Ensure files mentioned in Packages & Sources exist
412     """
413     for suite in [ "stable", "testing", "unstable" ]:
414         for component in Cnf.ValueList("Suite::%s::Components" % (suite)):
415             architectures = Cnf.ValueList("Suite::%s::Architectures" % (suite))
416             for arch in [ i.lower() for i in architectures ]:
417                 if arch == "source":
418                     validate_sources(suite, component)
419                 elif arch == "all":
420                     continue
421                 else:
422                     validate_packages(suite, component, arch)
423
424 ################################################################################
425
426 def check_files_not_symlinks():
427     """
428     Check files in the database aren't symlinks
429     """
430     print "Building list of database files... ",
431     before = time.time()
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()
435
436     for i in q_files:
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))
440         else:
441             if os.path.islink(filename):
442                 utils.warn("%s: is a symlink." % (filename))
443
444 ################################################################################
445
446 def chk_bd_process_dir (unused, dirname, filenames):
447     for name in filenames:
448         if not name.endswith(".dsc"):
449             continue
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)
454             if field:
455                 try:
456                     apt_pkg.ParseSrcDepends(field)
457                 except:
458                     print "E: [%s] %s: %s" % (filename, field_name, field)
459                     pass
460
461 ################################################################################
462
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)
466
467 ################################################################################
468
469 def main ():
470     global Cnf, projectB, db_files, waste, excluded
471
472     Cnf = utils.get_conf()
473     Arguments = [('h',"help","Check-Archive::Options::Help")]
474     for i in [ "help" ]:
475         if not Cnf.has_key("Check-Archive::Options::%s" % (i)):
476             Cnf["Check-Archive::Options::%s" % (i)] = ""
477
478     args = apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
479
480     Options = Cnf.SubTree("Check-Archive::Options")
481     if Options["Help"]:
482         usage()
483
484     if len(args) < 1:
485         utils.warn("dak check-archive requires at least one argument")
486         usage(1)
487     elif len(args) > 1:
488         utils.warn("dak check-archive accepts only one argument")
489         usage(1)
490     mode = args[0].lower()
491
492     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
493     database.init(Cnf, projectB)
494
495     if mode == "checksums":
496         check_checksums()
497     elif mode == "files":
498         check_files()
499     elif mode == "dsc-syntax":
500         check_dscs()
501     elif mode == "missing-overrides":
502         check_override()
503     elif mode == "source-in-one-dir":
504         check_source_in_one_dir()
505     elif mode == "timestamps":
506         check_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()
515     else:
516         utils.warn("unknown mode '%s'" % (mode))
517         usage(1)
518
519 ################################################################################
520
521 if __name__ == '__main__':
522     main()