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