3 import distutils.version
6 import logging.handlers
11 from wizard import app, command, deploy, scripts, shell, util
13 kib_buffer = 1024 * 10 # 10 MiB we will always leave available
15 def main(argv, baton):
16 options, args = parse_args(argv, baton)
21 shell.drop_priviledges(dir, options.log_file)
23 if os.path.exists(".scripts/blacklisted"):
24 raise BlacklistedError()
27 use_shm = False # if you are running --continue, this is guaranteed to be False
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()
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(".")
41 sh.call("git", "status")
42 raise LocalChangesError()
43 except shell.CallError:
46 d = deploy.Deployment(".")
48 d.verifyTag(options.srv_path)
49 d.verifyGit(options.srv_path)
52 if not options.dry_run:
54 # perform database backup, this should be done before checking quota
55 if not options.dry_run:
56 backup = d.backup(options)
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")
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: # 10 mebibytes
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
74 # XXX: git merge-tree is another possibility for
75 # reducing filesystem interactions, and also probably
76 # works better with extra merging functionality. However,
77 # I don't know how I would put the results back in the
79 use_shm = os.path.exists("/dev/shm")
80 temp_dir, temp_wc_dir = perform_tmp_clone(sh, use_shm)
81 with util.ChangeDirectory(temp_wc_dir):
82 sh.call("git", "remote", "add", "scripts", repo)
83 sh.call("git", "fetch", "-q", "scripts")
84 user_commit, next_commit = calculate_parents(sh, version)
85 # save variables so that --continue will work
86 # yeah yeah no trailing newline whatever
87 open(".git/WIZARD_REPO", "w").write(repo)
88 open(".git/WIZARD_UPGRADE_VERSION", "w").write(version)
89 open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (user_commit, next_commit))
90 if options.log_file: open(".git/WIZARD_LOG_FILE", "w").write(options.log_file)
91 perform_merge(sh, repo, d, version, use_shm, kib_limit and kib_limit - kib_usage or None)
92 # variables: version, user_commit, next_commit, temp_wc_dir
93 with util.ChangeDirectory(temp_wc_dir):
95 sh.call("git", "status")
96 sh.call("git", "commit", "-m", "throw-away commit")
97 except shell.CallError:
99 message = make_commit_message(version)
100 new_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
101 final_commit = sh.eval("git", "commit-tree", new_tree,
102 "-p", user_commit, "-p", next_commit, input=message, log=True)
103 # a master branch may not necessarily exist if the user
104 # was manually installed to an earlier version
106 sh.call("git", "checkout", "-q", "-b", "master", "--")
107 except shell.CallError:
108 sh.call("git", "checkout", "-q", "master", "--")
109 sh.call("git", "reset", "-q", "--hard", final_commit)
110 # This is a quick sanity check to make sure we didn't completely
113 # Till now, all of our operations were in a tmp sandbox.
115 logging.info("Dry run, bailing. See results at %s" % temp_wc_dir)
117 # XXX: frob .htaccess to make site inaccessible
118 with util.IgnoreKeyboardInterrupts():
119 with util.LockDirectory(".scripts-upgrade-lock"):
120 # git merge (which performs a fast forward)
121 sh.call("git", "pull", "-q", temp_wc_dir, "master")
122 # after the pull is successful, the directory now
123 # has the objects for this commit, so we can safely
124 # nuke the shm directory. We refrain from nuking the
125 # tmp directory in case we messed up the merge resolution
126 # and want to be able to use it again.
128 shutil.rmtree(temp_dir)
129 version_obj = distutils.version.LooseVersion(version.partition('-')[2])
132 d.upgrade(version_obj, options)
134 except app.UpgradeFailure:
135 logging.warning("Upgrade failed: rolling back")
136 perform_restore(d, backup)
138 except deploy.WebVerificationError as e:
139 logging.warning("Web verification failed: rolling back")
140 logging.info("Web page that was output was:\n\n%s" % e.contents)
141 perform_restore(d, backup)
142 raise app.UpgradeVerificationFailure("Upgrade caused website to become inaccessible; site was rolled back")
143 # XXX: frob .htaccess to make site accessible
144 # to do this, check if .htaccess changed, first. Upgrade
145 # process might have frobbed it. Don't be
146 # particularly worried if the segment disappeared
148 def perform_restore(d, backup):
149 # You don't want d.restore() because it doesn't perform
150 # the file level backup
151 shell.Shell().call("wizard", "restore", backup)
154 except deploy.WebVerificationError:
155 logging.critical("Web verification failed after rollback")
157 def make_commit_message(version):
158 message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), version, util.get_git_footer())
160 message += "\nUpgraded-by: " + util.get_operator_git()
161 except util.NoOperatorInfo:
165 def calculate_newest_version(sh, repo):
166 # XXX: put this in Application
167 return sh.eval("git", "--git-dir="+repo, "describe", "--tags", "master")
169 def calculate_parents(sh, version):
170 user_commit = sh.eval("git", "rev-parse", "HEAD")
171 next_commit = sh.eval("git", "rev-parse", version)
172 return user_commit, next_commit
174 def perform_pre_commit(sh):
175 message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
177 message += "\nPre-commit-by: " + util.get_operator_git()
178 except util.NoOperatorInfo:
181 sh.call("git", "commit", "-a", "-m", message)
182 except shell.CallError:
183 logging.info("No changes detected")
185 def perform_tmp_clone(sh, use_shm):
187 dir = "/dev/shm/wizard"
188 if not os.path.exists(dir):
192 temp_dir = tempfile.mkdtemp(prefix="wizard", dir=dir)
193 temp_wc_dir = os.path.join(temp_dir, "repo")
194 logging.info("Using temporary directory: " + temp_wc_dir)
195 sh.call("git", "clone", "-q", "--shared", ".", temp_wc_dir)
196 return temp_dir, temp_wc_dir
198 def perform_merge(sh, repo, d, version, use_shm, kib_avail):
199 # Note: avail_quota == None means unlimited
200 # naive merge algorithm:
201 # sh.call("git", "merge", "-m", message, "scripts/master")
202 # crazy merge algorithm:
203 def make_virtual_commit(tag, parents = []):
204 """WARNING: Changes state of Git repository"""
205 sh.call("git", "checkout", "-q", tag, "--")
207 for file in d.application.parametrized_files:
209 sh.call("git", "add", "--", file)
210 except shell.CallError:
212 virtual_tree = sh.eval("git", "write-tree", log=True)
213 parent_args = itertools.chain(*(["-p", p] for p in parents))
214 virtual_commit = sh.eval("git", "commit-tree", virtual_tree,
215 *parent_args, input="", log=True)
216 sh.call("git", "reset", "--hard")
217 return virtual_commit
218 user_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
219 base_virtual_commit = make_virtual_commit(d.app_version.scripts_tag)
220 next_virtual_commit = make_virtual_commit(version, [base_virtual_commit])
221 user_virtual_commit = sh.eval("git", "commit-tree", user_tree,
222 "-p", base_virtual_commit, input="", log=True)
223 sh.call("git", "checkout", user_virtual_commit, "--")
224 pre_usage = scripts.get_disk_usage()
226 sh.call("git", "merge", next_virtual_commit)
227 except shell.CallError as e:
228 conflicts = e.stderr.count("CONFLICT") # not perfect, if there is a file named CONFLICT
229 logging.info("Merge failed with these messages:\n\n" + e.stderr)
230 # Run the application's specific merge resolution algorithms
231 # and see if we can salvage it
233 if d.application.resolveConflicts(curdir):
234 logging.info("Resolved conflicts with application specific knowledge")
235 sh.call("git", "commit", "-a", "-m", "merge")
237 # XXX: Maybe should recalculate conflicts
238 logging.info("Conflict info:\n" + sh.eval("git", "diff"))
240 # Keeping all of our autoinstalls in shared memory is
241 # a recipe for disaster, so let's move them to slightly
242 # less volatile storage (a temporary directory)
243 os.chdir(tempfile.gettempdir())
244 newdir = tempfile.mkdtemp(prefix="wizard")
245 # shutil, not os; at least on Ubuntu os.move fails
246 # with "[Errno 18] Invalid cross-device link"
247 shutil.move(curdir, newdir)
248 shutil.rmtree(os.path.dirname(curdir))
249 curdir = os.path.join(newdir, "repo")
251 print "%d %s" % (conflicts, curdir)
254 post_usage = scripts.get_disk_usage()
255 kib_delta = (post_usage - pre_usage) / 1024
256 if kib_avail is not None and kib_delta - kib_avail < kib_buffer:
259 def parse_args(argv, baton):
260 usage = """usage: %prog upgrade [ARGS] [DIR]
262 Upgrades an autoinstall to the latest version. This involves
263 updating files and running .scripts/update. If the merge fails,
264 this program will write the number of conflicts and the directory
265 of the conflicted working tree to stdout, separated by a space."""
266 parser = command.WizardOptionParser(usage)
267 parser.add_option("--dry-run", dest="dry_run", action="store_true",
268 default=False, help="Prints would would be run without changing anything")
269 # notice trailing underscore
270 parser.add_option("--continue", dest="continue_", action="store_true",
271 default=False, help="Continues an upgrade that has had its merge manually "
272 "resolved using the current working directory as the resolved copy.")
273 parser.add_option("--force", dest="force", action="store_true",
274 default=False, help="Force running upgrade even if it's already at latest version.")
275 baton.push(parser, "srv_path")
276 options, args = parser.parse_all(argv)
278 parser.error("too many arguments")
281 class Error(command.Error):
282 """Base exception for all exceptions raised by upgrade"""
285 class QuotaTooLow(Error):
289 ERROR: The locker quota was too low to complete the autoinstall
293 class AlreadyUpgraded(Error):
297 ERROR: This autoinstall is already at the latest version."""
299 class MergeFailed(Error):
303 ERROR: Merge failed. Resolve the merge by cd'ing to the
304 temporary directory, finding conflicted files with `git status`,
305 resolving the files, adding them using `git add` and then
306 running `wizard upgrade --continue`."""
308 class LocalChangesError(Error):
312 ERROR: Local changes occurred in the install while the merge was
313 being processed so that a pull would not result in a fast-forward.
314 The best way to resolve this is probably to attempt an upgrade again,
315 with git rerere to remember merge resolutions (XXX: not sure if
316 this actually works)."""
318 class BlacklistedError(Error):
322 ERROR: This autoinstall was manually blacklisted against errors;
323 if the user has not been notified of this, please send them