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()
160 self.prod.verifyTag(options.srv_path)
161 self.prod.verifyGit(options.srv_path)
162 self.prod.verifyConfigured()
164 shell.call("git", "fetch", "--tags") # XXX: hack since some installs have stale tags
165 except shell.CallError as e:
166 if "Disk quota exceeded" in e.stderr:
170 self.prod.verifyVersion()
171 except deploy.VersionMismatchError as e:
172 # XXX: kind of hacky, mainly it does change the Git working copy
173 # state (although /very/ non-destructively)
174 shell.call("git", "merge", "--strategy=ours", self.prod.application.makeVersion(str(e.real_version)).scripts_tag)
177 self.prod.verifyWeb()
178 self.preflightAlreadyUpgraded()
179 self.preflightQuota()
180 def preflightBlacklist(self):
181 if os.path.exists(".scripts/blacklisted"):
182 reason = open(".scripts/blacklisted").read()
183 # ignore blank blacklisted files
186 raise BlacklistedError(reason)
188 logging.warning("Application was blacklisted, but no reason was found");
189 def preflightAlreadyUpgraded(self):
190 if self.version == self.prod.app_version.scripts_tag and not self.options.force:
191 # don't log this error; we need to have the traceback line
192 # so that the parsing code can catch it
193 # XXX: maybe we should build this in as a flag to add
194 # to exceptions w/ our exception handler
195 sys.stderr.write("Traceback:\n (n/a)\nAlreadyUpgraded\n")
197 def preflightQuota(self):
198 kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
199 if kib_limit is not None and (kib_limit - kib_usage) < kib_buffer:
203 if not self.options.dry_run:
204 self.mergePreCommit()
206 logging.debug("Temporary WC dir is %s", self.temp_wc_dir)
207 with util.ChangeDirectory(self.temp_wc_dir):
208 self.wc = deploy.WorkingCopy(".")
209 shell.call("git", "remote", "add", "scripts", self.repo)
210 shell.call("git", "fetch", "-q", "scripts")
211 self.user_commit = shell.eval("git", "rev-parse", "HEAD")
212 self.next_commit = shell.eval("git", "rev-parse", self.version)
213 self.mergeSaveState()
215 def mergePreCommit(self):
216 message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
218 message += "\nPre-commit-by: " + util.get_operator_git()
219 except util.NoOperatorInfo:
222 shell.call("git", "commit", "-a", "-m", message)
223 except shell.CallError:
224 logging.info("No changes detected")
225 def mergeClone(self):
226 # If /dev/shm exists, it's a tmpfs and we can use it
227 # to do a fast git merge. Don't forget to move it to
229 if not self.options.dry_run and not self.options.debug:
230 self.use_shm = os.path.exists("/dev/shm")
232 dir = "/dev/shm/wizard"
233 if not os.path.exists(dir):
239 self.temp_dir = tempfile.mkdtemp(prefix="wizard", dir=dir)
240 self.temp_wc_dir = os.path.join(self.temp_dir, "repo")
241 logging.info("Using temporary directory: " + self.temp_wc_dir)
242 shell.call("git", "clone", "-q", "--shared", ".", self.temp_wc_dir)
243 def mergeSaveState(self):
244 """Save variables so that ``--continue`` will work."""
245 # yeah yeah no trailing newline whatever
246 open(".git/WIZARD_UPGRADE_VERSION", "w").write(self.version)
247 open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (self.user_commit, self.next_commit))
248 open(".git/WIZARD_SIZE", "w").write(str(scripts.get_disk_usage()))
249 if self.options.log_file:
250 open(".git/WIZARD_LOG_FILE", "w").write(self.options.log_file)
251 def mergePerform(self):
252 def prepare_config():
253 self.wc.prepareConfig()
254 shell.call("git", "add", ".")
255 def resolve_conflicts():
256 return self.wc.resolveConflicts()
257 shell.call("git", "config", "merge.conflictstyle", "diff3")
259 if self.options.rr_cache is None:
260 self.options.rr_cache = os.path.join(self.prod.location, ".git", "rr-cache")
261 if not os.path.exists(self.options.rr_cache):
262 os.mkdir(self.options.rr_cache)
263 os.symlink(self.options.rr_cache, os.path.join(self.wc.location, ".git", "rr-cache"))
264 shell.call("git", "config", "rerere.enabled", "true")
266 merge.merge(self.wc.app_version.scripts_tag, self.version,
267 prepare_config, resolve_conflicts)
268 except merge.MergeError:
272 for line in shell.eval("git", "ls-files", "--unmerged").splitlines():
273 files.add(line.split(None, 3)[-1])
274 conflicts = len(files)
275 # XXX: this is kind of fiddly; note that temp_dir still points at the OLD
276 # location after this code.
277 self.temp_wc_dir = mv_shm_to_tmp(os.getcwd(), self.use_shm)
278 self.wc.location = self.temp_wc_dir
279 os.chdir(self.temp_wc_dir)
280 open(os.path.join(self.prod.location, ".scripts/pending"), "w").write(self.temp_wc_dir)
281 if self.options.non_interactive:
282 print "%d %s" % (conflicts, self.temp_wc_dir)
285 user_shell = os.getenv("SHELL")
286 if not user_shell: user_shell = "/bin/bash"
287 # XXX: scripts specific hack, since mbash doesn't respect the current working directory
288 # When the revolution comes (i.e. $ATHENA_HOMEDIR/Scripts is your Scripts home
289 # directory) this isn't strictly necessary, but we'll probably need to support
290 # web_scripts directories ad infinitum.
291 if user_shell == "/usr/local/bin/mbash": user_shell = "/bin/bash"
294 print "ERROR: The merge failed with %d conflicts in these files:" % conflicts
296 for file in sorted(files):
299 print "Please resolve these conflicts (edit and then `git add`), and"
300 print "then type 'exit'. You will now be dropped into a shell whose working"
301 print "directory is %s" % self.temp_wc_dir
303 shell.call(user_shell, "-i", interactive=True)
304 except shell.CallError as e:
305 logging.warning("Shell returned non-zero exit code %d" % e.code)
306 if shell.eval("git", "ls-files", "--unmerged").strip():
308 print "WARNING: There are still unmerged files."
309 out = raw_input("Continue editing? [y/N]: ")
310 if out == "y" or out == "Y":
313 print "Aborting. The conflicted working copy can be found at:"
315 print " %s" % self.temp_wc_dir
317 print "and you can resume the upgrade process by running in that directory:"
319 print " wizard upgrade --continue"
323 def postflight(self):
324 with util.ChangeDirectory(self.temp_wc_dir):
325 if shell.eval("git", "ls-files", "-u").strip():
326 raise UnmergedChangesError
327 shell.call("git", "commit", "--allow-empty", "-am", "throw-away commit")
328 self.wc.parametrize(self.prod)
329 shell.call("git", "add", ".")
330 message = self.postflightCommitMessage()
331 new_tree = shell.eval("git", "write-tree")
332 final_commit = shell.eval("git", "commit-tree", new_tree,
333 "-p", self.user_commit, "-p", self.next_commit, input=message, log=True)
334 # a master branch may not necessarily exist if the user
335 # was manually installed to an earlier version
337 shell.call("git", "checkout", "-q", "-b", "master", "--")
338 except shell.CallError:
339 shell.call("git", "checkout", "-q", "master", "--")
340 shell.call("git", "reset", "-q", "--hard", final_commit)
341 # This is a quick sanity check to make sure we didn't completely
343 self.wc.invalidateCache()
344 self.wc.verifyVersion()
345 def postflightCommitMessage(self):
346 message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), self.version, util.get_git_footer())
348 message += "\nUpgraded-by: " + util.get_operator_git()
349 except util.NoOperatorInfo:
354 # Ok, now we have to do a crazy complicated dance to see if we're
355 # going to have enough quota to finish what we need
356 pre_size = int(open(os.path.join(self.temp_wc_dir, ".git/WIZARD_SIZE"), "r").read())
357 post_size = scripts.get_disk_usage(self.temp_wc_dir)
358 backup = self.prod.backup(self.options)
359 kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
360 if kib_limit is not None and (kib_limit - kib_usage) - (post_size - pre_size) / 1024 < kib_buffer:
361 shutil.rmtree(os.path.join(".scripts/backups", shell.eval("wizard", "restore").splitlines()[0]))
365 def upgrade(self, backup):
366 # XXX: frob .htaccess to make site inaccessible
367 with util.IgnoreKeyboardInterrupts():
368 with util.LockDirectory(".scripts-upgrade-lock"):
369 shell.call("git", "fetch", "--tags")
370 # git merge (which performs a fast forward)
371 shell.call("git", "pull", "-q", self.temp_wc_dir, "master")
372 version_obj = distutils.version.LooseVersion(self.version.partition('-')[2])
375 self.prod.upgrade(version_obj, self.options)
376 self.prod.verifyWeb()
377 except app.UpgradeFailure:
378 logging.warning("Upgrade failed: rolling back")
379 self.upgradeRollback(backup)
381 except deploy.WebVerificationError as e:
382 logging.warning("Web verification failed: rolling back")
383 self.upgradeRollback(backup)
384 raise app.UpgradeVerificationFailure()
385 # XXX: frob .htaccess to make site accessible
386 # to do this, check if .htaccess changed, first. Upgrade
387 # process might have frobbed it. Don't be
388 # particularly worried if the segment disappeared
389 def upgradeRollback(self, backup):
390 # You don't want d.restore() because it doesn't perform
391 # the file level backup
392 shell.call("wizard", "restore", backup)
394 self.prod.verifyWeb()
395 except deploy.WebVerificationError:
396 logging.critical("Web verification failed after rollback")
400 def mv_shm_to_tmp(curdir, use_shm):
401 if not use_shm: return curdir
402 # Keeping all of our autoinstalls in shared memory is
403 # a recipe for disaster, so let's move them to slightly
404 # less volatile storage (a temporary directory)
405 os.chdir(tempfile.gettempdir())
406 newdir = tempfile.mkdtemp(prefix="wizard")
407 # shutil, not os; at least on Ubuntu os.move fails
408 # with "[Errno 18] Invalid cross-device link"
409 shutil.move(curdir, newdir)
410 shutil.rmtree(os.path.dirname(curdir))
411 curdir = os.path.join(newdir, "repo")
414 def parse_args(argv, baton):
415 usage = """usage: %prog upgrade [ARGS] [DIR]
417 Upgrades an autoinstall to the latest version. This involves
418 updating files and running .scripts/update. If the merge fails,
419 this program will write the number of conflicts and the directory
420 of the conflicted working tree to stdout, separated by a space."""
421 parser = command.WizardOptionParser(usage)
422 parser.add_option("--dry-run", dest="dry_run", action="store_true",
423 default=False, help="Prints would would be run without changing anything")
424 # notice trailing underscore
425 parser.add_option("--continue", dest="continue_", action="store_true",
426 default=False, help="Continues an upgrade that has had its merge manually "
427 "resolved using the current working directory as the resolved copy.")
428 parser.add_option("--force", dest="force", action="store_true",
429 default=False, help="Force running upgrade even if it's already at latest version.")
430 parser.add_option("--non-interactive", dest="non_interactive", action="store_true",
431 default=False, help="Don't drop to shell in event of conflict.")
432 parser.add_option("--rr-cache", dest="rr_cache", metavar="PATH",
433 default=None, help="Use this folder to reuse recorded merge resolutions. Defaults to"
434 "your production copy's rr-cache, if it exists.")
435 baton.push(parser, "srv_path")
436 options, args = parser.parse_all(argv)
438 parser.error("too many arguments")
441 class Error(command.Error):
442 """Base exception for all exceptions raised by upgrade"""
445 class QuotaTooLow(Error):
449 ERROR: The locker quota was too low to complete the autoinstall
453 class AlreadyUpgraded(Error):
458 ERROR: This autoinstall is already at the latest version."""
460 class MergeFailed(Error):
465 ERROR: Merge failed. Above is the temporary directory that
466 the conflicted merge is in: resolve the merge by cd'ing to the
467 temporary directory, finding conflicted files with `git status`,
468 resolving the files, adding them using `git add` and then
469 running `wizard upgrade --continue`."""
471 class LocalChangesError(Error):
475 ERROR: Local changes occurred in the install while the merge was
476 being processed so that a pull would not result in a fast-forward.
477 The best way to resolve this is probably to attempt an upgrade again,
478 with git rerere to remember merge resolutions (XXX: not sure if
479 this actually works)."""
481 class UnmergedChangesError(Error):
485 ERROR: You attempted to continue an upgrade, but there were
486 still local unmerged changes in your working copy. Please resolve
487 them all and try again."""
489 class BlacklistedError(Error):
490 #: Reason why the autoinstall was blacklisted
492 exitcode = errno_blacklisted
493 def __init__(self, reason):
498 ERROR: This autoinstall was manually blacklisted against errors;
499 if the user has not been notified of this, please send them
502 The reason was: %s""" % self.reason
504 class CannotResumeError(Error):
508 ERROR: We cannot resume the upgrade process; either this working
509 copy is missing essential metadata, or you've attempt to continue
510 from a production copy that does not have any pending upgrades.