]> scripts.mit.edu Git - wizard.git/blobdiff - wizard/command/upgrade.py
Reduce duplication in test scripts, more logging.
[wizard.git] / wizard / command / upgrade.py
index 981273cc94ccd1973457580f7f5ea755f15b3406..476c1b78ca3890be9715227ac3bb382dff42adfb 100644 (file)
-import optparse
 import sys
+import distutils.version
 import os
 import shutil
 import logging.handlers
-import errno
 import tempfile
 import itertools
 
-from wizard import command, deploy, shell, util
+from wizard import app, command, deploy, scripts, shell, util
 
-# XXX: need errors for history sanity checking (if the user is on a completely
-# different history tree, we should abort, and manually figure out the
-# appropriate rebase)
+kib_buffer = 1024 * 30 # 30 MiB we will always leave available
+errno_blacklisted = 64
 
 def main(argv, baton):
     options, args = parse_args(argv, baton)
-    command.chdir(args[0])
-    d = make_deployment_from_cwd()
-    repo = d.application.repository(options.srv_path)
-    util.set_git_env()
+    if args:
+        dir = args[0]
+    else:
+        dir = "."
+    shell.drop_priviledges(dir, options.log_file)
+    util.chdir(dir)
     sh = shell.Shell()
-    if not options.dry_run:
-        perform_pre_commit(sh)
-    temp_wc_dir = perform_tmp_clone(sh)
-    with util.ChangeDirectory(temp_wc_dir):
+    util.set_git_env()
+    use_shm = False # if you are running --continue, this is guaranteed to be False
+    temp_dir = None
+    try: # global try-finally for cleaning up /dev/shm if it's being used
+        if options.continue_:
+            temp_wc_dir = os.getcwd()
+            wc = deploy.WorkingCopy(".")
+            user_commit, next_commit = open(".git/WIZARD_PARENTS", "r").read().split()
+            repo = open(".git/WIZARD_REPO", "r").read()
+            version = open(".git/WIZARD_UPGRADE_VERSION", "r").read()
+            if not options.log_file and os.path.exists(".git/WIZARD_LOG_FILE"):
+                options.log_file = open(".git/WIZARD_LOG_FILE", "r").read()
+                # reload logging
+                command.setup_file_logger(options.log_file, options.debug)
+            logging.info("Continuing upgrade...")
+            util.chdir(sh.eval("git", "config", "remote.origin.url"))
+            d = deploy.ProductionCopy(".")
+            try:
+                sh.call("git", "status")
+                raise LocalChangesError()
+            except shell.CallError:
+                pass
+        else:
+            d = deploy.ProductionCopy(".")
+            if os.path.exists(".scripts/blacklisted"):
+                reason = open(".scripts/blacklisted").read()
+                # ignore blank blacklisted files
+                if reason:
+                    print reason
+                    raise BlacklistedError(reason)
+                else:
+                    logging.warning("Application was blacklisted, but no reason was found");
+            d.verify()
+            d.verifyTag(options.srv_path)
+            d.verifyGit(options.srv_path)
+            d.verifyConfigured()
+            d.verifyVersion()
+            if not options.dry_run:
+                d.verifyWeb()
+            repo = d.application.repository(options.srv_path)
+            version = calculate_newest_version(sh, repo)
+            if version == d.app_version.scripts_tag and not options.force:
+                # don't log this error
+                # XXX: maybe we should build this in as a flag to add
+                # to exceptions w/ our exception handler
+                sys.stderr.write("Traceback:\n  (n/a)\nAlreadyUpgraded\n")
+                sys.exit(1)
+            logging.info("Upgrading %s" % os.getcwd())
+            kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
+            if kib_limit is not None and (kib_limit - kib_usage) < kib_buffer:
+                raise QuotaTooLow
+            if not options.dry_run:
+                perform_pre_commit(sh)
+            # If /dev/shm exists, it's a tmpfs and we can use it
+            # to do a fast git merge. Don't forget to move it to
+            # /tmp if it fails.
+            if not options.dry_run:
+                use_shm = os.path.exists("/dev/shm")
+            temp_dir, temp_wc_dir = perform_tmp_clone(sh, use_shm)
+            with util.ChangeDirectory(temp_wc_dir):
+                wc = deploy.WorkingCopy(".")
+                sh.call("git", "remote", "add", "scripts", repo)
+                sh.call("git", "fetch", "-q", "scripts")
+                user_commit, next_commit = calculate_parents(sh, version)
+                # save variables so that --continue will work
+                # yeah yeah no trailing newline whatever
+                open(".git/WIZARD_REPO", "w").write(repo)
+                open(".git/WIZARD_UPGRADE_VERSION", "w").write(version)
+                open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (user_commit, next_commit))
+                open(".git/WIZARD_SIZE", "w").write(str(scripts.get_disk_usage()))
+                if options.log_file:
+                    open(".git/WIZARD_LOG_FILE", "w").write(options.log_file)
+                perform_merge(sh, repo, d, wc, version, use_shm, kib_limit and kib_limit - kib_usage or None)
+        # variables: version, user_commit, next_commit, temp_wc_dir
+        with util.ChangeDirectory(temp_wc_dir):
+            try:
+                sh.call("git", "status")
+                sh.call("git", "commit", "-m", "throw-away commit")
+            except shell.CallError:
+                pass
+            message = make_commit_message(version)
+            new_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
+            final_commit = sh.eval("git", "commit-tree", new_tree,
+                    "-p", user_commit, "-p", next_commit, input=message, log=True)
+            # a master branch may not necessarily exist if the user
+            # was manually installed to an earlier version
+            try:
+                sh.call("git", "checkout", "-q", "-b", "master", "--")
+            except shell.CallError:
+                sh.call("git", "checkout", "-q", "master", "--")
+            sh.call("git", "reset", "-q", "--hard", final_commit)
+            # This is a quick sanity check to make sure we didn't completely
+            # mess up the merge
+            wc.invalidateCache()
+            wc.verifyVersion()
+        # Till now, all of our operations were in a tmp sandbox.
         if options.dry_run:
-            # we delayed performing the pre upgrade commit
-            # until we're in the temporary directory
-            perform_pre_commit(sh)
-        sh.call("git", "remote", "add", "scripts", repo)
-        sh.call("git", "fetch", "scripts")
-        version = sh.eval("git", "--git-dir="+repo, "describe", "--tags", "master")
-        user_commit = sh.eval("git", "rev-parse", "HEAD")
-        next_commit = sh.eval("git", "rev-parse", version)
-        perform_merge(sh, repo, d, version)
-        # Make it possible to resume here
-        new_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
-        message = make_commit_message(version)
-        final_commit = sh.eval("git", "commit-tree", new_tree, "-p", user_commit, "-p", next_commit, input=message)
-        try:
-            sh.call("git", "checkout", "-b", "master", "--")
-        except shell.CallError:
-            sh.call("git", "checkout", "master", "--")
-        sh.call("git", "reset", "--hard", final_commit)
-    # Till now, all of our operations were in a tmp sandbox.
-    if options.dry_run:
-        logging.info("Dry run, bailing.  See results at %s" % temp_wc_dir)
-        return
-    # XXX: frob .htaccess to make site inaccessible
-    # git merge (which performs a fast forward)
-    #   - merge could fail (race); that's /really/ dangerous.
-    sh.call("git", "pull", temp_wc_dir, "master")
-    # run update script
-    sh.call(".scripts/update")
-    # XXX: frob .htaccess to make site accessible
-    # XXX:  - check if .htaccess changed, first.  Upgrade
-    #       process might have frobbed it.  Don't be
-    #       particularly worried if the segment dissappeared
-
-def make_deployment_from_cwd():
-    if not os.path.isdir(".git"):
-        raise NotAutoinstallError()
+            logging.info("Dry run, bailing.  See results at %s" % temp_wc_dir)
+            return
+        # Ok, now we have to do a crazy complicated dance to see if we're
+        # going to have enough quota to finish what we need
+        pre_size = int(open(os.path.join(temp_wc_dir, ".git/WIZARD_SIZE"), "r").read())
+        post_size = scripts.get_disk_usage(temp_wc_dir)
+        kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
+        backup = d.backup(options)
+        if kib_limit is not None and (kib_limit - kib_usage) - (post_size - pre_size) / 1024 < kib_buffer:
+            shutil.rmtree(os.path.join(".scripts/backups", sh.eval("wizard", "restore").splitlines()[0]))
+            raise QuotaTooLow
+        # XXX: frob .htaccess to make site inaccessible
+        with util.IgnoreKeyboardInterrupts():
+            with util.LockDirectory(".scripts-upgrade-lock"):
+                # git merge (which performs a fast forward)
+                sh.call("git", "pull", "-q", temp_wc_dir, "master")
+                version_obj = distutils.version.LooseVersion(version.partition('-')[2])
+                try:
+                    # run update script
+                    d.upgrade(version_obj, options)
+                    d.verifyWeb()
+                except app.UpgradeFailure:
+                    logging.warning("Upgrade failed: rolling back")
+                    perform_restore(d, backup)
+                    raise
+                except deploy.WebVerificationError as e:
+                    logging.warning("Web verification failed: rolling back")
+                    perform_restore(d, backup)
+                    raise app.UpgradeVerificationFailure()
+        # XXX: frob .htaccess to make site accessible
+        #       to do this, check if .htaccess changed, first.  Upgrade
+        #       process might have frobbed it.  Don't be
+        #       particularly worried if the segment disappeared
+    finally:
+        if use_shm and temp_dir and os.path.exists(temp_dir):
+            shutil.rmtree(temp_dir)
+
+def perform_restore(d, backup):
+    # You don't want d.restore() because it doesn't perform
+    # the file level backup
+    shell.Shell().call("wizard", "restore", backup)
     try:
-        d = deploy.Deployment(".")
-    except IOError as e:
-        if e.errno == errno.ENOENT:
-            raise NotAutoinstallError()
-        else: raise e
-    return d
+        d.verifyWeb()
+    except deploy.WebVerificationError:
+        logging.critical("Web verification failed after rollback")
 
 def make_commit_message(version):
     message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), version, util.get_git_footer())
@@ -75,90 +169,175 @@ def make_commit_message(version):
         message += "\nUpgraded-by: " + util.get_operator_git()
     except util.NoOperatorInfo:
         pass
+    return message
+
+def calculate_newest_version(sh, repo):
+    # XXX: put this in Application
+    return sh.eval("git", "--git-dir="+repo, "describe", "--tags", "master")
+
+def calculate_parents(sh, version):
+    user_commit = sh.eval("git", "rev-parse", "HEAD")
+    next_commit = sh.eval("git", "rev-parse", version)
+    return user_commit, next_commit
 
 def perform_pre_commit(sh):
+    message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
+    try:
+        message += "\nPre-commit-by: " + util.get_operator_git()
+    except util.NoOperatorInfo:
+        pass
     try:
-        message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
-        try:
-            message += "\nPre-commit-by: " + util.get_operator_git()
-        except util.NoOperatorInfo:
-            pass
         sh.call("git", "commit", "-a", "-m", message)
     except shell.CallError:
         logging.info("No changes detected")
-        pass
 
-def perform_tmp_clone(sh):
-    temp_dir = tempfile.mkdtemp(prefix="wizard")
+def perform_tmp_clone(sh, use_shm):
+    if use_shm:
+        dir = "/dev/shm/wizard"
+        if not os.path.exists(dir):
+            os.mkdir(dir)
+            os.chmod(dir, 0o777)
+    else:
+        dir = None
+    temp_dir = tempfile.mkdtemp(prefix="wizard", dir=dir)
     temp_wc_dir = os.path.join(temp_dir, "repo")
     logging.info("Using temporary directory: " + temp_wc_dir)
-    sh.call("git", "clone", "--shared", ".", temp_wc_dir)
-    return temp_wc_dir
+    sh.call("git", "clone", "-q", "--shared", ".", temp_wc_dir)
+    return temp_dir, temp_wc_dir
 
-def perform_merge(sh, repo, d, version):
+def perform_merge(sh, repo, d, wc, version, use_shm, kib_avail):
+    # Note: avail_quota == None means unlimited
+    # naive merge algorithm:
+    # sh.call("git", "merge", "-m", message, "scripts/master")
+    # crazy merge algorithm:
+    def make_virtual_commit(tag, parents = []):
+        """WARNING: Changes state of Git repository"""
+        sh.call("git", "checkout", "-q", tag, "--")
+        wc.parametrize(d)
+        for file in wc.application.parametrized_files:
+            try:
+                sh.call("git", "add", "--", file)
+            except shell.CallError:
+                pass
+        virtual_tree = sh.eval("git", "write-tree", log=True)
+        parent_args = itertools.chain(*(["-p", p] for p in parents))
+        virtual_commit = sh.eval("git", "commit-tree", virtual_tree,
+                *parent_args, input="", log=True)
+        sh.call("git", "reset", "--hard")
+        return virtual_commit
+    user_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
+    base_virtual_commit = make_virtual_commit(wc.app_version.scripts_tag)
+    next_virtual_commit = make_virtual_commit(version, [base_virtual_commit])
+    user_virtual_commit = sh.eval("git", "commit-tree", user_tree,
+            "-p", base_virtual_commit, input="", log=True)
+    sh.call("git", "checkout", user_virtual_commit, "--")
+    wc.prepareMerge()
+    try:
+        sh.call("git", "commit", "--amend", "-a", "-m", "amendment")
+    except shell.CallError as e:
+        pass
     try:
-        # naive merge algorithm:
-        # sh.call("git", "merge", "-m", message, "scripts/master")
-        # crazy merge algorithm:
-        def make_virtual_commit(tag, parents = []):
-            """WARNING: Changes state of Git repository"""
-            sh.call("git", "checkout", tag, "--")
-            d.parametrize(".")
-            for file in d.application.parametrized_files:
-                try:
-                    sh.call("git", "add", "--", file)
-                except shell.CallError:
-                    pass
-            virtual_tree = sh.eval("git", "write-tree")
-            parent_args = itertools.chain(*(["-p", p] for p in parents))
-            virtual_commit = sh.eval("git", "commit-tree", virtual_tree, *parent_args, input="")
-            sh.call("git", "reset", "--hard")
-            return virtual_commit
-        user_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
-        base_virtual_commit = make_virtual_commit(d.app_version.pristine_tag)
-        next_virtual_commit = make_virtual_commit(version, [base_virtual_commit])
-        user_virtual_commit = sh.eval("git", "commit-tree", user_tree, "-p", base_virtual_commit, input="")
-        sh.call("git", "checkout", user_virtual_commit, "--")
         sh.call("git", "merge", next_virtual_commit)
-    except shell.CallError:
-        print os.getcwd()
+    except shell.CallError as e:
+        conflicts = e.stdout.count("CONFLICT") # not perfect, if there is a file named CONFLICT
+        logging.info("Merge failed with these messages:\n\n" + e.stderr)
+        # Run the application's specific merge resolution algorithms
+        # and see if we can salvage it
+        curdir = os.getcwd()
+        if wc.resolveConflicts():
+            logging.info("Resolved conflicts with application specific knowledge")
+            sh.call("git", "commit", "-a", "-m", "merge")
+            return
+        # XXX: Maybe should recalculate conflicts
+        logging.info("Conflict info:\n" + sh.eval("git", "diff"))
+        curdir = mv_shm_to_tmp(curdir, use_shm)
+        print "%d %s" % (conflicts, curdir)
         raise MergeFailed
 
+def mv_shm_to_tmp(curdir, use_shm):
+    if not use_shm: return curdir
+    # Keeping all of our autoinstalls in shared memory is
+    # a recipe for disaster, so let's move them to slightly
+    # less volatile storage (a temporary directory)
+    os.chdir(tempfile.gettempdir())
+    newdir = tempfile.mkdtemp(prefix="wizard")
+    # shutil, not os; at least on Ubuntu os.move fails
+    # with "[Errno 18] Invalid cross-device link"
+    shutil.move(curdir, newdir)
+    shutil.rmtree(os.path.dirname(curdir))
+    curdir = os.path.join(newdir, "repo")
+    return curdir
+
 def parse_args(argv, baton):
-    usage = """usage: %prog upgrade [ARGS] DIR
+    usage = """usage: %prog upgrade [ARGS] [DIR]
 
 Upgrades an autoinstall to the latest version.  This involves
-updating files and running .scripts/update.
-
-WARNING: This is still experimental."""
+updating files and running .scripts/update.  If the merge fails,
+this program will write the number of conflicts and the directory
+of the conflicted working tree to stdout, separated by a space."""
     parser = command.WizardOptionParser(usage)
     parser.add_option("--dry-run", dest="dry_run", action="store_true",
             default=False, help="Prints would would be run without changing anything")
+    # notice trailing underscore
+    parser.add_option("--continue", dest="continue_", action="store_true",
+            default=False, help="Continues an upgrade that has had its merge manually "
+            "resolved using the current working directory as the resolved copy.")
+    parser.add_option("--force", dest="force", action="store_true",
+            default=False, help="Force running upgrade even if it's already at latest version.")
     baton.push(parser, "srv_path")
     options, args = parser.parse_all(argv)
     if len(args) > 1:
         parser.error("too many arguments")
-    elif not args:
-        parser.error("must specify directory")
     return options, args
 
 class Error(command.Error):
     """Base exception for all exceptions raised by upgrade"""
     pass
 
-class NotAutoinstallError(Error):
+class QuotaTooLow(Error):
     def __str__(self):
         return """
 
-ERROR: Could not find .git file. Are you sure
-this is an autoinstalled application? Did you remember
-to migrate it?
+ERROR: The locker quota was too low to complete the autoinstall
+upgrade.
 """
 
+class AlreadyUpgraded(Error):
+    def __str__(self):
+        return """
+
+ERROR: This autoinstall is already at the latest version."""
+
 class MergeFailed(Error):
     def __str__(self):
         return """
 
-ERROR: Merge failed.  Change directory to the temporary
-directory and manually resolve the merge.
-"""
+ERROR: Merge failed.  Resolve the merge by cd'ing to the
+temporary directory, finding conflicted files with `git status`,
+resolving the files, adding them using `git add` and then
+running `wizard upgrade --continue`."""
+
+class LocalChangesError(Error):
+    def __str__(self):
+        return """
+
+ERROR: Local changes occurred in the install while the merge was
+being processed so that a pull would not result in a fast-forward.
+The best way to resolve this is probably to attempt an upgrade again,
+with git rerere to remember merge resolutions (XXX: not sure if
+this actually works)."""
+
+class BlacklistedError(Error):
+    #: Reason why the autoinstall was blacklisted
+    reason = None
+    exitcode = errno_blacklisted
+    def __init__(self, reason):
+        self.reason = reason
+    def __str__(self):
+        return """
+
+ERROR: This autoinstall was manually blacklisted against errors;
+if the user has not been notified of this, please send them
+mail.
+
+The reason was: %s""" % self.reason