]> git.decadent.org.uk Git - dak.git/blob - dak/import_archive.py
00b5d1b6b5d8f1673bf2bf9cc5358244694c9d9a
[dak.git] / dak / import_archive.py
1 #!/usr/bin/env python
2
3 # Populate the DB
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006  James Troup <james@nocrew.org>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20 ###############################################################################
21
22 # 04:36|<aj> elmo: you're making me waste 5 seconds per architecture!!!!!! YOU BASTARD!!!!!
23
24 ###############################################################################
25
26 # This code is a horrible mess for two reasons:
27
28 #   (o) For Debian's usage, it's doing something like 160k INSERTs,
29 #   even on auric, that makes the program unusable unless we get
30 #   involed in sorts of silly optimization games (local dicts to avoid
31 #   redundant SELECTS, using COPY FROM rather than INSERTS etc.)
32
33 #   (o) It's very site specific, because I don't expect to use this
34 #   script again in a hurry, and I don't want to spend any more time
35 #   on it than absolutely necessary.
36
37 ###############################################################################
38
39 import commands, os, pg, sys, time
40 import apt_pkg
41 from daklib import database
42 from daklib import utils
43 from daklib.dak_exceptions import *
44 from daklib.regexes import re_arch_from_filename, re_taint_free, re_no_epoch, \
45                            re_extract_src_version
46
47 ###############################################################################
48
49 Cnf = None
50 projectB = None
51 files_id_cache = {}
52 source_cache = {}
53 arch_all_cache = {}
54 binary_cache = {}
55 location_path_cache = {}
56 #
57 files_id_serial = 0
58 source_id_serial = 0
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 = {}
66 #
67 binaries_id_serial = 0
68 binaries_query_cache = None
69 bin_associations_id_serial = 0
70 bin_associations_query_cache = None
71 #
72 source_cache_for_binaries = {}
73 reject_message = ""
74
75 ################################################################################
76
77 def usage(exit_code=0):
78     print """Usage: dak import-archive
79 Initializes a projectB database from an existing archive
80
81   -a, --action              actually perform the initalization
82   -h, --help                show this help and exit."""
83     sys.exit(exit_code)
84
85 ###############################################################################
86
87 def reject (str, prefix="Rejected: "):
88     global reject_message
89     if str:
90         reject_message += prefix + str + "\n"
91
92 ###############################################################################
93
94 def check_signature (filename):
95     if not re_taint_free.match(os.path.basename(filename)):
96         reject("!!WARNING!! tainted filename: '%s'." % (filename))
97         return None
98
99     status_read, status_write = os.pipe()
100     cmd = "gpgv --status-fd %s %s %s" \
101           % (status_write, utils.gpg_keyring_args(), filename)
102     (output, status, exit_status) = utils.gpgv_get_status_output(cmd, status_read, status_write)
103
104     # Process the status-fd output
105     keywords = {}
106     bad = internal_error = ""
107     for line in status.split('\n'):
108         line = line.strip()
109         if line == "":
110             continue
111         split = line.split()
112         if len(split) < 2:
113             internal_error += "gpgv status line is malformed (< 2 atoms) ['%s'].\n" % (line)
114             continue
115         (gnupg, keyword) = split[:2]
116         if gnupg != "[GNUPG:]":
117             internal_error += "gpgv status line is malformed (incorrect prefix '%s').\n" % (gnupg)
118             continue
119         args = split[2:]
120         if keywords.has_key(keyword) and keyword != "NODATA" and keyword != "SIGEXPIRED":
121             internal_error += "found duplicate status token ('%s').\n" % (keyword)
122             continue
123         else:
124             keywords[keyword] = args
125
126     # If we failed to parse the status-fd output, let's just whine and bail now
127     if internal_error:
128         reject("internal error while performing signature check on %s." % (filename))
129         reject(internal_error, "")
130         reject("Please report the above errors to the Archive maintainers by replying to this mail.", "")
131         return None
132
133     # Now check for obviously bad things in the processed output
134     if keywords.has_key("SIGEXPIRED"):
135         utils.warn("%s: signing key has expired." % (filename))
136     if keywords.has_key("KEYREVOKED"):
137         reject("key used to sign %s has been revoked." % (filename))
138         bad = 1
139     if keywords.has_key("BADSIG"):
140         reject("bad signature on %s." % (filename))
141         bad = 1
142     if keywords.has_key("ERRSIG") and not keywords.has_key("NO_PUBKEY"):
143         reject("failed to check signature on %s." % (filename))
144         bad = 1
145     if keywords.has_key("NO_PUBKEY"):
146         args = keywords["NO_PUBKEY"]
147         if len(args) < 1:
148             reject("internal error while checking signature on %s." % (filename))
149             bad = 1
150         else:
151             fingerprint = args[0]
152     if keywords.has_key("BADARMOR"):
153         reject("ascii armour of signature was corrupt in %s." % (filename))
154         bad = 1
155     if keywords.has_key("NODATA"):
156         utils.warn("no signature found for %s." % (filename))
157         return "NOSIG"
158         #reject("no signature found in %s." % (filename))
159         #bad = 1
160
161     if bad:
162         return None
163
164     # Next check gpgv exited with a zero return code
165     if exit_status and not keywords.has_key("NO_PUBKEY"):
166         reject("gpgv failed while checking %s." % (filename))
167         if status.strip():
168             reject(utils.prefix_multi_line_string(status, " [GPG status-fd output:] "), "")
169         else:
170             reject(utils.prefix_multi_line_string(output, " [GPG output:] "), "")
171         return None
172
173     # Sanity check the good stuff we expect
174     if not keywords.has_key("VALIDSIG"):
175         if not keywords.has_key("NO_PUBKEY"):
176             reject("signature on %s does not appear to be valid [No VALIDSIG]." % (filename))
177             bad = 1
178     else:
179         args = keywords["VALIDSIG"]
180         if len(args) < 1:
181             reject("internal error while checking signature on %s." % (filename))
182             bad = 1
183         else:
184             fingerprint = args[0]
185     if not keywords.has_key("GOODSIG") and not keywords.has_key("NO_PUBKEY"):
186         reject("signature on %s does not appear to be valid [No GOODSIG]." % (filename))
187         bad = 1
188     if not keywords.has_key("SIG_ID") and not keywords.has_key("NO_PUBKEY"):
189         reject("signature on %s does not appear to be valid [No SIG_ID]." % (filename))
190         bad = 1
191
192     # Finally ensure there's not something we don't recognise
193     known_keywords = utils.Dict(VALIDSIG="",SIG_ID="",GOODSIG="",BADSIG="",ERRSIG="",
194                                 SIGEXPIRED="",KEYREVOKED="",NO_PUBKEY="",BADARMOR="",
195                                 NODATA="")
196
197     for keyword in keywords.keys():
198         if not known_keywords.has_key(keyword):
199             reject("found unknown status token '%s' from gpgv with args '%r' in %s." % (keyword, keywords[keyword], filename))
200             bad = 1
201
202     if bad:
203         return None
204     else:
205         return fingerprint
206
207 ################################################################################
208
209 # Prepares a filename or directory (s) to be file.filename by stripping any part of the location (sub) from it.
210 def poolify (s, sub):
211     for i in xrange(len(sub)):
212         if sub[i:] == s[0:len(sub)-i]:
213             return s[len(sub)-i:]
214     return s
215
216 def update_archives ():
217     projectB.query("DELETE FROM archive")
218     for archive in Cnf.SubTree("Archive").List():
219         SubSec = Cnf.SubTree("Archive::%s" % (archive))
220         projectB.query("INSERT INTO archive (name, origin_server, description) VALUES ('%s', '%s', '%s')"
221                        % (archive, SubSec["OriginServer"], SubSec["Description"]))
222
223 def update_components ():
224     projectB.query("DELETE FROM component")
225     for component in Cnf.SubTree("Component").List():
226         SubSec = Cnf.SubTree("Component::%s" % (component))
227         projectB.query("INSERT INTO component (name, description, meets_dfsg) VALUES ('%s', '%s', '%s')" %
228                        (component, SubSec["Description"], SubSec["MeetsDFSG"]))
229
230 def update_locations ():
231     projectB.query("DELETE FROM location")
232     for location in Cnf.SubTree("Location").List():
233         SubSec = Cnf.SubTree("Location::%s" % (location))
234         archive_id = database.get_archive_id(SubSec["archive"])
235         type = SubSec.Find("type")
236         if type == "legacy-mixed":
237             projectB.query("INSERT INTO location (path, archive, type) VALUES ('%s', %d, '%s')" % (location, archive_id, SubSec["type"]))
238         else:
239             for component in Cnf.SubTree("Component").List():
240                 component_id = database.get_component_id(component)
241                 projectB.query("INSERT INTO location (path, component, archive, type) VALUES ('%s', %d, %d, '%s')" %
242                                (location, component_id, archive_id, SubSec["type"]))
243
244 def update_architectures ():
245     projectB.query("DELETE FROM architecture")
246     for arch in Cnf.SubTree("Architectures").List():
247         projectB.query("INSERT INTO architecture (arch_string, description) VALUES ('%s', '%s')" % (arch, Cnf["Architectures::%s" % (arch)]))
248
249 def update_suites ():
250     projectB.query("DELETE FROM suite")
251     for suite in Cnf.SubTree("Suite").List():
252         SubSec = Cnf.SubTree("Suite::%s" %(suite))
253         projectB.query("INSERT INTO suite (suite_name) VALUES ('%s')" % suite.lower())
254         for i in ("Version", "Origin", "Description"):
255             if SubSec.has_key(i):
256                 projectB.query("UPDATE suite SET %s = '%s' WHERE suite_name = '%s'" % (i.lower(), SubSec[i], suite.lower()))
257         for architecture in Cnf.ValueList("Suite::%s::Architectures" % (suite)):
258             architecture_id = database.get_architecture_id (architecture)
259             projectB.query("INSERT INTO suite_architectures (suite, architecture) VALUES (currval('suite_id_seq'), %d)" % (architecture_id))
260
261 def update_override_type():
262     projectB.query("DELETE FROM override_type")
263     for type in Cnf.ValueList("OverrideType"):
264         projectB.query("INSERT INTO override_type (type) VALUES ('%s')" % (type))
265
266 def update_priority():
267     projectB.query("DELETE FROM priority")
268     for priority in Cnf.SubTree("Priority").List():
269         projectB.query("INSERT INTO priority (priority, level) VALUES ('%s', %s)" % (priority, Cnf["Priority::%s" % (priority)]))
270
271 def update_section():
272     projectB.query("DELETE FROM section")
273     for component in Cnf.SubTree("Component").List():
274         if Cnf["Control-Overrides::ComponentPosition"] == "prefix":
275             suffix = ""
276             if component != 'main':
277                 prefix = component + '/'
278             else:
279                 prefix = ""
280         else:
281             prefix = ""
282             if component != 'main':
283                 suffix = '/' + component
284             else:
285                 suffix = ""
286         for section in Cnf.ValueList("Section"):
287             projectB.query("INSERT INTO section (section) VALUES ('%s%s%s')" % (prefix, section, suffix))
288
289 def get_location_path(directory):
290     global location_path_cache
291
292     if location_path_cache.has_key(directory):
293         return location_path_cache[directory]
294
295     q = projectB.query("SELECT DISTINCT path FROM location WHERE path ~ '%s'" % (directory))
296     try:
297         path = q.getresult()[0][0]
298     except:
299         utils.fubar("[import-archive] get_location_path(): Couldn't get path for %s" % (directory))
300     location_path_cache[directory] = path
301     return path
302
303 ################################################################################
304
305 def get_or_set_files_id (filename, size, md5sum, location_id):
306     global files_id_cache, files_id_serial, files_query_cache
307
308     cache_key = "_".join((filename, size, md5sum, repr(location_id)))
309     if not files_id_cache.has_key(cache_key):
310         files_id_serial += 1
311         files_query_cache.write("%d\t%s\t%s\t%s\t%d\t\\N\n" % (files_id_serial, filename, size, md5sum, location_id))
312         files_id_cache[cache_key] = files_id_serial
313
314     return files_id_cache[cache_key]
315
316 ###############################################################################
317
318 def process_sources (filename, suite, component, archive):
319     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
320
321     suite = suite.lower()
322     suite_id = database.get_suite_id(suite)
323     try:
324         file = utils.open_file (filename)
325     except CantOpenError:
326         utils.warn("can't open '%s'" % (filename))
327         return
328     Scanner = apt_pkg.ParseTagFile(file)
329     while Scanner.Step() != 0:
330         package = Scanner.Section["package"]
331         version = Scanner.Section["version"]
332         directory = Scanner.Section["directory"]
333         dsc_file = os.path.join(Cnf["Dir::Root"], directory, "%s_%s.dsc" % (package, re_no_epoch.sub('', version)))
334         # Sometimes the Directory path is a lie; check in the pool
335         if not os.path.exists(dsc_file):
336             if directory.split('/')[0] == "dists":
337                 directory = Cnf["Dir::PoolRoot"] + utils.poolify(package, component)
338                 dsc_file = os.path.join(Cnf["Dir::Root"], directory, "%s_%s.dsc" % (package, re_no_epoch.sub('', version)))
339         if not os.path.exists(dsc_file):
340             utils.fubar("%s not found." % (dsc_file))
341         install_date = time.strftime("%Y-%m-%d", time.localtime(os.path.getmtime(dsc_file)))
342         fingerprint = check_signature(dsc_file)
343         fingerprint_id = database.get_or_set_fingerprint_id(fingerprint)
344         if reject_message:
345             utils.fubar("%s: %s" % (dsc_file, reject_message))
346         maintainer = Scanner.Section["maintainer"]
347         maintainer = maintainer.replace("'", "\\'")
348         maintainer_id = database.get_or_set_maintainer_id(maintainer)
349         location = get_location_path(directory.split('/')[0])
350         location_id = database.get_location_id (location, component, archive)
351         if not directory.endswith("/"):
352             directory += '/'
353         directory = poolify (directory, location)
354         if directory != "" and not directory.endswith("/"):
355             directory += '/'
356         no_epoch_version = re_no_epoch.sub('', version)
357         # Add all files referenced by the .dsc to the files table
358         ids = []
359         for line in Scanner.Section["files"].split('\n'):
360             id = None
361             (md5sum, size, filename) = line.strip().split()
362             # Don't duplicate .orig.tar.gz's
363             if filename.endswith(".orig.tar.gz"):
364                 cache_key = "%s_%s_%s" % (filename, size, md5sum)
365                 if orig_tar_gz_cache.has_key(cache_key):
366                     id = orig_tar_gz_cache[cache_key]
367                 else:
368                     id = get_or_set_files_id (directory + filename, size, md5sum, location_id)
369                     orig_tar_gz_cache[cache_key] = id
370             else:
371                 id = get_or_set_files_id (directory + filename, size, md5sum, location_id)
372             ids.append(id)
373             # If this is the .dsc itself; save the ID for later.
374             if filename.endswith(".dsc"):
375                 files_id = id
376         filename = directory + package + '_' + no_epoch_version + '.dsc'
377         cache_key = "%s_%s" % (package, version)
378         if not source_cache.has_key(cache_key):
379             nasty_key = "%s_%s" % (package, version)
380             source_id_serial += 1
381             if not source_cache_for_binaries.has_key(nasty_key):
382                 source_cache_for_binaries[nasty_key] = source_id_serial
383             tmp_source_id = source_id_serial
384             source_cache[cache_key] = source_id_serial
385             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))
386             for id in ids:
387                 dsc_files_id_serial += 1
388                 dsc_files_query_cache.write("%d\t%d\t%d\n" % (dsc_files_id_serial, tmp_source_id,id))
389         else:
390             tmp_source_id = source_cache[cache_key]
391
392         src_associations_id_serial += 1
393         src_associations_query_cache.write("%d\t%d\t%d\n" % (src_associations_id_serial, suite_id, tmp_source_id))
394
395     file.close()
396
397 ###############################################################################
398
399 def process_packages (filename, suite, component, archive):
400     global arch_all_cache, binary_cache, binaries_id_serial, binaries_query_cache, bin_associations_id_serial, bin_associations_query_cache, reject_message
401
402     count_total = 0
403     count_bad = 0
404     suite = suite.lower()
405     suite_id = database.get_suite_id(suite)
406     try:
407         file = utils.open_file (filename)
408     except CantOpenError:
409         utils.warn("can't open '%s'" % (filename))
410         return
411     Scanner = apt_pkg.ParseTagFile(file)
412     while Scanner.Step() != 0:
413         package = Scanner.Section["package"]
414         version = Scanner.Section["version"]
415         maintainer = Scanner.Section["maintainer"]
416         maintainer = maintainer.replace("'", "\\'")
417         maintainer_id = database.get_or_set_maintainer_id(maintainer)
418         architecture = Scanner.Section["architecture"]
419         architecture_id = database.get_architecture_id (architecture)
420         fingerprint = "NOSIG"
421         fingerprint_id = database.get_or_set_fingerprint_id(fingerprint)
422         if not Scanner.Section.has_key("source"):
423             source = package
424         else:
425             source = Scanner.Section["source"]
426         source_version = ""
427         if source.find("(") != -1:
428             m = re_extract_src_version.match(source)
429             source = m.group(1)
430             source_version = m.group(2)
431         if not source_version:
432             source_version = version
433         filename = Scanner.Section["filename"]
434         if filename.endswith(".deb"):
435             type = "deb"
436         else:
437             type = "udeb"
438         location = get_location_path(filename.split('/')[0])
439         location_id = database.get_location_id (location, component.replace("/debian-installer", ""), archive)
440         filename = poolify (filename, location)
441         if architecture == "all":
442             filename = re_arch_from_filename.sub("binary-all", filename)
443         cache_key = "%s_%s" % (source, source_version)
444         source_id = source_cache_for_binaries.get(cache_key, None)
445         size = Scanner.Section["size"]
446         md5sum = Scanner.Section["md5sum"]
447         files_id = get_or_set_files_id (filename, size, md5sum, location_id)
448         cache_key = "%s_%s_%s_%d_%d_%d_%d" % (package, version, repr(source_id), architecture_id, location_id, files_id, suite_id)
449         if not arch_all_cache.has_key(cache_key):
450             arch_all_cache[cache_key] = 1
451             cache_key = "%s_%s_%s_%d" % (package, version, repr(source_id), architecture_id)
452             if not binary_cache.has_key(cache_key):
453                 if not source_id:
454                     source_id = "\N"
455                     count_bad += 1
456                 else:
457                     source_id = repr(source_id)
458                 binaries_id_serial += 1
459                 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))
460                 binary_cache[cache_key] = binaries_id_serial
461                 tmp_binaries_id = binaries_id_serial
462             else:
463                 tmp_binaries_id = binary_cache[cache_key]
464
465             bin_associations_id_serial += 1
466             bin_associations_query_cache.write("%d\t%d\t%d\n" % (bin_associations_id_serial, suite_id, tmp_binaries_id))
467             count_total += 1
468
469     file.close()
470     if count_bad != 0:
471         print "%d binary packages processed; %d with no source match which is %.2f%%" % (count_total, count_bad, (float(count_bad)/count_total)*100)
472     else:
473         print "%d binary packages processed; 0 with no source match which is 0%%" % (count_total)
474
475 ###############################################################################
476
477 def do_sources(sources, suite, component, server):
478     (fd, temp_filename) = utils.temp_filename()
479     (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (sources, temp_filename))
480     if (result != 0):
481         utils.fubar("Gunzip invocation failed!\n%s" % (output), result)
482     print 'Processing '+sources+'...'
483     process_sources (temp_filename, suite, component, server)
484     os.unlink(temp_filename)
485
486 ###############################################################################
487
488 def do_da_do_da ():
489     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
490
491     Cnf = utils.get_conf()
492     Arguments = [('a', "action", "Import-Archive::Options::Action"),
493                  ('h', "help", "Import-Archive::Options::Help")]
494     for i in [ "action", "help" ]:
495         if not Cnf.has_key("Import-Archive::Options::%s" % (i)):
496             Cnf["Import-Archive::Options::%s" % (i)] = ""
497
498     apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
499
500     Options = Cnf.SubTree("Import-Archive::Options")
501     if Options["Help"]:
502         usage()
503
504     if not Options["Action"]:
505         utils.warn("""no -a/--action given; not doing anything.
506 Please read the documentation before running this script.
507 """)
508         usage(1)
509
510     print "Re-Creating DB..."
511     (result, output) = commands.getstatusoutput("psql -f init_pool.sql template1")
512     if (result != 0):
513         utils.fubar("psql invocation failed!\n", result)
514     print output
515
516     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
517
518     database.init (Cnf, projectB)
519
520     print "Adding static tables from conf file..."
521     projectB.query("BEGIN WORK")
522     update_architectures()
523     update_components()
524     update_archives()
525     update_locations()
526     update_suites()
527     update_override_type()
528     update_priority()
529     update_section()
530     projectB.query("COMMIT WORK")
531
532     files_query_cache = utils.open_file(Cnf["Import-Archive::ExportDir"]+"files","w")
533     source_query_cache = utils.open_file(Cnf["Import-Archive::ExportDir"]+"source","w")
534     src_associations_query_cache = utils.open_file(Cnf["Import-Archive::ExportDir"]+"src_associations","w")
535     dsc_files_query_cache = utils.open_file(Cnf["Import-Archive::ExportDir"]+"dsc_files","w")
536     binaries_query_cache = utils.open_file(Cnf["Import-Archive::ExportDir"]+"binaries","w")
537     bin_associations_query_cache = utils.open_file(Cnf["Import-Archive::ExportDir"]+"bin_associations","w")
538
539     projectB.query("BEGIN WORK")
540     # Process Sources files to popoulate `source' and friends
541     for location in Cnf.SubTree("Location").List():
542         SubSec = Cnf.SubTree("Location::%s" % (location))
543         server = SubSec["Archive"]
544         type = Cnf.Find("Location::%s::Type" % (location))
545         if type == "legacy-mixed":
546             sources = location + 'Sources.gz'
547             suite = Cnf.Find("Location::%s::Suite" % (location))
548             do_sources(sources, suite, "",  server)
549         elif type == "legacy" or type == "pool":
550             for suite in Cnf.ValueList("Location::%s::Suites" % (location)):
551                 for component in Cnf.SubTree("Component").List():
552                     sources = Cnf["Dir::Root"] + "dists/" + Cnf["Suite::%s::CodeName" % (suite)] + '/' + component + '/source/' + 'Sources.gz'
553                     do_sources(sources, suite, component, server)
554         else:
555             utils.fubar("Unknown location type ('%s')." % (type))
556
557     # Process Packages files to populate `binaries' and friends
558
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 (packages, suite, "", server)
568         elif type == "legacy" or type == "pool":
569             for suite in Cnf.ValueList("Location::%s::Suites" % (location)):
570                 udeb_components = map(lambda x: x+"/debian-installer",
571                                       Cnf.ValueList("Suite::%s::UdebComponents" % suite))
572                 for component in Cnf.SubTree("Component").List() + udeb_components:
573                     architectures = filter(utils.real_arch,
574                                            Cnf.ValueList("Suite::%s::Architectures" % (suite)))
575                     for architecture in architectures:
576                         packages = Cnf["Dir::Root"] + "dists/" + Cnf["Suite::%s::CodeName" % (suite)] + '/' + component + '/binary-' + architecture + '/Packages'
577                         print 'Processing '+packages+'...'
578                         process_packages (packages, suite, component, server)
579
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["Import-Archive::ExportDir"]+"files"))
588     print "Writing data to `source' table..."
589     projectB.query("COPY source FROM '%s'" % (Cnf["Import-Archive::ExportDir"]+"source"))
590     print "Writing data to `src_associations' table..."
591     projectB.query("COPY src_associations FROM '%s'" % (Cnf["Import-Archive::ExportDir"]+"src_associations"))
592     print "Writing data to `dsc_files' table..."
593     projectB.query("COPY dsc_files FROM '%s'" % (Cnf["Import-Archive::ExportDir"]+"dsc_files"))
594     print "Writing data to `binaries' table..."
595     projectB.query("COPY binaries FROM '%s'" % (Cnf["Import-Archive::ExportDir"]+"binaries"))
596     print "Writing data to `bin_associations' table..."
597     projectB.query("COPY bin_associations FROM '%s'" % (Cnf["Import-Archive::ExportDir"]+"bin_associations"))
598     print "Committing..."
599     projectB.query("COMMIT WORK")
600
601     # Add the constraints and otherwise generally clean up the database.
602     # See add_constraints.sql for more details...
603
604     print "Running add_constraints.sql..."
605     (result, output) = commands.getstatusoutput("psql %s < add_constraints.sql" % (Cnf["DB::Name"]))
606     print output
607     if (result != 0):
608         utils.fubar("psql invocation failed!\n%s" % (output), result)
609
610     return
611
612 ################################################################################
613
614 def main():
615     utils.try_with_debug(do_da_do_da)
616
617 ################################################################################
618
619 if __name__ == '__main__':
620     main()