]> git.decadent.org.uk Git - dak.git/blob - neve
changelog entry for ryan's shania fix; whitespace + override fix for w-p-u; copyright...
[dak.git] / neve
1 #!/usr/bin/env python
2
3 # Populate the DB
4 # Copyright (C) 2000, 2001  James Troup <james@nocrew.org>
5 # $Id: neve,v 1.6 2001-11-04 22:41:31 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, sys, string, tempfile
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 #
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
74 ###############################################################################################################
75
76 # Prepares a filename or directory (s) to be file.filename by stripping any part of the location (sub) from it.
77 def poolify (s, sub):
78     for i in xrange(len(sub)):
79         if sub[i:] == s[0:len(sub)-i]:
80             return s[len(sub)-i:];
81     return s;
82
83 def update_archives ():
84     projectB.query("DELETE FROM archive")
85     for archive in Cnf.SubTree("Archive").List():
86         SubSec = Cnf.SubTree("Archive::%s" % (archive));
87         projectB.query("INSERT INTO archive (name, origin_server, description) VALUES ('%s', '%s', '%s')"
88                        % (archive, SubSec["OriginServer"], SubSec["Description"]));
89
90 def update_components ():
91     projectB.query("DELETE FROM component")
92     for component in Cnf.SubTree("Component").List():
93         SubSec = Cnf.SubTree("Component::%s" % (component));
94         projectB.query("INSERT INTO component (name, description, meets_dfsg) VALUES ('%s', '%s', '%s')" %
95                        (component, SubSec["Description"], SubSec["MeetsDFSG"]));
96
97 def update_locations ():
98     projectB.query("DELETE FROM location")
99     for location in Cnf.SubTree("Location").List():
100         SubSec = Cnf.SubTree("Location::%s" % (location));
101         archive_id = db_access.get_archive_id(SubSec["archive"]);
102         type = SubSec.Find("type");
103         if type == "legacy-mixed":
104             projectB.query("INSERT INTO location (path, archive, type) VALUES ('%s', %d, '%s')" % (location, archive_id, SubSec["type"]));
105         else:
106             for component in Cnf.SubTree("Component").List():
107                 component_id = db_access.get_component_id(component);
108                 projectB.query("INSERT INTO location (path, component, archive, type) VALUES ('%s', %d, %d, '%s')" %
109                                (location, component_id, archive_id, SubSec["type"]));
110
111 def update_architectures ():
112     projectB.query("DELETE FROM architecture")
113     for arch in Cnf.SubTree("Architectures").List():
114         projectB.query("INSERT INTO architecture (arch_string, description) VALUES ('%s', '%s')" % (arch, Cnf["Architectures::%s" % (arch)]))
115
116 def update_suites ():
117     projectB.query("DELETE FROM suite")
118     for suite in Cnf.SubTree("Suite").List():
119         SubSec = Cnf.SubTree("Suite::%s" %(suite))
120         projectB.query("INSERT INTO suite (suite_name) VALUES ('%s')" % string.lower(suite));
121         for i in ("Version", "Origin", "Description"):
122             if SubSec.has_key(i):
123                 projectB.query("UPDATE suite SET %s = '%s' WHERE suite_name = '%s'" % (string.lower(i), SubSec[i], string.lower(suite)))
124         for architecture in Cnf.SubTree("Suite::%s::Architectures" % (suite)).List():
125             architecture_id = db_access.get_architecture_id (architecture);
126             projectB.query("INSERT INTO suite_architectures (suite, architecture) VALUES (currval('suite_id_seq'), %d)" % (architecture_id));
127
128 ##############################################################################################################
129
130 def get_or_set_files_id (filename, size, md5sum, location_id):
131     global files_id_cache, files_id_serial, files_query_cache;
132
133     cache_key = string.join((filename, size, md5sum, repr(location_id)), '~')
134     if not files_id_cache.has_key(cache_key):
135         files_id_serial = files_id_serial + 1
136         files_query_cache.write("%d\t%s\t%s\t%s\t%d\n" % (files_id_serial, filename, size, md5sum, location_id));
137         files_id_cache[cache_key] = files_id_serial
138
139     return files_id_cache[cache_key]
140
141 ##############################################################################################################
142
143 def process_sources (location, filename, suite, component, archive):
144     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;
145
146     suite = string.lower(suite)
147     suite_id = db_access.get_suite_id(suite);
148     if suite == 'stable':
149         testing_id = db_access.get_suite_id("testing");
150     try:
151         file = utils.open_file (filename);
152     except utils.cant_open_exc:
153         print "WARNING: can't open '%s'" % (filename);
154         return;
155     Scanner = apt_pkg.ParseTagFile(file)
156     while Scanner.Step() != 0:
157         package = Scanner.Section["package"]
158         version = Scanner.Section["version"]
159         maintainer = Scanner.Section["maintainer"]
160         maintainer = string.replace(maintainer, "'", "\\'")
161         maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
162         directory = Scanner.Section["directory"]
163         location_id = db_access.get_location_id (location, component, archive)
164         if directory[-1:] != "/":
165             directory = directory + '/';
166         directory = poolify (directory, location);
167         if directory != "" and directory[-1:] != "/":
168             directory = directory + '/';
169         no_epoch_version = utils.re_no_epoch.sub('', version)
170         # Add all files referenced by the .dsc to the files table
171         ids = [];
172         for line in string.split(Scanner.Section["files"],'\n'):
173             id = None;
174             (md5sum, size, filename) = string.split(string.strip(line));
175             # Don't duplicate .orig.tar.gz's
176             if filename[-12:] == ".orig.tar.gz":
177                 cache_key = "%s~%s~%s" % (filename, size, md5sum);
178                 if orig_tar_gz_cache.has_key(cache_key):
179                     id = orig_tar_gz_cache[cache_key];
180                 else:
181                     id = get_or_set_files_id (directory + filename, size, md5sum, location_id);
182                     orig_tar_gz_cache[cache_key] = id;
183             else:
184                 id = get_or_set_files_id (directory + filename, size, md5sum, location_id);
185             ids.append(id);
186             # If this is the .dsc itself; save the ID for later.
187             if filename[-4:] == ".dsc":
188                 files_id = id;
189         filename = directory + package + '_' + no_epoch_version + '.dsc'
190         cache_key = "%s~%s" % (package, version)
191         if not source_cache.has_key(cache_key):
192             nasty_key = "%s~%s" % (package, version)
193             source_id_serial = source_id_serial + 1;
194             if not source_cache_for_binaries.has_key(nasty_key):
195                 source_cache_for_binaries[nasty_key] = source_id_serial;
196             tmp_source_id = source_id_serial;
197             source_cache[cache_key] = source_id_serial;
198             source_query_cache.write("%d\t%s\t%s\t%d\t%d\n" % (source_id_serial, package, version, maintainer_id, files_id))
199             for id in ids:
200                 dsc_files_id_serial = dsc_files_id_serial + 1;
201                 dsc_files_query_cache.write("%d\t%d\t%d\n" % (dsc_files_id_serial, tmp_source_id,id));
202         else:
203             tmp_source_id = source_cache[cache_key];
204
205         src_associations_id_serial = src_associations_id_serial + 1;
206         src_associations_query_cache.write("%d\t%d\t%d\n" % (src_associations_id_serial, suite_id, tmp_source_id))
207         # populate 'testing' with a mirror of 'stable'
208         if suite == "stable":
209             src_associations_id_serial = src_associations_id_serial + 1;
210             src_associations_query_cache.write("%d\t%d\t%d\n" % (src_associations_id_serial, testing_id, tmp_source_id))
211
212     file.close()
213
214 ##############################################################################################################
215
216 def process_packages (location, filename, suite, component, archive):
217     global arch_all_cache, binary_cache, binaries_id_serial, binaries_query_cache, bin_associations_id_serial, bin_associations_query_cache;
218
219     count_total = 0;
220     count_bad = 0;
221     suite = string.lower(suite);
222     suite_id = db_access.get_suite_id(suite);
223     if suite == "stable":
224         testing_id = db_access.get_suite_id("testing");
225     try:
226         file = utils.open_file (filename);
227     except utils.cant_open_exc:
228         print "WARNING: can't open '%s'" % (filename);
229         return;
230     Scanner = apt_pkg.ParseTagFile(file);
231     while Scanner.Step() != 0:
232         package = Scanner.Section["package"]
233         version = Scanner.Section["version"]
234         maintainer = Scanner.Section["maintainer"]
235         maintainer = string.replace(maintainer, "'", "\\'")
236         maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
237         architecture = Scanner.Section["architecture"]
238         architecture_id = db_access.get_architecture_id (architecture);
239         if not Scanner.Section.has_key("source"):
240             source = package
241         else:
242             source = Scanner.Section["source"]
243         source_version = ""
244         if string.find(source, "(") != -1:
245             m = utils.re_extract_src_version.match(source)
246             source = m.group(1)
247             source_version = m.group(2)
248         if not source_version:
249             source_version = version
250         filename = Scanner.Section["filename"]
251         location_id = db_access.get_location_id (location, component, archive)
252         filename = poolify (filename, location)
253         if architecture == "all":
254             filename = re_arch_from_filename.sub("binary-all", filename);
255         cache_key = "%s~%s" % (source, source_version);
256         source_id = source_cache_for_binaries.get(cache_key, None);
257         size = Scanner.Section["size"];
258         md5sum = Scanner.Section["md5sum"];
259         files_id = get_or_set_files_id (filename, size, md5sum, location_id);
260         type = "deb"; # FIXME
261         cache_key = "%s~%s~%s~%d~%d~%d" % (package, version, repr(source_id), architecture_id, location_id, files_id);
262         if not arch_all_cache.has_key(cache_key):
263             arch_all_cache[cache_key] = 1;
264             cache_key = "%s~%s~%s~%d" % (package, version, repr(source_id), architecture_id);
265             if not binary_cache.has_key(cache_key):
266                 if not source_id:
267                     source_id = "\N";
268                     count_bad = count_bad + 1;
269                 else:
270                     source_id = repr(source_id);
271                 binaries_id_serial = binaries_id_serial + 1;
272                 binaries_query_cache.write("%d\t%s\t%s\t%d\t%s\t%d\t%d\t%s\n" % (binaries_id_serial, package, version, maintainer_id, source_id, architecture_id, files_id, type));
273                 binary_cache[cache_key] = binaries_id_serial;
274                 tmp_binaries_id = binaries_id_serial;
275             else:
276                 tmp_binaries_id = binary_cache[cache_key];
277
278             bin_associations_id_serial = bin_associations_id_serial + 1;
279             bin_associations_query_cache.write("%d\t%d\t%d\n" % (bin_associations_id_serial, suite_id, tmp_binaries_id));
280             if suite == "stable":
281                 bin_associations_id_serial = bin_associations_id_serial + 1;
282                 bin_associations_query_cache.write("%d\t%d\t%d\n" % (bin_associations_id_serial, testing_id, tmp_binaries_id));
283             count_total = count_total +1;
284
285     file.close();
286     if count_bad != 0:
287         print "%d binary packages processed; %d with no source match which is %.2f%%" % (count_total, count_bad, (float(count_bad)/count_total)*100);
288     else:
289         print "%d binary packages processed; 0 with no source match which is 0%%" % (count_total);
290
291 ##############################################################################################################
292
293 def do_sources(location, prefix, suite, component, server):
294     temp_filename = tempfile.mktemp();
295     fd = os.open(temp_filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
296     os.close(fd);
297     sources = location + prefix + 'Sources.gz';
298     (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (sources, temp_filename));
299     if (result != 0):
300         utils.fubar("Gunzip invocation failed!\n%s" % (output), result);
301     print 'Processing '+sources+'...';
302     process_sources (location, temp_filename, suite, component, server);
303     os.unlink(temp_filename);
304
305 ##############################################################################################################
306
307 def main ():
308     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;
309
310     apt_pkg.init();
311
312     Cnf = apt_pkg.newConfiguration();
313     apt_pkg.ReadConfigFileISC(Cnf,utils.which_conf_file());
314
315     print "Re-Creating DB..."
316     (result, output) = commands.getstatusoutput("psql -f init_pool.sql")
317     if (result != 0):
318         utils.fubar("psql invocation failed!\n", result);
319     print output
320
321     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]), None, None, 'postgres')
322
323     db_access.init (Cnf, projectB);
324
325     print "Adding static tables from conf file..."
326     projectB.query("BEGIN WORK");
327     update_architectures();
328     update_components();
329     update_archives();
330     update_locations();
331     update_suites();
332     projectB.query("COMMIT WORK");
333
334     files_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"files","w");
335     source_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"source","w");
336     src_associations_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"src_associations","w");
337     dsc_files_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"dsc_files","w");
338     binaries_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"binaries","w");
339     bin_associations_query_cache = utils.open_file(Cnf["Neve::ExportDir"]+"bin_associations","w");
340
341     projectB.query("BEGIN WORK");
342     # Process Sources files to popoulate `source' and friends
343     for location in Cnf.SubTree("Location").List():
344         SubSec = Cnf.SubTree("Location::%s" % (location));
345         server = SubSec["Archive"];
346         type = Cnf.Find("Location::%s::Type" % (location));
347         if type == "legacy-mixed":
348             prefix = ''
349             suite = Cnf.Find("Location::%s::Suite" % (location));
350             do_sources(location, prefix, suite, "",  server);
351         elif type == "legacy":
352             for suite in Cnf.SubTree("Location::%s::Suites" % (location)).List():
353                 for component in Cnf.SubTree("Component").List():
354                     prefix = Cnf.Find("Suite::%s::CodeName" % (suite)) + '/' + component + '/source/'
355                     do_sources(location, prefix, suite, component, server);
356         elif type == "pool":
357             continue;
358 #            for component in Cnf.SubTree("Component").List():
359 #                prefix = component + '/'
360 #                do_sources(location, prefix);
361         else:
362             utils.fubar("Unknown location type ('%s')." % (type));
363
364     # Process Packages files to populate `binaries' and friends
365
366     for location in Cnf.SubTree("Location").List():
367         SubSec = Cnf.SubTree("Location::%s" % (location));
368         server = SubSec["Archive"];
369         type = Cnf.Find("Location::%s::Type" % (location));
370         if type == "legacy-mixed":
371             packages = location + 'Packages';
372             suite = Cnf.Find("Location::%s::Suite" % (location));
373             print 'Processing '+location+'...';
374             process_packages (location, packages, suite, "", server);
375         elif type == "legacy":
376             for suite in Cnf.SubTree("Location::%s::Suites" % (location)).List():
377                 for component in Cnf.SubTree("Component").List():
378                     for architecture in Cnf.SubTree("Suite::%s::Architectures" % (suite)).List():
379                         if architecture == "source" or architecture == "all":
380                             continue;
381                         packages = location + Cnf.Find("Suite::%s::CodeName" % (suite)) + '/' + component + '/binary-' + architecture + '/Packages'
382                         print 'Processing '+packages+'...';
383                         process_packages (location, packages, suite, component, server);
384         elif type == "pool":
385             continue;
386
387     files_query_cache.close();
388     source_query_cache.close();
389     src_associations_query_cache.close();
390     dsc_files_query_cache.close();
391     binaries_query_cache.close();
392     bin_associations_query_cache.close();
393     print "Writing data to `files' table...";
394     projectB.query("COPY files FROM '%s'" % (Cnf["Neve::ExportDir"]+"files"));
395     print "Writing data to `source' table...";
396     projectB.query("COPY source FROM '%s'" % (Cnf["Neve::ExportDir"]+"source"));
397     print "Writing data to `src_associations' table...";
398     projectB.query("COPY src_associations FROM '%s'" % (Cnf["Neve::ExportDir"]+"src_associations"));
399     print "Writing data to `dsc_files' table...";
400     projectB.query("COPY dsc_files FROM '%s'" % (Cnf["Neve::ExportDir"]+"dsc_files"));
401     print "Writing data to `binaries' table...";
402     projectB.query("COPY binaries FROM '%s'" % (Cnf["Neve::ExportDir"]+"binaries"));
403     print "Writing data to `bin_associations' table...";
404     projectB.query("COPY bin_associations FROM '%s'" % (Cnf["Neve::ExportDir"]+"bin_associations"));
405     print "Committing...";
406     projectB.query("COMMIT WORK");
407
408     # Add the constraints and otherwise generally clean up the database.
409     # See add_constraints.sql for more details...
410
411     print "Running add_constraints.sql...";
412     (result, output) = commands.getstatusoutput("psql projectb < add_constraints.sql");
413     print output
414     if (result != 0):
415         utils.fubar("psql invocation failed!\n%s" % (output), result);
416
417     return;
418
419 if __name__ == '__main__':
420     main()