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