]> git.decadent.org.uk Git - dak.git/blob - dak/admin.py
Make admin.py more robust.
[dak.git] / dak / admin.py
1 #!/usr/bin/env python
2
3 """Configure dak parameters in the database"""
4 # Copyright (C) 2009  Mark Hymers <mhy@debian.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 import sys
23
24 import apt_pkg
25
26 from daklib import utils
27 from daklib.dbconn import *
28
29 ################################################################################
30
31 dispatch = {}
32 dryrun = False
33
34 ################################################################################
35 def warn(msg):
36     print >> sys.stderr, msg
37
38 def die(msg, exit_code=1):
39     print >> sys.stderr, msg
40     sys.exit(exit_code)
41
42 def die_arglen(args, args_needed, msg):
43     if len(args) < args_needed:
44         die(msg)
45
46 def usage(exit_code=0):
47     """Perform administrative work on the dak database."""
48
49     print """Usage: dak admin COMMAND
50 Perform administrative work on the dak database.
51
52   -h, --help          show this help and exit.
53   -n, --dry-run       don't do anything, just show what would have been done
54                       (only applies to add or rm operations).
55
56   Commands can use a long or abbreviated form:
57
58   config / c:
59      c db                   show db config
60      c db-shell             show db config in a usable form for psql
61
62   architecture / a:
63      a list                 show a list of architectures
64      a rm ARCH              remove an architecture (will only work if
65                             no longer linked to any suites)
66      a add ARCH DESCRIPTION [SUITELIST]
67                             add architecture ARCH with DESCRIPTION.
68                             If SUITELIST is given, add to each of the
69                             suites at the same time
70
71   suite / s:
72      s list                 show a list of suites
73      s show SUITE           show config details for a suite
74      s add SUITE VERSION [ label=LABEL ] [ description=DESCRIPTION ]
75                          [ origin=ORIGIN ] [ codename=CODENAME ]
76                             add suite SUITE, version VERSION. label,
77                             description, origin and codename are optional.
78
79   suite-architecture / s-a:
80      s-a list-suite ARCH    show the suites an ARCH is in
81      s-a list-arch SUITE    show the architectures in a SUITE
82      s-a add SUITE ARCH     add ARCH to suite
83      s-a rm SUITE ARCH      remove ARCH from suite (will only work if
84                             no packages remain for the arch in the suite)
85 """
86     sys.exit(exit_code)
87
88 ################################################################################
89
90 def __architecture_list(d, args):
91     q = d.session().query(Architecture).order_by('arch_string')
92     for j in q.all():
93         # HACK: We should get rid of source from the arch table
94         if j.arch_string == 'source': continue
95         print j.arch_string
96     sys.exit(0)
97
98 def __architecture_add(d, args):
99     die_arglen(args, 4, "E: adding an architecture requires a name and a description")
100     print "Adding architecture %s" % args[2]
101     suites = [str(x) for x in args[4:]]
102     if len(suites) > 0:
103         print "Adding to suites %s" % ", ".join(suites)
104     if not dryrun:
105         try:
106             s = d.session()
107             a = Architecture()
108             a.arch_string = str(args[2]).lower()
109             a.description = str(args[3])
110             s.add(a)
111             for sn in suites:
112                 su = get_suite(sn, s)
113                 if su is not None:
114                     a.suites.append(su)
115                 else:
116                     warn("W: Cannot find suite %s" % su)
117             s.commit()
118         except IntegrityError, e:
119             die("E: Integrity error adding architecture %s (it probably already exists)" % args[2])
120         except SQLAlchemyError, e:
121             die("E: Error adding architecture %s (%s)" % (args[2], e))
122     print "Architecture %s added" % (args[2])
123
124 def __architecture_rm(d, args):
125     die_arglen(args, 3, "E: removing an architecture requires at least a name")
126     print "Removing architecture %s" % args[2]
127     if not dryrun:
128         try:
129             s = d.session()
130             a = get_architecture(args[2].lower(), s)
131             if a is None:
132                 die("E: Cannot find architecture %s" % args[2])
133             s.delete(a)
134             s.commit()
135         except IntegrityError, e:
136             die("E: Integrity error removing architecture %s (suite-arch entries probably still exist)" % args[2])
137         except SQLAlchemyError, e:
138             die("E: Error removing architecture %s (%s)" % (args[2], e))
139     print "Architecture %s removed" % args[2]
140
141 def architecture(command):
142     args = [str(x) for x in command]
143     Cnf = utils.get_conf()
144     d = DBConn()
145
146     die_arglen(args, 2, "E: architecture needs at least a command")
147
148     mode = args[1].lower()
149     if mode == 'list':
150         __architecture_list(d, args)
151     elif mode == 'add':
152         __architecture_add(d, args)
153     elif mode == 'rm':
154         __architecture_rm(d, args)
155     else:
156         die("E: architecture command unknown")
157
158 dispatch['architecture'] = architecture
159 dispatch['a'] = architecture
160
161 ################################################################################
162
163 def __suite_list(d, args):
164     s = d.session()
165     for j in s.query(Suite).order_by('suite_name').all():
166         print j.suite_name
167
168 def __suite_show(d, args):
169     if len(args) < 2:
170         die("E: showing an suite entry requires a suite")
171
172     s = d.session()
173     su = get_suite(args[2].lower())
174     if su is None:
175         die("E: can't find suite entry for %s" % (args[2].lower()))
176
177     print su.details()
178
179 def __suite_add(d, args):
180     die_arglen(args, 4, "E: adding a suite requires at least a name and a version")
181     suite_name = args[2].lower()
182     version = args[3]
183     rest = args[3:]
184
185     def get_field(field):
186         for varval in args:
187             if varval.startswith(field + '='):
188                 return varval.split('=')[1]
189         return None
190
191     print "Adding suite %s" % suite_name
192     if not dryrun:
193         try:
194             s = d.session()
195             suite = Suite()
196             suite.suite_name = suite_name
197             suite.version = version
198             suite.label = get_field('label')
199             suite.description = get_field('description')
200             suite.origin = get_field('origin')
201             suite.codename = get_field('codename')
202             s.add(suite)
203             s.commit()
204         except IntegrityError, e:
205             die("E: Integrity error adding suite %s (it probably already exists)" % suite_name)
206         except SQLAlchemyError, e:
207             die("E: Error adding suite %s (%s)" % (suite_name, e))
208     print "Suite %s added" % (suite_name)
209
210 def suite(command):
211     args = [str(x) for x in command]
212     Cnf = utils.get_conf()
213     d = DBConn()
214
215     die_arglen(args, 2, "E: suite needs at least a command")
216
217     mode = args[1].lower()
218
219     if mode == 'list':
220         __suite_list(d, args)
221     elif mode == 'show':
222         __suite_show(d, args)
223     elif mode == 'add':
224         __suite_add(d, args)
225     else:
226         die("E: suite command unknown")
227
228 dispatch['suite'] = suite
229 dispatch['s'] = suite
230
231 ################################################################################
232
233 def __suite_architecture_list(d, args):
234     s = d.session()
235     for j in s.query(Suite).order_by('suite_name').all():
236         print j.suite_name + ' ' + \
237               ','.join([a.architecture.arch_string for a in j.suitearchitectures])
238
239 def __suite_architecture_listarch(d, args):
240     die_arglen(args, 3, "E: suite-architecture list-arch requires a suite")
241     suite = get_suite(args[2].lower(), d.session())
242     if suite is None:
243         die('E: suite %s is invalid' % args[2].lower())
244     a = suite.get_architectures(skipsrc = True, skipall = True)
245     for j in a:
246         print j.arch_string
247
248
249 def __suite_architecture_listsuite(d, args):
250     die_arglen(args, 3, "E: suite-architecture list-suite requires an arch")
251     architecture = get_architecture(args[2].lower(), d.session())
252     if architecture is None:
253         die("E: architecture %s is invalid" % args[2].lower())
254     for j in architecture.suites:
255         print j.suite_name
256
257
258 def __suite_architecture_add(d, args):
259     if len(args) < 3:
260         die("E: adding a suite-architecture entry requires a suite and arch")
261
262     s = d.session()
263
264     suite = get_suite(args[2].lower(), s)
265     if suite is None: die("E: Can't find suite %s" % args[2].lower())
266
267     arch = get_architecture(args[3].lower(), s)
268     if arch is None: die("E: Can't find architecture %s" % args[3].lower())
269
270     if not dryrun:
271         try:
272             suite.architectures.append(arch)
273             s.commit()
274         except IntegrityError, e:
275             die("E: Can't add suite-architecture entry (%s, %s) - probably already exists" % (args[2].lower(), args[3].lower()))
276         except SQLAlchemyError, e:
277             die("E: Can't add suite-architecture entry (%s, %s) - %s" % (args[2].lower(), args[3].lower(), e))
278
279     print "Added suite-architecture entry for %s, %s" % (args[2].lower(), args[3].lower())
280
281
282 def __suite_architecture_rm(d, args):
283     if len(args) < 3:
284         die("E: removing an suite-architecture entry requires a suite and arch")
285
286     s = d.session()
287     if not dryrun:
288         try:
289             suite_name = args[2].lower()
290             suite = get_suite(suite_name, s)
291             if suite is None:
292                 die('E: no such suite %s' % suite_name)
293             arch_string = args[3].lower()
294             architecture = get_architecture(arch_string, s)
295             if architecture not in suite.architectures:
296                 die("E: architecture %s not found in suite %s" % (arch_string, suite_name))
297             suite.architectures.remove(architecture)
298             s.commit()
299         except IntegrityError, e:
300             die("E: Can't remove suite-architecture entry (%s, %s) - it's probably referenced" % (args[2].lower(), args[3].lower()))
301         except SQLAlchemyError, e:
302             die("E: Can't remove suite-architecture entry (%s, %s) - %s" % (args[2].lower(), args[3].lower(), e))
303
304     print "Removed suite-architecture entry for %s, %s" % (args[2].lower(), args[3].lower())
305
306
307 def suite_architecture(command):
308     args = [str(x) for x in command]
309     Cnf = utils.get_conf()
310     d = DBConn()
311
312     die_arglen(args, 2, "E: suite-architecture needs at least a command")
313
314     mode = args[1].lower()
315
316     if mode == 'list':
317         __suite_architecture_list(d, args)
318     elif mode == 'list-arch':
319         __suite_architecture_listarch(d, args)
320     elif mode == 'list-suite':
321         __suite_architecture_listsuite(d, args)
322     elif mode == 'add':
323         __suite_architecture_add(d, args)
324     elif mode == 'rm':
325         __suite_architecture_rm(d, args)
326     else:
327         die("E: suite-architecture command unknown")
328
329 dispatch['suite-architecture'] = suite_architecture
330 dispatch['s-a'] = suite_architecture
331
332 ################################################################################
333
334 def show_config(command):
335     args = [str(x) for x in command]
336     cnf = utils.get_conf()
337
338     die_arglen(args, 2, "E: config needs at least a command")
339
340     mode = args[1].lower()
341
342     if mode == 'db':
343         connstr = ""
344         if cnf["DB::Host"]:
345             # TCP/IP
346             connstr = "postgres://%s" % cnf["DB::Host"]
347             if cnf["DB::Port"] and cnf["DB::Port"] != "-1":
348                 connstr += ":%s" % cnf["DB::Port"]
349             connstr += "/%s" % cnf["DB::Name"]
350         else:
351             # Unix Socket
352             connstr = "postgres:///%s" % cnf["DB::Name"]
353             if cnf["DB::Port"] and cnf["DB::Port"] != "-1":
354                 connstr += "?port=%s" % cnf["DB::Port"]
355         print connstr
356     elif mode == 'db-shell':
357         e = ['PGDATABASE']
358         print "PGDATABASE=%s" % cnf["DB::Name"]
359         if cnf["DB::Host"]:
360             print "PGHOST=%s" % cnf["DB::Host"]
361             e.append('PGHOST')
362         if cnf["DB::Port"] and cnf["DB::Port"] != "-1":
363             print "PGPORT=%s" % cnf["DB::Port"]
364             e.append('PGPORT')
365         print "export " + " ".join(e)
366     else:
367         die("E: config command unknown")
368
369 dispatch['config'] = show_config
370 dispatch['c'] = show_config
371
372 ################################################################################
373
374 def main():
375     """Perform administrative work on the dak database"""
376     global dryrun
377     Cnf = utils.get_conf()
378     arguments = [('h', "help", "Admin::Options::Help"),
379                  ('n', "dry-run", "Admin::Options::Dry-Run")]
380     for i in [ "help", "dry-run" ]:
381         if not Cnf.has_key("Admin::Options::%s" % (i)):
382             Cnf["Admin::Options::%s" % (i)] = ""
383
384     arguments = apt_pkg.ParseCommandLine(Cnf, arguments, sys.argv)
385
386     options = Cnf.SubTree("Admin::Options")
387     if options["Help"] or len(arguments) < 1:
388         usage()
389     if options["Dry-Run"]:
390         dryrun = True
391
392     subcommand = str(arguments[0])
393
394     if subcommand in dispatch.keys():
395         dispatch[subcommand](arguments)
396     else:
397         die("E: Unknown command")
398
399 ################################################################################
400
401 if __name__ == '__main__':
402     main()