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