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