2 import distutils.version
6 import logging.handlers
12 from wizard import app, command, deploy, merge, shell, user, util
14 buffer = 1024 * 1024 * 30 # 30 MiB we will always leave available
15 errno_blacklisted = 64
17 def main(argv, baton):
18 options, args = parse_args(argv, baton)
19 dir = os.path.abspath(args[0]) if args else os.getcwd()
21 shell.drop_priviledges(dir, options.log_file)
23 upgrade = Upgrade(options)
25 if not options.non_interactive:
26 print "Upgrade complete"
28 class Upgrade(object):
30 Represents the algorithm for upgrading an application. This is in
31 a class and not a function because it's a multi-step process that
32 requires state betweens steps. Steps are represented as methods
36 #: Version of application we are upgrading to, i.e. the latest version.
37 version = None # XXX: This is a string... I'm not convinced it should be
38 #: String commit ID of the user's latest wc; i.e. "ours"
40 #: String commit ID of the latest, greatest scripts version; i.e. "theirs"
42 #: The temporary directory that the system gave us; may stay as ``None``
43 #: if we don't ever make ourselves a temporary directory (e.g. ``--continue``).
44 #: While we should clean this up if it is set to something, it may
45 #: not correspond to anything useful.
47 #: The temporary directory containing our working copy for merging
49 #: We place the temporary repositories inside a tmpfs while merging;
50 #: this makes merges not disk-bound and affords a modest speed increase.
51 #: If you are running ``--continue``, this is guaranteed to be ``False``.
53 #: Upstream repository to use. This does not need to be saved.
56 #: Instance of :class:`wizard.deploy.WorkingCopy` for this upgrade
58 #: Instance of :class:`wizard.deploy.ProductionCopy` for this upgrade
61 #: Options object that the installer was called with
64 def __init__(self, options):
66 self.user_commit = None
67 self.next_commit = None
69 self.temp_wc_dir = None
70 self.use_shm = False # False until proven otherwise.
73 self.options = options
75 def execute(self, dir):
77 Executes an upgrade. This is the entry-point. This expects
78 that it's current working directory is the same as ``dir``.
80 assert os.path.abspath(dir) == os.getcwd()
82 if self.options.continue_:
83 logging.info("Continuing upgrade...")
86 logging.info("Upgrading %s" % os.getcwd())
90 # Till now, all of our operations were in a tmp sandbox.
91 if self.options.dry_run:
92 logging.info("Dry run, bailing. See results at %s" % self.temp_wc_dir)
94 backup = self.backup()
97 if self.use_shm and self.temp_dir and os.path.exists(self.temp_dir):
98 shutil.rmtree(self.temp_dir)
102 In the event of a ``--continue`` flag, we have to restore state and
103 perform some sanity checks.
108 util.chdir(shell.eval("git", "config", "remote.origin.url"))
110 def resumeChdir(self):
112 If we called ``--continue`` inside a production copy, check if
113 :file:`.scripts/pending` exists and change to that directory if so.
115 if os.path.exists(".scripts/pending"):
116 newdir = open(".scripts/pending").read().strip()
117 logging.warning("Detected production copy; changing directory to %s", newdir)
119 def resumeState(self):
120 self.temp_wc_dir = os.getcwd()
121 self.wc = deploy.WorkingCopy(".")
123 self.user_commit, self.next_commit = open(".git/WIZARD_PARENTS", "r").read().split()
124 self.version = open(".git/WIZARD_UPGRADE_VERSION", "r").read()
126 if e.errno == errno.ENOENT:
127 raise CannotResumeError()
130 def resumeLogging(self):
131 options = self.options
132 if not options.log_file and os.path.exists(".git/WIZARD_LOG_FILE"):
133 options.log_file = open(".git/WIZARD_LOG_FILE", "r").read()
134 command.setup_file_logger(options.log_file, options.debug)
135 def resumeProd(self):
136 """Restore :attr:`prod` attribute, and check if the production copy has drifted."""
137 self.prod = deploy.ProductionCopy(".")
139 r1 = shell.eval("git", "diff-files", "--name-only").strip()
140 r2 = shell.eval("git", "diff-index", "--name-only", "HEAD").strip()
142 raise LocalChangesError()
143 except shell.CallError:
145 # Working copy is not anchored anywhere useful for git describe,
146 # so we need to give it a hint.
147 self.wc.setAppVersion(self.prod.app_version)
151 Make sure that a number of pre-upgrade invariants are met before
154 options = self.options
156 self.prod = deploy.ProductionCopy(".")
158 self.repo = self.prod.application.repository(options.srv_path)
159 # XXX: put this in Application
160 self.version = shell.eval("git", "--git-dir="+self.repo, "describe", "--tags", "master")
161 self.preflightBlacklist()
163 self.prod.verifyDatabase()
164 self.prod.verifyTag(options.srv_path)
165 self.prod.verifyGit(options.srv_path)
166 self.prod.verifyConfigured()
168 shell.call("git", "fetch", "--tags") # XXX: hack since some installs have stale tags
169 except shell.CallError as e:
170 if "Disk quota exceeded" in e.stderr:
174 self.prod.verifyVersion()
175 except deploy.VersionMismatchError as e:
176 # XXX: kind of hacky, mainly it does change the Git working copy
177 # state (although /very/ non-destructively)
179 shell.call("git", "merge", "--strategy=ours", self.prod.application.makeVersion(str(e.real_version)).scripts_tag)
180 except shell.CallError as e2:
181 if "does not point to a commit" in e2.stderr:
182 raise UnknownVersionError(e.real_version)
188 raise VersionRematchFailed
189 self.prod.verifyWeb()
190 self.preflightAlreadyUpgraded()
191 self.preflightQuota()
192 def preflightBlacklist(self):
193 if os.path.exists(".scripts/blacklisted"):
194 reason = open(".scripts/blacklisted").read()
195 # ignore blank blacklisted files
198 raise BlacklistedError(reason)
200 logging.warning("Application was blacklisted, but no reason was found");
201 def preflightAlreadyUpgraded(self):
202 if self.version == self.prod.app_version.scripts_tag and not self.options.force:
203 # don't log this error; we need to have the traceback line
204 # so that the parsing code can catch it
205 # XXX: maybe we should build this in as a flag to add
206 # to exceptions w/ our exception handler
207 sys.stderr.write("Traceback:\n (n/a)\nAlreadyUpgraded\n")
209 def preflightQuota(self):
210 usage, limit = user.quota()
211 if limit is not None and (limit - usage) < buffer:
215 if not self.options.dry_run:
216 self.mergePreCommit()
218 logging.debug("Temporary WC dir is %s", self.temp_wc_dir)
219 with util.ChangeDirectory(self.temp_wc_dir):
220 self.wc = deploy.WorkingCopy(".")
221 shell.call("git", "remote", "add", "scripts", self.repo)
222 shell.call("git", "fetch", "-q", "scripts")
223 self.user_commit = shell.eval("git", "rev-parse", "HEAD")
224 self.next_commit = shell.eval("git", "rev-parse", self.version)
225 self.mergeSaveState()
227 def mergePreCommit(self):
228 def get_file_set(rev):
229 return set(shell.eval("git", "ls-tree", "-r", "--name-only", rev).split("\n"))
230 # add all files that are unversioned but would be replaced by the pull,
231 # and generate a new commit
232 old_files = get_file_set("HEAD")
233 new_files = get_file_set(self.version)
234 added_files = new_files - old_files
235 for f in added_files:
236 if os.path.lexists(f): # broken symbolic links count too!
237 shell.call("git", "add", f)
238 message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
240 message += "\nPre-commit-by: " + util.get_operator_git()
241 except util.NoOperatorInfo:
244 shell.call("git", "commit", "-a", "-m", message)
245 except shell.CallError as e:
246 if "Permission denied" in e.stderr:
247 raise util.PermissionsError
250 logging.info("No changes detected")
251 def mergeClone(self):
252 # If /dev/shm exists, it's a tmpfs and we can use it
253 # to do a fast git merge. Don't forget to move it to
255 if not self.options.dry_run and not self.options.debug:
256 self.use_shm = os.path.exists("/dev/shm")
258 dir = "/dev/shm/wizard"
259 if not os.path.exists(dir):
265 self.temp_dir = tempfile.mkdtemp(prefix="wizard", dir=dir)
266 self.temp_wc_dir = os.path.join(self.temp_dir, "repo")
267 logging.info("Using temporary directory: " + self.temp_wc_dir)
268 shell.call("git", "clone", "-q", "--shared", ".", self.temp_wc_dir)
269 def mergeSaveState(self):
270 """Save variables so that ``--continue`` will work."""
271 # yeah yeah no trailing newline whatever
272 open(".git/WIZARD_UPGRADE_VERSION", "w").write(self.version)
273 open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (self.user_commit, self.next_commit))
274 open(".git/WIZARD_SIZE", "w").write(str(util.disk_usage()))
275 if self.options.log_file:
276 open(".git/WIZARD_LOG_FILE", "w").write(self.options.log_file)
277 def mergePerform(self):
278 def prepare_config():
279 self.wc.prepareConfig()
280 shell.call("git", "add", ".")
281 def resolve_conflicts():
282 return self.wc.resolveConflicts()
283 shell.call("git", "config", "merge.conflictstyle", "diff3")
285 if self.options.rr_cache is None:
286 self.options.rr_cache = os.path.join(self.prod.location, ".git", "rr-cache")
287 if not os.path.exists(self.options.rr_cache):
288 os.mkdir(self.options.rr_cache)
289 os.symlink(self.options.rr_cache, os.path.join(self.wc.location, ".git", "rr-cache"))
290 shell.call("git", "config", "rerere.enabled", "true")
292 merge.merge(self.wc.app_version.scripts_tag, self.version,
293 prepare_config, resolve_conflicts)
294 except merge.MergeError:
298 for line in shell.eval("git", "ls-files", "--unmerged").splitlines():
299 files.add(line.split(None, 3)[-1])
300 conflicts = len(files)
301 # XXX: this is kind of fiddly; note that temp_dir still points at the OLD
302 # location after this code.
303 self.temp_wc_dir = mv_shm_to_tmp(os.getcwd(), self.use_shm)
304 self.wc.location = self.temp_wc_dir
305 os.chdir(self.temp_wc_dir)
306 open(os.path.join(self.prod.location, ".scripts/pending"), "w").write(self.temp_wc_dir)
307 if self.options.non_interactive:
308 print "%d %s" % (conflicts, self.temp_wc_dir)
311 user_shell = os.getenv("SHELL")
312 if not user_shell: user_shell = "/bin/bash"
313 # XXX: scripts specific hack, since mbash doesn't respect the current working directory
314 # When the revolution comes (i.e. $ATHENA_HOMEDIR/Scripts is your Scripts home
315 # directory) this isn't strictly necessary, but we'll probably need to support
316 # web_scripts directories ad infinitum.
317 if user_shell == "/usr/local/bin/mbash": user_shell = "/bin/bash"
320 print "ERROR: The merge failed with %d conflicts in these files:" % conflicts
322 for file in sorted(files):
325 print "Please resolve these conflicts (edit and then `git add`), and"
326 print "then type 'exit'. You will now be dropped into a shell whose working"
327 print "directory is %s" % self.temp_wc_dir
329 shell.call(user_shell, "-i", interactive=True)
330 except shell.CallError as e:
331 logging.warning("Shell returned non-zero exit code %d" % e.code)
332 if shell.eval("git", "ls-files", "--unmerged").strip():
334 print "WARNING: There are still unmerged files."
335 out = raw_input("Continue editing? [y/N]: ")
336 if out == "y" or out == "Y":
339 print "Aborting. The conflicted working copy can be found at:"
341 print " %s" % self.temp_wc_dir
343 print "and you can resume the upgrade process by running in that directory:"
345 print " wizard upgrade --continue"
349 def postflight(self):
350 with util.ChangeDirectory(self.temp_wc_dir):
351 if shell.eval("git", "ls-files", "-u").strip():
352 raise UnmergedChangesError
353 shell.call("git", "commit", "--allow-empty", "-am", "throw-away commit")
354 self.wc.parametrize(self.prod)
355 shell.call("git", "add", ".")
356 message = self.postflightCommitMessage()
357 new_tree = shell.eval("git", "write-tree")
358 final_commit = shell.eval("git", "commit-tree", new_tree,
359 "-p", self.user_commit, "-p", self.next_commit, input=message, log=True)
360 # a master branch may not necessarily exist if the user
361 # was manually installed to an earlier version
363 shell.call("git", "checkout", "-q", "-b", "master", "--")
364 except shell.CallError:
365 shell.call("git", "checkout", "-q", "master", "--")
366 shell.call("git", "reset", "-q", "--hard", final_commit)
367 # This is a quick sanity check to make sure we didn't completely
369 self.wc.invalidateCache()
370 self.wc.verifyVersion()
371 def postflightCommitMessage(self):
372 message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), self.version, util.get_git_footer())
374 message += "\nUpgraded-by: " + util.get_operator_git()
375 except util.NoOperatorInfo:
380 # Ok, now we have to do a crazy complicated dance to see if we're
381 # going to have enough quota to finish what we need
382 pre_size = int(open(os.path.join(self.temp_wc_dir, ".git/WIZARD_SIZE"), "r").read())
383 post_size = util.disk_usage(self.temp_wc_dir)
384 backup = self.prod.backup(self.options)
385 usage, limit = user.quota()
386 if limit is not None and (limit - usage) - (post_size - pre_size) < buffer:
387 shutil.rmtree(os.path.join(".scripts/backups", shell.eval("wizard", "restore").splitlines()[0]))
391 def upgrade(self, backup):
392 # XXX: frob .htaccess to make site inaccessible
393 with util.IgnoreKeyboardInterrupts():
394 with util.LockDirectory(".scripts-upgrade-lock"):
395 shell.call("git", "fetch", "--tags")
396 # git merge (which performs a fast forward)
397 shell.call("git", "pull", "-q", self.temp_wc_dir, "master")
398 version_obj = distutils.version.LooseVersion(self.version.partition('-')[2])
401 self.prod.upgrade(version_obj, self.options)
402 self.prod.verifyWeb()
403 except app.UpgradeFailure:
404 logging.warning("Upgrade failed: rolling back")
405 self.upgradeRollback(backup)
407 except deploy.WebVerificationError as e:
408 logging.warning("Web verification failed: rolling back")
409 self.upgradeRollback(backup)
410 raise app.UpgradeVerificationFailure()
411 # XXX: frob .htaccess to make site accessible
412 # to do this, check if .htaccess changed, first. Upgrade
413 # process might have frobbed it. Don't be
414 # particularly worried if the segment disappeared
415 def upgradeRollback(self, backup):
416 # You don't want d.restore() because it doesn't perform
417 # the file level backup
418 if not self.options.disable_rollback:
419 shell.call("wizard", "restore", backup)
421 self.prod.verifyWeb()
422 except deploy.WebVerificationError:
423 logging.critical("Web verification failed after rollback")
425 logging.warning("Rollback was disabled; you can rollback with `wizard restore %s`", backup)
429 def mv_shm_to_tmp(curdir, use_shm):
430 if not use_shm: return curdir
431 # Keeping all of our autoinstalls in shared memory is
432 # a recipe for disaster, so let's move them to slightly
433 # less volatile storage (a temporary directory)
434 os.chdir(tempfile.gettempdir())
435 newdir = tempfile.mkdtemp(prefix="wizard")
436 # shutil, not os; at least on Ubuntu os.move fails
437 # with "[Errno 18] Invalid cross-device link"
438 shutil.move(curdir, newdir)
439 shutil.rmtree(os.path.dirname(curdir))
440 curdir = os.path.join(newdir, "repo")
443 def parse_args(argv, baton):
444 usage = """usage: %prog upgrade [ARGS] [DIR]
446 Upgrades an autoinstall to the latest version. This involves
447 updating files and running .scripts/update. If the merge fails,
448 this program will write the number of conflicts and the directory
449 of the conflicted working tree to stdout, separated by a space."""
450 parser = command.WizardOptionParser(usage)
451 parser.add_option("--dry-run", dest="dry_run", action="store_true",
452 default=False, help="Prints would would be run without changing anything")
453 # notice trailing underscore
454 parser.add_option("--continue", dest="continue_", action="store_true",
455 default=False, help="Continues an upgrade that has had its merge manually "
456 "resolved using the current working directory as the resolved copy.")
457 parser.add_option("--force", dest="force", action="store_true",
458 default=False, help="Force running upgrade even if it's already at latest version.")
459 parser.add_option("--non-interactive", dest="non_interactive", action="store_true",
460 default=False, help="Don't drop to shell in event of conflict.")
461 parser.add_option("--rr-cache", dest="rr_cache", metavar="PATH",
462 default=None, help="Use this folder to reuse recorded merge resolutions. Defaults to"
463 "your production copy's rr-cache, if it exists.")
464 parser.add_option("--disable-rollback", dest="disable_rollback", action="store_true",
465 default=command.boolish(os.getenv("WIZARD_DISABLE_ROLLBACK")),
466 help="Skips rollback in the event of a failed upgrade. Envvar is WIZARD_DISABLE_ROLLBACK.")
467 baton.push(parser, "srv_path")
468 options, args = parser.parse_all(argv)
470 parser.error("too many arguments")
473 class Error(command.Error):
474 """Base exception for all exceptions raised by upgrade"""
477 class QuotaTooLow(Error):
481 ERROR: The locker quota was too low to complete the autoinstall
485 class AlreadyUpgraded(Error):
490 ERROR: This autoinstall is already at the latest version."""
492 class MergeFailed(Error):
497 ERROR: Merge failed. Above is the temporary directory that
498 the conflicted merge is in: resolve the merge by cd'ing to the
499 temporary directory, finding conflicted files with `git status`,
500 resolving the files, adding them using `git add` and then
501 running `wizard upgrade --continue`."""
503 class LocalChangesError(Error):
507 ERROR: Local changes occurred in the install while the merge was
508 being processed so that a pull would not result in a fast-forward.
509 The best way to resolve this is probably to attempt an upgrade again,
510 with git rerere to remember merge resolutions (XXX: not sure if
511 this actually works)."""
513 class UnmergedChangesError(Error):
517 ERROR: You attempted to continue an upgrade, but there were
518 still local unmerged changes in your working copy. Please resolve
519 them all and try again."""
521 class BlacklistedError(Error):
522 #: Reason why the autoinstall was blacklisted
524 exitcode = errno_blacklisted
525 def __init__(self, reason):
530 ERROR: This autoinstall was manually blacklisted against errors;
531 if the user has not been notified of this, please send them
534 The reason was: %s""" % self.reason
536 class CannotResumeError(Error):
540 ERROR: We cannot resume the upgrade process; either this working
541 copy is missing essential metadata, or you've attempt to continue
542 from a production copy that does not have any pending upgrades.
545 class VersionRematchFailed(Error):
549 ERROR: Your Git version information was not consistent with your
550 files on the system, and we were unable to create a fake merge
551 to make the two consistent. Please contact scripts@mit.edu
552 with this error message.
555 class UnknownVersionError(Error):
556 #: Version that we didn't have
558 def __init__(self, version):
559 self.version = version
563 ERROR: The version you are attempting to upgrade from (%s)
564 is unknown to the repository Wizard is using. Please contact
565 scripts@mit.edu with this error message.
566 """ % str(self.version)