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