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
121 changes: 121 additions & 0 deletions .github/scripts/actions-timings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
#!/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.

"""Export per-job queue, preparation and verification seconds using the GitHub API.

Usage: python3 .github/scripts/actions-timings.py --repo apache/shenyu --limit 50 > timings.csv
Queue includes dependency wait; runner_queue_seconds shows the API-observable runner wait.
Verification is the duration of test/check steps, including compilation within those steps.
Image builds, tool installation, deployment, cache handling and post steps are preparation.
Failed, skipped and cancelled runs remain visible and must not be averaged with successful runs.
"""

import argparse
import concurrent.futures
import csv
import datetime
import json
import re
import subprocess
import sys
import time

VERIFY = re.compile(
r"^(?:Run (?:test|Maven tests|E2E Tests|Java 21 compatibility tests|Apache RAT)|"
r"Build with Maven$|Replay registration contract|Check resolved registry|"
r"Check Agent|Check License|Check WAT|Verify list/detail|Run native fresh|"
r"Check harness|Build disposable Admin|Perform CodeQL|Test |Check test result|"
r"Cluster Test|Require every|checking job status|python3 .*test-)", re.IGNORECASE)


def api(path):
"""Retry transient API failures once, respecting the repository's backoff policy."""
for attempt in range(2):
result = subprocess.run(["gh", "api", path], text=True, capture_output=True)
if result.returncode == 0:
return json.loads(result.stdout)
if attempt == 0 and re.search(r"429|5\d\d|timeout|timed out", result.stderr, re.IGNORECASE):
time.sleep(20 if "429" in result.stderr else 2)
continue
raise RuntimeError(result.stderr.strip())


def seconds(start, end):
"""Incomplete/skipped timestamps have no measurable duration."""
if not start or not end:
return 0
return max(0, (datetime.datetime.fromisoformat(end.replace("Z", "+00:00"))
- datetime.datetime.fromisoformat(start.replace("Z", "+00:00"))).total_seconds())


def row(run, job, repo):
"""Partition the job's lifetime, retaining skipped jobs as zero-duration rows."""
elapsed = seconds(job.get("started_at"), job.get("completed_at"))
verification = 0
for step in job.get("steps", []):
if step.get("conclusion") == "skipped":
continue
name = step["name"]
# Build-only jobs use this same label; their tests are disabled explicitly.
if name == "Build with Maven" and not (run["name"] == "ci" and job["name"] == "pr_build"):
continue
if VERIFY.search(name):
verification += seconds(step.get("started_at"), step.get("completed_at"))
skipped = job.get("conclusion") == "skipped"
queue = 0 if skipped else seconds(run["created_at"], job.get("started_at"))
runner_queue = 0 if skipped else seconds(job.get("created_at"), job.get("started_at"))
return {
"repository": repo, "run_id": run["id"], "attempt": run["run_attempt"],
"workflow": run["name"], "event": run["event"], "sha": run["head_sha"],
"job_id": job["id"], "job": job["name"], "status": job["status"],
"conclusion": job.get("conclusion"), "queue_seconds": queue,
"runner_queue_seconds": runner_queue, "preparation_seconds": max(0, elapsed - verification),
"verification_seconds": verification, "url": job["html_url"],
}


def collect(repo, run):
jobs = []
page = 1
while True:
response = api(f"repos/{repo}/actions/runs/{run['id']}/jobs?per_page=100&page={page}")
jobs.extend(response["jobs"])
if len(jobs) >= response["total_count"]:
return [row(run, job, repo) for job in jobs]
page += 1


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo", default="apache/shenyu")
parser.add_argument("--limit", type=int, default=50, choices=range(1, 101))
parser.add_argument("--run", action="append", type=int, help="Inspect specific run IDs instead of recent runs")
args = parser.parse_args()
if args.run:
runs = [api(f"repos/{args.repo}/actions/runs/{run_id}") for run_id in args.run]
else:
runs = api(f"repos/{args.repo}/actions/runs?per_page={args.limit}")["workflow_runs"]
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as pool:
results = list(pool.map(lambda run: collect(args.repo, run), runs))
rows = [item for group in results for item in group]
if rows:
writer = csv.DictWriter(sys.stdout, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)


if __name__ == "__main__":
main()
20 changes: 20 additions & 0 deletions .github/scripts/expand-ci-module-roots.sh
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,18 @@ set -euo pipefail

group_roots="${GROUP_ROOTS:-}"
modules=()
excludes=()

add_module() {
local module="$1"
local existing
local excluded

for excluded in ${excludes[@]+"${excludes[@]}"}; do
if [[ "${module}" == "${excluded}" || "${module}" == "${excluded}/"* ]]; then
return
fi
done

for existing in "${modules[@]}"; do
if [[ "${existing}" == "${module}" ]]; then
Expand All @@ -34,8 +42,20 @@ add_module() {
}

IFS=',' read -ra roots <<< "${group_roots}"
# Move a slow subtree into its own shard without duplicating the remaining roots.
for root in "${roots[@]}"; do
if [[ "${root}" == \!* ]]; then
excluded="${root#\!}"
if [[ ! -f "${excluded}/pom.xml" ]]; then
echo "Excluded Maven module root is missing: ${excluded}" >&2
exit 1
fi
excludes+=("${excluded}")
fi
done
for root in "${roots[@]}"; do
[[ -n "${root}" ]] || continue
[[ "${root}" != \!* ]] || continue

if [[ ! -f "${root}/pom.xml" ]]; then
echo "Maven module root is missing: ${root}" >&2
Expand Down
5 changes: 4 additions & 1 deletion .github/scripts/resolve-ci-modules.sh
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ is_ignored_change() {
local file="$1"

case "${file}" in
.github/workflows/ci.yml|.github/scripts/*|actions/*)
return 1
;;
# The opt-in reactor is packaged and smoke-tested by minimal-http.yml.
shenyu-bootstrap-http/*|script/performance/minimal-http/*)
return 0
Expand All @@ -109,7 +112,7 @@ while IFS= read -r file; do
has_code_changes=true

case "${file}" in
pom.xml|mvnw|mvnw.cmd|.mvn/*|actions/*)
pom.xml|mvnw|mvnw.cmd|.mvn/*|actions/*|.github/workflows/ci.yml|.github/scripts/*)
full_build_required=true
;;
esac
Expand Down
53 changes: 53 additions & 0 deletions .github/scripts/resolve-example-projects.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#!/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.

"""Select every example image consumed by an integration case, before building."""

import re
import sys
import xml.etree.ElementTree as ET
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
NS = {"m": "http://maven.apache.org/POM/4.0.0"}
IMAGE = re.compile(r'''(?:image:\s*|kind load docker-image\s+)["']?(?:apache/)?(shenyu-examples?-[\w-]+):''')


def resolve(case, root=ROOT):
"""Fail closed when a new deployment has no identifiable example image."""
if not re.fullmatch(r"shenyu-integrated-test-[a-z0-9-]+", case):
raise ValueError(f"Invalid integration case: {case}")
directory = root / "shenyu-integrated-test" / case
if not (directory / "pom.xml").is_file():
raise ValueError(f"Integration case does not exist: {case}")
images = set()
for path in directory.rglob("*"):
if "target" not in path.parts and path.suffix in (".sh", ".yaml", ".yml"):
images.update(IMAGE.findall(path.read_text()))
if not images:
raise ValueError(f"No example images found for {case}; inspect its deployment before enabling CI")
artifacts = {
ET.parse(path).getroot().findtext("m:artifactId", namespaces=NS)
for path in (root / "shenyu-examples").rglob("pom.xml")
if "target" not in path.parts
}
if images - artifacts:
raise ValueError(f"Example images without Maven modules: {sorted(images - artifacts)}")
return ",".join(":" + image for image in sorted(images))


if __name__ == "__main__":
print(resolve(sys.argv[1]))
4 changes: 4 additions & 0 deletions .github/scripts/resolve-test-case-matrix-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -278,4 +278,8 @@ for infrastructure in \
assert_file_output "e2e" "${infrastructure}" "run_e2e_cases" "true"
done


assert_file_output "k8s-examples-http" ".github/workflows/k8s-examples-http.yml" "run_k8s_examples" "true"
assert_file_output "k8s-examples-http" "actions/setup-java-with-retry/action.yml" "run_k8s_examples" "true"
assert_file_output "e2e" ".github/scripts/select-e2e-sync.sh" "run_e2e_cases" "true"
echo "CI test routing tests passed"
29 changes: 28 additions & 1 deletion .github/scripts/resolve-test-case-matrix.sh
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ resolve_k8s_change() {
return 0
fi


if [[ "${mode}" == "k8s-examples-http" ]]; then
case "${file}" in
pom.xml|mvnw|mvnw.cmd|.mvn/*|\
Expand Down Expand Up @@ -312,6 +313,8 @@ map_direct_case_path() {
;;
esac
fi


}

map_domain_path() {
Expand Down Expand Up @@ -426,6 +429,11 @@ while IFS= read -r file; do

if [[ "${mode}" == "e2e" ]]; then
case "${file}" in
.github/scripts/select-e2e-sync.sh)
add_admin_register_e2e_cases
add_unique e2e_cases "e2e-logging-rocketmq-compose"
continue
;;
.github/workflows/e2e-k8s.yml|.github/scripts/*e2e-maven-repository*|.github/scripts/resolve-test-case-matrix.sh|.github/scripts/resolve-test-case-matrix-test.sh)
full_required=true
continue
Expand All @@ -435,13 +443,32 @@ while IFS= read -r file; do

if [[ "${mode}" == "k8s-ingress" ]]; then
case "${file}" in
.github/workflows/integrated-test-k8s-ingress.yml)
.github/workflows/integrated-test-k8s-ingress.yml|.github/scripts/resolve-example-projects.py|actions/*)
add_k8s_ingress_all
continue
;;
esac
fi

# Changes to the workflow or shared preparation code must exercise the matrix.
if [[ "${mode}" == "integration" ]]; then
case "${file}" in
.github/workflows/integrated-test.yml|.github/scripts/resolve-example-projects.py|.github/scripts/resolve-test-case-matrix*|actions/*)
full_required=true
continue
;;
esac
fi

if [[ "${mode}" == "k8s-examples-http" ]]; then
case "${file}" in
.github/workflows/k8s-examples-http.yml|.github/scripts/install-k3s*|.github/scripts/free-disk-space*|actions/*)
run_k8s_examples=true
continue
;;
esac
fi

if is_ignored_change "${file}"; then
continue
fi
Expand Down
10 changes: 8 additions & 2 deletions .github/scripts/restore-shenyu-local-repo.sh
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@
set -euo pipefail

artifact_dir="${1:-/tmp/shenyu-m2}"
target_dir="${HOME}/.m2/repository/org/apache"
target_dir="${2:-${HOME}/.m2/repository}/org/apache"

if [[ -f "${artifact_dir}/repository.tar.gz" ]]; then
tar -xzf "${artifact_dir}/repository.tar.gz" -C "${artifact_dir}"
fi

if [[ ! -d "${artifact_dir}/org/apache/shenyu" ]]; then
echo "ShenYu local repository artifact is missing: ${artifact_dir}/org/apache/shenyu" >&2
Expand All @@ -27,7 +31,9 @@ fi

mkdir -p "${target_dir}"
if [[ -d "${target_dir}/shenyu" ]]; then
mv "${target_dir}/shenyu" "${target_dir}/shenyu.backup.${GITHUB_RUN_ID:-$$}"
# Backups under ~/.m2/repository grow every saved dependency cache indefinitely.
backup_dir="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/shenyu-m2-previous.XXXXXX")"
mv "${target_dir}/shenyu" "${backup_dir}/shenyu"
fi
cp -R "${artifact_dir}/org/apache/shenyu" "${target_dir}/shenyu"

Expand Down
29 changes: 29 additions & 0 deletions .github/scripts/select-e2e-sync.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#!/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.

# shellcheck disable=SC2034
# SYNC_ARRAY is consumed by the sourcing protocol runners; manual runs keep all channels.
SYNC_ARRAY=("websocket" "http" "zookeeper")
if [[ -n "${SHENYU_E2E_SYNC:-}" ]]; then
case "${SHENYU_E2E_SYNC}" in
websocket|http|zookeeper) SYNC_ARRAY=("${SHENYU_E2E_SYNC}") ;;
*)
echo "Unsupported E2E sync channel: ${SHENYU_E2E_SYNC}" >&2
exit 1
;;
esac
fi
Loading
Loading