]> git.decadent.org.uk Git - dak.git/blob - dak/check_archive.py
Merge remote-tracking branch 'ansgar/pu/wheezy' into merge
[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 stat
36 import sys
37 import time
38 import apt_pkg
39 import apt_inst
40
41 from daklib.dbconn import *
42 from daklib import utils
43 from daklib.config import Config
44 from daklib.dak_exceptions import InvalidDscError, ChangesUnicodeError, CantOpenError
45
46 ################################################################################
47
48 db_files = {}                  #: Cache of filenames as known by the database
49 waste = 0.0                    #: How many bytes are "wasted" by files not referenced in database
50 excluded = {}                  #: List of files which are excluded from files check
51 current_file = None
52 future_files = {}
53 current_time = time.time()     #: now()
54
55 ################################################################################
56
57 def usage(exit_code=0):
58     print """Usage: dak check-archive MODE
59 Run various sanity checks of the archive and/or database.
60
61   -h, --help                show this help and exit.
62
63 The following MODEs are available:
64
65   checksums          - validate the checksums stored in the database
66   files              - check files in the database against what's in the archive
67   dsc-syntax         - validate the syntax of .dsc files in the archive
68   missing-overrides  - check for missing overrides
69   source-in-one-dir  - ensure the source for each package is in one directory
70   timestamps         - check for future timestamps in .deb's
71   files-in-dsc       - ensure each .dsc references appropriate Files
72   validate-indices   - ensure files mentioned in Packages & Sources exist
73   files-not-symlinks - check files in the database aren't symlinks
74   validate-builddeps - validate build-dependencies of .dsc files in the archive
75   add-missing-source-checksums - add missing checksums for source packages
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(os.path.join(dirname,name))
101         if os.path.isfile(filename) and not os.path.islink(filename) and not db_files.has_key(filename) and not excluded.has_key(filename):
102             waste += os.stat(filename)[stat.ST_SIZE]
103             print "%s" % (filename)
104
105 ################################################################################
106
107 def check_files():
108     """
109     Prepare the dictionary of existing filenames, then walk through the archive
110     pool/ directory to compare it.
111     """
112     global db_files
113
114     cnf = Config()
115
116     print "Building list of database files..."
117     q = DBConn().session().query(PoolFile).join(Location).order_by('path', 'location')
118
119     print "Missing files:"
120     db_files.clear()
121
122     for f in q.all():
123         filename = os.path.abspath(os.path.join(f.location.path, f.filename))
124         db_files[filename] = ""
125         if os.access(filename, os.R_OK) == 0:
126             if f.last_used:
127                 print "(last used: %s) %s" % (f.last_used, filename)
128             else:
129                 print "%s" % (filename)
130
131
132     filename = os.path.join(cnf["Dir::Override"], 'override.unreferenced')
133     if os.path.exists(filename):
134         f = utils.open_file(filename)
135         for filename in f.readlines():
136             filename = filename[:-1]
137             excluded[filename] = ""
138
139     print "Existent files not in db:"
140
141     os.path.walk(os.path.join(cnf["Dir::Root"], 'pool/'), process_dir, None)
142
143     print
144     print "%s wasted..." % (utils.size_type(waste))
145
146 ################################################################################
147
148 def check_dscs():
149     """
150     Parse every .dsc file in the archive and check for it's validity.
151     """
152
153     count = 0
154
155     for src in DBConn().session().query(DBSource).order_by(DBSource.source, DBSource.version):
156         f = src.poolfile.fullpath
157         try:
158             utils.parse_changes(f, signing_rules=1, dsc_file=1)
159         except InvalidDscError:
160             utils.warn("syntax error in .dsc file %s" % f)
161             count += 1
162         except ChangesUnicodeError:
163             utils.warn("found invalid dsc file (%s), not properly utf-8 encoded" % f)
164             count += 1
165         except CantOpenError:
166             utils.warn("missing dsc file (%s)" % f)
167             count += 1
168         except Exception as e:
169             utils.warn("miscellaneous error parsing dsc file (%s): %s" % (f, str(e)))
170             count += 1
171
172     if count:
173         utils.warn("Found %s invalid .dsc files." % (count))
174
175 ################################################################################
176
177 def check_override():
178     """
179     Check for missing overrides in stable and unstable.
180     """
181     session = DBConn().session()
182
183     for suite_name in [ "stable", "unstable" ]:
184         print suite_name
185         print "-" * len(suite_name)
186         print
187         suite = get_suite(suite_name)
188         q = session.execute("""
189 SELECT DISTINCT b.package FROM binaries b, bin_associations ba
190  WHERE b.id = ba.bin AND ba.suite = :suiteid AND NOT EXISTS
191        (SELECT 1 FROM override o WHERE o.suite = :suiteid AND o.package = b.package)"""
192                           % {'suiteid': suite.suite_id})
193
194         for j in q.fetchall():
195             print j[0]
196
197         q = session.execute("""
198 SELECT DISTINCT s.source FROM source s, src_associations sa
199   WHERE s.id = sa.source AND sa.suite = :suiteid AND NOT EXISTS
200        (SELECT 1 FROM override o WHERE o.suite = :suiteid and o.package = s.source)"""
201                           % {'suiteid': suite.suite_id})
202         for j in q.fetchall():
203             print j[0]
204
205 ################################################################################
206
207
208 def check_source_in_one_dir():
209     """
210     Ensure that the source files for any given package is all in one
211     directory so that 'apt-get source' works...
212     """
213
214     # Not the most enterprising method, but hey...
215     broken_count = 0
216
217     session = DBConn().session()
218
219     q = session.query(DBSource)
220     for s in q.all():
221         first_path = ""
222         first_filename = ""
223         broken = False
224
225         qf = session.query(PoolFile).join(Location).join(DSCFile).filter_by(source_id=s.source_id)
226         for f in qf.all():
227             # 0: path
228             # 1: filename
229             filename = os.path.join(f.location.path, f.filename)
230             path = os.path.dirname(filename)
231
232             if first_path == "":
233                 first_path = path
234                 first_filename = filename
235             elif first_path != path:
236                 symlink = path + '/' + os.path.basename(first_filename)
237                 if not os.path.exists(symlink):
238                     broken = True
239                     print "WOAH, we got a live one here... %s [%s] {%s}" % (filename, s.source_id, symlink)
240         if broken:
241             broken_count += 1
242
243     print "Found %d source packages where the source is not all in one directory." % (broken_count)
244
245 ################################################################################
246 def check_checksums():
247     """
248     Validate all files
249     """
250     print "Getting file information from database..."
251     q = DBConn().session().query(PoolFile)
252
253     print "Checking file checksums & sizes..."
254     for f in q:
255         filename = os.path.abspath(os.path.join(f.location.path, f.filename))
256
257         try:
258             fi = utils.open_file(filename)
259         except:
260             utils.warn("can't open '%s'." % (filename))
261             continue
262
263         size = os.stat(filename)[stat.ST_SIZE]
264         if size != f.filesize:
265             utils.warn("**WARNING** size mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, size, f.filesize))
266
267         md5sum = apt_pkg.md5sum(fi)
268         if md5sum != f.md5sum:
269             utils.warn("**WARNING** md5sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, md5sum, f.md5sum))
270
271         fi.seek(0)
272         sha1sum = apt_pkg.sha1sum(fi)
273         if sha1sum != f.sha1sum:
274             utils.warn("**WARNING** sha1sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha1sum, f.sha1sum))
275
276         fi.seek(0)
277         sha256sum = apt_pkg.sha256sum(fi)
278         if sha256sum != f.sha256sum:
279             utils.warn("**WARNING** sha256sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha256sum, f.sha256sum))
280
281     print "Done."
282
283 ################################################################################
284 #
285
286 def Ent(Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
287     global future_files
288
289     if MTime > current_time:
290         future_files[current_file] = MTime
291         print "%s: %s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % (current_file, Kind,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor)
292
293 def check_timestamps():
294     """
295     Check all files for timestamps in the future; common from hardware
296     (e.g. alpha) which have far-future dates as their default dates.
297     """
298
299     global current_file
300
301     q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.deb$'))
302
303     db_files.clear()
304     count = 0
305
306     for pf in q.all():
307         filename = os.path.abspath(os.path.join(pf.location.path, pf.filename))
308         if os.access(filename, os.R_OK):
309             f = utils.open_file(filename)
310             current_file = filename
311             sys.stderr.write("Processing %s.\n" % (filename))
312             apt_inst.debExtract(f, Ent, "control.tar.gz")
313             f.seek(0)
314             apt_inst.debExtract(f, Ent, "data.tar.gz")
315             count += 1
316
317     print "Checked %d files (out of %d)." % (count, len(db_files.keys()))
318
319 ################################################################################
320
321 def check_files_in_dsc():
322     """
323     Ensure each .dsc lists appropriate files in its Files field (according
324     to the format announced in its Format field).
325     """
326     count = 0
327
328     print "Building list of database files..."
329     q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.dsc$'))
330
331     if q.count() > 0:
332         print "Checking %d files..." % len(ql)
333     else:
334         print "No files to check."
335
336     for pf in q.all():
337         filename = os.path.abspath(os.path.join(pf.location.path + pf.filename))
338
339         try:
340             # NB: don't enforce .dsc syntax
341             dsc = utils.parse_changes(filename, dsc_file=1)
342         except:
343             utils.fubar("error parsing .dsc file '%s'." % (filename))
344
345         reasons = utils.check_dsc_files(filename, dsc)
346         for r in reasons:
347             utils.warn(r)
348
349         if len(reasons) > 0:
350             count += 1
351
352     if count:
353         utils.warn("Found %s invalid .dsc files." % (count))
354
355
356 ################################################################################
357
358 def validate_sources(suite, component):
359     """
360     Ensure files mentioned in Sources exist
361     """
362     filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suite, component)
363     print "Processing %s..." % (filename)
364     # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
365     (fd, temp_filename) = utils.temp_filename()
366     (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
367     if (result != 0):
368         sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
369         sys.exit(result)
370     sources = utils.open_file(temp_filename)
371     Sources = apt_pkg.ParseTagFile(sources)
372     while Sources.Step():
373         source = Sources.Section.Find('Package')
374         directory = Sources.Section.Find('Directory')
375         files = Sources.Section.Find('Files')
376         for i in files.split('\n'):
377             (md5, size, name) = i.split()
378             filename = "%s/%s/%s" % (Cnf["Dir::Root"], directory, name)
379             if not os.path.exists(filename):
380                 if directory.find("potato") == -1:
381                     print "W: %s missing." % (filename)
382                 else:
383                     pool_location = utils.poolify (source, component)
384                     pool_filename = "%s/%s/%s" % (Cnf["Dir::Pool"], pool_location, name)
385                     if not os.path.exists(pool_filename):
386                         print "E: %s missing (%s)." % (filename, pool_filename)
387                     else:
388                         # Create symlink
389                         pool_filename = os.path.normpath(pool_filename)
390                         filename = os.path.normpath(filename)
391                         src = utils.clean_symlink(pool_filename, filename, Cnf["Dir::Root"])
392                         print "Symlinking: %s -> %s" % (filename, src)
393                         #os.symlink(src, filename)
394     sources.close()
395     os.unlink(temp_filename)
396
397 ########################################
398
399 def validate_packages(suite, component, architecture):
400     """
401     Ensure files mentioned in Packages exist
402     """
403     filename = "%s/dists/%s/%s/binary-%s/Packages.gz" \
404                % (Cnf["Dir::Root"], suite, component, architecture)
405     print "Processing %s..." % (filename)
406     # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
407     (fd, temp_filename) = utils.temp_filename()
408     (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
409     if (result != 0):
410         sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
411         sys.exit(result)
412     packages = utils.open_file(temp_filename)
413     Packages = apt_pkg.ParseTagFile(packages)
414     while Packages.Step():
415         filename = "%s/%s" % (Cnf["Dir::Root"], Packages.Section.Find('Filename'))
416         if not os.path.exists(filename):
417             print "W: %s missing." % (filename)
418     packages.close()
419     os.unlink(temp_filename)
420
421 ########################################
422
423 def check_indices_files_exist():
424     """
425     Ensure files mentioned in Packages & Sources exist
426     """
427     for suite in [ "stable", "testing", "unstable" ]:
428         for component in get_component_names():
429             architectures = get_suite_architectures(suite)
430             for arch in [ i.arch_string.lower() for i in architectures ]:
431                 if arch == "source":
432                     validate_sources(suite, component)
433                 elif arch == "all":
434                     continue
435                 else:
436                     validate_packages(suite, component, arch)
437
438 ################################################################################
439
440 def check_files_not_symlinks():
441     """
442     Check files in the database aren't symlinks
443     """
444     print "Building list of database files... ",
445     before = time.time()
446     q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.dsc$'))
447
448     for pf in q.all():
449         filename = os.path.abspath(os.path.join(pf.location.path, pf.filename))
450         if os.access(filename, os.R_OK) == 0:
451             utils.warn("%s: doesn't exist." % (filename))
452         else:
453             if os.path.islink(filename):
454                 utils.warn("%s: is a symlink." % (filename))
455
456 ################################################################################
457
458 def chk_bd_process_dir (unused, dirname, filenames):
459     for name in filenames:
460         if not name.endswith(".dsc"):
461             continue
462         filename = os.path.abspath(dirname+'/'+name)
463         dsc = utils.parse_changes(filename, dsc_file=1)
464         for field_name in [ "build-depends", "build-depends-indep" ]:
465             field = dsc.get(field_name)
466             if field:
467                 try:
468                     apt_pkg.ParseSrcDepends(field)
469                 except:
470                     print "E: [%s] %s: %s" % (filename, field_name, field)
471                     pass
472
473 ################################################################################
474
475 def check_build_depends():
476     """ Validate build-dependencies of .dsc files in the archive """
477     cnf = Config()
478     os.path.walk(cnf["Dir::Root"], chk_bd_process_dir, None)
479
480 ################################################################################
481
482 _add_missing_source_checksums_query = R"""
483 INSERT INTO source_metadata
484   (src_id, key_id, value)
485 SELECT
486   s.id,
487   :checksum_key,
488   E'\n' ||
489     (SELECT STRING_AGG(' ' || tmp.checksum || ' ' || tmp.size || ' ' || tmp.basename, E'\n' ORDER BY tmp.basename)
490      FROM
491        (SELECT
492             CASE :checksum_type
493               WHEN 'Files' THEN f.md5sum
494               WHEN 'Checksums-Sha1' THEN f.sha1sum
495               WHEN 'Checksums-Sha256' THEN f.sha256sum
496             END AS checksum,
497             f.size,
498             SUBSTRING(f.filename FROM E'/([^/]*)\\Z') AS basename
499           FROM files f JOIN dsc_files ON f.id = dsc_files.file
500           WHERE dsc_files.source = s.id AND f.id != s.file
501        ) AS tmp
502     )
503
504   FROM
505     source s
506   WHERE NOT EXISTS (SELECT 1 FROM source_metadata md WHERE md.src_id=s.id AND md.key_id = :checksum_key);
507 """
508
509 def add_missing_source_checksums():
510     """ Add missing source checksums to source_metadata """
511     session = DBConn().session()
512     for checksum in ['Files', 'Checksums-Sha1', 'Checksums-Sha256']:
513         checksum_key = get_or_set_metadatakey(checksum, session).key_id
514         rows = session.execute(_add_missing_source_checksums_query,
515             {'checksum_key': checksum_key, 'checksum_type': checksum}).rowcount
516         if rows > 0:
517             print "Added {0} missing entries for {1}".format(rows, checksum)
518     session.commit()
519
520 ################################################################################
521
522 def main ():
523     global db_files, waste, excluded
524
525     cnf = Config()
526
527     Arguments = [('h',"help","Check-Archive::Options::Help")]
528     for i in [ "help" ]:
529         if not cnf.has_key("Check-Archive::Options::%s" % (i)):
530             cnf["Check-Archive::Options::%s" % (i)] = ""
531
532     args = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
533
534     Options = cnf.subtree("Check-Archive::Options")
535     if Options["Help"]:
536         usage()
537
538     if len(args) < 1:
539         utils.warn("dak check-archive requires at least one argument")
540         usage(1)
541     elif len(args) > 1:
542         utils.warn("dak check-archive accepts only one argument")
543         usage(1)
544     mode = args[0].lower()
545
546     # Initialize DB
547     DBConn()
548
549     if mode == "checksums":
550         check_checksums()
551     elif mode == "files":
552         check_files()
553     elif mode == "dsc-syntax":
554         check_dscs()
555     elif mode == "missing-overrides":
556         check_override()
557     elif mode == "source-in-one-dir":
558         check_source_in_one_dir()
559     elif mode == "timestamps":
560         check_timestamps()
561     elif mode == "files-in-dsc":
562         check_files_in_dsc()
563     elif mode == "validate-indices":
564         check_indices_files_exist()
565     elif mode == "files-not-symlinks":
566         check_files_not_symlinks()
567     elif mode == "validate-builddeps":
568         check_build_depends()
569     elif mode == "add-missing-source-checksums":
570         add_missing_source_checksums()
571     else:
572         utils.warn("unknown mode '%s'" % (mode))
573         usage(1)
574
575 ################################################################################
576
577 if __name__ == '__main__':
578     main()