You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by tq...@apache.org on 2026/10/14 21:10:47 UTC
(tvm) branch native-jenkins-groovy created (now 05e76fcb0d)
This is an automated email from the ASF dual-hosted git repository.
tqchen pushed a change to branch native-jenkins-groovy
in repository https://gitbox.apache.org/repos/asf/tvm.git
at 05e76fcb0d [REFACTOR][CI] Share native Jenkins pipelines and organize CI helpers
This branch includes the following new commits:
new 05e76fcb0d [REFACTOR][CI] Share native Jenkins pipelines and organize CI helpers
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(tvm) 01/01: [REFACTOR][CI] Share native Jenkins pipelines and organize CI helpers
Posted by tq...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
tqchen pushed a commit to branch native-jenkins-groovy
in repository https://gitbox.apache.org/repos/asf/tvm.git
commit 05e76fcb0db39e50a459f0a381db761678eb18c4
Author: Tianqi Chen <tq...@users.noreply.github.com>
AuthorDate: Wed Oct 14 21:10:26 2026 +0000
[REFACTOR][CI] Share native Jenkins pipelines and organize CI helpers
---
.github/actions/setup/action.yml | 6 +-
.github/workflows/nightly_docker_update.yml | 24 -
.github/workflows/publish_wheel.yml | 6 +-
.github/workflows/tvmbot.yml | 2 +-
ci/README.md | 15 +-
ci/{scripts => }/github/__init__.py | 0
ci/{scripts/jenkins => github}/git_utils.py | 0
ci/{scripts => }/github/github_tvmbot.py | 12 +-
ci/jenkins/README.md | 58 +-
ci/jenkins/data.py | 6 +-
ci/jenkins/generate.py | 226 -------
ci/jenkins/generated/arm_jenkinsfile.groovy | 518 ++-------------
.../Prepare.groovy.j2 => generated/common.groovy} | 233 +++++--
ci/jenkins/generated/cpu_jenkinsfile.groovy | 584 ++---------------
ci/jenkins/generated/docker_jenkinsfile.groovy | 686 +++-----------------
ci/jenkins/generated/gpu_jenkinsfile.groovy | 702 +++------------------
ci/jenkins/generated/wasm_jenkinsfile.groovy | 521 ++-------------
.../scripts}/determine_docker_images.py | 7 +-
.../scripts}/git_change_docker.sh | 0
.../jenkins => jenkins/scripts}/git_skip_ci.py | 51 +-
.../scripts}/git_skip_ci_globs.py | 2 +-
.../jenkins => jenkins/scripts}/http_utils.py | 0
ci/{scripts/jenkins => jenkins/scripts}/retry.sh | 0
ci/{scripts/jenkins => jenkins/scripts}/s3.py | 45 +-
.../scripts}/should_rebuild_docker.py | 19 +-
ci/jenkins/templates/arm_jenkinsfile.groovy.j2 | 35 -
ci/jenkins/templates/cpu_jenkinsfile.groovy.j2 | 52 --
ci/jenkins/templates/docker_jenkinsfile.groovy.j2 | 202 ------
ci/jenkins/templates/gpu_jenkinsfile.groovy.j2 | 144 -----
ci/jenkins/templates/utils/Build.groovy.j2 | 27 -
ci/jenkins/templates/utils/Test.groovy.j2 | 6 -
ci/jenkins/templates/utils/base.groovy.j2 | 111 ----
ci/jenkins/templates/utils/macros.j2 | 169 -----
ci/jenkins/templates/wasm_jenkinsfile.groovy.j2 | 39 --
ci/{scripts => }/package/README.md | 0
ci/{scripts => }/package/build-environment.yaml | 0
.../package/manylinux_build_libtvm_runtime_cuda.sh | 2 +-
.../package/windows_build_libtvm_runtime_cuda.bat | 4 +-
ci/scripts/jenkins/cmd_utils.py | 107 ----
ci/scripts/jenkins/git_change_docs.sh | 39 --
ci/scripts/jenkins/open_docker_update_pr.py | 214 -------
ci/scripts/jenkins/should_run_slow_tests.py | 85 ---
docker/bash.sh | 2 +-
docker/dev_common.sh | 2 +-
docs/contribute/ci.rst | 2 +-
docs/contribute/testing.rst | 2 +-
pyproject.toml | 2 +-
tests/python/ci/test_ci.py | 122 +---
tests/python/ci/test_jenkins_helpers.py | 134 ++++
tests/python/ci/test_tvmbot.py | 6 +-
tests/python/ci/test_utils.py | 4 +-
tests/scripts/release/gather_prs.py | 6 +-
tests/scripts/release/make_notes.py | 5 -
tests/scripts/setup-pytest-env.sh | 2 +-
tests/scripts/task_build.py | 43 +-
55 files changed, 815 insertions(+), 4476 deletions(-)
diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml
index 980e5d087f..2eea89fa79 100644
--- a/.github/actions/setup/action.yml
+++ b/.github/actions/setup/action.yml
@@ -9,14 +9,14 @@ runs:
CACHE_NUMBER: 2
with:
path: ~/conda_pkgs_dir
- key: ${{ runner.os }}-conda-${{ env.CACHE_NUMBER }}-${{ hashFiles('ci/scripts/package/build-environment.yaml') }}
+ key: ${{ runner.os }}-conda-${{ env.CACHE_NUMBER }}-${{ hashFiles('ci/package/build-environment.yaml') }}
- uses: conda-incubator/setup-miniconda@v4.0.1
continue-on-error: true
id: conda1
with:
activate-environment: tvm-build
channel-priority: strict
- environment-file: ci/scripts/package/build-environment.yaml
+ environment-file: ci/package/build-environment.yaml
auto-activate-base: false
miniforge-version: latest
python-version: "3.10"
@@ -27,7 +27,7 @@ runs:
with:
activate-environment: tvm-build
channel-priority: strict
- environment-file: ci/scripts/package/build-environment.yaml
+ environment-file: ci/package/build-environment.yaml
auto-activate-base: false
miniforge-version: latest
use-only-tar-bz2: true
diff --git a/.github/workflows/nightly_docker_update.yml b/.github/workflows/nightly_docker_update.yml
deleted file mode 100644
index 7b056342f5..0000000000
--- a/.github/workflows/nightly_docker_update.yml
+++ /dev/null
@@ -1,24 +0,0 @@
-
-name: Nightly Docker Update
-on:
- workflow_dispatch:
-
-concurrency:
- group: nightly-docker-update
- cancel-in-progress: true
-
-jobs:
- open_update_pr:
- permissions:
- contents: write
- pull-requests: write
- if: github.repository == 'apache/tvm'
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v6.0.2
- - name: Open PR to update Docker images
- env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- run: |
- set -eux
- python ci/scripts/jenkins/open_docker_update_pr.py
diff --git a/.github/workflows/publish_wheel.yml b/.github/workflows/publish_wheel.yml
index a2fedda9e0..7a56cb2732 100644
--- a/.github/workflows/publish_wheel.yml
+++ b/.github/workflows/publish_wheel.yml
@@ -60,19 +60,19 @@ jobs:
os: ubuntu-latest
container: quay.io/manylinux_cuda/manylinux_2_28_x86_64_cuda13_1:latest
arch: x86_64
- script: ci/scripts/package/manylinux_build_libtvm_runtime_cuda.sh
+ script: ci/package/manylinux_build_libtvm_runtime_cuda.sh
lib: build-wheel-cuda/lib/libtvm_runtime_cuda.so
- name: "CUDA runtime sidecar (Linux aarch64, manylinux_2_28)"
os: ubuntu-24.04-arm
container: quay.io/manylinux_cuda/manylinux_2_28_aarch64_cuda13_1:latest
arch: aarch64
- script: ci/scripts/package/manylinux_build_libtvm_runtime_cuda.sh
+ script: ci/package/manylinux_build_libtvm_runtime_cuda.sh
lib: build-wheel-cuda/lib/libtvm_runtime_cuda.so
- name: "CUDA runtime sidecar (Windows AMD64)"
os: windows-2022
container: ""
arch: AMD64
- script: ci/scripts/package/windows_build_libtvm_runtime_cuda.bat
+ script: ci/package/windows_build_libtvm_runtime_cuda.bat
lib: build-wheel-cuda/lib/tvm_runtime_cuda.dll
steps:
# The containerized Linux legs check out as root; mark the tree safe so git
diff --git a/.github/workflows/tvmbot.yml b/.github/workflows/tvmbot.yml
index aa6bbcaace..393b723696 100644
--- a/.github/workflows/tvmbot.yml
+++ b/.github/workflows/tvmbot.yml
@@ -28,4 +28,4 @@ jobs:
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -eux
- python ci/scripts/github/github_tvmbot.py --pr "$PR_NUMBER" --run-url "$RUN_URL" --trigger-comment-json "$ISSUE_COMMENT"
+ python ci/github/github_tvmbot.py --pr "$PR_NUMBER" --run-url "$RUN_URL" --trigger-comment-json "$ISSUE_COMMENT"
diff --git a/ci/README.md b/ci/README.md
index d66b289b4b..d4ac4ed5b4 100644
--- a/ci/README.md
+++ b/ci/README.md
@@ -26,8 +26,9 @@ TVM project in a healthy state and preventing breakages. CI in TVM is broken int
- The tests themselves, all of which live underneath [`tests`](../tests).
- Definitions of test suites, with each suite defined as a separate `task_` script in
[`tests/scripts`](../tests/scripts).
- - Scripts and automation [`ci/scripts`](../ci/scripts).
- - The linux test sequence (in [`Jenkinsfile`](../ci/jenkins/templates/)), which lints and builds TVM and runs test
+ - GitHub automation [`ci/github`](github), package builds [`ci/package`](package),
+ and Jenkins host commands [`ci/jenkins/scripts`](jenkins/scripts).
+ - The linux test sequence (in [`Jenkinsfile`](../ci/jenkins/generated/)), which lints and builds TVM and runs test
suites using Docker on Linux.
- The Windows and Mac test sequences (in [`.github/actions`](../.github/actions)).
- GitHub Actions that support the code review process (in [`.github/actions`](../.github/actions)).
@@ -64,7 +65,7 @@ Each CI job runs most of its work inside a Docker container, built from files
in the [`docker/`](../docker) folder. These
files are built nightly in Jenkins via the [tvm-docker](https://ci.tlcpack.ai/job/tvm-docker/) job.
The images for these containers are hosted in the [tlcpack Docker Hub](https://hub.docker.com/u/tlcpack)
-and referenced in the [`jenkins/templates`](/ci/jenkins/templates/). These can be inspected and run
+and referenced in the [`jenkins/generated`](/ci/jenkins/generated/). These can be inspected and run
locally via standard Docker commands.
### `ci-docker-staging`
@@ -84,11 +85,11 @@ and ask them to push your PR as a branch to test the changes.
TVM uses Jenkins for running Linux continuous integration (CI) tests on
[branches](https://ci.tlcpack.ai/job/tvm/) and
[pull requests](https://ci.tlcpack.ai/job/tvm/view/change-requests/) through a
-build configuration specified in a [`Jenkinsfile`](/ci/jenkins/templates/).
+build configuration specified in a [`Jenkinsfile`](/ci/jenkins/generated/).
Other jobs run in GitHub Actions for Windows and MacOS jobs.
## `Jenkinsfile`
-The template files in this directory are used to generate the [`Jenkinsfile`](/ci/jenkins/templates/) used by Jenkins to run CI jobs for each commit to PRs and branches.
-
-To regenerate the `Jenkinsfile`, run `make` in the `ci/jenkins` dir.
+The native Groovy entry points in `ci/jenkins/generated/` load shared helpers
+from `common.groovy`. Edit these sources directly; no generation step is needed.
+See [Jenkins pipeline documentation](jenkins/README.md) for trust and rollout checks.
diff --git a/ci/scripts/github/__init__.py b/ci/github/__init__.py
similarity index 100%
rename from ci/scripts/github/__init__.py
rename to ci/github/__init__.py
diff --git a/ci/scripts/jenkins/git_utils.py b/ci/github/git_utils.py
similarity index 100%
rename from ci/scripts/jenkins/git_utils.py
rename to ci/github/git_utils.py
diff --git a/ci/scripts/github/github_tvmbot.py b/ci/github/github_tvmbot.py
similarity index 98%
rename from ci/scripts/github/github_tvmbot.py
rename to ci/github/github_tvmbot.py
index 6975bc9d35..a46e0074f1 100755
--- a/ci/scripts/github/github_tvmbot.py
+++ b/ci/github/github_tvmbot.py
@@ -15,25 +15,19 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-# ruff: noqa: E402, E501, F841, RUF012
+# ruff: noqa: E501, F841, RUF012
import argparse
import json
import logging
import os
import re
-import sys
import traceback
import warnings
from collections.abc import Callable
from pathlib import Path
from typing import Any
-# Hackery to enable importing of utils from ci/scripts/jenkins
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-sys.path.append(str(REPO_ROOT / "ci" / "scripts" / "jenkins"))
-
-from cmd_utils import init_log
from git_utils import GitHubRepo, git, parse_remote, post
Review = dict[str, Any]
@@ -729,7 +723,9 @@ if __name__ == "__main__":
help="run but don't send any request to GitHub",
)
args = parser.parse_args()
- init_log()
+ logging.basicConfig(
+ format="[%(filename)s:%(lineno)d %(levelname)s] %(message)s", level=logging.INFO
+ )
comment = json.loads(args.trigger_comment_json)
body = comment["body"].strip()
diff --git a/ci/jenkins/README.md b/ci/jenkins/README.md
index dd6b652bee..a7bb6c7a5a 100644
--- a/ci/jenkins/README.md
+++ b/ci/jenkins/README.md
@@ -35,21 +35,53 @@ https://github.com/apache/tvm/actions has the logs for each of these workflows.
TVM uses Jenkins for running Linux continuous integration (CI) tests on
[branches](https://ci.tlcpack.ai/job/tvm/) and
[pull requests](https://ci.tlcpack.ai/job/tvm/view/change-requests/) through a
-build configuration specified in a [`Jenkinsfile`](/ci/jenkins/templates/).
+build configuration specified in a [`Jenkinsfile`](generated/).
Other jobs run in GitHub Actions for Windows and MacOS jobs.
-## `Jenkinsfile`
-
-The template files in this directory are used to generate the [`Jenkinsfile`](/ci/jenkins/templates/) used by Jenkins to run CI jobs for each commit to PRs and branches.
-
-To regenerate the `Jenkinsfile`, run
-
-```bash
-python3 -mvenv _venv
-_venv/bin/pip3 install -r ci/jenkins/requirements.txt
-_venv/bin/python3 ci/jenkins/generate.py
-```
+## Pipeline entry points
+
+The five `generated/*_jenkinsfile.groovy` paths remain Jenkins job entry points.
+Despite the historical directory name, these are native Groovy sources: edit
+and review them directly. `generated/common.groovy` shares preparation, checkout,
+Docker setup, artifacts and spot fallback policy. Platform commands and deployment
+stay visible in their respective job files. Image tags remain in
+`docker-images.ini`; artifact bundles remain in `data.py`.
+
+Host-side commands live in `scripts/`. GitHub bot and release API helpers live
+in `../github/`. The retained `determine_docker_images.py` supports both
+Jenkins image selection and local `--lookup-only` lookup; `should_rebuild_docker.py`
+and the standalone skip commands retain their command-line interfaces.
+
+### Trust and rollout
+
+Each entry point first uses `readTrusted` to read the helper at Jenkins' pinned
+SCM revision. When an untrusted PR modifies that file, Jenkins refuses the read.
+The entry point then checks out a fresh bootstrap workspace and reads the helper
+from the fetched **PR target branch** in the canonical Apache repository. It pins
+that exact target commit for all subsequent source merges, including release
+branch targets. It never evaluates workspace helper code or substitutes `main`.
+The bootstrap runs only built-in checkout/Git commands, without repository scripts
+or credentials. Missing target files and evaluation errors fail the build.
+
+This fallback adds a bootstrap node allocation for a refused helper read; it has
+the same spot-to-on-demand Exception fallback as preparation. Cancellation still
+runs once before preparation. Trusted helper changes use Jenkins' selected
+revision directly. Host scripts and artifact metadata follow the pinned target
+revision for PR authors outside `CONTRIBUTORS.md`.
+
+Before enabling the migration on production jobs, validate it with the existing
+Jenkins plugin versions and sandbox settings on a trusted branch: run all five
+entry points, suspend/resume across a node step, and exercise spot loss, a normal
+build-command failure, superseded builds, and a failed on-demand retry. Check
+trusted and untrusted PRs both with and without a common-helper change, and a
+release-target PR. Verify image overrides and disabled deployment gates before
+checking enabled docs/Docker deployment in the normal trusted deployment context.
+Local mocked execution checks pipeline control flow but cannot certify Jenkins
+CPS serialization, sandbox approvals, SCM trust configuration, or real agent loss.
+No job path or controller reconfiguration is part of this migration.
# Infrastructure
-While all TVM tests are contained within the apache/tvm repository, the infrastructure used to run the tests is donated by the TVM Community. To encourage collaboration, the configuration for TVM's CI infrastructure is stored in a public GitHub repository. TVM community members are encouraged to contribute improvements. The configuration, along with documentation of TVM's CI infrastructure, is in the [tlc-pack/ci](https://github.com/tlc-pack/ci) repo.
+The community's infrastructure configuration and documentation live in
+[tlc-pack/ci](https://github.com/tlc-pack/ci). Coordinate external callers when
+changing any retained script interface.
diff --git a/ci/jenkins/data.py b/ci/jenkins/data.py
index 0811451b53..fd75107e7d 100644
--- a/ci/jenkins/data.py
+++ b/ci/jenkins/data.py
@@ -18,9 +18,9 @@
"""Bundle registry for CI artifact stashing.
Single source of truth for the file lists uploaded to / downloaded from S3 by
-``ci/scripts/jenkins/s3.py``. This module deliberately carries nothing else —
-docker image tags live in ``ci/jenkins/docker-images.ini`` and Jinja-template
-metadata (image platforms, AWS endpoints) lives in ``ci/jenkins/generate.py``.
+``ci/jenkins/scripts/s3.py``. This module deliberately carries nothing else —
+docker image tags live in ``ci/jenkins/docker-images.ini`` and pipeline
+configuration lives in ``ci/jenkins/generated/common.groovy``.
CLI: ``python3 ci/jenkins/data.py <bundle> [<bundle> ...]`` resolves bundle
names to their file paths (one per line; exit 1 on unknown name). Used by
diff --git a/ci/jenkins/generate.py b/ci/jenkins/generate.py
deleted file mode 100644
index 6a860f3f34..0000000000
--- a/ci/jenkins/generate.py
+++ /dev/null
@@ -1,226 +0,0 @@
-#!/usr/bin/env python3
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-import argparse
-import configparser
-import datetime
-import difflib
-import re
-import textwrap
-from dataclasses import dataclass
-from pathlib import Path
-
-import jinja2
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent
-JENKINS_DIR = REPO_ROOT / "ci" / "jenkins"
-TEMPLATES_DIR = JENKINS_DIR / "templates"
-GENERATED_DIR = JENKINS_DIR / "generated"
-DOCKER_IMAGES_INI = JENKINS_DIR / "docker-images.ini"
-
-# Platform mapping for the CI image registry. The ini section names are the
-# image names; this dict pins their Jenkins agent label. Keep in sync with
-# the [jenkins] section of docker-images.ini when adding/removing images.
-_IMAGE_PLATFORMS = {
- "ci_arm": "ARM",
- "ci_cpu": "CPU",
- "ci_gpu": "GPU",
- "ci_wasm": "CPU",
-}
-
-
-def _build_render_context() -> dict:
- """Build the Jinja render context: image metadata + AWS endpoints."""
- config = configparser.ConfigParser()
- config.read(DOCKER_IMAGES_INI)
- images = [
- {"name": name, "platform": platform}
- for name, platform in _IMAGE_PLATFORMS.items()
- if config.has_option("jenkins", name)
- ]
- aws_default_region = "us-west-2"
- return {
- "images": images,
- "aws_default_region": aws_default_region,
- "aws_ecr_url": f"dkr.ecr.{aws_default_region}.amazonaws.com",
- }
-
-
-data = _build_render_context()
-
-
-class Change:
- IMAGES_ONLY = object()
- NONE = object()
- FULL = object()
-
-
-@dataclass
-class ChangeData:
- diff: str | None
- content: str
- destination: Path
- source: Path
-
-
-def lines_without_generated_tag(content):
- return [
- line for line in content.splitlines(keepends=True) if not line.startswith("// Generated at")
- ]
-
-
-def change_type(lines: list[str]) -> Change:
- """
- Return True if 'line' only edits an image tag or if 'line' is not a changed
- line in a diff
- """
- added_images = []
- removed_images = []
- diff_lines = []
-
- for line in lines[2:]:
- if not line.startswith("-") and not line.startswith("+"):
- # not a diff line, ignore it
- continue
-
- diff_lines.append(line)
-
- if len(diff_lines) == 0:
- # no changes made
- return Change.NONE
-
- for line in diff_lines:
- is_add = line.startswith("+")
- line = line.strip().lstrip("+").lstrip("-")
- match = re.search(
- r"^(ci_[a-zA-Z0-9]+) = \'.*\'$",
- line.strip().lstrip("+").lstrip("-"),
- flags=re.MULTILINE,
- )
- if match is None:
- # matched a non-image line, quit early
- return Change.FULL
-
- if is_add:
- added_images.append(match.groups()[0])
- else:
- removed_images.append(match.groups()[0])
-
- # make sure that the added image lines match the removed image lines
- if len(added_images) > 0 and added_images == removed_images:
- return Change.IMAGES_ONLY
- else:
- return Change.FULL
-
-
-def update_jenkinsfile(source: Path) -> ChangeData:
- destination = GENERATED_DIR / source.stem
-
- data["generated_time"] = datetime.datetime.now().isoformat()
- if destination.exists():
- with open(destination) as f:
- old_generated_content = f.read()
-
- timestamp_match = re.search(
- r"^// Generated at (.*)$", old_generated_content, flags=re.MULTILINE
- )
- if not timestamp_match:
- raise RuntimeError(
- f"Could not find timestamp in Jenkinsfile: {destination.relative_to(TEMPLATES_DIR)}"
- )
- original_timestamp = timestamp_match.groups()[0]
-
- environment = jinja2.Environment(
- loader=jinja2.FileSystemLoader(TEMPLATES_DIR),
- undefined=jinja2.StrictUndefined,
- lstrip_blocks=True,
- trim_blocks=True,
- keep_trailing_newline=True,
- )
- template = environment.get_template(str(source.relative_to(TEMPLATES_DIR)))
- new_content = template.render(**data)
-
- if not destination.exists():
- # New file, create it from scratch
- return ChangeData(
- diff=new_content, content=new_content, source=source, destination=destination
- )
-
- diff = [
- line
- for line in difflib.unified_diff(
- lines_without_generated_tag(old_generated_content),
- lines_without_generated_tag(new_content),
- )
- ]
- change = change_type(diff)
- if (not args.force and change == Change.IMAGES_ONLY) or change == Change.NONE:
- if change != Change.NONE:
- print("Detected only Docker-image name changes, skipping timestamp update")
- new_content = new_content.replace(data["generated_time"], original_timestamp)
-
- diff = "".join(diff)
-
- return ChangeData(diff=diff, content=new_content, source=source, destination=destination)
-
-
-if __name__ == "__main__":
- help = "Regenerate Jenkinsfile from template"
- parser = argparse.ArgumentParser(description=help)
- parser.add_argument("--force", action="store_true", help="always overwrite timestamp")
- parser.add_argument("--check", action="store_true", help="just verify the output didn't change")
- args = parser.parse_args()
-
- sources = TEMPLATES_DIR.glob("*_jenkinsfile.groovy.j2")
- changes = [update_jenkinsfile(source) for source in sources if source.name != "base.groovy.j2"]
-
- if args.check:
- if all(not data.diff for data in changes):
- print("Success, the newly generated Jenkinsfiles matched the ones on disk")
- exit(0)
- else:
- print(
- textwrap.dedent(
- """
- Newly generated Jenkinsfiles did not match the ones on disk! If you have made
- edits to the Jenkinsfiles in generated/, move them to the corresponding source and
- regenerate the Jenkinsfiles from the templates with
-
- python3 -m pip install -r jenkins/requirements.txt
- python3 jenkins/generate.py
-
- Diffed changes:
- """
- ).strip()
- )
- for data in changes:
- if data.diff:
- source = data.source.relative_to(REPO_ROOT)
- print(source)
- print(data.diff)
-
- exit(1)
- else:
- for data in changes:
- with open(data.destination, "w") as f:
- f.write(data.content)
-
- if not data.diff:
- print(f"Wrote output to {data.destination.relative_to(REPO_ROOT)}, no changes made")
- else:
- print(f"Wrote output to {data.destination.relative_to(REPO_ROOT)}, changes:")
- print(data.diff)
diff --git a/ci/jenkins/generated/arm_jenkinsfile.groovy b/ci/jenkins/generated/arm_jenkinsfile.groovy
index 3442caded7..e70ce07525 100644
--- a/ci/jenkins/generated/arm_jenkinsfile.groovy
+++ b/ci/jenkins/generated/arm_jenkinsfile.groovy
@@ -14,489 +14,53 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-// -*- mode: groovy -*-
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-
-// Jenkins pipeline
-// See documents at https://jenkins.io/doc/book/pipeline/jenkinsfile/
-
-// Docker env used for testing
-// Different image may have different version tag
-// because some of them are more stable than anoter.
-//
-// Docker images are maintained by PMC, cached in dockerhub
-// and remains relatively stable over the time.
-// Flow for upgrading docker env(need commiter)
-//
-// - Send PR to upgrade build script in the repo
-// - Build the new docker image
-// - Tag the docker image with a new version and push to a binary cache.
-// - Update the version in the Jenkinsfile, send a PR
-// - Fix any issues wrt to the new image version in the PR
-// - Merge the PR and now we are in new version
-// - Tag the new version as the lates
-// - Periodically cleanup the old versions on local workers
-//
-
-// ============================= IMPORTANT NOTE =============================
-// This file is generated by 'jenkins/generate.py'. Do not edit this file directly!
-// Make edits to 'jenkins/Jenkinsfile.j2' and regenerate this with
-// 'python3 jenkins/generate.py'
-// Note: This timestamp is here to ensure that updates to the Jenkinsfile are
-// always rebased on main before merging:
-// Generated at 2026-07-05T01:05:57.719405
-
-import org.jenkinsci.plugins.pipeline.modeldefinition.Utils
-// These are set at runtime from data in ci/jenkins/docker-images.yml, update
-// image tags in that file
-ci_gpu = ''
-ci_cpu = ''
-ci_minimal = ''
-ci_wasm = ''
-ci_cortexm = ''
-ci_arm = ''
-ci_riscv = ''
-
-// Parameters to allow overriding (in Jenkins UI), the images
-// to be used by a given build. When provided, they take precedence
-// over default values above.
-properties([
- parameters([
- string(name: 'ci_arm_param', defaultValue: ''),
- string(name: 'ci_cpu_param', defaultValue: ''),
- string(name: 'ci_gpu_param', defaultValue: ''),
- string(name: 'ci_wasm_param', defaultValue: ''),
- ])
-])
-
-// Placeholders for newly built Docker image names (if rebuild_docker_images
-// is used)
- built_ci_arm = null;
- built_ci_cpu = null;
- built_ci_gpu = null;
- built_ci_wasm = null;
-
-// Global variable assigned during Sanity Check that holds the sha1 which should be
-// merged into the PR in all branches.
-upstream_revision = null
-
-// command to start a docker container
-docker_run = 'docker/bash.sh --env CI --env PLATFORM --env SKIP_SLOW_TESTS --env TEST_STEP_NAME'
-docker_build = 'docker/build.sh'
-// timeout in minutes
-max_time = 180
-rebuild_docker_images = false
-
-s3_bucket = 'tvm-jenkins-artifacts-prod'
-s3_prefix = "tvm/${env.BRANCH_NAME}/${env.BUILD_NUMBER}"
-
-// Jenkins script root directory
-jenkins_scripts_root = "ci/scripts/jenkins"
-
-
-// General note: Jenkins has limits on the size of a method (or top level code)
-// that are pretty strict, so most usage of groovy methods in these templates
-// are purely to satisfy the JVM
-def per_exec_ws(folder) {
- return "workspace/exec_${env.EXECUTOR_NUMBER}/" + folder
-}
-
-// initialize source codes
-def init_git() {
- retry(5) {
- checkout scm
- }
-
- // Add more info about job node
- sh (
- script: './tests/scripts/task_show_node_info.sh',
- label: 'Show executor node info',
- )
-
- // Determine merge commit to use for all stages
- if (env.CHANGE_TARGET) {
- // This is a PR build, so merge with the latest of the PR's target branch
- // (e.g. main or a release branch like v0.25.0).
- merge_with_target()
- } else {
- // This is a branch build (main or a release branch). Only set
- // upstream_revision to HEAD and skip merging to avoid a race with another
- // commit merged to the branch.
- update_upstream_revision("HEAD")
- }
-
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- retry 3 timeout 5m git submodule update --init --recursive -f --jobs 0
- """,
- label: 'Update git submodules',
- )
- checkout_trusted_files()
-}
-
-def update_upstream_revision(git_ref) {
- if (upstream_revision == null) {
- upstream_revision = sh(
- script: "git log -1 ${git_ref} --format=\'%H\'",
- label: 'Determine upstream revision',
- returnStdout: true,
- ).trim()
- }
-}
-
-def merge_with_target() {
- def target = env.CHANGE_TARGET
- sh (
- script: "git fetch origin ${target}",
- label: "Fetch target branch ${target}",
- )
- update_upstream_revision("FETCH_HEAD")
- sh (
- script: "git -c user.name=TVM-Jenkins -c user.email=jenkins@tvm.apache.org merge ${upstream_revision}",
- label: "Merge to origin/${target}"
- )
-}
-
-def docker_init(image) {
- // Clear out all Docker images that aren't going to be used
- sh(
- script: """
- set -eux
- docker image ls --all
- IMAGES=\$(docker image ls --all --format '{{.Repository}}:{{.Tag}} {{.ID}}')
-
- echo -e "Found images:\\n\$IMAGES"
- echo "\$IMAGES" | { grep -vE '${image}' || test \$? = 1; } | { xargs docker rmi || test \$? = 123; }
-
- docker image ls --all
- """,
- label: 'Clean old Docker images',
- )
-
- if (image.contains("amazonaws.com")) {
- // If this string is in the image name it's from ECR and needs to be pulled
- // with the right credentials
- ecr_pull(image)
- } else {
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- retry 5 docker pull ${image}
- """,
- label: 'Pull docker image',
- )
- }
-}
-
-def ecr_pull(full_name) {
- aws_account_id = sh(
- returnStdout: true,
- script: 'aws sts get-caller-identity | grep Account | cut -f4 -d\\"',
- label: 'Get AWS ID'
- ).trim()
-
- try {
- withEnv([
- "AWS_ACCOUNT_ID=${aws_account_id}",
- 'AWS_DEFAULT_REGION=us-west-2',
- "AWS_ECR_REPO=${aws_account_id}.dkr.ecr.us-west-2.amazonaws.com"]) {
- sh(
- script: '''
- set -eux
- aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ECR_REPO
- ''',
- label: 'Log in to ECR'
- )
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- retry 5 docker pull ${full_name}
- """,
- label: 'Pull image from ECR'
- )
- }
- } finally {
- withEnv([
- "AWS_ACCOUNT_ID=${aws_account_id}",
- 'AWS_DEFAULT_REGION=us-west-2',
- "AWS_ECR_REPO=${aws_account_id}.dkr.ecr.us-west-2.amazonaws.com"]) {
- sh(
- script: 'docker logout $AWS_ECR_REPO',
- label: 'Clean up login credentials'
- )
+// readTrusted pins trusted revisions, but rejects helper edits in untrusted PRs.
+// In that case use the PR target, pinning the same commit for all source merges.
+def helper
+String target_revision = null
+try {
+ helper = readTrusted('ci/jenkins/generated/common.groovy')
+} catch (hudson.AbortException | java.io.FileNotFoundException ex) {
+ if (!env.CHANGE_TARGET) throw ex
+ echo 'Loading shared pipeline from the pinned PR target: ' + ex.toString()
+ def from_target = { label ->
+ node(label) {
+ ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/pipeline") {
+ // No PR-owned executable or credentials run during this bootstrap.
+ deleteDir()
+ retry(5) { checkout scm }
+ // Quote the branch as data and fetch only from the canonical repository.
+ def target = env.CHANGE_TARGET.replace("'", "'\"'\"'")
+ sh(script: "git fetch https://github.com/apache/tvm.git 'refs/heads/${target}'",
+ label: 'Fetch trusted pipeline target')
+ def revision = sh(script: 'git rev-parse FETCH_HEAD', returnStdout: true).trim()
+ def source = sh(script: "git show ${revision}:ci/jenkins/generated/common.groovy",
+ returnStdout: true)
+ return [revision, source]
+ }
}
}
-}
-
-def should_skip_slow_tests(pr_number) {
- withCredentials([string(
- credentialsId: 'tvm-bot-jenkins-reader',
- variable: 'GITHUB_TOKEN',
- )]) {
- // Exit code of 1 means run slow tests, exit code of 0 means skip slow tests
- result = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/should_run_slow_tests.py --pr '${pr_number}'",
- label: 'Check if CI should run slow tests',
- )
- }
- return result == 0
-}
-
-def cancel_previous_build() {
- // cancel previous build if it is not on main.
- if (env.BRANCH_NAME != 'main') {
- def buildNumber = env.BUILD_NUMBER as int
- // Milestone API allows us to cancel previous build
- // with the same milestone number
- if (buildNumber > 1) milestone(buildNumber - 1)
- milestone(buildNumber)
- }
-}
-
-def is_last_build() {
- // check whether it is last build
+ def pinned
try {
- return currentBuild.number == currentBuild.rawBuild.project.getLastBuild().number
- } catch (Throwable ex) {
- echo 'Error during check is_last_build ' + ex.toString()
- return false
+ pinned = from_target('CPU-SMALL-SPOT')
+ } catch (Exception failure) {
+ pinned = from_target('CPU-SMALL')
}
+ target_revision = pinned[0]
+ helper = pinned[1]
}
+// Evaluation is outside the read/fetch fallback: script errors must propagate.
+ci = evaluate(helper)
+if (target_revision != null) ci.upstream_revision = target_revision
+ci.start()
-def checkout_trusted_files() {
- // trust everything from branch builds
- if (env.BRANCH_NAME == null || !env.BRANCH_NAME.startsWith('PR-')) {
- return;
- }
-
- // trust peoople listed in CONTRIBUTING.md
- grep_code = sh(
- returnStatus: true,
- script: "git show '${upstream_revision}:CONTRIBUTORS.md' | grep '@${env.CHANGE_AUTHOR}'",
- label: 'Check if change is from a contributor',
- )
-
- if (grep_code == 1) {
- // Any scripts that run on the bare host and not inside a Docker container
- // (especially those that access secrets) should be checked out here so
- // only trusted versions are used in CI
- sh(
- script: "git checkout ${upstream_revision} ${jenkins_scripts_root}/.",
- label: 'Check out trusted files',
- )
- }
-}
-
-def should_skip_ci(pr_number) {
- if (env.BRANCH_NAME == null || !env.BRANCH_NAME.startsWith('PR-')) {
- // never skip CI on build sourced from a branch
- return false
- }
- glob_skip_ci_code = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_skip_ci_globs.py",
- label: 'Check if CI should be skipped due to changed files',
- )
- if (glob_skip_ci_code == 0) {
- return true
- }
- withCredentials([string(
- credentialsId: 'tvm-bot-jenkins-reader',
- variable: 'GITHUB_TOKEN',
- )]) {
- // Exit code of 1 means run full CI (or the script had an error, so run
- // full CI just in case). Exit code of 0 means skip CI.
- git_skip_ci_code = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_skip_ci.py --pr '${pr_number}'",
- label: 'Check if CI should be skipped',
- )
- }
- return git_skip_ci_code == 0
-}
-
-def prepare(node_type) {
- stage('Prepare') {
- node(node_type) {
- ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/prepare") {
- init_git()
-
- if (env.DETERMINE_DOCKER_IMAGES == 'yes') {
- sh(
- script: "./${jenkins_scripts_root}/determine_docker_images.py ci_arm ci_cpu ci_gpu ci_wasm ",
- label: 'Decide whether to use tlcpack or tlcpackstaging for Docker images',
- )
- // Pull image names from the results of should_rebuild_docker.py
- ci_arm = sh(
- script: "cat .docker-image-names/ci_arm",
- label: "Find docker image name for ci_arm",
- returnStdout: true,
- ).trim()
- ci_cpu = sh(
- script: "cat .docker-image-names/ci_cpu",
- label: "Find docker image name for ci_cpu",
- returnStdout: true,
- ).trim()
- ci_gpu = sh(
- script: "cat .docker-image-names/ci_gpu",
- label: "Find docker image name for ci_gpu",
- returnStdout: true,
- ).trim()
- ci_wasm = sh(
- script: "cat .docker-image-names/ci_wasm",
- label: "Find docker image name for ci_wasm",
- returnStdout: true,
- ).trim()
- }
-
- ci_arm = params.ci_arm_param ?: ci_arm
- ci_cpu = params.ci_cpu_param ?: ci_cpu
- ci_gpu = params.ci_gpu_param ?: ci_gpu
- ci_wasm = params.ci_wasm_param ?: ci_wasm
-
- sh (script: """
- echo "Docker images being used in this build:"
- echo " ci_arm = ${ci_arm}"
- echo " ci_cpu = ${ci_cpu}"
- echo " ci_gpu = ${ci_gpu}"
- echo " ci_wasm = ${ci_wasm}"
- """, label: 'Docker image names')
-
- is_docs_only_build = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_change_docs.sh",
- label: 'Check for docs only changes',
- )
- skip_ci = should_skip_ci(env.CHANGE_ID)
- skip_slow_tests = should_skip_slow_tests(env.CHANGE_ID)
- rebuild_docker_images = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_change_docker.sh",
- label: 'Check for any docker changes',
- )
-
- if (skip_ci) {
- // Don't rebuild when skipping CI
- rebuild_docker_images = false
- }
- }
- }
- }
-}
-def python_unittest(image) {
- sh (
- script: "${docker_run} ${image} ./tests/scripts/task_python_unittest.sh",
- label: 'Run Python unit tests',
- )
-}
-
-def make_cpp_tests(image, build_dir) {
- sh (
- script: """
- set -eux
- ${docker_run} ${image} python3 ./tests/scripts/task_build.py \
- --sccache-bucket tvm-sccache-prod \
- --sccache-region us-west-2 \
- --cmake-target cpptest \
- --build-dir ${build_dir}
- """,
- label: 'Make C++ tests',
- )
-}
-
-def cmake_build(image, path) {
- sh (
- script: "${docker_run} --env CI_NUM_EXECUTORS ${image} ./tests/scripts/task_build.py --sccache-bucket tvm-sccache-prod --sccache-region us-west-2 --build-dir ${path}",
- label: 'Run CMake build',
- )
-}
-def cpp_unittest(image) {
- sh (
- script: "${docker_run} --env CI_NUM_EXECUTORS ${image} ./tests/scripts/task_cpp_unittest.sh",
- label: 'Run C++ tests',
+ci.build('ARM-GRAVITON3', 'BUILD: arm', 'tvm/build-arm', images.ci_arm, 'arm') {
+ sh(
+ script: "${docker_run} ${images.ci_arm} ./tests/scripts/task_config_build_arm.sh build",
+ label: 'Create ARM CMake config',
)
+ ci.cmake_build(images.ci_arm, 'build')
+ ci.make_cpp_tests(images.ci_arm, 'build')
+ ci.upload('arm', '--bundle tvm_lib --bundle cpptest')
}
-
-cancel_previous_build()
-
-try {
- prepare('CPU-SMALL-SPOT')
-} catch(Exception ex) {
- prepare('CPU-SMALL')
-}
-def run_build(node_type) {
- if (!skip_ci && is_docs_only_build != 1) {
- echo 'Begin running node_type ' + node_type
- node(node_type) {
- ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/build-arm") {
- init_git()
- docker_init(ci_arm)
- timeout(time: max_time, unit: 'MINUTES') {
-
- withEnv([
- 'PLATFORM=arm',
- ], {
- sh (
- script: "${docker_run} ${ci_arm} ./tests/scripts/task_config_build_arm.sh build",
- label: 'Create ARM CMake config',
- )
- cmake_build(ci_arm, 'build')
- make_cpp_tests(ci_arm, 'build')
- sh(
- script: "./${jenkins_scripts_root}/s3.py --action upload --bucket ${s3_bucket} --prefix ${s3_prefix}/arm --bundle tvm_lib --bundle cpptest",
- label: 'Upload artifacts to S3',
- )
- })
- }
- }
- }
- echo 'End running node_type ' + node_type
- } else {
- Utils.markStageSkippedForConditional('BUILD: arm')
- }
-}
-def build() {
- stage('Build') {
- try {
- run_build('ARM-GRAVITON3-SPOT')
- } catch (hudson.AbortException abortEx) {
- echo "Received normal AbortException, exit now. Details:" + abortEx.toString()
- throw abortEx
- } catch (Throwable ex) {
- echo 'Exception during SPOT run ' + ex.toString()
- if (is_last_build()) {
- // retry if we are currently at last build
- // mark the current stage as success
- // and try again via on demand node
- echo 'Retry on-demand given it is last build'
- currentBuild.result = 'SUCCESS'
- run_build('ARM-GRAVITON3')
- } else {
- echo 'Exit since it is not last build'
- throw ex
- }
- }
- }
-}
-build()
diff --git a/ci/jenkins/templates/utils/Prepare.groovy.j2 b/ci/jenkins/generated/common.groovy
similarity index 50%
rename from ci/jenkins/templates/utils/Prepare.groovy.j2
rename to ci/jenkins/generated/common.groovy
index b74e7f4ba5..886bf3fa36 100644
--- a/ci/jenkins/templates/utils/Prepare.groovy.j2
+++ b/ci/jenkins/generated/common.groovy
@@ -1,3 +1,39 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import org.jenkinsci.plugins.pipeline.modeldefinition.Utils
+
+// Keep the image names aligned with docker-images.ini. Tags are resolved in prepare.
+image_platforms = [ci_arm: 'ARM', ci_cpu: 'CPU', ci_gpu: 'GPU', ci_wasm: 'CPU']
+images = image_platforms.collectEntries { name, platform -> [(name): ''] }
+built_images = [:]
+upstream_revision = null
+max_time = 180
+rebuild_docker_images = false
+docker_run = 'docker/bash.sh --env CI --env PLATFORM --env TEST_STEP_NAME'
+docker_build = 'docker/build.sh'
+s3_bucket = 'tvm-jenkins-artifacts-prod'
+s3_prefix = "tvm/${env.BRANCH_NAME}/${env.BUILD_NUMBER}"
+jenkins_scripts_root = 'ci/jenkins/scripts'
+
+properties([parameters(image_platforms.collect { name, platform ->
+ string(name: "${name}_param", defaultValue: '')
+})])
+
def per_exec_ws(folder) {
return "workspace/exec_${env.EXECUTOR_NUMBER}/" + folder
}
@@ -66,7 +102,7 @@ def docker_init(image) {
script: """
set -eux
docker image ls --all
- IMAGES=\$(docker image ls --all --format {% raw %}'{{.Repository}}:{{.Tag}} {{.ID}}'{% endraw %})
+ IMAGES=\$(docker image ls --all --format '{{.Repository}}:{{.Tag}} {{.ID}}')
echo -e "Found images:\\n\$IMAGES"
echo "\$IMAGES" | { grep -vE '${image}' || test \$? = 1; } | { xargs docker rmi || test \$? = 123; }
@@ -102,8 +138,8 @@ def ecr_pull(full_name) {
try {
withEnv([
"AWS_ACCOUNT_ID=${aws_account_id}",
- 'AWS_DEFAULT_REGION={{ aws_default_region }}',
- "AWS_ECR_REPO=${aws_account_id}.{{ aws_ecr_url }}"]) {
+ 'AWS_DEFAULT_REGION=us-west-2',
+ "AWS_ECR_REPO=${aws_account_id}.dkr.ecr.us-west-2.amazonaws.com"]) {
sh(
script: '''
set -eux
@@ -123,8 +159,8 @@ def ecr_pull(full_name) {
} finally {
withEnv([
"AWS_ACCOUNT_ID=${aws_account_id}",
- 'AWS_DEFAULT_REGION={{ aws_default_region }}',
- "AWS_ECR_REPO=${aws_account_id}.{{ aws_ecr_url }}"]) {
+ 'AWS_DEFAULT_REGION=us-west-2',
+ "AWS_ECR_REPO=${aws_account_id}.dkr.ecr.us-west-2.amazonaws.com"]) {
sh(
script: 'docker logout $AWS_ECR_REPO',
label: 'Clean up login credentials'
@@ -133,21 +169,6 @@ def ecr_pull(full_name) {
}
}
-def should_skip_slow_tests(pr_number) {
- withCredentials([string(
- credentialsId: 'tvm-bot-jenkins-reader',
- variable: 'GITHUB_TOKEN',
- )]) {
- // Exit code of 1 means run slow tests, exit code of 0 means skip slow tests
- result = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/should_run_slow_tests.py --pr '${pr_number}'",
- label: 'Check if CI should run slow tests',
- )
- }
- return result == 0
-}
-
def cancel_previous_build() {
// cancel previous build if it is not on main.
if (env.BRANCH_NAME != 'main') {
@@ -175,7 +196,7 @@ def checkout_trusted_files() {
return;
}
- // trust peoople listed in CONTRIBUTING.md
+ // Trust contributors listed in the pinned target revision.
grep_code = sh(
returnStatus: true,
script: "git show '${upstream_revision}:CONTRIBUTORS.md' | grep '@${env.CHANGE_AUTHOR}'",
@@ -187,7 +208,7 @@ def checkout_trusted_files() {
// (especially those that access secrets) should be checked out here so
// only trusted versions are used in CI
sh(
- script: "git checkout ${upstream_revision} ${jenkins_scripts_root}/.",
+ script: "git checkout ${upstream_revision} ${jenkins_scripts_root}/. ci/jenkins/data.py",
label: 'Check out trusted files',
)
}
@@ -229,37 +250,25 @@ def prepare(node_type) {
if (env.DETERMINE_DOCKER_IMAGES == 'yes') {
sh(
- script: "./${jenkins_scripts_root}/determine_docker_images.py {% for image in images %}{{ image.name }} {% endfor %}",
+ script: "./${jenkins_scripts_root}/determine_docker_images.py ${images.keySet().join(' ')}",
label: 'Decide whether to use tlcpack or tlcpackstaging for Docker images',
)
- // Pull image names from the results of should_rebuild_docker.py
- {% for image in images %}
- {{ image.name }} = sh(
- script: "cat .docker-image-names/{{ image.name }}",
- label: "Find docker image name for {{ image.name }}",
- returnStdout: true,
- ).trim()
- {% endfor %}
+ images.keySet().each { name ->
+ images[name] = sh(
+ script: "cat .docker-image-names/${name}",
+ label: "Find docker image name for ${name}",
+ returnStdout: true,
+ ).trim()
+ }
}
-
- {% for image in images %}
- {{ image.name }} = params.{{ image.name }}_param ?: {{ image.name }}
- {% endfor %}
-
- sh (script: """
- echo "Docker images being used in this build:"
- {% for image in images %}
- echo " {{ image.name }} = ${ {{- image.name -}} }"
- {% endfor %}
- """, label: 'Docker image names')
-
- is_docs_only_build = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_change_docs.sh",
- label: 'Check for docs only changes',
+ images.keySet().each { name -> images[name] = params["${name}_param"] ?: images[name] }
+ sh(
+ script: 'echo "Docker images being used in this build:"\n' +
+ images.collect { name, image -> "echo \" ${name} = ${image}\"" }.join('\n'),
+ label: 'Docker image names',
)
+
skip_ci = should_skip_ci(env.CHANGE_ID)
- skip_slow_tests = should_skip_slow_tests(env.CHANGE_ID)
rebuild_docker_images = sh (
returnStatus: true,
script: "./${jenkins_scripts_root}/git_change_docker.sh",
@@ -274,3 +283,131 @@ def prepare(node_type) {
}
}
}
+def python_unittest(image) {
+ sh (
+ script: "${docker_run} ${image} ./tests/scripts/task_python_unittest.sh",
+ label: 'Run Python unit tests',
+ )
+}
+
+def make_cpp_tests(image, build_dir) {
+ sh (
+ script: """
+ set -eux
+ ${docker_run} ${image} python3 ./tests/scripts/task_build.py \
+ --sccache-bucket tvm-sccache-prod \
+ --sccache-region us-west-2 \
+ --cmake-target cpptest \
+ --build-dir ${build_dir}
+ """,
+ label: 'Make C++ tests',
+ )
+}
+
+def cmake_build(image, path) {
+ sh (
+ script: "${docker_run} --env CI_NUM_EXECUTORS ${image} ./tests/scripts/task_build.py --sccache-bucket tvm-sccache-prod --sccache-region us-west-2 --build-dir ${path}",
+ label: 'Run CMake build',
+ )
+}
+def cpp_unittest(image) {
+ sh (
+ script: "${docker_run} --env CI_NUM_EXECUTORS ${image} ./tests/scripts/task_cpp_unittest.sh",
+ label: 'Run C++ tests',
+ )
+}
+
+// Preparation retries Exceptions unconditionally; Errors and cancellation of the
+// previous build are deliberately outside this fallback.
+def start() {
+ cancel_previous_build()
+ try {
+ prepare('CPU-SMALL-SPOT')
+ } catch (Exception ex) {
+ prepare('CPU-SMALL')
+ }
+}
+
+// A failed build command is final. Infrastructure failures retry only while
+// this is the newest build; tests intentionally also retry AbortException.
+def build(label, name, folder, image, platform, body) {
+ stage('Build') {
+ try {
+ run_on_node("${label}-SPOT", name, folder, image, ["PLATFORM=${platform}"], body)
+ } catch (hudson.AbortException ex) {
+ echo 'Received normal AbortException, exit now. Details:' + ex.toString()
+ throw ex
+ } catch (Throwable ex) {
+ retry_latest(ex) {
+ run_on_node(label, name, folder, image, ["PLATFORM=${platform}"], body)
+ }
+ }
+ }
+}
+
+def retry_latest(ex, body) {
+ echo 'Exception during SPOT run ' + ex.toString()
+ if (!is_last_build()) {
+ echo 'Exit since it is not last build'
+ throw ex
+ }
+ echo 'Retry on-demand given it is last build'
+ currentBuild.result = 'SUCCESS'
+ // Do not catch failure of the on-demand retry.
+ body()
+}
+
+def test(label, name, folder, image, platform, body) {
+ def variables = ["PLATFORM=${platform}", "TEST_STEP_NAME=${name}"]
+ try {
+ run_on_node("${label}-SPOT", name, folder, image, variables, body)
+ } catch (Throwable ex) {
+ retry_latest(ex) { run_on_node(label, name, folder, image, variables, body) }
+ }
+}
+
+def run_on_node(label, name, folder, image, variables, body) {
+ if (skip_ci) {
+ Utils.markStageSkippedForConditional(name)
+ return
+ }
+ echo 'Begin running on node_type ' + label
+ node(label) {
+ ws(per_exec_ws(folder)) {
+ init_git()
+ docker_init(image)
+ timeout(time: max_time, unit: 'MINUTES') {
+ withEnv(variables) { body() }
+ }
+ }
+ }
+ echo 'End running on node_type ' + label
+}
+
+def upload(tag, options) {
+ sh(
+ script: "./${jenkins_scripts_root}/s3.py --action upload --bucket ${s3_bucket} --prefix ${s3_prefix}/${tag} ${options}",
+ label: 'Upload artifacts to S3',
+ )
+}
+
+def download(tag) {
+ sh(
+ script: "./${jenkins_scripts_root}/s3.py --action download --bucket ${s3_bucket} --prefix ${s3_prefix}/${tag}",
+ label: 'Download artifacts from S3',
+ )
+}
+
+def deploy_step(name, enabled, folder, body) {
+ if (enabled) {
+ node('CPU') {
+ ws(per_exec_ws(folder)) {
+ timeout(time: max_time, unit: 'MINUTES') { body() }
+ }
+ }
+ } else {
+ Utils.markStageSkippedForConditional(name)
+ }
+}
+
+return this
diff --git a/ci/jenkins/generated/cpu_jenkinsfile.groovy b/ci/jenkins/generated/cpu_jenkinsfile.groovy
index 0d3e408235..e252832c65 100644
--- a/ci/jenkins/generated/cpu_jenkinsfile.groovy
+++ b/ci/jenkins/generated/cpu_jenkinsfile.groovy
@@ -14,551 +14,63 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-// -*- mode: groovy -*-
-
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-
-// Jenkins pipeline
-// See documents at https://jenkins.io/doc/book/pipeline/jenkinsfile/
-
-// Docker env used for testing
-// Different image may have different version tag
-// because some of them are more stable than anoter.
-//
-// Docker images are maintained by PMC, cached in dockerhub
-// and remains relatively stable over the time.
-// Flow for upgrading docker env(need commiter)
-//
-// - Send PR to upgrade build script in the repo
-// - Build the new docker image
-// - Tag the docker image with a new version and push to a binary cache.
-// - Update the version in the Jenkinsfile, send a PR
-// - Fix any issues wrt to the new image version in the PR
-// - Merge the PR and now we are in new version
-// - Tag the new version as the lates
-// - Periodically cleanup the old versions on local workers
-//
-
-// ============================= IMPORTANT NOTE =============================
-// This file is generated by 'jenkins/generate.py'. Do not edit this file directly!
-// Make edits to 'jenkins/Jenkinsfile.j2' and regenerate this with
-// 'python3 jenkins/generate.py'
-// Note: This timestamp is here to ensure that updates to the Jenkinsfile are
-// always rebased on main before merging:
-// Generated at 2026-07-05T01:05:57.741181
-
-import org.jenkinsci.plugins.pipeline.modeldefinition.Utils
-// These are set at runtime from data in ci/jenkins/docker-images.yml, update
-// image tags in that file
-ci_gpu = ''
-ci_cpu = ''
-ci_minimal = ''
-ci_wasm = ''
-ci_cortexm = ''
-ci_arm = ''
-ci_riscv = ''
-
-// Parameters to allow overriding (in Jenkins UI), the images
-// to be used by a given build. When provided, they take precedence
-// over default values above.
-properties([
- parameters([
- string(name: 'ci_arm_param', defaultValue: ''),
- string(name: 'ci_cpu_param', defaultValue: ''),
- string(name: 'ci_gpu_param', defaultValue: ''),
- string(name: 'ci_wasm_param', defaultValue: ''),
- ])
-])
-
-// Placeholders for newly built Docker image names (if rebuild_docker_images
-// is used)
- built_ci_arm = null;
- built_ci_cpu = null;
- built_ci_gpu = null;
- built_ci_wasm = null;
-
-// Global variable assigned during Sanity Check that holds the sha1 which should be
-// merged into the PR in all branches.
-upstream_revision = null
-
-// command to start a docker container
-docker_run = 'docker/bash.sh --env CI --env PLATFORM --env SKIP_SLOW_TESTS --env TEST_STEP_NAME'
-docker_build = 'docker/build.sh'
-// timeout in minutes
-max_time = 180
-rebuild_docker_images = false
-
-s3_bucket = 'tvm-jenkins-artifacts-prod'
-s3_prefix = "tvm/${env.BRANCH_NAME}/${env.BUILD_NUMBER}"
-
-// Jenkins script root directory
-jenkins_scripts_root = "ci/scripts/jenkins"
-
-
-// General note: Jenkins has limits on the size of a method (or top level code)
-// that are pretty strict, so most usage of groovy methods in these templates
-// are purely to satisfy the JVM
-def per_exec_ws(folder) {
- return "workspace/exec_${env.EXECUTOR_NUMBER}/" + folder
-}
-
-// initialize source codes
-def init_git() {
- retry(5) {
- checkout scm
- }
-
- // Add more info about job node
- sh (
- script: './tests/scripts/task_show_node_info.sh',
- label: 'Show executor node info',
- )
-
- // Determine merge commit to use for all stages
- if (env.CHANGE_TARGET) {
- // This is a PR build, so merge with the latest of the PR's target branch
- // (e.g. main or a release branch like v0.25.0).
- merge_with_target()
- } else {
- // This is a branch build (main or a release branch). Only set
- // upstream_revision to HEAD and skip merging to avoid a race with another
- // commit merged to the branch.
- update_upstream_revision("HEAD")
- }
-
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- retry 3 timeout 5m git submodule update --init --recursive -f --jobs 0
- """,
- label: 'Update git submodules',
- )
- checkout_trusted_files()
-}
-
-def update_upstream_revision(git_ref) {
- if (upstream_revision == null) {
- upstream_revision = sh(
- script: "git log -1 ${git_ref} --format=\'%H\'",
- label: 'Determine upstream revision',
- returnStdout: true,
- ).trim()
- }
-}
-
-def merge_with_target() {
- def target = env.CHANGE_TARGET
- sh (
- script: "git fetch origin ${target}",
- label: "Fetch target branch ${target}",
- )
- update_upstream_revision("FETCH_HEAD")
- sh (
- script: "git -c user.name=TVM-Jenkins -c user.email=jenkins@tvm.apache.org merge ${upstream_revision}",
- label: "Merge to origin/${target}"
- )
-}
-
-def docker_init(image) {
- // Clear out all Docker images that aren't going to be used
- sh(
- script: """
- set -eux
- docker image ls --all
- IMAGES=\$(docker image ls --all --format '{{.Repository}}:{{.Tag}} {{.ID}}')
-
- echo -e "Found images:\\n\$IMAGES"
- echo "\$IMAGES" | { grep -vE '${image}' || test \$? = 1; } | { xargs docker rmi || test \$? = 123; }
-
- docker image ls --all
- """,
- label: 'Clean old Docker images',
- )
-
- if (image.contains("amazonaws.com")) {
- // If this string is in the image name it's from ECR and needs to be pulled
- // with the right credentials
- ecr_pull(image)
- } else {
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- retry 5 docker pull ${image}
- """,
- label: 'Pull docker image',
- )
- }
-}
-
-def ecr_pull(full_name) {
- aws_account_id = sh(
- returnStdout: true,
- script: 'aws sts get-caller-identity | grep Account | cut -f4 -d\\"',
- label: 'Get AWS ID'
- ).trim()
-
- try {
- withEnv([
- "AWS_ACCOUNT_ID=${aws_account_id}",
- 'AWS_DEFAULT_REGION=us-west-2',
- "AWS_ECR_REPO=${aws_account_id}.dkr.ecr.us-west-2.amazonaws.com"]) {
- sh(
- script: '''
- set -eux
- aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ECR_REPO
- ''',
- label: 'Log in to ECR'
- )
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- retry 5 docker pull ${full_name}
- """,
- label: 'Pull image from ECR'
- )
- }
- } finally {
- withEnv([
- "AWS_ACCOUNT_ID=${aws_account_id}",
- 'AWS_DEFAULT_REGION=us-west-2',
- "AWS_ECR_REPO=${aws_account_id}.dkr.ecr.us-west-2.amazonaws.com"]) {
- sh(
- script: 'docker logout $AWS_ECR_REPO',
- label: 'Clean up login credentials'
- )
- }
- }
-}
-
-def should_skip_slow_tests(pr_number) {
- withCredentials([string(
- credentialsId: 'tvm-bot-jenkins-reader',
- variable: 'GITHUB_TOKEN',
- )]) {
- // Exit code of 1 means run slow tests, exit code of 0 means skip slow tests
- result = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/should_run_slow_tests.py --pr '${pr_number}'",
- label: 'Check if CI should run slow tests',
- )
- }
- return result == 0
-}
-
-def cancel_previous_build() {
- // cancel previous build if it is not on main.
- if (env.BRANCH_NAME != 'main') {
- def buildNumber = env.BUILD_NUMBER as int
- // Milestone API allows us to cancel previous build
- // with the same milestone number
- if (buildNumber > 1) milestone(buildNumber - 1)
- milestone(buildNumber)
- }
-}
-
-def is_last_build() {
- // check whether it is last build
- try {
- return currentBuild.number == currentBuild.rawBuild.project.getLastBuild().number
- } catch (Throwable ex) {
- echo 'Error during check is_last_build ' + ex.toString()
- return false
- }
-}
-
-def checkout_trusted_files() {
- // trust everything from branch builds
- if (env.BRANCH_NAME == null || !env.BRANCH_NAME.startsWith('PR-')) {
- return;
- }
-
- // trust peoople listed in CONTRIBUTING.md
- grep_code = sh(
- returnStatus: true,
- script: "git show '${upstream_revision}:CONTRIBUTORS.md' | grep '@${env.CHANGE_AUTHOR}'",
- label: 'Check if change is from a contributor',
- )
-
- if (grep_code == 1) {
- // Any scripts that run on the bare host and not inside a Docker container
- // (especially those that access secrets) should be checked out here so
- // only trusted versions are used in CI
- sh(
- script: "git checkout ${upstream_revision} ${jenkins_scripts_root}/.",
- label: 'Check out trusted files',
- )
- }
-}
-
-def should_skip_ci(pr_number) {
- if (env.BRANCH_NAME == null || !env.BRANCH_NAME.startsWith('PR-')) {
- // never skip CI on build sourced from a branch
- return false
- }
- glob_skip_ci_code = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_skip_ci_globs.py",
- label: 'Check if CI should be skipped due to changed files',
- )
- if (glob_skip_ci_code == 0) {
- return true
- }
- withCredentials([string(
- credentialsId: 'tvm-bot-jenkins-reader',
- variable: 'GITHUB_TOKEN',
- )]) {
- // Exit code of 1 means run full CI (or the script had an error, so run
- // full CI just in case). Exit code of 0 means skip CI.
- git_skip_ci_code = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_skip_ci.py --pr '${pr_number}'",
- label: 'Check if CI should be skipped',
- )
- }
- return git_skip_ci_code == 0
-}
-
-def prepare(node_type) {
- stage('Prepare') {
- node(node_type) {
- ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/prepare") {
- init_git()
-
- if (env.DETERMINE_DOCKER_IMAGES == 'yes') {
- sh(
- script: "./${jenkins_scripts_root}/determine_docker_images.py ci_arm ci_cpu ci_gpu ci_wasm ",
- label: 'Decide whether to use tlcpack or tlcpackstaging for Docker images',
- )
- // Pull image names from the results of should_rebuild_docker.py
- ci_arm = sh(
- script: "cat .docker-image-names/ci_arm",
- label: "Find docker image name for ci_arm",
- returnStdout: true,
- ).trim()
- ci_cpu = sh(
- script: "cat .docker-image-names/ci_cpu",
- label: "Find docker image name for ci_cpu",
- returnStdout: true,
- ).trim()
- ci_gpu = sh(
- script: "cat .docker-image-names/ci_gpu",
- label: "Find docker image name for ci_gpu",
- returnStdout: true,
- ).trim()
- ci_wasm = sh(
- script: "cat .docker-image-names/ci_wasm",
- label: "Find docker image name for ci_wasm",
- returnStdout: true,
- ).trim()
- }
-
- ci_arm = params.ci_arm_param ?: ci_arm
- ci_cpu = params.ci_cpu_param ?: ci_cpu
- ci_gpu = params.ci_gpu_param ?: ci_gpu
- ci_wasm = params.ci_wasm_param ?: ci_wasm
-
- sh (script: """
- echo "Docker images being used in this build:"
- echo " ci_arm = ${ci_arm}"
- echo " ci_cpu = ${ci_cpu}"
- echo " ci_gpu = ${ci_gpu}"
- echo " ci_wasm = ${ci_wasm}"
- """, label: 'Docker image names')
-
- is_docs_only_build = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_change_docs.sh",
- label: 'Check for docs only changes',
- )
- skip_ci = should_skip_ci(env.CHANGE_ID)
- skip_slow_tests = should_skip_slow_tests(env.CHANGE_ID)
- rebuild_docker_images = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_change_docker.sh",
- label: 'Check for any docker changes',
- )
-
- if (skip_ci) {
- // Don't rebuild when skipping CI
- rebuild_docker_images = false
- }
- }
- }
- }
-}
-def python_unittest(image) {
- sh (
- script: "${docker_run} ${image} ./tests/scripts/task_python_unittest.sh",
- label: 'Run Python unit tests',
- )
-}
-
-def make_cpp_tests(image, build_dir) {
- sh (
- script: """
- set -eux
- ${docker_run} ${image} python3 ./tests/scripts/task_build.py \
- --sccache-bucket tvm-sccache-prod \
- --sccache-region us-west-2 \
- --cmake-target cpptest \
- --build-dir ${build_dir}
- """,
- label: 'Make C++ tests',
- )
-}
-
-def cmake_build(image, path) {
- sh (
- script: "${docker_run} --env CI_NUM_EXECUTORS ${image} ./tests/scripts/task_build.py --sccache-bucket tvm-sccache-prod --sccache-region us-west-2 --build-dir ${path}",
- label: 'Run CMake build',
- )
-}
-def cpp_unittest(image) {
- sh (
- script: "${docker_run} --env CI_NUM_EXECUTORS ${image} ./tests/scripts/task_cpp_unittest.sh",
- label: 'Run C++ tests',
- )
-}
-
-cancel_previous_build()
+// readTrusted pins trusted revisions, but rejects helper edits in untrusted PRs.
+// In that case use the PR target, pinning the same commit for all source merges.
+def helper
+String target_revision = null
try {
- prepare('CPU-SMALL-SPOT')
-} catch(Exception ex) {
- prepare('CPU-SMALL')
-}
-def run_build(node_type) {
- if (!skip_ci && is_docs_only_build != 1) {
- echo 'Begin running node_type ' + node_type
- node(node_type) {
- ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/build-cpu") {
- init_git()
- docker_init(ci_cpu)
- timeout(time: max_time, unit: 'MINUTES') {
-
- withEnv([
- 'PLATFORM=cpu',
- ], {
- sh (
- script: "${docker_run} ${ci_cpu} ./tests/scripts/task_config_build_cpu.sh build",
- label: 'Create CPU CMake config',
- )
- cmake_build(ci_cpu, 'build')
- make_cpp_tests(ci_cpu, 'build')
- sh(
- script: "./${jenkins_scripts_root}/s3.py --action upload --bucket ${s3_bucket} --prefix ${s3_prefix}/cpu --bundle tvm_lib --bundle cpptest",
- label: 'Upload artifacts to S3',
- )
- })
- }
+ helper = readTrusted('ci/jenkins/generated/common.groovy')
+} catch (hudson.AbortException | java.io.FileNotFoundException ex) {
+ if (!env.CHANGE_TARGET) throw ex
+ echo 'Loading shared pipeline from the pinned PR target: ' + ex.toString()
+ def from_target = { label ->
+ node(label) {
+ ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/pipeline") {
+ // No PR-owned executable or credentials run during this bootstrap.
+ deleteDir()
+ retry(5) { checkout scm }
+ // Quote the branch as data and fetch only from the canonical repository.
+ def target = env.CHANGE_TARGET.replace("'", "'\"'\"'")
+ sh(script: "git fetch https://github.com/apache/tvm.git 'refs/heads/${target}'",
+ label: 'Fetch trusted pipeline target')
+ def revision = sh(script: 'git rev-parse FETCH_HEAD', returnStdout: true).trim()
+ def source = sh(script: "git show ${revision}:ci/jenkins/generated/common.groovy",
+ returnStdout: true)
+ return [revision, source]
}
}
- echo 'End running node_type ' + node_type
- } else {
- Utils.markStageSkippedForConditional('BUILD: CPU')
}
-}
-def build() {
- stage('Build') {
- try {
- run_build('CPU-SPOT')
- } catch (hudson.AbortException abortEx) {
- echo "Received normal AbortException, exit now. Details:" + abortEx.toString()
- throw abortEx
- } catch (Throwable ex) {
- echo 'Exception during SPOT run ' + ex.toString()
- if (is_last_build()) {
- // retry if we are currently at last build
- // mark the current stage as success
- // and try again via on demand node
- echo 'Retry on-demand given it is last build'
- currentBuild.result = 'SUCCESS'
- run_build('CPU')
- } else {
- echo 'Exit since it is not last build'
- throw ex
- }
- }
+ def pinned
+ try {
+ pinned = from_target('CPU-SMALL-SPOT')
+ } catch (Exception failure) {
+ pinned = from_target('CPU-SMALL')
}
+ target_revision = pinned[0]
+ helper = pinned[1]
}
-build()
+// Evaluation is outside the read/fetch fallback: script errors must propagate.
+ci = evaluate(helper)
+if (target_revision != null) ci.upstream_revision = target_revision
+ci.start()
-
-
-def run_unittest_CPU(node_type) {
- echo 'Begin running on node_type ' + node_type
- if (!skip_ci && is_docs_only_build != 1) {
- node(node_type) {
- ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/ut-python-cpu") {
- // NOTE: if exception happens, it will be caught outside
- init_git()
- docker_init(ci_cpu)
- timeout(time: max_time, unit: 'MINUTES') {
- withEnv([
- 'PLATFORM=cpu',
- 'TEST_STEP_NAME=unittest: CPU',
- "SKIP_SLOW_TESTS=${skip_slow_tests}"], {
- sh(
- script: "./${jenkins_scripts_root}/s3.py --action download --bucket ${s3_bucket} --prefix ${s3_prefix}/cpu",
- label: 'Download artifacts from S3',
- )
-
- cpp_unittest(ci_cpu)
- python_unittest(ci_cpu)
- })
- }
- }
- }
- echo 'End running on node_type ' + node_type
- } else {
- Utils.markStageSkippedForConditional('unittest: CPU')
- }
+ci.build('CPU', 'BUILD: CPU', 'tvm/build-cpu', images.ci_cpu, 'cpu') {
+ sh(
+ script: "${docker_run} ${images.ci_cpu} ./tests/scripts/task_config_build_cpu.sh build",
+ label: 'Create CPU CMake config',
+ )
+ ci.cmake_build(images.ci_cpu, 'build')
+ ci.make_cpp_tests(images.ci_cpu, 'build')
+ ci.upload('cpu', '--bundle tvm_lib --bundle cpptest')
}
-
-def test() {
- stage('Test') {
- environment {
- SKIP_SLOW_TESTS = "${skip_slow_tests}"
+stage('Test') {
+ parallel('unittest: CPU': {
+ ci.test('CPU-SMALL', 'unittest: CPU', 'tvm/ut-python-cpu', images.ci_cpu, 'cpu') {
+ ci.download('cpu')
+ ci.cpp_unittest(images.ci_cpu)
+ ci.python_unittest(images.ci_cpu)
}
- parallel(
- 'unittest: CPU': {
- try {
- run_unittest_CPU('CPU-SMALL-SPOT')
- } catch (Throwable ex) {
- echo 'Exception during SPOT run ' + ex.toString()
- if (is_last_build()) {
- // retry if at last build
- // mark the current stage as success
- // and try again via on demand node
- echo 'Retry on-demand given it is last build'
- currentBuild.result = 'SUCCESS'
- run_unittest_CPU('CPU-SMALL')
- } else {
- echo 'Exit since it is not last build'
- throw ex
- }
- }
- },
- )
- }
+ })
}
-test()
diff --git a/ci/jenkins/generated/docker_jenkinsfile.groovy b/ci/jenkins/generated/docker_jenkinsfile.groovy
index 8ffe78942a..a980ad31ca 100644
--- a/ci/jenkins/generated/docker_jenkinsfile.groovy
+++ b/ci/jenkins/generated/docker_jenkinsfile.groovy
@@ -14,437 +14,47 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-// -*- mode: groovy -*-
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-
-// Jenkins pipeline
-// See documents at https://jenkins.io/doc/book/pipeline/jenkinsfile/
-
-// Docker env used for testing
-// Different image may have different version tag
-// because some of them are more stable than anoter.
-//
-// Docker images are maintained by PMC, cached in dockerhub
-// and remains relatively stable over the time.
-// Flow for upgrading docker env(need commiter)
-//
-// - Send PR to upgrade build script in the repo
-// - Build the new docker image
-// - Tag the docker image with a new version and push to a binary cache.
-// - Update the version in the Jenkinsfile, send a PR
-// - Fix any issues wrt to the new image version in the PR
-// - Merge the PR and now we are in new version
-// - Tag the new version as the lates
-// - Periodically cleanup the old versions on local workers
-//
-
-// ============================= IMPORTANT NOTE =============================
-// This file is generated by 'jenkins/generate.py'. Do not edit this file directly!
-// Make edits to 'jenkins/Jenkinsfile.j2' and regenerate this with
-// 'python3 jenkins/generate.py'
-// Note: This timestamp is here to ensure that updates to the Jenkinsfile are
-// always rebased on main before merging:
-// Generated at 2026-07-05T01:05:57.759905
-
-import org.jenkinsci.plugins.pipeline.modeldefinition.Utils
-// These are set at runtime from data in ci/jenkins/docker-images.yml, update
-// image tags in that file
-ci_gpu = ''
-ci_cpu = ''
-ci_minimal = ''
-ci_wasm = ''
-ci_cortexm = ''
-ci_arm = ''
-ci_riscv = ''
-
-// Parameters to allow overriding (in Jenkins UI), the images
-// to be used by a given build. When provided, they take precedence
-// over default values above.
-properties([
- parameters([
- string(name: 'ci_arm_param', defaultValue: ''),
- string(name: 'ci_cpu_param', defaultValue: ''),
- string(name: 'ci_gpu_param', defaultValue: ''),
- string(name: 'ci_wasm_param', defaultValue: ''),
- ])
-])
-
-// Placeholders for newly built Docker image names (if rebuild_docker_images
-// is used)
- built_ci_arm = null;
- built_ci_cpu = null;
- built_ci_gpu = null;
- built_ci_wasm = null;
-
-// Global variable assigned during Sanity Check that holds the sha1 which should be
-// merged into the PR in all branches.
-upstream_revision = null
-
-// command to start a docker container
-docker_run = 'docker/bash.sh --env CI --env PLATFORM --env SKIP_SLOW_TESTS --env TEST_STEP_NAME'
-docker_build = 'docker/build.sh'
-// timeout in minutes
-max_time = 180
-rebuild_docker_images = false
-
-s3_bucket = 'tvm-jenkins-artifacts-prod'
-s3_prefix = "tvm/${env.BRANCH_NAME}/${env.BUILD_NUMBER}"
-
-// Jenkins script root directory
-jenkins_scripts_root = "ci/scripts/jenkins"
-
-
-// General note: Jenkins has limits on the size of a method (or top level code)
-// that are pretty strict, so most usage of groovy methods in these templates
-// are purely to satisfy the JVM
-def per_exec_ws(folder) {
- return "workspace/exec_${env.EXECUTOR_NUMBER}/" + folder
-}
-
-// initialize source codes
-def init_git() {
- retry(5) {
- checkout scm
- }
-
- // Add more info about job node
- sh (
- script: './tests/scripts/task_show_node_info.sh',
- label: 'Show executor node info',
- )
-
- // Determine merge commit to use for all stages
- if (env.CHANGE_TARGET) {
- // This is a PR build, so merge with the latest of the PR's target branch
- // (e.g. main or a release branch like v0.25.0).
- merge_with_target()
- } else {
- // This is a branch build (main or a release branch). Only set
- // upstream_revision to HEAD and skip merging to avoid a race with another
- // commit merged to the branch.
- update_upstream_revision("HEAD")
- }
-
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- retry 3 timeout 5m git submodule update --init --recursive -f --jobs 0
- """,
- label: 'Update git submodules',
- )
- checkout_trusted_files()
-}
-
-def update_upstream_revision(git_ref) {
- if (upstream_revision == null) {
- upstream_revision = sh(
- script: "git log -1 ${git_ref} --format=\'%H\'",
- label: 'Determine upstream revision',
- returnStdout: true,
- ).trim()
- }
-}
-
-def merge_with_target() {
- def target = env.CHANGE_TARGET
- sh (
- script: "git fetch origin ${target}",
- label: "Fetch target branch ${target}",
- )
- update_upstream_revision("FETCH_HEAD")
- sh (
- script: "git -c user.name=TVM-Jenkins -c user.email=jenkins@tvm.apache.org merge ${upstream_revision}",
- label: "Merge to origin/${target}"
- )
-}
-
-def docker_init(image) {
- // Clear out all Docker images that aren't going to be used
- sh(
- script: """
- set -eux
- docker image ls --all
- IMAGES=\$(docker image ls --all --format '{{.Repository}}:{{.Tag}} {{.ID}}')
-
- echo -e "Found images:\\n\$IMAGES"
- echo "\$IMAGES" | { grep -vE '${image}' || test \$? = 1; } | { xargs docker rmi || test \$? = 123; }
-
- docker image ls --all
- """,
- label: 'Clean old Docker images',
- )
-
- if (image.contains("amazonaws.com")) {
- // If this string is in the image name it's from ECR and needs to be pulled
- // with the right credentials
- ecr_pull(image)
- } else {
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- retry 5 docker pull ${image}
- """,
- label: 'Pull docker image',
- )
- }
-}
-
-def ecr_pull(full_name) {
- aws_account_id = sh(
- returnStdout: true,
- script: 'aws sts get-caller-identity | grep Account | cut -f4 -d\\"',
- label: 'Get AWS ID'
- ).trim()
-
- try {
- withEnv([
- "AWS_ACCOUNT_ID=${aws_account_id}",
- 'AWS_DEFAULT_REGION=us-west-2',
- "AWS_ECR_REPO=${aws_account_id}.dkr.ecr.us-west-2.amazonaws.com"]) {
- sh(
- script: '''
- set -eux
- aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ECR_REPO
- ''',
- label: 'Log in to ECR'
- )
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- retry 5 docker pull ${full_name}
- """,
- label: 'Pull image from ECR'
- )
- }
- } finally {
- withEnv([
- "AWS_ACCOUNT_ID=${aws_account_id}",
- 'AWS_DEFAULT_REGION=us-west-2',
- "AWS_ECR_REPO=${aws_account_id}.dkr.ecr.us-west-2.amazonaws.com"]) {
- sh(
- script: 'docker logout $AWS_ECR_REPO',
- label: 'Clean up login credentials'
- )
+// readTrusted pins trusted revisions, but rejects helper edits in untrusted PRs.
+// In that case use the PR target, pinning the same commit for all source merges.
+def helper
+String target_revision = null
+try {
+ helper = readTrusted('ci/jenkins/generated/common.groovy')
+} catch (hudson.AbortException | java.io.FileNotFoundException ex) {
+ if (!env.CHANGE_TARGET) throw ex
+ echo 'Loading shared pipeline from the pinned PR target: ' + ex.toString()
+ def from_target = { label ->
+ node(label) {
+ ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/pipeline") {
+ // No PR-owned executable or credentials run during this bootstrap.
+ deleteDir()
+ retry(5) { checkout scm }
+ // Quote the branch as data and fetch only from the canonical repository.
+ def target = env.CHANGE_TARGET.replace("'", "'\"'\"'")
+ sh(script: "git fetch https://github.com/apache/tvm.git 'refs/heads/${target}'",
+ label: 'Fetch trusted pipeline target')
+ def revision = sh(script: 'git rev-parse FETCH_HEAD', returnStdout: true).trim()
+ def source = sh(script: "git show ${revision}:ci/jenkins/generated/common.groovy",
+ returnStdout: true)
+ return [revision, source]
+ }
}
}
-}
-
-def should_skip_slow_tests(pr_number) {
- withCredentials([string(
- credentialsId: 'tvm-bot-jenkins-reader',
- variable: 'GITHUB_TOKEN',
- )]) {
- // Exit code of 1 means run slow tests, exit code of 0 means skip slow tests
- result = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/should_run_slow_tests.py --pr '${pr_number}'",
- label: 'Check if CI should run slow tests',
- )
- }
- return result == 0
-}
-
-def cancel_previous_build() {
- // cancel previous build if it is not on main.
- if (env.BRANCH_NAME != 'main') {
- def buildNumber = env.BUILD_NUMBER as int
- // Milestone API allows us to cancel previous build
- // with the same milestone number
- if (buildNumber > 1) milestone(buildNumber - 1)
- milestone(buildNumber)
- }
-}
-
-def is_last_build() {
- // check whether it is last build
+ def pinned
try {
- return currentBuild.number == currentBuild.rawBuild.project.getLastBuild().number
- } catch (Throwable ex) {
- echo 'Error during check is_last_build ' + ex.toString()
- return false
- }
-}
-
-def checkout_trusted_files() {
- // trust everything from branch builds
- if (env.BRANCH_NAME == null || !env.BRANCH_NAME.startsWith('PR-')) {
- return;
- }
-
- // trust peoople listed in CONTRIBUTING.md
- grep_code = sh(
- returnStatus: true,
- script: "git show '${upstream_revision}:CONTRIBUTORS.md' | grep '@${env.CHANGE_AUTHOR}'",
- label: 'Check if change is from a contributor',
- )
-
- if (grep_code == 1) {
- // Any scripts that run on the bare host and not inside a Docker container
- // (especially those that access secrets) should be checked out here so
- // only trusted versions are used in CI
- sh(
- script: "git checkout ${upstream_revision} ${jenkins_scripts_root}/.",
- label: 'Check out trusted files',
- )
- }
-}
-
-def should_skip_ci(pr_number) {
- if (env.BRANCH_NAME == null || !env.BRANCH_NAME.startsWith('PR-')) {
- // never skip CI on build sourced from a branch
- return false
+ pinned = from_target('CPU-SMALL-SPOT')
+ } catch (Exception failure) {
+ pinned = from_target('CPU-SMALL')
}
- glob_skip_ci_code = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_skip_ci_globs.py",
- label: 'Check if CI should be skipped due to changed files',
- )
- if (glob_skip_ci_code == 0) {
- return true
- }
- withCredentials([string(
- credentialsId: 'tvm-bot-jenkins-reader',
- variable: 'GITHUB_TOKEN',
- )]) {
- // Exit code of 1 means run full CI (or the script had an error, so run
- // full CI just in case). Exit code of 0 means skip CI.
- git_skip_ci_code = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_skip_ci.py --pr '${pr_number}'",
- label: 'Check if CI should be skipped',
- )
- }
- return git_skip_ci_code == 0
+ target_revision = pinned[0]
+ helper = pinned[1]
}
+// Evaluation is outside the read/fetch fallback: script errors must propagate.
+ci = evaluate(helper)
+if (target_revision != null) ci.upstream_revision = target_revision
+ci.start()
-def prepare(node_type) {
- stage('Prepare') {
- node(node_type) {
- ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/prepare") {
- init_git()
-
- if (env.DETERMINE_DOCKER_IMAGES == 'yes') {
- sh(
- script: "./${jenkins_scripts_root}/determine_docker_images.py ci_arm ci_cpu ci_gpu ci_wasm ",
- label: 'Decide whether to use tlcpack or tlcpackstaging for Docker images',
- )
- // Pull image names from the results of should_rebuild_docker.py
- ci_arm = sh(
- script: "cat .docker-image-names/ci_arm",
- label: "Find docker image name for ci_arm",
- returnStdout: true,
- ).trim()
- ci_cpu = sh(
- script: "cat .docker-image-names/ci_cpu",
- label: "Find docker image name for ci_cpu",
- returnStdout: true,
- ).trim()
- ci_gpu = sh(
- script: "cat .docker-image-names/ci_gpu",
- label: "Find docker image name for ci_gpu",
- returnStdout: true,
- ).trim()
- ci_wasm = sh(
- script: "cat .docker-image-names/ci_wasm",
- label: "Find docker image name for ci_wasm",
- returnStdout: true,
- ).trim()
- }
-
- ci_arm = params.ci_arm_param ?: ci_arm
- ci_cpu = params.ci_cpu_param ?: ci_cpu
- ci_gpu = params.ci_gpu_param ?: ci_gpu
- ci_wasm = params.ci_wasm_param ?: ci_wasm
-
- sh (script: """
- echo "Docker images being used in this build:"
- echo " ci_arm = ${ci_arm}"
- echo " ci_cpu = ${ci_cpu}"
- echo " ci_gpu = ${ci_gpu}"
- echo " ci_wasm = ${ci_wasm}"
- """, label: 'Docker image names')
-
- is_docs_only_build = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_change_docs.sh",
- label: 'Check for docs only changes',
- )
- skip_ci = should_skip_ci(env.CHANGE_ID)
- skip_slow_tests = should_skip_slow_tests(env.CHANGE_ID)
- rebuild_docker_images = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_change_docker.sh",
- label: 'Check for any docker changes',
- )
-
- if (skip_ci) {
- // Don't rebuild when skipping CI
- rebuild_docker_images = false
- }
- }
- }
- }
-}
-def python_unittest(image) {
- sh (
- script: "${docker_run} ${image} ./tests/scripts/task_python_unittest.sh",
- label: 'Run Python unit tests',
- )
-}
-
-def make_cpp_tests(image, build_dir) {
- sh (
- script: """
- set -eux
- ${docker_run} ${image} python3 ./tests/scripts/task_build.py \
- --sccache-bucket tvm-sccache-prod \
- --sccache-region us-west-2 \
- --cmake-target cpptest \
- --build-dir ${build_dir}
- """,
- label: 'Make C++ tests',
- )
-}
-
-def cmake_build(image, path) {
- sh (
- script: "${docker_run} --env CI_NUM_EXECUTORS ${image} ./tests/scripts/task_build.py --sccache-bucket tvm-sccache-prod --sccache-region us-west-2 --build-dir ${path}",
- label: 'Run CMake build',
- )
-}
-def cpp_unittest(image) {
- sh (
- script: "${docker_run} --env CI_NUM_EXECUTORS ${image} ./tests/scripts/task_cpp_unittest.sh",
- label: 'Run C++ tests',
- )
-}
-
-cancel_previous_build()
-
-try {
- prepare('CPU-SMALL-SPOT')
-} catch(Exception ex) {
- prepare('CPU-SMALL')
-}
def ecr_push(full_name) {
aws_account_id = sh(
returnStdout: true,
@@ -511,7 +121,7 @@ def update_docker(ecr_image, hub_image) {
sh("echo \"Skipping '${ecr_image}' -> '${hub_image}' since it doesn\'t look like an ECR image\"")
return
}
- docker_init(ecr_image)
+ ci.docker_init(ecr_image)
sh(
script: """
set -eux
@@ -527,188 +137,74 @@ def update_docker(ecr_image, hub_image) {
def deploy() {
stage('Deploy') {
- if (env.BRANCH_NAME == 'main') {
- parallel(
- 'Upload built Docker images': {
- if (env.DEPLOY_DOCKER_IMAGES == 'yes' && rebuild_docker_images && upstream_revision != null) {
- node('CPU') {
- ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/deploy-docker") {
- timeout(time: max_time, unit: 'MINUTES') {
- init_git()
- try {
- withCredentials([string(
- credentialsId: 'dockerhub-tlcpackstaging-key',
- variable: 'DOCKERHUB_KEY',
- )]) {
- sh(
- script: 'docker login -u tlcpackstaging -p ${DOCKERHUB_KEY}',
- label: 'Log in to Docker Hub',
- )
- }
- def date_Ymd_HMS = sh(
- script: 'python3 -c \'import datetime; print(datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))\'',
- label: 'Determine date',
- returnStdout: true,
- ).trim()
- def tag = "${date_Ymd_HMS}-${upstream_revision.substring(0, 8)}"
- update_docker(built_ci_arm, "tlcpackstaging/ci_arm:${tag}")
- update_docker(built_ci_cpu, "tlcpackstaging/ci_cpu:${tag}")
- update_docker(built_ci_gpu, "tlcpackstaging/ci_gpu:${tag}")
- update_docker(built_ci_wasm, "tlcpackstaging/ci_wasm:${tag}")
- } finally {
- sh(
- script: 'docker logout',
- label: 'Clean up login credentials'
- )
- }
+ if (env.BRANCH_NAME != 'main') return
+ parallel(
+ 'Upload built Docker images': {
+ ci.deploy_step('Upload built Docker images',
+ env.DEPLOY_DOCKER_IMAGES == 'yes' && rebuild_docker_images && upstream_revision != null,
+ 'tvm/deploy-docker') {
+ ci.init_git()
+ try {
+ withCredentials([string(credentialsId: 'dockerhub-tlcpackstaging-key', variable: 'DOCKERHUB_KEY')]) {
+ sh(script: 'docker login -u tlcpackstaging -p ${DOCKERHUB_KEY}', label: 'Log in to Docker Hub')
+ }
+ def date = sh(
+ script: 'python3 -c \'import datetime; print(datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))\'',
+ label: 'Determine date', returnStdout: true,
+ ).trim()
+ def tag = "${date}-${upstream_revision.substring(0, 8)}"
+ images.keySet().each { name -> update_docker(built_images[name], "tlcpackstaging/${name}:${tag}") }
+ } finally {
+ sh(script: 'docker logout', label: 'Clean up login credentials')
}
}
- }
- } else {
- Utils.markStageSkippedForConditional('Upload built Docker images')
- }
- },
- 'Tag tlcpackstaging to tlcpack': {
- if (env.DEPLOY_DOCKER_IMAGES == 'yes') {
- node('CPU') {
- ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/tag-images") {
- timeout(time: max_time, unit: 'MINUTES') {
- init_git()
- withCredentials([string(
- credentialsId: 'dockerhub-tlcpack-key',
- variable: 'TLCPACK_TOKEN',
- )]) {
- try {
- sh(
- script: 'echo $TLCPACK_TOKEN | docker login --username octomldriazati --password-stdin',
- label: 'Log in to Docker Hub'
- )
- if (ci_arm.contains("tlcpackstaging")) {
- // Push image to tlcpack
- def tag = ci_arm.split(":")[1]
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- docker pull tlcpackstaging/ci_arm:${tag}
- docker tag tlcpackstaging/ci_arm:${tag} tlcpack/ci-arm:${tag}
- retry 5 docker push tlcpack/ci-arm:${tag}
- """,
- label: 'Tag tlcpackstaging/ci_arm image to tlcpack',
- )
- }
- if (ci_cpu.contains("tlcpackstaging")) {
- // Push image to tlcpack
- def tag = ci_cpu.split(":")[1]
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- docker pull tlcpackstaging/ci_cpu:${tag}
- docker tag tlcpackstaging/ci_cpu:${tag} tlcpack/ci-cpu:${tag}
- retry 5 docker push tlcpack/ci-cpu:${tag}
- """,
- label: 'Tag tlcpackstaging/ci_cpu image to tlcpack',
- )
- }
- if (ci_gpu.contains("tlcpackstaging")) {
- // Push image to tlcpack
- def tag = ci_gpu.split(":")[1]
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- docker pull tlcpackstaging/ci_gpu:${tag}
- docker tag tlcpackstaging/ci_gpu:${tag} tlcpack/ci-gpu:${tag}
- retry 5 docker push tlcpack/ci-gpu:${tag}
- """,
- label: 'Tag tlcpackstaging/ci_gpu image to tlcpack',
- )
- }
- if (ci_wasm.contains("tlcpackstaging")) {
- // Push image to tlcpack
- def tag = ci_wasm.split(":")[1]
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- docker pull tlcpackstaging/ci_wasm:${tag}
- docker tag tlcpackstaging/ci_wasm:${tag} tlcpack/ci-wasm:${tag}
- retry 5 docker push tlcpack/ci-wasm:${tag}
- """,
- label: 'Tag tlcpackstaging/ci_wasm image to tlcpack',
- )
- }
- } finally {
- sh(
- script: 'docker logout',
- label: 'Clean up login credentials'
- )
- }
- }
+ },
+ 'Tag tlcpackstaging to tlcpack': {
+ ci.deploy_step('Tag tlcpackstaging to tlcpack', env.DEPLOY_DOCKER_IMAGES == 'yes', 'tvm/tag-images') {
+ ci.init_git()
+ withCredentials([string(credentialsId: 'dockerhub-tlcpack-key', variable: 'TLCPACK_TOKEN')]) {
+ try {
+ sh(script: 'echo $TLCPACK_TOKEN | docker login --username octomldriazati --password-stdin', label: 'Log in to Docker Hub')
+ images.each { name, image ->
+ if (image.contains('tlcpackstaging')) {
+ def tag = image.split(':')[1]
+ sh(
+ script: """
+ set -eux
+ . ${jenkins_scripts_root}/retry.sh
+ docker pull tlcpackstaging/${name}:${tag}
+ docker tag tlcpackstaging/${name}:${tag} tlcpack/${name.replace('_', '-')}:${tag}
+ retry 5 docker push tlcpack/${name.replace('_', '-')}:${tag}
+ """,
+ label: "Tag tlcpackstaging/${name} image to tlcpack",
+ )
+ }
+ }
+ } finally {
+ sh(script: 'docker logout', label: 'Clean up login credentials')
+ }
}
}
- }
- } else {
- Utils.markStageSkippedForConditional('Tag tlcpackstaging to tlcpack')
- }
- },
- )
- }
+ },
+ )
}
}
-
-
if (rebuild_docker_images) {
stage('Docker Image Build') {
- parallel(
- 'ci_arm': {
- node('ARM') {
- timeout(time: max_time, unit: 'MINUTES') {
- init_git()
- // We're purposefully not setting the built image here since they
- // are not yet being uploaded to tlcpack
- // ci_arm = build_image('ci_arm')
- built_ci_arm = build_image('ci_arm');
- }
- }
- },
- 'ci_cpu': {
- node('CPU') {
- timeout(time: max_time, unit: 'MINUTES') {
- init_git()
- // We're purposefully not setting the built image here since they
- // are not yet being uploaded to tlcpack
- // ci_cpu = build_image('ci_cpu')
- built_ci_cpu = build_image('ci_cpu');
- }
- }
- },
- 'ci_gpu': {
- node('GPU') {
- timeout(time: max_time, unit: 'MINUTES') {
- init_git()
- // We're purposefully not setting the built image here since they
- // are not yet being uploaded to tlcpack
- // ci_gpu = build_image('ci_gpu')
- built_ci_gpu = build_image('ci_gpu');
- }
- }
- },
- 'ci_wasm': {
- node('CPU') {
+ def builds = [:]
+ image_platforms.each { name, label ->
+ builds[name] = {
+ node(label) {
timeout(time: max_time, unit: 'MINUTES') {
- init_git()
- // We're purposefully not setting the built image here since they
- // are not yet being uploaded to tlcpack
- // ci_wasm = build_image('ci_wasm')
- built_ci_wasm = build_image('ci_wasm');
+ ci.init_git()
+ // Test images remain unchanged until deployment publishes these builds.
+ built_images[name] = build_image(name)
}
}
- },
- )
+ }
+ }
+ parallel(builds)
}
-
deploy()
}
diff --git a/ci/jenkins/generated/gpu_jenkinsfile.groovy b/ci/jenkins/generated/gpu_jenkinsfile.groovy
index e7ce14c4ba..8c98cd16cb 100644
--- a/ci/jenkins/generated/gpu_jenkinsfile.groovy
+++ b/ci/jenkins/generated/gpu_jenkinsfile.groovy
@@ -14,625 +14,89 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-// -*- mode: groovy -*-
-
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-
-// Jenkins pipeline
-// See documents at https://jenkins.io/doc/book/pipeline/jenkinsfile/
-
-// Docker env used for testing
-// Different image may have different version tag
-// because some of them are more stable than anoter.
-//
-// Docker images are maintained by PMC, cached in dockerhub
-// and remains relatively stable over the time.
-// Flow for upgrading docker env(need commiter)
-//
-// - Send PR to upgrade build script in the repo
-// - Build the new docker image
-// - Tag the docker image with a new version and push to a binary cache.
-// - Update the version in the Jenkinsfile, send a PR
-// - Fix any issues wrt to the new image version in the PR
-// - Merge the PR and now we are in new version
-// - Tag the new version as the lates
-// - Periodically cleanup the old versions on local workers
-//
-
-// ============================= IMPORTANT NOTE =============================
-// This file is generated by 'jenkins/generate.py'. Do not edit this file directly!
-// Make edits to 'jenkins/Jenkinsfile.j2' and regenerate this with
-// 'python3 jenkins/generate.py'
-// Note: This timestamp is here to ensure that updates to the Jenkinsfile are
-// always rebased on main before merging:
-// Generated at 2026-07-05T12:52:04.884879
-
-import org.jenkinsci.plugins.pipeline.modeldefinition.Utils
-// These are set at runtime from data in ci/jenkins/docker-images.yml, update
-// image tags in that file
-ci_gpu = ''
-ci_cpu = ''
-ci_minimal = ''
-ci_wasm = ''
-ci_cortexm = ''
-ci_arm = ''
-ci_riscv = ''
-
-// Parameters to allow overriding (in Jenkins UI), the images
-// to be used by a given build. When provided, they take precedence
-// over default values above.
-properties([
- parameters([
- string(name: 'ci_arm_param', defaultValue: ''),
- string(name: 'ci_cpu_param', defaultValue: ''),
- string(name: 'ci_gpu_param', defaultValue: ''),
- string(name: 'ci_wasm_param', defaultValue: ''),
- ])
-])
-
-// Placeholders for newly built Docker image names (if rebuild_docker_images
-// is used)
- built_ci_arm = null;
- built_ci_cpu = null;
- built_ci_gpu = null;
- built_ci_wasm = null;
-
-// Global variable assigned during Sanity Check that holds the sha1 which should be
-// merged into the PR in all branches.
-upstream_revision = null
-
-// command to start a docker container
-docker_run = 'docker/bash.sh --env CI --env PLATFORM --env SKIP_SLOW_TESTS --env TEST_STEP_NAME'
-docker_build = 'docker/build.sh'
-// timeout in minutes
-max_time = 180
-rebuild_docker_images = false
-
-s3_bucket = 'tvm-jenkins-artifacts-prod'
-s3_prefix = "tvm/${env.BRANCH_NAME}/${env.BUILD_NUMBER}"
-
-// Jenkins script root directory
-jenkins_scripts_root = "ci/scripts/jenkins"
-
-
-// General note: Jenkins has limits on the size of a method (or top level code)
-// that are pretty strict, so most usage of groovy methods in these templates
-// are purely to satisfy the JVM
-def per_exec_ws(folder) {
- return "workspace/exec_${env.EXECUTOR_NUMBER}/" + folder
-}
-
-// initialize source codes
-def init_git() {
- retry(5) {
- checkout scm
- }
-
- // Add more info about job node
- sh (
- script: './tests/scripts/task_show_node_info.sh',
- label: 'Show executor node info',
- )
-
- // Determine merge commit to use for all stages
- if (env.CHANGE_TARGET) {
- // This is a PR build, so merge with the latest of the PR's target branch
- // (e.g. main or a release branch like v0.25.0).
- merge_with_target()
- } else {
- // This is a branch build (main or a release branch). Only set
- // upstream_revision to HEAD and skip merging to avoid a race with another
- // commit merged to the branch.
- update_upstream_revision("HEAD")
- }
-
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- retry 3 timeout 5m git submodule update --init --recursive -f --jobs 0
- """,
- label: 'Update git submodules',
- )
- checkout_trusted_files()
-}
-
-def update_upstream_revision(git_ref) {
- if (upstream_revision == null) {
- upstream_revision = sh(
- script: "git log -1 ${git_ref} --format=\'%H\'",
- label: 'Determine upstream revision',
- returnStdout: true,
- ).trim()
- }
-}
-
-def merge_with_target() {
- def target = env.CHANGE_TARGET
- sh (
- script: "git fetch origin ${target}",
- label: "Fetch target branch ${target}",
- )
- update_upstream_revision("FETCH_HEAD")
- sh (
- script: "git -c user.name=TVM-Jenkins -c user.email=jenkins@tvm.apache.org merge ${upstream_revision}",
- label: "Merge to origin/${target}"
- )
-}
-
-def docker_init(image) {
- // Clear out all Docker images that aren't going to be used
- sh(
- script: """
- set -eux
- docker image ls --all
- IMAGES=\$(docker image ls --all --format '{{.Repository}}:{{.Tag}} {{.ID}}')
-
- echo -e "Found images:\\n\$IMAGES"
- echo "\$IMAGES" | { grep -vE '${image}' || test \$? = 1; } | { xargs docker rmi || test \$? = 123; }
-
- docker image ls --all
- """,
- label: 'Clean old Docker images',
- )
-
- if (image.contains("amazonaws.com")) {
- // If this string is in the image name it's from ECR and needs to be pulled
- // with the right credentials
- ecr_pull(image)
- } else {
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- retry 5 docker pull ${image}
- """,
- label: 'Pull docker image',
- )
- }
-}
-
-def ecr_pull(full_name) {
- aws_account_id = sh(
- returnStdout: true,
- script: 'aws sts get-caller-identity | grep Account | cut -f4 -d\\"',
- label: 'Get AWS ID'
- ).trim()
-
- try {
- withEnv([
- "AWS_ACCOUNT_ID=${aws_account_id}",
- 'AWS_DEFAULT_REGION=us-west-2',
- "AWS_ECR_REPO=${aws_account_id}.dkr.ecr.us-west-2.amazonaws.com"]) {
- sh(
- script: '''
- set -eux
- aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ECR_REPO
- ''',
- label: 'Log in to ECR'
- )
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- retry 5 docker pull ${full_name}
- """,
- label: 'Pull image from ECR'
- )
- }
- } finally {
- withEnv([
- "AWS_ACCOUNT_ID=${aws_account_id}",
- 'AWS_DEFAULT_REGION=us-west-2',
- "AWS_ECR_REPO=${aws_account_id}.dkr.ecr.us-west-2.amazonaws.com"]) {
- sh(
- script: 'docker logout $AWS_ECR_REPO',
- label: 'Clean up login credentials'
- )
- }
- }
-}
-
-def should_skip_slow_tests(pr_number) {
- withCredentials([string(
- credentialsId: 'tvm-bot-jenkins-reader',
- variable: 'GITHUB_TOKEN',
- )]) {
- // Exit code of 1 means run slow tests, exit code of 0 means skip slow tests
- result = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/should_run_slow_tests.py --pr '${pr_number}'",
- label: 'Check if CI should run slow tests',
- )
- }
- return result == 0
-}
-
-def cancel_previous_build() {
- // cancel previous build if it is not on main.
- if (env.BRANCH_NAME != 'main') {
- def buildNumber = env.BUILD_NUMBER as int
- // Milestone API allows us to cancel previous build
- // with the same milestone number
- if (buildNumber > 1) milestone(buildNumber - 1)
- milestone(buildNumber)
- }
-}
-
-def is_last_build() {
- // check whether it is last build
- try {
- return currentBuild.number == currentBuild.rawBuild.project.getLastBuild().number
- } catch (Throwable ex) {
- echo 'Error during check is_last_build ' + ex.toString()
- return false
- }
-}
-
-def checkout_trusted_files() {
- // trust everything from branch builds
- if (env.BRANCH_NAME == null || !env.BRANCH_NAME.startsWith('PR-')) {
- return;
- }
-
- // trust peoople listed in CONTRIBUTING.md
- grep_code = sh(
- returnStatus: true,
- script: "git show '${upstream_revision}:CONTRIBUTORS.md' | grep '@${env.CHANGE_AUTHOR}'",
- label: 'Check if change is from a contributor',
- )
-
- if (grep_code == 1) {
- // Any scripts that run on the bare host and not inside a Docker container
- // (especially those that access secrets) should be checked out here so
- // only trusted versions are used in CI
- sh(
- script: "git checkout ${upstream_revision} ${jenkins_scripts_root}/.",
- label: 'Check out trusted files',
- )
- }
-}
-
-def should_skip_ci(pr_number) {
- if (env.BRANCH_NAME == null || !env.BRANCH_NAME.startsWith('PR-')) {
- // never skip CI on build sourced from a branch
- return false
- }
- glob_skip_ci_code = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_skip_ci_globs.py",
- label: 'Check if CI should be skipped due to changed files',
- )
- if (glob_skip_ci_code == 0) {
- return true
- }
- withCredentials([string(
- credentialsId: 'tvm-bot-jenkins-reader',
- variable: 'GITHUB_TOKEN',
- )]) {
- // Exit code of 1 means run full CI (or the script had an error, so run
- // full CI just in case). Exit code of 0 means skip CI.
- git_skip_ci_code = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_skip_ci.py --pr '${pr_number}'",
- label: 'Check if CI should be skipped',
- )
- }
- return git_skip_ci_code == 0
-}
-
-def prepare(node_type) {
- stage('Prepare') {
- node(node_type) {
- ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/prepare") {
- init_git()
-
- if (env.DETERMINE_DOCKER_IMAGES == 'yes') {
- sh(
- script: "./${jenkins_scripts_root}/determine_docker_images.py ci_arm ci_cpu ci_gpu ci_wasm ",
- label: 'Decide whether to use tlcpack or tlcpackstaging for Docker images',
- )
- // Pull image names from the results of should_rebuild_docker.py
- ci_arm = sh(
- script: "cat .docker-image-names/ci_arm",
- label: "Find docker image name for ci_arm",
- returnStdout: true,
- ).trim()
- ci_cpu = sh(
- script: "cat .docker-image-names/ci_cpu",
- label: "Find docker image name for ci_cpu",
- returnStdout: true,
- ).trim()
- ci_gpu = sh(
- script: "cat .docker-image-names/ci_gpu",
- label: "Find docker image name for ci_gpu",
- returnStdout: true,
- ).trim()
- ci_wasm = sh(
- script: "cat .docker-image-names/ci_wasm",
- label: "Find docker image name for ci_wasm",
- returnStdout: true,
- ).trim()
- }
-
- ci_arm = params.ci_arm_param ?: ci_arm
- ci_cpu = params.ci_cpu_param ?: ci_cpu
- ci_gpu = params.ci_gpu_param ?: ci_gpu
- ci_wasm = params.ci_wasm_param ?: ci_wasm
-
- sh (script: """
- echo "Docker images being used in this build:"
- echo " ci_arm = ${ci_arm}"
- echo " ci_cpu = ${ci_cpu}"
- echo " ci_gpu = ${ci_gpu}"
- echo " ci_wasm = ${ci_wasm}"
- """, label: 'Docker image names')
-
- is_docs_only_build = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_change_docs.sh",
- label: 'Check for docs only changes',
- )
- skip_ci = should_skip_ci(env.CHANGE_ID)
- skip_slow_tests = should_skip_slow_tests(env.CHANGE_ID)
- rebuild_docker_images = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_change_docker.sh",
- label: 'Check for any docker changes',
- )
-
- if (skip_ci) {
- // Don't rebuild when skipping CI
- rebuild_docker_images = false
- }
- }
- }
- }
-}
-def python_unittest(image) {
- sh (
- script: "${docker_run} ${image} ./tests/scripts/task_python_unittest.sh",
- label: 'Run Python unit tests',
- )
-}
-
-def make_cpp_tests(image, build_dir) {
- sh (
- script: """
- set -eux
- ${docker_run} ${image} python3 ./tests/scripts/task_build.py \
- --sccache-bucket tvm-sccache-prod \
- --sccache-region us-west-2 \
- --cmake-target cpptest \
- --build-dir ${build_dir}
- """,
- label: 'Make C++ tests',
- )
-}
-
-def cmake_build(image, path) {
- sh (
- script: "${docker_run} --env CI_NUM_EXECUTORS ${image} ./tests/scripts/task_build.py --sccache-bucket tvm-sccache-prod --sccache-region us-west-2 --build-dir ${path}",
- label: 'Run CMake build',
- )
-}
-def cpp_unittest(image) {
- sh (
- script: "${docker_run} --env CI_NUM_EXECUTORS ${image} ./tests/scripts/task_cpp_unittest.sh",
- label: 'Run C++ tests',
- )
-}
-
-cancel_previous_build()
+// readTrusted pins trusted revisions, but rejects helper edits in untrusted PRs.
+// In that case use the PR target, pinning the same commit for all source merges.
+def helper
+String target_revision = null
try {
- prepare('CPU-SMALL-SPOT')
-} catch(Exception ex) {
- prepare('CPU-SMALL')
-}
-def run_build(node_type) {
- if (!skip_ci) {
- echo 'Begin running node_type ' + node_type
- node(node_type) {
- ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/build-gpu") {
- init_git()
- docker_init(ci_gpu)
- timeout(time: max_time, unit: 'MINUTES') {
-
- withEnv([
- 'PLATFORM=gpu',
- ], {
- sh "${docker_run} --no-gpu ${ci_gpu} ./tests/scripts/task_config_build_gpu.sh build"
- cmake_build("${ci_gpu} --no-gpu", 'build')
- sh(
- script: "./${jenkins_scripts_root}/s3.py --action upload --bucket ${s3_bucket} --prefix ${s3_prefix}/gpu --bundle tvm_lib --bundle tvm_lib_gpu_extra",
- label: 'Upload artifacts to S3',
- )
-
-
- // compiler test
- sh "rm -rf build"
- sh "${docker_run} --no-gpu ${ci_gpu} ./tests/scripts/task_config_build_gpu_other.sh build"
- sh "${docker_run} --env CI_NUM_EXECUTORS ${ci_gpu} --no-gpu ./tests/scripts/task_build.py --sccache-bucket tvm-sccache-prod --sccache-region us-west-2 --cmake-target tvm_runtime --build-dir build"
- })
- }
+ helper = readTrusted('ci/jenkins/generated/common.groovy')
+} catch (hudson.AbortException | java.io.FileNotFoundException ex) {
+ if (!env.CHANGE_TARGET) throw ex
+ echo 'Loading shared pipeline from the pinned PR target: ' + ex.toString()
+ def from_target = { label ->
+ node(label) {
+ ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/pipeline") {
+ // No PR-owned executable or credentials run during this bootstrap.
+ deleteDir()
+ retry(5) { checkout scm }
+ // Quote the branch as data and fetch only from the canonical repository.
+ def target = env.CHANGE_TARGET.replace("'", "'\"'\"'")
+ sh(script: "git fetch https://github.com/apache/tvm.git 'refs/heads/${target}'",
+ label: 'Fetch trusted pipeline target')
+ def revision = sh(script: 'git rev-parse FETCH_HEAD', returnStdout: true).trim()
+ def source = sh(script: "git show ${revision}:ci/jenkins/generated/common.groovy",
+ returnStdout: true)
+ return [revision, source]
}
}
- echo 'End running node_type ' + node_type
- } else {
- Utils.markStageSkippedForConditional('BUILD: GPU')
}
-}
-def build() {
- stage('Build') {
- try {
- run_build('CPU-SPOT')
- } catch (hudson.AbortException abortEx) {
- echo "Received normal AbortException, exit now. Details:" + abortEx.toString()
- throw abortEx
- } catch (Throwable ex) {
- echo 'Exception during SPOT run ' + ex.toString()
- if (is_last_build()) {
- // retry if we are currently at last build
- // mark the current stage as success
- // and try again via on demand node
- echo 'Retry on-demand given it is last build'
- currentBuild.result = 'SUCCESS'
- run_build('CPU')
- } else {
- echo 'Exit since it is not last build'
- throw ex
- }
- }
- }
-}
-build()
-
-
-def run_unittest_GPU(node_type) {
- echo 'Begin running on node_type ' + node_type
- if (!skip_ci && is_docs_only_build != 1) {
- node(node_type) {
- ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/ut-python-gpu") {
- // NOTE: if exception happens, it will be caught outside
- init_git()
- docker_init(ci_gpu)
- timeout(time: max_time, unit: 'MINUTES') {
- withEnv([
- 'PLATFORM=gpu',
- 'TEST_STEP_NAME=unittest: GPU',
- "SKIP_SLOW_TESTS=${skip_slow_tests}"], {
- sh(
- script: "./${jenkins_scripts_root}/s3.py --action download --bucket ${s3_bucket} --prefix ${s3_prefix}/gpu",
- label: 'Download artifacts from S3',
- )
-
- sh (
- script: "${docker_run} ${ci_gpu} ./tests/scripts/task_java_unittest.sh",
- label: 'Run Java unit tests',
- )
- sh (
- script: "${docker_run} ${ci_gpu} ./tests/scripts/task_python_unittest_gpuonly.sh",
- label: 'Run Python GPU unit tests',
- )
- })
- }
- }
- }
- echo 'End running on node_type ' + node_type
- } else {
- Utils.markStageSkippedForConditional('unittest: GPU')
+ def pinned
+ try {
+ pinned = from_target('CPU-SMALL-SPOT')
+ } catch (Exception failure) {
+ pinned = from_target('CPU-SMALL')
}
+ target_revision = pinned[0]
+ helper = pinned[1]
}
+// Evaluation is outside the read/fetch fallback: script errors must propagate.
+ci = evaluate(helper)
+if (target_revision != null) ci.upstream_revision = target_revision
+ci.start()
+ci.build('CPU', 'BUILD: GPU', 'tvm/build-gpu', images.ci_gpu, 'gpu') {
+ sh "${docker_run} --no-gpu ${images.ci_gpu} ./tests/scripts/task_config_build_gpu.sh build"
+ ci.cmake_build("${images.ci_gpu} --no-gpu", 'build')
+ ci.upload('gpu', '--bundle tvm_lib --bundle tvm_lib_gpu_extra')
-
-def run_docs_GPU(node_type) {
- echo 'Begin running on node_type ' + node_type
- if (!skip_ci) {
- node(node_type) {
- ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/docs-python-gpu") {
- // NOTE: if exception happens, it will be caught outside
- init_git()
- docker_init(ci_gpu)
- timeout(time: max_time, unit: 'MINUTES') {
- withEnv([
- 'PLATFORM=gpu',
- 'TEST_STEP_NAME=docs: GPU',
- "SKIP_SLOW_TESTS=${skip_slow_tests}"], {
- sh(
- script: "./${jenkins_scripts_root}/s3.py --action download --bucket ${s3_bucket} --prefix ${s3_prefix}/gpu",
- label: 'Download artifacts from S3',
- )
-
- sh (
- script: "${docker_run} ${ci_gpu} ./tests/scripts/task_python_docs.sh",
- label: 'Build docs',
- )
- sh(
- script: "./${jenkins_scripts_root}/s3.py --action upload --bucket ${s3_bucket} --prefix ${s3_prefix}/docs --items docs.tgz",
- label: 'Upload artifacts to S3',
- )
-
- sh(
- script: "aws s3 cp --no-progress _docs s3://${s3_bucket}/${s3_prefix}/docs --recursive",
- label: 'Upload docs to S3',
- )
- })
- }
- }
- }
- echo 'End running on node_type ' + node_type
- } else {
- Utils.markStageSkippedForConditional('docs: GPU')
- }
+ // Check the compiler-only GPU configuration after publishing the test build.
+ sh 'rm -rf build'
+ sh "${docker_run} --no-gpu ${images.ci_gpu} ./tests/scripts/task_config_build_gpu_other.sh build"
+ sh "${docker_run} --env CI_NUM_EXECUTORS ${images.ci_gpu} --no-gpu ./tests/scripts/task_build.py --sccache-bucket tvm-sccache-prod --sccache-region us-west-2 --cmake-target tvm_runtime --build-dir build"
}
-
-
-def test() {
- stage('Test') {
- environment {
- SKIP_SLOW_TESTS = "${skip_slow_tests}"
- }
- parallel(
+stage('Test') {
+ parallel(
'unittest: GPU': {
- try {
- run_unittest_GPU('GPU-SPOT')
- } catch (Throwable ex) {
- echo 'Exception during SPOT run ' + ex.toString()
- if (is_last_build()) {
- // retry if at last build
- // mark the current stage as success
- // and try again via on demand node
- echo 'Retry on-demand given it is last build'
- currentBuild.result = 'SUCCESS'
- run_unittest_GPU('GPU')
- } else {
- echo 'Exit since it is not last build'
- throw ex
- }
+ ci.test('GPU', 'unittest: GPU', 'tvm/ut-python-gpu', images.ci_gpu, 'gpu') {
+ ci.download('gpu')
+ sh(
+ script: "${docker_run} ${images.ci_gpu} ./tests/scripts/task_java_unittest.sh",
+ label: 'Run Java unit tests',
+ )
+ sh(
+ script: "${docker_run} ${images.ci_gpu} ./tests/scripts/task_python_unittest_gpuonly.sh",
+ label: 'Run Python GPU unit tests',
+ )
}
},
'docs: GPU': {
- try {
- run_docs_GPU('GPU-SPOT')
- } catch (Throwable ex) {
- echo 'Exception during SPOT run ' + ex.toString()
- if (is_last_build()) {
- // retry if at last build
- // mark the current stage as success
- // and try again via on demand node
- echo 'Retry on-demand given it is last build'
- currentBuild.result = 'SUCCESS'
- run_docs_GPU('GPU')
- } else {
- echo 'Exit since it is not last build'
- throw ex
- }
+ ci.test('GPU', 'docs: GPU', 'tvm/docs-python-gpu', images.ci_gpu, 'gpu') {
+ ci.download('gpu')
+ sh(
+ script: "${docker_run} ${images.ci_gpu} ./tests/scripts/task_python_docs.sh",
+ label: 'Build docs',
+ )
+ ci.upload('docs', '--items docs.tgz')
+ sh(
+ script: "aws s3 cp --no-progress _docs s3://${s3_bucket}/${s3_prefix}/docs --recursive",
+ label: 'Upload docs to S3',
+ )
}
},
- )
- }
+ )
}
-test()
-
-
def deploy_docs() {
// Note: This code must stay in the Jenkinsfile to ensure that it runs
@@ -674,31 +138,17 @@ def deploy_docs() {
}
}
-def deploy() {
- stage('Deploy') {
- if (env.BRANCH_NAME == 'main') {
- parallel(
- 'Deploy Docs': {
- if (env.DOCS_DEPLOY_ENABLED == 'yes') {
- node('CPU') {
- ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/deploy-docs") {
- timeout(time: max_time, unit: 'MINUTES') {
- init_git()
- sh(
- script: "./${jenkins_scripts_root}/s3.py --action download --bucket ${s3_bucket} --prefix ${s3_prefix}/docs --items docs.tgz",
- label: 'Download docs folder from S3',
- )
- deploy_docs()
- }
- }
+stage('Deploy') {
+ if (env.BRANCH_NAME == 'main') {
+ parallel('Deploy Docs': {
+ ci.deploy_step('Deploy Docs', env.DOCS_DEPLOY_ENABLED == 'yes', 'tvm/deploy-docs') {
+ ci.init_git()
+ sh(
+ script: "./${jenkins_scripts_root}/s3.py --action download --bucket ${s3_bucket} --prefix ${s3_prefix}/docs --items docs.tgz",
+ label: 'Download docs folder from S3',
+ )
+ deploy_docs()
}
- } else {
- Utils.markStageSkippedForConditional('Deploy Docs')
- }
- },
- )
- }
+ })
}
}
-
-deploy()
diff --git a/ci/jenkins/generated/wasm_jenkinsfile.groovy b/ci/jenkins/generated/wasm_jenkinsfile.groovy
index 7421fa86ca..1887926335 100644
--- a/ci/jenkins/generated/wasm_jenkinsfile.groovy
+++ b/ci/jenkins/generated/wasm_jenkinsfile.groovy
@@ -14,490 +14,57 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
-// -*- mode: groovy -*-
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-
-// Jenkins pipeline
-// See documents at https://jenkins.io/doc/book/pipeline/jenkinsfile/
-
-// Docker env used for testing
-// Different image may have different version tag
-// because some of them are more stable than anoter.
-//
-// Docker images are maintained by PMC, cached in dockerhub
-// and remains relatively stable over the time.
-// Flow for upgrading docker env(need commiter)
-//
-// - Send PR to upgrade build script in the repo
-// - Build the new docker image
-// - Tag the docker image with a new version and push to a binary cache.
-// - Update the version in the Jenkinsfile, send a PR
-// - Fix any issues wrt to the new image version in the PR
-// - Merge the PR and now we are in new version
-// - Tag the new version as the lates
-// - Periodically cleanup the old versions on local workers
-//
-
-// ============================= IMPORTANT NOTE =============================
-// This file is generated by 'jenkins/generate.py'. Do not edit this file directly!
-// Make edits to 'jenkins/Jenkinsfile.j2' and regenerate this with
-// 'python3 jenkins/generate.py'
-// Note: This timestamp is here to ensure that updates to the Jenkinsfile are
-// always rebased on main before merging:
-// Generated at 2026-07-05T01:05:57.802104
-
-import org.jenkinsci.plugins.pipeline.modeldefinition.Utils
-// These are set at runtime from data in ci/jenkins/docker-images.yml, update
-// image tags in that file
-ci_gpu = ''
-ci_cpu = ''
-ci_minimal = ''
-ci_wasm = ''
-ci_cortexm = ''
-ci_arm = ''
-ci_riscv = ''
-
-// Parameters to allow overriding (in Jenkins UI), the images
-// to be used by a given build. When provided, they take precedence
-// over default values above.
-properties([
- parameters([
- string(name: 'ci_arm_param', defaultValue: ''),
- string(name: 'ci_cpu_param', defaultValue: ''),
- string(name: 'ci_gpu_param', defaultValue: ''),
- string(name: 'ci_wasm_param', defaultValue: ''),
- ])
-])
-
-// Placeholders for newly built Docker image names (if rebuild_docker_images
-// is used)
- built_ci_arm = null;
- built_ci_cpu = null;
- built_ci_gpu = null;
- built_ci_wasm = null;
-
-// Global variable assigned during Sanity Check that holds the sha1 which should be
-// merged into the PR in all branches.
-upstream_revision = null
-
-// command to start a docker container
-docker_run = 'docker/bash.sh --env CI --env PLATFORM --env SKIP_SLOW_TESTS --env TEST_STEP_NAME'
-docker_build = 'docker/build.sh'
-// timeout in minutes
-max_time = 180
-rebuild_docker_images = false
-
-s3_bucket = 'tvm-jenkins-artifacts-prod'
-s3_prefix = "tvm/${env.BRANCH_NAME}/${env.BUILD_NUMBER}"
-
-// Jenkins script root directory
-jenkins_scripts_root = "ci/scripts/jenkins"
-
-
-// General note: Jenkins has limits on the size of a method (or top level code)
-// that are pretty strict, so most usage of groovy methods in these templates
-// are purely to satisfy the JVM
-def per_exec_ws(folder) {
- return "workspace/exec_${env.EXECUTOR_NUMBER}/" + folder
-}
-
-// initialize source codes
-def init_git() {
- retry(5) {
- checkout scm
- }
-
- // Add more info about job node
- sh (
- script: './tests/scripts/task_show_node_info.sh',
- label: 'Show executor node info',
- )
-
- // Determine merge commit to use for all stages
- if (env.CHANGE_TARGET) {
- // This is a PR build, so merge with the latest of the PR's target branch
- // (e.g. main or a release branch like v0.25.0).
- merge_with_target()
- } else {
- // This is a branch build (main or a release branch). Only set
- // upstream_revision to HEAD and skip merging to avoid a race with another
- // commit merged to the branch.
- update_upstream_revision("HEAD")
- }
-
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- retry 3 timeout 5m git submodule update --init --recursive -f --jobs 0
- """,
- label: 'Update git submodules',
- )
- checkout_trusted_files()
-}
-
-def update_upstream_revision(git_ref) {
- if (upstream_revision == null) {
- upstream_revision = sh(
- script: "git log -1 ${git_ref} --format=\'%H\'",
- label: 'Determine upstream revision',
- returnStdout: true,
- ).trim()
- }
-}
-
-def merge_with_target() {
- def target = env.CHANGE_TARGET
- sh (
- script: "git fetch origin ${target}",
- label: "Fetch target branch ${target}",
- )
- update_upstream_revision("FETCH_HEAD")
- sh (
- script: "git -c user.name=TVM-Jenkins -c user.email=jenkins@tvm.apache.org merge ${upstream_revision}",
- label: "Merge to origin/${target}"
- )
-}
-
-def docker_init(image) {
- // Clear out all Docker images that aren't going to be used
- sh(
- script: """
- set -eux
- docker image ls --all
- IMAGES=\$(docker image ls --all --format '{{.Repository}}:{{.Tag}} {{.ID}}')
-
- echo -e "Found images:\\n\$IMAGES"
- echo "\$IMAGES" | { grep -vE '${image}' || test \$? = 1; } | { xargs docker rmi || test \$? = 123; }
-
- docker image ls --all
- """,
- label: 'Clean old Docker images',
- )
-
- if (image.contains("amazonaws.com")) {
- // If this string is in the image name it's from ECR and needs to be pulled
- // with the right credentials
- ecr_pull(image)
- } else {
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- retry 5 docker pull ${image}
- """,
- label: 'Pull docker image',
- )
- }
-}
-
-def ecr_pull(full_name) {
- aws_account_id = sh(
- returnStdout: true,
- script: 'aws sts get-caller-identity | grep Account | cut -f4 -d\\"',
- label: 'Get AWS ID'
- ).trim()
-
- try {
- withEnv([
- "AWS_ACCOUNT_ID=${aws_account_id}",
- 'AWS_DEFAULT_REGION=us-west-2',
- "AWS_ECR_REPO=${aws_account_id}.dkr.ecr.us-west-2.amazonaws.com"]) {
- sh(
- script: '''
- set -eux
- aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ECR_REPO
- ''',
- label: 'Log in to ECR'
- )
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- retry 5 docker pull ${full_name}
- """,
- label: 'Pull image from ECR'
- )
- }
- } finally {
- withEnv([
- "AWS_ACCOUNT_ID=${aws_account_id}",
- 'AWS_DEFAULT_REGION=us-west-2',
- "AWS_ECR_REPO=${aws_account_id}.dkr.ecr.us-west-2.amazonaws.com"]) {
- sh(
- script: 'docker logout $AWS_ECR_REPO',
- label: 'Clean up login credentials'
- )
+// readTrusted pins trusted revisions, but rejects helper edits in untrusted PRs.
+// In that case use the PR target, pinning the same commit for all source merges.
+def helper
+String target_revision = null
+try {
+ helper = readTrusted('ci/jenkins/generated/common.groovy')
+} catch (hudson.AbortException | java.io.FileNotFoundException ex) {
+ if (!env.CHANGE_TARGET) throw ex
+ echo 'Loading shared pipeline from the pinned PR target: ' + ex.toString()
+ def from_target = { label ->
+ node(label) {
+ ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/pipeline") {
+ // No PR-owned executable or credentials run during this bootstrap.
+ deleteDir()
+ retry(5) { checkout scm }
+ // Quote the branch as data and fetch only from the canonical repository.
+ def target = env.CHANGE_TARGET.replace("'", "'\"'\"'")
+ sh(script: "git fetch https://github.com/apache/tvm.git 'refs/heads/${target}'",
+ label: 'Fetch trusted pipeline target')
+ def revision = sh(script: 'git rev-parse FETCH_HEAD', returnStdout: true).trim()
+ def source = sh(script: "git show ${revision}:ci/jenkins/generated/common.groovy",
+ returnStdout: true)
+ return [revision, source]
+ }
}
}
-}
-
-def should_skip_slow_tests(pr_number) {
- withCredentials([string(
- credentialsId: 'tvm-bot-jenkins-reader',
- variable: 'GITHUB_TOKEN',
- )]) {
- // Exit code of 1 means run slow tests, exit code of 0 means skip slow tests
- result = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/should_run_slow_tests.py --pr '${pr_number}'",
- label: 'Check if CI should run slow tests',
- )
- }
- return result == 0
-}
-
-def cancel_previous_build() {
- // cancel previous build if it is not on main.
- if (env.BRANCH_NAME != 'main') {
- def buildNumber = env.BUILD_NUMBER as int
- // Milestone API allows us to cancel previous build
- // with the same milestone number
- if (buildNumber > 1) milestone(buildNumber - 1)
- milestone(buildNumber)
- }
-}
-
-def is_last_build() {
- // check whether it is last build
+ def pinned
try {
- return currentBuild.number == currentBuild.rawBuild.project.getLastBuild().number
- } catch (Throwable ex) {
- echo 'Error during check is_last_build ' + ex.toString()
- return false
+ pinned = from_target('CPU-SMALL-SPOT')
+ } catch (Exception failure) {
+ pinned = from_target('CPU-SMALL')
}
+ target_revision = pinned[0]
+ helper = pinned[1]
}
+// Evaluation is outside the read/fetch fallback: script errors must propagate.
+ci = evaluate(helper)
+if (target_revision != null) ci.upstream_revision = target_revision
+ci.start()
-def checkout_trusted_files() {
- // trust everything from branch builds
- if (env.BRANCH_NAME == null || !env.BRANCH_NAME.startsWith('PR-')) {
- return;
- }
-
- // trust peoople listed in CONTRIBUTING.md
- grep_code = sh(
- returnStatus: true,
- script: "git show '${upstream_revision}:CONTRIBUTORS.md' | grep '@${env.CHANGE_AUTHOR}'",
- label: 'Check if change is from a contributor',
- )
-
- if (grep_code == 1) {
- // Any scripts that run on the bare host and not inside a Docker container
- // (especially those that access secrets) should be checked out here so
- // only trusted versions are used in CI
- sh(
- script: "git checkout ${upstream_revision} ${jenkins_scripts_root}/.",
- label: 'Check out trusted files',
- )
- }
-}
-
-def should_skip_ci(pr_number) {
- if (env.BRANCH_NAME == null || !env.BRANCH_NAME.startsWith('PR-')) {
- // never skip CI on build sourced from a branch
- return false
- }
- glob_skip_ci_code = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_skip_ci_globs.py",
- label: 'Check if CI should be skipped due to changed files',
- )
- if (glob_skip_ci_code == 0) {
- return true
- }
- withCredentials([string(
- credentialsId: 'tvm-bot-jenkins-reader',
- variable: 'GITHUB_TOKEN',
- )]) {
- // Exit code of 1 means run full CI (or the script had an error, so run
- // full CI just in case). Exit code of 0 means skip CI.
- git_skip_ci_code = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_skip_ci.py --pr '${pr_number}'",
- label: 'Check if CI should be skipped',
- )
- }
- return git_skip_ci_code == 0
-}
-
-def prepare(node_type) {
- stage('Prepare') {
- node(node_type) {
- ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/prepare") {
- init_git()
-
- if (env.DETERMINE_DOCKER_IMAGES == 'yes') {
- sh(
- script: "./${jenkins_scripts_root}/determine_docker_images.py ci_arm ci_cpu ci_gpu ci_wasm ",
- label: 'Decide whether to use tlcpack or tlcpackstaging for Docker images',
- )
- // Pull image names from the results of should_rebuild_docker.py
- ci_arm = sh(
- script: "cat .docker-image-names/ci_arm",
- label: "Find docker image name for ci_arm",
- returnStdout: true,
- ).trim()
- ci_cpu = sh(
- script: "cat .docker-image-names/ci_cpu",
- label: "Find docker image name for ci_cpu",
- returnStdout: true,
- ).trim()
- ci_gpu = sh(
- script: "cat .docker-image-names/ci_gpu",
- label: "Find docker image name for ci_gpu",
- returnStdout: true,
- ).trim()
- ci_wasm = sh(
- script: "cat .docker-image-names/ci_wasm",
- label: "Find docker image name for ci_wasm",
- returnStdout: true,
- ).trim()
- }
-
- ci_arm = params.ci_arm_param ?: ci_arm
- ci_cpu = params.ci_cpu_param ?: ci_cpu
- ci_gpu = params.ci_gpu_param ?: ci_gpu
- ci_wasm = params.ci_wasm_param ?: ci_wasm
-
- sh (script: """
- echo "Docker images being used in this build:"
- echo " ci_arm = ${ci_arm}"
- echo " ci_cpu = ${ci_cpu}"
- echo " ci_gpu = ${ci_gpu}"
- echo " ci_wasm = ${ci_wasm}"
- """, label: 'Docker image names')
-
- is_docs_only_build = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_change_docs.sh",
- label: 'Check for docs only changes',
- )
- skip_ci = should_skip_ci(env.CHANGE_ID)
- skip_slow_tests = should_skip_slow_tests(env.CHANGE_ID)
- rebuild_docker_images = sh (
- returnStatus: true,
- script: "./${jenkins_scripts_root}/git_change_docker.sh",
- label: 'Check for any docker changes',
- )
-
- if (skip_ci) {
- // Don't rebuild when skipping CI
- rebuild_docker_images = false
- }
- }
- }
- }
-}
-def python_unittest(image) {
- sh (
- script: "${docker_run} ${image} ./tests/scripts/task_python_unittest.sh",
- label: 'Run Python unit tests',
- )
-}
-
-def make_cpp_tests(image, build_dir) {
- sh (
- script: """
- set -eux
- ${docker_run} ${image} python3 ./tests/scripts/task_build.py \
- --sccache-bucket tvm-sccache-prod \
- --sccache-region us-west-2 \
- --cmake-target cpptest \
- --build-dir ${build_dir}
- """,
- label: 'Make C++ tests',
- )
-}
-
-def cmake_build(image, path) {
- sh (
- script: "${docker_run} --env CI_NUM_EXECUTORS ${image} ./tests/scripts/task_build.py --sccache-bucket tvm-sccache-prod --sccache-region us-west-2 --build-dir ${path}",
- label: 'Run CMake build',
+ci.build('CPU', 'BUILD: WASM', 'tvm/build-wasm', images.ci_wasm, 'wasm') {
+ sh(
+ script: "${docker_run} ${images.ci_wasm} ./tests/scripts/task_config_build_wasm.sh build",
+ label: 'Create WASM CMake config',
)
-}
-def cpp_unittest(image) {
- sh (
- script: "${docker_run} --env CI_NUM_EXECUTORS ${image} ./tests/scripts/task_cpp_unittest.sh",
- label: 'Run C++ tests',
+ ci.cmake_build(images.ci_wasm, 'build')
+ ci.make_cpp_tests(images.ci_wasm, 'build')
+ ci.cpp_unittest(images.ci_wasm)
+ sh(
+ script: "${docker_run} ${images.ci_wasm} ./tests/scripts/task_web_wasm.sh",
+ label: 'Run WASM lint and tests',
)
}
-
-cancel_previous_build()
-
-try {
- prepare('CPU-SMALL-SPOT')
-} catch(Exception ex) {
- prepare('CPU-SMALL')
-}
-def run_build(node_type) {
- if (!skip_ci && is_docs_only_build != 1) {
- echo 'Begin running node_type ' + node_type
- node(node_type) {
- ws("workspace/exec_${env.EXECUTOR_NUMBER}/tvm/build-wasm") {
- init_git()
- docker_init(ci_wasm)
- timeout(time: max_time, unit: 'MINUTES') {
-
- withEnv([
- 'PLATFORM=wasm',
- ], {
- sh (
- script: "${docker_run} ${ci_wasm} ./tests/scripts/task_config_build_wasm.sh build",
- label: 'Create WASM CMake config',
- )
- cmake_build(ci_wasm, 'build')
- make_cpp_tests(ci_wasm, 'build')
- cpp_unittest(ci_wasm)
- sh (
- script: "${docker_run} ${ci_wasm} ./tests/scripts/task_web_wasm.sh",
- label: 'Run WASM lint and tests',
- )
- })
- }
- }
- }
- echo 'End running node_type ' + node_type
- } else {
- Utils.markStageSkippedForConditional('BUILD: WASM')
- }
-}
-def build() {
- stage('Build') {
- try {
- run_build('CPU-SPOT')
- } catch (hudson.AbortException abortEx) {
- echo "Received normal AbortException, exit now. Details:" + abortEx.toString()
- throw abortEx
- } catch (Throwable ex) {
- echo 'Exception during SPOT run ' + ex.toString()
- if (is_last_build()) {
- // retry if we are currently at last build
- // mark the current stage as success
- // and try again via on demand node
- echo 'Retry on-demand given it is last build'
- currentBuild.result = 'SUCCESS'
- run_build('CPU')
- } else {
- echo 'Exit since it is not last build'
- throw ex
- }
- }
- }
-}
-build()
diff --git a/ci/scripts/jenkins/determine_docker_images.py b/ci/jenkins/scripts/determine_docker_images.py
similarity index 96%
rename from ci/scripts/jenkins/determine_docker_images.py
rename to ci/jenkins/scripts/determine_docker_images.py
index 3f3deb5c57..905186d7f4 100755
--- a/ci/scripts/jenkins/determine_docker_images.py
+++ b/ci/jenkins/scripts/determine_docker_images.py
@@ -25,9 +25,10 @@ import urllib.error
from pathlib import Path
from typing import Any
-from cmd_utils import REPO_ROOT, init_log
from http_utils import get
+REPO_ROOT = Path(__file__).resolve().parents[3]
+
DOCKER_API_BASE = "https://hub.docker.com/v2/"
PAGE_SIZE = 25
TEST_DATA = None
@@ -83,7 +84,9 @@ def lookup_image_tag(name: str) -> str:
if __name__ == "__main__":
- init_log()
+ logging.basicConfig(
+ format="[%(filename)s:%(lineno)d %(levelname)s] %(message)s", level=logging.INFO
+ )
parser = argparse.ArgumentParser(
description="Writes out Docker images names to be used to .docker-image-names/"
)
diff --git a/ci/scripts/jenkins/git_change_docker.sh b/ci/jenkins/scripts/git_change_docker.sh
similarity index 100%
rename from ci/scripts/jenkins/git_change_docker.sh
rename to ci/jenkins/scripts/git_change_docker.sh
diff --git a/ci/scripts/jenkins/git_skip_ci.py b/ci/jenkins/scripts/git_skip_ci.py
similarity index 56%
rename from ci/scripts/jenkins/git_skip_ci.py
rename to ci/jenkins/scripts/git_skip_ci.py
index 3f7caa0f8d..f7c84923f9 100755
--- a/ci/scripts/jenkins/git_skip_ci.py
+++ b/ci/jenkins/scripts/git_skip_ci.py
@@ -17,11 +17,44 @@
# under the License.
import argparse
+import json
import logging
import os
+import re
+import subprocess
+from urllib import request
+
+
+def parse_remote(remote: str) -> tuple[str, str]:
+ """
+ Get a GitHub (user, repo) pair out of a git remote
+ """
+ if remote.startswith("https://"):
+ # Parse HTTP remote
+ parts = remote.split("/")
+ if len(parts) < 2:
+ raise RuntimeError(f"Unable to parse remote '{remote}'")
+ user, repo = parts[-2], parts[-1].replace(".git", "")
+ else:
+ # Parse SSH remote
+ m = re.search(r":(.*)/(.*)\.git", remote)
+ if m is None or len(m.groups()) != 2:
+ raise RuntimeError(f"Unable to parse remote '{remote}'")
+ user, repo = m.groups()
+
+ user = os.getenv("DEBUG_USER", user)
+ repo = os.getenv("DEBUG_REPO", repo)
+ return user, repo
+
+
+def git(command, **kwargs):
+ command = ["git", *command]
+ logging.info(f"Running {command}")
+ proc = subprocess.run(command, stdout=subprocess.PIPE, encoding="utf-8", **kwargs)
+ if proc.returncode != 0:
+ raise RuntimeError(f"Command failed {command}:\nstdout:\n{proc.stdout}")
+ return proc.stdout.strip()
-from cmd_utils import init_log, tags_from_title
-from git_utils import GitHubRepo, git, parse_remote
if __name__ == "__main__":
help = "Exits with 0 if CI should be skipped, 1 otherwise"
@@ -32,7 +65,9 @@ if __name__ == "__main__":
"--pr-title", help="(testing) PR title to use instead of fetching from GitHub"
)
args = parser.parse_args()
- init_log()
+ logging.basicConfig(
+ format="[%(filename)s:%(lineno)d %(levelname)s] %(message)s", level=logging.INFO
+ )
branch = git(["rev-parse", "--abbrev-ref", "HEAD"])
log = git(["log", "--format=%s", "-1"])
@@ -45,11 +80,15 @@ if __name__ == "__main__":
if args.pr_title:
title = args.pr_title
else:
- github = GitHubRepo(token=os.environ["GITHUB_TOKEN"], user=user, repo=repo)
- pr = github.get(f"pulls/{args.pr}")
+ req = request.Request(
+ f"https://api.github.com/repos/{user}/{repo}/pulls/{args.pr}",
+ headers={"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}"},
+ )
+ with request.urlopen(req) as response:
+ pr = json.loads(response.read())
title = pr["title"]
logging.info(f"pr title: {title}")
- tags = tags_from_title(title)
+ tags = [tag.strip() for tag in re.findall(r"\[(.*?)\]", title)]
logging.info(f"Found title tags: {tags}")
return "skip ci" in tags
diff --git a/ci/scripts/jenkins/git_skip_ci_globs.py b/ci/jenkins/scripts/git_skip_ci_globs.py
similarity index 98%
rename from ci/scripts/jenkins/git_skip_ci_globs.py
rename to ci/jenkins/scripts/git_skip_ci_globs.py
index 90970eecc6..f7fc0860ec 100755
--- a/ci/scripts/jenkins/git_skip_ci_globs.py
+++ b/ci/jenkins/scripts/git_skip_ci_globs.py
@@ -20,7 +20,7 @@
import argparse
import fnmatch
-from git_utils import git
+from git_skip_ci import git
globs = [
"*.md",
diff --git a/ci/scripts/jenkins/http_utils.py b/ci/jenkins/scripts/http_utils.py
similarity index 100%
rename from ci/scripts/jenkins/http_utils.py
rename to ci/jenkins/scripts/http_utils.py
diff --git a/ci/scripts/jenkins/retry.sh b/ci/jenkins/scripts/retry.sh
similarity index 100%
rename from ci/scripts/jenkins/retry.sh
rename to ci/jenkins/scripts/retry.sh
diff --git a/ci/scripts/jenkins/s3.py b/ci/jenkins/scripts/s3.py
similarity index 83%
rename from ci/scripts/jenkins/s3.py
rename to ci/jenkins/scripts/s3.py
index e2e65dcadb..c0859228d2 100755
--- a/ci/scripts/jenkins/s3.py
+++ b/ci/jenkins/scripts/s3.py
@@ -20,10 +20,11 @@ import argparse
import importlib.util
import logging
import re
+import subprocess
from enum import Enum
from pathlib import Path
-from cmd_utils import REPO_ROOT, Sh, init_log
+REPO_ROOT = Path(__file__).resolve().parents[3]
DATA_PY = REPO_ROOT / "ci" / "jenkins" / "data.py"
@@ -49,9 +50,8 @@ def resolve_bundles(bundle_names: list[str]) -> list[str]:
return items
-RETRY_SCRIPT = REPO_ROOT / "ci" / "scripts" / "jenkins" / "retry.sh"
+RETRY_SCRIPT = REPO_ROOT / "ci" / "jenkins" / "scripts" / "retry.sh"
S3_DOWNLOAD_REGEX = re.compile(r"download: s3://.* to (.*)")
-SH = Sh()
class Action(Enum):
@@ -61,7 +61,7 @@ class Action(Enum):
def show_md5(item: str) -> None:
if not Path(item).is_dir():
- sh.run(f"md5sum {item}")
+ subprocess.run(["md5sum", item], check=True)
def parse_output_files(stdout: str) -> list[str]:
@@ -91,25 +91,44 @@ def chmod(files: list[str]) -> None:
to_chmod = [str(f) for f in files]
logging.info(f"Adding execute bit for files: {to_chmod}")
if len(to_chmod) > 0:
- SH.run(f"chmod +x {' '.join(to_chmod)}")
+ subprocess.run(["chmod", "+x", *to_chmod], check=True)
def s3(source: str, destination: str, recursive: bool) -> list[str]:
"""
Send or download the source to the destination in S3
"""
- cmd = f". {RETRY_SCRIPT.relative_to(REPO_ROOT)} && retry 3 aws s3 cp --no-progress"
-
+ # Retry each transfer independently; retain retry.sh's bounded random backoff.
+ command = [
+ "bash",
+ "-c",
+ '. "$1"; shift; retry 3 "$@"',
+ "s3",
+ str(RETRY_SCRIPT),
+ "aws",
+ "s3",
+ "cp",
+ "--no-progress",
+ ]
if recursive:
- cmd += " --recursive"
-
- cmd += f" {source} {destination}"
- _, stdout = SH.tee(cmd)
+ command.append("--recursive")
+ command.extend([source, destination])
+ logging.info("Copying %s to %s", source, destination)
+ with subprocess.Popen(command, stdout=subprocess.PIPE, text=True) as process:
+ output = []
+ for line in process.stdout:
+ print(line, end="", flush=True)
+ output.append(line)
+ stdout = "".join(output)
+ if process.wait():
+ raise subprocess.CalledProcessError(process.returncode, command, stdout)
return stdout
if __name__ == "__main__":
- init_log()
+ logging.basicConfig(
+ format="[%(filename)s:%(lineno)d %(levelname)s] %(message)s", level=logging.INFO
+ )
help = "Uploads or downloads files from S3"
parser = argparse.ArgumentParser(description=help)
parser.add_argument("--action", help="either 'upload' or 'download'", required=True)
@@ -133,8 +152,6 @@ if __name__ == "__main__":
logging.info(args)
- sh = Sh()
-
if Path.cwd() != REPO_ROOT:
logging.error(f"s3.py can only be executed from the repo root, instead was in {Path.cwd()}")
exit(1)
diff --git a/ci/scripts/jenkins/should_rebuild_docker.py b/ci/jenkins/scripts/should_rebuild_docker.py
similarity index 91%
rename from ci/scripts/jenkins/should_rebuild_docker.py
rename to ci/jenkins/scripts/should_rebuild_docker.py
index 0c608dc43a..fbd72ef65c 100755
--- a/ci/scripts/jenkins/should_rebuild_docker.py
+++ b/ci/jenkins/scripts/should_rebuild_docker.py
@@ -23,7 +23,6 @@ import logging
import subprocess
from typing import Any
-from cmd_utils import Sh, init_log
from http_utils import get
DOCKER_API_BASE = "https://hub.docker.com/v2/"
@@ -57,9 +56,10 @@ def any_docker_changes_since(hash: str) -> bool:
Check the docker/ directory, return True if there have been any code changes
since the specified hash
"""
- sh = Sh()
- cmd = f"git diff {hash} -- docker/"
- proc = sh.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+ cmd = ["git", "diff", hash, "--", "docker/"]
+ proc = subprocess.run(
+ cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=True
+ )
stdout = proc.stdout.strip()
return stdout != "", stdout
@@ -68,9 +68,10 @@ def does_commit_exist(hash: str) -> bool:
"""
Returns True if the hash exists in the repo
"""
- sh = Sh()
- cmd = f"git rev-parse -q {hash}"
- proc = sh.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False)
+ cmd = ["git", "rev-parse", "-q", hash]
+ proc = subprocess.run(
+ cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=False
+ )
print(proc.stdout)
if proc.returncode == 0:
return True
@@ -136,7 +137,9 @@ def main():
if __name__ == "__main__":
- init_log()
+ logging.basicConfig(
+ format="[%(filename)s:%(lineno)d %(levelname)s] %(message)s", level=logging.INFO
+ )
parser = argparse.ArgumentParser(
description="Exits 0 if Docker images don't need to be rebuilt, 1 otherwise"
)
diff --git a/ci/jenkins/templates/arm_jenkinsfile.groovy.j2 b/ci/jenkins/templates/arm_jenkinsfile.groovy.j2
deleted file mode 100644
index 2bddbab4c7..0000000000
--- a/ci/jenkins/templates/arm_jenkinsfile.groovy.j2
+++ /dev/null
@@ -1,35 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-{% include "utils/base.groovy.j2" with context %}
-{% import 'utils/macros.j2' as m with context -%}
-
-{% call m.invoke_build(
- name='BUILD: arm',
- node='ARM-GRAVITON3',
- condition='!skip_ci && is_docs_only_build != 1',
- ws='tvm/build-arm',
- docker_image='ci_arm',
- platform="arm",
-) %}
- sh (
- script: "${docker_run} ${ci_arm} ./tests/scripts/task_config_build_arm.sh build",
- label: 'Create ARM CMake config',
- )
- cmake_build(ci_arm, 'build')
- make_cpp_tests(ci_arm, 'build')
- {{ m.upload_artifacts(tag='arm', bundles=["tvm_lib", "cpptest"]) }}
-{% endcall %}
diff --git a/ci/jenkins/templates/cpu_jenkinsfile.groovy.j2 b/ci/jenkins/templates/cpu_jenkinsfile.groovy.j2
deleted file mode 100644
index 62b7c3dfea..0000000000
--- a/ci/jenkins/templates/cpu_jenkinsfile.groovy.j2
+++ /dev/null
@@ -1,52 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-{% include "utils/base.groovy.j2" with context %}
-{% import 'utils/macros.j2' as m with context -%}
-
-{% call m.invoke_build(
- name='BUILD: CPU',
- node='CPU',
- condition='!skip_ci && is_docs_only_build != 1',
- ws='tvm/build-cpu',
- docker_image='ci_cpu',
- platform="cpu",
-) %}
- sh (
- script: "${docker_run} ${ci_cpu} ./tests/scripts/task_config_build_cpu.sh build",
- label: 'Create CPU CMake config',
- )
- cmake_build(ci_cpu, 'build')
- make_cpp_tests(ci_cpu, 'build')
- {{ m.upload_artifacts(tag='cpu', bundles=["tvm_lib", "cpptest"]) }}
-{% endcall %}
-
-{% set test_method_names = [] %}
-
-
-{% call m.test_step(
- name="unittest: CPU",
- ws="tvm/ut-python-cpu",
- platform="cpu",
- docker_image="ci_cpu",
- test_method_names=test_method_names,
-) %}
- {{ m.download_artifacts(tag='cpu') }}
- cpp_unittest(ci_cpu)
- python_unittest(ci_cpu)
-{% endcall %}
-
-{{ m.invoke_tests(node="CPU-SMALL", test_method_names=test_method_names) -}}
diff --git a/ci/jenkins/templates/docker_jenkinsfile.groovy.j2 b/ci/jenkins/templates/docker_jenkinsfile.groovy.j2
deleted file mode 100644
index beb9b478ba..0000000000
--- a/ci/jenkins/templates/docker_jenkinsfile.groovy.j2
+++ /dev/null
@@ -1,202 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-{% include "utils/base.groovy.j2" with context %}
-{% import 'utils/macros.j2' as m with context -%}
-
-def ecr_push(full_name) {
- aws_account_id = sh(
- returnStdout: true,
- script: 'aws sts get-caller-identity | grep Account | cut -f4 -d\\"',
- label: 'Get AWS ID'
- ).trim()
-
- def ecr_name = "${aws_account_id}.{{ aws_ecr_url }}/${full_name}"
- try {
- withEnv([
- "AWS_ACCOUNT_ID=${aws_account_id}",
- 'AWS_DEFAULT_REGION={{ aws_default_region }}',
- "AWS_ECR_REPO=${aws_account_id}.{{ aws_ecr_url }}"]) {
- sh(
- script: '''
- set -eux
- aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ECR_REPO
- ''',
- label: 'Log in to ECR'
- )
- sh(
- script: """
- set -x
- . ${jenkins_scripts_root}/retry.sh
- docker tag ${full_name} \$AWS_ECR_REPO/${full_name}
- retry 5 docker push \$AWS_ECR_REPO/${full_name}
- """,
- label: 'Upload image to ECR'
- )
- }
- } finally {
- withEnv([
- "AWS_ACCOUNT_ID=${aws_account_id}",
- 'AWS_DEFAULT_REGION={{ aws_default_region }}',
- "AWS_ECR_REPO=${aws_account_id}.{{ aws_ecr_url }}"]) {
- sh(
- script: 'docker logout $AWS_ECR_REPO',
- label: 'Clean up login credentials'
- )
- }
- }
- return ecr_name
-}
-
-def build_image(image_name) {
- hash = sh(
- returnStdout: true,
- script: 'git log -1 --format=\'%h\''
- ).trim()
- def full_name = "${image_name}:${env.BRANCH_NAME}-${hash}-${env.BUILD_NUMBER}".replace('/', '_')
- sh(
- script: "${docker_build} ${image_name} --spec ${full_name}",
- label: 'Build docker image'
- )
- return ecr_push(full_name)
-}
-
-def update_docker(ecr_image, hub_image) {
- if (ecr_image == null) {
- sh("image was not rebuilt, skipping")
- return
- }
- if (!ecr_image.contains("amazonaws.com")) {
- sh("echo \"Skipping '${ecr_image}' -> '${hub_image}' since it doesn\'t look like an ECR image\"")
- return
- }
- docker_init(ecr_image)
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- docker tag \
- ${ecr_image} \
- ${hub_image}
- retry 5 docker push ${hub_image}
- """,
- label: "Update ${hub_image} on Docker Hub",
- )
-}
-
-def deploy() {
- stage('Deploy') {
- if (env.BRANCH_NAME == 'main') {
- parallel(
- {% call m.deploy_step(
- name="Upload built Docker images",
- feature_flag="env.DEPLOY_DOCKER_IMAGES == 'yes' && rebuild_docker_images && upstream_revision != null",
- ws="tvm/deploy-docker",
- ) %}
- init_git()
- try {
- withCredentials([string(
- credentialsId: 'dockerhub-tlcpackstaging-key',
- variable: 'DOCKERHUB_KEY',
- )]) {
- sh(
- script: 'docker login -u tlcpackstaging -p ${DOCKERHUB_KEY}',
- label: 'Log in to Docker Hub',
- )
- }
- def date_Ymd_HMS = sh(
- script: 'python3 -c \'import datetime; print(datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))\'',
- label: 'Determine date',
- returnStdout: true,
- ).trim()
- def tag = "${date_Ymd_HMS}-${upstream_revision.substring(0, 8)}"
- {% for image in images %}
- update_docker(built_{{ image.name }}, "tlcpackstaging/{{ image.name }}:${tag}")
- {% endfor %}
- } finally {
- sh(
- script: 'docker logout',
- label: 'Clean up login credentials'
- )
- }
- {% endcall %}
- {% call m.deploy_step(
- name="Tag tlcpackstaging to tlcpack",
- feature_flag="env.DEPLOY_DOCKER_IMAGES == 'yes'",
- ws="tvm/tag-images",
- ) %}
- init_git()
- withCredentials([string(
- credentialsId: 'dockerhub-tlcpack-key',
- variable: 'TLCPACK_TOKEN',
- )]) {
- try {
- sh(
- script: 'echo $TLCPACK_TOKEN | docker login --username octomldriazati --password-stdin',
- label: 'Log in to Docker Hub'
- )
- {% for image in images %}
- if ({{ image.name }}.contains("tlcpackstaging")) {
- // Push image to tlcpack
- def tag = {{ image.name }}.split(":")[1]
- sh(
- script: """
- set -eux
- . ${jenkins_scripts_root}/retry.sh
- docker pull tlcpackstaging/{{ image.name }}:${tag}
- docker tag tlcpackstaging/{{ image.name }}:${tag} tlcpack/{{ image.name.replace("_", "-") }}:${tag}
- retry 5 docker push tlcpack/{{ image.name.replace("_", "-") }}:${tag}
- """,
- label: 'Tag tlcpackstaging/{{ image.name }} image to tlcpack',
- )
- }
- {% endfor %}
- } finally {
- sh(
- script: 'docker logout',
- label: 'Clean up login credentials'
- )
- }
- }
- {% endcall %}
- )
- }
- }
-}
-
-
-
-if (rebuild_docker_images) {
- stage('Docker Image Build') {
- parallel(
- {% for image in images %}
- '{{ image.name }}': {
- node('{{ image.platform }}') {
- timeout(time: max_time, unit: 'MINUTES') {
- init_git()
- // We're purposefully not setting the built image here since they
- // are not yet being uploaded to tlcpack
- // {{ image.name }} = build_image('{{ image.name }}')
- built_{{ image.name }} = build_image('{{ image.name }}');
- }
- }
- },
- {% endfor %}
- )
- }
-
- deploy()
-}
diff --git a/ci/jenkins/templates/gpu_jenkinsfile.groovy.j2 b/ci/jenkins/templates/gpu_jenkinsfile.groovy.j2
deleted file mode 100644
index 4553fbefa2..0000000000
--- a/ci/jenkins/templates/gpu_jenkinsfile.groovy.j2
+++ /dev/null
@@ -1,144 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-{% include "utils/base.groovy.j2" with context %}
-{% import 'utils/macros.j2' as m with context -%}
-
-{% call m.invoke_build(
- name='BUILD: GPU',
- node='CPU',
- condition='!skip_ci',
- ws='tvm/build-gpu',
- docker_image='ci_gpu',
- platform="gpu",
-) %}
- sh "${docker_run} --no-gpu ${ci_gpu} ./tests/scripts/task_config_build_gpu.sh build"
- cmake_build("${ci_gpu} --no-gpu", 'build')
- {{ m.upload_artifacts(tag='gpu', bundles=["tvm_lib", "tvm_lib_gpu_extra"]) }}
-
- // compiler test
- sh "rm -rf build"
- sh "${docker_run} --no-gpu ${ci_gpu} ./tests/scripts/task_config_build_gpu_other.sh build"
- sh "${docker_run} --env CI_NUM_EXECUTORS ${ci_gpu} --no-gpu ./tests/scripts/task_build.py --sccache-bucket tvm-sccache-prod --sccache-region us-west-2 --cmake-target tvm_runtime --build-dir build"
-{% endcall %}
-
-{% set test_method_names = [] %}
-
-{% call m.test_step(
- name="unittest: GPU",
- ws="tvm/ut-python-gpu",
- platform="gpu",
- docker_image="ci_gpu",
- test_method_names=test_method_names,
-) %}
- {{ m.download_artifacts(tag='gpu') }}
- sh (
- script: "${docker_run} ${ci_gpu} ./tests/scripts/task_java_unittest.sh",
- label: 'Run Java unit tests',
- )
- sh (
- script: "${docker_run} ${ci_gpu} ./tests/scripts/task_python_unittest_gpuonly.sh",
- label: 'Run Python GPU unit tests',
- )
-{% endcall %}
-
-
-{% call m.test_step(
- name="docs: GPU",
- ws="tvm/docs-python-gpu",
- platform="gpu",
- docker_image="ci_gpu",
- condition="!skip_ci",
- test_method_names=test_method_names,
-) %}
- {{ m.download_artifacts(tag='gpu') }}
- sh (
- script: "${docker_run} ${ci_gpu} ./tests/scripts/task_python_docs.sh",
- label: 'Build docs',
- )
- {{ m.upload_artifacts(tag='docs', filenames=["docs.tgz"]) }}
- sh(
- script: "aws s3 cp --no-progress _docs s3://${s3_bucket}/${s3_prefix}/docs --recursive",
- label: 'Upload docs to S3',
- )
-{% endcall %}
-
-
-{{ m.invoke_tests(node="GPU", test_method_names=test_method_names) }}
-
-
-def deploy_docs() {
- // Note: This code must stay in the Jenkinsfile to ensure that it runs
- // from a trusted context only
- sh(
- script: '''
- set -eux
- rm -rf tvm-site
- git clone -b $DOCS_DEPLOY_BRANCH --depth=1 https://github.com/apache/tvm-site
- cd tvm-site
- git status
- git checkout -B $DOCS_DEPLOY_BRANCH
-
- git ls-tree HEAD docs/ --name-only | grep -vP '^docs/v\\d' | xargs rm -rf
- mkdir -p docs
- tar xf ../docs.tgz -C docs
- COMMIT=$(cat docs/commit_hash)
- git add .
- git config user.name tvm-bot
- git config user.email 95660001+tvm-bot@users.noreply.github.com
- git commit -m"deploying docs (apache/tvm@$COMMIT)"
- git status
- ''',
- label: 'Unpack docs and update tvm-site'
- )
-
- withCredentials([string(
- credentialsId: 'docs-push-token',
- variable: 'GITHUB_TOKEN',
- )]) {
- sh(
- script: '''
- cd tvm-site
- git remote add deploy https://$GITHUB_TOKEN:x-oauth-basic@github.com/apache/tvm-site.git
- git push deploy $DOCS_DEPLOY_BRANCH || true
- ''',
- label: 'Upload docs to apache/tvm-site'
- )
- }
-}
-
-def deploy() {
- stage('Deploy') {
- if (env.BRANCH_NAME == 'main') {
- parallel(
- {% call m.deploy_step(
- name="Deploy Docs",
- feature_flag="env.DOCS_DEPLOY_ENABLED == 'yes'",
- ws="tvm/deploy-docs",
- ) %}
- init_git()
- sh(
- script: "./${jenkins_scripts_root}/s3.py --action download --bucket ${s3_bucket} --prefix ${s3_prefix}/docs --items docs.tgz",
- label: 'Download docs folder from S3',
- )
- deploy_docs()
- {% endcall %}
- )
- }
- }
-}
-
-deploy()
diff --git a/ci/jenkins/templates/utils/Build.groovy.j2 b/ci/jenkins/templates/utils/Build.groovy.j2
deleted file mode 100644
index 42bd4a991f..0000000000
--- a/ci/jenkins/templates/utils/Build.groovy.j2
+++ /dev/null
@@ -1,27 +0,0 @@
-def python_unittest(image) {
- sh (
- script: "${docker_run} ${image} ./tests/scripts/task_python_unittest.sh",
- label: 'Run Python unit tests',
- )
-}
-
-def make_cpp_tests(image, build_dir) {
- sh (
- script: """
- set -eux
- ${docker_run} ${image} python3 ./tests/scripts/task_build.py \
- --sccache-bucket tvm-sccache-prod \
- --sccache-region us-west-2 \
- --cmake-target cpptest \
- --build-dir ${build_dir}
- """,
- label: 'Make C++ tests',
- )
-}
-
-def cmake_build(image, path) {
- sh (
- script: "${docker_run} --env CI_NUM_EXECUTORS ${image} ./tests/scripts/task_build.py --sccache-bucket tvm-sccache-prod --sccache-region us-west-2 --build-dir ${path}",
- label: 'Run CMake build',
- )
-}
diff --git a/ci/jenkins/templates/utils/Test.groovy.j2 b/ci/jenkins/templates/utils/Test.groovy.j2
deleted file mode 100644
index 48041983b9..0000000000
--- a/ci/jenkins/templates/utils/Test.groovy.j2
+++ /dev/null
@@ -1,6 +0,0 @@
-def cpp_unittest(image) {
- sh (
- script: "${docker_run} --env CI_NUM_EXECUTORS ${image} ./tests/scripts/task_cpp_unittest.sh",
- label: 'Run C++ tests',
- )
-}
diff --git a/ci/jenkins/templates/utils/base.groovy.j2 b/ci/jenkins/templates/utils/base.groovy.j2
deleted file mode 100644
index a8fda460b7..0000000000
--- a/ci/jenkins/templates/utils/base.groovy.j2
+++ /dev/null
@@ -1,111 +0,0 @@
-// -*- mode: groovy -*-
-
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-
-// Jenkins pipeline
-// See documents at https://jenkins.io/doc/book/pipeline/jenkinsfile/
-
-// Docker env used for testing
-// Different image may have different version tag
-// because some of them are more stable than anoter.
-//
-// Docker images are maintained by PMC, cached in dockerhub
-// and remains relatively stable over the time.
-// Flow for upgrading docker env(need commiter)
-//
-// - Send PR to upgrade build script in the repo
-// - Build the new docker image
-// - Tag the docker image with a new version and push to a binary cache.
-// - Update the version in the Jenkinsfile, send a PR
-// - Fix any issues wrt to the new image version in the PR
-// - Merge the PR and now we are in new version
-// - Tag the new version as the lates
-// - Periodically cleanup the old versions on local workers
-//
-
-// ============================= IMPORTANT NOTE =============================
-// This file is generated by 'jenkins/generate.py'. Do not edit this file directly!
-// Make edits to 'jenkins/Jenkinsfile.j2' and regenerate this with
-// 'python3 jenkins/generate.py'
-// Note: This timestamp is here to ensure that updates to the Jenkinsfile are
-// always rebased on main before merging:
-// Generated at {{ generated_time }}
-
-import org.jenkinsci.plugins.pipeline.modeldefinition.Utils
-{% import 'utils/macros.j2' as m with context -%}
-
-
-// These are set at runtime from data in ci/jenkins/docker-images.yml, update
-// image tags in that file
-ci_gpu = ''
-ci_cpu = ''
-ci_minimal = ''
-ci_wasm = ''
-ci_cortexm = ''
-ci_arm = ''
-ci_riscv = ''
-
-// Parameters to allow overriding (in Jenkins UI), the images
-// to be used by a given build. When provided, they take precedence
-// over default values above.
-properties([
- parameters([
- {% for image in images %}
- string(name: '{{ image.name }}_param', defaultValue: ''),
- {% endfor %}
- ])
-])
-
-// Placeholders for newly built Docker image names (if rebuild_docker_images
-// is used)
-{% for image in images %}
- built_{{ image.name }} = null;
-{% endfor %}
-
-// Global variable assigned during Sanity Check that holds the sha1 which should be
-// merged into the PR in all branches.
-upstream_revision = null
-
-// command to start a docker container
-docker_run = 'docker/bash.sh --env CI --env PLATFORM --env SKIP_SLOW_TESTS --env TEST_STEP_NAME'
-docker_build = 'docker/build.sh'
-// timeout in minutes
-max_time = 180
-rebuild_docker_images = false
-
-s3_bucket = 'tvm-jenkins-artifacts-prod'
-s3_prefix = "tvm/${env.BRANCH_NAME}/${env.BUILD_NUMBER}"
-
-// Jenkins script root directory
-jenkins_scripts_root = "ci/scripts/jenkins"
-
-
-// General note: Jenkins has limits on the size of a method (or top level code)
-// that are pretty strict, so most usage of groovy methods in these templates
-// are purely to satisfy the JVM
-{% include "utils/Prepare.groovy.j2" %}
-{% include "utils/Build.groovy.j2" %}
-{% include "utils/Test.groovy.j2" %}
-
-cancel_previous_build()
-
-try {
- prepare('CPU-SMALL-SPOT')
-} catch(Exception ex) {
- prepare('CPU-SMALL')
-}
diff --git a/ci/jenkins/templates/utils/macros.j2 b/ci/jenkins/templates/utils/macros.j2
deleted file mode 100644
index 959d91725f..0000000000
--- a/ci/jenkins/templates/utils/macros.j2
+++ /dev/null
@@ -1,169 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-
-{% macro per_exec_ws(folder) -%}
- "workspace/exec_${env.EXECUTOR_NUMBER}/{{ folder }}"
-{%- endmacro -%}
-
-{% macro test_step(name, ws, docker_image, platform, test_method_names, condition="!skip_ci && is_docs_only_build != 1") %}
-{% set method_name = "run_" + name.replace(":", "").replace(" ", "-").replace("-", "_") %}
-def {{ method_name }}(node_type) {
- echo 'Begin running on node_type ' + node_type
- if ({{ condition }}) {
- node(node_type) {
- ws({{ per_exec_ws(ws) }}) {
- // NOTE: if exception happens, it will be caught outside
- init_git()
- docker_init({{ docker_image }})
- timeout(time: max_time, unit: 'MINUTES') {
- withEnv([
- 'PLATFORM={{ platform }}',
- 'TEST_STEP_NAME={{ name }}',
- "SKIP_SLOW_TESTS=${skip_slow_tests}"], {
- {{ caller() | trim | indent(width=12) }}
- })
- }
- }
- }
- echo 'End running on node_type ' + node_type
- } else {
- Utils.markStageSkippedForConditional('{{ name }}')
- }
-}
-{% set _ = test_method_names.append((name, method_name)) %}
-
-{% endmacro %}
-
-{% macro invoke_build(name, condition, node, docker_image, ws, platform) %}
-def run_build(node_type) {
- if ({{ condition }}) {
- echo 'Begin running node_type ' + node_type
- node(node_type) {
- ws({{ per_exec_ws(ws) }}) {
- init_git()
- docker_init({{ docker_image }})
- timeout(time: max_time, unit: 'MINUTES') {
-
- withEnv([
- 'PLATFORM={{ platform }}',
- ], {
- {{ caller() | trim | indent(width=6) }}
- })
- }
- }
- }
- echo 'End running node_type ' + node_type
- } else {
- Utils.markStageSkippedForConditional('{{ name }}')
- }
-}
-def build() {
- stage('Build') {
- try {
- run_build('{{ node }}-SPOT')
- } catch (hudson.AbortException abortEx) {
- echo "Received normal AbortException, exit now. Details:" + abortEx.toString()
- throw abortEx
- } catch (Throwable ex) {
- echo 'Exception during SPOT run ' + ex.toString()
- if (is_last_build()) {
- // retry if we are currently at last build
- // mark the current stage as success
- // and try again via on demand node
- echo 'Retry on-demand given it is last build'
- currentBuild.result = 'SUCCESS'
- run_build('{{ node }}')
- } else {
- echo 'Exit since it is not last build'
- throw ex
- }
- }
- }
-}
-build()
-{% endmacro %}
-
-{% macro invoke_tests(node, test_method_names) %}
-def test() {
- stage('Test') {
- environment {
- SKIP_SLOW_TESTS = "${skip_slow_tests}"
- }
- parallel(
- {% for stage_name, method_name in test_method_names %}
- '{{ stage_name }}': {
- try {
- {{ method_name }}('{{ node }}-SPOT')
- } catch (Throwable ex) {
- echo 'Exception during SPOT run ' + ex.toString()
- if (is_last_build()) {
- // retry if at last build
- // mark the current stage as success
- // and try again via on demand node
- echo 'Retry on-demand given it is last build'
- currentBuild.result = 'SUCCESS'
- {{ method_name }}('{{ node }}')
- } else {
- echo 'Exit since it is not last build'
- throw ex
- }
- }
- },
- {% endfor %}
- )
- }
-}
-test()
-{% endmacro %}
-
-{% macro deploy_step(name, feature_flag, ws) %}
- '{{ name }}': {
- if ({{ feature_flag }}) {
- node('CPU') {
- ws({{ per_exec_ws(ws) }}) {
- timeout(time: max_time, unit: 'MINUTES') {
- {{ caller() | indent(width=10) | trim }}
- }
- }
- }
- } else {
- Utils.markStageSkippedForConditional('{{ name }}')
- }
- },
-{% endmacro %}
-
-{% macro upload_artifacts(tag, bundles=none, filenames=none) %}
-{% if bundles is not none %}
-sh(
- script: "./${jenkins_scripts_root}/s3.py --action upload --bucket ${s3_bucket} --prefix ${s3_prefix}/{{ tag }}{% for b in bundles %} --bundle {{ b }}{% endfor %}",
- label: 'Upload artifacts to S3',
- )
-{% elif filenames is not none %}
-{% set items = ' '.join(filenames) %}
-sh(
- script: "./${jenkins_scripts_root}/s3.py --action upload --bucket ${s3_bucket} --prefix ${s3_prefix}/{{ tag }} --items {{ items }}",
- label: 'Upload artifacts to S3',
- )
-{% endif %}
-{% endmacro %}
-
-{% macro download_artifacts(tag) %}
-sh(
- script: "./${jenkins_scripts_root}/s3.py --action download --bucket ${s3_bucket} --prefix ${s3_prefix}/{{ tag }}",
- label: 'Download artifacts from S3',
- )
-{% endmacro %}
diff --git a/ci/jenkins/templates/wasm_jenkinsfile.groovy.j2 b/ci/jenkins/templates/wasm_jenkinsfile.groovy.j2
deleted file mode 100644
index 8e7d909bd1..0000000000
--- a/ci/jenkins/templates/wasm_jenkinsfile.groovy.j2
+++ /dev/null
@@ -1,39 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-{% include "utils/base.groovy.j2" with context %}
-{% import 'utils/macros.j2' as m with context -%}
-
-{% call m.invoke_build(
- name='BUILD: WASM',
- node='CPU',
- condition='!skip_ci && is_docs_only_build != 1',
- ws='tvm/build-wasm',
- docker_image='ci_wasm',
- platform='wasm',
-) %}
- sh (
- script: "${docker_run} ${ci_wasm} ./tests/scripts/task_config_build_wasm.sh build",
- label: 'Create WASM CMake config',
- )
- cmake_build(ci_wasm, 'build')
- make_cpp_tests(ci_wasm, 'build')
- cpp_unittest(ci_wasm)
- sh (
- script: "${docker_run} ${ci_wasm} ./tests/scripts/task_web_wasm.sh",
- label: 'Run WASM lint and tests',
- )
-{% endcall %}
diff --git a/ci/scripts/package/README.md b/ci/package/README.md
similarity index 100%
rename from ci/scripts/package/README.md
rename to ci/package/README.md
diff --git a/ci/scripts/package/build-environment.yaml b/ci/package/build-environment.yaml
similarity index 100%
rename from ci/scripts/package/build-environment.yaml
rename to ci/package/build-environment.yaml
diff --git a/ci/scripts/package/manylinux_build_libtvm_runtime_cuda.sh b/ci/package/manylinux_build_libtvm_runtime_cuda.sh
similarity index 97%
rename from ci/scripts/package/manylinux_build_libtvm_runtime_cuda.sh
rename to ci/package/manylinux_build_libtvm_runtime_cuda.sh
index d0d847ae83..4f793ccfd7 100755
--- a/ci/scripts/package/manylinux_build_libtvm_runtime_cuda.sh
+++ b/ci/package/manylinux_build_libtvm_runtime_cuda.sh
@@ -25,7 +25,7 @@
# Usage: manylinux_build_libtvm_runtime_cuda.sh
set -euxo pipefail
-repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
build_dir="${repo_root}/build-wheel-cuda"
parallel="$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 4)"
diff --git a/ci/scripts/package/windows_build_libtvm_runtime_cuda.bat b/ci/package/windows_build_libtvm_runtime_cuda.bat
similarity index 97%
rename from ci/scripts/package/windows_build_libtvm_runtime_cuda.bat
rename to ci/package/windows_build_libtvm_runtime_cuda.bat
index 4864c18a80..0c375b441a 100644
--- a/ci/scripts/package/windows_build_libtvm_runtime_cuda.bat
+++ b/ci/package/windows_build_libtvm_runtime_cuda.bat
@@ -23,8 +23,8 @@ rem build-wheel-cuda\lib\ for the wheel build to bundle. Windows mirror of
rem manylinux_build_libtvm_runtime_cuda.sh. Run with: shell: cmd.
setlocal enableextensions
-rem repo root = this script's directory / ..\..\.. (native Windows paths; no cygpath).
-pushd "%~dp0..\..\.." || exit /b 1
+rem repo root = this script's directory / ..\.. (native Windows paths; no cygpath).
+pushd "%~dp0..\.." || exit /b 1
set "repo_root=%CD%"
popd
set "build_dir=%repo_root%\build-wheel-cuda"
diff --git a/ci/scripts/jenkins/cmd_utils.py b/ci/scripts/jenkins/cmd_utils.py
deleted file mode 100644
index e1cd8e9b20..0000000000
--- a/ci/scripts/jenkins/cmd_utils.py
+++ /dev/null
@@ -1,107 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-import logging
-import os
-import re
-import subprocess
-import sys
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-assert (REPO_ROOT / "Jenkinsfile").exists
-
-
-class RelativePathFilter(logging.Filter):
- def filter(self, record):
- path = Path(record.pathname).resolve()
- record.relativepath = str(path.relative_to(REPO_ROOT))
- return True
-
-
-def init_log():
- logging.basicConfig(
- format="[%(relativepath)s:%(lineno)d %(levelname)-1s] %(message)s", level=logging.INFO
- )
-
- # Flush on every log call (logging and then calling subprocess.run can make
- # the output look confusing)
- logging.root.handlers[0].addFilter(RelativePathFilter())
- logging.root.handlers[0].flush = sys.stderr.flush
-
-
-class Sh:
- def __init__(self, env=None, cwd=None):
- self.env = os.environ.copy()
- if env is not None:
- self.env.update(env)
- self.cwd = cwd
-
- def tee(self, cmd: str, **kwargs):
- """
- Run 'cmd' in a shell then return the (process, stdout) as a tuple
- """
-
- logging.info(f"+ {cmd}")
-
- kwargs = {
- **self._default_popen_flags(),
- **kwargs,
- "stdout": subprocess.PIPE,
- }
- proc = subprocess.Popen(cmd, **kwargs)
-
- stdout = []
-
- def _tee_output(s):
- stdout.append(s)
- print(s, end="")
-
- while proc.poll() is None:
- _tee_output(proc.stdout.readline())
- _tee_output(proc.stdout.read())
-
- stdout = "".join(stdout)
- if proc.returncode:
- raise subprocess.CalledProcessError(proc.returncode, proc.args, stdout)
-
- return proc, stdout
-
- def run(self, cmd: str, **kwargs):
- logging.info(f"+ {cmd}")
-
- kwargs = {
- **self._default_popen_flags(),
- "check": True,
- **kwargs,
- }
-
- return subprocess.run(cmd, **kwargs)
-
- def _default_popen_flags(self):
- return {
- "shell": True,
- "env": self.env,
- "encoding": "utf-8",
- "cwd": self.cwd,
- }
-
-
-def tags_from_title(title: str) -> list[str]:
- tags = re.findall(r"\[(.*?)\]", title)
- tags = [t.strip() for t in tags]
- return tags
diff --git a/ci/scripts/jenkins/git_change_docs.sh b/ci/scripts/jenkins/git_change_docs.sh
deleted file mode 100755
index 35b1bb7ec3..0000000000
--- a/ci/scripts/jenkins/git_change_docs.sh
+++ /dev/null
@@ -1,39 +0,0 @@
-#!/usr/bin/env bash
-
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-set -eux
-
-FOUND_ONE_FILE=0
-SAW_NON_DOC_CHANGES=0
-
-changed_files=$(git diff --no-commit-id --name-only -r origin/main)
-
-for file in $changed_files; do
- FOUND_ONE_FILE=1
- if ! grep -q "docs/" <<< "$file"; then
- SAW_NON_DOC_CHANGES=1
- break
- fi
-done
-
-if [ ${FOUND_ONE_FILE} -eq 0 ] || [ ${SAW_NON_DOC_CHANGES} -eq 1 ]; then
- exit 0
-else
- exit 1
-fi
diff --git a/ci/scripts/jenkins/open_docker_update_pr.py b/ci/scripts/jenkins/open_docker_update_pr.py
deleted file mode 100755
index 0172fe0221..0000000000
--- a/ci/scripts/jenkins/open_docker_update_pr.py
+++ /dev/null
@@ -1,214 +0,0 @@
-#!/usr/bin/env python3
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-import argparse
-import configparser
-import datetime
-import json
-import logging
-import os
-import re
-import shlex
-from collections.abc import Callable
-from typing import Any
-from urllib import error
-
-from cmd_utils import REPO_ROOT, Sh, init_log
-from git_utils import GitHubRepo, git, parse_remote
-from should_rebuild_docker import docker_api
-
-JENKINS_DIR = REPO_ROOT / "ci" / "jenkins"
-IMAGES_FILE = JENKINS_DIR / "docker-images.ini"
-GENERATE_SCRIPT = JENKINS_DIR / "generate.py"
-GITHUB_TOKEN = os.environ["GITHUB_TOKEN"]
-BRANCH = "nightly-docker-update"
-
-
-def _testing_docker_api(data: dict[str, Any]) -> Callable[[str], dict[str, Any]]:
- """Returns a function that can be used in place of docker_api"""
-
- def mock(url: str) -> dict[str, Any]:
- if url in data:
- return data[url]
- else:
- raise error.HTTPError(url, 404, f"Not found: {url}", {}, None)
-
- return mock
-
-
-def parse_docker_date(d: str) -> datetime.datetime:
- """Turn a date string from the Docker API into a datetime object"""
- return datetime.datetime.strptime(d, "%Y-%m-%dT%H:%M:%S.%fZ")
-
-
-def check_tag(tag: dict[str, Any]) -> bool:
- return re.match(r"^[0-9]+-[0-9]+-[a-z0-9]+$", tag["name"]) is not None
-
-
-def latest_tag(user: str, repo: str) -> list[dict[str, Any]]:
- """
- Queries Docker Hub and finds the most recent tag for the specified image/repo pair
- """
- r = docker_api(f"repositories/{user}/{repo}/tags")
- results = r["results"]
-
- for result in results:
- result["last_updated"] = parse_docker_date(result["last_updated"])
-
- results = list(sorted(results, key=lambda d: d["last_updated"]))
- results = [tag for tag in results if check_tag(tag)]
- return results[-1]
-
-
-def latest_tlcpackstaging_image(source: str) -> str | None:
- """
- Finds the latest full tag to use in the Jenkinsfile or returns None if no
- update is needed
- """
- name, current_tag = source.split(":")
- user, repo = name.split("/")
- logging.info(
- f"Running with name: {name}, current_tag: {current_tag}, user: {user}, repo: {repo}"
- )
-
- staging_repo = repo.replace("-", "_")
- latest_tlcpackstaging_tag = latest_tag(user="tlcpackstaging", repo=staging_repo)
- logging.info(f"Found latest tlcpackstaging tag:\n{latest_tlcpackstaging_tag}")
-
- if latest_tlcpackstaging_tag["name"] == current_tag:
- logging.info("tlcpackstaging tag is the same as the one in the Jenkinsfile")
-
- latest_tlcpack_tag = latest_tag(user="tlcpack", repo=repo)
- logging.info(f"Found latest tlcpack tag:\n{latest_tlcpack_tag}")
-
- if latest_tlcpack_tag["name"] == latest_tlcpackstaging_tag["name"]:
- logging.info("Tag names were the same, no update needed")
- return None
-
- if latest_tlcpack_tag["last_updated"] > latest_tlcpackstaging_tag["last_updated"]:
- new_spec = f"tlcpack/{repo}:{latest_tlcpack_tag['name']}"
- else:
- # Even if the image doesn't exist in tlcpack, it will fall back to tlcpackstaging
- # so hardcode the username here
- new_spec = f"tlcpack/{repo}:{latest_tlcpackstaging_tag['name']}"
- logging.info("Using tlcpackstaging tag on tlcpack")
-
- logging.info(f"Found newer image, using: {new_spec}")
- return new_spec
-
-
-if __name__ == "__main__":
- init_log()
- help = "Open a PR to update the Docker images to use the latest available in tlcpackstaging"
- parser = argparse.ArgumentParser(description=help)
- parser.add_argument("--remote", default="origin", help="ssh remote to parse")
- parser.add_argument("--dry-run", action="store_true", help="don't send PR to GitHub")
- parser.add_argument("--testing-docker-data", help="JSON data to mock Docker Hub API response")
- args = parser.parse_args()
-
- # Install test mock if necessary
- if args.testing_docker_data is not None:
- docker_api = _testing_docker_api(data=json.loads(args.testing_docker_data))
-
- remote = git(["config", "--get", f"remote.{args.remote}.url"])
- user, repo = parse_remote(remote)
-
- # Read the existing images from ci/jenkins/docker-images.ini.
- # The ini has a single ``[jenkins]`` section with a shared ``ci_tag`` key
- # and one ``ci_<name>: tlcpack/ci-<name>:%(ci_tag)s`` entry per image.
- # Resolve each image to its full spec (with interpolation applied) and
- # check against Docker Hub for newer tags.
- logging.info(f"Reading {IMAGES_FILE}")
- config = configparser.ConfigParser()
- config.read(IMAGES_FILE)
- with open(IMAGES_FILE) as f:
- content = f.read()
-
- replacements = {}
- for key in config.options("jenkins"):
- if key == "ci_tag":
- continue
- image_spec = config.get("jenkins", key)
- logging.info(f"Found {key} = {image_spec}")
- new_image = latest_tlcpackstaging_image(image_spec)
- if new_image is None:
- logging.info("No new image found")
- continue
- logging.info(f"Using new image {new_image}")
- # Rewrite the ``ci_<name>:`` line with the resolved tag (breaking
- # the ``%(ci_tag)s`` interpolation for that single entry) so the
- # update is unambiguous and doesn't disturb other images that share
- # the old tag.
- old_line_re = re.compile(rf"^{re.escape(key)}\s*[:=].*$", re.MULTILINE)
- new_line = f"{key}: {new_image}"
- replacements[old_line_re] = new_line
-
- # Re-generate the Jenkinsfiles
- command = f"python3 {shlex.quote(str(GENERATE_SCRIPT))}"
-
- for old_line_re, new_line in replacements.items():
- content = old_line_re.sub(new_line, content)
-
- print(f"Updated to:\n{content}")
-
- if args.dry_run:
- print(f"Would have run:\n{command}")
- else:
- with open(IMAGES_FILE, "w") as f:
- f.write(content)
- Sh().run(command)
-
- # Publish the PR
- title = "[ci][docker] Nightly Docker image update"
- body = "This bumps the Docker images to the latest versions from Docker Hub."
- message = f"{title}\n\n\n{body}"
-
- if args.dry_run:
- logging.info("Dry run, would have committed Jenkinsfiles")
- else:
- logging.info("Creating git commit")
- git(["checkout", "-B", BRANCH])
- git(["add", str(JENKINS_DIR.relative_to(REPO_ROOT))])
- git(["config", "user.name", "tvm-bot"])
- git(["config", "user.email", "95660001+tvm-bot@users.noreply.github.com"])
- git(["commit", "-m", message])
- git(["push", "--set-upstream", args.remote, BRANCH, "--force"])
-
- logging.info("Sending PR to GitHub")
- github = GitHubRepo(user=user, repo=repo, token=GITHUB_TOKEN)
- data = {
- "title": title,
- "body": body,
- "head": BRANCH,
- "base": "main",
- "maintainer_can_modify": True,
- }
- url = "pulls"
- if args.dry_run:
- logging.info(f"Dry run, would have sent {data} to {url}")
- else:
- try:
- github.post(url, data=data)
- except error.HTTPError as e:
- # Ignore the exception if the PR already exists (which gives a 422). The
- # existing PR will have been updated in place
- if e.code == 422:
- logging.info("PR already exists, ignoring error")
- logging.exception(e)
- else:
- raise e
diff --git a/ci/scripts/jenkins/should_run_slow_tests.py b/ci/scripts/jenkins/should_run_slow_tests.py
deleted file mode 100755
index 31126d7daf..0000000000
--- a/ci/scripts/jenkins/should_run_slow_tests.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/bin/env python3
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-import argparse
-import os
-import textwrap
-
-from git_utils import GitHubRepo, git, parse_remote
-
-SLOW_TEST_TRIGGERS = [
- "@tvm-bot run slow tests",
- "@tvm-bot run slow test",
- "@tvm-bot run slow",
- "@tvm-bot slow tests",
- "@tvm-bot slow test",
- "@tvm-bot slow",
-]
-
-
-def check_match(s: str, searches: list[str]) -> tuple[bool, str | None]:
- for search in searches:
- if search in s:
- return True, search
-
- return False, None
-
-
-def display(long_str: str) -> str:
- return textwrap.indent(long_str, " ")
-
-
-if __name__ == "__main__":
- help = "Exits with 1 if CI should run slow tests, 0 otherwise"
- parser = argparse.ArgumentParser(description=help)
- parser.add_argument("--pr", required=True)
- parser.add_argument("--remote", default="origin", help="ssh remote to parse")
- parser.add_argument(
- "--pr-body", help="(testing) PR body to use instead of fetching from GitHub"
- )
- args = parser.parse_args()
-
- branch = git(["rev-parse", "--abbrev-ref", "HEAD"])
-
- # Don't skip slow tests on main or ci-docker-staging
- skip_branches = {"main", "ci-docker-staging"}
- if branch in skip_branches:
- print(f"Branch {branch} is in {skip_branches}, running slow tests")
- exit(1)
- print(f"Branch {branch} is not in {skip_branches}, checking last commit...")
-
- if args.pr_body:
- body = args.pr_body
- else:
- remote = git(["config", "--get", f"remote.{args.remote}.url"])
- user, repo = parse_remote(remote)
-
- github = GitHubRepo(token=os.environ["GITHUB_TOKEN"], user=user, repo=repo)
- pr = github.get(f"pulls/{args.pr}")
- body = pr["body"]
-
- body_match, reason = check_match(body, SLOW_TEST_TRIGGERS)
-
- if body_match:
- print(f"Matched {reason} in PR body:\n{display(body)}, running slow tests")
- exit(1)
-
- print(
- f"PR Body:\n{display(body)}\ndid not have any of {SLOW_TEST_TRIGGERS}, skipping slow tests"
- )
- exit(0)
diff --git a/docker/bash.sh b/docker/bash.sh
index ff4c902fbc..86ba2c33ea 100755
--- a/docker/bash.sh
+++ b/docker/bash.sh
@@ -431,7 +431,7 @@ if [ -n "${EXPANDED_SHORTCUT}" ]; then
if [ "${CI+x}" == "x" ]; then
DOCKER_IMAGE_NAME="${EXPANDED_SHORTCUT}"
else
- python3 ci/scripts/jenkins/determine_docker_images.py "$DOCKER_IMAGE_NAME" 2> /dev/null
+ python3 ci/jenkins/scripts/determine_docker_images.py "$DOCKER_IMAGE_NAME" 2> /dev/null
DOCKER_IMAGE_NAME=$(cat ".docker-image-names/$DOCKER_IMAGE_NAME")
if [[ "$DOCKER_IMAGE_NAME" == *"tlcpackstaging"* ]]; then
echo "WARNING: resolved docker image to fallback tag in tlcpackstaging" >&2
diff --git a/docker/dev_common.sh b/docker/dev_common.sh
index 68799676a3..0f5be61f66 100755
--- a/docker/dev_common.sh
+++ b/docker/dev_common.sh
@@ -30,7 +30,7 @@ GIT_TOPLEVEL=$(cd $(dirname ${BASH_SOURCE[0]}) && git rev-parse --show-toplevel)
DOCKER_IS_ROOTLESS=$(docker info 2> /dev/null | grep 'Context: \+rootless' || true)
function lookup_image_spec() {
- img_spec=$(python3 "${GIT_TOPLEVEL}/ci/scripts/jenkins/determine_docker_images.py" \
+ img_spec=$(python3 "${GIT_TOPLEVEL}/ci/jenkins/scripts/determine_docker_images.py" \
--lookup-only "$1" 2>/dev/null)
if [ -n "${img_spec}" ]; then
has_similar_docker_image=1
diff --git a/docs/contribute/ci.rst b/docs/contribute/ci.rst
index 12cee2e5ee..09f921f0df 100644
--- a/docs/contribute/ci.rst
+++ b/docs/contribute/ci.rst
@@ -28,7 +28,7 @@ TVM uses a combination of Jenkins and GitHub Actions for continuous integration
- **Jenkins** runs Linux CI tests on
`branches <https://ci.tlcpack.ai/job/tvm/>`_ and
`pull requests <https://ci.tlcpack.ai/job/tvm/view/change-requests/>`_ through a
- build configuration specified in `Jenkinsfile templates <https://github.com/apache/tvm/blob/main/ci/jenkins/templates/>`_.
+ build configuration specified in `Jenkins pipelines <https://github.com/apache/tvm/blob/main/ci/jenkins/generated/>`_.
Jenkins is the primary CI step that is codified to block merging.
- **GitHub Actions** runs `linting <https://github.com/apache/tvm/blob/main/.github/workflows/lint.yml>`_
(via pre-commit hooks) on pushes and pull requests, as well as minimal
diff --git a/docs/contribute/testing.rst b/docs/contribute/testing.rst
index 44a996da01..d7e5c1b92f 100644
--- a/docs/contribute/testing.rst
+++ b/docs/contribute/testing.rst
@@ -233,7 +233,7 @@ Running in a Local Docker Container
The ``docker/bash.sh`` script can be used to run unit tests inside the
same docker image as is used by the CI. The first argument should
specify which docker image to run (e.g. ``docker/bash.sh ci_gpu``).
-Allowed image names are defined in ``ci/jenkins/data.py`` in the TVM source directory,
+Allowed image names are defined in ``ci/jenkins/docker-images.ini`` in the TVM source directory,
and map to images at `tlcpack`_.
If no additional arguments are given, the docker image will be loaded
diff --git a/pyproject.toml b/pyproject.toml
index 19874f2051..5c7512032f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -179,7 +179,7 @@ include = [
"tests/**/*.py",
"docs/**/*.py",
"apps/**/*.py",
- "ci/scripts/**/*.py",
+ "ci/**/*.py",
"conftest.py",
"jvm/**/*.py",
"web/tests/**/*.py",
diff --git a/tests/python/ci/test_ci.py b/tests/python/ci/test_ci.py
index c716bf1490..3b3a9cad2b 100644
--- a/tests/python/ci/test_ci.py
+++ b/tests/python/ci/test_ci.py
@@ -18,14 +18,11 @@
"""Test various CI scripts and GitHub Actions workflows"""
import json
-import os
import subprocess
from pathlib import Path
import pytest
-import tvm.testing
-
from .test_utils import JENKINS_SCRIPT_ROOT, TempGit, run_script
@@ -170,123 +167,6 @@ def assert_in(needle: str, haystack: str):
raise AssertionError(f"item not found:\n{needle}\nin:\n{haystack}")
-@pytest.mark.skipif(
- os.getenv("WHEEL_TEST", "").lower() in {"true", "1", "yes"},
- reason="Test not supported in wheel.",
-)
-@parameterize_named(
- same_tags=dict(
- tlcpackstaging_body={
- "results": [
- {
- "last_updated": "2022-06-01T00:00:00.123456Z",
- "name": "123-123-abc",
- },
- ]
- },
- tlcpack_body={
- "results": [
- {
- "last_updated": "2022-06-01T00:00:00.123456Z",
- "name": "123-123-abc",
- },
- ]
- },
- expected="Tag names were the same, no update needed",
- expected_images=[],
- ),
- staging_update=dict(
- tlcpackstaging_body={
- "results": [
- {
- "last_updated": "2022-06-01T01:00:00.123456Z",
- "name": "234-234-abc-staging",
- },
- {
- "last_updated": "2022-06-01T00:00:00.123456Z",
- "name": "456-456-abc",
- },
- ]
- },
- tlcpack_body={
- "results": [
- {
- "last_updated": "2022-06-01T00:00:00.123456Z",
- "name": "123-123-abc",
- },
- ]
- },
- expected="Using tlcpackstaging tag on tlcpack",
- expected_images=[
- "ci_arm: tlcpack/ci-arm:456-456-abc",
- ],
- ),
- tlcpack_update=dict(
- tlcpackstaging_body={
- "results": [
- {
- "last_updated": "2022-06-01T00:00:00.123456Z",
- "name": "123-123-abc",
- },
- ]
- },
- tlcpack_body={
- "results": [
- {
- "last_updated": "2022-06-01T00:01:00.123456Z",
- "name": "234-234-abc",
- },
- ]
- },
- expected="Found newer image, using: tlcpack",
- expected_images=[
- "ci_arm: tlcpack/ci-arm:234-234-abc",
- ],
- ),
-)
-def test_open_docker_update_pr(
- tmpdir_factory, tlcpackstaging_body, tlcpack_body, expected, expected_images
-):
- """Test workflow to open a PR to update Docker images"""
- tag_script = JENKINS_SCRIPT_ROOT / "open_docker_update_pr.py"
-
- git = TempGit(tmpdir_factory.mktemp("tmp_git_dir"))
- git.run("config", "user.name", "ci")
- git.run("config", "user.email", "email@example.com")
- images = [
- "ci_arm",
- "ci_cortexm",
- "ci_cpu",
- "ci_gpu",
- "ci_minimal",
- "ci_riscv",
- "ci_wasm",
- ]
-
- docker_data = {}
- for image in images:
- docker_data[f"repositories/tlcpackstaging/{image}/tags"] = tlcpackstaging_body
- docker_data[f"repositories/tlcpack/{image.replace('_', '-')}/tags"] = tlcpack_body
-
- proc = run_script(
- [
- tag_script,
- "--dry-run",
- "--testing-docker-data",
- json.dumps(docker_data),
- ],
- cwd=git.cwd,
- env={"GITHUB_TOKEN": "1234"},
- stderr=subprocess.STDOUT,
- )
-
- for line in expected_images:
- if line not in proc.stdout:
- raise RuntimeError(f"Missing line {line} in output:\n{proc.stdout}")
-
- assert_in(expected, proc.stdout)
-
-
@parameterize_named(
use_tlcpack=dict(
images=["ci_arm", "ci_cpu"],
@@ -423,4 +303,4 @@ def test_should_rebuild_docker(tmpdir_factory, changed_files, name, check, expec
if __name__ == "__main__":
- tvm.testing.main()
+ raise SystemExit(pytest.main([__file__]))
diff --git a/tests/python/ci/test_jenkins_helpers.py b/tests/python/ci/test_jenkins_helpers.py
new file mode 100644
index 0000000000..b9d26a78a0
--- /dev/null
+++ b/tests/python/ci/test_jenkins_helpers.py
@@ -0,0 +1,134 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Host-side Jenkins commands preserve retries, paths and build configuration."""
+
+import importlib.util
+import json
+import os
+import shutil
+import subprocess
+import sys
+
+import pytest
+
+from .test_utils import JENKINS_SCRIPT_ROOT, REPO_ROOT
+
+
+def load_s3():
+ spec = importlib.util.spec_from_file_location("jenkins_s3", JENKINS_SCRIPT_ROOT / "s3.py")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def executable(path, body):
+ path.write_text("#!/usr/bin/env python3\n" + body)
+ path.chmod(0o755)
+
+
+@pytest.mark.parametrize("failures", [2, 3])
+def test_s3_transfer_retries(tmp_path, monkeypatch, failures):
+ # Run the real retry.sh with fake AWS and sleep, without network or delays.
+ executable(
+ tmp_path / "aws",
+ """
+import json, os, pathlib, sys
+log = pathlib.Path(os.environ["AWS_LOG"])
+with log.open("a") as out:
+ out.write(json.dumps(sys.argv[1:]) + "\\n")
+attempt = len(log.read_text().splitlines())
+print("download: s3://bucket/file to file name")
+sys.exit(1 if attempt <= int(os.environ["FAILURES"]) else 0)
+""",
+ )
+ executable(
+ tmp_path / "sleep",
+ """
+import os, pathlib, sys
+with pathlib.Path(os.environ["SLEEP_LOG"]).open("a") as out:
+ out.write(sys.argv[1] + "\\n")
+""",
+ )
+ monkeypatch.setenv("PATH", f"{tmp_path}:{os.environ['PATH']}")
+ monkeypatch.setenv("FAILURES", str(failures))
+ monkeypatch.setenv("SLEEP_LOG", str(tmp_path / "sleeps"))
+ s3 = load_s3()
+ for transfer in range(2):
+ log = tmp_path / f"aws-{transfer}"
+ monkeypatch.setenv("AWS_LOG", str(log))
+ if failures == 3:
+ with pytest.raises(subprocess.CalledProcessError):
+ s3.s3("s3://bucket/file", "file name", False)
+ else:
+ assert s3.parse_output_files(s3.s3("s3://bucket/file", "file name", False))
+ commands = [json.loads(line) for line in log.read_text().splitlines()]
+ assert commands == [["s3", "cp", "--no-progress", "s3://bucket/file", "file name"]] * 3
+ delays = (tmp_path / "sleeps").read_text().splitlines()
+ assert len(delays) == 4
+ assert all(30 <= int(delay) <= 200 for delay in delays)
+
+
+def test_build_environment_and_target(tmp_path):
+ # Run the entry point in a minimal checkout, capturing the tool boundary.
+ script = tmp_path / "tests/scripts/task_build.py"
+ script.parent.mkdir(parents=True)
+ shutil.copy(REPO_ROOT / "tests/scripts/task_build.py", script)
+ (tmp_path / "build").mkdir()
+ executable(
+ tmp_path / "cmake",
+ """
+import json, os, pathlib, sys
+with pathlib.Path(os.environ["COMMAND_LOG"]).open("a") as out:
+ entry = [sys.argv[1:], os.getcwd(), os.environ["SCCACHE_BUCKET"], os.environ["CC"]]
+ out.write(json.dumps(entry) + "\\n")
+""",
+ )
+ executable(tmp_path / "sccache", "pass\n")
+ log = tmp_path / "commands"
+ env = dict(
+ os.environ,
+ PATH=f"{tmp_path}:{os.environ['PATH']}",
+ COMMAND_LOG=str(log),
+ AWS_ACCESS_KEY_ID="test",
+ CI_NUM_EXECUTORS="2",
+ VERBOSE="false",
+ )
+ subprocess.run(
+ [
+ sys.executable,
+ script,
+ "--debug",
+ "--cmake-target",
+ "cpptest",
+ "--sccache-bucket",
+ "test-cache",
+ ],
+ cwd=tmp_path,
+ env=env,
+ check=True,
+ )
+ configure, build = [json.loads(line) for line in log.read_text().splitlines()]
+ assert configure == [
+ ["-GNinja", "-DCMAKE_BUILD_TYPE=Debug", ".."],
+ str(tmp_path / "build"),
+ "test-cache",
+ "/opt/sccache/cc",
+ ]
+ assert build[0][:4] == ["--build", ".", "--", "cpptest"]
+ assert build[0][4].startswith("-j") and int(build[0][4][2:]) >= 1
+ assert len(build[0]) == 5
+ assert build[1:] == configure[1:]
diff --git a/tests/python/ci/test_tvmbot.py b/tests/python/ci/test_tvmbot.py
index ddd98b2a29..89ca2a1562 100644
--- a/tests/python/ci/test_tvmbot.py
+++ b/tests/python/ci/test_tvmbot.py
@@ -26,8 +26,6 @@ from typing import Any
import pytest
-import tvm
-
from .test_utils import GITHUB_SCRIPT_ROOT, TempGit, run_script
SUCCESS_EXPECTED_OUTPUT = """
@@ -54,7 +52,7 @@ class _TvmBotTest:
os.getenv("WHEEL_TEST", "").lower() in {"true", "1", "yes"},
reason="Test not supported in wheel.",
)
- def test(self, tmpdir_factory):
+ def test_command(self, tmpdir_factory):
"""
Run the tvm-bot script using the data from preprocess_data
"""
@@ -284,4 +282,4 @@ class TestIgnoreJobs(_TvmBotTest):
if __name__ == "__main__":
- tvm.testing.main()
+ raise SystemExit(pytest.main([__file__]))
diff --git a/tests/python/ci/test_utils.py b/tests/python/ci/test_utils.py
index 9c54fcd309..946e72fa6b 100644
--- a/tests/python/ci/test_utils.py
+++ b/tests/python/ci/test_utils.py
@@ -25,8 +25,8 @@ import subprocess
from typing import Any
REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent.parent.parent
-GITHUB_SCRIPT_ROOT = REPO_ROOT / "ci" / "scripts" / "github"
-JENKINS_SCRIPT_ROOT = REPO_ROOT / "ci" / "scripts" / "jenkins"
+GITHUB_SCRIPT_ROOT = REPO_ROOT / "ci" / "github"
+JENKINS_SCRIPT_ROOT = REPO_ROOT / "ci" / "jenkins" / "scripts"
class TempGit:
diff --git a/tests/scripts/release/gather_prs.py b/tests/scripts/release/gather_prs.py
index f12fc318d0..ed77de41cc 100644
--- a/tests/scripts/release/gather_prs.py
+++ b/tests/scripts/release/gather_prs.py
@@ -21,15 +21,15 @@ import argparse
import csv
import os
import pickle
+import re
import sys
from collections.abc import Callable
from pathlib import Path
from typing import Any
REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-sys.path.append(str(REPO_ROOT / "ci" / "scripts" / "jenkins"))
+sys.path.append(str(REPO_ROOT / "ci" / "github"))
-from cmd_utils import tags_from_title
from git_utils import GitHubRepo, git
GITHUB_TOKEN = os.environ["GITHUB_TOKEN"]
@@ -161,7 +161,7 @@ def write_csv(
if len(nodes) == 0:
continue
pr = nodes[0]
- tags = tags_from_title(pr["title"])
+ tags = [tag.strip() for tag in re.findall(r"\[(.*?)\]", pr["title"])]
actual_tags = []
for t in tags:
items = [x.strip() for x in t.split(",")]
diff --git a/tests/scripts/release/make_notes.py b/tests/scripts/release/make_notes.py
index d5fca9543a..603b917478 100644
--- a/tests/scripts/release/make_notes.py
+++ b/tests/scripts/release/make_notes.py
@@ -24,11 +24,6 @@ import sys
from collections import defaultdict
from pathlib import Path
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-sys.path.append(str(REPO_ROOT / "tests" / "scripts"))
-sys.path.append(str(REPO_ROOT / "tests" / "scripts" / "github"))
-sys.path.append(str(REPO_ROOT / "tests" / "scripts" / "jenkins"))
-
# Tag dictionary used to create a mapping relation to categorize PRs owning same tag.
TAG_DICT = {
"metaschedule": "MetaSchedule",
diff --git a/tests/scripts/setup-pytest-env.sh b/tests/scripts/setup-pytest-env.sh
index 171ddbc2d0..c62b770baf 100755
--- a/tests/scripts/setup-pytest-env.sh
+++ b/tests/scripts/setup-pytest-env.sh
@@ -39,7 +39,7 @@ function cleanup() {
set +x
if [ "${#pytest_errors[@]}" -gt 0 ]; then
echo "These pytest invocations failed, the results can be found in the Jenkins 'Tests' tab or by scrolling up through the raw logs here."
- python3 ci/scripts/jenkins/pytest_wrapper.py "${pytest_errors[@]}"
+ printf '%s\n' "${pytest_errors[@]}"
exit 1
fi
set -x
diff --git a/tests/scripts/task_build.py b/tests/scripts/task_build.py
index c6c30c9bbd..c240ec51c0 100755
--- a/tests/scripts/task_build.py
+++ b/tests/scripts/task_build.py
@@ -15,22 +15,20 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-# ruff: noqa: E402
import argparse
import logging
import multiprocessing
import os
import shutil
-import sys
+import subprocess
from pathlib import Path
-# Hackery to enable importing of utils from ci/scripts/jenkins
REPO_ROOT = Path(__file__).resolve().parent.parent.parent
-sys.path.append(str(REPO_ROOT / "ci" / "scripts" / "jenkins"))
-from cmd_utils import REPO_ROOT, Sh, init_log
if __name__ == "__main__":
- init_log()
+ logging.basicConfig(
+ format="[%(filename)s:%(lineno)d %(levelname)s] %(message)s", level=logging.INFO
+ )
parser = argparse.ArgumentParser(description="List pytest nodeids for a folder")
parser.add_argument("--sccache-bucket", required=False, help="sccache bucket name")
@@ -48,7 +46,7 @@ if __name__ == "__main__":
use_sccache = sccache_exe is not None
build_dir = Path(os.getcwd()) / args.build_dir
build_dir = build_dir.relative_to(REPO_ROOT)
- env = {}
+ env = os.environ.copy()
if use_sccache:
if args.sccache_bucket and "AWS_ACCESS_KEY_ID" in os.environ:
@@ -70,12 +68,10 @@ if __name__ == "__main__":
reason = "<unknown>"
logging.info(f"Not using sccache, reason: {reason}")
- sh = Sh(env)
-
if use_sccache:
- sh.run("sccache --start-server", check=False)
+ subprocess.run(["sccache", "--start-server"], env=env, check=False)
logging.info("===== sccache stats =====")
- sh.run("sccache --show-stats")
+ subprocess.run(["sccache", "--show-stats"], env=env, check=True)
executors = int(os.environ.get("CI_NUM_EXECUTORS", 1))
build_platform = os.environ.get("PLATFORM", None)
@@ -85,22 +81,21 @@ if __name__ == "__main__":
available_cpus = nproc // executors
num_cpus = max(available_cpus, 1)
- if args.debug:
- sh.run("cmake -GNinja -DCMAKE_BUILD_TYPE=Debug ..", cwd=build_dir)
- else:
- sh.run("cmake -GNinja -DCMAKE_BUILD_TYPE=RelWithDebInfo ..", cwd=build_dir)
+ build_type = "Debug" if args.debug else "RelWithDebInfo"
+ subprocess.run(
+ ["cmake", "-GNinja", f"-DCMAKE_BUILD_TYPE={build_type}", ".."],
+ cwd=build_dir,
+ env=env,
+ check=True,
+ )
- target = ""
+ ninja_args = [f"-j{num_cpus}"]
if args.cmake_target:
- target = args.cmake_target
-
- verbose = os.environ.get("VERBOSE", "true").lower() in {"1", "true", "yes"}
- ninja_args = [target, f"-j{num_cpus}"]
- if verbose:
+ ninja_args.insert(0, args.cmake_target)
+ if os.environ.get("VERBOSE", "true").lower() in {"1", "true", "yes"}:
ninja_args.append("-v")
-
- sh.run("cmake --build . -- " + " ".join(ninja_args), cwd=build_dir)
+ subprocess.run(["cmake", "--build", ".", "--", *ninja_args], cwd=build_dir, env=env, check=True)
if use_sccache:
logging.info("===== sccache stats =====")
- sh.run("sccache --show-stats")
+ subprocess.run(["sccache", "--show-stats"], env=env, check=True)