]> git.decadent.org.uk Git - dak.git/blob - tea
use EXISTS (SELECT 1. Add new check validate-indices.
[dak.git] / tea
1 #!/usr/bin/env python
2
3 # Sanity check the database
4 # Copyright (C) 2000, 2001, 2002, 2003  James Troup <james@nocrew.org>
5 # $Id: tea,v 1.23 2003-09-07 13:52:17 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, tempfile, 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 """
64     sys.exit(exit_code)
65
66 ################################################################################
67
68 def process_dir (unused, dirname, filenames):
69     global waste, db_files, excluded;
70
71     if dirname.find('/disks-') != -1 or dirname.find('upgrade-') != -1:
72         return;
73     # hack; can't handle .changes files
74     if dirname.find('proposed-updates') != -1:
75         return;
76     for name in filenames:
77         filename = os.path.abspath(dirname+'/'+name);
78         filename = filename.replace('potato-proposed-updates', 'proposed-updates');
79         if os.path.isfile(filename) and not os.path.islink(filename) and not db_files.has_key(filename) and not excluded.has_key(filename):
80             waste += os.stat(filename)[stat.ST_SIZE];
81             print filename
82
83 ################################################################################
84
85 def check_files():
86     global db_files;
87
88     print "Building list of database files...";
89     q = projectB.query("SELECT l.path, f.filename FROM files f, location l WHERE f.location = l.id")
90     ql = q.getresult();
91
92     db_files.clear();
93     for i in ql:
94         filename = os.path.abspath(i[0] + i[1]);
95         db_files[filename] = "";
96         if os.access(filename, os.R_OK) == 0:
97             utils.warn("'%s' doesn't exist." % (filename));
98
99     file = utils.open_file(Cnf["Dir::Override"]+'override.unreferenced');
100     for filename in file.readlines():
101         filename = filename[:-1];
102         excluded[filename] = "";
103
104     print "Checking against existent files...";
105
106     os.path.walk(Cnf["Dir::Root"]+'dists/', process_dir, None);
107
108     print
109     print "%s wasted..." % (utils.size_type(waste));
110
111 ################################################################################
112
113 def check_dscs():
114     count = 0;
115     suite = 'unstable';
116     for component in Cnf.SubTree("Component").List():
117         if component == "mixed":
118             continue;
119         component = component.lower();
120         list_filename = '%s%s_%s_source.list' % (Cnf["Dir::Lists"], suite, component);
121         list_file = utils.open_file(list_filename);
122         for line in list_file.readlines():
123             file = line[:-1];
124             try:
125                 utils.parse_changes(file, dsc_whitespace_rules=1);
126             except utils.invalid_dsc_format_exc, line:
127                 utils.warn("syntax error in .dsc file '%s', line %s." % (file, line));
128                 count += 1;
129
130     if count:
131         utils.warn("Found %s invalid .dsc files." % (count));
132
133 ################################################################################
134
135 def check_override():
136     for suite in [ "stable", "unstable" ]:
137         print suite
138         print "-------------"
139         print
140         suite_id = db_access.get_suite_id(suite);
141         q = projectB.query("""
142 SELECT DISTINCT b.package FROM binaries b, bin_associations ba
143  WHERE b.id = ba.bin AND ba.suite = %s AND NOT EXISTS
144        (SELECT 1 FROM override o WHERE o.suite = %s AND o.package = b.package)"""
145                            % (suite_id, suite_id));
146         print q
147         q = projectB.query("""
148 SELECT DISTINCT s.source FROM source s, src_associations sa
149   WHERE s.id = sa.source AND sa.suite = %s AND NOT EXISTS
150        (SELECT 1 FROM override o WHERE o.suite = %s and o.package = s.source)"""
151                            % (suite_id, suite_id));
152         print q
153
154 ################################################################################
155
156 # Ensure that the source files for any given package is all in one
157 # directory so that 'apt-get source' works...
158
159 def check_source_in_one_dir():
160     # Not the most enterprising method, but hey...
161     broken_count = 0;
162     q = projectB.query("SELECT id FROM source;");
163     for i in q.getresult():
164         source_id = i[0];
165         q2 = projectB.query("""
166 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"""
167                             % (source_id));
168         first_path = "";
169         first_filename = "";
170         broken = 0;
171         for j in q2.getresult():
172             filename = j[0] + j[1];
173             path = os.path.dirname(filename);
174             if first_path == "":
175                 first_path = path;
176                 first_filename = filename;
177             elif first_path != path:
178                 symlink = path + '/' + os.path.basename(first_filename);
179                 if not os.path.exists(symlink):
180                     broken = 1;
181                     print "WOAH, we got a live one here... %s [%s] {%s}" % (filename, source_id, symlink);
182         if broken:
183             broken_count += 1;
184     print "Found %d source packages where the source is not all in one directory." % (broken_count);
185
186 ################################################################################
187
188 def check_md5sums():
189     print "Getting file information from database...";
190     q = projectB.query("SELECT l.path, f.filename, f.md5sum, f.size FROM files f, location l WHERE f.location = l.id")
191     ql = q.getresult();
192
193     print "Checking file md5sums & sizes...";
194     for i in ql:
195         filename = os.path.abspath(i[0] + i[1]);
196         db_md5sum = i[2];
197         db_size = int(i[3]);
198         try:
199             file = utils.open_file(filename);
200         except:
201             utils.warn("can't open '%s'." % (filename));
202             continue;
203         md5sum = apt_pkg.md5sum(file);
204         size = os.stat(filename)[stat.ST_SIZE];
205         if md5sum != db_md5sum:
206             utils.warn("**WARNING** md5sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, md5sum, db_md5sum));
207         if size != db_size:
208             utils.warn("**WARNING** size mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, size, db_size));
209
210     print "Done."
211
212 ################################################################################
213 #
214 # Check all files for timestamps in the future; common from hardware
215 # (e.g. alpha) which have far-future dates as their default dates.
216
217 def Ent(Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
218     global future_files;
219
220     if MTime > current_time:
221         future_files[current_file] = MTime;
222         print "%s: %s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % (current_file, Kind,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor);
223
224 def check_timestamps():
225     global current_file;
226
227     q = projectB.query("SELECT l.path, f.filename FROM files f, location l WHERE f.location = l.id AND f.filename ~ '.deb$'")
228     ql = q.getresult();
229     db_files.clear();
230     count = 0;
231     for i in ql:
232         filename = os.path.abspath(i[0] + i[1]);
233         if os.access(filename, os.R_OK):
234             file = utils.open_file(filename);
235             current_file = filename;
236             sys.stderr.write("Processing %s.\n" % (filename));
237             apt_inst.debExtract(file,Ent,"control.tar.gz");
238             file.seek(0);
239             apt_inst.debExtract(file,Ent,"data.tar.gz");
240             count += 1;
241     print "Checked %d files (out of %d)." % (count, len(db_files.keys()));
242
243 ################################################################################
244
245 def check_missing_tar_gz_in_dsc():
246     count = 0;
247
248     print "Building list of database files...";
249     q = projectB.query("SELECT l.path, f.filename FROM files f, location l WHERE f.location = l.id AND f.filename ~ '.dsc$'");
250     ql = q.getresult();
251     if ql:
252         print "Checking %d files..." % len(ql);
253     else:
254         print "No files to check."
255     for i in ql:
256         filename = os.path.abspath(i[0] + i[1]);
257         try:
258             # NB: don't enforce .dsc syntax
259             dsc = utils.parse_changes(filename);
260         except:
261             utils.fubar("error parsing .dsc file '%s'." % (filename));
262         dsc_files = utils.build_file_list(dsc, is_a_dsc=1);
263         has_tar = 0;
264         for file in dsc_files.keys():
265             m = utils.re_issource.match(file);
266             if not m:
267                 utils.fubar("%s not recognised as source." % (file));
268             type = m.group(3);
269             if type == "orig.tar.gz" or type == "tar.gz":
270                 has_tar = 1;
271         if not has_tar:
272             utils.warn("%s has no .tar.gz in the .dsc file." % (file));
273             count += 1;
274
275     if count:
276         utils.warn("Found %s invalid .dsc files." % (count));
277
278
279 ################################################################################
280
281 def validate_sources(suite, component):
282     filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suite, component);
283     print "Processing %s..." % (filename);
284     # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
285     temp_filename = tempfile.mktemp();
286     fd = os.open(temp_filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
287     os.close(fd);
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             s = i.split();
300             (md5, size, name) = s;
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 = 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 = utils.clean_symlink(pool_filename, filename, Cnf["Dir::Root"]);
315                         print "Symlinking: %s -> %s" % (filename, src);
316                         #os.symlink(src, filename);
317     os.unlink(temp_filename);
318
319 ########################################
320
321 def validate_packages(suite, component, architecture):
322     filename = "%s/dists/%s/%s/binary-%s/Packages" \
323                % (Cnf["Dir::Root"], suite, component, architecture);
324     print "Processing %s..." % (filename);
325     packages = utils.open_file(filename);
326     Packages = apt_pkg.ParseTagFile(packages);
327     while Packages.Step():
328         filename = "%s/%s" % (Cnf["Dir::Root"], Packages.Section.Find('Filename'));
329         if not os.path.exists(filename):
330             print "W: %s missing." % (filename);
331     packages.close();
332
333 ########################################
334
335 def check_indices_files_exist():
336     for suite in [ "stable", "testing", "unstable" ]:
337         for component in Cnf.ValueList("Suite::%s::Components" % (suite)):
338             architectures = Cnf.ValueList("Suite::%s::Architectures" % (suite));
339             for arch in map(string.lower, architectures):
340                 if arch == "source":
341                     validate_sources(suite, component);
342                 elif arch == "all":
343                     continue;
344                 else:
345                     validate_packages(suite, component, arch);
346
347 ################################################################################
348
349 def main ():
350     global Cnf, projectB, db_files, waste, excluded;
351
352     Cnf = utils.get_conf();
353     Arguments = [('h',"help","Tea::Options::Help")];
354     for i in [ "help" ]:
355         if not Cnf.has_key("Tea::Options::%s" % (i)):
356             Cnf["Tea::Options::%s" % (i)] = "";
357
358     args = apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv);
359
360     Options = Cnf.SubTree("Tea::Options")
361     if Options["Help"]:
362         usage();
363
364     if len(args) < 1:
365         utils.warn("tea requires at least one argument");
366         usage(1);
367     elif len(args) > 1:
368         utils.warn("tea accepts only one argument");
369         usage(1);
370     mode = args[0].lower();
371
372     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]));
373     db_access.init(Cnf, projectB);
374
375     if mode == "md5sums":
376         check_md5sums();
377     elif mode == "files":
378         check_files();
379     elif mode == "dsc-syntax":
380         check_dscs();
381     elif mode == "missing-overrides":
382         check_override();
383     elif mode == "source-in-one-dir":
384         check_source_in_one_dir();
385     elif mode == "timestamps":
386         check_timestamps();
387     elif mode == "tar-gz-in-dsc":
388         check_missing_tar_gz_in_dsc();
389     elif mode == "validate-indices":
390         check_indices_files_exist();
391     else:
392         utils.warn("unknown mode '%s'" % (mode));
393         usage(1);
394
395 ################################################################################
396
397 if __name__ == '__main__':
398     main();
399