Merge pull request 'Add w10k: deploy Puppet environments as sha-pinned git worktrees' (#1) from benvin/scaffold into main

Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
2026-11-08 21:41:21 +11:00
23 changed files with 3625 additions and 1 deletions
+4
View File
@@ -0,0 +1,4 @@
/w10k
/w10k-*
dist/
sha256sums.txt
+30
View File
@@ -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
+30
View File
@@ -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
+18
View File
@@ -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
+30
View File
@@ -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
+156
View File
@@ -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
+30
View File
@@ -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
+57
View File
@@ -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)
+1 -1
View File
@@ -1,3 +1,3 @@
# w10k
worktree-r10k: r10k/g10k replacement deploying Puppet environments and Puppetfile modules as sha-pinned git worktrees
worktree-r10k: r10k/g10k replacement deploying Puppet environments and Puppetfile modules as sha-pinned git worktrees
+13
View File
@@ -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
)
+13
View File
@@ -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=
+139
View File
@@ -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
}
+109
View File
@@ -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)
}
}
}
+862
View File
@@ -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
}
File diff suppressed because it is too large Load Diff
+168
View File
@@ -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()
}
+118
View File
@@ -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)
}
}
+87
View File
@@ -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)
}
+349
View File
@@ -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
}
+167
View File
@@ -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)
}
}
})
}
+119
View File
@@ -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
}
+35
View File
@@ -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
+32
View File
@@ -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 <ben@unkin.net>"
export PACKAGE_HOMEPAGE="https://git.unkin.net/unkin/w10k"
export PACKAGE_LICENSE="MIT"
envsubst <packaging/nfpm.yaml >"${DIST}/nfpm.yaml"
nfpm pkg --config "${DIST}/nfpm.yaml" --target "${DIST}" --packager rpm
ls -1 "${DIST}"/*.rpm