]> git.decadent.org.uk Git - dak.git/blob - dak/check_archive.py
lotsa files
[dak.git] / dak / check_archive.py
1 #!/usr/bin/env python
2
3 """ Various different sanity checks """
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006  James Troup <james@nocrew.org>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20 ################################################################################
21
22 #   And, lo, a great and menacing voice rose from the depths, and with
23 #   great wrath and vehemence it's voice boomed across the
24 #   land... ``hehehehehehe... that *tickles*''
25 #                                                       -- aj on IRC
26
27 ################################################################################
28
29 import commands, os, pg, stat, sys, time
30 import apt_pkg, apt_inst
31 from daklib import database
32 from daklib import utils
33 from daklib.regexes import re_issource
34
35 ################################################################################
36
37 Cnf = None
38 projectB = None
39 db_files = {}
40 waste = 0.0
41 excluded = {}
42 current_file = None
43 future_files = {}
44 current_time = time.time()
45
46 ################################################################################
47
48 def usage(exit_code=0):
49     print """Usage: dak check-archive MODE
50 Run various sanity checks of the archive and/or database.
51
52   -h, --help                show this help and exit.
53
54 The following MODEs are available:
55
56   checksums          - validate the checksums stored in the database
57   files              - check files in the database against what's in the archive
58   dsc-syntax         - validate the syntax of .dsc files in the archive
59   missing-overrides  - check for missing overrides
60   source-in-one-dir  - ensure the source for each package is in one directory
61   timestamps         - check for future timestamps in .deb's
62   tar-gz-in-dsc      - ensure each .dsc lists a .tar.gz file
63   validate-indices   - ensure files mentioned in Packages & Sources exist
64   files-not-symlinks - check files in the database aren't symlinks
65   validate-builddeps - validate build-dependencies of .dsc files in the archive
66 """
67     sys.exit(exit_code)
68
69 ################################################################################
70
71 def process_dir (unused, dirname, filenames):
72     global waste, db_files, excluded
73
74     if dirname.find('/disks-') != -1 or dirname.find('upgrade-') != -1:
75         return
76     # hack; can't handle .changes files
77     if dirname.find('proposed-updates') != -1:
78         return
79     for name in filenames:
80         filename = os.path.abspath(dirname+'/'+name)
81         filename = filename.replace('potato-proposed-updates', 'proposed-updates')
82         if os.path.isfile(filename) and not os.path.islink(filename) and not db_files.has_key(filename) and not excluded.has_key(filename):
83             waste += os.stat(filename)[stat.ST_SIZE]
84             print "%s" % (filename)
85
86 ################################################################################
87
88 def check_files():
89     global db_files
90
91     print "Building list of database files..."
92     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")
93     ql = q.getresult()
94
95     print "Missing files:"
96     db_files.clear()
97     for i in ql:
98         filename = os.path.abspath(i[0] + i[1])
99         db_files[filename] = ""
100         if os.access(filename, os.R_OK) == 0:
101             if i[2]:
102                 print "(last used: %s) %s" % (i[2], filename)
103             else:
104                 print "%s" % (filename)
105
106
107     filename = Cnf["Dir::Override"]+'override.unreferenced'
108     if os.path.exists(filename):
109         f = utils.open_file(filename)
110         for filename in f.readlines():
111             filename = filename[:-1]
112             excluded[filename] = ""
113
114     print "Existent files not in db:"
115
116     os.path.walk(Cnf["Dir::Root"]+'pool/', process_dir, None)
117
118     print
119     print "%s wasted..." % (utils.size_type(waste))
120
121 ################################################################################
122
123 def check_dscs():
124     count = 0
125     suite = 'unstable'
126     for component in Cnf.SubTree("Component").List():
127         if component == "mixed":
128             continue
129         component = component.lower()
130         list_filename = '%s%s_%s_source.list' % (Cnf["Dir::Lists"], suite, component)
131         list_file = utils.open_file(list_filename)
132         for line in list_file.readlines():
133             f = line[:-1]
134             try:
135                 utils.parse_changes(f, signing_rules=1)
136             except InvalidDscError, line:
137                 utils.warn("syntax error in .dsc file '%s', line %s." % (f, line))
138                 count += 1
139
140     if count:
141         utils.warn("Found %s invalid .dsc files." % (count))
142
143 ################################################################################
144
145 def check_override():
146     for suite in [ "stable", "unstable" ]:
147         print suite
148         print "-"*len(suite)
149         print
150         suite_id = database.get_suite_id(suite)
151         q = projectB.query("""
152 SELECT DISTINCT b.package FROM binaries b, bin_associations ba
153  WHERE b.id = ba.bin AND ba.suite = %s AND NOT EXISTS
154        (SELECT 1 FROM override o WHERE o.suite = %s AND o.package = b.package)"""
155                            % (suite_id, suite_id))
156         print q
157         q = projectB.query("""
158 SELECT DISTINCT s.source FROM source s, src_associations sa
159   WHERE s.id = sa.source AND sa.suite = %s AND NOT EXISTS
160        (SELECT 1 FROM override o WHERE o.suite = %s and o.package = s.source)"""
161                            % (suite_id, suite_id))
162         print q
163
164 ################################################################################
165
166 # Ensure that the source files for any given package is all in one
167 # directory so that 'apt-get source' works...
168
169 def check_source_in_one_dir():
170     # Not the most enterprising method, but hey...
171     broken_count = 0
172     q = projectB.query("SELECT id FROM source;")
173     for i in q.getresult():
174         source_id = i[0]
175         q2 = projectB.query("""
176 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"""
177                             % (source_id))
178         first_path = ""
179         first_filename = ""
180         broken = 0
181         for j in q2.getresult():
182             filename = j[0] + j[1]
183             path = os.path.dirname(filename)
184             if first_path == "":
185                 first_path = path
186                 first_filename = filename
187             elif first_path != path:
188                 symlink = path + '/' + os.path.basename(first_filename)
189                 if not os.path.exists(symlink):
190                     broken = 1
191                     print "WOAH, we got a live one here... %s [%s] {%s}" % (filename, source_id, symlink)
192         if broken:
193             broken_count += 1
194     print "Found %d source packages where the source is not all in one directory." % (broken_count)
195
196 ################################################################################
197
198 def check_checksums():
199     print "Getting file information from database..."
200     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")
201     ql = q.getresult()
202
203     print "Checking file checksums & sizes..."
204     for i in ql:
205         filename = os.path.abspath(i[0] + i[1])
206         db_md5sum = i[2]
207         db_sha1sum = i[3]
208         db_sha256sum = i[4]
209         db_size = int(i[5])
210         try:
211             f = utils.open_file(filename)
212         except:
213             utils.warn("can't open '%s'." % (filename))
214             continue
215         md5sum = apt_pkg.md5sum(f)
216         size = os.stat(filename)[stat.ST_SIZE]
217         if md5sum != db_md5sum:
218             utils.warn("**WARNING** md5sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, md5sum, db_md5sum))
219         if size != db_size:
220             utils.warn("**WARNING** size mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, size, db_size))
221         # Until the main database is filled, we need to not spit 500,000 warnings
222         # every time we scan the archive.  Yet another hack (TM) which can go away
223         # once this is all working
224         if db_sha1sum is not None and db_sha1sum != '':
225             f.seek(0)
226             sha1sum = apt_pkg.sha1sum(f)
227             if sha1sum != db_sha1sum:
228                 utils.warn("**WARNING** sha1sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha1sum, db_sha1sum))
229
230         if db_sha256sum is not None and db_sha256sum != '':
231             f.seek(0)
232             sha256sum = apt_pkg.sha256sum(f)
233             if sha256sum != db_sha256sum:
234                 utils.warn("**WARNING** sha256sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha256sum, db_sha256sum))
235
236     print "Done."
237
238 ################################################################################
239 #
240 # Check all files for timestamps in the future; common from hardware
241 # (e.g. alpha) which have far-future dates as their default dates.
242
243 def Ent(Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
244     global future_files
245
246     if MTime > current_time:
247         future_files[current_file] = MTime
248         print "%s: %s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % (current_file, Kind,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor)
249
250 def check_timestamps():
251     global current_file
252
253     q = projectB.query("SELECT l.path, f.filename FROM files f, location l WHERE f.location = l.id AND f.filename ~ '.deb$'")
254     ql = q.getresult()
255     db_files.clear()
256     count = 0
257     for i in ql:
258         filename = os.path.abspath(i[0] + i[1])
259         if os.access(filename, os.R_OK):
260             f = utils.open_file(filename)
261             current_file = filename
262             sys.stderr.write("Processing %s.\n" % (filename))
263             apt_inst.debExtract(f, Ent, "control.tar.gz")
264             f.seek(0)
265             apt_inst.debExtract(f, Ent, "data.tar.gz")
266             count += 1
267     print "Checked %d files (out of %d)." % (count, len(db_files.keys()))
268
269 ################################################################################
270
271 def check_missing_tar_gz_in_dsc():
272     count = 0
273
274     print "Building list of database files..."
275     q = projectB.query("SELECT l.path, f.filename FROM files f, location l WHERE f.location = l.id AND f.filename ~ '.dsc$'")
276     ql = q.getresult()
277     if ql:
278         print "Checking %d files..." % len(ql)
279     else:
280         print "No files to check."
281     for i in ql:
282         filename = os.path.abspath(i[0] + i[1])
283         try:
284             # NB: don't enforce .dsc syntax
285             dsc = utils.parse_changes(filename)
286         except:
287             utils.fubar("error parsing .dsc file '%s'." % (filename))
288         dsc_files = utils.build_file_list(dsc, is_a_dsc=1)
289         has_tar = 0
290         for f in dsc_files.keys():
291             m = re_issource.match(f)
292             if not m:
293                 utils.fubar("%s not recognised as source." % (f))
294             ftype = m.group(3)
295             if ftype == "orig.tar.gz" or ftype == "tar.gz":
296                 has_tar = 1
297         if not has_tar:
298             utils.warn("%s has no .tar.gz in the .dsc file." % (f))
299             count += 1
300
301     if count:
302         utils.warn("Found %s invalid .dsc files." % (count))
303
304
305 ################################################################################
306
307 def validate_sources(suite, component):
308     filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suite, component)
309     print "Processing %s..." % (filename)
310     # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
311     (fd, temp_filename) = utils.temp_filename()
312     (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
313     if (result != 0):
314         sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
315         sys.exit(result)
316     sources = utils.open_file(temp_filename)
317     Sources = apt_pkg.ParseTagFile(sources)
318     while Sources.Step():
319         source = Sources.Section.Find('Package')
320         directory = Sources.Section.Find('Directory')
321         files = Sources.Section.Find('Files')
322         for i in files.split('\n'):
323             (md5, size, name) = i.split()
324             filename = "%s/%s/%s" % (Cnf["Dir::Root"], directory, name)
325             if not os.path.exists(filename):
326                 if directory.find("potato") == -1:
327                     print "W: %s missing." % (filename)
328                 else:
329                     pool_location = utils.poolify (source, component)
330                     pool_filename = "%s/%s/%s" % (Cnf["Dir::Pool"], pool_location, name)
331                     if not os.path.exists(pool_filename):
332                         print "E: %s missing (%s)." % (filename, pool_filename)
333                     else:
334                         # Create symlink
335                         pool_filename = os.path.normpath(pool_filename)
336                         filename = os.path.normpath(filename)
337                         src = utils.clean_symlink(pool_filename, filename, Cnf["Dir::Root"])
338                         print "Symlinking: %s -> %s" % (filename, src)
339                         #os.symlink(src, filename)
340     sources.close()
341     os.unlink(temp_filename)
342
343 ########################################
344
345 def validate_packages(suite, component, architecture):
346     filename = "%s/dists/%s/%s/binary-%s/Packages.gz" \
347                % (Cnf["Dir::Root"], suite, component, architecture)
348     print "Processing %s..." % (filename)
349     # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
350     (fd, temp_filename) = utils.temp_filename()
351     (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
352     if (result != 0):
353         sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
354         sys.exit(result)
355     packages = utils.open_file(temp_filename)
356     Packages = apt_pkg.ParseTagFile(packages)
357     while Packages.Step():
358         filename = "%s/%s" % (Cnf["Dir::Root"], Packages.Section.Find('Filename'))
359         if not os.path.exists(filename):
360             print "W: %s missing." % (filename)
361     packages.close()
362     os.unlink(temp_filename)
363
364 ########################################
365
366 def check_indices_files_exist():
367     for suite in [ "stable", "testing", "unstable" ]:
368         for component in Cnf.ValueList("Suite::%s::Components" % (suite)):
369             architectures = Cnf.ValueList("Suite::%s::Architectures" % (suite))
370             for arch in [ i.lower() for i in architectures ]:
371                 if arch == "source":
372                     validate_sources(suite, component)
373                 elif arch == "all":
374                     continue
375                 else:
376                     validate_packages(suite, component, arch)
377
378 ################################################################################
379
380 def check_files_not_symlinks():
381     print "Building list of database files... ",
382     before = time.time()
383     q = projectB.query("SELECT l.path, f.filename, f.id FROM files f, location l WHERE f.location = l.id")
384     print "done. (%d seconds)" % (int(time.time()-before))
385     q_files = q.getresult()
386
387     for i in q_files:
388         filename = os.path.normpath(i[0] + i[1])
389         if os.access(filename, os.R_OK) == 0:
390             utils.warn("%s: doesn't exist." % (filename))
391         else:
392             if os.path.islink(filename):
393                 utils.warn("%s: is a symlink." % (filename))
394
395 ################################################################################
396
397 def chk_bd_process_dir (unused, dirname, filenames):
398     for name in filenames:
399         if not name.endswith(".dsc"):
400             continue
401         filename = os.path.abspath(dirname+'/'+name)
402         dsc = utils.parse_changes(filename)
403         for field_name in [ "build-depends", "build-depends-indep" ]:
404             field = dsc.get(field_name)
405             if field:
406                 try:
407                     apt_pkg.ParseSrcDepends(field)
408                 except:
409                     print "E: [%s] %s: %s" % (filename, field_name, field)
410                     pass
411
412 ################################################################################
413
414 def check_build_depends():
415     os.path.walk(Cnf["Dir::Root"], chk_bd_process_dir, None)
416
417 ################################################################################
418
419 def main ():
420     global Cnf, projectB, db_files, waste, excluded
421
422     Cnf = utils.get_conf()
423     Arguments = [('h',"help","Check-Archive::Options::Help")]
424     for i in [ "help" ]:
425         if not Cnf.has_key("Check-Archive::Options::%s" % (i)):
426             Cnf["Check-Archive::Options::%s" % (i)] = ""
427
428     args = apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
429
430     Options = Cnf.SubTree("Check-Archive::Options")
431     if Options["Help"]:
432         usage()
433
434     if len(args) < 1:
435         utils.warn("dak check-archive requires at least one argument")
436         usage(1)
437     elif len(args) > 1:
438         utils.warn("dak check-archive accepts only one argument")
439         usage(1)
440     mode = args[0].lower()
441
442     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
443     database.init(Cnf, projectB)
444
445     if mode == "checksums":
446         check_checksums()
447     elif mode == "files":
448         check_files()
449     elif mode == "dsc-syntax":
450         check_dscs()
451     elif mode == "missing-overrides":
452         check_override()
453     elif mode == "source-in-one-dir":
454         check_source_in_one_dir()
455     elif mode == "timestamps":
456         check_timestamps()
457     elif mode == "tar-gz-in-dsc":
458         check_missing_tar_gz_in_dsc()
459     elif mode == "validate-indices":
460         check_indices_files_exist()
461     elif mode == "files-not-symlinks":
462         check_files_not_symlinks()
463     elif mode == "validate-builddeps":
464         check_build_depends()
465     else:
466         utils.warn("unknown mode '%s'" % (mode))
467         usage(1)
468
469 ################################################################################
470
471 if __name__ == '__main__':
472     main()