diff --git a/.github/workflows/docs-validation.yml b/.github/workflows/docs-validation.yml new file mode 100644 index 00000000000..ef0950ad778 --- /dev/null +++ b/.github/workflows/docs-validation.yml @@ -0,0 +1,100 @@ +name: "Docs: Validate Documentation" + +on: + pull_request: + paths: + - '**.md' + - 'test/docs/**' + - '.github/workflows/docs-validation.yml' + - '.markdownlint.json' + push: + branches: + - main + paths: + - '**.md' + - 'test/docs/**' + +permissions: + contents: read + +jobs: + markdown-lint: + name: Markdown Linting + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + fetch-depth: 0 + + # Linting every .md in the repo is not viable: ~198 files carry pre-existing + # violations. Lint only in-scope files that this change actually touches, and + # widen SCOPE as more docs are brought up to standard. + - name: Collect changed Markdown files in scope + id: changed + env: + BASE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} + run: | + set -euo pipefail + + base="${BASE_SHA:-}" + if [[ -z "${base}" ]] || ! git cat-file -e "${base}^{commit}" 2>/dev/null; then + # First push to a branch, or a force push: fall back to the previous commit. + base="$(git rev-parse HEAD^ 2>/dev/null || git rev-parse HEAD)" + fi + + files="$(git diff --name-only --diff-filter=ACMR "${base}" HEAD -- \ + docs/personal-dev.md test/docs/ \ + | { grep -E '\.md$' || true; } \ + | tr '\n' ' ' | sed 's/ *$//')" + + # When only config/workflow files changed, lint the baseline scope + # so invalid config can still be caught. + if [[ -z "${files}" ]]; then + changed_configs="$(git diff --name-only --diff-filter=ACMR "${base}" HEAD -- \ + .markdownlint.json .github/workflows/docs-validation.yml \ + || true)" + if [[ -n "${changed_configs}" ]]; then + files="docs/personal-dev.md test/docs/README.md" + existing="" + for f in ${files}; do + if [[ -f "${f}" ]]; then + existing="${existing} ${f}" + fi + done + files="$(echo "${existing}" | sed 's/^ *//')" + echo "Config changed; linting baseline: ${files}" + else + echo "No in-scope Markdown changed; nothing to lint." + fi + else + echo "Linting: ${files}" + fi + + echo "files=${files}" >> "$GITHUB_OUTPUT" + + - name: Lint changed Markdown files + if: steps.changed.outputs.files != '' + uses: nosborn/github-action-markdown-cli@f5d8cad27b5690b173425c45f762f8662ecf47e8 # v3.3.0 + with: + files: ${{ steps.changed.outputs.files }} + config_file: .markdownlint.json + + readme-tests: + name: README Command Tests + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + + - name: Setup Go + uses: actions/setup-go@v6 + with: + go-version-file: go.work + + # dry-run asserts only on the docs, so no az/kubectl install is needed. + - name: Run personal-dev README tests + run: | + bash test/docs/personal-dev-readme-test.sh + env: + TEST_MODE: dry-run diff --git a/.markdownlint.json b/.markdownlint.json new file mode 100644 index 00000000000..dd8c9151abd --- /dev/null +++ b/.markdownlint.json @@ -0,0 +1,18 @@ +{ + "default": true, + "MD013": { + "line_length": 120, + "code_blocks": false, + "tables": false + }, + "MD033": false, + "MD041": false, + "MD028": false, + "MD060": false, + "MD024": { + "siblings_only": true + }, + "MD046": { + "style": "fenced" + } +} diff --git a/Makefile b/Makefile index 97a7edfff7c..677537aef08 100644 --- a/Makefile +++ b/Makefile @@ -739,6 +739,12 @@ image-updater: # Component updater (shared version bumper; Istio wired today — tooling/component-updater/README.md) COMPONENT ?= +# Documentation tests +test-docs: + @echo "Running documentation tests..." + @bash ./test/docs/personal-dev-readme-test.sh +.PHONY: test-docs + SUBSCRIPTION_ID ?= component-updater-check: @$(MAKE) -C tooling/component-updater check COMPONENT="$(COMPONENT)" SUBSCRIPTION_ID="$(SUBSCRIPTION_ID)" diff --git a/docs/personal-dev.md b/docs/personal-dev.md index f5f1de576a0..02086453d3a 100644 --- a/docs/personal-dev.md +++ b/docs/personal-dev.md @@ -1,10 +1,14 @@ # ARO HCP Personal DEV Environment -A personal DEV environment is a fully-fledged ARO HCP service stack that provides all major infrastructure and service components required to create hosted control planes in a region. Each ARO HCP team member creates their own personal DEV environment for development purposes. +A personal DEV environment is a fully-fledged ARO HCP service stack that provides all major infrastructure and service +components required to create hosted control planes in a region. Each ARO HCP team member creates their own personal DEV +environment for development purposes. -These environments are hosted in the Red Hat Azure tenant, meaning that all [restrictions](environments.md#azure-tenants) of that tenant apply. +These environments are hosted in the Red Hat Azure tenant, meaning that all +[restrictions](environments.md#azure-tenants) of that tenant apply. -This document will describe how to create and manage a personal DEV environment and how to access them for development purposes. +This document will describe how to create and manage a personal DEV environment and how to access them for development +purposes. ## Prerequisites @@ -12,8 +16,11 @@ Creating a personal DEV environment requires several prerequisites being met. Ensure you have access to the RH Azure tenant: -- **RH account**: You need to have a Red Hat account to access the Red Hat Azure tenant (`redhat0.onmicrosoft.com`) where personal DEV environments are created -- **Subscription access**: You need access to the `ARO Hosted Control Planes (EA Subscription 1)` subscription in the Red Hat Azure tenant. Consult the [ARO HCP onboarding guide](https://docs.google.com/document/d/1KUZSLknIkSd6usFPe_OcEYWJyW6mFeotc2lIsLgE3JA/) +- **RH account**: You need to have a Red Hat account to access the Red Hat Azure tenant (`redhat0.onmicrosoft.com`) + where personal DEV environments are created +- **Subscription access**: You need access to the `ARO Hosted Control Planes (EA Subscription 1)` subscription in the + Red Hat Azure tenant. Consult the [ARO HCP onboarding + guide](https://docs.google.com/document/d/1KUZSLknIkSd6usFPe_OcEYWJyW6mFeotc2lIsLgE3JA/) - `az` utility >= `2.68.0` - `az bicep` at the latest version, use `az bicep install` to add this to your system - `az login` with your Red Hat account: @@ -30,22 +37,33 @@ az account set --subscription 1d3378d3-5a3f-4712-85a1-2485495dfc4b The following additional tools are also required: -- GNU Make 4.x or newer - macOS's bundled GNU Make 3.81 fails with "multiple target patterns" at `test/Makefile:77`. Install with `brew install make` and use `gmake`, or put `$(brew --prefix make)/libexec/gnubin` first on `PATH`. +- GNU Make 4.x or newer - macOS's bundled GNU Make 3.81 fails with "multiple target patterns" at + `test/Makefile:77`. Install with `brew install make` and use `gmake`, or put + `$(brew --prefix make)/libexec/gnubin` first on `PATH`. - `kubectl` at the latest version - use `az aks install-cli` to add this to your system -- Standalone `bicep` at the version pinned in [`dev-infrastructure/openshift-ci/versions.mk`](../dev-infrastructure/openshift-ci/versions.mk). Install the matching binary from the [Bicep releases](https://github.com/Azure/bicep/releases) on `PATH`, or pass `BICEP=/path/to/bicep` to Make. Infrastructure `fmt` and `lint` use this binary directly without Azure CLI authentication; `NPROC` controls their parallelism. +- Standalone `bicep` at the version pinned in + [`dev-infrastructure/openshift-ci/versions.mk`](../dev-infrastructure/openshift-ci/versions.mk). Install the + matching binary from the [Bicep releases](https://github.com/Azure/bicep/releases) on `PATH`, or pass + `BICEP=/path/to/bicep` to Make. Infrastructure `fmt` and `lint` use this binary directly without Azure CLI + authentication; `NPROC` controls their parallelism. -All other tools should be transparently installed by the `make` targets that require them - if you find any missing dependencies, please send a pull request to make sure that the next person to onboard doesn't hit any issues! +All other tools should be transparently installed by the `make` targets that require them - if you find any missing +dependencies, please send a pull request to make sure that the next person to onboard doesn't hit any issues! ## Full Personal DEV Environment Setup > [!IMPORTANT] Environment Cleanup -> A word of caution upfront: dev infrastructure is automatically deleted after 48h. Setting `PERSIST=true` extends retention to 15 days instead of permanent. +> A word of caution upfront: dev infrastructure is automatically deleted after 48h. Setting `PERSIST=true` extends +> retention to 15 days instead of permanent. > Please consider the implication on cost if you decide to persist your infrastructure. > [!CAUTION] Cleanup-sensitive naming patterns -> The following resource group naming patterns trigger special cleanup rules. Avoid them for custom `DEPLOY_ENV` values or ad-hoc resource groups. See [`resourcegroups.policy.yaml`](../tooling/cleanup-sweeper/resourcegroups.policy.yaml) for details. +> The following resource group naming patterns trigger special cleanup rules. Avoid them for custom `DEPLOY_ENV` values +> or ad-hoc resource groups. See [`resourcegroups.policy.yaml`](../tooling/cleanup-sweeper/resourcegroups.policy.yaml) +> for details. > -> **Prefixes:** `hcp-underlay-pers-`, `hcp-underlay-prow-`, `hcp-underlay-ci`, `hcp-underlay-dev-`, `hcp-underlay-perf-`, `hcp-underlay-int-`, `hcp-underlay-stg-`, `hcp-underlay-prod-` +> **Prefixes:** `hcp-underlay-pers-`, `hcp-underlay-prow-`, `hcp-underlay-ci`, `hcp-underlay-cspr-`, +> `hcp-underlay-dev-`, `hcp-underlay-perf-`, `hcp-underlay-int-`, `hcp-underlay-stg-`, `hcp-underlay-prod-` > > **Suffixes:** `-shared-resources` @@ -55,70 +73,218 @@ The creation process can take up to 20 minutes. make personal-dev-env ``` -This command creates a personal DEV environment with a unique name that is derived from your username. It builds and pushes all in-repo service images (frontend, backend, admin, sessiongate) from your local checkout and deploys them along with all required infrastructure components. +This command creates a personal DEV environment with a unique name that is derived from your username. It builds and +pushes all in-repo service images (frontend, backend, admin, sessiongate) from your local checkout and deploys them +along with all required infrastructure components. -> [!NOTE] Update Personal DEV Environment -> This command can be used to update your personal DEV environment as well. It will apply the latest changes to the infrastructure and services. Steps are cached, so it's quick and safe to re-run the entire environment setup. -> If you only want to update individual aspects of the environment, follow the [partial setup](#partial-personal-dev-environment-setup) instructions. +> [!NOTE] Update Personal DEV Environment +> This command can be used to update your personal DEV environment as well. It will apply the latest changes to the +> infrastructure and services. Steps are cached, so it's quick and safe to re-run the entire environment setup. +> If you only want to update individual aspects of the environment, follow the [partial +> setup](#partial-personal-dev-environment-setup) instructions. > [!TIP] Make Options -> [Make Options](./make-options.md) describes how to customize the make build e.g. by defining the container engine to be used or limiting parallel jobs. This can be of help when experiencing problems with the build. +> [Make Options](./make-options.md) describes how to customize the make build e.g. by defining the container engine to +> be used or limiting parallel jobs. This can be of help when experiencing problems with the build. ### Service Cluster Node Pools -New personal DEV service clusters run all workloads on one autoscaling system pool of three to five `Standard_D4ds_v5` nodes (`svc.aks.systemPoolOnly`), as the CI service clusters do. See [Service Cluster Consolidation](ci/system-pool-only.md) for the placement details. The management cluster is unchanged. +New personal DEV service clusters run all workloads on one autoscaling system pool of three to five +`Standard_D4ds_v5` nodes (`svc.aks.systemPoolOnly`), as the CI service clusters do. See +[Service Cluster Consolidation](ci/system-pool-only.md) for the placement details. The management cluster is unchanged. > [!IMPORTANT] -> A personal environment created before this change cannot be redeployed. Its system pool was created as `Standard_D2s_v3` with a 32 GB OS disk, and AKS does not allow either property to change on an existing pool, so the service-cluster deployment fails with `PropertyChangeNotAllowed`. Delete and recreate the environment to pick up this topology — personal environments are meant to be short-lived. If you need to keep an existing one running, set `svc.aks.systemPoolOnly` to `false` and remove the `systemAgentPool` override in the `pers` section of your local `config/config.yaml`. +> A personal environment created before this change cannot be redeployed. Its system pool was created as +> `Standard_D2s_v3` with a 32 GB OS disk, and AKS does not allow either property to change on an existing pool, so the +> service-cluster deployment fails with `PropertyChangeNotAllowed`. Delete and recreate the environment to pick up this +> topology — personal environments are meant to be short-lived. If you need to keep an existing one running, set +> `svc.aks.systemPoolOnly` to `false` and remove the `systemAgentPool` override in the `pers` section of your local +> `config/config.yaml`. -Note also that redeploying would not consolidate such a cluster even if the system pool were compatible: ARM does not delete the user and infra pools once the Bicep stops emitting them. +Note also that redeploying would not consolidate such a cluster even if the system pool were compatible: ARM does not +delete the user and infra pools once the Bicep stops emitting them. ### Local Cluster Service Development Setup -If you plan to run the Cluster Service locally (not deployed to Kubernetes) for development, use the following command instead: +If you plan to run the Cluster Service locally (not deployed to Kubernetes) for development, use the following command +instead: ```bash make local-pers-dev-env ``` This command performs all the steps of `personal-dev-env` plus: + - Grants your user permissions to access Key Vaults (service and management) - Grants your user permissions to access OIDC storage -- Generates the local configuration files for cluster service: provision-shards, ocp-versions, azure-runtime, azure-operators-mi +- Generates the local configuration files for cluster service: provision-shards, ocp-versions, azure-runtime, + azure-operators-mi -After this, the config files are created in `cluster-service/local/`. This contains the configuration needed to run the Cluster Service locally against your personal dev environment. +After this, the config files are created in `cluster-service/local/`. This contains the configuration needed to run the +Cluster Service locally against your personal dev environment. ## Partial Personal DEV Environment Setup -The process described in the previous section caches steps, but even the process of determining that a step should not run again will take a second or two. In case you want to install or update only a specific part of the environment for maximum speed, you can use the following commands. +The process described in the previous section caches steps, but even the process of determining that a step should not +run again will take a second or two. In case you want to install or update only a specific part of the environment for +maximum speed, you can use the following commands. > [!IMPORTANT] -> Please understand the ARO HCP [architecture](high-level-architecture.md) and the [service deployment concept](service-deployment-concept.md) before proceeding with the partial setup. Not every command can be run in isolation without it's prerequisites being met, e.g. before deploying services, you need to provision the cluster +> Please understand the ARO HCP [architecture](high-level-architecture.md) and the [service deployment +> concept](service-deployment-concept.md) before proceeding with the partial setup. Not every command can be run in +> isolation without it's prerequisites being met, e.g. before deploying services, you need to provision the cluster ### Partial Commands -The `make entrypoint/` and `make pipeline/` targets select entrypoints or pipelines from the [`topology.yaml`](./pipeline-topology.md) to run. Use tab completion in your editor to find the available options. +The `make entrypoint/` and `make pipeline/` targets select entrypoints or pipelines from the +[`topology.yaml`](./pipeline-topology.md) to run. Use tab completion in your editor to find the available options. + +## Troubleshooting a failed or slow setup + +Setup is long-running and talks to a lot of Azure APIs, so partial failures and timeouts are normal rather than +exceptional. Work through these in order. + +### First: just re-run it + +```bash +make personal-dev-env +``` + +Steps are cached in `.step-cache` (gitignored), keyed by a hash of each step's inputs. A re-run skips everything that +already succeeded with unchanged inputs and picks up where it stopped, so a transient Azure error or a timeout usually +costs only the failed step. This is the right first response to almost any failure. + +### Find out what actually failed + +The run writes three artifacts, all gitignored: + +| Path | What it tells you | +|---|---| +| `_artifacts/junit_entrypoint.xml` | Per-step pass/fail — the quickest way to see *which* step broke | +| `timing/steps.yaml` | How long every step took — use this when the run is slow rather than broken | +| `_artifacts/config.yaml` | The fully rendered config the run actually used, after all templating and overrides | + +Turn `timing/steps.yaml` into something readable: + +```bash +make visualize +``` + +To see the dependency graph — what runs, in what order, and what a failed step blocks: + +```bash +make graph/entrypoint/Region # writes .graph.dot and .graph.html +``` + +### Turn up the logs + +`LOG_LEVEL` defaults to `3` and maps to templatize's `--verbosity`. Raise it when a step fails without a useful message: + +```bash +make personal-dev-env LOG_LEVEL=7 +``` + +### When it times out + +Two different timeouts are worth separating. + +A step that fails while *waiting for an earlier deployment of the same pipeline to finish* is hitting +`--deployment-timeout-seconds`, which defaults to 180: + +```bash +make personal-dev-env EXTRA_ARGS="--deployment-timeout-seconds=600" +``` + +A run that fails under Azure API throttling, or is hard to read because many steps interleave, benefits from running +serially. Concurrency is unbounded by default: + +```bash +make personal-dev-env EXTRA_ARGS="--concurrency=1" +``` + +Both `LOG_LEVEL` and `EXTRA_ARGS` propagate down to the underlying `entrypoint/Region` run, so they work on +`make personal-dev-env`, `make entrypoint/` and `make pipeline/` alike. + +If the failure is in the image build rather than the deployment, limit build parallelism instead — see +[Make Options](./make-options.md): + +```bash +make personal-dev-env BUILD_SERVICES_OPTS="-j1" +``` + +### Re-run only the broken part + +Once you know which service group failed, re-run that alone instead of the whole region: + +```bash +make pipeline/RP.Frontend +make entrypoint/Region # everything, still cached +``` + +### Force a clean re-run + +If you suspect the cache is masking the real problem — for example a step that "succeeds" from cache but left behind +broken state — bypass or discard it: + +```bash +make personal-dev-env STEP_CACHE_DIR="" # ignore the cache for this run +rm -rf .step-cache # discard it permanently +``` + +### Check the inputs before a long run + +Catch a malformed pipeline or config before spending 20 minutes finding out: + +```bash +make validate-config-pipelines +``` + +If a step fails because a tool is missing or out of date: + +```bash +make install-tools +``` + +### Start over + +Preview what a teardown would remove without touching anything (`CLEANUP_DRY_RUN` defaults to `true`): + +```bash +make cleanup-entrypoint/Region +``` + +Then delete for real with the command in [Cleanup](#cleanup). Note that a non-dry-run cleanup also deletes +`.step-cache`, so the next `make personal-dev-env` is a full, uncached rebuild. ## Accessing the environment -Once the environment has been provisioned, you can inspect it in the Azure Portal. Look out for the following Resourcegroups: +Once the environment has been provisioned, you can inspect it in the Azure Portal. Look out for the following +Resourcegroups: - **hcp-underlay-$(regionShort)$(usernameShortPrefix)**: holds the regional resources like Eventgrid, DNS zones, ... -- **hcp-underlay-$(regionShort)$(usernameShortPrefix)-svc**: holds the service cluster and supporting infra for its components -- **hcp-underlay-$(regionShort)$(usernameShortPrefix)-mgmt-1**: holds the management cluster and supporting infra for its components +- **hcp-underlay-$(regionShort)$(usernameShortPrefix)-svc**: holds the service cluster and supporting infra for its + components +- **hcp-underlay-$(regionShort)$(usernameShortPrefix)-mgmt-1**: holds the management cluster and supporting infra for + its components -The `-svc` and `-mgmt-1` resource groups contain the service and management AKS clusters respectively. Access to these clusters has been granted as part of the provisioning process and you can find respective kubeconfigs in `~/.kube/` as files that are named after their Resourcegroups. You can also use the following helpers to setup the `KUBECONFIG` environment variable: +The `-svc` and `-mgmt-1` resource groups contain the service and management AKS clusters respectively. Access to these +clusters has been granted as part of the provisioning process and you can find respective kubeconfigs in `~/.kube/` as +files that are named after their Resourcegroups. You can also use the following helpers to setup the `KUBECONFIG` +environment variable: ```bash export KUBECONFIG=$(make infra.svc.aks.kubeconfigfile) export KUBECONFIG=$(make infra.mgmt.aks.kubeconfigfile) ``` -The cluster in personal DEV have no reachable ingress. To interact with the services you deploy use `kubectl port-forward` +The cluster in personal DEV have no reachable ingress. To interact with the services you deploy use `kubectl +port-forward` ```bash kubectl port-forward svc/aro-hcp-frontend 8443:8443 -n aro-hcp kubectl port-forward svc/clusters-service 8000:8000 -n clusters-service + kubectl port-forward svc/maestro 8001:8000 -n maestro + kubectl port-forward svc/maestro-grpc 8090 -n maestro ``` To access the CS Azure Postgres DB run @@ -141,7 +307,8 @@ By default, metrics from infra/management services are ingested into Azure Manag ## Cleanup -Besides the automated cleanup for non-persistent environments, you can manually delete your personal DEV environment with the following command, choosing to wait for the deletion to complete or not: +Besides the automated cleanup for non-persistent environments, you can manually delete your personal DEV environment +with the following command, choosing to wait for the deletion to complete or not: ```bash make cleanup-entrypoint/Region CLEANUP_DRY_RUN=false CLEANUP_WAIT=true @@ -149,10 +316,14 @@ Besides the automated cleanup for non-persistent environments, you can manually ## Responsibilities -- **Lifecycle**: The personal DEV environments lifecycle is the responsibility of the individual team member. This includes creating, updating, and deleting the environment as well as keeping track of recent change and bugfixes and applying them. +- **Lifecycle**: The personal DEV environments lifecycle is the responsibility of the individual team member. This + includes creating, updating, and deleting the environment as well as keeping track of recent change and bugfixes and + applying them. > [!TIP] > Delete personal DEV environments when they are no longer needed to free up resources and prevent unnecessary costs. > If you require only a temporary personal DEV environment, don't mark it with `PERSIST=true`. -- **Security**: Your AKS clusters will have access to the shared Service Key Vault which contains certificates and credentials for identities that can act in the Red Hat ARO HCP subscription. Keep this in mind when working with your infrastructure. +- **Security**: Your AKS clusters will have access to the shared Service Key Vault which contains certificates and + credentials for identities that can act in the Red Hat ARO HCP subscription. Keep this in mind when working with your + infrastructure. diff --git a/test/docs/README.md b/test/docs/README.md new file mode 100644 index 00000000000..6d0f1f780b0 --- /dev/null +++ b/test/docs/README.md @@ -0,0 +1,157 @@ +# Documentation Tests + +This directory contains automated tests for validating README files and documentation. + +## Overview + +These tests ensure that: + +- Commands documented in READMEs are syntactically correct +- Required tools and prerequisites are properly documented +- Internal links point to existing files +- Make targets mentioned in docs actually exist +- Code examples use current API versions + +## Tests + +### personal-dev-readme-test.sh + +Validates the [personal-dev.md](../../docs/personal-dev.md) documentation. + +**What it tests:** + +- README file exists and has required sections +- Azure CLI prerequisites are documented (version >= 2.68.0) +- All documented make targets exist +- kubectl commands are valid +- PERSIST environment variable is documented +- Cleanup retention periods are correct (48h / 15 days) +- Resource group naming patterns are documented +- Azure tenant/subscription IDs are valid GUIDs +- Internal documentation links are not broken +- Required tools (az, kubectl) are available (`full` mode only) + +**Running locally:** + +```bash +./test/docs/personal-dev-readme-test.sh # dry-run (default) +make test-docs # same thing + +TEST_MODE=full ./test/docs/personal-dev-readme-test.sh +``` + +**Test modes:** + +- `dry-run` (default): docs assertions only. No tooling, no network, no Azure access. +- `full`: adds checks that `az` and `kubectl` are installed locally. + +An unrecognised `TEST_MODE` exits 2 rather than silently falling back. + +## CI Integration + +Tests run automatically on PRs that modify: + +- Any `*.md` files +- Test scripts in `test/docs/` +- CI workflow configurations + +See [.github/workflows/docs-validation.yml](../../.github/workflows/docs-validation.yml) + +## Adding New Tests + +To test a new README: + +1. Create a test script in `test/docs/` +2. Follow the pattern from `personal-dev-readme-test.sh` +3. Add to the CI workflow +4. Document in this README + +### Test Script Template + +```bash +#!/usr/bin/env bash +set -euo pipefail + +README_FILE="/path/to/readme.md" +TESTS_RUN=0 +TESTS_PASSED=0 +TESTS_FAILED=0 + +test_start() { + TESTS_RUN=$((TESTS_RUN + 1)) + echo "[TEST ${TESTS_RUN}] $1" +} + +test_pass() { + TESTS_PASSED=$((TESTS_PASSED + 1)) + echo "✓ PASS" +} + +test_fail() { + TESTS_FAILED=$((TESTS_FAILED + 1)) + echo "✗ FAIL: $1" +} + +# Your tests here +test_something() { + test_start "Test description" + if [[ condition ]]; then + test_pass + else + test_fail "Reason" + fi +} + +# Summary +echo "Tests: ${TESTS_RUN} | Passed: ${TESTS_PASSED} | Failed: ${TESTS_FAILED}" +[[ ${TESTS_FAILED} -eq 0 ]] && exit 0 || exit 1 +``` + +## Markdown Linting + +Configuration lives in `.markdownlint.json`. + +CI lints only the files a change actually touches, and only within a scoped allowlist +(`docs/personal-dev.md` and `test/docs/`). Most of the repo predates this config and +carries violations, so linting `**/*.md` would fail on files unrelated to your change. +Widen the `SCOPE` list in the workflow as more docs are brought up to standard. + +**Run locally:** + +```bash +npx markdownlint-cli --config .markdownlint.json docs/personal-dev.md test/docs/ + +# Auto-fix what can be fixed mechanically +npx markdownlint-cli --config .markdownlint.json --fix docs/personal-dev.md test/docs/ +``` + +## Link Checking + +Offline. Targets with a URI scheme (`http:`, `https:`, `mailto:`, ...) and same-page +`#anchor` links are skipped, never fetched; everything else is resolved on disk, +relative to the directory holding the file under test. + +The trade-off is deliberate: dead external URLs are not caught, but the suite can +never fail because a third-party site is slow, rate-limiting, or behind a login. + +## Troubleshooting + +### Tests fail on macOS + +Some GNU tools work differently on macOS. The test scripts are designed to be portable, but if you encounter issues: + +```bash +brew install grep # GNU grep +brew install gnu-sed # GNU sed +``` + +### kubectl warnings during tests + +Expected when running without a kubeconfig. The tests check that the tool exists, +never that it can reach a cluster. + +### Make targets not found + +A real failure: the suite resolves the repo root from its own location, so the +working directory does not matter. A documented target no longer exists, or no +longer resolves under `make -n`. Fix the docs, or the `targets` list in the script. diff --git a/test/docs/personal-dev-readme-test.sh b/test/docs/personal-dev-readme-test.sh new file mode 100755 index 00000000000..f8e369097c6 --- /dev/null +++ b/test/docs/personal-dev-readme-test.sh @@ -0,0 +1,320 @@ +#!/usr/bin/env bash +# Copyright 2025 Microsoft Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Validates that docs/personal-dev.md stays in step with the repo. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)" +README_FILE="${REPO_ROOT}/docs/personal-dev.md" + +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +TESTS_RUN=0 +TESTS_PASSED=0 +TESTS_FAILED=0 + +# 'dry-run' checks the docs only, needs no tooling and no network. 'full' also +# asserts the documented tools are installed locally. +TEST_MODE="${TEST_MODE:-dry-run}" + +case "${TEST_MODE}" in + dry-run | full) ;; + *) + echo "Unknown TEST_MODE '${TEST_MODE}' (expected 'dry-run' or 'full')" >&2 + exit 2 + ;; +esac + +log_info() { + echo -e "${GREEN}[INFO]${NC} $*" +} + +log_warn() { + echo -e "${YELLOW}[WARN]${NC} $*" +} + +log_error() { + echo -e "${RED}[ERROR]${NC} $*" +} + +test_start() { + TESTS_RUN=$((TESTS_RUN + 1)) + log_info "Test ${TESTS_RUN}: $1" +} + +# Print the target of every markdown link, one per line. awk, not grep: a greedy +# grep keeps only the last link on a line, and non-greedy needs grep -P, which +# BSD grep on macOS lacks. +extract_link_targets() { + awk '{ + rest = $0 + while (match(rest, /\[[^]]*\]\([^)]*\)/)) { + link = substr(rest, RSTART, RLENGTH) + sub(/^\[[^]]*\]\(/, "", link) + sub(/\)$/, "", link) + print link + rest = substr(rest, RSTART + RLENGTH) + } + }' "$1" +} + +test_pass() { + TESTS_PASSED=$((TESTS_PASSED + 1)) + log_info "✓ PASS" +} + +test_fail() { + TESTS_FAILED=$((TESTS_FAILED + 1)) + log_error "✗ FAIL: $1" +} + +test_readme_exists() { + test_start "README file exists" + if [[ -f "${README_FILE}" ]]; then + test_pass + else + test_fail "README file not found at ${README_FILE}" + fi +} + +test_prerequisites_documented() { + test_start "Prerequisites section exists" + if grep -q "## Prerequisites" "${README_FILE}"; then + test_pass + else + test_fail "Prerequisites section not found" + fi +} + +test_az_version_documented() { + test_start "Azure CLI version requirement documented" + if grep -q "az.*utility.*>=.*2.68.0" "${README_FILE}"; then + test_pass + else + test_fail "Azure CLI version requirement not found or outdated" + fi +} + +test_make_targets_exist() { + test_start "Documented make targets exist" + + local targets=("personal-dev-env" "local-pers-dev-env" "infra.svc.aks.kubeconfigfile" + "infra.mgmt.aks.kubeconfigfile" "cleanup-entrypoint/Region" + "visualize" "graph/entrypoint/Region" "pipeline/RP.Frontend" + "entrypoint/Region" "validate-config-pipelines" "install-tools") + local all_exist=true + + cd "${REPO_ROOT}" + + for target in "${targets[@]}"; do + # Use --dry-run with -q where possible to avoid triggering binary builds + # that make -n would start (e.g. templatize rebuild for visualize). + if ! timeout 10 make -n "${target}" &>/dev/null; then + rc=$? + if [[ ${rc} -eq 124 ]]; then + # Timed out: target needs a rebuild. Fall back to checking that + # the Makefile actually defines the target or pattern. + if grep -qE "^${target%%/*}[ :]" Makefile 2>/dev/null || \ + grep -qE "^\.PHONY:.*${target%%/*}" Makefile 2>/dev/null || \ + grep -q "${target%%/*}" Makefile 2>/dev/null; then + log_warn " Make target '${target}' dry-run timed out; pattern exists, assuming OK" + else + log_error " Make target '${target}' not found (timed out and no Makefile pattern)" + all_exist=false + fi + else + log_error " Make target '${target}' not found or invalid (make -n failed)" + all_exist=false + fi + fi + done + + if ${all_exist}; then + test_pass + else + test_fail "Some documented make targets don't exist" + fi +} + +test_persist_documented() { + test_start "PERSIST environment variable documented" + if grep -q "PERSIST=true" "${README_FILE}"; then + test_pass + else + test_fail "PERSIST environment variable not documented" + fi +} + +test_cleanup_retention_documented() { + test_start "Cleanup retention periods documented" + if grep -q "48h" "${README_FILE}" && grep -q "15 days" "${README_FILE}"; then + test_pass + else + test_fail "Cleanup retention periods not correctly documented" + fi +} + +test_resource_group_patterns() { + test_start "Resource group naming patterns documented" + if grep -q "hcp-underlay-.*-svc" "${README_FILE}" && + grep -q "hcp-underlay-.*-mgmt" "${README_FILE}"; then + test_pass + else + test_fail "Resource group naming patterns not documented" + fi +} + +test_azure_ids_format() { + test_start "Azure IDs are valid GUIDs" + + local tenant_id + tenant_id=$(grep 'az login --tenant' "${README_FILE}" | grep -o '[A-Fa-f0-9]\{8\}-[A-Fa-f0-9]\{4\}-[A-Fa-f0-9]\{4\}-[A-Fa-f0-9]\{4\}-[A-Fa-f0-9]\{12\}' | head -1 || echo "") + local sub_id + sub_id=$(grep 'az account set --subscription' "${README_FILE}" | grep -o '[A-Fa-f0-9]\{8\}-[A-Fa-f0-9]\{4\}-[A-Fa-f0-9]\{4\}-[A-Fa-f0-9]\{4\}-[A-Fa-f0-9]\{12\}' | head -1 || echo "") + + if [[ "${tenant_id}" =~ ^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$ ]] && + [[ "${sub_id}" =~ ^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$ ]]; then + test_pass + else + test_fail "Azure tenant or subscription ID format invalid" + fi +} + +test_observability_section() { + test_start "Observability section exists" + if grep -q "## Observability" "${README_FILE}"; then + test_pass + else + test_fail "Observability section not found" + fi +} + +test_cleanup_command() { + test_start "Cleanup command is valid" + if grep -q "make cleanup-entrypoint/Region CLEANUP_DRY_RUN=false CLEANUP_WAIT=true" "${README_FILE}"; then + test_pass + else + test_fail "Cleanup command not found or incorrect" + fi +} + +# +# Offline: targets with a URI scheme are skipped, never fetched. +test_internal_links() { + test_start "Internal documentation links resolve on disk" + + local all_valid=true + local checked=0 + local skipped=0 + + local base_dir + base_dir="$(cd "$(dirname "${README_FILE}")" &>/dev/null && pwd)" + + while IFS= read -r target; do + # Drop any "#anchor" suffix; a bare "#anchor" link leaves an empty path. + local file_path="${target%%#*}" + + # Same-page anchor, or a link with a URI scheme we deliberately do not follow. + if [[ -z "${file_path}" ]] || [[ "${file_path}" =~ ^[a-zA-Z][a-zA-Z0-9+.-]*: ]]; then + skipped=$((skipped + 1)) + continue + fi + + checked=$((checked + 1)) + if [[ ! -e "${base_dir}/${file_path}" ]]; then + log_error " Broken link: ${file_path}" + all_valid=false + fi + done < <(extract_link_targets "${README_FILE}") + + if ${all_valid}; then + log_info " ${checked} local link(s) resolved, ${skipped} external/anchor link(s) skipped" + test_pass + else + test_fail "Some internal links are broken" + fi +} + +# TEST_MODE=full only. +test_az_cli_available() { + test_start "Azure CLI is installed" + if command -v az &>/dev/null; then + local version + version=$(az version --query '"azure-cli"' -o tsv 2>/dev/null || echo "unknown") + log_info " Found az CLI version: ${version}" + test_pass + else + test_fail "Azure CLI not installed" + fi +} + +test_kubectl_available() { + test_start "kubectl is installed" + if command -v kubectl &>/dev/null; then + local version + version=$(kubectl version --client -o yaml 2>/dev/null | awk '/gitVersion:/ { print $2; exit }' || true) + version="${version:-unknown}" + log_info " Found kubectl version: ${version}" + test_pass + else + test_fail "kubectl not installed" + fi +} + +main() { + log_info "Starting personal-dev.md README tests (mode: ${TEST_MODE})" + log_info "================================================" + + test_readme_exists + test_prerequisites_documented + test_az_version_documented + test_make_targets_exist + test_persist_documented + test_cleanup_retention_documented + test_resource_group_patterns + test_azure_ids_format + test_observability_section + test_cleanup_command + test_internal_links + + if [[ "${TEST_MODE}" == "full" ]]; then + test_az_cli_available + test_kubectl_available + else + log_info "Skipping tool-availability tests (set TEST_MODE=full to run them)" + fi + + echo "" + log_info "================================================" + log_info "Test Summary:" + log_info " Total: ${TESTS_RUN}" + log_info " Passed: ${TESTS_PASSED}" + log_info " Failed: ${TESTS_FAILED}" + + if [[ ${TESTS_FAILED} -eq 0 ]]; then + log_info "All tests passed! ✓" + exit 0 + else + log_error "Some tests failed" + exit 1 + fi +} + +main "$@"