diff --git a/.github/scripts/pr-tests.cjs b/.github/scripts/pr-tests.cjs index 156a8fc01..bf8f8b63a 100644 --- a/.github/scripts/pr-tests.cjs +++ b/.github/scripts/pr-tests.cjs @@ -1,11 +1,11 @@ // This controller is loaded only from the trusted workflow commit, never a PR. -const SUITES = new Set(['cloud', 'openwhisk']); +const SUITES = new Set(['cloud', 'openwhisk', 'local']); const WRITE_PERMISSIONS = new Set(['admin', 'maintain', 'write']); function parseCommand(body) { - const match = /^\/test (cloud|openwhisk) ([0-9a-f]{40})$/.exec(body.trim()); + const match = /^\/test (cloud|openwhisk|local) ([0-9a-f]{40})$/.exec(body.trim()); if (!match) { - throw new Error('Usage: /test '); + throw new Error('Usage: /test '); } return { suite: match[1], sha: match[2] }; } @@ -87,7 +87,11 @@ async function report({ github, context, env = process.env }) { if (!SUITES.has(env.TEST_SUITE) || !/^[0-9a-f]{40}$/.test(env.TEST_SHA)) { throw new Error('Invalid regression status target'); } - const result = env.TEST_SUITE === 'cloud' ? env.CLOUD_RESULT : env.OPENWHISK_RESULT; + const result = { + cloud: env.CLOUD_RESULT, + openwhisk: env.OPENWHISK_RESULT, + local: env.LOCAL_RESULT, + }[env.TEST_SUITE]; const state = result === 'success' ? 'success' : result === 'failure' ? 'failure' : 'error'; await status(github, context, { sha: env.TEST_SHA, suite: env.TEST_SUITE, state, diff --git a/.github/workflows/pr-tests.yml b/.github/workflows/pr-tests.yml index d0acc09eb..a1c5d44f6 100644 --- a/.github/workflows/pr-tests.yml +++ b/.github/workflows/pr-tests.yml @@ -17,7 +17,7 @@ on: suite: description: Test suite type: choice - options: [cloud, openwhisk] + options: [cloud, openwhisk, local] required: true permissions: @@ -93,8 +93,17 @@ jobs: with: code_ref: ${{ needs.resolve.outputs.sha }} + local: + needs: resolve + if: needs.resolve.outputs.suite == 'local' + permissions: + contents: read + uses: $/.github/workflows/regression-local.yml + with: + code_ref: ${{ needs.resolve.outputs.sha }} + report: - needs: [resolve, cloud, openwhisk] + needs: [resolve, cloud, openwhisk, local] if: always() && needs.resolve.result == 'success' runs-on: ubuntu-latest permissions: @@ -113,6 +122,7 @@ jobs: TEST_SUITE: ${{ needs.resolve.outputs.suite }} CLOUD_RESULT: ${{ needs.cloud.result }} OPENWHISK_RESULT: ${{ needs.openwhisk.result }} + LOCAL_RESULT: ${{ needs.local.result }} with: script: | await require('./.github/scripts/pr-tests.cjs').report({ github, context }); diff --git a/.github/workflows/regression-local.yml b/.github/workflows/regression-local.yml new file mode 100644 index 000000000..e475c5cff --- /dev/null +++ b/.github/workflows/regression-local.yml @@ -0,0 +1,127 @@ +name: Local Regression + +on: + workflow_call: + inputs: + code_ref: + description: Approved commit to test; empty uses the triggering commit + type: string + required: false + default: "" + workflow_dispatch: + push: + branches: + - master + - "feature/**" + +jobs: + regression: + strategy: + matrix: + language: [python, nodejs] + architecture: [x64, arm64] + include: + - language: python + version: "3.11" + - language: nodejs + version: "20" + fail-fast: false + + name: ${{ matrix.language }} ${{ matrix.version }} ${{ matrix.architecture }} + # Local functions run on the Docker daemon's architecture, so each + # architecture needs a native runner. + runs-on: ${{ matrix.architecture == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-latest' }} + timeout-minutes: 60 + + env: + RESOURCE_PREFIX: ci + LANGUAGE: ${{ matrix.language }} + LANGUAGE_VERSION: ${{ matrix.version }} + ARCHITECTURE: ${{ matrix.architecture }} + + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.code_ref || github.sha }} + submodules: recursive + persist-credentials: false + + - name: Install uv + uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + with: + enable-cache: ${{ inputs.code_ref == '' }} + + - name: Create virtual environment and install SeBS + run: | + uv venv + uv pip install . + + - name: Start RustFS and ScyllaDB + run: | + set -o pipefail + uv run sebs storage start all configs/storage.json --output-json storage.json + + - name: Create local regression config + run: | + jq \ + --arg language "${LANGUAGE}" \ + --arg version "${LANGUAGE_VERSION}" \ + --arg architecture "${ARCHITECTURE}" \ + ' + .experiments.deployment = "local" + | .deployment.name = "local" + | .experiments.architecture = $architecture + | .experiments.system_variant = "package" + | .experiments.runtime.language = $language + | .experiments.runtime.version = $version + ' configs/example.json > local-regression.json + + - name: Run local regression + id: regression + continue-on-error: true + timeout-minutes: 45 + run: | + set -o pipefail + uv run sebs benchmark regression test \ + --config local-regression.json \ + --storage-configuration storage.json \ + --deployment local \ + --language ${LANGUAGE} \ + --language-version ${LANGUAGE_VERSION} \ + --architecture ${ARCHITECTURE} \ + --selected-architecture \ + --resource-prefix ${RESOURCE_PREFIX} \ + --filter-output + + - name: Collect function container logs + if: steps.regression.outcome == 'failure' + run: | + mkdir -p diagnostics + docker ps -a > diagnostics/containers.txt 2>&1 || true + for container in $(docker ps -a --format '{{.Names}}'); do + docker logs "${container}" > "diagnostics/${container}.log" 2>&1 || true + done + + - name: Upload regression artifacts + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: local-regression-artifacts-${{ matrix.language }}-${{ matrix.version }}-${{ matrix.architecture }} + path: | + diagnostics/ + regression-cache/ + storage.json + local-regression.json + regression_*.json + regression_*.log + if-no-files-found: ignore + + - name: Fail job when regression failed + if: steps.regression.outcome == 'failure' + run: exit 1 + + - name: Cleanup + if: always() + run: | + uv run sebs storage stop all storage.json || true diff --git a/CHANGELOG.md b/CHANGELOG.md index 28eef2641..406922e01 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,16 @@ ### Bug Fixes +* `sebs docker build --platform` for another architecture (e.g., x64 images on an ARM machine) failed with Docker's containerd image store, the default since Docker 29: "image ... does not provide the specified platform". Docker's build API runs the legacy builder, so SeBS now builds such images with BuildKit (`docker build --platform`). + +* Local functions failed to start when their server needed more than 2.5 seconds, e.g., Node.js containers emulated with QEMU; SeBS now waits up to 30 seconds. + +* `sebs docker build` and `sebs docker push` exit with status 1 and list the failed images when an image fails; they always exited with 0. + +* Node.js packages built for another architecture (e.g., arm64 functions on an x86 machine) contained native binaries of the build machine: npm selects platform-specific packages, such as sharp's `@img/sharp-linux-arm64`, by `--cpu`, `--os`, and `--libc`, not by `--arch`. The installer now passes all of them. Requires rebuilding the build images. + +* Python packages for x64 functions built on ARM machines (e.g., Apple Silicon) contained ARM binaries: multi-platform build images run natively there, so the installer now downloads x86 wheels for x64 targets. Cross-architecture builds accept all manylinux wheels compatible with the build image's glibc instead of only `manylinux_2_17`, which rejected old pinned packages (e.g., Pillow 8.0.0) and new releases (e.g., numpy for Python 3.14). Python dependencies are always installed from wheels. + * Change to input of 120.uploader benchmark to conform with new Wikipedia policies (#308) * Pull Minio images from the SeBS archive `spcleth/serverless-benchmarks:minio-reproducibility-archive-`, as MinIO no longer publishes images on Docker Hub or quay.io. @@ -22,6 +32,8 @@ ### Improvements +* Local deployment on ARM machines (Apple Silicon, Graviton): the local build and run images for Python and Node.js are multi-platform (x64 and arm64), and SeBS warns when the configured architecture differs from the host's. + * PAPI hardware counters in local Python images use the distribution's PAPI through a small C binding with overflow sampling (`sebs_papi`). It replaces the pypapi submodule, whose bundled PAPI predates many current CPUs, and is compiled in the run images, which previously shipped pypapi without its native module. Requires the updated local run images. * Support for multiple variants of the same programming language (#286). diff --git a/configs/systems.json b/configs/systems.json index b070a2bd1..a3640c1f5 100644 --- a/configs/systems.json +++ b/configs/systems.json @@ -23,6 +23,11 @@ "3.9": "python:3.9-slim", "3.10": "python:3.10-slim", "3.11": "python:3.11-slim" + }, + "arm64": { + "3.9": "python:3.9-slim", + "3.10": "python:3.10-slim", + "3.11": "python:3.11-slim" } }, "images": [ @@ -48,6 +53,10 @@ "x64": { "18": "ubuntu:22.04", "20": "ubuntu:22.04" + }, + "arm64": { + "18": "ubuntu:22.04", + "20": "ubuntu:22.04" } }, "images": [ @@ -68,7 +77,8 @@ } }, "architecture": [ - "x64" + "x64", + "arm64" ], "deployments": [ "package" diff --git a/dockerfiles/nodejs_installer.sh b/dockerfiles/nodejs_installer.sh index 01a3eaf95..b2871e7ee 100644 --- a/dockerfiles/nodejs_installer.sh +++ b/dockerfiles/nodejs_installer.sh @@ -7,9 +7,9 @@ fi cd /mnt/function if [ "${TARGET_ARCHITECTURE}" == "arm64" ]; then - npm install --arch=arm64 + npm install --arch=arm64 --cpu=arm64 --os=linux --libc=glibc elif [ "${TARGET_ARCHITECTURE}" = "x64" ]; then - npm install --arch=x64 + npm install --arch=x64 --cpu=x64 --os=linux --libc=glibc else echo "Unsupported architecture: $TARGET_ARCHITECTURE" exit 1 diff --git a/dockerfiles/python_installer.sh b/dockerfiles/python_installer.sh index 5525cf873..fd046350d 100644 --- a/dockerfiles/python_installer.sh +++ b/dockerfiles/python_installer.sh @@ -2,9 +2,35 @@ set -e cd /mnt/function -PLATFORM_ARG="" if [[ "${TARGET_ARCHITECTURE}" == "arm64" ]]; then - PLATFORM_ARG="--platform manylinux_2_17_aarch64 --only-binary=:all:" + TARGET_MACHINE="aarch64" +else + TARGET_MACHINE="x86_64" +fi + +# Install only wheels: no package is compiled, so packages never depend on the build machine. +PLATFORM_ARG="--only-binary=:all:" +if [[ "$(uname -m)" != "${TARGET_MACHINE}" ]]; then + # Cross-architecture build, e.g., arm64 functions on an x86 machine, or x64 functions + # on Apple Silicon, where the multi-platform build image runs natively. + # Without --platform, pip would install wheels for the build container's architecture. + # pip does not expand --platform to compatible tags, so we list all manylinux tags up to + # the image's glibc: both variants of a build image use the same distribution and glibc. + GLIBC_MINOR=$(python3 -c "import platform; print(platform.libc_ver()[1].split('.')[1])") + LOWEST_MINOR=5 + LEGACY_TAGS="manylinux2014 manylinux2010 manylinux1" + if [[ "${TARGET_MACHINE}" == "aarch64" ]]; then + LOWEST_MINOR=17 + LEGACY_TAGS="manylinux2014" + fi + for ((minor = GLIBC_MINOR; minor >= LOWEST_MINOR; minor--)); do + PLATFORM_ARG="${PLATFORM_ARG} --platform manylinux_2_${minor}_${TARGET_MACHINE}" + done + for tag in ${LEGACY_TAGS}; do + PLATFORM_ARG="${PLATFORM_ARG} --platform ${tag}_${TARGET_MACHINE}" + done + # Plain Linux wheels, e.g., the PyTorch CPU wheels pinned by 411.image-recognition. + PLATFORM_ARG="${PLATFORM_ARG} --platform linux_${TARGET_MACHINE}" fi if [[ "${TARGET_ARCHITECTURE}" == "arm64" ]] && [[ -f "requirements.txt.arm.${PYTHON_VERSION}" ]]; then diff --git a/docs/contributing.md b/docs/contributing.md index 3ca209e92..90cbe1c8e 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -39,10 +39,12 @@ SHA, and post one of these commands as a new comment: ```text /test cloud /test openwhisk +/test local ``` `cloud` runs the existing AWS/GCP/Azure matrix; `openwhisk` runs the existing -OpenWhisk matrix on kind. Each command must occupy the whole comment. Editing +OpenWhisk matrix on kind; `local` runs the local Docker deployment on x64 and +arm64 runners. Each command must occupy the whole comment. Editing an existing comment does not launch tests. Bot comments, ordinary issue comments, and commands from users without repository write access are ignored. @@ -52,9 +54,10 @@ targets `master`, and still has the specified head SHA. The dispatched workflow checks the target again before starting. A later push requires a new review and command; an earlier success remains attached only to the commit actually tested. -Results appear in the PR's status checks as `regression/cloud` or -`regression/openwhisk`, with a link to the run and its artifacts. For rejected -commands, inspect the **Run PR tests** request run in Actions. The same suites can +Results appear in the PR's status checks as `regression/cloud`, +`regression/openwhisk`, or `regression/local`, with a link to the run and its +artifacts. For rejected commands, inspect the **Run PR tests** request run in +Actions. The same suites can also be launched using **Actions → Run PR tests → Run workflow**, selecting branch `master` and supplying the PR number, suite, and reviewed head SHA. diff --git a/docs/platforms.md b/docs/platforms.md index c80ac441e..39ab3af5c 100644 --- a/docs/platforms.md +++ b/docs/platforms.md @@ -44,12 +44,18 @@ On Ubuntu-based distributions, this requires installing an OS package and execut ### Multi-platform Docker Images Build images, which encapsulate package building, are available as both x64 and arm64 for Python and Node.js on AWS Lambda. +The local deployment's build and run images for Python and Node.js are multi-platform too: local functions run on the host, so x86 and ARM machines (e.g., Apple Silicon, Graviton) pull the image of their own architecture. +Set the experiment's `architecture` to the host's (`x64` or `arm64`) for local deployments; SeBS warns about a mismatch, since dependencies are installed for the configured architecture. + To rebuild multi-platform images, an additional flag is needed to enable the internal `docker buildx` command: ```bash sebs docker build --image-type build --language python --deployment aws --language-version 3.11 --multi-platform +sebs docker build --deployment local --language python --language-version 3.11 --multi-platform ``` +A multi-platform build pushes the images for both architectures, and the combined manifest, to the repository. `sebs docker push --multi-platform` skips these images; without the flag, it pushes the locally built single-platform image. + When rebuilding build images (not necessary for regular users, only for developers), make sure that your Docker installation supports multi-platform images, e.g., [you use `containerd` image store](https://docs.docker.com/engine/storage/containerd/) - old Docker installations might not change the storage type after an upgrade to Docker 29.0, where `containerd` is the default. ## Cloud Account Identifiers diff --git a/sebs/cli.py b/sebs/cli.py index 08a79532c..59d794387 100644 --- a/sebs/cli.py +++ b/sebs/cli.py @@ -1095,9 +1095,9 @@ def docker_build( try: builder = DockerImageBuilder(config, get_project_root(), verbose=verbose) except docker.errors.DockerException: - return + sys.exit(1) - builder.build( + failed = builder.build( deployment=deployment, image_type=image_type, language=language, @@ -1108,6 +1108,21 @@ def docker_build( multi_platform=multi_platform, parallel=parallel, ) + _exit_on_failed_images("build", failed) + + +def _exit_on_failed_images(operation: str, failed: List[str]) -> None: + """Exit with status 1 and list the images whose build or push failed. + + Args: + operation: 'build' or 'push' + failed: Names of the failed images + """ + if failed: + click.echo(f"Failed to {operation} {len(failed)} image(s):", err=True) + for name in failed: + click.echo(f" {name}", err=True) + sys.exit(1) @docker_cmd.command("push") @@ -1142,6 +1157,12 @@ def docker_build( type=str, help="Specific dependency for cpp (opencv, boost, etc.)", ) +@click.option( + "--multi-platform/--no-multi-platform", + default=False, + type=bool, + help="When true, skip multi-platform images: their build already pushed them", +) @click.option("--verbose/--no-verbose", default=False, help="Enable verbose output") def docker_push_images( deployment, @@ -1150,12 +1171,14 @@ def docker_push_images( language_version, architecture, dependency_type, + multi_platform, verbose, ): """Push Docker infrastructure images to registry. This command pushes infrastructure images (build, run, manage, dependencies) to DockerHub. Images must be built locally first using 'docker build'. + Pass the same --multi-platform flag as to 'docker build'. """ from sebs.config import SeBSConfig from sebs.docker_builder import DockerImageBuilder @@ -1165,16 +1188,18 @@ def docker_push_images( try: builder = DockerImageBuilder(config, get_project_root(), verbose=verbose) except docker.errors.DockerException: - return + sys.exit(1) - builder.push( + failed = builder.push( deployment=deployment, image_type=image_type, language=language, language_version=language_version, architecture=architecture, dependency_type=dependency_type, + multi_platform=multi_platform, ) + _exit_on_failed_images("push", failed) def main(): diff --git a/sebs/docker_builder.py b/sebs/docker_builder.py index 3324e5b73..9785bb661 100644 --- a/sebs/docker_builder.py +++ b/sebs/docker_builder.py @@ -64,6 +64,8 @@ def __init__( self.config = config self.project_dir = project_dir self.dockerfiles_dir = os.path.join(project_dir, "dockerfiles") + # Images whose build or push failed in the current operation + self._failed: List[str] = [] if docker_client is None: try: @@ -82,10 +84,10 @@ def _should_use_multiplatform( ) -> bool: """Check if multi-platform build should be used for this image. - Multi-platform builds (x64 + arm64) are only enabled for: - - AWS platform - - Build images only - - Python or Node.js languages + Multi-platform builds (x64 + arm64) are enabled for: + - AWS build images of Python, Node.js, and Java; + - local build and run images of Python and Node.js: local functions run + on the host, so x86 and ARM machines pull the image of their architecture. Args: system: Deployment platform (e.g., 'aws', 'gcp') @@ -95,9 +97,11 @@ def _should_use_multiplatform( Returns: True if multi-platform build should be used, False otherwise """ - return ( - system == "aws" and image_type == "build" and language in ["python", "nodejs", "java"] - ) + if system == "aws": + return image_type == "build" and language in ["python", "nodejs", "java"] + if system == "local": + return image_type in ["build", "run"] and language in ["python", "nodejs"] + return False def _execute_multiplatform_build( self, @@ -254,8 +258,9 @@ def _execute_build( """ Execute the actual build operation for a single image. - For AWS Python/Node.js build images, uses multi-platform build (x64 + arm64). - For all other images, uses standard single-platform build. + With multi_platform, AWS build images and local build and run images are built + for x64 and arm64 (see _should_use_multiplatform). All other images use a + standard single-platform build. Args: system: Deployment platform @@ -311,13 +316,18 @@ def _execute_build( self.logging.debug(f"Building {image_name} from {dockerfile}") self.logging.debug(f"Build args: {buildargs}") + if platform_arg: + return self._execute_platform_build(image_name, dockerfile, buildargs, platform_arg) + try: + # Unlike the Docker CLI, docker-py keeps intermediate containers by default. self.docker_client.images.build( path=str(self.project_dir), dockerfile=dockerfile, buildargs=buildargs, tag=image_name, - platform=platform_arg, + rm=True, + forcerm=True, ) self.logging.info(f"Successfully built: {image_name}") return True @@ -330,32 +340,81 @@ def _execute_build( self.logging.debug(line["stream"].strip()) return False + def _execute_platform_build( + self, image_name: str, dockerfile: str, buildargs: dict, platform: str + ) -> bool: + """Build a single-platform image for the given platform with BuildKit. + + The build API of the Docker daemon, used by docker-py, runs the legacy builder. + With the containerd image store (default since Docker 29), it fails on images + for a platform other than the host's: "image ... does not provide the specified + platform". + + Args: + image_name: Docker image tag + dockerfile: Path to Dockerfile + buildargs: Build args + platform: Docker platform, e.g., linux/amd64 + + Returns: + True if build succeeded, False otherwise + """ + cmd = [ + "docker", + "build", + "--platform", + platform, + "--provenance", + "false", + "--load", + "-f", + dockerfile, + "-t", + image_name, + ] + for key, value in buildargs.items(): + cmd.extend(["--build-arg", f"{key}={value}"]) + cmd.append(str(self.project_dir)) + + try: + output = execute(cmd, cwd=str(self.project_dir)) + except RuntimeError as exc: + self.logging.error(f"Build failed for {image_name}") + self.logging.error(exc) + return False + self.logging.debug(f"Build log:\n{output}") + self.logging.info(f"Successfully built: {image_name}") + return True + def _execute_push( self, system: str, image_type: str, language: Optional[str] = None, version: Optional[str] = None, + multi_platform: bool = False, **kwargs, # Ignore extra args like version_name, platform, parallel ) -> bool: """ Execute the actual push operation for a single image. - Multi-platform images (AWS Python/Node.js build images) are skipped - as they are already pushed during the build process. + With multi_platform, multi-platform images (see _should_use_multiplatform) + are skipped, as the multi-platform build already pushed them. Otherwise, + the locally built image is pushed. Args: system: Deployment platform image_type: Type of image language: Programming language, optional version: Language version, optional + multi_platform: If the images were built for both x64 and arm64 **kwargs: Additional arguments (ignored for push) Returns: True if push succeeded, False otherwise """ # Skip multi-platform images - they're already pushed during build - if self._should_use_multiplatform(system, image_type, language): + if multi_platform and self._should_use_multiplatform(system, image_type, language): image_name = self.config.docker_image_name(system, image_type, language, version) self.logging.info( f"Skipping push for multi-platform image (pushed during build): {image_name}" @@ -378,7 +437,7 @@ def _execute_push( try: # Parse image name into repository and tag # Format: repository:tag - repository, tag = image_name.split(":", 1) + repository, tag = image_name.rsplit(":", 1) DockerImageBuilder.push_image_with_progress( self.docker_client, repository, tag, self.logging, disable_rich_output=False @@ -430,7 +489,7 @@ def _process_image( # Execute the appropriate operation if operation == "build": - return self._execute_build( + success = self._execute_build( system, image_type, language, @@ -441,10 +500,16 @@ def _process_image( parallel, ) elif operation == "push": - return self._execute_push(system, image_type, language, version) + success = self._execute_push(system, image_type, language, version, multi_platform) else: raise ValueError(f"Unknown operation: {operation}") + if not success: + self._failed.append( + self.config.docker_image_name(system, image_type, language, version) + ) + return success + def _process_language( self, operation: str, @@ -678,6 +743,7 @@ def _process( parallel: Number of parallel workers, default 1 """ systems_config = self.config._system_config + self._failed = [] if deployment: if deployment in systems_config: @@ -696,6 +762,7 @@ def _process( ) else: self.logging.error(f"Unknown deployment: {deployment}") + self._failed.append(deployment) else: for system, system_dict in systems_config.items(): self._process_system( @@ -723,7 +790,7 @@ def build( platform: Optional[str] = None, multi_platform: bool = False, parallel: int = 1, - ) -> None: + ) -> List[str]: """ Build Docker images for SeBS infrastructure. @@ -743,6 +810,9 @@ def build( platform: Docker platform override, optional multi_platform: If we should build both x64 and arm64 parallel: Number of parallel workers, default 1 + + Returns: + Names of the images that failed to build (empty if all succeeded) """ self._process( operation="build", @@ -756,6 +826,7 @@ def build( multi_platform=multi_platform, parallel=parallel, ) + return list(self._failed) def push( self, @@ -765,7 +836,8 @@ def push( language_version: Optional[str] = None, architecture: str = "x64", dependency_type: Optional[str] = None, - ) -> None: + multi_platform: bool = False, + ) -> List[str]: """ Push Docker images to registry. @@ -782,6 +854,11 @@ def push( language_version: Specific version, pushes all if None architecture: Target architecture, default "x64" dependency_type: Specific dependency for cpp, optional + multi_platform: If the images were built for both x64 and arm64; + skips the images that the multi-platform build already pushed + + Returns: + Names of the images that failed to push (empty if all succeeded) """ self._process( operation="push", @@ -791,7 +868,9 @@ def push( language_version=language_version, architecture=architecture, dependency_type=dependency_type, + multi_platform=multi_platform, ) + return list(self._failed) @staticmethod def show_progress(txt: str, progress: Progress, layer_tasks: Dict[str, TaskID]): diff --git a/sebs/faas/container.py b/sebs/faas/container.py index c178ac3cd..6d28bd5ca 100644 --- a/sebs/faas/container.py +++ b/sebs/faas/container.py @@ -304,8 +304,9 @@ def build_base_image( } try: + # Unlike the Docker CLI, docker-py keeps intermediate containers by default. image, _ = self.docker_client.images.build( - tag=image_uri, path=build_dir, buildargs=buildargs + tag=image_uri, path=build_dir, buildargs=buildargs, rm=True, forcerm=True ) except docker.errors.BuildError as e: self.logging.error("Docker build failed!") diff --git a/sebs/local/local.py b/sebs/local/local.py index b93adc9fa..1561c1ed4 100644 --- a/sebs/local/local.py +++ b/sebs/local/local.py @@ -31,7 +31,7 @@ from sebs.config import SeBSConfig from sebs.experiments.config import SystemVariant from sebs.storage.resources import SelfHostedSystemResources -from sebs.utils import LoggingHandlers, is_linux +from sebs.utils import LoggingHandlers, docker_architecture, host_architecture, is_linux from sebs.local.config import LocalConfig from sebs.local.function import LocalFunction from sebs.faas.function import Function, FunctionConfig, ExecutionResult, Trigger @@ -53,6 +53,8 @@ class Local(System): """ DEFAULT_PORT = 9000 + # Seconds to wait for the function server to start + STARTUP_TIMEOUT = 30 @staticmethod def name() -> str: @@ -202,7 +204,8 @@ def package_code( directory: Directory containing the function code language: Programming language (e.g., "python", "nodejs") language_version: Language version (e.g., "3.11", "20") - architecture: Target architecture (unused for local) + architecture: Target architecture; must match the host's, since local + containers run natively (a mismatch is reported as a warning) benchmark: Benchmark name is_cached: Whether the package is from cache @@ -210,6 +213,22 @@ def package_code( Tuple[str, int]: (package_path, size_bytes) """ + # Function containers run on the Docker daemon's architecture, which can differ + # from this process', e.g., for x86 Python under Rosetta on Apple Silicon. + docker_arch = docker_architecture(self._docker_client) + python_arch = host_architecture() + running_on = f"Running on platform {docker_arch}" + if python_arch != docker_arch: + running_on += f", emulated as {python_arch}" + if architecture != docker_arch: + self.logging.warning( + f"{running_on}. Packaging for {architecture}, but local functions run on " + f"{docker_arch}: set the experiment's architecture to {docker_arch}, " + "or dependencies with native code may not load." + ) + elif python_arch != docker_arch: + self.logging.info(f"{running_on}.") + CONFIG_FILES = { "python": ["handler.py", "requirements.txt", ".python_packages"], "nodejs": ["handler.js", "package.json", "node_modules"], @@ -395,8 +414,8 @@ def _start_container( func.set_container(container, port) func._measurement_pid = pid - # Wait until server starts - max_attempts = 10 + # Wait until server starts; emulated containers (e.g., x64 on arm64) start slower. + max_attempts = int(Local.STARTUP_TIMEOUT / 0.25) attempts = 0 while attempts < max_attempts: try: diff --git a/sebs/regression.py b/sebs/regression.py index 9aabf7e90..5c464d377 100644 --- a/sebs/regression.py +++ b/sebs/regression.py @@ -11,6 +11,7 @@ - Azure Functions - Google Cloud Functions - OpenWhisk +- Local Docker deployments - Multiple runtime languages (Python, Node.js) - Multiple architectures (x64, arm64) - Different deployment types (package, container) @@ -87,6 +88,11 @@ architectures_openwhisk = ["x64"] deployments_openwhisk = ["container"] +# Local-specific configurations; functions run on the Docker daemon's architecture, +# so CI selects one architecture per runner with --selected-architecture. +architectures_local = ["x64", "arm64"] +deployments_local = ["package"] + # User-defined config passed during initialization, set in regression_suite() cloud_config: Optional[dict] = None @@ -1191,6 +1197,86 @@ def get_deployment(self, benchmark_name, architecture, deployment_type): return deployment_client +class LocalTestSequence: + """Shared deployment setup for benchmarks running in local Docker containers.""" + + def get_deployment(self, benchmark_name, architecture, deployment_type): + """Get a local deployment client for the specified configuration. + + Args: + benchmark_name: Name of the benchmark to deploy + architecture: Architecture to deploy on; must match the Docker daemon's + deployment_type: Deployment type (package) + + Returns: + An initialized local deployment client + + Raises: + AssertionError: If cloud_config is not set + """ + deployment_name = "local" + assert cloud_config, "Cloud configuration is required" + + # Create a copy of the config and set architecture and deployment type + config_copy = copy.deepcopy(cloud_config) + config_copy["experiments"]["architecture"] = architecture + config_copy["experiments"]["system_variant"] = deployment_type + + # Create log file name based on test parameters + f = f"regression_{deployment_name}_{benchmark_name}_{architecture}_{deployment_type}.log" + deployment_client = self.client.get_deployment( # type: ignore[attr-defined] + config_copy, + logging_filename=os.path.join(self.client.output_dir, f), # type: ignore + ) + + # Synchronize resource initialization with a lock + with type(self).lock: # type: ignore[attr-defined] + deployment_client.initialize(resource_prefix=RESOURCE_PREFIX, quiet=LOGGING_REDACTED) + return deployment_client + + +class LocalTestSequencePython( + LocalTestSequence, + unittest.TestCase, + metaclass=TestSequenceMeta, + benchmarks=benchmarks_python, + architectures=architectures_local, + deployments=deployments_local, + deployment_name="local", + triggers=[Trigger.TriggerType.HTTP], +): + """Test suite for Python benchmarks in local Docker containers. + + Attributes: + benchmarks: List of Python benchmarks to test + architectures: List of local architectures to test (x64, arm64) + deployments: List of deployment types to test (package) + deployment_name: Platform name ("local") + triggers: List of trigger types to test (HTTP) + """ + + +class LocalTestSequenceNodejs( + LocalTestSequence, + unittest.TestCase, + metaclass=TestSequenceMeta, + benchmarks=benchmarks_nodejs, + architectures=architectures_local, + deployments=deployments_local, + deployment_name="local", + triggers=[Trigger.TriggerType.HTTP], +): + """Test suite for Node.js benchmarks in local Docker containers. + + Attributes: + benchmarks: List of Node.js benchmarks to test + architectures: List of local architectures to test (x64, arm64) + deployments: List of deployment types to test (package) + deployment_name: Platform name ("local") + triggers: List of trigger types to test (HTTP) + """ + + # Stream result handler for concurrent test execution # Based on https://stackoverflow.com/questions/22484805/ # a-simple-working-example-for-testtools-concurrentstreamtestsuite @@ -1300,8 +1386,9 @@ def filter_out_benchmarks( if (deployment_name == "aws" and language == "cpp" and deployment_type == "package"): return "411.image-recognition" not in benchmark - # Filter out image recognition on ARM architecture on AWS - if (deployment_name == "aws" and architecture == "arm64"): + # Filter out image recognition on ARM architecture on AWS and local: + # its requirements pin x86 PyTorch wheels + if (deployment_name in ["aws", "local"] and architecture == "arm64"): return "411.image-recognition" not in benchmark # Filter out image recognition on newer Python versions on GCP @@ -1420,6 +1507,13 @@ def regression_suite( unittest.defaultTestLoader.loadTestsFromTestCase(OpenWhiskTestSequenceJava) ) + # Add local tests if requested + if "local" in providers: + if language == "python": + suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(LocalTestSequencePython)) + elif language == "nodejs": + suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(LocalTestSequenceNodejs)) + # Prepare the list of tests to run tests: List[unittest.TestCase] = [] # mypy is confused here about the type diff --git a/sebs/utils.py b/sebs/utils.py index f5504324b..a3c75bd9a 100644 --- a/sebs/utils.py +++ b/sebs/utils.py @@ -17,6 +17,7 @@ import subprocess import uuid import click +import docker import datetime import ipaddress import platform @@ -701,6 +702,35 @@ def has_platform(name: str) -> bool: return False +def _sebs_architecture(machine: str) -> str: + """Translate a machine name ("x86_64", "aarch64", ...) to SeBS's naming. + + Returns "x64" or "arm64"; other architectures are returned unchanged. + """ + machine = machine.lower() + if machine in ("x86_64", "amd64"): + return "x64" + if machine in ("arm64", "aarch64"): + return "arm64" + return machine + + +def host_architecture() -> str: + """Architecture of this Python process in SeBS's naming, e.g., "x64" or "arm64". + + It can differ from the machine's, e.g., for x86 Python under Rosetta on Apple Silicon. + """ + return _sebs_architecture(platform.machine()) + + +def docker_architecture(docker_client: docker.client.DockerClient) -> str: + """Architecture of the Docker daemon in SeBS's naming, e.g., "x64" or "arm64". + + Containers run natively on this architecture. + """ + return _sebs_architecture(docker_client.info()["Architecture"]) + + def is_linux() -> bool: """ Check if the system is Linux and not Windows Subsystem for Linux.