diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6fde1e4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/w10k +/w10k-* +dist/ +sha256sums.txt diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..24236dd --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,30 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.6.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + - id: check-merge-conflict + - id: mixed-line-ending + args: [--fix=lf] + + - repo: https://github.com/dnephin/pre-commit-golang + rev: v0.5.1 + hooks: + - id: go-fmt + + - repo: local + hooks: + - id: go-vet-mod + name: go vet (module) + entry: go vet ./... + language: system + types: [go] + pass_filenames: false + - id: go-test-mod + name: go test (module) + entry: go test ./... + language: system + types: [go] + pass_filenames: false diff --git a/.woodpecker/build.yaml b/.woodpecker/build.yaml new file mode 100644 index 0000000..c8e553d --- /dev/null +++ b/.woodpecker/build.yaml @@ -0,0 +1,30 @@ +when: + - event: pull_request + +steps: + - 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-w10k + 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 + backend_options: + kubernetes: + serviceAccountName: default + resources: + requests: + memory: 512Mi + cpu: 1 + limits: + memory: 2Gi + cpu: 2 diff --git a/.woodpecker/lint.yaml b/.woodpecker/lint.yaml new file mode 100644 index 0000000..dffd4d5 --- /dev/null +++ b/.woodpecker/lint.yaml @@ -0,0 +1,18 @@ +when: + - event: pull_request + +steps: + - name: lint + image: golangci/golangci-lint:v2.13.1 + commands: + - golangci-lint run ./... + backend_options: + kubernetes: + serviceAccountName: default + resources: + requests: + memory: 512Mi + cpu: 1 + limits: + memory: 2Gi + cpu: 2 diff --git a/.woodpecker/pre-commit.yaml b/.woodpecker/pre-commit.yaml new file mode 100644 index 0000000..a7c86a9 --- /dev/null +++ b/.woodpecker/pre-commit.yaml @@ -0,0 +1,30 @@ +when: + - event: pull_request + +steps: + - name: pre-commit + 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-w10k + 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: + - uvx pre-commit run --all-files + backend_options: + kubernetes: + serviceAccountName: default + resources: + requests: + memory: 512Mi + cpu: 1 + limits: + memory: 2Gi + cpu: 2 diff --git a/.woodpecker/release.yaml b/.woodpecker/release.yaml new file mode 100644 index 0000000..fd84368 --- /dev/null +++ b/.woodpecker/release.yaml @@ -0,0 +1,156 @@ +when: + - event: tag + ref: refs/tags/v* + +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-w10k + 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 + + - 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-w10k + 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} + - | + for osarch in linux/amd64 linux/arm64 darwin/amd64 darwin/arm64; do + os="$${osarch%/*}"; arch="$${osarch#*/}" + CGO_ENABLED=0 GOOS="$$os" GOARCH="$$arch" \ + go build -ldflags="-s -w -X main.version=${CI_COMMIT_TAG}" \ + -o "w10k-$${os}-$${arch}" . + done + depends_on: [test] + backend_options: + kubernetes: + serviceAccountName: default + resources: + requests: + memory: 512Mi + cpu: 1 + limits: + memory: 2Gi + cpu: 2 + + - 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 + + - 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") + 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 in $$REPO; skipping" + continue + fi + 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 + + - 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 + 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}" + ASSETS="w10k-linux-amd64 w10k-linux-arm64 w10k-darwin-amd64 w10k-darwin-arm64 $$(ls dist/*.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/.woodpecker/test.yaml b/.woodpecker/test.yaml new file mode 100644 index 0000000..d894aba --- /dev/null +++ b/.woodpecker/test.yaml @@ -0,0 +1,30 @@ +when: + - event: pull_request + +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-w10k + 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 -v -race ./... + backend_options: + kubernetes: + serviceAccountName: default + resources: + requests: + memory: 512Mi + cpu: 1 + limits: + memory: 2Gi + cpu: 2 diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..601b4f2 --- /dev/null +++ b/Makefile @@ -0,0 +1,57 @@ +BINARY := w10k +DIST := dist +VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo dev) +GOFLAGS := -ldflags="-s -w -X main.version=$(VERSION)" +OS ?= $(shell go env GOOS) +ARCH ?= $(shell go env GOARCH) + +.PHONY: all build test lint fmt pre-commit clean install rpm rpm-package patch minor major _tag + +all: build + +build: + CGO_ENABLED=0 GOOS=$(OS) GOARCH=$(ARCH) go build $(GOFLAGS) -o $(DIST)/$(BINARY) . + +test: + go test -v -race ./... + +lint: + golangci-lint run ./... + +fmt: + gofmt -w . + +pre-commit: + uvx pre-commit run --all-files + +clean: + rm -rf $(DIST) $(BINARY) + +install: + go install $(GOFLAGS) . + +rpm: build rpm-package + +rpm-package: + ./scripts/build-rpm.sh $(VERSION) + +_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) diff --git a/README.md b/README.md index 863d1df..141e2af 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,3 @@ # w10k -worktree-r10k: r10k/g10k replacement deploying Puppet environments and Puppetfile modules as sha-pinned git worktrees \ No newline at end of file +worktree-r10k: r10k/g10k replacement deploying Puppet environments and Puppetfile modules as sha-pinned git worktrees diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..22f5faf --- /dev/null +++ b/go.mod @@ -0,0 +1,13 @@ +module git.unkin.net/unkin/w10k + +go 1.25.7 + +require ( + github.com/spf13/cobra v1.10.2 + gopkg.in/yaml.v3 v3.0.1 +) + +require ( + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/spf13/pflag v1.0.9 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..47edb24 --- /dev/null +++ b/go.sum @@ -0,0 +1,13 @@ +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/deploy/config.go b/internal/deploy/config.go new file mode 100644 index 0000000..0943c71 --- /dev/null +++ b/internal/deploy/config.go @@ -0,0 +1,139 @@ +package deploy + +import ( + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + "gopkg.in/yaml.v3" +) + +type Config struct { + Cachedir string `yaml:"cachedir"` + Sources map[string]*Source `yaml:"sources"` + W10k struct { + GCGrace *time.Duration `yaml:"gc_grace"` + GitTimeout *time.Duration `yaml:"git_timeout"` + } `yaml:"w10k"` +} + +type Source struct { + Name string `yaml:"-"` + Remote string `yaml:"remote"` + Basedir string `yaml:"basedir"` + PrefixRaw any `yaml:"prefix"` + IgnoreBranchPrefixes []string `yaml:"ignore_branch_prefixes"` + InvalidBranches string `yaml:"invalid_branches"` + Prefix string `yaml:"-"` +} + +func LoadConfig(path string) (*Config, error) { + b, err := os.ReadFile(path) + if err != nil { + return nil, err + } + return ParseConfig(b) +} + +func ParseConfig(b []byte) (*Config, error) { + var n yaml.Node + if err := yaml.Unmarshal(b, &n); err != nil { + return nil, err + } + stripSymbols(&n) + var c Config + if err := n.Decode(&c); err != nil { + return nil, err + } + if c.Cachedir == "" { + return nil, fmt.Errorf("cachedir is required") + } + if c.W10k.GCGrace != nil && *c.W10k.GCGrace < 0 { + return nil, fmt.Errorf("w10k.gc_grace must not be negative") + } + if c.W10k.GitTimeout != nil && *c.W10k.GitTimeout <= 0 { + return nil, fmt.Errorf("w10k.git_timeout must be positive") + } + if len(c.Sources) == 0 { + return nil, fmt.Errorf("no sources defined") + } + var err error + if c.Cachedir, err = filepath.Abs(c.Cachedir); err != nil { + return nil, err + } + for name, s := range c.Sources { + if !wordOnly.MatchString(name) { + return nil, fmt.Errorf("source %q: name must match \\w+", name) + } + s.Name = name + if s.Remote == "" || s.Basedir == "" { + return nil, fmt.Errorf("source %q: remote and basedir are required", name) + } + if s.Basedir, err = filepath.Abs(s.Basedir); err != nil { + return nil, err + } + switch p := s.PrefixRaw.(type) { + case nil: + case bool: + if p { + s.Prefix = name + } + case string: + s.Prefix = p + default: + return nil, fmt.Errorf("source %q: prefix must be a bool or string", name) + } + s.InvalidBranches = strings.TrimPrefix(s.InvalidBranches, ":") + switch s.InvalidBranches { + case "": + s.InvalidBranches = "correct_and_warn" + case "correct_and_warn", "correct", "error": + default: + return nil, fmt.Errorf("source %q: invalid_branches must be correct_and_warn, correct or error", name) + } + } + return &c, nil +} + +func stripSymbols(n *yaml.Node) { + if n.Kind == yaml.MappingNode { + for i := 0; i < len(n.Content); i += 2 { + n.Content[i].Value = strings.TrimPrefix(n.Content[i].Value, ":") + } + } + for _, c := range n.Content { + stripSymbols(c) + } +} + +var ( + wordOnly = regexp.MustCompile(`^\w+$`) + nonWord = regexp.MustCompile(`\W`) +) + +func (s *Source) Ignored(branch string) bool { + for _, p := range s.IgnoreBranchPrefixes { + if strings.HasPrefix(branch, p) { + return true + } + } + return false +} + +// EnvName applies prefix and invalid_branches handling; corrected reports a \W substitution. +func (s *Source) EnvName(branch string) (name string, corrected bool, err error) { + name = branch + if s.Prefix != "" { + name = s.Prefix + "_" + branch + } + if wordOnly.MatchString(name) { + return name, false, nil + } + if s.InvalidBranches == "error" { + return "", false, fmt.Errorf("branch %q is not a valid environment name", branch) + } + return nonWord.ReplaceAllString(name, "_"), true, nil +} diff --git a/internal/deploy/config_test.go b/internal/deploy/config_test.go new file mode 100644 index 0000000..dc52d9c --- /dev/null +++ b/internal/deploy/config_test.go @@ -0,0 +1,109 @@ +package deploy + +import ( + "testing" + "time" +) + +func TestParseConfigSymbolKeys(t *testing.T) { + c, err := ParseConfig([]byte(` +:cachedir: '/var/cache/w10k' +:sources: + :unkin: + remote: 'https://git.unkin.net/unkin/puppet-prod.git' + basedir: '/etc/puppetlabs/code/environments' +`)) + if err != nil { + t.Fatal(err) + } + s := c.Sources["unkin"] + if c.Cachedir != "/var/cache/w10k" || s == nil || s.Name != "unkin" || s.Remote != "https://git.unkin.net/unkin/puppet-prod.git" || s.Basedir != "/etc/puppetlabs/code/environments" { + t.Fatalf("unexpected config %+v %+v", c, s) + } + if s.Prefix != "" || s.InvalidBranches != "correct_and_warn" { + t.Fatalf("defaults wrong: %+v", s) + } +} + +func TestParseConfigOptions(t *testing.T) { + c, err := ParseConfig([]byte(` +cachedir: /c +w10k: + git_timeout: 90s +sources: + a: + remote: r + basedir: /a + prefix: true + ignore_branch_prefixes: [wip/, tmp] + invalid_branches: ':error' + b: + remote: r + basedir: /b + prefix: custom + invalid_branches: correct +`)) + if err != nil { + t.Fatal(err) + } + a, b := c.Sources["a"], c.Sources["b"] + if c.W10k.GitTimeout == nil || *c.W10k.GitTimeout != 90*time.Second { + t.Fatalf("git_timeout: %v", c.W10k.GitTimeout) + } + if a.Prefix != "a" || a.InvalidBranches != "error" || len(a.IgnoreBranchPrefixes) != 2 { + t.Fatalf("a: %+v", a) + } + if b.Prefix != "custom" || b.InvalidBranches != "correct" { + t.Fatalf("b: %+v", b) + } +} + +func TestParseConfigErrors(t *testing.T) { + for name, in := range map[string]string{ + "no cachedir": "sources: {a: {remote: r, basedir: /b}}", + "no sources": "cachedir: /c", + "zero git_timeout": "cachedir: /c\nw10k: {git_timeout: 0s}\nsources: {a: {remote: r, basedir: /b}}", + "no remote": "cachedir: /c\nsources: {a: {basedir: /b}}", + "bad prefix": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, prefix: [x]}}", + "bad invalid": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, invalid_branches: nope}}", + "bad source name": "cachedir: /c\nsources: {a-b: {remote: r, basedir: /b}}", + } { + if _, err := ParseConfig([]byte(in)); err == nil { + t.Errorf("%s: expected error", name) + } + } +} + +func TestEnvName(t *testing.T) { + cases := []struct { + src Source + branch string + want string + corrected bool + err bool + }{ + {Source{InvalidBranches: "correct_and_warn"}, "develop", "develop", false, false}, + {Source{InvalidBranches: "correct_and_warn"}, "benvin/foo-bar", "benvin_foo_bar", true, false}, + {Source{InvalidBranches: "correct_and_warn"}, "release/1.2.3", "release_1_2_3", true, false}, + {Source{InvalidBranches: "correct"}, "a.b", "a_b", true, false}, + {Source{InvalidBranches: "error"}, "benvin/foo", "", false, true}, + {Source{InvalidBranches: "error"}, "ok_name", "ok_name", false, false}, + {Source{Prefix: "unkin", InvalidBranches: "correct_and_warn"}, "develop", "unkin_develop", false, false}, + {Source{Prefix: "unkin", InvalidBranches: "correct_and_warn"}, "a/b", "unkin_a_b", true, false}, + } + for _, c := range cases { + got, corrected, err := c.src.EnvName(c.branch) + if (err != nil) != c.err || got != c.want || corrected != c.corrected { + t.Errorf("EnvName(%q, %+v) = %q, %v, %v; want %q, %v, err=%v", c.branch, c.src, got, corrected, err, c.want, c.corrected, c.err) + } + } +} + +func TestIgnored(t *testing.T) { + s := Source{IgnoreBranchPrefixes: []string{"wip/", "tmp"}} + for b, want := range map[string]bool{"wip/x": true, "tmpfoo": true, "develop": false, "x/wip/": false} { + if s.Ignored(b) != want { + t.Errorf("Ignored(%q) != %v", b, want) + } + } +} diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go new file mode 100644 index 0000000..0fdbb21 --- /dev/null +++ b/internal/deploy/deploy.go @@ -0,0 +1,862 @@ +package deploy + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log" + "maps" + "os" + "path/filepath" + "regexp" + "runtime/debug" + "slices" + "sort" + "strings" + "sync" + "syscall" + "time" +) + +const ( + markerFile = ".g10k-deploy.json" + gcStateFile = "gc-state.json" + asideTag = ".w10k-old-" + gcTag = ".gc-" +) + +var ( + envRefspecs = []string{"+refs/heads/*:refs/heads/*"} + modFetchOpts = []string{"-c", "protocol.file.allow=never"} + modRefspecs = []string{"+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*", "+HEAD:refs/w10k/HEAD"} + unsafeChars = regexp.MustCompile(`[^A-Za-z0-9._-]`) + gcLeftover = regexp.MustCompile(`\.gc-[A-Z2-7]{26}$`) +) + +type Deployer struct { + runGit func(ctx context.Context, dir string, args ...string) (string, error) + cfg *Config + grace time.Duration + gitTimeout time.Duration + now func() time.Time + sem chan struct{} + mu sync.Mutex + flights map[string]*flight + wtLocks sync.Map +} + +type flight struct { + done chan struct{} + val string + err error +} + +type deployResult struct { + Name string `json:"name"` + Signature string `json:"signature"` + StartedAt time.Time `json:"started_at"` + FinishedAt time.Time `json:"finished_at"` + DeploySuccess bool `json:"deploy_success"` + PuppetfileChecksum string `json:"puppetfile_checksum"` + GitDir string `json:"git_dir"` + GitURL string `json:"git_url"` + Modules []string `json:"modules"` +} + +type resolved struct { + path string + dir string + key string +} + +func New(cfg *Config, jobs int, grace time.Duration) *Deployer { + if jobs < 1 { + jobs = 1 + } + gt := defaultGitTimeout + if cfg.W10k.GitTimeout != nil { + gt = *cfg.W10k.GitTimeout + } + return &Deployer{runGit: runGit, cfg: cfg, grace: grace, gitTimeout: gt, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}} +} + +func (d *Deployer) once(key string, fn func() (string, error)) (string, error) { + d.mu.Lock() + f, ok := d.flights[key] + if !ok { + f = &flight{done: make(chan struct{})} + d.flights[key] = f + } + d.mu.Unlock() + if !ok { + func() { + defer close(f.done) + defer recoverErr(&f.err, key) + f.val, f.err = fn() + }() + } + <-f.done + return f.val, f.err +} + +func (d *Deployer) limit(fn func() error) error { + d.sem <- struct{}{} + defer func() { <-d.sem }() + return fn() +} + +func (d *Deployer) path(parts ...string) string { + return filepath.Join(append([]string{d.cfg.Cachedir}, parts...)...) +} + +func (d *Deployer) srcMirror(s *Source) string { return d.path("sources", s.Name+".git") } +func (d *Deployer) srcWorktrees(s *Source) string { return d.path("worktrees", s.Name) } + +func shortHash(s string) string { + sum := sha256.Sum256([]byte(s)) + return hex.EncodeToString(sum[:8]) +} + +func urlKey(url string) string { + k := unsafeChars.ReplaceAllString(url, "_") + if len(k) > 64 { + k = k[len(k)-64:] + } + return k + "-" + shortHash(url) +} + +// doneFile is the out-of-tree completion marker for a cache dir; a branch can commit anything inside its own worktree. +func (d *Deployer) doneFile(dir string) string { + rel, _ := filepath.Rel(d.cfg.Cachedir, dir) + return d.path("state", rel+".done") +} + +func (d *Deployer) complete(dir string) bool { + _, err := os.Stat(d.doneFile(dir)) + _, derr := os.Stat(dir) + return err == nil && derr == nil +} + +func (d *Deployer) markDone(dir string, b []byte) error { + done := d.doneFile(dir) + if err := os.MkdirAll(filepath.Dir(done), 0o755); err != nil { + return err + } + return writeAtomic(done, b) +} + +// discard unmarks dir, renames it aside atomically and only then deletes it, so an interrupted GC never leaves a reusable half-deleted dir. +func (d *Deployer) discard(ctx context.Context, mirror, dir string) error { + if err := os.Remove(d.doneFile(dir)); err != nil && !os.IsNotExist(err) { + return err + } + gc := dir + gcTag + rand.Text() + if mirror == "" { + if err := os.Rename(dir, gc); err != nil { + return err + } + return os.RemoveAll(gc) + } + if _, err := d.git(ctx, mirror, "worktree", "move", "--", dir, gc); err != nil { + if err := os.Rename(dir, gc); err != nil { + return err + } + } + return d.removeWorktree(ctx, mirror, gc) +} + +func recoverErr(err *error, what string) { + if r := recover(); r != nil { + log.Printf("%s: panic: %v\n%s", what, r, debug.Stack()) + *err = fmt.Errorf("panic: %v", r) + } +} + +// Lock takes an exclusive flock on the cachedir, released by the returned func. +func (d *Deployer) Lock() (func(), error) { + if err := os.MkdirAll(d.cfg.Cachedir, 0o755); err != nil { + return nil, err + } + f, err := os.OpenFile(d.path(".lock"), os.O_CREATE|os.O_RDWR, 0o644) + if err != nil { + return nil, err + } + if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil { + _ = f.Close() + return nil, err + } + return func() { _ = f.Close() }, nil +} + +func (d *Deployer) Sources() []*Source { + var out []*Source + for _, s := range d.cfg.Sources { + out = append(out, s) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out +} + +func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) error { + want := map[string]bool{} + for _, e := range only { + want[e] = true + } + found := map[string]bool{} + var errs []error + for _, s := range d.Sources() { + if err := d.deploySource(ctx, s, want, found, modules); err != nil { + errs = append(errs, fmt.Errorf("source %s: %w", s.Name, err)) + } + } + for e := range want { + if !found[e] { + errs = append(errs, fmt.Errorf("environment %s not found", e)) + } + } + errs = append(errs, d.gc(ctx, len(only) == 0)) + return errors.Join(errs...) +} + +type envRef struct{ branch, sha string } + +func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envRef, []error) { + all, err := d.branches(ctx, d.srcMirror(s)) + if err != nil { + return nil, []error{err} + } + names := make([]string, 0, len(all)) + for b := range all { + names = append(names, b) + } + sort.Strings(names) + claims := map[string][]string{} + exact := map[string]string{} + var errs []error + for _, b := range names { + if s.Ignored(b) { + continue + } + name, corrected, err := s.EnvName(b) + if err != nil { + errs = append(errs, err) + continue + } + if !corrected { + exact[name] = b + } + claims[name] = append(claims[name], b) + } + envs := map[string]envRef{} + for _, name := range slices.Sorted(maps.Keys(claims)) { + bs := claims[name] + win, isExact := exact[name] + if !isExact && len(bs) == 1 { + win = bs[0] + } + if win == "" { + errs = append(errs, fmt.Errorf("branches %s all correct to environment %s, skipped", strings.Join(bs, ", "), name)) + continue + } + for _, b := range bs { + if b != win { + errs = append(errs, fmt.Errorf("branch %s collides with environment %s, skipped", b, name)) + } + } + if !isExact && s.InvalidBranches == "correct_and_warn" { + log.Printf("warning: branch %s deployed as environment %s", win, name) + } + envs[name] = envRef{win, all[win]} + } + return envs, errs +} + +func (d *Deployer) deploySource(ctx context.Context, s *Source, want, found map[string]bool, modules bool) error { + if err := d.syncMirror(ctx, d.srcMirror(s), s.Remote, nil, envRefspecs); err != nil { + return err + } + envs, errs := d.Environments(ctx, s) + if envs == nil { + return errors.Join(errs...) + } + full := len(want) == 0 + if err := os.MkdirAll(s.Basedir, 0o755); err != nil { + return err + } + var mu sync.Mutex + var wg sync.WaitGroup + for name, ref := range envs { + if !full && !want[name] { + continue + } + found[name] = true + wg.Add(1) + go func() { + defer wg.Done() + err := func() (err error) { + defer recoverErr(&err, "environment "+name) + return d.deployEnv(ctx, s, name, ref, modules) + }() + if err != nil { + mu.Lock() + errs = append(errs, fmt.Errorf("environment %s: %w", name, err)) + mu.Unlock() + } + }() + } + wg.Wait() + if full { + errs = append(errs, d.purge(s, envs)) + } + return errors.Join(errs...) +} + +func linkTarget(link string) string { + t, err := os.Readlink(link) + if err != nil { + return "" + } + if !filepath.IsAbs(t) { + t = filepath.Join(filepath.Dir(link), t) + } + return filepath.Clean(t) +} + +func (d *Deployer) owned(s *Source, link string) string { + if t := linkTarget(link); filepath.Dir(t) == d.srcWorktrees(s) { + return t + } + return "" +} + +func (d *Deployer) deployEnv(ctx context.Context, s *Source, name string, ref envRef, modules bool) error { + sha := ref.sha + link := filepath.Join(s.Basedir, name) + cur := d.owned(s, link) + if cur != "" && !modules && strings.HasPrefix(filepath.Base(cur), sha+"-") && d.complete(cur) { + return nil + } + pf, checksum, err := d.puppetfile(ctx, d.srcMirror(s), sha) + if err != nil { + return err + } + mods, err := d.installModules(ctx, pf) + if err != nil { + return err + } + h := sha256.New() + for _, m := range mods { + _, _ = fmt.Fprintf(h, "%s %s\n", m.path, m.key) + } + target := filepath.Join(d.srcWorktrees(s), sha+"-"+hex.EncodeToString(h.Sum(nil))[:12]) + if cur == target && d.complete(cur) { + return nil + } + if _, err := d.once("env:"+target, func() (string, error) { + if d.complete(target) { + return "", nil + } + started := d.now().UTC() + if err := d.checkout(ctx, s, sha, target, mods); err != nil { + return "", err + } + return "", d.prepare(s, ref, checksum, target, mods, started) + }); err != nil { + return err + } + if err := Swap(target, link); err != nil { + return err + } + log.Printf("environment %s -> %s", name, filepath.Base(target)) + return nil +} + +func (d *Deployer) puppetfile(ctx context.Context, mirror, sha string) (*Puppetfile, string, error) { + if _, err := d.git(ctx, mirror, "cat-file", "-e", sha+":Puppetfile"); err != nil { + return &Puppetfile{Moduledir: "modules"}, "", nil + } + src, err := d.git(ctx, mirror, "cat-file", "blob", sha+":Puppetfile") + if err != nil { + return nil, "", err + } + pf, err := ParsePuppetfile(src) + if err != nil { + return nil, "", fmt.Errorf("puppetfile: %w", err) + } + sum := sha256.Sum256([]byte(src)) + return pf, hex.EncodeToString(sum[:]), nil +} + +func (d *Deployer) installModules(ctx context.Context, pf *Puppetfile) ([]resolved, error) { + out := make([]resolved, len(pf.Modules)) + errs := make([]error, len(pf.Modules)) + var wg sync.WaitGroup + for i, m := range pf.Modules { + wg.Add(1) + go func() { + defer wg.Done() + var err error + defer func() { + if err != nil { + errs[i] = fmt.Errorf("module %s: %w", m.Name, err) + } + }() + defer recoverErr(&err, "module "+m.Name) + if m.Git != "" { + out[i], err = d.gitModule(ctx, m) + } else { + out[i], err = d.forgeModule(ctx, forgeURL(pf.Forge), m) + } + out[i].path = m.Path(pf) + }() + } + wg.Wait() + sort.Slice(out, func(i, j int) bool { return out[i].path < out[j].path }) + return out, errors.Join(errs...) +} + +func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) { + key := urlKey(m.Git) + mirror := d.path("git", key+".git") + if _, err := d.once("fetch:"+mirror, func() (string, error) { + return "", d.syncMirror(ctx, mirror, m.Git, modFetchOpts, modRefspecs) + }); err != nil { + return resolved{}, err + } + var cands []string + switch m.RefKind { + case "tag": + cands = []string{"refs/tags/" + m.Ref} + case "branch": + cands = []string{"refs/heads/" + m.Ref} + case "commit": + cands = []string{m.Ref} + case "ref": + cands = []string{"refs/heads/" + m.Ref, "refs/tags/" + m.Ref, m.Ref} + default: + cands = []string{"refs/w10k/HEAD"} + } + sha, err := d.revParse(ctx, mirror, cands...) + if err != nil { + return resolved{}, err + } + dir := d.path("modules", key, sha) + _, err = d.once("mod:"+dir, func() (string, error) { + if d.complete(dir) { + return "", nil + } + tmp := dir + ".tmp" + for _, p := range []string{tmp, dir} { + if err := d.removeWorktree(ctx, mirror, p); err != nil { + return "", err + } + } + if _, err := d.git(ctx, mirror, "worktree", "add", "--detach", "-q", "--", tmp, sha); err != nil { + return "", err + } + if _, err := d.git(ctx, mirror, "worktree", "move", "--", tmp, dir); err != nil { + return "", err + } + return "", d.markDone(dir, nil) + }) + return resolved{dir: dir, key: "git " + m.Git + " " + sha}, err +} + +func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (resolved, error) { + slug := m.Owner + "-" + m.Name + version := m.Version + if version == "" { + v, err := d.once("latest:"+base+" "+slug, func() (string, error) { + var v string + err := d.limit(func() (err error) { v, err = forgeLatest(ctx, base, slug); return err }) + return v, err + }) + if err != nil { + return resolved{}, err + } + version = v + } + release := slug + "-" + version + dir := d.path("forge", release+"-"+shortHash(base)) + _, err := d.once("forge:"+dir, func() (string, error) { + if d.complete(dir) { + return "", nil + } + if err := os.RemoveAll(dir); err != nil { + return "", err + } + if err := d.limit(func() error { return forgeInstall(ctx, base, release, dir) }); err != nil { + return "", err + } + return "", d.markDone(dir, nil) + }) + return resolved{dir: dir, key: "forge " + base + " " + release}, err +} + +func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string, mods []resolved) error { + mirror := d.srcMirror(s) + if err := os.Remove(d.doneFile(target)); err != nil && !os.IsNotExist(err) { + return err + } + if err := d.removeWorktree(ctx, mirror, target); err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + if _, err := d.git(ctx, mirror, "worktree", "add", "--detach", "-q", "--", target, sha); err != nil { + return err + } + root, err := os.OpenRoot(target) + if err != nil { + return err + } + defer func() { _ = root.Close() }() + for _, mod := range mods { + if err := linkModule(root, mod.path, mod.dir); err != nil { + return err + } + } + return nil +} + +// linkModule creates rel -> dir inside root; os.Root refuses any committed symlink that leads outside. +func linkModule(root *os.Root, rel, dir string) error { + if !filepath.IsLocal(rel) { + return fmt.Errorf("module path %q escapes the environment", rel) + } + if err := root.MkdirAll(filepath.Dir(rel), 0o755); err != nil { + return fmt.Errorf("module path %s: %w", rel, err) + } + if err := root.RemoveAll(rel); err != nil { + return fmt.Errorf("module path %s: %w", rel, err) + } + return root.Symlink(dir, rel) +} + +// prepare runs last before a worktree can be swapped in; its out-of-tree done file marks the worktree complete. +func (d *Deployer) prepare(s *Source, ref envRef, checksum, target string, mods []resolved, started time.Time) error { + r := deployResult{ + Name: ref.branch, + Signature: ref.sha, + StartedAt: started, + FinishedAt: d.now().UTC(), + DeploySuccess: true, + PuppetfileChecksum: checksum, + GitDir: d.srcMirror(s), + GitURL: s.Remote, + Modules: []string{}, + } + for _, m := range mods { + r.Modules = append(r.Modules, m.dir) + } + b, err := json.MarshalIndent(r, "", " ") + if err != nil { + return err + } + b = append(b, '\n') + if err := writeMarker(target, b); err != nil { + return err + } + return d.markDone(target, b) +} + +// writeMarker replaces whatever the branch committed at the marker paths without following it. +func writeMarker(dir string, b []byte) error { + root, err := os.OpenRoot(dir) + if err != nil { + return err + } + defer func() { _ = root.Close() }() + tmp := markerFile + ".tmp" + if err := root.RemoveAll(tmp); err != nil { + return err + } + f, err := root.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL|syscall.O_NOFOLLOW, 0o644) + if err != nil { + return err + } + if _, err := f.Write(b); err != nil { + _ = f.Close() + return err + } + if err := f.Close(); err != nil { + return err + } + if err := root.RemoveAll(markerFile); err != nil { + return err + } + return root.Rename(tmp, markerFile) +} + +func writeAtomic(p string, b []byte) error { + tmp := p + ".tmp" + if err := os.WriteFile(tmp, b, 0o644); err != nil { + return err + } + return os.Rename(tmp, p) +} + +// Swap points link at target via a temporary symlink renamed over it; a real directory is moved aside for GC. +func Swap(target, link string) error { + dir, base := filepath.Dir(link), filepath.Base(link) + tmp := filepath.Join(dir, "."+base+".w10k") + _ = os.Remove(tmp) + if err := os.Symlink(target, tmp); err != nil { + return err + } + if fi, err := os.Lstat(link); err == nil && fi.IsDir() { + aside := filepath.Join(dir, fmt.Sprintf(".%s%s%d", base, asideTag, time.Now().UnixNano())) + if err := os.Rename(link, aside); err != nil { + return err + } + } + return os.Rename(tmp, link) +} + +func (d *Deployer) purge(s *Source, envs map[string]envRef) error { + entries, err := os.ReadDir(s.Basedir) + if err != nil { + return err + } + for _, e := range entries { + if _, ok := envs[e.Name()]; ok { + continue + } + link := filepath.Join(s.Basedir, e.Name()) + if d.owned(s, link) == "" { + continue + } + if err := os.Remove(link); err != nil { + return err + } + log.Printf("environment %s removed", e.Name()) + } + return nil +} + +// Live returns env name -> worktree for every environment symlink owned by s. +func (d *Deployer) Live(s *Source) (map[string]string, error) { + entries, err := os.ReadDir(s.Basedir) + if os.IsNotExist(err) { + return nil, nil + } + if err != nil { + return nil, err + } + live := map[string]string{} + for _, e := range entries { + if t := d.owned(s, filepath.Join(s.Basedir, e.Name())); t != "" { + live[e.Name()] = t + } + } + return live, nil +} + +type gcRun struct { + d *Deployer + ctx context.Context + marks map[string]time.Time + seen map[string]bool + errs []error +} + +// collect marks p on first sight and removes it only once a previous run's mark is older than the grace period. +func (g *gcRun) collect(p string, remove func() error) { + g.seen[p] = true + t, ok := g.marks[p] + if !ok { + g.marks[p] = g.d.now() + log.Printf("gc: marked %s", p) + return + } + if g.d.now().Sub(t) < g.d.grace { + return + } + if err := remove(); err != nil { + g.errs = append(g.errs, err) + return + } + delete(g.marks, p) + log.Printf("gc: removed %s", p) +} + +func (g *gcRun) sweep(mirror, dir string, live map[string]bool, remove func(string) error) { + entries, err := os.ReadDir(dir) + if err != nil { + if !os.IsNotExist(err) { + g.errs = append(g.errs, err) + } + return + } + for _, e := range entries { + p := filepath.Join(dir, e.Name()) + if gcLeftover.MatchString(e.Name()) { + if err := os.RemoveAll(p); err != nil { + g.errs = append(g.errs, err) + } + continue + } + if live[p] { + continue + } + g.collect(p, func() error { return remove(p) }) + } + if mirror != "" { + if _, err := os.Stat(mirror); err == nil { + if _, err := g.d.git(g.ctx, mirror, "worktree", "prune"); err != nil { + g.errs = append(g.errs, err) + } + } + } +} + +func (d *Deployer) GC(ctx context.Context) error { return d.gc(ctx, true) } + +// gc drops the mark of everything live this run; only a sweep may add marks or delete, and only where every live set it needs was computed. +func (d *Deployer) gc(ctx context.Context, sweep bool) (err error) { + g := &gcRun{d: d, ctx: ctx, marks: d.loadMarks(), seen: map[string]bool{}} + defer func() { + for p := range g.marks { + if !g.seen[p] { + delete(g.marks, p) + } + } + err = errors.Join(append(g.errs, d.saveMarks(g.marks))...) + }() + + liveEnv := map[string]bool{} + var ok []*Source + for _, s := range d.Sources() { + live, err := d.Live(s) + if err != nil { + g.errs = append(g.errs, fmt.Errorf("gc: %w", err)) + continue + } + ok = append(ok, s) + for _, t := range live { + liveEnv[t] = true + } + } + if !sweep { + liveMod, err := d.moduleRefs(liveEnv) + if err != nil || len(g.errs) > 0 { + g.errs = append(g.errs, err) + return nil + } + for p := range g.marks { + g.seen[p] = !liveEnv[p] && !liveMod[p] + } + return nil + } + + for _, s := range ok { + mirror := d.srcMirror(s) + g.sweep(mirror, d.srcWorktrees(s), liveEnv, func(p string) error { + if err := os.Remove(d.doneFile(p)); err != nil && !os.IsNotExist(err) { + return err + } + return d.removeWorktree(ctx, mirror, p) + }) + entries, _ := os.ReadDir(s.Basedir) + for _, e := range entries { + if p := filepath.Join(s.Basedir, e.Name()); strings.HasPrefix(e.Name(), ".") && strings.Contains(e.Name(), asideTag) { + g.collect(p, func() error { return os.RemoveAll(p) }) + } + } + } + if len(ok) < len(d.cfg.Sources) { + return nil + } + liveMod, err := d.moduleRefs(liveEnv) + if err != nil { + g.errs = append(g.errs, err) + } else { + keys, _ := os.ReadDir(d.path("modules")) + for _, k := range keys { + mirror := d.path("git", k.Name()+".git") + g.sweep(mirror, d.path("modules", k.Name()), liveMod, func(p string) error { return d.discard(ctx, mirror, p) }) + } + g.sweep("", d.path("forge"), liveMod, func(p string) error { return d.discard(ctx, "", p) }) + } + return nil +} + +// loadMarks treats an unreadable state file as empty, which only delays deletion. +func (d *Deployer) loadMarks() map[string]time.Time { + marks := map[string]time.Time{} + b, err := os.ReadFile(d.path(gcStateFile)) + if err == nil { + err = json.Unmarshal(b, &marks) + } + if err != nil && !os.IsNotExist(err) { + log.Printf("gc: discarding unreadable %s: %v", gcStateFile, err) + marks = map[string]time.Time{} + } + return marks +} + +func (d *Deployer) saveMarks(marks map[string]time.Time) error { + b, err := json.MarshalIndent(marks, "", " ") + if err != nil { + return err + } + return writeAtomic(d.path(gcStateFile), b) +} + +// moduleRefs returns every module dir referenced by any source's env worktree on disk or by any link in a configured basedir. +func (d *Deployer) moduleRefs(liveEnv map[string]bool) (map[string]bool, error) { + wts := map[string]bool{} + for p := range liveEnv { + wts[p] = true + } + for _, s := range d.Sources() { + entries, err := os.ReadDir(s.Basedir) + if err != nil && !os.IsNotExist(err) { + return nil, err + } + for _, e := range entries { + if t := linkTarget(filepath.Join(s.Basedir, e.Name())); filepath.Dir(filepath.Dir(t)) == d.path("worktrees") { + wts[t] = true + } + } + } + srcs, err := os.ReadDir(d.path("worktrees")) + if err != nil && !os.IsNotExist(err) { + return nil, err + } + for _, src := range srcs { + dir := d.path("worktrees", src.Name()) + entries, err := os.ReadDir(dir) + if err != nil { + return nil, err + } + for _, e := range entries { + if p := filepath.Join(dir, e.Name()); !wts[p] { + wts[p] = false + } + } + } + refs := map[string]bool{} + for p, live := range wts { + b, err := os.ReadFile(d.doneFile(p)) + if os.IsNotExist(err) && !live { + continue + } + var r deployResult + if err == nil { + err = json.Unmarshal(b, &r) + } + if err != nil { + return nil, fmt.Errorf("gc: module refs of %s: %w", p, err) + } + for _, m := range r.Modules { + refs[m] = true + } + } + return refs, nil +} diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go new file mode 100644 index 0000000..c9acd44 --- /dev/null +++ b/internal/deploy/deploy_test.go @@ -0,0 +1,1058 @@ +package deploy + +import ( + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "net/http/cgi" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +func mkdirs(t *testing.T, paths ...string) { + t.Helper() + for _, p := range paths { + if err := os.MkdirAll(p, 0o755); err != nil { + t.Fatal(err) + } + } +} + +func TestSwapOverSymlinkAbsolute(t *testing.T) { + dir := t.TempDir() + a, b := filepath.Join(dir, "cache", "a"), filepath.Join(dir, "cache", "b") + mkdirs(t, a, b, filepath.Join(dir, "envs")) + link := filepath.Join(dir, "envs", "develop") + for _, target := range []string{a, b, b} { + if err := Swap(target, link); err != nil { + t.Fatal(err) + } + if got, err := os.Readlink(link); err != nil || got != target { + t.Fatalf("link -> %q (%v), want absolute %q", got, err, target) + } + } + if _, err := os.Stat(a); err != nil { + t.Fatal("swap must not touch the previous target") + } + if entries, _ := os.ReadDir(filepath.Dir(link)); len(entries) != 1 { + t.Fatalf("leftover temp files: %v", entries) + } +} + +func TestSwapDirectoryCutover(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "cache", "a") + link := filepath.Join(dir, "envs", "develop") + mkdirs(t, target, link) + if err := os.WriteFile(filepath.Join(link, "site.pp"), []byte("old"), 0o644); err != nil { + t.Fatal(err) + } + if err := Swap(target, link); err != nil { + t.Fatal(err) + } + if got, _ := os.Readlink(link); got != target { + t.Fatalf("link -> %q", got) + } + matches, _ := filepath.Glob(filepath.Join(dir, "envs", ".develop"+asideTag+"*", "site.pp")) + if len(matches) != 1 { + t.Fatalf("old g10k directory should be moved aside intact, got %v", matches) + } +} + +func TestGCGrace(t *testing.T) { + root := t.TempDir() + cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": {Name: "s", Basedir: filepath.Join(root, "envs")}}} + clock := time.Unix(1_700_000_000, 0) + gc := func() { + d := New(cfg, 1, 10*time.Minute) + d.now = func() time.Time { return clock } + if err := d.GC(context.Background()); err != nil { + t.Fatal(err) + } + } + d := New(cfg, 1, 0) + old, cur := filepath.Join(d.srcWorktrees(cfg.Sources["s"]), "old"), filepath.Join(d.srcWorktrees(cfg.Sources["s"]), "cur") + aside := filepath.Join(cfg.Sources["s"].Basedir, ".develop"+asideTag+"1") + mkdirs(t, old, cur, aside) + mkdirs(t, filepath.Dir(d.doneFile(old))) + for _, p := range []string{old, cur} { + if err := os.WriteFile(d.doneFile(p), []byte(`{"modules":[]}`), 0o644); err != nil { + t.Fatal(err) + } + } + if err := Swap(cur, filepath.Join(cfg.Sources["s"].Basedir, "develop")); err != nil { + t.Fatal(err) + } + + gc() + if !exists(old) || !exists(aside) { + t.Fatal("first sight must only mark") + } + clock = clock.Add(9 * time.Minute) + gc() + if !exists(old) || !exists(aside) { + t.Fatal("inside grace must keep") + } + if err := Swap(old, filepath.Join(cfg.Sources["s"].Basedir, "develop")); err != nil { + t.Fatal(err) + } + gc() + clock = clock.Add(2 * time.Minute) + gc() + if !exists(old) || exists(aside) { + t.Fatal("re-referenced worktree must be unmarked; aside dir past grace removed") + } + if !exists(cur) { + t.Fatal("newly unreferenced worktree must get a fresh mark, not inherit an old one") + } + clock = clock.Add(11 * time.Minute) + gc() + if exists(cur) || !exists(old) { + t.Fatal("past grace must remove only the unreferenced worktree") + } +} + +func TestLockExcludes(t *testing.T) { + d := New(&Config{Cachedir: t.TempDir()}, 1, 0) + unlock, err := d.Lock() + if err != nil { + t.Fatal(err) + } + got := make(chan struct{}) + go func() { + u, err := d.Lock() + if err == nil { + u() + } + close(got) + }() + select { + case <-got: + t.Fatal("second lock acquired while first held") + case <-time.After(100 * time.Millisecond): + } + unlock() + select { + case <-got: + case <-time.After(5 * time.Second): + t.Fatal("second lock never acquired") + } +} + +func gitT(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", append([]string{"-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false"}, args...)...) + cmd.Dir = dir + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + return strings.TrimSpace(string(out)) +} + +func commit(t *testing.T, dir string, files map[string]string) string { + t.Helper() + for p, c := range files { + full := filepath.Join(dir, p) + if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(full, []byte(c), 0o644); err != nil { + t.Fatal(err) + } + } + gitT(t, dir, "add", "-A") + gitT(t, dir, "commit", "-q", "-m", "c") + return gitT(t, dir, "rev-parse", "HEAD") +} + +func newRepo(t *testing.T, dir string) { + t.Helper() + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + gitT(t, dir, "init", "-q", "-b", "main") +} + +func readMarker(t *testing.T, env string) deployResult { + t.Helper() + b, err := os.ReadFile(filepath.Join(env, markerFile)) + if err != nil { + t.Fatal(err) + } + var m deployResult + if err := json.Unmarshal(b, &m); err != nil { + t.Fatal(err) + } + return m +} + +func exists(p string) bool { + _, err := os.Lstat(p) + return err == nil +} + +func dirCount(t *testing.T, p string) int { + t.Helper() + e, err := os.ReadDir(p) + if err != nil && !os.IsNotExist(err) { + t.Fatal(err) + } + return len(e) +} + +type fixture struct { + t *testing.T + root string + control string + mod string + modDir string + gitURL string + basedir string + cfg *Config + clock time.Time + forgeURL string + hit func(string) int +} + +func newFixture(t *testing.T) *fixture { + f := &fixture{t: t, root: t.TempDir(), clock: time.Unix(1_700_000_000, 0)} + var mu sync.Mutex + hits := map[string]int{} + forge := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + hits[r.URL.Path]++ + mu.Unlock() + switch r.URL.Path { + case "/v3/modules/acme-latest": + _, _ = fmt.Fprint(w, `{"current_release":{"version":"2.0.0"}}`) + case "/v3/files/acme-thing-1.0.0.tar.gz", "/v3/files/acme-latest-2.0.0.tar.gz": + top := strings.TrimSuffix(filepath.Base(r.URL.Path), ".tar.gz") + _, _ = w.Write(tarball(t, entry{name: top + "/metadata.json", body: `{"name":"` + top + `"}`, mode: 0o644})) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(forge.Close) + f.forgeURL = forge.URL + f.hit = func(p string) int { mu.Lock(); defer mu.Unlock(); return hits[p] } + + gitBin, err := exec.LookPath("git") + if err != nil { + t.Fatal(err) + } + gitSrv := httptest.NewServer(&cgi.Handler{Path: gitBin, Args: []string{"http-backend"}, Env: []string{"GIT_PROJECT_ROOT=" + f.root, "GIT_HTTP_EXPORT_ALL=1"}}) + t.Cleanup(gitSrv.Close) + f.gitURL = gitSrv.URL + + f.modDir = filepath.Join(f.root, "mod") + f.mod = f.url(f.modDir) + newRepo(t, f.modDir) + commit(t, f.modDir, map[string]string{"manifests/init.pp": "class bind {}\n"}) + gitT(t, f.modDir, "tag", "1.0") + + f.control = filepath.Join(f.root, "control") + newRepo(t, f.control) + f.basedir = filepath.Join(f.root, "code", "environments") + cfg, err := ParseConfig([]byte(fmt.Sprintf("cachedir: %s\nsources:\n unkin:\n remote: %s\n basedir: %s\n", filepath.Join(f.root, "code", "cache"), f.control, f.basedir))) + if err != nil { + t.Fatal(err) + } + f.cfg = cfg + return f +} + +// url serves a repo under f.root over git smart HTTP; module sources must be remote. +func (f *fixture) url(dir string) string { + rel, err := filepath.Rel(f.root, dir) + if err != nil { + f.t.Fatal(err) + } + return f.gitURL + "/" + filepath.ToSlash(rel) +} + +func (f *fixture) puppetfile() string { + return fmt.Sprintf(`forge '%s' +moduledir 'external_modules' +mod 'acme-thing', '1.0.0' +mod 'acme-latest', :latest +mod 'bind', + :git => '%s', + :tag => '1.0' +mod 'tracker', :git => '%s', :branch => 'main' +`, f.forgeURL, f.mod, f.mod) +} + +func (f *fixture) deployer() *Deployer { + d := New(f.cfg, 4, 10*time.Minute) + d.now = func() time.Time { return f.clock } + return d +} + +func (f *fixture) deploy(modules bool, only ...string) error { + return f.deployer().Deploy(context.Background(), only, modules) +} + +func (f *fixture) mustDeploy(modules bool) { + f.t.Helper() + if err := f.deploy(modules); err != nil { + f.t.Fatal(err) + } +} + +func (f *fixture) settle() { + f.t.Helper() + for range 2 { + f.clock = f.clock.Add(11 * time.Minute) + f.mustDeploy(false) + } +} + +func (f *fixture) env(name string) string { + return f.deployer().owned(f.cfg.Sources["unkin"], filepath.Join(f.basedir, name)) +} + +func (f *fixture) cache(parts ...string) string { + return filepath.Join(append([]string{f.cfg.Cachedir}, parts...)...) +} + +func (f *fixture) forgeDir(release string) string { + return f.cache("forge", release+"-"+shortHash(f.forgeURL)) +} + +func TestDeployIntegration(t *testing.T) { + f := newFixture(t) + sha1 := commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile(), "manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "branch", "benvin/foo-bar") + + f.mustDeploy(false) + main1, foo1 := f.env("main"), f.env("benvin_foo_bar") + if main1 == "" || main1 != foo1 || !strings.HasPrefix(filepath.Base(main1), sha1+"-") { + t.Fatalf("envs not deployed as shared sha worktree: main=%q foo=%q", main1, foo1) + } + if l, _ := os.Readlink(filepath.Join(f.basedir, "main")); !filepath.IsAbs(l) { + t.Fatalf("env link must be absolute: %s", l) + } + if l, _ := os.Readlink(filepath.Join(main1, "external_modules", "bind")); !filepath.IsAbs(l) { + t.Fatalf("module link must be absolute: %s", l) + } + if m := readMarker(t, main1); m.Signature != sha1 || !m.DeploySuccess || len(m.Modules) != 4 || len(m.PuppetfileChecksum) != 64 || m.GitURL != f.control { + t.Fatalf("deploy file %+v", m) + } + for _, p := range []string{"manifests/site.pp", "external_modules/thing/metadata.json", "external_modules/latest/metadata.json", "external_modules/bind/manifests/init.pp", "external_modules/tracker/manifests/init.pp"} { + if _, err := os.Stat(filepath.Join(f.basedir, "main", p)); err != nil { + t.Errorf("missing %s: %v", p, err) + } + } + if f.hit("/v3/files/acme-thing-1.0.0.tar.gz") != 1 || f.hit("/v3/modules/acme-latest") != 1 { + t.Fatal("forge modules should be fetched once") + } + if dirCount(t, f.cache("modules", urlKey(f.mod))) != 1 { + t.Fatal("tag and branch at the same sha should share one module worktree") + } + + f.mustDeploy(false) + if f.env("main") != main1 || f.hit("/v3/files/acme-thing-1.0.0.tar.gz") != 1 || f.hit("/v3/modules/acme-latest") != 1 { + t.Fatal("unchanged sha must be a no-op") + } + + sha2 := commit(t, f.control, map[string]string{"manifests/site.pp": "node default { }\n"}) + f.mustDeploy(false) + main2 := f.env("main") + if !strings.HasPrefix(filepath.Base(main2), sha2+"-") || f.env("benvin_foo_bar") != main1 { + t.Fatalf("moved branch: main=%s foo=%s", main2, f.env("benvin_foo_bar")) + } + + gitT(t, f.control, "branch", "-D", "benvin/foo-bar") + f.mustDeploy(false) + if exists(filepath.Join(f.basedir, "benvin_foo_bar")) { + t.Fatal("deleted branch must remove the env link") + } + if !exists(main1) { + t.Fatal("worktree must never be deleted in the run that unreferenced it") + } + f.settle() + if exists(main1) || dirCount(t, f.cache("worktrees", "unkin")) != 1 { + t.Fatal("unreferenced worktree must be GC'd after grace") + } + if wl := gitT(t, f.cache("sources", "unkin.git"), "worktree", "list"); strings.Contains(wl, filepath.Base(main1)) { + t.Fatalf("worktree not pruned:\n%s", wl) + } + + commit(t, f.modDir, map[string]string{"manifests/init.pp": "class tracker {}\n"}) + f.mustDeploy(false) + if f.env("main") != main2 { + t.Fatal("module branch move must not redeploy without --modules") + } + f.mustDeploy(true) + main3 := f.env("main") + if main3 == main2 { + t.Fatal("--modules should rebuild when a module ref moved") + } + f.settle() + if exists(main2) || dirCount(t, f.cache("modules", urlKey(f.mod))) != 2 { + t.Fatal("old env GC'd; bind (tag) and tracker (moved branch) are distinct module worktrees") + } + + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("forge '%s'\nmoduledir 'external_modules'\nmod 'acme-latest', :latest\n", f.forgeURL)}) + f.mustDeploy(false) + if dirCount(t, f.cache("modules", urlKey(f.mod))) != 2 || !exists(f.forgeDir("acme-thing-1.0.0")) { + t.Fatal("modules still referenced by a worktree awaiting GC must be kept") + } + f.settle() + f.settle() + if dirCount(t, f.cache("modules", urlKey(f.mod))) != 0 || exists(f.forgeDir("acme-thing-1.0.0")) || !exists(f.forgeDir("acme-latest-2.0.0")) { + t.Fatal("dropped modules must be GC'd, kept ones retained") + } + + if err := f.deploy(false, "nope"); err == nil || !strings.Contains(err.Error(), "nope not found") { + t.Fatalf("unknown env: %v", err) + } + if !exists(filepath.Join(f.basedir, "main")) { + t.Fatal("filtered deploy must not purge other envs") + } + + commit(t, f.control, map[string]string{"Puppetfile": "mod 'broken', :svn => 'x'\n"}) + if err := f.deploy(false); err == nil { + t.Fatal("bad Puppetfile must fail") + } + if f.env("main") == "" || !exists(f.env("main")) { + t.Fatal("failed build must leave the live env untouched") + } +} + +func TestInFlightCompileSurvivesSwap(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile(), "manifests/site.pp": "node default {}\n"}) + f.mustDeploy(false) + + resolved, err := os.Readlink(filepath.Join(f.basedir, "main")) + if err != nil { + t.Fatal(err) + } + var files []string + var walk func(string) + walk = func(dir string) { + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + p := filepath.Join(dir, e.Name()) + if fi, err := os.Stat(p); err == nil && fi.IsDir() { + walk(p) + } else if e.Name() != ".git" { + files = append(files, p) + } + } + } + walk(resolved) + joined := strings.Join(files, "\n") + for _, want := range []string{"manifests/site.pp", "external_modules/bind/manifests/init.pp", "external_modules/thing/metadata.json", markerFile} { + if !strings.Contains(joined, filepath.Join(resolved, want)) { + t.Fatalf("walk missed %s in:\n%s", want, joined) + } + } + + commit(t, f.control, map[string]string{"Puppetfile": "", "manifests/site.pp": "node default { }\n"}) + f.clock = f.clock.Add(time.Minute) + f.mustDeploy(false) + if f.env("main") == resolved { + t.Fatal("branch move must swap the env") + } + f.clock = f.clock.Add(8 * time.Minute) + f.mustDeploy(false) + for _, p := range files { + if _, err := os.ReadFile(p); err != nil { + t.Fatalf("in-flight compile lost %s: %v", p, err) + } + } + + f.clock = f.clock.Add(3 * time.Minute) + f.mustDeploy(false) + if exists(resolved) { + t.Fatal("old worktree must be removed once grace has passed") + } +} + +func TestGitURLOptionInjection(t *testing.T) { + f := newFixture(t) + pwned := filepath.Join(f.root, "pwned") + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'evil', :git => '--upload-pack=touch %s;'\n", pwned)}) + if err := f.deploy(false); err == nil { + t.Fatal("option-like :git must be rejected") + } + if exists(pwned) { + t.Fatal("injected --upload-pack ran") + } +} + +func TestInstallPathThroughCommittedSymlink(t *testing.T) { + f := newFixture(t) + victim := filepath.Join(f.root, "victim") + mkdirs(t, filepath.Join(victim, "bind", "keep")) + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'bind', :git => '%s', :tag => '1.0', :install_path => 'escape'\n", f.mod)}) + if err := os.Symlink(victim, filepath.Join(f.control, "escape")); err != nil { + t.Fatal(err) + } + gitT(t, f.control, "add", "-A") + gitT(t, f.control, "commit", "-q", "-m", "link") + if err := f.deploy(false); err == nil { + t.Fatal("install_path through a committed symlink must fail") + } + if !exists(filepath.Join(victim, "bind", "keep")) { + t.Fatal("deploy wrote outside the worktree") + } + if f.env("main") != "" { + t.Fatal("failed build must not go live") + } +} + +func TestNestedInstallPathSharedModule(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("forge '%s'\nmod 'acme-thing', '1.0.0'\n", f.forgeURL)}) + f.mustDeploy(false) + gitT(t, f.control, "checkout", "-q", "-b", "attacker") + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("forge '%s'\nmod 'acme-thing', '1.0.0'\nmod 'metadata', :git => '%s', :tag => '1.0', :install_path => 'modules/thing'\n", f.forgeURL, f.mod)}) + if err := f.deploy(false); err == nil { + t.Fatal("nested install_path must fail") + } + if exists(filepath.Join(f.forgeDir("acme-thing-1.0.0"), "metadata")) { + t.Fatal("shared forge cache dir mutated by another branch") + } +} + +func TestCommittedMarkerDoesNotCompleteWorktree(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{ + "Puppetfile": fmt.Sprintf("mod 'bind', :git => '%s', :tag => '1.0'\n", f.mod), + markerFile: `{"modules":[]}`, + "modules": "a file, so the module link fails", + }) + for range 2 { + if err := f.deploy(false); err == nil { + t.Fatal("broken build must fail") + } + if f.env("main") != "" { + t.Fatal("incomplete worktree went live") + } + } +} + +func TestMirrorKeyDistinctURLs(t *testing.T) { + f := newFixture(t) + other, victim := filepath.Join(f.root, "m_od"), filepath.Join(f.root, "m", "od") + if urlKey(f.url(other)) == urlKey(f.url(victim)) { + t.Fatal("distinct URLs share a mirror key") + } + newRepo(t, other) + commit(t, other, map[string]string{"manifests/init.pp": "class evil {}\n"}) + gitT(t, other, "tag", "1.0") + newRepo(t, victim) + commit(t, victim, map[string]string{"manifests/init.pp": "class good {}\n"}) + gitT(t, victim, "tag", "1.0") + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'x', :git => '%s', :tag => '1.0'\n", f.url(victim))}) + gitT(t, f.control, "checkout", "-q", "-b", "attacker") + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'x', :git => '%s', :tag => '1.0'\n", f.url(other))}) + for range 5 { + f.mustDeploy(true) + b, _ := os.ReadFile(filepath.Join(f.env("main"), "modules", "x", "manifests", "init.pp")) + if !strings.Contains(string(b), "good") { + t.Fatalf("main got another branch's module: %q", b) + } + } +} + +func TestForgeCacheKeyedByBase(t *testing.T) { + f := newFixture(t) + gitT(t, f.control, "checkout", "-q", "-b", "a") + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("forge '%s'\nmod 'acme-thing', '1.0.0'\n", f.forgeURL)}) + f.mustDeploy(false) + gitT(t, f.control, "checkout", "-q", "-b", "b") + commit(t, f.control, map[string]string{"Puppetfile": "forge 'http://127.0.0.1:1'\nmod 'acme-thing', '1.0.0'\n"}) + if err := f.deploy(false); err == nil { + t.Fatal("release cached from one forge was served for another") + } +} + +func TestJobsBoundGitProcesses(t *testing.T) { + f := newFixture(t) + var pf strings.Builder + for i := range 6 { + repo := filepath.Join(f.root, fmt.Sprintf("r%d", i)) + newRepo(t, repo) + commit(t, repo, map[string]string{"manifests/init.pp": "class m {}\n"}) + fmt.Fprintf(&pf, "mod 'm%d', :git => '%s'\n", i, f.url(repo)) + } + commit(t, f.control, map[string]string{"Puppetfile": pf.String()}) + for i := range 4 { + gitT(t, f.control, "branch", fmt.Sprintf("b%d", i)) + } + const jobs = 2 + var mu sync.Mutex + cur, peak := 0, 0 + d := New(f.cfg, jobs, 10*time.Minute) + d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) { + mu.Lock() + cur++ + peak = max(peak, cur) + mu.Unlock() + defer func() { mu.Lock(); cur--; mu.Unlock() }() + time.Sleep(time.Millisecond) + return runGit(ctx, dir, args...) + } + if err := d.Deploy(context.Background(), nil, true); err != nil { + t.Fatal(err) + } + if peak > jobs { + t.Fatalf("%d concurrent git processes with -j %d", peak, jobs) + } +} + +func TestCommittedMarkerTmpSymlinkWritesOutside(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + f.mustDeploy(false) + victim := filepath.Join(f.basedir, "main", "manifests", "site.pp") + + gitT(t, f.control, "checkout", "-q", "-b", "attacker") + if err := os.Symlink(victim, filepath.Join(f.control, markerFile+".tmp")); err != nil { + t.Fatal(err) + } + gitT(t, f.control, "add", "-f", "-A") + gitT(t, f.control, "commit", "-q", "-m", "link") + _ = f.deploy(false) + + if b, _ := os.ReadFile(victim); string(b) != "node default {}\n" { + t.Fatalf("branch overwrote a live env file via committed symlink:\n%s", b) + } +} + +func TestStalledGitRemoteFailsOnlyItsEnv(t *testing.T) { + f := newFixture(t) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = ln.Close() }) + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + t.Cleanup(func() { _ = c.Close() }) + } + }() + timeout := 2 * time.Second + f.cfg.W10k.GitTimeout = &timeout + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "slow") + commit(t, f.control, map[string]string{"Puppetfile": "mod 'slow', :git => 'http://" + ln.Addr().String() + "/x.git'\n"}) + done := make(chan error, 1) + go func() { done <- f.deploy(false) }() + select { + case err := <-done: + if err == nil || !strings.Contains(err.Error(), "environment slow") { + t.Fatalf("stalled remote must fail its env, got %v", err) + } + case <-time.After(20 * time.Second): + t.Fatal("deploy still blocked on a stalled :git remote after 20s") + } + if f.env("main") == "" || f.env("slow") != "" { + t.Fatalf("main=%q slow=%q", f.env("main"), f.env("slow")) + } +} + +func TestGCKeepsModulesOfRemovedSource(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'bind', :git => '%s', :tag => '1.0'\n", f.mod)}) + f.mustDeploy(false) + site := filepath.Join(f.basedir, "main", "modules", "bind", "manifests", "init.pp") + if !exists(site) { + t.Fatal("module not deployed") + } + other := filepath.Join(f.root, "other") + newRepo(t, other) + commit(t, other, map[string]string{"manifests/site.pp": "node default {}\n"}) + cfg, err := ParseConfig(fmt.Appendf(nil, "cachedir: %s\nsources:\n other:\n remote: %s\n basedir: %s\n", f.cfg.Cachedir, other, filepath.Join(f.root, "other-envs"))) + if err != nil { + t.Fatal(err) + } + f.cfg = cfg + f.settle() + if _, err := os.Stat(site); err != nil { + t.Fatalf("GC deleted a module still linked from a removed source's live env: %v", err) + } +} + +func TestPuppetfileLocalRepoRejected(t *testing.T) { + f := newFixture(t) + secret := filepath.Join(f.root, "secret") + newRepo(t, secret) + commit(t, secret, map[string]string{"manifests/init.pp": "# private\n"}) + for _, g := range []string{"file://" + secret, secret} { + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'loot', :git => '%s'\n", g)}) + if err := f.deploy(false); err == nil { + t.Fatalf(":git %s accepted", g) + } + if p := filepath.Join(f.basedir, "main", "modules", "loot", "manifests", "init.pp"); exists(p) { + t.Fatalf("untrusted Puppetfile cloned a local repo into the env: %s", p) + } + } +} + +func TestModuleFetchRefusesFileProtocol(t *testing.T) { + f := newFixture(t) + d := f.deployer() + if err := d.syncMirror(context.Background(), filepath.Join(f.root, "m.git"), "file://"+f.modDir, modFetchOpts, modRefspecs); err == nil || !strings.Contains(err.Error(), "transport 'file' not allowed") { + t.Fatalf("module fetch over file:// not refused: %v", err) + } +} + +func TestInterruptedModuleGCNotReused(t *testing.T) { + f := newFixture(t) + pf := fmt.Sprintf("mod 'bind', :git => '%s', :tag => '1.0'\n", f.mod) + commit(t, f.control, map[string]string{"Puppetfile": pf}) + f.mustDeploy(false) + commit(t, f.control, map[string]string{"Puppetfile": "\n"}) + f.mustDeploy(false) + f.clock = f.clock.Add(11 * time.Minute) + f.mustDeploy(false) + f.clock = f.clock.Add(11 * time.Minute) + d := f.deployer() + crashed := false + d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) { + if len(args) > 1 && args[0] == "worktree" && args[1] == "remove" && strings.Contains(args[len(args)-1], "/modules/") { + _ = os.Remove(filepath.Join(args[len(args)-1], "manifests", "init.pp")) + crashed = true + panic("crash mid-removal") + } + return runGit(ctx, dir, args...) + } + func() { + defer func() { _ = recover() }() + _ = d.GC(context.Background()) + }() + if !crashed { + t.Fatal("GC never reached module removal") + } + commit(t, f.control, map[string]string{"Puppetfile": pf + "# again\n"}) + f.mustDeploy(false) + if p := filepath.Join(f.basedir, "main", "modules", "bind", "manifests", "init.pp"); !exists(p) { + t.Fatalf("env went live with a half-deleted module dir reused from cache: %s missing", p) + } + if n := dirCount(t, f.cache("modules", urlKey(f.mod))); n != 1 { + t.Fatalf("interrupted GC leftover not removed: %d entries", n) + } +} + +func TestUnmarkedCacheDirsRebuilt(t *testing.T) { + f := newFixture(t) + pf := fmt.Sprintf("forge '%s'\nmod 'acme-thing', '1.0.0'\nmod 'bind', :git => '%s', :tag => '1.0'\n", f.forgeURL, f.mod) + commit(t, f.control, map[string]string{"Puppetfile": pf}) + f.mustDeploy(false) + d := f.deployer() + forge := f.forgeDir("acme-thing-1.0.0") + mods, _ := os.ReadDir(f.cache("modules", urlKey(f.mod))) + mod := f.cache("modules", urlKey(f.mod), mods[0].Name()) + for _, dir := range []string{forge, mod} { + if err := os.Remove(d.doneFile(dir)); err != nil { + t.Fatal(err) + } + } + mustRemove(t, filepath.Join(forge, "metadata.json"), filepath.Join(mod, "manifests", "init.pp")) + leftover := f.cache("forge", "x"+gcTag+strings.Repeat("A", 26)) + mkdirs(t, leftover) + commit(t, f.control, map[string]string{"Puppetfile": pf + "# again\n"}) + f.mustDeploy(false) + for _, p := range []string{"modules/thing/metadata.json", "modules/bind/manifests/init.pp"} { + if !exists(filepath.Join(f.env("main"), p)) { + t.Fatalf("unmarked cache dir reused: %s missing", p) + } + } + if exists(leftover) { + t.Fatal("gc leftover not removed") + } +} + +func mustRemove(t *testing.T, paths ...string) { + t.Helper() + for _, p := range paths { + if err := os.Remove(p); err != nil { + t.Fatal(err) + } + } +} + +func TestPanicFailsOnlyItsEnv(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "bad") + bad := commit(t, f.control, map[string]string{"manifests/site.pp": "# bad\n"}) + d := f.deployer() + d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) { + if len(args) > 2 && args[0] == "cat-file" && strings.HasPrefix(args[2], bad) { + panic("boom") + } + return runGit(ctx, dir, args...) + } + err := d.Deploy(context.Background(), nil, false) + if err == nil || !strings.Contains(err.Error(), "environment bad: panic: boom") { + t.Fatalf("panic not reported as env error: %v", err) + } + if f.env("main") == "" || f.env("bad") != "" { + t.Fatalf("main=%q bad=%q", f.env("main"), f.env("bad")) + } + if !exists(f.cache(gcStateFile)) { + t.Fatal("GC skipped after a panicking env") + } +} + +func TestConcurrentWorktreeAddsOneMirror(t *testing.T) { + f := newFixture(t) + for i := range 40 { + gitT(t, f.control, "checkout", "-q", "-B", fmt.Sprintf("b%d", i)) + commit(t, f.control, map[string]string{"n": fmt.Sprint(i)}) + } + d := New(f.cfg, 16, 10*time.Minute) + d.now = func() time.Time { return f.clock } + if err := d.Deploy(context.Background(), nil, false); err != nil { + t.Fatal(err) + } +} + +func TestGCRefsErrorDropsMarkOfLiveWorktree(t *testing.T) { + root := t.TempDir() + s := &Source{Name: "s", Basedir: filepath.Join(root, "envs")} + cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": s}} + clock := time.Unix(1_700_000_000, 0) + gc := func() error { + d := New(cfg, 1, 10*time.Minute) + d.now = func() time.Time { return clock } + return d.GC(context.Background()) + } + d := New(cfg, 1, 0) + old, cur, broken := filepath.Join(d.srcWorktrees(s), "old"), filepath.Join(d.srcWorktrees(s), "cur"), filepath.Join(d.srcWorktrees(s), "broken") + mkdirs(t, old, cur, broken, s.Basedir, filepath.Dir(d.doneFile(old))) + for _, p := range []string{old, cur} { + if err := os.WriteFile(d.doneFile(p), []byte(`{"modules":[]}`), 0o644); err != nil { + t.Fatal(err) + } + } + link := filepath.Join(s.Basedir, "develop") + if err := Swap(cur, link); err != nil { + t.Fatal(err) + } + if err := gc(); err != nil { + t.Fatal(err) + } + clock = clock.Add(time.Hour) + if err := Swap(old, link); err != nil { + t.Fatal(err) + } + if err := Swap(broken, filepath.Join(s.Basedir, "other")); err != nil { + t.Fatal(err) + } + if err := gc(); err == nil { + t.Fatal("want moduleRefs error from live worktree without done file") + } + if err := os.WriteFile(d.doneFile(broken), []byte(`{"modules":[]}`), 0o644); err != nil { + t.Fatal(err) + } + if err := Swap(cur, link); err != nil { + t.Fatal(err) + } + _ = gc() + if !exists(old) { + t.Fatal("worktree unreferenced this run was deleted in the same run via a stale mark kept while it was live") + } +} + +func TestDeployOnlyLeavesLaterSourceAlone(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "branch", "production") + other := filepath.Join(f.root, "other") + newRepo(t, other) + commit(t, other, map[string]string{"manifests/site.pp": "node default {}\n"}) + otherBase := filepath.Join(f.root, "other-envs") + cfg, err := ParseConfig(fmt.Appendf(nil, "cachedir: %s\nsources:\n aaa:\n remote: %s\n basedir: %s\n zzz:\n remote: %s\n basedir: %s\n", f.cfg.Cachedir, f.control, f.basedir, other, otherBase)) + if err != nil { + t.Fatal(err) + } + f.cfg = cfg + if err := f.deploy(false, "production"); err != nil { + t.Fatal(err) + } + if exists(filepath.Join(otherBase, "main")) { + t.Fatal("deploy production also deployed every env of the next source") + } +} + +func TestDeployMarkerNameIsBranch(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "feat/x") + commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) + if err := f.deploy(false, "feat_x"); err != nil { + t.Fatal(err) + } + if m := readMarker(t, f.env("feat_x")); m.Name != "feat/x" { + t.Fatalf("marker name %q, want branch feat/x", m.Name) + } +} + +func TestTargetedDeploySkipsGC(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + f.mustDeploy(false) + old := f.env("main") + commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) + f.mustDeploy(false) + f.clock = f.clock.Add(time.Hour) + if err := f.deploy(false, "main"); err != nil { + t.Fatal(err) + } + if !exists(old) { + t.Fatalf("targeted deploy ran GC and removed %s", old) + } +} + +func TestTargetedDeployDropsMarkOfReusedWorktree(t *testing.T) { + f := newFixture(t) + sha1 := commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + f.mustDeploy(false) + w1 := f.env("main") + commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) + f.mustDeploy(false) + f.clock = f.clock.Add(time.Hour) + gitT(t, f.control, "reset", "-q", "--hard", sha1) + if err := f.deploy(false, "main"); err != nil || f.env("main") != w1 { + t.Fatalf("targeted deploy did not reuse %s: %v", w1, err) + } + commit(t, f.control, map[string]string{"manifests/site.pp": "node y {}\n"}) + if err := f.deploy(false, "main"); err != nil { + t.Fatal(err) + } + f.mustDeploy(false) + if !exists(w1) { + t.Fatal("worktree live during a targeted deploy kept its earlier mark and was deleted without grace") + } +} + +func TestGCLiveErrorDropsMarkOfLiveWorktree(t *testing.T) { + root := t.TempDir() + s := &Source{Name: "s", Basedir: filepath.Join(root, "envs")} + u := &Source{Name: "u", Basedir: filepath.Join(root, "uenvs")} + cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": s, "u": u}} + clock := time.Unix(1_700_000_000, 0) + gc := func() error { + d := New(cfg, 1, 10*time.Minute) + d.now = func() time.Time { return clock } + return d.GC(context.Background()) + } + d := New(cfg, 1, 0) + old, cur := filepath.Join(d.srcWorktrees(s), "old"), filepath.Join(d.srcWorktrees(s), "cur") + mkdirs(t, old, cur, s.Basedir, filepath.Dir(d.doneFile(old))) + for _, p := range []string{old, cur} { + if err := os.WriteFile(d.doneFile(p), []byte(`{"modules":[]}`), 0o644); err != nil { + t.Fatal(err) + } + } + link := filepath.Join(s.Basedir, "develop") + if err := Swap(cur, link); err != nil { + t.Fatal(err) + } + if err := gc(); err != nil { + t.Fatal(err) + } + clock = clock.Add(time.Hour) + if err := Swap(old, link); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(u.Basedir, nil, 0o644); err != nil { + t.Fatal(err) + } + if err := gc(); err == nil { + t.Fatal("want Live error") + } + if err := os.Remove(u.Basedir); err != nil { + t.Fatal(err) + } + if err := Swap(cur, link); err != nil { + t.Fatal(err) + } + _ = gc() + if !exists(old) { + t.Fatal("worktree unreferenced this run was deleted in the same run via a mark kept by GC's early return") + } +} + +func TestGCCorruptStateTreatedAsEmpty(t *testing.T) { + root := t.TempDir() + s := &Source{Name: "s", Basedir: filepath.Join(root, "envs")} + cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": s}} + d := New(cfg, 1, 10*time.Minute) + old := filepath.Join(d.srcWorktrees(s), "old") + mkdirs(t, old, s.Basedir) + state := d.path(gcStateFile) + if err := os.WriteFile(state, []byte("{not json"), 0o644); err != nil { + t.Fatal(err) + } + if err := d.GC(context.Background()); err != nil { + t.Fatalf("corrupt state wedged GC: %v", err) + } + b, err := os.ReadFile(state) + if err != nil { + t.Fatal(err) + } + var marks map[string]time.Time + if err := json.Unmarshal(b, &marks); err != nil { + t.Fatalf("state not rewritten: %v", err) + } + if _, ok := marks[old]; !ok || !exists(old) { + t.Fatal("unreferenced worktree must be freshly marked, not deleted") + } +} + +func TestExactBranchWinsEnvName(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "feature_x") + legit := commit(t, f.control, map[string]string{"manifests/site.pp": "node legit {}\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "feature-x") + commit(t, f.control, map[string]string{"manifests/site.pp": "node evil {}\n"}) + err := f.deploy(false) + if got := f.env("feature_x"); !strings.HasPrefix(filepath.Base(got), legit+"-") { + t.Fatalf("env feature_x -> %s, want branch feature_x (%s); a pushed feature-x took it over", filepath.Base(got), legit) + } + if err == nil || !strings.Contains(err.Error(), "feature-x") { + t.Fatalf("want collision error naming feature-x, got %v", err) + } +} + +func TestCorrectedBranchCollisionSkipsAll(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "branch", "feature-x") + gitT(t, f.control, "branch", "feature.x") + err := f.deploy(false) + if exists(filepath.Join(f.basedir, "feature_x")) { + t.Fatal("colliding corrected branches must not deploy feature_x") + } + if err == nil || !strings.Contains(err.Error(), "feature-x") || !strings.Contains(err.Error(), "feature.x") { + t.Fatalf("want collision error naming both branches, got %v", err) + } + if f.env("main") == "" { + t.Fatal("collision must not block other envs") + } +} diff --git a/internal/deploy/forge.go b/internal/deploy/forge.go new file mode 100644 index 0000000..e89172a --- /dev/null +++ b/internal/deploy/forge.go @@ -0,0 +1,168 @@ +package deploy + +import ( + "archive/tar" + "compress/gzip" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "time" +) + +const ( + defaultForge = "https://forgeapi.puppet.com" + maxForgeDownload = 100 << 20 + maxForgeExtracted = 512 << 20 +) + +var httpClient = &http.Client{Timeout: 5 * time.Minute} + +func forgeURL(s string) string { + switch strings.TrimSuffix(strings.TrimPrefix(strings.TrimPrefix(s, "https://"), "http://"), "/") { + case "", "forge.puppetlabs.com", "forge.puppet.com", "forgeapi.puppetlabs.com", "forgeapi.puppet.com": + return defaultForge + } + if !strings.Contains(s, "://") { + s = "https://" + s + } + return strings.TrimSuffix(s, "/") +} + +func forgeGet(ctx context.Context, url string) (io.ReadCloser, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", "w10k") + resp, err := httpClient.Do(req) + if err != nil { + return nil, err + } + if resp.StatusCode != http.StatusOK { + _ = resp.Body.Close() + return nil, fmt.Errorf("GET %s: %s", url, resp.Status) + } + return resp.Body, nil +} + +func forgeLatest(ctx context.Context, base, slug string) (string, error) { + body, err := forgeGet(ctx, base+"/v3/modules/"+slug) + if err != nil { + return "", err + } + defer func() { _ = body.Close() }() + var r struct { + CurrentRelease struct { + Version string `json:"version"` + } `json:"current_release"` + } + if err := json.NewDecoder(body).Decode(&r); err != nil { + return "", fmt.Errorf("%s: %w", slug, err) + } + if !versionStr.MatchString(r.CurrentRelease.Version) { + return "", fmt.Errorf("%s: forge returned no usable current_release", slug) + } + return r.CurrentRelease.Version, nil +} + +func forgeInstall(ctx context.Context, base, release, dir string) error { + body, err := forgeGet(ctx, base+"/v3/files/"+release+".tar.gz") + if err != nil { + return err + } + defer func() { _ = body.Close() }() + if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil { + return err + } + tmp, err := os.MkdirTemp(filepath.Dir(dir), ".tmp-") + if err != nil { + return err + } + if err := extract(&capReader{r: body, n: maxForgeDownload}, tmp, maxForgeExtracted); err != nil { + _ = os.RemoveAll(tmp) + return fmt.Errorf("%s: %w", release, err) + } + return os.Rename(tmp, dir) +} + +// capReader fails once more than n bytes are read, so an oversized stream errors instead of being truncated silently. +type capReader struct { + r io.Reader + n int64 +} + +func (c *capReader) Read(p []byte) (int, error) { + if int64(len(p)) > c.n+1 { + p = p[:c.n+1] + } + n, err := c.r.Read(p) + if c.n -= int64(n); c.n < 0 { + return 0, fmt.Errorf("archive exceeds size cap") + } + return n, err +} + +func extract(r io.Reader, dst string, limit int64) error { + gz, err := gzip.NewReader(r) + if err != nil { + return err + } + cr := &capReader{r: gz, n: limit} + root, err := os.OpenRoot(dst) + if err != nil { + return err + } + defer func() { _ = root.Close() }() + tr := tar.NewReader(cr) + for { + hdr, err := tr.Next() + if err == io.EOF { + return nil + } + if err != nil { + return err + } + _, rel, _ := strings.Cut(strings.TrimPrefix(hdr.Name, "./"), "/") + if rel == "" { + continue + } + rel = filepath.Clean(rel) + if !filepath.IsLocal(rel) { + return fmt.Errorf("unsafe path %q in archive", hdr.Name) + } + switch hdr.Typeflag { + case tar.TypeDir: + if err := root.MkdirAll(rel, 0o755); err != nil { + return err + } + case tar.TypeReg: + if err := writeFile(root, rel, tr, hdr.Mode&0o111 != 0); err != nil { + return err + } + } + } +} + +func writeFile(root *os.Root, p string, r io.Reader, exec bool) error { + if err := root.MkdirAll(filepath.Dir(p), 0o755); err != nil { + return err + } + mode := os.FileMode(0o644) + if exec { + mode = 0o755 + } + f, err := root.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode) + if err != nil { + return err + } + if _, err := io.Copy(f, r); err != nil { + _ = f.Close() + return err + } + return f.Close() +} diff --git a/internal/deploy/forge_test.go b/internal/deploy/forge_test.go new file mode 100644 index 0000000..6598222 --- /dev/null +++ b/internal/deploy/forge_test.go @@ -0,0 +1,118 @@ +package deploy + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "io" + "os" + "path/filepath" + "strings" + "testing" +) + +type entry struct { + name string + body string + mode int64 + typ byte +} + +func tarball(t *testing.T, entries ...entry) []byte { + t.Helper() + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + for _, e := range entries { + typ := e.typ + if typ == 0 { + typ = tar.TypeReg + } + hdr := &tar.Header{Name: e.name, Mode: e.mode, Size: int64(len(e.body)), Typeflag: typ} + if typ != tar.TypeReg { + hdr.Size = 0 + hdr.Linkname = e.body + } + if err := tw.WriteHeader(hdr); err != nil { + t.Fatal(err) + } + if typ == tar.TypeReg { + if _, err := tw.Write([]byte(e.body)); err != nil { + t.Fatal(err) + } + } + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + if err := gz.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func TestExtractStripsTopDir(t *testing.T) { + dst := t.TempDir() + err := extract(bytes.NewReader(tarball(t, + entry{name: "puppetlabs-stdlib-9.7.0/", typ: tar.TypeDir, mode: 0o755}, + entry{name: "puppetlabs-stdlib-9.7.0/spec/", typ: tar.TypeDir, mode: 0o755}, + entry{name: "puppetlabs-stdlib-9.7.0/metadata.json", body: "{}", mode: 0o600}, + entry{name: "./puppetlabs-stdlib-9.7.0/lib/x.rb", body: "x", mode: 0o644}, + entry{name: "puppetlabs-stdlib-9.7.0/bin/run", body: "#!", mode: 0o700}, + entry{name: "puppetlabs-stdlib-9.7.0/link", body: "/etc/passwd", typ: tar.TypeSymlink}, + )), dst, maxForgeExtracted) + if err != nil { + t.Fatal(err) + } + for p, perm := range map[string]os.FileMode{"spec": 0o755 | os.ModeDir, "metadata.json": 0o644, "lib/x.rb": 0o644, "bin/run": 0o755} { + fi, err := os.Stat(filepath.Join(dst, p)) + if err != nil || fi.Mode()&(os.ModePerm|os.ModeDir) != perm { + t.Errorf("%s: %v %v", p, fi, err) + } + } + if _, err := os.Lstat(filepath.Join(dst, "link")); !os.IsNotExist(err) { + t.Error("symlink should be skipped") + } +} + +func TestExtractRejectsTraversal(t *testing.T) { + dst := t.TempDir() + err := extract(bytes.NewReader(tarball(t, entry{name: "m-1/../../evil", body: "x", mode: 0o644})), dst, maxForgeExtracted) + if err == nil { + t.Fatal("expected traversal error") + } +} + +func TestForgeURL(t *testing.T) { + for in, want := range map[string]string{ + "": defaultForge, + "forge.puppetlabs.com": defaultForge, + "https://forge.puppet.com/": defaultForge, + "forge.example.com": "https://forge.example.com", + "http://127.0.0.1:8080/": "http://127.0.0.1:8080", + "https://artifacts/api/forge/": "https://artifacts/api/forge", + } { + if got := forgeURL(in); got != want { + t.Errorf("forgeURL(%q) = %q, want %q", in, got, want) + } + } +} + +func TestExtractRejectsOversize(t *testing.T) { + big := entry{name: "m/a", body: strings.Repeat("x", 4096), mode: 0o644} + if err := extract(bytes.NewReader(tarball(t, big)), t.TempDir(), 1024); err == nil { + t.Fatal("want extracted size cap error") + } + if err := extract(bytes.NewReader(tarball(t, big)), t.TempDir(), 1<<20); err != nil { + t.Fatal(err) + } +} + +func TestCapReaderErrorsAtCap(t *testing.T) { + if _, err := io.ReadAll(&capReader{r: strings.NewReader("abcdef"), n: 4}); err == nil { + t.Fatal("want cap error") + } + if b, err := io.ReadAll(&capReader{r: strings.NewReader("abc"), n: 4}); err != nil || string(b) != "abc" { + t.Fatalf("under cap: %q %v", b, err) + } +} diff --git a/internal/deploy/git.go b/internal/deploy/git.go new file mode 100644 index 0000000..2c6cb20 --- /dev/null +++ b/internal/deploy/git.go @@ -0,0 +1,87 @@ +package deploy + +import ( + "bytes" + "context" + "fmt" + "os" + "os/exec" + "slices" + "strings" + "sync" + "syscall" + "time" +) + +const defaultGitTimeout = 10 * time.Minute + +func runGit(ctx context.Context, dir string, args ...string) (string, error) { + cmd := exec.CommandContext(ctx, "git", append([]string{"-c", "http.lowSpeedLimit=1", "-c", "http.lowSpeedTime=60"}, args...)...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0") + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) } + cmd.WaitDelay = 5 * time.Second + var out, errb bytes.Buffer + cmd.Stdout, cmd.Stderr = &out, &errb + if err := cmd.Run(); err != nil { + return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String())) + } + return strings.TrimSpace(out.String()), nil +} + +// git holds a -j slot only for the subprocess itself; worktree commands are serialized per repo since concurrent adds read each other's half-written admin dirs. +func (d *Deployer) git(ctx context.Context, dir string, args ...string) (out string, err error) { + if len(args) > 0 && args[0] == "worktree" { + mu, _ := d.wtLocks.LoadOrStore(dir, &sync.Mutex{}) + mu.(*sync.Mutex).Lock() + defer mu.(*sync.Mutex).Unlock() + } + err = d.limit(func() error { + ctx, cancel := context.WithTimeout(ctx, d.gitTimeout) + defer cancel() + out, err = d.runGit(ctx, dir, args...) + return err + }) + return out, err +} + +func (d *Deployer) syncMirror(ctx context.Context, mirror, url string, opts, refspecs []string) error { + if _, err := os.Stat(mirror); os.IsNotExist(err) { + if _, err := d.git(ctx, "", "init", "-q", "--bare", "--", mirror); err != nil { + return err + } + } + args := slices.Concat(opts, []string{"fetch", "-q", "--prune", "--force", "--", url}, refspecs) + _, err := d.git(ctx, mirror, args...) + return err +} + +func (d *Deployer) branches(ctx context.Context, mirror string) (map[string]string, error) { + out, err := d.git(ctx, mirror, "for-each-ref", "--format=%(objectname) %(refname)", "refs/heads/") + if err != nil { + return nil, err + } + m := map[string]string{} + for _, l := range strings.Split(out, "\n") { + sha, ref, ok := strings.Cut(l, " ") + if ok { + m[strings.TrimPrefix(ref, "refs/heads/")] = sha + } + } + return m, nil +} + +func (d *Deployer) revParse(ctx context.Context, mirror string, candidates ...string) (string, error) { + for _, c := range candidates { + if sha, err := d.git(ctx, mirror, "rev-parse", "--verify", "--quiet", "--end-of-options", c+"^{commit}"); err == nil { + return sha, nil + } + } + return "", fmt.Errorf("cannot resolve %s", strings.Join(candidates, " or ")) +} + +func (d *Deployer) removeWorktree(ctx context.Context, mirror, path string) error { + _, _ = d.git(ctx, mirror, "worktree", "remove", "--force", "--", path) + return os.RemoveAll(path) +} diff --git a/internal/deploy/puppetfile.go b/internal/deploy/puppetfile.go new file mode 100644 index 0000000..512b4a2 --- /dev/null +++ b/internal/deploy/puppetfile.go @@ -0,0 +1,349 @@ +package deploy + +import ( + "fmt" + "net/url" + "path/filepath" + "regexp" + "strings" +) + +type Puppetfile struct { + Forge string + Moduledir string + Modules []Module +} + +type Module struct { + Owner string + Name string + Version string + Git string + RefKind string + Ref string + InstallPath string +} + +// Path is the module's install location relative to the environment root. +func (m Module) Path(pf *Puppetfile) string { + dir := pf.Moduledir + if m.InstallPath != "" { + dir = m.InstallPath + } + return filepath.Join(dir, m.Name) +} + +type tokKind int + +const ( + tIdent tokKind = iota + tString + tSymbol + tLabel + tArrow + tComma + tLParen + tRParen + tNewline + tEOF +) + +type token struct { + kind tokKind + val string + line int +} + +func isIdent(c byte) bool { + return c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' +} + +func lex(src string) ([]token, error) { + var toks []token + line := 1 + for i := 0; i < len(src); { + c := src[i] + switch { + case c == ' ' || c == '\t' || c == '\r': + i++ + case c == '#': + for i < len(src) && src[i] != '\n' { + i++ + } + case c == '\n': + toks = append(toks, token{tNewline, "", line}) + line++ + i++ + case c == '\'' || c == '"': + var sb strings.Builder + j := i + 1 + for ; j < len(src) && src[j] != c; j++ { + if src[j] == '\n' { + break + } + if src[j] == '\\' && j+1 < len(src) { + j++ + } + sb.WriteByte(src[j]) + } + if j >= len(src) || src[j] != c { + return nil, fmt.Errorf("line %d: unterminated string", line) + } + toks = append(toks, token{tString, sb.String(), line}) + i = j + 1 + case c == ':' && i+1 < len(src) && isIdent(src[i+1]): + j := i + 1 + for j < len(src) && isIdent(src[j]) { + j++ + } + toks = append(toks, token{tSymbol, src[i+1 : j], line}) + i = j + case isIdent(c): + j := i + for j < len(src) && isIdent(src[j]) { + j++ + } + if j < len(src) && src[j] == ':' && (j+1 >= len(src) || src[j+1] != ':') { + toks = append(toks, token{tLabel, src[i:j], line}) + i = j + 1 + } else { + toks = append(toks, token{tIdent, src[i:j], line}) + i = j + } + case strings.HasPrefix(src[i:], "=>"): + toks = append(toks, token{tArrow, "", line}) + i += 2 + case c == ',': + toks = append(toks, token{tComma, "", line}) + i++ + case c == '(': + toks = append(toks, token{tLParen, "", line}) + i++ + case c == ')': + toks = append(toks, token{tRParen, "", line}) + i++ + default: + return nil, fmt.Errorf("line %d: unexpected %q", line, c) + } + } + return append(toks, token{tEOF, "", line}), nil +} + +type call struct { + name string + line int + args []token + opts map[string]token +} + +func parseCalls(toks []token) ([]call, error) { + var calls []call + i := 0 + next := func() token { + t := toks[i] + if t.kind != tEOF { + i++ + } + return t + } + peek := func() token { return toks[i] } + skipNL := func() { + for peek().kind == tNewline { + i++ + } + } + for { + skipNL() + t := next() + if t.kind == tEOF { + return calls, nil + } + if t.kind != tIdent { + return nil, fmt.Errorf("line %d: expected a statement", t.line) + } + c := call{name: t.val, line: t.line, opts: map[string]token{}} + paren := peek().kind == tLParen + if paren { + i++ + skipNL() + } + for k := peek().kind; k != tNewline && k != tEOF && k != tRParen; k = peek().kind { + a := next() + switch { + case a.kind == tLabel || a.kind == tSymbol && peek().kind == tArrow: + if a.kind == tSymbol { + i++ + } + v := next() + if v.kind != tString && v.kind != tSymbol { + return nil, fmt.Errorf("line %d: %s needs a value", a.line, a.val) + } + c.opts[a.val] = v + case a.kind == tString || a.kind == tSymbol: + c.args = append(c.args, a) + default: + return nil, fmt.Errorf("line %d: unexpected token in %s", a.line, c.name) + } + if peek().kind != tComma { + break + } + i++ + skipNL() + } + if paren { + skipNL() + if next().kind != tRParen { + return nil, fmt.Errorf("line %d: expected )", c.line) + } + } + if k := peek().kind; k != tNewline && k != tEOF { + return nil, fmt.Errorf("line %d: unexpected trailing tokens", c.line) + } + calls = append(calls, c) + } +} + +var ( + moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) + ownerName = regexp.MustCompile(`^[A-Za-z0-9]+$`) + versionStr = regexp.MustCompile(`^[0-9A-Za-z.+-]+$`) +) + +func ParsePuppetfile(src string) (*Puppetfile, error) { + toks, err := lex(src) + if err != nil { + return nil, err + } + calls, err := parseCalls(toks) + if err != nil { + return nil, err + } + pf := &Puppetfile{Moduledir: "modules"} + for _, c := range calls { + switch c.name { + case "forge", "moduledir": + if len(c.args) != 1 || c.args[0].kind != tString || len(c.opts) > 0 { + return nil, fmt.Errorf("line %d: %s takes one string", c.line, c.name) + } + if c.name == "forge" { + pf.Forge = c.args[0].val + } else if pf.Moduledir, err = localPath(c.args[0].val); err != nil { + return nil, fmt.Errorf("line %d: moduledir: %w", c.line, err) + } + case "mod": + m, err := parseMod(c) + if err != nil { + return nil, fmt.Errorf("line %d: %w", c.line, err) + } + pf.Modules = append(pf.Modules, m) + default: + return nil, fmt.Errorf("line %d: unsupported statement %q", c.line, c.name) + } + } + seen := map[string]bool{} + for _, m := range pf.Modules { + p := m.Path(pf) + if seen[p] { + return nil, fmt.Errorf("duplicate module %s", p) + } + seen[p] = true + } + for p := range seen { + for d := filepath.Dir(p); d != "."; d = filepath.Dir(d) { + if seen[d] { + return nil, fmt.Errorf("module %s is nested inside module %s", p, d) + } + } + } + return pf, nil +} + +var scpURL = regexp.MustCompile(`^[A-Za-z0-9._][A-Za-z0-9._-]*@[A-Za-z0-9.][A-Za-z0-9.-]*:[^:]+$`) + +func remoteURL(s string) bool { + if scpURL.MatchString(s) { + return true + } + u, err := url.Parse(s) + if err != nil || u.Hostname() == "" || strings.HasPrefix(u.Host, "-") || strings.HasPrefix(u.User.Username(), "-") { + return false + } + return u.Scheme == "https" || u.Scheme == "http" || u.Scheme == "ssh" +} + +func localPath(p string) (string, error) { + if !filepath.IsLocal(p) { + return "", fmt.Errorf("%q must be a relative path inside the environment", p) + } + return filepath.Clean(p), nil +} + +func parseMod(c call) (Module, error) { + var m Module + if len(c.args) == 0 || c.args[0].kind != tString { + return m, fmt.Errorf("mod needs a name") + } + full := c.args[0].val + if i := strings.IndexAny(full, "-/"); i >= 0 { + m.Owner, m.Name = full[:i], full[i+1:] + } else { + m.Name = full + } + if !moduleName.MatchString(m.Name) { + return m, fmt.Errorf("invalid module name %q", full) + } + for k, v := range c.opts { + if v.kind != tString { + return m, fmt.Errorf("mod %s: :%s must be a string", full, k) + } + switch k { + case "git": + if !remoteURL(v.val) { + return m, fmt.Errorf("mod %s: :git %q must be an https, http, ssh or user@host:path URL", full, v.val) + } + m.Git = v.val + case "tag", "branch", "ref", "commit": + if v.val == "" || strings.HasPrefix(v.val, "-") { + return m, fmt.Errorf("mod %s: invalid :%s %q", full, k, v.val) + } + if m.RefKind != "" { + return m, fmt.Errorf("mod %s: only one of :tag, :branch, :ref, :commit allowed", full) + } + m.RefKind, m.Ref = k, v.val + case "install_path": + p, err := localPath(v.val) + if err != nil { + return m, fmt.Errorf("mod %s: install_path: %w", full, err) + } + m.InstallPath = p + default: + return m, fmt.Errorf("mod %s: unsupported option :%s", full, k) + } + } + if m.Git != "" { + if len(c.args) > 1 { + return m, fmt.Errorf("mod %s: git modules take no version", full) + } + return m, nil + } + if m.RefKind != "" { + return m, fmt.Errorf("mod %s: :%s requires :git", full, m.RefKind) + } + if !ownerName.MatchString(m.Owner) { + return m, fmt.Errorf("forge module %q must be owner-name", full) + } + if len(c.args) > 2 { + return m, fmt.Errorf("mod %s: too many arguments", full) + } + if len(c.args) == 2 { + v := c.args[1] + switch { + case v.val == "latest": + case v.kind == tString && versionStr.MatchString(v.val): + m.Version = v.val + default: + return m, fmt.Errorf("mod %s: unsupported version %q", full, v.val) + } + } + return m, nil +} diff --git a/internal/deploy/puppetfile_test.go b/internal/deploy/puppetfile_test.go new file mode 100644 index 0000000..d5b67c9 --- /dev/null +++ b/internal/deploy/puppetfile_test.go @@ -0,0 +1,167 @@ +package deploy + +import ( + "path/filepath" + "reflect" + "testing" +) + +func TestParsePuppetfileEstate(t *testing.T) { + pf, err := ParsePuppetfile(`forge 'forge.puppetlabs.com' +moduledir 'external_modules' + +# puppetlabs +mod 'puppetlabs-stdlib', '9.7.0' +mod 'puppetlabs-yumrepo_core', '2.1.0' # trailing comment + +mod 'bind', + :git => 'https://git.unkin.net/unkinben/puppet-bind.git', + :tag => '1.0' +`) + if err != nil { + t.Fatal(err) + } + if pf.Forge != "forge.puppetlabs.com" || pf.Moduledir != "external_modules" { + t.Fatalf("header: %+v", pf) + } + want := []Module{ + {Owner: "puppetlabs", Name: "stdlib", Version: "9.7.0"}, + {Owner: "puppetlabs", Name: "yumrepo_core", Version: "2.1.0"}, + {Name: "bind", Git: "https://git.unkin.net/unkinben/puppet-bind.git", RefKind: "tag", Ref: "1.0"}, + } + if !reflect.DeepEqual(pf.Modules, want) { + t.Fatalf("modules:\n got %+v\nwant %+v", pf.Modules, want) + } + if p := pf.Modules[2].Path(pf); p != "external_modules/bind" { + t.Fatalf("path %s", p) + } +} + +func TestParsePuppetfileForms(t *testing.T) { + pf, err := ParsePuppetfile(` +mod "puppet/systemd", "8.1.0" +mod 'saz-sudo', :latest +mod 'saz-ssh' +mod 'a-b', 'latest' +mod('x', + git: 'https://example/x.git', + branch: 'main') +mod 'y', :git => "https://h/y#not-a-comment", :ref => 'v1' +mod 'z', :git => 'git@h:g', :commit => 'abc123', :install_path => 'site' +mod 'h', :git => 'ssh://h/g2' +`) + if err != nil { + t.Fatal(err) + } + want := []Module{ + {Owner: "puppet", Name: "systemd", Version: "8.1.0"}, + {Owner: "saz", Name: "sudo"}, + {Owner: "saz", Name: "ssh"}, + {Owner: "a", Name: "b"}, + {Name: "x", Git: "https://example/x.git", RefKind: "branch", Ref: "main"}, + {Name: "y", Git: "https://h/y#not-a-comment", RefKind: "ref", Ref: "v1"}, + {Name: "z", Git: "git@h:g", RefKind: "commit", Ref: "abc123", InstallPath: "site"}, + {Name: "h", Git: "ssh://h/g2"}, + } + if !reflect.DeepEqual(pf.Modules, want) { + t.Fatalf("modules:\n got %+v\nwant %+v", pf.Modules, want) + } + if pf.Moduledir != "modules" { + t.Fatalf("default moduledir %q", pf.Moduledir) + } + if p := pf.Modules[6].Path(pf); p != "site/z" { + t.Fatalf("install_path %s", p) + } +} + +func TestParsePuppetfileErrors(t *testing.T) { + for name, in := range map[string]string{ + "unterminated": "mod 'a-b", + "unknown stmt": "require 'x'", + "unknown option": "mod 'x', :git => 'git@h:g', :default_branch => 'main'", + "two refs": "mod 'x', :git => 'git@h:g', :tag => 'a', :branch => 'b'", + "ref without git": "mod 'a-b', :tag => '1'", + "git version": "mod 'x', '1.0', :git => 'git@h:g'", + "no owner": "mod 'stdlib', '1.0'", + "bad name": "mod 'a-B@d', '1.0'", + "bad version": "mod 'a-b', '../../etc'", + "abs moduledir": "moduledir '/etc'", + "escape moduledir": "moduledir '../x'", + "escape install": "mod 'x', :git => 'git@h:g', :install_path => '../../x'", + "duplicate": "mod 'a-b', '1'\nmod 'c-b', '2'", + "final moduledir": "mod 'a-x', '1'\nmoduledir 'site'\nmod 'x', :git => 'git@h:g', :install_path => 'site'", + "nested": "mod 'a-thing', '1'\nmod 'metadata', :git => 'git@h:g', :install_path => 'modules/thing'", + "option git": "mod 'x', :git => '--upload-pack=touch /tmp/x'", + "option ref": "mod 'x', :git => 'git@h:g', :branch => '--output=/tmp/x'", + "trailing junk": "mod 'a-b', '1' 'c'", + "bad char": "mod 'a-b', '1'; x", + } { + if _, err := ParsePuppetfile(in); err == nil { + t.Errorf("%s: expected error", name) + } + } +} + +func TestParsePuppetfileFinalModuledir(t *testing.T) { + pf, err := ParsePuppetfile("mod 'a-x', '1'\nmoduledir 'site'\nmod 'x', :git => 'git@h:g', :install_path => 'modules'\n") + if err != nil { + t.Fatal(err) + } + if p := pf.Modules[0].Path(pf); p != "site/x" { + t.Fatalf("forge module path %s, want final moduledir", p) + } +} + +func TestParsePuppetfileTrailingOptionNoPanic(t *testing.T) { + for _, src := range []string{"mod 'x', git:", "mod 'x', :git =>", "mod('x', git:", "mod 'x', git:\n", "mod 'x', :git => ,"} { + func() { + defer func() { + if r := recover(); r != nil { + t.Errorf("ParsePuppetfile(%q) panicked: %v", src, r) + } + }() + if _, err := ParsePuppetfile(src); err == nil { + t.Errorf("ParsePuppetfile(%q) accepted", src) + } + }() + } +} + +func TestParsePuppetfileGitRemoteOnly(t *testing.T) { + for _, g := range []string{"file:///srv/repo", "/srv/repo", "../repo", "repo", "ext::sh -c id", "host:repo", "git@host::x", "https:///x", "ftp://h/x", "git://h/x", "ssh://-oProxyCommand=id/x", "ssh://-oProxyCommand=id@h/x", "-oProxyCommand=id@h:x", "git@-oProxyCommand=id:x"} { + if _, err := ParsePuppetfile("mod 'x', :git => '" + g + "'"); err == nil { + t.Errorf(":git %q accepted", g) + } + } + for _, g := range []string{"https://h/x.git", "http://h:8080/x", "ssh://git@h/x", "git@git.unkin.net:unkin/x.git"} { + if _, err := ParsePuppetfile("mod 'x', :git => '" + g + "'"); err != nil { + t.Errorf(":git %q rejected: %v", g, err) + } + } +} + +func FuzzParsePuppetfile(f *testing.F) { + for _, s := range []string{ + "forge 'forge.puppetlabs.com'\nmoduledir 'external_modules'\n\n# puppetlabs\nmod 'puppetlabs-stdlib', '9.7.0'\nmod 'puppetlabs-yumrepo_core', '2.1.0' # trailing comment\n\nmod 'bind',\n :git => 'https://git.unkin.net/unkinben/puppet-bind.git',\n :tag => '1.0'\n", + "mod \"puppet/systemd\", \"8.1.0\"\nmod 'saz-sudo', :latest\nmod('x',\n git: 'https://example/x.git',\n branch: 'main')\nmod 'z', :git => 'git@h:g', :commit => 'abc123', :install_path => 'site'\n", + "mod 'a-x', '1'\nmoduledir 'site'\nmod 'x', :git => 'git@h:g', :install_path => 'modules'\n", + "mod 'x', git:", + "mod 'x', :git =>", + } { + f.Add(s) + } + f.Fuzz(func(t *testing.T, src string) { + pf, err := ParsePuppetfile(src) + if err != nil { + return + } + for _, m := range pf.Modules { + if p := m.Path(pf); !filepath.IsLocal(p) { + t.Fatalf("module path %q escapes", p) + } + if m.Git != "" && !remoteURL(m.Git) { + t.Fatalf("non-remote :git %q", m.Git) + } + } + }) +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..d5f5157 --- /dev/null +++ b/main.go @@ -0,0 +1,119 @@ +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + "path/filepath" + "sort" + "strings" + "syscall" + "time" + + "git.unkin.net/unkin/w10k/internal/deploy" + "github.com/spf13/cobra" +) + +var version = "dev" + +func main() { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := rootCmd().ExecuteContext(ctx); err != nil { + os.Exit(1) + } +} + +func rootCmd() *cobra.Command { + var cfgPath string + var jobs int + var grace time.Duration + var root *cobra.Command + load := func() (*deploy.Deployer, error) { + cfg, err := deploy.LoadConfig(cfgPath) + if err != nil { + return nil, err + } + g := grace + if !root.PersistentFlags().Changed("gc-grace") && cfg.W10k.GCGrace != nil { + g = *cfg.W10k.GCGrace + } + if g < 0 { + return nil, fmt.Errorf("--gc-grace must not be negative") + } + return deploy.New(cfg, jobs, g), nil + } + locked := func(fn func(*deploy.Deployer) error) error { + d, err := load() + if err != nil { + return err + } + unlock, err := d.Lock() + if err != nil { + return err + } + defer unlock() + return fn(d) + } + + root = &cobra.Command{ + Use: "w10k", + Short: "Deploy Puppet environments and Puppetfile modules as sha-pinned git worktrees", + Version: version, + SilenceUsage: true, + } + root.PersistentFlags().StringVarP(&cfgPath, "config", "c", "/etc/puppetlabs/r10k/r10k.yaml", "r10k.yaml path") + root.PersistentFlags().IntVarP(&jobs, "jobs", "j", 8, "maximum concurrent git/forge operations") + root.PersistentFlags().DurationVar(&grace, "gc-grace", 10*time.Minute, "keep unreferenced worktrees and modules this long after a run marks them (overrides w10k.gc_grace)") + + var modules bool + deployCmd := &cobra.Command{ + Use: "deploy [env...]", + Short: "Deploy all environments, or only the named ones", + RunE: func(cmd *cobra.Command, args []string) error { + return locked(func(d *deploy.Deployer) error { return d.Deploy(cmd.Context(), args, modules) }) + }, + } + deployCmd.Flags().BoolVarP(&modules, "modules", "m", false, "re-resolve Puppetfile modules for unchanged environments") + + listCmd := &cobra.Command{ + Use: "list", + Short: "List deployed environments", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + d, err := load() + if err != nil { + return err + } + for _, s := range d.Sources() { + live, err := d.Live(s) + if err != nil { + return err + } + envs := make([]string, 0, len(live)) + for e := range live { + envs = append(envs, e) + } + sort.Strings(envs) + for _, e := range envs { + sha, _, _ := strings.Cut(filepath.Base(live[e]), "-") + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\n", s.Name, e, sha) + } + } + return nil + }, + } + + gcCmd := &cobra.Command{ + Use: "gc", + Short: "Remove worktrees and modules no longer referenced by any environment", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + return locked(func(d *deploy.Deployer) error { return d.GC(cmd.Context()) }) + }, + } + + root.AddCommand(deployCmd, listCmd, gcCmd) + return root +} diff --git a/packaging/nfpm.yaml b/packaging/nfpm.yaml new file mode 100644 index 0000000..c65533b --- /dev/null +++ b/packaging/nfpm.yaml @@ -0,0 +1,35 @@ +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} + +depends: + - git + +contents: + - src: dist/w10k + dst: /usr/bin/w10k + file_info: + mode: 0755 + owner: root + group: root + - src: dist/completions/w10k.bash + dst: /usr/share/bash-completion/completions/w10k + file_info: + mode: 0644 + - src: dist/completions/_w10k + dst: /usr/share/zsh/site-functions/_w10k + file_info: + mode: 0644 + - src: dist/completions/w10k.fish + dst: /usr/share/fish/vendor_completions.d/w10k.fish + file_info: + mode: 0644 diff --git a/scripts/build-rpm.sh b/scripts/build-rpm.sh new file mode 100755 index 0000000..15440c9 --- /dev/null +++ b/scripts/build-rpm.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +VERSION="${1:-${CI_COMMIT_TAG:-0.0.0-dev}}" +VERSION="${VERSION#v}" +DIST="dist" + +if [ ! -f "${DIST}/w10k" ]; then + echo "ERROR: ${DIST}/w10k not found; run 'make build' first" >&2 + exit 1 +fi + +mkdir -p "${DIST}/completions" +"./${DIST}/w10k" completion bash >"${DIST}/completions/w10k.bash" +"./${DIST}/w10k" completion zsh >"${DIST}/completions/_w10k" +"./${DIST}/w10k" completion fish >"${DIST}/completions/w10k.fish" + +export PACKAGE_NAME="w10k" +export PACKAGE_VERSION="${VERSION}" +export PACKAGE_RELEASE="1" +export PACKAGE_ARCH="amd64" +export PACKAGE_PLATFORM="linux" +export PACKAGE_DESCRIPTION="Deploy Puppet environments and Puppetfile modules as sha-pinned git worktrees" +export PACKAGE_MAINTAINER="Ben Vincent " +export PACKAGE_HOMEPAGE="https://git.unkin.net/unkin/w10k" +export PACKAGE_LICENSE="MIT" + +envsubst "${DIST}/nfpm.yaml" +nfpm pkg --config "${DIST}/nfpm.yaml" --target "${DIST}" --packager rpm +ls -1 "${DIST}"/*.rpm