From 132a20d1ce8ca40b2583afee73db32013878f234 Mon Sep 17 00:00:00 2001 From: Toby Lawrence Date: Tue, 1 Dec 2026 19:19:29 +0000 Subject: [PATCH] chore(ci): cache the macOS integration builds --- .gitlab/e2e.yml | 94 +- .gitlab/test.yml | 2 + .gitlab/windows.yml | 10 +- Cargo.lock | 1427 ++--------------- Cargo.toml | 1 - LICENSE-3rdparty.csv | 83 - Makefile | 19 +- bin/agent-data-plane/tests/version_cli.rs | 21 + bin/correctness/panoramic/Cargo.toml | 3 - bin/correctness/panoramic/build.rs | 23 - bin/correctness/panoramic/src/cli.rs | 23 +- bin/correctness/panoramic/src/collector.rs | 5 + .../panoramic/src/machine_output.rs | 71 +- bin/correctness/panoramic/src/main.rs | 6 + bin/correctness/panoramic/src/reporter.rs | 12 +- bin/correctness/panoramic/src/revision.rs | 291 ++++ ci/tooling/build-smp-images.sh | 6 +- ci/tooling/get-macos-harness.sh | 39 + ci/tooling/harness_cache.py | 647 ++++++++ ci/tooling/install_macos_agent.py | 31 +- ci/tooling/macos_target_dir.py | 233 +++ ci/tooling/test_harness_cache.py | 648 ++++++++ ci/tooling/test_install_macos_agent.py | 50 + ci/tooling/test_macos_target_dir.py | 269 ++++ codereview_guideline.md | 3 +- deny.toml | 14 - docs/agent-data-plane/releasing.md | 9 +- docs/development/conventions.md | 3 +- docs/development/panoramic.md | 109 +- .../development/plans/macos-integration-ci.md | 26 +- lib/saluki-metadata/build.rs | 74 +- lib/saluki-metadata/src/lib.rs | 196 ++- 32 files changed, 2802 insertions(+), 1646 deletions(-) delete mode 100644 bin/correctness/panoramic/build.rs create mode 100644 bin/correctness/panoramic/src/revision.rs create mode 100755 ci/tooling/get-macos-harness.sh create mode 100644 ci/tooling/harness_cache.py create mode 100644 ci/tooling/macos_target_dir.py create mode 100644 ci/tooling/test_harness_cache.py create mode 100644 ci/tooling/test_macos_target_dir.py diff --git a/.gitlab/e2e.yml b/.gitlab/e2e.yml index c1a5d8aeb3f..517fa45c25d 100644 --- a/.gitlab/e2e.yml +++ b/.gitlab/e2e.yml @@ -206,16 +206,76 @@ test-integration-linux-amd64: variables: TEST_ARCH: amd64 +# Builds the macOS integration harness (panoramic, datadog-intake and millstone) for arm64, and caches it in the GitLab +# package registry under a hash of its inputs. When the registry already has the harness for that hash, the job stops. +# test-integration-macos-arm64 takes the harness from the cache. See "The macOS harness cache" in +# docs/development/panoramic.md. Like test-integration-macos-arm64, this job has no rules, so the two jobs run in the +# same pipelines. +build-macos-harness-arm64: + extends: + - .macos-arm64-test-job + stage: e2e + needs: [] + # When this job fails, it publishes a failure marker, and the test job fails with an error that links here. Without + # the marker, the test job builds the harness itself. So a failure here doesn't fail the pipeline on its own. + allow_failure: true + retry: + max: 2 + when: + - runner_system_failure + - stuck_or_timeout_failure + - scheduler_failure + - api_failure + - data_integrity_failure + - unknown_failure + timeout: 30m + artifacts: + expire_in: 1 week + paths: + - target/cargo-timings/ + when: always + variables: + # Stop the script early enough for after_script to publish the failure marker. + RUNNER_SCRIPT_TIMEOUT: 25m + RUNNER_AFTER_SCRIPT_TIMEOUT: 5m + CARGO_TIMINGS: "true" + before_script: + - sysctl hw.ncpu hw.physicalcpu hw.memsize machdep.cpu.brand_string || true + script: + - if python3 ci/tooling/harness_cache.py exists; then exit 0; fi + - make build-integration-harness-host + - python3 ci/tooling/harness_cache.py publish + after_script: + # A canceled job publishes no marker, so the test job builds the harness itself instead of failing. + - if [ "$CI_JOB_STATUS" = "failed" ]; then python3 ci/tooling/harness_cache.py mark-failed; fi + # Runs the integration cases that declare macOS on a macOS runner: a Tart VM on arm64, a bare-metal host on amd64. No # Docker: panoramic spawns ADP and the Core Agent as real macOS processes. Up to PANORAMIC_HOST_SLOTS cases run at once, # each in its own host slot: slot 0 uses /tmp/panoramic and the declared ports, and slot k uses /tmp/panoramic-k and the # ports +10·k. The Datadog Agent is installed into a sandbox under /tmp/saluki-dda by the Makefile target (idempotent: # re-uses the install across runs if the pinned version is already present). The sandbox install never touches # /opt/datadog-agent, so any system install on the runner is left alone. +# +# The job builds ADP with $BUILD_PROFILE, the profile that the pipeline ships. Then ci/tooling/get-macos-harness.sh puts +# the harness in target/release/. On arm64, it takes the harness from the cache that build-macos-harness-arm64 fills. +# On amd64, it takes the shared harness from the cache when the cache has it, and builds the harness otherwise. +# ci/tooling/macos_target_dir.py keeps target/release/ between jobs when the job sets MACOS_PERSISTENT_TARGET to "true", +# and does nothing otherwise. .test-integration-macos-base: stage: e2e needs: [] - retry: 2 + # Retry only infrastructure failures. The script exits with 75 (EX_TEMPFAIL) when a download fails. GitLab retries a + # job that matches `when` or `exit_codes`. See "Retries of the macOS jobs" in docs/development/panoramic.md. + retry: + max: 2 + when: + - runner_system_failure + - stuck_or_timeout_failure + - scheduler_failure + - api_failure + - data_integrity_failure + - unknown_failure + exit_codes: [75] timeout: 48m id_tokens: DD_STS_OIDC_TOKEN: @@ -234,6 +294,9 @@ test-integration-linux-amd64: PANORAMIC_LOG_DIR: integration-logs/${CI_JOB_ID} # Write cargo timing reports, so the build phases can be measured per job. CARGO_TIMINGS: "true" + # The script runs the Agent installer, and then `make provision-macos-test-env`, which reads the same directories. + MACOS_TEST_AGENT_INSTALL_DIR: /tmp/saluki-dda/datadog-agent + MACOS_TEST_AGENT_DMG_DIR: /tmp/saluki-dda-dmg-cache before_script: - unset DD_STS_OIDC_TOKEN DD_API_KEY # Record the runner's CPU and memory, which the build times depend on. @@ -264,14 +327,23 @@ test-integration-linux-amd64: - bash ci/tooling/macos-listener-sampler.sh stop # These are the prerequisites of `make test-integration-macos-ci`, one per line so that the log timestamps show the # duration of each. - # Provisioning is network-bound, so it runs in the background while the CPU-bound builds run. + # get-macos-harness.sh runs `make build-integration-harness-host` when the job doesn't take the harness from the + # cache. Provisioning is network-bound, so it runs in the background while the job builds and fetches. + # macos_target_dir.py runs before the first build, so that every build uses the persistent directory. + # + # make exits with 2 when a recipe fails, whatever the exit code of the recipe. So the job runs the Agent installer + # before make, and keeps its exit code 75 for a failed download. The tool step only installs the Rust version in + # rust-toolchain.toml, cargo-binstall and cargo-auditable, so the job exits with 75 when it fails. script: - mkdir -p "$PANORAMIC_LOG_DIR" - - make provision-macos-test-env > "$PANORAMIC_LOG_DIR/provision.log" 2>&1 & + - (python3 ci/tooling/install_macos_agent.py --install-dir "$MACOS_TEST_AGENT_INSTALL_DIR" --cache-dir "$MACOS_TEST_AGENT_DMG_DIR" && make provision-macos-test-env) > "$PANORAMIC_LOG_DIR/provision.log" 2>&1 & - PROVISION_PID=$! - - make build-integration-harness-host + - python3 ci/tooling/macos_target_dir.py link --profile release + - make cargo-install-cargo-auditable || exit 75 - make build-adp-host - - if wait "$PROVISION_PID"; then cat "$PANORAMIC_LOG_DIR/provision.log"; else cat "$PANORAMIC_LOG_DIR/provision.log"; exit 1; fi + - bash ci/tooling/get-macos-harness.sh + # zsh reserves `status`, so the exit code goes in `provision_status`. + - if wait "$PROVISION_PID"; then cat "$PANORAMIC_LOG_DIR/provision.log"; else provision_status=$?; cat "$PANORAMIC_LOG_DIR/provision.log"; exit "$provision_status"; fi # Temporary: record the listeners while the cases run, to check the first runs with several host slots. - bash ci/tooling/macos-listener-sampler.sh start "$PANORAMIC_LOG_DIR/host-diag/listeners.txt" - make test-integration-macos-run @@ -300,6 +372,10 @@ test-integration-macos-arm64: - .test-integration-macos-base variables: PANORAMIC_HOST_SLOTS: "4" + # The seconds that get-macos-harness.sh waits for build-macos-harness-arm64, which starts with this job. The wait + # covers a build job that is a few minutes slower than the ADP build here. After the wait, a local harness build + # still fits in RUNNER_SCRIPT_TIMEOUT. + HARNESS_CACHE_WAIT: "480" test-integration-macos-amd64: extends: @@ -309,3 +385,11 @@ test-integration-macos-amd64: variables: # One case at a time until dogstatsd-replay-unix is checked with several host slots on Intel. PANORAMIC_HOST_SLOTS: "1" + # The hosts keep their disk between jobs, so cargo builds only what changed since the last job on the host. Tag + # pipelines build ADP with the optimized-release profile, which stays in the checkout and builds from scratch. See + # "The persistent build directory of the amd64 macOS jobs" in docs/development/panoramic.md. + MACOS_PERSISTENT_TARGET: "true" + # No job builds the harness for amd64 ahead of this job. So get-macos-harness.sh looks for the shared harness once, + # and builds the harness when the cache doesn't have it. On the default branch, it then publishes that harness. + HARNESS_CACHE_WAIT: "0" + HARNESS_CACHE_PUBLISH: "true" diff --git a/.gitlab/test.yml b/.gitlab/test.yml index 9a831657bc1..5eac7d1b13f 100644 --- a/.gitlab/test.yml +++ b/.gitlab/test.yml @@ -162,6 +162,8 @@ check-correctness-fixtures: stage: test script: - python3 -m unittest -v ci/tooling/test_panoramic_junit.py + - make test-harness-cache + - make test-macos-target-dir - make generate-correctness-fixtures - git diff --exit-code || (echo "Correctness case fixtures not up-to-date. Run 'make generate-correctness-fixtures' locally and commit."; exit 1) diff --git a/.gitlab/windows.yml b/.gitlab/windows.yml index 963917b729a..e4e19977ec7 100644 --- a/.gitlab/windows.yml +++ b/.gitlab/windows.yml @@ -122,11 +122,11 @@ test-integration-windows-amd64: DD_STS_OIDC_TOKEN: aud: dd-sts needs: [] - # Matches the retry policy on the linux/darwin integration jobs (see `.test-integration-linux-base` and - # `.test-integration-macos-base` in .gitlab/e2e.yml). This is a last-resort net stacked under - # the in-harness mitigations, not the primary fix: a retry re-runs the whole job, including the - # cargo build and a possible cold pull of the multi-GB build image, so it is expensive and it - # only helps for failures that don't reproduce. + # Matches the retry policy of the Linux integration jobs (`.test-integration-linux-base` in + # .gitlab/e2e.yml). This is a last-resort net stacked under the in-harness mitigations, not the + # primary fix: a retry re-runs the whole job, including the cargo build and a possible cold pull + # of the multi-GB build image, so it is expensive and it only helps for failures that don't + # reproduce. retry: 2 # Leave time outside the script budgets for the Cargo cache and test artifacts. timeout: 55m diff --git a/Cargo.lock b/Cargo.lock index ffb908a7739..a88114028ed 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -722,46 +722,12 @@ dependencies = [ "time", ] -[[package]] -name = "bon" -version = "3.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a05442cd7005532d0cfedec676b5b9333d2b4c7c3afabe2b1a9ce2742fbe2ee6" -dependencies = [ - "bon-macros", -] - -[[package]] -name = "bon-macros" -version = "3.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93833e97ac7c46ba97045afcf247238c27057538fcf2f06344662ddd5f567be6" -dependencies = [ - "darling", - "ident_case", - "prettyplease 0.3.0", - "proc-macro2", - "quote", - "syn 3.0.10", -] - [[package]] name = "borrow-or-share" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c" -[[package]] -name = "bstr" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" -dependencies = [ - "memchr", - "regex-automata", - "serde_core", -] - [[package]] name = "bumpalo" version = "3.20.2" @@ -993,15 +959,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" -[[package]] -name = "clru" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "197fd99cb113a8d5d9b6376f3aa817f32c1078f2343b714fff7d2ca44fdf67d5" -dependencies = [ - "hashbrown 0.16.1", -] - [[package]] name = "cmake" version = "0.1.58" @@ -1194,19 +1151,6 @@ dependencies = [ "itertools 0.13.0", ] -[[package]] -name = "crossbeam" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e71406cd8807725f7ac2f999a4cdd32e98f829fdf65f528343cebf945e41df1e" -dependencies = [ - "crossbeam-channel", - "crossbeam-deque", - "crossbeam-epoch", - "crossbeam-queue", - "crossbeam-utils", -] - [[package]] name = "crossbeam-channel" version = "0.5.15" @@ -1260,9 +1204,9 @@ dependencies = [ "crossterm_winapi", "document-features", "mio", - "parking_lot 0.12.5", + "parking_lot", "rustix 1.1.6", - "signal-hook 0.3.18", + "signal-hook", "signal-hook-mio", "winapi", ] @@ -1335,20 +1279,6 @@ dependencies = [ "syn 3.0.10", ] -[[package]] -name = "dashmap" -version = "6.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" -dependencies = [ - "cfg-if", - "crossbeam-utils", - "hashbrown 0.14.5", - "lock_api 0.4.14", - "once_cell", - "parking_lot_core 0.9.12", -] - [[package]] name = "data-encoding" version = "2.11.0" @@ -1461,7 +1391,7 @@ dependencies = [ "datadog-agent-commons", "datadog-agent-remote-config", "datadog-protos", - "faster-hex 1.0.0", + "faster-hex", "metrics", "metrics-util", "saluki-common", @@ -1726,7 +1656,7 @@ dependencies = [ "backtrace", "lazy_static", "mintex", - "parking_lot 0.12.5", + "parking_lot", "rustc-hash 1.1.0", "serde", "serde_json", @@ -1774,17 +1704,6 @@ dependencies = [ "litrs", ] -[[package]] -name = "dua-core" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d687862f3206e7c660daeb6ab0200c65e58fccd7e508819e4bd9949304c640a8" -dependencies = [ - "crossbeam", - "libc", - "windows-sys 0.61.2", -] - [[package]] name = "dunce" version = "1.0.5" @@ -1849,18 +1768,6 @@ dependencies = [ "windows-sys 0.59.0", ] -[[package]] -name = "faster-hex" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04839bdf9d8c10f66806fad16b852fc72aab80873aebc3cb69d85b4fa41543ed" -dependencies = [ - "autocfg", - "defmt 0.3.100", - "heapless", - "serde", -] - [[package]] name = "faster-hex" version = "1.0.0" @@ -1870,16 +1777,6 @@ dependencies = [ "defmt 0.3.100", ] -[[package]] -name = "faster-hex" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52094542d09210d54b87d1a7a13996182c8170cd84e7baa56b332b7ca0d7a7de" -dependencies = [ - "defmt 0.3.100", - "serde", -] - [[package]] name = "fastrand" version = "2.4.1" @@ -2009,1061 +1906,148 @@ dependencies = [ ] [[package]] -name = "futures-channel" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-executor" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" - -[[package]] -name = "futures-macro" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "futures-sink" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" - -[[package]] -name = "futures-task" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "slab", -] - -[[package]] -name = "generator" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f04ae4152da20c76fe800fa48659201d5cf627c5149ca0b707b69d7eef6cf9" -dependencies = [ - "cc", - "cfg-if", - "libc", - "log", - "rustversion", - "windows-link 0.2.1", - "windows-result 0.4.1", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "wasi", - "wasm-bindgen", -] - -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if", - "libc", - "r-efi 5.3.0", - "wasip2", -] - -[[package]] -name = "getrandom" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" -dependencies = [ - "cfg-if", - "libc", - "r-efi 6.0.0", - "rand_core 0.10.1", - "wasip2", - "wasip3", -] - -[[package]] -name = "gimli" -version = "0.32.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" - -[[package]] -name = "gix" -version = "0.90.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b92b20c1560511a9014b16e29db2f3c6f0580d4fe289b70f41131277b065a3b0" -dependencies = [ - "gix-actor", - "gix-attributes", - "gix-command", - "gix-commitgraph", - "gix-config", - "gix-credentials", - "gix-date", - "gix-diff", - "gix-dir", - "gix-discover", - "gix-error", - "gix-filter", - "gix-fs", - "gix-glob", - "gix-hash", - "gix-hashtable", - "gix-ignore", - "gix-index", - "gix-lock", - "gix-negotiate", - "gix-note", - "gix-object", - "gix-odb", - "gix-pack", - "gix-parallel", - "gix-path", - "gix-pathspec", - "gix-prompt", - "gix-protocol", - "gix-quote", - "gix-ref", - "gix-refspec", - "gix-revision", - "gix-revwalk", - "gix-sec", - "gix-shallow", - "gix-status", - "gix-submodule", - "gix-tempfile", - "gix-trace", - "gix-transport", - "gix-traverse", - "gix-url", - "gix-utils", - "gix-validate", - "gix-worktree", - "gix-worktree-state", - "gix-worktree-stream", - "gix-zlib", - "nonempty", - "parking_lot 0.12.5", - "signal-hook 0.4.4", - "smallvec", -] - -[[package]] -name = "gix-actor" -version = "0.44.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78243d3371019288a40a75ba1a58de2815c32591fc87b9f7cb01918bce364ca8" -dependencies = [ - "bstr", - "gix-date", - "gix-error", -] - -[[package]] -name = "gix-attributes" -version = "0.37.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b9947d93a94d41ddde66ac655674269121cbebaf6cdee30d8d0e7dbe85edb4c" -dependencies = [ - "bstr", - "gix-error", - "gix-glob", - "gix-parallel", - "gix-path", - "gix-quote", - "gix-trace", - "smallvec", - "unicode-bom", -] - -[[package]] -name = "gix-bitmap" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9543567ee22142c81fdf75b2811160bec749a5b9f48665e4763f88b1789b8612" -dependencies = [ - "gix-error", -] - -[[package]] -name = "gix-chunk" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60cd5f0e47ffae98bad241ccbc031693765004fb4c2a419f7fda2963232af1e3" -dependencies = [ - "gix-error", -] - -[[package]] -name = "gix-command" -version = "0.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2986e78ebad43510ccd7dd18bd9f22e9afd52f2de791e2979b9c715bacb6f0a8" -dependencies = [ - "bstr", - "gix-error", - "gix-path", - "gix-quote", - "gix-trace", -] - -[[package]] -name = "gix-commitgraph" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60b53b700d2a506cf98075099df1fcc0558265cbb47fd86bc6d03c231e4bd72a" -dependencies = [ - "bstr", - "gix-chunk", - "gix-error", - "gix-hash", - "memmap2", - "nonempty", -] - -[[package]] -name = "gix-config" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e11ccf82e9630c4e7befbae07cbe90e79de61dc73a34448c2dec70a13da9ebf" -dependencies = [ - "bstr", - "gix-config-value", - "gix-error", - "gix-glob", - "gix-parallel", - "gix-path", - "gix-ref", - "gix-sec", - "gix-trace", - "gix-utils", - "smallvec", - "unicode-bom", -] - -[[package]] -name = "gix-config-value" -version = "0.21.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7666081ef0ecc5e1dc54bc6ce16dac9d7b9490780f6c130393ef9e50c909d4a" -dependencies = [ - "bitflags 2.11.1", - "bstr", - "gix-error", - "gix-path", - "gix-utils", - "libc", -] - -[[package]] -name = "gix-credentials" -version = "0.42.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8487f709886267337ee39231a5e68f3c6a4e28fd59e056fc9e66e9638941c633" -dependencies = [ - "bstr", - "gix-command", - "gix-config-value", - "gix-date", - "gix-error", - "gix-path", - "gix-prompt", - "gix-quote", - "gix-sec", - "gix-trace", - "gix-url", - "percent-encoding", -] - -[[package]] -name = "gix-date" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c538190012dbb536df54734ec38cc1109270c73f2f76585c011dd5b0c9f087c" -dependencies = [ - "bstr", - "gix-error", - "itoa", - "jiff 0.2.27", -] - -[[package]] -name = "gix-diff" -version = "0.70.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c794988335792f85c3ca79c385c950b3a921a71ba3df361cb1f9e5b6bd4a6e4" -dependencies = [ - "bstr", - "gix-attributes", - "gix-command", - "gix-error", - "gix-filter", - "gix-fs", - "gix-hash", - "gix-imara-diff", - "gix-index", - "gix-object", - "gix-path", - "gix-pathspec", - "gix-tempfile", - "gix-trace", - "gix-traverse", - "gix-worktree", -] - -[[package]] -name = "gix-dir" -version = "0.32.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af939f21c65d4f15457c72d08c874d454893185c51a3596e3c2bd3d9c567618d" -dependencies = [ - "bstr", - "gix-discover", - "gix-error", - "gix-fs", - "gix-ignore", - "gix-index", - "gix-object", - "gix-path", - "gix-pathspec", - "gix-trace", - "gix-utils", - "gix-worktree", -] - -[[package]] -name = "gix-discover" -version = "0.57.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a0875f4e5408713fcf92265973cc38bf9dc5a93384ce218beba0572b7785a03" -dependencies = [ - "bstr", - "dunce", - "gix-error", - "gix-fs", - "gix-path", - "gix-ref", - "gix-sec", -] - -[[package]] -name = "gix-error" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50ad6c42fa50280f382026ff838a8afa7ab2ad83e92349cab4392972baae69cd" -dependencies = [ - "bstr", -] - -[[package]] -name = "gix-filter" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8df8d50fda4684c6ec366f75e4082ab6fc3d437d3deec30ff88462710b68d17" -dependencies = [ - "bstr", - "encoding_rs", - "gix-attributes", - "gix-command", - "gix-error", - "gix-hash", - "gix-object", - "gix-packetline", - "gix-path", - "gix-quote", - "gix-trace", - "gix-utils", - "smallvec", -] - -[[package]] -name = "gix-fs" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "808f23d897ddfe847d9b7206bda947901885be623bdf96b226a2dccf87f018c7" -dependencies = [ - "bstr", - "gix-error", - "gix-parallel", - "gix-path", - "gix-utils", - "libc", - "walkdir", -] - -[[package]] -name = "gix-glob" -version = "0.29.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a12789fa68a150293ad8834d267b31044240532b5ccf2734d228fe985cba2be" -dependencies = [ - "bitflags 2.11.1", - "bstr", - "gix-fs", - "gix-path", - "gix-trace", - "gix-utils", -] - -[[package]] -name = "gix-hash" -version = "0.28.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4802ffb87e051795822bfdaa8ab9075b23e316684f7054e6ce4a246b2b76f4e" -dependencies = [ - "faster-hex 0.10.1", - "gix-error", - "gix-utils", - "sha1dc", -] - -[[package]] -name = "gix-hashtable" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f66822aee11ccb28d6a2e63b587254e578fb52a138bd5806b58d8560125592b" -dependencies = [ - "gix-hash", - "hashbrown 0.17.2", - "parking_lot 0.12.5", -] - -[[package]] -name = "gix-ignore" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "968f12fe42896873504f46127cd5bf0f9a34fc1479a781f43cf94b5d8d760a15" -dependencies = [ - "bstr", - "gix-glob", - "gix-path", - "gix-trace", - "unicode-bom", -] - -[[package]] -name = "gix-imara-diff" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23347fa4a29a440eebf045d0bc21da465c0dc70434c2a4bcdfcc658f16c9e27e" -dependencies = [ - "bstr", - "hashbrown 0.15.5", -] - -[[package]] -name = "gix-index" -version = "0.58.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06bfc736774a623307eda890c918d308ef5acd37402bde2d6768fccb1f6ecb5d" -dependencies = [ - "bitflags 2.11.1", - "bstr", - "filetime", - "fnv", - "gix-bitmap", - "gix-error", - "gix-fs", - "gix-hash", - "gix-lock", - "gix-object", - "gix-parallel", - "gix-trace", - "gix-traverse", - "gix-utils", - "gix-validate", - "hashbrown 0.17.2", - "itoa", - "libc", - "memmap2", - "rustix 1.1.6", - "smallvec", -] - -[[package]] -name = "gix-lock" -version = "26.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64783de116c477c5ea4a7f3b56e18ab363dabfdae2724291ea0587b642cadb3d" -dependencies = [ - "gix-error", - "gix-fs", - "gix-tempfile", - "gix-utils", -] - -[[package]] -name = "gix-macros" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79ca2ec664aea06d549444f9cd35546dd1732b2ea188b48159cea4fbf2a05848" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "gix-negotiate" -version = "0.38.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "148bee10394df68d44c245e05b4c0747edf19144405c6c36a9eee29db9bb250d" -dependencies = [ - "bitflags 2.11.1", - "gix-commitgraph", - "gix-date", - "gix-error", - "gix-hash", - "gix-object", - "gix-revwalk", -] - -[[package]] -name = "gix-note" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8473688f2262f4364f521b39ce2a5dbe94494f327fc19c945318d7aff580952e" -dependencies = [ - "gix-error", - "gix-hash", - "gix-object", -] - -[[package]] -name = "gix-object" -version = "0.66.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "beaf9086dd00b9d2a177ca3ae83210ce926cee7c0faa112e053851221cd8f94d" -dependencies = [ - "bstr", - "gix-actor", - "gix-command", - "gix-date", - "gix-error", - "gix-hash", - "gix-hashtable", - "gix-path", - "gix-tempfile", - "gix-utils", - "gix-validate", - "itoa", - "smallvec", -] - -[[package]] -name = "gix-odb" -version = "0.87.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "941b5b99fed282a5b05b54ea486c36c76b558afe151e6804c3acdd5c8f3c3459" -dependencies = [ - "arc-swap", - "crc32fast", - "gix-error", - "gix-fs", - "gix-hash", - "gix-hashtable", - "gix-object", - "gix-pack", - "gix-parallel", - "gix-path", - "gix-quote", - "gix-trace", - "gix-utils", - "gix-zlib", - "memmap2", - "parking_lot 0.12.5", - "tempfile", -] - -[[package]] -name = "gix-pack" -version = "0.77.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2ef461798b1e6cb652192c69dfc9658dfc1bab457ef812dd1ab85d75104cbef" -dependencies = [ - "clru", - "crc32fast", - "gix-chunk", - "gix-error", - "gix-hash", - "gix-hashtable", - "gix-object", - "gix-parallel", - "gix-path", - "gix-tempfile", - "gix-trace", - "gix-utils", - "gix-zlib", - "memmap2", - "parking_lot 0.12.5", - "smallvec", -] - -[[package]] -name = "gix-packetline" -version = "0.24.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e198121152a397ad1007e3334931b04b393fa17f6af34f17b33e376b15bf5ea" -dependencies = [ - "bstr", - "faster-hex 2.1.0", - "gix-error", - "gix-trace", -] - -[[package]] -name = "gix-parallel" -version = "0.50.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3a5c86eeec0194a3444611b4762ba05cc5029408a617348b4f6a74a34c222cd" -dependencies = [ - "crossbeam-channel", - "gix-trace", - "once_cell", - "parking_lot 0.13.0", -] - -[[package]] -name = "gix-path" -version = "0.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "615e3ff75800c67022ec8065b67e0846420a88c5f484e6c4fd81c78472e4c77a" -dependencies = [ - "bstr", - "gix-error", - "gix-trace", - "gix-validate", - "winreg", -] - -[[package]] -name = "gix-pathspec" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "490aa03a11e0cbb998a0a593b75e27ea2e30df4ebd8f84f60e0641b9b72270e8" -dependencies = [ - "bitflags 2.11.1", - "bstr", - "gix-attributes", - "gix-config-value", - "gix-error", - "gix-glob", - "gix-path", -] - -[[package]] -name = "gix-prompt" -version = "0.19.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e090a9a8faea3a6ba8b341aa7f209a7d889f53663aa504b7f4b0151c8dfcbf68" -dependencies = [ - "gix-command", - "gix-config-value", - "gix-error", - "parking_lot 0.13.0", - "rustix 1.1.6", -] - -[[package]] -name = "gix-protocol" -version = "0.68.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83677ebae6a1a09dc07f2435b5ebe68470dc51afb74052135e98fd7c11f85ba9" -dependencies = [ - "bstr", - "gix-credentials", - "gix-date", - "gix-error", - "gix-hash", - "gix-lock", - "gix-macros", - "gix-negotiate", - "gix-object", - "gix-ref", - "gix-refspec", - "gix-revwalk", - "gix-shallow", - "gix-trace", - "gix-transport", - "gix-utils", - "nonempty", -] - -[[package]] -name = "gix-quote" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5069a7ec021bb47abe9f12dcc075d292e8cf4a9dff5fffd38595b39c6b419aaa" -dependencies = [ - "bstr", - "gix-error", - "gix-utils", -] - -[[package]] -name = "gix-ref" -version = "0.69.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68686e4697b9cd15d1b152ef51df870513210ed22938eacc13b3672b76035f13" -dependencies = [ - "gix-actor", - "gix-error", - "gix-fs", - "gix-hash", - "gix-lock", - "gix-object", - "gix-parallel", - "gix-path", - "gix-tempfile", - "gix-utils", - "gix-validate", - "memmap2", -] - -[[package]] -name = "gix-refspec" -version = "0.47.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2569309da6fdc230973cf5b846508154c0e813fda60f2b2da768cc5655ed312c" -dependencies = [ - "bstr", - "gix-error", - "gix-hash", - "gix-validate", - "smallvec", -] - -[[package]] -name = "gix-revision" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "241465fc73530f41d0a1c18320c5e291365b7c2c2a3dfd07afe2a5d6265085c8" -dependencies = [ - "bitflags 2.11.1", - "bstr", - "gix-commitgraph", - "gix-date", - "gix-error", - "gix-hash", - "gix-hashtable", - "gix-object", - "gix-revwalk", - "gix-trace", - "nonempty", -] - -[[package]] -name = "gix-revwalk" -version = "0.38.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b46edeacd25d9d3131941ae6bc91002bf7ba10e130393b7e9bc23d528625447" -dependencies = [ - "gix-commitgraph", - "gix-date", - "gix-error", - "gix-hash", - "gix-hashtable", - "gix-object", - "smallvec", -] - -[[package]] -name = "gix-sec" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9598d1f35baec7038c2d278bfcc18f1d8951f41dcc3f51ab6175661dfe5a6137" -dependencies = [ - "bitflags 2.11.1", - "gix-path", - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "gix-shallow" -version = "0.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d805949578724b5164c90ec6d19567832ccaa5ba8a3fe26f7befc52007e2407" -dependencies = [ - "bstr", - "gix-error", - "gix-hash", - "gix-lock", - "nonempty", -] - -[[package]] -name = "gix-status" -version = "0.37.0" +name = "futures-channel" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31b00c359278210e3cc0803d057db1d61c5d6694c21ed9ad0b8f8f862157247a" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ - "bstr", - "filetime", - "gix-diff", - "gix-dir", - "gix-error", - "gix-filter", - "gix-fs", - "gix-hash", - "gix-index", - "gix-object", - "gix-parallel", - "gix-path", - "gix-pathspec", - "gix-trace", - "gix-utils", - "gix-worktree", - "hashbrown 0.16.1", - "portable-atomic", + "futures-core", + "futures-sink", ] [[package]] -name = "gix-submodule" -version = "0.36.1" +name = "futures-core" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d558a1307b6f3de2a92bd91d0570c53952d4f2329e6860813007508c8ed413dc" -dependencies = [ - "bstr", - "gix-config", - "gix-error", - "gix-path", - "gix-pathspec", - "gix-refspec", - "gix-url", -] +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" [[package]] -name = "gix-tempfile" -version = "26.0.1" +name = "futures-executor" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8fdb135a043d6106b59bc58d59a326b277e495ec26fb9e02a1e2b6354bf4b5a" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" dependencies = [ - "dashmap", - "gix-fs", - "libc", - "parking_lot 0.12.5", - "signal-hook 0.4.4", - "signal-hook-registry", - "tempfile", - "windows-sys 0.61.2", + "futures-core", + "futures-task", + "futures-util", ] [[package]] -name = "gix-trace" -version = "0.3.2" +name = "futures-io" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c96f84d731a96780e6a7ad5ee70b4ecc398499946b62617945fbaeb6ab878f8" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" [[package]] -name = "gix-transport" -version = "0.62.0" +name = "futures-macro" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdcd9cdfd8745aa38f926a4a380c13d76b200d7338de57fc492982cd5a6652ba" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ - "bstr", - "gix-command", - "gix-error", - "gix-packetline", - "gix-path", - "gix-quote", - "gix-sec", - "gix-trace", - "gix-url", - "gix-utils", + "proc-macro2", + "quote", + "syn 3.0.10", ] [[package]] -name = "gix-traverse" -version = "0.64.0" +name = "futures-sink" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00171e00e91508300d0361072c4eb110ec0f1322d8b95ed36887231702a38ebc" -dependencies = [ - "bitflags 2.11.1", - "gix-commitgraph", - "gix-date", - "gix-error", - "gix-hash", - "gix-hashtable", - "gix-object", - "gix-revwalk", - "smallvec", -] +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" [[package]] -name = "gix-url" -version = "0.40.1" +name = "futures-task" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "def12e1016b872f1094442882f627905c59bd73480435291a4958cf373a8f28d" -dependencies = [ - "bstr", - "gix-error", - "gix-path", - "gix-utils", - "percent-encoding", -] +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" [[package]] -name = "gix-utils" -version = "0.5.3" +name = "futures-util" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6d46894c7a4fd9c5e26d233a0fa836002ba0af9a11aef58923d317c486e10" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ - "bstr", - "bytes", - "fastrand", - "getrandom 0.4.2", - "gix-error", - "prodash", - "unicode-normalization", + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", ] [[package]] -name = "gix-validate" -version = "0.13.2" +name = "generator" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d6f293fd8abd9bd9bc1e0a23541f73607e932b5a2bde2246320da38edde5726" +checksum = "52f04ae4152da20c76fe800fa48659201d5cf627c5149ca0b707b69d7eef6cf9" dependencies = [ - "bstr", - "gix-error", + "cc", + "cfg-if", + "libc", + "log", + "rustversion", + "windows-link 0.2.1", + "windows-result 0.4.1", ] [[package]] -name = "gix-worktree" -version = "0.59.0" +name = "generic-array" +version = "0.14.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe92aec0a25cf073394492a6ee2aa4d27632acde91a653d34de0e4da6afb485d" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ - "bstr", - "dua-core", - "gix-attributes", - "gix-error", - "gix-fs", - "gix-glob", - "gix-hash", - "gix-ignore", - "gix-index", - "gix-object", - "gix-path", - "gix-trace", - "gix-utils", - "gix-validate", + "typenum", + "version_check", ] [[package]] -name = "gix-worktree-state" -version = "0.37.0" +name = "getrandom" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18abf655ef8b8467657ac64b337171a9f4612ca6a421858a765857584beec9e8" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ - "bstr", - "gix-error", - "gix-filter", - "gix-fs", - "gix-index", - "gix-object", - "gix-parallel", - "gix-path", - "gix-trace", - "gix-utils", - "gix-worktree", - "io-close", + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", ] [[package]] -name = "gix-worktree-stream" -version = "0.39.0" +name = "getrandom" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fe5d65793848ffb596f6c5596fd120b132038736525628227e2388ca454f64d" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ - "gix-attributes", - "gix-error", - "gix-filter", - "gix-fs", - "gix-hash", - "gix-object", - "gix-parallel", - "gix-path", - "gix-trace", - "gix-traverse", - "gix-utils", - "parking_lot 0.12.5", + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", ] [[package]] -name = "gix-zlib" -version = "0.4.1" +name = "getrandom" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81a49a8b263d2a140f1c178ff93375b8d4cc7b1d3252cd87ce1ca88bce62b9b9" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ - "gix-error", - "zlib-rs", + "cfg-if", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasip2", + "wasip3", ] +[[package]] +name = "gimli" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" + [[package]] name = "glob" version = "0.3.3" @@ -3167,21 +2151,6 @@ dependencies = [ "simdutf8", ] -[[package]] -name = "hash32" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" -dependencies = [ - "byteorder", -] - -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" - [[package]] name = "hashbrown" version = "0.15.5" @@ -3237,16 +2206,6 @@ dependencies = [ "http", ] -[[package]] -name = "heapless" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" -dependencies = [ - "hash32", - "stable_deref_trait", -] - [[package]] name = "heck" version = "0.5.0" @@ -3591,16 +2550,6 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" -[[package]] -name = "io-close" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cadcf447f06744f8ce713d2d6239bb5bde2c357a452397a9ed90c625da390bc" -dependencies = [ - "libc", - "winapi", -] - [[package]] name = "ipnet" version = "2.12.2" @@ -3638,12 +2587,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "392c70591e8749fe235ddaf513e6f58b26bce3dcc16524cecc8936f75afa161e" dependencies = [ "jiff-static 0.2.27", - "jiff-tzdb-platform", "log", "portable-atomic", "portable-atomic-util", "serde_core", - "windows-link 0.2.1", ] [[package]] @@ -3654,7 +2601,7 @@ checksum = "c5e77cbfb9fff4798e283c2d69dff39fc2c45e7da017e5ce95b654e46ea41236" dependencies = [ "jiff-core", "jiff-static 1.0.2", - "jiff-tzdb 1.0.0", + "jiff-tzdb", "log", "portable-atomic", "portable-atomic-util", @@ -3694,27 +2641,12 @@ dependencies = [ "syn 3.0.10", ] -[[package]] -name = "jiff-tzdb" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e" - [[package]] name = "jiff-tzdb" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc" -[[package]] -name = "jiff-tzdb-platform" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" -dependencies = [ - "jiff-tzdb 0.1.8", -] - [[package]] name = "jni" version = "0.22.4" @@ -4147,15 +3079,6 @@ dependencies = [ "scopeguard", ] -[[package]] -name = "lock_api" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65d91b22da179613dcf4d6ec8349563f52a363f6849e03b00dd0a185ec4a59af" -dependencies = [ - "scopeguard", -] - [[package]] name = "log" version = "0.4.32" @@ -4250,15 +3173,6 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" -[[package]] -name = "memmap2" -version = "0.9.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" -dependencies = [ - "libc", -] - [[package]] name = "memoffset" version = "0.9.1" @@ -4455,12 +3369,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "nonempty" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9737e026353e5cd0736f98eddae28665118eb6f6600902a7f50db585621fecb6" - [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -4706,7 +3614,6 @@ dependencies = [ "tracing", "tracing-subscriber", "treediff", - "vergen-gix", ] [[package]] @@ -4735,18 +3642,8 @@ version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" dependencies = [ - "lock_api 0.4.14", - "parking_lot_core 0.9.12", -] - -[[package]] -name = "parking_lot" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9cf937ca4e1d0b7578784559063422fc39ae7c5a00f02471f2614d5486fd226" -dependencies = [ - "lock_api 0.5.0", - "parking_lot_core 0.10.0", + "lock_api", + "parking_lot_core", ] [[package]] @@ -4757,19 +3654,7 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.5.18", - "smallvec", - "windows-link 0.2.1", -] - -[[package]] -name = "parking_lot_core" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cfff060068cc18aa7815010fcaf80c68c7fb9e85fc7f5c0f9bf142c21d19826" -dependencies = [ - "libc", - "redox_syscall 0.9.5", + "redox_syscall", "smallvec", "windows-link 0.2.1", ] @@ -5080,15 +3965,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "prodash" -version = "31.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf52d87428247c5aa3760ac8e7d8b13ec7b3579b955a8c3f311668b6860acba5" -dependencies = [ - "parking_lot 0.12.5", -] - [[package]] name = "prometheus-exposition" version = "0.1.0" @@ -5430,15 +4306,6 @@ dependencies = [ "bitflags 2.11.1", ] -[[package]] -name = "redox_syscall" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" -dependencies = [ - "bitflags 2.11.1", -] - [[package]] name = "ref-cast" version = "1.0.27" @@ -5880,7 +4747,7 @@ dependencies = [ "datadog-protos", "ddsketch", "dhat", - "faster-hex 1.0.0", + "faster-hex", "float-cmp", "fnv", "foldhash 0.2.0", @@ -6528,12 +5395,6 @@ dependencies = [ "digest 0.11.3", ] -[[package]] -name = "sha1dc" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5b0ebf6537e3e8db8bb7d21ecb6d7399738c953c757945c6b95e46c4e95df7b" - [[package]] name = "sha2" version = "0.10.9" @@ -6592,16 +5453,6 @@ dependencies = [ "signal-hook-registry", ] -[[package]] -name = "signal-hook" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a0c28ca5908dbdbcd52e6fdaa00358ab88637f8ab33e1f188dd510eb44b53d" -dependencies = [ - "libc", - "signal-hook-registry", -] - [[package]] name = "signal-hook-mio" version = "0.2.5" @@ -6610,7 +5461,7 @@ checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" dependencies = [ "libc", "mio", - "signal-hook 0.3.18", + "signal-hook", ] [[package]] @@ -6933,7 +5784,7 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "662b54ef6f7b4e71f683dadc787bbb2d8e8ef2f91b682ebed3164a5a7abca905" dependencies = [ - "parking_lot 0.12.5", + "parking_lot", "pin-project", ] @@ -7064,21 +5915,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "tinyvec" -version = "1.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cf0ded5c4e56918d8f8a339e1bb67d038d3bc6d144ac407904015ba2e4cde9b" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - [[package]] name = "tokio" version = "1.54.1" @@ -7574,27 +6410,12 @@ dependencies = [ "version_check", ] -[[package]] -name = "unicode-bom" -version = "2.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7eec5d1121208364f6793f7d2e222bf75a915c19557537745b195b253dd64217" - [[package]] name = "unicode-ident" version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" -[[package]] -name = "unicode-normalization" -version = "0.1.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" -dependencies = [ - "tinyvec", -] - [[package]] name = "unicode-segmentation" version = "1.13.2" @@ -7672,44 +6493,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" -[[package]] -name = "vergen" -version = "10.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1e657ec41dc2e06c78ab6f8228914c6e8c4b604b485d8f7436f4081e8565938" -dependencies = [ - "anyhow", - "bon", - "rustversion", - "vergen-lib", -] - -[[package]] -name = "vergen-gix" -version = "10.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0675d2a71d99c561f92633144d023acb83dcdf595b2b5d10456ce6a08746f3c5" -dependencies = [ - "anyhow", - "bon", - "gix", - "rustversion", - "time", - "vergen", - "vergen-lib", -] - -[[package]] -name = "vergen-lib" -version = "10.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7693a14090017adc8eac3c3af50fa3b502b567e85b9f524ee089be122021d50" -dependencies = [ - "anyhow", - "bon", - "rustversion", -] - [[package]] name = "version_check" version = "0.9.5" @@ -8162,16 +6945,6 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1" -[[package]] -name = "winreg" -version = "0.56.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" -dependencies = [ - "cfg-if", - "windows-sys 0.61.2", -] - [[package]] name = "wit-bindgen" version = "0.51.0" @@ -8410,12 +7183,6 @@ dependencies = [ "syn 3.0.10", ] -[[package]] -name = "zlib-rs" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" - [[package]] name = "zmij" version = "1.0.21" diff --git a/Cargo.toml b/Cargo.toml index bfe90361c3d..9317168ffe5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -279,7 +279,6 @@ opentelemetry-semantic-conventions = { version = "0.33.0", default-features = fa comfy-table = { version = "8", default-features = false } dtoa = { version = "1", default-features = false } itoa = { version = "1", default-features = false } -vergen-gix = { version = "10", default-features = false } ryu = { version = "1", default-features = false } ryu-js = { version = "1.0.4", default-features = false } colored = { version = "3", default-features = false } diff --git a/LICENSE-3rdparty.csv b/LICENSE-3rdparty.csv index 686f01c26be..7320a4728e8 100644 --- a/LICENSE-3rdparty.csv +++ b/LICENSE-3rdparty.csv @@ -44,10 +44,7 @@ bitmask-enum,https://github.com/Lukas3674/rust-bitmask-enum,MIT OR Apache-2.0,Lu block-buffer,https://github.com/RustCrypto/utils,MIT OR Apache-2.0,RustCrypto Developers bollard,https://github.com/fussybeaver/bollard,Apache-2.0,Bollard contributors bollard-stubs,https://github.com/fussybeaver/bollard,Apache-2.0,Bollard contributors -bon,https://github.com/elastio/bon,MIT OR Apache-2.0,The bon Authors -bon-macros,https://github.com/elastio/bon,MIT OR Apache-2.0,The bon-macros Authors borrow-or-share,https://github.com/yescallop/borrow-or-share,MIT-0,Scallop Ye -bstr,https://github.com/BurntSushi/bstr,MIT OR Apache-2.0,Andrew Gallant bumpalo,https://github.com/fitzgen/bumpalo,MIT OR Apache-2.0,Nick Fitzgerald byte-unit,https://github.com/magiclen/byte-unit,MIT,Magic Len bytemuck,https://github.com/Lokathor/bytemuck,Zlib OR Apache-2.0 OR MIT,Lokathor @@ -72,7 +69,6 @@ clap,https://github.com/clap-rs/clap,MIT OR Apache-2.0,The clap Authors clap_builder,https://github.com/clap-rs/clap,MIT OR Apache-2.0,The clap_builder Authors clap_derive,https://github.com/clap-rs/clap,MIT OR Apache-2.0,The clap_derive Authors clap_lex,https://github.com/clap-rs/clap,MIT OR Apache-2.0,The clap_lex Authors -clru,https://github.com/marmeladema/clru-rs,MIT,marmeladema colored,https://github.com/mackwic/colored,MPL-2.0,Thomas Wickham combine,https://github.com/Marwes/combine,MIT,Markus Westerlind comfy-table,https://github.com/nukesor/comfy-table,MIT,Arne Beer @@ -88,7 +84,6 @@ core_detect,https://github.com/thomcc/core_detect,MIT OR Apache-2.0,Thom Chiovol cpufeatures,https://github.com/RustCrypto/utils,MIT OR Apache-2.0,RustCrypto Developers crc32fast,https://github.com/srijs/rust-crc32fast,MIT OR Apache-2.0,"Sam Rijs , Alex Crichton " criterion-plot,https://github.com/criterion-rs/criterion.rs,Apache-2.0 OR MIT,"Jorge Aparicio , Brook Heisler " -crossbeam,https://github.com/crossbeam-rs/crossbeam,MIT OR Apache-2.0,The crossbeam Authors crossbeam-channel,https://github.com/crossbeam-rs/crossbeam,MIT OR Apache-2.0,The crossbeam-channel Authors crossbeam-deque,https://github.com/crossbeam-rs/crossbeam,MIT OR Apache-2.0,The crossbeam-deque Authors crossbeam-epoch,https://github.com/crossbeam-rs/crossbeam,MIT OR Apache-2.0,The crossbeam-epoch Authors @@ -101,7 +96,6 @@ crypto-common,https://github.com/RustCrypto/traits,MIT OR Apache-2.0,RustCrypto darling,https://github.com/TedDriggs/darling,MIT,Ted Driggs darling_core,https://github.com/TedDriggs/darling,MIT,Ted Driggs darling_macro,https://github.com/TedDriggs/darling,MIT,Ted Driggs -dashmap,https://github.com/xacrimon/dashmap,MIT,Acrimon data-encoding,https://github.com/ia0/data-encoding,MIT,Julien Cretin debug-ignore,https://github.com/sunshowers-code/debug-ignore,MIT OR Apache-2.0,The debug-ignore Authors defmt,https://github.com/knurling-rs/defmt,MIT OR Apache-2.0,The Knurling-rs developers @@ -116,8 +110,6 @@ derive_more-impl,https://github.com/JelteF/derive_more,MIT,Jelte Fennema document-features,https://github.com/slint-ui/document-features,MIT OR Apache-2.0,Slint Developers -dua-core,https://github.com/Byron/dua-cli,MIT,Sebastian Thiel dyn-clone,https://github.com/dtolnay/dyn-clone,MIT OR Apache-2.0,David Tolnay either,https://github.com/rayon-rs/either,MIT OR Apache-2.0,bluss encoding_rs,https://github.com/hsivonen/encoding_rs,(Apache-2.0 OR MIT) AND BSD-3-Clause,Henri Sivonen @@ -125,7 +117,6 @@ encoding_rs_io,https://github.com/BurntSushi/encoding_rs_io,MIT OR Apache-2.0,An enum_dispatch,https://gitlab.com/antonok/enum_dispatch,MIT OR Apache-2.0,Anton Lazarev equivalent,https://github.com/indexmap-rs/equivalent,Apache-2.0 OR MIT,The equivalent Authors errno,https://github.com/lambda-fairy/rust-errno,MIT OR Apache-2.0,"Chris Wong , Dan Gohman " -faster-hex,https://github.com/NervosFoundation/faster-hex,MIT,zhangsoledad <787953403@qq.com> faster-hex,https://github.com/nervosnetwork/faster-hex,MIT,zhangsoledad <787953403@qq.com> fastrand,https://github.com/smol-rs/fastrand,Apache-2.0 OR MIT,Stjepan Glavina figment,https://github.com/SergioBenitez/Figment,MIT OR Apache-2.0,Sergio Benitez @@ -152,74 +143,16 @@ generator,https://github.com/Xudong-Huang/generator-rs,MIT OR Apache-2.0,Xudong generic-array,https://github.com/fizyk20/generic-array,MIT,"Bartłomiej Kamiński , Aaron Trent " getrandom,https://github.com/rust-random/getrandom,MIT OR Apache-2.0,The Rand Project Developers gimli,https://github.com/gimli-rs/gimli,MIT OR Apache-2.0,The gimli Authors -gix,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-actor,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-attributes,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-bitmap,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-chunk,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-command,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-commitgraph,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,"Conor Davis , Sebastian Thiel " -gix-config,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Edward Shen -gix-config-value,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-credentials,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-date,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-diff,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-dir,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-discover,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-error,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-filter,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-fs,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-glob,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-hash,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-hashtable,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Pascal Kuthe -gix-ignore,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-imara-diff,https://github.com/GitoxideLabs/gitoxide,Apache-2.0,"pascalkuthe , Sebastian Thiel " -gix-index,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-lock,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-macros,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,"Jiahao XU , Andre Bogus , Sebastian Thiel " -gix-negotiate,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-note,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-object,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-odb,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-pack,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-packetline,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-parallel,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-path,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-pathspec,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-prompt,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-protocol,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-quote,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-ref,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-refspec,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-revision,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-revwalk,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-sec,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-shallow,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-status,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,"Sebastian Thiel , Pascal Kuthe " -gix-submodule,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-tempfile,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-trace,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-transport,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-traverse,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-url,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-utils,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-validate,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-worktree,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-worktree-state,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-worktree-stream,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel -gix-zlib,https://github.com/GitoxideLabs/gitoxide,MIT OR Apache-2.0,Sebastian Thiel glob,https://github.com/rust-lang/glob,MIT OR Apache-2.0,The Rust Project Developers granit-parser,https://github.com/bourumir-wyngs/granit-parser,MIT OR Apache-2.0,"Ethiraric , David Aguilar , Yuheng Chen , Bourumir Wyngs " guppy,https://github.com/guppy-rs/guppy,MIT OR Apache-2.0,"Rain , Brandon Williams " guppy-workspace-hack,https://github.com/facebookincubator/cargo-guppy,MIT OR Apache-2.0,The guppy-workspace-hack Authors h2,https://github.com/hyperium/h2,MIT,"Carl Lerche , Sean McArthur " half,https://github.com/VoidStarKat/half-rs,MIT OR Apache-2.0,Kathryn Long -hash32,https://github.com/japaric/hash32,MIT OR Apache-2.0,Jorge Aparicio hashbrown,https://github.com/rust-lang/hashbrown,MIT OR Apache-2.0,Amanieu d'Antras hashbrown,https://github.com/rust-lang/hashbrown,MIT OR Apache-2.0,The hashbrown Authors headers,https://github.com/hyperium/headers,MIT,Sean McArthur headers-core,https://github.com/hyperium/headers,MIT,Sean McArthur -heapless,https://github.com/rust-embedded/heapless,MIT OR Apache-2.0,"Jorge Aparicio , Per Lindgren , Emil Fresk " heck,https://github.com/withoutboats/heck,MIT OR Apache-2.0,The heck Authors hex,https://github.com/KokaKiwi/rust-hex,MIT OR Apache-2.0,KokaKiwi home,https://github.com/rust-lang/cargo,MIT OR Apache-2.0,Brian Anderson @@ -250,7 +183,6 @@ idna,https://github.com/servo/rust-url,MIT OR Apache-2.0,The rust-url developers idna_adapter,https://github.com/hsivonen/idna_adapter,Apache-2.0 OR MIT,The rust-url developers indexmap,https://github.com/indexmap-rs/indexmap,Apache-2.0 OR MIT,The indexmap Authors inlinable_string,https://github.com/fitzgen/inlinable_string,Apache-2.0 OR MIT,Nick Fitzgerald -io-close,https://gitlab.com/wufz/io-close,MIT OR Apache-2.0,wufz ipnet,https://github.com/krisprice/ipnet,MIT OR Apache-2.0,Kris Price itertools,https://github.com/rust-itertools/itertools,MIT OR Apache-2.0,bluss itoa,https://github.com/dtolnay/itoa,MIT OR Apache-2.0,David Tolnay @@ -258,7 +190,6 @@ jiff,https://github.com/BurntSushi/jiff,Unlicense OR MIT,Andrew Gallant jiff-static,https://github.com/BurntSushi/jiff,Unlicense OR MIT,Andrew Gallant jiff-tzdb,https://github.com/BurntSushi/jiff,Unlicense OR MIT,Andrew Gallant -jiff-tzdb-platform,https://github.com/BurntSushi/jiff,Unlicense OR MIT,Andrew Gallant jni,https://github.com/jni-rs/jni-rs,MIT OR Apache-2.0,jni team jni-macros,https://github.com/jni-rs/jni-rs,MIT OR Apache-2.0,The jni-macros Authors jni-sys,https://github.com/jni-rs/jni-sys,MIT OR Apache-2.0,"Steven Fackler , Robert Bragg " @@ -306,7 +237,6 @@ matchers,https://github.com/hawkw/matchers,MIT,Eliza Weisman matchit,https://github.com/ibraheemdev/matchit,MIT AND BSD-3-Clause,Ibraheem Ahmed matrixmultiply,https://github.com/bluss/matrixmultiply,MIT OR Apache-2.0,"bluss, R. Janis Goldschmidt" memchr,https://github.com/BurntSushi/memchr,Unlicense OR MIT,"Andrew Gallant , bluss" -memmap2,https://github.com/RazrFalcon/memmap2-rs,MIT OR Apache-2.0,"Dan Burkert , Yevhenii Reizner , The Contributors" memoffset,https://github.com/Gilnaa/memoffset,MIT,Gilad Naaman metrics,https://github.com/metrics-rs/metrics,MIT,Toby Lawrence metrics-util,https://github.com/metrics-rs/metrics,MIT,Toby Lawrence @@ -323,7 +253,6 @@ nohash-hasher,https://github.com/paritytech/nohash-hasher,Apache-2.0 OR MIT,Pari noisy_float,https://github.com/SergiusIW/noisy_float-rs,Apache-2.0,Matthew Michelotti nom,https://github.com/Geal/nom,MIT,contact@geoffroycouprie.com nom,https://github.com/rust-bakery/nom,MIT,contact@geoffroycouprie.com -nonempty,https://github.com/cloudhead/nonempty,MIT,Alexis Sellier nu-ansi-term,https://github.com/nushell/nu-ansi-term,MIT,"ogham@bsago.me, Ryan Scheel (Havvy) , Josh Triplett , The Nushell Project Developers" num-bigint,https://github.com/rust-num/num-bigint,MIT OR Apache-2.0,The Rust Project Developers num-complex,https://github.com/rust-num/num-complex,MIT OR Apache-2.0,The Rust Project Developers @@ -373,7 +302,6 @@ ppv-lite86,https://github.com/cryptocorrosion/cryptocorrosion,MIT OR Apache-2.0, prettyplease,https://github.com/dtolnay/prettyplease,MIT OR Apache-2.0,David Tolnay proc-macro2,https://github.com/dtolnay/proc-macro2,MIT OR Apache-2.0,"David Tolnay , Alex Crichton " proc-macro2-diagnostics,https://github.com/SergioBenitez/proc-macro2-diagnostics,MIT OR Apache-2.0,Sergio Benitez -prodash,https://github.com/GitoxideLabs/prodash,MIT,Sebastian Thiel proptest,https://github.com/proptest-rs/proptest,MIT OR Apache-2.0,Jason Lingle prost,https://github.com/tokio-rs/prost,Apache-2.0,"Dan Burkert , Lucio Franco , Casper Meijn , Tokio Contributors " prost-build,https://github.com/tokio-rs/prost,Apache-2.0,"Dan Burkert , Lucio Franco , Casper Meijn , Tokio Contributors " @@ -398,7 +326,6 @@ rawpointer,https://github.com/bluss/rawpointer,MIT OR Apache-2.0,bluss rayon,https://github.com/rayon-rs/rayon,MIT OR Apache-2.0,The rayon Authors rayon-core,https://github.com/rayon-rs/rayon,MIT OR Apache-2.0,The rayon-core Authors rcgen,https://github.com/rustls/rcgen,MIT OR Apache-2.0,The rcgen Authors -redox_syscall,https://gitlab.redox-os.org/redox-os/kernel,MIT,Jeremy Soller redox_syscall,https://gitlab.redox-os.org/redox-os/syscall,MIT,Jeremy Soller ref-cast,https://github.com/dtolnay/ref-cast,MIT OR Apache-2.0,David Tolnay ref-cast-impl,https://github.com/dtolnay/ref-cast,MIT OR Apache-2.0,David Tolnay @@ -461,13 +388,11 @@ serde_with,https://github.com/jonasbb/serde_with,MIT OR Apache-2.0,"Jonas Bushar serde_with_macros,https://github.com/jonasbb/serde_with,MIT OR Apache-2.0,Jonas Bushart serde_yaml,https://github.com/dtolnay/serde-yaml,MIT OR Apache-2.0,David Tolnay sha1,https://github.com/RustCrypto/hashes,MIT OR Apache-2.0,RustCrypto Developers -sha1dc,https://github.com/srijs/sha1dc,MIT OR Apache-2.0,The sha1dc Authors sha2,https://github.com/RustCrypto/hashes,MIT OR Apache-2.0,RustCrypto Developers shake,https://github.com/RustCrypto/XOFs,MIT OR Apache-2.0,RustCrypto Developers sharded-slab,https://github.com/hawkw/sharded-slab,MIT,Eliza Weisman shlex,https://github.com/comex/rust-shlex,MIT OR Apache-2.0,"comex , Fenhl , Adrian Taylor , Alex Touchet , Daniel Parks , Garrett Berg " signal-hook,https://github.com/vorner/signal-hook,Apache-2.0 OR MIT,"Michal 'vorner' Vaner , Thomas Himmelstoss " -signal-hook,https://github.com/vorner/signal-hook,MIT OR Apache-2.0,"Michal 'vorner' Vaner , Thomas Himmelstoss " signal-hook-mio,https://github.com/vorner/signal-hook,MIT OR Apache-2.0,"Michal 'vorner' Vaner , Thomas Himmelstoss " signal-hook-registry,https://github.com/vorner/signal-hook,MIT OR Apache-2.0,"Michal 'vorner' Vaner , Masaki Hara " simd-adler32,https://github.com/mcountryman/simd-adler32,MIT,Marvin Countryman @@ -510,8 +435,6 @@ time-core,https://github.com/time-rs/time,MIT OR Apache-2.0,"Jacob Pratt , Time contributors" tinystr,https://github.com/unicode-org/icu4x,Unicode-3.0,The ICU4X Project Developers tinytemplate,https://github.com/bheisler/TinyTemplate,Apache-2.0 OR MIT,Brook Heisler -tinyvec,https://github.com/Lokathor/tinyvec,Zlib OR Apache-2.0 OR MIT,Lokathor -tinyvec_macros,https://github.com/Soveu/tinyvec_macros,MIT OR Apache-2.0 OR Zlib,Soveu tokio,https://github.com/tokio-rs/tokio,MIT,Tokio Contributors tokio-macros,https://github.com/tokio-rs/tokio,MIT,Tokio Contributors tokio-rustls,https://github.com/rustls/tokio-rustls,MIT OR Apache-2.0,The tokio-rustls Authors @@ -547,9 +470,7 @@ typify-impl,https://github.com/oxidecomputer/typify,Apache-2.0,The typify-impl A ucd-trie,https://github.com/BurntSushi/ucd-generate,MIT OR Apache-2.0,Andrew Gallant unarray,https://github.com/cameron1024/unarray,MIT OR Apache-2.0,The unarray Authors uncased,https://github.com/SergioBenitez/uncased,MIT OR Apache-2.0,Sergio Benitez -unicode-bom,https://gitlab.com/philbooth/unicode-bom,Apache-2.0,Phil Booth unicode-ident,https://github.com/dtolnay/unicode-ident,(MIT OR Apache-2.0) AND Unicode-3.0,David Tolnay -unicode-normalization,https://github.com/unicode-rs/unicode-normalization,MIT OR Apache-2.0,"kwantam , Manish Goregaokar " unicode-segmentation,https://github.com/unicode-rs/unicode-segmentation,MIT OR Apache-2.0,"kwantam , Manish Goregaokar " unicode-width,https://github.com/unicode-rs/unicode-width,MIT OR Apache-2.0,"kwantam , Manish Goregaokar " unicode-xid,https://github.com/unicode-rs/unicode-xid,MIT OR Apache-2.0,"erick.tryzelaar , kwantam , Manish Goregaokar " @@ -560,8 +481,6 @@ utf8-width,https://github.com/magiclen/utf8-width,MIT,Magic Len uuid,https://github.com/uuid-rs/uuid,Apache-2.0 OR MIT,The uuid Authors valuable,https://github.com/tokio-rs/valuable,MIT,The valuable Authors -vergen,https://github.com/rustyhorde/vergen,MIT OR Apache-2.0,Jason Ozias -vergen-lib,https://github.com/rustyhorde/vergen,MIT OR Apache-2.0,Jason Ozias vsock,https://github.com/rust-vsock/vsock-rs,Apache-2.0,"fsyncd, rust-vsock" walkdir,https://github.com/BurntSushi/walkdir,Unlicense OR MIT,Andrew Gallant want,https://github.com/seanmonstar/want,MIT,Sean McArthur @@ -607,7 +526,6 @@ windows_x86_64_gnu,https://github.com/microsoft/windows-rs,MIT OR Apache-2.0,Mic windows_x86_64_gnullvm,https://github.com/microsoft/windows-rs,MIT OR Apache-2.0,Microsoft windows_x86_64_msvc,https://github.com/microsoft/windows-rs,MIT OR Apache-2.0,Microsoft winnow,https://github.com/winnow-rs/winnow,MIT,The winnow Authors -winreg,https://github.com/gentoo90/winreg-rs,MIT,Igor Shaula wit-bindgen,https://github.com/bytecodealliance/wit-bindgen,Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT,Alex Crichton wit-bindgen-core,https://github.com/bytecodealliance/wit-bindgen,Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT,Alex Crichton wit-bindgen-rust,https://github.com/bytecodealliance/wit-bindgen,Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT,Alex Crichton @@ -628,7 +546,6 @@ zeroize,https://github.com/RustCrypto/utils,Apache-2.0 OR MIT,The RustCrypto Pro zerotrie,https://github.com/unicode-org/icu4x,Unicode-3.0,The ICU4X Project Developers zerovec,https://github.com/unicode-org/icu4x,Unicode-3.0,The ICU4X Project Developers zerovec-derive,https://github.com/unicode-org/icu4x,Unicode-3.0,Manish Goregaokar -zlib-rs,https://github.com/trifectatechfoundation/zlib-rs,Zlib,The zlib-rs Authors zmij,https://github.com/dtolnay/zmij,MIT,David Tolnay zstd,https://github.com/gyscos/zstd-rs,BSD-3-Clause,Alexandre Bury zstd-safe,https://github.com/gyscos/zstd-rs,BSD-3-Clause,Alexandre Bury diff --git a/Makefile b/Makefile index 8e0b5bb837a..52b4e280f39 100644 --- a/Makefile +++ b/Makefile @@ -714,7 +714,8 @@ build-integration-harness-host: $(if $(filter true,$(CI)),cargo-install-cargo-au build-integration-harness-host: ## Builds panoramic, datadog-intake and millstone for the current host, where the macOS integration cases run them @echo "[*] Building panoramic, datadog-intake and millstone (release, host target)..." # One invocation with --bin resolves features across the workspace, as build-adp-host does. With the same cargo -# subcommand as build-adp-host, the ADP build then reuses the crates that this build compiles. +# subcommand as build-adp-host, the two builds share the crates that both compile. +# The harness cache key in ci/tooling/harness_cache.py doesn't cover this recipe. Bump its SALT when you change it. @cargo $(ADP_CARGO_BUILD_SUBCMD) --profile release --bin panoramic --bin datadog-intake --bin millstone $(CARGO_TIMINGS_ARG) .PHONY: build-adp-aix @@ -792,9 +793,11 @@ provision-macos-test-env: ## Installs the macOS Datadog Agent named in .datadog- @echo "[*] Agent binary: $(MACOS_TEST_AGENT_INSTALL_DIR)/bin/agent/agent" .PHONY: test-integration-macos-ci -# CI runs these prerequisites one per script line in .gitlab/e2e.yml, so that the log timestamps show the duration of -# each, and it provisions in the background while the builds run. Keep the two lists the same. -test-integration-macos-ci: build-integration-harness-host build-adp-host provision-macos-test-env test-integration-macos-run ## CI entry point: builds binaries, ensures Agent + cert are provisioned, then runs the macOS integration cases (host processes) +# CI runs these prerequisites as separate script lines in .gitlab/e2e.yml, so that the log timestamps show the duration +# of each. +# There, helper scripts under ci/tooling/ wrap some of them: the harness cache and the persistent amd64 build +# directory. When the prerequisites change, change the job script too. +test-integration-macos-ci: build-adp-host build-integration-harness-host provision-macos-test-env test-integration-macos-run ## CI entry point: builds binaries, ensures Agent + cert are provisioned, then runs the macOS integration cases (host processes) # Installs the Rust toolchain $(1) with the components $(2), unless rustup already has all of them. `rustup toolchain # install` downloads the channel manifest even when nothing is missing, so this check lets a machine or an image that @@ -1051,6 +1054,14 @@ test-agent-version: ## Runs unit tests for the Agent version tooling test-devcontainer-updates: ## Runs unit tests for the devcontainer update pull request tooling @$(PYTHON) -m unittest ci/tooling/devcontainer-updates/test_devcontainer_updates.py -v +.PHONY: test-harness-cache +test-harness-cache: ## Runs unit tests for the macOS integration harness cache + @$(PYTHON) -m unittest ci/tooling/test_harness_cache.py -v + +.PHONY: test-macos-target-dir +test-macos-target-dir: ## Runs unit tests for the persistent target directory of the amd64 macOS CI jobs + @$(PYTHON) -m unittest ci/tooling/test_macos_target_dir.py -v + .PHONY: check-agent-version check-agent-version: ## Validates .datadog-agent-version.json and .datadog-agent-release-lines.jsonl @$(PYTHON) ci/tooling/agent_version.py validate diff --git a/bin/agent-data-plane/tests/version_cli.rs b/bin/agent-data-plane/tests/version_cli.rs index 449284c200b..ca4f6dfaed3 100644 --- a/bin/agent-data-plane/tests/version_cli.rs +++ b/bin/agent-data-plane/tests/version_cli.rs @@ -22,6 +22,11 @@ fn run_version_command(extra_args: &[&str]) -> String { String::from_utf8(output.stdout).expect("version output should be valid UTF-8") } +/// Returns the value of a build environment variable, or `default` if it was unset or empty. +fn build_env_or(value: Option<&'static str>, default: &'static str) -> &'static str { + value.filter(|value| !value.is_empty()).unwrap_or(default) +} + #[test] fn version_command_reports_the_applications_identity() { // Parsing as JSON also covers the version command continuing to run before logging is initialized: were it to run @@ -37,6 +42,22 @@ fn version_command_reports_the_applications_identity() { assert_eq!(details["version"], env!("CARGO_PKG_VERSION")); } +#[test] +fn version_command_reports_the_build_metadata_of_the_binary() { + let details: serde_json::Value = + serde_json::from_str(&run_version_command(&["--json"])).expect("version output should be valid JSON"); + + // Cargo compiles this test and the binary with the same environment, and rebuilds both when it changes. + assert_eq!( + details["git_hash"], + build_env_or(option_env!("APP_GIT_HASH"), "unknown") + ); + assert_eq!( + details["build_time"], + build_env_or(option_env!("APP_BUILD_TIME"), "0000-00-00 00:00:00") + ); +} + #[test] fn version_command_reports_the_version_in_human_readable_form() { let stdout = run_version_command(&[]); diff --git a/bin/correctness/panoramic/Cargo.toml b/bin/correctness/panoramic/Cargo.toml index 35a64a7c1fc..a566830dcd6 100644 --- a/bin/correctness/panoramic/Cargo.toml +++ b/bin/correctness/panoramic/Cargo.toml @@ -5,9 +5,6 @@ edition = { workspace = true } license = { workspace = true } repository = { workspace = true } -[build-dependencies] -vergen-gix = { workspace = true } - [lints] workspace = true diff --git a/bin/correctness/panoramic/build.rs b/bin/correctness/panoramic/build.rs deleted file mode 100644 index 4141383b888..00000000000 --- a/bin/correctness/panoramic/build.rs +++ /dev/null @@ -1,23 +0,0 @@ -//! Records the Git revision this binary was built from, for the machine-readable test reports. -//! -//! `vergen-gix` reads the repository through `gix`, so no `git` executable has to exist on the -//! machine doing the build. - -use vergen_gix::{Emitter, Gix}; - -fn main() { - // Best effort: a build outside a checkout, such as from a source tarball, still has to succeed. - // The binary reports these fallback values as an unknown revision. - if let Err(e) = emit_revision() { - println!("cargo:warning=Could not read the Git revision: {}", e); - println!("cargo:rustc-env=VERGEN_GIT_SHA="); - println!("cargo:rustc-env=VERGEN_GIT_DIRTY=false"); - } -} - -/// Emits the SHA and dirty state of the repository this crate is being built from. -fn emit_revision() -> Result<(), Box> { - let gix = Gix::builder().sha(false).dirty(true).build(); - Emitter::default().add_instructions(&gix)?.emit()?; - Ok(()) -} diff --git a/bin/correctness/panoramic/src/cli.rs b/bin/correctness/panoramic/src/cli.rs index a57e4a8478a..054987c3a88 100644 --- a/bin/correctness/panoramic/src/cli.rs +++ b/bin/correctness/panoramic/src/cli.rs @@ -221,6 +221,18 @@ pub struct RunCommand { /// `timeout` is, with one whole number and a unit (ms, s, m or h), such as `90m` #[arg(long, default_value = "30m", value_parser = parse_kind_setup_timeout, verbatim_doc_comment)] pub kind_setup_timeout: Duration, + + /// Revision that `run.json` reports as `build_revision`: a commit SHA, with an + /// optional `-dirty` suffix. A value that is not a SHA reports `unknown`. When this + /// is unset, panoramic uses `--ci-commit-sha`, then the Git checkout that holds + /// the first test directory + #[arg(long, value_name = "SHA", env = "PANORAMIC_REVISION", verbatim_doc_comment)] + pub revision: Option, + + /// Commit SHA of the CI pipeline, which GitLab CI sets. `--revision` takes + /// precedence + #[arg(long, value_name = "SHA", env = "CI_COMMIT_SHA", verbatim_doc_comment)] + pub ci_commit_sha: Option, } /// Parses `--kind-setup-timeout` the way a case's `timeout` is parsed. @@ -345,8 +357,13 @@ mod tests { ("log_dir", "PANORAMIC_LOG_DIR"), ("set", "PANORAMIC_SET"), ("host_slots", "PANORAMIC_HOST_SLOTS"), + ("revision", "PANORAMIC_REVISION"), ]; + /// Settings that panoramic shares with the CI environment, each an argument on `run` whose + /// fallback has no `PANORAMIC_` prefix. + const SHARED_ENV_FALLBACKS: &[(&str, &str)] = &[("ci_commit_sha", "CI_COMMIT_SHA")]; + fn run_command_of(cli: &Cli) -> &RunCommand { match &cli.command { Command::Run(cmd) => cmd, @@ -409,7 +426,7 @@ mod tests { fn help_footer_covers_only_the_external_environment_variables() { // The footer is hand-written prose, so it's the one place a Panoramic-owned setting could be // documented twice: once by clap next to its flag, once here. Keep it to the exceptions. - for (_, var) in PANORAMIC_ENV_FALLBACKS { + for (_, var) in PANORAMIC_ENV_FALLBACKS.iter().chain(SHARED_ENV_FALLBACKS) { assert!( !ENV_HELP.contains(var), "the help footer should not re-document {}", @@ -438,7 +455,7 @@ mod tests { let command = Cli::command(); let run = command.find_subcommand("run").expect("run subcommand should exist"); - for (id, var) in PANORAMIC_ENV_FALLBACKS { + for (id, var) in PANORAMIC_ENV_FALLBACKS.iter().chain(SHARED_ENV_FALLBACKS) { let arg = run .get_arguments() .find(|arg| arg.get_id() == id) @@ -453,7 +470,7 @@ mod tests { let command = Cli::command(); let list = command.find_subcommand("list").expect("list subcommand should exist"); - for (id, _) in PANORAMIC_ENV_FALLBACKS { + for (id, _) in PANORAMIC_ENV_FALLBACKS.iter().chain(SHARED_ENV_FALLBACKS) { assert!( !list.get_arguments().any(|arg| arg.get_id() == id), "'{}' should not be defined on `list`", diff --git a/bin/correctness/panoramic/src/collector.rs b/bin/correctness/panoramic/src/collector.rs index 827c1955a99..9f186af6c47 100644 --- a/bin/correctness/panoramic/src/collector.rs +++ b/bin/correctness/panoramic/src/collector.rs @@ -334,6 +334,7 @@ mod tests { use crate::machine_output::RUN_REPORT_FILE_NAME; use crate::reporter::test_support::step; use crate::reporter::OutputFormat; + use crate::revision::UNKNOWN_REVISION; use crate::runner::test_support::{test_runner_settings, Behavior, ScriptedTest}; use crate::runner::{RunArgs, Runner}; @@ -355,6 +356,7 @@ mod tests { let log_dir = tempfile::tempdir().expect("temp dir should be creatable"); let selected = tests.iter().map(|t| t.name.clone()).collect(); let report = RunReport::new( + UNKNOWN_REVISION.to_string(), Vec::new(), "linux".to_string(), 1, @@ -668,6 +670,7 @@ mod tests { let log_dir = tempfile::tempdir().expect("temp dir should be creatable"); let selected = vec!["a".to_string(), "b".to_string()]; let report = RunReport::new( + UNKNOWN_REVISION.to_string(), Vec::new(), "linux".to_string(), 1, @@ -736,6 +739,7 @@ mod tests { for (case, results, interrupted, expected) in cases { let log_dir = tempfile::tempdir().expect("temp dir should be creatable"); let report = RunReport::new( + UNKNOWN_REVISION.to_string(), Vec::new(), "linux".to_string(), 1, @@ -762,6 +766,7 @@ mod tests { // cluster may remain. let log_dir = tempfile::tempdir().expect("temp dir should be creatable"); let report = RunReport::new( + UNKNOWN_REVISION.to_string(), Vec::new(), "linux".to_string(), 1, diff --git a/bin/correctness/panoramic/src/machine_output.rs b/bin/correctness/panoramic/src/machine_output.rs index 8589ea6dfd4..bc24b4a7d0e 100644 --- a/bin/correctness/panoramic/src/machine_output.rs +++ b/bin/correctness/panoramic/src/machine_output.rs @@ -17,9 +17,6 @@ use crate::core::result::{ TimeoutAttribution, }; -/// Reported when the build could not read a repository to get a revision from. -const UNKNOWN_REVISION: &str = "unknown"; - /// File name of the run-level report, written directly under the run's log directory. pub const RUN_REPORT_FILE_NAME: &str = "run.json"; @@ -72,8 +69,8 @@ pub struct RunReport { pub state: RunState, /// First interruption reason, set when `state` becomes `interrupted`. pub interrupted_reason: Option, - /// Revision of the repository this binary was built from: a commit SHA, `-dirty` suffixed when - /// the checkout had uncommitted changes, or `unknown` when the build could not read a repository. + /// Revision that the run tests: a commit SHA, `-dirty` suffixed when the checkout has changes + /// that are not committed, or `unknown`. [`crate::revision`] says where it comes from. pub build_revision: String, /// Test-case directories the run discovered from. pub suite_dirs: Vec, @@ -328,14 +325,14 @@ pub struct AssertionReport { impl RunReport { /// Creates a report in the `running` state that lists every selected test as not run. pub fn new( - suite_dirs: Vec, runtime: String, parallelism: usize, host_slots: usize, log_dir: PathBuf, - selected: Vec, + build_revision: String, suite_dirs: Vec, runtime: String, parallelism: usize, host_slots: usize, + log_dir: PathBuf, selected: Vec, ) -> Self { Self { schema_version: REPORT_SCHEMA_VERSION, state: RunState::Running, interrupted_reason: None, - build_revision: build_revision(), + build_revision, suite_dirs, runtime, set: BTreeMap::new(), @@ -438,27 +435,6 @@ impl TestReport { } } -/// Revision of the repository this binary was built from, as recorded by the build script. -fn build_revision() -> String { - revision(env!("VERGEN_GIT_SHA"), env!("VERGEN_GIT_DIRTY")) -} - -/// Formats the build script's SHA and dirty flag as a revision string. -/// -/// A value that is not a SHA collapses to `unknown` on its own, with no `-dirty` suffix to read as -/// provenance the build never had. -fn revision(sha: &str, dirty: &str) -> String { - if sha.is_empty() || !sha.chars().all(|c| c.is_ascii_hexdigit()) { - return UNKNOWN_REVISION.to_string(); - } - - if dirty == "true" { - format!("{}-dirty", sha) - } else { - sha.to_string() - } -} - /// Scans a test's captured output for lines worth reading first, capped and in artifact order. /// /// Returns the lines and whether the cap cut the set short. @@ -640,6 +616,7 @@ mod tests { use crate::core::result::{ErrorKind, TestOutcome, TimeoutAttribution}; use crate::events::TestEvent; use crate::reporter::test_support::step; + use crate::revision::UNKNOWN_REVISION; #[test] fn test_report_pins_the_contract_field_names() { @@ -974,42 +951,21 @@ mod tests { } #[test] - fn run_report_records_the_revision_it_was_built_from() { + fn run_report_records_its_parallelism_and_host_slots() { let report = RunReport::new( - vec![PathBuf::from("/cases")], - "linux".to_string(), - 1, - 1, + UNKNOWN_REVISION.to_string(), + Vec::new(), + "mac".to_string(), + 4, + 2, PathBuf::from("/logs"), Vec::new(), ); - - // A build outside a checkout reports `unknown`; inside one it is a SHA, optionally dirty. - let revision = report.build_revision.trim_end_matches("-dirty"); - assert!( - revision == UNKNOWN_REVISION || revision.chars().all(|c| c.is_ascii_hexdigit()), - "revision was: {}", - report.build_revision - ); - assert!(!revision.is_empty()); - } - - #[test] - fn run_report_records_its_parallelism_and_host_slots() { - let report = RunReport::new(Vec::new(), "mac".to_string(), 4, 2, PathBuf::from("/logs"), Vec::new()); let json = serde_json::to_value(&report).expect("the run report should serialize"); assert_eq!(json["parallelism"], 4); assert_eq!(json["host_slots"], 2); } - #[test] - fn revision_collapses_to_unknown_without_a_sha() { - assert_eq!(revision("", "true"), UNKNOWN_REVISION); - assert_eq!(revision("VERGEN_IDEMPOTENT_OUTPUT", "true"), UNKNOWN_REVISION); - assert_eq!(revision("abc123", "true"), "abc123-dirty"); - assert_eq!(revision("abc123", "false"), "abc123"); - } - #[test] fn run_report_totals_separate_failures_from_errors() { let results = [ @@ -1045,6 +1001,7 @@ mod tests { let log_dir = tempfile::tempdir().expect("temp dir should be creatable"); let selected = vec!["a".to_string(), "b".to_string(), "c".to_string()]; let report = RunReport::new( + "abc123-dirty".to_string(), Vec::new(), "linux".to_string(), 1, @@ -1069,6 +1026,7 @@ mod tests { let json = serde_json::to_value(collector.report()).expect("run report should serialize"); assert_eq!(json["schema_version"], 2); + assert_eq!(json["build_revision"], "abc123-dirty"); assert_eq!(json["state"], "interrupted"); assert_eq!(json["interrupted_reason"]["kind"], "signal"); assert_eq!(json["interrupted_reason"]["source"], "SIGTERM"); @@ -1096,6 +1054,7 @@ mod tests { }; let mut report = RunReport::new( + UNKNOWN_REVISION.to_string(), Vec::new(), "linux".to_string(), 1, diff --git a/bin/correctness/panoramic/src/main.rs b/bin/correctness/panoramic/src/main.rs index b03d1e47b70..25fc2b12567 100644 --- a/bin/correctness/panoramic/src/main.rs +++ b/bin/correctness/panoramic/src/main.rs @@ -48,6 +48,7 @@ use self::machine_output::RunReport; mod reporter; use self::reporter::{OutputFormat, Reporter}; +mod revision; mod runner; mod steps; mod test; @@ -229,6 +230,10 @@ async fn run_tests(cmd: cli::RunCommand, use_tui: bool) -> ExitCode { None => test_cases, }; + // Read the revision before the run writes files, which can be inside the checkout. + let checkout = cmd.test_dirs.first().map_or(Path::new("."), |dir| dir.as_path()); + let revision = revision::resolve(cmd.revision.as_deref(), cmd.ci_commit_sha.as_deref(), checkout).await; + // Create log directory. let log_dir = match cmd .log_dir() @@ -302,6 +307,7 @@ async fn run_tests(cmd: cli::RunCommand, use_tui: bool) -> ExitCode { }; let mut report = RunReport::new( + revision, cmd.test_dirs.clone(), participant_case::runtime_of(cmd.subject_os).to_string(), cmd.parallelism.get(), diff --git a/bin/correctness/panoramic/src/reporter.rs b/bin/correctness/panoramic/src/reporter.rs index 2d3ef5e18ec..2864f549fc2 100644 --- a/bin/correctness/panoramic/src/reporter.rs +++ b/bin/correctness/panoramic/src/reporter.rs @@ -288,6 +288,7 @@ mod tests { use crate::core::record::ActiveStep; use crate::core::result::{ErrorKind, Issue, IssueKind, StopCause, StoppedBy, TimeoutAttribution}; use crate::events::TestEvent; + use crate::revision::UNKNOWN_REVISION; const LABELS: [&str; 5] = ["PASS", "FAIL", "ERROR", "TIMEOUT", "INTERRUPTED"]; @@ -434,7 +435,15 @@ mod tests { finished: bool, ) -> RunCollector { let selected = selected.iter().map(|name| name.to_string()).collect(); - let report = RunReport::new(Vec::new(), "linux".to_string(), 1, 1, log_dir.to_path_buf(), selected); + let report = RunReport::new( + UNKNOWN_REVISION.to_string(), + Vec::new(), + "linux".to_string(), + 1, + 1, + log_dir.to_path_buf(), + selected, + ); let mut collector = RunCollector::start(report, fail_fast); for event in &events { collector.observe(event); @@ -508,6 +517,7 @@ mod tests { ); let mut long_run = RunReport::new( + UNKNOWN_REVISION.to_string(), Vec::new(), "linux".to_string(), 1, diff --git a/bin/correctness/panoramic/src/revision.rs b/bin/correctness/panoramic/src/revision.rs new file mode 100644 index 00000000000..6fd1a8a8496 --- /dev/null +++ b/bin/correctness/panoramic/src/revision.rs @@ -0,0 +1,291 @@ +//! Resolves the revision that a run reports. +//! +//! `panoramic run` reads the revision when it starts, so a binary that another commit built still reports the code +//! that the run tests. The first source that is set gives the revision: +//! +//! 1. `--revision`, or `PANORAMIC_REVISION` +//! 2. `--ci-commit-sha`, or `CI_COMMIT_SHA` +//! 3. the Git checkout that holds the first test directory +//! +//! A setting that is not a commit SHA gives [`UNKNOWN_REVISION`], and the sources after it stay unused. + +use std::path::Path; + +use saluki_error::{generic_error, ErrorContext as _, GenericError}; +use tokio::process::Command; +use tracing::warn; + +/// Reported when panoramic cannot tell the revision. +pub const UNKNOWN_REVISION: &str = "unknown"; + +/// Marks a revision whose checkout has changes that are not committed. +const DIRTY_SUFFIX: &str = "-dirty"; + +/// Resolves the revision of the run: a commit SHA, `-dirty` suffixed when the checkout has changes that are not +/// committed, or [`UNKNOWN_REVISION`]. +/// +/// An empty setting counts as unset. +pub async fn resolve(revision: Option<&str>, ci_commit_sha: Option<&str>, checkout: &Path) -> String { + if let Some(value) = revision.filter(|value| !value.is_empty()) { + return from_setting("--revision (PANORAMIC_REVISION)", value); + } + if let Some(value) = ci_commit_sha.filter(|value| !value.is_empty()) { + return from_setting("--ci-commit-sha (CI_COMMIT_SHA)", value); + } + + match checkout_revision(checkout).await { + Ok(revision) => revision, + Err(e) => { + let error = format!("{:#}", e); + warn!( + checkout = %checkout.display(), + %error, + "Failed to read the revision of the Git checkout. Reporting an unknown revision. Set `--revision` to \ + report a known one." + ); + UNKNOWN_REVISION.to_string() + } + } +} + +/// Checks a revision that a setting gives: a commit SHA, with an optional `-dirty` suffix. +fn from_setting(setting: &'static str, value: &str) -> String { + if is_sha(value.strip_suffix(DIRTY_SUFFIX).unwrap_or(value)) { + return value.to_string(); + } + + warn!( + setting, + value, "Revision setting is not a commit SHA. Reporting an unknown revision." + ); + UNKNOWN_REVISION.to_string() +} + +fn is_sha(value: &str) -> bool { + !value.is_empty() && value.chars().all(|c| c.is_ascii_hexdigit()) +} + +/// Reads the commit and the state of the Git checkout that holds `dir`. +/// +/// A file that Git does not track makes the checkout dirty, unless Git ignores it. +async fn checkout_revision(dir: &Path) -> Result { + let output = git(dir, &["rev-parse", "--verify", "HEAD"]).await?; + let output = String::from_utf8_lossy(&output); + let sha = output.trim(); + if !is_sha(sha) { + return Err(generic_error!( + "`git rev-parse` printed '{}', which is not a commit SHA", + sha + )); + } + + // `--no-optional-locks` stops `git status` from writing the index, which another Git process can have locked. + // `--untracked-files=normal` overrides a `status.showUntrackedFiles` setting that hides new files. + let status = git( + dir, + &[ + "--no-optional-locks", + "status", + "--porcelain", + "--untracked-files=normal", + ], + ) + .await?; + if status.trim_ascii().is_empty() { + Ok(sha.to_string()) + } else { + Ok(format!("{}{}", sha, DIRTY_SUFFIX)) + } +} + +/// Runs `git` in `dir`, and returns what it prints to stdout. +/// +/// The output stays in bytes, because `git status` can print file names that are not UTF-8. +async fn git(dir: &Path, args: &[&str]) -> Result, GenericError> { + let command = format!("git {}", args.join(" ")); + let output = Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .kill_on_drop(true) + .output() + .await + .with_error_context(|| format!("Failed to run `{}`", command))?; + + if !output.status.success() { + return Err(generic_error!( + "`{}` failed ({}): {}", + command, + output.status, + String::from_utf8_lossy(&output.stderr).trim() + )); + } + + Ok(output.stdout) +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use super::*; + + /// A checkout path that does not exist, so a test that reaches the checkout gets an unknown revision. + fn missing_checkout(dir: &tempfile::TempDir) -> PathBuf { + dir.path().join("missing") + } + + #[tokio::test] + async fn revision_setting_outranks_the_ci_commit_and_the_checkout() { + let dir = tempfile::tempdir().expect("temp dir should be creatable"); + let checkout = missing_checkout(&dir); + + assert_eq!(resolve(Some("abc123"), Some("def456"), &checkout).await, "abc123"); + assert_eq!(resolve(Some("abc123-dirty"), None, &checkout).await, "abc123-dirty"); + } + + #[tokio::test] + async fn ci_commit_outranks_the_checkout() { + let dir = tempfile::tempdir().expect("temp dir should be creatable"); + let checkout = missing_checkout(&dir); + + assert_eq!(resolve(None, Some("def456"), &checkout).await, "def456"); + } + + #[tokio::test] + async fn empty_settings_count_as_unset() { + let dir = tempfile::tempdir().expect("temp dir should be creatable"); + let checkout = missing_checkout(&dir); + + assert_eq!(resolve(Some(""), Some("def456"), &checkout).await, "def456"); + assert_eq!(resolve(Some(""), Some(""), &checkout).await, UNKNOWN_REVISION); + } + + #[tokio::test] + async fn setting_that_is_not_a_sha_reports_unknown() { + let dir = tempfile::tempdir().expect("temp dir should be creatable"); + let checkout = missing_checkout(&dir); + + // A setting that is set decides the revision, so a bad value does not fall through to the next source. + for value in [ + "main", + "v1.2.3", + " abc123", + "-dirty", + "main-dirty", + "abc123-dirty-dirty", + ] { + assert_eq!( + resolve(Some(value), Some("def456"), &checkout).await, + UNKNOWN_REVISION, + "value was: {:?}", + value + ); + } + assert_eq!(resolve(None, Some("main"), &checkout).await, UNKNOWN_REVISION); + } + + #[tokio::test] + async fn checkout_that_git_cannot_read_reports_unknown() { + let dir = tempfile::tempdir().expect("temp dir should be creatable"); + + assert_eq!(resolve(None, None, &missing_checkout(&dir)).await, UNKNOWN_REVISION); + } + + // The Windows CI image is not certain to have Git. + #[cfg(unix)] + #[tokio::test] + async fn checkout_reports_its_commit_and_its_changes() { + fn git_in(dir: &Path, args: &[&str]) -> String { + let output = std::process::Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .output() + .expect("git should be installed"); + assert!(output.status.success(), "git {:?} failed: {:?}", args, output); + String::from_utf8(output.stdout).expect("git output should be UTF-8") + } + + let dir = tempfile::tempdir().expect("temp dir should be creatable"); + let repo = dir.path(); + let cases = repo.join("cases"); + std::fs::create_dir(&cases).expect("cases dir should be creatable"); + + git_in(repo, &["init", "-q"]); + assert_eq!( + resolve(None, None, repo).await, + UNKNOWN_REVISION, + "a repository with no commit" + ); + + std::fs::write(repo.join(".gitignore"), "ignored.txt\n").expect(".gitignore should be writable"); + std::fs::write(cases.join("config.yaml"), "name: a\n").expect("case file should be writable"); + git_in(repo, &["add", "."]); + git_in( + repo, + &[ + "-c", + "user.name=panoramic", + "-c", + "user.email=panoramic@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "-q", + "--no-verify", + "-m", + "initial", + ], + ); + let head = git_in(repo, &["rev-parse", "HEAD"]).trim().to_string(); + + assert_eq!(resolve(None, None, repo).await, head); + assert_eq!( + resolve(None, None, &cases).await, + head, + "a test directory inside the checkout" + ); + + // The settings outrank a checkout that Git can read, and a bad setting does not fall through to it. + assert_eq!(resolve(Some("abc123"), Some("def456"), &cases).await, "abc123"); + assert_eq!(resolve(None, Some("def456"), &cases).await, "def456"); + assert_eq!(resolve(None, Some("main"), &cases).await, UNKNOWN_REVISION); + + std::fs::write(repo.join("ignored.txt"), "").expect("ignored file should be writable"); + assert_eq!(resolve(None, None, &cases).await, head, "an ignored file"); + + // This Git setting hides new files from `git status`, but not from the dirty check. + git_in(repo, &["config", "status.showUntrackedFiles", "no"]); + std::fs::write(repo.join("untracked.txt"), "").expect("untracked file should be writable"); + assert_eq!( + resolve(None, None, &cases).await, + format!("{}-dirty", head), + "an untracked file" + ); + std::fs::remove_file(repo.join("untracked.txt")).expect("untracked file should be removable"); + + // With `core.quotePath` off, `git status` prints this file name as bytes that are not UTF-8. + #[cfg(target_os = "linux")] + { + use std::os::unix::ffi::OsStrExt as _; + + git_in(repo, &["config", "core.quotePath", "false"]); + let name = repo.join(std::ffi::OsStr::from_bytes(b"latin-1-\xe9.txt")); + std::fs::write(&name, "").expect("file with a Latin-1 name should be writable"); + assert_eq!( + resolve(None, None, &cases).await, + format!("{}-dirty", head), + "a file name that is not UTF-8" + ); + std::fs::remove_file(&name).expect("file with a Latin-1 name should be removable"); + } + + std::fs::write(cases.join("config.yaml"), "name: b\n").expect("case file should be writable"); + assert_eq!( + resolve(None, None, &cases).await, + format!("{}-dirty", head), + "a modified file" + ); + } +} diff --git a/ci/tooling/build-smp-images.sh b/ci/tooling/build-smp-images.sh index b2f646c2c96..033899dc9b6 100755 --- a/ci/tooling/build-smp-images.sh +++ b/ci/tooling/build-smp-images.sh @@ -139,10 +139,8 @@ fi # The ADP key includes all of these arguments, so a change to them makes a new key. # -# We don't pass `APP_GIT_HASH`. `saluki-metadata` embeds it, so a new value on each commit -# invalidates that crate and every crate that depends on it in the compiler cache, including -# `saluki-components`. The binary then reports an unknown Git hash. The image tag and the -# `git.commit` label still identify the built commit. +# We don't pass `APP_GIT_HASH`, so the binary reports an unknown Git hash. The image tag and the +# `git.commit` label identify the built commit. adp_build_args=( "BUILD_PROFILE=${SMP_BUILD_PROFILE}" "BUILD_TARGET=${BUILD_TARGET}" diff --git a/ci/tooling/get-macos-harness.sh b/ci/tooling/get-macos-harness.sh new file mode 100755 index 00000000000..48a372ad2e0 --- /dev/null +++ b/ci/tooling/get-macos-harness.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# Puts the macOS integration harness (panoramic, datadog-intake and millstone) in target/release/. +# +# Without HARNESS_CACHE_WAIT, the script builds the harness. With it, the script installs the harness from the harness +# cache, and waits up to HARNESS_CACHE_WAIT seconds for build-macos-harness-arm64 to publish it. With a wait of 0, the +# script looks once. When the cache has no harness: +# +# - if the build job failed, the script fails +# - otherwise, for example when the wait ends or the script can't read the cache, the script builds the harness +# +# When HARNESS_CACHE_PUBLISH is "true" and the job runs on the default branch, the script publishes the harness that it +# builds, for all pipelines. When the upload fails, the script prints a warning and continues. +# +# See "The macOS harness cache" in docs/development/panoramic.md. +set -euo pipefail + +# The exit code of `harness_cache.py fetch` when the harness build job of the pipeline failed. +readonly FETCH_BUILD_FAILED=3 + +if [[ -n "${HARNESS_CACHE_WAIT:-}" ]]; then + status=0 + python3 ci/tooling/harness_cache.py fetch --wait "$HARNESS_CACHE_WAIT" || status=$? + case "$status" in + 0) exit 0 ;; + "$FETCH_BUILD_FAILED") exit 1 ;; + *) echo "[*] The harness cache can't give this job a harness, so this job builds the harness." ;; + esac +fi + +make build-integration-harness-host + +if [[ "${HARNESS_CACHE_PUBLISH:-}" == "true" ]]; then + if [[ -n "${CI_COMMIT_BRANCH:-}" && "${CI_COMMIT_BRANCH}" == "${CI_DEFAULT_BRANCH:-}" ]]; then + python3 ci/tooling/harness_cache.py publish || + echo "WARNING: could not publish the harness; the job continues with the harness that it built" >&2 + else + echo "[*] This job isn't on the default branch, so it doesn't publish the harness." + fi +fi diff --git a/ci/tooling/harness_cache.py b/ci/tooling/harness_cache.py new file mode 100644 index 00000000000..3f180dba775 --- /dev/null +++ b/ci/tooling/harness_cache.py @@ -0,0 +1,647 @@ +#!/usr/bin/env python3 +"""Cache the macOS integration harness in the GitLab generic package registry. + +The harness is panoramic, datadog-intake and millstone, as `make build-integration-harness-host` builds them into +`target/release/`. The cache stores the three binaries in one `tar.gz` archive, under a key that hashes these inputs: + +- each tracked file of the local packages that the three binaries depend on, from the resolved graph of `cargo metadata` +- each tracked file outside those packages that their Rust sources embed with `include_bytes!`, `include_str!` or + `include!` +- `Cargo.lock`, the root `Cargo.toml`, `rust-toolchain.toml` and `.cargo/config.toml` +- the manifest of each workspace member, because a build that selects binaries with `--bin` unifies features across the + whole workspace +- the target triple, the profile, the binary names and `SALT` + +The key hashes the Git blob of each file in the index, so it ignores changes in the working tree. `publish` refuses to +run when the working tree changes an input. The key doesn't cover environment variables such as `RUSTFLAGS`, which CI +doesn't set. + +One key has two versions of the package in the registry: + +- `` is for all pipelines. Only a pipeline on the default branch publishes it. +- `-p` is for one pipeline. A pipeline on another ref publishes it, and only that pipeline reads it. + When the build job fails, or can't upload the harness, it publishes `failed.json` there, so that a waiting test job + stops waiting. The `stage` of the marker is `build` when the job failed, and `publish` when only the upload failed. + +A version holds the archive, named after its SHA-256, and `manifest.json`, which records the archive name, size and +SHA-256. `publish` uploads the manifest last, so a manifest always names an archive that is already in the registry. +""" + +import argparse +import enum +import hashlib +import json +import os +import posixpath +import re +import shutil +import subprocess +import sys +import tarfile +import tempfile +import time +import zlib +from pathlib import Path + + +# Bump SALT to discard every cached harness, for example when the recipe of `build-integration-harness-host` changes. +SALT = "1" +PACKAGE_NAME = "macos-integration-harness" +PROFILE = "release" +BINARIES = ("panoramic", "datadog-intake", "millstone") +ROOT_INPUTS = ("Cargo.lock", "Cargo.toml", "rust-toolchain.toml", ".cargo/config.toml") +MANIFEST_FILE = "manifest.json" +FAILED_FILE = "failed.json" +BUILD_STAGE = "build" +PUBLISH_STAGE = "publish" +SHA256_RE = re.compile(r"[0-9a-f]{64}") +INCLUDE_RE = re.compile(r'\binclude(?:_bytes|_str)?!\s*\(\s*"([^"\\]+)"\s*\)') +# Normal and build dependencies end up in the binaries. Dev dependencies don't. +LINKED_DEPENDENCY_KINDS = (None, "build") +REPOSITORY_ROOT = Path(__file__).resolve().parents[2] +REFUSED_STATUSES = (401, 403) +REDIRECT_STATUSES = (301, 302, 303, 307, 308) +SMALL_FILE_TIMEOUT = 60 +ARCHIVE_TIMEOUT = 300 + + +class CacheError(Exception): + """The harness key could not be computed, or a cached harness could not be used.""" + + +class Fetched(enum.IntEnum): + """The outcome of `fetch`, as the exit code of the command. argparse exits with 2 on a usage error.""" + + INSTALLED = 0 + MISSING = 1 + BUILD_FAILED = 3 + + +def run(command, cwd): + """Run `command` in `cwd` and return its standard output.""" + result = subprocess.run(command, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + if result.returncode != 0: + raise CacheError(f"`{' '.join(command)}` failed with exit code {result.returncode}: {result.stderr.strip()}") + return result.stdout + + +def warn(message): + print(f"WARNING: {message}", file=sys.stderr) + + +def host_target(root, run=run): + for line in run(["rustc", "-vV"], root).splitlines(): + if line.startswith("host: "): + return line[len("host: "):].strip() + raise CacheError("`rustc -vV` printed no host triple") + + +def load_metadata(root, target, run=run): + command = ["cargo", "metadata", "--format-version", "1", "--locked", "--filter-platform", target] + return json.loads(run(command, root)) + + +def relative_to_workspace(path, metadata): + root = Path(metadata["workspace_root"]).resolve() + try: + relative = Path(path).resolve().relative_to(root) + except ValueError: + raise CacheError(f"{path} is outside the workspace root {root}") from None + return relative.as_posix() + + +def harness_package_dirs(metadata): + """Return the directories of the local packages that the harness binaries depend on, relative to the workspace.""" + packages = {package["id"]: package for package in metadata["packages"]} + nodes = {node["id"]: node for node in metadata["resolve"]["nodes"]} + + owners = {} + for package_id in metadata["workspace_members"]: + for target in packages[package_id]["targets"]: + if "bin" in target["kind"] and target["name"] in BINARIES: + owners[target["name"]] = package_id + missing = [binary for binary in BINARIES if binary not in owners] + if missing: + raise CacheError(f"no workspace member has a binary named {', '.join(missing)}") + + seen = set() + pending = list(owners.values()) + while pending: + package_id = pending.pop() + if package_id in seen: + continue + seen.add(package_id) + for dependency in nodes[package_id]["deps"]: + if any(kind["kind"] in LINKED_DEPENDENCY_KINDS for kind in dependency["dep_kinds"]): + pending.append(dependency["pkg"]) + + # `Cargo.lock` pins the registry and Git packages. A local package, including a `[patch]` target, has no source. + return sorted( + { + relative_to_workspace(Path(packages[package_id]["manifest_path"]).parent, metadata) + for package_id in seen + if packages[package_id]["source"] is None + } + ) + + +def workspace_manifests(metadata): + packages = {package["id"]: package for package in metadata["packages"]} + return sorted( + relative_to_workspace(packages[package_id]["manifest_path"], metadata) + for package_id in metadata["workspace_members"] + ) + + +def tracked_files(root, run=run): + """Return the mode and blob hash of each file in the Git index, by path.""" + files = {} + for entry in run(["git", "ls-files", "--stage", "-z"], root).split("\0"): + if entry: + info, path = entry.split("\t", 1) + mode, blob, _stage = info.split(" ") + files[path] = (mode, blob) + return files + + +def is_under(path, directory): + return directory == "." or path == directory or path.startswith(directory + "/") + + +def blob_texts(root, blobs): + """Return the text of each Git blob in `blobs`, in order.""" + request = "".join(f"{blob}\n" for blob in blobs).encode("ascii") + result = subprocess.run(["git", "cat-file", "--batch"], cwd=root, input=request, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + if result.returncode != 0: + raise CacheError(f"`git cat-file --batch` failed with exit code {result.returncode}: {result.stderr.strip()}") + texts, offset, output = [], 0, result.stdout + for blob in blobs: + end = output.index(b"\n", offset) + header = output[offset:end].split(b" ") + if len(header) != 3 or header[1] != b"blob": + raise CacheError(f"Git has no blob {blob}") + start, size = end + 1, int(header[2]) + texts.append(output[start:start + size].decode("utf-8", errors="replace")) + offset = start + size + 1 + return texts + + +def embedded_files(root, package_dirs, tracked): + """Return the tracked files outside `package_dirs` that the Rust sources in `package_dirs` embed.""" + sources = [ + path for path in sorted(tracked) if path.endswith(".rs") and any(is_under(path, d) for d in package_dirs) + ] + embedded = set() + for path, text in zip(sources, blob_texts(root, [tracked[path][1] for path in sources])): + for literal in INCLUDE_RE.findall(text): + included = posixpath.normpath(posixpath.join(posixpath.dirname(path), literal)) + # A path that isn't tracked is generated, or it's an example in a comment. + if included in tracked and not any(is_under(included, directory) for directory in package_dirs): + embedded.add(included) + return sorted(embedded) + + +def changed_inputs(root, inputs, run=run): + """Return the inputs that the working tree changes from the Git index, and the untracked files among them.""" + git = ["git", "--literal-pathspecs"] + changed = run([*git, "diff", "--name-only", "-z", "--", *inputs], root).split("\0") + untracked = run([*git, "ls-files", "--others", "--exclude-standard", "-z", "--", *inputs], root).split("\0") + return sorted(path for path in set(changed) | set(untracked) if path) + + +class Key: + """The cache key of the harness, with the lines that its digest hashes.""" + + def __init__(self, target, lines, changed): + self.lines = lines + self.changed = changed + self.value = f"{target}-{PROFILE}-{hashlib.sha256(''.join(lines).encode('utf-8')).hexdigest()}" + + +def compute_key(root, metadata, target, run=run): + tracked = tracked_files(root, run) + package_dirs = harness_package_dirs(metadata) + embedded = embedded_files(root, package_dirs, tracked) + files = set(ROOT_INPUTS) | set(workspace_manifests(metadata)) | set(embedded) + for path in sorted(files): + if path not in tracked: + raise CacheError(f"the harness input {path} isn't tracked by Git") + + selected = sorted(path for path in tracked if path in files or any(is_under(path, d) for d in package_dirs)) + lines = [f"salt {SALT}\n", f"target {target}\n", f"profile {PROFILE}\n", f"binaries {' '.join(BINARIES)}\n"] + lines += [f"{tracked[path][0]} {tracked[path][1]} {path}\n" for path in selected] + return Key(target, lines, changed_inputs(root, package_dirs + sorted(files), run)) + + +class Registry: + """A package in the generic package registry of a GitLab project, which `curl` reads and writes.""" + + def __init__(self, api_url, project_id, token, run=subprocess.run): + self.base = f"{api_url.rstrip('/')}/projects/{project_id}/packages/generic/{PACKAGE_NAME}" + self.token = token + self.run = run + + @classmethod + def from_environment(cls, environ): + missing = [name for name in ("CI_API_V4_URL", "CI_PROJECT_ID", "CI_JOB_TOKEN") if not environ.get(name)] + if missing: + raise CacheError(f"the package registry needs {', '.join(missing)}, which isn't set") + return cls(environ["CI_API_V4_URL"], environ["CI_PROJECT_ID"], environ["CI_JOB_TOKEN"]) + + def url(self, version, name): + return f"{self.base}/{version}/{name}" + + def get(self, version, name, destination, timeout=SMALL_FILE_TIMEOUT): + """Download a file to `destination`. Return the HTTP status, or 0 when the request fails. + + The registry can answer with a redirect to object storage. The token goes only to the registry, so the + download from the redirect target is a second request without it. + """ + status, location = self.curl(["--output", str(destination), self.url(version, name)], timeout) + if status not in REDIRECT_STATUSES or not location: + return status + status, _location = self.curl(["--location", "--output", str(destination), location], timeout, + authenticate=False) + return status + + def put(self, version, name, source, timeout=SMALL_FILE_TIMEOUT): + """Upload `source` as a file. Return the HTTP status, or 0 when the request fails.""" + status, _location = self.curl(["--upload-file", str(source), "--output", os.devnull, + self.url(version, name)], timeout) + return status + + def curl(self, arguments, timeout, authenticate=True): + """Run curl, and return the HTTP status (0 when the request fails) and the target of a redirect.""" + # The generic package registry takes a CI job token only in the `JOB-TOKEN` header. The header goes in + # through standard input, so the token stays out of the process list. + escaped = self.token.replace("\\", "\\\\").replace('"', '\\"') + config = f'header = "JOB-TOKEN: {escaped}"\n' if authenticate else "" + # A transfer that stalls fails after 30 seconds, and no retry starts after `timeout`, so a slow registry costs + # a bounded time and the caller falls back to a local build. + command = [ + "curl", "--silent", "--show-error", "--connect-timeout", "15", "--max-time", str(timeout), + "--speed-limit", "65536", "--speed-time", "30", "--retry", "3", "--retry-delay", "2", + "--retry-max-time", str(timeout), "--retry-connrefused", "--config", "-", + "--write-out", "%{http_code} %{redirect_url}", *arguments, + ] + result = self.run(command, input=config, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + if result.returncode != 0: + warn(f"curl failed with exit code {result.returncode} for {arguments[-1]}: {result.stderr.strip()}") + return 0, "" + code, _, location = result.stdout.strip().partition(" ") + try: + return int(code), location.strip() + except ValueError: + return 0, "" + + +class DirectoryRegistry: + """A local directory that stands in for the package registry, to run the cache without GitLab.""" + + def __init__(self, root): + self.root = Path(root) + + def url(self, version, name): + return str(self.root / PACKAGE_NAME / version / name) + + def get(self, version, name, destination, timeout=None): + source = Path(self.url(version, name)) + if not source.is_file(): + return 404 + shutil.copyfile(source, destination) + return 200 + + def put(self, version, name, source, timeout=None): + destination = Path(self.url(version, name)) + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, destination) + return 201 + + +def pipeline_version(key, pipeline_id): + return f"{key}-p{pipeline_id}" + + +def archive_member(binary): + return f"target/{PROFILE}/{binary}" + + +def sha256_file(path): + digest = hashlib.sha256() + with Path(path).open("rb") as file: + for chunk in iter(lambda: file.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def parse_manifest(text, key): + """Return the manifest in `text` if it describes an archive for `key`, and `None` otherwise.""" + try: + manifest = json.loads(text) + except ValueError: + return None + if not isinstance(manifest, dict) or manifest.get("key") != key: + return None + sha256, size = manifest.get("sha256"), manifest.get("size") + if not isinstance(sha256, str) or not SHA256_RE.fullmatch(sha256): + return None + if not isinstance(size, int) or isinstance(size, bool) or size <= 0: + return None + if manifest.get("archive") != f"harness-{sha256}.tar.gz": + return None + return manifest + + +def read_manifest(registry, version, key, scratch): + """Return the HTTP status of the manifest of `version`, and the manifest if it is valid.""" + path = Path(scratch) / f"{version}.{MANIFEST_FILE}" + status = registry.get(version, MANIFEST_FILE, path) + if status != 200: + return status, None + manifest = parse_manifest(path.read_text(encoding="utf-8", errors="replace"), key) + if manifest is None: + warn(f"{registry.url(version, MANIFEST_FILE)} isn't a valid manifest for key {key}; ignoring it") + return status, manifest + + +def download_archive(registry, version, manifest, scratch): + path = Path(scratch) / manifest["archive"] + url = registry.url(version, manifest["archive"]) + status = registry.get(version, manifest["archive"], path, ARCHIVE_TIMEOUT) + if status != 200: + raise CacheError(f"could not download {url} (HTTP status {status})") + size = path.stat().st_size + if size != manifest["size"]: + raise CacheError(f"{url} has {size} bytes, but its manifest records {manifest['size']}") + actual = sha256_file(path) + if actual != manifest["sha256"]: + raise CacheError(f"{url} has SHA-256 {actual}, but its manifest records {manifest['sha256']}") + return path + + +def extract(archive, destination): + """Write the binaries in `archive` under `destination`. Replace each file atomically.""" + expected = sorted(archive_member(binary) for binary in BINARIES) + try: + with tarfile.open(archive, "r:gz") as tar: + members = tar.getmembers() + names = sorted(member.name for member in members) + if names != expected or not all(member.isfile() for member in members): + raise CacheError(f"{archive} holds {names}, but a harness archive holds the files {expected}") + for member in members: + path = Path(destination) / member.name + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, partial = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + try: + with os.fdopen(descriptor, "wb") as output: + shutil.copyfileobj(tar.extractfile(member), output) + os.chmod(partial, 0o755) + os.replace(partial, path) + finally: + Path(partial).unlink(missing_ok=True) + except (tarfile.TarError, EOFError, zlib.error) as error: + raise CacheError(f"could not read {archive}: {error}") from error + + +def fetch(registry, key, pipeline_id, destination, wait, poll_interval, scratch, clock=time.monotonic, + sleep=time.sleep): + """Install a cached harness under `destination`, and return what happened. + + Polls for up to `wait` seconds, until a version of `key` has a manifest or the build job of the pipeline publishes + a failure marker. + """ + versions = [key] + ([pipeline_version(key, pipeline_id)] if pipeline_id else []) + start = clock() + deadline = start + wait + while True: + for version in versions: + status, manifest = read_manifest(registry, version, key, scratch) + if manifest is not None: + waited = clock() - start + archive = download_archive(registry, version, manifest, scratch) + extract(archive, destination) + url = registry.url(version, manifest["archive"]) + print(f"[*] Installed the harness from {url}, after a wait of {waited:.0f} seconds") + return Fetched.INSTALLED + if status in REFUSED_STATUSES: + raise CacheError(f"the registry refused {registry.url(version, MANIFEST_FILE)} (HTTP status {status})") + if pipeline_id: + version = pipeline_version(key, pipeline_id) + path = Path(scratch) / FAILED_FILE + if registry.get(version, FAILED_FILE, path) == 200: + return report_failure(path, registry.url(version, FAILED_FILE)) + remaining = deadline - clock() + if remaining <= 0: + print(f"[*] The registry has no harness for key {key}, after a wait of {clock() - start:.0f} seconds") + return Fetched.MISSING + sleep(min(poll_interval, remaining)) + + +def report_failure(path, url): + """Print what the failure marker at `path` reports, and return the outcome of the fetch.""" + try: + marker = json.loads(path.read_text(encoding="utf-8", errors="replace")) + except ValueError: + marker = None + # The marker reports a failed build unless it says that only the upload failed. + details = marker if isinstance(marker, dict) else {} + job = details.get("job_url") or url + if details.get("stage") == PUBLISH_STAGE: + print(f"[*] The harness build job built the harness, but could not publish it: {job}") + return Fetched.MISSING + print(f"error: the harness build job of this pipeline failed, so this job has no harness: {job}", file=sys.stderr) + print("error: fix or retry that job, and retry this job after that job passes", file=sys.stderr) + return Fetched.BUILD_FAILED + + +def create_archive(binary_dir, scratch): + """Write the harness binaries in `binary_dir` to an archive. Return its path, SHA-256 and size.""" + path = Path(scratch) / "harness.tar.gz" + with tarfile.open(path, "w:gz", compresslevel=6) as tar: + for binary in BINARIES: + source = Path(binary_dir) / binary + if not source.is_file(): + raise CacheError(f"{source} doesn't exist; run `make build-integration-harness-host` first") + info = tar.gettarinfo(str(source), arcname=archive_member(binary)) + info.mode, info.uid, info.gid, info.uname, info.gname = 0o755, 0, 0, "", "" + with source.open("rb") as file: + tar.addfile(info, file) + return path, sha256_file(path), path.stat().st_size + + +def publish(registry, key, version, archive, scratch, environ): + """Upload `archive` and its manifest as `version`. Return whether both uploads succeeded.""" + path, sha256, size = archive + name = f"harness-{sha256}.tar.gz" + status = registry.put(version, name, path, ARCHIVE_TIMEOUT) + if status not in (200, 201): + warn(f"could not upload {registry.url(version, name)} (HTTP status {status})") + return False + + manifest = { + "key": key, + "archive": name, + "size": size, + "sha256": sha256, + "commit": environ.get("CI_COMMIT_SHA"), + "job_url": environ.get("CI_JOB_URL"), + } + manifest_path = Path(scratch) / MANIFEST_FILE + manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") + status = registry.put(version, MANIFEST_FILE, manifest_path) + if status not in (200, 201): + warn(f"could not upload {registry.url(version, MANIFEST_FILE)} (HTTP status {status})") + return False + print(f"[*] Published the harness ({size} bytes) to {registry.url(version, name)}") + return True + + +def mark_failed(registry, key, pipeline_id, stage, scratch, environ): + """Tell a waiting test job that the harness build job of this pipeline publishes no harness. + + `stage` is `BUILD_STAGE` when the job failed, and `PUBLISH_STAGE` when only the upload failed. Returns whether the + upload of the marker succeeded. + """ + version = pipeline_version(key, pipeline_id) + marker = { + "key": key, + "stage": stage, + "job_url": environ.get("CI_JOB_URL"), + "job_status": environ.get("CI_JOB_STATUS"), + } + path = Path(scratch) / FAILED_FILE + path.write_text(json.dumps(marker, indent=2) + "\n", encoding="utf-8") + status = registry.put(version, FAILED_FILE, path) + if status not in (200, 201): + warn(f"could not upload {registry.url(version, FAILED_FILE)} (HTTP status {status})") + return False + print(f"[*] Published a failure marker for the {stage} stage at {registry.url(version, FAILED_FILE)}") + return True + + +def on_default_branch(environ): + """Return whether the pipeline runs for a commit on the default branch. + + Every branch of the project is protected, so `CI_COMMIT_REF_PROTECTED` can't tell the default branch apart. + """ + branch = environ.get("CI_COMMIT_BRANCH") + return bool(branch) and branch == environ.get("CI_DEFAULT_BRANCH") + + +def publish_version(key, environ): + """Return the version that this job publishes: the shared one on the default branch, and its own one otherwise.""" + if on_default_branch(environ): + return key + if not environ.get("CI_PIPELINE_ID"): + raise CacheError("CI_PIPELINE_ID isn't set, so a job off the default branch has no version to publish") + return pipeline_version(key, environ["CI_PIPELINE_ID"]) + + +def open_registry(arguments, environ): + if arguments.registry_dir: + return DirectoryRegistry(arguments.registry_dir) + return Registry.from_environment(environ) + + +def command_key(arguments, root, key, environ, scratch): + if arguments.explain: + sys.stderr.write("".join(key.lines)) + print(key.value) + return 0 + + +def command_exists(arguments, root, key, environ, scratch): + registry = open_registry(arguments, environ) + status, manifest = read_manifest(registry, key.value, key.value, scratch) + if status in REFUSED_STATUSES: + warn(f"the registry refused {registry.url(key.value, MANIFEST_FILE)} (HTTP status {status})") + if manifest is None: + print(f"[*] The registry has no shared harness for key {key.value}") + return 1 + print(f"[*] The registry has a shared harness for key {key.value}") + return 0 + + +def command_fetch(arguments, root, key, environ, scratch): + registry = open_registry(arguments, environ) + pipeline_id = environ.get("CI_PIPELINE_ID") + return int(fetch(registry, key.value, pipeline_id, root, arguments.wait, arguments.poll_interval, scratch)) + + +def command_publish(arguments, root, key, environ, scratch): + if key.changed: + raise CacheError("the working tree changes the harness inputs, so the key doesn't describe the binaries") + version = publish_version(key.value, environ) + archive = create_archive(Path(environ.get("CARGO_TARGET_DIR") or root / "target") / PROFILE, scratch) + try: + registry = open_registry(arguments, environ) + except CacheError as error: + warn(f"could not publish the harness: {error}") + return 0 + if not publish(registry, key.value, version, archive, scratch, environ) and environ.get("CI_PIPELINE_ID"): + mark_failed(registry, key.value, environ["CI_PIPELINE_ID"], PUBLISH_STAGE, scratch, environ) + return 0 + + +def command_mark_failed(arguments, root, key, environ, scratch): + if not environ.get("CI_PIPELINE_ID"): + raise CacheError("CI_PIPELINE_ID isn't set, so there is no version for the failure marker") + registry = open_registry(arguments, environ) + mark_failed(registry, key.value, environ["CI_PIPELINE_ID"], BUILD_STAGE, scratch, environ) + return 0 + + +COMMANDS = { + "key": command_key, + "exists": command_exists, + "fetch": command_fetch, + "publish": command_publish, + "mark-failed": command_mark_failed, +} + + +def parse_arguments(argv): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--registry-dir", type=Path, + help="use this directory as the package registry, instead of the GitLab project of the job") + commands = parser.add_subparsers(dest="command", required=True) + key_parser = commands.add_parser("key", help="print the cache key") + key_parser.add_argument("--target", help="the target triple (default: the host triple of rustc)") + key_parser.add_argument("--explain", action="store_true", help="print the lines that the key hashes to stderr") + commands.add_parser("exists", help="exit with 0 if the registry has the shared version of the key") + fetch_parser = commands.add_parser( + "fetch", + help="install a cached harness into target/release/", + description="Install a cached harness into target/release/. Exit with 0 when it does, with 3 when the " + "harness build job of the pipeline failed, and with 1 otherwise.", + ) + fetch_parser.add_argument("--wait", type=float, default=0, help="seconds to wait for the build job (default: 0)") + fetch_parser.add_argument("--poll-interval", type=float, default=10, help="seconds between polls (default: 10)") + commands.add_parser("publish", help="upload the harness in target/release/") + commands.add_parser("mark-failed", help="tell the test job that the harness build job failed") + return parser.parse_args(argv) + + +def main(argv=None, environ=None): + environ = os.environ if environ is None else environ + arguments = parse_arguments(argv) + try: + target = getattr(arguments, "target", None) or host_target(REPOSITORY_ROOT) + metadata = load_metadata(REPOSITORY_ROOT, target) + root = Path(metadata["workspace_root"]) + key = compute_key(root, metadata, target) + if key.changed and arguments.command != "mark-failed": + warn(f"the working tree changes these harness inputs, which the key ignores: {', '.join(key.changed)}") + with tempfile.TemporaryDirectory(prefix="harness-cache-") as scratch: + return COMMANDS[arguments.command](arguments, root, key, environ, Path(scratch)) + except (CacheError, OSError, ValueError, KeyError) as error: + if arguments.command == "mark-failed": + warn(f"could not mark the harness build as failed: {error}") + return 0 + print(f"error: {error}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/ci/tooling/install_macos_agent.py b/ci/tooling/install_macos_agent.py index 757a4f8ac1a..060a3170868 100644 --- a/ci/tooling/install_macos_agent.py +++ b/ci/tooling/install_macos_agent.py @@ -7,6 +7,10 @@ The DMG for the host architecture is verified against its recorded SHA-256 before it is mounted, whether it was just downloaded or found in the cache. A marker recording the version, URL and checksum is written only after a successful install, and an installation is reused only when its marker matches the version file and the Agent executable exists. + +The script exits with 75 (`EX_TEMPFAIL`) when the download fails because of the network or the server, and the macOS +integration jobs retry that exit code. It exits with 1 on any other error, including an HTTP 4xx status other than 408 +and 429, because that error happens again on each run. """ import argparse @@ -29,12 +33,18 @@ MARKER_NAME = ".saluki-agent-version.json" AGENT_EXECUTABLE = Path("bin/agent/agent") CLEANUP_SCRIPT = Path(__file__).resolve().with_name("cleanup-macos-dda-mounts.sh") +# `curl --retry` treats these statuses as transient, like server errors. +TEMPORARY_CLIENT_STATUSES = (408, 429) class InstallError(Exception): """The macOS Agent could not be fetched, verified or installed.""" +class TemporaryDownloadError(InstallError): + """The download failed because of the network or the server, so a later run can succeed.""" + + def sha256_file(path): digest = hashlib.sha256() with Path(path).open("rb") as file: @@ -43,11 +53,21 @@ def sha256_file(path): return digest.hexdigest() -def download(url, destination): +def download(url, destination, run=subprocess.run): """Download `url` to `destination`, failing on any HTTP error.""" - result = subprocess.run(["curl", "-fL", "--retry", "3", "--connect-timeout", "30", "-o", str(destination), url]) - if result.returncode != 0: - raise InstallError(f"could not download {url} (curl exit code {result.returncode})") + result = run( + ["curl", "-fL", "--retry", "3", "--connect-timeout", "30", "--write-out", "%{http_code}", "-o", + str(destination), url], + stdout=subprocess.PIPE, text=True, + ) + if result.returncode == 0: + return + # curl writes 000 when it gets no HTTP response. + status = result.stdout.strip() + message = f"could not download {url} (curl exit code {result.returncode}, HTTP status {status or 'unknown'})" + if status.isdigit() and 400 <= int(status) < 500 and int(status) not in TEMPORARY_CLIENT_STATUSES: + raise InstallError(message) + raise TemporaryDownloadError(message) def fetch_verified(url, sha256, cache_dir, fetch=download): @@ -168,6 +188,9 @@ def main(argv=None): try: version_file = agent_version.load_version_file(arguments.file) provision(version_file, arch, Path(arguments.install_dir), Path(arguments.cache_dir)) + except TemporaryDownloadError as error: + print(f"error: {error}", file=sys.stderr) + return os.EX_TEMPFAIL except (agent_version.VersionFileError, InstallError, OSError) as error: print(f"error: {error}", file=sys.stderr) return 1 diff --git a/ci/tooling/macos_target_dir.py b/ci/tooling/macos_target_dir.py new file mode 100644 index 00000000000..91ee9f54bce --- /dev/null +++ b/ci/tooling/macos_target_dir.py @@ -0,0 +1,233 @@ +#!/usr/bin/env python3 +"""Keep cargo profile directories between the jobs of a persistent macOS CI host. + +The amd64 macOS runners are hosts that keep their disk between jobs. At the start of each job, `git clean` deletes +`target/`, because Git doesn't track it. `link --profile PROFILE` keeps `target/PROFILE/` in a persistent directory, and +puts a link to it in `target/`. `git clean` deletes the link, not the directory that it points to. So cargo builds only +what changed since the last job on the host. The rest of `target/`, such as `target/cargo-timings/`, stays in the +checkout, and each job starts without it. + +The persistent directory of a job is `//`, and the slot is `CI_CONCURRENT_ID`. It holds: + +- `target/PROFILE/`, which `target/PROFILE` in the checkout links to. Its real path also holds `/target/PROFILE/`, so a + pattern such as `/target/release/agent-data-plane` matches a program that starts from either path. +- `rust-toolchain.toml`, a copy of the file that the last job used. + +Before it links, `link` deletes `target/` of the slot in these cases: + +- The copy of `rust-toolchain.toml` differs from the file in the checkout. With a new compiler, cargo builds everything + again. +- `du -sk` reports more than the size limit. Cargo never deletes old artifacts. + +`link` does nothing unless `MACOS_PERSISTENT_TARGET` is `true`. It never fails the job. When it can't check or prepare +the persistent directory, it prints a warning and links nothing, so cargo builds in a fresh `target/`. + +See "The persistent build directory of the amd64 macOS jobs" in docs/development/panoramic.md. +""" + +import argparse +import os +import re +import shutil +import subprocess +import sys +import uuid +from pathlib import Path + + +ENABLE_VARIABLE = "MACOS_PERSISTENT_TARGET" +SLOT_VARIABLE = "CI_CONCURRENT_ID" +REPOSITORY_ROOT = Path(__file__).resolve().parents[2] +TOOLCHAIN_FILE = "rust-toolchain.toml" +TARGET_DIR = "target" +STALE_PREFIX = "stale-target-" +DEFAULT_MAX_GIB = 40 +KIB_PER_GIB = 1024 * 1024 +DU_TIMEOUT = 120 +NAME_RE = re.compile(r"[A-Za-z0-9_-]+") + + +class TargetDirError(Exception): + """The persistent directory could not be checked or prepared.""" + + +def info(message): + # Flush, so that the message comes before the output of the next command in the job log. + print(f"[*] {message}", flush=True) + + +def warn(message): + print(f"WARNING: {message}", file=sys.stderr, flush=True) + + +def gib(kib): + return f"{kib / KIB_PER_GIB:.1f} GiB" + + +def checked_name(kind, value): + """Return `value` if it can name a directory, and raise `TargetDirError` otherwise.""" + if not value or not NAME_RE.fullmatch(value): + raise TargetDirError(f"{value!r} isn't a valid {kind}") + return value + + +def disk_usage_kib(path, run=subprocess.run): + """Return the KiB that `du -sk` reports for `path`.""" + command = ["du", "-sk", str(path)] + try: + result = run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=DU_TIMEOUT) + except subprocess.TimeoutExpired: + raise TargetDirError(f"`du -sk {path}` ran for more than {DU_TIMEOUT} seconds") from None + fields = result.stdout.split() + if result.returncode != 0 or not fields or not fields[0].isdigit(): + raise TargetDirError(f"`du -sk {path}` failed with exit code {result.returncode}: {result.stderr.strip()}") + return int(fields[0]) + + +def remove_stale(slot_dir): + """Delete what an interrupted purge left in `slot_dir`.""" + for stale in sorted(slot_dir.glob(f"{STALE_PREFIX}*")): + try: + shutil.rmtree(stale) + except OSError as error: + warn(f"could not delete {stale}: {error}") + + +def purge(target): + """Delete `target`. + + The rename comes first, so that an interrupted delete leaves no partial `target` for the next build. The next run + deletes what it leaves. + """ + stale = target.with_name(f"{STALE_PREFIX}{uuid.uuid4().hex}") + os.rename(target, stale) + try: + shutil.rmtree(stale) + except OSError as error: + warn(f"could not delete {stale}, which the next job deletes: {error}") + + +def purge_reason(target, marker, toolchain, max_kib, run=subprocess.run): + """Return why `target` must go before a build with `toolchain`, or `None` when the build can use it.""" + if not marker.is_file(): + return f"it has no copy of the {TOOLCHAIN_FILE} that built it" + if marker.read_bytes() != toolchain: + return f"another {TOOLCHAIN_FILE} built it" + size = disk_usage_kib(target, run) + if size > max_kib: + return f"it holds {gib(size)}, more than the limit of {gib(max_kib)}" + info(f"Keeping {target}, which holds {gib(size)} of the limit of {gib(max_kib)}") + return None + + +def prepare(slot_dir, toolchain, max_kib, run=subprocess.run): + """Make `target/` of `slot_dir` ready for a build with `toolchain`, the content of `rust-toolchain.toml`. + + Returns the path of `target/` of `slot_dir`. + """ + slot_dir.mkdir(parents=True, exist_ok=True) + remove_stale(slot_dir) + target = slot_dir / TARGET_DIR + marker = slot_dir / TOOLCHAIN_FILE + if not target.exists(): + info(f"{target} doesn't exist, so cargo builds everything") + else: + reason = purge_reason(target, marker, toolchain, max_kib, run) + if reason is not None: + info(f"Deleting {target}, because {reason}") + purge(target) + target.mkdir(exist_ok=True) + partial = marker.with_name(f".{marker.name}.{os.getpid()}") + partial.write_bytes(toolchain) + os.replace(partial, marker) + return target + + +def link_profile(checkout_target, persistent_target, profile): + """Link `checkout_target/profile` to `persistent_target/profile`. Return whether the link is in place.""" + persistent = persistent_target / profile + persistent.mkdir(exist_ok=True) + link = checkout_target / profile + if link.is_symlink(): + if Path(os.readlink(link)) == persistent: + return True + link.unlink() + elif link.exists(): + warn(f"{link} isn't a link, so this job keeps it, and builds the {profile} profile in it") + return False + checkout_target.mkdir(exist_ok=True) + link.symlink_to(persistent, target_is_directory=True) + return True + + +def link(checkout, root, slot, profiles, max_kib, run=subprocess.run): + """Link each profile directory of `checkout` into the persistent directory `root/slot`. Return the linked ones.""" + slot = checked_name("slot", slot) + profiles = [checked_name("profile", profile) for profile in profiles] + toolchain_file = checkout / TOOLCHAIN_FILE + try: + toolchain = toolchain_file.read_bytes() + except OSError as error: + raise TargetDirError(f"could not read {toolchain_file}: {error}") from error + + persistent_target = prepare(root / slot, toolchain, max_kib, run) + linked = [] + for profile in profiles: + try: + if link_profile(checkout / TARGET_DIR, persistent_target, profile): + linked.append(profile) + except OSError as error: + warn(f"could not link the {profile} profile: {error}") + for profile in linked: + info(f"{checkout / TARGET_DIR / profile} links to {persistent_target / profile}") + return linked + + +def default_root(): + return Path.home() / ".cache" / "saluki-ci" / "target" + + +def command_link(arguments, environ): + if environ.get(ENABLE_VARIABLE) != "true": + info(f"{ENABLE_VARIABLE} isn't true, so the build uses the target directory of the checkout") + return 0 + try: + slot = arguments.slot or environ.get(SLOT_VARIABLE) + if slot is None: + raise TargetDirError(f"{SLOT_VARIABLE} isn't set; pass --slot") + root = Path(os.path.abspath(arguments.root or default_root())) + link(arguments.checkout, root, slot, arguments.profile, arguments.max_gib * KIB_PER_GIB) + # The persistent directory only saves time: any error, including a bug in this script, means a fresh build. + except Exception as error: + warn(f"could not prepare the persistent target directory: {error}") + warn("the build uses the target directory of the checkout") + return 0 + + +def parse_arguments(argv): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + commands = parser.add_subparsers(dest="command", required=True) + link_parser = commands.add_parser( + "link", + help="link target/PROFILE to a persistent directory, when MACOS_PERSISTENT_TARGET is true", + ) + link_parser.add_argument("--profile", action="append", required=True, + help="a cargo profile whose directory persists; repeat it for more profiles") + link_parser.add_argument("--root", type=Path, + help="the directory that holds the slots (default: ~/.cache/saluki-ci/target)") + link_parser.add_argument("--slot", help=f"the slot of this job (default: ${SLOT_VARIABLE})") + link_parser.add_argument("--max-gib", type=int, default=DEFAULT_MAX_GIB, + help=f"delete the persistent directory when it holds more (default: {DEFAULT_MAX_GIB})") + link_parser.add_argument("--checkout", type=Path, default=REPOSITORY_ROOT, + help="the checkout whose target/ gets the links (default: this repository)") + return parser.parse_args(argv) + + +def main(argv=None, environ=None): + environ = os.environ if environ is None else environ + arguments = parse_arguments(argv) + return command_link(arguments, environ) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/ci/tooling/test_harness_cache.py b/ci/tooling/test_harness_cache.py new file mode 100644 index 00000000000..9bbf5e1bf2d --- /dev/null +++ b/ci/tooling/test_harness_cache.py @@ -0,0 +1,648 @@ +import contextlib +import importlib.util +import io +import json +import os +import subprocess +import tarfile +import tempfile +import unittest +import unittest.mock +from pathlib import Path + + +TOOLING = Path(__file__).parent +spec = importlib.util.spec_from_file_location("harness_cache", TOOLING / "harness_cache.py") +subject = importlib.util.module_from_spec(spec) +spec.loader.exec_module(subject) + +# The CI variables of a pipeline on the default branch, and of one on another branch. +DEFAULT_BRANCH = {"CI_COMMIT_BRANCH": "main", "CI_DEFAULT_BRANCH": "main"} +TOPIC_BRANCH = {"CI_COMMIT_BRANCH": "topic", "CI_DEFAULT_BRANCH": "main"} + + +TARGET = "aarch64-apple-darwin" +KEY = f"{TARGET}-release-{'0' * 64}" +REGISTRY_SOURCE = "registry+https://github.com/rust-lang/crates.io-index" + +# A workspace with each kind of edge that the closure has to follow or skip. +FILES = { + "Cargo.toml": "[workspace]\n", + "Cargo.lock": "version = 4\n", + "rust-toolchain.toml": "[toolchain]\n", + ".cargo/config.toml": "[build]\n", + "README.md": "not an input\n", + "docker/run": "#!/bin/sh\n", + "docker/unused": "not embedded\n", + "bin/panoramic/Cargo.toml": "[package]\n", + "bin/panoramic/src/main.rs": ( + 'const RUN: &[u8] = include_bytes!(\n "../../../docker/run"\n);\n' + 'const LOCAL: &str = include_str!("local.txt");\n' + '// An example: include_str!("../../../README.md") and include!("missing.rs").\n' + ), + "bin/panoramic/src/local.txt": "inside the package\n", + "bin/intake/Cargo.toml": "[package]\n", + "bin/intake/src/main.rs": "fn main() {}\n", + "bin/millstone/Cargo.toml": "[package]\n", + "bin/millstone/src/main.rs": "fn main() {}\n", + "lib/common/Cargo.toml": "[package]\n", + "lib/common/src/lib.rs": "pub fn common() {}\n", + "lib/build-helper/Cargo.toml": "[package]\n", + "lib/build-helper/src/lib.rs": "pub fn helper() {}\n", + "lib/test-util/Cargo.toml": "[package]\n", + "lib/test-util/src/lib.rs": "pub fn test_util() {}\n", + "lib/patched/Cargo.toml": "[package]\n", + "lib/patched/src/lib.rs": "pub fn patched() {}\n", + "lib/unrelated/Cargo.toml": "[package]\n", + "lib/unrelated/src/lib.rs": "pub fn unrelated() {}\n", +} + + +def make_metadata(root): + """Return `cargo metadata` output for the workspace in FILES, rooted at `root`.""" + + def package(name, path, bins=(), source=None): + targets = [{"name": binary, "kind": ["bin"]} for binary in bins] + [{"name": name, "kind": ["lib"]}] + manifest = str(Path(root) / path / "Cargo.toml") if path else f"/registry/{name}/Cargo.toml" + return {"id": f"{name}-id", "name": name, "source": source, "manifest_path": manifest, "targets": targets} + + packages = [ + package("panoramic", "bin/panoramic", ["panoramic"]), + package("datadog-intake", "bin/intake", ["datadog-intake"]), + package("millstone", "bin/millstone", ["millstone"]), + package("common", "lib/common"), + package("build-helper", "lib/build-helper"), + package("test-util", "lib/test-util"), + package("patched", "lib/patched"), + package("unrelated", "lib/unrelated"), + package("serde", None, source=REGISTRY_SOURCE), + ] + edges = { + "panoramic": [("common", None), ("test-util", "dev"), ("serde", None)], + "datadog-intake": [("common", None)], + "common": [("build-helper", "build")], + # A `[patch]` entry replaces a registry dependency with a local package. + "serde": [("patched", None)], + "unrelated": [("common", None)], + } + nodes = [ + { + "id": f"{name}-id", + "deps": [ + {"pkg": f"{dependency}-id", "dep_kinds": [{"kind": kind}]} for dependency, kind in edges.get(name, []) + ], + } + for name in [package["name"] for package in packages] + ] + members = [package["id"] for package in packages if package["source"] is None] + return { + "workspace_root": str(root), + "workspace_members": members, + "packages": packages, + "resolve": {"nodes": nodes}, + } + + +def git(root, *arguments): + subprocess.run(["git", *arguments], cwd=root, check=True, stdout=subprocess.DEVNULL) + + +class WorkspaceTest(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name).resolve() + # A Git hook exports variables such as GIT_INDEX_FILE. Without this, `git add` writes to the caller's index. + environment = {name: value for name, value in os.environ.items() if not name.startswith("GIT_")} + environment["GIT_CEILING_DIRECTORIES"] = str(self.root.parent) + patcher = unittest.mock.patch.dict(os.environ, environment, clear=True) + patcher.start() + self.addCleanup(patcher.stop) + for path, contents in FILES.items(): + self.write(path, contents) + git(self.root, "init", "--quiet") + git(self.root, "add", "--all") + self.metadata = make_metadata(self.root) + + def write(self, path, contents): + (self.root / path).parent.mkdir(parents=True, exist_ok=True) + (self.root / path).write_text(contents, encoding="utf-8") + + def stage(self, path, contents): + self.write(path, contents) + git(self.root, "add", path) + + def key(self, target=TARGET): + return subject.compute_key(self.root, self.metadata, target) + + +class ClosureTest(WorkspaceTest): + def test_follows_normal_build_and_patched_dependencies(self): + self.assertEqual( + subject.harness_package_dirs(self.metadata), + ["bin/intake", "bin/millstone", "bin/panoramic", "lib/build-helper", "lib/common", "lib/patched"], + ) + + def test_missing_binary_is_an_error(self): + self.metadata["packages"][2]["targets"] = [] + with self.assertRaisesRegex(subject.CacheError, "millstone"): + subject.harness_package_dirs(self.metadata) + + def test_embedded_files_are_the_tracked_files_outside_the_packages(self): + package_dirs = subject.harness_package_dirs(self.metadata) + tracked = subject.tracked_files(self.root) + self.assertEqual(subject.embedded_files(self.root, package_dirs, tracked), ["README.md", "docker/run"]) + + def test_workspace_manifests_cover_every_member(self): + manifests = subject.workspace_manifests(self.metadata) + self.assertIn("lib/unrelated/Cargo.toml", manifests) + self.assertIn("lib/test-util/Cargo.toml", manifests) + self.assertEqual(len(manifests), 8) + + +class KeyTest(WorkspaceTest): + def test_key_is_stable_and_names_the_target_and_profile(self): + first, second = self.key(), self.key() + self.assertEqual(first.value, second.value) + self.assertRegex(first.value, rf"^{TARGET}-release-[0-9a-f]{{64}}$") + self.assertEqual(first.changed, []) + + def test_inputs_change_the_key(self): + for path in [ + "lib/common/src/lib.rs", + "lib/patched/src/lib.rs", + "lib/build-helper/src/lib.rs", + "bin/panoramic/src/local.txt", + "docker/run", + "Cargo.lock", + "Cargo.toml", + "rust-toolchain.toml", + ".cargo/config.toml", + "lib/unrelated/Cargo.toml", + ]: + with self.subTest(path=path): + before = self.key().value + self.stage(path, FILES[path] + "// changed\n") + self.assertNotEqual(self.key().value, before) + + def test_other_files_leave_the_key_alone(self): + before = self.key().value + for path in ["lib/unrelated/src/lib.rs", "lib/test-util/src/lib.rs", "docker/unused", "docs/new.md"]: + self.stage(path, "// changed\n") + self.assertEqual(self.key().value, before) + + def test_target_and_salt_change_the_key(self): + before = self.key().value + self.assertNotEqual(self.key("x86_64-apple-darwin").value, before) + with unittest.mock.patch.object(subject, "SALT", "test"): + self.assertNotEqual(self.key().value, before) + + def test_working_tree_changes_are_reported_and_not_hashed(self): + before = self.key().value + self.write("lib/common/src/lib.rs", "// not staged\n") + self.write("bin/panoramic/src/new.rs", "// untracked\n") + self.write("lib/unrelated/src/lib.rs", "// not an input\n") + key = self.key() + self.assertEqual(key.value, before) + self.assertEqual(key.changed, ["bin/panoramic/src/new.rs", "lib/common/src/lib.rs"]) + + def test_deleted_input_is_reported(self): + before = self.key().value + (self.root / "bin/panoramic/src/main.rs").unlink() + key = self.key() + self.assertEqual(key.value, before) + self.assertEqual(key.changed, ["bin/panoramic/src/main.rs"]) + + def test_untracked_root_input_is_an_error(self): + git(self.root, "rm", "--quiet", "--cached", ".cargo/config.toml") + with self.assertRaisesRegex(subject.CacheError, r"\.cargo/config\.toml"): + self.key() + + +class FakeCurl: + def __init__(self, returncode=0, stdout="200 ", stderr="", responses=None): + self.responses = list(responses or []) + self.result = (returncode, stdout, stderr) + self.calls = [] + + def __call__(self, command, **options): + self.calls.append((command, options)) + returncode, stdout, stderr = self.responses.pop(0) if self.responses else self.result + return subprocess.CompletedProcess(command, returncode, stdout, stderr) + + +class RegistryTest(unittest.TestCase): + def registry(self, curl, token="glcbt-secret"): + return subject.Registry("https://gitlab.example.com/api/v4/", "42", token, run=curl) + + def test_token_goes_in_the_job_token_header_through_standard_input(self): + curl = FakeCurl(stdout="201 ") + status = self.registry(curl).put("v1", "manifest.json", "/tmp/manifest.json") + self.assertEqual(status, 201) + command, options = curl.calls[0] + self.assertNotIn("glcbt-secret", " ".join(command)) + self.assertEqual(options["input"], 'header = "JOB-TOKEN: glcbt-secret"\n') + base = "https://gitlab.example.com/api/v4/projects/42/packages/generic/macos-integration-harness" + self.assertEqual(command[-1], f"{base}/v1/manifest.json") + self.assertIn("--upload-file", command) + self.assertNotIn("--location", command) + + def test_token_is_escaped_for_the_curl_config(self): + curl = FakeCurl() + self.registry(curl, token='a"b\\c').get("v1", "manifest.json", "/tmp/out") + self.assertEqual(curl.calls[0][1]["input"], 'header = "JOB-TOKEN: a\\"b\\\\c"\n') + + def test_redirect_target_is_downloaded_without_the_token(self): + target = "https://objects.example.com/blob?signature=1" + curl = FakeCurl(responses=[(0, f"302 {target}", ""), (0, "200 ", "")]) + status = self.registry(curl).get("v1", "harness.tar.gz", "/tmp/out") + self.assertEqual(status, 200) + self.assertEqual(len(curl.calls), 2) + self.assertNotIn("--location", curl.calls[0][0]) + command, options = curl.calls[1] + self.assertEqual(command[-1], target) + self.assertIn("--location", command) + self.assertEqual(options["input"], "") + + def test_curl_failure_is_status_zero(self): + with contextlib.redirect_stderr(io.StringIO()) as stderr: + curl = FakeCurl(returncode=7, stdout="000", stderr="connection refused") + status = self.registry(curl).get("v1", "f", "/x") + self.assertEqual(status, 0) + self.assertIn("connection refused", stderr.getvalue()) + + def test_from_environment_names_missing_variables(self): + environ = {"CI_API_V4_URL": "https://gitlab.example.com/api/v4", "CI_PROJECT_ID": "1"} + with self.assertRaisesRegex(subject.CacheError, "CI_JOB_TOKEN"): + subject.Registry.from_environment(environ) + + +class FakeClock: + def __init__(self, on_sleep=None): + self.now = 0.0 + self.sleeps = [] + self.on_sleep = on_sleep + + def __call__(self): + return self.now + + def sleep(self, seconds): + self.sleeps.append(seconds) + self.now += seconds + if self.on_sleep: + self.on_sleep(len(self.sleeps)) + + +class RefusingRegistry(subject.DirectoryRegistry): + def get(self, version, name, destination, timeout=None): + return 403 + + +class FailingUploadRegistry(subject.DirectoryRegistry): + def __init__(self, root, fails): + super().__init__(root) + self.fails = fails + + def put(self, version, name, source, timeout=None): + if self.fails(name): + return 500 + return super().put(version, name, source, timeout) + + +class CacheTest(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + self.registry = subject.DirectoryRegistry(self.root / "registry") + self.binaries = self.root / "build/target/release" + self.binaries.mkdir(parents=True) + for binary in subject.BINARIES: + (self.binaries / binary).write_bytes(f"binary {binary}\n".encode()) + self.destination = self.root / "checkout" + self.scratch = self.root / "scratch" + self.scratch.mkdir() + self.environ = {"CI_COMMIT_SHA": "abc123", "CI_JOB_URL": "https://gitlab.example.com/jobs/1"} + + def publish(self, version, registry=None): + archive = subject.create_archive(self.binaries, self.scratch) + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + return subject.publish(registry or self.registry, KEY, version, archive, self.scratch, self.environ) + + def fetch(self, pipeline_id=None, wait=0, clock=None, registry=None): + clock = clock or FakeClock() + with contextlib.redirect_stdout(io.StringIO()) as stdout, contextlib.redirect_stderr(io.StringIO()) as stderr: + fetched = subject.fetch(registry or self.registry, KEY, pipeline_id, self.destination, wait, 10, + self.scratch, clock=clock, sleep=clock.sleep) + self.output = stdout.getvalue() + stderr.getvalue() + return fetched + + def mark_failed(self, stage): + environ = {"CI_JOB_STATUS": "failed", "CI_JOB_URL": "https://gitlab.example.com/jobs/2"} + with contextlib.redirect_stdout(io.StringIO()): + self.assertTrue(subject.mark_failed(self.registry, KEY, "77", stage, self.scratch, environ)) + + def assert_installed(self): + for binary in subject.BINARIES: + path = self.destination / "target/release" / binary + self.assertEqual(path.read_bytes(), f"binary {binary}\n".encode()) + self.assertEqual(path.stat().st_mode & 0o777, 0o755) + + def manifest_path(self, version): + return Path(self.registry.url(version, subject.MANIFEST_FILE)) + + def test_shared_version_round_trip(self): + self.assertTrue(self.publish(KEY)) + self.assertEqual(self.fetch(), subject.Fetched.INSTALLED) + self.assert_installed() + manifest = json.loads(self.manifest_path(KEY).read_text()) + self.assertEqual(manifest["commit"], "abc123") + self.assertEqual(manifest["archive"], f"harness-{manifest['sha256']}.tar.gz") + + def test_fetch_replaces_existing_binaries(self): + (self.destination / "target/release").mkdir(parents=True) + (self.destination / "target/release/panoramic").write_bytes(b"stale") + self.publish(KEY) + self.assertEqual(self.fetch(), subject.Fetched.INSTALLED) + self.assert_installed() + + def test_pipeline_version_is_read_only_by_its_pipeline(self): + self.publish(subject.pipeline_version(KEY, "77")) + self.assertEqual(self.fetch(), subject.Fetched.MISSING) + self.assertEqual(self.fetch(pipeline_id="78"), subject.Fetched.MISSING) + self.assertEqual(self.fetch(pipeline_id="77"), subject.Fetched.INSTALLED) + self.assert_installed() + + def test_fetch_waits_for_the_build_job(self): + def publish_on_second_sleep(sleeps): + if sleeps == 2: + self.publish(subject.pipeline_version(KEY, "77")) + + clock = FakeClock(on_sleep=publish_on_second_sleep) + self.assertEqual(self.fetch(pipeline_id="77", wait=300, clock=clock), subject.Fetched.INSTALLED) + self.assertEqual(clock.sleeps, [10, 10]) + self.assertIn("after a wait of 20 seconds", self.output) + self.assert_installed() + + def test_build_failure_marker_stops_the_wait_with_an_error(self): + self.mark_failed(subject.BUILD_STAGE) + clock = FakeClock() + self.assertEqual(self.fetch(pipeline_id="77", wait=300, clock=clock), subject.Fetched.BUILD_FAILED) + self.assertEqual(clock.sleeps, []) + self.assertIn("error: the harness build job of this pipeline failed", self.output) + self.assertIn("https://gitlab.example.com/jobs/2", self.output) + + def test_publish_failure_marker_stops_the_wait_with_a_miss(self): + self.mark_failed(subject.PUBLISH_STAGE) + clock = FakeClock() + self.assertEqual(self.fetch(pipeline_id="77", wait=300, clock=clock), subject.Fetched.MISSING) + self.assertEqual(clock.sleeps, []) + self.assertIn("could not publish", self.output) + self.assertNotIn("error:", self.output) + + def test_unreadable_failure_marker_reports_a_failed_build(self): + version = subject.pipeline_version(KEY, "77") + for contents in ["not JSON", '["a list"]']: + with self.subTest(contents=contents): + marker = Path(self.registry.url(version, subject.FAILED_FILE)) + marker.parent.mkdir(parents=True, exist_ok=True) + marker.write_text(contents) + self.assertEqual(self.fetch(pipeline_id="77", wait=300), subject.Fetched.BUILD_FAILED) + self.assertIn(str(marker), self.output) + + def test_manifest_wins_over_a_stale_failure_marker(self): + self.mark_failed(subject.BUILD_STAGE) + self.publish(subject.pipeline_version(KEY, "77")) + self.assertEqual(self.fetch(pipeline_id="77"), subject.Fetched.INSTALLED) + self.assert_installed() + + def test_wait_ends_at_the_deadline(self): + clock = FakeClock() + self.assertEqual(self.fetch(pipeline_id="77", wait=25, clock=clock), subject.Fetched.MISSING) + self.assertEqual(clock.sleeps, [10, 10, 5]) + + def test_refused_request_stops_the_wait(self): + with self.assertRaisesRegex(subject.CacheError, "HTTP status 403"): + self.fetch(pipeline_id="77", wait=300, registry=RefusingRegistry(self.root / "registry")) + + def test_failed_archive_upload_skips_the_manifest(self): + registry = FailingUploadRegistry(self.root / "registry", lambda name: name.endswith(".tar.gz")) + self.assertFalse(self.publish(KEY, registry)) + self.assertFalse(self.manifest_path(KEY).exists()) + + def test_failed_manifest_upload_leaves_a_miss(self): + registry = FailingUploadRegistry(self.root / "registry", lambda name: name == subject.MANIFEST_FILE) + self.assertFalse(self.publish(KEY, registry)) + self.assertEqual(self.fetch(), subject.Fetched.MISSING) + + def test_manifest_for_another_key_is_ignored(self): + self.publish(KEY) + manifest = json.loads(self.manifest_path(KEY).read_text()) + manifest["key"] = "another" + self.manifest_path(KEY).write_text(json.dumps(manifest)) + self.assertEqual(self.fetch(), subject.Fetched.MISSING) + + def test_archive_that_differs_from_its_manifest_is_rejected(self): + self.publish(KEY) + manifest = json.loads(self.manifest_path(KEY).read_text()) + archive = Path(self.registry.url(KEY, manifest["archive"])) + + archive.write_bytes(archive.read_bytes() + b"x") + with self.assertRaisesRegex(subject.CacheError, "bytes"): + self.fetch() + + contents = bytearray(archive.read_bytes()[:-1]) + contents[-1] ^= 0xFF + archive.write_bytes(bytes(contents)) + with self.assertRaisesRegex(subject.CacheError, "SHA-256"): + self.fetch() + self.assertFalse((self.destination / "target").exists()) + + def test_archive_with_other_members_is_rejected(self): + archive = self.root / "evil.tar.gz" + with tarfile.open(archive, "w:gz") as tar: + for name in [subject.archive_member(binary) for binary in subject.BINARIES] + ["../outside"]: + tar.add(self.binaries / "panoramic", arcname=name) + with self.assertRaisesRegex(subject.CacheError, "outside"): + subject.extract(archive, self.destination) + self.assertFalse((self.root / "outside").exists()) + + def test_missing_binary_fails_the_archive(self): + (self.binaries / "millstone").unlink() + with self.assertRaisesRegex(subject.CacheError, "millstone"): + subject.create_archive(self.binaries, self.scratch) + + def test_publish_version_depends_on_the_branch(self): + self.assertEqual(subject.publish_version(KEY, {**DEFAULT_BRANCH, "CI_PIPELINE_ID": "7"}), KEY) + self.assertEqual(subject.publish_version(KEY, {**TOPIC_BRANCH, "CI_PIPELINE_ID": "7"}), + f"{KEY}-p7") + with self.assertRaisesRegex(subject.CacheError, "CI_PIPELINE_ID"): + subject.publish_version(KEY, {}) + + +class MainTest(unittest.TestCase): + """Exit codes of the commands, which the CI jobs depend on.""" + + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + self.registry_dir = self.root / "registry" + self.changed = [] + patches = [ + unittest.mock.patch.object(subject, "host_target", return_value=TARGET), + unittest.mock.patch.object(subject, "load_metadata", return_value={"workspace_root": str(self.root)}), + unittest.mock.patch.object(subject, "compute_key", side_effect=self.key), + ] + for patch in patches: + patch.start() + self.addCleanup(patch.stop) + release = self.root / "target/release" + release.mkdir(parents=True) + for binary in subject.BINARIES: + (release / binary).write_bytes(b"binary") + + def key(self, *_): + return subject.Key(TARGET, [], self.changed) + + def main(self, *argv, environ=None, registry=True): + prefix = ["--registry-dir", str(self.registry_dir)] if registry else [] + with contextlib.redirect_stdout(io.StringIO()) as stdout, contextlib.redirect_stderr(io.StringIO()) as stderr: + code = subject.main(prefix + list(argv), environ if environ is not None else {}) + self.stdout, self.stderr = stdout.getvalue(), stderr.getvalue() + return code + + def test_publish_then_exists_and_fetch(self): + environ = dict(DEFAULT_BRANCH) + self.assertEqual(self.main("exists", environ=environ), 1) + self.assertEqual(self.main("publish", environ=environ), 0) + self.assertEqual(self.main("exists", environ=environ), 0) + self.assertEqual(self.main("fetch", environ=environ), 0) + + def test_publish_off_the_default_branch_is_not_shared(self): + environ = {**TOPIC_BRANCH, "CI_PIPELINE_ID": "9"} + self.assertEqual(self.main("publish", environ=environ), 0) + self.assertEqual(self.main("exists", environ=environ), 1) + self.assertEqual(self.main("fetch", environ={}), 1) + self.assertEqual(self.main("fetch", environ=environ), 0) + + def test_publish_without_registry_is_a_warning(self): + self.assertEqual(self.main("publish", environ={"CI_PIPELINE_ID": "9"}, registry=False), 0) + self.assertIn("WARNING: could not publish the harness", self.stderr) + self.assertNotIn("Traceback", self.stderr) + + def marker(self, pipeline_id): + version = subject.pipeline_version(subject.Key(TARGET, [], []).value, pipeline_id) + path = Path(subject.DirectoryRegistry(self.registry_dir).url(version, subject.FAILED_FILE)) + return json.loads(path.read_text()) + + def test_failed_upload_lets_the_test_job_build_the_harness(self): + environ = {"CI_PIPELINE_ID": "9"} + with unittest.mock.patch.object(subject, "publish", return_value=False): + self.assertEqual(self.main("publish", environ=environ), 0) + self.assertEqual(self.marker("9")["stage"], subject.PUBLISH_STAGE) + self.assertEqual(self.main("fetch", "--wait", "300", environ=environ), 1) + + def test_failed_build_fails_the_fetch(self): + environ = {"CI_PIPELINE_ID": "9", "CI_JOB_STATUS": "failed"} + self.assertEqual(self.main("mark-failed", environ=environ), 0) + self.assertEqual(self.marker("9")["stage"], subject.BUILD_STAGE) + self.assertEqual(self.main("fetch", "--wait", "300", environ=environ), 3) + self.assertIn("error: the harness build job of this pipeline failed", self.stderr) + + def test_publish_refuses_changed_inputs(self): + self.changed = ["lib/common/src/lib.rs"] + self.assertEqual(self.main("publish", environ={"CI_PIPELINE_ID": "9"}), 1) + self.assertIn("error:", self.stderr) + + def test_publish_without_binaries_is_an_error(self): + (self.root / "target/release/panoramic").unlink() + self.assertEqual(self.main("publish", environ={"CI_PIPELINE_ID": "9"}), 1) + + def test_fetch_without_registry_is_a_miss(self): + self.assertEqual(self.main("fetch", environ={}, registry=False), 1) + self.assertIn("CI_JOB_TOKEN", self.stderr) + + def test_mark_failed_never_fails_the_job(self): + self.assertEqual(self.main("mark-failed", environ={}), 0) + self.assertEqual(self.main("mark-failed", environ={"CI_PIPELINE_ID": "9"}, registry=False), 0) + with unittest.mock.patch.object(subject, "load_metadata", side_effect=subject.CacheError("no cargo")): + self.assertEqual(self.main("mark-failed", environ={"CI_PIPELINE_ID": "9"}), 0) + self.assertIn("no cargo", self.stderr) + + def test_key_errors_fail(self): + with unittest.mock.patch.object(subject, "load_metadata", side_effect=subject.CacheError("no cargo")): + self.assertEqual(self.main("key"), 1) + + +# A stand-in `python3` that records its arguments, and exits with the code in `FAKE__CODE`. +FAKE_PYTHON = """#!/bin/sh +printf '%s\\n' "$*" >> "$FAKE_LOG" +case "$2" in + fetch) exit "${FAKE_FETCH_CODE:-0}" ;; + publish) exit "${FAKE_PUBLISH_CODE:-0}" ;; +esac +exit 99 +""" +# A stand-in `make` that records its arguments, and exits with the code in `FAKE_BUILD_CODE`. +FAKE_MAKE = """#!/bin/sh +printf 'make %s\\n' "$*" >> "$FAKE_LOG" +exit "${FAKE_BUILD_CODE:-0}" +""" +FETCH = "ci/tooling/harness_cache.py fetch --wait {wait}" +BUILD = "make build-integration-harness-host" +PUBLISH = "ci/tooling/harness_cache.py publish" + + +class GetHarnessScriptTest(unittest.TestCase): + """The commands that get-macos-harness.sh runs for each job configuration, and its exit code.""" + + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + (self.root / "bin").mkdir() + python = self.root / "bin" / "python3" + python.write_text(FAKE_PYTHON, encoding="utf-8") + python.chmod(0o755) + make = self.root / "bin" / "make" + make.write_text(FAKE_MAKE, encoding="utf-8") + make.chmod(0o755) + self.log = self.root / "calls" + + def run_script(self, variables, codes): + self.log.write_text("", encoding="utf-8") + environ = {"PATH": f"{self.root / 'bin'}{os.pathsep}{os.environ['PATH']}", "FAKE_LOG": str(self.log)} + environ.update(variables) + environ.update({f"FAKE_{name.upper()}_CODE": str(code) for name, code in codes.items()}) + result = subprocess.run(["bash", str(TOOLING / "get-macos-harness.sh")], cwd=self.root, env=environ, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + return result.returncode, self.log.read_text(encoding="utf-8").splitlines(), result.stderr + + def test_commands_and_exit_codes(self): + arm64 = {"HARNESS_CACHE_WAIT": "480"} + amd64 = {"HARNESS_CACHE_WAIT": "0", "HARNESS_CACHE_PUBLISH": "true", **DEFAULT_BRANCH} + amd64_topic = {**amd64, **TOPIC_BRANCH} + fetch_480, fetch_0 = FETCH.format(wait=480), FETCH.format(wait=0) + cases = [ + ("no cache", {}, {}, 0, [BUILD]), + ("arm64 hit", arm64, {"fetch": 0}, 0, [fetch_480]), + ("arm64 failed build job", arm64, {"fetch": 3}, 1, [fetch_480]), + ("arm64 miss", arm64, {"fetch": 1}, 0, [fetch_480, BUILD]), + ("arm64 failed local build", arm64, {"fetch": 1, "build": 2}, 2, [fetch_480, BUILD]), + ("amd64 hit", amd64, {"fetch": 0}, 0, [fetch_0]), + ("amd64 miss publishes", amd64, {"fetch": 1}, 0, [fetch_0, BUILD, PUBLISH]), + ("amd64 failed publish", amd64, {"fetch": 1, "publish": 1}, 0, [fetch_0, BUILD, PUBLISH]), + ("amd64 failed local build", amd64, {"fetch": 1, "build": 2}, 2, [fetch_0, BUILD]), + ("amd64 topic branch miss", amd64_topic, {"fetch": 1}, 0, [fetch_0, BUILD]), + ] + for name, variables, codes, expected_code, expected_calls in cases: + with self.subTest(name): + code, calls, stderr = self.run_script(variables, codes) + self.assertEqual((code, calls), (expected_code, expected_calls), stderr) + if codes.get("publish"): + self.assertIn("WARNING: could not publish the harness", stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/ci/tooling/test_install_macos_agent.py b/ci/tooling/test_install_macos_agent.py index b6d495ff592..1f3992897b4 100644 --- a/ci/tooling/test_install_macos_agent.py +++ b/ci/tooling/test_install_macos_agent.py @@ -11,6 +11,8 @@ import unittest.mock from pathlib import Path +import yaml + TOOLING = Path(__file__).parent sys.path.insert(0, str(TOOLING)) @@ -148,5 +150,53 @@ def test_a_failed_install_leaves_no_marker(self): self.assertFalse((self.install_dir / subject.MARKER_NAME).exists()) +class DownloadTest(unittest.TestCase): + def download(self, returncode, status): + def curl(command, **_): + return subprocess.CompletedProcess(command, returncode, stdout=status) + + subject.download("https://example.test/agent.dmg", "/nonexistent/agent.dmg", curl) + + def test_a_successful_download_raises_nothing(self): + self.download(0, "200") + + def test_network_and_server_errors_are_temporary(self): + # A refused connection, a timeout, a server error, statuses that curl retries, and a transfer cut after the + # headers. + failures = ((7, "000"), (28, "000"), (22, "503"), (22, "429"), (22, "408"), (56, "200"), (7, "")) + for returncode, status in failures: + with self.subTest(returncode=returncode, status=status): + with self.assertRaises(subject.TemporaryDownloadError): + self.download(returncode, status) + + def test_other_client_errors_are_not_temporary(self): + for status in ("403", "404"): + with self.subTest(status=status): + with self.assertRaisesRegex(subject.InstallError, f"HTTP status {status}") as raised: + self.download(22, status) + self.assertNotIsInstance(raised.exception, subject.TemporaryDownloadError) + + +class MainTest(unittest.TestCase): + def main(self, error): + patch = unittest.mock.patch.object + with patch(subject.platform, "machine", return_value="arm64"), \ + patch(subject.agent_version, "load_version_file", return_value=version_file_for()), \ + patch(subject, "provision", side_effect=error), \ + contextlib.redirect_stderr(io.StringIO()): + return subject.main(["--install-dir", "unused", "--cache-dir", "unused"]) + + def test_exit_codes(self): + self.assertEqual(self.main(None), 0) + self.assertEqual(self.main(subject.TemporaryDownloadError("could not download")), os.EX_TEMPFAIL) + self.assertEqual(self.main(subject.InstallError("bad checksum")), 1) + + def test_the_macos_integration_jobs_retry_a_temporary_download_failure(self): + jobs = yaml.safe_load((TOOLING.parents[1] / ".gitlab/e2e.yml").read_text(encoding="utf-8")) + retry = jobs[".test-integration-macos-base"]["retry"] + self.assertIn(os.EX_TEMPFAIL, retry["exit_codes"]) + self.assertNotIn("script_failure", retry["when"]) + + if __name__ == "__main__": unittest.main() diff --git a/ci/tooling/test_macos_target_dir.py b/ci/tooling/test_macos_target_dir.py new file mode 100644 index 00000000000..80e75aeeccf --- /dev/null +++ b/ci/tooling/test_macos_target_dir.py @@ -0,0 +1,269 @@ +import contextlib +import importlib.util +import io +import os +import subprocess +import tempfile +import unittest +import unittest.mock +from pathlib import Path + + +TOOLING = Path(__file__).parent +spec = importlib.util.spec_from_file_location("macos_target_dir", TOOLING / "macos_target_dir.py") +subject = importlib.util.module_from_spec(spec) +spec.loader.exec_module(subject) + + +TOOLCHAIN = b'[toolchain]\nchannel = "1.96.0"\n' +NEW_TOOLCHAIN = b'[toolchain]\nchannel = "1.97.0"\n' +LIMIT_KIB = 40 * subject.KIB_PER_GIB + + +def quiet(function, *args, **kwargs): + """Call `function` and return its result and everything that it printed.""" + with contextlib.redirect_stdout(io.StringIO()) as stdout, contextlib.redirect_stderr(io.StringIO()) as stderr: + result = function(*args, **kwargs) + return result, stdout.getvalue() + stderr.getvalue() + + +def failing_du(command, **options): + return subprocess.CompletedProcess(command, 1, "", "du: target: Permission denied") + + +def slow_du(command, **options): + raise subprocess.TimeoutExpired(command, options["timeout"]) + + +class Checkout(unittest.TestCase): + """A checkout with `rust-toolchain.toml`, and an empty root for the persistent directories.""" + + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + base = Path(directory.name).resolve() + self.checkout = base / "builds" / "runner" / "0" / "saluki" + self.checkout.mkdir(parents=True) + (self.checkout / "rust-toolchain.toml").write_bytes(TOOLCHAIN) + self.root = base / "cache" + self.slot_dir = self.root / "0" + self.persistent = self.slot_dir / "target" + + def link(self, profiles=("release",), max_kib=LIMIT_KIB, run=subprocess.run, slot="0"): + linked, self.output = quiet(subject.link, self.checkout, self.root, slot, list(profiles), max_kib, run) + return linked + + def build(self, profile="release", name="agent-data-plane", content=b"binary\n"): + """Write a file the way cargo does, through `target/` of the checkout.""" + path = self.checkout / "target" / profile / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content) + return path + + def git_clean(self): + """Delete `target/` of the checkout, as `git clean -ffdx` does at the start of a job.""" + subject.shutil.rmtree(self.checkout / "target") + + +class LinkTest(Checkout): + def test_first_link_creates_the_persistent_directory(self): + self.assertEqual(self.link(), ["release"]) + link = self.checkout / "target" / "release" + self.assertTrue(link.is_symlink()) + self.assertEqual(Path(os.readlink(link)), self.persistent / "release") + self.assertEqual((self.slot_dir / "rust-toolchain.toml").read_bytes(), TOOLCHAIN) + self.assertIn("so cargo builds everything", self.output) + + def test_build_output_outlives_the_checkout(self): + self.link() + self.build() + self.git_clean() + self.assertEqual(self.link(), ["release"]) + self.assertEqual((self.checkout / "target" / "release" / "agent-data-plane").read_bytes(), b"binary\n") + self.assertIn("Keeping", self.output) + + def test_only_the_named_profiles_persist(self): + self.link(profiles=["release"]) + self.build(profile="optimized-release") + self.build(profile="release") + self.assertFalse((self.checkout / "target" / "optimized-release").is_symlink()) + self.assertEqual(sorted(path.name for path in self.persistent.iterdir()), ["release"]) + + def test_several_profiles_persist(self): + self.assertEqual(self.link(profiles=["release", "optimized-release"]), ["release", "optimized-release"]) + self.assertTrue((self.checkout / "target" / "optimized-release").is_symlink()) + + def test_programs_match_the_cleanup_patterns_through_either_path(self): + self.link() + program = self.build() + # before_script stops leftover programs with `pkill -f /target/release/agent-data-plane`. + pattern = "/target/release/agent-data-plane" + self.assertIn(pattern, str(program)) + self.assertIn(pattern, str(program.resolve())) + self.assertNotEqual(program.resolve(), program) + + def test_new_toolchain_deletes_the_persistent_directory(self): + self.link() + self.build() + (self.checkout / "rust-toolchain.toml").write_bytes(NEW_TOOLCHAIN) + self.git_clean() + self.assertEqual(self.link(), ["release"]) + self.assertIn("another rust-toolchain.toml built it", self.output) + self.assertFalse((self.persistent / "release" / "agent-data-plane").exists()) + self.assertEqual((self.slot_dir / "rust-toolchain.toml").read_bytes(), NEW_TOOLCHAIN) + + def test_missing_toolchain_copy_deletes_the_persistent_directory(self): + (self.persistent / "release").mkdir(parents=True) + (self.persistent / "release" / "old").write_bytes(b"old\n") + self.link() + self.assertIn("it has no copy of the rust-toolchain.toml", self.output) + self.assertFalse((self.persistent / "release" / "old").exists()) + + def test_directory_over_the_limit_is_deleted(self): + self.link() + self.build(content=os.urandom(64 * 1024)) + self.git_clean() + self.assertEqual(self.link(max_kib=16), ["release"]) + self.assertIn("more than the limit", self.output) + self.assertEqual(list((self.persistent / "release").iterdir()), []) + + def test_directory_under_the_limit_is_kept(self): + self.link() + self.build(content=os.urandom(64 * 1024)) + self.git_clean() + self.link(max_kib=1024) + self.assertTrue((self.persistent / "release" / "agent-data-plane").exists()) + + def test_failed_size_check_links_nothing(self): + self.link() + self.git_clean() + for run in (failing_du, slow_du): + with self.subTest(run=run.__name__): + with self.assertRaises(subject.TargetDirError): + self.link(run=run) + self.assertFalse((self.checkout / "target").exists()) + + def test_interrupted_purge_is_cleaned_up(self): + stale = self.slot_dir / f"{subject.STALE_PREFIX}leftover" + (stale / "release").mkdir(parents=True) + (stale / "release" / "old").write_bytes(b"old\n") + self.link() + self.assertFalse(stale.exists()) + + def test_failed_delete_of_a_purge_is_a_warning(self): + self.link() + self.build() + (self.checkout / "rust-toolchain.toml").write_bytes(NEW_TOOLCHAIN) + self.git_clean() + with unittest.mock.patch.object(subject.shutil, "rmtree", side_effect=PermissionError("denied")): + self.assertEqual(self.link(), ["release"]) + self.assertIn("which the next job deletes", self.output) + # The rename still gives the build an empty directory. + self.assertEqual(list((self.persistent / "release").iterdir()), []) + + def test_real_directory_in_the_checkout_is_kept(self): + self.build() + self.assertEqual(self.link(), []) + self.assertIn("isn't a link, so this job keeps it", self.output) + self.assertEqual((self.checkout / "target" / "release" / "agent-data-plane").read_bytes(), b"binary\n") + + def test_link_to_another_directory_is_replaced(self): + elsewhere = self.root / "elsewhere" + elsewhere.mkdir(parents=True) + (self.checkout / "target").mkdir() + (self.checkout / "target" / "release").symlink_to(elsewhere) + self.assertEqual(self.link(), ["release"]) + self.assertEqual(Path(os.readlink(self.checkout / "target" / "release")), self.persistent / "release") + self.assertTrue(elsewhere.is_dir()) + + def test_existing_link_is_kept(self): + self.link() + self.assertEqual(self.link(), ["release"]) + + def test_invalid_names_are_errors(self): + for slot, profile in (("../0", "release"), ("", "release"), ("0", "../release"), ("0", "release/x")): + with self.subTest(slot=slot, profile=profile): + with self.assertRaises(subject.TargetDirError): + self.link(profiles=[profile], slot=slot) + + def test_missing_toolchain_file_is_an_error(self): + (self.checkout / "rust-toolchain.toml").unlink() + with self.assertRaises(subject.TargetDirError): + self.link() + + +class GitCleanTest(Checkout): + """`git clean -ffdx` deletes the links in `target/`, and leaves the directories that they point to.""" + + def test_git_clean_keeps_the_persistent_directory(self): + # A Git hook exports variables such as GIT_INDEX_FILE. Without this, Git works on the caller's repository. + environment = {name: value for name, value in os.environ.items() if not name.startswith("GIT_")} + environment["GIT_CEILING_DIRECTORIES"] = str(self.checkout.parent) + + def git(*arguments): + subprocess.run(["git", *arguments], cwd=self.checkout, env=environment, check=True, + stdout=subprocess.DEVNULL) + + (self.checkout / ".gitignore").write_text("target/\n", encoding="utf-8") + git("init", "--quiet") + self.link() + self.build() + status = subprocess.run(["git", "status", "--porcelain", "--untracked-files=all"], cwd=self.checkout, + env=environment, check=True, stdout=subprocess.PIPE, text=True).stdout + self.assertNotIn("target", status) + git("clean", "-ffdx", "--quiet") + self.assertFalse((self.checkout / "target").exists()) + self.assertEqual((self.persistent / "release" / "agent-data-plane").read_bytes(), b"binary\n") + + +class CommandTest(Checkout): + def main(self, environ, *argv): + argv = ["link", "--profile", "release", "--root", str(self.root), "--checkout", str(self.checkout), *argv] + code, self.output = quiet(subject.main, argv, environ) + return code + + def test_disabled_links_nothing(self): + self.assertEqual(self.main({"CI_CONCURRENT_ID": "0"}), 0) + self.assertIn("MACOS_PERSISTENT_TARGET isn't true", self.output) + self.assertFalse(self.root.exists()) + self.assertFalse((self.checkout / "target").exists()) + + def test_enabled_links_the_slot_of_the_job(self): + self.assertEqual(self.main({"MACOS_PERSISTENT_TARGET": "true", "CI_CONCURRENT_ID": "3"}), 0) + link = self.checkout / "target" / "release" + self.assertEqual(Path(os.readlink(link)), self.root / "3" / "target" / "release") + + def test_slot_option_overrides_the_variable(self): + self.assertEqual(self.main({"MACOS_PERSISTENT_TARGET": "true", "CI_CONCURRENT_ID": "3"}, "--slot", "7"), 0) + self.assertTrue((self.root / "7" / "target" / "release").is_dir()) + + def test_size_limit_is_in_gib(self): + captured = {} + + def link(checkout, root, slot, profiles, max_kib, run=subprocess.run): + captured["max_kib"] = max_kib + return profiles + + with unittest.mock.patch.object(subject, "link", side_effect=link): + self.main({"MACOS_PERSISTENT_TARGET": "true", "CI_CONCURRENT_ID": "0"}, "--max-gib", "2") + self.assertEqual(captured["max_kib"], 2 * 1024 * 1024) + + def test_missing_slot_is_a_warning(self): + self.assertEqual(self.main({"MACOS_PERSISTENT_TARGET": "true"}), 0) + self.assertIn("CI_CONCURRENT_ID isn't set", self.output) + self.assertFalse((self.checkout / "target").exists()) + + def test_any_error_is_a_warning(self): + with unittest.mock.patch.object(subject, "prepare", side_effect=KeyError("HOME")): + self.assertEqual(self.main({"MACOS_PERSISTENT_TARGET": "true", "CI_CONCURRENT_ID": "0"}), 0) + self.assertIn("the build uses the target directory of the checkout", self.output) + self.assertFalse((self.checkout / "target").exists()) + + def test_profile_is_required(self): + with self.assertRaises(SystemExit) as raised: + quiet(subject.main, ["link"], {}) + self.assertEqual(raised.exception.code, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/codereview_guideline.md b/codereview_guideline.md index e28deb85d30..45331b2246c 100644 --- a/codereview_guideline.md +++ b/codereview_guideline.md @@ -377,7 +377,8 @@ Also: ### Build and release plumbing - A renamed or new build variable has the same name in every producer and consumer. This covers Make variables, - Docker build `ARG` values, CI variables, and the `APP_*` variables that `lib/saluki-metadata/build.rs` reads. + Docker build `ARG` values, CI variables, and the `APP_*` variables that `declare_app_details!` in + `lib/saluki-metadata/src/lib.rs` reads. - Developers build on macOS. Flag `Makefile` defaults from the host, such as `rustc -vV` or `uname`, that reach Linux container builds. Flag scripts that fail on an unknown architecture. - In `Cargo.lock`, flag a downgrade of a crate that the pull request doesn't target. diff --git a/deny.toml b/deny.toml index b49531a8b17..6d9f7a4f425 100644 --- a/deny.toml +++ b/deny.toml @@ -37,20 +37,6 @@ ignore = [ # chrono is unmaintained. No known vulnerability. Our own code uses `jiff`, but chrono still arrives through # `lading-payload`, which only millstone uses, until lading drops it. { id = "RUSTSEC-2026-0543", reason = "unmaintained only; only lading-payload (millstone) still depends on chrono" }, - - # heapless 0.8 has several unsoundness advisories. It arrives only through `faster-hex` 0.10, which `gix` uses in the - # `panoramic` build script through `vergen-gix`. `faster-hex` uses heapless only when its `alloc` feature is off, but - # Cargo cannot evaluate a feature in a target-specific dependency, so the crate is always in the graph. `gix` enables - # `alloc`, so no heapless code is used. The latest `gix` still uses `faster-hex` 0.10. - { id = "RUSTSEC-2026-0574", reason = "faster-hex 0.10 never uses heapless with alloc on; panoramic build only" }, - { id = "RUSTSEC-2026-0575", reason = "faster-hex 0.10 never uses heapless with alloc on; panoramic build only" }, - { id = "RUSTSEC-2026-0576", reason = "faster-hex 0.10 never uses heapless with alloc on; panoramic build only" }, - { id = "RUSTSEC-2026-0577", reason = "faster-hex 0.10 never uses heapless with alloc on; panoramic build only" }, - { id = "RUSTSEC-2026-0578", reason = "faster-hex 0.10 never uses heapless with alloc on; panoramic build only" }, - { id = "RUSTSEC-2026-0579", reason = "faster-hex 0.10 never uses heapless with alloc on; panoramic build only" }, - { id = "RUSTSEC-2026-0580", reason = "faster-hex 0.10 never uses heapless with alloc on; panoramic build only" }, - { id = "RUSTSEC-2026-0581", reason = "faster-hex 0.10 never uses heapless with alloc on; panoramic build only" }, - { id = "RUSTSEC-2026-0582", reason = "faster-hex 0.10 never uses heapless with alloc on; panoramic build only" }, ] [graph] diff --git a/docs/agent-data-plane/releasing.md b/docs/agent-data-plane/releasing.md index c04ec61bb0f..6feafc45bf3 100644 --- a/docs/agent-data-plane/releasing.md +++ b/docs/agent-data-plane/releasing.md @@ -266,9 +266,12 @@ regular CI builds. The relevant build arguments are all prefixed with `APP_` and - `APP_BUILD_TIME`: the time the build was performed (set to the creation time of the GitLab CI pipeline) - `APP_DEV_BUILD`: whether this is a development build (set to `false` only for tag pipelines) -Note that `APP_DEV_BUILD` also acts as a safety check: when it is `false`, `saluki-metadata`'s build script fails the -build if any of the values above are missing or still hold their placeholder defaults. This keeps a release binary from -silently shipping metadata that reports `unknown`. +The `declare_app_details!` macro from `saluki-metadata` captures these values when the `agent-data-plane` crate +compiles. A new value rebuilds only that crate, and not the shared crates that it depends on. + +`APP_DEV_BUILD` also acts as a safety check: when it is `false`, the `agent-data-plane` crate fails to compile if any of +the preceding values are missing or still hold their placeholder defaults. This keeps a release binary from silently +shipping metadata that reports `unknown`. This build metadata shouldn't need to be manually changed on a per-release basis, and so this section is mostly informational and not relevant to the release process itself. diff --git a/docs/development/conventions.md b/docs/development/conventions.md index 767cc48e53a..30ef1796480 100644 --- a/docs/development/conventions.md +++ b/docs/development/conventions.md @@ -178,7 +178,8 @@ Examples are the `Makefile`, `ci/`, `docker/`, `.gitlab-ci.yml`, and `Cargo.lock - A renamed or new build variable has the same name in every producer and consumer. This covers Make variables, - Docker build `ARG` values, CI variables, and the `APP_*` variables that `lib/saluki-metadata/build.rs` reads. + Docker build `ARG` values, CI variables, and the `APP_*` variables that `declare_app_details!` in + `lib/saluki-metadata/src/lib.rs` reads. - Developers build on macOS. Flag `Makefile` defaults from the host, such as `rustc -vV` or `uname`, that reach Linux container builds. Flag scripts that fail on an unknown architecture. - In `Cargo.lock`, flag a downgrade of a crate that the pull request doesn't target. diff --git a/docs/development/panoramic.md b/docs/development/panoramic.md index a41816a4d03..2963796864a 100644 --- a/docs/development/panoramic.md +++ b/docs/development/panoramic.md @@ -83,6 +83,8 @@ target/release/panoramic plan test/integration/cases/adp-cmd-host --subject-os l | `--log-level ` | The log level of panoramic and its libraries. The default is `info`. | | `--kind-cluster-name `, `--no-delete-kind-cluster` | The kind cluster of the cases that run pods, and whether to keep it after the run. | | `--kind-setup-timeout ` | How long making the kind cluster and loading the images may take before the first case, written like a case `timeout`. The default is `30m`. | +| `--revision `, `PANORAMIC_REVISION` | The revision that `run.json` reports. See [Results](#results). | +| `--ci-commit-sha `, `CI_COMMIT_SHA` | The commit of the CI pipeline, which `run.json` reports when `--revision` is unset. | `PANORAMIC_SET` takes the `--set` entries as a comma-separated list. CI uses it to run the cases against the images a pipeline built. `NAME` is the reference exactly as the case or the participant type writes it. A name given twice is @@ -138,12 +140,105 @@ container or a pod from starting. | --- | --- | | `test-integration-linux-arm64` | Every integration case on Linux, with the images the pipeline built. | | `test-integration-linux-amd64` | The same cases on Intel. Pushes to development and merge queue branches skip it. | -| `test-integration-macos-arm64` | The cases that declare macOS, as host processes. | -| `test-integration-macos-amd64` | The same cases on Intel. Pushes to development and merge queue branches skip it. | +| `test-integration-macos-arm64` | The cases that declare macOS, as host processes. It builds ADP, and takes the harness from the [harness cache](#the-macos-harness-cache). | +| `test-integration-macos-amd64` | The same cases on Intel. It keeps its [build directory](#the-persistent-build-directory-of-the-amd64-macos-jobs) between jobs, and takes the harness from the [harness cache](#the-macos-harness-cache) when the cache has it. Pushes to development and merge queue branches skip it. | +| `build-macos-harness-arm64` | Builds panoramic, datadog-intake and millstone for arm64 macOS, unless the [harness cache](#the-macos-harness-cache) has them. | | `test-integration-windows-amd64` | The cases that declare Windows, in Windows containers. | | `generate-correctness-pipeline` | Makes one `test-correctness-` job for each correctness case. | | `run-correctness-tests` | Runs the generated jobs. A case with pods gets the longer kind template. | +#### The macOS harness cache + +The harness is panoramic, datadog-intake and millstone. When the cache doesn't have it, `build-macos-harness-arm64` +builds it and stores it in the GitLab generic package registry. `ci/tooling/harness_cache.py` computes the key and reads +and writes the registry. The key is a hash of the Git blobs of these files: + +- the files of the local packages that the three binaries depend on, from `cargo metadata` +- the files outside those packages that their sources embed +- `Cargo.lock`, `rust-toolchain.toml`, `.cargo/config.toml`, and the manifest of the workspace and of each member + +The key also covers the target triple, the profile and a salt. When you change the recipe of +`make build-integration-harness-host`, bump `SALT` in the script. To see what a key covers, run +`python3 ci/tooling/harness_cache.py key --explain`. + +A pipeline on the default branch publishes a harness that every pipeline can use. A pipeline on another ref publishes +a harness that only that pipeline uses. Every branch of the project is protected, so the scripts compare +`CI_COMMIT_BRANCH` with `CI_DEFAULT_BRANCH`, and not `CI_COMMIT_REF_PROTECTED`. + +The scripts send `CI_JOB_TOKEN` in the `JOB-TOKEN` header, which is the only form of a job token that the generic +package registry accepts. When the registry redirects a download to object storage, the scripts follow the redirect +without the token. + +`test-integration-macos-arm64` builds ADP first. Then `ci/tooling/get-macos-harness.sh` polls the registry every 10 +seconds, for up to `HARNESS_CACHE_WAIT` seconds. The job sets 480 seconds. When the registry has no harness yet, the +test job does one of these: + +- When the build job fails, it publishes a failure marker. The test job then stops with an error that links to the + build job. Retry the test job only after the build job passes. A test job that starts before then finds the marker + again. +- When the build job builds the harness but can't upload it, its marker says so. The test job then builds the harness. +- When the wait ends, or the test job can't read the registry, the test job builds the harness. + +No job builds the harness for amd64 ahead of `test-integration-macos-amd64`. That job sets `HARNESS_CACHE_WAIT` to 0, +so `get-macos-harness.sh` looks for the shared harness once. When the registry doesn't have it, the job builds the +harness. The job also sets `HARNESS_CACHE_PUBLISH` to `true`, so on the default branch it then publishes the +shared harness. A failed upload is a warning. On another ref, the job publishes nothing, because no other job reads its +harness. + +#### The persistent build directory of the amd64 macOS jobs + +The amd64 macOS runners are hosts that keep their disk between jobs. At the start of each job, `git clean` deletes +`target/`, because Git doesn't track it. So `test-integration-macos-amd64` sets `MACOS_PERSISTENT_TARGET` to `true`, +and runs `python3 ci/tooling/macos_target_dir.py link --profile release` before its first build. The script keeps +`target/release/` in `~/.cache/saluki-ci/target//target/release/` on the host, and links it into +`target/`. `git clean` deletes the link, not the directory that it points to. So cargo builds only what changed since +the last job on the host. + +Only `target/release/` persists. The harness always builds with this profile, and ADP builds with it in every pipeline +except tag pipelines. Tag pipelines build ADP with `optimized-release`, in the checkout, from scratch. The rest of +`target/`, such as `target/cargo-timings/`, also stays in the checkout. So the job artifacts hold the timing reports of +that job only. + +Next to the persistent directory, the script keeps a copy of the `rust-toolchain.toml` of the last job. Before it +links, the script deletes the persistent directory in these cases: + +- The copy differs from `rust-toolchain.toml` in the checkout. With a new compiler, cargo builds everything again. +- `du -sk` reports more than 40 GiB. Cargo never deletes old artifacts, so the directory grows with each change to + the dependencies. The job log shows the size before each build. + +The script never fails the job. When it can't check or prepare the persistent directory, it prints a warning, and cargo +builds in the checkout from scratch. To turn it off, set `MACOS_PERSISTENT_TARGET` to `false`. To clear it on a host, +delete `~/.cache/saluki-ci/target/`. + +A program that starts from `target/release/` shows that path in its command line. The real path of the persistent +directory also holds `/target/release/`. So the `pkill -f /target/release/...` patterns in `before_script` match the +program through either path. + +#### Retries of the macOS jobs + +`test-integration-macos-arm64` and `test-integration-macos-amd64` retry a failed job up to two times, but only when the +failure comes from the infrastructure. A retry runs the whole job again. So a failed build, a failed test case or a +job that runs past its timeout fails at once. GitLab retries the job in these cases: + +- GitLab reports a runner system failure, a stuck job, a scheduler failure, an API failure, a data integrity failure + or an unknown failure. +- The script exits with 75 (`EX_TEMPFAIL`). + +The script exits with 75 in these cases: + +- `ci/tooling/install_macos_agent.py` can't download the Agent DMG because of the network or the server. An HTTP 4xx + status other than 408 and 429 happens again on each run, so the installer exits with 1 for it. +- `make cargo-install-cargo-auditable` fails. This step only installs the Rust version in `rust-toolchain.toml`, + cargo-binstall and cargo-auditable. + +`make` exits with 2 when a recipe fails, whatever the exit code of the recipe. So the job runs the installer before +`make provision-macos-test-env`, and gives the tool step the exit code 75 itself. When you add a download to the job, +give its failure the exit code 75 in the same way. A problem with the harness cache never fails the job, so this step +doesn't need the exit code. + +`build-macos-harness-arm64` retries only on the failures that GitLab reports. When its script fails, its failure marker +stops the test job, so a retry of the build job can't help that test job. + ## The case file ```yaml @@ -496,6 +591,16 @@ runner writes `plan.json` from the settled outcome, so a case that does not pass cancelled or dropped after its cleanup grace. A skipped case has no plan. The report lists the file under `artifacts`. +The `build_revision` key of `run.json` names the commit that the run tests. Panoramic reads it when the run starts, +from the first source that is set: + +1. `--revision`, or `PANORAMIC_REVISION`. +2. `--ci-commit-sha`, or `CI_COMMIT_SHA`, which GitLab CI sets. +3. The Git checkout that holds the first test directory. A checkout with changes that are not committed gets a + `-dirty` suffix. A new file is a change, unless Git ignores it. + +The key is `unknown` when the source is not a commit SHA, or when Git cannot read the checkout. + The exit code of a run is: | Code | Meaning | diff --git a/docs/development/plans/macos-integration-ci.md b/docs/development/plans/macos-integration-ci.md index 3918e9aacfa..03a72daa234 100644 --- a/docs/development/plans/macos-integration-ci.md +++ b/docs/development/plans/macos-integration-ci.md @@ -59,7 +59,10 @@ data for more than 2,600 arm64 runs and 1,900 amd64 runs since 2026-11-10. Refer - **Build topology:** build the harness (panoramic, datadog-intake, millstone) in a parallel job, and cache it by a hash of its inputs. ADP builds in the test job. - **ADP profile:** always test the shipped ADP profile. ADP keeps `--profile $BUILD_PROFILE` and cargo-auditable. -- **Compile cache:** use `buildcache` with the S3 bucket that the Linux Docker builds use. +- **Compile cache:** none on the macOS jobs. PR 1's timings showed that each build ends with about 2 minutes on one + core, in the thin LTO and the link of the binary, which a compile cache can't shorten. buildcache could save at most + about a minute of the ADP build, for an S3 credentials check, a build of buildcache on the VM and CMake and Ninja on + the image. - **Intel unit tests:** `unit-tests-macos-amd64` stays pre-merge. Queueing on the Intel pool at the pipeline level is out of scope. - **Stability windows:** shorten them in cases that aren't about lasting behavior. @@ -99,23 +102,24 @@ The effort lands as four stacked pull requests. Each one ticks its box and adds open. - Check the `adp-config-otlp` keys against one configuration snapshot. - ADP retries its first IPC connect with exponential backoff. -- [ ] **4. Build caches.** +- [x] **4. Build caches.** - Panoramic reads its revision at run time, so a cached binary reports the right revision. - - A job builds or fetches the harness, keyed by a hash of its inputs and stored in the GitLab generic package - registry. The test job builds only ADP and fetches the harness. + - `build-macos-harness-arm64` builds the harness when the cache doesn't have it, keyed by a hash of its inputs and + stored in the GitLab generic package registry. The arm64 test job builds only ADP and takes the harness from the + cache. - Build metadata moves into the binary crate, so the shared crates stop rebuilding on every commit. - - buildcache on the Tart VMs. - - A persistent target directory on amd64. - - Retry only infrastructure failures. + - The amd64 job keeps its target directory between jobs, with a size cap. + - The jobs retry only infrastructure failures. A failed download exits with 75, which is retried. ## Follow-ups - Turn on host slots on amd64, after a check of `dogstatsd-replay-unix` there. - Remove the listener sampler once the first runs with host slots show no undeclared listeners. - Lower the job timeouts once the new p99 is known. +- Confirm that `CI_JOB_TOKEN` can upload to the generic package registry with the `JOB-TOKEN` header. The registry is + enabled. The first run sent the token as a basic-auth password, and the registry answered 401. - Ask CI-platform to: - - bake the toolchain, cargo-binstall, cargo-auditable, cargo-nextest and `buildcache` into the Tart image; - - confirm that the Tart IAM role can read and write the build cache bucket; + - bake the toolchain, cargo-binstall, cargo-auditable and cargo-nextest into the Tart image; - place saluki's compile jobs one VM per host, or use larger VMs. ## Expected outcome @@ -126,8 +130,8 @@ The effort lands as four stacked pull requests. Each one ticks its box and adds | PR 1 | ~15.5 min | ~19 min | | PR 2 | ~10.5 min | ~13.5 min | | PR 3 | ~10 min | ~12.5 min | -| PR 4 | ~6–6.5 min (p90 ~8) | ~6–7.5 min | -| Follow-ups | ~5.5–6 min (p90 ~7) | ~6–7 min | +| PR 4 | ~7–7.5 min (p90 ~9) | ~6–7.5 min | +| Follow-ups | ~6.5–7 min (p90 ~8) | ~6–7 min | ## Results diff --git a/lib/saluki-metadata/build.rs b/lib/saluki-metadata/build.rs index daa57ffd53f..117b387817e 100644 --- a/lib/saluki-metadata/build.rs +++ b/lib/saluki-metadata/build.rs @@ -1,76 +1,14 @@ fn main() { println!("cargo:rerun-if-changed=build.rs"); - println!("cargo:rerun-if-env-changed=APP_GIT_HASH"); - println!("cargo:rerun-if-env-changed=APP_BUILD_TIME"); - println!("cargo:rerun-if-env-changed=APP_DEV_BUILD"); println!("cargo:rerun-if-env-changed=TARGET"); - // This is really, really simple: we look for some specific environment variables and write the values to a file - // that will get imported by lib.rs. Ta-da. + // Cargo sets `TARGET` only for build scripts, so we pass it on to the crate. // - // Only build metadata lives here. Which application is being built isn't knowable from this crate -- one compiled - // copy is shared by every binary in the workspace -- so names and versions are declared by the binaries themselves - // and registered at startup. See `declare_app_details!`. - let app_git_hash = get_env_var_or_default("APP_GIT_HASH", "unknown"); - let app_build_time = get_env_var_or_default("APP_BUILD_TIME", "0000-00-00 00:00:00"); - let app_dev_build = get_env_var_bool_or_default("APP_DEV_BUILD", true); - let target_arch = get_env_var_or_default("TARGET", "unknown-arch"); - - // Release builds shouldn't silently ship the placeholder values above, so treat any that survive as a build - // failure. CI sets APP_DEV_BUILD at the workflow level, so on a tag pipeline it's also set for jobs that only test - // or lint; those run through the Makefile, which exports this metadata for every recipe, so they satisfy the check - // the same way a real build does. - if !app_dev_build { - let mut placeholders = Vec::new(); - - if app_git_hash == "unknown" || app_git_hash == "not-in-git" { - placeholders.push("APP_GIT_HASH"); - } - if app_build_time.starts_with("0000-00-00") { - placeholders.push("APP_BUILD_TIME"); - } - - if !placeholders.is_empty() { - panic!( - "APP_DEV_BUILD is 'false', marking this a release build, but the following build metadata environment \ - variables are unset or still hold their placeholder defaults: {}. Set them in whichever build entry \ - point is being used, or set APP_DEV_BUILD=true if this isn't actually a release build.", - placeholders.join(", ") - ); - } - } - - let details_file = std::env::var("OUT_DIR").unwrap() + "/details.rs"; - std::fs::write( - details_file, - format!( - r#" - pub const DETECTED_GIT_HASH: &str = "{}"; - pub const DETECTED_APP_BUILD_TIME: &str = "{}"; - pub const DETECTED_APP_DEV_BUILD: bool = {}; - pub const DETECTED_TARGET_ARCH: &str = "{}"; - "#, - app_git_hash, app_build_time, app_dev_build, target_arch, - ), - ) - .expect("failed to write details file"); -} - -/// Returns the value the given environment variable, or the default value if the environment variable is missing/empty. -fn get_env_var_or_default(var_name: &str, default: &str) -> String { - std::env::var(var_name) + // Don't read the `APP_*` variables here. Some change on each commit, and every crate that depends on this one would + // then rebuild. `declare_app_details!` reads them in the calling crate. + let target_arch = std::env::var("TARGET") .ok() .filter(|s| !s.is_empty()) - .unwrap_or(default.to_string()) -} - -/// Returns the value the given environment variable after parsing as a boolean, or the default value if the environment -/// variable is missing/empty, or if it's not a valid boolean. -fn get_env_var_bool_or_default(var_name: &str, default: bool) -> bool { - let value = get_env_var_or_default(var_name, "").to_ascii_lowercase(); - match value.as_str() { - "true" => true, - "false" => false, - _ => default, - } + .unwrap_or_else(|| "unknown-arch".to_string()); + println!("cargo:rustc-env=SALUKI_METADATA_TARGET_ARCH={target_arch}"); } diff --git a/lib/saluki-metadata/src/lib.rs b/lib/saluki-metadata/src/lib.rs index 825023434ac..a34a0fae773 100644 --- a/lib/saluki-metadata/src/lib.rs +++ b/lib/saluki-metadata/src/lib.rs @@ -2,10 +2,9 @@ use std::sync::OnceLock; use serde::{Serialize, Serializer}; -#[allow(dead_code)] -mod details { - include!(concat!(env!("OUT_DIR"), "/details.rs")); -} +const UNKNOWN_GIT_HASH: &str = "unknown"; +const UNKNOWN_BUILD_TIME: &str = "0000-00-00 00:00:00"; +const TARGET_ARCH: &str = env!("SALUKI_METADATA_TARGET_ARCH"); static APP_DETAILS: OnceLock = OnceLock::new(); @@ -19,7 +18,8 @@ static UNREGISTERED_APP_DETAILS: AppDetails = /// fall under the general umbrella of "build metadata." /// /// If the application hasn't registered its details through [`set_app_details`], the name and version fields report -/// `"unknown"` and `0.0.0` respectively. Build metadata is always populated, since it's captured at compile time. +/// `"unknown"` and `0.0.0` respectively. The build metadata reports the defaults that [`AppDetails`] lists, except the +/// target architecture, which this crate always knows. pub fn get_app_details() -> &'static AppDetails { APP_DETAILS.get().unwrap_or(&UNREGISTERED_APP_DETAILS) } @@ -41,9 +41,13 @@ pub fn set_app_details(details: AppDetails) { /// Declares the details for the application being compiled. /// -/// The caller supplies the three names that identify the application. Everything else is filled in automatically: the -/// version comes from the calling crate's Cargo manifest, and the build metadata from `saluki-metadata`'s own build -/// script. +/// The caller supplies the three names that identify the application, as constant expressions. The macro fills in the +/// rest in the calling crate: the version from its Cargo manifest, and the build metadata from the environment +/// variables that [`AppDetails`] lists. When one of these variables changes, Cargo rebuilds only the calling crate. +/// +/// When `APP_DEV_BUILD` is `false`, the calling crate fails to compile if `APP_GIT_HASH` or `APP_BUILD_TIME` is unset or +/// holds a placeholder. This keeps a release binary from shipping placeholder metadata. The check also fails `cargo +/// check`. /// /// # Examples /// @@ -59,8 +63,9 @@ pub fn set_app_details(details: AppDetails) { /// #[macro_export] macro_rules! declare_app_details { - (full_name = $full_name:expr, short_name = $short_name:expr, identifier = $identifier:expr $(,)?) => { - $crate::AppDetails::new( + (full_name = $full_name:expr, short_name = $short_name:expr, identifier = $identifier:expr $(,)?) => {{ + // `cargo check` evaluates a `const` item, but not an inline `const` block in a function body. + const __DECLARED_APP_DETAILS: $crate::AppDetails = $crate::AppDetails::new( $full_name, $short_name, $identifier, @@ -71,6 +76,27 @@ macro_rules! declare_app_details { $crate::const_parse_u32(env!("CARGO_PKG_VERSION_PATCH")), ), ) + .with_build_metadata( + option_env!("APP_GIT_HASH"), + option_env!("APP_BUILD_TIME"), + option_env!("APP_DEV_BUILD"), + ); + __DECLARED_APP_DETAILS + }}; +} + +/// Panics with a message that names the build metadata variables that hold placeholders. +/// +/// A `const` panic can't join strings, so each set of names gets its own message. +macro_rules! release_build_placeholder_panic { + ($names:literal) => { + panic!(concat!( + "APP_DEV_BUILD is 'false', marking this a release build, but the following build metadata environment \ + variables are unset or still hold their placeholder defaults: ", + $names, + ". Set them in whichever build entry point is being used, or set APP_DEV_BUILD=true if this isn't actually \ + a release build." + )) }; } @@ -86,6 +112,13 @@ pub const fn const_parse_u32(s: &str) -> u32 { } } +const fn non_empty_or(value: Option<&'static str>, default: &'static str) -> &'static str { + match value { + Some(value) if !value.is_empty() => value, + _ => default, + } +} + /// Application details. /// /// # Configuration @@ -94,16 +127,18 @@ pub const fn const_parse_u32(s: &str) -> u32 { /// [`declare_app_details!`] and registered with [`set_app_details`]. The version comes from that binary's Cargo /// manifest. /// -/// The remaining fields describe the build rather than the application, so they're captured at compile time from the -/// following environment variables: +/// The remaining fields describe the build rather than the application. [`declare_app_details!`] captures them when +/// the calling crate compiles, from the following environment variables: /// /// - `APP_GIT_HASH`: Git hash of the application. If this isn't set, the default value is `"unknown"`. /// - `APP_BUILD_TIME`: Build time of the application. If this isn't set, the default value is `"0000-00-00 00:00:00"`. /// - `APP_DEV_BUILD`: Whether the application is a development build. If this isn't set, the default value is `true`. -/// - `TARGET`: Target architecture of the application. If this isn't set, the default value is `"unknown-arch"`. /// -/// Environment variables prefixed with `APP_` are expected to be set by the build script/tooling, while others are -/// provided automatically by Cargo. +/// The build tooling sets these variables. An empty value counts as unset. Details from [`AppDetails::new`] and the +/// details of an unregistered application report the default values. +/// +/// The target architecture comes from the `TARGET` environment variable that Cargo gives to the build script of this +/// crate. If this isn't set, the default value is `"unknown-arch"`. #[derive(Serialize)] pub struct AppDetails { full_name: &'static str, @@ -119,8 +154,8 @@ pub struct AppDetails { impl AppDetails { /// Creates a new `AppDetails` from the given application identity. /// - /// Build metadata is filled in from the values captured at compile time, so callers can't get it wrong. Prefer - /// [`declare_app_details!`], which also derives the version from the calling crate's Cargo manifest. + /// The Git hash, the build time, and the development build flag report their default values. Prefer + /// [`declare_app_details!`], which captures them, and the version, in the calling crate. pub const fn new( full_name: &'static str, short_name: &'static str, identifier: &'static str, version: Version, ) -> Self { @@ -129,10 +164,49 @@ impl AppDetails { short_name, identifier, version, - git_hash: details::DETECTED_GIT_HASH, - build_time: details::DETECTED_APP_BUILD_TIME, - dev_build: details::DETECTED_APP_DEV_BUILD, - target_arch: details::DETECTED_TARGET_ARCH, + git_hash: UNKNOWN_GIT_HASH, + build_time: UNKNOWN_BUILD_TIME, + dev_build: true, + target_arch: TARGET_ARCH, + } + } + + /// Sets the build metadata from the raw values of the `APP_*` build environment variables. + /// + /// [`declare_app_details!`] calls this with `option_env!` values from the calling crate. A value that is `None` or + /// empty gives the default value. Only `"false"`, in any letter case, marks a release build. + /// + /// # Panics + /// + /// Panics if `dev_build` marks a release build and the Git hash or the build time holds a placeholder. In a `const` + /// item, the panic fails the build. + #[doc(hidden)] + pub const fn with_build_metadata( + self, git_hash: Option<&'static str>, build_time: Option<&'static str>, dev_build: Option<&'static str>, + ) -> Self { + let git_hash = non_empty_or(git_hash, UNKNOWN_GIT_HASH); + let build_time = non_empty_or(build_time, UNKNOWN_BUILD_TIME); + let dev_build = match dev_build { + Some(value) => !value.as_bytes().eq_ignore_ascii_case(b"false"), + None => true, + }; + + if !dev_build { + let placeholder_git_hash = matches!(git_hash.as_bytes(), b"unknown" | b"not-in-git"); + let placeholder_build_time = matches!(build_time.as_bytes().first_chunk::<10>(), Some(b"0000-00-00")); + match (placeholder_git_hash, placeholder_build_time) { + (true, true) => release_build_placeholder_panic!("APP_GIT_HASH, APP_BUILD_TIME"), + (true, false) => release_build_placeholder_panic!("APP_GIT_HASH"), + (false, true) => release_build_placeholder_panic!("APP_BUILD_TIME"), + (false, false) => {} + } + } + + Self { + git_hash, + build_time, + dev_build, + ..self } } @@ -166,7 +240,8 @@ impl AppDetails { /// Returns the Git hash used to build the application. /// - /// If the Git hash couldn't be detected, this will return `"unknown"`. + /// Returns `"unknown"` if `APP_GIT_HASH` was unset at build time, or if the details don't come from + /// [`declare_app_details!`]. pub fn git_hash(&self) -> &'static str { self.git_hash } @@ -180,7 +255,8 @@ impl AppDetails { /// Returns the build time of the application. /// - /// If the build time couldn't be detected, this will return `"0000-00-00 00:00:00"`. + /// Returns `"0000-00-00 00:00:00"` if `APP_BUILD_TIME` was unset at build time, or if the details don't come from + /// [`declare_app_details!`]. pub fn build_time(&self) -> &'static str { self.build_time } @@ -190,7 +266,8 @@ impl AppDetails { /// Development builds generally encompass all local builds, and any CI builds which aren't related to versioned /// artifacts intended for public release. /// - /// If the development build flag couldn't be detected, this will return `true`. + /// Returns `false` only if the details come from [`declare_app_details!`] and `APP_DEV_BUILD` was `false` at build + /// time. pub fn is_dev_build(&self) -> bool { self.dev_build } @@ -265,3 +342,74 @@ impl Serialize for Version { serializer.serialize_str(self.raw) } } + +#[cfg(test)] +mod tests { + use super::*; + + const REAL_GIT_HASH: Option<&str> = Some("abc1234"); + const REAL_BUILD_TIME: Option<&str> = Some("2026-12-01T00:00:00Z"); + + fn details() -> AppDetails { + AppDetails::new("Test Application", "test", "ta", Version::new("1.2.3", 1, 2, 3)) + } + + #[test] + fn new_reports_default_build_metadata() { + let details = details(); + assert_eq!(details.git_hash(), "unknown"); + assert_eq!(details.build_time(), "0000-00-00 00:00:00"); + assert!(details.is_dev_build()); + assert_eq!(details.target_arch(), env!("SALUKI_METADATA_TARGET_ARCH")); + } + + #[test] + fn unset_or_empty_build_metadata_gives_defaults() { + for value in [None, Some("")] { + let details = details().with_build_metadata(value, value, value); + assert_eq!(details.git_hash(), "unknown"); + assert_eq!(details.build_time(), "0000-00-00 00:00:00"); + assert!(details.is_dev_build()); + } + } + + #[test] + fn build_metadata_comes_from_the_given_values() { + let details = details().with_build_metadata(REAL_GIT_HASH, REAL_BUILD_TIME, Some("true")); + assert_eq!(details.git_hash(), "abc1234"); + assert_eq!(details.build_time(), "2026-12-01T00:00:00Z"); + assert!(details.is_dev_build()); + } + + #[test] + fn only_false_marks_a_release_build() { + for (value, dev_build) in [ + ("false", false), + ("FALSE", false), + ("False", false), + ("true", true), + ("0", true), + ] { + let details = details().with_build_metadata(REAL_GIT_HASH, REAL_BUILD_TIME, Some(value)); + assert_eq!(details.is_dev_build(), dev_build, "APP_DEV_BUILD={value}"); + } + } + + #[test] + #[should_panic(expected = "placeholder defaults: APP_GIT_HASH, APP_BUILD_TIME.")] + fn release_build_rejects_unset_metadata() { + details().with_build_metadata(None, None, Some("false")); + } + + #[test] + #[should_panic(expected = "placeholder defaults: APP_GIT_HASH.")] + fn release_build_rejects_a_git_hash_from_outside_git() { + details().with_build_metadata(Some("not-in-git"), REAL_BUILD_TIME, Some("false")); + } + + #[test] + #[should_panic(expected = "placeholder defaults: APP_BUILD_TIME.")] + fn release_build_rejects_the_makefile_build_time_placeholder() { + details().with_build_metadata(REAL_GIT_HASH, Some("0000-00-00T00:00:00-00:00"), Some("false")); + } +}