4 # Copyright (C) 2000, 2001, 2002 James Troup <james@nocrew.org>
5 # $Id: neve,v 1.15 2002-11-22 04:07:16 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 get_location_path(directory):
327 global location_path_cache;
329 if location_path_cache.has_key(directory):
330 return location_path_cache[directory];
332 q = projectB.query("SELECT DISTINCT path FROM location WHERE path ~ '%s'" % (directory));
334 path = q.getresult()[0][0];
336 utils.fubar("[neve] get_location_path(): Couldn't get path for %s" % (directory));
337 location_path_cache[directory] = path;
340 ###############################################################################
342 def get_or_set_files_id (filename, size, md5sum, location_id):
343 global files_id_cache, files_id_serial, files_query_cache;
345 cache_key = "~".join((filename, size, md5sum, repr(location_id)));
346 if not files_id_cache.has_key(cache_key):
348 files_query_cache.write("%d\t%s\t%s\t%s\t%d\n" % (files_id_serial, filename, size, md5sum, location_id));
349 files_id_cache[cache_key] = files_id_serial
351 return files_id_cache[cache_key]
353 ###############################################################################
355 def process_sources (filename, suite, component, archive):
356 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;
358 suite = suite.lower();
359 suite_id = db_access.get_suite_id(suite);
361 file = utils.open_file (filename);
362 except utils.cant_open_exc:
363 utils.warn("can't open '%s'" % (filename));
365 Scanner = apt_pkg.ParseTagFile(file);
366 while Scanner.Step() != 0:
367 package = Scanner.Section["package"];
368 version = Scanner.Section["version"];
369 directory = Scanner.Section["directory"];
370 dsc_file = os.path.join(Cnf["Dir::Root"], directory, "%s_%s.dsc" % (package, utils.re_no_epoch.sub('', version)));
371 install_date = time.strftime("%Y-%m-%d", time.localtime(os.path.getmtime(dsc_file)));
372 fingerprint = check_signature(dsc_file);
373 fingerprint_id = db_access.get_or_set_fingerprint_id(fingerprint);
375 utils.fubar("%s: %s" % (dsc_file, reject_message));
376 maintainer = Scanner.Section["maintainer"]
377 maintainer = maintainer.replace("'", "\\'");
378 maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
379 location = get_location_path(directory.split('/')[0]);
380 location_id = db_access.get_location_id (location, component, archive);
381 if not directory.endswith("/"):
383 directory = poolify (directory, location);
384 if directory != "" and not directory.endswith("/"):
386 no_epoch_version = utils.re_no_epoch.sub('', version);
387 # Add all files referenced by the .dsc to the files table
389 for line in Scanner.Section["files"].split('\n'):
391 (md5sum, size, filename) = line.strip().split();
392 # Don't duplicate .orig.tar.gz's
393 if filename.endswith(".orig.tar.gz"):
394 cache_key = "%s~%s~%s" % (filename, size, md5sum);
395 if orig_tar_gz_cache.has_key(cache_key):
396 id = orig_tar_gz_cache[cache_key];
398 id = get_or_set_files_id (directory + filename, size, md5sum, location_id);
399 orig_tar_gz_cache[cache_key] = id;
401 id = get_or_set_files_id (directory + filename, size, md5sum, location_id);
403 # If this is the .dsc itself; save the ID for later.
404 if filename.endswith(".dsc"):
406 filename = directory + package + '_' + no_epoch_version + '.dsc'
407 cache_key = "%s~%s" % (package, version);
408 if not source_cache.has_key(cache_key):
409 nasty_key = "%s~%s" % (package, version)
410 source_id_serial += 1;
411 if not source_cache_for_binaries.has_key(nasty_key):
412 source_cache_for_binaries[nasty_key] = source_id_serial;
413 tmp_source_id = source_id_serial;
414 source_cache[cache_key] = source_id_serial;
415 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))
417 dsc_files_id_serial += 1;
418 dsc_files_query_cache.write("%d\t%d\t%d\n" % (dsc_files_id_serial, tmp_source_id,id));
420 tmp_source_id = source_cache[cache_key];
422 src_associations_id_serial += 1;
423 src_associations_query_cache.write("%d\t%d\t%d\n" % (src_associations_id_serial, suite_id, tmp_source_id))
427 ###############################################################################
429 def process_packages (filename, suite, component, archive):
430 global arch_all_cache, binary_cache, binaries_id_serial, binaries_query_cache, bin_associations_id_serial, bin_associations_query_cache, reject_message;
434 suite = suite.lower();
435 suite_id = db_access.get_suite_id(suite);
437 file = utils.open_file (filename);
438 except utils.cant_open_exc:
439 utils.warn("can't open '%s'" % (filename));
441 Scanner = apt_pkg.ParseTagFile(file);
442 while Scanner.Step() != 0:
443 package = Scanner.Section["package"]
444 version = Scanner.Section["version"]
445 maintainer = Scanner.Section["maintainer"]
446 maintainer = maintainer.replace("'", "\\'")
447 maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
448 architecture = Scanner.Section["architecture"]
449 architecture_id = db_access.get_architecture_id (architecture);
450 fingerprint = "NOSIG";
451 fingerprint_id = db_access.get_or_set_fingerprint_id(fingerprint);
452 if not Scanner.Section.has_key("source"):
455 source = Scanner.Section["source"]
457 if source.find("(") != -1:
458 m = utils.re_extract_src_version.match(source)
460 source_version = m.group(2)
461 if not source_version:
462 source_version = version
463 filename = Scanner.Section["filename"]
464 location = get_location_path(filename.split('/')[0]);
465 location_id = db_access.get_location_id (location, component, archive)
466 filename = poolify (filename, location)
467 if architecture == "all":
468 filename = re_arch_from_filename.sub("binary-all", filename);
469 cache_key = "%s~%s" % (source, source_version);
470 source_id = source_cache_for_binaries.get(cache_key, None);
471 size = Scanner.Section["size"];
472 md5sum = Scanner.Section["md5sum"];
473 files_id = get_or_set_files_id (filename, size, md5sum, location_id);
474 type = "deb"; # FIXME
475 cache_key = "%s~%s~%s~%d~%d~%d" % (package, version, repr(source_id), architecture_id, location_id, files_id);
476 if not arch_all_cache.has_key(cache_key):
477 arch_all_cache[cache_key] = 1;
478 cache_key = "%s~%s~%s~%d" % (package, version, repr(source_id), architecture_id);
479 if not binary_cache.has_key(cache_key):
484 source_id = repr(source_id);
485 binaries_id_serial += 1;
486 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));
487 binary_cache[cache_key] = binaries_id_serial;
488 tmp_binaries_id = binaries_id_serial;
490 tmp_binaries_id = binary_cache[cache_key];
492 bin_associations_id_serial += 1;
493 bin_associations_query_cache.write("%d\t%d\t%d\n" % (bin_associations_id_serial, suite_id, tmp_binaries_id));
498 print "%d binary packages processed; %d with no source match which is %.2f%%" % (count_total, count_bad, (float(count_bad)/count_total)*100);
500 print "%d binary packages processed; 0 with no source match which is 0%%" % (count_total);
502 ###############################################################################
504 def do_sources(sources, suite, component, server):
505 temp_filename = tempfile.mktemp();
506 fd = os.open(temp_filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
508 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (sources, temp_filename));
510 utils.fubar("Gunzip invocation failed!\n%s" % (output), result);
511 print 'Processing '+sources+'...';
512 process_sources (temp_filename, suite, component, server);
513 os.unlink(temp_filename);
515 ###############################################################################
518 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;
520 Cnf = utils.get_conf();
522 print "Re-Creating DB..."
523 (result, output) = commands.getstatusoutput("psql -f init_pool.sql template1");
525 utils.fubar("psql invocation failed!\n", result);
528 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]));
530 db_access.init (Cnf, projectB);
532 print "Adding static tables from conf file..."
533 projectB.query("BEGIN WORK");
534 update_architectures();
539 update_override_type();
541 projectB.query("COMMIT WORK");
543 files_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"files","w");
544 source_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"source","w");
545 src_associations_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"src_associations","w");
546 dsc_files_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"dsc_files","w");
547 binaries_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"binaries","w");
548 bin_associations_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"bin_associations","w");
550 projectB.query("BEGIN WORK");
551 # Process Sources files to popoulate `source' and friends
552 for location in Cnf.SubTree("Location").List():
553 SubSec = Cnf.SubTree("Location::%s" % (location));
554 server = SubSec["Archive"];
555 type = Cnf.Find("Location::%s::Type" % (location));
556 if type == "legacy-mixed":
557 sources = location + 'Sources.gz';
558 suite = Cnf.Find("Location::%s::Suite" % (location));
559 do_sources(sources, suite, "", server);
560 elif type == "legacy" or type == "pool":
561 for suite in Cnf.ValueList("Location::%s::Suites" % (location)):
562 for component in Cnf.SubTree("Component").List():
563 sources = Cnf["Dir::Root"] + "dists/" + Cnf["Suite::%s::CodeName" % (suite)] + '/' + component + '/source/' + 'Sources.gz';
564 do_sources(sources, suite, component, server);
566 utils.fubar("Unknown location type ('%s')." % (type));
568 # Process Packages files to populate `binaries' and friends
570 for location in Cnf.SubTree("Location").List():
571 SubSec = Cnf.SubTree("Location::%s" % (location));
572 server = SubSec["Archive"];
573 type = Cnf.Find("Location::%s::Type" % (location));
574 if type == "legacy-mixed":
575 packages = location + 'Packages';
576 suite = Cnf.Find("Location::%s::Suite" % (location));
577 print 'Processing '+location+'...';
578 process_packages (packages, suite, "", server);
579 elif type == "legacy" or type == "pool":
580 for suite in Cnf.ValueList("Location::%s::Suites" % (location)):
581 for component in Cnf.SubTree("Component").List():
582 architectures = filter(utils.real_arch,
583 Cnf.ValueList("Suite::%s::Architectures" % (suite)));
584 for architecture in architectures:
585 packages = Cnf["Dir::Root"] + "dists/" + Cnf["Suite::%s::CodeName" % (suite)] + '/' + component + '/binary-' + architecture + '/Packages'
586 print 'Processing '+packages+'...';
587 process_packages (packages, suite, component, server);
589 files_query_cache.close();
590 source_query_cache.close();
591 src_associations_query_cache.close();
592 dsc_files_query_cache.close();
593 binaries_query_cache.close();
594 bin_associations_query_cache.close();
595 print "Writing data to `files' table...";
596 projectB.query("COPY files FROM '%s'" % (Cnf["Neve::ExportDir"]+"files"));
597 print "Writing data to `source' table...";
598 projectB.query("COPY source FROM '%s'" % (Cnf["Neve::ExportDir"]+"source"));
599 print "Writing data to `src_associations' table...";
600 projectB.query("COPY src_associations FROM '%s'" % (Cnf["Neve::ExportDir"]+"src_associations"));
601 print "Writing data to `dsc_files' table...";
602 projectB.query("COPY dsc_files FROM '%s'" % (Cnf["Neve::ExportDir"]+"dsc_files"));
603 print "Writing data to `binaries' table...";
604 projectB.query("COPY binaries FROM '%s'" % (Cnf["Neve::ExportDir"]+"binaries"));
605 print "Writing data to `bin_associations' table...";
606 projectB.query("COPY bin_associations FROM '%s'" % (Cnf["Neve::ExportDir"]+"bin_associations"));
607 print "Committing...";
608 projectB.query("COMMIT WORK");
610 # Add the constraints and otherwise generally clean up the database.
611 # See add_constraints.sql for more details...
613 print "Running add_constraints.sql...";
614 (result, output) = commands.getstatusoutput("psql %s < add_constraints.sql" % (Cnf["DB::Name"]));
617 utils.fubar("psql invocation failed!\n%s" % (output), result);
621 ################################################################################
629 ################################################################################
631 if __name__ == '__main__':