4 # Copyright (C) 2000, 2001, 2002 James Troup <james@nocrew.org>
5 # $Id: neve,v 1.13 2002-06-09 17:33:46 troup Exp $
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.
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.
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
21 ###############################################################################
23 # 04:36|<aj> elmo: you're making me waste 5 seconds per architecture!!!!!! YOU BASTARD!!!!!
25 ###############################################################################
27 # This code is a horrible mess for two reasons:
29 # (o) For Debian's usage, it's doing something like 160k INSERTs,
30 # even on auric, that makes the program unusable unless we get
31 # involed in sorts of silly optimization games (local dicts to avoid
32 # redundant SELECTS, using COPY FROM rather than INSERTS etc.)
34 # (o) It's very site specific, because I don't expect to use this
35 # script again in a hurry, and I don't want to spend any more time
36 # on it than absolutely necessary.
38 ###############################################################################
40 import commands, os, pg, re, select, string, tempfile, time;
42 import db_access, utils;
44 ###############################################################################
46 re_arch_from_filename = re.compile(r"binary-[^/]+")
48 ###############################################################################
59 src_associations_id_serial = 0;
60 dsc_files_id_serial = 0;
61 files_query_cache = None;
62 source_query_cache = None;
63 src_associations_query_cache = None;
64 dsc_files_query_cache = None;
65 orig_tar_gz_cache = {};
67 binaries_id_serial = 0;
68 binaries_query_cache = None;
69 bin_associations_id_serial = 0;
70 bin_associations_query_cache = None;
72 source_cache_for_binaries = {};
75 ###############################################################################
77 # Our very own version of commands.getouputstatus(), hacked to support
79 def get_status_output(cmd, status_read, status_write):
80 cmd = ['/bin/sh', '-c', cmd];
81 p2cread, p2cwrite = os.pipe();
82 c2pread, c2pwrite = os.pipe();
83 errout, errin = os.pipe();
93 for i in range(3, 256):
100 os.execvp(cmd[0], cmd);
106 os.dup2(c2pread, c2pwrite);
107 os.dup2(errout, errin);
109 output = status = "";
111 i, o, e = select.select([c2pwrite, errin, status_read], [], []);
114 r = os.read(fd, 8196);
116 more_data.append(fd);
117 if fd == c2pwrite or fd == errin:
119 elif fd == status_read:
122 utils.fubar("Unexpected file descriptor [%s] returned from select\n" % (fd));
124 pid, exit_status = os.waitpid(pid, 0)
126 os.close(status_write);
127 os.close(status_read);
135 return output, status, exit_status;
137 ###############################################################################
139 def Dict(**dict): return dict
141 def reject (str, prefix="Rejected: "):
142 global reject_message;
144 reject_message = reject_message + prefix + str + "\n";
146 ###############################################################################
148 def check_signature (filename):
149 if not utils.re_taint_free.match(os.path.basename(filename)):
150 reject("!!WARNING!! tainted filename: '%s'." % (filename));
153 status_read, status_write = os.pipe();
154 cmd = "gpgv --status-fd %s --keyring %s --keyring %s %s" \
155 % (status_write, Cnf["Dinstall::PGPKeyring"], Cnf["Dinstall::GPGKeyring"], filename);
156 (output, status, exit_status) = get_status_output(cmd, status_read, status_write);
158 # Process the status-fd output
160 bad = internal_error = "";
161 for line in string.split(status, '\n'):
162 line = string.strip(line);
165 split = string.split(line);
167 internal_error = internal_error + "gpgv status line is malformed (< 2 atoms) ['%s'].\n" % (line);
169 (gnupg, keyword) = split[:2];
170 if gnupg != "[GNUPG:]":
171 internal_error = internal_error + "gpgv status line is malformed (incorrect prefix '%s').\n" % (gnupg);
174 if keywords.has_key(keyword) and keyword != "NODATA" and keyword != "SIGEXPIRED":
175 internal_error = internal_error + "found duplicate status token ('%s')." % (keyword);
178 keywords[keyword] = args;
180 # If we failed to parse the status-fd output, let's just whine and bail now
182 reject("internal error while performing signature check on %s." % (filename));
183 reject(internal_error, "");
184 reject("Please report the above errors to the Archive maintainers by replying to this mail.", "");
187 # Now check for obviously bad things in the processed output
188 if keywords.has_key("SIGEXPIRED"):
189 utils.warn("%s: signing key has expired." % (filename));
190 if keywords.has_key("KEYREVOKED"):
191 reject("key used to sign %s has been revoked." % (filename));
193 if keywords.has_key("BADSIG"):
194 reject("bad signature on %s." % (filename));
196 if keywords.has_key("ERRSIG") and not keywords.has_key("NO_PUBKEY"):
197 reject("failed to check signature on %s." % (filename));
199 if keywords.has_key("NO_PUBKEY"):
200 args = keywords["NO_PUBKEY"];
202 reject("internal error while checking signature on %s." % (filename));
205 fingerprint = args[0];
206 if keywords.has_key("BADARMOR"):
207 reject("ascii armour of signature was corrupt in %s." % (filename));
209 if keywords.has_key("NODATA"):
210 utils.warn("no signature found for %s." % (filename));
212 #reject("no signature found in %s." % (filename));
218 # Next check gpgv exited with a zero return code
219 if exit_status and not keywords.has_key("NO_PUBKEY"):
220 reject("gpgv failed while checking %s." % (filename));
221 if string.strip(status):
222 reject(utils.prefix_multi_line_string(status, " [GPG status-fd output:] "), "");
224 reject(utils.prefix_multi_line_string(output, " [GPG output:] "), "");
227 # Sanity check the good stuff we expect
228 if not keywords.has_key("VALIDSIG"):
229 if not keywords.has_key("NO_PUBKEY"):
230 reject("signature on %s does not appear to be valid [No VALIDSIG]." % (filename));
233 args = keywords["VALIDSIG"];
235 reject("internal error while checking signature on %s." % (filename));
238 fingerprint = args[0];
239 if not keywords.has_key("GOODSIG") and not keywords.has_key("NO_PUBKEY"):
240 reject("signature on %s does not appear to be valid [No GOODSIG]." % (filename));
242 if not keywords.has_key("SIG_ID") and not keywords.has_key("NO_PUBKEY"):
243 reject("signature on %s does not appear to be valid [No SIG_ID]." % (filename));
246 # Finally ensure there's not something we don't recognise
247 known_keywords = Dict(VALIDSIG="",SIG_ID="",GOODSIG="",BADSIG="",ERRSIG="",
248 SIGEXPIRED="",KEYREVOKED="",NO_PUBKEY="",BADARMOR="",
251 for keyword in keywords.keys():
252 if not known_keywords.has_key(keyword):
253 reject("found unknown status token '%s' from gpgv with args '%s' in %s." % (keyword, repr(keywords[keyword]), filename));
261 #########################################################################################
263 # Prepares a filename or directory (s) to be file.filename by stripping any part of the location (sub) from it.
264 def poolify (s, sub):
265 for i in xrange(len(sub)):
266 if sub[i:] == s[0:len(sub)-i]:
267 return s[len(sub)-i:];
270 def update_archives ():
271 projectB.query("DELETE FROM archive")
272 for archive in Cnf.SubTree("Archive").List():
273 SubSec = Cnf.SubTree("Archive::%s" % (archive));
274 projectB.query("INSERT INTO archive (name, origin_server, description) VALUES ('%s', '%s', '%s')"
275 % (archive, SubSec["OriginServer"], SubSec["Description"]));
277 def update_components ():
278 projectB.query("DELETE FROM component")
279 for component in Cnf.SubTree("Component").List():
280 SubSec = Cnf.SubTree("Component::%s" % (component));
281 projectB.query("INSERT INTO component (name, description, meets_dfsg) VALUES ('%s', '%s', '%s')" %
282 (component, SubSec["Description"], SubSec["MeetsDFSG"]));
284 def update_locations ():
285 projectB.query("DELETE FROM location")
286 for location in Cnf.SubTree("Location").List():
287 SubSec = Cnf.SubTree("Location::%s" % (location));
288 archive_id = db_access.get_archive_id(SubSec["archive"]);
289 type = SubSec.Find("type");
290 if type == "legacy-mixed":
291 projectB.query("INSERT INTO location (path, archive, type) VALUES ('%s', %d, '%s')" % (location, archive_id, SubSec["type"]));
293 for component in Cnf.SubTree("Component").List():
294 component_id = db_access.get_component_id(component);
295 projectB.query("INSERT INTO location (path, component, archive, type) VALUES ('%s', %d, %d, '%s')" %
296 (location, component_id, archive_id, SubSec["type"]));
298 def update_architectures ():
299 projectB.query("DELETE FROM architecture")
300 for arch in Cnf.SubTree("Architectures").List():
301 projectB.query("INSERT INTO architecture (arch_string, description) VALUES ('%s', '%s')" % (arch, Cnf["Architectures::%s" % (arch)]))
303 def update_suites ():
304 projectB.query("DELETE FROM suite")
305 for suite in Cnf.SubTree("Suite").List():
306 SubSec = Cnf.SubTree("Suite::%s" %(suite))
307 projectB.query("INSERT INTO suite (suite_name) VALUES ('%s')" % string.lower(suite));
308 for i in ("Version", "Origin", "Description"):
309 if SubSec.has_key(i):
310 projectB.query("UPDATE suite SET %s = '%s' WHERE suite_name = '%s'" % (string.lower(i), SubSec[i], string.lower(suite)))
311 for architecture in Cnf.ValueList("Suite::%s::Architectures" % (suite)):
312 architecture_id = db_access.get_architecture_id (architecture);
313 projectB.query("INSERT INTO suite_architectures (suite, architecture) VALUES (currval('suite_id_seq'), %d)" % (architecture_id));
315 def update_override_type():
316 projectB.query("DELETE FROM override_type");
317 for type in Cnf.ValueList("OverrideType"):
318 projectB.query("INSERT INTO override_type (type) VALUES ('%s')" % (type));
320 def update_priority():
321 projectB.query("DELETE FROM priority");
322 for priority in Cnf.SubTree("Priority").List():
323 projectB.query("INSERT INTO priority (priority, level) VALUES ('%s', %s)" % (priority, Cnf["Priority::%s" % (priority)]));
325 ###############################################################################
327 def get_or_set_files_id (filename, size, md5sum, location_id):
328 global files_id_cache, files_id_serial, files_query_cache;
330 cache_key = string.join((filename, size, md5sum, repr(location_id)), '~')
331 if not files_id_cache.has_key(cache_key):
332 files_id_serial = files_id_serial + 1
333 files_query_cache.write("%d\t%s\t%s\t%s\t%d\n" % (files_id_serial, filename, size, md5sum, location_id));
334 files_id_cache[cache_key] = files_id_serial
336 return files_id_cache[cache_key]
338 ###############################################################################
340 def process_sources (location, filename, suite, component, archive, dsc_dir):
341 global source_cache, source_query_cache, src_associations_query_cache, dsc_files_query_cache, source_id_serial, src_associations_id_serial, dsc_files_id_serial, source_cache_for_binaries, orig_tar_gz_cache, reject_message;
343 suite = string.lower(suite);
344 suite_id = db_access.get_suite_id(suite);
346 file = utils.open_file (filename);
347 except utils.cant_open_exc:
348 print "WARNING: can't open '%s'" % (filename);
350 Scanner = apt_pkg.ParseTagFile(file);
351 while Scanner.Step() != 0:
352 package = Scanner.Section["package"];
353 version = Scanner.Section["version"];
354 dsc_file = os.path.join(dsc_dir, "%s_%s.dsc" % (package, utils.re_no_epoch.sub('', version)));
355 install_date = time.strftime("%Y-%m-%d", time.localtime(os.path.getmtime(dsc_file)));
356 fingerprint = check_signature(dsc_file);
357 fingerprint_id = db_access.get_or_set_fingerprint_id(fingerprint);
359 utils.fubar("%s: %s" % (dsc_file, reject_message));
360 maintainer = Scanner.Section["maintainer"]
361 maintainer = string.replace(maintainer, "'", "\\'");
362 maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
363 directory = Scanner.Section["directory"];
364 location_id = db_access.get_location_id (location, component, archive);
365 if directory[-1:] != "/":
366 directory = directory + '/';
367 directory = poolify (directory, location);
368 if directory != "" and directory[-1:] != "/":
369 directory = directory + '/';
370 no_epoch_version = utils.re_no_epoch.sub('', version);
371 # Add all files referenced by the .dsc to the files table
373 for line in string.split(Scanner.Section["files"],'\n'):
375 (md5sum, size, filename) = string.split(string.strip(line));
376 # Don't duplicate .orig.tar.gz's
377 if filename[-12:] == ".orig.tar.gz":
378 cache_key = "%s~%s~%s" % (filename, size, md5sum);
379 if orig_tar_gz_cache.has_key(cache_key):
380 id = orig_tar_gz_cache[cache_key];
382 id = get_or_set_files_id (directory + filename, size, md5sum, location_id);
383 orig_tar_gz_cache[cache_key] = id;
385 id = get_or_set_files_id (directory + filename, size, md5sum, location_id);
387 # If this is the .dsc itself; save the ID for later.
388 if filename[-4:] == ".dsc":
390 filename = directory + package + '_' + no_epoch_version + '.dsc'
391 cache_key = "%s~%s" % (package, version);
392 if not source_cache.has_key(cache_key):
393 nasty_key = "%s~%s" % (package, version)
394 source_id_serial = source_id_serial + 1;
395 if not source_cache_for_binaries.has_key(nasty_key):
396 source_cache_for_binaries[nasty_key] = source_id_serial;
397 tmp_source_id = source_id_serial;
398 source_cache[cache_key] = source_id_serial;
399 source_query_cache.write("%d\t%s\t%s\t%d\t%d\t%s\t%s\n" % (source_id_serial, package, version, maintainer_id, files_id, install_date, fingerprint_id))
401 dsc_files_id_serial = dsc_files_id_serial + 1;
402 dsc_files_query_cache.write("%d\t%d\t%d\n" % (dsc_files_id_serial, tmp_source_id,id));
404 tmp_source_id = source_cache[cache_key];
406 src_associations_id_serial = src_associations_id_serial + 1;
407 src_associations_query_cache.write("%d\t%d\t%d\n" % (src_associations_id_serial, suite_id, tmp_source_id))
411 ###############################################################################
413 def process_packages (location, filename, suite, component, archive):
414 global arch_all_cache, binary_cache, binaries_id_serial, binaries_query_cache, bin_associations_id_serial, bin_associations_query_cache, reject_message;
418 suite = string.lower(suite);
419 suite_id = db_access.get_suite_id(suite);
421 file = utils.open_file (filename);
422 except utils.cant_open_exc:
423 print "WARNING: can't open '%s'" % (filename);
425 Scanner = apt_pkg.ParseTagFile(file);
426 while Scanner.Step() != 0:
427 package = Scanner.Section["package"]
428 version = Scanner.Section["version"]
429 maintainer = Scanner.Section["maintainer"]
430 maintainer = string.replace(maintainer, "'", "\\'")
431 maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
432 architecture = Scanner.Section["architecture"]
433 architecture_id = db_access.get_architecture_id (architecture);
434 fingerprint = "NOSIG";
435 fingerprint_id = db_access.get_or_set_fingerprint_id(fingerprint);
436 if not Scanner.Section.has_key("source"):
439 source = Scanner.Section["source"]
441 if string.find(source, "(") != -1:
442 m = utils.re_extract_src_version.match(source)
444 source_version = m.group(2)
445 if not source_version:
446 source_version = version
447 filename = Scanner.Section["filename"]
448 location_id = db_access.get_location_id (location, component, archive)
449 filename = poolify (filename, location)
450 if architecture == "all":
451 filename = re_arch_from_filename.sub("binary-all", filename);
452 cache_key = "%s~%s" % (source, source_version);
453 source_id = source_cache_for_binaries.get(cache_key, None);
454 size = Scanner.Section["size"];
455 md5sum = Scanner.Section["md5sum"];
456 files_id = get_or_set_files_id (filename, size, md5sum, location_id);
457 type = "deb"; # FIXME
458 cache_key = "%s~%s~%s~%d~%d~%d" % (package, version, repr(source_id), architecture_id, location_id, files_id);
459 if not arch_all_cache.has_key(cache_key):
460 arch_all_cache[cache_key] = 1;
461 cache_key = "%s~%s~%s~%d" % (package, version, repr(source_id), architecture_id);
462 if not binary_cache.has_key(cache_key):
465 count_bad = count_bad + 1;
467 source_id = repr(source_id);
468 binaries_id_serial = binaries_id_serial + 1;
469 binaries_query_cache.write("%d\t%s\t%s\t%d\t%s\t%d\t%d\t%s\t%s\n" % (binaries_id_serial, package, version, maintainer_id, source_id, architecture_id, files_id, type, fingerprint_id));
470 binary_cache[cache_key] = binaries_id_serial;
471 tmp_binaries_id = binaries_id_serial;
473 tmp_binaries_id = binary_cache[cache_key];
475 bin_associations_id_serial = bin_associations_id_serial + 1;
476 bin_associations_query_cache.write("%d\t%d\t%d\n" % (bin_associations_id_serial, suite_id, tmp_binaries_id));
477 count_total = count_total +1;
481 print "%d binary packages processed; %d with no source match which is %.2f%%" % (count_total, count_bad, (float(count_bad)/count_total)*100);
483 print "%d binary packages processed; 0 with no source match which is 0%%" % (count_total);
485 ###############################################################################
487 def do_sources(location, prefix, suite, component, server):
488 temp_filename = tempfile.mktemp();
489 fd = os.open(temp_filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
491 sources = location + prefix + 'Sources.gz';
492 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (sources, temp_filename));
494 utils.fubar("Gunzip invocation failed!\n%s" % (output), result);
495 print 'Processing '+sources+'...';
496 process_sources (location, temp_filename, suite, component, server, os.path.dirname(sources));
497 os.unlink(temp_filename);
499 ###############################################################################
502 global Cnf, projectB, query_cache, files_query_cache, source_query_cache, src_associations_query_cache, dsc_files_query_cache, bin_associations_query_cache, binaries_query_cache;
504 Cnf = utils.get_conf();
506 print "Re-Creating DB..."
507 (result, output) = commands.getstatusoutput("psql -f init_pool.sql template1");
509 utils.fubar("psql invocation failed!\n", result);
512 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]));
514 db_access.init (Cnf, projectB);
516 print "Adding static tables from conf file..."
517 projectB.query("BEGIN WORK");
518 update_architectures();
523 update_override_type();
525 projectB.query("COMMIT WORK");
527 files_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"files","w");
528 source_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"source","w");
529 src_associations_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"src_associations","w");
530 dsc_files_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"dsc_files","w");
531 binaries_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"binaries","w");
532 bin_associations_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"bin_associations","w");
534 projectB.query("BEGIN WORK");
535 # Process Sources files to popoulate `source' and friends
536 for location in Cnf.SubTree("Location").List():
537 SubSec = Cnf.SubTree("Location::%s" % (location));
538 server = SubSec["Archive"];
539 type = Cnf.Find("Location::%s::Type" % (location));
540 if type == "legacy-mixed":
542 suite = Cnf.Find("Location::%s::Suite" % (location));
543 do_sources(location, prefix, suite, "", server);
544 elif type == "legacy":
545 for suite in Cnf.ValueList("Location::%s::Suites" % (location)):
546 for component in Cnf.SubTree("Component").List():
547 prefix = Cnf["Suite::%s::CodeName" % (suite)] + '/' + component + '/source/'
548 do_sources(location, prefix, suite, component, server);
551 # for component in Cnf.SubTree("Component").List():
552 # prefix = component + '/'
553 # do_sources(location, prefix);
555 utils.fubar("Unknown location type ('%s')." % (type));
557 # Process Packages files to populate `binaries' and friends
559 for location in Cnf.SubTree("Location").List():
560 SubSec = Cnf.SubTree("Location::%s" % (location));
561 server = SubSec["Archive"];
562 type = Cnf.Find("Location::%s::Type" % (location));
563 if type == "legacy-mixed":
564 packages = location + 'Packages';
565 suite = Cnf.Find("Location::%s::Suite" % (location));
566 print 'Processing '+location+'...';
567 process_packages (location, packages, suite, "", server);
568 elif type == "legacy":
569 for suite in Cnf.ValueList("Location::%s::Suites" % (location)):
570 for component in Cnf.SubTree("Component").List():
571 architectures = filter(utils.real_arch,
572 Cnf.ValueList("Suite::%s::Architectures" % (suite)));
573 for architecture in architectures:
574 packages = location + Cnf["Suite::%s::CodeName" % (suite)] + '/' + component + '/binary-' + architecture + '/Packages'
575 print 'Processing '+packages+'...';
576 process_packages (location, packages, suite, component, server);
580 files_query_cache.close();
581 source_query_cache.close();
582 src_associations_query_cache.close();
583 dsc_files_query_cache.close();
584 binaries_query_cache.close();
585 bin_associations_query_cache.close();
586 print "Writing data to `files' table...";
587 projectB.query("COPY files FROM '%s'" % (Cnf["Neve::ExportDir"]+"files"));
588 print "Writing data to `source' table...";
589 projectB.query("COPY source FROM '%s'" % (Cnf["Neve::ExportDir"]+"source"));
590 print "Writing data to `src_associations' table...";
591 projectB.query("COPY src_associations FROM '%s'" % (Cnf["Neve::ExportDir"]+"src_associations"));
592 print "Writing data to `dsc_files' table...";
593 projectB.query("COPY dsc_files FROM '%s'" % (Cnf["Neve::ExportDir"]+"dsc_files"));
594 print "Writing data to `binaries' table...";
595 projectB.query("COPY binaries FROM '%s'" % (Cnf["Neve::ExportDir"]+"binaries"));
596 print "Writing data to `bin_associations' table...";
597 projectB.query("COPY bin_associations FROM '%s'" % (Cnf["Neve::ExportDir"]+"bin_associations"));
598 print "Committing...";
599 projectB.query("COMMIT WORK");
601 # Add the constraints and otherwise generally clean up the database.
602 # See add_constraints.sql for more details...
604 print "Running add_constraints.sql...";
605 (result, output) = commands.getstatusoutput("psql %s < add_constraints.sql" % (Cnf["DB::Name"]));
608 utils.fubar("psql invocation failed!\n%s" % (output), result);
612 if __name__ == '__main__':