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