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