2 import distutils.version
5 import logging.handlers
9 from wizard import app, command, deploy, scripts, shell, util
11 kib_buffer = 1024 * 30 # 30 MiB we will always leave available
12 errno_blacklisted = 64
14 def main(argv, baton):
15 options, args = parse_args(argv, baton)
20 shell.drop_priviledges(dir, options.log_file)
24 use_shm = False # if you are running --continue, this is guaranteed to be False
26 try: # global try-finally for cleaning up /dev/shm if it's being used
28 temp_wc_dir = os.getcwd()
29 wc = deploy.WorkingCopy(".")
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.setup_file_logger(options.log_file, options.debug)
37 logging.info("Continuing upgrade...")
38 util.chdir(sh.eval("git", "config", "remote.origin.url"))
39 d = deploy.ProductionCopy(".")
41 sh.call("git", "status")
42 raise LocalChangesError()
43 except shell.CallError:
46 d = deploy.ProductionCopy(".")
47 if os.path.exists(".scripts/blacklisted"):
48 reason = open(".scripts/blacklisted").read()
50 raise BlacklistedError(reason)
52 d.verifyTag(options.srv_path)
53 d.verifyGit(options.srv_path)
56 if not options.dry_run:
58 repo = d.application.repository(options.srv_path)
59 version = calculate_newest_version(sh, repo)
60 if version == d.app_version.scripts_tag and not options.force:
61 # don't log this error
62 # XXX: maybe we should build this in as a flag to add
63 # to exceptions w/ our exception handler
64 sys.stderr.write("Traceback:\n (n/a)\nAlreadyUpgraded\n")
66 logging.info("Upgrading %s" % os.getcwd())
67 kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
68 if kib_limit is not None and (kib_limit - kib_usage) < kib_buffer:
70 if not options.dry_run:
71 perform_pre_commit(sh)
72 # If /dev/shm exists, it's a tmpfs and we can use it
73 # to do a fast git merge. Don't forget to move it to
75 if not options.dry_run:
76 use_shm = os.path.exists("/dev/shm")
77 temp_dir, temp_wc_dir = perform_tmp_clone(sh, use_shm)
78 with util.ChangeDirectory(temp_wc_dir):
79 wc = deploy.WorkingCopy(".")
80 sh.call("git", "remote", "add", "scripts", repo)
81 sh.call("git", "fetch", "-q", "scripts")
82 user_commit, next_commit = calculate_parents(sh, version)
83 # save variables so that --continue will work
84 # yeah yeah no trailing newline whatever
85 open(".git/WIZARD_REPO", "w").write(repo)
86 open(".git/WIZARD_UPGRADE_VERSION", "w").write(version)
87 open(".git/WIZARD_PARENTS", "w").write("%s\n%s" % (user_commit, next_commit))
88 open(".git/WIZARD_SIZE", "w").write(str(scripts.get_disk_usage()))
90 open(".git/WIZARD_LOG_FILE", "w").write(options.log_file)
91 perform_merge(sh, repo, d, wc, 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
114 # Till now, all of our operations were in a tmp sandbox.
116 logging.info("Dry run, bailing. See results at %s" % temp_wc_dir)
118 # Ok, now we have to do a crazy complicated dance to see if we're
119 # going to have enough quota to finish what we need
120 pre_size = int(open(os.path.join(temp_wc_dir, ".git/WIZARD_SIZE"), "r").read())
121 post_size = scripts.get_disk_usage(temp_wc_dir)
122 kib_usage, kib_limit = scripts.get_quota_usage_and_limit()
123 backup = d.backup(options)
124 if kib_limit is not None and (kib_limit - kib_usage) - (post_size - pre_size) / 1024 < kib_buffer:
125 shutil.rmtree(os.path.join(".scripts/backups", sh.eval("wizard", "restore").splitlines()[0]))
127 # XXX: frob .htaccess to make site inaccessible
128 with util.IgnoreKeyboardInterrupts():
129 with util.LockDirectory(".scripts-upgrade-lock"):
130 # git merge (which performs a fast forward)
131 sh.call("git", "pull", "-q", temp_wc_dir, "master")
132 version_obj = distutils.version.LooseVersion(version.partition('-')[2])
135 d.upgrade(version_obj, options)
137 except app.UpgradeFailure:
138 logging.warning("Upgrade failed: rolling back")
139 perform_restore(d, backup)
141 except deploy.WebVerificationError as e:
142 logging.warning("Web verification failed: rolling back")
143 perform_restore(d, backup)
144 raise app.UpgradeVerificationFailure(e.contents)
145 # XXX: frob .htaccess to make site accessible
146 # to do this, check if .htaccess changed, first. Upgrade
147 # process might have frobbed it. Don't be
148 # particularly worried if the segment disappeared
150 if use_shm and temp_dir and os.path.exists(temp_dir):
151 shutil.rmtree(temp_dir)
153 def perform_restore(d, backup):
154 # You don't want d.restore() because it doesn't perform
155 # the file level backup
156 shell.Shell().call("wizard", "restore", backup)
159 except deploy.WebVerificationError:
160 logging.critical("Web verification failed after rollback")
162 def make_commit_message(version):
163 message = "Upgraded autoinstall in %s to %s.\n\n%s" % (util.get_dir_owner(), version, util.get_git_footer())
165 message += "\nUpgraded-by: " + util.get_operator_git()
166 except util.NoOperatorInfo:
170 def calculate_newest_version(sh, repo):
171 # XXX: put this in Application
172 return sh.eval("git", "--git-dir="+repo, "describe", "--tags", "master")
174 def calculate_parents(sh, version):
175 user_commit = sh.eval("git", "rev-parse", "HEAD")
176 next_commit = sh.eval("git", "rev-parse", version)
177 return user_commit, next_commit
179 def perform_pre_commit(sh):
180 message = "Pre-commit of %s locker before autoinstall upgrade.\n\n%s" % (util.get_dir_owner(), util.get_git_footer())
182 message += "\nPre-commit-by: " + util.get_operator_git()
183 except util.NoOperatorInfo:
186 sh.call("git", "commit", "-a", "-m", message)
187 except shell.CallError:
188 logging.info("No changes detected")
190 def perform_tmp_clone(sh, use_shm):
192 dir = "/dev/shm/wizard"
193 if not os.path.exists(dir):
198 temp_dir = tempfile.mkdtemp(prefix="wizard", dir=dir)
199 temp_wc_dir = os.path.join(temp_dir, "repo")
200 logging.info("Using temporary directory: " + temp_wc_dir)
201 sh.call("git", "clone", "-q", "--shared", ".", temp_wc_dir)
202 return temp_dir, temp_wc_dir
204 def perform_merge(sh, repo, d, wc, version, use_shm, kib_avail):
205 # Note: avail_quota == None means unlimited
206 # naive merge algorithm:
207 # sh.call("git", "merge", "-m", message, "scripts/master")
208 # crazy merge algorithm:
209 def make_virtual_commit(tag, parents = []):
210 """WARNING: Changes state of Git repository"""
211 sh.call("git", "checkout", "-q", tag, "--")
213 for file in wc.application.parametrized_files:
215 sh.call("git", "add", "--", file)
216 except shell.CallError:
218 virtual_tree = sh.eval("git", "write-tree", log=True)
219 parent_args = itertools.chain(*(["-p", p] for p in parents))
220 virtual_commit = sh.eval("git", "commit-tree", virtual_tree,
221 *parent_args, input="", log=True)
222 sh.call("git", "reset", "--hard")
223 return virtual_commit
224 user_tree = sh.eval("git", "rev-parse", "HEAD^{tree}")
225 base_virtual_commit = make_virtual_commit(wc.app_version.scripts_tag)
226 next_virtual_commit = make_virtual_commit(version, [base_virtual_commit])
227 user_virtual_commit = sh.eval("git", "commit-tree", user_tree,
228 "-p", base_virtual_commit, input="", log=True)
229 sh.call("git", "checkout", user_virtual_commit, "--")
231 sh.call("git", "commit", "--amend", "-a", "-m", "amendment")
233 sh.call("git", "merge", next_virtual_commit)
234 except shell.CallError as e:
235 conflicts = e.stdout.count("CONFLICT") # not perfect, if there is a file named CONFLICT
236 logging.info("Merge failed with these messages:\n\n" + e.stderr)
237 # Run the application's specific merge resolution algorithms
238 # and see if we can salvage it
240 if wc.resolveConflicts():
241 logging.info("Resolved conflicts with application specific knowledge")
242 sh.call("git", "commit", "-a", "-m", "merge")
244 # XXX: Maybe should recalculate conflicts
245 logging.info("Conflict info:\n" + sh.eval("git", "diff"))
246 curdir = mv_shm_to_tmp(curdir, use_shm)
247 print "%d %s" % (conflicts, curdir)
250 def mv_shm_to_tmp(curdir, use_shm):
251 if not use_shm: return curdir
252 # Keeping all of our autoinstalls in shared memory is
253 # a recipe for disaster, so let's move them to slightly
254 # less volatile storage (a temporary directory)
255 os.chdir(tempfile.gettempdir())
256 newdir = tempfile.mkdtemp(prefix="wizard")
257 # shutil, not os; at least on Ubuntu os.move fails
258 # with "[Errno 18] Invalid cross-device link"
259 shutil.move(curdir, newdir)
260 shutil.rmtree(os.path.dirname(curdir))
261 curdir = os.path.join(newdir, "repo")
264 def parse_args(argv, baton):
265 usage = """usage: %prog upgrade [ARGS] [DIR]
267 Upgrades an autoinstall to the latest version. This involves
268 updating files and running .scripts/update. If the merge fails,
269 this program will write the number of conflicts and the directory
270 of the conflicted working tree to stdout, separated by a space."""
271 parser = command.WizardOptionParser(usage)
272 parser.add_option("--dry-run", dest="dry_run", action="store_true",
273 default=False, help="Prints would would be run without changing anything")
274 # notice trailing underscore
275 parser.add_option("--continue", dest="continue_", action="store_true",
276 default=False, help="Continues an upgrade that has had its merge manually "
277 "resolved using the current working directory as the resolved copy.")
278 parser.add_option("--force", dest="force", action="store_true",
279 default=False, help="Force running upgrade even if it's already at latest version.")
280 baton.push(parser, "srv_path")
281 options, args = parser.parse_all(argv)
283 parser.error("too many arguments")
286 class Error(command.Error):
287 """Base exception for all exceptions raised by upgrade"""
290 class QuotaTooLow(Error):
294 ERROR: The locker quota was too low to complete the autoinstall
298 class AlreadyUpgraded(Error):
302 ERROR: This autoinstall is already at the latest version."""
304 class MergeFailed(Error):
308 ERROR: Merge failed. Resolve the merge by cd'ing to the
309 temporary directory, finding conflicted files with `git status`,
310 resolving the files, adding them using `git add` and then
311 running `wizard upgrade --continue`."""
313 class LocalChangesError(Error):
317 ERROR: Local changes occurred in the install while the merge was
318 being processed so that a pull would not result in a fast-forward.
319 The best way to resolve this is probably to attempt an upgrade again,
320 with git rerere to remember merge resolutions (XXX: not sure if
321 this actually works)."""
323 class BlacklistedError(Error):
324 #: Reason why the autoinstall was blacklisted
326 exitcode = errno_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