]> scripts.mit.edu Git - wizard.git/blob - wizard/command/upgrade.py
Make the commit not get call errors subsumed.
[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
10 from wizard import app, command, deploy, scripts, shell, util
11
12 kib_buffer = 1024 * 30 # 30 MiB we will always leave available
13 errno_blacklisted = 64
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     sh = shell.Shell()
24     util.set_git_env()
25     use_shm = False # if you are running --continue, this is guaranteed to be False
26     temp_dir = None
27     try: # global try-finally for cleaning up /dev/shm if it's being used
28         if options.continue_:
29             temp_wc_dir = os.getcwd()
30             wc = deploy.WorkingCopy(".")
31             user_commit, next_commit = open(".git/WIZARD_PARENTS", "r").read().split()
32             repo = open(".git/WIZARD_REPO", "r").read()
33             version = open(".git/WIZARD_UPGRADE_VERSION", "r").read()
34             if not options.log_file and os.path.exists(".git/WIZARD_LOG_FILE"):
35                 options.log_file = open(".git/WIZARD_LOG_FILE", "r").read()
36                 # reload logging
37                 command.setup_file_logger(options.log_file, options.debug)
38             logging.info("Continuing upgrade...")
39             util.chdir(sh.eval("git", "config", "remote.origin.url"))
40             d = deploy.ProductionCopy(".")
41             try:
42                 sh.call("git", "status")
43                 raise LocalChangesError()
44             except shell.CallError:
45                 pass
46         else:
47             d = deploy.ProductionCopy(".")
48             if os.path.exists(".scripts/blacklisted"):
49                 reason = open(".scripts/blacklisted").read()
50                 # ignore blank blacklisted files
51                 if reason:
52                     print reason
53                     raise BlacklistedError(reason)
54                 else:
55                     logging.warning("Application was blacklisted, but no reason was found");
56             # before doing verification, do a quick pull of tags
57             sh.call("git", "fetch", "--tags")
58             d.verify()
59             d.verifyTag(options.srv_path)
60             d.verifyGit(options.srv_path)
61             d.verifyConfigured()
62             d.verifyVersion()
63             if not options.dry_run:
64                 d.verifyWeb()
65             repo = d.application.repository(options.srv_path)
66             version = calculate_newest_version(sh, repo)
67             if version == d.app_version.scripts_tag and not options.force:
68                 # don't log this error
69                 # XXX: maybe we should build this in as a flag to add
70                 # to exceptions w/ our exception handler
71                 sys.stderr.write("Traceback:\n  (n/a)\nAlreadyUpgraded\n")
72                 sys.exit(1)
73             logging.info("Upgrading %s" % os.getcwd())
74             kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
75             if kib_limit is not None and (kib_limit - kib_usage) < kib_buffer:
76                 raise QuotaTooLow
77             if not options.dry_run:
78                 perform_pre_commit(sh)
79             # If /dev/shm exists, it's a tmpfs and we can use it
80             # to do a fast git merge. Don't forget to move it to
81             # /tmp if it fails.
82             if not options.dry_run and not options.debug:
83                 use_shm = os.path.exists("/dev/shm")
84             temp_dir, temp_wc_dir = perform_tmp_clone(sh, use_shm)
85             logging.debug("Temporary WC dir is %s", temp_wc_dir)
86             with util.ChangeDirectory(temp_wc_dir):
87                 wc = deploy.WorkingCopy(".")
88                 sh.call("git", "remote", "add", "scripts", repo)
89                 sh.call("git", "fetch", "-q", "scripts")
90                 user_commit, next_commit = calculate_parents(sh, version)
91                 # save variables so that --continue will work
92                 # yeah yeah no trailing newline whatever
93                 open(".git/WIZARD_REPO", "w").write(repo)
94                 open(".git/WIZARD_UPGRADE_VERSION", "w").write(version)
95                 open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (user_commit, next_commit))
96                 open(".git/WIZARD_SIZE", "w").write(str(scripts.get_disk_usage()))
97                 if options.log_file:
98                     open(".git/WIZARD_LOG_FILE", "w").write(options.log_file)
99                 temp_wc_dir = perform_merge(sh, repo, d, wc, version, use_shm, kib_limit and kib_limit - kib_usage or None, options.non_interactive)
100                 wc.location = temp_wc_dir
101         # variables: version, user_commit, next_commit, temp_wc_dir
102         with util.ChangeDirectory(temp_wc_dir):
103             try:
104                 sh.call("git", "status")
105             except shell.CallError:
106                 pass
107             else:
108                 sh.call("git", "commit", "-m", "throw-away commit")
109             message = make_commit_message(version)
110             new_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
111             final_commit = sh.eval("git", "commit-tree", new_tree,
112                     "-p", user_commit, "-p", next_commit, input=message, log=True)
113             # a master branch may not necessarily exist if the user
114             # was manually installed to an earlier version
115             try:
116                 sh.call("git", "checkout", "-q", "-b", "master", "--")
117             except shell.CallError:
118                 sh.call("git", "checkout", "-q", "master", "--")
119             sh.call("git", "reset", "-q", "--hard", final_commit)
120             # This is a quick sanity check to make sure we didn't completely
121             # mess up the merge
122             wc.invalidateCache()
123             wc.verifyVersion()
124         # Till now, all of our operations were in a tmp sandbox.
125         if options.dry_run:
126             logging.info("Dry run, bailing.  See results at %s" % temp_wc_dir)
127             return
128         # Ok, now we have to do a crazy complicated dance to see if we're
129         # going to have enough quota to finish what we need
130         pre_size = int(open(os.path.join(temp_wc_dir, ".git/WIZARD_SIZE"), "r").read())
131         post_size = scripts.get_disk_usage(temp_wc_dir)
132         kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
133         backup = d.backup(options)
134         if kib_limit is not None and (kib_limit - kib_usage) - (post_size - pre_size) / 1024 < kib_buffer:
135             shutil.rmtree(os.path.join(".scripts/backups", sh.eval("wizard", "restore").splitlines()[0]))
136             raise QuotaTooLow
137         # XXX: frob .htaccess to make site inaccessible
138         with util.IgnoreKeyboardInterrupts():
139             with util.LockDirectory(".scripts-upgrade-lock"):
140                 sh.call("git", "fetch", "--tags")
141                 # git merge (which performs a fast forward)
142                 sh.call("git", "pull", "-q", temp_wc_dir, "master")
143                 version_obj = distutils.version.LooseVersion(version.partition('-')[2])
144                 try:
145                     # run update script
146                     d.upgrade(version_obj, options)
147                     d.verifyWeb()
148                 except app.UpgradeFailure:
149                     logging.warning("Upgrade failed: rolling back")
150                     perform_restore(d, backup)
151                     raise
152                 except deploy.WebVerificationError as e:
153                     logging.warning("Web verification failed: rolling back")
154                     perform_restore(d, backup)
155                     raise app.UpgradeVerificationFailure()
156         # XXX: frob .htaccess to make site accessible
157         #       to do this, check if .htaccess changed, first.  Upgrade
158         #       process might have frobbed it.  Don't be
159         #       particularly worried if the segment disappeared
160     finally:
161         if use_shm and temp_dir and os.path.exists(temp_dir):
162             shutil.rmtree(temp_dir)
163     if not options.non_interactive:
164         print "Upgrade complete"
165
166 def perform_restore(d, backup):
167     # You don't want d.restore() because it doesn't perform
168     # the file level backup
169     shell.Shell().call("wizard", "restore", backup)
170     try:
171         d.verifyWeb()
172     except deploy.WebVerificationError:
173         logging.critical("Web verification failed after rollback")
174
175 def make_commit_message(version):
176     message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), version, util.get_git_footer())
177     try:
178         message += "\nUpgraded-by: " + util.get_operator_git()
179     except util.NoOperatorInfo:
180         pass
181     return message
182
183 def calculate_newest_version(sh, repo):
184     # XXX: put this in Application
185     return sh.eval("git", "--git-dir="+repo, "describe", "--tags", "master")
186
187 def calculate_parents(sh, version):
188     user_commit = sh.eval("git", "rev-parse", "HEAD")
189     next_commit = sh.eval("git", "rev-parse", version)
190     return user_commit, next_commit
191
192 def perform_pre_commit(sh):
193     message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
194     try:
195         message += "\nPre-commit-by: " + util.get_operator_git()
196     except util.NoOperatorInfo:
197         pass
198     try:
199         sh.call("git", "commit", "-a", "-m", message)
200     except shell.CallError:
201         logging.info("No changes detected")
202
203 def perform_tmp_clone(sh, use_shm):
204     if use_shm:
205         dir = "/dev/shm/wizard"
206         if not os.path.exists(dir):
207             os.mkdir(dir)
208             os.chmod(dir, 0o777)
209     else:
210         dir = None
211     temp_dir = tempfile.mkdtemp(prefix="wizard", dir=dir)
212     temp_wc_dir = os.path.join(temp_dir, "repo")
213     logging.info("Using temporary directory: " + temp_wc_dir)
214     sh.call("git", "clone", "-q", "--shared", ".", temp_wc_dir)
215     return temp_dir, temp_wc_dir
216
217 def perform_merge(sh, repo, d, wc, version, use_shm, kib_avail, non_interactive):
218     # Note: avail_quota == None means unlimited
219     # naive merge algorithm:
220     # sh.call("git", "merge", "-m", message, "scripts/master")
221     # crazy merge algorithm:
222     def make_virtual_commit(tag, parents = []):
223         """WARNING: Changes state of Git repository"""
224         sh.call("git", "checkout", "-q", tag, "--")
225         wc.parametrize(d)
226         for file in wc.application.parametrized_files:
227             try:
228                 sh.call("git", "add", "--", file)
229             except shell.CallError:
230                 pass
231         virtual_tree = sh.eval("git", "write-tree", log=True)
232         parent_args = itertools.chain(*(["-p", p] for p in parents))
233         virtual_commit = sh.eval("git", "commit-tree", virtual_tree,
234                 *parent_args, input="", log=True)
235         sh.call("git", "reset", "--hard")
236         return virtual_commit
237     user_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
238     base_virtual_commit = make_virtual_commit(wc.app_version.scripts_tag)
239     next_virtual_commit = make_virtual_commit(version, [base_virtual_commit])
240     user_virtual_commit = sh.eval("git", "commit-tree", user_tree,
241             "-p", base_virtual_commit, input="", log=True)
242     sh.call("git", "checkout", user_virtual_commit, "--")
243     wc.prepareMerge()
244     try:
245         sh.call("git", "commit", "--amend", "-a", "-m", "amendment")
246     except shell.CallError as e:
247         pass
248     try:
249         sh.call("git", "config", "merge.conflictstyle", "diff3")
250         sh.call("git", "merge", next_virtual_commit)
251     except shell.CallError as e:
252         logging.info("Merge failed with these messages:\n\n" + e.stderr)
253         # Run the application's specific merge resolution algorithms
254         # and see if we can salvage it
255         curdir = os.getcwd()
256         if wc.resolveConflicts():
257             logging.info("Resolved conflicts with application specific knowledge")
258             sh.call("git", "commit", "-a", "-m", "merge")
259             return os.getcwd()
260         logging.info("Conflict info:\n" + sh.eval("git", "diff"))
261         outlines = sh.eval("git", "ls-files", "--unmerged").splitlines()
262         files = set()
263         for line in outlines:
264             _, _, _, name = line.split(None, 3)
265             files.add(name)
266         conflicts = len(files)
267         curdir = mv_shm_to_tmp(curdir, use_shm)
268         os.chdir(curdir)
269         open(os.path.join(d.location, ".scripts/pending"), "w").write(curdir)
270         if non_interactive:
271             print "%d %s" % (conflicts, curdir)
272             raise MergeFailed
273         else:
274             user_shell = os.getenv("SHELL")
275             if not user_shell: user_shell = "/bin/bash"
276             while 1:
277                 print
278                 print "ERROR: The merge failed with %d conflicts in these files:" % conflicts
279                 print
280                 for file in sorted(files):
281                     print "  * %s" % file
282                 print
283                 print "Please resolve these conflicts (edit and then `git add`), and"
284                 print "then type 'exit'."
285                 sh.call(user_shell, "-i", interactive=True)
286                 if sh.eval("git", "ls-files", "--unmerged").strip():
287                     print
288                     print "WARNING: There are still unmerged files."
289                     out = raw_input("Continue editing? [y/N]: ")
290                     if out == "y" or out == "Y":
291                         continue
292                     else:
293                         print "Aborting.  The conflicted working copy can be found at:"
294                         print
295                         print "    %s" % os.getcwd()
296                         print
297                         print "and you can resume the upgrade process by running in that directory:"
298                         print
299                         print "    wizard upgrade --continue"
300                         sys.exit(1)
301                 break
302     return os.getcwd()
303
304 def mv_shm_to_tmp(curdir, use_shm):
305     if not use_shm: return curdir
306     # Keeping all of our autoinstalls in shared memory is
307     # a recipe for disaster, so let's move them to slightly
308     # less volatile storage (a temporary directory)
309     os.chdir(tempfile.gettempdir())
310     newdir = tempfile.mkdtemp(prefix="wizard")
311     # shutil, not os; at least on Ubuntu os.move fails
312     # with "[Errno 18] Invalid cross-device link"
313     shutil.move(curdir, newdir)
314     shutil.rmtree(os.path.dirname(curdir))
315     curdir = os.path.join(newdir, "repo")
316     return curdir
317
318 def parse_args(argv, baton):
319     usage = """usage: %prog upgrade [ARGS] [DIR]
320
321 Upgrades an autoinstall to the latest version.  This involves
322 updating files and running .scripts/update.  If the merge fails,
323 this program will write the number of conflicts and the directory
324 of the conflicted working tree to stdout, separated by a space."""
325     parser = command.WizardOptionParser(usage)
326     parser.add_option("--dry-run", dest="dry_run", action="store_true",
327             default=False, help="Prints would would be run without changing anything")
328     # notice trailing underscore
329     parser.add_option("--continue", dest="continue_", action="store_true",
330             default=False, help="Continues an upgrade that has had its merge manually "
331             "resolved using the current working directory as the resolved copy.")
332     parser.add_option("--force", dest="force", action="store_true",
333             default=False, help="Force running upgrade even if it's already at latest version.")
334     parser.add_option("--non-interactive", dest="non_interactive", action="store_true",
335             default=False, help="Don't drop to shell in event of conflict.")
336     baton.push(parser, "srv_path")
337     options, args = parser.parse_all(argv)
338     if len(args) > 1:
339         parser.error("too many arguments")
340     return options, args
341
342 class Error(command.Error):
343     """Base exception for all exceptions raised by upgrade"""
344     pass
345
346 class QuotaTooLow(Error):
347     def __str__(self):
348         return """
349
350 ERROR: The locker quota was too low to complete the autoinstall
351 upgrade.
352 """
353
354 class AlreadyUpgraded(Error):
355     quiet = True
356     def __str__(self):
357         return """
358
359 ERROR: This autoinstall is already at the latest version."""
360
361 class MergeFailed(Error):
362     quiet = True
363     def __str__(self):
364         return """
365
366 ERROR: Merge failed.  Above is the temporary directory that
367 the conflicted merge is in: resolve the merge by cd'ing to the
368 temporary directory, finding conflicted files with `git status`,
369 resolving the files, adding them using `git add` and then
370 running `wizard upgrade --continue`."""
371
372 class LocalChangesError(Error):
373     def __str__(self):
374         return """
375
376 ERROR: Local changes occurred in the install while the merge was
377 being processed so that a pull would not result in a fast-forward.
378 The best way to resolve this is probably to attempt an upgrade again,
379 with git rerere to remember merge resolutions (XXX: not sure if
380 this actually works)."""
381
382 class BlacklistedError(Error):
383     #: Reason why the autoinstall was blacklisted
384     reason = None
385     exitcode = errno_blacklisted
386     def __init__(self, reason):
387         self.reason = reason
388     def __str__(self):
389         return """
390
391 ERROR: This autoinstall was manually blacklisted against errors;
392 if the user has not been notified of this, please send them
393 mail.
394
395 The reason was: %s""" % self.reason