]> scripts.mit.edu Git - wizard.git/blob - wizard/command/upgrade.py
Implement disk quota checking.
[wizard.git] / wizard / command / upgrade.py
1 import optparse
2 import sys
3 import distutils.version
4 import os
5 import shutil
6 import logging.handlers
7 import errno
8 import tempfile
9 import itertools
10
11 from wizard import app, command, deploy, scripts, shell, util
12
13 kib_buffer = 1024 * 1024 * 10 # 10 MiB we will always leave available
14
15 def main(argv, baton):
16     options, args = parse_args(argv, baton)
17     if args:
18         dir = args[0]
19     else:
20         dir = "."
21     shell.drop_priviledges(dir, options.log_file)
22     util.chdir(dir)
23     if os.path.exists(".scripts/blacklisted"):
24         raise BlacklistedError()
25     sh = shell.Shell()
26     util.set_git_env()
27     use_shm = False # if you are running --continue, this is guaranteed to be False
28     if options.continue_:
29         temp_wc_dir = os.getcwd()
30         user_commit, next_commit = open(".git/WIZARD_PARENTS", "r").read().split()
31         repo = open(".git/WIZARD_REPO", "r").read()
32         version = open(".git/WIZARD_UPGRADE_VERSION", "r").read()
33         if not options.log_file and os.path.exists(".git/WIZARD_LOG_FILE"):
34             options.log_file = open(".git/WIZARD_LOG_FILE", "r").read()
35             # reload logging
36             command.addFileLogger(options.log_file, options.debug)
37         logging.info("Continuing upgrade...")
38         util.chdir(sh.eval("git", "config", "remote.origin.url"))
39         d = deploy.Deployment(".")
40         try:
41             sh.call("git", "status")
42             raise LocalChangesError()
43         except shell.CallError:
44             pass
45     else:
46         d = deploy.Deployment(".")
47         d.verify()
48         d.verifyTag(options.srv_path)
49         d.verifyGit(options.srv_path)
50         d.verifyConfigured()
51         d.verifyVersion()
52         if not options.dry_run:
53             d.verifyWeb()
54         # perform database backup
55         if not options.dry_run:
56             backup = d.backup(options)
57         # we do this before checking quota
58         kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
59         if kib_limit and (kib_limit - kib_usage) < kib_buffer: # 10 mebibytes
60             raise QuotaTooLow
61         repo = d.application.repository(options.srv_path)
62         version = calculate_newest_version(sh, repo)
63         if version == d.app_version.scripts_tag and not options.force:
64             # don't log this error
65             # XXX: maybe we should build this in as a flag to add
66             # to exceptions w/ our exception handler
67             sys.stderr.write("Traceback:\n  (n/a)\nAlreadyUpgraded\n")
68             sys.exit(1)
69         logging.info("Upgrading %s" % os.getcwd())
70         if not options.dry_run:
71             perform_pre_commit(sh)
72         # If /dev/shm exists, it's a tmpfs and we can use it
73         # to do a fast git merge. Don't forget to move it to
74         # /tmp if it fails.
75         # XXX: git merge-tree is another possibility for
76         # reducing filesystem interactions, and also probably
77         # works better with extra merging functionality.  However,
78         # I don't know how I would put the results back in the
79         # working tree.
80         use_shm = os.path.exists("/dev/shm")
81         temp_dir, temp_wc_dir = perform_tmp_clone(sh, use_shm)
82         with util.ChangeDirectory(temp_wc_dir):
83             sh.call("git", "remote", "add", "scripts", repo)
84             sh.call("git", "fetch", "-q", "scripts")
85             user_commit, next_commit = calculate_parents(sh, version)
86             # save variables so that --continue will work
87             # yeah yeah no trailing newline whatever
88             open(".git/WIZARD_REPO", "w").write(repo)
89             open(".git/WIZARD_UPGRADE_VERSION", "w").write(version)
90             open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (user_commit, next_commit))
91             if options.log_file: open(".git/WIZARD_LOG_FILE", "w").write(options.log_file)
92             perform_merge(sh, repo, d, version, use_shm, kib_limit and kib_limit - kib_usage or None)
93     # variables: version, user_commit, next_commit, temp_wc_dir
94     with util.ChangeDirectory(temp_wc_dir):
95         try:
96             sh.call("git", "status")
97             sh.call("git", "commit", "-m", "throw-away commit")
98         except shell.CallError:
99             pass
100         message = make_commit_message(version)
101         new_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
102         final_commit = sh.eval("git", "commit-tree", new_tree,
103                 "-p", user_commit, "-p", next_commit, input=message, log=True)
104         # a master branch may not necessarily exist if the user
105         # was manually installed to an earlier version
106         try:
107             sh.call("git", "checkout", "-q", "-b", "master", "--")
108         except shell.CallError:
109             sh.call("git", "checkout", "-q", "master", "--")
110         sh.call("git", "reset", "-q", "--hard", final_commit)
111         # This is a quick sanity check to make sure we didn't completely
112         # mess up the merge
113         d.verifyVersion()
114     # Till now, all of our operations were in a tmp sandbox.
115     if options.dry_run:
116         logging.info("Dry run, bailing.  See results at %s" % temp_wc_dir)
117         return
118     # XXX: frob .htaccess to make site inaccessible
119     with util.IgnoreKeyboardInterrupts():
120         with util.LockDirectory(".scripts-upgrade-lock"):
121             # git merge (which performs a fast forward)
122             sh.call("git", "pull", "-q", temp_wc_dir, "master")
123             # after the pull is successful, the directory now
124             # has the objects for this commit, so we can safely
125             # nuke the shm directory.  We refrain from nuking the
126             # tmp directory in case we messed up the merge resolution
127             # and want to be able to use it again.
128             if use_shm:
129                 shutil.rmtree(temp_dir)
130             version_obj = distutils.version.LooseVersion(version.partition('-')[2])
131             try:
132                 # run update script
133                 d.upgrade(version_obj, options)
134                 d.verifyWeb()
135             except app.UpgradeFailure:
136                 logging.warning("Upgrade failed: rolling back")
137                 perform_restore(d, backup)
138                 raise
139             except deploy.WebVerificationError as e:
140                 logging.warning("Web verification failed: rolling back")
141                 logging.info("Web page that was output was:\n\n%s" % e.contents)
142                 perform_restore(d, backup)
143                 raise app.UpgradeVerificationFailure("Upgrade caused website to become inaccessible; site was rolled back")
144     # XXX: frob .htaccess to make site accessible
145     #       to do this, check if .htaccess changed, first.  Upgrade
146     #       process might have frobbed it.  Don't be
147     #       particularly worried if the segment disappeared
148
149 def perform_restore(d, backup):
150     # You don't want d.restore() because it doesn't perform
151     # the file level backup
152     shell.Shell().call("wizard", "restore", backup)
153     try:
154         d.verifyWeb()
155     except deploy.WebVerificationError:
156         logging.critical("Web verification failed after rollback")
157
158 def make_commit_message(version):
159     message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), version, util.get_git_footer())
160     try:
161         message += "\nUpgraded-by: " + util.get_operator_git()
162     except util.NoOperatorInfo:
163         pass
164     return message
165
166 def calculate_newest_version(sh, repo):
167     # XXX: put this in Application
168     return sh.eval("git", "--git-dir="+repo, "describe", "--tags", "master")
169
170 def calculate_parents(sh, version):
171     user_commit = sh.eval("git", "rev-parse", "HEAD")
172     next_commit = sh.eval("git", "rev-parse", version)
173     return user_commit, next_commit
174
175 def perform_pre_commit(sh):
176     message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
177     try:
178         message += "\nPre-commit-by: " + util.get_operator_git()
179     except util.NoOperatorInfo:
180         pass
181     try:
182         sh.call("git", "commit", "-a", "-m", message)
183     except shell.CallError:
184         logging.info("No changes detected")
185
186 def perform_tmp_clone(sh, use_shm):
187     if use_shm:
188         dir = "/dev/shm/wizard"
189         if not os.path.exists(dir):
190             os.mkdir(dir)
191     else:
192         dir = None
193     temp_dir = tempfile.mkdtemp(prefix="wizard", dir=dir)
194     temp_wc_dir = os.path.join(temp_dir, "repo")
195     logging.info("Using temporary directory: " + temp_wc_dir)
196     sh.call("git", "clone", "-q", "--shared", ".", temp_wc_dir)
197     return temp_dir, temp_wc_dir
198
199 def perform_merge(sh, repo, d, version, use_shm, kib_avail):
200     # Note: avail_quota == None means unlimited
201     # naive merge algorithm:
202     # sh.call("git", "merge", "-m", message, "scripts/master")
203     # crazy merge algorithm:
204     def make_virtual_commit(tag, parents = []):
205         """WARNING: Changes state of Git repository"""
206         sh.call("git", "checkout", "-q", tag, "--")
207         d.parametrize(".")
208         for file in d.application.parametrized_files:
209             try:
210                 sh.call("git", "add", "--", file)
211             except shell.CallError:
212                 pass
213         virtual_tree = sh.eval("git", "write-tree", log=True)
214         parent_args = itertools.chain(*(["-p", p] for p in parents))
215         virtual_commit = sh.eval("git", "commit-tree", virtual_tree,
216                 *parent_args, input="", log=True)
217         sh.call("git", "reset", "--hard")
218         return virtual_commit
219     user_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
220     base_virtual_commit = make_virtual_commit(d.app_version.scripts_tag)
221     next_virtual_commit = make_virtual_commit(version, [base_virtual_commit])
222     user_virtual_commit = sh.eval("git", "commit-tree", user_tree,
223             "-p", base_virtual_commit, input="", log=True)
224     sh.call("git", "checkout", user_virtual_commit, "--")
225     pre_usage = scripts.get_disk_usage()
226     try:
227         sh.call("git", "merge", next_virtual_commit)
228     except shell.CallError as e:
229         conflicts = e.stderr.count("CONFLICT") # not perfect, if there is a file named CONFLICT
230         logging.info("Merge failed with these messages:\n\n" + e.stderr)
231         # Run the application's specific merge resolution algorithms
232         # and see if we can salvage it
233         curdir = os.getcwd()
234         if d.application.resolveConflicts(curdir):
235             logging.info("Resolved conflicts with application specific knowledge")
236             sh.call("git", "commit", "-a", "-m", "merge")
237             return
238         # XXX: Maybe should recalculate conflicts
239         logging.info("Conflict info:\n" + sh.eval("git", "diff"))
240         if use_shm:
241             # Keeping all of our autoinstalls in shared memory is
242             # a recipe for disaster, so let's move them to slightly
243             # less volatile storage (a temporary directory)
244             os.chdir(tempfile.gettempdir())
245             newdir = tempfile.mkdtemp(prefix="wizard")
246             # shutil, not os; at least on Ubuntu os.move fails
247             # with "[Errno 18] Invalid cross-device link"
248             shutil.move(curdir, newdir)
249             shutil.rmtree(os.path.dirname(curdir))
250             curdir = os.path.join(newdir, "repo")
251             os.chdir(curdir)
252         print "%d %s" % (conflicts, curdir)
253         raise MergeFailed
254     finally:
255         post_usage = scripts.get_disk_usage()
256         kib_delta = (post_usage - pre_usage) / 1024
257         if kib_avail is not None and kib_delta - kib_avail < kib_buffer:
258             raise QuotaTooLow
259
260 def parse_args(argv, baton):
261     usage = """usage: %prog upgrade [ARGS] [DIR]
262
263 Upgrades an autoinstall to the latest version.  This involves
264 updating files and running .scripts/update.  If the merge fails,
265 this program will write the number of conflicts and the directory
266 of the conflicted working tree to stdout, separated by a space."""
267     parser = command.WizardOptionParser(usage)
268     parser.add_option("--dry-run", dest="dry_run", action="store_true",
269             default=False, help="Prints would would be run without changing anything")
270     # notice trailing underscore
271     parser.add_option("--continue", dest="continue_", action="store_true",
272             default=False, help="Continues an upgrade that has had its merge manually "
273             "resolved using the current working directory as the resolved copy.")
274     parser.add_option("--force", dest="force", action="store_true",
275             default=False, help="Force running upgrade even if it's already at latest version.")
276     baton.push(parser, "srv_path")
277     options, args = parser.parse_all(argv)
278     if len(args) > 1:
279         parser.error("too many arguments")
280     return options, args
281
282 class Error(command.Error):
283     """Base exception for all exceptions raised by upgrade"""
284     pass
285
286 class QuotaTooLow(Error):
287     def __str__(self):
288         return """
289
290 ERROR: The locker quota was too low to complete the autoinstall
291 upgrade.
292 """
293
294 class AlreadyUpgraded(Error):
295     def __str__(self):
296         return """
297
298 ERROR: This autoinstall is already at the latest version."""
299
300 class MergeFailed(Error):
301     def __str__(self):
302         return """
303
304 ERROR: Merge failed.  Resolve the merge by cd'ing to the
305 temporary directory, finding conflicted files with `git status`,
306 resolving the files, adding them using `git add` and then
307 running `wizard upgrade --continue`."""
308
309 class LocalChangesError(Error):
310     def __str__(self):
311         return """
312
313 ERROR: Local changes occurred in the install while the merge was
314 being processed so that a pull would not result in a fast-forward.
315 The best way to resolve this is probably to attempt an upgrade again,
316 with git rerere to remember merge resolutions (XXX: not sure if
317 this actually works)."""
318
319 class BlacklistedError(Error):
320     def __str__(self):
321         return """
322
323 ERROR: This autoinstall was manually blacklisted against errors;
324 if the user has not been notified of this, please send them
325 mail."""