]> scripts.mit.edu Git - wizard.git/blobdiff - wizard/command/upgrade.py
Change to production directory before running certain commands.
[wizard.git] / wizard / command / upgrade.py
index aae43eee3fc309ff8b1335a03b444e2d48941360..e31e7b935b9402ef51c01a673cc0b39171154b12 100644 (file)
@@ -1,6 +1,7 @@
 import sys
 import distutils.version
 import os
+import os.path
 import shutil
 import logging.handlers
 import tempfile
@@ -8,17 +9,15 @@ import itertools
 import time
 import errno
 
-from wizard import app, command, deploy, merge, scripts, shell, util
+from wizard import app, command, deploy, merge, shell, user, util
 
-kib_buffer = 1024 * 30 # 30 MiB we will always leave available
+buffer = 1024 * 1024 * 30 # 30 MiB we will always leave available
 errno_blacklisted = 64
 
 def main(argv, baton):
     options, args = parse_args(argv, baton)
-    if args:
-        dir = args[0]
-    else:
-        dir = "."
+    dir = os.path.abspath(args[0]) if args else os.getcwd()
+    os.chdir(dir)
     shell.drop_priviledges(dir, options.log_file)
     util.set_git_env()
     upgrade = Upgrade(options)
@@ -38,7 +37,7 @@ class Upgrade(object):
     version = None # XXX: This is a string... I'm not convinced it should be
     #: String commit ID of the user's latest wc; i.e. "ours"
     user_commit = None
-    #: String commit ID of the latest, greatest scripts version; i.e. "theirs"
+    #: String commit ID of the latest, greatest wizard version; i.e. "theirs"
     next_commit = None
     #: The temporary directory that the system gave us; may stay as ``None``
     #: if we don't ever make ourselves a temporary directory (e.g. ``--continue``).
@@ -75,27 +74,31 @@ class Upgrade(object):
 
     def execute(self, dir):
         """
-        Executes an upgrade.  This is the entry-point.
+        Executes an upgrade.  This is the entry-point.  This expects
+        that it's current working directory is the same as ``dir``.
         """
-        with util.ChangeDirectory(dir):
-            try:
-                if self.options.continue_:
-                    logging.info("Continuing upgrade...")
-                    self.resume()
-                else:
-                    logging.info("Upgrading %s" % os.getcwd())
-                    self.preflight()
-                    self.merge()
-                self.postflight()
-                # Till now, all of our operations were in a tmp sandbox.
-                if self.options.dry_run:
-                    logging.info("Dry run, bailing.  See results at %s" % self.temp_wc_dir)
-                    return
-                backup = self.backup()
-                self.upgrade(backup)
-            finally:
-                if self.use_shm and self.temp_dir and os.path.exists(self.temp_dir):
-                    shutil.rmtree(self.temp_dir)
+        assert os.path.abspath(dir) == os.getcwd()
+        try:
+            if self.options.continue_:
+                logging.info("Continuing upgrade...")
+                self.resume()
+            else:
+                logging.info("Upgrading %s" % os.getcwd())
+                self.preflight()
+                self.merge()
+            self.postflight()
+            # Till now, all of our operations were in a tmp sandbox.
+            if self.options.dry_run:
+                logging.info("Dry run, bailing.  See results at %s" % self.temp_wc_dir)
+                return
+            backup = self.backup()
+            self.upgrade(backup)
+            # Note: disable_rollback assumes that upgrade is the last
+            # step, if you add another setp you may have to modify this
+            # to accomodate that.
+        finally:
+            if self.use_shm and self.temp_dir and os.path.exists(self.temp_dir):
+                shutil.rmtree(self.temp_dir)
 
     def resume(self):
         """
@@ -110,12 +113,9 @@ class Upgrade(object):
     def resumeChdir(self):
         """
         If we called ``--continue`` inside a production copy,  check if
-        :file:`.scripts/pending` exists and change to that directory if so.
+        :file:`.wizard/pending` exists and change to that directory if so.
         """
-        if os.path.exists(".scripts/pending"):
-            newdir = open(".scripts/pending").read().strip()
-            logging.warning("Detected production copy; changing directory to %s", newdir)
-            os.chdir(newdir)
+        util.chdir_to_production()
     def resumeState(self):
         self.temp_wc_dir = os.getcwd()
         self.wc = deploy.WorkingCopy(".")
@@ -136,8 +136,13 @@ class Upgrade(object):
         """Restore :attr:`prod` attribute, and check if the production copy has drifted."""
         self.prod = deploy.ProductionCopy(".")
         try:
-            shell.call("git", "status")
-            raise LocalChangesError()
+            # simulate the action of `git status`, based on cmd_status()'s call to
+            # refresh_cache() in builtin-commit.c
+            shell.call("git", "update-index", "-q", "--unmerged", "--refresh")
+            r1 = shell.eval("git", "diff-files", "--name-only").strip()
+            r2 = shell.eval("git", "diff-index", "--name-only", "HEAD").strip()
+            if r1 or r2:
+                raise LocalChangesError()
         except shell.CallError:
             pass
         # Working copy is not anchored anywhere useful for git describe,
@@ -150,23 +155,49 @@ class Upgrade(object):
         attempting anything.
         """
         options = self.options
-        self.prod = deploy.ProductionCopy(".")
-        self.repo = self.prod.application.repository(options.srv_path)
-        # XXX: put this in Application
-        self.version = shell.eval("git", "--git-dir="+self.repo, "describe", "--tags", "master")
-        self.preflightBlacklist()
-        self.prod.verify()
-        self.prod.verifyTag(options.srv_path)
-        self.prod.verifyGit(options.srv_path)
-        self.prod.verifyConfigured()
-        shell.call("git", "fetch", "--tags") # XXX: hack since some installs have stale tags
-        self.prod.verifyVersion()
-        self.prod.verifyWeb()
+        for i in range(0,2):
+            self.prod = deploy.ProductionCopy(".")
+            self.prod.verify()
+            self.repo = self.prod.application.repository(options.srv_path)
+            # XXX: put this in Application
+            self.version = shell.eval("git", "--git-dir="+self.repo, "describe", "--tags", "master")
+            self.preflightBlacklist()
+            self.prod.verify()
+            self.prod.verifyDatabase()
+            self.prod.verifyTag(options.srv_path)
+            self.prod.verifyGit(options.srv_path)
+            if not options.skip_verification:
+                self.prod.verifyConfigured()
+            try:
+                shell.call("git", "fetch", "--tags") # XXX: hack since some installs have stale tags
+            except shell.CallError as e:
+                if "Disk quota exceeded" in e.stderr:
+                    raise QuotaTooLow
+                raise
+            try:
+                self.prod.verifyVersion()
+            except deploy.VersionMismatchError as e:
+                # XXX: kind of hacky, mainly it does change the Git working copy
+                # state (although /very/ non-destructively)
+                try:
+                    shell.call("git", "merge", "--strategy=ours", self.prod.application.makeVersion(str(e.real_version)).wizard_tag)
+                except shell.CallError as e2:
+                    if "does not point to a commit" in e2.stderr:
+                        raise UnknownVersionError(e.real_version)
+                    else:
+                        raise
+                continue
+            break
+        else:
+            raise VersionRematchFailed
+        if not options.skip_verification:
+            self.prod.verifyWeb()
         self.preflightAlreadyUpgraded()
         self.preflightQuota()
     def preflightBlacklist(self):
-        if os.path.exists(".scripts/blacklisted"):
-            reason = open(".scripts/blacklisted").read()
+        # XXX: should use deploy info
+        if os.path.exists(".wizard/blacklisted"):
+            reason = open(".wizard/blacklisted").read()
             # ignore blank blacklisted files
             if reason:
                 print reason
@@ -174,7 +205,7 @@ class Upgrade(object):
             else:
                 logging.warning("Application was blacklisted, but no reason was found");
     def preflightAlreadyUpgraded(self):
-        if self.version == self.prod.app_version.scripts_tag and not self.options.force:
+        if self.version == self.prod.app_version.wizard_tag and not self.options.force:
             # don't log this error; we need to have the traceback line
             # so that the parsing code can catch it
             # XXX: maybe we should build this in as a flag to add
@@ -182,9 +213,12 @@ class Upgrade(object):
             sys.stderr.write("Traceback:\n  (n/a)\nAlreadyUpgraded\n")
             sys.exit(2)
     def preflightQuota(self):
-        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
+        r = user.quota()
+        if r is not None:
+            usage, limit = r
+            if limit is not None and (limit - usage) < buffer:
+                logging.info("preflightQuota: limit = %d, usage = %d, buffer = %d", limit, usage, buffer)
+                raise QuotaTooLow
 
     def merge(self):
         if not self.options.dry_run:
@@ -193,21 +227,35 @@ class Upgrade(object):
         logging.debug("Temporary WC dir is %s", self.temp_wc_dir)
         with util.ChangeDirectory(self.temp_wc_dir):
             self.wc = deploy.WorkingCopy(".")
-            shell.call("git", "remote", "add", "scripts", self.repo)
-            shell.call("git", "fetch", "-q", "scripts")
+            shell.call("git", "remote", "add", "wizard", self.repo)
+            shell.call("git", "fetch", "-q", "wizard")
             self.user_commit = shell.eval("git", "rev-parse", "HEAD")
             self.next_commit = shell.eval("git", "rev-parse", self.version)
             self.mergeSaveState()
             self.mergePerform()
     def mergePreCommit(self):
-        message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
+        def get_file_set(rev):
+            return set(shell.eval("git", "ls-tree", "-r", "--name-only", rev).split("\n"))
+        # add all files that are unversioned but would be replaced by the pull,
+        # and generate a new commit
+        old_files = get_file_set("HEAD")
+        new_files = get_file_set(self.version)
+        added_files = new_files - old_files
+        for f in added_files:
+            if os.path.lexists(f): # broken symbolic links count too!
+                shell.call("git", "add", f)
+        message = "Pre-commit before autoinstall upgrade.\n\n%s" % util.get_git_footer()
         try:
             message += "\nPre-commit-by: " + util.get_operator_git()
         except util.NoOperatorInfo:
             pass
         try:
             shell.call("git", "commit", "-a", "-m", message)
-        except shell.CallError:
+        except shell.CallError as e:
+            if "Permission denied" in e.stderr:
+                raise util.PermissionsError
+            elif e.stderr:
+                raise
             logging.info("No changes detected")
     def mergeClone(self):
         # If /dev/shm exists, it's a tmpfs and we can use it
@@ -232,7 +280,7 @@ class Upgrade(object):
         # yeah yeah no trailing newline whatever
         open(".git/WIZARD_UPGRADE_VERSION", "w").write(self.version)
         open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (self.user_commit, self.next_commit))
-        open(".git/WIZARD_SIZE", "w").write(str(scripts.get_disk_usage()))
+        open(".git/WIZARD_SIZE", "w").write(str(util.disk_usage()))
         if self.options.log_file:
             open(".git/WIZARD_LOG_FILE", "w").write(self.options.log_file)
     def mergePerform(self):
@@ -250,7 +298,7 @@ class Upgrade(object):
         os.symlink(self.options.rr_cache, os.path.join(self.wc.location, ".git", "rr-cache"))
         shell.call("git", "config", "rerere.enabled", "true")
         try:
-            merge.merge(self.wc.app_version.scripts_tag, self.version,
+            merge.merge(self.wc.app_version.wizard_tag, self.version,
                         prepare_config, resolve_conflicts)
         except merge.MergeError:
             self.mergeFail()
@@ -264,7 +312,7 @@ class Upgrade(object):
         self.temp_wc_dir = mv_shm_to_tmp(os.getcwd(), self.use_shm)
         self.wc.location = self.temp_wc_dir
         os.chdir(self.temp_wc_dir)
-        open(os.path.join(self.prod.location, ".scripts/pending"), "w").write(self.temp_wc_dir)
+        open(self.prod.pending_file, "w").write(self.temp_wc_dir)
         if self.options.non_interactive:
             print "%d %s" % (conflicts, self.temp_wc_dir)
             raise MergeFailed
@@ -309,12 +357,9 @@ class Upgrade(object):
 
     def postflight(self):
         with util.ChangeDirectory(self.temp_wc_dir):
-            try:
-                shell.call("git", "status")
-            except shell.CallError:
-                pass
-            else:
-                shell.call("git", "commit", "--allow-empty", "-am", "throw-away commit")
+            if shell.eval("git", "ls-files", "-u").strip():
+                raise UnmergedChangesError
+            shell.call("git", "commit", "--allow-empty", "-am", "throw-away commit")
             self.wc.parametrize(self.prod)
             shell.call("git", "add", ".")
             message = self.postflightCommitMessage()
@@ -333,7 +378,7 @@ class Upgrade(object):
             self.wc.invalidateCache()
             self.wc.verifyVersion()
     def postflightCommitMessage(self):
-        message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), self.version, util.get_git_footer())
+        message = "Upgraded autoinstall to %s.\n\n%s" % (self.version, util.get_git_footer())
         try:
             message += "\nUpgraded-by: " + util.get_operator_git()
         except util.NoOperatorInfo:
@@ -344,18 +389,21 @@ class Upgrade(object):
         # 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(self.temp_wc_dir, ".git/WIZARD_SIZE"), "r").read())
-        post_size = scripts.get_disk_usage(self.temp_wc_dir)
+        post_size = util.disk_usage(self.temp_wc_dir)
         backup = self.prod.backup(self.options)
-        kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
-        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", shell.eval("wizard", "restore").splitlines()[0]))
-            raise QuotaTooLow
+        r = user.quota()
+        if r is not None:
+            usage, limit = r
+            if limit is not None and (limit - usage) - (post_size - pre_size) < buffer:
+                shutil.rmtree(os.path.join(self.prod.backup_dir, shell.eval("wizard", "restore").splitlines()[0]))
+                raise QuotaTooLow
         return backup
 
     def upgrade(self, backup):
         # XXX: frob .htaccess to make site inaccessible
+        # XXX: frob Git to disallow Git operations after the pull
         with util.IgnoreKeyboardInterrupts():
-            with util.LockDirectory(".scripts-upgrade-lock"):
+            with util.LockDirectory(".wizard-upgrade-lock"):
                 shell.call("git", "fetch", "--tags")
                 # git merge (which performs a fast forward)
                 shell.call("git", "pull", "-q", self.temp_wc_dir, "master")
@@ -379,11 +427,14 @@ class Upgrade(object):
     def upgradeRollback(self, backup):
         # You don't want d.restore() because it doesn't perform
         # the file level backup
-        shell.call("wizard", "restore", backup)
-        try:
-            self.prod.verifyWeb()
-        except deploy.WebVerificationError:
-            logging.critical("Web verification failed after rollback")
+        if not self.options.disable_rollback:
+            shell.call("wizard", "restore", backup)
+            try:
+                self.prod.verifyWeb()
+            except deploy.WebVerificationError:
+                logging.critical("Web verification failed after rollback")
+        else:
+            logging.warning("Rollback was disabled; you can rollback with `wizard restore %s`", backup)
 
 # utility functions
 
@@ -404,9 +455,9 @@ def mv_shm_to_tmp(curdir, use_shm):
 def parse_args(argv, baton):
     usage = """usage: %prog upgrade [ARGS] [DIR]
 
-Upgrades an autoinstall to the latest version.  This involves
-updating files and running .scripts/update.  If the merge fails,
-this program will write the number of conflicts and the directory
+Upgrades an autoinstall to the latest version.  This involves updating
+files the upgrade script associated with this application.  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",
@@ -417,11 +468,16 @@ of the conflicted working tree to stdout, separated by a space."""
             "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.")
+    parser.add_option("--skip-verification", dest="skip_verification", action="store_true",
+            default=False, help="Skip running configuration and web verification checks.")
     parser.add_option("--non-interactive", dest="non_interactive", action="store_true",
             default=False, help="Don't drop to shell in event of conflict.")
     parser.add_option("--rr-cache", dest="rr_cache", metavar="PATH",
             default=None, help="Use this folder to reuse recorded merge resolutions.  Defaults to"
             "your production copy's rr-cache, if it exists.")
+    parser.add_option("--disable-rollback", dest="disable_rollback", action="store_true",
+            default=util.boolish(os.getenv("WIZARD_DISABLE_ROLLBACK")),
+            help="Skips rollback in the event of a failed upgrade. Envvar is WIZARD_DISABLE_ROLLBACK.")
     baton.push(parser, "srv_path")
     options, args = parser.parse_all(argv)
     if len(args) > 1:
@@ -468,6 +524,14 @@ 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 UnmergedChangesError(Error):
+    def __str__(self):
+        return """
+
+ERROR: You attempted to continue an upgrade, but there were
+still local unmerged changes in your working copy.  Please resolve
+them all and try again."""
+
 class BlacklistedError(Error):
     #: Reason why the autoinstall was blacklisted
     reason = None
@@ -491,3 +555,22 @@ ERROR: We cannot resume the upgrade process; either this working
 copy is missing essential metadata, or you've attempt to continue
 from a production copy that does not have any pending upgrades.
 """
+
+class VersionRematchFailed(Error):
+    def __str__(self):
+        return """
+
+ERROR: Your Git version information was not consistent with your
+files on the system, and we were unable to create a fake merge
+to make the two consistent."""
+
+class UnknownVersionError(Error):
+    #: Version that we didn't have
+    version = None
+    def __init__(self, version):
+        self.version = version
+    def __str__(self):
+        return """
+
+ERROR: The version you are attempting to upgrade from (%s)
+is unknown to the repository Wizard is using.""" % str(self.version)