]> scripts.mit.edu Git - wizard.git/blob - wizard/command/upgrade.py
Rewrite merge functionality into its own module.
[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, merge, 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         # 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         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()
158         self.prod.verify()
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
171             if reason:
172                 print reason
173                 raise BlacklistedError(reason)
174             else:
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")
183             sys.exit(2)
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:
187             raise QuotaTooLow
188
189     def merge(self):
190         if not self.options.dry_run:
191             self.mergePreCommit()
192         self.mergeClone()
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()
201             self.mergePerform()
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())
204         try:
205             message += "\nPre-commit-by: " + util.get_operator_git()
206         except util.NoOperatorInfo:
207             pass
208         try:
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
215         # /tmp if it fails.
216         if not self.options.dry_run and not self.options.debug:
217             self.use_shm = os.path.exists("/dev/shm")
218         if self.use_shm:
219             dir = "/dev/shm/wizard"
220             if not os.path.exists(dir):
221                 os.mkdir(dir)
222                 # XXX: race
223                 os.chmod(dir, 0o777)
224         else:
225             dir = None
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")
246         try:
247             merge.merge(self.wc.app_version.scripts_tag, self.version,
248                         prepare_config, resolve_conflicts)
249         except merge.MergeError:
250             self.mergeFail()
251     def mergeFail(self):
252         files = set()
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)
264             raise MergeFailed
265         else:
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"
273             while 1:
274                 print
275                 print "ERROR: The merge failed with %d conflicts in these files:" % conflicts
276                 print
277                 for file in sorted(files):
278                     print "  * %s" % file
279                 print
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
283                 try:
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():
288                     print
289                     print "WARNING: There are still unmerged files."
290                     out = raw_input("Continue editing? [y/N]: ")
291                     if out == "y" or out == "Y":
292                         continue
293                     else:
294                         print "Aborting.  The conflicted working copy can be found at:"
295                         print
296                         print "    %s" % self.temp_wc_dir
297                         print
298                         print "and you can resume the upgrade process by running in that directory:"
299                         print
300                         print "    wizard upgrade --continue"
301                         sys.exit(1)
302                 break
303
304     def postflight(self):
305         with util.ChangeDirectory(self.temp_wc_dir):
306             try:
307                 shell.call("git", "status")
308             except shell.CallError:
309                 pass
310             else:
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
320             try:
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
326             # mess up the merge
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())
331         try:
332             message += "\nUpgraded-by: " + util.get_operator_git()
333         except util.NoOperatorInfo:
334             pass
335         return message
336
337     def backup(self):
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]))
346             raise QuotaTooLow
347         return backup
348
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])
357                 try:
358                     # run update script
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)
364                     raise
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)
377         try:
378             self.prod.verifyWeb()
379         except deploy.WebVerificationError:
380             logging.critical("Web verification failed after rollback")
381
382 # utility functions
383
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")
396     return curdir
397
398 def parse_args(argv, baton):
399     usage = """usage: %prog upgrade [ARGS] [DIR]
400
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)
418     if len(args) > 1:
419         parser.error("too many arguments")
420     return options, args
421
422 class Error(command.Error):
423     """Base exception for all exceptions raised by upgrade"""
424     pass
425
426 class QuotaTooLow(Error):
427     def __str__(self):
428         return """
429
430 ERROR: The locker quota was too low to complete the autoinstall
431 upgrade.
432 """
433
434 class AlreadyUpgraded(Error):
435     quiet = True
436     def __str__(self):
437         return """
438
439 ERROR: This autoinstall is already at the latest version."""
440
441 class MergeFailed(Error):
442     quiet = True
443     def __str__(self):
444         return """
445
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`."""
451
452 class LocalChangesError(Error):
453     def __str__(self):
454         return """
455
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)."""
461
462 class BlacklistedError(Error):
463     #: Reason why the autoinstall was blacklisted
464     reason = None
465     exitcode = errno_blacklisted
466     def __init__(self, reason):
467         self.reason = reason
468     def __str__(self):
469         return """
470
471 ERROR: This autoinstall was manually blacklisted against errors;
472 if the user has not been notified of this, please send them
473 mail.
474
475 The reason was: %s""" % self.reason
476
477 class CannotResumeError(Error):
478     def __str__(self):
479         return """
480
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.
484 """