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