2 import distutils.version
6 import logging.handlers
12 from wizard import app, command, deploy, merge, scripts, shell, util
14 kib_buffer = 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 shell.call("git", "status")
140 raise LocalChangesError()
141 except shell.CallError:
143 # Working copy is not anchored anywhere useful for git describe,
144 # so we need to give it a hint.
145 self.wc.setAppVersion(self.prod.app_version)
149 Make sure that a number of pre-upgrade invariants are met before
152 options = self.options
154 self.prod = deploy.ProductionCopy(".")
156 self.repo = self.prod.application.repository(options.srv_path)
157 # XXX: put this in Application
158 self.version = shell.eval("git", "--git-dir="+self.repo, "describe", "--tags", "master")
159 self.preflightBlacklist()
161 self.prod.verifyDatabase()
162 self.prod.verifyTag(options.srv_path)
163 self.prod.verifyGit(options.srv_path)
164 self.prod.verifyConfigured()
166 shell.call("git", "fetch", "--tags") # XXX: hack since some installs have stale tags
167 except shell.CallError as e:
168 if "Disk quota exceeded" in e.stderr:
172 self.prod.verifyVersion()
173 except deploy.VersionMismatchError as e:
174 # XXX: kind of hacky, mainly it does change the Git working copy
175 # state (although /very/ non-destructively)
176 shell.call("git", "merge", "--strategy=ours", self.prod.application.makeVersion(str(e.real_version)).scripts_tag)
180 raise VersionRematchFailed
181 self.prod.verifyWeb()
182 self.preflightAlreadyUpgraded()
183 self.preflightQuota()
184 def preflightBlacklist(self):
185 if os.path.exists(".scripts/blacklisted"):
186 reason = open(".scripts/blacklisted").read()
187 # ignore blank blacklisted files
190 raise BlacklistedError(reason)
192 logging.warning("Application was blacklisted, but no reason was found");
193 def preflightAlreadyUpgraded(self):
194 if self.version == self.prod.app_version.scripts_tag and not self.options.force:
195 # don't log this error; we need to have the traceback line
196 # so that the parsing code can catch it
197 # XXX: maybe we should build this in as a flag to add
198 # to exceptions w/ our exception handler
199 sys.stderr.write("Traceback:\n (n/a)\nAlreadyUpgraded\n")
201 def preflightQuota(self):
202 kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
203 if kib_limit is not None and (kib_limit - kib_usage) < kib_buffer:
207 if not self.options.dry_run:
208 self.mergePreCommit()
210 logging.debug("Temporary WC dir is %s", self.temp_wc_dir)
211 with util.ChangeDirectory(self.temp_wc_dir):
212 self.wc = deploy.WorkingCopy(".")
213 shell.call("git", "remote", "add", "scripts", self.repo)
214 shell.call("git", "fetch", "-q", "scripts")
215 self.user_commit = shell.eval("git", "rev-parse", "HEAD")
216 self.next_commit = shell.eval("git", "rev-parse", self.version)
217 self.mergeSaveState()
219 def mergePreCommit(self):
220 def get_file_set(rev):
221 return set(shell.eval("git", "ls-tree", "-r", "--name-only", rev).split("\n"))
222 # add all files that are unversioned but would be replaced by the pull,
223 # and generate a new commit
224 old_files = get_file_set("HEAD")
225 new_files = get_file_set(self.version)
226 added_files = new_files - old_files
227 for f in added_files:
228 if os.path.exists(f):
229 shell.call("git", "add", f)
230 message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
232 message += "\nPre-commit-by: " + util.get_operator_git()
233 except util.NoOperatorInfo:
236 shell.call("git", "commit", "-a", "-m", message)
237 except shell.CallError as e:
238 if "Permission denied" in e.stderr:
239 raise util.PermissionsError
242 logging.info("No changes detected")
243 def mergeClone(self):
244 # If /dev/shm exists, it's a tmpfs and we can use it
245 # to do a fast git merge. Don't forget to move it to
247 if not self.options.dry_run and not self.options.debug:
248 self.use_shm = os.path.exists("/dev/shm")
250 dir = "/dev/shm/wizard"
251 if not os.path.exists(dir):
257 self.temp_dir = tempfile.mkdtemp(prefix="wizard", dir=dir)
258 self.temp_wc_dir = os.path.join(self.temp_dir, "repo")
259 logging.info("Using temporary directory: " + self.temp_wc_dir)
260 shell.call("git", "clone", "-q", "--shared", ".", self.temp_wc_dir)
261 def mergeSaveState(self):
262 """Save variables so that ``--continue`` will work."""
263 # yeah yeah no trailing newline whatever
264 open(".git/WIZARD_UPGRADE_VERSION", "w").write(self.version)
265 open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (self.user_commit, self.next_commit))
266 open(".git/WIZARD_SIZE", "w").write(str(scripts.get_disk_usage()))
267 if self.options.log_file:
268 open(".git/WIZARD_LOG_FILE", "w").write(self.options.log_file)
269 def mergePerform(self):
270 def prepare_config():
271 self.wc.prepareConfig()
272 shell.call("git", "add", ".")
273 def resolve_conflicts():
274 return self.wc.resolveConflicts()
275 shell.call("git", "config", "merge.conflictstyle", "diff3")
277 if self.options.rr_cache is None:
278 self.options.rr_cache = os.path.join(self.prod.location, ".git", "rr-cache")
279 if not os.path.exists(self.options.rr_cache):
280 os.mkdir(self.options.rr_cache)
281 os.symlink(self.options.rr_cache, os.path.join(self.wc.location, ".git", "rr-cache"))
282 shell.call("git", "config", "rerere.enabled", "true")
284 merge.merge(self.wc.app_version.scripts_tag, self.version,
285 prepare_config, resolve_conflicts)
286 except merge.MergeError:
290 for line in shell.eval("git", "ls-files", "--unmerged").splitlines():
291 files.add(line.split(None, 3)[-1])
292 conflicts = len(files)
293 # XXX: this is kind of fiddly; note that temp_dir still points at the OLD
294 # location after this code.
295 self.temp_wc_dir = mv_shm_to_tmp(os.getcwd(), self.use_shm)
296 self.wc.location = self.temp_wc_dir
297 os.chdir(self.temp_wc_dir)
298 open(os.path.join(self.prod.location, ".scripts/pending"), "w").write(self.temp_wc_dir)
299 if self.options.non_interactive:
300 print "%d %s" % (conflicts, self.temp_wc_dir)
303 user_shell = os.getenv("SHELL")
304 if not user_shell: user_shell = "/bin/bash"
305 # XXX: scripts specific hack, since mbash doesn't respect the current working directory
306 # When the revolution comes (i.e. $ATHENA_HOMEDIR/Scripts is your Scripts home
307 # directory) this isn't strictly necessary, but we'll probably need to support
308 # web_scripts directories ad infinitum.
309 if user_shell == "/usr/local/bin/mbash": user_shell = "/bin/bash"
312 print "ERROR: The merge failed with %d conflicts in these files:" % conflicts
314 for file in sorted(files):
317 print "Please resolve these conflicts (edit and then `git add`), and"
318 print "then type 'exit'. You will now be dropped into a shell whose working"
319 print "directory is %s" % self.temp_wc_dir
321 shell.call(user_shell, "-i", interactive=True)
322 except shell.CallError as e:
323 logging.warning("Shell returned non-zero exit code %d" % e.code)
324 if shell.eval("git", "ls-files", "--unmerged").strip():
326 print "WARNING: There are still unmerged files."
327 out = raw_input("Continue editing? [y/N]: ")
328 if out == "y" or out == "Y":
331 print "Aborting. The conflicted working copy can be found at:"
333 print " %s" % self.temp_wc_dir
335 print "and you can resume the upgrade process by running in that directory:"
337 print " wizard upgrade --continue"
341 def postflight(self):
342 with util.ChangeDirectory(self.temp_wc_dir):
343 if shell.eval("git", "ls-files", "-u").strip():
344 raise UnmergedChangesError
345 shell.call("git", "commit", "--allow-empty", "-am", "throw-away commit")
346 self.wc.parametrize(self.prod)
347 shell.call("git", "add", ".")
348 message = self.postflightCommitMessage()
349 new_tree = shell.eval("git", "write-tree")
350 final_commit = shell.eval("git", "commit-tree", new_tree,
351 "-p", self.user_commit, "-p", self.next_commit, input=message, log=True)
352 # a master branch may not necessarily exist if the user
353 # was manually installed to an earlier version
355 shell.call("git", "checkout", "-q", "-b", "master", "--")
356 except shell.CallError:
357 shell.call("git", "checkout", "-q", "master", "--")
358 shell.call("git", "reset", "-q", "--hard", final_commit)
359 # This is a quick sanity check to make sure we didn't completely
361 self.wc.invalidateCache()
362 self.wc.verifyVersion()
363 def postflightCommitMessage(self):
364 message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), self.version, util.get_git_footer())
366 message += "\nUpgraded-by: " + util.get_operator_git()
367 except util.NoOperatorInfo:
372 # Ok, now we have to do a crazy complicated dance to see if we're
373 # going to have enough quota to finish what we need
374 pre_size = int(open(os.path.join(self.temp_wc_dir, ".git/WIZARD_SIZE"), "r").read())
375 post_size = scripts.get_disk_usage(self.temp_wc_dir)
376 backup = self.prod.backup(self.options)
377 kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
378 if kib_limit is not None and (kib_limit - kib_usage) - (post_size - pre_size) / 1024 < kib_buffer:
379 shutil.rmtree(os.path.join(".scripts/backups", shell.eval("wizard", "restore").splitlines()[0]))
383 def upgrade(self, backup):
384 # XXX: frob .htaccess to make site inaccessible
385 with util.IgnoreKeyboardInterrupts():
386 with util.LockDirectory(".scripts-upgrade-lock"):
387 shell.call("git", "fetch", "--tags")
388 # git merge (which performs a fast forward)
389 shell.call("git", "pull", "-q", self.temp_wc_dir, "master")
390 version_obj = distutils.version.LooseVersion(self.version.partition('-')[2])
393 self.prod.upgrade(version_obj, self.options)
394 self.prod.verifyWeb()
395 except app.UpgradeFailure:
396 logging.warning("Upgrade failed: rolling back")
397 self.upgradeRollback(backup)
399 except deploy.WebVerificationError as e:
400 logging.warning("Web verification failed: rolling back")
401 self.upgradeRollback(backup)
402 raise app.UpgradeVerificationFailure()
403 # XXX: frob .htaccess to make site accessible
404 # to do this, check if .htaccess changed, first. Upgrade
405 # process might have frobbed it. Don't be
406 # particularly worried if the segment disappeared
407 def upgradeRollback(self, backup):
408 # You don't want d.restore() because it doesn't perform
409 # the file level backup
410 shell.call("wizard", "restore", backup)
412 self.prod.verifyWeb()
413 except deploy.WebVerificationError:
414 logging.critical("Web verification failed after rollback")
418 def mv_shm_to_tmp(curdir, use_shm):
419 if not use_shm: return curdir
420 # Keeping all of our autoinstalls in shared memory is
421 # a recipe for disaster, so let's move them to slightly
422 # less volatile storage (a temporary directory)
423 os.chdir(tempfile.gettempdir())
424 newdir = tempfile.mkdtemp(prefix="wizard")
425 # shutil, not os; at least on Ubuntu os.move fails
426 # with "[Errno 18] Invalid cross-device link"
427 shutil.move(curdir, newdir)
428 shutil.rmtree(os.path.dirname(curdir))
429 curdir = os.path.join(newdir, "repo")
432 def parse_args(argv, baton):
433 usage = """usage: %prog upgrade [ARGS] [DIR]
435 Upgrades an autoinstall to the latest version. This involves
436 updating files and running .scripts/update. If the merge fails,
437 this program will write the number of conflicts and the directory
438 of the conflicted working tree to stdout, separated by a space."""
439 parser = command.WizardOptionParser(usage)
440 parser.add_option("--dry-run", dest="dry_run", action="store_true",
441 default=False, help="Prints would would be run without changing anything")
442 # notice trailing underscore
443 parser.add_option("--continue", dest="continue_", action="store_true",
444 default=False, help="Continues an upgrade that has had its merge manually "
445 "resolved using the current working directory as the resolved copy.")
446 parser.add_option("--force", dest="force", action="store_true",
447 default=False, help="Force running upgrade even if it's already at latest version.")
448 parser.add_option("--non-interactive", dest="non_interactive", action="store_true",
449 default=False, help="Don't drop to shell in event of conflict.")
450 parser.add_option("--rr-cache", dest="rr_cache", metavar="PATH",
451 default=None, help="Use this folder to reuse recorded merge resolutions. Defaults to"
452 "your production copy's rr-cache, if it exists.")
453 baton.push(parser, "srv_path")
454 options, args = parser.parse_all(argv)
456 parser.error("too many arguments")
459 class Error(command.Error):
460 """Base exception for all exceptions raised by upgrade"""
463 class QuotaTooLow(Error):
467 ERROR: The locker quota was too low to complete the autoinstall
471 class AlreadyUpgraded(Error):
476 ERROR: This autoinstall is already at the latest version."""
478 class MergeFailed(Error):
483 ERROR: Merge failed. Above is the temporary directory that
484 the conflicted merge is in: resolve the merge by cd'ing to the
485 temporary directory, finding conflicted files with `git status`,
486 resolving the files, adding them using `git add` and then
487 running `wizard upgrade --continue`."""
489 class LocalChangesError(Error):
493 ERROR: Local changes occurred in the install while the merge was
494 being processed so that a pull would not result in a fast-forward.
495 The best way to resolve this is probably to attempt an upgrade again,
496 with git rerere to remember merge resolutions (XXX: not sure if
497 this actually works)."""
499 class UnmergedChangesError(Error):
503 ERROR: You attempted to continue an upgrade, but there were
504 still local unmerged changes in your working copy. Please resolve
505 them all and try again."""
507 class BlacklistedError(Error):
508 #: Reason why the autoinstall was blacklisted
510 exitcode = errno_blacklisted
511 def __init__(self, reason):
516 ERROR: This autoinstall was manually blacklisted against errors;
517 if the user has not been notified of this, please send them
520 The reason was: %s""" % self.reason
522 class CannotResumeError(Error):
526 ERROR: We cannot resume the upgrade process; either this working
527 copy is missing essential metadata, or you've attempt to continue
528 from a production copy that does not have any pending upgrades.
531 class VersionRematchFailed(Error):
535 ERROR: Your Git version information was not consistent with your
536 files on the system, and we were unable to create a fake merge
537 to make the two consistent. Please contact scripts@mit.edu.