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