]> git.decadent.org.uk Git - dak.git/blob - dak/control_suite.py
allow squeeze-updates to be reset
[dak.git] / dak / control_suite.py
1 #!/usr/bin/env python
2
3 """ Manipulate suite tags """
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 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 # 8to6Guy: "Wow, Bob, You look rough!"
23 # BTAF: "Mbblpmn..."
24 # BTAF <.oO>: "You moron! This is what you get for staying up all night drinking vodka and salad dressing!"
25 # BTAF <.oO>: "This coffee I.V. drip is barely even keeping me awake! I need something with more kick! But what?"
26 # BTAF: "OMIGOD! I OVERDOSED ON HEROIN"
27 # CoWorker#n: "Give him air!!"
28 # CoWorker#n+1: "We need a syringe full of adrenaline!"
29 # CoWorker#n+2: "Stab him in the heart!"
30 # BTAF: "*YES!*"
31 # CoWorker#n+3: "Bob's been overdosing quite a bit lately..."
32 # CoWorker#n+4: "Third time this week."
33
34 # -- http://www.angryflower.com/8to6.gif
35
36 #######################################################################################
37
38 # Adds or removes packages from a suite.  Takes the list of files
39 # either from stdin or as a command line argument.  Special action
40 # "set", will reset the suite (!) and add all packages from scratch.
41
42 #######################################################################################
43
44 import sys
45 import apt_pkg
46 import os
47
48 from daklib.config import Config
49 from daklib.dbconn import *
50 from daklib import daklog
51 from daklib import utils
52
53 #######################################################################################
54
55 Logger = None
56
57 ################################################################################
58
59 def usage (exit_code=0):
60     print """Usage: dak control-suite [OPTIONS] [FILE]
61 Display or alter the contents of a suite using FILE(s), or stdin.
62
63   -a, --add=SUITE            add to SUITE
64   -h, --help                 show this help and exit
65   -l, --list=SUITE           list the contents of SUITE
66   -r, --remove=SUITE         remove from SUITE
67   -s, --set=SUITE            set SUITE
68   -b, --britney              generate changelog entry for britney runs"""
69
70     sys.exit(exit_code)
71
72 #######################################################################################
73
74 def get_id(package, version, architecture, session):
75     if architecture == "source":
76         q = session.execute("SELECT id FROM source WHERE source = :package AND version = :version",
77                             {'package': package, 'version': version})
78     else:
79         q = session.execute("""SELECT b.id FROM binaries b, architecture a
80                                 WHERE b.package = :package AND b.version = :version
81                                   AND (a.arch_string = :arch OR a.arch_string = 'all')
82                                   AND b.architecture = a.id""",
83                                {'package': package, 'version': version, 'arch': architecture})
84
85     ql = q.fetchall()
86     if len(ql) < 1:
87         utils.warn("Couldn't find '%s_%s_%s'." % (package, version, architecture))
88         return None
89
90     if len(ql) > 1:
91         utils.warn("Found more than one match for '%s_%s_%s'." % (package, version, architecture))
92         return None
93
94     return ql[0][0]
95
96 #######################################################################################
97
98 def britney_changelog(packages, suite, session):
99
100     old = {}
101     current = {}
102     Cnf = utils.get_conf()
103
104     try:
105         q = session.execute("SELECT changelog FROM suite WHERE id = :suiteid", \
106                             {'suiteid': suite.suite_id})
107         brit_file = q.fetchone()[0]
108     except:
109         brit_file = None
110
111     if brit_file:
112         brit_file = os.path.join(Cnf['Dir::Root'], brit_file)
113     else:
114         return
115
116     q = session.execute("""SELECT s.source, s.version, sa.id
117                              FROM source s, src_associations sa
118                             WHERE sa.suite = :suiteid
119                               AND sa.source = s.id""", {'suiteid': suite.suite_id})
120
121     for p in q.fetchall():
122         current[p[0]] = p[1]
123     for p in packages.keys():
124         p = p.split()
125         if p[2] == "source":
126             old[p[0]] = p[1]
127
128     new = {}
129     for p in current.keys():
130         if p in old.keys():
131             if apt_pkg.VersionCompare(current[p], old[p]) > 0:
132                 new[p] = [current[p], old[p]]
133         else:
134             new[p] = [current[p], 0]
135
136     query =  "SELECT source, changelog FROM changelogs WHERE"
137     for p in new.keys():
138         query += " source = '%s' AND version > '%s' AND version <= '%s'" \
139                  % (p, new[p][1], new[p][0])
140         query += " AND architecture LIKE '%source%' AND distribution in \
141                   ('unstable', 'experimental', 'testing-proposed-updates') OR"
142     query += " False ORDER BY source, version DESC"
143     q = session.execute(query)
144
145     pu = None
146     brit = utils.open_file(brit_file, 'w')
147
148     for u in q:
149         if pu and pu != u[0]:
150             brit.write("\n")
151         brit.write("%s\n" % u[1])
152         pu = u[0]
153     if q.rowcount: brit.write("\n\n\n")
154
155     for p in list(set(old.keys()).difference(current.keys())):
156         brit.write("REMOVED: %s %s\n" % (p, old[p]))
157
158     brit.flush()
159     brit.close()
160
161 #######################################################################################
162
163 def set_suite(file, suite, session, britney=False):
164     suite_id = suite.suite_id
165     lines = file.readlines()
166
167     # Our session is already in a transaction
168
169     # Build up a dictionary of what is currently in the suite
170     current = {}
171     q = session.execute("""SELECT b.package, b.version, a.arch_string, ba.id
172                              FROM binaries b, bin_associations ba, architecture a
173                             WHERE ba.suite = :suiteid
174                               AND ba.bin = b.id AND b.architecture = a.id""", {'suiteid': suite_id})
175     for i in q.fetchall():
176         key = " ".join(i[:3])
177         current[key] = i[3]
178
179     q = session.execute("""SELECT s.source, s.version, sa.id
180                              FROM source s, src_associations sa
181                             WHERE sa.suite = :suiteid
182                               AND sa.source = s.id""", {'suiteid': suite_id})
183     for i in q.fetchall():
184         key = " ".join(i[:2]) + " source"
185         current[key] = i[2]
186
187     # Build up a dictionary of what should be in the suite
188     desired = {}
189     for line in lines:
190         split_line = line.strip().split()
191         if len(split_line) != 3:
192             utils.warn("'%s' does not break into 'package version architecture'." % (line[:-1]))
193             continue
194         key = " ".join(split_line)
195         desired[key] = ""
196
197     # Check to see which packages need removed and remove them
198     for key in current.keys():
199         if not desired.has_key(key):
200             (package, version, architecture) = key.split()
201             pkid = current[key]
202             if architecture == "source":
203                 session.execute("""DELETE FROM src_associations WHERE id = :pkid""", {'pkid': pkid})
204             else:
205                 session.execute("""DELETE FROM bin_associations WHERE id = :pkid""", {'pkid': pkid})
206             Logger.log(["removed", key, pkid])
207
208     # Check to see which packages need added and add them
209     for key in desired.keys():
210         if not current.has_key(key):
211             (package, version, architecture) = key.split()
212             pkid = get_id (package, version, architecture, session)
213             if not pkid:
214                 continue
215             if architecture == "source":
216                 session.execute("""INSERT INTO src_associations (suite, source)
217                                         VALUES (:suiteid, :pkid)""", {'suiteid': suite_id, 'pkid': pkid})
218             else:
219                 session.execute("""INSERT INTO bin_associations (suite, bin)
220                                         VALUES (:suiteid, :pkid)""", {'suiteid': suite_id, 'pkid': pkid})
221             Logger.log(["added", key, pkid])
222
223     session.commit()
224
225     if britney:
226         britney_changelog(current, suite, session)
227
228 #######################################################################################
229
230 def process_file(file, suite, action, session, britney=False):
231     if action == "set":
232         set_suite(file, suite, session, britney)
233         return
234
235     suite_id = suite.suite_id
236
237     lines = file.readlines()
238
239     # Our session is already in a transaction
240     for line in lines:
241         split_line = line.strip().split()
242         if len(split_line) != 3:
243             utils.warn("'%s' does not break into 'package version architecture'." % (line[:-1]))
244             continue
245
246         (package, version, architecture) = split_line
247
248         pkid = get_id(package, version, architecture, session)
249         if not pkid:
250             continue
251
252         if architecture == "source":
253             # Find the existing association ID, if any
254             q = session.execute("""SELECT id FROM src_associations
255                                     WHERE suite = :suiteid and source = :pkid""",
256                                     {'suiteid': suite_id, 'pkid': pkid})
257             ql = q.fetchall()
258             if len(ql) < 1:
259                 association_id = None
260             else:
261                 association_id = ql[0][0]
262
263             # Take action
264             if action == "add":
265                 if association_id:
266                     utils.warn("'%s_%s_%s' already exists in suite %s." % (package, version, architecture, suite))
267                     continue
268                 else:
269                     session.execute("""INSERT INTO src_associations (suite, source)
270                                             VALUES (:suiteid, :pkid)""",
271                                        {'suiteid': suite_id, 'pkid': pkid})
272             elif action == "remove":
273                 if association_id == None:
274                     utils.warn("'%s_%s_%s' doesn't exist in suite %s." % (package, version, architecture, suite))
275                     continue
276                 else:
277                     session.execute("""DELETE FROM src_associations WHERE id = :pkid""", {'pkid': association_id})
278         else:
279             # Find the existing associations ID, if any
280             q = session.execute("""SELECT id FROM bin_associations
281                                     WHERE suite = :suiteid and bin = :pkid""",
282                                     {'suiteid': suite_id, 'pkid': pkid})
283             ql = q.fetchall()
284             if len(ql) < 1:
285                 association_id = None
286             else:
287                 association_id = ql[0][0]
288
289             # Take action
290             if action == "add":
291                 if association_id:
292                     utils.warn("'%s_%s_%s' already exists in suite %s." % (package, version, architecture, suite))
293                     continue
294                 else:
295                     session.execute("""INSERT INTO bin_associations (suite, bin)
296                                             VALUES (:suiteid, :pkid)""",
297                                        {'suiteid': suite_id, 'pkid': pkid})
298             elif action == "remove":
299                 if association_id == None:
300                     utils.warn("'%s_%s_%s' doesn't exist in suite %s." % (package, version, architecture, suite))
301                     continue
302                 else:
303                     session.execute("""DELETE FROM bin_associations WHERE id = :pkid""", {'pkid': association_id})
304
305     session.commit()
306
307 #######################################################################################
308
309 def get_list(suite, session):
310     suite_id = suite.suite_id
311     # List binaries
312     q = session.execute("""SELECT b.package, b.version, a.arch_string
313                              FROM binaries b, bin_associations ba, architecture a
314                             WHERE ba.suite = :suiteid
315                               AND ba.bin = b.id AND b.architecture = a.id""", {'suiteid': suite_id})
316     for i in q.fetchall():
317         print " ".join(i)
318
319     # List source
320     q = session.execute("""SELECT s.source, s.version
321                              FROM source s, src_associations sa
322                             WHERE sa.suite = :suiteid
323                               AND sa.source = s.id""", {'suiteid': suite_id})
324     for i in q.fetchall():
325         print " ".join(i) + " source"
326
327 #######################################################################################
328
329 def main ():
330     global Logger
331
332     cnf = Config()
333
334     Arguments = [('a',"add","Control-Suite::Options::Add", "HasArg"),
335                  ('b',"britney","Control-Suite::Options::Britney"),
336                  ('h',"help","Control-Suite::Options::Help"),
337                  ('l',"list","Control-Suite::Options::List","HasArg"),
338                  ('r',"remove", "Control-Suite::Options::Remove", "HasArg"),
339                  ('s',"set", "Control-Suite::Options::Set", "HasArg")]
340
341     for i in ["add", "britney", "help", "list", "remove", "set", "version" ]:
342         if not cnf.has_key("Control-Suite::Options::%s" % (i)):
343             cnf["Control-Suite::Options::%s" % (i)] = ""
344
345     try:
346         file_list = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv);
347     except SystemError, e:
348         print "%s\n" % e
349         usage(1)
350     Options = cnf.SubTree("Control-Suite::Options")
351
352     if Options["Help"]:
353         usage()
354
355     session = DBConn().session()
356
357     action = None
358
359     for i in ("add", "list", "remove", "set"):
360         if cnf["Control-Suite::Options::%s" % (i)] != "":
361             suite_name = cnf["Control-Suite::Options::%s" % (i)]
362             suite = get_suite(suite_name, session=session)
363             if suite is None:
364                 utils.fubar("Unknown suite '%s'." % (suite_name))
365             else:
366                 if action:
367                     utils.fubar("Can only perform one action at a time.")
368                 action = i
369
370     # Need an action...
371     if action == None:
372         utils.fubar("No action specified.")
373
374     # Safety/Sanity check
375     # XXX: This should be stored in the database
376     if action == "set" and suite_name not in ["testing", "squeeze-updates"]:
377         utils.fubar("Will not reset suite %s" % (suite_name))
378
379     britney = False
380     if action == "set" and cnf["Control-Suite::Options::Britney"]:
381         britney = True
382
383     if action == "list":
384         get_list(suite, session)
385     else:
386         Logger = daklog.Logger(cnf.Cnf, "control-suite")
387         if file_list:
388             for f in file_list:
389                 process_file(utils.open_file(f), suite, action, session, britney)
390         else:
391             process_file(sys.stdin, suite, action, session, britney)
392         Logger.close()
393
394 #######################################################################################
395
396 if __name__ == '__main__':
397     main()