]> git.decadent.org.uk Git - dak.git/blob - dak/transitions.py
Fix yaml dump bug in syck by using yaml instead
[dak.git] / dak / transitions.py
1 #!/usr/bin/env python
2
3 # Display, edit and check the release manager's transition file.
4 # Copyright (C) 2008 Joerg Jaspert <joerg@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 # <elmo> if klecker.d.o died, I swear to god, I'm going to migrate to gentoo.
23
24 ################################################################################
25
26 import os, pg, sys, time, errno, fcntl, tempfile, pwd, re
27 import apt_pkg
28 from daklib import database
29 from daklib import utils
30 from daklib.dak_exceptions import TransitionsError
31 import syck
32 import yaml
33
34 # Globals
35 Cnf = None
36 Options = None
37 projectB = None
38
39 re_broken_package = re.compile(r"[a-zA-Z]\w+\s+\-.*")
40
41 ################################################################################
42
43 #####################################
44 #### This may run within sudo !! ####
45 #####################################
46 def init():
47     global Cnf, Options, projectB
48
49     apt_pkg.init()
50
51     Cnf = utils.get_conf()
52
53     Arguments = [('h',"help","Edit-Transitions::Options::Help"),
54                  ('e',"edit","Edit-Transitions::Options::Edit"),
55                  ('i',"import","Edit-Transitions::Options::Import", "HasArg"),
56                  ('c',"check","Edit-Transitions::Options::Check"),
57                  ('s',"sudo","Edit-Transitions::Options::Sudo"),
58                  ('n',"no-action","Edit-Transitions::Options::No-Action")]
59
60     for i in ["help", "no-action", "edit", "import", "check", "sudo"]:
61         if not Cnf.has_key("Edit-Transitions::Options::%s" % (i)):
62             Cnf["Edit-Transitions::Options::%s" % (i)] = ""
63
64     apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
65
66     Options = Cnf.SubTree("Edit-Transitions::Options")
67
68     if Options["help"]:
69         usage()
70
71     whoami = os.getuid()
72     whoamifull = pwd.getpwuid(whoami)
73     username = whoamifull[0]
74     if username != "dak":
75         print "Non-dak user: %s" % username
76         Options["sudo"] = "y"
77
78     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
79     database.init(Cnf, projectB)
80
81 ################################################################################
82
83 def usage (exit_code=0):
84     print """Usage: transitions [OPTION]...
85 Update and check the release managers transition file.
86
87 Options:
88
89   -h, --help                show this help and exit.
90   -e, --edit                edit the transitions file
91   -i, --import <file>       check and import transitions from file
92   -c, --check               check the transitions file, remove outdated entries
93   -S, --sudo                use sudo to update transitions file
94   -n, --no-action           don't do anything (only affects check)"""
95
96     sys.exit(exit_code)
97
98 ################################################################################
99
100 #####################################
101 #### This may run within sudo !! ####
102 #####################################
103 def load_transitions(trans_file):
104     # Parse the yaml file
105     sourcefile = file(trans_file, 'r')
106     sourcecontent = sourcefile.read()
107     failure = False
108     try:
109         trans = syck.load(sourcecontent)
110     except syck.error, msg:
111         # Someone fucked it up
112         print "ERROR: %s" % (msg)
113         return None
114
115     # lets do further validation here
116     checkkeys = ["source", "reason", "packages", "new", "rm"]
117
118     # If we get an empty definition - we just have nothing to check, no transitions defined
119     if type(trans) != dict:
120         # This can be anything. We could have no transitions defined. Or someone totally fucked up the
121         # file, adding stuff in a way we dont know or want. Then we set it empty - and simply have no
122         # transitions anymore. User will see it in the information display after he quit the editor and
123         # could fix it
124         trans = ""
125         return trans
126
127     try:
128         for test in trans:
129             t = trans[test]
130
131             # First check if we know all the keys for the transition and if they have
132             # the right type (and for the packages also if the list has the right types
133             # included, ie. not a list in list, but only str in the list)
134             for key in t:
135                 if key not in checkkeys:
136                     print "ERROR: Unknown key %s in transition %s" % (key, test)
137                     failure = True
138
139                 if key == "packages":
140                     if type(t[key]) != list:
141                         print "ERROR: Unknown type %s for packages in transition %s." % (type(t[key]), test)
142                         failure = True
143                     try:
144                         for package in t["packages"]:
145                             if type(package) != str:
146                                 print "ERROR: Packages list contains invalid type %s (as %s) in transition %s" % (type(package), package, test)
147                                 failure = True
148                             if re_broken_package.match(package):
149                                 # Someone had a space too much (or not enough), we have something looking like
150                                 # "package1 - package2" now.
151                                 print "ERROR: Invalid indentation of package list in transition %s, around package(s): %s" % (test, package)
152                                 failure = True
153                     except TypeError:
154                         # In case someone has an empty packages list
155                         print "ERROR: No packages defined in transition %s" % (test)
156                         failure = True
157                         continue
158
159                 elif type(t[key]) != str:
160                     if key == "new" and type(t[key]) == int:
161                         # Ok, debian native version
162                         continue
163                     else:
164                         print "ERROR: Unknown type %s for key %s in transition %s" % (type(t[key]), key, test)
165                         failure = True
166
167             # And now the other way round - are all our keys defined?
168             for key in checkkeys:
169                 if key not in t:
170                     print "ERROR: Missing key %s in transition %s" % (key, test)
171                     failure = True
172     except TypeError:
173         # In case someone defined very broken things
174         print "ERROR: Unable to parse the file"
175         failure = True
176
177
178     if failure:
179         return None
180
181     return trans
182
183 ################################################################################
184
185 #####################################
186 #### This may run within sudo !! ####
187 #####################################
188 def lock_file(f):
189     for retry in range(10):
190         lock_fd = os.open(f, os.O_RDWR | os.O_CREAT)
191         try:
192             fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
193             return lock_fd
194         except OSError, e:
195             if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EEXIST':
196                 print "Unable to get lock for %s (try %d of 10)" % \
197                         (file, retry+1)
198                 time.sleep(60)
199             else:
200                 raise
201
202     utils.fubar("Couldn't obtain lock for %s." % (f))
203
204 ################################################################################
205
206 #####################################
207 #### This may run within sudo !! ####
208 #####################################
209 def write_transitions(from_trans):
210     """Update the active transitions file safely.
211        This function takes a parsed input file (which avoids invalid
212        files or files that may be be modified while the function is
213        active), and ensure the transitions file is updated atomically
214        to avoid locks."""
215
216     trans_file = Cnf["Dinstall::Reject::ReleaseTransitions"]
217     trans_temp = trans_file + ".tmp"
218
219     trans_lock = lock_file(trans_file)
220     temp_lock  = lock_file(trans_temp)
221
222     destfile = file(trans_temp, 'w')
223     yaml.dump(from_trans, destfile, default_flow_style=False)
224     destfile.close()
225
226     os.rename(trans_temp, trans_file)
227     os.close(temp_lock)
228     os.close(trans_lock)
229
230 ################################################################################
231
232 ##########################################
233 #### This usually runs within sudo !! ####
234 ##########################################
235 def write_transitions_from_file(from_file):
236     """We have a file we think is valid; if we're using sudo, we invoke it
237        here, otherwise we just parse the file and call write_transitions"""
238
239     # Lets check if from_file is in the directory we expect it to be in
240     if not os.path.abspath(from_file).startswith(Cnf["Transitions::TempPath"]):
241         print "Will not accept transitions file outside of %s" % (Cnf["Transitions::TempPath"])
242         sys.exit(3)
243
244     if Options["sudo"]:
245         os.spawnl(os.P_WAIT, "/usr/bin/sudo", "/usr/bin/sudo", "-u", "dak", "-H",
246               "/usr/local/bin/dak", "transitions", "--import", from_file)
247     else:
248         trans = load_transitions(from_file)
249         if trans is None:
250             raise TransitionsError, "Unparsable transitions file %s" % (file)
251         write_transitions(trans)
252
253 ################################################################################
254
255 def temp_transitions_file(transitions):
256     # NB: file is unlinked by caller, but fd is never actually closed.
257     # We need the chmod, as the file is (most possibly) copied from a
258     # sudo-ed script and would be unreadable if it has default mkstemp mode
259
260     (fd, path) = tempfile.mkstemp("", "transitions", Cnf["Transitions::TempPath"])
261     os.chmod(path, 0644)
262     f = open(path, "w")
263     yaml.dump(transitions, f, default_flow_style=False)
264     return path
265
266 ################################################################################
267
268 def edit_transitions():
269     trans_file = Cnf["Dinstall::Reject::ReleaseTransitions"]
270     edit_file = temp_transitions_file(load_transitions(trans_file))
271
272     editor = os.environ.get("EDITOR", "vi")
273
274     while True:
275         result = os.system("%s %s" % (editor, edit_file))
276         if result != 0:
277             os.unlink(edit_file)
278             utils.fubar("%s invocation failed for %s, not removing tempfile." % (editor, edit_file))
279
280         # Now try to load the new file
281         test = load_transitions(edit_file)
282
283         if test == None:
284             # Edit is broken
285             print "Edit was unparsable."
286             prompt = "[E]dit again, Drop changes?"
287             default = "E"
288         else:
289             print "Edit looks okay.\n"
290             print "The following transitions are defined:"
291             print "------------------------------------------------------------------------"
292             transition_info(test)
293
294             prompt = "[S]ave, Edit again, Drop changes?"
295             default = "S"
296
297         answer = "XXX"
298         while prompt.find(answer) == -1:
299             answer = utils.our_raw_input(prompt)
300             if answer == "":
301                 answer = default
302             answer = answer[:1].upper()
303
304         if answer == 'E':
305             continue
306         elif answer == 'D':
307             os.unlink(edit_file)
308             print "OK, discarding changes"
309             sys.exit(0)
310         elif answer == 'S':
311             # Ready to save
312             break
313         else:
314             print "You pressed something you shouldn't have :("
315             sys.exit(1)
316
317     # We seem to be done and also have a working file. Copy over.
318     write_transitions_from_file(edit_file)
319     os.unlink(edit_file)
320
321     print "Transitions file updated."
322
323 ################################################################################
324
325 def check_transitions(transitions):
326     to_dump = 0
327     to_remove = []
328     # Now look through all defined transitions
329     for trans in transitions:
330         t = transitions[trans]
331         source = t["source"]
332         expected = t["new"]
333
334         # Will be None if nothing is in testing.
335         current = database.get_suite_version(source, "testing")
336
337         print_info(trans, source, expected, t["rm"], t["reason"], t["packages"])
338
339         if current == None:
340             # No package in testing
341             print "Transition source %s not in testing, transition still ongoing." % (source)
342         else:
343             compare = apt_pkg.VersionCompare(current, expected)
344             if compare < 0:
345                 # This is still valid, the current version in database is older than
346                 # the new version we wait for
347                 print "This transition is still ongoing, we currently have version %s" % (current)
348             else:
349                 print "REMOVE: This transition is over, the target package reached testing. REMOVE"
350                 print "%s wanted version: %s, has %s" % (source, expected, current)
351                 to_remove.append(trans)
352                 to_dump = 1
353         print "-------------------------------------------------------------------------"
354
355     if to_dump:
356         prompt = "Removing: "
357         for remove in to_remove:
358             prompt += remove
359             prompt += ","
360
361         prompt += " Commit Changes? (y/N)"
362         answer = ""
363
364         if Options["no-action"]:
365             answer="n"
366         else:
367             answer = utils.our_raw_input(prompt).lower()
368
369         if answer == "":
370             answer = "n"
371
372         if answer == 'n':
373             print "Not committing changes"
374             sys.exit(0)
375         elif answer == 'y':
376             print "Committing"
377             for remove in to_remove:
378                 del transitions[remove]
379
380             edit_file = temp_transitions_file(transitions)
381             write_transitions_from_file(edit_file)
382
383             print "Done"
384         else:
385             print "WTF are you typing?"
386             sys.exit(0)
387
388 ################################################################################
389
390 def print_info(trans, source, expected, rm, reason, packages):
391     print """Looking at transition: %s
392 Source:      %s
393 New Version: %s
394 Responsible: %s
395 Description: %s
396 Blocked Packages (total: %d): %s
397 """ % (trans, source, expected, rm, reason, len(packages), ", ".join(packages))
398     return
399
400 ################################################################################
401
402 def transition_info(transitions):
403     for trans in transitions:
404         t = transitions[trans]
405         source = t["source"]
406         expected = t["new"]
407
408         # Will be None if nothing is in testing.
409         current = database.get_suite_version(source, "testing")
410
411         print_info(trans, source, expected, t["rm"], t["reason"], t["packages"])
412
413         if current == None:
414             # No package in testing
415             print "Transition source %s not in testing, transition still ongoing." % (source)
416         else:
417             compare = apt_pkg.VersionCompare(current, expected)
418             print "Apt compare says: %s" % (compare)
419             if compare < 0:
420                 # This is still valid, the current version in database is older than
421                 # the new version we wait for
422                 print "This transition is still ongoing, we currently have version %s" % (current)
423             else:
424                 print "This transition is over, the target package reached testing, should be removed"
425                 print "%s wanted version: %s, has %s" % (source, expected, current)
426         print "-------------------------------------------------------------------------"
427
428 ################################################################################
429
430 def main():
431     global Cnf
432
433     #####################################
434     #### This can run within sudo !! ####
435     #####################################
436     init()
437
438     # Check if there is a file defined (and existant)
439     transpath = Cnf.get("Dinstall::Reject::ReleaseTransitions", "")
440     if transpath == "":
441         utils.warn("Dinstall::Reject::ReleaseTransitions not defined")
442         sys.exit(1)
443     if not os.path.exists(transpath):
444         utils.warn("ReleaseTransitions file, %s, not found." %
445                           (Cnf["Dinstall::Reject::ReleaseTransitions"]))
446         sys.exit(1)
447     # Also check if our temp directory is defined and existant
448     temppath = Cnf.get("Transitions::TempPath", "")
449     if temppath == "":
450         utils.warn("Transitions::TempPath not defined")
451         sys.exit(1)
452     if not os.path.exists(temppath):
453         utils.warn("Temporary path %s not found." %
454                           (Cnf["Transitions::TempPath"]))
455         sys.exit(1)
456
457     if Options["import"]:
458         try:
459             write_transitions_from_file(Options["import"])
460         except TransitionsError, m:
461             print m
462             sys.exit(2)
463         sys.exit(0)
464     ##############################################
465     #### Up to here it can run within sudo !! ####
466     ##############################################
467
468     # Parse the yaml file
469     transitions = load_transitions(transpath)
470     if transitions == None:
471         # Something very broken with the transitions, exit
472         utils.warn("Could not parse existing transitions file. Aborting.")
473         sys.exit(2)
474
475     if Options["edit"]:
476         # Let's edit the transitions file
477         edit_transitions()
478     elif Options["check"]:
479         # Check and remove outdated transitions
480         check_transitions(transitions)
481     else:
482         # Output information about the currently defined transitions.
483         print "Currently defined transitions:"
484         transition_info(transitions)
485
486     sys.exit(0)
487
488 ################################################################################
489
490 if __name__ == '__main__':
491     main()