import time
import errno
+# XXX: read().strip() is an accident waiting to happen if anyone ever
+# makes a directory with a trailing or leading space. Unlikely, but yeah.
+
from wizard import app, command, deploy, merge, shell, user, util
buffer = 1024 * 1024 * 30 # 30 MiB we will always leave available
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``).
logging.info("Upgrading %s" % os.getcwd())
self.preflight()
self.merge()
+ # Note invariant: we expect you to be in the production
+ # directory at this point, even if you --continue'd from
+ # the temporary directory!
self.postflight()
# Till now, all of our operations were in a tmp sandbox.
if self.options.dry_run:
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)
self.resumeChdir()
self.resumeState()
self.resumeLogging()
- util.chdir(shell.eval("git", "config", "remote.origin.url"))
self.resumeProd()
def resumeChdir(self):
"""
- If we called ``--continue`` inside a production copy, check if
- :file:`.scripts/pending` exists and change to that directory if so.
+ If we called ``--continue`` inside a working copy (the usual
+ situation), check if :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)
- def resumeState(self):
self.temp_wc_dir = os.getcwd()
- self.wc = deploy.WorkingCopy(".")
- try:
- self.user_commit, self.next_commit = open(".git/WIZARD_PARENTS", "r").read().split()
- self.version = open(".git/WIZARD_UPGRADE_VERSION", "r").read()
- except IOError as e:
- if e.errno == errno.ENOENT:
- raise CannotResumeError()
- else:
- raise
+ didChdir = command.chdir_to_production()
+ self.prod = deploy.ProductionCopy(".")
+ pending_dir = open(self.prod.pending_file).read().strip()
+ if not didChdir:
+ logging.warning("Continued from a production copy; using working copy at %s", pending_dir)
+ self.temp_wc_dir = pending_dir
+ elif self.temp_wc_dir != pending_dir:
+ # prefer the original working copy, but warn that someone
+ # else someone a started an upgrade in the meantime (XXX:
+ # actually, that someone else should bug out, not clobber)
+ logging.warning("Someone else appears to have started an upgrade at %s", pending_dir)
+ def resumeState(self):
+ with util.ChangeDirectory(self.temp_wc_dir):
+ self.wc = deploy.WorkingCopy(".")
+ try:
+ self.user_commit, self.next_commit = open(".git/WIZARD_PARENTS", "r").read().split()
+ self.version = open(".git/WIZARD_UPGRADE_VERSION", "r").read()
+ except IOError as e:
+ if e.errno == errno.ENOENT:
+ raise CannotResumeError()
+ else:
+ raise
def resumeLogging(self):
- options = self.options
- if not options.log_file and os.path.exists(".git/WIZARD_LOG_FILE"):
- options.log_file = open(".git/WIZARD_LOG_FILE", "r").read()
- command.setup_file_logger(options.log_file, options.debug)
+ with util.ChangeDirectory(self.temp_wc_dir):
+ options = self.options
+ if not options.log_file and os.path.exists(".git/WIZARD_LOG_FILE"):
+ options.log_file = open(".git/WIZARD_LOG_FILE", "r").read()
+ command.setup_file_logger(options.log_file, options.debug)
def resumeProd(self):
"""Restore :attr:`prod` attribute, and check if the production copy has drifted."""
- self.prod = deploy.ProductionCopy(".")
try:
# simulate the action of `git status`, based on cmd_status()'s call to
# refresh_cache() in builtin-commit.c
self.prod.verify()
self.prod.verifyDatabase()
self.prod.verifyTag(options.srv_path)
- self.prod.verifyGit(options.srv_path)
- self.prod.verifyConfigured()
+ try:
+ self.prod.verifyGit(options.srv_path)
+ except deploy.InconsistentWizardTagError:
+ shell.call("git", "fetch")
+ shell.call("git", "fetch", "--tags")
+ shell.call("wizard", "remaster")
+ self.prod.verifyGit(options.srv_path)
+ except deploy.HeadNotDescendantError:
+ shell.call("wizard", "remaster")
+ 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:
# 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)).scripts_tag)
+ 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)
break
else:
raise VersionRematchFailed
- self.prod.verifyWeb()
+ self.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
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
sys.stderr.write("Traceback:\n (n/a)\nAlreadyUpgraded\n")
sys.exit(2)
def preflightQuota(self):
- usage, limit = user.quota()
- if limit is not None and (limit - usage) < 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:
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()
for f in added_files:
if os.path.lexists(f): # broken symbolic links count too!
shell.call("git", "add", f)
- message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
+ 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:
self.temp_dir = tempfile.mkdtemp(prefix="wizard", dir=dir)
self.temp_wc_dir = os.path.join(self.temp_dir, "repo")
logging.info("Using temporary directory: " + self.temp_wc_dir)
- shell.call("git", "clone", "-q", "--shared", ".", self.temp_wc_dir)
+ shell.call("git", "clone", "-q", ".", self.temp_wc_dir)
def mergeSaveState(self):
"""Save variables so that ``--continue`` will work."""
# yeah yeah no trailing newline whatever
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()
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)
+ if os.path.exists(self.prod.pending_file):
+ mtime = os.path.getmtime(self.prod.pending_file)
+ pending_location = open(self.prod.pending_file).read().strip()
+ # don't complain if .wizard/pending is a day old
+ if mtime > (time.time() - 60 * 60 * 24):
+ raise UpgradeInProgressError(pending_location, mtime)
+ else:
+ logging.warning("Probably harmless old pending upgrade at %s from %s", pending_location, time.ctime(mtime))
+ 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
print "Please resolve these conflicts (edit and then `git add`), and"
print "then type 'exit'. You will now be dropped into a shell whose working"
print "directory is %s" % self.temp_wc_dir
+ print
+ print "NOTE: If you resolve these conflicts, and then the upgrade fails for"
+ print "an unrelated reason, you can run 'wizard upgrade --continue' from this"
+ print "directory to try again."
try:
shell.call(user_shell, "-i", interactive=True)
except shell.CallError as e:
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:
pre_size = int(open(os.path.join(self.temp_wc_dir, ".git/WIZARD_SIZE"), "r").read())
post_size = util.disk_usage(self.temp_wc_dir)
backup = self.prod.backup(self.options)
- usage, limit = user.quota()
- if limit is not None and (limit - usage) - (post_size - pre_size) < 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")
try:
# run update script
self.prod.upgrade(version_obj, self.options)
- self.prod.verifyWeb()
+ self.verifyWeb()
+ try:
+ os.unlink(self.prod.pending_file)
+ except OSError as e:
+ if e.errno != errno.ENOENT:
+ raise
except app.UpgradeFailure:
logging.warning("Upgrade failed: rolling back")
self.upgradeRollback(backup)
if not self.options.disable_rollback:
shell.call("wizard", "restore", backup)
try:
- self.prod.verifyWeb()
+ self.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)
+ def verifyWeb(self):
+ if not self.options.skip_verification:
+ self.prod.verifyWeb()
+
+
# utility functions
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",
"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=command.boolish(os.getenv("WIZARD_DISABLE_ROLLBACK")),
+ 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:
parser.error("too many arguments")
+ if options.skip_verification:
+ logging.warning("Verification is disabled; Wizard may break your application and will not tell you about it")
return options, args
class Error(command.Error):
ERROR: This autoinstall was manually blacklisted against errors;
if the user has not been notified of this, please send them
-mail.
+mail. If you know that this application is blacklisted and
+would like to attempt an upgrade anyway, run:
+
+ wizard blacklist --delete
The reason was: %s""" % self.reason
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. Please contact scripts@mit.edu
-with this error message.
-"""
+to make the two consistent."""
class UnknownVersionError(Error):
#: Version that we didn't have
return """
ERROR: The version you are attempting to upgrade from (%s)
-is unknown to the repository Wizard is using. Please contact
-scripts@mit.edu with this error message.
-""" % str(self.version)
+is unknown to the repository Wizard is using.""" % str(self.version)
+
+class UpgradeInProgressError(Error):
+ #: Location of pending upgrade
+ location = None
+ #: Time of pending upgrade
+ time = None
+ def __init__(self, location, time):
+ self.location = location
+ self.time = time
+ def __str__(self):
+ return """
+
+ERROR: There is already an upgrade in progress at
+
+ %s
+
+which was last started at %s.
+
+To ignore and start another upgrade anyway, remove the file
+.wizard/pending and try again.""" % (self.location, time.ctime(self.time))