2020-01-08 00:06:39 +01:00
|
|
|
"""
|
|
|
|
Use libraries from a virtualenv (by modifying sys.path) in production.
|
|
|
|
"""
|
2024-01-29 00:32:21 +01:00
|
|
|
|
2020-01-08 00:06:39 +01:00
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
|
2020-06-11 00:54:34 +02:00
|
|
|
|
2020-01-08 00:06:39 +01:00
|
|
|
def setup_path() -> None:
|
setup_path: Ensure that the right venv is activated.
`setup_path()` previously only checked that some `zulip-py3-venv` was
the `sys.prefix`, not that it was the one associated with this
deployment. When `uwsgi` is started, it is started from `bin/uwsgi`
within a `zulip-py3-venv` virtualenv, and as such sets
`sys.executable` to that, resulting in uwsgi workers picking up the
library path of that virtualenv. On first start, `sys.path` thus
already matches the expected virtualenv, and the `setup_path` in
`zproject.wsgi` does nothing.
If a rolling restart was later done into a deployment with a different
virtualenv, the `zproject.wsgi` call to `setup_path()` did not change
`sys.path` to the new virtualenv, since it was already running within
_a_ virtualenv. This led to dependency version mismatches, and
potentially even more disastrous consequences if the old (but still
erroneously in use) virtualenv was later garbage-collected.
PR #26771 was a previous attempt to resolve this, but failed due to
not thinking of the uwsgi binary itself as possibly providing a
virtualenv path. We leave the `chdir` hooks from that in-place, since
it cannot hurt for the "master" uwsgi process to be chdir'd to `/`,
and the `hook-post-fork` `chdir` is reasonable as well.
Resolve the virtualenv in `setup_path()`, and activate it if it
differs from the one that is currently active. To be sure that no
other old virtualenvs are used, we also filter out any paths which
appear to be from other Zulip virtualenvs.
2024-08-23 23:48:04 +02:00
|
|
|
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
|
|
venv = os.path.realpath(os.path.join(BASE_DIR, "zulip-py3-venv"))
|
|
|
|
if sys.prefix != venv:
|
|
|
|
sys.path = list(filter(lambda p: "/zulip-py3-venv/" not in p, sys.path))
|
2020-01-08 00:06:39 +01:00
|
|
|
activate_this = os.path.join(venv, "bin", "activate_this.py")
|
|
|
|
activate_locals = dict(__file__=activate_this)
|
2020-10-24 09:33:54 +02:00
|
|
|
with open(activate_this) as f:
|
2023-01-03 02:18:00 +01:00
|
|
|
exec(f.read(), activate_locals) # noqa: S102
|
2020-03-21 13:52:22 +01:00
|
|
|
# Check that the python version running this function
|
|
|
|
# is same as python version that created the virtualenv.
|
|
|
|
python_version = "python{}.{}".format(*sys.version_info[:2])
|
2021-02-12 08:20:45 +01:00
|
|
|
if not os.path.exists(os.path.join(venv, "lib", python_version)):
|
2020-01-08 00:06:39 +01:00
|
|
|
raise RuntimeError(venv + " was not set up for this Python version")
|