]> scripts.mit.edu Git - wizard.git/blobdiff - wizard/command/upgrade.py
Major updates to resolution code from runs.
[wizard.git] / wizard / command / upgrade.py
index ed8c8ce645632a8b9e4ae7efee5dc5489d3df826..f56d00b821e73f90359b4c9443b3c408d93a1f6a 100644 (file)
@@ -8,7 +8,9 @@ import errno
 import tempfile
 import itertools
 
-from wizard import app, command, deploy, shell, util
+from wizard import app, command, deploy, scripts, shell, util
+
+kib_buffer = 1024 * 30 # 30 MiB we will always leave available
 
 def main(argv, baton):
     options, args = parse_args(argv, baton)
@@ -22,11 +24,17 @@ def main(argv, baton):
         raise BlacklistedError()
     sh = shell.Shell()
     util.set_git_env()
+    use_shm = False # if you are running --continue, this is guaranteed to be False
     if options.continue_:
         temp_wc_dir = os.getcwd()
         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.addFileLogger(options.log_file, options.debug)
+        logging.info("Continuing upgrade...")
         util.chdir(sh.eval("git", "config", "remote.origin.url"))
         d = deploy.Deployment(".")
         try:
@@ -46,20 +54,40 @@ def main(argv, baton):
         repo = d.application.repository(options.srv_path)
         version = calculate_newest_version(sh, repo)
         if version == d.app_version.scripts_tag and not options.force:
-            raise AlreadyUpgraded
+            # 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: # 10 mebibytes
+            raise QuotaTooLow
         if not options.dry_run:
             perform_pre_commit(sh)
-        temp_wc_dir = perform_tmp_clone(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.
+        # XXX: git merge-tree is another possibility for
+        # reducing filesystem interactions, and also probably
+        # works better with extra merging functionality.  However,
+        # I don't know how I would put the results back in the
+        # working tree.
+        use_shm = os.path.exists("/dev/shm")
+        temp_dir, temp_wc_dir = perform_tmp_clone(sh, use_shm)
         with util.ChangeDirectory(temp_wc_dir):
             sh.call("git", "remote", "add", "scripts", repo)
-            sh.call("git", "fetch", "scripts")
+            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))
-            perform_merge(sh, repo, d, version)
+            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, 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:
@@ -74,22 +102,38 @@ def main(argv, baton):
         # a master branch may not necessarily exist if the user
         # was manually installed to an earlier version
         try:
-            sh.call("git", "checkout", "-b", "master", "--")
+            sh.call("git", "checkout", "-q", "-b", "master", "--")
         except shell.CallError:
-            sh.call("git", "checkout", "master", "--")
-        sh.call("git", "reset", "--hard", final_commit)
+            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
         d.verifyVersion()
     # 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
-    # perform database backup
+    # 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", temp_wc_dir, "master")
+            sh.call("git", "pull", "-q", temp_wc_dir, "master")
+            # after the pull is successful, the directory now
+            # has the objects for this commit, so we can safely
+            # nuke the shm directory.  We refrain from nuking the
+            # tmp directory in case we messed up the merge resolution
+            # and want to be able to use it again.
+            if use_shm:
+                shutil.rmtree(temp_dir)
             version_obj = distutils.version.LooseVersion(version.partition('-')[2])
             try:
                 # run update script
@@ -101,9 +145,8 @@ def main(argv, baton):
                 raise
             except deploy.WebVerificationError as e:
                 logging.warning("Web verification failed: rolling back")
-                logging.info("Web page that was output was:\n\n%s" % e.contents)
                 perform_restore(d, backup)
-                raise app.UpgradeVerificationFailure("Upgrade caused website to become inaccessible; site was rolled back")
+                raise app.UpgradeVerificationFailure(e.contents)
     # XXX: frob .htaccess to make site accessible
     #       to do this, check if .htaccess changed, first.  Upgrade
     #       process might have frobbed it.  Don't be
@@ -146,20 +189,28 @@ def perform_pre_commit(sh):
     except shell.CallError:
         logging.info("No changes detected")
 
-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, 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", tag, "--")
+        sh.call("git", "checkout", "-q", tag, "--")
         d.parametrize(".")
         for file in d.application.parametrized_files:
             try:
@@ -178,20 +229,44 @@ def perform_merge(sh, repo, d, version):
     user_virtual_commit = sh.eval("git", "commit-tree", user_tree,
             "-p", base_virtual_commit, input="", log=True)
     sh.call("git", "checkout", user_virtual_commit, "--")
+    d.application.prepareMerge(os.getcwd())
+    sh.call("git", "commit", "--amend", "-a", "-m", "amendment")
     try:
         sh.call("git", "merge", next_virtual_commit)
-    except shell.CallError:
-        print os.getcwd()
-        logging.info("Conflict info:\n", sh.eval("git", "diff"))
+    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 d.application.resolveConflicts(curdir):
+            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"))
+        if use_shm:
+            # 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")
+            os.chdir(curdir)
+        print "%d %s" % (conflicts, curdir)
         raise MergeFailed
 
 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.
-
-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")
@@ -211,6 +286,14 @@ class Error(command.Error):
     """Base exception for all exceptions raised by upgrade"""
     pass
 
+class QuotaTooLow(Error):
+    def __str__(self):
+        return """
+
+ERROR: The locker quota was too low to complete the autoinstall
+upgrade.
+"""
+
 class AlreadyUpgraded(Error):
     def __str__(self):
         return """