]> scripts.mit.edu Git - wizard.git/blob - wizard/command/upgrade.py
66e1d6bd48909a2f1bfcd77f96ab4735eff43a59
[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 command, deploy, shell, util
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     if options.continue_:
24         temp_wc_dir = os.getcwd()
25         user_commit, next_commit = open(".git/WIZARD_PARENTS", "r").read().split()
26         repo = open(".git/WIZARD_REPO", "r").read()
27         version = open(".git/WIZARD_UPGRADE_VERSION", "r").read()
28         util.chdir(sh.eval("git", "config", "remote.origin.url"))
29         d = deploy.Deployment(".")
30         try:
31             sh.call("git", "status")
32             raise LocalChangesError()
33         except shell.CallError:
34             pass
35     else:
36         d = deploy.Deployment(".")
37         d.verify()
38         d.verifyTag(options.srv_path)
39         d.verifyGit(options.srv_path)
40         d.verifyConfigured()
41         d.verifyVersion()
42         repo = d.application.repository(options.srv_path)
43         version = calculate_newest_version(sh, repo)
44         if version == d.app_version.scripts_tag and not options.force:
45             raise AlreadyUpgraded
46         if not options.dry_run:
47             perform_pre_commit(sh)
48         temp_wc_dir = perform_tmp_clone(sh)
49         with util.ChangeDirectory(temp_wc_dir):
50             sh.call("git", "remote", "add", "scripts", repo)
51             sh.call("git", "fetch", "scripts")
52             user_commit, next_commit = calculate_parents(sh, version)
53             # save variables so that --continue will work
54             # yeah yeah no trailing newline whatever
55             open(".git/WIZARD_REPO", "w").write(repo)
56             open(".git/WIZARD_UPGRADE_VERSION", "w").write(version)
57             open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (user_commit, next_commit))
58             perform_merge(sh, repo, d, version)
59     # variables: version, user_commit, next_commit, temp_wc_dir
60     with util.ChangeDirectory(temp_wc_dir):
61         message = make_commit_message(version)
62         new_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
63         final_commit = sh.eval("git", "commit-tree", new_tree,
64                 "-p", user_commit, "-p", next_commit, input=message, log=True)
65         # a master branch may not necessarily exist if the user
66         # was manually installed to an earlier version
67         try:
68             sh.call("git", "checkout", "-b", "master", "--")
69         except shell.CallError:
70             sh.call("git", "checkout", "master", "--")
71         sh.call("git", "reset", "--hard", final_commit)
72     # Till now, all of our operations were in a tmp sandbox.
73     if options.dry_run:
74         logging.info("Dry run, bailing.  See results at %s" % temp_wc_dir)
75         return
76     # perform database backup
77     d.backup(options)
78     # XXX: frob .htaccess to make site inaccessible
79     # XXX: need locking
80     # git merge (which performs a fast forward)
81     #   - merge could fail (race); that's /really/ dangerous.
82     sh.call("git", "pull", temp_wc_dir, "master")
83     # run update script
84     version_obj = distutils.version.LooseVersion(version.partition('-')[2])
85     d.application.upgrade(version_obj, options)
86     # XXX: frob .htaccess to make site accessible
87     # XXX:  - check if .htaccess changed, first.  Upgrade
88     #       process might have frobbed it.  Don't be
89     #       particularly worried if the segment dissappeared
90
91 def make_commit_message(version):
92     message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), version, util.get_git_footer())
93     try:
94         message += "\nUpgraded-by: " + util.get_operator_git()
95     except util.NoOperatorInfo:
96         pass
97     return message
98
99 def calculate_newest_version(sh, repo):
100     # XXX: put this in Application
101     return sh.eval("git", "--git-dir="+repo, "describe", "--tags", "master")
102
103 def calculate_parents(sh, version):
104     user_commit = sh.eval("git", "rev-parse", "HEAD")
105     next_commit = sh.eval("git", "rev-parse", version)
106     return user_commit, next_commit
107
108 def perform_pre_commit(sh):
109     message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
110     try:
111         message += "\nPre-commit-by: " + util.get_operator_git()
112     except util.NoOperatorInfo:
113         pass
114     try:
115         sh.call("git", "commit", "-a", "-m", message)
116     except shell.CallError:
117         logging.info("No changes detected")
118
119 def perform_tmp_clone(sh):
120     temp_dir = tempfile.mkdtemp(prefix="wizard")
121     temp_wc_dir = os.path.join(temp_dir, "repo")
122     logging.info("Using temporary directory: " + temp_wc_dir)
123     sh.call("git", "clone", "--shared", ".", temp_wc_dir)
124     return temp_wc_dir
125
126 def perform_merge(sh, repo, d, version):
127     # naive merge algorithm:
128     # sh.call("git", "merge", "-m", message, "scripts/master")
129     # crazy merge algorithm:
130     def make_virtual_commit(tag, parents = []):
131         """WARNING: Changes state of Git repository"""
132         sh.call("git", "checkout", tag, "--")
133         d.parametrize(".")
134         for file in d.application.parametrized_files:
135             try:
136                 sh.call("git", "add", "--", file)
137             except shell.CallError:
138                 pass
139         virtual_tree = sh.eval("git", "write-tree", log=True)
140         parent_args = itertools.chain(*(["-p", p] for p in parents))
141         virtual_commit = sh.eval("git", "commit-tree", virtual_tree,
142                 *parent_args, input="", log=True)
143         sh.call("git", "reset", "--hard")
144         return virtual_commit
145     user_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
146     base_virtual_commit = make_virtual_commit(d.app_version.scripts_tag)
147     next_virtual_commit = make_virtual_commit(version, [base_virtual_commit])
148     user_virtual_commit = sh.eval("git", "commit-tree", user_tree,
149             "-p", base_virtual_commit, input="", log=True)
150     sh.call("git", "checkout", user_virtual_commit, "--")
151     try:
152         sh.call("git", "merge", next_virtual_commit)
153     except shell.CallError:
154         print os.getcwd()
155         logging.info("Conflict info:\n", sh.eval("git", "diff"))
156         raise MergeFailed
157
158 def parse_args(argv, baton):
159     usage = """usage: %prog upgrade [ARGS] [DIR]
160
161 Upgrades an autoinstall to the latest version.  This involves
162 updating files and running .scripts/update.
163
164 WARNING: This is still experimental."""
165     parser = command.WizardOptionParser(usage)
166     parser.add_option("--dry-run", dest="dry_run", action="store_true",
167             default=False, help="Prints would would be run without changing anything")
168     # notice trailing underscore
169     parser.add_option("--continue", dest="continue_", action="store_true",
170             default=False, help="Continues an upgrade that has had its merge manually "
171             "resolved using the current working directory as the resolved copy.")
172     parser.add_option("--force", dest="force", action="store_true",
173             default=False, help="Force running upgrade even if it's already at latest version.")
174     baton.push(parser, "srv_path")
175     options, args = parser.parse_all(argv)
176     if len(args) > 1:
177         parser.error("too many arguments")
178     return options, args
179
180 class Error(command.Error):
181     """Base exception for all exceptions raised by upgrade"""
182     pass
183
184 class AlreadyUpgraded(Error):
185     def __str__(self):
186         return """
187
188 ERROR: This autoinstall is already at the latest version."""
189
190 class MergeFailed(Error):
191     def __str__(self):
192         return """
193
194 ERROR: Merge failed.  Resolve the merge by cd'ing to the
195 temporary directory, finding conflicted files with `git status`,
196 resolving the files, adding them using `git add`, and then
197 committing your changes with `git commit` (your log message
198 will be ignored), and then running `wizard upgrade --continue`."""
199
200 class LocalChangesError(Error):
201     def __str__(self):
202         return """
203
204 ERROR: Local changes occurred in the install while the merge was
205 being processed so that a pull would not result in a fast-forward.
206 The best way to resolve this is probably to attempt an upgrade again,
207 with git rerere to remember merge resolutions (XXX: not sure if
208 this actually works)."""
209