]> git.decadent.org.uk Git - dak.git/blob - neve
add -i to quinn-diff invocation
[dak.git] / neve
1 #!/usr/bin/env python
2
3 # Populate the DB
4 # Copyright (C) 2000, 2001, 2002  James Troup <james@nocrew.org>
5 # $Id: neve,v 1.17 2003-01-02 18:15:07 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 # 04:36|<aj> elmo: you're making me waste 5 seconds per architecture!!!!!! YOU BASTARD!!!!!
24
25 ###############################################################################
26
27 # This code is a horrible mess for two reasons:
28
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.)
33
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.
37
38 ###############################################################################
39
40 import commands, os, pg, re, select, sys, tempfile, time;
41 import apt_pkg;
42 import db_access, utils;
43
44 ###############################################################################
45
46 re_arch_from_filename = re.compile(r"binary-[^/]+")
47
48 ###############################################################################
49
50 Cnf = None;
51 projectB = None;
52 files_id_cache = {};
53 source_cache = {};
54 arch_all_cache = {};
55 binary_cache = {};
56 location_path_cache = {};
57 #
58 files_id_serial = 0;
59 source_id_serial = 0;
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 = {};
67 #
68 binaries_id_serial = 0;
69 binaries_query_cache = None;
70 bin_associations_id_serial = 0;
71 bin_associations_query_cache = None;
72 #
73 source_cache_for_binaries = {};
74 reject_message = "";
75
76 ################################################################################
77
78 def usage(exit_code=0):
79     print """Usage: neve
80 Initializes a projectB database from an existing archive
81
82   -a, --action              actually perform the initalization
83   -h, --help                show this help and exit."""
84     sys.exit(exit_code)
85
86 ###############################################################################
87
88 # Our very own version of commands.getouputstatus(), hacked to support
89 # gpgv's status fd.
90 def get_status_output(cmd, status_read, status_write):
91     cmd = ['/bin/sh', '-c', cmd];
92     p2cread, p2cwrite = os.pipe();
93     c2pread, c2pwrite = os.pipe();
94     errout, errin = os.pipe();
95     pid = os.fork();
96     if pid == 0:
97         # Child
98         os.close(0);
99         os.close(1);
100         os.dup(p2cread);
101         os.dup(c2pwrite);
102         os.close(2);
103         os.dup(errin);
104         for i in range(3, 256):
105             if i != status_write:
106                 try:
107                     os.close(i);
108                 except:
109                     pass;
110         try:
111             os.execvp(cmd[0], cmd);
112         finally:
113             os._exit(1);
114
115     # parent
116     os.close(p2cread)
117     os.dup2(c2pread, c2pwrite);
118     os.dup2(errout, errin);
119
120     output = status = "";
121     while 1:
122         i, o, e = select.select([c2pwrite, errin, status_read], [], []);
123         more_data = [];
124         for fd in i:
125             r = os.read(fd, 8196);
126             if len(r) > 0:
127                 more_data.append(fd);
128                 if fd == c2pwrite or fd == errin:
129                     output += r;
130                 elif fd == status_read:
131                     status += r;
132                 else:
133                     utils.fubar("Unexpected file descriptor [%s] returned from select\n" % (fd));
134         if not more_data:
135             pid, exit_status = os.waitpid(pid, 0)
136             try:
137                 os.close(status_write);
138                 os.close(status_read);
139                 os.close(c2pwrite);
140                 os.close(p2cwrite);
141                 os.close(errin);
142             except:
143                 pass;
144             break;
145
146     return output, status, exit_status;
147
148 ###############################################################################
149
150 def Dict(**dict): return dict
151
152 def reject (str, prefix="Rejected: "):
153     global reject_message;
154     if str:
155         reject_message += prefix + str + "\n";
156
157 ###############################################################################
158
159 def check_signature (filename):
160     if not utils.re_taint_free.match(os.path.basename(filename)):
161         reject("!!WARNING!! tainted filename: '%s'." % (filename));
162         return None;
163
164     status_read, status_write = os.pipe();
165     cmd = "gpgv --status-fd %s --keyring %s --keyring %s %s" \
166           % (status_write, Cnf["Dinstall::PGPKeyring"], Cnf["Dinstall::GPGKeyring"], filename);
167     (output, status, exit_status) = get_status_output(cmd, status_read, status_write);
168
169     # Process the status-fd output
170     keywords = {};
171     bad = internal_error = "";
172     for line in status.split('\n'):
173         line = line.strip();
174         if line == "":
175             continue;
176         split = line.split();
177         if len(split) < 2:
178             internal_error += "gpgv status line is malformed (< 2 atoms) ['%s'].\n" % (line);
179             continue;
180         (gnupg, keyword) = split[:2];
181         if gnupg != "[GNUPG:]":
182             internal_error += "gpgv status line is malformed (incorrect prefix '%s').\n" % (gnupg);
183             continue;
184         args = split[2:];
185         if keywords.has_key(keyword) and keyword != "NODATA" and keyword != "SIGEXPIRED":
186             internal_error += "found duplicate status token ('%s')." % (keyword);
187             continue;
188         else:
189             keywords[keyword] = args;
190
191     # If we failed to parse the status-fd output, let's just whine and bail now
192     if internal_error:
193         reject("internal error while performing signature check on %s." % (filename));
194         reject(internal_error, "");
195         reject("Please report the above errors to the Archive maintainers by replying to this mail.", "");
196         return None;
197
198     # Now check for obviously bad things in the processed output
199     if keywords.has_key("SIGEXPIRED"):
200         utils.warn("%s: signing key has expired." % (filename));
201     if keywords.has_key("KEYREVOKED"):
202         reject("key used to sign %s has been revoked." % (filename));
203         bad = 1;
204     if keywords.has_key("BADSIG"):
205         reject("bad signature on %s." % (filename));
206         bad = 1;
207     if keywords.has_key("ERRSIG") and not keywords.has_key("NO_PUBKEY"):
208         reject("failed to check signature on %s." % (filename));
209         bad = 1;
210     if keywords.has_key("NO_PUBKEY"):
211         args = keywords["NO_PUBKEY"];
212         if len(args) < 1:
213             reject("internal error while checking signature on %s." % (filename));
214             bad = 1;
215         else:
216             fingerprint = args[0];
217     if keywords.has_key("BADARMOR"):
218         reject("ascii armour of signature was corrupt in %s." % (filename));
219         bad = 1;
220     if keywords.has_key("NODATA"):
221         utils.warn("no signature found for %s." % (filename));
222         return "NOSIG";
223         #reject("no signature found in %s." % (filename));
224         #bad = 1;
225
226     if bad:
227         return None;
228
229     # Next check gpgv exited with a zero return code
230     if exit_status and not keywords.has_key("NO_PUBKEY"):
231         reject("gpgv failed while checking %s." % (filename));
232         if status.strip():
233             reject(utils.prefix_multi_line_string(status, " [GPG status-fd output:] "), "");
234         else:
235             reject(utils.prefix_multi_line_string(output, " [GPG output:] "), "");
236         return None;
237
238     # Sanity check the good stuff we expect
239     if not keywords.has_key("VALIDSIG"):
240         if not keywords.has_key("NO_PUBKEY"):
241             reject("signature on %s does not appear to be valid [No VALIDSIG]." % (filename));
242             bad = 1;
243     else:
244         args = keywords["VALIDSIG"];
245         if len(args) < 1:
246             reject("internal error while checking signature on %s." % (filename));
247             bad = 1;
248         else:
249             fingerprint = args[0];
250     if not keywords.has_key("GOODSIG") and not keywords.has_key("NO_PUBKEY"):
251         reject("signature on %s does not appear to be valid [No GOODSIG]." % (filename));
252         bad = 1;
253     if not keywords.has_key("SIG_ID") and not keywords.has_key("NO_PUBKEY"):
254         reject("signature on %s does not appear to be valid [No SIG_ID]." % (filename));
255         bad = 1;
256
257     # Finally ensure there's not something we don't recognise
258     known_keywords = Dict(VALIDSIG="",SIG_ID="",GOODSIG="",BADSIG="",ERRSIG="",
259                           SIGEXPIRED="",KEYREVOKED="",NO_PUBKEY="",BADARMOR="",
260                           NODATA="");
261
262     for keyword in keywords.keys():
263         if not known_keywords.has_key(keyword):
264             reject("found unknown status token '%s' from gpgv with args '%r' in %s." % (keyword, keywords[keyword], filename));
265             bad = 1;
266
267     if bad:
268         return None;
269     else:
270         return fingerprint;
271
272 ################################################################################
273
274 # Prepares a filename or directory (s) to be file.filename by stripping any part of the location (sub) from it.
275 def poolify (s, sub):
276     for i in xrange(len(sub)):
277         if sub[i:] == s[0:len(sub)-i]:
278             return s[len(sub)-i:];
279     return s;
280
281 def update_archives ():
282     projectB.query("DELETE FROM archive")
283     for archive in Cnf.SubTree("Archive").List():
284         SubSec = Cnf.SubTree("Archive::%s" % (archive));
285         projectB.query("INSERT INTO archive (name, origin_server, description) VALUES ('%s', '%s', '%s')"
286                        % (archive, SubSec["OriginServer"], SubSec["Description"]));
287
288 def update_components ():
289     projectB.query("DELETE FROM component")
290     for component in Cnf.SubTree("Component").List():
291         SubSec = Cnf.SubTree("Component::%s" % (component));
292         projectB.query("INSERT INTO component (name, description, meets_dfsg) VALUES ('%s', '%s', '%s')" %
293                        (component, SubSec["Description"], SubSec["MeetsDFSG"]));
294
295 def update_locations ():
296     projectB.query("DELETE FROM location")
297     for location in Cnf.SubTree("Location").List():
298         SubSec = Cnf.SubTree("Location::%s" % (location));
299         archive_id = db_access.get_archive_id(SubSec["archive"]);
300         type = SubSec.Find("type");
301         if type == "legacy-mixed":
302             projectB.query("INSERT INTO location (path, archive, type) VALUES ('%s', %d, '%s')" % (location, archive_id, SubSec["type"]));
303         else:
304             for component in Cnf.SubTree("Component").List():
305                 component_id = db_access.get_component_id(component);
306                 projectB.query("INSERT INTO location (path, component, archive, type) VALUES ('%s', %d, %d, '%s')" %
307                                (location, component_id, archive_id, SubSec["type"]));
308
309 def update_architectures ():
310     projectB.query("DELETE FROM architecture")
311     for arch in Cnf.SubTree("Architectures").List():
312         projectB.query("INSERT INTO architecture (arch_string, description) VALUES ('%s', '%s')" % (arch, Cnf["Architectures::%s" % (arch)]))
313
314 def update_suites ():
315     projectB.query("DELETE FROM suite")
316     for suite in Cnf.SubTree("Suite").List():
317         SubSec = Cnf.SubTree("Suite::%s" %(suite))
318         projectB.query("INSERT INTO suite (suite_name) VALUES ('%s')" % suite.lower());
319         for i in ("Version", "Origin", "Description"):
320             if SubSec.has_key(i):
321                 projectB.query("UPDATE suite SET %s = '%s' WHERE suite_name = '%s'" % (i.lower(), SubSec[i], suite.lower()))
322         for architecture in Cnf.ValueList("Suite::%s::Architectures" % (suite)):
323             architecture_id = db_access.get_architecture_id (architecture);
324             projectB.query("INSERT INTO suite_architectures (suite, architecture) VALUES (currval('suite_id_seq'), %d)" % (architecture_id));
325
326 def update_override_type():
327     projectB.query("DELETE FROM override_type");
328     for type in Cnf.ValueList("OverrideType"):
329         projectB.query("INSERT INTO override_type (type) VALUES ('%s')" % (type));
330
331 def update_priority():
332     projectB.query("DELETE FROM priority");
333     for priority in Cnf.SubTree("Priority").List():
334         projectB.query("INSERT INTO priority (priority, level) VALUES ('%s', %s)" % (priority, Cnf["Priority::%s" % (priority)]));
335
336 def update_section():
337     projectB.query("DELETE FROM section");
338     for component in Cnf.SubTree("Component").List():
339         if Cnf["Natalie::ComponentPosition"] == "prefix":
340             suffix = "";
341             if component != 'main':
342                 prefix = component + '/';
343             else:
344                 prefix = "";
345         else:
346             prefix = "";
347             component = component.replace("non-US/", "");
348             if component != 'main':
349                 suffix = '/' + component;
350             else:
351                 suffix = "";
352         for section in Cnf.ValueList("Section"):
353             projectB.query("INSERT INTO section (section) VALUES ('%s%s%s')" % (prefix, section, suffix));
354
355 def get_location_path(directory):
356     global location_path_cache;
357
358     if location_path_cache.has_key(directory):
359         return location_path_cache[directory];
360
361     q = projectB.query("SELECT DISTINCT path FROM location WHERE path ~ '%s'" % (directory));
362     try:
363         path = q.getresult()[0][0];
364     except:
365         utils.fubar("[neve] get_location_path(): Couldn't get path for %s" % (directory));
366     location_path_cache[directory] = path;
367     return path;
368
369 ################################################################################
370
371 def get_or_set_files_id (filename, size, md5sum, location_id):
372     global files_id_cache, files_id_serial, files_query_cache;
373
374     cache_key = "~".join((filename, size, md5sum, repr(location_id)));
375     if not files_id_cache.has_key(cache_key):
376         files_id_serial += 1
377         files_query_cache.write("%d\t%s\t%s\t%s\t%d\n" % (files_id_serial, filename, size, md5sum, location_id));
378         files_id_cache[cache_key] = files_id_serial
379
380     return files_id_cache[cache_key]
381
382 ###############################################################################
383
384 def process_sources (filename, suite, component, archive):
385     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;
386
387     suite = suite.lower();
388     suite_id = db_access.get_suite_id(suite);
389     try:
390         file = utils.open_file (filename);
391     except utils.cant_open_exc:
392         utils.warn("can't open '%s'" % (filename));
393         return;
394     Scanner = apt_pkg.ParseTagFile(file);
395     while Scanner.Step() != 0:
396         package = Scanner.Section["package"];
397         version = Scanner.Section["version"];
398         directory = Scanner.Section["directory"];
399         dsc_file = os.path.join(Cnf["Dir::Root"], directory, "%s_%s.dsc" % (package, utils.re_no_epoch.sub('', version)));
400         # Sometimes the Directory path is a lie; check in the pool
401         if not os.path.exists(dsc_file):
402             if directory.split('/')[0] == "dists":
403                 directory = Cnf["Dir::PoolRoot"] + utils.poolify(package, component);
404                 dsc_file = os.path.join(Cnf["Dir::Root"], directory, "%s_%s.dsc" % (package, utils.re_no_epoch.sub('', version)));
405         if not os.path.exists(dsc_file):
406             utils.fubar("%s not found." % (dsc_file));
407         install_date = time.strftime("%Y-%m-%d", time.localtime(os.path.getmtime(dsc_file)));
408         fingerprint = check_signature(dsc_file);
409         fingerprint_id = db_access.get_or_set_fingerprint_id(fingerprint);
410         if reject_message:
411             utils.fubar("%s: %s" % (dsc_file, reject_message));
412         maintainer = Scanner.Section["maintainer"]
413         maintainer = maintainer.replace("'", "\\'");
414         maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
415         location = get_location_path(directory.split('/')[0]);
416         location_id = db_access.get_location_id (location, component, archive);
417         if not directory.endswith("/"):
418             directory += '/';
419         directory = poolify (directory, location);
420         if directory != "" and not directory.endswith("/"):
421             directory += '/';
422         no_epoch_version = utils.re_no_epoch.sub('', version);
423         # Add all files referenced by the .dsc to the files table
424         ids = [];
425         for line in Scanner.Section["files"].split('\n'):
426             id = None;
427             (md5sum, size, filename) = line.strip().split();
428             # Don't duplicate .orig.tar.gz's
429             if filename.endswith(".orig.tar.gz"):
430                 cache_key = "%s~%s~%s" % (filename, size, md5sum);
431                 if orig_tar_gz_cache.has_key(cache_key):
432                     id = orig_tar_gz_cache[cache_key];
433                 else:
434                     id = get_or_set_files_id (directory + filename, size, md5sum, location_id);
435                     orig_tar_gz_cache[cache_key] = id;
436             else:
437                 id = get_or_set_files_id (directory + filename, size, md5sum, location_id);
438             ids.append(id);
439             # If this is the .dsc itself; save the ID for later.
440             if filename.endswith(".dsc"):
441                 files_id = id;
442         filename = directory + package + '_' + no_epoch_version + '.dsc'
443         cache_key = "%s~%s" % (package, version);
444         if not source_cache.has_key(cache_key):
445             nasty_key = "%s~%s" % (package, version)
446             source_id_serial += 1;
447             if not source_cache_for_binaries.has_key(nasty_key):
448                 source_cache_for_binaries[nasty_key] = source_id_serial;
449             tmp_source_id = source_id_serial;
450             source_cache[cache_key] = source_id_serial;
451             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))
452             for id in ids:
453                 dsc_files_id_serial += 1;
454                 dsc_files_query_cache.write("%d\t%d\t%d\n" % (dsc_files_id_serial, tmp_source_id,id));
455         else:
456             tmp_source_id = source_cache[cache_key];
457
458         src_associations_id_serial += 1;
459         src_associations_query_cache.write("%d\t%d\t%d\n" % (src_associations_id_serial, suite_id, tmp_source_id))
460
461     file.close();
462
463 ###############################################################################
464
465 def process_packages (filename, suite, component, archive):
466     global arch_all_cache, binary_cache, binaries_id_serial, binaries_query_cache, bin_associations_id_serial, bin_associations_query_cache, reject_message;
467
468     count_total = 0;
469     count_bad = 0;
470     suite = suite.lower();
471     suite_id = db_access.get_suite_id(suite);
472     try:
473         file = utils.open_file (filename);
474     except utils.cant_open_exc:
475         utils.warn("can't open '%s'" % (filename));
476         return;
477     Scanner = apt_pkg.ParseTagFile(file);
478     while Scanner.Step() != 0:
479         package = Scanner.Section["package"]
480         version = Scanner.Section["version"]
481         maintainer = Scanner.Section["maintainer"]
482         maintainer = maintainer.replace("'", "\\'")
483         maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
484         architecture = Scanner.Section["architecture"]
485         architecture_id = db_access.get_architecture_id (architecture);
486         fingerprint = "NOSIG";
487         fingerprint_id = db_access.get_or_set_fingerprint_id(fingerprint);
488         if not Scanner.Section.has_key("source"):
489             source = package
490         else:
491             source = Scanner.Section["source"]
492         source_version = ""
493         if source.find("(") != -1:
494             m = utils.re_extract_src_version.match(source)
495             source = m.group(1)
496             source_version = m.group(2)
497         if not source_version:
498             source_version = version
499         filename = Scanner.Section["filename"]
500         location = get_location_path(filename.split('/')[0]);
501         location_id = db_access.get_location_id (location, component, archive)
502         filename = poolify (filename, location)
503         if architecture == "all":
504             filename = re_arch_from_filename.sub("binary-all", filename);
505         cache_key = "%s~%s" % (source, source_version);
506         source_id = source_cache_for_binaries.get(cache_key, None);
507         size = Scanner.Section["size"];
508         md5sum = Scanner.Section["md5sum"];
509         files_id = get_or_set_files_id (filename, size, md5sum, location_id);
510         type = "deb"; # FIXME
511         cache_key = "%s~%s~%s~%d~%d~%d~%d" % (package, version, repr(source_id), architecture_id, location_id, files_id, suite_id);
512         if not arch_all_cache.has_key(cache_key):
513             arch_all_cache[cache_key] = 1;
514             cache_key = "%s~%s~%s~%d" % (package, version, repr(source_id), architecture_id);
515             if not binary_cache.has_key(cache_key):
516                 if not source_id:
517                     source_id = "\N";
518                     count_bad += 1;
519                 else:
520                     source_id = repr(source_id);
521                 binaries_id_serial += 1;
522                 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));
523                 binary_cache[cache_key] = binaries_id_serial;
524                 tmp_binaries_id = binaries_id_serial;
525             else:
526                 tmp_binaries_id = binary_cache[cache_key];
527
528             bin_associations_id_serial += 1;
529             bin_associations_query_cache.write("%d\t%d\t%d\n" % (bin_associations_id_serial, suite_id, tmp_binaries_id));
530             count_total += 1;
531
532     file.close();
533     if count_bad != 0:
534         print "%d binary packages processed; %d with no source match which is %.2f%%" % (count_total, count_bad, (float(count_bad)/count_total)*100);
535     else:
536         print "%d binary packages processed; 0 with no source match which is 0%%" % (count_total);
537
538 ###############################################################################
539
540 def do_sources(sources, suite, component, server):
541     temp_filename = tempfile.mktemp();
542     fd = os.open(temp_filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
543     os.close(fd);
544     (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (sources, temp_filename));
545     if (result != 0):
546         utils.fubar("Gunzip invocation failed!\n%s" % (output), result);
547     print 'Processing '+sources+'...';
548     process_sources (temp_filename, suite, component, server);
549     os.unlink(temp_filename);
550
551 ###############################################################################
552
553 def do_da_do_da ():
554     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;
555
556     Cnf = utils.get_conf();
557     Arguments = [('a', "action", "Neve::Options::Action"),
558                  ('h', "help", "Neve::Options::Help")];
559     for i in [ "action", "help" ]:
560         if not Cnf.has_key("Neve::Options::%s" % (i)):
561             Cnf["Neve::Options::%s" % (i)] = "";
562
563     apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv);
564
565     Options = Cnf.SubTree("Neve::Options")
566     if Options["Help"]:
567         usage();
568
569     if not Options["Action"]:
570         utils.warn("""no -a/--action given; not doing anything.
571 Please read the documentation before running this script.
572 """);
573         usage(1);
574
575     print "Re-Creating DB..."
576     (result, output) = commands.getstatusoutput("psql -f init_pool.sql template1");
577     if (result != 0):
578         utils.fubar("psql invocation failed!\n", result);
579     print output;
580
581     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]));
582
583     db_access.init (Cnf, projectB);
584
585     print "Adding static tables from conf file..."
586     projectB.query("BEGIN WORK");
587     update_architectures();
588     update_components();
589     update_archives();
590     update_locations();
591     update_suites();
592     update_override_type();
593     update_priority();
594     update_section();
595     projectB.query("COMMIT WORK");
596
597     files_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"files","w");
598     source_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"source","w");
599     src_associations_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"src_associations","w");
600     dsc_files_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"dsc_files","w");
601     binaries_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"binaries","w");
602     bin_associations_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"bin_associations","w");
603
604     projectB.query("BEGIN WORK");
605     # Process Sources files to popoulate `source' and friends
606     for location in Cnf.SubTree("Location").List():
607         SubSec = Cnf.SubTree("Location::%s" % (location));
608         server = SubSec["Archive"];
609         type = Cnf.Find("Location::%s::Type" % (location));
610         if type == "legacy-mixed":
611             sources = location + 'Sources.gz';
612             suite = Cnf.Find("Location::%s::Suite" % (location));
613             do_sources(sources, suite, "",  server);
614         elif type == "legacy" or type == "pool":
615             for suite in Cnf.ValueList("Location::%s::Suites" % (location)):
616                 for component in Cnf.SubTree("Component").List():
617                     sources = Cnf["Dir::Root"] + "dists/" + Cnf["Suite::%s::CodeName" % (suite)] + '/' + component + '/source/' + 'Sources.gz';
618                     do_sources(sources, suite, component, server);
619         else:
620             utils.fubar("Unknown location type ('%s')." % (type));
621
622     # Process Packages files to populate `binaries' and friends
623
624     for location in Cnf.SubTree("Location").List():
625         SubSec = Cnf.SubTree("Location::%s" % (location));
626         server = SubSec["Archive"];
627         type = Cnf.Find("Location::%s::Type" % (location));
628         if type == "legacy-mixed":
629             packages = location + 'Packages';
630             suite = Cnf.Find("Location::%s::Suite" % (location));
631             print 'Processing '+location+'...';
632             process_packages (packages, suite, "", server);
633         elif type == "legacy" or type == "pool":
634             for suite in Cnf.ValueList("Location::%s::Suites" % (location)):
635                 for component in Cnf.SubTree("Component").List():
636                     architectures = filter(utils.real_arch,
637                                            Cnf.ValueList("Suite::%s::Architectures" % (suite)));
638                     for architecture in architectures:
639                         packages = Cnf["Dir::Root"] + "dists/" + Cnf["Suite::%s::CodeName" % (suite)] + '/' + component + '/binary-' + architecture + '/Packages'
640                         print 'Processing '+packages+'...';
641                         process_packages (packages, suite, component, server);
642
643     files_query_cache.close();
644     source_query_cache.close();
645     src_associations_query_cache.close();
646     dsc_files_query_cache.close();
647     binaries_query_cache.close();
648     bin_associations_query_cache.close();
649     print "Writing data to `files' table...";
650     projectB.query("COPY files FROM '%s'" % (Cnf["Neve::ExportDir"]+"files"));
651     print "Writing data to `source' table...";
652     projectB.query("COPY source FROM '%s'" % (Cnf["Neve::ExportDir"]+"source"));
653     print "Writing data to `src_associations' table...";
654     projectB.query("COPY src_associations FROM '%s'" % (Cnf["Neve::ExportDir"]+"src_associations"));
655     print "Writing data to `dsc_files' table...";
656     projectB.query("COPY dsc_files FROM '%s'" % (Cnf["Neve::ExportDir"]+"dsc_files"));
657     print "Writing data to `binaries' table...";
658     projectB.query("COPY binaries FROM '%s'" % (Cnf["Neve::ExportDir"]+"binaries"));
659     print "Writing data to `bin_associations' table...";
660     projectB.query("COPY bin_associations FROM '%s'" % (Cnf["Neve::ExportDir"]+"bin_associations"));
661     print "Committing...";
662     projectB.query("COMMIT WORK");
663
664     # Add the constraints and otherwise generally clean up the database.
665     # See add_constraints.sql for more details...
666
667     print "Running add_constraints.sql...";
668     (result, output) = commands.getstatusoutput("psql %s < add_constraints.sql" % (Cnf["DB::Name"]));
669     print output
670     if (result != 0):
671         utils.fubar("psql invocation failed!\n%s" % (output), result);
672
673     return;
674
675 ################################################################################
676
677 def main():
678     utils.try_with_debug(do_da_do_da);
679
680 ################################################################################
681
682 if __name__ == '__main__':
683     main();