]> scripts.mit.edu Git - wizard.git/blob - wizard/command/upgrade.py
Rewrite parametrize to use new parametrizeWithVars
[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         for i in range(0,2):
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.verify()
161             self.prod.verifyDatabase()
162             self.prod.verifyTag(options.srv_path)
163             self.prod.verifyGit(options.srv_path)
164             self.prod.verifyConfigured()
165             try:
166                 shell.call("git", "fetch", "--tags") # XXX: hack since some installs have stale tags
167             except shell.CallError as e:
168                 if "Disk quota exceeded" in e.stderr:
169                     raise QuotaTooLow
170                 raise
171             try:
172                 self.prod.verifyVersion()
173             except deploy.VersionMismatchError as e:
174                 # XXX: kind of hacky, mainly it does change the Git working copy
175                 # state (although /very/ non-destructively)
176                 shell.call("git", "merge", "--strategy=ours", self.prod.application.makeVersion(str(e.real_version)).scripts_tag)
177                 continue
178             break
179         else:
180             raise VersionRematchFailed
181         self.prod.verifyWeb()
182         self.preflightAlreadyUpgraded()
183         self.preflightQuota()
184     def preflightBlacklist(self):
185         if os.path.exists(".scripts/blacklisted"):
186             reason = open(".scripts/blacklisted").read()
187             # ignore blank blacklisted files
188             if reason:
189                 print reason
190                 raise BlacklistedError(reason)
191             else:
192                 logging.warning("Application was blacklisted, but no reason was found");
193     def preflightAlreadyUpgraded(self):
194         if self.version == self.prod.app_version.scripts_tag and not self.options.force:
195             # don't log this error; we need to have the traceback line
196             # so that the parsing code can catch it
197             # XXX: maybe we should build this in as a flag to add
198             # to exceptions w/ our exception handler
199             sys.stderr.write("Traceback:\n  (n/a)\nAlreadyUpgraded\n")
200             sys.exit(2)
201     def preflightQuota(self):
202         kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
203         if kib_limit is not None and (kib_limit - kib_usage) < kib_buffer:
204             raise QuotaTooLow
205
206     def merge(self):
207         if not self.options.dry_run:
208             self.mergePreCommit()
209         self.mergeClone()
210         logging.debug("Temporary WC dir is %s", self.temp_wc_dir)
211         with util.ChangeDirectory(self.temp_wc_dir):
212             self.wc = deploy.WorkingCopy(".")
213             shell.call("git", "remote", "add", "scripts", self.repo)
214             shell.call("git", "fetch", "-q", "scripts")
215             self.user_commit = shell.eval("git", "rev-parse", "HEAD")
216             self.next_commit = shell.eval("git", "rev-parse", self.version)
217             self.mergeSaveState()
218             self.mergePerform()
219     def mergePreCommit(self):
220         def get_file_set(rev):
221             return set(shell.eval("git", "ls-tree", "-r", "--name-only", rev).split("\n"))
222         # add all files that are unversioned but would be replaced by the pull,
223         # and generate a new commit
224         old_files = get_file_set("HEAD")
225         new_files = get_file_set(self.version)
226         added_files = new_files - old_files
227         for f in added_files:
228             if os.path.exists(f):
229                 shell.call("git", "add", f)
230         message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
231         try:
232             message += "\nPre-commit-by: " + util.get_operator_git()
233         except util.NoOperatorInfo:
234             pass
235         try:
236             shell.call("git", "commit", "-a", "-m", message)
237         except shell.CallError as e:
238             if "Permission denied" in e.stderr:
239                 raise util.PermissionsError
240             elif e.stderr:
241                 raise
242             logging.info("No changes detected")
243     def mergeClone(self):
244         # If /dev/shm exists, it's a tmpfs and we can use it
245         # to do a fast git merge. Don't forget to move it to
246         # /tmp if it fails.
247         if not self.options.dry_run and not self.options.debug:
248             self.use_shm = os.path.exists("/dev/shm")
249         if self.use_shm:
250             dir = "/dev/shm/wizard"
251             if not os.path.exists(dir):
252                 os.mkdir(dir)
253                 # XXX: race
254                 os.chmod(dir, 0o777)
255         else:
256             dir = None
257         self.temp_dir = tempfile.mkdtemp(prefix="wizard", dir=dir)
258         self.temp_wc_dir = os.path.join(self.temp_dir, "repo")
259         logging.info("Using temporary directory: " + self.temp_wc_dir)
260         shell.call("git", "clone", "-q", "--shared", ".", self.temp_wc_dir)
261     def mergeSaveState(self):
262         """Save variables so that ``--continue`` will work."""
263         # yeah yeah no trailing newline whatever
264         open(".git/WIZARD_UPGRADE_VERSION", "w").write(self.version)
265         open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (self.user_commit, self.next_commit))
266         open(".git/WIZARD_SIZE", "w").write(str(scripts.get_disk_usage()))
267         if self.options.log_file:
268             open(".git/WIZARD_LOG_FILE", "w").write(self.options.log_file)
269     def mergePerform(self):
270         def prepare_config():
271             self.wc.prepareConfig()
272             shell.call("git", "add", ".")
273         def resolve_conflicts():
274             return self.wc.resolveConflicts()
275         shell.call("git", "config", "merge.conflictstyle", "diff3")
276         # setup rerere
277         if self.options.rr_cache is None:
278             self.options.rr_cache = os.path.join(self.prod.location, ".git", "rr-cache")
279         if not os.path.exists(self.options.rr_cache):
280             os.mkdir(self.options.rr_cache)
281         os.symlink(self.options.rr_cache, os.path.join(self.wc.location, ".git", "rr-cache"))
282         shell.call("git", "config", "rerere.enabled", "true")
283         try:
284             merge.merge(self.wc.app_version.scripts_tag, self.version,
285                         prepare_config, resolve_conflicts)
286         except merge.MergeError:
287             self.mergeFail()
288     def mergeFail(self):
289         files = set()
290         for line in shell.eval("git", "ls-files", "--unmerged").splitlines():
291             files.add(line.split(None, 3)[-1])
292         conflicts = len(files)
293         # XXX: this is kind of fiddly; note that temp_dir still points at the OLD
294         # location after this code.
295         self.temp_wc_dir = mv_shm_to_tmp(os.getcwd(), self.use_shm)
296         self.wc.location = self.temp_wc_dir
297         os.chdir(self.temp_wc_dir)
298         open(os.path.join(self.prod.location, ".scripts/pending"), "w").write(self.temp_wc_dir)
299         if self.options.non_interactive:
300             print "%d %s" % (conflicts, self.temp_wc_dir)
301             raise MergeFailed
302         else:
303             user_shell = os.getenv("SHELL")
304             if not user_shell: user_shell = "/bin/bash"
305             # XXX: scripts specific hack, since mbash doesn't respect the current working directory
306             # When the revolution comes (i.e. $ATHENA_HOMEDIR/Scripts is your Scripts home
307             # directory) this isn't strictly necessary, but we'll probably need to support
308             # web_scripts directories ad infinitum.
309             if user_shell == "/usr/local/bin/mbash": user_shell = "/bin/bash"
310             while 1:
311                 print
312                 print "ERROR: The merge failed with %d conflicts in these files:" % conflicts
313                 print
314                 for file in sorted(files):
315                     print "  * %s" % file
316                 print
317                 print "Please resolve these conflicts (edit and then `git add`), and"
318                 print "then type 'exit'.  You will now be dropped into a shell whose working"
319                 print "directory is %s" % self.temp_wc_dir
320                 try:
321                     shell.call(user_shell, "-i", interactive=True)
322                 except shell.CallError as e:
323                     logging.warning("Shell returned non-zero exit code %d" % e.code)
324                 if shell.eval("git", "ls-files", "--unmerged").strip():
325                     print
326                     print "WARNING: There are still unmerged files."
327                     out = raw_input("Continue editing? [y/N]: ")
328                     if out == "y" or out == "Y":
329                         continue
330                     else:
331                         print "Aborting.  The conflicted working copy can be found at:"
332                         print
333                         print "    %s" % self.temp_wc_dir
334                         print
335                         print "and you can resume the upgrade process by running in that directory:"
336                         print
337                         print "    wizard upgrade --continue"
338                         sys.exit(1)
339                 break
340
341     def postflight(self):
342         with util.ChangeDirectory(self.temp_wc_dir):
343             if shell.eval("git", "ls-files", "-u").strip():
344                 raise UnmergedChangesError
345             shell.call("git", "commit", "--allow-empty", "-am", "throw-away commit")
346             self.wc.parametrize(self.prod)
347             shell.call("git", "add", ".")
348             message = self.postflightCommitMessage()
349             new_tree = shell.eval("git", "write-tree")
350             final_commit = shell.eval("git", "commit-tree", new_tree,
351                     "-p", self.user_commit, "-p", self.next_commit, input=message, log=True)
352             # a master branch may not necessarily exist if the user
353             # was manually installed to an earlier version
354             try:
355                 shell.call("git", "checkout", "-q", "-b", "master", "--")
356             except shell.CallError:
357                 shell.call("git", "checkout", "-q", "master", "--")
358             shell.call("git", "reset", "-q", "--hard", final_commit)
359             # This is a quick sanity check to make sure we didn't completely
360             # mess up the merge
361             self.wc.invalidateCache()
362             self.wc.verifyVersion()
363     def postflightCommitMessage(self):
364         message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), self.version, util.get_git_footer())
365         try:
366             message += "\nUpgraded-by: " + util.get_operator_git()
367         except util.NoOperatorInfo:
368             pass
369         return message
370
371     def backup(self):
372         # Ok, now we have to do a crazy complicated dance to see if we're
373         # going to have enough quota to finish what we need
374         pre_size = int(open(os.path.join(self.temp_wc_dir, ".git/WIZARD_SIZE"), "r").read())
375         post_size = scripts.get_disk_usage(self.temp_wc_dir)
376         backup = self.prod.backup(self.options)
377         kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
378         if kib_limit is not None and (kib_limit - kib_usage) - (post_size - pre_size) / 1024 < kib_buffer:
379             shutil.rmtree(os.path.join(".scripts/backups", shell.eval("wizard", "restore").splitlines()[0]))
380             raise QuotaTooLow
381         return backup
382
383     def upgrade(self, backup):
384         # XXX: frob .htaccess to make site inaccessible
385         with util.IgnoreKeyboardInterrupts():
386             with util.LockDirectory(".scripts-upgrade-lock"):
387                 shell.call("git", "fetch", "--tags")
388                 # git merge (which performs a fast forward)
389                 shell.call("git", "pull", "-q", self.temp_wc_dir, "master")
390                 version_obj = distutils.version.LooseVersion(self.version.partition('-')[2])
391                 try:
392                     # run update script
393                     self.prod.upgrade(version_obj, self.options)
394                     self.prod.verifyWeb()
395                 except app.UpgradeFailure:
396                     logging.warning("Upgrade failed: rolling back")
397                     self.upgradeRollback(backup)
398                     raise
399                 except deploy.WebVerificationError as e:
400                     logging.warning("Web verification failed: rolling back")
401                     self.upgradeRollback(backup)
402                     raise app.UpgradeVerificationFailure()
403         # XXX: frob .htaccess to make site accessible
404         #       to do this, check if .htaccess changed, first.  Upgrade
405         #       process might have frobbed it.  Don't be
406         #       particularly worried if the segment disappeared
407     def upgradeRollback(self, backup):
408         # You don't want d.restore() because it doesn't perform
409         # the file level backup
410         shell.call("wizard", "restore", backup)
411         try:
412             self.prod.verifyWeb()
413         except deploy.WebVerificationError:
414             logging.critical("Web verification failed after rollback")
415
416 # utility functions
417
418 def mv_shm_to_tmp(curdir, use_shm):
419     if not use_shm: return curdir
420     # Keeping all of our autoinstalls in shared memory is
421     # a recipe for disaster, so let's move them to slightly
422     # less volatile storage (a temporary directory)
423     os.chdir(tempfile.gettempdir())
424     newdir = tempfile.mkdtemp(prefix="wizard")
425     # shutil, not os; at least on Ubuntu os.move fails
426     # with "[Errno 18] Invalid cross-device link"
427     shutil.move(curdir, newdir)
428     shutil.rmtree(os.path.dirname(curdir))
429     curdir = os.path.join(newdir, "repo")
430     return curdir
431
432 def parse_args(argv, baton):
433     usage = """usage: %prog upgrade [ARGS] [DIR]
434
435 Upgrades an autoinstall to the latest version.  This involves
436 updating files and running .scripts/update.  If the merge fails,
437 this program will write the number of conflicts and the directory
438 of the conflicted working tree to stdout, separated by a space."""
439     parser = command.WizardOptionParser(usage)
440     parser.add_option("--dry-run", dest="dry_run", action="store_true",
441             default=False, help="Prints would would be run without changing anything")
442     # notice trailing underscore
443     parser.add_option("--continue", dest="continue_", action="store_true",
444             default=False, help="Continues an upgrade that has had its merge manually "
445             "resolved using the current working directory as the resolved copy.")
446     parser.add_option("--force", dest="force", action="store_true",
447             default=False, help="Force running upgrade even if it's already at latest version.")
448     parser.add_option("--non-interactive", dest="non_interactive", action="store_true",
449             default=False, help="Don't drop to shell in event of conflict.")
450     parser.add_option("--rr-cache", dest="rr_cache", metavar="PATH",
451             default=None, help="Use this folder to reuse recorded merge resolutions.  Defaults to"
452             "your production copy's rr-cache, if it exists.")
453     baton.push(parser, "srv_path")
454     options, args = parser.parse_all(argv)
455     if len(args) > 1:
456         parser.error("too many arguments")
457     return options, args
458
459 class Error(command.Error):
460     """Base exception for all exceptions raised by upgrade"""
461     pass
462
463 class QuotaTooLow(Error):
464     def __str__(self):
465         return """
466
467 ERROR: The locker quota was too low to complete the autoinstall
468 upgrade.
469 """
470
471 class AlreadyUpgraded(Error):
472     quiet = True
473     def __str__(self):
474         return """
475
476 ERROR: This autoinstall is already at the latest version."""
477
478 class MergeFailed(Error):
479     quiet = True
480     def __str__(self):
481         return """
482
483 ERROR: Merge failed.  Above is the temporary directory that
484 the conflicted merge is in: resolve the merge by cd'ing to the
485 temporary directory, finding conflicted files with `git status`,
486 resolving the files, adding them using `git add` and then
487 running `wizard upgrade --continue`."""
488
489 class LocalChangesError(Error):
490     def __str__(self):
491         return """
492
493 ERROR: Local changes occurred in the install while the merge was
494 being processed so that a pull would not result in a fast-forward.
495 The best way to resolve this is probably to attempt an upgrade again,
496 with git rerere to remember merge resolutions (XXX: not sure if
497 this actually works)."""
498
499 class UnmergedChangesError(Error):
500     def __str__(self):
501         return """
502
503 ERROR: You attempted to continue an upgrade, but there were
504 still local unmerged changes in your working copy.  Please resolve
505 them all and try again."""
506
507 class BlacklistedError(Error):
508     #: Reason why the autoinstall was blacklisted
509     reason = None
510     exitcode = errno_blacklisted
511     def __init__(self, reason):
512         self.reason = reason
513     def __str__(self):
514         return """
515
516 ERROR: This autoinstall was manually blacklisted against errors;
517 if the user has not been notified of this, please send them
518 mail.
519
520 The reason was: %s""" % self.reason
521
522 class CannotResumeError(Error):
523     def __str__(self):
524         return """
525
526 ERROR: We cannot resume the upgrade process; either this working
527 copy is missing essential metadata, or you've attempt to continue
528 from a production copy that does not have any pending upgrades.
529 """
530
531 class VersionRematchFailed(Error):
532     def __str__(self):
533         return """
534
535 ERROR: Your Git version information was not consistent with your
536 files on the system, and we were unable to create a fake merge
537 to make the two consistent.  Please contact scripts@mit.edu.
538 """