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