3 """ Display, edit and check the release manager's transition file. """
4 # Copyright (C) 2008 Joerg Jaspert <joerg@debian.org>
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.
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.
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
20 ################################################################################
22 # <elmo> if klecker.d.o died, I swear to god, I'm going to migrate to gentoo.
24 ################################################################################
26 import os, pg, sys, time, errno, fcntl, tempfile, pwd
28 from daklib import database
29 from daklib import utils
30 from daklib.dak_exceptions import TransitionsError
31 from daklib.regexes import re_broken_package
39 ################################################################################
41 #####################################
42 #### This may run within sudo !! ####
43 #####################################
45 global Cnf, Options, projectB
49 Cnf = utils.get_conf()
51 Arguments = [('h',"help","Edit-Transitions::Options::Help"),
52 ('e',"edit","Edit-Transitions::Options::Edit"),
53 ('i',"import","Edit-Transitions::Options::Import", "HasArg"),
54 ('c',"check","Edit-Transitions::Options::Check"),
55 ('s',"sudo","Edit-Transitions::Options::Sudo"),
56 ('n',"no-action","Edit-Transitions::Options::No-Action")]
58 for i in ["help", "no-action", "edit", "import", "check", "sudo"]:
59 if not Cnf.has_key("Edit-Transitions::Options::%s" % (i)):
60 Cnf["Edit-Transitions::Options::%s" % (i)] = ""
62 apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
64 Options = Cnf.SubTree("Edit-Transitions::Options")
70 whoamifull = pwd.getpwuid(whoami)
71 username = whoamifull[0]
73 print "Non-dak user: %s" % username
76 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
77 database.init(Cnf, projectB)
79 ################################################################################
81 def usage (exit_code=0):
82 print """Usage: transitions [OPTION]...
83 Update and check the release managers transition file.
87 -h, --help show this help and exit.
88 -e, --edit edit the transitions file
89 -i, --import <file> check and import transitions from file
90 -c, --check check the transitions file, remove outdated entries
91 -S, --sudo use sudo to update transitions file
92 -n, --no-action don't do anything (only affects check)"""
96 ################################################################################
98 #####################################
99 #### This may run within sudo !! ####
100 #####################################
101 def load_transitions(trans_file):
102 # Parse the yaml file
103 sourcefile = file(trans_file, 'r')
104 sourcecontent = sourcefile.read()
107 trans = yaml.load(sourcecontent)
108 except yaml.YAMLError, exc:
109 # Someone fucked it up
110 print "ERROR: %s" % (exc)
113 # lets do further validation here
114 checkkeys = ["source", "reason", "packages", "new", "rm"]
116 # If we get an empty definition - we just have nothing to check, no transitions defined
117 if type(trans) != dict:
118 # This can be anything. We could have no transitions defined. Or someone totally fucked up the
119 # file, adding stuff in a way we dont know or want. Then we set it empty - and simply have no
120 # transitions anymore. User will see it in the information display after he quit the editor and
129 # First check if we know all the keys for the transition and if they have
130 # the right type (and for the packages also if the list has the right types
131 # included, ie. not a list in list, but only str in the list)
133 if key not in checkkeys:
134 print "ERROR: Unknown key %s in transition %s" % (key, test)
137 if key == "packages":
138 if type(t[key]) != list:
139 print "ERROR: Unknown type %s for packages in transition %s." % (type(t[key]), test)
142 for package in t["packages"]:
143 if type(package) != str:
144 print "ERROR: Packages list contains invalid type %s (as %s) in transition %s" % (type(package), package, test)
146 if re_broken_package.match(package):
147 # Someone had a space too much (or not enough), we have something looking like
148 # "package1 - package2" now.
149 print "ERROR: Invalid indentation of package list in transition %s, around package(s): %s" % (test, package)
152 # In case someone has an empty packages list
153 print "ERROR: No packages defined in transition %s" % (test)
157 elif type(t[key]) != str:
158 if key == "new" and type(t[key]) == int:
159 # Ok, debian native version
162 print "ERROR: Unknown type %s for key %s in transition %s" % (type(t[key]), key, test)
165 # And now the other way round - are all our keys defined?
166 for key in checkkeys:
168 print "ERROR: Missing key %s in transition %s" % (key, test)
171 # In case someone defined very broken things
172 print "ERROR: Unable to parse the file"
181 ################################################################################
183 #####################################
184 #### This may run within sudo !! ####
185 #####################################
187 for retry in range(10):
188 lock_fd = os.open(f, os.O_RDWR | os.O_CREAT)
190 fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
193 if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EEXIST':
194 print "Unable to get lock for %s (try %d of 10)" % \
200 utils.fubar("Couldn't obtain lock for %s." % (f))
202 ################################################################################
204 #####################################
205 #### This may run within sudo !! ####
206 #####################################
207 def write_transitions(from_trans):
208 """Update the active transitions file safely.
209 This function takes a parsed input file (which avoids invalid
210 files or files that may be be modified while the function is
211 active), and ensure the transitions file is updated atomically
214 trans_file = Cnf["Dinstall::Reject::ReleaseTransitions"]
215 trans_temp = trans_file + ".tmp"
217 trans_lock = lock_file(trans_file)
218 temp_lock = lock_file(trans_temp)
220 destfile = file(trans_temp, 'w')
221 yaml.dump(from_trans, destfile, default_flow_style=False)
224 os.rename(trans_temp, trans_file)
228 ################################################################################
230 ##########################################
231 #### This usually runs within sudo !! ####
232 ##########################################
233 def write_transitions_from_file(from_file):
234 """We have a file we think is valid; if we're using sudo, we invoke it
235 here, otherwise we just parse the file and call write_transitions"""
237 # Lets check if from_file is in the directory we expect it to be in
238 if not os.path.abspath(from_file).startswith(Cnf["Transitions::TempPath"]):
239 print "Will not accept transitions file outside of %s" % (Cnf["Transitions::TempPath"])
243 os.spawnl(os.P_WAIT, "/usr/bin/sudo", "/usr/bin/sudo", "-u", "dak", "-H",
244 "/usr/local/bin/dak", "transitions", "--import", from_file)
246 trans = load_transitions(from_file)
248 raise TransitionsError, "Unparsable transitions file %s" % (file)
249 write_transitions(trans)
251 ################################################################################
253 def temp_transitions_file(transitions):
254 # NB: file is unlinked by caller, but fd is never actually closed.
255 # We need the chmod, as the file is (most possibly) copied from a
256 # sudo-ed script and would be unreadable if it has default mkstemp mode
258 (fd, path) = tempfile.mkstemp("", "transitions", Cnf["Transitions::TempPath"])
261 yaml.dump(transitions, f, default_flow_style=False)
264 ################################################################################
266 def edit_transitions():
267 trans_file = Cnf["Dinstall::Reject::ReleaseTransitions"]
268 edit_file = temp_transitions_file(load_transitions(trans_file))
270 editor = os.environ.get("EDITOR", "vi")
273 result = os.system("%s %s" % (editor, edit_file))
276 utils.fubar("%s invocation failed for %s, not removing tempfile." % (editor, edit_file))
278 # Now try to load the new file
279 test = load_transitions(edit_file)
283 print "Edit was unparsable."
284 prompt = "[E]dit again, Drop changes?"
287 print "Edit looks okay.\n"
288 print "The following transitions are defined:"
289 print "------------------------------------------------------------------------"
290 transition_info(test)
292 prompt = "[S]ave, Edit again, Drop changes?"
296 while prompt.find(answer) == -1:
297 answer = utils.our_raw_input(prompt)
300 answer = answer[:1].upper()
306 print "OK, discarding changes"
312 print "You pressed something you shouldn't have :("
315 # We seem to be done and also have a working file. Copy over.
316 write_transitions_from_file(edit_file)
319 print "Transitions file updated."
321 ################################################################################
323 def check_transitions(transitions):
326 # Now look through all defined transitions
327 for trans in transitions:
328 t = transitions[trans]
332 # Will be None if nothing is in testing.
333 current = database.get_suite_version(source, "testing")
335 print_info(trans, source, expected, t["rm"], t["reason"], t["packages"])
338 # No package in testing
339 print "Transition source %s not in testing, transition still ongoing." % (source)
341 compare = apt_pkg.VersionCompare(current, expected)
343 # This is still valid, the current version in database is older than
344 # the new version we wait for
345 print "This transition is still ongoing, we currently have version %s" % (current)
347 print "REMOVE: This transition is over, the target package reached testing. REMOVE"
348 print "%s wanted version: %s, has %s" % (source, expected, current)
349 to_remove.append(trans)
351 print "-------------------------------------------------------------------------"
354 prompt = "Removing: "
355 for remove in to_remove:
359 prompt += " Commit Changes? (y/N)"
362 if Options["no-action"]:
365 answer = utils.our_raw_input(prompt).lower()
371 print "Not committing changes"
375 for remove in to_remove:
376 del transitions[remove]
378 edit_file = temp_transitions_file(transitions)
379 write_transitions_from_file(edit_file)
383 print "WTF are you typing?"
386 ################################################################################
388 def print_info(trans, source, expected, rm, reason, packages):
389 print """Looking at transition: %s
394 Blocked Packages (total: %d): %s
395 """ % (trans, source, expected, rm, reason, len(packages), ", ".join(packages))
398 ################################################################################
400 def transition_info(transitions):
401 for trans in transitions:
402 t = transitions[trans]
406 # Will be None if nothing is in testing.
407 current = database.get_suite_version(source, "testing")
409 print_info(trans, source, expected, t["rm"], t["reason"], t["packages"])
412 # No package in testing
413 print "Transition source %s not in testing, transition still ongoing." % (source)
415 compare = apt_pkg.VersionCompare(current, expected)
416 print "Apt compare says: %s" % (compare)
418 # This is still valid, the current version in database is older than
419 # the new version we wait for
420 print "This transition is still ongoing, we currently have version %s" % (current)
422 print "This transition is over, the target package reached testing, should be removed"
423 print "%s wanted version: %s, has %s" % (source, expected, current)
424 print "-------------------------------------------------------------------------"
426 ################################################################################
431 #####################################
432 #### This can run within sudo !! ####
433 #####################################
436 # Check if there is a file defined (and existant)
437 transpath = Cnf.get("Dinstall::Reject::ReleaseTransitions", "")
439 utils.warn("Dinstall::Reject::ReleaseTransitions not defined")
441 if not os.path.exists(transpath):
442 utils.warn("ReleaseTransitions file, %s, not found." %
443 (Cnf["Dinstall::Reject::ReleaseTransitions"]))
445 # Also check if our temp directory is defined and existant
446 temppath = Cnf.get("Transitions::TempPath", "")
448 utils.warn("Transitions::TempPath not defined")
450 if not os.path.exists(temppath):
451 utils.warn("Temporary path %s not found." %
452 (Cnf["Transitions::TempPath"]))
455 if Options["import"]:
457 write_transitions_from_file(Options["import"])
458 except TransitionsError, m:
462 ##############################################
463 #### Up to here it can run within sudo !! ####
464 ##############################################
466 # Parse the yaml file
467 transitions = load_transitions(transpath)
468 if transitions == None:
469 # Something very broken with the transitions, exit
470 utils.warn("Could not parse existing transitions file. Aborting.")
474 # Let's edit the transitions file
476 elif Options["check"]:
477 # Check and remove outdated transitions
478 check_transitions(transitions)
480 # Output information about the currently defined transitions.
481 print "Currently defined transitions:"
482 transition_info(transitions)
486 ################################################################################
488 if __name__ == '__main__':