2 import distutils.version
5 import logging.handlers
10 from wizard import app, command, deploy, scripts, shell, util
12 kib_buffer = 1024 * 30 # 30 MiB we will always leave available
13 errno_blacklisted = 64
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()
50 # ignore blank blacklisted files
53 raise BlacklistedError(reason)
55 logging.warning("Application was blacklisted, but no reason was found");
56 # before doing verification, do a quick pull of tags
57 sh.call("git", "fetch", "--tags")
59 d.verifyTag(options.srv_path)
60 d.verifyGit(options.srv_path)
63 if not options.dry_run:
65 repo = d.application.repository(options.srv_path)
66 version = calculate_newest_version(sh, repo)
67 if version == d.app_version.scripts_tag and not options.force:
68 # don't log this error
69 # XXX: maybe we should build this in as a flag to add
70 # to exceptions w/ our exception handler
71 sys.stderr.write("Traceback:\n (n/a)\nAlreadyUpgraded\n")
73 logging.info("Upgrading %s" % os.getcwd())
74 kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
75 if kib_limit is not None and (kib_limit - kib_usage) < kib_buffer:
77 if not options.dry_run:
78 perform_pre_commit(sh)
79 # If /dev/shm exists, it's a tmpfs and we can use it
80 # to do a fast git merge. Don't forget to move it to
82 if not options.dry_run and not options.debug:
83 use_shm = os.path.exists("/dev/shm")
84 temp_dir, temp_wc_dir = perform_tmp_clone(sh, use_shm)
85 logging.debug("Temporary WC dir is %s", temp_wc_dir)
86 with util.ChangeDirectory(temp_wc_dir):
87 wc = deploy.WorkingCopy(".")
88 sh.call("git", "remote", "add", "scripts", repo)
89 sh.call("git", "fetch", "-q", "scripts")
90 user_commit, next_commit = calculate_parents(sh, version)
91 # save variables so that --continue will work
92 # yeah yeah no trailing newline whatever
93 open(".git/WIZARD_REPO", "w").write(repo)
94 open(".git/WIZARD_UPGRADE_VERSION", "w").write(version)
95 open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (user_commit, next_commit))
96 open(".git/WIZARD_SIZE", "w").write(str(scripts.get_disk_usage()))
98 open(".git/WIZARD_LOG_FILE", "w").write(options.log_file)
99 temp_wc_dir = perform_merge(sh, repo, d, wc, version, use_shm, kib_limit and kib_limit - kib_usage or None, options.non_interactive)
100 wc.location = temp_wc_dir
101 # variables: version, user_commit, next_commit, temp_wc_dir
102 with util.ChangeDirectory(temp_wc_dir):
104 sh.call("git", "status")
105 except shell.CallError:
108 sh.call("git", "commit", "-m", "throw-away commit")
109 message = make_commit_message(version)
110 new_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
111 final_commit = sh.eval("git", "commit-tree", new_tree,
112 "-p", user_commit, "-p", next_commit, input=message, log=True)
113 # a master branch may not necessarily exist if the user
114 # was manually installed to an earlier version
116 sh.call("git", "checkout", "-q", "-b", "master", "--")
117 except shell.CallError:
118 sh.call("git", "checkout", "-q", "master", "--")
119 sh.call("git", "reset", "-q", "--hard", final_commit)
120 # This is a quick sanity check to make sure we didn't completely
124 # Till now, all of our operations were in a tmp sandbox.
126 logging.info("Dry run, bailing. See results at %s" % temp_wc_dir)
128 # Ok, now we have to do a crazy complicated dance to see if we're
129 # going to have enough quota to finish what we need
130 pre_size = int(open(os.path.join(temp_wc_dir, ".git/WIZARD_SIZE"), "r").read())
131 post_size = scripts.get_disk_usage(temp_wc_dir)
132 kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
133 backup = d.backup(options)
134 if kib_limit is not None and (kib_limit - kib_usage) - (post_size - pre_size) / 1024 < kib_buffer:
135 shutil.rmtree(os.path.join(".scripts/backups", sh.eval("wizard", "restore").splitlines()[0]))
137 # XXX: frob .htaccess to make site inaccessible
138 with util.IgnoreKeyboardInterrupts():
139 with util.LockDirectory(".scripts-upgrade-lock"):
140 sh.call("git", "fetch", "--tags")
141 # git merge (which performs a fast forward)
142 sh.call("git", "pull", "-q", temp_wc_dir, "master")
143 version_obj = distutils.version.LooseVersion(version.partition('-')[2])
146 d.upgrade(version_obj, options)
148 except app.UpgradeFailure:
149 logging.warning("Upgrade failed: rolling back")
150 perform_restore(d, backup)
152 except deploy.WebVerificationError as e:
153 logging.warning("Web verification failed: rolling back")
154 perform_restore(d, backup)
155 raise app.UpgradeVerificationFailure()
156 # XXX: frob .htaccess to make site accessible
157 # to do this, check if .htaccess changed, first. Upgrade
158 # process might have frobbed it. Don't be
159 # particularly worried if the segment disappeared
161 if use_shm and temp_dir and os.path.exists(temp_dir):
162 shutil.rmtree(temp_dir)
163 if not options.non_interactive:
164 print "Upgrade complete"
166 def perform_restore(d, backup):
167 # You don't want d.restore() because it doesn't perform
168 # the file level backup
169 shell.Shell().call("wizard", "restore", backup)
172 except deploy.WebVerificationError:
173 logging.critical("Web verification failed after rollback")
175 def make_commit_message(version):
176 message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), version, util.get_git_footer())
178 message += "\nUpgraded-by: " + util.get_operator_git()
179 except util.NoOperatorInfo:
183 def calculate_newest_version(sh, repo):
184 # XXX: put this in Application
185 return sh.eval("git", "--git-dir="+repo, "describe", "--tags", "master")
187 def calculate_parents(sh, version):
188 user_commit = sh.eval("git", "rev-parse", "HEAD")
189 next_commit = sh.eval("git", "rev-parse", version)
190 return user_commit, next_commit
192 def perform_pre_commit(sh):
193 message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
195 message += "\nPre-commit-by: " + util.get_operator_git()
196 except util.NoOperatorInfo:
199 sh.call("git", "commit", "-a", "-m", message)
200 except shell.CallError:
201 logging.info("No changes detected")
203 def perform_tmp_clone(sh, use_shm):
205 dir = "/dev/shm/wizard"
206 if not os.path.exists(dir):
211 temp_dir = tempfile.mkdtemp(prefix="wizard", dir=dir)
212 temp_wc_dir = os.path.join(temp_dir, "repo")
213 logging.info("Using temporary directory: " + temp_wc_dir)
214 sh.call("git", "clone", "-q", "--shared", ".", temp_wc_dir)
215 return temp_dir, temp_wc_dir
217 def perform_merge(sh, repo, d, wc, version, use_shm, kib_avail, non_interactive):
218 # Note: avail_quota == None means unlimited
219 # naive merge algorithm:
220 # sh.call("git", "merge", "-m", message, "scripts/master")
221 # crazy merge algorithm:
222 def make_virtual_commit(tag, parents = []):
223 """WARNING: Changes state of Git repository"""
224 sh.call("git", "checkout", "-q", tag, "--")
226 for file in wc.application.parametrized_files:
228 sh.call("git", "add", "--", file)
229 except shell.CallError:
231 virtual_tree = sh.eval("git", "write-tree", log=True)
232 parent_args = itertools.chain(*(["-p", p] for p in parents))
233 virtual_commit = sh.eval("git", "commit-tree", virtual_tree,
234 *parent_args, input="", log=True)
235 sh.call("git", "reset", "--hard")
236 return virtual_commit
237 user_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
238 base_virtual_commit = make_virtual_commit(wc.app_version.scripts_tag)
239 next_virtual_commit = make_virtual_commit(version, [base_virtual_commit])
240 user_virtual_commit = sh.eval("git", "commit-tree", user_tree,
241 "-p", base_virtual_commit, input="", log=True)
242 sh.call("git", "checkout", user_virtual_commit, "--")
245 sh.call("git", "commit", "--amend", "-a", "-m", "amendment")
246 except shell.CallError as e:
249 sh.call("git", "config", "merge.conflictstyle", "diff3")
250 sh.call("git", "merge", next_virtual_commit)
251 except shell.CallError as e:
252 logging.info("Merge failed with these messages:\n\n" + e.stderr)
253 # Run the application's specific merge resolution algorithms
254 # and see if we can salvage it
256 if wc.resolveConflicts():
257 logging.info("Resolved conflicts with application specific knowledge")
258 sh.call("git", "commit", "-a", "-m", "merge")
260 logging.info("Conflict info:\n" + sh.eval("git", "diff"))
261 outlines = sh.eval("git", "ls-files", "--unmerged").splitlines()
263 for line in outlines:
264 _, _, _, name = line.split(None, 3)
266 conflicts = len(files)
267 curdir = mv_shm_to_tmp(curdir, use_shm)
269 open(os.path.join(d.location, ".scripts/pending"), "w").write(curdir)
271 print "%d %s" % (conflicts, curdir)
274 user_shell = os.getenv("SHELL")
275 if not user_shell: user_shell = "/bin/bash"
278 print "ERROR: The merge failed with %d conflicts in these files:" % conflicts
280 for file in sorted(files):
283 print "Please resolve these conflicts (edit and then `git add`), and"
284 print "then type 'exit'."
285 sh.call(user_shell, "-i", interactive=True)
286 if sh.eval("git", "ls-files", "--unmerged").strip():
288 print "WARNING: There are still unmerged files."
289 out = raw_input("Continue editing? [y/N]: ")
290 if out == "y" or out == "Y":
293 print "Aborting. The conflicted working copy can be found at:"
295 print " %s" % os.getcwd()
297 print "and you can resume the upgrade process by running in that directory:"
299 print " wizard upgrade --continue"
304 def mv_shm_to_tmp(curdir, use_shm):
305 if not use_shm: return curdir
306 # Keeping all of our autoinstalls in shared memory is
307 # a recipe for disaster, so let's move them to slightly
308 # less volatile storage (a temporary directory)
309 os.chdir(tempfile.gettempdir())
310 newdir = tempfile.mkdtemp(prefix="wizard")
311 # shutil, not os; at least on Ubuntu os.move fails
312 # with "[Errno 18] Invalid cross-device link"
313 shutil.move(curdir, newdir)
314 shutil.rmtree(os.path.dirname(curdir))
315 curdir = os.path.join(newdir, "repo")
318 def parse_args(argv, baton):
319 usage = """usage: %prog upgrade [ARGS] [DIR]
321 Upgrades an autoinstall to the latest version. This involves
322 updating files and running .scripts/update. If the merge fails,
323 this program will write the number of conflicts and the directory
324 of the conflicted working tree to stdout, separated by a space."""
325 parser = command.WizardOptionParser(usage)
326 parser.add_option("--dry-run", dest="dry_run", action="store_true",
327 default=False, help="Prints would would be run without changing anything")
328 # notice trailing underscore
329 parser.add_option("--continue", dest="continue_", action="store_true",
330 default=False, help="Continues an upgrade that has had its merge manually "
331 "resolved using the current working directory as the resolved copy.")
332 parser.add_option("--force", dest="force", action="store_true",
333 default=False, help="Force running upgrade even if it's already at latest version.")
334 parser.add_option("--non-interactive", dest="non_interactive", action="store_true",
335 default=False, help="Don't drop to shell in event of conflict.")
336 baton.push(parser, "srv_path")
337 options, args = parser.parse_all(argv)
339 parser.error("too many arguments")
342 class Error(command.Error):
343 """Base exception for all exceptions raised by upgrade"""
346 class QuotaTooLow(Error):
350 ERROR: The locker quota was too low to complete the autoinstall
354 class AlreadyUpgraded(Error):
359 ERROR: This autoinstall is already at the latest version."""
361 class MergeFailed(Error):
366 ERROR: Merge failed. Above is the temporary directory that
367 the conflicted merge is in: resolve the merge by cd'ing to the
368 temporary directory, finding conflicted files with `git status`,
369 resolving the files, adding them using `git add` and then
370 running `wizard upgrade --continue`."""
372 class LocalChangesError(Error):
376 ERROR: Local changes occurred in the install while the merge was
377 being processed so that a pull would not result in a fast-forward.
378 The best way to resolve this is probably to attempt an upgrade again,
379 with git rerere to remember merge resolutions (XXX: not sure if
380 this actually works)."""
382 class BlacklistedError(Error):
383 #: Reason why the autoinstall was blacklisted
385 exitcode = errno_blacklisted
386 def __init__(self, reason):
391 ERROR: This autoinstall was manually blacklisted against errors;
392 if the user has not been notified of this, please send them
395 The reason was: %s""" % self.reason