Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ updates:
directory: "/" # This points to .github/workflows
schedule:
interval: "daily"
cooldown:
default-days: 7
24 changes: 24 additions & 0 deletions .github/workflows/lava-pr-approval.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
# SPDX-License-Identifier: BSD-3-Clause
name: LAVA PR approval
run-name: 'LAVA PR approval - PR #${{ github.event.pull_request.number }} review ${{ github.event.review.id }} - ${{ github.event.review.state }}'

on:
pull_request_review:
types: [submitted]

permissions: {}

jobs:
approved:
if: >-
github.repository == 'qualcomm-linux/qcom-linux-testkit' &&
github.event.review.state == 'approved' &&
github.event.pull_request.base.ref == 'main' &&
!github.event.pull_request.draft
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
# Fork reviews have a read-only token. This job never checks out PR code,
# uses secrets or submits jobs. The trusted workflow revalidates the IDs.
- run: echo 'Approval recorded for trusted validation dispatch.'
48 changes: 48 additions & 0 deletions .github/workflows/lava-pr-approved.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
# SPDX-License-Identifier: BSD-3-Clause
name: Dispatch approved LAVA PR

on:
# Fork reviews cannot dispatch with their read-only token. The privileged
# handler uses default-branch code and no PR artifacts, caches or commands.
# API checks bind the approval to a repository writer and the current PR SHA.
workflow_run: # zizmor: ignore[dangerous-triggers] Required trusted handoff for fork approvals, inputs are revalidated.
workflows: [LAVA PR approval]
types: [completed]

permissions:
contents: read
pull-requests: read
actions: write
checks: write

# Serialize repeated approval notifications for the same source branch only.
# Different PR branches do not compete for one global pending slot.
concurrency:
group: lava-approval-${{ github.event.workflow_run.head_repository.full_name }}-${{ github.event.workflow_run.head_branch }}
cancel-in-progress: false
queue: max

jobs:
dispatch:
if: >-
github.repository == 'qualcomm-linux/qcom-linux-testkit' &&
github.event.workflow_run.event == 'pull_request_review' &&
github.event.workflow_run.conclusion == 'success' &&
endsWith(github.event.workflow_run.display_title, ' - approved')
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout trusted controller
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
ref: ${{ github.sha }}
persist-credentials: false
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7
with:
python-version: '3.11'
- run: python -m pip install -r .github/ci/lava-pr-requirements.txt
- name: Revalidate approval and dispatch changed PR tests
env:
GH_TOKEN: ${{ github.token }}
run: python .github/workflows/lava_pr_validation.py approve
12 changes: 10 additions & 2 deletions .github/workflows/lava-pr-validation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,11 @@ permissions:
contents: read
actions: read

# Keep one controller active across manual invocations and cleanup.
# Different PRs may validate together. Keep submissions for one PR serialized.
concurrency:
group: testkit-lava-foundries
group: testkit-lava-foundries-pr-${{ inputs.pr }}
cancel-in-progress: false
queue: max

jobs:
request:
Expand All @@ -74,6 +75,7 @@ jobs:
sha: ${{ steps.context.outputs.sha }}
context_attempt: ${{ steps.context.outputs.context_attempt }}
include_meta_qcom: ${{ steps.context.outputs.include_meta_qcom }}
validation_slot: ${{ steps.context.outputs.validation_slot }}
steps:
- name: Checkout trusted controller
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
Expand Down Expand Up @@ -110,6 +112,12 @@ jobs:
if: github.repository == 'qualcomm-linux/qcom-linux-testkit' && github.ref == 'refs/heads/main'
environment: lava-foundries
runs-on: ubuntu-latest
# Three native queues cap validation jobs across manual and approval runs.
# Pending jobs wait without occupying a hosted runner or replacing each other.
concurrency:
group: testkit-lava-foundries-slot-${{ needs.request.outputs.validation_slot }}
cancel-in-progress: false
queue: max
# Hosted jobs are limited to six hours. The five-hour request deadline
# leaves time for preparation, cancellation, collection and artifact upload.
timeout-minutes: 350
Expand Down
120 changes: 115 additions & 5 deletions .github/workflows/lava_pr_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
# SPDX-License-Identifier: BSD-3-Clause

"""Trusted manual LAVA controller and independent finalizer. Never run PR code here."""
"""Trusted LAVA dispatch, controller and finalizer. Never run PR code here."""

import argparse
from collections import Counter
Expand Down Expand Up @@ -155,6 +155,106 @@ def github():
return API(GITHUB, os.environ.get("GH_TOKEN", ""))


def dispatch_approval():
"""Revalidate a review notification, then dispatch one PR-only run per approved SHA."""
if os.environ.get("GITHUB_EVENT_NAME") != "workflow_run" or os.environ.get("GITHUB_REPOSITORY") != REPOSITORY:
raise ValueError("Approval dispatch requires this repository's trusted workflow_run event")
event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text(encoding="utf-8"))
run_id = str(event.get("workflow_run", {}).get("id", ""))
if not re.fullmatch(r"[1-9][0-9]{0,19}", run_id):
raise ValueError("Invalid approval workflow run ID")
gh = github()
endpoint = f"/repos/{REPOSITORY}"
workflow = gh.get(f"{endpoint}/actions/workflows/lava-pr-approval.yml")
run = gh.get(f"{endpoint}/actions/runs/{run_id}")
if (run.get("repository", {}).get("full_name") != REPOSITORY or
run.get("workflow_id") != workflow["id"] or
run.get("path") != ".github/workflows/lava-pr-approval.yml" or
run.get("event") != "pull_request_review" or
run.get("status") != "completed" or run.get("conclusion") != "success"):
raise ValueError("The notification is not a completed approval workflow")
# Treat the run title only as untrusted numeric lookup hints. GitHub's review
# and permission APIs, not the PR-controlled workflow, authorize dispatch.
match = re.fullmatch(r"LAVA PR approval - PR #([1-9][0-9]*) review ([1-9][0-9]*) - approved",
run.get("display_title", ""))
if not match:
raise ValueError("The approval notification has no valid PR and review IDs")
number, review_id = match.groups()
pr = gh.get(f"{endpoint}/pulls/{number}")
review = gh.get(f"{endpoint}/pulls/{number}/reviews/{review_id}")
sha = pr["head"]["sha"]
if (pr["state"] != "open" or pr.get("draft") or pr["base"]["ref"] != "main" or
pr["base"]["repo"]["full_name"] != REPOSITORY or
review.get("state") != "APPROVED" or review.get("commit_id") != sha):
print("Approval is stale, dismissed, or not for an open ready PR targeting main. No jobs dispatched.")
return
if not re.fullmatch(r"[0-9a-f]{40}", sha):
raise ValueError("The approved revision is not a full commit SHA")
reviewer = review["user"]
if (reviewer["id"] != run.get("actor", {}).get("id") or
pr["head"]["ref"] != run.get("head_branch")):
raise ValueError("Review author or source branch does not match the triggering run")
# pull_request_review uses a PR merge commit. Some run responses expose the
# head SHA directly, accept only that SHA or a merge whose second parent is it.
if run.get("head_sha") != sha:
commit = gh.get(f"{endpoint}/git/commits/{run['head_sha']}")
parents = commit.get("parents", [])
if len(parents) != 2 or parents[1].get("sha") != sha:
raise ValueError("Approval workflow is not bound to the reviewed revision")
permission = gh.get(f"{endpoint}/collaborators/{reviewer['login']}/permission")
if permission.get("permission") not in {"write", "maintain", "admin"}:
print("Automatic hardware validation requires approval from a repository writer or maintainer.")
return
reviews = [item for item in gh.pages(f"{endpoint}/pulls/{number}/reviews", per_page=100)
if item["user"]["id"] == reviewer["id"] and item["state"] not in {"COMMENTED", "PENDING"}]
if not reviews or max(reviews, key=lambda item: item["id"])["id"] != int(review_id):
print("A newer review supersedes this approval. No jobs dispatched.")
return
files = list(gh.pages(f"{endpoint}/pulls/{number}/files", per_page=100))
if len(files) != pr["changed_files"]:
raise ValueError("The complete PR file list is unavailable, use manual test selection")
config = json.loads((Path(__file__).resolve().parents[1] / "ci/lava-pr-validation.json").read_text(encoding="utf-8"))
if not any(item["status"] != "removed" and not item["filename"].lower().endswith((".md", ".rst")) and
(item["filename"].startswith("Runner/suites/") or item["filename"] in config["associations"])
for item in files):
print("No changed suites or configured associations. Use manual test_names for shared-only changes.")
return
marker = f"testkit-lava-approval:{number}:{sha}"
checks = list(gh.pages(f"{endpoint}/commits/{sha}/check-runs", "check_runs", per_page=100, filter="all"))
claims = [check for check in checks if check.get("external_id") == marker and
check.get("app", {}).get("slug") == "github-actions"]
if any(check.get("conclusion") != "failure" for check in claims):
print("This approved revision already has an automatic dispatch. Use a manual run for another validation.")
return
# Record intent before POST. An interrupted or ambiguous dispatch must not
# submit duplicate hardware work when another approval notification arrives.
claim = gh.request("POST", f"{endpoint}/check-runs", json=dict(
name="LAVA approval dispatch", head_sha=sha, external_id=marker, status="completed", conclusion="neutral",
details_url=f"https://github.com/{REPOSITORY}/actions/runs/{os.environ['GITHUB_RUN_ID']}",
output=dict(title="LAVA approval dispatch reserved", summary=(
"Automatic dispatch reserved. If this workflow does not confirm acceptance, use a manual validation run."
)))).json()
inputs = dict(pr=number, revision=sha, targets="meta-qcom", include_meta_qcom="false",
distro="meta-qcom-main", image_type="base", submit="true", selections="{}")
try:
gh.request("POST", f"{endpoint}/actions/workflows/lava-pr-validation.yml/dispatches",
json=dict(ref="main", inputs=inputs))
except APIError as failure:
if failure.status in {400, 401, 403, 404, 422}:
gh.request("PATCH", f"{endpoint}/check-runs/{claim['id']}", json=dict(
status="completed", conclusion="failure", output=dict(title="LAVA approval dispatch rejected",
summary="GitHub rejected the workflow dispatch. Correct access or inputs, then rerun the approval workflow.")))
raise
gh.request("PATCH", f"{endpoint}/check-runs/{claim['id']}", json=dict(
status="completed", conclusion="neutral", output=dict(title="LAVA approval dispatched",
summary="PR-only validation requested. Hardware results are reported by the separate LAVA PR validation check.")))
message = f"Dispatched PR #{number} at {sha}, changed tests only, latest meta-qcom-main base images."
print(message)
if os.environ.get("GITHUB_STEP_SUMMARY"):
with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as summary:
summary.write(message + "\n")


def previous_request(gh, run_id, attempt, kind="request", filename="manifest.json"):
"""Freeze reruns to the most recent immutable request from this workflow run."""
if int(attempt) == 1:
Expand Down Expand Up @@ -249,9 +349,13 @@ def begin_request(folder):
gh = github()
run_id = os.environ["VALIDATION_RUN_ID"]
attempt = os.environ["GITHUB_RUN_ATTEMPT"]
run_number = os.environ["GITHUB_RUN_NUMBER"]
number = os.environ["PR_NUMBER"]
if any(not re.fullmatch(r"[1-9][0-9]{0,19}", value) for value in (run_id, attempt, number)):
raise ValueError("Invalid run, attempt or PR number")
if any(not re.fullmatch(r"[1-9][0-9]{0,19}", value) for value in (run_id, attempt, run_number, number)):
raise ValueError("Invalid run, attempt, workflow run number or PR number")
# Run numbers distribute new requests over three queues and stay fixed on
# reruns. GitHub holds each queue's lock for the entire validation job.
validation_slot = (int(run_number) - 1) % 3 + 1
pr = gh.get(f"/repos/{REPOSITORY}/pulls/{number}")
if pr["state"] != "open" or pr["base"]["ref"] != "main":
raise ValueError("Select an open PR targeting main")
Expand Down Expand Up @@ -280,7 +384,10 @@ def begin_request(folder):
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output:
output.write(f"sha={sha}\ncontext_attempt={attempt}\n")
output.write(f"include_meta_qcom={str(include_meta_qcom).lower()}\n")
update_validation_status(gh, context, "queued", "Waiting for a runner to prepare and submit the selected LAVA tests.")
output.write(f"validation_slot={validation_slot}\n")
message = f"Waiting for hosted validation slot {validation_slot}/3 to prepare the selected LAVA tests."
print(message)
update_validation_status(gh, context, "queued", message)


def resolve_request():
Expand Down Expand Up @@ -1325,7 +1432,7 @@ def finish_jobs(folder, manifest, lifecycle=True):

def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=["begin", "start", "preflight", "plans", "prepare", "validate", "run", "resolve",
parser.add_argument("command", choices=["approve", "begin", "start", "preflight", "plans", "prepare", "validate", "run", "resolve",
"collect", "publish", "finish", "cleanup"])
parser.add_argument("--output", type=Path, default=Path("lava-output"))
args = parser.parse_args()
Expand All @@ -1344,6 +1451,9 @@ def main():

def execute(args):
"""Run one controller stage, preserving failures at the CLI boundary."""
if args.command == "approve":
dispatch_approval()
return 0
if args.command == "begin":
begin_request(args.output)
return 0
Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/shellcheck.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ on:
branches: [ "main" ]
workflow_dispatch:

permissions:
contents: read

jobs:
shellcheck:
# Ubuntu 24.04 provides the pinned ShellCheck 0.9.0-1 package below.
Expand All @@ -21,6 +24,7 @@ jobs:
uses: actions/checkout@v7
with:
fetch-depth: 0
persist-credentials: false

- name: Install ShellCheck from apt
run: |
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/test-inventory-pages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
persist-credentials: false

- name: Setup Python
uses: actions/setup-python@v7
Expand Down
7 changes: 6 additions & 1 deletion .github/workflows/weekly-testkit-snapshot-tag.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ jobs:
with:
ref: main
fetch-depth: 0
persist-credentials: false

- name: Compute tag
id: tag
Expand Down Expand Up @@ -136,12 +137,16 @@ jobs:
shell: bash
env:
TAG_NAME: ${{ steps.tag.outputs.tag }}
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail

TAG="$TAG_NAME"

git push origin "$TAG"
# Supply credentials only to this push, without saving them in Git config.
git -c credential.helper= \
-c 'credential.helper=!gh auth git-credential' \
push origin "$TAG"

- name: Verify remote tag
shell: bash
Expand Down
32 changes: 12 additions & 20 deletions .github/workflows/zstd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
persist-credentials: false

- name: Install zstd
run: |
Expand All @@ -28,7 +30,7 @@ jobs:
id: version
run: |
TAG="${GITHUB_REF#refs/tags/}" # e.g. v1.2.3
echo "tag_name=$TAG" >> $GITHUB_OUTPUT
echo "tag_name=$TAG" >> "$GITHUB_OUTPUT"

- name: Create .tar.zst archive
env:
Expand All @@ -39,23 +41,13 @@ jobs:
"$TAG_NAME" \
| zstd -o "${GITHUB_WORKSPACE}/${TAG_NAME}.tar.zst"

- name: Create GitHub Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.PAT }} # your PAT secret with repo scope
with:
tag_name: ${{ steps.version.outputs.tag_name }}
release_name: Release ${{ steps.version.outputs.tag_name }}
draft: false
prerelease: false

- name: Upload .tar.zst to GitHub Release
uses: actions/upload-release-asset@v1
- name: Publish GitHub release and archive
env:
GITHUB_TOKEN: ${{ secrets.PAT }} # same PAT here
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ${{ github.workspace }}/${{ steps.version.outputs.tag_name }}.tar.zst
asset_name: ${{ steps.version.outputs.tag_name }}.tar.zst
asset_content_type: application/zstd
GH_TOKEN: ${{ secrets.PAT }}
TAG_NAME: ${{ steps.version.outputs.tag_name }}
run: |
gh release create "$TAG_NAME" "${GITHUB_WORKSPACE}/${TAG_NAME}.tar.zst" \
--repo "$GITHUB_REPOSITORY" \
--verify-tag \
--title "Release $TAG_NAME" \
--notes ""
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,17 @@ automatically. Uncheck `include_meta_qcom` to omit baseline tests. Advanced
`selections` JSON remains available for parameters, tags or fresh-boot tests,
but a suite must not appear in both inputs.

Approval by a repository writer or maintainer automatically requests one
PR-only validation per approved commit, using the latest `meta-qcom-main`
base multimedia images and enabled targets. Stale approvals and changes with
no suite or configured association do not submit jobs. Shared-only changes,
overlay images and tests needing explicit parameters use the manual workflow.
Up to three validation jobs run concurrently on GitHub-hosted `ubuntu-latest`
runners. Requests enter three queues in round-robin order, with up to 100 pending
jobs per queue. A request waits for its assigned queue, even if another queue is
idle. Runs for the same PR remain serialized. Short request, reporting and
recovery jobs run separately, and LAVA schedules the selected board jobs.

Other CI systems can invoke the same suites and collect their result files
and artifacts.

Expand Down
Loading