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