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