Files
cibuildwheel/cibuildwheel/linux.py
T

514 lines
20 KiB
Python
Raw Normal View History

from __future__ import annotations
2019-11-12 23:51:27 +00:00
import subprocess
import sys
import textwrap
from collections.abc import Iterable, Iterator, Sequence, Set
2022-04-28 09:19:27 -04:00
from dataclasses import dataclass
2022-05-24 17:35:46 -06:00
from pathlib import Path, PurePath, PurePosixPath
from typing import OrderedDict, Tuple
2017-03-19 21:27:29 +00:00
from packaging.version import Version
from . import errors
from ._compat.typing import assert_never
2021-01-22 09:33:22 -05:00
from .architecture import Architecture
2020-11-13 16:30:27 +00:00
from .logger import log
from .oci_container import OCIContainer, OCIContainerEngineConfig
from .options import BuildOptions, Options
2023-04-18 23:05:34 -04:00
from .typing import PathOrStr
2021-01-06 13:50:58 -05:00
from .util import (
2023-08-26 19:37:29 +01:00
BuildFrontendConfig,
2021-01-06 13:50:58 -05:00
BuildSelector,
find_compatible_wheel,
2021-01-06 13:50:58 -05:00
get_build_verbosity_extra_flags,
prepare_command,
2021-01-09 15:40:40 -05:00
read_python_configs,
2022-09-06 00:56:20 -04:00
split_config_settings,
test_fail_cwd_file,
unwrap,
2021-01-06 13:50:58 -05:00
)
2020-02-21 06:42:19 -05:00
2022-04-28 09:19:27 -04:00
@dataclass(frozen=True)
class PythonConfiguration:
version: str
identifier: str
path_str: str
@property
2022-05-24 17:35:46 -06:00
def path(self) -> PurePosixPath:
return PurePosixPath(self.path_str)
2022-04-28 09:19:27 -04:00
@dataclass(frozen=True)
class BuildStep:
platform_configs: list[PythonConfiguration]
2021-09-21 11:34:20 -04:00
platform_tag: str
container_engine: OCIContainerEngineConfig
container_image: str
2021-09-21 11:34:20 -04:00
2020-12-16 23:17:51 +00:00
def get_python_configurations(
2021-01-09 15:40:40 -05:00
build_selector: BuildSelector,
architectures: Set[Architecture],
) -> list[PythonConfiguration]:
2021-05-03 11:45:43 -04:00
full_python_configs = read_python_configs("linux")
2021-01-09 15:40:40 -05:00
python_configurations = [PythonConfiguration(**item) for item in full_python_configs]
2021-01-01 16:53:45 -05:00
# return all configurations whose arch is in our `architectures` set,
2020-12-28 00:43:24 +00:00
# and match the build/skip rules
return [
2021-04-30 17:56:34 -04:00
c
for c in python_configurations
2020-12-31 16:35:26 +00:00
if any(c.identifier.endswith(arch.value) for arch in architectures)
and build_selector(c.identifier)
]
2017-04-11 22:57:42 +01:00
def container_image_for_python_configuration(
config: PythonConfiguration, build_options: BuildOptions
) -> str:
2021-10-12 02:05:47 +01:00
# e.g
# identifier is 'cp310-manylinux_x86_64'
# platform_tag is 'manylinux_x86_64'
# platform_arch is 'x86_64'
_, platform_tag = config.identifier.split("-", 1)
_, platform_arch = platform_tag.split("_", 1)
assert build_options.manylinux_images is not None
assert build_options.musllinux_images is not None
return (
build_options.manylinux_images[platform_arch]
if platform_tag.startswith("manylinux")
else build_options.musllinux_images[platform_arch]
)
2021-09-23 15:27:58 -04:00
def get_build_steps(
options: Options, python_configurations: list[PythonConfiguration]
2021-09-22 10:51:38 -04:00
) -> Iterator[BuildStep]:
2021-10-12 02:05:47 +01:00
"""
Groups PythonConfigurations into BuildSteps. Each BuildStep represents a
separate container instance.
2021-10-12 02:05:47 +01:00
"""
steps = OrderedDict[Tuple[str, str, str, OCIContainerEngineConfig], BuildStep]()
2021-09-20 12:17:42 -04:00
2021-10-12 02:05:47 +01:00
for config in python_configurations:
_, platform_tag = config.identifier.split("-", 1)
2021-09-20 12:17:42 -04:00
build_options = options.build_options(config.identifier)
2021-10-12 02:05:47 +01:00
before_all = build_options.before_all
container_image = container_image_for_python_configuration(config, build_options)
container_engine = build_options.container_engine
step_key = (platform_tag, container_image, before_all, container_engine)
2021-10-12 02:05:47 +01:00
if step_key in steps:
steps[step_key].platform_configs.append(config)
else:
steps[step_key] = BuildStep(
platform_configs=[config],
platform_tag=platform_tag,
container_engine=container_engine,
container_image=container_image,
2021-10-12 02:05:47 +01:00
)
yield from steps.values()
2021-09-20 12:17:42 -04:00
def check_all_python_exist(
*, platform_configs: Iterable[PythonConfiguration], container: OCIContainer
) -> None:
exist = True
has_manylinux_interpreters = True
messages = []
try:
# use capture_output to keep quiet
container.call(["manylinux-interpreters", "--help"], capture_output=True)
except subprocess.CalledProcessError:
has_manylinux_interpreters = False
for config in platform_configs:
python_path = config.path / "bin" / "python"
try:
if has_manylinux_interpreters:
container.call(["manylinux-interpreters", "ensure", config.path.name])
container.call(["test", "-x", python_path])
except subprocess.CalledProcessError:
messages.append(
f" '{python_path}' executable doesn't exist in image '{container.image}' to build '{config.identifier}'."
)
exist = False
if not exist:
message = "\n".join(messages)
raise errors.FatalError(message)
def build_in_container(
2021-10-12 02:05:47 +01:00
*,
options: Options,
platform_configs: Sequence[PythonConfiguration],
container: OCIContainer,
container_project_path: PurePath,
container_package_dir: PurePath,
) -> None:
2022-05-24 17:35:46 -06:00
container_output_dir = PurePosixPath("/output")
check_all_python_exist(platform_configs=platform_configs, container=container)
log.step("Copying project into container...")
container.copy_into(Path.cwd(), container_project_path)
2021-10-12 02:05:47 +01:00
before_all_options_identifier = platform_configs[0].identifier
before_all_options = options.build_options(before_all_options_identifier)
if before_all_options.before_all:
log.step("Running before_all...")
env = container.get_environment()
env["PATH"] = f'/opt/python/cp38-cp38/bin:{env["PATH"]}'
env["PIP_DISABLE_PIP_VERSION_CHECK"] = "1"
2022-10-11 10:06:35 -04:00
env["PIP_ROOT_USER_ACTION"] = "ignore"
2021-10-12 02:05:47 +01:00
env = before_all_options.environment.as_dictionary(
env, executor=container.environment_executor
2021-10-12 02:05:47 +01:00
)
before_all_prepared = prepare_command(
2021-10-12 02:05:47 +01:00
before_all_options.before_all,
project=container_project_path,
package=container_package_dir,
)
container.call(["sh", "-c", before_all_prepared], env=env)
built_wheels: list[PurePosixPath] = []
2022-04-18 14:24:53 +02:00
for config in platform_configs:
log.build_start(config.identifier)
2021-10-12 02:05:47 +01:00
build_options = options.build_options(config.identifier)
2023-08-26 19:37:29 +01:00
build_frontend = build_options.build_frontend or BuildFrontendConfig("pip")
2024-06-09 15:45:31 -04:00
use_uv = build_frontend.name == "build[uv]" and Version(config.version) >= Version("3.8")
pip = ["uv", "pip"] if use_uv else ["pip"]
dependency_constraint_flags: list[PathOrStr] = []
2021-10-12 02:05:47 +01:00
if build_options.dependency_constraints:
constraints_file = build_options.dependency_constraints.get_for_python_version(
config.version
)
container_constraints_file = PurePosixPath("/constraints.txt")
container.copy_into(constraints_file, container_constraints_file)
dependency_constraint_flags = ["-c", container_constraints_file]
log.step("Setting up build environment...")
env = container.get_environment()
2022-10-13 22:29:52 -04:00
env["PIP_DISABLE_PIP_VERSION_CHECK"] = "1"
env["PIP_ROOT_USER_ACTION"] = "ignore"
# put this config's python top of the list
python_bin = config.path / "bin"
env["PATH"] = f'{python_bin}:{env["PATH"]}'
env = build_options.environment.as_dictionary(env, executor=container.environment_executor)
# check config python is still on PATH
which_python = container.call(["which", "python"], env=env, capture_output=True).strip()
2022-05-24 17:35:46 -06:00
if PurePosixPath(which_python) != python_bin / "python":
msg = "python available on PATH doesn't match our installed instance. If you have modified PATH, ensure that you don't overwrite cibuildwheel's entry or insert python above it."
raise errors.FatalError(msg)
2024-06-09 15:45:31 -04:00
if use_uv:
which_uv = container.call(["which", "uv"], env=env, capture_output=True).strip()
if not which_uv:
msg = "uv not found on PATH. You must use a supported manylinux or musllinux environment with uv."
raise errors.FatalError(msg)
2024-06-09 15:45:31 -04:00
else:
which_pip = container.call(["which", "pip"], env=env, capture_output=True).strip()
if PurePosixPath(which_pip) != python_bin / "pip":
msg = "pip available on PATH doesn't match our installed instance. If you have modified PATH, ensure that you don't overwrite cibuildwheel's entry or insert pip above it."
raise errors.FatalError(msg)
compatible_wheel = find_compatible_wheel(built_wheels, config.identifier)
if compatible_wheel:
2022-04-18 14:24:53 +02:00
log.step_end()
print(
f"\nFound previously built wheel {compatible_wheel.name}, that's compatible with {config.identifier}. Skipping build step..."
)
repaired_wheels = [compatible_wheel]
else:
2022-04-18 14:24:53 +02:00
if build_options.before_build:
log.step("Running before_build...")
before_build_prepared = prepare_command(
build_options.before_build,
project=container_project_path,
package=container_package_dir,
)
container.call(["sh", "-c", before_build_prepared], env=env)
2022-04-18 14:24:53 +02:00
log.step("Building wheel...")
2022-05-24 17:35:46 -06:00
temp_dir = PurePosixPath("/tmp/cibuildwheel")
2022-04-18 14:24:53 +02:00
built_wheel_dir = temp_dir / "built_wheel"
container.call(["rm", "-rf", built_wheel_dir])
container.call(["mkdir", "-p", built_wheel_dir])
2023-08-26 19:37:29 +01:00
extra_flags = split_config_settings(build_options.config_settings, build_frontend.name)
extra_flags += build_frontend.args
2023-08-26 19:37:29 +01:00
if build_frontend.name == "pip":
extra_flags += get_build_verbosity_extra_flags(build_options.build_verbosity)
container.call(
2022-04-18 14:24:53 +02:00
[
"python",
"-m",
"pip",
"wheel",
container_package_dir,
f"--wheel-dir={built_wheel_dir}",
"--no-deps",
2022-09-06 00:56:20 -04:00
*extra_flags,
2022-04-18 14:24:53 +02:00
],
env=env,
)
2024-06-09 15:45:31 -04:00
elif build_frontend.name == "build" or build_frontend.name == "build[uv]":
if not 0 <= build_options.build_verbosity < 2:
msg = f"build_verbosity {build_options.build_verbosity} is not supported for build frontend. Ignoring."
log.warning(msg)
if use_uv and "--no-isolation" not in extra_flags and "-n" not in extra_flags:
2024-06-09 15:45:31 -04:00
extra_flags += ["--installer=uv"]
container.call(
2022-04-18 14:24:53 +02:00
[
"python",
"-m",
"build",
container_package_dir,
"--wheel",
f"--outdir={built_wheel_dir}",
2022-09-06 00:56:20 -04:00
*extra_flags,
2022-04-18 14:24:53 +02:00
],
env=env,
)
else:
assert_never(build_frontend)
2022-04-18 14:24:53 +02:00
built_wheel = container.glob(built_wheel_dir, "*.whl")[0]
2022-04-18 14:24:53 +02:00
repaired_wheel_dir = temp_dir / "repaired_wheel"
container.call(["rm", "-rf", repaired_wheel_dir])
container.call(["mkdir", "-p", repaired_wheel_dir])
2022-04-18 14:24:53 +02:00
if built_wheel.name.endswith("none-any.whl"):
raise errors.NonPlatformWheelError()
2022-04-18 14:24:53 +02:00
if build_options.repair_command:
log.step("Repairing wheel...")
repair_command_prepared = prepare_command(
build_options.repair_command, wheel=built_wheel, dest_dir=repaired_wheel_dir
)
container.call(["sh", "-c", repair_command_prepared], env=env)
2022-04-18 14:24:53 +02:00
else:
container.call(["mv", built_wheel, repaired_wheel_dir])
2022-04-18 14:24:53 +02:00
repaired_wheels = container.glob(repaired_wheel_dir, "*.whl")
for repaired_wheel in repaired_wheels:
if repaired_wheel.name in {wheel.name for wheel in built_wheels}:
raise errors.AlreadyBuiltWheelError(repaired_wheel.name)
2021-10-12 02:05:47 +01:00
if build_options.test_command and build_options.test_selector(config.identifier):
log.step("Testing wheel...")
# set up a virtual environment to install and test from, to make sure
# there are no dependencies that were pulled in at build time.
2024-06-09 15:45:31 -04:00
if not use_uv:
container.call(
["pip", "install", "virtualenv", *dependency_constraint_flags], env=env
)
testing_temp_dir = PurePosixPath(
container.call(["mktemp", "-d"], capture_output=True).strip()
)
venv_dir = testing_temp_dir / "venv"
2024-06-09 15:45:31 -04:00
if use_uv:
container.call(["uv", "venv", venv_dir], env=env)
else:
# Use embedded dependencies from virtualenv to ensure determinism
venv_args = ["--no-periodic-update", "--pip=embed"]
# In Python<3.12, setuptools & wheel are installed as well
if Version(config.version) < Version("3.12"):
venv_args.extend(("--setuptools=embed", "--wheel=embed"))
container.call(["python", "-m", "virtualenv", *venv_args, venv_dir], env=env)
virtualenv_env = env.copy()
virtualenv_env["PATH"] = f"{venv_dir / 'bin'}:{virtualenv_env['PATH']}"
2024-05-29 02:20:02 -04:00
virtualenv_env["VIRTUAL_ENV"] = str(venv_dir)
2021-10-12 02:05:47 +01:00
if build_options.before_test:
before_test_prepared = prepare_command(
2021-10-12 02:05:47 +01:00
build_options.before_test,
project=container_project_path,
package=container_package_dir,
)
container.call(["sh", "-c", before_test_prepared], env=virtualenv_env)
# Install the wheel we just built
# Note: If auditwheel produced two wheels, it's because the earlier produced wheel
# conforms to multiple manylinux standards. These multiple versions of the wheel are
# functionally the same, differing only in name, wheel metadata, and possibly include
# different external shared libraries. so it doesn't matter which one we run the tests on.
# Let's just pick the first one.
wheel_to_test = repaired_wheels[0]
container.call(
2024-06-09 15:45:31 -04:00
[*pip, "install", str(wheel_to_test) + build_options.test_extras],
env=virtualenv_env,
)
# Install any requirements to run the tests
2021-10-12 02:05:47 +01:00
if build_options.test_requires:
2024-06-09 15:45:31 -04:00
container.call([*pip, "install", *build_options.test_requires], env=virtualenv_env)
# Run the tests from a different directory
test_command_prepared = prepare_command(
2021-10-12 02:05:47 +01:00
build_options.test_command,
project=container_project_path,
package=container_package_dir,
wheel=wheel_to_test,
)
test_cwd = testing_temp_dir / "test_cwd"
container.call(["mkdir", "-p", test_cwd])
container.copy_into(test_fail_cwd_file, test_cwd / "test_fail.py")
container.call(["sh", "-c", test_command_prepared], cwd=test_cwd, env=virtualenv_env)
# clean up test environment
container.call(["rm", "-rf", testing_temp_dir])
# move repaired wheels to output
if compatible_wheel is None:
container.call(["mkdir", "-p", container_output_dir])
container.call(["mv", *repaired_wheels, container_output_dir])
2022-04-18 14:24:53 +02:00
built_wheels.extend(
container_output_dir / repaired_wheel.name for repaired_wheel in repaired_wheels
)
log.build_end()
log.step("Copying wheels back to host...")
# copy the output back into the host
container.copy_out(container_output_dir, options.globals.output_dir)
log.step_end()
2023-01-30 15:53:44 -05:00
def build(options: Options, tmp_path: Path) -> None: # noqa: ARG001
2021-09-19 00:19:28 -04:00
python_configurations = get_python_configurations(
2021-10-12 02:05:47 +01:00
options.globals.build_selector, options.globals.architectures
2021-09-19 00:19:28 -04:00
)
2017-04-11 22:57:42 +01:00
2020-06-17 00:18:40 +02:00
cwd = Path.cwd()
2021-10-12 02:05:47 +01:00
abs_package_dir = options.globals.package_dir.resolve()
2020-06-17 00:18:40 +02:00
if cwd != abs_package_dir and cwd not in abs_package_dir.parents:
2022-09-05 13:11:46 -04:00
msg = "package_dir must be inside the working directory"
raise Exception(msg)
2022-05-24 17:35:46 -06:00
container_project_path = PurePosixPath("/project")
container_package_dir = container_project_path / abs_package_dir.relative_to(cwd)
2021-10-12 02:05:47 +01:00
for build_step in get_build_steps(options, python_configurations):
try:
# check the container engine is installed
subprocess.run(
[build_step.container_engine.name, "--version"],
check=True,
stdout=subprocess.DEVNULL,
)
except subprocess.CalledProcessError as error:
msg = unwrap(
f"""
cibuildwheel: {build_step.container_engine.name} not found. An
OCI exe like Docker or Podman is required to run Linux builds.
If you're building on Travis CI, add `services: [docker]` to
your .travis.yml. If you're building on Circle CI in Linux,
add a `setup_remote_docker` step to your .circleci/config.yml.
If you're building on Cirrus CI, use `docker_builder` task.
"""
)
raise errors.ConfigurationError(msg) from error
try:
2021-10-12 02:05:47 +01:00
ids_to_build = [x.identifier for x in build_step.platform_configs]
log.step(f"Starting container image {build_step.container_image}...")
print(f"info: This container will host the build for {', '.join(ids_to_build)}...")
2021-09-21 11:34:20 -04:00
with OCIContainer(
image=build_step.container_image,
2023-09-07 19:05:58 +02:00
enforce_32_bit=build_step.platform_tag.endswith("i686"),
2021-04-30 17:56:34 -04:00
cwd=container_project_path,
engine=build_step.container_engine,
) as container:
build_in_container(
2021-10-12 02:05:47 +01:00
options=options,
platform_configs=build_step.platform_configs,
container=container,
2021-10-12 02:05:47 +01:00
container_project_path=container_project_path,
container_package_dir=container_package_dir,
)
2020-11-01 11:43:28 +00:00
except subprocess.CalledProcessError as error:
2021-10-12 02:05:47 +01:00
troubleshoot(options, error)
msg = f"Command {error.cmd} failed with code {error.returncode}. {error.stdout or ''}"
raise errors.FatalError(msg) from error
def _matches_prepared_command(error_cmd: Sequence[str], command_template: str) -> bool:
2021-08-26 15:23:57 -07:00
if len(error_cmd) < 3 or error_cmd[0:2] != ["sh", "-c"]:
return False
command_prefix = command_template.split("{", maxsplit=1)[0].strip()
return error_cmd[2].startswith(command_prefix)
2021-10-12 02:05:47 +01:00
def troubleshoot(options: Options, error: Exception) -> None:
2021-06-23 10:47:18 -04:00
if isinstance(error, subprocess.CalledProcessError) and (
error.cmd[0:4] == ["python", "-m", "pip", "wheel"]
or error.cmd[0:3] == ["python", "-m", "build"]
2021-09-19 00:19:28 -04:00
or _matches_prepared_command(
2021-10-12 02:05:47 +01:00
error.cmd, options.build_options(None).repair_command
) # TODO allow matching of overrides too?
2021-06-23 10:47:18 -04:00
):
2021-10-12 02:05:47 +01:00
# the wheel build step or the repair step failed
so_files = list(options.globals.package_dir.glob("**/*.so"))
if so_files:
2021-04-30 17:56:34 -04:00
print(
textwrap.dedent(
2021-05-03 11:45:43 -04:00
"""
2021-05-02 16:37:38 +02:00
NOTE: Shared object (.so) files found in this project.
2021-05-02 16:37:38 +02:00
These files might be built against the wrong OS, causing problems with
2021-08-26 15:23:57 -07:00
auditwheel. If possible, run cibuildwheel in a clean checkout.
2021-05-02 16:37:38 +02:00
If you're using Cython and have previously done an in-place build,
remove those build files (*.so and *.c) before starting cibuildwheel.
2021-08-26 15:23:57 -07:00
setuptools uses the build/ folder to store its build cache. It
may be necessary to remove those build files (*.so and *.o) before
starting cibuildwheel.
Files that belong to a virtual environment are probably not an issue
unless you used a custom command telling cibuildwheel to activate it.
2021-05-03 11:45:43 -04:00
"""
2021-04-30 17:56:34 -04:00
),
file=sys.stderr,
)
2021-05-03 11:45:43 -04:00
print(" Files detected:")
print("\n".join(f" {f}" for f in so_files))
2022-10-07 08:47:31 -04:00
print()