2 import distutils.version
5 import logging.handlers
11 from wizard import app, command, deploy, scripts, shell, util
13 kib_buffer = 1024 * 30 # 30 MiB we will always leave available
14 errno_blacklisted = 64
16 def main(argv, baton):
17 options, args = parse_args(argv, baton)
22 shell.drop_priviledges(dir, options.log_file)
24 upgrade = Upgrade(options)
26 if not options.non_interactive:
27 print "Upgrade complete"
29 class Upgrade(object):
31 Represents the algorithm for upgrading an application. This is in
32 a class and not a function because it's a multi-step process that
33 requires state betweens steps. Steps are represented as methods
37 #: Version of application we are upgrading to, i.e. the latest version.
38 version = None # XXX: This is a string... I'm not convinced it should be
39 #: String commit ID of the user's latest wc; i.e. "ours"
41 #: String commit ID of the latest, greatest scripts version; i.e. "theirs"
43 #: The temporary directory that the system gave us; may stay as ``None``
44 #: if we don't ever make ourselves a temporary directory (e.g. ``--continue``).
45 #: While we should clean this up if it is set to something, it may
46 #: not correspond to anything useful.
48 #: The temporary directory containing our working copy for merging
50 #: We place the temporary repositories inside a tmpfs while merging;
51 #: this makes merges not disk-bound and affords a modest speed increase.
52 #: If you are running ``--continue``, this is guaranteed to be ``False``.
54 #: Upstream repository to use. This does not need to be saved.
57 #: Instance of :class:`wizard.deploy.WorkingCopy` for this upgrade
59 #: Instance of :class:`wizard.deploy.ProductionCopy` for this upgrade
62 #: Options object that the installer was called with
65 def __init__(self, options):
67 self.user_commit = None
68 self.next_commit = None
70 self.temp_wc_dir = None
71 self.use_shm = False # False until proven otherwise.
74 self.options = options
76 def execute(self, dir):
78 Executes an upgrade. This is the entry-point.
80 with util.ChangeDirectory(dir):
82 if self.options.continue_:
83 logging.info("Continuing upgrade...")
86 logging.info("Upgrading %s" % os.getcwd())
90 # Till now, all of our operations were in a tmp sandbox.
91 if self.options.dry_run:
92 logging.info("Dry run, bailing. See results at %s" % self.temp_wc_dir)
94 backup = self.backup()
97 if self.use_shm and self.temp_dir and os.path.exists(self.temp_dir):
98 shutil.rmtree(self.temp_dir)
102 In the event of a ``--continue`` flag, we have to restore state and
103 perform some sanity checks.
108 util.chdir(shell.eval("git", "config", "remote.origin.url"))
110 def resumeChdir(self):
112 If we called ``--continue`` inside a production copy, check if
113 :file:`.scripts/pending` exists and change to that directory if so.
115 if os.path.exists(".scripts/pending"):
116 newdir = open(".scripts/pending").read().strip()
117 logging.warning("Detected production copy; changing directory to %s", newdir)
119 def resumeState(self):
120 self.temp_wc_dir = os.getcwd()
121 self.wc = deploy.WorkingCopy(".")
123 self.user_commit, self.next_commit = open(".git/WIZARD_PARENTS", "r").read().split()
124 self.version = open(".git/WIZARD_UPGRADE_VERSION", "r").read()
126 if e.errno == errno.ENOENT:
127 raise CannotResumeError()
130 def resumeLogging(self):
131 options = self.options
132 if not options.log_file and os.path.exists(".git/WIZARD_LOG_FILE"):
133 options.log_file = open(".git/WIZARD_LOG_FILE", "r").read()
134 command.setup_file_logger(options.log_file, options.debug)
135 def resumeProd(self):
136 """Restore :attr:`prod` attribute, and check if the production copy has drifted."""
137 self.prod = deploy.ProductionCopy(".")
139 shell.call("git", "status")
140 raise LocalChangesError()
141 except shell.CallError:
146 Make sure that a number of pre-upgrade invariants are met before
149 options = self.options
150 self.prod = deploy.ProductionCopy(".")
151 self.repo = self.prod.application.repository(options.srv_path)
152 # XXX: put this in Application
153 self.version = shell.eval("git", "--git-dir="+self.repo, "describe", "--tags", "master")
154 self.preflightBlacklist()
156 self.prod.verifyTag(options.srv_path)
157 self.prod.verifyGit(options.srv_path)
158 self.prod.verifyConfigured()
159 shell.call("git", "fetch", "--tags") # XXX: hack since some installs have stale tags
160 self.prod.verifyVersion()
161 self.prod.verifyWeb()
162 self.preflightAlreadyUpgraded()
163 self.preflightQuota()
164 def preflightBlacklist(self):
165 if os.path.exists(".scripts/blacklisted"):
166 reason = open(".scripts/blacklisted").read()
167 # ignore blank blacklisted files
170 raise BlacklistedError(reason)
172 logging.warning("Application was blacklisted, but no reason was found");
173 def preflightAlreadyUpgraded(self):
174 if self.version == self.prod.app_version.scripts_tag and not self.options.force:
175 # don't log this error; we need to have the traceback line
176 # so that the parsing code can catch it
177 # XXX: maybe we should build this in as a flag to add
178 # to exceptions w/ our exception handler
179 sys.stderr.write("Traceback:\n (n/a)\nAlreadyUpgraded\n")
181 def preflightQuota(self):
182 kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
183 if kib_limit is not None and (kib_limit - kib_usage) < kib_buffer:
187 if not self.options.dry_run:
188 self.mergePreCommit()
190 logging.debug("Temporary WC dir is %s", self.temp_wc_dir)
191 with util.ChangeDirectory(self.temp_wc_dir):
192 self.wc = deploy.WorkingCopy(".")
193 shell.call("git", "remote", "add", "scripts", self.repo)
194 shell.call("git", "fetch", "-q", "scripts")
195 self.user_commit = shell.eval("git", "rev-parse", "HEAD")
196 self.next_commit = shell.eval("git", "rev-parse", self.version)
197 self.mergeSaveState()
199 def mergePreCommit(self):
200 message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
202 message += "\nPre-commit-by: " + util.get_operator_git()
203 except util.NoOperatorInfo:
206 shell.call("git", "commit", "-a", "-m", message)
207 except shell.CallError:
208 logging.info("No changes detected")
209 def mergeClone(self):
210 # If /dev/shm exists, it's a tmpfs and we can use it
211 # to do a fast git merge. Don't forget to move it to
213 if not self.options.dry_run and not self.options.debug:
214 self.use_shm = os.path.exists("/dev/shm")
216 dir = "/dev/shm/wizard"
217 if not os.path.exists(dir):
223 self.temp_dir = tempfile.mkdtemp(prefix="wizard", dir=dir)
224 self.temp_wc_dir = os.path.join(self.temp_dir, "repo")
225 logging.info("Using temporary directory: " + self.temp_wc_dir)
226 shell.call("git", "clone", "-q", "--shared", ".", self.temp_wc_dir)
227 def mergeSaveState(self):
228 """Save variables so that ``--continue`` will work."""
229 # yeah yeah no trailing newline whatever
230 open(".git/WIZARD_UPGRADE_VERSION", "w").write(self.version)
231 open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (self.user_commit, self.next_commit))
232 open(".git/WIZARD_SIZE", "w").write(str(scripts.get_disk_usage()))
233 if self.options.log_file:
234 open(".git/WIZARD_LOG_FILE", "w").write(self.options.log_file)
235 def mergePerform(self):
236 def make_virtual_commit(rev, parents = []):
238 Takes a revision and generates a "virtual" commit with
239 user-specific variables instantiated for a smooth, easy
244 Changes the state of the working copy.
246 shell.call("git", "checkout", "-q", rev, "--")
247 self.wc.parametrize(self.prod)
248 for file in self.wc.application.parametrized_files:
250 shell.call("git", "add", "--", file)
251 except shell.CallError:
253 virtual_tree = shell.eval("git", "write-tree", log=True)
254 parent_args = itertools.chain(*(["-p", p] for p in parents))
255 virtual_commit = shell.eval("git", "commit-tree", virtual_tree,
256 *parent_args, input="", log=True)
257 shell.call("git", "reset", "--hard")
258 return virtual_commit
259 user_tree = shell.eval("git", "rev-parse", "HEAD^{tree}")
260 base_virtual_commit = make_virtual_commit(self.wc.app_version.scripts_tag)
261 next_virtual_commit = make_virtual_commit(self.version, [base_virtual_commit])
262 user_virtual_commit = shell.eval("git", "commit-tree", user_tree,
263 "-p", base_virtual_commit, input="", log=True)
264 shell.call("git", "checkout", user_virtual_commit, "--")
265 self.wc.prepareMerge()
267 shell.call("git", "commit", "--amend", "-a", "-m", "amendment")
268 except shell.CallError as e:
270 shell.call("git", "config", "merge.conflictstyle", "diff3")
272 shell.call("git", "merge", next_virtual_commit)
273 except shell.CallError as e:
274 logging.info("Merge failed with these messages:\n\n" + e.stderr)
275 # Run the application's specific merge resolution algorithms
276 # and see if we can salvage it
277 if self.wc.resolveConflicts():
278 logging.info("Resolved conflicts with application specific knowledge")
279 shell.call("git", "commit", "-a", "-m", "merge")
282 for line in shell.eval("git", "ls-files", "--unmerged").splitlines():
283 files.add(line.split(None, 3)[-1])
284 conflicts = len(files)
285 # XXX: this is kind of fiddly; note that temp_dir still points at the OLD
286 # location after this code.
287 self.temp_wc_dir = mv_shm_to_tmp(os.getcwd(), self.use_shm)
288 self.wc.location = self.temp_wc_dir
289 os.chdir(self.temp_wc_dir)
290 open(os.path.join(self.prod.location, ".scripts/pending"), "w").write(self.temp_wc_dir)
291 if self.options.non_interactive:
292 print "%d %s" % (conflicts, self.temp_wc_dir)
295 user_shell = os.getenv("SHELL")
296 if not user_shell: user_shell = "/bin/bash"
297 # XXX: scripts specific hack, since mbash doesn't respect the current working directory
298 # When the revolution comes (i.e. $ATHENA_HOMEDIR/Scripts is your Scripts home
299 # directory) this isn't strictly necessary, but we'll probably need to support
300 # web_scripts directories ad infinitum.
301 if user_shell == "/usr/local/bin/mbash": user_shell = "/bin/bash"
304 print "ERROR: The merge failed with %d conflicts in these files:" % conflicts
306 for file in sorted(files):
309 print "Please resolve these conflicts (edit and then `git add`), and"
310 print "then type 'exit'. You will now be dropped into a shell whose working"
311 print "directory is %s" % self.temp_wc_dir
313 shell.call(user_shell, "-i", interactive=True)
314 except shell.CallError as e:
315 logging.warning("Shell returned non-zero exit code %d" % e.code)
316 if shell.eval("git", "ls-files", "--unmerged").strip():
318 print "WARNING: There are still unmerged files."
319 out = raw_input("Continue editing? [y/N]: ")
320 if out == "y" or out == "Y":
323 print "Aborting. The conflicted working copy can be found at:"
325 print " %s" % self.temp_wc_dir
327 print "and you can resume the upgrade process by running in that directory:"
329 print " wizard upgrade --continue"
333 def postflight(self):
334 with util.ChangeDirectory(self.temp_wc_dir):
336 shell.call("git", "status")
337 except shell.CallError:
340 shell.call("git", "commit", "--allow-empty", "-am", "throw-away commit")
341 message = self.postflightCommitMessage()
342 new_tree = shell.eval("git", "rev-parse", "HEAD^{tree}")
343 final_commit = shell.eval("git", "commit-tree", new_tree,
344 "-p", self.user_commit, "-p", self.next_commit, input=message, log=True)
345 # a master branch may not necessarily exist if the user
346 # was manually installed to an earlier version
348 shell.call("git", "checkout", "-q", "-b", "master", "--")
349 except shell.CallError:
350 shell.call("git", "checkout", "-q", "master", "--")
351 shell.call("git", "reset", "-q", "--hard", final_commit)
352 # This is a quick sanity check to make sure we didn't completely
354 self.wc.invalidateCache()
355 self.wc.verifyVersion()
356 def postflightCommitMessage(self):
357 message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), self.version, util.get_git_footer())
359 message += "\nUpgraded-by: " + util.get_operator_git()
360 except util.NoOperatorInfo:
365 # Ok, now we have to do a crazy complicated dance to see if we're
366 # going to have enough quota to finish what we need
367 pre_size = int(open(os.path.join(self.temp_wc_dir, ".git/WIZARD_SIZE"), "r").read())
368 post_size = scripts.get_disk_usage(self.temp_wc_dir)
369 backup = self.prod.backup(self.options)
370 kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
371 if kib_limit is not None and (kib_limit - kib_usage) - (post_size - pre_size) / 1024 < kib_buffer:
372 shutil.rmtree(os.path.join(".scripts/backups", shell.eval("wizard", "restore").splitlines()[0]))
376 def upgrade(self, backup):
377 # XXX: frob .htaccess to make site inaccessible
378 with util.IgnoreKeyboardInterrupts():
379 with util.LockDirectory(".scripts-upgrade-lock"):
380 shell.call("git", "fetch", "--tags")
381 # git merge (which performs a fast forward)
382 shell.call("git", "pull", "-q", self.temp_wc_dir, "master")
383 version_obj = distutils.version.LooseVersion(self.version.partition('-')[2])
386 self.prod.upgrade(version_obj, self.options)
387 self.prod.verifyWeb()
388 except app.UpgradeFailure:
389 logging.warning("Upgrade failed: rolling back")
390 self.upgradeRollback(backup)
392 except deploy.WebVerificationError as e:
393 logging.warning("Web verification failed: rolling back")
394 self.upgradeRollback(backup)
395 raise app.UpgradeVerificationFailure()
396 # XXX: frob .htaccess to make site accessible
397 # to do this, check if .htaccess changed, first. Upgrade
398 # process might have frobbed it. Don't be
399 # particularly worried if the segment disappeared
400 def upgradeRollback(self, backup):
401 # You don't want d.restore() because it doesn't perform
402 # the file level backup
403 shell.call("wizard", "restore", backup)
405 self.prod.verifyWeb()
406 except deploy.WebVerificationError:
407 logging.critical("Web verification failed after rollback")
411 def mv_shm_to_tmp(curdir, use_shm):
412 if not use_shm: return curdir
413 # Keeping all of our autoinstalls in shared memory is
414 # a recipe for disaster, so let's move them to slightly
415 # less volatile storage (a temporary directory)
416 os.chdir(tempfile.gettempdir())
417 newdir = tempfile.mkdtemp(prefix="wizard")
418 # shutil, not os; at least on Ubuntu os.move fails
419 # with "[Errno 18] Invalid cross-device link"
420 shutil.move(curdir, newdir)
421 shutil.rmtree(os.path.dirname(curdir))
422 curdir = os.path.join(newdir, "repo")
425 def parse_args(argv, baton):
426 usage = """usage: %prog upgrade [ARGS] [DIR]
428 Upgrades an autoinstall to the latest version. This involves
429 updating files and running .scripts/update. If the merge fails,
430 this program will write the number of conflicts and the directory
431 of the conflicted working tree to stdout, separated by a space."""
432 parser = command.WizardOptionParser(usage)
433 parser.add_option("--dry-run", dest="dry_run", action="store_true",
434 default=False, help="Prints would would be run without changing anything")
435 # notice trailing underscore
436 parser.add_option("--continue", dest="continue_", action="store_true",
437 default=False, help="Continues an upgrade that has had its merge manually "
438 "resolved using the current working directory as the resolved copy.")
439 parser.add_option("--force", dest="force", action="store_true",
440 default=False, help="Force running upgrade even if it's already at latest version.")
441 parser.add_option("--non-interactive", dest="non_interactive", action="store_true",
442 default=False, help="Don't drop to shell in event of conflict.")
443 baton.push(parser, "srv_path")
444 options, args = parser.parse_all(argv)
446 parser.error("too many arguments")
449 class Error(command.Error):
450 """Base exception for all exceptions raised by upgrade"""
453 class QuotaTooLow(Error):
457 ERROR: The locker quota was too low to complete the autoinstall
461 class AlreadyUpgraded(Error):
466 ERROR: This autoinstall is already at the latest version."""
468 class MergeFailed(Error):
473 ERROR: Merge failed. Above is the temporary directory that
474 the conflicted merge is in: resolve the merge by cd'ing to the
475 temporary directory, finding conflicted files with `git status`,
476 resolving the files, adding them using `git add` and then
477 running `wizard upgrade --continue`."""
479 class LocalChangesError(Error):
483 ERROR: Local changes occurred in the install while the merge was
484 being processed so that a pull would not result in a fast-forward.
485 The best way to resolve this is probably to attempt an upgrade again,
486 with git rerere to remember merge resolutions (XXX: not sure if
487 this actually works)."""
489 class BlacklistedError(Error):
490 #: Reason why the autoinstall was blacklisted
492 exitcode = errno_blacklisted
493 def __init__(self, reason):
498 ERROR: This autoinstall was manually blacklisted against errors;
499 if the user has not been notified of this, please send them
502 The reason was: %s""" % self.reason
504 class CannotResumeError(Error):
508 ERROR: We cannot resume the upgrade process; either this working
509 copy is missing essential metadata, or you've attempt to continue
510 from a production copy that does not have any pending upgrades.