diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 567306c..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Release -on: [workflow_dispatch] - -permissions: - contents: read - packages: read - -jobs: - build: - runs-on: ubuntu-22.04 - container: - # Published by .github/workflows/devcontainer.yml. - image: ghcr.io/datadog/httpd-datadog/devcontainer:main - credentials: - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 - - name: Build - run: make ci-build PRESET=ci-release - - name: Export library - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: mod_datadog_artifact - path: dist/lib/mod_datadog.so - - name: Export library (debug symbol) - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: mod_datadog_artifact-debug - path: dist/lib/mod_datadog.so.debug diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index faab61d..ac23e8f 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -54,6 +54,7 @@ stages: SCCACHE_REGION: us-east-1 SCCACHE_S3_KEY_PREFIX: httpd-datadog RUSTC_WRAPPER: /usr/bin/sccache + RUM: "ON" # The GitLab repository identity has read/write access only to this # repository's prefix in the shared sccache bucket. needs: @@ -65,7 +66,7 @@ stages: - if [ -n "${CI_COMMIT_TAG:-}" ]; then export SCCACHE_RECACHE=1; fi - > cmake --preset=ci-release - -DHTTPD_DATADOG_ENABLE_RUM=ON + -DHTTPD_DATADOG_ENABLE_RUM=${RUM} -DCMAKE_TOOLCHAIN_FILE=/sysroot/${TOOLCHAIN_ARCH}-none-linux-musl/Toolchain.cmake -DCMAKE_C_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_COMPILER_LAUNCHER=sccache @@ -76,7 +77,8 @@ stages: - mkdir -p artifacts/$ARCH upload - cp dist/lib/mod_datadog.so artifacts/$ARCH/ - cp dist/lib/mod_datadog.so.debug artifacts/$ARCH/ || true - - cd artifacts/$ARCH && zip ../../upload/mod_datadog-${ARCH}.zip mod_datadog.so && cd - + # upload/ is the S3 payload, which only has RUM builds. + - if [ "$RUM" = "ON" ]; then cd artifacts/$ARCH && zip ../../upload/mod_datadog-${ARCH}.zip mod_datadog.so && cd -; fi artifacts: paths: - artifacts/$ARCH/mod_datadog.so @@ -158,6 +160,15 @@ build:arm64: - .build-template - .arm64 +# Published on GitHub releases as mod_datadog_artifact.zip, the asset name +# users and system-tests download. +build:amd64:no-rum: + extends: + - .build-template + - .amd64 + variables: + RUM: "OFF" + unit-test:amd64: extends: - .unit-test-template @@ -198,6 +209,14 @@ check-module-load:arm64: - .test-arm64 - .check-module-load-template +check-module-load:amd64:no-rum: + extends: + - .test-amd64 + - .check-module-load-template + needs: + - job: "build:amd64:no-rum" + artifacts: true + .upload-template: stage: aws needs: @@ -218,7 +237,6 @@ check-module-load:arm64: script: - aws s3 cp upload/ "${S3_PATH}/" --recursive --acl public-read - echo "Uploaded to ${S3_PATH}/" - after_script: - | PUBLIC_URL=$(echo "${S3_PATH}" | sed 's|s3://\([^/]*\)/|https://\1.s3.amazonaws.com/|') echo "Public URLs:" @@ -229,6 +247,14 @@ check-module-load:arm64: curl -sSfI "${PUBLIC_URL}/$(basename $f)" && echo " $(basename $f) verified" || echo " $(basename $f) not accessible" done +# Release builds: s3://rum-auto-instrumentation/httpd/__/, +# the layout used by past releases. +.release-s3-path: + before_script: + - export S3_PATH="s3://rum-auto-instrumentation/httpd/$(echo "$CI_PIPELINE_CREATED_AT" | cut -c1-10 | tr - _)_${CI_COMMIT_TAG}_$(echo "$CI_COMMIT_SHA" | cut -c1-7)" + rules: + - if: $CI_COMMIT_TAG =~ /^v?[0-9]+\.[0-9]+\.[0-9]+$/ + # Branch snapshots require a 30-day expiry rule in ddoghq/cloud-inventory: # datacenters/us1.prod.dog/rum-auto-instrumentation/main.tf upload-branch-snapshots: @@ -236,7 +262,7 @@ upload-branch-snapshots: variables: S3_PATH: s3://rum-auto-instrumentation/httpd/branch-snapshots/pipeline-${CI_PIPELINE_ID} rules: - - if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH + - if: $CI_COMMIT_BRANCH && $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH upload-snapshots: extends: .upload-template @@ -252,6 +278,26 @@ upload-snapshots-latest: rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH +upload-release: + extends: + - .upload-template + - .release-s3-path + +# httpd/latest/ is what users download. `scripts/release.py --publish` runs it +# after the smoke tests. +promote-s3-latest: + extends: .release-s3-path + stage: aws + needs: ["upload-release"] + tags: ["arch:amd64"] + image: registry.ddbuild.io/images/aws-cli:2.33.12 + script: + - aws s3 cp "${S3_PATH}/" s3://rum-auto-instrumentation/httpd/latest/ --recursive --acl public-read + rules: + - if: $CI_COMMIT_TAG =~ /^v?[0-9]+\.[0-9]+\.[0-9]+$/ + when: manual + allow_failure: true + # ── One-pipeline overrides ──────────────────────────────────────────── # # These re-declare only the keys we change; everything else still comes from diff --git a/doc/release.md b/doc/release.md index 919950b..8692a8d 100644 --- a/doc/release.md +++ b/doc/release.md @@ -27,6 +27,37 @@ Release artifact are generated through a Continuous Integration pipeline. Our CI ensures cross-platform compatibility by compiling shared libraries for both Linux `x86_64` and `arm64` architectures. It generates shared libaries for each HTTPD version supported. +### GitHub Release and S3 + +All release files come from the GitLab pipeline of the version tag. + +1. Push the `vX.Y.Z` tag. The `upload-release` job uploads the RUM builds to + `s3://rum-auto-instrumentation/httpd/_vX.Y.Z_/`. +2. When the pipeline is green, create the draft GitHub release: + + ```sh + scripts/release.py --version-tag vX.Y.Z + ``` + + It downloads the builds, signs each zip with your GPG key (`--local-user` to pick one) and + creates the draft with `gh`. Use `--dry-run --out-dir DIR` to only prepare the files. + + | Asset | Build | + | ----- | ----- | + | `mod_datadog_artifact.zip`, `mod_datadog_artifact-debug.zip` | `x86_64`, RUM disabled at build time | + | `mod_datadog-amd64.zip`, `mod_datadog-amd64-debug.zip` | `x86_64`, RUM | + | `mod_datadog-arm64.zip`, `mod_datadog-arm64-debug.zip` | `arm64`, RUM | + +3. Run the smoke tests. +4. Publish the release: + + ```sh + scripts/release.py --version-tag vX.Y.Z --publish + ``` + + It runs the manual `promote-s3-latest` job, which copies the S3 files to `httpd/latest/`, then + publishes the draft. + ### OCI Package The same modules are also published as an OCI package named `datadog-apm-library-httpd`, through diff --git a/scripts/release.py b/scripts/release.py new file mode 100755 index 0000000..e9771bf --- /dev/null +++ b/scripts/release.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Release mod_datadog from the GitLab pipeline of a version tag. + +Usage: + scripts/release.py --version-tag v1.2.3 [--pipeline-id ID] [--local-user KEYID] + scripts/release.py --version-tag v1.2.3 --pipeline-id ID --dry-run --out-dir DIR + scripts/release.py --version-tag v1.2.3 --publish + +By default, the script downloads the module builds of the pipeline, zips them, +signs each zip with GPG and creates a draft release with `gh`. + +--publish (after the smoke tests) runs the manual promote-s3-latest job, then +publishes the draft release. + +GitLab token: GITLAB_TOKEN, or `ddtool auth gitlab token`. +""" + +import argparse +import json +import os +import re +import shlex +import stat +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.request +import zipfile +from pathlib import Path +from urllib.parse import quote + +GITLAB_API = "https://gitlab.ddbuild.io/api/v4" +GITLAB_PROJECT = quote("DataDog/httpd-datadog", safe="") +GITHUB_REPO = "DataDog/httpd-datadog" + +# Release asset prefix -> GitLab build job. All builds store the module in +# artifacts//. +ASSETS = { + "mod_datadog_artifact": ("build:amd64:no-rum", "amd64"), + "mod_datadog-amd64": ("build:amd64", "amd64"), + "mod_datadog-arm64": ("build:arm64", "arm64"), +} + + +def run(command, **kwargs): + print("+", shlex.join(str(arg) for arg in command), file=sys.stderr) + return subprocess.run([str(arg) for arg in command], check=True, **kwargs) + + +def gitlab_token() -> str: + if token := os.environ.get("GITLAB_TOKEN"): + return token + result = run(["ddtool", "auth", "gitlab", "token"], capture_output=True, text=True) + if not result.stdout.strip(): + raise SystemExit(f"No GitLab token from ddtool:\n{result.stderr}") + return result.stdout.strip().splitlines()[-1] + + +def gitlab_get(path: str, token: str, method: str = "GET") -> bytes: + url = f"{GITLAB_API}/projects/{GITLAB_PROJECT}{path}" + print(f"+ {method}", url, file=sys.stderr) + request = urllib.request.Request( + url, headers={"Authorization": f"Bearer {token}"}, method=method + ) + try: + with urllib.request.urlopen(request) as response: + return response.read() + except urllib.error.HTTPError as error: + body = error.read().decode(errors="replace") + raise SystemExit(f"GitLab API error {error.code} for {url}: {body}") from error + + +def find_pipeline(tag: str, token: str) -> int: + pipelines = json.loads( + gitlab_get(f"/pipelines?ref={quote(tag, safe='')}&scope=tags&per_page=1", token) + ) + if not pipelines: + raise SystemExit(f"No pipeline found for tag {tag}.") + return pipelines[0]["id"] + + +def pipeline_jobs(pipeline_id: int, token: str) -> dict[str, dict]: + jobs = {} + page = 1 + while page_jobs := json.loads( + gitlab_get(f"/pipelines/{pipeline_id}/jobs?per_page=100&page={page}", token) + ): + jobs.update((job["name"], job) for job in page_jobs) + page += 1 + + failed = [ + name + for name, job in jobs.items() + if job["status"] not in ("success", "manual", "skipped", "created") + and not job["allow_failure"] + ] + if failed: + raise SystemExit( + f"Pipeline {pipeline_id} has unsuccessful jobs: {', '.join(failed)}" + ) + return jobs + + +def write_zip(path: Path, name: str, data: bytes) -> None: + info = zipfile.ZipInfo(name, date_time=time.localtime()[:6]) + info.compress_type = zipfile.ZIP_DEFLATED + # Without it, unzip creates the file with mode 0600. + info.external_attr = (stat.S_IFREG | 0o644) << 16 + with zipfile.ZipFile(path, "w") as out: + out.writestr(info, data) + + +def prepare_assets(jobs: dict[str, dict], token: str, out_dir: Path) -> list[Path]: + assets = [] + for prefix, (job_name, arch) in ASSETS.items(): + job = jobs.get(job_name) + if job is None or job["status"] != "success": + raise SystemExit(f"Job {job_name} is missing or did not succeed.") + for suffix, name in ( + ("", "mod_datadog.so"), + ("-debug", "mod_datadog.so.debug"), + ): + data = gitlab_get( + f"/jobs/{job['id']}/artifacts/artifacts/{arch}/{name}", token + ) + asset = out_dir / f"{prefix}{suffix}.zip" + write_zip(asset, name, data) + assets.append(asset) + return assets + + +def publish(tag: str, jobs: dict[str, dict], token: str, dry_run: bool) -> None: + view = ["gh", "release", "view", tag, "--repo", GITHUB_REPO] + if subprocess.run(view, stdout=subprocess.DEVNULL).returncode != 0: + raise SystemExit(f"No GitHub release for {tag}. Create the draft first.") + job = jobs.get("promote-s3-latest") + if job is None: + raise SystemExit("Job promote-s3-latest not found.") + publish_command = ["gh", "release", "edit", tag, "--draft=false", "--repo", GITHUB_REPO] # fmt: skip + if dry_run: + print( + f"Dry run, not playing promote-s3-latest ({job['status']}): {job['web_url']}" + ) + print("Dry run, not running:", shlex.join(publish_command)) + return + + if job["status"] == "manual": + gitlab_get(f"/jobs/{job['id']}/play", token, method="POST") + print(f"Waiting for promote-s3-latest: {job['web_url']}") + while ( + status := json.loads(gitlab_get(f"/jobs/{job['id']}", token))["status"] + ) != "success": + if status in ("failed", "canceled", "skipped"): + raise SystemExit( + f"promote-s3-latest is {status}. Retry it in GitLab, then run --publish again." + ) + time.sleep(10) + run(publish_command) + + +def main() -> int: + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument( + "--version-tag", required=True, help="Version tag, for example v1.2.3." + ) + parser.add_argument( + "--pipeline-id", + type=int, + help="GitLab pipeline ID. Default: latest pipeline of the tag.", + ) + parser.add_argument( + "--local-user", + help="GPG key used to sign the assets. Default: gpg default key.", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Print the release commands, but do not run them.", + ) + parser.add_argument( + "--publish", + action="store_true", + help="After the smoke tests: update S3 latest, then publish the draft.", + ) + parser.add_argument( + "--out-dir", type=Path, help="Keep the assets in this directory." + ) + args = parser.parse_args() + if not re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+", args.version_tag): + parser.error(f"--version-tag must look like v1.2.3, got {args.version_tag!r}.") + + token = gitlab_token() + pipeline_id = args.pipeline_id or find_pipeline(args.version_tag, token) + print( + f"Pipeline: https://gitlab.ddbuild.io/DataDog/httpd-datadog/-/pipelines/{pipeline_id}" + ) + pipeline = json.loads(gitlab_get(f"/pipelines/{pipeline_id}", token)) + # The tag may have moved: check GitLab built the GitHub tag commit. + result = subprocess.run( + [ + "gh", + "api", + f"repos/{GITHUB_REPO}/commits/refs/tags/{args.version_tag}", + "-q", + ".sha", + ], + stdout=subprocess.PIPE, + text=True, + ) + tag_sha = result.stdout.strip() if result.returncode == 0 else "" + if not ( + pipeline["tag"] + and pipeline["ref"] == args.version_tag + and pipeline["sha"] == tag_sha + ): + problem = ( + f"Pipeline {pipeline_id} ({pipeline['ref']} at {pipeline['sha']}) is not" + f" the pipeline of tag {args.version_tag} ({tag_sha or 'not found'})." + ) + if not args.dry_run: + raise SystemExit(problem) + print(f"Warning: {problem}") + jobs = pipeline_jobs(pipeline_id, token) + + if args.publish: + publish(args.version_tag, jobs, token, args.dry_run) + return 0 + + with tempfile.TemporaryDirectory() as tmp: + out_dir = args.out_dir or Path(tmp) + out_dir.mkdir(parents=True, exist_ok=True) + assets = prepare_assets(jobs, token, out_dir) + + gpg = ["gpg", "--yes", "--armor", "--detach-sign"] + if args.local_user: + gpg += ["--local-user", args.local_user] + signatures = [] + for asset in assets: + run([*gpg, asset]) + signatures.append(asset.with_name(asset.name + ".asc")) + + command = [ + "gh", + "release", + "create", + args.version_tag, + "--draft", + "--generate-notes", + "--verify-tag", + "--repo", + GITHUB_REPO, + *assets, + *signatures, + ] + if args.dry_run: + print("Dry run, not running:", shlex.join(str(arg) for arg in command)) + else: + run(command) + return 0 + + +if __name__ == "__main__": + sys.exit(main())