]> git.decadent.org.uk Git - dak.git/blob - dak/check_archive.py
Merge commit 'mhy/sqlalchemy' 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.regexes import re_issource
44 from daklib.config import Config
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   tar-gz-in-dsc      - ensure each .dsc lists a .tar.gz file
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 """
76     sys.exit(exit_code)
77
78 ################################################################################
79
80 def process_dir (unused, dirname, filenames):
81     """
82     Process a directory and output every files name which is not listed already
83     in the C{filenames} or global C{excluded} dictionaries.
84
85     @type dirname: string
86     @param dirname: the directory to look at
87
88     @type filenames: dict
89     @param filenames: Known filenames to ignore
90     """
91     global waste, db_files, excluded
92
93     if dirname.find('/disks-') != -1 or dirname.find('upgrade-') != -1:
94         return
95     # hack; can't handle .changes files
96     if dirname.find('proposed-updates') != -1:
97         return
98     for name in filenames:
99         filename = os.path.abspath(dirname+'/'+name)
100         filename = filename.replace('potato-proposed-updates', 'proposed-updates')
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(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(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     cnf = Config()
154
155     count = 0
156     suite = 'unstable'
157
158     for component in cnf.SubTree("Component").List():
159         component = component.lower()
160         list_filename = '%s%s_%s_source.list' % (cnf["Dir::Lists"], suite, component)
161         list_file = utils.open_file(list_filename)
162
163         for line in list_file.readlines():
164             f = line[:-1]
165             try:
166                 utils.parse_changes(f, signing_rules=1)
167             except InvalidDscError, line:
168                 utils.warn("syntax error in .dsc file '%s', line %s." % (f, line))
169                 count += 1
170             except ChangesUnicodeError:
171                 utils.warn("found invalid changes file, not properly utf-8 encoded")
172                 count += 1
173
174     if count:
175         utils.warn("Found %s invalid .dsc files." % (count))
176
177 ################################################################################
178
179 def check_override():
180     """
181     Check for missing overrides in stable and unstable.
182     """
183     session = DBConn().session()
184
185     for suite_name in [ "stable", "unstable" ]:
186         print suite_name
187         print "-" * len(suite_name)
188         print
189         suite = get_suite(suite)
190         q = s.execute("""
191 SELECT DISTINCT b.package FROM binaries b, bin_associations ba
192  WHERE b.id = ba.bin AND ba.suite = :suiteid AND NOT EXISTS
193        (SELECT 1 FROM override o WHERE o.suite = :suiteid AND o.package = b.package)"""
194                           % {'suiteid': suite.suite_id})
195
196         for j in q.fetchall():
197             print j[0]
198
199         q = s.execute("""
200 SELECT DISTINCT s.source FROM source s, src_associations sa
201   WHERE s.id = sa.source AND sa.suite = :suiteid AND NOT EXISTS
202        (SELECT 1 FROM override o WHERE o.suite = :suiteid and o.package = s.source)"""
203                           % {'suiteid': suite.suite_id})
204         for j in q.fetchall():
205             print j[0]
206
207 ################################################################################
208
209
210 def check_source_in_one_dir():
211     """
212     Ensure that the source files for any given package is all in one
213     directory so that 'apt-get source' works...
214     """
215
216     # Not the most enterprising method, but hey...
217     broken_count = 0
218
219     session = DBConn().session()
220
221     q = session.query(DBSource)
222     for s in q.all():
223         first_path = ""
224         first_filename = ""
225         broken = False
226
227         qf = session.query(PoolFile).join(Location).join(DSCFile).filter_by(source_id=s.source_id)
228         for f in qf.all():
229             # 0: path
230             # 1: filename
231             filename = os.path.join(f.location.path, f.filename)
232             path = os.path.dirname(filename)
233
234             if first_path == "":
235                 first_path = path
236                 first_filename = filename
237             elif first_path != path:
238                 symlink = path + '/' + os.path.basename(first_filename)
239                 if not os.path.exists(symlink):
240                     broken = True
241                     print "WOAH, we got a live one here... %s [%s] {%s}" % (filename, s.source_id, symlink)
242         if broken:
243             broken_count += 1
244
245     print "Found %d source packages where the source is not all in one directory." % (broken_count)
246
247 ################################################################################
248 def check_checksums():
249     """
250     Validate all files
251     """
252     print "Getting file information from database..."
253     q = DBConn().session().query(PoolFile)
254
255     print "Checking file checksums & sizes..."
256     for f in q:
257         filename = os.path.abspath(os.path.join(f.location.path, f.filename))
258
259         try:
260             fi = utils.open_file(filename)
261         except:
262             utils.warn("can't open '%s'." % (filename))
263             continue
264
265         size = os.stat(filename)[stat.ST_SIZE]
266         if size != f.filesize:
267             utils.warn("**WARNING** size mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, size, f.filesize))
268
269         md5sum = apt_pkg.md5sum(fi)
270         if md5sum != f.md5sum:
271             utils.warn("**WARNING** md5sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, md5sum, f.md5sum))
272
273         fi.seek(0)
274         sha1sum = apt_pkg.sha1sum(fi)
275         if sha1sum != f.sha1sum:
276             utils.warn("**WARNING** sha1sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha1sum, f.sha1sum))
277
278         fi.seek(0)
279         sha256sum = apt_pkg.sha256sum(fi)
280         if sha256sum != f.sha256sum:
281             utils.warn("**WARNING** sha256sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha256sum, f.sha256sum))
282
283     print "Done."
284
285 ################################################################################
286 #
287
288 def Ent(Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
289     global future_files
290
291     if MTime > current_time:
292         future_files[current_file] = MTime
293         print "%s: %s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % (current_file, Kind,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor)
294
295 def check_timestamps():
296     """
297     Check all files for timestamps in the future; common from hardware
298     (e.g. alpha) which have far-future dates as their default dates.
299     """
300
301     global current_file
302
303     q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.deb$'))
304
305     db_files.clear()
306     count = 0
307
308     for pf in q.all():
309         filename = os.path.abspath(os.path.join(pf.location.path, pf.filename))
310         if os.access(filename, os.R_OK):
311             f = utils.open_file(filename)
312             current_file = filename
313             sys.stderr.write("Processing %s.\n" % (filename))
314             apt_inst.debExtract(f, Ent, "control.tar.gz")
315             f.seek(0)
316             apt_inst.debExtract(f, Ent, "data.tar.gz")
317             count += 1
318
319     print "Checked %d files (out of %d)." % (count, len(db_files.keys()))
320
321 ################################################################################
322
323 def check_missing_tar_gz_in_dsc():
324     """
325     Ensure each .dsc lists a .tar.gz file
326     """
327     count = 0
328
329     print "Building list of database files..."
330     q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.dsc$'))
331
332     if q.count() > 0:
333         print "Checking %d files..." % len(ql)
334     else:
335         print "No files to check."
336
337     for pf in q.all():
338         filename = os.path.abspath(os.path.join(pf.location.path + pf.filename))
339
340         try:
341             # NB: don't enforce .dsc syntax
342             dsc = utils.parse_changes(filename)
343         except:
344             utils.fubar("error parsing .dsc file '%s'." % (filename))
345
346         dsc_files = utils.build_file_list(dsc, is_a_dsc=1)
347         has_tar = 0
348
349         for f in dsc_files.keys():
350             m = re_issource.match(f)
351             if not m:
352                 utils.fubar("%s not recognised as source." % (f))
353             ftype = m.group(3)
354             if ftype == "orig.tar.gz" or ftype == "tar.gz":
355                 has_tar = 1
356
357         if not has_tar:
358             utils.warn("%s has no .tar.gz in the .dsc file." % (f))
359             count += 1
360
361     if count:
362         utils.warn("Found %s invalid .dsc files." % (count))
363
364
365 ################################################################################
366
367 def validate_sources(suite, component):
368     """
369     Ensure files mentioned in Sources exist
370     """
371     filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suite, component)
372     print "Processing %s..." % (filename)
373     # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
374     (fd, temp_filename) = utils.temp_filename()
375     (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
376     if (result != 0):
377         sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
378         sys.exit(result)
379     sources = utils.open_file(temp_filename)
380     Sources = apt_pkg.ParseTagFile(sources)
381     while Sources.Step():
382         source = Sources.Section.Find('Package')
383         directory = Sources.Section.Find('Directory')
384         files = Sources.Section.Find('Files')
385         for i in files.split('\n'):
386             (md5, size, name) = i.split()
387             filename = "%s/%s/%s" % (Cnf["Dir::Root"], directory, name)
388             if not os.path.exists(filename):
389                 if directory.find("potato") == -1:
390                     print "W: %s missing." % (filename)
391                 else:
392                     pool_location = utils.poolify (source, component)
393                     pool_filename = "%s/%s/%s" % (Cnf["Dir::Pool"], pool_location, name)
394                     if not os.path.exists(pool_filename):
395                         print "E: %s missing (%s)." % (filename, pool_filename)
396                     else:
397                         # Create symlink
398                         pool_filename = os.path.normpath(pool_filename)
399                         filename = os.path.normpath(filename)
400                         src = utils.clean_symlink(pool_filename, filename, Cnf["Dir::Root"])
401                         print "Symlinking: %s -> %s" % (filename, src)
402                         #os.symlink(src, filename)
403     sources.close()
404     os.unlink(temp_filename)
405
406 ########################################
407
408 def validate_packages(suite, component, architecture):
409     """
410     Ensure files mentioned in Packages exist
411     """
412     filename = "%s/dists/%s/%s/binary-%s/Packages.gz" \
413                % (Cnf["Dir::Root"], suite, component, architecture)
414     print "Processing %s..." % (filename)
415     # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
416     (fd, temp_filename) = utils.temp_filename()
417     (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
418     if (result != 0):
419         sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
420         sys.exit(result)
421     packages = utils.open_file(temp_filename)
422     Packages = apt_pkg.ParseTagFile(packages)
423     while Packages.Step():
424         filename = "%s/%s" % (Cnf["Dir::Root"], Packages.Section.Find('Filename'))
425         if not os.path.exists(filename):
426             print "W: %s missing." % (filename)
427     packages.close()
428     os.unlink(temp_filename)
429
430 ########################################
431
432 def check_indices_files_exist():
433     """
434     Ensure files mentioned in Packages & Sources exist
435     """
436     for suite in [ "stable", "testing", "unstable" ]:
437         for component in Cnf.ValueList("Suite::%s::Components" % (suite)):
438             architectures = database.get_suite_architectures(suite)
439             for arch in [ i.lower() for i in architectures ]:
440                 if arch == "source":
441                     validate_sources(suite, component)
442                 elif arch == "all":
443                     continue
444                 else:
445                     validate_packages(suite, component, arch)
446
447 ################################################################################
448
449 def check_files_not_symlinks():
450     """
451     Check files in the database aren't symlinks
452     """
453     print "Building list of database files... ",
454     before = time.time()
455     q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.dsc$'))
456
457     for pf in q.all():
458         filename = os.path.abspath(os.path.join(pf.location.path, pf.filename))
459         if os.access(filename, os.R_OK) == 0:
460             utils.warn("%s: doesn't exist." % (filename))
461         else:
462             if os.path.islink(filename):
463                 utils.warn("%s: is a symlink." % (filename))
464
465 ################################################################################
466
467 def chk_bd_process_dir (unused, dirname, filenames):
468     for name in filenames:
469         if not name.endswith(".dsc"):
470             continue
471         filename = os.path.abspath(dirname+'/'+name)
472         dsc = utils.parse_changes(filename)
473         for field_name in [ "build-depends", "build-depends-indep" ]:
474             field = dsc.get(field_name)
475             if field:
476                 try:
477                     apt_pkg.ParseSrcDepends(field)
478                 except:
479                     print "E: [%s] %s: %s" % (filename, field_name, field)
480                     pass
481
482 ################################################################################
483
484 def check_build_depends():
485     """ Validate build-dependencies of .dsc files in the archive """
486     os.path.walk(cnf["Dir::Root"], chk_bd_process_dir, None)
487
488 ################################################################################
489
490 def main ():
491     global db_files, waste, excluded
492
493     cnf = Config()
494
495     Arguments = [('h',"help","Check-Archive::Options::Help")]
496     for i in [ "help" ]:
497         if not cnf.has_key("Check-Archive::Options::%s" % (i)):
498             cnf["Check-Archive::Options::%s" % (i)] = ""
499
500     args = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
501
502     Options = cnf.SubTree("Check-Archive::Options")
503     if Options["Help"]:
504         usage()
505
506     if len(args) < 1:
507         utils.warn("dak check-archive requires at least one argument")
508         usage(1)
509     elif len(args) > 1:
510         utils.warn("dak check-archive accepts only one argument")
511         usage(1)
512     mode = args[0].lower()
513
514     # Initialize DB
515     DBConn()
516
517     if mode == "checksums":
518         check_checksums()
519     elif mode == "files":
520         check_files()
521     elif mode == "dsc-syntax":
522         check_dscs()
523     elif mode == "missing-overrides":
524         check_override()
525     elif mode == "source-in-one-dir":
526         check_source_in_one_dir()
527     elif mode == "timestamps":
528         check_timestamps()
529     elif mode == "tar-gz-in-dsc":
530         check_missing_tar_gz_in_dsc()
531     elif mode == "validate-indices":
532         check_indices_files_exist()
533     elif mode == "files-not-symlinks":
534         check_files_not_symlinks()
535     elif mode == "validate-builddeps":
536         check_build_depends()
537     else:
538         utils.warn("unknown mode '%s'" % (mode))
539         usage(1)
540
541 ################################################################################
542
543 if __name__ == '__main__':
544     main()