From dbba4d7ebf7529edcf313d6fe254064972b9c8ff Mon Sep 17 00:00:00 2001 From: JackieTien97 Date: Sun, 22 Nov 2026 18:14:30 +0800 Subject: [PATCH 1/3] Scope PR SonarCloud analysis to PR diff and fix master OOM --- .github/scripts/select-sonar-modules.py | 229 ++++++++++++++++++++++++ .github/workflows/sonar-codecov.yml | 47 ++++- 2 files changed, 272 insertions(+), 4 deletions(-) create mode 100755 .github/scripts/select-sonar-modules.py diff --git a/.github/scripts/select-sonar-modules.py b/.github/scripts/select-sonar-modules.py new file mode 100755 index 0000000000000..11c5770e22cbe --- /dev/null +++ b/.github/scripts/select-sonar-modules.py @@ -0,0 +1,229 @@ +#!/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. +# + +"""Resolve Maven modules impacted by Sonar-analyzable PR diff changes. + +SonarCloud for apache_iotdb analyzes main Java sources (`src/main/java/**` and +`src/main/i18n/en/**`) in the default Maven reactor excluding `distribution` +(and excluding profile-only modules such as `integration-test`, `code-coverage`, +`iotdb-client/client-cpp`, and `iotdb-core/ainode`). + +Given a base Git ref and head ref, this script inspects the three-dot PR diff +(`...`), maps changed analyzable Java files to their enclosing +Maven modules, and emits `run_sonar` and `modules` outputs for GitHub Actions. +""" + +from __future__ import annotations + +import argparse +from pathlib import Path, PurePosixPath +import subprocess +import sys +import xml.etree.ElementTree as ET + +EXCLUDED_MODULES = {"distribution"} +ANALYZABLE_SOURCE_PREFIXES = ("src/main/java/", "src/main/i18n/en/") +MAVEN_NS = "{http://maven.apache.org/POM/4.0.0}" + + +def discover_reactor_modules(repo_root: Path) -> set[str]: + """Walk default `` from the root pom.xml, excluding non-Sonar modules.""" + modules: set[str] = set() + + def walk(rel_dir: PurePosixPath) -> None: + rel_str = "." if rel_dir == PurePosixPath(".") else rel_dir.as_posix() + if rel_str in EXCLUDED_MODULES: + return + pom_path = repo_root / rel_str / "pom.xml" if rel_str != "." else repo_root / "pom.xml" + if not pom_path.is_file(): + return + modules.add(rel_str) + + tree = ET.parse(pom_path) + root = tree.getroot() + ns = MAVEN_NS if root.tag.startswith(MAVEN_NS) else "" + modules_elem = root.find(f"{ns}modules") + if modules_elem is None: + return + for child in modules_elem.findall(f"{ns}module"): + if not child.text: + continue + child_name = child.text.strip() + if not child_name: + continue + child_rel = ( + PurePosixPath(child_name) + if rel_str == "." + else rel_dir / PurePosixPath(child_name) + ) + walk(child_rel) + + walk(PurePosixPath(".")) + modules.discard(".") + return modules + + +def find_enclosing_module(rel_path: str, eligible_modules: set[str]) -> str | None: + """Return the nearest enclosing eligible Maven module for a repo-relative path.""" + parent = PurePosixPath(rel_path).parent + while str(parent) not in ("", "."): + candidate = parent.as_posix() + if candidate in eligible_modules: + return candidate + parent = parent.parent + return None + + +def is_analyzable_source(rel_path: str, module_dir: str) -> bool: + """Check whether `rel_path` is a main Java source indexed by SonarCloud.""" + if not rel_path.endswith(".java"): + return False + prefix = f"{module_dir}/" + if not rel_path.startswith(prefix): + return False + module_rel = rel_path[len(prefix) :] + return module_rel.startswith(ANALYZABLE_SOURCE_PREFIXES) + + +def select_modules_for_files( + changed_files: list[str], + repo_root: Path, + eligible_modules: set[str], + *, + require_existing: bool = True, +) -> tuple[list[str], list[str]]: + """Map changed repo-relative paths to sorted Sonar-analyzable files and modules.""" + analyzable_files: list[str] = [] + selected_modules: set[str] = set() + + for raw_path in changed_files: + rel_path = raw_path.replace("\\", "/") + while rel_path.startswith("./"): + rel_path = rel_path[2:] + if not rel_path: + continue + if require_existing and not (repo_root / rel_path).is_file(): + continue + module_dir = find_enclosing_module(rel_path, eligible_modules) + if module_dir is None: + continue + if is_analyzable_source(rel_path, module_dir): + analyzable_files.append(rel_path) + selected_modules.add(module_dir) + + return sorted(analyzable_files), sorted(selected_modules) + + +def git_changed_files(repo_root: Path, base_ref: str, head_ref: str) -> tuple[str, list[str]]: + """Verify merge-base and return (merge_base_sha, changed_files) for `...`.""" + merge_base = subprocess.check_output( + ["git", "merge-base", base_ref, head_ref], + cwd=repo_root, + text=True, + ).strip() + + diff_output = subprocess.check_output( + [ + "git", + "-c", + "core.quotepath=false", + "diff", + "-z", + "--name-only", + "--diff-filter=ACMR", + f"{base_ref}...{head_ref}", + ], + cwd=repo_root, + ) + files = [entry.decode("utf-8", errors="surrogateescape") for entry in diff_output.split(b"\0") if entry] + return merge_base, files + + +def write_github_outputs(output_path: Path, run_sonar: bool, modules: list[str]) -> None: + with output_path.open("a", encoding="utf-8") as fh: + fh.write(f"run_sonar={'true' if run_sonar else 'false'}\n") + fh.write(f"modules={','.join(modules)}\n") + + +def parse_args(argv: list[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Select Maven modules for PR-diff SonarCloud analysis." + ) + parser.add_argument( + "--repo-root", + type=Path, + default=Path(__file__).resolve().parents[2], + help="Path to the repository root.", + ) + parser.add_argument( + "--base-ref", + required=True, + help="Git base ref to diff against (e.g. refs/remotes/origin/master).", + ) + parser.add_argument( + "--head-ref", + default="HEAD", + help="Git head ref to diff (default: HEAD).", + ) + parser.add_argument( + "--github-output", + type=Path, + default=None, + help="Optional path to $GITHUB_OUTPUT file.", + ) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(sys.argv[1:] if argv is None else argv) + repo_root = args.repo_root.resolve() + + eligible_modules = discover_reactor_modules(repo_root) + merge_base, changed_files = git_changed_files(repo_root, args.base_ref, args.head_ref) + analyzable_files, selected_modules = select_modules_for_files( + changed_files, + repo_root, + eligible_modules, + require_existing=(args.head_ref == "HEAD"), + ) + + print(f"Base ref: {args.base_ref}") + print(f"Merge base: {merge_base}") + print(f"Changed files in PR diff (ACMR): {len(changed_files)}") + print(f"Sonar-analyzable changed Java files: {len(analyzable_files)}") + for path in analyzable_files[:50]: + print(f" - {path}") + if len(analyzable_files) > 50: + print(f" ... and {len(analyzable_files) - 50} more") + + run_sonar = bool(selected_modules) + if run_sonar: + print(f"Selected Maven modules for SonarCloud (-pl): {','.join(selected_modules)}") + else: + print("No Sonar-analyzable main Java sources changed in this PR; skipping SonarCloud scan.") + + if args.github_output is not None: + write_github_outputs(args.github_output, run_sonar, selected_modules) + + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.github/workflows/sonar-codecov.yml b/.github/workflows/sonar-codecov.yml index 88f69e5938d4f..0a25a3705e5b2 100644 --- a/.github/workflows/sonar-codecov.yml +++ b/.github/workflows/sonar-codecov.yml @@ -68,10 +68,38 @@ jobs: sonar: runs-on: ubuntu-latest - if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'apache/iotdb' || github.event_name == 'push' + if: >- + (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'apache/iotdb') || + (github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/dev/1.3')) + env: + MAVEN_OPTS: -Xms2g -Xmx8g -Dhttp.keepAlive=false -Dmaven.wagon.http.pool=false -Dmaven.wagon.http.retryHandler.class=standard -Dmaven.wagon.http.retryHandler.count=3 steps: - uses: actions/checkout@v5 + with: + fetch-depth: 0 + - name: Select SonarCloud scan scope + id: sonar-scope + shell: bash + env: + EVENT_NAME: ${{ github.event_name }} + BASE_REF: ${{ github.base_ref }} + run: | + set -euo pipefail + if [ "${EVENT_NAME}" = "push" ]; then + echo "Push event on ${GITHUB_REF}: running full SonarCloud scan (excluding distribution)." + echo 'run_sonar=true' >> "${GITHUB_OUTPUT}" + echo 'modules=!distribution' >> "${GITHUB_OUTPUT}" + exit 0 + fi + if ! git rev-parse --verify --quiet "refs/remotes/origin/${BASE_REF}" >/dev/null; then + git fetch --no-tags origin "+refs/heads/${BASE_REF}:refs/remotes/origin/${BASE_REF}" + fi + python3 .github/scripts/select-sonar-modules.py \ + --base-ref "refs/remotes/origin/${BASE_REF}" \ + --head-ref HEAD \ + --github-output "${GITHUB_OUTPUT}" - name: Set up JDK 21 + if: steps.sonar-scope.outputs.run_sonar == 'true' uses: actions/setup-java@v5 with: distribution: corretto @@ -79,19 +107,30 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Cache Maven packages + if: steps.sonar-scope.outputs.run_sonar == 'true' uses: actions/cache@v5 with: path: ~/.m2 key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} restore-keys: ${{ runner.os }}-m2- + - name: Cache SonarCloud packages + if: steps.sonar-scope.outputs.run_sonar == 'true' + uses: actions/cache@v5 + with: + path: ~/.sonar/cache + key: ${{ runner.os }}-sonar + restore-keys: ${{ runner.os }}-sonar - name: SonarCloud Report + if: steps.sonar-scope.outputs.run_sonar == 'true' + shell: bash env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SONAR_TOKEN: ${{ secrets.SONARCLOUD_TOKEN }} + SONAR_MODULES: ${{ steps.sonar-scope.outputs.modules }} run: | - mvn -B -P with-integration-tests,with-code-coverage verify sonar:sonar \ + mvn -B verify sonar:sonar \ -Dsonar.organization=apache \ -Dsonar.projectKey=apache_iotdb \ -Dsonar.host.url=https://sonarcloud.io \ - -Dsonar.token=${{ secrets.SONARCLOUD_TOKEN }} \ - -DskipTests -pl '!distribution,!integration-test' -am + -Dsonar.token="${SONAR_TOKEN}" \ + -DskipTests -pl "${SONAR_MODULES}" -am From 1674abb8e001203fbc30c866abb2acf5344e998d Mon Sep 17 00:00:00 2001 From: JackieTien97 Date: Mon, 23 Nov 2026 09:15:09 +0800 Subject: [PATCH 2/3] Address review feedback: keep full scan scope, checkout PR head, preserve release push baselines --- ...onar-modules.py => check-sonar-pr-diff.py} | 35 ++++++++++--------- .github/workflows/sonar-codecov.yml | 13 +++---- 2 files changed, 23 insertions(+), 25 deletions(-) rename .github/scripts/{select-sonar-modules.py => check-sonar-pr-diff.py} (85%) diff --git a/.github/scripts/select-sonar-modules.py b/.github/scripts/check-sonar-pr-diff.py similarity index 85% rename from .github/scripts/select-sonar-modules.py rename to .github/scripts/check-sonar-pr-diff.py index 11c5770e22cbe..9d5979cf4673c 100755 --- a/.github/scripts/select-sonar-modules.py +++ b/.github/scripts/check-sonar-pr-diff.py @@ -18,7 +18,7 @@ # under the License. # -"""Resolve Maven modules impacted by Sonar-analyzable PR diff changes. +"""Check whether a PR diff touches any Sonar-analyzable main Java source. SonarCloud for apache_iotdb analyzes main Java sources (`src/main/java/**` and `src/main/i18n/en/**`) in the default Maven reactor excluding `distribution` @@ -26,8 +26,8 @@ `iotdb-client/client-cpp`, and `iotdb-core/ainode`). Given a base Git ref and head ref, this script inspects the three-dot PR diff -(`...`), maps changed analyzable Java files to their enclosing -Maven modules, and emits `run_sonar` and `modules` outputs for GitHub Actions. +(`...`) and emits `run_sonar=true|false` for GitHub Actions so PRs +without analyzable Java changes can skip the SonarCloud build and scan. """ from __future__ import annotations @@ -102,16 +102,15 @@ def is_analyzable_source(rel_path: str, module_dir: str) -> bool: return module_rel.startswith(ANALYZABLE_SOURCE_PREFIXES) -def select_modules_for_files( +def find_analyzable_files( changed_files: list[str], repo_root: Path, eligible_modules: set[str], *, require_existing: bool = True, -) -> tuple[list[str], list[str]]: - """Map changed repo-relative paths to sorted Sonar-analyzable files and modules.""" +) -> list[str]: + """Filter changed repo-relative paths to sorted Sonar-analyzable Java files.""" analyzable_files: list[str] = [] - selected_modules: set[str] = set() for raw_path in changed_files: rel_path = raw_path.replace("\\", "/") @@ -126,9 +125,8 @@ def select_modules_for_files( continue if is_analyzable_source(rel_path, module_dir): analyzable_files.append(rel_path) - selected_modules.add(module_dir) - return sorted(analyzable_files), sorted(selected_modules) + return sorted(analyzable_files) def git_changed_files(repo_root: Path, base_ref: str, head_ref: str) -> tuple[str, list[str]]: @@ -152,19 +150,22 @@ def git_changed_files(repo_root: Path, base_ref: str, head_ref: str) -> tuple[st ], cwd=repo_root, ) - files = [entry.decode("utf-8", errors="surrogateescape") for entry in diff_output.split(b"\0") if entry] + files = [ + entry.decode("utf-8", errors="surrogateescape") + for entry in diff_output.split(b"\0") + if entry + ] return merge_base, files -def write_github_outputs(output_path: Path, run_sonar: bool, modules: list[str]) -> None: +def write_github_outputs(output_path: Path, run_sonar: bool) -> None: with output_path.open("a", encoding="utf-8") as fh: fh.write(f"run_sonar={'true' if run_sonar else 'false'}\n") - fh.write(f"modules={','.join(modules)}\n") def parse_args(argv: list[str]) -> argparse.Namespace: parser = argparse.ArgumentParser( - description="Select Maven modules for PR-diff SonarCloud analysis." + description="Determine whether a PR diff touches Sonar-analyzable Java sources." ) parser.add_argument( "--repo-root", @@ -197,7 +198,7 @@ def main(argv: list[str] | None = None) -> int: eligible_modules = discover_reactor_modules(repo_root) merge_base, changed_files = git_changed_files(repo_root, args.base_ref, args.head_ref) - analyzable_files, selected_modules = select_modules_for_files( + analyzable_files = find_analyzable_files( changed_files, repo_root, eligible_modules, @@ -213,14 +214,14 @@ def main(argv: list[str] | None = None) -> int: if len(analyzable_files) > 50: print(f" ... and {len(analyzable_files) - 50} more") - run_sonar = bool(selected_modules) + run_sonar = bool(analyzable_files) if run_sonar: - print(f"Selected Maven modules for SonarCloud (-pl): {','.join(selected_modules)}") + print("Analyzable Java changes detected; running full-reactor SonarCloud PR analysis.") else: print("No Sonar-analyzable main Java sources changed in this PR; skipping SonarCloud scan.") if args.github_output is not None: - write_github_outputs(args.github_output, run_sonar, selected_modules) + write_github_outputs(args.github_output, run_sonar) return 0 diff --git a/.github/workflows/sonar-codecov.yml b/.github/workflows/sonar-codecov.yml index 0a25a3705e5b2..92bf0d61102fb 100644 --- a/.github/workflows/sonar-codecov.yml +++ b/.github/workflows/sonar-codecov.yml @@ -68,16 +68,15 @@ jobs: sonar: runs-on: ubuntu-latest - if: >- - (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'apache/iotdb') || - (github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/dev/1.3')) + if: (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'apache/iotdb') || github.event_name == 'push' env: MAVEN_OPTS: -Xms2g -Xmx8g -Dhttp.keepAlive=false -Dmaven.wagon.http.pool=false -Dmaven.wagon.http.retryHandler.class=standard -Dmaven.wagon.http.retryHandler.count=3 steps: - uses: actions/checkout@v5 with: + ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} fetch-depth: 0 - - name: Select SonarCloud scan scope + - name: Check SonarCloud scan scope id: sonar-scope shell: bash env: @@ -88,13 +87,12 @@ jobs: if [ "${EVENT_NAME}" = "push" ]; then echo "Push event on ${GITHUB_REF}: running full SonarCloud scan (excluding distribution)." echo 'run_sonar=true' >> "${GITHUB_OUTPUT}" - echo 'modules=!distribution' >> "${GITHUB_OUTPUT}" exit 0 fi if ! git rev-parse --verify --quiet "refs/remotes/origin/${BASE_REF}" >/dev/null; then git fetch --no-tags origin "+refs/heads/${BASE_REF}:refs/remotes/origin/${BASE_REF}" fi - python3 .github/scripts/select-sonar-modules.py \ + python3 .github/scripts/check-sonar-pr-diff.py \ --base-ref "refs/remotes/origin/${BASE_REF}" \ --head-ref HEAD \ --github-output "${GITHUB_OUTPUT}" @@ -126,11 +124,10 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SONAR_TOKEN: ${{ secrets.SONARCLOUD_TOKEN }} - SONAR_MODULES: ${{ steps.sonar-scope.outputs.modules }} run: | mvn -B verify sonar:sonar \ -Dsonar.organization=apache \ -Dsonar.projectKey=apache_iotdb \ -Dsonar.host.url=https://sonarcloud.io \ -Dsonar.token="${SONAR_TOKEN}" \ - -DskipTests -pl "${SONAR_MODULES}" -am + -DskipTests -pl '!distribution' -am From 437e6d05daadca42dd55e0f5199f1c61d045dd08 Mon Sep 17 00:00:00 2001 From: JackieTien97 Date: Mon, 23 Nov 2026 09:41:48 +0800 Subject: [PATCH 3/3] Skip SonarCloud analysis for example and integration-test modules --- .github/scripts/check-sonar-pr-diff.py | 15 +++++++++++---- example/pom.xml | 3 +++ integration-test/pom.xml | 1 + 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/.github/scripts/check-sonar-pr-diff.py b/.github/scripts/check-sonar-pr-diff.py index 9d5979cf4673c..1caa45aec1566 100755 --- a/.github/scripts/check-sonar-pr-diff.py +++ b/.github/scripts/check-sonar-pr-diff.py @@ -21,9 +21,10 @@ """Check whether a PR diff touches any Sonar-analyzable main Java source. SonarCloud for apache_iotdb analyzes main Java sources (`src/main/java/**` and -`src/main/i18n/en/**`) in the default Maven reactor excluding `distribution` -(and excluding profile-only modules such as `integration-test`, `code-coverage`, -`iotdb-client/client-cpp`, and `iotdb-core/ainode`). +`src/main/i18n/en/**`) in the default Maven reactor excluding `distribution`, +any module (and its subtree) marked `true` (such as +`example`), and profile-only modules (`integration-test`, `code-coverage`, +`iotdb-client/client-cpp`, `iotdb-core/ainode`). Given a base Git ref and head ref, this script inspects the three-dot PR diff (`...`) and emits `run_sonar=true|false` for GitHub Actions so PRs @@ -54,11 +55,17 @@ def walk(rel_dir: PurePosixPath) -> None: pom_path = repo_root / rel_str / "pom.xml" if rel_str != "." else repo_root / "pom.xml" if not pom_path.is_file(): return - modules.add(rel_str) tree = ET.parse(pom_path) root = tree.getroot() ns = MAVEN_NS if root.tag.startswith(MAVEN_NS) else "" + props_elem = root.find(f"{ns}properties") + if props_elem is not None: + sonar_skip = props_elem.findtext(f"{ns}sonar.skip", "").strip().lower() + if sonar_skip == "true": + return + modules.add(rel_str) + modules_elem = root.find(f"{ns}modules") if modules_elem is None: return diff --git a/example/pom.xml b/example/pom.xml index 2e27f19cc5c59..81d31a00ffb96 100644 --- a/example/pom.xml +++ b/example/pom.xml @@ -29,6 +29,9 @@ iotdb-examples pom IoTDB: Examples + + true + jdbc mqtt diff --git a/integration-test/pom.xml b/integration-test/pom.xml index f9045c99508e8..87040d53ab1a7 100644 --- a/integration-test/pom.xml +++ b/integration-test/pom.xml @@ -90,6 +90,7 @@ 2 Ratis 3 + true