import optparse
import sys
+import distutils.version
import os
import shutil
import logging.handlers
import tempfile
import itertools
-from wizard import command, deploy, shell, util
+from wizard import app, command, deploy, shell, util
def main(argv, baton):
options, args = parse_args(argv, baton)
if args:
- util.chdir(args[0])
+ dir = args[0]
+ else:
+ dir = "."
+ shell.drop_priviledges(dir, options.log_file)
+ util.chdir(dir)
+ if os.path.exists(".scripts/blacklisted"):
+ 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()
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:
- raise AlreadyUpgraded
+ 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())
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)
+ perform_merge(sh, repo, d, version, use_shm)
# 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,
# 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
+ backup = d.backup(options)
# XXX: frob .htaccess to make site inaccessible
- # XXX: need locking
- # 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
- d.application.upgrade(options)
+ 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")
+ # 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
+ 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")
+ 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")
# XXX: frob .htaccess to make site accessible
- # XXX: - check if .htaccess changed, first. Upgrade
+ # to do this, check if .htaccess changed, first. Upgrade
# process might have frobbed it. Don't be
- # particularly worried if the segment dissappeared
+ # particularly worried if the segment disappeared
+
+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.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())
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)
+ 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):
# 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:
try:
sh.call("git", "merge", next_virtual_commit)
except shell.CallError:
- print os.getcwd()
+ # 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
+ 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")
+ print curdir
raise MergeFailed
def parse_args(argv, baton):
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:
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
-committing your changes with `git commit` (your log message
-will be ignored), and then running `wizard upgrade --continue`."""
+resolving the files, adding them using `git add` and then
+running `wizard upgrade --continue`."""
class LocalChangesError(Error):
def __str__(self):
with git rerere to remember merge resolutions (XXX: not sure if
this actually works)."""
+class BlacklistedError(Error):
+ 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."""