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