From 8c03ae3b75e90b84e934beba89154b9c327b6069 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Wed, 25 Nov 2026 23:57:11 +1100 Subject: [PATCH] Prepare for GitHub migration --- .github/CODEOWNERS | 1 + .github/workflows/ci.yml | 57 ++++++++++ .github/workflows/release.yml | 18 ++++ .github/zizmor.yml | 7 ++ .gitignore | 1 + .goreleaser.yaml | 107 +++++++++++++++---- .woodpecker/release.yaml | 185 --------------------------------- AGENTS.md | 53 ++++++---- Makefile | 66 +++++------- README.md | 42 ++++++++ cmd/pblastreport/main.go | 3 + cmd/pburl/main.go | 3 + internal/puppet/config.go | 99 +++++++++++------- internal/puppet/puppet_test.go | 109 +++++++++++++------ main.go | 121 +++++---------------- main_test.go | 165 ++++++++--------------------- packaging/config.example.yaml | 7 ++ packaging/nfpm.yaml | 82 --------------- scripts/build-rpm.sh | 49 --------- scripts/completions.sh | 10 ++ scripts/sign.sh | 9 ++ 21 files changed, 511 insertions(+), 683 deletions(-) create mode 100644 .github/CODEOWNERS create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/release.yml create mode 100644 .github/zizmor.yml delete mode 100644 .woodpecker/release.yaml create mode 100644 README.md create mode 100644 packaging/config.example.yaml delete mode 100644 packaging/nfpm.yaml delete mode 100755 scripts/build-rpm.sh create mode 100755 scripts/completions.sh create mode 100755 scripts/sign.sh diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..711107c --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @IUCLabs/maintainers diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..df2022f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,57 @@ +name: ci + +on: + pull_request: + push: + branches: [main] + +permissions: {} + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + ci: + uses: IUCLabs/workflows/.github/workflows/pre-commit.yml@v0.1.1 + permissions: + contents: read + with: + go_version_file: go.mod + + actions: + uses: IUCLabs/workflows/.github/workflows/actions.yml@v0.1.1 + permissions: + contents: read + + go: + uses: IUCLabs/workflows/.github/workflows/go-ci.yml@v0.1.1 + permissions: + contents: read + pull-requests: read + + release-snapshot: + uses: IUCLabs/workflows/.github/workflows/release-goreleaser.yml@v0.1.1 + # the called job declares the release permissions; snapshot skips Vault, signing and publishing + permissions: + contents: write + id-token: write + packages: write + with: + image: false + snapshot: true + runs_on: ubuntu-latest + + goreleaser-check: + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7.3.0 + with: + distribution: goreleaser + version: v2.20.2 + args: check diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..ff2b102 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,18 @@ +name: release + +on: + push: + tags: ["v*"] + +permissions: {} + +jobs: + release: + uses: IUCLabs/workflows/.github/workflows/release-goreleaser.yml@v0.1.1 + permissions: + contents: write + id-token: write + packages: write + with: + image: false + vault_role: release-shared diff --git a/.github/zizmor.yml b/.github/zizmor.yml new file mode 100644 index 0000000..21475c9 --- /dev/null +++ b/.github/zizmor.yml @@ -0,0 +1,7 @@ +rules: + unpinned-uses: + config: + policies: + # shared workflows are pinned to their release tags + "IUCLabs/*": ref-pin + "*": hash-pin diff --git a/.gitignore b/.gitignore index 2ad83ab..910f7e3 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ /pburl-* /pblastreport-* dist/ +/completions/ diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 30179cb..e10a977 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -1,38 +1,99 @@ version: 2 - project_name: node-lookup before: hooks: - - go mod tidy - - go test ./... + - scripts/completions.sh +# Each tool has a linux/amd64 build (the only one packaged into the RPM) and an +# "-other" build for the remaining platforms. builds: - - env: - - CGO_ENABLED=0 - goos: - - linux - - darwin - goarch: - - amd64 - - arm64 + - &build + id: node-lookup + main: . binary: node-lookup + env: + - CGO_ENABLED=0 + mod_timestamp: "{{ .CommitTimestamp }}" + flags: + - -trimpath ldflags: - - -s -w -X main.version={{.Version}} + - -s -w -X main.version={{ .Tag }} + goos: [linux] + goarch: [amd64] + - &other + <<: *build + id: node-lookup-other + goos: [linux, darwin] + goarch: [amd64, arm64] + ignore: + - goos: linux + goarch: amd64 + - <<: *build + id: pburl + main: ./cmd/pburl + binary: pburl + - <<: *other + id: pburl-other + main: ./cmd/pburl + binary: pburl + - <<: *build + id: pblastreport + main: ./cmd/pblastreport + binary: pblastreport + - <<: *other + id: pblastreport-other + main: ./cmd/pblastreport + binary: pblastreport archives: - - formats: - - tar.gz - name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}" + - formats: [binary] + name_template: "{{ .Binary }}-{{ .Os }}-{{ .Arch }}" + +nfpms: + - package_name: node-lookup + ids: [node-lookup, pburl, pblastreport] + formats: [rpm] + file_name_template: "{{ .ConventionalFileName }}" + release: "1" + section: default + maintainer: Ben Vincent <12552114+neoloc@users.noreply.github.com> + homepage: https://github.com/IUCLabs/node-lookup + license: MIT + description: "CLI tools for PuppetDB: node-lookup (fact lookup/filtering) plus pburl and pblastreport (Puppetboard URLs and last-report times)" + bindir: /usr/bin + provides: [node-lookup] + contents: + - src: completions/bash/* + dst: /usr/share/bash-completion/completions/ + file_info: + mode: 0644 + - src: completions/zsh/* + dst: /usr/share/zsh/site-functions/ + file_info: + mode: 0644 + - src: completions/fish/* + dst: /usr/share/fish/vendor_completions.d/ + file_info: + mode: 0644 + - src: packaging/config.example.yaml + dst: /usr/share/doc/node-lookup/config.example.yaml + type: doc + file_info: + mode: 0644 checksum: - name_template: "checksums.txt" + name_template: "{{ .ProjectName }}_{{ .Version }}_SHA256SUMS" + algorithm: sha256 + +signs: + - artifacts: checksum + cmd: scripts/sign.sh + args: ["${artifact}", "${signature}"] + +release: + use_existing_draft: true + mode: keep-existing changelog: - sort: asc - filters: - exclude: - - "^docs:" - - "^test:" - - "^ci:" - - "^chore:" + disable: true diff --git a/.woodpecker/release.yaml b/.woodpecker/release.yaml deleted file mode 100644 index 20ea6a7..0000000 --- a/.woodpecker/release.yaml +++ /dev/null @@ -1,185 +0,0 @@ -when: - - event: tag - -steps: - - name: test - image: artifactapi.k8s.syd1.au.unkin.net/docker-internal/gobuilder:0.1.2-alma9 - environment: - GOCACHE_S3_BUCKET: gocache - GOCACHE_S3_REGION: us-east-1 - GOCACHE_S3_ENDPOINT_URL: https://s3.ceph.unkin.net - GOCACHE_S3_PATH_STYLE: "true" - GOCACHE_KEY_PREFIX: ci-node-lookup - GOCACHE_METRICS: "true" - GOCACHEPROG: go-cache-plugin --cache-dir=/tmp/gocache - AWS_ACCESS_KEY_ID: - from_secret: GOCACHE_AWS_ACCESS_KEY_ID - AWS_SECRET_ACCESS_KEY: - from_secret: GOCACHE_AWS_SECRET_ACCESS_KEY - commands: - - go test -race ./... - backend_options: - kubernetes: - serviceAccountName: default - resources: - requests: - memory: 512Mi - cpu: 1 - limits: - memory: 2Gi - cpu: 2 - - # Build all binaries into dist/ (consumed by the RPM step) plus the - # cross-platform binaries attached to the Gitea release. Each tool is a - # separate main package, so they are built individually per os/arch. - - name: build - image: artifactapi.k8s.syd1.au.unkin.net/docker-internal/gobuilder:0.1.2-alma9 - environment: - GOCACHE_S3_BUCKET: gocache - GOCACHE_S3_REGION: us-east-1 - GOCACHE_S3_ENDPOINT_URL: https://s3.ceph.unkin.net - GOCACHE_S3_PATH_STYLE: "true" - GOCACHE_KEY_PREFIX: ci-node-lookup - GOCACHE_METRICS: "true" - GOCACHEPROG: go-cache-plugin --cache-dir=/tmp/gocache - AWS_ACCESS_KEY_ID: - from_secret: GOCACHE_AWS_ACCESS_KEY_ID - AWS_SECRET_ACCESS_KEY: - from_secret: GOCACHE_AWS_SECRET_ACCESS_KEY - commands: - - make build VERSION=${CI_COMMIT_TAG} - # Shell variables/expansions are escaped as $$ so Woodpecker leaves them - # for the shell instead of substituting them (as pipeline vars) at parse - # time. ${CI_COMMIT_TAG} is a real Woodpecker var and stays single-$. - - | - for entry in "node-lookup:." "pburl:./cmd/pburl" "pblastreport:./cmd/pblastreport"; do - name="$${entry%%:*}"; pkg="$${entry##*:}" - for osarch in linux/amd64 linux/arm64 darwin/amd64 darwin/arm64; do - os="$${osarch%/*}"; arch="$${osarch#*/}" - GOOS="$$os" GOARCH="$$arch" \ - go build -ldflags="-s -w -X main.version=${CI_COMMIT_TAG}" \ - -o "$${name}-$${os}-$${arch}" "$$pkg" - done - done - depends_on: [test] - backend_options: - kubernetes: - serviceAccountName: default - resources: - requests: - memory: 512Mi - cpu: 1 - limits: - memory: 2Gi - cpu: 2 - - # Package the built binary + generated shell completions into an RPM. - - name: package - image: artifactapi.k8s.syd1.au.unkin.net/docker-internal/rpmbuilder:0.1.0-alma9 - commands: - - ./scripts/build-rpm.sh ${CI_COMMIT_TAG} - depends_on: [build] - backend_options: - kubernetes: - serviceAccountName: default - resources: - requests: - memory: 512Mi - cpu: 1 - limits: - memory: 2Gi - cpu: 2 - - # Publish the RPM to the artifactapi local rpm repo (a real yum repo; - # repodata regenerates automatically). - - name: upload-rpm - image: git.unkin.net/unkin/almalinux9-base:20260606 - commands: - - | - HOST="https://artifactapi.k8s.syd1.au.unkin.net" - REPO="rpm-internal" - set -o pipefail - VAULT="https://vault.service.consul:8200" - AUTH=$$(mktemp) - VT=$$(jq -n --rawfile jwt /var/run/secrets/kubernetes.io/serviceaccount/token '{role:"woodpecker_artifactapi_writer",jwt:$$jwt}' \ - | curl -sf -d @- "$$VAULT/v1/auth/k8s/au/syd1/login" | jq -er .auth.client_token) || exit 1 - printf 'X-Vault-Token: %s\n' "$$VT" | curl -sf -H @- "$$VAULT/v1/identity/oidc/token/artifactapi-writer" \ - | jq -er '"Authorization: Bearer " + .data.token' > "$$AUTH" || exit 1 - for rpm in dist/*.rpm; do - FILE=$$(basename "$$rpm") - # artifactapi has no HEAD route (returns 405); probe with GET against - # the served path (RPMs are stored under Packages/) to avoid re-upload. - code=$$(curl -s -o /dev/null -w '%{http_code}' "$$HOST/api/v2/remotes/$$REPO/files/Packages/$$FILE" || true) - if [ "$$code" = "200" ]; then - echo "$$FILE already exists in $$REPO (HTTP $$code); skipping upload" - continue - fi - echo "Uploading $$FILE to $$REPO (existence probe returned $$code)" - curl -f -X PUT \ - "$$HOST/api/v2/remotes/$$REPO/files/$$FILE" \ - -H "Content-Type: application/x-rpm" -H @"$$AUTH" \ - --data-binary @"$$rpm" - done - depends_on: [package] - backend_options: - kubernetes: - serviceAccountName: default - resources: - requests: - memory: 128Mi - cpu: 100m - limits: - memory: 512Mi - cpu: 500m - - # Cut a Gitea release with the cross-platform binaries attached. - - name: release - image: git.unkin.net/unkin/almalinux9-base:20260606 - environment: - RELEASER_TOKEN: - from_secret: RELEASER_TOKEN - commands: - - | - curl --output /usr/local/bin/tea https://artifactapi.k8s.syd1.au.unkin.net/api/v1/remote/gitea-dl/tea/0.12.0/tea-0.12.0-linux-amd64 && chmod +x /usr/local/bin/tea - tea logins add --name gitea --url https://git.unkin.net --token "$${RELEASER_TOKEN}" --no-version-check - # $$ escapes shell vars/substitutions so Woodpecker doesn't blank them - # at parse time; ${CI_COMMIT_TAG}/${CI_REPO} are real Woodpecker vars. - # Find the previous release tag for the changelog range. Several tags can - # point at the same commit (e.g. v0.5.3 and v0.5.4), so we skip tags on - # the current commit and pick the newest semver tag that is a real - # ancestor of this one -- describe HEAD^ would jump too far back. - CUR_SHA=$$(git rev-list -n1 "${CI_COMMIT_TAG}") - PREV_TAG="" - for t in $$(git tag --sort=-v:refname); do - [ "$$t" = "${CI_COMMIT_TAG}" ] && continue - [ "$$(git rev-list -n1 "$$t")" = "$$CUR_SHA" ] && continue - if git merge-base --is-ancestor "$$t" "${CI_COMMIT_TAG}" 2>/dev/null; then - PREV_TAG="$$t"; break - fi - done - if [ -n "$$PREV_TAG" ]; then - NOTES=$$(git log "$${PREV_TAG}..${CI_COMMIT_TAG}" --pretty=format:"- %s") - else - NOTES=$$(git log --pretty=format:"- %s") - fi - tea releases create --tag "${CI_COMMIT_TAG}" --title "${CI_COMMIT_TAG}" --note "$${NOTES}" --login gitea --repo "${CI_REPO}" - # The build step writes the 12 cross-compiled binaries into the workspace - # root; the package step writes the RPM to dist/. Generate a checksums - # manifest over everything we attach so downloads can be verified. - RPM=$$(ls dist/*.rpm 2>/dev/null | head -1) - ASSETS="node-lookup-linux-amd64 node-lookup-linux-arm64 node-lookup-darwin-amd64 node-lookup-darwin-arm64 pburl-linux-amd64 pburl-linux-arm64 pburl-darwin-amd64 pburl-darwin-arm64 pblastreport-linux-amd64 pblastreport-linux-arm64 pblastreport-darwin-amd64 pblastreport-darwin-arm64" - [ -n "$$RPM" ] && ASSETS="$$ASSETS $$RPM" - sha256sum $$ASSETS > sha256sums.txt - tea releases assets create "${CI_COMMIT_TAG}" $$ASSETS sha256sums.txt \ - --login gitea --repo "${CI_REPO}" - depends_on: [upload-rpm] - backend_options: - kubernetes: - serviceAccountName: default - resources: - requests: - memory: 128Mi - cpu: 100m - limits: - memory: 512Mi - cpu: 500m diff --git a/AGENTS.md b/AGENTS.md index c92fc47..e457109 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,14 +22,17 @@ main.go # node-lookup CLI source (module root, package mai main_test.go # node-lookup unit tests (mock PuppetDB via httptest) cmd/pburl/main.go # pburl CLI cmd/pblastreport/main.go # pblastreport CLI (report.go: report-time formatting) -internal/puppet/ # shared: config, puppetdb nodes query, board URLs, stdin +internal/puppet/ # shared: config (all 3 tools), puppetdb nodes query, board URLs, stdin go.mod # Go module (module name: node-lookup) go.sum # dependency checksums Makefile # build / test / lint / completions / rpm / version-bump targets -packaging/nfpm.yaml # nfpm spec (envsubst-templated) for the RPM (all 3 binaries) -scripts/build-rpm.sh # generates completions + packages the RPM with nfpm -.woodpecker/ # CI: build, test, pre-commit (PR) + release (tag) -dist/ # build output: binaries, completions, RPM (not committed) +.goreleaser.yaml # raw binaries (linux+darwin, amd64+arm64) + amd64 RPM, signed checksums +packaging/config.example.yaml # example config, shipped in the RPM as a doc +scripts/completions.sh # generates completions/ (goreleaser before hook) +scripts/sign.sh # signs the checksums via the Vault gpg engine +.github/workflows/ # CI (PR + main) and release (v* tag) via IUCLabs/workflows +.woodpecker/ # legacy PR checks (build, test, pre-commit) +dist/ # build output (not committed) ``` Every binary is a separate `main` package, so `make build` builds each with its @@ -45,15 +48,16 @@ go build -o node-lookup ./... Requires Go 1.21+. Dependencies: `github.com/spf13/cobra` (CLI), `gopkg.in/yaml.v3` (Ansible output). -## Packaging (RPM) +## Packaging and release ```bash -make rpm # build the binary + package it into dist/*.rpm via nfpm +make rpm # goreleaser snapshot: dist/ binaries + RPM (unsigned) +make patch # or minor/major: draft a GitHub release, then push the tag ``` -`scripts/build-rpm.sh` generates bash/zsh/fish completions from the built binary -and bundles them alongside `/usr/bin/node-lookup`. On a `v*` tag the release -pipeline builds the RPM and `PUT`s it to the artifactapi `rpm-internal` repo. +goreleaser builds all three tools; the amd64 RPM bundles the binaries, their +bash/zsh/fish completions and `config.example.yaml` as a doc. The `release` +workflow attaches the assets to the draft release and publishes it. ## Shell completions @@ -109,19 +113,26 @@ PuppetDB v4 `nodes` endpoint (derived from the configured facts URL). ## Configuration -Precedence (lowest → highest): **defaults < config file < env vars < `--url` flag** +All three tools share one config, loaded by `internal/puppet`. Precedence +(highest first): **flags > `NODE_LOOKUP_*` env vars > `~/.config/node-lookup/config.yaml` > `/etc/node-lookup/config.yaml`**. +There are no built-in hostnames: a tool fails with an error naming the config +paths when a value it needs is unset (`puppetdb_url` for node-lookup and +pblastreport, `puppetboard_url` for pburl and pblastreport). Only `role_fact` +has a default (`enc_role`); an empty `domain` disables short-name qualifying. ### Config file -XDG location: `$XDG_CONFIG_HOME/node-lookup/config.yaml` (default: `~/.config/node-lookup/config.yaml`) +User location: `$XDG_CONFIG_HOME/node-lookup/config.yaml` (default `~/.config/node-lookup/config.yaml`). +See `packaging/config.example.yaml`: ```yaml -puppetdb_url: http://puppetdbapi.service.consul:8080/pdb/query/v4/facts +puppetdb_url: http://puppetdb.example.com:8080/pdb/query/v4/facts +puppetboard_url: https://puppetboard.example.com +domain: example.com role_fact: enc_role -puppetboard_url: https://puppetboard.k8s.syd1.au.unkin.net # used by pburl / pblastreport ``` -Generate the default config file: +Write a config template (empty values to fill in): ```bash ./node-lookup config init ``` @@ -138,7 +149,7 @@ Show the active configuration (after all overrides applied): | `NODE_LOOKUP_URL` | `puppetdb_url` | PuppetDB facts endpoint | | `NODE_LOOKUP_ROLE_FACT` | `role_fact` | Fact name used by `-R` flag | | `NODE_LOOKUP_PUPPETBOARD_URL` | `puppetboard_url` | Puppetboard base URL (pburl / pblastreport) | -| `NODE_LOOKUP_DOMAIN` | `domain` | Domain appended to short (dotless) `-n` node names (default `main.unkin.net`) | +| `NODE_LOOKUP_DOMAIN` | `domain` | Domain appended to short (dotless) `-n` node names (empty: no qualifying) | ### CLI flags @@ -147,14 +158,14 @@ Show the active configuration (after all overrides applied): ## Code Patterns -- **`loadConfig()`**: reads config file → applies env vars → returns `config` struct. Called once at startup in `main()`. +- **`puppet.Load()`**: reads `/etc` then user config file → applies env vars. Each command applies its flags, then `cfg.Require(keys...)`. `main()` calls `execute(args)` so tests can drive the CLI. - **`buildQuery()`**: returns a PuppetDB PQL-compatible JSON array string. Uses `roleFact` from config (not hardcoded). Match modifiers: `-p` (partial/regex, uses `~` op), `-i` (inverse, wraps with `not`), composable. - **Multiple facts**: `-F` accepts a comma-separated list (`ipaddress,enc_role`). `splitFactNames()`/`nameFilter()` turn several names into an `or` over `["=","name",]` clauses; JSON output keys each value by the fact's real name so all requested facts appear per host. - **Match value / `matchValue()`**: the value to match comes from `-m/--match` or, if that is empty, an optional positional argument. The positional fallback exists because pflag does not attach a space-separated value to a string flag grouped with a bool flag, so in `-pm k8s` the `k8s` arrives as a positional. `-m` still wins when both are given. - **`queryPuppetDB(url, query)`**: takes the URL as a parameter — never reads globals. - **`processResults()`**: iterates facts, returns sorted `"certname value"` strings. JSON string values are unquoted; other JSON types rendered as compact JSON. - **Output modes**: JSON (`-j`), count (`-C`), Ansible YAML (`-A`), node-only (`-1`), value-only (`-2`), default (node + value). `-j` and `-A` share `factsByHost()`, so both attach the queried fact(s) per host — as an object under the host (`-j`) or as inventory host vars (`-A`). -- **Short node names / `qualifyNode()`**: a `-n` value (and stdin-sourced node names) with no dot is auto-qualified to `.` (domain defaults to `main.unkin.net`, overridable via `--domain`/`NODE_LOOKUP_DOMAIN`), so `-n ausyd1nxvm2120` resolves the same as its FQDN. A name that already contains a dot (any domain) is left unchanged; a single trailing dot is stripped; empty input is preserved. +- **Short node names / `qualifyNode()`**: a `-n` value (and stdin-sourced node names) with no dot is auto-qualified to `.` (domain from config, `--domain` or `NODE_LOOKUP_DOMAIN`; empty disables it), so `-n host1` resolves the same as its FQDN. A name that already contains a dot (any domain) is left unchanged; a single trailing dot is stripped; empty input is preserved. - **Stdin support**: `stdinReader()` reads node names from stdin only when it is a real pipe/redirect carrying data (and no `-n` given). Terminals, `/dev/null`, and empty/closed pipes fall through to a normal query — so running without a TTY (e.g. invoked by an agent or CI) behaves like an interactive run instead of consuming empty input. - **SIGPIPE handling**: `signal.Ignore(syscall.SIGPIPE)` so pipes to `head` etc. work cleanly. @@ -169,10 +180,10 @@ make test # go test -v -race ./... ``` `main_test.go` covers query construction (all `-m`/`-p`/`-i` combinations), value -rendering, result processing/counting, config precedence (defaults < file < env), -`writeDefaultConfig`, the `stdinReader` no-TTY behavior, and every `run()` output +rendering, result processing/counting, flag-over-env precedence, the missing +`puppetdb_url` error, `writeDefaultConfig`, the `stdinReader` no-TTY behavior, and every `run()` output mode (default, `-1`, `-2`, `-C`, `-j`, `-A`, `-a`). PuppetDB is stubbed with -`httptest` — no live Consul/PuppetDB access is required. +`httptest` — no live PuppetDB access is required. ## Gotchas diff --git a/Makefile b/Makefile index 8838e0c..da1e7b9 100644 --- a/Makefile +++ b/Makefile @@ -12,13 +12,12 @@ ARCH ?= $(shell go env GOARCH) # companion tools live under cmd/. Usable inside a shell for-loop over $(BINARIES). pkgpath = $$([ "$$b" = "node-lookup" ] && echo . || echo ./cmd/$$b) -.PHONY: all build test lint fmt clean install completions rpm rpm-package patch minor major _tag +.PHONY: all build test lint fmt clean install completions rpm patch minor major all: build -# Build every binary into dist/ so the nfpm packaging step -# (scripts/build-rpm.sh) can find them. Each main package needs its own -o, so -# they are built individually rather than with a single ./... invocation. +# Each main package needs its own -o, so they are built individually rather +# than with a single ./... invocation. build: @for b in $(BINARIES); do \ echo "building $$b"; \ @@ -35,46 +34,33 @@ fmt: gofmt -w . clean: - rm -rf $(DIST) $(BINARIES) + rm -rf $(DIST) $(BINARIES) completions install: go install $(GOFLAGS) ./... -# Generate bash/zsh/fish completions for every binary into dist/completions. -completions: build - @mkdir -p $(DIST)/completions - @for b in $(BINARIES); do \ - $(DIST)/$$b completion bash > $(DIST)/completions/$$b.bash; \ - $(DIST)/$$b completion zsh > $(DIST)/completions/_$$b; \ - $(DIST)/$$b completion fish > $(DIST)/completions/$$b.fish; \ - done +# Generate bash/zsh/fish completions for every binary into completions/. +completions: + ./scripts/completions.sh -# Build the binary then package it (with completions) into an RPM via nfpm. -rpm: build rpm-package +# Snapshot release: raw binaries plus the RPM in dist/, unsigned. +rpm: + GOTOOLCHAIN=auto go run github.com/goreleaser/goreleaser/v2@v2.20.2 release --snapshot --clean --skip=sign -# Package an already-built binary into an RPM (used by CI after the build step). -rpm-package: - ./scripts/build-rpm.sh $(VERSION) +DEFAULT_BRANCH ?= main -# Bump helpers — reads the latest semver tag and creates the next one. -# If no tag exists yet, starts from v0.0.0. -_LATEST := $(shell git tag --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$$' | head -1) -_BASE := $(if $(_LATEST),$(_LATEST),v0.0.0) -_MAJ := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f1) -_MIN := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f2) -_PAT := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f3) - -patch: - @NEW=v$(_MAJ).$(_MIN).$(shell expr $(_PAT) + 1); \ - git tag $$NEW && echo "Tagged $$NEW" && $(MAKE) _tag TAG=$$NEW - -minor: - @NEW=v$(_MAJ).$(shell expr $(_MIN) + 1).0; \ - git tag $$NEW && echo "Tagged $$NEW" && $(MAKE) _tag TAG=$$NEW - -major: - @NEW=v$(shell expr $(_MAJ) + 1).0.0; \ - git tag $$NEW && echo "Tagged $$NEW" && $(MAKE) _tag TAG=$$NEW - -_tag: - git push origin $(TAG) +# Draft the release with generated notes, then push the tag; the release +# workflow attaches assets to the draft and publishes it. +patch minor major: + @git fetch --quiet --tags origin $(DEFAULT_BRANCH) + @test "$$(git branch --show-current)" = "$(DEFAULT_BRANCH)" || { echo "ERROR: not on $(DEFAULT_BRANCH)"; exit 1; } + @test -z "$$(git status --porcelain)" || { echo "ERROR: working tree not clean"; exit 1; } + @test "$$(git rev-parse HEAD)" = "$$(git rev-parse origin/$(DEFAULT_BRANCH))" || { echo "ERROR: HEAD is not origin/$(DEFAULT_BRANCH)"; exit 1; } + @LATEST=$$(git tag --list 'v*' --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$$' | head -1); \ + NEW=$$(echo "$${LATEST:-v0.0.0}" | sed 's/^v//' | awk -F. -v b=$@ '{ \ + if (b == "major") print "v" ($$1+1) ".0.0"; \ + else if (b == "minor") print "v" $$1 "." ($$2+1) ".0"; \ + else print "v" $$1 "." $$2 "." ($$3+1) }'); \ + SHA=$$(git rev-parse HEAD); \ + gh release create "$$NEW" --draft --target "$$SHA" --generate-notes --title "$$NEW" || exit 1; \ + git push origin "$$SHA:refs/tags/$$NEW" || { gh release delete "$$NEW" --yes; exit 1; } diff --git a/README.md b/README.md new file mode 100644 index 0000000..a5c19ca --- /dev/null +++ b/README.md @@ -0,0 +1,42 @@ +# node-lookup + +CLI tools for PuppetDB: + +- `node-lookup` queries and filters node facts. +- `pburl` prints the Puppetboard node-page URL for each host. +- `pblastreport` prints each host's last Puppet report time and Puppetboard URL. + +## Install + +Download a binary (`--`, linux/darwin on amd64/arm64) or the +x86_64 RPM from [releases](https://github.com/IUCLabs/node-lookup/releases). +The RPM installs all three tools with bash/zsh/fish completions. + +Verify downloads with `node-lookup__SHA256SUMS` and its `.sig`. + +## Configure + +The tools share one config. Precedence, highest first: flags, `NODE_LOOKUP_*` +env vars, `~/.config/node-lookup/config.yaml`, `/etc/node-lookup/config.yaml`. +There are no built-in endpoints; start from +[`packaging/config.example.yaml`](https://github.com/IUCLabs/node-lookup/blob/main/packaging/config.example.yaml) +(the RPM ships it under `/usr/share/doc/node-lookup/`). + +```bash +node-lookup -R # every node with its role fact +node-lookup -n host1 -a # all facts for one node +node-lookup -R | pblastreport # last report time per node +node-lookup config show # effective config +``` + +## Develop and release + +```bash +make test +make rpm # goreleaser snapshot into dist/ +make patch # or minor/major: drafts the GitHub release, then pushes the tag +``` + +The `release` workflow builds the binaries and RPM, signs the checksums and +publishes the draft. See [AGENTS.md](https://github.com/IUCLabs/node-lookup/blob/main/AGENTS.md) +for code layout and flags. diff --git a/cmd/pblastreport/main.go b/cmd/pblastreport/main.go index 37bb175..08c44f3 100644 --- a/cmd/pblastreport/main.go +++ b/cmd/pblastreport/main.go @@ -52,6 +52,9 @@ func main() { if cmd.Flags().Changed("url") { cfg.PuppetDBURL = pdbURL } + if err := cfg.Require("puppetdb_url", "puppetboard_url"); err != nil { + return err + } loc := time.Local if tz != "" { diff --git a/cmd/pburl/main.go b/cmd/pburl/main.go index 991bfc2..47d2c67 100644 --- a/cmd/pburl/main.go +++ b/cmd/pburl/main.go @@ -38,6 +38,9 @@ func main() { if cmd.Flags().Changed("puppetboard-url") { cfg.PuppetboardURL = boardURL } + if err := cfg.Require("puppetboard_url"); err != nil { + return err + } hosts := puppet.ReadHosts(os.Stdin, args) if len(hosts) == 0 { return fmt.Errorf("no hosts given (pass as arguments or pipe node-lookup output)") diff --git a/internal/puppet/config.go b/internal/puppet/config.go index c945a24..fa9be8a 100644 --- a/internal/puppet/config.go +++ b/internal/puppet/config.go @@ -1,48 +1,62 @@ // Package puppet holds the small pieces of PuppetDB/Puppetboard plumbing shared -// by the node-lookup companion tools (pburl, pblastreport): config loading, +// by node-lookup and its companion tools (pburl, pblastreport): config loading, // PuppetDB "nodes" queries, Puppetboard URL construction, and reading hostnames // from piped node-lookup output. // -// It intentionally reads the SAME config file, env vars, and defaults as the -// node-lookup CLI so a single `~/.config/node-lookup/config.yaml` configures -// every tool in the family. +// Every tool reads the same config files and env vars, so one config file +// configures the whole family. package puppet import ( "fmt" "os" "path/filepath" + "strings" "gopkg.in/yaml.v3" ) const ( - // DefaultPuppetDBURL is the PuppetDB v4 facts endpoint (shared with node-lookup). - DefaultPuppetDBURL = "http://puppetdbapi.service.consul:8080/pdb/query/v4/facts" // DefaultRoleFact is the role fact node-lookup queries with -R. DefaultRoleFact = "enc_role" - // DefaultPuppetboardURL is the base URL of the Puppetboard web UI. - DefaultPuppetboardURL = "https://puppetboard.k8s.syd1.au.unkin.net" appName = "node-lookup" configFileName = "config.yaml" ) -// Config mirrors node-lookup's config plus the puppetboard_url key used by the -// companion tools. Fields map 1:1 to config file keys and env vars. +// SystemConfigPath is the system-wide config file, read before the user one. +var SystemConfigPath = filepath.Join("/etc", appName, configFileName) + +// Config is shared by all tools. Fields map 1:1 to config file keys and +// NODE_LOOKUP_* env vars. type Config struct { PuppetDBURL string `yaml:"puppetdb_url"` RoleFact string `yaml:"role_fact"` PuppetboardURL string `yaml:"puppetboard_url"` + // Domain is appended to short (dotless) node names; empty disables that. + Domain string `yaml:"domain"` } -// DefaultConfig returns the built-in defaults. -func DefaultConfig() Config { - return Config{ - PuppetDBURL: DefaultPuppetDBURL, - RoleFact: DefaultRoleFact, - PuppetboardURL: DefaultPuppetboardURL, +// envVars maps each config key to its env var. +var envVars = map[string]string{ + "puppetdb_url": "NODE_LOOKUP_URL", + "role_fact": "NODE_LOOKUP_ROLE_FACT", + "puppetboard_url": "NODE_LOOKUP_PUPPETBOARD_URL", + "domain": "NODE_LOOKUP_DOMAIN", +} + +func (c *Config) field(key string) *string { + switch key { + case "puppetdb_url": + return &c.PuppetDBURL + case "role_fact": + return &c.RoleFact + case "puppetboard_url": + return &c.PuppetboardURL + case "domain": + return &c.Domain } + panic("unknown config key " + key) } // ConfigDir returns the XDG_CONFIG_HOME/node-lookup directory. @@ -55,36 +69,47 @@ func ConfigDir() string { return filepath.Join(base, appName) } -// ConfigPath returns the full path to the shared config file. +// ConfigPath returns the full path to the user config file. func ConfigPath() string { return filepath.Join(ConfigDir(), configFileName) } -// Load reads the config file (if present), then applies env var overrides. -// Precedence (lowest → highest): defaults < config file < env vars. +// Load merges, lowest precedence first: the built-in role fact, the system +// config file, the user config file, then NODE_LOOKUP_* env vars. Flags are +// applied by the caller, which then calls Require. func Load() (Config, error) { - cfg := DefaultConfig() - - path := ConfigPath() - data, err := os.ReadFile(path) - if err != nil && !os.IsNotExist(err) { - return cfg, fmt.Errorf("reading config %s: %w", path, err) - } - if err == nil { + cfg := Config{RoleFact: DefaultRoleFact} + for _, path := range []string{SystemConfigPath, ConfigPath()} { + data, err := os.ReadFile(path) + if os.IsNotExist(err) { + continue + } + if err != nil { + return cfg, fmt.Errorf("reading config %s: %w", path, err) + } if err := yaml.Unmarshal(data, &cfg); err != nil { return cfg, fmt.Errorf("parsing config %s: %w", path, err) } } - - if v := os.Getenv("NODE_LOOKUP_URL"); v != "" { - cfg.PuppetDBURL = v + for key, env := range envVars { + if v := os.Getenv(env); v != "" { + *cfg.field(key) = v + } } - if v := os.Getenv("NODE_LOOKUP_ROLE_FACT"); v != "" { - cfg.RoleFact = v - } - if v := os.Getenv("NODE_LOOKUP_PUPPETBOARD_URL"); v != "" { - cfg.PuppetboardURL = v - } - return cfg, nil } + +// Require returns an error naming every missing key and where to set it. +func (c Config) Require(keys ...string) error { + var missing []string + for _, k := range keys { + if *c.field(k) == "" { + missing = append(missing, fmt.Sprintf("%s (env %s)", k, envVars[k])) + } + } + if len(missing) == 0 { + return nil + } + return fmt.Errorf("missing config: %s; set it in %s or %s, via env, or with a flag", + strings.Join(missing, ", "), ConfigPath(), SystemConfigPath) +} diff --git a/internal/puppet/puppet_test.go b/internal/puppet/puppet_test.go index 163ff5b..3a2eff2 100644 --- a/internal/puppet/puppet_test.go +++ b/internal/puppet/puppet_test.go @@ -12,50 +12,91 @@ import ( // ---- config ----------------------------------------------------------------- -func TestLoad_Defaults(t *testing.T) { - t.Setenv("XDG_CONFIG_HOME", t.TempDir()) - t.Setenv("NODE_LOOKUP_URL", "") - t.Setenv("NODE_LOOKUP_ROLE_FACT", "") - t.Setenv("NODE_LOOKUP_PUPPETBOARD_URL", "") +// isolate points both config files into a temp dir and clears the env vars. +func isolate(t *testing.T) (system, user string) { + t.Helper() + dir := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "home")) + old := SystemConfigPath + SystemConfigPath = filepath.Join(dir, "etc", configFileName) + t.Cleanup(func() { SystemConfigPath = old }) + for _, env := range envVars { + t.Setenv(env, "") + } + return SystemConfigPath, ConfigPath() +} - cfg, err := Load() - if err != nil { +func writeFile(t *testing.T, path, body string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { t.Fatal(err) } - if cfg.PuppetDBURL != DefaultPuppetDBURL { - t.Fatalf("expected default puppetdb url, got %s", cfg.PuppetDBURL) - } - if cfg.PuppetboardURL != DefaultPuppetboardURL { - t.Fatalf("expected default puppetboard url, got %s", cfg.PuppetboardURL) + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) } } -func TestLoad_FileAndEnvOverride(t *testing.T) { - dir := t.TempDir() - t.Setenv("XDG_CONFIG_HOME", dir) - t.Setenv("NODE_LOOKUP_URL", "") - t.Setenv("NODE_LOOKUP_ROLE_FACT", "") - t.Setenv("NODE_LOOKUP_PUPPETBOARD_URL", "https://env.example.net") +func TestLoad_NoConfigHasOnlyRoleFact(t *testing.T) { + isolate(t) + cfg, err := Load() + if err != nil { + t.Fatal(err) + } + if cfg != (Config{RoleFact: DefaultRoleFact}) { + t.Fatalf("expected only the role fact default, got %+v", cfg) + } +} - cfgDir := filepath.Join(dir, appName) - if err := os.MkdirAll(cfgDir, 0o755); err != nil { - t.Fatal(err) - } - body := "puppetdb_url: http://file:8080/pdb/query/v4/facts\npuppetboard_url: https://file.example.net\n" - if err := os.WriteFile(filepath.Join(cfgDir, configFileName), []byte(body), 0o644); err != nil { - t.Fatal(err) - } +func TestLoad_Precedence(t *testing.T) { + system, user := isolate(t) + writeFile(t, system, "puppetdb_url: http://system\npuppetboard_url: https://system\ndomain: system.example.com\nrole_fact: system_role\n") + writeFile(t, user, "puppetboard_url: https://user\ndomain: user.example.com\n") + t.Setenv("NODE_LOOKUP_DOMAIN", "env.example.com") cfg, err := Load() if err != nil { t.Fatal(err) } - if cfg.PuppetDBURL != "http://file:8080/pdb/query/v4/facts" { - t.Fatalf("file override failed: %s", cfg.PuppetDBURL) + want := Config{ + PuppetDBURL: "http://system", // only in the system file + PuppetboardURL: "https://user", // user file beats system file + Domain: "env.example.com", // env beats both files + RoleFact: "system_role", // file beats the built-in default } - // env beats the file for puppetboard_url - if cfg.PuppetboardURL != "https://env.example.net" { - t.Fatalf("env should beat file: %s", cfg.PuppetboardURL) + if cfg != want { + t.Fatalf("got %+v, want %+v", cfg, want) + } +} + +func TestLoad_InvalidYAMLNamesPath(t *testing.T) { + system, _ := isolate(t) + writeFile(t, system, ":\tinvalid: yaml:\n") + _, err := Load() + if err == nil || !strings.Contains(err.Error(), system) { + t.Fatalf("expected parse error naming %s, got %v", system, err) + } +} + +func TestRequire_MissingNamesKeysAndPaths(t *testing.T) { + system, user := isolate(t) + err := Config{PuppetboardURL: "https://board"}.Require("puppetdb_url", "puppetboard_url", "domain") + if err == nil { + t.Fatal("expected an error") + } + msg := err.Error() + for _, want := range []string{"puppetdb_url (env NODE_LOOKUP_URL)", "domain (env NODE_LOOKUP_DOMAIN)", system, user} { + if !strings.Contains(msg, want) { + t.Fatalf("error %q missing %q", msg, want) + } + } + if strings.Contains(msg, "puppetboard_url") { + t.Fatalf("set key reported missing: %q", msg) + } +} + +func TestRequire_AllSet(t *testing.T) { + if err := (Config{PuppetDBURL: "http://pdb"}).Require("puppetdb_url"); err != nil { + t.Fatal(err) } } @@ -63,9 +104,9 @@ func TestLoad_FileAndEnvOverride(t *testing.T) { func TestNodesEndpoint(t *testing.T) { cases := map[string]string{ - "http://puppetdbapi.service.consul:8080/pdb/query/v4/facts": "http://puppetdbapi.service.consul:8080/pdb/query/v4/nodes", - "http://h:8080/pdb/query/v4/facts/": "http://h:8080/pdb/query/v4/nodes", - "https://h/facts": "https://h/nodes", + "http://puppetdb.example.com:8080/pdb/query/v4/facts": "http://puppetdb.example.com:8080/pdb/query/v4/nodes", + "http://h:8080/pdb/query/v4/facts/": "http://h:8080/pdb/query/v4/nodes", + "https://h/facts": "https://h/nodes", } for in, want := range cases { if got := NodesEndpoint(in); got != want { diff --git a/main.go b/main.go index e42a55e..7b3b0c9 100644 --- a/main.go +++ b/main.go @@ -9,110 +9,36 @@ import ( "net/url" "os" "os/signal" - "path/filepath" "sort" "strings" "syscall" + "node-lookup/internal/puppet" + "github.com/spf13/cobra" "gopkg.in/yaml.v3" ) -const ( - defaultPuppetDBURL = "http://puppetdbapi.service.consul:8080/pdb/query/v4/facts" - defaultRoleFact = "enc_role" - defaultPuppetboardURL = "https://puppetboard.k8s.syd1.au.unkin.net" - defaultDomain = "main.unkin.net" - configFileName = "config.yaml" - appName = "node-lookup" -) +const appName = "node-lookup" var version = "dev" -// config holds all configurable values. Fields map 1:1 to config file keys, -// env vars (NODE_LOOKUP_*), and (where applicable) CLI flags. -type config struct { - PuppetDBURL string `yaml:"puppetdb_url"` - RoleFact string `yaml:"role_fact"` - // PuppetboardURL is not used by node-lookup itself; it is scaffolded here so - // the shared config file also configures the companion tools (pburl, - // pblastreport) that read this same file. - PuppetboardURL string `yaml:"puppetboard_url"` - // Domain is appended to a short (dotless) -n node name to form its FQDN. - Domain string `yaml:"domain"` -} - -func defaultConfig() config { - return config{ - PuppetDBURL: defaultPuppetDBURL, - RoleFact: defaultRoleFact, - PuppetboardURL: defaultPuppetboardURL, - Domain: defaultDomain, - } -} - -// configDir returns the XDG_CONFIG_HOME/node-lookup directory. -func configDir() string { - base := os.Getenv("XDG_CONFIG_HOME") - if base == "" { - home, _ := os.UserHomeDir() - base = filepath.Join(home, ".config") - } - return filepath.Join(base, appName) -} - -// configPath returns the full path to the config file. -func configPath() string { - return filepath.Join(configDir(), configFileName) -} - -// loadConfig reads the config file (if present), then applies env var overrides. -// Precedence (lowest → highest): defaults < config file < env vars < CLI flags. -func loadConfig() (config, error) { - cfg := defaultConfig() - - path := configPath() - data, err := os.ReadFile(path) - if err != nil && !os.IsNotExist(err) { - return cfg, fmt.Errorf("reading config %s: %w", path, err) - } - if err == nil { - if err := yaml.Unmarshal(data, &cfg); err != nil { - return cfg, fmt.Errorf("parsing config %s: %w", path, err) - } - } - - if v := os.Getenv("NODE_LOOKUP_URL"); v != "" { - cfg.PuppetDBURL = v - } - if v := os.Getenv("NODE_LOOKUP_ROLE_FACT"); v != "" { - cfg.RoleFact = v - } - if v := os.Getenv("NODE_LOOKUP_PUPPETBOARD_URL"); v != "" { - cfg.PuppetboardURL = v - } - if v := os.Getenv("NODE_LOOKUP_DOMAIN"); v != "" { - cfg.Domain = v - } - - return cfg, nil -} +type config = puppet.Config // writeDefaultConfig creates the config directory and writes a default config file. func writeDefaultConfig() error { - dir := configDir() + dir := puppet.ConfigDir() if err := os.MkdirAll(dir, 0o755); err != nil { return fmt.Errorf("creating config dir: %w", err) } - path := configPath() + path := puppet.ConfigPath() if _, err := os.Stat(path); err == nil { return fmt.Errorf("config already exists at %s", path) } - cfg := defaultConfig() - data, _ := yaml.Marshal(cfg) - header := []byte("# node-lookup configuration\n# Fields can be overridden with env vars: NODE_LOOKUP_URL, NODE_LOOKUP_ROLE_FACT, NODE_LOOKUP_PUPPETBOARD_URL, NODE_LOOKUP_DOMAIN\n# puppetboard_url is used by the companion tools (pburl, pblastreport).\n# domain is appended to short (dotless) -n node names to form their FQDN.\n\n") + data, _ := yaml.Marshal(config{RoleFact: puppet.DefaultRoleFact}) + header := []byte("# node-lookup configuration; fill in the empty values.\n# Fields can be overridden with env vars: NODE_LOOKUP_URL, NODE_LOOKUP_ROLE_FACT, NODE_LOOKUP_PUPPETBOARD_URL, NODE_LOOKUP_DOMAIN\n# puppetboard_url is used by the companion tools (pburl, pblastreport).\n# domain is appended to short (dotless) -n node names to form their FQDN.\n\n") if err := os.WriteFile(path, append(header, data...), 0o644); err != nil { return fmt.Errorf("writing config: %w", err) } @@ -152,15 +78,15 @@ func nameFilter(names []string) []interface{} { } // qualifyNode auto-qualifies a short (dotless) node name by appending -// ".", so `-n ausyd1nxvm2120` resolves the same as its FQDN. A name +// ".", so `-n host1` resolves the same as its FQDN. A name // that already contains a dot is treated as already-qualified (including names -// in other domains like *.k8s.syd1.au.unkin.net) and returned unchanged. A +// in other domains) and returned unchanged; so is any name when domain is empty. A // single trailing dot is stripped first, so a dotless name with a trailing dot // is still qualified. Empty input is returned unchanged to preserve the // existing "no node given" behavior. func qualifyNode(name, domain string) string { name = strings.TrimSuffix(name, ".") - if name == "" || strings.Contains(name, ".") { + if name == "" || domain == "" || strings.Contains(name, ".") { return name } return name + "." + domain @@ -463,10 +389,17 @@ func run(cfg config, nodeName, factName, match string, showRole, partial, invers } func main() { - cfg, err := loadConfig() + if err := execute(os.Args[1:]); err != nil { + os.Exit(1) + } +} + +// execute builds and runs the CLI; cobra prints any returned error. +func execute(args []string) error { + cfg, err := puppet.Load() if err != nil { fmt.Fprintln(os.Stderr, "config error:", err) - os.Exit(1) + return err } var ( @@ -505,6 +438,9 @@ func main() { return nil }, RunE: func(cmd *cobra.Command, args []string) error { + if err := cfg.Require("puppetdb_url"); err != nil { + return err + } return run(cfg, nodeName, factName, matchValue(match, args), showRole, partial, inverse, nodeOnly, valueOnly, count, ansible, jsonMode, allFacts) }, SilenceUsage: true, @@ -513,7 +449,7 @@ func main() { f := rootCmd.Flags() f.StringVarP(&nodeName, "node", "n", "", "Node name") f.StringVarP(&factName, "fact", "F", "", "Fact name (comma-separated for several, e.g. -F ipaddress,enc_role)") - f.BoolVarP(&showRole, "role", "R", false, "Show role fact ("+defaultRoleFact+" by default)") + f.BoolVarP(&showRole, "role", "R", false, "Show role fact ("+puppet.DefaultRoleFact+" by default)") f.StringVarP(&match, "match", "m", "", "Value to match (use with -p and/or -i)") f.BoolVarP(&partial, "partial", "p", false, "Partial/regex match modifier (combine with -m)") f.BoolVarP(&inverse, "inverse", "i", false, "Inverse match modifier (combine with -m)") @@ -533,7 +469,7 @@ func main() { configInitCmd := &cobra.Command{ Use: "init", - Short: "Write a default config file to " + configPath(), + Short: "Write a default config file to " + puppet.ConfigPath(), RunE: func(cmd *cobra.Command, args []string) error { return writeDefaultConfig() }, @@ -544,7 +480,7 @@ func main() { Use: "show", Short: "Print the active configuration", RunE: func(cmd *cobra.Command, args []string) error { - fmt.Printf("config file : %s\n", configPath()) + fmt.Printf("config files : %s, %s\n", puppet.SystemConfigPath, puppet.ConfigPath()) fmt.Printf("puppetdb_url : %s\n", cfg.PuppetDBURL) fmt.Printf("role_fact : %s\n", cfg.RoleFact) fmt.Printf("puppetboard_url: %s\n", cfg.PuppetboardURL) @@ -565,7 +501,6 @@ func main() { } rootCmd.AddCommand(versionCmd) - if err := rootCmd.Execute(); err != nil { - os.Exit(1) - } + rootCmd.SetArgs(args) + return rootCmd.Execute() } diff --git a/main_test.go b/main_test.go index 4636ac7..ae7ac85 100644 --- a/main_test.go +++ b/main_test.go @@ -12,6 +12,8 @@ import ( "testing" "time" + "node-lookup/internal/puppet" + "gopkg.in/yaml.v3" ) @@ -170,17 +172,17 @@ func TestSplitFactNames(t *testing.T) { } func TestQualifyNode(t *testing.T) { - const domain = "main.unkin.net" + const domain = "example.com" cases := []struct { name string in string want string }{ - {"short name appends domain", "ausyd1nxvm2120", "ausyd1nxvm2120.main.unkin.net"}, - {"fqdn in default domain unchanged", "ausyd1nxvm2120.main.unkin.net", "ausyd1nxvm2120.main.unkin.net"}, - {"multi-label fqdn other domain unchanged", "foo.k8s.syd1.au.unkin.net", "foo.k8s.syd1.au.unkin.net"}, - {"short name with trailing dot qualified", "ausyd1nxvm2120.", "ausyd1nxvm2120.main.unkin.net"}, - {"fqdn with trailing dot stripped", "foo.main.unkin.net.", "foo.main.unkin.net"}, + {"short name appends domain", "host1", "host1.example.com"}, + {"fqdn in default domain unchanged", "host1.example.com", "host1.example.com"}, + {"multi-label fqdn other domain unchanged", "foo.k8s.example.net", "foo.k8s.example.net"}, + {"short name with trailing dot qualified", "host1.", "host1.example.com"}, + {"fqdn with trailing dot stripped", "foo.example.com.", "foo.example.com"}, {"empty unchanged", "", ""}, } for _, tc := range cases { @@ -192,9 +194,9 @@ func TestQualifyNode(t *testing.T) { } } -func TestQualifyNode_CustomDomain(t *testing.T) { - if got := qualifyNode("host1", "example.com"); got != "host1.example.com" { - t.Fatalf("qualifyNode with custom domain = %q, want host1.example.com", got) +func TestQualifyNode_EmptyDomain(t *testing.T) { + if got := qualifyNode("host1", ""); got != "host1" { + t.Fatalf("qualifyNode with no domain = %q, want host1", got) } } @@ -413,121 +415,46 @@ func TestQueryPuppetDB_ConnectionRefused(t *testing.T) { // ---- config ----------------------------------------------------------------- -func TestLoadConfig_Defaults(t *testing.T) { - t.Setenv("XDG_CONFIG_HOME", t.TempDir()) - t.Setenv("NODE_LOOKUP_URL", "") - t.Setenv("NODE_LOOKUP_ROLE_FACT", "") - - cfg, err := loadConfig() - if err != nil { - t.Fatal(err) - } - if cfg.PuppetDBURL != defaultPuppetDBURL { - t.Fatalf("expected default URL, got %s", cfg.PuppetDBURL) - } - if cfg.RoleFact != defaultRoleFact { - t.Fatalf("expected default role fact, got %s", cfg.RoleFact) - } - if cfg.Domain != defaultDomain { - t.Fatalf("expected default domain, got %s", cfg.Domain) - } -} - -func TestLoadConfig_DomainEnvOverride(t *testing.T) { - t.Setenv("XDG_CONFIG_HOME", t.TempDir()) - t.Setenv("NODE_LOOKUP_DOMAIN", "example.com") - - cfg, err := loadConfig() - if err != nil { - t.Fatal(err) - } - if cfg.Domain != "example.com" { - t.Fatalf("domain env override failed: %s", cfg.Domain) - } -} - -func TestLoadConfig_EnvOverride(t *testing.T) { - t.Setenv("XDG_CONFIG_HOME", t.TempDir()) - t.Setenv("NODE_LOOKUP_URL", "http://custom:9090/facts") - t.Setenv("NODE_LOOKUP_ROLE_FACT", "my_role") - - cfg, err := loadConfig() - if err != nil { - t.Fatal(err) - } - if cfg.PuppetDBURL != "http://custom:9090/facts" { - t.Fatalf("env override failed: %s", cfg.PuppetDBURL) - } - if cfg.RoleFact != "my_role" { - t.Fatalf("env override failed: %s", cfg.RoleFact) - } -} - -func TestLoadConfig_FileOverride(t *testing.T) { +// isolateConfig points the system and user config files at empty temp paths +// and clears the NODE_LOOKUP_* env vars. +func isolateConfig(t *testing.T) { + t.Helper() dir := t.TempDir() t.Setenv("XDG_CONFIG_HOME", dir) - t.Setenv("NODE_LOOKUP_URL", "") - t.Setenv("NODE_LOOKUP_ROLE_FACT", "") - - cfgDir := filepath.Join(dir, appName) - if err := os.MkdirAll(cfgDir, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(cfgDir, configFileName), []byte("puppetdb_url: http://file:8080/facts\nrole_fact: file_role\n"), 0o644); err != nil { - t.Fatal(err) - } - - cfg, err := loadConfig() - if err != nil { - t.Fatal(err) - } - if cfg.PuppetDBURL != "http://file:8080/facts" { - t.Fatalf("file override failed: %s", cfg.PuppetDBURL) - } - if cfg.RoleFact != "file_role" { - t.Fatalf("file override failed: %s", cfg.RoleFact) + old := puppet.SystemConfigPath + puppet.SystemConfigPath = filepath.Join(dir, "etc-config.yaml") + t.Cleanup(func() { puppet.SystemConfigPath = old }) + for _, env := range []string{"NODE_LOOKUP_URL", "NODE_LOOKUP_ROLE_FACT", "NODE_LOOKUP_PUPPETBOARD_URL", "NODE_LOOKUP_DOMAIN"} { + t.Setenv(env, "") } } -func TestLoadConfig_EnvOverridesFile(t *testing.T) { - dir := t.TempDir() - t.Setenv("XDG_CONFIG_HOME", dir) - t.Setenv("NODE_LOOKUP_URL", "http://env:9999/facts") - t.Setenv("NODE_LOOKUP_ROLE_FACT", "") +func TestExecute_FlagsBeatEnv(t *testing.T) { + isolateConfig(t) + var gotQuery string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotQuery = r.URL.Query().Get("query") + _, _ = w.Write([]byte("[]")) + })) + defer srv.Close() + t.Setenv("NODE_LOOKUP_URL", "http://127.0.0.1:1/unreachable") + t.Setenv("NODE_LOOKUP_DOMAIN", "env.example.com") - cfgDir := filepath.Join(dir, appName) - if err := os.MkdirAll(cfgDir, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(cfgDir, configFileName), []byte("puppetdb_url: http://file:8080/facts\n"), 0o644); err != nil { - t.Fatal(err) - } - - cfg, err := loadConfig() - if err != nil { - t.Fatal(err) - } - if cfg.PuppetDBURL != "http://env:9999/facts" { - t.Fatalf("env should beat file, got %s", cfg.PuppetDBURL) + captureStdout(t, func() { + if err := execute([]string{"--url", srv.URL, "--domain", "flag.example.com", "-n", "host1", "-R"}); err != nil { + t.Errorf("execute: %v", err) + } + }) + if !strings.Contains(gotQuery, "host1.flag.example.com") { + t.Fatalf("flags should beat env, query was %q", gotQuery) } } -func TestLoadConfig_InvalidYAML(t *testing.T) { - dir := t.TempDir() - t.Setenv("XDG_CONFIG_HOME", dir) - t.Setenv("NODE_LOOKUP_URL", "") - t.Setenv("NODE_LOOKUP_ROLE_FACT", "") - - cfgDir := filepath.Join(dir, appName) - if err := os.MkdirAll(cfgDir, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(cfgDir, configFileName), []byte(":\tinvalid: yaml:\n"), 0o644); err != nil { - t.Fatal(err) - } - - if _, err := loadConfig(); err == nil { - t.Fatal("expected error for invalid YAML") +func TestExecute_MissingPuppetDBURL(t *testing.T) { + isolateConfig(t) + err := execute([]string{"-R"}) + if err == nil || !strings.Contains(err.Error(), "puppetdb_url") || !strings.Contains(err.Error(), puppet.SystemConfigPath) { + t.Fatalf("expected missing puppetdb_url error naming the config path, got %v", err) } } @@ -538,7 +465,7 @@ func TestWriteDefaultConfig(t *testing.T) { if err := writeDefaultConfig(); err != nil { t.Fatal(err) } - data, err := os.ReadFile(filepath.Join(dir, appName, configFileName)) + data, err := os.ReadFile(filepath.Join(dir, appName, "config.yaml")) if err != nil { t.Fatal(err) } @@ -892,7 +819,7 @@ func withStdin(t *testing.T, content string) { t.Cleanup(func() { os.Stdin = old; _ = f.Close() }) } -const pipedLookup = "hosta.main.unkin.net puppetdbapi.service.consul\nhostb.main.unkin.net puppetdbapi.service.consul\n" +const pipedLookup = "hosta.example.com puppetdb.example.com\nhostb.example.com puppetdb.example.com\n" func TestRun_CountPipedWithRoleQueriesEachNode(t *testing.T) { withStdin(t, pipedLookup) @@ -918,7 +845,7 @@ func TestRun_CountPipedWithRoleQueriesEachNode(t *testing.T) { } func TestRun_CountPipedWithoutQueryCountsInput(t *testing.T) { - withStdin(t, pipedLookup+"hostc.main.unkin.net other\n") + withStdin(t, pipedLookup+"hostc.example.com other\n") cfg := config{PuppetDBURL: "http://unused", RoleFact: "enc_role"} out := strings.TrimSpace(captureStdout(t, func() { @@ -926,7 +853,7 @@ func TestRun_CountPipedWithoutQueryCountsInput(t *testing.T) { t.Fatalf("run returned error: %v", err) } })) - if out != "1: other\n2: puppetdbapi.service.consul" { + if out != "1: other\n2: puppetdb.example.com" { t.Fatalf("expected counts of piped values, got: %q", out) } } diff --git a/packaging/config.example.yaml b/packaging/config.example.yaml new file mode 100644 index 0000000..1aa0383 --- /dev/null +++ b/packaging/config.example.yaml @@ -0,0 +1,7 @@ +# node-lookup, pburl and pblastreport config. +# Read from /etc/node-lookup/config.yaml, then ~/.config/node-lookup/config.yaml; +# NODE_LOOKUP_* env vars and flags override both. +puppetdb_url: http://puppetdb.example.com:8080/pdb/query/v4/facts +puppetboard_url: https://puppetboard.example.com +domain: example.com +role_fact: enc_role diff --git a/packaging/nfpm.yaml b/packaging/nfpm.yaml deleted file mode 100644 index 4a3085d..0000000 --- a/packaging/nfpm.yaml +++ /dev/null @@ -1,82 +0,0 @@ ---- -# nfpm config for building the node-lookup RPM. -# Rendered through envsubst (see scripts/build-rpm.sh) then fed to `nfpm pkg`. - -name: ${PACKAGE_NAME} -version: ${PACKAGE_VERSION} -release: ${PACKAGE_RELEASE} -arch: ${PACKAGE_ARCH} -platform: ${PACKAGE_PLATFORM} -section: default -priority: extra -description: "${PACKAGE_DESCRIPTION}" - -maintainer: ${PACKAGE_MAINTAINER} -homepage: ${PACKAGE_HOMEPAGE} -license: ${PACKAGE_LICENSE} - -disable_globbing: false - -replaces: - - node-lookup -provides: - - node-lookup - -contents: - # The CLI binaries: node-lookup and its companion tools. - - src: dist/node-lookup - dst: /usr/bin/node-lookup - file_info: - mode: 0755 - owner: root - group: root - - src: dist/pburl - dst: /usr/bin/pburl - file_info: - mode: 0755 - owner: root - group: root - - src: dist/pblastreport - dst: /usr/bin/pblastreport - file_info: - mode: 0755 - owner: root - group: root - - # Shell completions (generated by scripts/build-rpm.sh before packaging). - - src: dist/completions/node-lookup.bash - dst: /usr/share/bash-completion/completions/node-lookup - file_info: - mode: 0644 - - src: dist/completions/_node-lookup - dst: /usr/share/zsh/site-functions/_node-lookup - file_info: - mode: 0644 - - src: dist/completions/node-lookup.fish - dst: /usr/share/fish/vendor_completions.d/node-lookup.fish - file_info: - mode: 0644 - - src: dist/completions/pburl.bash - dst: /usr/share/bash-completion/completions/pburl - file_info: - mode: 0644 - - src: dist/completions/_pburl - dst: /usr/share/zsh/site-functions/_pburl - file_info: - mode: 0644 - - src: dist/completions/pburl.fish - dst: /usr/share/fish/vendor_completions.d/pburl.fish - file_info: - mode: 0644 - - src: dist/completions/pblastreport.bash - dst: /usr/share/bash-completion/completions/pblastreport - file_info: - mode: 0644 - - src: dist/completions/_pblastreport - dst: /usr/share/zsh/site-functions/_pblastreport - file_info: - mode: 0644 - - src: dist/completions/pblastreport.fish - dst: /usr/share/fish/vendor_completions.d/pblastreport.fish - file_info: - mode: 0644 diff --git a/scripts/build-rpm.sh b/scripts/build-rpm.sh deleted file mode 100755 index 817c575..0000000 --- a/scripts/build-rpm.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env bash -# -# Package the (already built) node-lookup, pburl and pblastreport binaries into -# an RPM with nfpm, bundling generated bash/zsh/fish shell completions. -# Usage: scripts/build-rpm.sh [version] (version defaults to $CI_COMMIT_TAG) -# -set -euo pipefail - -ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -cd "${ROOT_DIR}" - -VERSION="${1:-${CI_COMMIT_TAG:-0.0.0-dev}}" -VERSION="${VERSION#v}" # strip a leading v -BINARY="node-lookup" -BINARIES=(node-lookup pburl pblastreport) -DIST="dist" - -for b in "${BINARIES[@]}"; do - if [ ! -f "${DIST}/${b}" ]; then - echo "ERROR: ${DIST}/${b} not found; run 'make build' first" >&2 - exit 1 - fi -done - -# Generate shell completions from the freshly built binaries so they always -# match the shipped flags/subcommands. -COMP_DIR="${DIST}/completions" -mkdir -p "${COMP_DIR}" -for b in "${BINARIES[@]}"; do - "./${DIST}/${b}" completion bash >"${COMP_DIR}/${b}.bash" - "./${DIST}/${b}" completion zsh >"${COMP_DIR}/_${b}" - "./${DIST}/${b}" completion fish >"${COMP_DIR}/${b}.fish" -done - -export PACKAGE_NAME="${BINARY}" -export PACKAGE_VERSION="${VERSION}" -export PACKAGE_RELEASE="1" -export PACKAGE_ARCH="amd64" -export PACKAGE_PLATFORM="linux" -export PACKAGE_DESCRIPTION="CLI tools for PuppetDB: node-lookup (fact lookup/filtering) plus pburl and pblastreport (Puppetboard URLs and last-report times)" -export PACKAGE_MAINTAINER="Ben Vincent " -export PACKAGE_HOMEPAGE="https://git.unkin.net/unkin/node-lookup" -export PACKAGE_LICENSE="MIT" - -envsubst "${DIST}/nfpm.yaml" -nfpm pkg --config "${DIST}/nfpm.yaml" --target "${DIST}" --packager rpm - -echo "Built:" -ls -1 "${DIST}"/*.rpm diff --git a/scripts/completions.sh b/scripts/completions.sh new file mode 100755 index 0000000..319d3ad --- /dev/null +++ b/scripts/completions.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Generate bash/zsh/fish completions for every tool, named as installed. +set -euo pipefail +mkdir -p completions/bash completions/zsh completions/fish +for entry in node-lookup:. pburl:./cmd/pburl pblastreport:./cmd/pblastreport; do + b=${entry%%:*} pkg=${entry#*:} + go run "$pkg" completion bash >"completions/bash/$b" + go run "$pkg" completion zsh >"completions/zsh/_$b" + go run "$pkg" completion fish >"completions/fish/$b.fish" +done diff --git a/scripts/sign.sh b/scripts/sign.sh new file mode 100755 index 0000000..e95575d --- /dev/null +++ b/scripts/sign.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Detached binary signature of $1 into $2 via the Vault gpg engine. +set -euo pipefail +b=$(base64 -w0 "$1") +jq -n --arg input "$b" '{input: $input, format: "base64"}' \ + | curl -sSf --cacert "${VAULT_CACERT:-/etc/vault-ca/ca.crt}" \ + -H "X-Vault-Token: ${VAULT_TOKEN}" -d @- \ + "${VAULT_ADDR}/v1/gpg/sign/iuclabs-release" \ + | jq -er .data.signature | base64 -d > "$2"