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