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