configure: create a python venv and ensure meson, sphinx
Subsystems (2)
cover configure: create a python venv and ensure meson, sphinx
This patch series creates a mandatory python virtual environment ("venv") during configure time and uses it to ensure the availability of meson and sphinx.
See https://www.qemu.org/2023/03/24/python/ for motivations. The summary is that the goal of this series is to ensure that the python used to run meson is the same python used to run Sphinx, tests, and any build-time python scripting we have. As it stands, meson and sphinx (and their extensions) *may* run in a different python environment than the one configured and chosen by the user at configure/build time.
The effective change of this series is that QEMU will now unconditionally create a venv at configure-time and will ensure that meson (and sphinx, if docs are enabled) are available through that venv.
Some important points as a pre-emptive "FAQ":
- This venv is unconditionally created and lives at {build_dir}/pyvenv.
- The python interpreter used by this venv is always the one identified by configure. (Which in turn is always the one specified by --python or $PYTHON)
- *almost* all python scripts in qemu.git executed as part of the build system, meson, sphinx, avocado tests, vm tests or CI are always executed within this venv.
(iotests are not yet integrated; I plan to tackle this separately as a follow-up in order to have a more tightly focused scope on that series.)
- It remains possible to build and test fully offline.
(In most cases, you just need meson and sphinx from your distro's repo.)
- Distribution packaged 'meson' and 'sphinx' are still utilized whenever possible as the highest preference.
- Vendored versions of e.g. 'meson' are always preferred to PyPI versions for speed, repeatability and ensuring tarball builds work as-is offline.
(Sphinx will not be vendored, just like it already isn't.)
- Missing dependencies, when possible, are fetched and installed on-demand automatically to make developer environments "just work".
- Works for Python 3.6 and up, on Fedora, OpenSuSE, Red Hat, CentOS, Alpine, Debian, Ubuntu, NetBSD, OpenBSD, and hopefully everywhere
- No new dependencies (...for most platforms. Debian and NetBSD get an asterisk.)
- The meson git submodule is unused after this series and can be removed.
... I could write more, and I'm sure there's a few things that need buffing out or changing here and there, but I think it's largely good.
So, enjoy!
~js
John Snow (22):
python: update pylint configuration
python: add mkvenv.py
mkvenv: add better error message for missing pyexpat module
mkvenv: add nested venv workaround
mkvenv: add ensure subcommand
mkvenv: add diagnose() method for ensure() failures
mkvenv: add console script entry point generation
mkvenv: work around broken pip installations on Debian 10 tests/docker: add python3-venv dependency
tests/vm: Configure netbsd to use Python 3.10
tests/vm: add py310-expat to NetBSD
python: add vendor.py utility
configure: create a python venv unconditionally python/wheels: add vendored meson package
configure: use 'mkvenv ensure meson' to bootstrap meson qemu.git: drop meson git submodule
tests: Use configure-provided pyvenv for tests
configure: move --enable-docs and --disable-docs back to configure
configure: bootstrap sphinx with mkvenv
configure: add --enable-pypi and --disable-pypi
configure: Add courtesy hint to Python version failure message mkvenv.py: experiment; use distlib to generate script entry points
Paolo Bonzini (5):
python: shut up "pip install" during "make check-minreqs"
mkvenv: create pip binary in virtual environment
Python: Drop support for Python 3.6
mkvenv: mark command as required
python: bump some of the dependencies
docs/about/build-platforms.rst | 2 +- docs/conf.py | 9 - docs/devel/acpi-bits.rst | 6 +- docs/devel/testing.rst | 14 +- docs/meson.build | 2 +- configure | 155 ++-- .gitlab-ci.d/buildtest-template.yml | 4 +- .gitlab-ci.d/buildtest.yml | 6 +- .gitmodules | 3 - meson | 1 - meson_options.txt | 2 - python/Makefile | 19 +- python/scripts/mkvenv.py | 858 ++++++++++++++++++ python/scripts/vendor.py | 74 ++ python/setup.cfg | 27 +- python/tests/flake8.sh | 1 + python/tests/isort.sh | 1 + python/tests/minreqs.txt | 16 +- python/tests/mypy.sh | 1 + python/tests/pylint.sh | 1 + python/wheels/meson-0.61.5-py3-none-any.whl | Bin 0 -> 862509 bytes .../org.centos/stream/8/x86_64/test-avocado | 4 +- scripts/device-crash-test | 2 +- scripts/meson-buildoptions.sh | 3 - scripts/qapi/mypy.ini | 2 +- tests/Makefile.include | 10 +- .../dockerfiles/debian-all-test-cross.docker | 3 +- .../dockerfiles/debian-hexagon-cross.docker | 3 +- .../dockerfiles/debian-riscv64-cross.docker | 3 +- .../dockerfiles/debian-tricore-cross.docker | 3 +- tests/requirements.txt | 7 +- tests/vm/netbsd | 2 + 32 files changed, 1108 insertions(+), 136 deletions(-) delete mode 160000 meson create mode 100644 python/scripts/mkvenv.py create mode 100755 python/scripts/vendor.py create mode 100644 python/wheels/meson-0.61.5-py3-none-any.whl
Signature · 1 line
2.40.0
PATCH 1/27 python: shut up "pip install" during "make check-minreqs"
From: Paolo Bonzini <[email protected]>
"make check-minreqs" runs pip without the --disable-pip-version-check option, which causes the obnoxious "A new release of pip available" message.
Recent versions of pip also complain that some of the dependencies in our virtual environment rely on "setup.py install" instead of providing a pyproject.toml file; apparently it is deprecated to install them directly from pip instead of letting the "wheel" package take care of them. So, install "wheel" in the virtual environment.
--- python/Makefile | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
python/Makefile +6 -3
@@ -54,6 +54,7 @@ pipenv check-pipenv: @echo "pipenv was dropped; try 'make check-minreqs' or 'make min-venv'" @exit 1 +PIP_INSTALL = pip install --disable-pip-version-check .PHONY: min-venv min-venv: $(QEMU_MINVENV_DIR) $(QEMU_MINVENV_DIR)/bin/activate $(QEMU_MINVENV_DIR) $(QEMU_MINVENV_DIR)/bin/activate: setup.cfg tests/minreqs.txt
@@ -62,10 +63,12 @@ $(QEMU_MINVENV_DIR) $(QEMU_MINVENV_DIR)/bin/activate: setup.cfg tests/minreqs.tx @( \ echo "ACTIVATE $(QEMU_MINVENV_DIR)"; \ . $(QEMU_MINVENV_DIR)/bin/activate; \ + echo "INSTALL wheel $(QEMU_MINVENV_DIR)"; \ + $(PIP_INSTALL) wheel 1>/dev/null; \ echo "INSTALL -r tests/minreqs.txt $(QEMU_MINVENV_DIR)";\ - pip install -r tests/minreqs.txt 1>/dev/null; \ + $(PIP_INSTALL) -r tests/minreqs.txt 1>/dev/null; \ echo "INSTALL -e qemu $(QEMU_MINVENV_DIR)"; \ - pip install -e . 1>/dev/null; \ + $(PIP_INSTALL) -e . 1>/dev/null; \ ) @touch $(QEMU_MINVENV_DIR)
@@ -100,7 +103,7 @@ check-dev: dev-venv .PHONY: develop develop: - pip3 install --disable-pip-version-check -e .[devel] + $(PIP_INSTALL) -e .[devel] .PHONY: check check:
Signature · 1 line
2.40.0
PATCH 2/27 python: update pylint configuration
In reply to John SnowPylint 2.17.x decided that SocketAddrT was a bad name for a Type Alias for some reason. Sure, fine, whatever.
--- python/setup.cfg | 1 + 1 file changed, 1 insertion(+)
python/setup.cfg +1 -0
@@ -132,6 +132,7 @@ good-names=i, fd, # fd = os.open(...) c, # for c in string: ... T, # for TypeVars. See pylint#3401 + SocketAddrT, # Not sure why this is invalid. [pylint.similarities] # Ignore imports when computing similarities.
Signature · 1 line
2.40.0
PATCH 3/27 python: add mkvenv.py
In reply to John SnowThis script will be responsible for building a lightweight Python virtual environment at configure time. It works with Python 3.6 or newer.
It has been designed to:
- work *offline*, no PyPI required.
- work *quickly*, The fast path is only ~65ms on my machine.
- work *robustly*, with multiple fallbacks to keep things working.
- work *cooperatively*, using system packages where possible. (You can use your distro's meson, no problem.)
Due to its unique position in the build chain, it exists outside of the installable python packages in-tree and *must* be runnable without any third party dependencies.
Under normal circumstances, the only dependency required to execute this script is Python 3.6+ itself. The script is *faster* by several seconds when setuptools and pip are installed in the host environment, which is probably the case for a typical multi-purpose developer workstation.
In the event that pip/setuptools are missing or not usable, additional dependencies may be required on some distributions which remove certain Python stdlib modules to package them separately:
- Debian may require python3-venv to provide "ensurepip"
- NetBSD may require py310-expat to provide "pyexpat" * (* Or whichever version is current for NetBSD.)
--- python/scripts/mkvenv.py | 289 +++++++++++++++++++++++++++++++++++++++ python/setup.cfg | 9 ++ python/tests/flake8.sh | 1 + python/tests/isort.sh | 1 + python/tests/mypy.sh | 1 + python/tests/pylint.sh | 1 + 6 files changed, 302 insertions(+) create mode 100644 python/scripts/mkvenv.py
python/scripts/mkvenv.py new file +289 -0
@@ -0,0 +1,289 @@ +""" +mkvenv - QEMU pyvenv bootstrapping utility + +usage: mkvenv [-h] command ... + +QEMU pyvenv bootstrapping utility + +options: + -h, --help show this help message and exit + +Commands: + command Description + create create a venv + +-------------------------------------------------- + +usage: mkvenv create [-h] target + +positional arguments: + target Target directory to install virtual environment into. + +options: + -h, --help show this help message and exit + +""" + +# Copyright (C) 2022-2023 Red Hat, Inc. +# +# Authors: +# John Snow <[email protected]> +# Paolo Bonzini <[email protected]> +# +# This work is licensed under the terms of the GNU GPL, version 2 or +# later. See the COPYING file in the top-level directory. + +import argparse +from importlib.util import find_spec +import logging +import os +from pathlib import Path +import subprocess +import sys +from types import SimpleNamespace +from typing import Any, Optional, Union +import venv + + +# Do not add any mandatory dependencies from outside the stdlib: +# This script *must* be usable standalone! + +DirType = Union[str, bytes, "os.PathLike[str]", "os.PathLike[bytes]"] +logger = logging.getLogger("mkvenv") + + +class Ouch(RuntimeError): + """An Exception class we can't confuse with a builtin.""" + + +class QemuEnvBuilder(venv.EnvBuilder): + """ + An extension of venv.EnvBuilder for building QEMU's configure-time venv. + + As of this commit, it does not yet do anything particularly + different than the standard venv-creation utility. The next several + commits will gradually change that in small commits that highlight + each feature individually. + + Parameters for base class init: + - system_site_packages: bool = False + - clear: bool = False + - symlinks: bool = False + - upgrade: bool = False + - with_pip: bool = False + - prompt: Optional[str] = None + - upgrade_deps: bool = False (Since 3.9) + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + logger.debug("QemuEnvBuilder.__init__(...)") + super().__init__(*args, **kwargs) + + # Make the context available post-creation: + self._context: Optional[SimpleNamespace] = None + + def ensure_directories(self, env_dir: DirType) -> SimpleNamespace: + logger.debug("ensure_directories(env_dir=%s)", env_dir) + self._context = super().ensure_directories(env_dir) + return self._context + + def get_value(self, field: str) -> str: + """ + Get a string value from the context namespace after a call to build. + + For valid field names, see: + https://docs.python.org/3/library/venv.html#venv.EnvBuilder.ensure_directories + """ + ret = getattr(self._context, field) + assert isinstance(ret, str) + return ret + + +def need_ensurepip() -> bool: + """ + Tests for the presence of setuptools and pip. + + :return: `True` if we do not detect both packages. + """ + # Don't try to actually import them, it's fraught with danger: + # https://github.com/pypa/setuptools/issues/2993 + if find_spec("setuptools") and find_spec("pip"): + return False + return True + + +def check_ensurepip(with_pip: bool) -> None: + """ + Check that we have ensurepip. + + Raise a fatal exception with a helpful hint if it isn't available. + """ + if with_pip and not find_spec("ensurepip"): + msg = ( + "Python's ensurepip module is not found.\n" + "It's normally part of the Python standard library, " + "maybe your distribution packages it separately?\n" + "Either install ensurepip, or alleviate the need for it in the " + "first place by installing pip and setuptools for " + f"'{sys.executable}'.\n" + "(Hint: Debian puts ensurepip in its python3-venv package.)" + ) + raise Ouch(msg) + + +def make_venv( # pylint: disable=too-many-arguments + env_dir: Union[str, Path], + system_site_packages: bool = False, + clear: bool = True, + symlinks: Optional[bool] = None, + with_pip: Optional[bool] = None, +) -> None: + """ + Create a venv using `QemuEnvBuilder`. + + This is analogous to the `venv.create` module-level convenience + function that is part of the Python stdblib, except it uses + `QemuEnvBuilder` instead. + + :param env_dir: The directory to create/install to. + :param system_site_packages: + Allow inheriting packages from the system installation. + :param clear: When True, fully remove any prior venv and files. + :param symlinks: + Whether to use symlinks to the target interpreter or not. If + left unspecified, it will use symlinks except on Windows to + match behavior with the "venv" CLI tool. + :param with_pip: + Whether to run "ensurepip" or not. If unspecified, this will + default to False if system_site_packages is True and a usable + version of pip is found. + """ + logger.debug( + "%s: make_venv(env_dir=%s, system_site_packages=%s, " + "clear=%s, symlinks=%s, with_pip=%s)", + __file__, + str(env_dir), + system_site_packages, + clear, + symlinks, + with_pip, + ) + + # ensurepip is slow: venv creation can be very fast for cases where + # we allow the use of system_site_packages. Toggle ensure_pip on only + # in the cases where we really need it. + if with_pip is None: + with_pip = True if not system_site_packages else need_ensurepip() + logger.debug("with_pip unset, choosing %s", with_pip) + + check_ensurepip(with_pip) + + if symlinks is None: + # Default behavior of standard venv CLI + symlinks = os.name != "nt" + + builder = QemuEnvBuilder( + system_site_packages=system_site_packages, + clear=clear, + symlinks=symlinks, + with_pip=with_pip, + ) + + style = "non-isolated" if builder.system_site_packages else "isolated" + print( + f"mkvenv: Creating {style} virtual environment" + f" at '{str(env_dir)}'", + file=sys.stderr, + ) + + try: + logger.debug("Invoking builder.create()") + try: + builder.create(str(env_dir)) + except SystemExit as exc: + # Some versions of the venv module raise SystemExit; *nasty*! + # We want the exception that prompted it. It might be a subprocess + # error that has output we *really* want to see. + logger.debug("Intercepted SystemExit from EnvBuilder.create()") + raise exc.__cause__ or exc.__context__ or exc + logger.debug("builder.create() finished") + except subprocess.CalledProcessError as exc: + logger.error("mkvenv subprocess failed:") + logger.error("cmd: %s", exc.cmd) + logger.error("returncode: %d", exc.returncode) + + def _stringify(data: Union[str, bytes]) -> str: + if isinstance(data, bytes): + return data.decode() + return data + + lines = [] + if exc.stdout: + lines.append("========== stdout ==========") + lines.append(_stringify(exc.stdout)) + lines.append("============================") + if exc.stderr: + lines.append("========== stderr ==========") + lines.append(_stringify(exc.stderr)) + lines.append("============================") + if lines: + logger.error(os.linesep.join(lines)) + + raise Ouch("VENV creation subprocess failed.") from exc + + # print the python executable to stdout for configure. + print(builder.get_value("env_exe")) + + +def _add_create_subcommand(subparsers: Any) -> None: + subparser = subparsers.add_parser("create", help="create a venv") + subparser.add_argument( + "target", + type=str, + action="store", + help="Target directory to install virtual environment into.", + ) + + +def main() -> int: + """CLI interface to make_qemu_venv. See module docstring.""" + if os.environ.get("DEBUG") or os.environ.get("GITLAB_CI"): + # You're welcome. + logging.basicConfig(level=logging.DEBUG) + elif os.environ.get("V"): + logging.basicConfig(level=logging.INFO) + + parser = argparse.ArgumentParser( + prog="mkvenv", + description="QEMU pyvenv bootstrapping utility", + ) + subparsers = parser.add_subparsers( + title="Commands", + dest="command", + metavar="command", + help="Description", + ) + + _add_create_subcommand(subparsers) + + args = parser.parse_args() + try: + if args.command == "create": + make_venv( + args.target, + system_site_packages=True, + clear=True, + ) + logger.debug("mkvenv.py %s: exiting", args.command) + except Ouch as exc: + print("\n*** Ouch! ***\n", file=sys.stderr) + print(str(exc), "\n\n", file=sys.stderr) + return 1 + except: # pylint: disable=bare-except + logger.exception("mkvenv did not complete successfully:") + return 2 + return 0 + + +if __name__ == "__main__": + sys.exit(main())
python/setup.cfg +9 -0
@@ -103,6 +103,15 @@ ignore_missing_imports = True [mypy-pygments] ignore_missing_imports = True +[mypy-importlib.metadata] +ignore_missing_imports = True + +[mypy-importlib_metadata] +ignore_missing_imports = True + +[mypy-pkg_resources] +ignore_missing_imports = True + [pylint.messages control] # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this
python/tests/flake8.sh +1 -0
@@ -1,2 +1,3 @@ #!/bin/sh -e python3 -m flake8 qemu/ +python3 -m flake8 scripts/
python/tests/isort.sh +1 -0
@@ -1,2 +1,3 @@ #!/bin/sh -e python3 -m isort -c qemu/ +python3 -m isort -c scripts/
python/tests/mypy.sh +1 -0
@@ -1,2 +1,3 @@ #!/bin/sh -e python3 -m mypy -p qemu +python3 -m mypy scripts/
python/tests/pylint.sh +1 -0
@@ -1,3 +1,4 @@ #!/bin/sh -e # See commit message for environment variable explainer. SETUPTOOLS_USE_DISTUTILS=stdlib python3 -m pylint qemu/ +SETUPTOOLS_USE_DISTUTILS=stdlib python3 -m pylint scripts/
Signature · 1 line
2.40.0
PATCH 4/27 mkvenv: add better error message for missing pyexpat module
In reply to John SnowNetBSD debundles pyexpat from python, but ensurepip needs pyexpat. Try our best to offer a helpful error message instead of just failing catastrophically.
--- python/scripts/mkvenv.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-)
python/scripts/mkvenv.py +17 -1
@@ -118,7 +118,10 @@ def check_ensurepip(with_pip: bool) -> None: Raise a fatal exception with a helpful hint if it isn't available. """ - if with_pip and not find_spec("ensurepip"): + if not with_pip: + return + + if not find_spec("ensurepip"): msg = ( "Python's ensurepip module is not found.\n" "It's normally part of the Python standard library, "
@@ -130,6 +133,19 @@ def check_ensurepip(with_pip: bool) -> None: ) raise Ouch(msg) + # ensurepip uses pyexpat, which can also go missing on us: + if not find_spec("pyexpat"): + msg = ( + "Python's pyexpat module is not found.\n" + "It's normally part of the Python standard library, " + "maybe your distribution packages it separately?\n" + "Either install pyexpat, or alleviate the need for it in the " + "first place by installing pip and setuptools for " + f"'{sys.executable}'.\n\n" + "(Hint: NetBSD's pkgsrc debundles this to e.g. 'py310-expat'.)" + ) + raise Ouch(msg) + def make_venv( # pylint: disable=too-many-arguments env_dir: Union[str, Path],
Signature · 1 line
2.40.0
PATCH 5/27 mkvenv: add nested venv workaround
In reply to John SnowPython virtual environments do not typically nest; they may inherit from the top-level system packages or not at all.
For our purposes, it would be convenient to emulate "nested" virtual environments to allow callers of the configure script to install specific versions of python utilities in order to test build system features, utility version compatibility, etc.
While it is possible to install packages into the system environment (say, by using the --user flag), it's nicer to install test packages into a totally isolated environment instead.
As detailed in https://www.qemu.org/2023/03/24/python/, Emulate a nested venv environment by using .pth files installed into the site-packages folder that points to the parent environment when appropriate.
--- python/scripts/mkvenv.py | 92 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 87 insertions(+), 5 deletions(-)
python/scripts/mkvenv.py +87 -5
@@ -38,8 +38,10 @@ import logging import os from pathlib import Path +import site import subprocess import sys +import sysconfig from types import SimpleNamespace from typing import Any, Optional, Union import venv
@@ -52,6 +54,11 @@ logger = logging.getLogger("mkvenv") +def inside_a_venv() -> bool: + """Returns True if it is executed inside of a virtual environment.""" + return sys.prefix != sys.base_prefix + + class Ouch(RuntimeError): """An Exception class we can't confuse with a builtin."""
@@ -60,10 +67,9 @@ class QemuEnvBuilder(venv.EnvBuilder): """ An extension of venv.EnvBuilder for building QEMU's configure-time venv. - As of this commit, it does not yet do anything particularly - different than the standard venv-creation utility. The next several - commits will gradually change that in small commits that highlight - each feature individually. + The primary difference is that it emulates a "nested" virtual + environment when invoked from inside of an existing virtual + environment by including packages from the parent. Parameters for base class init: - system_site_packages: bool = False
@@ -77,16 +83,89 @@ class QemuEnvBuilder(venv.EnvBuilder): def __init__(self, *args: Any, **kwargs: Any) -> None: logger.debug("QemuEnvBuilder.__init__(...)") + + # For nested venv emulation: + self.use_parent_packages = False + if inside_a_venv(): + # Include parent packages only if we're in a venv and + # system_site_packages was True. + self.use_parent_packages = kwargs.pop( + "system_site_packages", False + ) + # Include system_site_packages only when the parent, + # The venv we are currently in, also does so. + kwargs["system_site_packages"] = sys.base_prefix in site.PREFIXES + super().__init__(*args, **kwargs) # Make the context available post-creation: self._context: Optional[SimpleNamespace] = None + def get_parent_libpath(self) -> Optional[str]: + """Return the libpath of the parent venv, if applicable.""" + if self.use_parent_packages: + return sysconfig.get_path("purelib") + return None + + @staticmethod + def compute_venv_libpath(context: SimpleNamespace) -> str: + """ + Compatibility wrapper for context.lib_path for Python < 3.12 + """ + # Python 3.12+, not strictly necessary because it's documented + # to be the same as 3.10 code below: + if sys.version_info >= (3, 12): + return context.lib_path + + # Python 3.10+ + if "venv" in sysconfig.get_scheme_names(): + lib_path = sysconfig.get_path( + "purelib", scheme="venv", vars={"base": context.env_dir} + ) + assert lib_path is not None + return lib_path + + # For Python <= 3.9 we need to hardcode this. Fortunately the + # code below was the same in Python 3.6-3.10, so there is only + # one case. + if sys.platform == "win32": + return os.path.join(context.env_dir, "Lib", "site-packages") + return os.path.join( + context.env_dir, + "lib", + "python%d.%d" % sys.version_info[:2], + "site-packages", + ) + def ensure_directories(self, env_dir: DirType) -> SimpleNamespace: logger.debug("ensure_directories(env_dir=%s)", env_dir) self._context = super().ensure_directories(env_dir) return self._context + def create(self, env_dir: DirType) -> None: + logger.debug("create(env_dir=%s)", env_dir) + super().create(env_dir) + assert self._context is not None + self.post_post_setup(self._context) + + def post_post_setup(self, context: SimpleNamespace) -> None: + """ + The final, final hook. Enter the venv and run commands inside of it. + """ + if self.use_parent_packages: + # We're inside of a venv and we want to include the parent + # venv's packages. + parent_libpath = self.get_parent_libpath() + assert parent_libpath is not None + logger.debug("parent_libpath: %s", parent_libpath) + + our_libpath = self.compute_venv_libpath(context) + logger.debug("our_libpath: %s", our_libpath) + + pth_file = os.path.join(our_libpath, "nested.pth") + with open(pth_file, "w", encoding="UTF-8") as file: + file.write(parent_libpath + os.linesep) + def get_value(self, field: str) -> str: """ Get a string value from the context namespace after a call to build.
@@ -206,9 +285,12 @@ def make_venv( # pylint: disable=too-many-arguments ) style = "non-isolated" if builder.system_site_packages else "isolated" + nested = "" + if builder.use_parent_packages: + nested = f"(with packages from '{builder.get_parent_libpath()}') " print( f"mkvenv: Creating {style} virtual environment" - f" at '{str(env_dir)}'", + f" {nested}at '{str(env_dir)}'", file=sys.stderr, )
Signature · 1 line
2.40.0
PATCH 6/27 mkvenv: add ensure subcommand
In reply to John SnowThis command is to be used to add various packages (or ensure they're already present) into the configure-provided venv in a modular fashion.
Examples:
mkvenv ensure --online --dir "${source_dir}/python/wheels/" "meson>=0.61.5" mkvenv ensure --online "sphinx>=1.6.0"
mkvenv ensure "qemu.qmp==0.0.2"
It's designed to look for packages in three places, in order:
(1) In system packages, if the version installed is already good enough. This way your distribution-provided meson, sphinx, etc are always used as first preference.
(2) In a vendored packages directory. Here I am suggesting qemu.git/python/wheels/ as that directory. This is intended to serve as a replacement for vendoring the meson source for QEMU tarballs. It is also highly likely to be extremely useful for packaging the "qemu.qmp" package in source distributions for platforms that do not yet package qemu.qmp separately.
(3) Online, via PyPI, ***only when "--online" is passed***. This is only ever used as a fallback if the first two sources do not have an appropriate package that meets the requirement. The ability to build QEMU and run tests *completely offline* is not impinged.
--- python/scripts/mkvenv.py | 130 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 129 insertions(+), 1 deletion(-)
python/scripts/mkvenv.py +129 -1
@@ -11,6 +11,7 @@ Commands: command Description create create a venv + ensure Ensure that the specified package is installed. --------------------------------------------------
@@ -22,6 +23,18 @@ options: -h, --help show this help message and exit +-------------------------------------------------- + +usage: mkvenv ensure [-h] [--online] [--dir DIR] dep_spec... + +positional arguments: + dep_spec PEP 508 Dependency specification, e.g. 'meson>=0.61.5' + +options: + -h, --help show this help message and exit + --online Install packages from PyPI, if necessary. + --dir DIR Path to vendored packages where we may install from. + """ # Copyright (C) 2022-2023 Red Hat, Inc.
@@ -43,7 +56,12 @@ import sys import sysconfig from types import SimpleNamespace -from typing import Any, Optional, Union +from typing import ( + Any, + Optional, + Sequence, + Union, +) import venv
@@ -333,6 +351,85 @@ def _stringify(data: Union[str, bytes]) -> str: print(builder.get_value("env_exe")) +def pip_install( + args: Sequence[str], + online: bool = False, + wheels_dir: Optional[Union[str, Path]] = None, + devnull: bool = False, +) -> None: + """ + Use pip to install a package or package(s) as specified in @args. + """ + loud = bool( + os.environ.get("DEBUG") + or os.environ.get("GITLAB_CI") + or os.environ.get("V") + ) + + full_args = [ + sys.executable, + "-m", + "pip", + "install", + "--disable-pip-version-check", + "-v" if loud else "-q", + ] + if not online: + full_args += ["--no-index"] + if wheels_dir: + full_args += ["--find-links", f"file://{str(wheels_dir)}"] + full_args += list(args) + subprocess.run( + full_args, + check=True, + stdout=subprocess.DEVNULL if devnull else None, + stderr=subprocess.DEVNULL if devnull else None, + ) + + +def ensure( + dep_specs: Sequence[str], + online: bool = False, + wheels_dir: Optional[Union[str, Path]] = None, +) -> None: + """ + Use pip to ensure we have the package specified by @dep_specs. + + If the package is already installed, do nothing. If online and + wheels_dir are both provided, prefer packages found in wheels_dir + first before connecting to PyPI. + + :param dep_specs: + PEP 508 dependency specifications. e.g. ['meson>=0.61.5']. + :param online: If True, fall back to PyPI. + :param wheels_dir: If specified, search this path for packages. + """ + # This first install command will: + # (A) Do nothing, if we already have a suitable package. + # (B) Install the package from vendored source, if possible. + # (C) Fail if neither A nor B. + try: + pip_install( + dep_specs, + online=False, + wheels_dir=wheels_dir, + devnull=online and not wheels_dir, + ) + # (A) or (B) happened. Success. + return + except subprocess.CalledProcessError: + # (C) Happened. + # The package is missing or isn't a suitable version, + # and we weren't able to install a suitable vendored package. + if online: + print( + f"mkvenv: installing {', '.join(dep_specs)}", file=sys.stderr + ) + pip_install(dep_specs, online=True) + else: + raise + + def _add_create_subcommand(subparsers: Any) -> None: subparser = subparsers.add_parser("create", help="create a venv") subparser.add_argument(
@@ -343,6 +440,30 @@ def _add_create_subcommand(subparsers: Any) -> None: ) +def _add_ensure_subcommand(subparsers: Any) -> None: + subparser = subparsers.add_parser( + "ensure", help="Ensure that the specified package is installed." + ) + subparser.add_argument( + "--online", + action="store_true", + help="Install packages from PyPI, if necessary.", + ) + subparser.add_argument( + "--dir", + type=str, + action="store", + help="Path to vendored packages where we may install from.", + ) + subparser.add_argument( + "dep_specs", + type=str, + action="store", + help="PEP 508 Dependency specification, e.g. 'meson>=0.61.5'", + nargs="+", + ) + + def main() -> int: """CLI interface to make_qemu_venv. See module docstring.""" if os.environ.get("DEBUG") or os.environ.get("GITLAB_CI"):
@@ -363,6 +484,7 @@ def main() -> int: ) _add_create_subcommand(subparsers) + _add_ensure_subcommand(subparsers) args = parser.parse_args() try:
@@ -372,6 +494,12 @@ def main() -> int: system_site_packages=True, clear=True, ) + if args.command == "ensure": + ensure( + dep_specs=args.dep_specs, + online=args.online, + wheels_dir=args.dir, + ) logger.debug("mkvenv.py %s: exiting", args.command) except Ouch as exc: print("\n*** Ouch! ***\n", file=sys.stderr)
Signature · 1 line
2.40.0
PATCH 7/27 mkvenv: add diagnose() method for ensure() failures
In reply to John SnowThis is a routine that is designed to print some usable info for human beings back out to the terminal if/when "mkvenv ensure" fails to locate or install a package during configure time, such as meson or sphinx.
Since we are requiring that "meson" and "sphinx" are installed to the same Python environment as QEMU is configured to build with, this can produce some surprising failures when things are mismatched. This method is here to try and ease that sting by offering some actionable diagnosis.
--- python/scripts/mkvenv.py | 165 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 152 insertions(+), 13 deletions(-)
python/scripts/mkvenv.py +152 -13
@@ -51,6 +51,8 @@ import logging import os from pathlib import Path +import re +import shutil import site import subprocess import sys
@@ -351,6 +353,115 @@ def _stringify(data: Union[str, bytes]) -> str: print(builder.get_value("env_exe")) +def pkgname_from_depspec(dep_spec: str) -> str: + """ + Parse package name out of a PEP-508 depspec. + + See https://peps.python.org/pep-0508/#names + """ + match = re.match( + r"^([A-Z0-9]([A-Z0-9._-]*[A-Z0-9])?)", dep_spec, re.IGNORECASE + ) + if not match: + raise ValueError( + f"dep_spec '{dep_spec}'" + " does not appear to contain a valid package name" + ) + return match.group(0) + + +def diagnose( + dep_spec: str, + online: bool, + wheels_dir: Optional[Union[str, Path]], + prog: Optional[str], +) -> str: + """ + Offer a summary to the user as to why a package failed to be installed. + + :param dep_spec: The package we tried to ensure, e.g. 'meson>=0.61.5' + :param online: Did we allow PyPI access? + :param prog: + Optionally, a shell program name that can be used as a + bellwether to detect if this program is installed elsewhere on + the system. This is used to offer advice when a program is + detected for a different python version. + :param wheels_dir: + Optionally, a directory that was searched for vendored packages. + """ + # pylint: disable=too-many-branches + + pkg_name = pkgname_from_depspec(dep_spec) + pkg_version = None + + has_importlib = False + try: + # Python 3.8+ stdlib + # pylint: disable=import-outside-toplevel + # pylint: disable=no-name-in-module + # pylint: disable=import-error + from importlib.metadata import ( # type: ignore + PackageNotFoundError, + version, + ) + + has_importlib = True + try: + pkg_version = version(pkg_name) + except PackageNotFoundError: + pass + except ModuleNotFoundError: + pass + + lines = [] + + if pkg_version: + lines.append( + f"Python package '{pkg_name}' version '{pkg_version}' was found," + " but isn't suitable." + ) + elif has_importlib: + lines.append( + f"Python package '{pkg_name}' was not found nor installed." + ) + else: + lines.append( + f"Python package '{pkg_name}' is either not found or" + " not a suitable version." + ) + + if wheels_dir: + lines.append( + "No suitable version found in, or failed to install from" + f" '{wheels_dir}'." + ) + else: + lines.append("No local package directory was searched.") + + if online: + lines.append("A suitable version could not be obtained from PyPI.") + else: + lines.append( + "mkvenv was configured to operate offline and did not check PyPI." + ) + + if prog and not pkg_version: + which = shutil.which(prog) + if which: + pypath = Path(sys.executable).resolve() + lines.append( + f"'{prog}' was detected on your system at '{which}', " + f"but the Python package '{pkg_name}' was not found by this " + f"Python interpreter ('{pypath}'). " + f"Typically this means that '{prog}' has been installed " + "against a different Python interpreter on your system." + ) + + lines = [f" • {line}" for line in lines] + lines.insert(0, f"Could not ensure availability of '{dep_spec}':") + return os.linesep.join(lines) + + def pip_install( args: Sequence[str], online: bool = False,
@@ -387,23 +498,11 @@ def pip_install( ) -def ensure( +def _do_ensure( dep_specs: Sequence[str], online: bool = False, wheels_dir: Optional[Union[str, Path]] = None, ) -> None: - """ - Use pip to ensure we have the package specified by @dep_specs. - - If the package is already installed, do nothing. If online and - wheels_dir are both provided, prefer packages found in wheels_dir - first before connecting to PyPI. - - :param dep_specs: - PEP 508 dependency specifications. e.g. ['meson>=0.61.5']. - :param online: If True, fall back to PyPI. - :param wheels_dir: If specified, search this path for packages. - """ # This first install command will: # (A) Do nothing, if we already have a suitable package. # (B) Install the package from vendored source, if possible.
@@ -430,6 +529,36 @@ def ensure( raise +def ensure( + dep_specs: Sequence[str], + online: bool = False, + wheels_dir: Optional[Union[str, Path]] = None, + prog: Optional[str] = None, +) -> None: + """ + Use pip to ensure we have the package specified by @dep_specs. + + If the package is already installed, do nothing. If online and + wheels_dir are both provided, prefer packages found in wheels_dir + first before connecting to PyPI. + + :param dep_specs: + PEP 508 dependency specifications. e.g. ['meson>=0.61.5']. + :param online: If True, fall back to PyPI. + :param wheels_dir: If specified, search this path for packages. + :param prog: + If specified, use this program name for error diagnostics that will + be presented to the user. e.g., 'sphinx-build' can be used as a + bellwether for the presence of 'sphinx'. + """ + print(f"mkvenv: checking for {', '.join(dep_specs)}", file=sys.stderr) + try: + _do_ensure(dep_specs, online, wheels_dir) + except subprocess.CalledProcessError as exc: + # Well, that's not good. + raise Ouch(diagnose(dep_specs[0], online, wheels_dir, prog)) from exc + + def _add_create_subcommand(subparsers: Any) -> None: subparser = subparsers.add_parser("create", help="create a venv") subparser.add_argument(
@@ -455,6 +584,15 @@ def _add_ensure_subcommand(subparsers: Any) -> None: action="store", help="Path to vendored packages where we may install from.", ) + subparser.add_argument( + "--diagnose", + type=str, + action="store", + help=( + "Name of a shell utility to use for " + "diagnostics if this command fails." + ), + ) subparser.add_argument( "dep_specs", type=str,
@@ -499,6 +637,7 @@ def main() -> int: dep_specs=args.dep_specs, online=args.online, wheels_dir=args.dir, + prog=args.diagnose, ) logger.debug("mkvenv.py %s: exiting", args.command) except Ouch as exc:
Signature · 1 line
2.40.0
Re: [PATCH 07/27] mkvenv: add diagnose() method for ensure() failures
Quoted 9 lines · John Snow
This is a routine that is designed to print some usable info for human beings back out to the terminal if/when "mkvenv ensure" fails to locate or install a package during configure time, such as meson or sphinx.
Since we are requiring that "meson" and "sphinx" are installed to the same Python environment as QEMU is configured to build with, this can produce some surprising failures when things are mismatched. This method is here to try and ease that sting by offering some actionable diagnosis.
I think this is a bit too verbose/scary, especially the "Ouch" for what was a totally normal occurrence before (no "--enable-docs" and sphinx absent or too old) and the "ERROR" from "pip install --no-index".
Here is an attempt to tone it down:
python/scripts/mkvenv.py +18 -7
@@ -74,6 +74,7 @@ Iterator, Optional, Sequence, + Tuple, Union, ) import venv
@@ -594,7 +595,7 @@ def diagnose( online: bool, wheels_dir: Optional[Union[str, Path]], prog: Optional[str], -) -> str: +) -> Tuple[str, bool]: """ Offer a summary to the user as to why a package failed to be installed.
@@ -610,6 +611,9 @@ def diagnose( """ # pylint: disable=too-many-branches + # Some errors are not particularly serious + bad = False + pkg_name = pkgname_from_depspec(dep_spec) pkg_version = None
@@ -654,11 +658,11 @@ def diagnose( "No suitable version found in, or failed to install from" f" '{wheels_dir}'." ) - else: - lines.append("No local package directory was searched.") + bad = True if online: lines.append("A suitable version could not be obtained from PyPI.") + bad = True else: lines.append( "mkvenv was configured to operate offline and did not check PyPI."
@@ -675,10 +679,14 @@ def diagnose( f"Typically this means that '{prog}' has been installed " "against a different Python interpreter on your system." ) + bad = True lines = [f" • {line}" for line in lines] - lines.insert(0, f"Could not ensure availability of '{dep_spec}':") - return os.linesep.join(lines) + if bad: + lines.insert(0, f"Could not ensure availability of '{dep_spec}':") + else: + lines.insert(0, f"'{dep_spec}' not found:") + return os.linesep.join(lines), bad def pip_install(
@@ -731,7 +739,7 @@ def _do_ensure( dep_specs, online=False, wheels_dir=wheels_dir, - devnull=online and not wheels_dir, + devnull=not wheels_dir, ) # (A) or (B) happened. Success. except subprocess.CalledProcessError:
@@ -778,7 +786,10 @@ def ensure( _do_ensure(dep_specs, online, wheels_dir) except subprocess.CalledProcessError as exc: # Well, that's not good. - raise Ouch(diagnose(dep_specs[0], online, wheels_dir, prog)) from exc + msg, bad = diagnose(dep_specs[0], online, wheels_dir, prog) + if bad: + raise Ouch(msg) from exc + print("", msg, "\n", sep="\n", file=sys.stderr) def post_venv_setup() -> None:
Paolo
Re: [PATCH 07/27] mkvenv: add diagnose() method for ensure() failures
Quoted 106 lines · Paolo Bonzini
Quoted 9 lines · John Snow
This is a routine that is designed to print some usable info for human beings back out to the terminal if/when "mkvenv ensure" fails to locate or install a package during configure time, such as meson or sphinx.
Since we are requiring that "meson" and "sphinx" are installed to the same Python environment as QEMU is configured to build with, this can produce some surprising failures when things are mismatched. This method is here to try and ease that sting by offering some actionable diagnosis.
I think this is a bit too verbose/scary, especially the "Ouch" for what was a totally normal occurrence before (no "--enable-docs" and sphinx absent or too old) and the "ERROR" from "pip install --no-index".
Here is an attempt to tone it down:
python/scripts/mkvenv.py +2
-1@@ -74,6 +74,7 @@ Iterator, Optional, Sequence, + Tuple, Union, ) import venv@@ -594,7 +595,7 @@ def diagnose( online: bool, wheels_dir: Optional[Union[str, Path]], prog: Optional[str], -) -> str: +) -> Tuple[str, bool]: """ Offer a summary to the user as to why a package failed to beinstalled.
python/scripts/mkvenv.py +5
-2@@ -610,6 +611,9 @@ def diagnose( """ # pylint: disable=too-many-branches + # Some errors are not particularly serious + bad = False + pkg_name = pkgname_from_depspec(dep_spec) pkg_version = None@@ -654,11 +658,11 @@ def diagnose( "No suitable version found in, or failed to install from" f" '{wheels_dir}'." ) - else: - lines.append("No local package directory was searched.") + bad = True if online: lines.append("A suitable version could not be obtained from PyPI.") + bad = True else: lines.append("mkvenv was configured to operate offline and did not check
PyPI."python/scripts/mkvenv.py +7
-4@@ -675,10 +679,14 @@ def diagnose( f"Typically this means that '{prog}' has been installed " "against a different Python interpreter on your system." ) + bad = True lines = [f" • {line}" for line in lines] - lines.insert(0, f"Could not ensure availability of '{dep_spec}':") - return os.linesep.join(lines) + if bad: + lines.insert(0, f"Could not ensure availability of '{dep_spec}':") + else: + lines.insert(0, f"'{dep_spec}' not found:") + return os.linesep.join(lines), bad def pip_install(@@ -731,7 +739,7 @@ def _do_ensure( dep_specs, online=False, wheels_dir=wheels_dir, - devnull=online and not wheels_dir, + devnull=not wheels_dir, ) # (A) or (B) happened. Success. except subprocess.CalledProcessError:@@ -778,7 +786,10 @@ def ensure( _do_ensure(dep_specs, online, wheels_dir) except subprocess.CalledProcessError as exc: # Well, that's not good. - raise Ouch(diagnose(dep_specs[0], online, wheels_dir, prog)) fromexc
python/scripts/mkvenv.py +4
-0+ msg, bad = diagnose(dep_specs[0], online, wheels_dir, prog) + if bad: + raise Ouch(msg) from exc + print("", msg, "\n", sep="\n", file=sys.stderr) def post_venv_setup() -> None:
Quoted 2 lines
Paolo
You're right, in the "optional" case for sphinx the error isn't really *that* bad or serious. I'll try to work this or something very similar to it in.
I was thinking it could be up to the caller to discard the input, but I suppose we can also route the semantics down into the tool, too.
I'll play with it.
--js
Quoted 1 line
Re: [PATCH 07/27] mkvenv: add diagnose() method for ensure() failures
Il gio 11 mag 2023, 17:53 John Snow <[email protected]> ha scritto:
Quoted 10 lines
You're right, in the "optional" case for sphinx the error isn't really *that* bad or serious. I'll try to work this or something very similar to it in.
I was thinking it could be up to the caller to discard the input, but I suppose we can also route the semantics down into the tool, too.
I'll play with it.
If you think that what I posted is okay or at least a start, I can squash it in.
Paolo
Quoted 3 lines
--js
Quoted 1 line
Re: [PATCH 07/27] mkvenv: add diagnose() method for ensure() failures
Quoted 12 lines · Paolo Bonzini
Il gio 11 mag 2023, 17:53 John Snow <[email protected]> ha scritto:
Quoted 8 lines
You're right, in the "optional" case for sphinx the error isn't really *that* bad or serious. I'll try to work this or something very similar to it in.
I was thinking it could be up to the caller to discard the input, but I suppose we can also route the semantics down into the tool, too.
Quoted 8 lines
Quoted 2 lines
I'll play with it.
If you think that what I posted is okay or at least a start, I can squash it in.
Paolo
I didn't want to bet that there wouldn't be more feedback 😅
but, you can squash it in pre-emptively and I'll do the same and we'll just see what happens.
--js
Quoted 1 line
PATCH 8/27 mkvenv: add console script entry point generation
In reply to John SnowWhen creating a virtual environment that inherits system packages, script entry points (like "meson", "sphinx-build", etc) are not re-generated with the correct shebang. When you are *inside* of the venv, this is not a problem, but if you are *outside* of it, you will not have a script that engages the virtual environment appropriately.
Add a mechanism that generates new entry points for pre-existing packages so that we can use these scripts to run "meson", "sphinx-build", "pip", unambiguously inside the venv.
NOTE: the "FIXME" command regarding Windows launcher binaries can be solved by using distlib. distlib is usually not installed on Linux distribution, but it is a dependency of pip (and therefore should be much more commonly available) on msys, where it is most useful.
--- python/scripts/mkvenv.py | 174 ++++++++++++++++++++++++++++++++++++++- python/setup.cfg | 1 + 2 files changed, 172 insertions(+), 3 deletions(-)
python/scripts/mkvenv.py +171 -3
@@ -54,12 +54,15 @@ import re import shutil import site +import stat import subprocess import sys import sysconfig from types import SimpleNamespace from typing import ( Any, + Dict, + Iterator, Optional, Sequence, Union,
@@ -353,6 +356,168 @@ def _stringify(data: Union[str, bytes]) -> str: print(builder.get_value("env_exe")) +def _gen_importlib(packages: Sequence[str]) -> Iterator[Dict[str, str]]: + # pylint: disable=import-outside-toplevel + # pylint: disable=no-name-in-module + # pylint: disable=import-error + try: + # First preference: Python 3.8+ stdlib + from importlib.metadata import ( # type: ignore + PackageNotFoundError, + distribution, + ) + except ImportError as exc: + logger.debug("%s", str(exc)) + # Second preference: Commonly available PyPI backport + from importlib_metadata import ( # type: ignore + PackageNotFoundError, + distribution, + ) + + # Borrowed from CPython (Lib/importlib/metadata/__init__.py) + pattern = re.compile( + r"(?P<module>[\w.]+)\s*" + r"(:\s*(?P<attr>[\w.]+)\s*)?" + r"((?P<extras>\[.*\])\s*)?$" + ) + + def _generator() -> Iterator[Dict[str, str]]: + for package in packages: + try: + entry_points = distribution(package).entry_points + except PackageNotFoundError: + continue + + # The EntryPoints type is only available in 3.10+, + # treat this as a vanilla list and filter it ourselves. + entry_points = filter( + lambda ep: ep.group == "console_scripts", entry_points + ) + + for entry_point in entry_points: + # Python 3.8 doesn't have 'module' or 'attr' attributes + if not ( + hasattr(entry_point, "module") + and hasattr(entry_point, "attr") + ): + match = pattern.match(entry_point.value) + assert match is not None + module = match.group("module") + attr = match.group("attr") + else: + module = entry_point.module + attr = entry_point.attr + yield { + "name": entry_point.name, + "module": module, + "import_name": attr, + "func": attr, + } + + return _generator() + + +def _gen_pkg_resources(packages: Sequence[str]) -> Iterator[Dict[str, str]]: + # pylint: disable=import-outside-toplevel + # Bundled with setuptools; has a good chance of being available. + import pkg_resources + + def _generator() -> Iterator[Dict[str, str]]: + for package in packages: + try: + eps = pkg_resources.get_entry_map(package, "console_scripts") + except pkg_resources.DistributionNotFound: + continue + + for entry_point in eps.values(): + yield { + "name": entry_point.name, + "module": entry_point.module_name, + "import_name": ".".join(entry_point.attrs), + "func": ".".join(entry_point.attrs), + } + + return _generator() + + +# Borrowed/adapted from pip's vendored version of distlib: +SCRIPT_TEMPLATE = r"""#!{python_path:s} +# -*- coding: utf-8 -*- +import re +import sys +from {module:s} import {import_name:s} +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit({func:s}()) +""" + + +def generate_console_scripts( + packages: Sequence[str], + python_path: Optional[str] = None, + bin_path: Optional[str] = None, +) -> None: + """ + Generate script shims for console_script entry points in @packages. + """ + if python_path is None: + python_path = sys.executable + if bin_path is None: + bin_path = sysconfig.get_path("scripts") + assert bin_path is not None + + logger.debug( + "generate_console_scripts(packages=%s, python_path=%s, bin_path=%s)", + packages, + python_path, + bin_path, + ) + + if not packages: + return + + def _get_entry_points() -> Iterator[Dict[str, str]]: + """Python 3.7 compatibility shim for iterating entry points.""" + # Python 3.8+, or Python 3.7 with importlib_metadata installed. + try: + return _gen_importlib(packages) + except ImportError as exc: + logger.debug("%s", str(exc)) + + # Python 3.7 with setuptools installed. + try: + return _gen_pkg_resources(packages) + except ImportError as exc: + logger.debug("%s", str(exc)) + raise Ouch( + "Neither importlib.metadata nor pkg_resources found, " + "can't generate console script shims.\n" + "Use Python 3.8+, or install importlib-metadata or setuptools." + ) from exc + + for entry_point in _get_entry_points(): + script_path = os.path.join(bin_path, entry_point["name"]) + script = SCRIPT_TEMPLATE.format(python_path=python_path, **entry_point) + + # If the script already exists (in any form), do not overwrite + # it nor recreate it in a new format. + suffixes = ("", ".exe", "-script.py", "-script.pyw") + if any(os.path.exists(f"{script_path}{s}") for s in suffixes): + continue + + # FIXME: this is only correct for POSIX systems. On Windows, the + # script source should be written to foo-script.py, and the py.exe + # launcher copied to foo.exe. Unfortunately there is no guarantee that + # py.exe exists on the machine. Creating the script like this is + # enough for msys and meson, both of which understand shebang lines. + with open(script_path, "w", encoding="UTF-8") as file: + file.write(script) + mode = os.stat(script_path).st_mode | stat.S_IEXEC + os.chmod(script_path, mode) + + logger.debug("wrote '%s'", script_path) + + def pkgname_from_depspec(dep_spec: str) -> str: """ Parse package name out of a PEP-508 depspec.
@@ -515,7 +680,6 @@ def _do_ensure( devnull=online and not wheels_dir, ) # (A) or (B) happened. Success. - return except subprocess.CalledProcessError: # (C) Happened. # The package is missing or isn't a suitable version,
@@ -525,8 +689,12 @@ def _do_ensure( f"mkvenv: installing {', '.join(dep_specs)}", file=sys.stderr ) pip_install(dep_specs, online=True) - else: - raise + return + raise + + # For case (A), we still need to generate entrypoint shims. + # (We generate them only if they do not exist, excluding (B).) + generate_console_scripts([pkgname_from_depspec(dep) for dep in dep_specs]) def ensure(
python/setup.cfg +1 -0
@@ -124,6 +124,7 @@ ignore_missing_imports = True # --disable=W". disable=consider-using-f-string, consider-using-with, + fixme, too-many-arguments, too-many-function-args, # mypy handles this with less false positives. too-many-instance-attributes,
Signature · 1 line
2.40.0
PATCH 9/27 mkvenv: create pip binary in virtual environment
In reply to John SnowFrom: Paolo Bonzini <[email protected]>
While pip can be invoked as "python -m pip", it is more standard to have it as a binary in the virtual environment. Instead of using ensurepip, which is slow, use the console shim generation that was just added for "mkvenv ensure".
--- python/scripts/mkvenv.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+)
python/scripts/mkvenv.py +34 -0
@@ -11,6 +11,8 @@ Commands: command Description create create a venv + post_init + post-venv initialization ensure Ensure that the specified package is installed. --------------------------------------------------
@@ -25,6 +27,13 @@ -------------------------------------------------- +usage: mkvenv post_init [-h] + +options: + -h, --help show this help message and exit + +-------------------------------------------------- + usage: mkvenv ensure [-h] [--online] [--dir DIR] dep_spec... positional arguments:
@@ -189,6 +198,13 @@ def post_post_setup(self, context: SimpleNamespace) -> None: with open(pth_file, "w", encoding="UTF-8") as file: file.write(parent_libpath + os.linesep) + args = [ + context.env_exe, + __file__, + "post_init", + ] + subprocess.run(args, check=True) + def get_value(self, field: str) -> str: """ Get a string value from the context namespace after a call to build.
@@ -727,6 +743,17 @@ def ensure( raise Ouch(diagnose(dep_specs[0], online, wheels_dir, prog)) from exc +def post_venv_setup() -> None: + """ + This is intended to be run *inside the venv* after it is created. + """ + logger.debug("post_venv_setup()") + # Generate a 'pip' script so the venv is usable in a normal + # way from the CLI. This only happens when we inherited pip from a + # parent/system-site and haven't run ensurepip in some way. + generate_console_scripts(["pip"]) + + def _add_create_subcommand(subparsers: Any) -> None: subparser = subparsers.add_parser("create", help="create a venv") subparser.add_argument(
@@ -737,6 +764,10 @@ def _add_create_subcommand(subparsers: Any) -> None: ) +def _add_post_init_subcommand(subparsers: Any) -> None: + subparsers.add_parser("post_init", help="post-venv initialization") + + def _add_ensure_subcommand(subparsers: Any) -> None: subparser = subparsers.add_parser( "ensure", help="Ensure that the specified package is installed."
@@ -790,6 +821,7 @@ def main() -> int: ) _add_create_subcommand(subparsers) + _add_post_init_subcommand(subparsers) _add_ensure_subcommand(subparsers) args = parser.parse_args()
@@ -800,6 +832,8 @@ def main() -> int: system_site_packages=True, clear=True, ) + if args.command == "post_init": + post_venv_setup() if args.command == "ensure": ensure( dep_specs=args.dep_specs,
Signature · 1 line
2.40.0
PATCH 10/27 mkvenv: work around broken pip installations on Debian 10
In reply to John SnowThis is a workaround intended for Debian 10, where the debian-patched pip does not function correctly if accessed from within a virtual environment.
We don't support Debian 10 as a build platform any longer, though we do still utilize it for our build-tricore-softmmu CI test. It's also possible that this bug might appear on other derivative platforms and this workaround may prove useful.
--- python/scripts/mkvenv.py | 68 ++++++++++++++++++++++++++++++---------- 1 file changed, 52 insertions(+), 16 deletions(-)
python/scripts/mkvenv.py +52 -16
@@ -230,26 +230,26 @@ def need_ensurepip() -> bool: return True -def check_ensurepip(with_pip: bool) -> None: +def check_ensurepip(prefix: str = "", suggest_remedy: bool = False) -> None: """ Check that we have ensurepip. Raise a fatal exception with a helpful hint if it isn't available. """ - if not with_pip: - return - if not find_spec("ensurepip"): msg = ( "Python's ensurepip module is not found.\n" "It's normally part of the Python standard library, " "maybe your distribution packages it separately?\n" - "Either install ensurepip, or alleviate the need for it in the " - "first place by installing pip and setuptools for " - f"'{sys.executable}'.\n" - "(Hint: Debian puts ensurepip in its python3-venv package.)" + "(Debian puts ensurepip in its python3-venv package.)\n" ) - raise Ouch(msg) + if suggest_remedy: + msg += ( + "Either install ensurepip, or alleviate the need for it in the" + " first place by installing pip and setuptools for " + f"'{sys.executable}'.\n" + ) + raise Ouch(prefix + msg) # ensurepip uses pyexpat, which can also go missing on us: if not find_spec("pyexpat"):
@@ -257,12 +257,15 @@ def check_ensurepip(with_pip: bool) -> None: "Python's pyexpat module is not found.\n" "It's normally part of the Python standard library, " "maybe your distribution packages it separately?\n" - "Either install pyexpat, or alleviate the need for it in the " - "first place by installing pip and setuptools for " - f"'{sys.executable}'.\n\n" - "(Hint: NetBSD's pkgsrc debundles this to e.g. 'py310-expat'.)" + "(NetBSD's pkgsrc debundles this to e.g. 'py310-expat'.)\n" ) - raise Ouch(msg) + if suggest_remedy: + msg += ( + "Either install pyexpat, or alleviate the need for it in the " + "first place by installing pip and setuptools for " + f"'{sys.executable}'.\n" + ) + raise Ouch(prefix + msg) def make_venv( # pylint: disable=too-many-arguments
@@ -310,7 +313,8 @@ def make_venv( # pylint: disable=too-many-arguments with_pip = True if not system_site_packages else need_ensurepip() logger.debug("with_pip unset, choosing %s", with_pip) - check_ensurepip(with_pip) + if with_pip: + check_ensurepip(suggest_remedy=True) if symlinks is None: # Default behavior of standard venv CLI
@@ -534,6 +538,36 @@ def _get_entry_points() -> Iterator[Dict[str, str]]: logger.debug("wrote '%s'", script_path) +def checkpip() -> None: + """ + Debian10 has a pip that's broken when used inside of a virtual environment. + + We try to detect and correct that case here. + """ + try: + # pylint: disable=import-outside-toplevel,unused-import,import-error + import pip._internal # type: ignore # noqa: F401 + + logger.debug("pip appears to be working correctly.") + return + except ModuleNotFoundError as exc: + if exc.name == "pip._internal": + # Uh, fair enough. They did say "internal". + # Let's just assume it's fine. + return + logger.warning("pip appears to be malfunctioning: %s", str(exc)) + + check_ensurepip("pip appears to be non-functional, and ") + + logger.debug("Attempting to repair pip ...") + subprocess.run( + (sys.executable, "-m", "ensurepip"), + stdout=subprocess.DEVNULL, + check=True, + ) + logger.debug("Pip is now (hopefully) repaired!") + + def pkgname_from_depspec(dep_spec: str) -> str: """ Parse package name out of a PEP-508 depspec.
@@ -748,7 +782,9 @@ def post_venv_setup() -> None: This is intended to be run *inside the venv* after it is created. """ logger.debug("post_venv_setup()") - # Generate a 'pip' script so the venv is usable in a normal + # Test for a broken pip (Debian 10 or derivative?) and fix it if needed + checkpip() + # Finally, generate a 'pip' script so the venv is usable in a normal # way from the CLI. This only happens when we inherited pip from a # parent/system-site and haven't run ensurepip in some way. generate_console_scripts(["pip"])
Signature · 1 line
2.40.0
PATCH 11/27 tests/docker: add python3-venv dependency
In reply to John SnowSeveral debian-based tests need the python3-venv dependency as a consequence of Debian debundling the "ensurepip" module normally included with Python.
As mkvenv.py stands as of this commit, Debian requires EITHER:
(A) setuptools and pip, or
(B) ensurepip
mkvenv is a few seconds faster if you have setuptools and pip, so developers should prefer the first requirement. For the purposes of CI, the time-save is a wash; it's only a matter of who is responsible for installing pip and when; the timing is about the same.
Arbitrarily, I chose adding ensurepip to the test configuration because it is normally part of the Python stdlib, and always having it allows us a more consistent cross-platform environment.
--- tests/docker/dockerfiles/debian-all-test-cross.docker | 3 ++- tests/docker/dockerfiles/debian-hexagon-cross.docker | 3 ++- tests/docker/dockerfiles/debian-riscv64-cross.docker | 3 ++- tests/docker/dockerfiles/debian-tricore-cross.docker | 3 ++- 4 files changed, 8 insertions(+), 4 deletions(-)
tests/docker/dockerfiles/debian-all-test-cross.docker +2 -1
@@ -57,7 +57,8 @@ RUN DEBIAN_FRONTEND=noninteractive eatmydata \ gcc-sh4-linux-gnu \ libc6-dev-sh4-cross \ gcc-sparc64-linux-gnu \ - libc6-dev-sparc64-cross + libc6-dev-sparc64-cross \ + python3-venv ENV QEMU_CONFIGURE_OPTS --disable-system --disable-docs --disable-tools ENV DEF_TARGET_LIST aarch64-linux-user,alpha-linux-user,arm-linux-user,hppa-linux-user,i386-linux-user,m68k-linux-user,mips-linux-user,mips64-linux-user,mips64el-linux-user,mipsel-linux-user,ppc-linux-user,ppc64-linux-user,ppc64le-linux-user,riscv64-linux-user,s390x-linux-user,sh4-linux-user,sparc64-linux-user
tests/docker/dockerfiles/debian-hexagon-cross.docker +2 -1
@@ -20,7 +20,8 @@ RUN apt-get update && \ bison \ flex \ git \ - ninja-build && \ + ninja-build \ + python3-venv && \ # Install QEMU build deps for use in CI DEBIAN_FRONTEND=noninteractive eatmydata \ apt build-dep -yy --arch-only qemu
tests/docker/dockerfiles/debian-riscv64-cross.docker +2 -1
@@ -28,7 +28,8 @@ RUN DEBIAN_FRONTEND=noninteractive eatmydata apt install -yy \ libglib2.0-dev \ ninja-build \ pkg-config \ - python3 + python3 \ + python3-venv # Add ports and riscv64 architecture RUN echo "deb http://ftp.ports.debian.org/debian-ports/ sid main" >> /etc/apt/sources.list
tests/docker/dockerfiles/debian-tricore-cross.docker +2 -1
@@ -33,7 +33,8 @@ RUN apt update && \ pkgconf \ python3-pip \ python3-setuptools \ - python3-wheel + python3-wheel \ + python3-venv RUN curl -#SL https://github.com/bkoppelmann/package_940/releases/download/tricore-toolchain-9.40/tricore-toolchain-9.4.0.tar.gz \ | tar -xzC /usr/local/
Signature · 1 line
2.40.0
PATCH 12/27 tests/vm: Configure netbsd to use Python 3.10
In reply to John SnowNetBSD removes some packages from the Python stdlib, but only re-packages them for Python 3.10. Switch to using Python 3.10.
--- tests/vm/netbsd | 1 + 1 file changed, 1 insertion(+)
tests/vm/netbsd +1 -0
@@ -30,6 +30,7 @@ class NetBSDVM(basevm.BaseVM): "git-base", "pkgconf", "xz", + "python310", "ninja-build", # gnu tools
Signature · 1 line
2.40.0
PATCH 13/27 tests/vm: add py310-expat to NetBSD
In reply to John SnowNetBSD cannot successfully run "ensurepip" without access to the pyexpat module, which NetBSD debundles. Like the Debian patch, it would be strictly faster long term to install pip/setuptools, and I recommend developers at their workstations take that approach instead.
For the purposes of a throwaway VM, there's not really a speed difference for who is responsible for installing pip; us (needs py310-pip) or Python (needs py310-expat).
--- tests/vm/netbsd | 1 + 1 file changed, 1 insertion(+)
tests/vm/netbsd +1 -0
@@ -31,6 +31,7 @@ class NetBSDVM(basevm.BaseVM): "pkgconf", "xz", "python310", + "py310-expat", "ninja-build", # gnu tools
Signature · 1 line
2.40.0
PATCH 14/27 python: add vendor.py utility
In reply to John SnowThis is a teeny-tiny script that just downloads any packages we want to vendor from PyPI and stores them in qemu.git/python/wheels/. If I'm hit by a meteor, it'll be easy to replicate what I have done in order to udpate the vendored source.
We don't really care which python runs it; it exists as a meta-utility with no external dependencies and we won't package or install it. It will be monitored by the linters/type checkers, though; so it's guaranteed safe on python 3.6+.
--- python/scripts/vendor.py | 74 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100755 python/scripts/vendor.py
python/scripts/vendor.py new file +74 -0
@@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +""" +vendor - QEMU python vendoring utility + +usage: vendor [-h] + +QEMU python vendoring utility + +options: + -h, --help show this help message and exit +""" + +# Copyright (C) 2023 Red Hat, Inc. +# +# Authors: +# John Snow <[email protected]> +# +# This work is licensed under the terms of the GNU GPL, version 2 or +# later. See the COPYING file in the top-level directory. + +import argparse +import os +from pathlib import Path +import subprocess +import sys +import tempfile + + +def main() -> int: + """Run the vendoring utility. See module-level docstring.""" + loud = False + if os.environ.get("DEBUG") or os.environ.get("V"): + loud = True + + # No options or anything for now, but I guess + # you'll figure that out when you run --help. + parser = argparse.ArgumentParser( + prog="vendor", + description="QEMU python vendoring utility", + ) + parser.parse_args() + + packages = { + "meson==0.61.5": + "58c2ddb5f885da0e929f15d89f38d8a7d97f981f56815bcba008414f8511f59a", + } + + vendor_dir = Path(__file__, "..", "..", "wheels").resolve() + + with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8") as file: + for dep_spec, checksum in packages.items(): + file.write(f"{dep_spec} --hash=sha256:{checksum}") + file.flush() + + cli_args = [ + "pip", + "download", + "--dest", + str(vendor_dir), + "--require-hashes", + "-r", + file.name, + ] + if loud: + cli_args.append("-v") + + print(" ".join(cli_args)) + subprocess.run(cli_args, check=True) + + return 0 + + +if __name__ == "__main__": + sys.exit(main())
Signature · 1 line
2.40.0
PATCH 15/27 configure: create a python venv unconditionally
In reply to John SnowThis patch changes the configure script so that it always creates and uses a python virtual environment unconditionally.
Meson bootstrapping is temporarily altered to force the use of meson from git or vendored source (as packaged in our source tarballs). A subsequent commit restores the use of distribution-vendored Meson.
--- configure | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-)
configure +29 -5
@@ -625,7 +625,6 @@ check_py_version() { python= first_python= if test -z "${PYTHON}"; then - explicit_python=no # A bare 'python' is traditionally python 2.x, but some distros # have it as python 3.x, so check in both places. for binary in python3 python python3.11 python3.10 python3.9 python3.8 python3.7 python3.6; do
@@ -644,7 +643,6 @@ else # Same as above, but only check the environment variable. has "${PYTHON}" || error_exit "The PYTHON environment variable does not point to an executable" python=$(command -v "$PYTHON") - explicit_python=yes if check_py_version "$python"; then # This one is good. first_python=
@@ -729,7 +727,7 @@ for opt do ;; --install=*) ;; - --python=*) python="$optarg" ; explicit_python=yes + --python=*) python="$optarg" ;; --skip-meson) skip_meson=yes ;;
@@ -1090,8 +1088,34 @@ if ! check_py_version "$python"; then "Use --python=/path/to/python to specify a supported Python." fi -# Resolve PATH + suppress writing compiled files -python="$(command -v "$python") -B" +# Resolve PATH +python="$(command -v "$python")" +explicit_python=yes + +# Create a Python virtual environment using our configured python. +# The stdout of this script will be the location of a symlink that +# points to the configured Python. +# Entry point scripts for pip, meson, and sphinx are generated if those +# packages are present. + +# Defaults assumed for now: +# - venv is cleared if it exists already; +# - venv is allowed to use system packages; +# - all setup is performed **offline**; +# - No packages are installed by default; +# - pip is not installed into the venv when possible, +# but ensurepip is called as a fallback when necessary. + +echo "python determined to be '$python'" +echo "python version: $($python --version)" + +python="$($python -B "${source_path}/python/scripts/mkvenv.py" create pyvenv)" +if test "$?" -ne 0 ; then + error_exit "python venv creation failed" +fi + +# Suppress writing compiled files +python="$python -B" has_meson() { local python_dir=$(dirname "$python")
Signature · 1 line
2.40.0
PATCH 16/27 python/wheels: add vendored meson package
In reply to John SnowIn preference to vendoring meson source, vendor a built distributable ("bdist" in python parlance). This has some benefits:
(1) We can get rid of a git submodule,
(2) Installing built meson into a venv doesn't require any extra dependencies (the python "wheel" package, chiefly.)
(3) We don't treat meson any differently than we would any other python package (we install it, end of story, done.)
(4) All future tarball *and* developer checkouts will function offline; No git or PyPI connection needed to fetch meson.
Note that because mkvenv prefers vendored packages to PyPI, as mkvenv is currently written we will never consult PyPI for meson. (Do keep in mind that your distribution's meson will be preferred above the vendored version, though.)
``` jsnow@scv ~/s/q/python (python-configure-venv)> python3 scripts/vendor.py pip download --dest /home/jsnow/src/qemu/python/wheels --require-hashes -r /tmp/tmpvo5qav7i Collecting meson==0.61.5 Using cached meson-0.61.5-py3-none-any.whl (862 kB) Saved ./wheels/meson-0.61.5-py3-none-any.whl Successfully downloaded meson ```
--- python/wheels/meson-0.61.5-py3-none-any.whl | Bin 0 -> 862509 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 python/wheels/meson-0.61.5-py3-none-any.whl
python/wheels/meson-0.61.5-py3-none-any.whl new file binary +0 -0
Signature · 1 line
2.40.0
PATCH 17/27 configure: use 'mkvenv ensure meson' to bootstrap meson
In reply to John SnowThis commit changes how we detect and install meson. It notably removes '--meson='.
Currently, configure creates a lightweight Python virtual environment unconditionally using the user's configured $python that inherits system packages. Temporarily, we forced the use of meson source present via git submodule or in the release tarball.
With this patch, we restore the ability to use a system-provided meson:
If Meson is installed in the build venv and meets our minimum version requirements, we will use that Meson. This includes a system provided meson, which would be visible via system-site packages inside the venv.
In the event that Meson is installed but *not for the chosen Python interpreter*, not found, or of insufficient version, we will attempt to install Meson from vendored source into the newly created Python virtual environment. This vendored installation replaces both the git submodule and tarball source mechanisms for sourcing meson.
As a result of this patch, the Python interpreter we use for both our own build scripts *and* Meson extensions are always known to be the exact same Python. As a further benefit, there will also be a symlink available in the build directory that points to the correct, configured python and can be used by e.g. manual tests to invoke the correct, configured Python unambiguously.
--- configure | 80 ++++++++++------------------- .gitlab-ci.d/buildtest-template.yml | 4 +- python/scripts/mkvenv.py | 4 ++ 3 files changed, 32 insertions(+), 56 deletions(-)
configure +26 -54
@@ -731,8 +731,6 @@ for opt do ;; --skip-meson) skip_meson=yes ;; - --meson=*) meson="$optarg" - ;; --ninja=*) ninja="$optarg" ;; --smbd=*) smbd="$optarg"
@@ -1017,7 +1015,6 @@ Advanced options (experts only): --cross-prefix-ARCH=PREFIX cross compiler prefix when building ARCH guest test cases --make=MAKE use specified make [$make] --python=PYTHON use specified python [$python] - --meson=MESON use specified meson [$meson] --ninja=NINJA use specified ninja [$ninja] --smbd=SMBD use specified smbd [$smbd] --with-git=GIT use specified git [$git]
@@ -1090,7 +1087,6 @@ fi # Resolve PATH python="$(command -v "$python")" -explicit_python=yes # Create a Python virtual environment using our configured python. # The stdout of this script will be the location of a symlink that
@@ -1102,7 +1098,6 @@ explicit_python=yes # - venv is cleared if it exists already; # - venv is allowed to use system packages; # - all setup is performed **offline**; -# - No packages are installed by default; # - pip is not installed into the venv when possible, # but ensurepip is called as a fallback when necessary.
@@ -1117,59 +1112,36 @@ fi # Suppress writing compiled files python="$python -B" -has_meson() { - local python_dir=$(dirname "$python") - # PEP405: pyvenv.cfg is either adjacent to the Python executable - # or one directory above - if test -f $python_dir/pyvenv.cfg || test -f $python_dir/../pyvenv.cfg; then - # Ensure that Meson and Python come from the same virtual environment - test -x "$python_dir/meson" && - test "$(command -v meson)" -ef "$python_dir/meson" - else - has meson - fi -} -if test -z "$meson"; then - if test "$explicit_python" = no && has_meson && version_ge "$(meson --version)" 0.61.5; then - meson=meson - elif test "$git_submodules_action" != 'ignore' ; then - meson=git - elif test -e "${source_path}/meson/meson.py" ; then - meson=internal - else - if test "$explicit_python" = yes; then - error_exit "--python requires using QEMU's embedded Meson distribution, but it was not found." - else - error_exit "Meson not found. Use --meson=/path/to/meson" - fi - fi +if ! $python "${source_path}/python/scripts/mkvenv.py" ensure \ + --dir "${source_path}/python/wheels" \ + --diagnose "meson" \ + "meson>=0.61.5" ; +then + exit 1 +fi + +# At this point, we expect Meson to be installed and available. +# We expect mkvenv or pip to have created pyvenv/bin/meson for us. +# We ignore PATH completely here: we want to use the venv's Meson +# *exclusively*. + +# "mkvenv ensure" has a limitation compared to "pip install": it is not +# able to create launcher .exe files on Windows. This limitation exists +# because "py.exe" is not guaranteed to exist on the machine (pip/setuptools +# work around the issue by bundling the .exe files as resources). +# This is not a problem for msys, since it emulates a POSIX environment; +# it is also okay for programs that meson.build looks up with find_program(), +# because in that case Meson checks the file for a shebang line. However, +# when meson wants to invoke itself as part of a build recipe, we need +# to convince it to put the python interpreter in front of the path to the +# script. To do so, run it using '-m'. +if test "$targetos" = windows; then + meson="$python -m mesonbuild.mesonmain" else - # Meson uses its own Python interpreter to invoke other Python scripts, - # but the user wants to use the one they specified with --python. - # - # We do not want to override the distro Python interpreter (and sometimes - # cannot: for example in Homebrew /usr/bin/meson is a bash script), so - # just require --meson=git|internal together with --python. - if test "$explicit_python" = yes; then - case "$meson" in - git | internal) ;; - *) error_exit "--python requires using QEMU's embedded Meson distribution." ;; - esac - fi + meson="$(cd pyvenv/bin; pwd)/meson" fi -if test "$meson" = git; then - git_submodules="${git_submodules} meson" -fi - -case "$meson" in - git | internal) - meson="$python ${source_path}/meson/meson.py" - ;; - *) meson=$(command -v "$meson") ;; -esac - # Probe for ninja if test -z "$ninja"; then
.gitlab-ci.d/buildtest-template.yml +2 -2
@@ -12,12 +12,12 @@ - mkdir build - cd build - ../configure --enable-werror --disable-docs --enable-fdt=system - ${LD_JOBS:+--meson=git} ${TARGETS:+--target-list="$TARGETS"} + ${TARGETS:+--target-list="$TARGETS"} $CONFIGURE_ARGS || { cat config.log meson-logs/meson-log.txt && exit 1; } - if test -n "$LD_JOBS"; then - ../meson/meson.py configure . -Dbackend_max_links="$LD_JOBS" ; + pyvenv/bin/meson configure . -Dbackend_max_links="$LD_JOBS" ; fi || exit 1; - make -j"$JOBS" - if test -n "$MAKE_CHECK_ARGS";
python/scripts/mkvenv.py +4 -0
@@ -530,6 +530,10 @@ def _get_entry_points() -> Iterator[Dict[str, str]]: # launcher copied to foo.exe. Unfortunately there is no guarantee that # py.exe exists on the machine. Creating the script like this is # enough for msys and meson, both of which understand shebang lines. + # It does requires some care when invoking meson however, which is + # worked around in configure. Note that a .exe launcher is needed + # and not for example a batch file, because the CreateProcess API + # (used by Ninja) cannot start them. with open(script_path, "w", encoding="UTF-8") as file: file.write(script) mode = os.stat(script_path).st_mode | stat.S_IEXEC
Signature · 1 line
2.40.0
PATCH 18/27 qemu.git: drop meson git submodule
In reply to John SnowNow that meson is installed from a vendored wheel, we don't need the git submodule anymore. Drop it.
--- .gitmodules | 3 --- meson | 1 - 2 files changed, 4 deletions(-) delete mode 160000 meson
.gitmodules +0 -3
@@ -49,9 +49,6 @@ [submodule "roms/qboot"] path = roms/qboot url = https://gitlab.com/qemu-project/qboot.git -[submodule "meson"] - path = meson - url = https://gitlab.com/qemu-project/meson.git [submodule "roms/vbootrom"] path = roms/vbootrom url = https://gitlab.com/qemu-project/vbootrom.git
meson deleted +0 -1
@@ -1 +0,0 @@ -Subproject commit 3a9b285a55b91b53b2acda987192274352ecb5be
Signature · 1 line
2.40.0
PATCH 19/27 tests: Use configure-provided pyvenv for tests
In reply to John SnowThis patch changes how the avocado tests are provided, ever so slightly. Instead of creating a new testing venv, use the configure-provided 'pyvenv' instead, and install optional packages into that.
--- docs/devel/acpi-bits.rst | 6 +++--- docs/devel/testing.rst | 14 +++++++------- .gitlab-ci.d/buildtest.yml | 6 +++--- scripts/ci/org.centos/stream/8/x86_64/test-avocado | 4 ++-- scripts/device-crash-test | 2 +- tests/Makefile.include | 10 +++++----- tests/requirements.txt | 7 +++++-- 7 files changed, 26 insertions(+), 23 deletions(-)
docs/devel/acpi-bits.rst +3 -3
@@ -61,19 +61,19 @@ Under ``tests/avocado/`` as the root we have: :: $ make check-venv (needed only the first time to create the venv) - $ ./tests/venv/bin/avocado run -t acpi tests/avocado + $ ./pyvenv/bin/avocado run -t acpi tests/avocado The above will run all acpi avocado tests including this one. In order to run the individual tests, perform the following: :: - $ ./tests/venv/bin/avocado run tests/avocado/acpi-bits.py --tap - + $ ./pyvenv/bin/avocado run tests/avocado/acpi-bits.py --tap - The above will produce output in tap format. You can omit "--tap -" in the end and it will produce output like the following: :: - $ ./tests/venv/bin/avocado run tests/avocado/acpi-bits.py + $ ./pyvenv/bin/avocado run tests/avocado/acpi-bits.py Fetching asset from tests/avocado/acpi-bits.py:AcpiBitsTest.test_acpi_smbios_bits JOB ID : eab225724da7b64c012c65705dc2fa14ab1defef JOB LOG : /home/anisinha/avocado/job-results/job-2022-10-10T17.58-eab2257/job.log
docs/devel/testing.rst +7 -7
@@ -882,9 +882,9 @@ You can run the avocado tests simply by executing: make check-avocado -This involves the automatic creation of Python virtual environment -within the build tree (at ``tests/venv``) which will have all the -right dependencies, and will save tests results also within the +This involves the automatic installation, from PyPI, of all the +necessary avocado-framework dependencies into the QEMU venv within the +build tree (at ``./pyvenv``). Test results are also saved within the build tree (at ``tests/results``). Note: the build environment must be using a Python 3 stack, and have
@@ -941,7 +941,7 @@ may be invoked by running: .. code:: - tests/venv/bin/avocado run $OPTION1 $OPTION2 tests/avocado/ + pyvenv/bin/avocado run $OPTION1 $OPTION2 tests/avocado/ Note that if ``make check-avocado`` was not executed before, it is possible to create the Python virtual environment with the dependencies
@@ -956,20 +956,20 @@ a test file. To run tests from a single file within the build tree, use: .. code:: - tests/venv/bin/avocado run tests/avocado/$TESTFILE + pyvenv/bin/avocado run tests/avocado/$TESTFILE To run a single test within a test file, use: .. code:: - tests/venv/bin/avocado run tests/avocado/$TESTFILE:$TESTCLASS.$TESTNAME + pyvenv/bin/avocado run tests/avocado/$TESTFILE:$TESTCLASS.$TESTNAME Valid test names are visible in the output from any previous execution of Avocado or ``make check-avocado``, and can also be queried using: .. code:: - tests/venv/bin/avocado list tests/avocado + pyvenv/bin/avocado list tests/avocado Manual Installation ~~~~~~~~~~~~~~~~~~~
.gitlab-ci.d/buildtest.yml +3 -3
@@ -103,7 +103,7 @@ crash-test-debian: script: - cd build - make NINJA=":" check-venv - - tests/venv/bin/python3 scripts/device-crash-test -q --tcg-only ./qemu-system-i386 + - pyvenv/bin/python3 scripts/device-crash-test -q --tcg-only ./qemu-system-i386 build-system-fedora: extends:
@@ -146,8 +146,8 @@ crash-test-fedora: script: - cd build - make NINJA=":" check-venv - - tests/venv/bin/python3 scripts/device-crash-test -q ./qemu-system-ppc - - tests/venv/bin/python3 scripts/device-crash-test -q ./qemu-system-riscv32 + - pyvenv/bin/python3 scripts/device-crash-test -q ./qemu-system-ppc + - pyvenv/bin/python3 scripts/device-crash-test -q ./qemu-system-riscv32 build-system-centos: extends:
scripts/ci/org.centos/stream/8/x86_64/test-avocado +2 -2
@@ -4,7 +4,7 @@ # KVM and x86_64, or tests that are generic enough to be valid for all # targets. Such a test list can be generated with: # -# ./tests/venv/bin/avocado list --filter-by-tags-include-empty \ +# ./pyvenv/bin/avocado list --filter-by-tags-include-empty \ # --filter-by-tags-include-empty-key -t accel:kvm,arch:x86_64 \ # tests/avocado/ #
@@ -22,7 +22,7 @@ # - tests/avocado/virtio_check_params.py:VirtioMaxSegSettingsCheck.test_machine_types # make get-vm-images -./tests/venv/bin/avocado run \ +./pyvenv/bin/avocado run \ --job-results-dir=tests/results/ \ tests/avocado/boot_linux.py:BootLinuxX8664.test_pc_i440fx_kvm \ tests/avocado/boot_linux.py:BootLinuxX8664.test_pc_q35_kvm \
scripts/device-crash-test +1 -1
@@ -43,7 +43,7 @@ except ModuleNotFoundError as exc: print(f"Module '{exc.name}' not found.") print(" Try 'make check-venv' from your build directory,") print(" and then one way to run this script is like so:") - print(f' > $builddir/tests/venv/bin/python3 "{path}"') + print(f' > $builddir/pyvenv/bin/python3 "{path}"') sys.exit(1) logger = logging.getLogger('device-crash-test')
tests/Makefile.include +5 -5
@@ -89,7 +89,8 @@ distclean-tcg: $(DISTCLEAN_TCG_TARGET_RULES) # Build up our target list from the filtered list of ninja targets TARGETS=$(patsubst libqemu-%.fa, %, $(filter libqemu-%.fa, $(ninja-targets))) -TESTS_VENV_DIR=$(BUILD_DIR)/tests/venv +TESTS_VENV_DIR=$(BUILD_DIR)/pyvenv +TESTS_VENV_TOKEN=$(BUILD_DIR)/pyvenv/tests.group TESTS_VENV_REQ=$(SRC_PATH)/tests/requirements.txt TESTS_RESULTS_DIR=$(BUILD_DIR)/tests/results TESTS_PYTHON=$(TESTS_VENV_DIR)/bin/python3
@@ -111,8 +112,7 @@ quiet-venv-pip = $(quiet-@)$(call quiet-command-run, \ $(TESTS_PYTHON) -m pip -q --disable-pip-version-check $1, \ "VENVPIP","$1") -$(TESTS_VENV_DIR): $(TESTS_VENV_REQ) - $(call quiet-command, $(PYTHON) -m venv $@, VENV, $@) +$(TESTS_VENV_TOKEN): $(TESTS_VENV_REQ) $(call quiet-venv-pip,install -e "$(SRC_PATH)/python/") $(call quiet-venv-pip,install -r $(TESTS_VENV_REQ)) $(call quiet-command, touch $@)
@@ -121,7 +121,7 @@ $(TESTS_RESULTS_DIR): $(call quiet-command, mkdir -p $@, \ MKDIR, $@) -check-venv: $(TESTS_VENV_DIR) +check-venv: $(TESTS_VENV_TOKEN) FEDORA_31_ARCHES_TARGETS=$(patsubst %-softmmu,%, $(filter %-softmmu,$(TARGETS))) FEDORA_31_ARCHES_CANDIDATES=$(patsubst ppc64,ppc64le,$(FEDORA_31_ARCHES_TARGETS))
@@ -167,7 +167,7 @@ check: check-build: run-ninja check-clean: - rm -rf $(TESTS_VENV_DIR) $(TESTS_RESULTS_DIR) + rm -rf $(TESTS_RESULTS_DIR) clean: check-clean clean-tcg distclean: distclean-tcg
tests/requirements.txt +5 -2
@@ -1,6 +1,9 @@ # Add Python module requirements, one per line, to be installed -# in the tests/venv Python virtual environment. For more info, +# in the qemu build_dir/pyvenv Python virtual environment. For more info, # refer to: https://pip.pypa.io/en/stable/user_guide/#id1 -# Note that qemu.git/python/ is always implicitly installed. +# +# Note that qemu.git/python/ is implicitly installed to this venv when +# 'make check-venv' is run, and will persist until configure is run +# again. avocado-framework==101.0 pycdlib==1.11.0
Signature · 1 line
2.40.0
PATCH 20/27 configure: move --enable-docs and --disable-docs back to configure
In reply to John SnowMove this option back from meson into configure for the purposes of using the configuration value to bootstrap Sphinx in different ways based on this value.
--- configure | 6 ++++++ 1 file changed, 6 insertions(+)
configure +6 -0
@@ -279,6 +279,7 @@ debug_tcg="no" sanitizers="no" tsan="no" fortify_source="yes" +docs="auto" EXESUF="" modules="no" prefix="/usr/local"
@@ -751,6 +752,10 @@ for opt do ;; --disable-debug-info) meson_option_add -Ddebug=false ;; + --enable-docs) docs=enabled + ;; + --disable-docs) docs=disabled + ;; --enable-modules) modules="yes" ;;
@@ -2630,6 +2635,7 @@ if test "$skip_meson" = no; then # QEMU options test "$cfi" != false && meson_option_add "-Dcfi=$cfi" + test "$docs" != auto && meson_option_add "-Ddocs=$docs" test "$fdt" != auto && meson_option_add "-Dfdt=$fdt" test -n "${LIB_FUZZING_ENGINE+xxx}" && meson_option_add "-Dfuzzing_engine=$LIB_FUZZING_ENGINE" test "$qemu_suffix" != qemu && meson_option_add "-Dqemu_suffix=$qemu_suffix"
Signature · 1 line
2.40.0
PATCH 21/27 configure: bootstrap sphinx with mkvenv
In reply to John SnowWhen docs are explicitly requested, require Sphinx>=1.6.0. When docs are explicitly disabled, don't bother to check for Sphinx at all. If docs are set to "auto", attempt to locate Sphinx, but continue onward if it wasn't located.
--- docs/conf.py | 9 --------- docs/meson.build | 2 +- configure | 21 +++++++++++++++++++-- meson_options.txt | 2 -- scripts/meson-buildoptions.sh | 3 --- 5 files changed, 20 insertions(+), 17 deletions(-)
docs/conf.py +0 -9
@@ -32,15 +32,6 @@ from distutils.version import LooseVersion from sphinx.errors import ConfigError -# Make Sphinx fail cleanly if using an old Python, rather than obscurely -# failing because some code in one of our extensions doesn't work there. -# In newer versions of Sphinx this will display nicely; in older versions -# Sphinx will also produce a Python backtrace but at least the information -# gets printed... -if sys.version_info < (3,6): - raise ConfigError( - "QEMU requires a Sphinx that uses Python 3.6 or better\n") - # The per-manual conf.py will set qemu_docdir for a single-manual build; # otherwise set it here if this is an entire-manual-set build. # This is always the absolute path of the docs/ directory in the source tree.
docs/meson.build +1 -1
@@ -1,4 +1,4 @@ -sphinx_build = find_program(get_option('sphinx_build'), +sphinx_build = find_program(fs.parent(python.full_path()) / 'sphinx-build', required: get_option('docs')) # Check if tools are available to build documentation.
configure +19 -2
@@ -1116,9 +1116,9 @@ fi # Suppress writing compiled files python="$python -B" +mkvenv="$python ${source_path}/python/scripts/mkvenv.py" - -if ! $python "${source_path}/python/scripts/mkvenv.py" ensure \ +if ! $mkvenv ensure \ --dir "${source_path}/python/wheels" \ --diagnose "meson" \ "meson>=0.61.5" ;
@@ -1147,6 +1147,23 @@ else meson="$(cd pyvenv/bin; pwd)/meson" fi +# Conditionally ensure Sphinx is installed. + +if test "$docs" != "disabled" ; then + if ! $mkvenv ensure \ + --diagnose "sphinx-build" \ + "sphinx>=1.6.0" sphinx_rtd_theme; + then + if test "$docs" = "enabled" ; then + exit 1 + fi + echo "Sphinx not found/usable, disabling docs." + docs=disabled + else + docs=enabled + fi +fi + # Probe for ninja if test -z "$ninja"; then
meson_options.txt +0 -2
@@ -12,8 +12,6 @@ option('pkgversion', type : 'string', value : '', description: 'use specified string as sub-version of the package') option('smbd', type : 'string', value : '', description: 'Path to smbd for slirp networking') -option('sphinx_build', type : 'string', value : 'sphinx-build', - description: 'Use specified sphinx-build for building document') option('iasl', type : 'string', value : '', description: 'Path to ACPI disassembler') option('tls_priority', type : 'string', value : 'NORMAL',
scripts/meson-buildoptions.sh +0 -3
@@ -57,8 +57,6 @@ meson_options_help() { printf "%s\n" ' --localedir=VALUE Locale data directory [share/locale]' printf "%s\n" ' --localstatedir=VALUE Localstate data directory [/var/local]' printf "%s\n" ' --mandir=VALUE Manual page directory [share/man]' - printf "%s\n" ' --sphinx-build=VALUE Use specified sphinx-build for building document' - printf "%s\n" ' [sphinx-build]' printf "%s\n" ' --sysconfdir=VALUE Sysconf data directory [etc]' printf "%s\n" ' --tls-priority=VALUE Default TLS protocol/cipher priority string' printf "%s\n" ' [NORMAL]'
@@ -425,7 +423,6 @@ _meson_option_parse() { --disable-sndio) printf "%s" -Dsndio=disabled ;; --enable-sparse) printf "%s" -Dsparse=enabled ;; --disable-sparse) printf "%s" -Dsparse=disabled ;; - --sphinx-build=*) quote_sh "-Dsphinx_build=$2" ;; --enable-spice) printf "%s" -Dspice=enabled ;; --disable-spice) printf "%s" -Dspice=disabled ;; --enable-spice-protocol) printf "%s" -Dspice_protocol=enabled ;;
Signature · 1 line
2.40.0
PATCH 22/27 configure: add --enable-pypi and --disable-pypi
In reply to John SnowIn the event that there's no vendored source present and no sufficient version of $package can be found, we will attempt to connect to PyPI to install the package if '--disable-pypi' was not passed.
This means that PyPI access is "enabled by default", but there are some subtleties that make this action occur much less frequently than you might imagine:
(1) While --enable-pypi is the default, vendored source will always be preferred when found, making PyPI a fallback. This should ensure that configure-time venv building "just works" for almost everyone in almost every circumstance.
(2) Because meson source is, at time of writing, vendored directly into qemu.git, PyPI will never be used for sourcing meson.
(3) Because Sphinx is an optional dependency, if docs are set to "auto", PyPI will not be used to obtain Sphinx source as a fallback and instead docs will be disabled. If PyPI sourcing of sphinx is desired, --enable-docs should be passed to force the lookup. I chose this as the default behavior to avoid adding new internet lookups to a "default" invocation of configure.
--- configure | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-)
configure +20 -1
@@ -624,6 +624,7 @@ check_py_version() { } python= +pypi="enabled" first_python= if test -z "${PYTHON}"; then # A bare 'python' is traditionally python 2.x, but some distros
@@ -889,6 +890,10 @@ for opt do --with-git-submodules=*) git_submodules_action="$optarg" ;; + --disable-pypi) pypi="disabled" + ;; + --enable-pypi) pypi="enabled" + ;; --enable-plugins) if test "$mingw32" = "yes"; then error_exit "TCG plugins not currently supported on Windows platforms" else
@@ -1102,7 +1107,9 @@ python="$(command -v "$python")" # Defaults assumed for now: # - venv is cleared if it exists already; # - venv is allowed to use system packages; -# - all setup is performed **offline**; +# - all setup can be performed offline; +# - missing packages may be fetched from PyPI, +# unless --disable-pypi is passed. # - pip is not installed into the venv when possible, # but ensurepip is called as a fallback when necessary.
@@ -1118,7 +1125,13 @@ fi python="$python -B" mkvenv="$python ${source_path}/python/scripts/mkvenv.py" +mkvenv_flags="" +if test "$pypi" = "enabled" ; then + mkvenv_flags="--online" +fi + if ! $mkvenv ensure \ + $mkvenv_flags \ --dir "${source_path}/python/wheels" \ --diagnose "meson" \ "meson>=0.61.5" ;
@@ -1149,8 +1162,14 @@ fi # Conditionally ensure Sphinx is installed. +mkvenv_flags="" +if test "$pypi" = "enabled" -a "$docs" = "enabled" ; then + mkvenv_flags="--online" +fi + if test "$docs" != "disabled" ; then if ! $mkvenv ensure \ + $mkvenv_flags \ --diagnose "sphinx-build" \ "sphinx>=1.6.0" sphinx_rtd_theme; then
Signature · 1 line
2.40.0
PATCH 23/27 Python: Drop support for Python 3.6
In reply to John SnowFrom: Paolo Bonzini <[email protected]>
Python 3.6 was EOL 2021-12-31. Newer versions of upstream libraries have begun dropping support for this version and it is becoming more cumbersome to support. Avocado-framework and qemu.qmp each have their own reasons for wanting to drop Python 3.6, but won't until QEMU does.
Versions of Python available in our supported build platforms as of today, with optional versions available in parentheses:
openSUSE Leap 15.4: 3.6.15 (3.9.10, 3.10.2) CentOS Stream 8: 3.6.8 (3.8.13, 3.9.16) CentOS Stream 9: 3.9.13 Fedora 36: 3.10 Fedora 37: 3.11 Debian 11: 3.9.2 Alpine 3.14, 3.15: 3.9.16 Alpine 3.16, 3.17: 3.10.10 Ubuntu 20.04 LTS: 3.8.10 Ubuntu 22.04 LTS: 3.10.4 NetBSD 9.3: 3.9.13* FreeBSD 12.4: 3.9.16 FreeBSD 13.1: 3.9.16 OpenBSD 7.2: 3.9.16
Note: Our VM tests install 3.9 explicitly for FreeBSD and 3.10 for NetBSD; the default for "python" or "python3" in FreeBSD is 3.9.16. NetBSD does not appear to have a default meta-package, but offers several options, the lowest of which is 3.7.15. "python39" appears to be a pre-requisite to one of the other packages we request in tests/vm/netbsd. pip, ensurepip and other Python essentials are currently only available for Python 3.10 for NetBSD.
CentOS and OpenSUSE support parallel installation of multiple Python interpreters, and binaries in /usr/bin will always use Python 3.6. However, the newly introduced support for virtual environments ensures that all build steps that execute QEMU Python code use a single interpreter.
Since it is safe to under our supported platform policy, bump our minimum supported version of Python to 3.7.
--- docs/about/build-platforms.rst | 2 +- configure | 10 +++++----- python/Makefile | 10 +++++----- python/setup.cfg | 7 +++---- python/tests/minreqs.txt | 2 +- scripts/qapi/mypy.ini | 2 +- 6 files changed, 16 insertions(+), 17 deletions(-)
docs/about/build-platforms.rst +1 -1
@@ -98,7 +98,7 @@ Python runtime option of the ``configure`` script to point QEMU to a supported version of the Python runtime. - As of QEMU |version|, the minimum supported version of Python is 3.6. + As of QEMU |version|, the minimum supported version of Python is 3.7. Python build dependencies Some of QEMU's build dependencies are written in Python. Usually these
configure +5 -5
@@ -618,9 +618,9 @@ esac check_py_version() { - # We require python >= 3.6. + # We require python >= 3.7. # NB: a True python conditional creates a non-zero return code (Failure) - "$1" -c 'import sys; sys.exit(sys.version_info < (3,6))' + "$1" -c 'import sys; sys.exit(sys.version_info < (3,7))' } python=
@@ -629,7 +629,7 @@ first_python= if test -z "${PYTHON}"; then # A bare 'python' is traditionally python 2.x, but some distros # have it as python 3.x, so check in both places. - for binary in python3 python python3.11 python3.10 python3.9 python3.8 python3.7 python3.6; do + for binary in python3 python python3.11 python3.10 python3.9 python3.8 python3.7; do if has "$binary"; then python=$(command -v "$binary") if check_py_version "$python"; then
@@ -1078,7 +1078,7 @@ then # If first_python is set, there was a binary somewhere even though # it was not suitable. Use it for the error message. if test -n "$first_python"; then - error_exit "Cannot use '$first_python', Python >= 3.6 is required." \ + error_exit "Cannot use '$first_python', Python >= 3.7 is required." \ "Use --python=/path/to/python to specify a supported Python." else error_exit "Python not found. Use --python=/path/to/python"
@@ -1091,7 +1091,7 @@ then fi if ! check_py_version "$python"; then - error_exit "Cannot use '$python', Python >= 3.6 is required." \ + error_exit "Cannot use '$python', Python >= 3.7 is required." \ "Use --python=/path/to/python to specify a supported Python." fi
python/Makefile +5 -5
@@ -9,14 +9,14 @@ help: @echo "make check-minreqs:" @echo " Run tests in the minreqs virtual environment." @echo " These tests use the oldest dependencies." - @echo " Requires: Python 3.6" - @echo " Hint (Fedora): 'sudo dnf install python3.6'" + @echo " Requires: Python 3.7" + @echo " Hint (Fedora): 'sudo dnf install python3.7'" @echo "" @echo "make check-tox:" @echo " Run tests against multiple python versions." @echo " These tests use the newest dependencies." - @echo " Requires: Python 3.6 - 3.10, and tox." - @echo " Hint (Fedora): 'sudo dnf install python3-tox python3.10'" + @echo " Requires: Python 3.7 - 3.11, and tox." + @echo " Hint (Fedora): 'sudo dnf install python3-tox python3.11'" @echo " The variable QEMU_TOX_EXTRA_ARGS can be use to pass extra" @echo " arguments to tox". @echo ""
@@ -59,7 +59,7 @@ PIP_INSTALL = pip install --disable-pip-version-check min-venv: $(QEMU_MINVENV_DIR) $(QEMU_MINVENV_DIR)/bin/activate $(QEMU_MINVENV_DIR) $(QEMU_MINVENV_DIR)/bin/activate: setup.cfg tests/minreqs.txt @echo "VENV $(QEMU_MINVENV_DIR)" - @python3.6 -m venv $(QEMU_MINVENV_DIR) + @python3.7 -m venv $(QEMU_MINVENV_DIR) @( \ echo "ACTIVATE $(QEMU_MINVENV_DIR)"; \ . $(QEMU_MINVENV_DIR)/bin/activate; \
python/setup.cfg +3 -4
@@ -14,7 +14,6 @@ classifiers = Natural Language :: English Operating System :: OS Independent Programming Language :: Python :: 3 :: Only - Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9
@@ -23,7 +22,7 @@ classifiers = Typing :: Typed [options] -python_requires = >= 3.6 +python_requires = >= 3.7 packages = qemu.qmp qemu.machine
@@ -76,7 +75,7 @@ exclude = __pycache__, [mypy] strict = True -python_version = 3.6 +python_version = 3.7 warn_unused_configs = True namespace_packages = True warn_unused_ignores = False
@@ -169,7 +168,7 @@ multi_line_output=3 # of python available on your system to run this test. [tox:tox] -envlist = py36, py37, py38, py39, py310, py311 +envlist = py37, py38, py39, py310, py311 skip_missing_interpreters = true [testenv]
python/tests/minreqs.txt +1 -1
@@ -1,5 +1,5 @@ # This file lists the ***oldest possible dependencies*** needed to run -# "make check" successfully under ***Python 3.6***. It is used primarily +# "make check" successfully under ***Python 3.7***. It is used primarily # by GitLab CI to ensure that our stated minimum versions in setup.cfg # are truthful and regularly validated. #
scripts/qapi/mypy.ini +1 -1
@@ -1,7 +1,7 @@ [mypy] strict = True disallow_untyped_calls = False -python_version = 3.6 +python_version = 3.7 [mypy-qapi.schema] disallow_untyped_defs = False
Signature · 1 line
2.40.0
PATCH 24/27 configure: Add courtesy hint to Python version failure message
In reply to John SnowIf we begin requiring Python 3.7+, a few platforms are going to need to install an additional Python interpreter package.
As a courtesy to the user, suggest the optional package they might need to install. This will hopefully minimize any downtime caused by the change in Python dependency.
Message-Id: <[email protected]>
--- configure | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
configure +4 -1
@@ -1092,7 +1092,10 @@ fi if ! check_py_version "$python"; then error_exit "Cannot use '$python', Python >= 3.7 is required." \ - "Use --python=/path/to/python to specify a supported Python." + "Use --python=/path/to/python to specify a supported Python." \ + "Maybe try:" \ + " openSUSE Leap 15.3+: zypper install python39" \ + " CentOS 8: dnf install python38" fi # Resolve PATH
Signature · 1 line
2.40.0
PATCH 25/27 mkvenv: mark command as required
In reply to John SnowFrom: Paolo Bonzini <[email protected]>
This is only available in Python 3.7+.
--- python/scripts/mkvenv.py | 1 + 1 file changed, 1 insertion(+)
python/scripts/mkvenv.py +1 -0
@@ -856,6 +856,7 @@ def main() -> int: subparsers = parser.add_subparsers( title="Commands", dest="command", + required=True, metavar="command", help="Description", )
Signature · 1 line
2.40.0
PATCH 26/27 python: bump some of the dependencies
In reply to John SnowFrom: Paolo Bonzini <[email protected]>
The version of pyflakes that is listed in python/tests/minreqs.txt breaks on Python 3.8 with the following message:
AttributeError: 'FlakesChecker' object has no attribute 'CONSTANT'
Now that we do not support EOL'd Python versions anymore, we can update to newer, fixed versions. It is a good time to do so, before Python packages start dropping support for Python 3.7 as well!
--- python/setup.cfg | 4 ++-- python/tests/minreqs.txt | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-)
python/setup.cfg +2 -2
@@ -35,11 +35,11 @@ packages = # Remember to update tests/minreqs.txt if changing anything below: devel = avocado-framework >= 90.0 - flake8 >= 3.6.0 + flake8 >= 5.0.4 fusepy >= 2.0.4 isort >= 5.1.2 mypy >= 0.780 - pylint >= 2.8.0 + pylint >= 2.17.3 tox >= 3.18.0 urwid >= 2.1.2 urwid-readline >= 0.13
python/tests/minreqs.txt +7 -7
@@ -23,23 +23,23 @@ fusepy==2.0.4 avocado-framework==90.0 # Linters -flake8==3.6.0 +flake8==5.0.4 isort==5.1.2 mypy==0.780 -pylint==2.8.0 +pylint==2.17.3 # Transitive flake8 dependencies -mccabe==0.6.0 -pycodestyle==2.4.0 -pyflakes==2.0.0 +mccabe==0.7.0 +pycodestyle==2.9.1 +pyflakes==2.5.0 # Transitive mypy dependencies mypy-extensions==0.4.3 typed-ast==1.4.0 -typing-extensions==3.7.4 +typing-extensions==4.5.0 # Transitive pylint dependencies -astroid==2.5.4 +astroid==2.15.4 lazy-object-proxy==1.4.0 toml==0.10.0 wrapt==1.12.1
Signature · 1 line
2.40.0
PATCH 27/27 mkvenv.py: experiment; use distlib to generate script entry points
In reply to John SnowThis is an experiment: by using pip's internal vendored distlib, we can generate script entry points for Windows, Mac and Linux using distlib's mechanisms. This is the same mechanism used when running "pip install", so it will be consistent with the most common method of package installation on all platforms. It also allows us to delete a good bit of vendored/borrowed code from inside of mkvenv.py, so there's less to maintain and the license might be more straightforward.
As a downside, if we're not willing to actually add a distlib requirement, we have to piggy-back on pip's vendored version, which could have downsides if they move our cheese in the future.
--- configure | 16 +----- python/scripts/mkvenv.py | 117 +++++++++++++-------------------------- python/setup.cfg | 7 ++- 3 files changed, 46 insertions(+), 94 deletions(-)
configure +1 -15
@@ -1147,21 +1147,7 @@ fi # We ignore PATH completely here: we want to use the venv's Meson # *exclusively*. -# "mkvenv ensure" has a limitation compared to "pip install": it is not -# able to create launcher .exe files on Windows. This limitation exists -# because "py.exe" is not guaranteed to exist on the machine (pip/setuptools -# work around the issue by bundling the .exe files as resources). -# This is not a problem for msys, since it emulates a POSIX environment; -# it is also okay for programs that meson.build looks up with find_program(), -# because in that case Meson checks the file for a shebang line. However, -# when meson wants to invoke itself as part of a build recipe, we need -# to convince it to put the python interpreter in front of the path to the -# script. To do so, run it using '-m'. -if test "$targetos" = windows; then - meson="$python -m mesonbuild.mesonmain" -else - meson="$(cd pyvenv/bin; pwd)/meson" -fi +meson="$(cd pyvenv/bin; pwd)/meson" # Conditionally ensure Sphinx is installed.
python/scripts/mkvenv.py +39 -78
202 lines not on this page · raw message
python/setup.cfg +6 -1
@@ -111,6 +111,12 @@ ignore_missing_imports = True [mypy-pkg_resources] ignore_missing_imports = True +[mypy-distlib] +ignore_missing_imports = True + +[mypy-pip._vendor.distlib] +ignore_missing_imports = True + [pylint.messages control] # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this
@@ -123,7 +129,6 @@ ignore_missing_imports = True # --disable=W". disable=consider-using-f-string, consider-using-with, - fixme, too-many-arguments, too-many-function-args, # mypy handles this with less false positives. too-many-instance-attributes,
Signature · 1 line
2.40.0
Re: [PATCH 27/27] mkvenv.py: experiment; use distlib to generate script entry points
Quoted 11 lines · John Snow
This is an experiment: by using pip's internal vendored distlib, we can generate script entry points for Windows, Mac and Linux using distlib's mechanisms. This is the same mechanism used when running "pip install", so it will be consistent with the most common method of package installation on all platforms. It also allows us to delete a good bit of vendored/borrowed code from inside of
mkvenv.py, so there's less to maintain and the license might be more straightforward.As a downside, if we're not willing to actually add a distlib requirement, we have to piggy-back on pip's vendored version, which could have downsides if they move our cheese in the future.
I think the downsides are limited since you're trying both the "real" distlib and pip's. Overall I like this, though I haven't made up my mind if it should be split and squashed earlier in the series.
Paolo
Re: [PATCH 27/27] mkvenv.py: experiment; use distlib to generate script entry points
In reply to John Snowpython/scripts/mkvenv.py def post_venv_setup() -> None: · line 754
Quoted 9 lines · John Snow
python/scripts/mkvenv.py +6
-0+ if checkpip(): + # We ran ensurepip. We need to re-run post_init...! + args = [sys.executable, __file__, "post_init"] + subprocess.run(args, check=True) + return + # Finally, generate a 'pip' script so the venv is usable in a normal # way from the CLI. This only happens when we inherited pip from a # parent/system-site and haven't run ensurepip in some way.
Can't this just be:
+ if not checkpip():
+ # Finally, generate a 'pip' script so the venv is usable in a normal + # way from the CLI. This only happens when we inherited pip from a + # parent/system-site and haven't run ensurepip in some way. + generate_console_scripts(["pip"])
even squashed in the original Debian 10 patch?
You don't need to generate the pip shims if ensurepip has been run.
Paolo
Re: [PATCH 27/27] mkvenv.py: experiment; use distlib to generate script entry points
Quoted 21 lines · Paolo Bonzini
python/scripts/mkvenv.py def post_venv_setup() -> None:
Quoted 7 lines · John Snow
python/scripts/mkvenv.py +6
-0+ if checkpip(): + # We ran ensurepip. We need to re-run post_init...! + args = [sys.executable, __file__, "post_init"] + subprocess.run(args, check=True) + return + # Finally, generate a 'pip' script so the venv is usable in anormal
Quoted 2 lines
# way from the CLI. This only happens when we inherited pip from a # parent/system-site and haven't run ensurepip in some way.Can't this just be:
(quoted diff) +2
-0+ if not checkpip(): + # Finally, generate a 'pip' script so the venv is usable in anormal
(quoted diff) +3
-0+ # way from the CLI. This only happens when we inherited pip from a + # parent/system-site and haven't run ensurepip in some way. + generate_console_scripts(["pip"])
Quoted 1 line
even squashed in the original
Debian 10 patch?
Quoted 5 lines
You don't need to generate the pip shims if ensurepip has been run.
Paolo
*cough*
You’re completely right. I was so preoccupied on diagnosing why it was failing I didn't even recognize that it wasn't even needed...
*facepalm*
I'll make that simplifying change, which will also allow me to just put the import in the global scope instead of trying to do it JIT to work around ensurepip shenanigans. Should be a few less "I know this is bad" comments for the linters, too.
--js
Quoted 1 line
Re: [PATCH 27/27] mkvenv.py: experiment; use distlib to generate script entry points
Il gio 11 mag 2023, 17:58 John Snow <[email protected]> ha scritto:
Quoted 6 lines
I'll make that simplifying change, which will also allow me to just put
Quoted 3 lines
the import in the global scope instead of trying to do it JIT to work around ensurepip shenanigans. Should be a few less "I know this is bad" comments for the linters, too.
I don't think you can do that because, until you are running in the new venv, you aren't guaranteed to have either distlib or pip. Once in the venv you'll get the latter via ensurepip, if it wasn't already present in the system site-packages.
Paolo
--js
Quoted 2 lines
Quoted 2 lines
Re: [PATCH 27/27] mkvenv.py: experiment; use distlib to generate script entry points
Quoted 10 lines · Paolo Bonzini
Il gio 11 mag 2023, 17:58 John Snow <[email protected]> ha scritto:
Quoted 6 lines
I'll make that simplifying change, which will also allow me to just put
Quoted 3 lines
the import in the global scope instead of trying to do it JIT to work around ensurepip shenanigans. Should be a few less "I know this is bad" comments for the linters, too.
Quoted 7 lines
I don't think you can do that because, until you are running in the new venv, you aren't guaranteed to have either distlib or pip. Once in the venv you'll get the latter via ensurepip, if it wasn't already present in the system site-packages.
Paolo
Yeah, not without a *little* trickery. It still needs a try/except but it can be moved up.
Or I could leave well enough alone and worry about cleaning up imports when we move to 3.8