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