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