4 # Copyright (C) 2000, 2001, 2002 James Troup <james@nocrew.org>
5 # $Id: neve,v 1.16 2002-11-26 15:49:50 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, tempfile, time;
42 import db_access, utils;
44 ###############################################################################
46 re_arch_from_filename = re.compile(r"binary-[^/]+")
48 ###############################################################################
56 location_path_cache = {};
60 src_associations_id_serial = 0;
61 dsc_files_id_serial = 0;
62 files_query_cache = None;
63 source_query_cache = None;
64 src_associations_query_cache = None;
65 dsc_files_query_cache = None;
66 orig_tar_gz_cache = {};
68 binaries_id_serial = 0;
69 binaries_query_cache = None;
70 bin_associations_id_serial = 0;
71 bin_associations_query_cache = None;
73 source_cache_for_binaries = {};
76 ###############################################################################
78 # Our very own version of commands.getouputstatus(), hacked to support
80 def get_status_output(cmd, status_read, status_write):
81 cmd = ['/bin/sh', '-c', cmd];
82 p2cread, p2cwrite = os.pipe();
83 c2pread, c2pwrite = os.pipe();
84 errout, errin = os.pipe();
94 for i in range(3, 256):
101 os.execvp(cmd[0], cmd);
107 os.dup2(c2pread, c2pwrite);
108 os.dup2(errout, errin);
110 output = status = "";
112 i, o, e = select.select([c2pwrite, errin, status_read], [], []);
115 r = os.read(fd, 8196);
117 more_data.append(fd);
118 if fd == c2pwrite or fd == errin:
120 elif fd == status_read:
123 utils.fubar("Unexpected file descriptor [%s] returned from select\n" % (fd));
125 pid, exit_status = os.waitpid(pid, 0)
127 os.close(status_write);
128 os.close(status_read);
136 return output, status, exit_status;
138 ###############################################################################
140 def Dict(**dict): return dict
142 def reject (str, prefix="Rejected: "):
143 global reject_message;
145 reject_message += prefix + str + "\n";
147 ###############################################################################
149 def check_signature (filename):
150 if not utils.re_taint_free.match(os.path.basename(filename)):
151 reject("!!WARNING!! tainted filename: '%s'." % (filename));
154 status_read, status_write = os.pipe();
155 cmd = "gpgv --status-fd %s --keyring %s --keyring %s %s" \
156 % (status_write, Cnf["Dinstall::PGPKeyring"], Cnf["Dinstall::GPGKeyring"], filename);
157 (output, status, exit_status) = get_status_output(cmd, status_read, status_write);
159 # Process the status-fd output
161 bad = internal_error = "";
162 for line in status.split('\n'):
166 split = line.split();
168 internal_error += "gpgv status line is malformed (< 2 atoms) ['%s'].\n" % (line);
170 (gnupg, keyword) = split[:2];
171 if gnupg != "[GNUPG:]":
172 internal_error += "gpgv status line is malformed (incorrect prefix '%s').\n" % (gnupg);
175 if keywords.has_key(keyword) and keyword != "NODATA" and keyword != "SIGEXPIRED":
176 internal_error += "found duplicate status token ('%s')." % (keyword);
179 keywords[keyword] = args;
181 # If we failed to parse the status-fd output, let's just whine and bail now
183 reject("internal error while performing signature check on %s." % (filename));
184 reject(internal_error, "");
185 reject("Please report the above errors to the Archive maintainers by replying to this mail.", "");
188 # Now check for obviously bad things in the processed output
189 if keywords.has_key("SIGEXPIRED"):
190 utils.warn("%s: signing key has expired." % (filename));
191 if keywords.has_key("KEYREVOKED"):
192 reject("key used to sign %s has been revoked." % (filename));
194 if keywords.has_key("BADSIG"):
195 reject("bad signature on %s." % (filename));
197 if keywords.has_key("ERRSIG") and not keywords.has_key("NO_PUBKEY"):
198 reject("failed to check signature on %s." % (filename));
200 if keywords.has_key("NO_PUBKEY"):
201 args = keywords["NO_PUBKEY"];
203 reject("internal error while checking signature on %s." % (filename));
206 fingerprint = args[0];
207 if keywords.has_key("BADARMOR"):
208 reject("ascii armour of signature was corrupt in %s." % (filename));
210 if keywords.has_key("NODATA"):
211 utils.warn("no signature found for %s." % (filename));
213 #reject("no signature found in %s." % (filename));
219 # Next check gpgv exited with a zero return code
220 if exit_status and not keywords.has_key("NO_PUBKEY"):
221 reject("gpgv failed while checking %s." % (filename));
223 reject(utils.prefix_multi_line_string(status, " [GPG status-fd output:] "), "");
225 reject(utils.prefix_multi_line_string(output, " [GPG output:] "), "");
228 # Sanity check the good stuff we expect
229 if not keywords.has_key("VALIDSIG"):
230 if not keywords.has_key("NO_PUBKEY"):
231 reject("signature on %s does not appear to be valid [No VALIDSIG]." % (filename));
234 args = keywords["VALIDSIG"];
236 reject("internal error while checking signature on %s." % (filename));
239 fingerprint = args[0];
240 if not keywords.has_key("GOODSIG") and not keywords.has_key("NO_PUBKEY"):
241 reject("signature on %s does not appear to be valid [No GOODSIG]." % (filename));
243 if not keywords.has_key("SIG_ID") and not keywords.has_key("NO_PUBKEY"):
244 reject("signature on %s does not appear to be valid [No SIG_ID]." % (filename));
247 # Finally ensure there's not something we don't recognise
248 known_keywords = Dict(VALIDSIG="",SIG_ID="",GOODSIG="",BADSIG="",ERRSIG="",
249 SIGEXPIRED="",KEYREVOKED="",NO_PUBKEY="",BADARMOR="",
252 for keyword in keywords.keys():
253 if not known_keywords.has_key(keyword):
254 reject("found unknown status token '%s' from gpgv with args '%r' in %s." % (keyword, keywords[keyword], filename));
262 #########################################################################################
264 # Prepares a filename or directory (s) to be file.filename by stripping any part of the location (sub) from it.
265 def poolify (s, sub):
266 for i in xrange(len(sub)):
267 if sub[i:] == s[0:len(sub)-i]:
268 return s[len(sub)-i:];
271 def update_archives ():
272 projectB.query("DELETE FROM archive")
273 for archive in Cnf.SubTree("Archive").List():
274 SubSec = Cnf.SubTree("Archive::%s" % (archive));
275 projectB.query("INSERT INTO archive (name, origin_server, description) VALUES ('%s', '%s', '%s')"
276 % (archive, SubSec["OriginServer"], SubSec["Description"]));
278 def update_components ():
279 projectB.query("DELETE FROM component")
280 for component in Cnf.SubTree("Component").List():
281 SubSec = Cnf.SubTree("Component::%s" % (component));
282 projectB.query("INSERT INTO component (name, description, meets_dfsg) VALUES ('%s', '%s', '%s')" %
283 (component, SubSec["Description"], SubSec["MeetsDFSG"]));
285 def update_locations ():
286 projectB.query("DELETE FROM location")
287 for location in Cnf.SubTree("Location").List():
288 SubSec = Cnf.SubTree("Location::%s" % (location));
289 archive_id = db_access.get_archive_id(SubSec["archive"]);
290 type = SubSec.Find("type");
291 if type == "legacy-mixed":
292 projectB.query("INSERT INTO location (path, archive, type) VALUES ('%s', %d, '%s')" % (location, archive_id, SubSec["type"]));
294 for component in Cnf.SubTree("Component").List():
295 component_id = db_access.get_component_id(component);
296 projectB.query("INSERT INTO location (path, component, archive, type) VALUES ('%s', %d, %d, '%s')" %
297 (location, component_id, archive_id, SubSec["type"]));
299 def update_architectures ():
300 projectB.query("DELETE FROM architecture")
301 for arch in Cnf.SubTree("Architectures").List():
302 projectB.query("INSERT INTO architecture (arch_string, description) VALUES ('%s', '%s')" % (arch, Cnf["Architectures::%s" % (arch)]))
304 def update_suites ():
305 projectB.query("DELETE FROM suite")
306 for suite in Cnf.SubTree("Suite").List():
307 SubSec = Cnf.SubTree("Suite::%s" %(suite))
308 projectB.query("INSERT INTO suite (suite_name) VALUES ('%s')" % suite.lower());
309 for i in ("Version", "Origin", "Description"):
310 if SubSec.has_key(i):
311 projectB.query("UPDATE suite SET %s = '%s' WHERE suite_name = '%s'" % (i.lower(), SubSec[i], suite.lower()))
312 for architecture in Cnf.ValueList("Suite::%s::Architectures" % (suite)):
313 architecture_id = db_access.get_architecture_id (architecture);
314 projectB.query("INSERT INTO suite_architectures (suite, architecture) VALUES (currval('suite_id_seq'), %d)" % (architecture_id));
316 def update_override_type():
317 projectB.query("DELETE FROM override_type");
318 for type in Cnf.ValueList("OverrideType"):
319 projectB.query("INSERT INTO override_type (type) VALUES ('%s')" % (type));
321 def update_priority():
322 projectB.query("DELETE FROM priority");
323 for priority in Cnf.SubTree("Priority").List():
324 projectB.query("INSERT INTO priority (priority, level) VALUES ('%s', %s)" % (priority, Cnf["Priority::%s" % (priority)]));
326 def update_section():
327 projectB.query("DELETE FROM section");
328 for component in Cnf.SubTree("Component").List():
329 if Cnf["Natalie::ComponentPosition"] == "prefix":
331 if component != 'main':
332 prefix = component + '/';
337 component = component.replace("non-US/", "");
338 if component != 'main':
339 suffix = '/' + component;
342 for section in Cnf.ValueList("Section"):
343 projectB.query("INSERT INTO section (section) VALUES ('%s%s%s')" % (prefix, section, suffix));
345 def get_location_path(directory):
346 global location_path_cache;
348 if location_path_cache.has_key(directory):
349 return location_path_cache[directory];
351 q = projectB.query("SELECT DISTINCT path FROM location WHERE path ~ '%s'" % (directory));
353 path = q.getresult()[0][0];
355 utils.fubar("[neve] get_location_path(): Couldn't get path for %s" % (directory));
356 location_path_cache[directory] = path;
359 ###############################################################################
361 def get_or_set_files_id (filename, size, md5sum, location_id):
362 global files_id_cache, files_id_serial, files_query_cache;
364 cache_key = "~".join((filename, size, md5sum, repr(location_id)));
365 if not files_id_cache.has_key(cache_key):
367 files_query_cache.write("%d\t%s\t%s\t%s\t%d\n" % (files_id_serial, filename, size, md5sum, location_id));
368 files_id_cache[cache_key] = files_id_serial
370 return files_id_cache[cache_key]
372 ###############################################################################
374 def process_sources (filename, suite, component, archive):
375 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;
377 suite = suite.lower();
378 suite_id = db_access.get_suite_id(suite);
380 file = utils.open_file (filename);
381 except utils.cant_open_exc:
382 utils.warn("can't open '%s'" % (filename));
384 Scanner = apt_pkg.ParseTagFile(file);
385 while Scanner.Step() != 0:
386 package = Scanner.Section["package"];
387 version = Scanner.Section["version"];
388 directory = Scanner.Section["directory"];
389 dsc_file = os.path.join(Cnf["Dir::Root"], directory, "%s_%s.dsc" % (package, utils.re_no_epoch.sub('', version)));
390 # Sometimes the Directory path is a lie; check in the pool
391 if not os.path.exists(dsc_file):
392 if directory.split('/')[0] == "dists":
393 directory = Cnf["Dir::PoolRoot"] + utils.poolify(package, component);
394 dsc_file = os.path.join(Cnf["Dir::Root"], directory, "%s_%s.dsc" % (package, utils.re_no_epoch.sub('', version)));
395 if not os.path.exists(dsc_file):
396 utils.fubar("%s not found." % (dsc_file));
397 install_date = time.strftime("%Y-%m-%d", time.localtime(os.path.getmtime(dsc_file)));
398 fingerprint = check_signature(dsc_file);
399 fingerprint_id = db_access.get_or_set_fingerprint_id(fingerprint);
401 utils.fubar("%s: %s" % (dsc_file, reject_message));
402 maintainer = Scanner.Section["maintainer"]
403 maintainer = maintainer.replace("'", "\\'");
404 maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
405 location = get_location_path(directory.split('/')[0]);
406 location_id = db_access.get_location_id (location, component, archive);
407 if not directory.endswith("/"):
409 directory = poolify (directory, location);
410 if directory != "" and not directory.endswith("/"):
412 no_epoch_version = utils.re_no_epoch.sub('', version);
413 # Add all files referenced by the .dsc to the files table
415 for line in Scanner.Section["files"].split('\n'):
417 (md5sum, size, filename) = line.strip().split();
418 # Don't duplicate .orig.tar.gz's
419 if filename.endswith(".orig.tar.gz"):
420 cache_key = "%s~%s~%s" % (filename, size, md5sum);
421 if orig_tar_gz_cache.has_key(cache_key):
422 id = orig_tar_gz_cache[cache_key];
424 id = get_or_set_files_id (directory + filename, size, md5sum, location_id);
425 orig_tar_gz_cache[cache_key] = id;
427 id = get_or_set_files_id (directory + filename, size, md5sum, location_id);
429 # If this is the .dsc itself; save the ID for later.
430 if filename.endswith(".dsc"):
432 filename = directory + package + '_' + no_epoch_version + '.dsc'
433 cache_key = "%s~%s" % (package, version);
434 if not source_cache.has_key(cache_key):
435 nasty_key = "%s~%s" % (package, version)
436 source_id_serial += 1;
437 if not source_cache_for_binaries.has_key(nasty_key):
438 source_cache_for_binaries[nasty_key] = source_id_serial;
439 tmp_source_id = source_id_serial;
440 source_cache[cache_key] = source_id_serial;
441 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))
443 dsc_files_id_serial += 1;
444 dsc_files_query_cache.write("%d\t%d\t%d\n" % (dsc_files_id_serial, tmp_source_id,id));
446 tmp_source_id = source_cache[cache_key];
448 src_associations_id_serial += 1;
449 src_associations_query_cache.write("%d\t%d\t%d\n" % (src_associations_id_serial, suite_id, tmp_source_id))
453 ###############################################################################
455 def process_packages (filename, suite, component, archive):
456 global arch_all_cache, binary_cache, binaries_id_serial, binaries_query_cache, bin_associations_id_serial, bin_associations_query_cache, reject_message;
460 suite = suite.lower();
461 suite_id = db_access.get_suite_id(suite);
463 file = utils.open_file (filename);
464 except utils.cant_open_exc:
465 utils.warn("can't open '%s'" % (filename));
467 Scanner = apt_pkg.ParseTagFile(file);
468 while Scanner.Step() != 0:
469 package = Scanner.Section["package"]
470 version = Scanner.Section["version"]
471 maintainer = Scanner.Section["maintainer"]
472 maintainer = maintainer.replace("'", "\\'")
473 maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
474 architecture = Scanner.Section["architecture"]
475 architecture_id = db_access.get_architecture_id (architecture);
476 fingerprint = "NOSIG";
477 fingerprint_id = db_access.get_or_set_fingerprint_id(fingerprint);
478 if not Scanner.Section.has_key("source"):
481 source = Scanner.Section["source"]
483 if source.find("(") != -1:
484 m = utils.re_extract_src_version.match(source)
486 source_version = m.group(2)
487 if not source_version:
488 source_version = version
489 filename = Scanner.Section["filename"]
490 location = get_location_path(filename.split('/')[0]);
491 location_id = db_access.get_location_id (location, component, archive)
492 filename = poolify (filename, location)
493 if architecture == "all":
494 filename = re_arch_from_filename.sub("binary-all", filename);
495 cache_key = "%s~%s" % (source, source_version);
496 source_id = source_cache_for_binaries.get(cache_key, None);
497 size = Scanner.Section["size"];
498 md5sum = Scanner.Section["md5sum"];
499 files_id = get_or_set_files_id (filename, size, md5sum, location_id);
500 type = "deb"; # FIXME
501 cache_key = "%s~%s~%s~%d~%d~%d~%d" % (package, version, repr(source_id), architecture_id, location_id, files_id, suite_id);
502 if not arch_all_cache.has_key(cache_key):
503 arch_all_cache[cache_key] = 1;
504 cache_key = "%s~%s~%s~%d" % (package, version, repr(source_id), architecture_id);
505 if not binary_cache.has_key(cache_key):
510 source_id = repr(source_id);
511 binaries_id_serial += 1;
512 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));
513 binary_cache[cache_key] = binaries_id_serial;
514 tmp_binaries_id = binaries_id_serial;
516 tmp_binaries_id = binary_cache[cache_key];
518 bin_associations_id_serial += 1;
519 bin_associations_query_cache.write("%d\t%d\t%d\n" % (bin_associations_id_serial, suite_id, tmp_binaries_id));
524 print "%d binary packages processed; %d with no source match which is %.2f%%" % (count_total, count_bad, (float(count_bad)/count_total)*100);
526 print "%d binary packages processed; 0 with no source match which is 0%%" % (count_total);
528 ###############################################################################
530 def do_sources(sources, suite, component, server):
531 temp_filename = tempfile.mktemp();
532 fd = os.open(temp_filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
534 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (sources, temp_filename));
536 utils.fubar("Gunzip invocation failed!\n%s" % (output), result);
537 print 'Processing '+sources+'...';
538 process_sources (temp_filename, suite, component, server);
539 os.unlink(temp_filename);
541 ###############################################################################
544 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;
546 Cnf = utils.get_conf();
548 print "Re-Creating DB..."
549 (result, output) = commands.getstatusoutput("psql -f init_pool.sql template1");
551 utils.fubar("psql invocation failed!\n", result);
554 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]));
556 db_access.init (Cnf, projectB);
558 print "Adding static tables from conf file..."
559 projectB.query("BEGIN WORK");
560 update_architectures();
565 update_override_type();
568 projectB.query("COMMIT WORK");
570 files_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"files","w");
571 source_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"source","w");
572 src_associations_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"src_associations","w");
573 dsc_files_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"dsc_files","w");
574 binaries_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"binaries","w");
575 bin_associations_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"bin_associations","w");
577 projectB.query("BEGIN WORK");
578 # Process Sources files to popoulate `source' and friends
579 for location in Cnf.SubTree("Location").List():
580 SubSec = Cnf.SubTree("Location::%s" % (location));
581 server = SubSec["Archive"];
582 type = Cnf.Find("Location::%s::Type" % (location));
583 if type == "legacy-mixed":
584 sources = location + 'Sources.gz';
585 suite = Cnf.Find("Location::%s::Suite" % (location));
586 do_sources(sources, suite, "", server);
587 elif type == "legacy" or type == "pool":
588 for suite in Cnf.ValueList("Location::%s::Suites" % (location)):
589 for component in Cnf.SubTree("Component").List():
590 sources = Cnf["Dir::Root"] + "dists/" + Cnf["Suite::%s::CodeName" % (suite)] + '/' + component + '/source/' + 'Sources.gz';
591 do_sources(sources, suite, component, server);
593 utils.fubar("Unknown location type ('%s')." % (type));
595 # Process Packages files to populate `binaries' and friends
597 for location in Cnf.SubTree("Location").List():
598 SubSec = Cnf.SubTree("Location::%s" % (location));
599 server = SubSec["Archive"];
600 type = Cnf.Find("Location::%s::Type" % (location));
601 if type == "legacy-mixed":
602 packages = location + 'Packages';
603 suite = Cnf.Find("Location::%s::Suite" % (location));
604 print 'Processing '+location+'...';
605 process_packages (packages, suite, "", server);
606 elif type == "legacy" or type == "pool":
607 for suite in Cnf.ValueList("Location::%s::Suites" % (location)):
608 for component in Cnf.SubTree("Component").List():
609 architectures = filter(utils.real_arch,
610 Cnf.ValueList("Suite::%s::Architectures" % (suite)));
611 for architecture in architectures:
612 packages = Cnf["Dir::Root"] + "dists/" + Cnf["Suite::%s::CodeName" % (suite)] + '/' + component + '/binary-' + architecture + '/Packages'
613 print 'Processing '+packages+'...';
614 process_packages (packages, suite, component, server);
616 files_query_cache.close();
617 source_query_cache.close();
618 src_associations_query_cache.close();
619 dsc_files_query_cache.close();
620 binaries_query_cache.close();
621 bin_associations_query_cache.close();
622 print "Writing data to `files' table...";
623 projectB.query("COPY files FROM '%s'" % (Cnf["Neve::ExportDir"]+"files"));
624 print "Writing data to `source' table...";
625 projectB.query("COPY source FROM '%s'" % (Cnf["Neve::ExportDir"]+"source"));
626 print "Writing data to `src_associations' table...";
627 projectB.query("COPY src_associations FROM '%s'" % (Cnf["Neve::ExportDir"]+"src_associations"));
628 print "Writing data to `dsc_files' table...";
629 projectB.query("COPY dsc_files FROM '%s'" % (Cnf["Neve::ExportDir"]+"dsc_files"));
630 print "Writing data to `binaries' table...";
631 projectB.query("COPY binaries FROM '%s'" % (Cnf["Neve::ExportDir"]+"binaries"));
632 print "Writing data to `bin_associations' table...";
633 projectB.query("COPY bin_associations FROM '%s'" % (Cnf["Neve::ExportDir"]+"bin_associations"));
634 print "Committing...";
635 projectB.query("COMMIT WORK");
637 # Add the constraints and otherwise generally clean up the database.
638 # See add_constraints.sql for more details...
640 print "Running add_constraints.sql...";
641 (result, output) = commands.getstatusoutput("psql %s < add_constraints.sql" % (Cnf["DB::Name"]));
644 utils.fubar("psql invocation failed!\n%s" % (output), result);
648 ################################################################################
651 utils.try_with_debug(do_da_do_da);
653 ################################################################################
655 if __name__ == '__main__':