2 import distutils.version
5 import logging.handlers
11 from wizard import app, command, deploy, merge, scripts, shell, util
13 kib_buffer = 1024 * 30 # 30 MiB we will always leave available
14 errno_blacklisted = 64
16 def main(argv, baton):
17 options, args = parse_args(argv, baton)
22 shell.drop_priviledges(dir, options.log_file)
24 upgrade = Upgrade(options)
26 if not options.non_interactive:
27 print "Upgrade complete"
29 class Upgrade(object):
31 Represents the algorithm for upgrading an application. This is in
32 a class and not a function because it's a multi-step process that
33 requires state betweens steps. Steps are represented as methods
37 #: Version of application we are upgrading to, i.e. the latest version.
38 version = None # XXX: This is a string... I'm not convinced it should be
39 #: String commit ID of the user's latest wc; i.e. "ours"
41 #: String commit ID of the latest, greatest scripts version; i.e. "theirs"
43 #: The temporary directory that the system gave us; may stay as ``None``
44 #: if we don't ever make ourselves a temporary directory (e.g. ``--continue``).
45 #: While we should clean this up if it is set to something, it may
46 #: not correspond to anything useful.
48 #: The temporary directory containing our working copy for merging
50 #: We place the temporary repositories inside a tmpfs while merging;
51 #: this makes merges not disk-bound and affords a modest speed increase.
52 #: If you are running ``--continue``, this is guaranteed to be ``False``.
54 #: Upstream repository to use. This does not need to be saved.
57 #: Instance of :class:`wizard.deploy.WorkingCopy` for this upgrade
59 #: Instance of :class:`wizard.deploy.ProductionCopy` for this upgrade
62 #: Options object that the installer was called with
65 def __init__(self, options):
67 self.user_commit = None
68 self.next_commit = None
70 self.temp_wc_dir = None
71 self.use_shm = False # False until proven otherwise.
74 self.options = options
76 def execute(self, dir):
78 Executes an upgrade. This is the entry-point.
80 with util.ChangeDirectory(dir):
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
153 self.prod = deploy.ProductionCopy(".")
154 self.repo = self.prod.application.repository(options.srv_path)
155 # XXX: put this in Application
156 self.version = shell.eval("git", "--git-dir="+self.repo, "describe", "--tags", "master")
157 self.preflightBlacklist()
159 self.prod.verifyTag(options.srv_path)
160 self.prod.verifyGit(options.srv_path)
161 self.prod.verifyConfigured()
162 shell.call("git", "fetch", "--tags") # XXX: hack since some installs have stale tags
163 self.prod.verifyVersion()
164 self.prod.verifyWeb()
165 self.preflightAlreadyUpgraded()
166 self.preflightQuota()
167 def preflightBlacklist(self):
168 if os.path.exists(".scripts/blacklisted"):
169 reason = open(".scripts/blacklisted").read()
170 # ignore blank blacklisted files
173 raise BlacklistedError(reason)
175 logging.warning("Application was blacklisted, but no reason was found");
176 def preflightAlreadyUpgraded(self):
177 if self.version == self.prod.app_version.scripts_tag and not self.options.force:
178 # don't log this error; we need to have the traceback line
179 # so that the parsing code can catch it
180 # XXX: maybe we should build this in as a flag to add
181 # to exceptions w/ our exception handler
182 sys.stderr.write("Traceback:\n (n/a)\nAlreadyUpgraded\n")
184 def preflightQuota(self):
185 kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
186 if kib_limit is not None and (kib_limit - kib_usage) < kib_buffer:
190 if not self.options.dry_run:
191 self.mergePreCommit()
193 logging.debug("Temporary WC dir is %s", self.temp_wc_dir)
194 with util.ChangeDirectory(self.temp_wc_dir):
195 self.wc = deploy.WorkingCopy(".")
196 shell.call("git", "remote", "add", "scripts", self.repo)
197 shell.call("git", "fetch", "-q", "scripts")
198 self.user_commit = shell.eval("git", "rev-parse", "HEAD")
199 self.next_commit = shell.eval("git", "rev-parse", self.version)
200 self.mergeSaveState()
202 def mergePreCommit(self):
203 message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
205 message += "\nPre-commit-by: " + util.get_operator_git()
206 except util.NoOperatorInfo:
209 shell.call("git", "commit", "-a", "-m", message)
210 except shell.CallError:
211 logging.info("No changes detected")
212 def mergeClone(self):
213 # If /dev/shm exists, it's a tmpfs and we can use it
214 # to do a fast git merge. Don't forget to move it to
216 if not self.options.dry_run and not self.options.debug:
217 self.use_shm = os.path.exists("/dev/shm")
219 dir = "/dev/shm/wizard"
220 if not os.path.exists(dir):
226 self.temp_dir = tempfile.mkdtemp(prefix="wizard", dir=dir)
227 self.temp_wc_dir = os.path.join(self.temp_dir, "repo")
228 logging.info("Using temporary directory: " + self.temp_wc_dir)
229 shell.call("git", "clone", "-q", "--shared", ".", self.temp_wc_dir)
230 def mergeSaveState(self):
231 """Save variables so that ``--continue`` will work."""
232 # yeah yeah no trailing newline whatever
233 open(".git/WIZARD_UPGRADE_VERSION", "w").write(self.version)
234 open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (self.user_commit, self.next_commit))
235 open(".git/WIZARD_SIZE", "w").write(str(scripts.get_disk_usage()))
236 if self.options.log_file:
237 open(".git/WIZARD_LOG_FILE", "w").write(self.options.log_file)
238 def mergePerform(self):
239 def prepare_config():
240 self.wc.prepareConfig()
241 shell.call("git", "add", ".")
242 def resolve_conflicts():
243 return self.wc.resolveConflicts()
244 shell.call("git", "config", "merge.conflictstyle", "diff3")
245 shell.call("git", "config", "rerere.enabled", "true")
247 merge.merge(self.wc.app_version.scripts_tag, self.version,
248 prepare_config, resolve_conflicts)
249 except merge.MergeError:
253 for line in shell.eval("git", "ls-files", "--unmerged").splitlines():
254 files.add(line.split(None, 3)[-1])
255 conflicts = len(files)
256 # XXX: this is kind of fiddly; note that temp_dir still points at the OLD
257 # location after this code.
258 self.temp_wc_dir = mv_shm_to_tmp(os.getcwd(), self.use_shm)
259 self.wc.location = self.temp_wc_dir
260 os.chdir(self.temp_wc_dir)
261 open(os.path.join(self.prod.location, ".scripts/pending"), "w").write(self.temp_wc_dir)
262 if self.options.non_interactive:
263 print "%d %s" % (conflicts, self.temp_wc_dir)
266 user_shell = os.getenv("SHELL")
267 if not user_shell: user_shell = "/bin/bash"
268 # XXX: scripts specific hack, since mbash doesn't respect the current working directory
269 # When the revolution comes (i.e. $ATHENA_HOMEDIR/Scripts is your Scripts home
270 # directory) this isn't strictly necessary, but we'll probably need to support
271 # web_scripts directories ad infinitum.
272 if user_shell == "/usr/local/bin/mbash": user_shell = "/bin/bash"
275 print "ERROR: The merge failed with %d conflicts in these files:" % conflicts
277 for file in sorted(files):
280 print "Please resolve these conflicts (edit and then `git add`), and"
281 print "then type 'exit'. You will now be dropped into a shell whose working"
282 print "directory is %s" % self.temp_wc_dir
284 shell.call(user_shell, "-i", interactive=True)
285 except shell.CallError as e:
286 logging.warning("Shell returned non-zero exit code %d" % e.code)
287 if shell.eval("git", "ls-files", "--unmerged").strip():
289 print "WARNING: There are still unmerged files."
290 out = raw_input("Continue editing? [y/N]: ")
291 if out == "y" or out == "Y":
294 print "Aborting. The conflicted working copy can be found at:"
296 print " %s" % self.temp_wc_dir
298 print "and you can resume the upgrade process by running in that directory:"
300 print " wizard upgrade --continue"
304 def postflight(self):
305 with util.ChangeDirectory(self.temp_wc_dir):
307 shell.call("git", "status")
308 except shell.CallError:
311 shell.call("git", "commit", "--allow-empty", "-am", "throw-away commit")
312 self.wc.parametrize(self.prod)
313 shell.call("git", "add", ".")
314 message = self.postflightCommitMessage()
315 new_tree = shell.eval("git", "write-tree")
316 final_commit = shell.eval("git", "commit-tree", new_tree,
317 "-p", self.user_commit, "-p", self.next_commit, input=message, log=True)
318 # a master branch may not necessarily exist if the user
319 # was manually installed to an earlier version
321 shell.call("git", "checkout", "-q", "-b", "master", "--")
322 except shell.CallError:
323 shell.call("git", "checkout", "-q", "master", "--")
324 shell.call("git", "reset", "-q", "--hard", final_commit)
325 # This is a quick sanity check to make sure we didn't completely
327 self.wc.invalidateCache()
328 self.wc.verifyVersion()
329 def postflightCommitMessage(self):
330 message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), self.version, util.get_git_footer())
332 message += "\nUpgraded-by: " + util.get_operator_git()
333 except util.NoOperatorInfo:
338 # Ok, now we have to do a crazy complicated dance to see if we're
339 # going to have enough quota to finish what we need
340 pre_size = int(open(os.path.join(self.temp_wc_dir, ".git/WIZARD_SIZE"), "r").read())
341 post_size = scripts.get_disk_usage(self.temp_wc_dir)
342 backup = self.prod.backup(self.options)
343 kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
344 if kib_limit is not None and (kib_limit - kib_usage) - (post_size - pre_size) / 1024 < kib_buffer:
345 shutil.rmtree(os.path.join(".scripts/backups", shell.eval("wizard", "restore").splitlines()[0]))
349 def upgrade(self, backup):
350 # XXX: frob .htaccess to make site inaccessible
351 with util.IgnoreKeyboardInterrupts():
352 with util.LockDirectory(".scripts-upgrade-lock"):
353 shell.call("git", "fetch", "--tags")
354 # git merge (which performs a fast forward)
355 shell.call("git", "pull", "-q", self.temp_wc_dir, "master")
356 version_obj = distutils.version.LooseVersion(self.version.partition('-')[2])
359 self.prod.upgrade(version_obj, self.options)
360 self.prod.verifyWeb()
361 except app.UpgradeFailure:
362 logging.warning("Upgrade failed: rolling back")
363 self.upgradeRollback(backup)
365 except deploy.WebVerificationError as e:
366 logging.warning("Web verification failed: rolling back")
367 self.upgradeRollback(backup)
368 raise app.UpgradeVerificationFailure()
369 # XXX: frob .htaccess to make site accessible
370 # to do this, check if .htaccess changed, first. Upgrade
371 # process might have frobbed it. Don't be
372 # particularly worried if the segment disappeared
373 def upgradeRollback(self, backup):
374 # You don't want d.restore() because it doesn't perform
375 # the file level backup
376 shell.call("wizard", "restore", backup)
378 self.prod.verifyWeb()
379 except deploy.WebVerificationError:
380 logging.critical("Web verification failed after rollback")
384 def mv_shm_to_tmp(curdir, use_shm):
385 if not use_shm: return curdir
386 # Keeping all of our autoinstalls in shared memory is
387 # a recipe for disaster, so let's move them to slightly
388 # less volatile storage (a temporary directory)
389 os.chdir(tempfile.gettempdir())
390 newdir = tempfile.mkdtemp(prefix="wizard")
391 # shutil, not os; at least on Ubuntu os.move fails
392 # with "[Errno 18] Invalid cross-device link"
393 shutil.move(curdir, newdir)
394 shutil.rmtree(os.path.dirname(curdir))
395 curdir = os.path.join(newdir, "repo")
398 def parse_args(argv, baton):
399 usage = """usage: %prog upgrade [ARGS] [DIR]
401 Upgrades an autoinstall to the latest version. This involves
402 updating files and running .scripts/update. If the merge fails,
403 this program will write the number of conflicts and the directory
404 of the conflicted working tree to stdout, separated by a space."""
405 parser = command.WizardOptionParser(usage)
406 parser.add_option("--dry-run", dest="dry_run", action="store_true",
407 default=False, help="Prints would would be run without changing anything")
408 # notice trailing underscore
409 parser.add_option("--continue", dest="continue_", action="store_true",
410 default=False, help="Continues an upgrade that has had its merge manually "
411 "resolved using the current working directory as the resolved copy.")
412 parser.add_option("--force", dest="force", action="store_true",
413 default=False, help="Force running upgrade even if it's already at latest version.")
414 parser.add_option("--non-interactive", dest="non_interactive", action="store_true",
415 default=False, help="Don't drop to shell in event of conflict.")
416 baton.push(parser, "srv_path")
417 options, args = parser.parse_all(argv)
419 parser.error("too many arguments")
422 class Error(command.Error):
423 """Base exception for all exceptions raised by upgrade"""
426 class QuotaTooLow(Error):
430 ERROR: The locker quota was too low to complete the autoinstall
434 class AlreadyUpgraded(Error):
439 ERROR: This autoinstall is already at the latest version."""
441 class MergeFailed(Error):
446 ERROR: Merge failed. Above is the temporary directory that
447 the conflicted merge is in: resolve the merge by cd'ing to the
448 temporary directory, finding conflicted files with `git status`,
449 resolving the files, adding them using `git add` and then
450 running `wizard upgrade --continue`."""
452 class LocalChangesError(Error):
456 ERROR: Local changes occurred in the install while the merge was
457 being processed so that a pull would not result in a fast-forward.
458 The best way to resolve this is probably to attempt an upgrade again,
459 with git rerere to remember merge resolutions (XXX: not sure if
460 this actually works)."""
462 class BlacklistedError(Error):
463 #: Reason why the autoinstall was blacklisted
465 exitcode = errno_blacklisted
466 def __init__(self, reason):
471 ERROR: This autoinstall was manually blacklisted against errors;
472 if the user has not been notified of this, please send them
475 The reason was: %s""" % self.reason
477 class CannotResumeError(Error):
481 ERROR: We cannot resume the upgrade process; either this working
482 copy is missing essential metadata, or you've attempt to continue
483 from a production copy that does not have any pending upgrades.