]> scripts.mit.edu Git - wizard.git/blob - wizard/command/upgrade.py
Nicer errors if not in autoinstall directory.
[wizard.git] / wizard / command / upgrade.py
1 import sys
2 import distutils.version
3 import os
4 import os.path
5 import shutil
6 import logging.handlers
7 import tempfile
8 import itertools
9 import time
10 import errno
11
12 from wizard import app, command, deploy, merge, scripts, shell, util
13
14 kib_buffer = 1024 * 30 # 30 MiB we will always leave available
15 errno_blacklisted = 64
16
17 def main(argv, baton):
18     options, args = parse_args(argv, baton)
19     dir = os.path.abspath(args[0]) if args else os.getcwd()
20     os.chdir(dir)
21     shell.drop_priviledges(dir, options.log_file)
22     util.set_git_env()
23     upgrade = Upgrade(options)
24     upgrade.execute(dir)
25     if not options.non_interactive:
26         print "Upgrade complete"
27
28 class Upgrade(object):
29     """
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
33     in this object.
34     """
35
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"
39     user_commit = None
40     #: String commit ID of the latest, greatest scripts version; i.e. "theirs"
41     next_commit = None
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.
46     temp_dir = None
47     #: The temporary directory containing our working copy for merging
48     temp_wc_dir = None
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``.
52     use_shm = None
53     #: Upstream repository to use.  This does not need to be saved.
54     repo = None
55
56     #: Instance of :class:`wizard.deploy.WorkingCopy` for this upgrade
57     wc = None
58     #: Instance of :class:`wizard.deploy.ProductionCopy` for this upgrade
59     prod = None
60
61     #: Options object that the installer was called with
62     options = None
63
64     def __init__(self, options):
65         self.version = None
66         self.user_commit = None
67         self.next_commit = None
68         self.temp_dir = None
69         self.temp_wc_dir = None
70         self.use_shm = False # False until proven otherwise.
71         self.wc = None
72         self.prod = None
73         self.options = options
74
75     def execute(self, dir):
76         """
77         Executes an upgrade.  This is the entry-point.  This expects
78         that it's current working directory is the same as ``dir``.
79         """
80         assert os.path.abspath(dir) == os.getcwd()
81         try:
82             if self.options.continue_:
83                 logging.info("Continuing upgrade...")
84                 self.resume()
85             else:
86                 logging.info("Upgrading %s" % os.getcwd())
87                 self.preflight()
88                 self.merge()
89             self.postflight()
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)
93                 return
94             backup = self.backup()
95             self.upgrade(backup)
96         finally:
97             if self.use_shm and self.temp_dir and os.path.exists(self.temp_dir):
98                 shutil.rmtree(self.temp_dir)
99
100     def resume(self):
101         """
102         In the event of a ``--continue`` flag, we have to restore state and
103         perform some sanity checks.
104         """
105         self.resumeChdir()
106         self.resumeState()
107         self.resumeLogging()
108         util.chdir(shell.eval("git", "config", "remote.origin.url"))
109         self.resumeProd()
110     def resumeChdir(self):
111         """
112         If we called ``--continue`` inside a production copy,  check if
113         :file:`.scripts/pending` exists and change to that directory if so.
114         """
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)
118             os.chdir(newdir)
119     def resumeState(self):
120         self.temp_wc_dir = os.getcwd()
121         self.wc = deploy.WorkingCopy(".")
122         try:
123             self.user_commit, self.next_commit = open(".git/WIZARD_PARENTS", "r").read().split()
124             self.version = open(".git/WIZARD_UPGRADE_VERSION", "r").read()
125         except IOError as e:
126             if e.errno == errno.ENOENT:
127                 raise CannotResumeError()
128             else:
129                 raise
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(".")
138         try:
139             shell.call("git", "status")
140             raise LocalChangesError()
141         except shell.CallError:
142             pass
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)
146
147     def preflight(self):
148         """
149         Make sure that a number of pre-upgrade invariants are met before
150         attempting anything.
151         """
152         options = self.options
153         while True:
154             self.prod = deploy.ProductionCopy(".")
155             self.prod.verify()
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()
163             shell.call("git", "fetch", "--tags") # XXX: hack since some installs have stale tags
164             try:
165                 self.prod.verifyVersion()
166             except deploy.VersionMismatchError as e:
167                 # XXX: kind of hacky, mainly it does change the Git working copy
168                 # state (although /very/ non-destructively)
169                 shell.call("git", "merge", "--strategy=ours", self.prod.application.makeVersion(str(e.real_version)).scripts_tag)
170                 continue
171             break
172         self.prod.verifyWeb()
173         self.preflightAlreadyUpgraded()
174         self.preflightQuota()
175     def preflightBlacklist(self):
176         if os.path.exists(".scripts/blacklisted"):
177             reason = open(".scripts/blacklisted").read()
178             # ignore blank blacklisted files
179             if reason:
180                 print reason
181                 raise BlacklistedError(reason)
182             else:
183                 logging.warning("Application was blacklisted, but no reason was found");
184     def preflightAlreadyUpgraded(self):
185         if self.version == self.prod.app_version.scripts_tag and not self.options.force:
186             # don't log this error; we need to have the traceback line
187             # so that the parsing code can catch it
188             # XXX: maybe we should build this in as a flag to add
189             # to exceptions w/ our exception handler
190             sys.stderr.write("Traceback:\n  (n/a)\nAlreadyUpgraded\n")
191             sys.exit(2)
192     def preflightQuota(self):
193         kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
194         if kib_limit is not None and (kib_limit - kib_usage) < kib_buffer:
195             raise QuotaTooLow
196
197     def merge(self):
198         if not self.options.dry_run:
199             self.mergePreCommit()
200         self.mergeClone()
201         logging.debug("Temporary WC dir is %s", self.temp_wc_dir)
202         with util.ChangeDirectory(self.temp_wc_dir):
203             self.wc = deploy.WorkingCopy(".")
204             shell.call("git", "remote", "add", "scripts", self.repo)
205             shell.call("git", "fetch", "-q", "scripts")
206             self.user_commit = shell.eval("git", "rev-parse", "HEAD")
207             self.next_commit = shell.eval("git", "rev-parse", self.version)
208             self.mergeSaveState()
209             self.mergePerform()
210     def mergePreCommit(self):
211         message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
212         try:
213             message += "\nPre-commit-by: " + util.get_operator_git()
214         except util.NoOperatorInfo:
215             pass
216         try:
217             shell.call("git", "commit", "-a", "-m", message)
218         except shell.CallError:
219             logging.info("No changes detected")
220     def mergeClone(self):
221         # If /dev/shm exists, it's a tmpfs and we can use it
222         # to do a fast git merge. Don't forget to move it to
223         # /tmp if it fails.
224         if not self.options.dry_run and not self.options.debug:
225             self.use_shm = os.path.exists("/dev/shm")
226         if self.use_shm:
227             dir = "/dev/shm/wizard"
228             if not os.path.exists(dir):
229                 os.mkdir(dir)
230                 # XXX: race
231                 os.chmod(dir, 0o777)
232         else:
233             dir = None
234         self.temp_dir = tempfile.mkdtemp(prefix="wizard", dir=dir)
235         self.temp_wc_dir = os.path.join(self.temp_dir, "repo")
236         logging.info("Using temporary directory: " + self.temp_wc_dir)
237         shell.call("git", "clone", "-q", "--shared", ".", self.temp_wc_dir)
238     def mergeSaveState(self):
239         """Save variables so that ``--continue`` will work."""
240         # yeah yeah no trailing newline whatever
241         open(".git/WIZARD_UPGRADE_VERSION", "w").write(self.version)
242         open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (self.user_commit, self.next_commit))
243         open(".git/WIZARD_SIZE", "w").write(str(scripts.get_disk_usage()))
244         if self.options.log_file:
245             open(".git/WIZARD_LOG_FILE", "w").write(self.options.log_file)
246     def mergePerform(self):
247         def prepare_config():
248             self.wc.prepareConfig()
249             shell.call("git", "add", ".")
250         def resolve_conflicts():
251             return self.wc.resolveConflicts()
252         shell.call("git", "config", "merge.conflictstyle", "diff3")
253         # setup rerere
254         if self.options.rr_cache is None:
255             self.options.rr_cache = os.path.join(self.prod.location, ".git", "rr-cache")
256         if not os.path.exists(self.options.rr_cache):
257             os.mkdir(self.options.rr_cache)
258         os.symlink(self.options.rr_cache, os.path.join(self.wc.location, ".git", "rr-cache"))
259         shell.call("git", "config", "rerere.enabled", "true")
260         try:
261             merge.merge(self.wc.app_version.scripts_tag, self.version,
262                         prepare_config, resolve_conflicts)
263         except merge.MergeError:
264             self.mergeFail()
265     def mergeFail(self):
266         files = set()
267         for line in shell.eval("git", "ls-files", "--unmerged").splitlines():
268             files.add(line.split(None, 3)[-1])
269         conflicts = len(files)
270         # XXX: this is kind of fiddly; note that temp_dir still points at the OLD
271         # location after this code.
272         self.temp_wc_dir = mv_shm_to_tmp(os.getcwd(), self.use_shm)
273         self.wc.location = self.temp_wc_dir
274         os.chdir(self.temp_wc_dir)
275         open(os.path.join(self.prod.location, ".scripts/pending"), "w").write(self.temp_wc_dir)
276         if self.options.non_interactive:
277             print "%d %s" % (conflicts, self.temp_wc_dir)
278             raise MergeFailed
279         else:
280             user_shell = os.getenv("SHELL")
281             if not user_shell: user_shell = "/bin/bash"
282             # XXX: scripts specific hack, since mbash doesn't respect the current working directory
283             # When the revolution comes (i.e. $ATHENA_HOMEDIR/Scripts is your Scripts home
284             # directory) this isn't strictly necessary, but we'll probably need to support
285             # web_scripts directories ad infinitum.
286             if user_shell == "/usr/local/bin/mbash": user_shell = "/bin/bash"
287             while 1:
288                 print
289                 print "ERROR: The merge failed with %d conflicts in these files:" % conflicts
290                 print
291                 for file in sorted(files):
292                     print "  * %s" % file
293                 print
294                 print "Please resolve these conflicts (edit and then `git add`), and"
295                 print "then type 'exit'.  You will now be dropped into a shell whose working"
296                 print "directory is %s" % self.temp_wc_dir
297                 try:
298                     shell.call(user_shell, "-i", interactive=True)
299                 except shell.CallError as e:
300                     logging.warning("Shell returned non-zero exit code %d" % e.code)
301                 if shell.eval("git", "ls-files", "--unmerged").strip():
302                     print
303                     print "WARNING: There are still unmerged files."
304                     out = raw_input("Continue editing? [y/N]: ")
305                     if out == "y" or out == "Y":
306                         continue
307                     else:
308                         print "Aborting.  The conflicted working copy can be found at:"
309                         print
310                         print "    %s" % self.temp_wc_dir
311                         print
312                         print "and you can resume the upgrade process by running in that directory:"
313                         print
314                         print "    wizard upgrade --continue"
315                         sys.exit(1)
316                 break
317
318     def postflight(self):
319         with util.ChangeDirectory(self.temp_wc_dir):
320             if shell.eval("git", "ls-files", "-u").strip():
321                 raise UnmergedChangesError
322             shell.call("git", "commit", "--allow-empty", "-am", "throw-away commit")
323             self.wc.parametrize(self.prod)
324             shell.call("git", "add", ".")
325             message = self.postflightCommitMessage()
326             new_tree = shell.eval("git", "write-tree")
327             final_commit = shell.eval("git", "commit-tree", new_tree,
328                     "-p", self.user_commit, "-p", self.next_commit, input=message, log=True)
329             # a master branch may not necessarily exist if the user
330             # was manually installed to an earlier version
331             try:
332                 shell.call("git", "checkout", "-q", "-b", "master", "--")
333             except shell.CallError:
334                 shell.call("git", "checkout", "-q", "master", "--")
335             shell.call("git", "reset", "-q", "--hard", final_commit)
336             # This is a quick sanity check to make sure we didn't completely
337             # mess up the merge
338             self.wc.invalidateCache()
339             self.wc.verifyVersion()
340     def postflightCommitMessage(self):
341         message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), self.version, util.get_git_footer())
342         try:
343             message += "\nUpgraded-by: " + util.get_operator_git()
344         except util.NoOperatorInfo:
345             pass
346         return message
347
348     def backup(self):
349         # Ok, now we have to do a crazy complicated dance to see if we're
350         # going to have enough quota to finish what we need
351         pre_size = int(open(os.path.join(self.temp_wc_dir, ".git/WIZARD_SIZE"), "r").read())
352         post_size = scripts.get_disk_usage(self.temp_wc_dir)
353         backup = self.prod.backup(self.options)
354         kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
355         if kib_limit is not None and (kib_limit - kib_usage) - (post_size - pre_size) / 1024 < kib_buffer:
356             shutil.rmtree(os.path.join(".scripts/backups", shell.eval("wizard", "restore").splitlines()[0]))
357             raise QuotaTooLow
358         return backup
359
360     def upgrade(self, backup):
361         # XXX: frob .htaccess to make site inaccessible
362         with util.IgnoreKeyboardInterrupts():
363             with util.LockDirectory(".scripts-upgrade-lock"):
364                 shell.call("git", "fetch", "--tags")
365                 # git merge (which performs a fast forward)
366                 shell.call("git", "pull", "-q", self.temp_wc_dir, "master")
367                 version_obj = distutils.version.LooseVersion(self.version.partition('-')[2])
368                 try:
369                     # run update script
370                     self.prod.upgrade(version_obj, self.options)
371                     self.prod.verifyWeb()
372                 except app.UpgradeFailure:
373                     logging.warning("Upgrade failed: rolling back")
374                     self.upgradeRollback(backup)
375                     raise
376                 except deploy.WebVerificationError as e:
377                     logging.warning("Web verification failed: rolling back")
378                     self.upgradeRollback(backup)
379                     raise app.UpgradeVerificationFailure()
380         # XXX: frob .htaccess to make site accessible
381         #       to do this, check if .htaccess changed, first.  Upgrade
382         #       process might have frobbed it.  Don't be
383         #       particularly worried if the segment disappeared
384     def upgradeRollback(self, backup):
385         # You don't want d.restore() because it doesn't perform
386         # the file level backup
387         shell.call("wizard", "restore", backup)
388         try:
389             self.prod.verifyWeb()
390         except deploy.WebVerificationError:
391             logging.critical("Web verification failed after rollback")
392
393 # utility functions
394
395 def mv_shm_to_tmp(curdir, use_shm):
396     if not use_shm: return curdir
397     # Keeping all of our autoinstalls in shared memory is
398     # a recipe for disaster, so let's move them to slightly
399     # less volatile storage (a temporary directory)
400     os.chdir(tempfile.gettempdir())
401     newdir = tempfile.mkdtemp(prefix="wizard")
402     # shutil, not os; at least on Ubuntu os.move fails
403     # with "[Errno 18] Invalid cross-device link"
404     shutil.move(curdir, newdir)
405     shutil.rmtree(os.path.dirname(curdir))
406     curdir = os.path.join(newdir, "repo")
407     return curdir
408
409 def parse_args(argv, baton):
410     usage = """usage: %prog upgrade [ARGS] [DIR]
411
412 Upgrades an autoinstall to the latest version.  This involves
413 updating files and running .scripts/update.  If the merge fails,
414 this program will write the number of conflicts and the directory
415 of the conflicted working tree to stdout, separated by a space."""
416     parser = command.WizardOptionParser(usage)
417     parser.add_option("--dry-run", dest="dry_run", action="store_true",
418             default=False, help="Prints would would be run without changing anything")
419     # notice trailing underscore
420     parser.add_option("--continue", dest="continue_", action="store_true",
421             default=False, help="Continues an upgrade that has had its merge manually "
422             "resolved using the current working directory as the resolved copy.")
423     parser.add_option("--force", dest="force", action="store_true",
424             default=False, help="Force running upgrade even if it's already at latest version.")
425     parser.add_option("--non-interactive", dest="non_interactive", action="store_true",
426             default=False, help="Don't drop to shell in event of conflict.")
427     parser.add_option("--rr-cache", dest="rr_cache", metavar="PATH",
428             default=None, help="Use this folder to reuse recorded merge resolutions.  Defaults to"
429             "your production copy's rr-cache, if it exists.")
430     baton.push(parser, "srv_path")
431     options, args = parser.parse_all(argv)
432     if len(args) > 1:
433         parser.error("too many arguments")
434     return options, args
435
436 class Error(command.Error):
437     """Base exception for all exceptions raised by upgrade"""
438     pass
439
440 class QuotaTooLow(Error):
441     def __str__(self):
442         return """
443
444 ERROR: The locker quota was too low to complete the autoinstall
445 upgrade.
446 """
447
448 class AlreadyUpgraded(Error):
449     quiet = True
450     def __str__(self):
451         return """
452
453 ERROR: This autoinstall is already at the latest version."""
454
455 class MergeFailed(Error):
456     quiet = True
457     def __str__(self):
458         return """
459
460 ERROR: Merge failed.  Above is the temporary directory that
461 the conflicted merge is in: resolve the merge by cd'ing to the
462 temporary directory, finding conflicted files with `git status`,
463 resolving the files, adding them using `git add` and then
464 running `wizard upgrade --continue`."""
465
466 class LocalChangesError(Error):
467     def __str__(self):
468         return """
469
470 ERROR: Local changes occurred in the install while the merge was
471 being processed so that a pull would not result in a fast-forward.
472 The best way to resolve this is probably to attempt an upgrade again,
473 with git rerere to remember merge resolutions (XXX: not sure if
474 this actually works)."""
475
476 class UnmergedChangesError(Error):
477     def __str__(self):
478         return """
479
480 ERROR: You attempted to continue an upgrade, but there were
481 still local unmerged changes in your working copy.  Please resolve
482 them all and try again."""
483
484 class BlacklistedError(Error):
485     #: Reason why the autoinstall was blacklisted
486     reason = None
487     exitcode = errno_blacklisted
488     def __init__(self, reason):
489         self.reason = reason
490     def __str__(self):
491         return """
492
493 ERROR: This autoinstall was manually blacklisted against errors;
494 if the user has not been notified of this, please send them
495 mail.
496
497 The reason was: %s""" % self.reason
498
499 class CannotResumeError(Error):
500     def __str__(self):
501         return """
502
503 ERROR: We cannot resume the upgrade process; either this working
504 copy is missing essential metadata, or you've attempt to continue
505 from a production copy that does not have any pending upgrades.
506 """