Merge origin/main; purge keeps names only skipped branches claim
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful

This commit is contained in:
2026-11-08 21:57:52 +11:00
9 changed files with 991 additions and 176 deletions
+300 -101
View File
@@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"log"
"log/slog"
"maps"
"os"
"path/filepath"
@@ -50,13 +51,16 @@ type Deployer struct {
mu sync.Mutex
flights map[string]*flight
skips map[string]int
counts map[string]int
Timings *slog.Logger
wtLocks sync.Map
}
type flight struct {
done chan struct{}
val string
err error
done chan struct{}
val string
worked bool
err error
}
type deployResult struct {
@@ -72,9 +76,11 @@ type deployResult struct {
}
type resolved struct {
path string
dir string
key string
name string
path string
dir string
key string
cache string
}
func New(cfg *Config, jobs int, grace time.Duration) *Deployer {
@@ -85,14 +91,15 @@ func New(cfg *Config, jobs int, grace time.Duration) *Deployer {
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{}, skips: map[string]int{}}
return &Deployer{runGit: runGit, cfg: cfg, grace: grace, gitTimeout: gt, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}, skips: map[string]int{}, counts: map[string]int{}}
}
func (d *Deployer) once(key string, fn func() (string, error)) (string, error) {
// once runs fn once per key; cache is miss for the caller that did the work, shared for callers that waited on it, hit when fn found it already done.
func (d *Deployer) once(key string, fn func() (string, bool, error)) (string, string, error) {
d.mu.Lock()
f, ok := d.flights[key]
if !ok {
f = &flight{done: make(chan struct{})}
f = &flight{done: make(chan struct{}), worked: true}
d.flights[key] = f
}
d.mu.Unlock()
@@ -100,15 +107,23 @@ func (d *Deployer) once(key string, fn func() (string, error)) (string, error) {
func() {
defer close(f.done)
defer recoverErr(&f.err, key)
f.val, f.err = fn()
f.val, f.worked, f.err = fn()
}()
}
<-f.done
return f.val, f.err
switch {
case !f.worked:
return f.val, "hit", f.err
case ok:
return f.val, "shared", f.err
}
return f.val, "miss", f.err
}
func (d *Deployer) limit(fn func() error) error {
func (d *Deployer) limit(ctx context.Context, fn func() error) error {
t := time.Now()
d.sem <- struct{}{}
addWait(ctx, time.Since(t))
defer func() { <-d.sem }()
return fn()
}
@@ -182,6 +197,8 @@ func recoverErr(err *error, what string) {
// Lock takes an exclusive flock on the cachedir, released by the returned func.
func (d *Deployer) Lock() (func(), error) {
_, end := d.phase(context.Background(), "lock")
defer end()
if err := os.MkdirAll(d.cfg.Cachedir, 0o755); err != nil {
return nil, err
}
@@ -205,24 +222,36 @@ func (d *Deployer) Sources() []*Source {
return out
}
// Deploy builds every environment, or only those named by env or branch; a named deploy skips purge and GC.
func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) error {
want := map[string]bool{}
for _, e := range only {
want[e] = true
}
ctx, end := d.phase(ctx, "run")
d.mu.Lock()
clear(d.skips)
d.mu.Unlock()
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))
maps.DeleteFunc(d.flights, func(_ string, f *flight) bool {
select {
case <-f.done:
return true
default:
return false
}
})
clear(d.skips)
clear(d.counts)
d.mu.Unlock()
var errs []error
var plans []*srcPlan
for _, s := range d.Sources() {
p, err := d.planSource(ctx, s)
if err != nil {
d.count("failed")
errs = append(errs, fmt.Errorf("source %s: %w", s.Name, err))
continue
}
plans = append(plans, p)
}
for e := range want {
if !found[e] {
errs = append(errs, fmt.Errorf("environment %s not found", e))
errs = append(errs, d.selectEnvs(plans, only)...)
for _, p := range plans {
if err := d.deploySource(ctx, p, modules); err != nil {
errs = append(errs, fmt.Errorf("source %s: %w", p.s.Name, err))
}
}
errs = append(errs, d.gc(ctx, len(only) == 0))
@@ -230,17 +259,90 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro
for _, e := range slices.Sorted(maps.Keys(d.skips)) {
log.Printf("environment %s: %d types skipped", e, d.skips[e])
}
var summary []any
for _, k := range []string{"created", "updated", "unchanged", "failed", "removed"} {
summary = append(summary, k, d.counts[k])
}
d.mu.Unlock()
end(summary...)
return errors.Join(errs...)
}
// srcPlan is a source's resolved envs, the branches that got none and why, and the envs to build (nil = all).
type srcPlan struct {
s *Source
envs map[string]envRef
skipped map[string]error
want map[string]bool
}
// selectEnvs resolves args to envs as a full deploy would: env names in any source first, else raw branch names.
func (d *Deployer) selectEnvs(plans []*srcPlan, only []string) []error {
if len(only) == 0 {
return nil
}
var errs []error
for _, p := range plans {
p.want = map[string]bool{}
}
for _, a := range only {
isEnv := slices.ContainsFunc(plans, func(p *srcPlan) bool { _, ok := p.envs[a]; return ok })
hit := false
var why []error
for _, p := range plans {
if isEnv {
if _, ok := p.envs[a]; ok {
p.want[a], hit = true, true
}
continue
}
for name, ref := range p.envs {
if ref.branch == a {
p.want[name], hit = true, true
}
}
for _, err := range p.skipErrs(func(b string) bool {
name, _, _ := p.s.EnvName(b)
return b == a || name == a
}) {
d.count("failed")
why = append(why, fmt.Errorf("source %s: %w", p.s.Name, err))
}
}
if !hit && len(why) == 0 {
why = append(why, fmt.Errorf("environment %s not found", a))
}
errs = append(errs, why...)
}
return errs
}
// skipErrs returns the distinct reasons, in branch order, for skipped branches match accepts.
func (p *srcPlan) skipErrs(match func(string) bool) []error {
var out []error
seen := map[error]bool{}
for _, b := range slices.Sorted(maps.Keys(p.skipped)) {
if err := p.skipped[b]; match(b) && !seen[err] {
seen[err] = true
out = append(out, err)
}
}
return out
}
func (d *Deployer) count(outcome string) {
d.mu.Lock()
d.counts[outcome]++
d.mu.Unlock()
}
type envRef struct{ branch, sha string }
// Environments maps env name -> branch; skipped holds names no branch won because only corrected branches claimed them.
func (d *Deployer) Environments(ctx context.Context, s *Source) (envs map[string]envRef, skipped map[string]bool, errs []error) {
// Environments maps env name -> branch and sha, and each branch that gets no env to why.
func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envRef, map[string]error, error) {
all, err := d.branches(ctx, d.srcMirror(s))
if err != nil {
return nil, nil, []error{err}
return nil, nil, err
}
names := make([]string, 0, len(all))
for b := range all {
@@ -249,13 +351,14 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (envs map[string
sort.Strings(names)
claims := map[string][]string{}
exact := map[string]string{}
skipped := map[string]error{}
for _, b := range names {
if s.Ignored(b) {
continue
}
name, corrected, err := s.EnvName(b)
if err != nil {
errs = append(errs, err)
skipped[b] = err
continue
}
if !corrected {
@@ -263,7 +366,7 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (envs map[string
}
claims[name] = append(claims[name], b)
}
envs, skipped = map[string]envRef{}, map[string]bool{}
envs := map[string]envRef{}
for _, name := range slices.Sorted(maps.Keys(claims)) {
bs := claims[name]
win, isExact := exact[name]
@@ -271,50 +374,61 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (envs map[string
win = bs[0]
}
if win == "" {
errs = append(errs, fmt.Errorf("branches %s all correct to environment %s, skipped", strings.Join(bs, ", "), name))
skipped[name] = true
err := fmt.Errorf("branches %s all correct to environment %s, skipped", strings.Join(bs, ", "), name)
for _, b := range bs {
skipped[b] = err
}
continue
}
for _, b := range bs {
if b != win {
errs = append(errs, fmt.Errorf("branch %s collides with environment %s, skipped", b, name))
skipped[b] = 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, skipped, errs
return envs, skipped, nil
}
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
func (d *Deployer) planSource(ctx context.Context, s *Source) (*srcPlan, error) {
fctx, end := d.phase(ctx, "source.fetch", "source", s.Name)
err := d.syncMirror(fctx, d.srcMirror(s), s.Remote, nil, envRefspecs)
end()
if err != nil {
return nil, err
}
envs, skipped, errs := d.Environments(ctx, s)
if envs == nil {
return errors.Join(errs...)
bctx, end := d.phase(ctx, "source.branches", "source", s.Name)
envs, skipped, err := d.Environments(bctx, s)
end("envs", len(envs))
return &srcPlan{s: s, envs: envs, skipped: skipped}, err
}
func (d *Deployer) deploySource(ctx context.Context, p *srcPlan, modules bool) error {
s, full := p.s, p.want == nil
var errs []error
if full {
errs = p.skipErrs(func(string) bool { return true })
for range errs {
d.count("failed")
}
}
full := len(want) == 0
if err := os.MkdirAll(s.Basedir, 0o755); err != nil {
return err
return errors.Join(append(errs, err)...)
}
var mu sync.Mutex
var wg sync.WaitGroup
for name, ref := range envs {
if !full && !want[name] {
for _, name := range slices.Sorted(maps.Keys(p.envs)) {
ref := p.envs[name]
if !full && !p.want[name] {
continue
}
found[name] = true
if _, corrected, _ := s.EnvName(ref.branch); corrected && s.InvalidBranches == "correct_and_warn" {
log.Printf("warning: branch %s deployed as environment %s", ref.branch, name)
}
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 {
if err := d.deployEnv(ctx, s, name, ref, modules); err != nil {
mu.Lock()
errs = append(errs, fmt.Errorf("environment %s: %w", name, err))
mu.Unlock()
@@ -323,7 +437,7 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, want, found map[
}
wg.Wait()
if full {
errs = append(errs, d.purge(s, envs, skipped))
errs = append(errs, d.purge(s, p.envs, p.skipped))
}
return errors.Join(errs...)
}
@@ -354,15 +468,33 @@ func (d *Deployer) worktreePrefix(sha string) string {
return sha + "-"
}
func (d *Deployer) deployEnv(ctx context.Context, s *Source, name string, ref envRef, modules bool) error {
func (d *Deployer) deployEnv(ctx context.Context, s *Source, name string, ref envRef, modules bool) (err error) {
sha := ref.sha
start := time.Now()
ctx, total := d.phase(ctx, "env.total", "source", s.Name, "env", name)
outcome := "unchanged"
defer func() {
if err != nil {
outcome = "failed"
}
d.count(outcome)
total("outcome", outcome)
}()
defer recoverErr(&err, "environment "+name)
link := filepath.Join(s.Basedir, name)
_, end := d.phase(ctx, "env.resolve", "sha", sha)
cur := d.owned(s, link)
prefix := d.worktreePrefix(sha)
if base := filepath.Base(cur); cur != "" && !modules && strings.HasPrefix(base, prefix) && len(base) == len(prefix)+12 && d.complete(cur) {
base := filepath.Base(cur)
unchanged := cur != "" && !modules && strings.HasPrefix(base, prefix) && len(base) == len(prefix)+12 && d.complete(cur)
end()
if unchanged {
d.emit(ctx, "env.skip", time.Since(start), "reason", "unchanged")
return nil
}
pf, checksum, err := d.puppetfile(ctx, d.srcMirror(s), sha)
pctx, end := d.phase(ctx, "env.puppetfile")
pf, checksum, err := d.puppetfile(pctx, d.srcMirror(s), sha)
end()
if err != nil {
return err
}
@@ -376,24 +508,33 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name string, ref en
}
target := filepath.Join(d.srcWorktrees(s), prefix+hex.EncodeToString(h.Sum(nil))[:12])
if cur == target && d.complete(cur) {
d.emit(ctx, "env.skip", time.Since(start), "reason", "modules_unchanged")
return nil
}
skipped, err := d.once("env:"+target, func() (string, error) {
skipped, _, err := d.once("env:"+target, func() (string, bool, error) {
if d.complete(target) {
return "", nil
return "", false, nil
}
started := d.now().UTC()
if err := d.checkout(ctx, s, sha, target, mods); err != nil {
return "", err
return "", true, err
}
return d.prepare(s, name, ref, checksum, target, mods, started)
v, err := d.prepare(ctx, s, name, ref, checksum, target, mods, started)
return v, true, err
})
if err != nil {
return err
}
if err := Swap(target, link); err != nil {
_, end = d.phase(ctx, "env.swap")
err = Swap(target, link)
end()
if err != nil {
return err
}
outcome = "updated"
if cur == "" {
outcome = "created"
}
if n, _ := strconv.Atoi(skipped); n > 0 {
d.mu.Lock()
d.skips[name] = n
@@ -450,9 +591,12 @@ func (d *Deployer) installModules(ctx context.Context, pf *Puppetfile) ([]resolv
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 {
pctx, end := d.phase(ctx, "module.fetch", "module", m.Name)
_, c, err := d.once("fetch:"+mirror, func() (string, bool, error) {
return "", true, d.syncMirror(pctx, mirror, m.Git, modFetchOpts, modRefspecs)
})
end("cache", c)
if err != nil {
return resolved{}, err
}
var cands []string
@@ -468,41 +612,47 @@ func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) {
default:
cands = []string{"refs/w10k/HEAD"}
}
sha, err := d.revParse(ctx, mirror, cands...)
pctx, end = d.phase(ctx, "module.resolve", "module", m.Name)
sha, err := d.revParse(pctx, mirror, cands...)
dir := d.path("modules", key, sha)
end()
if err != nil {
return resolved{}, err
}
dir := d.path("modules", key, sha)
_, err = d.once("mod:"+dir, func() (string, error) {
pctx, end = d.phase(ctx, "module.worktree", "module", m.Name)
_, c, err = d.once("mod:"+dir, func() (string, bool, error) {
if d.complete(dir) {
return "", nil
return "", false, nil
}
tmp := dir + ".tmp"
for _, p := range []string{tmp, dir} {
if err := d.removeWorktree(ctx, mirror, p); err != nil {
return "", err
if err := d.removeWorktree(pctx, mirror, p); err != nil {
return "", true, err
}
}
if _, err := d.git(ctx, mirror, "worktree", "add", "--detach", "-q", "--", tmp, sha); err != nil {
return "", err
if _, err := d.git(pctx, mirror, "worktree", "add", "--detach", "-q", "--", tmp, sha); err != nil {
return "", true, err
}
if _, err := d.git(ctx, mirror, "worktree", "move", "--", tmp, dir); err != nil {
return "", err
if _, err := d.git(pctx, mirror, "worktree", "move", "--", tmp, dir); err != nil {
return "", true, err
}
return "", d.markDone(dir, nil)
return "", true, d.markDone(dir, nil)
})
return resolved{dir: dir, key: "git " + m.Git + " " + sha}, err
end("cache", c)
return resolved{name: m.Name, dir: dir, key: "git " + m.Git + " " + sha, cache: c}, 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) {
pctx, end := d.phase(ctx, "module.resolve", "module", slug)
v, c, err := d.once("latest:"+base+" "+slug, func() (string, bool, error) {
var v string
err := d.limit(func() (err error) { v, err = forgeLatest(ctx, base, slug); return err })
return v, err
err := d.limit(pctx, func() (err error) { v, err = forgeLatest(ctx, base, slug); return err })
return v, true, err
})
end("cache", c)
if err != nil {
return resolved{}, err
}
@@ -510,19 +660,35 @@ func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (reso
}
release := slug + "-" + version
dir := d.path("forge", release+"-"+shortHash(base))
_, err := d.once("forge:"+dir, func() (string, error) {
start := time.Now()
var dl, ex, wait time.Duration
_, c, err := d.once("forge:"+dir, func() (string, bool, error) {
if d.complete(dir) {
return "", nil
return "", false, nil
}
if err := os.RemoveAll(dir); err != nil {
return "", err
return "", true, err
}
if err := d.limit(func() error { return forgeInstall(ctx, base, release, dir) }); err != nil {
return "", err
q := time.Now()
if err := d.limit(ctx, func() error {
wait = time.Since(q)
t := time.Now()
var err error
dl, err = forgeInstall(ctx, base, release, dir)
ex = time.Since(t) - dl
dl += wait
return err
}); err != nil {
return "", true, err
}
return "", d.markDone(dir, nil)
return "", true, d.markDone(dir, nil)
})
return resolved{dir: dir, key: "forge " + base + " " + release}, err
if c != "miss" {
dl = time.Since(start)
}
d.emit(ctx, "module.download", dl, "module", slug, "cache", c, "wait", wait.Round(time.Microsecond))
d.emit(ctx, "module.extract", ex, "module", slug, "cache", c)
return resolved{name: slug, dir: dir, key: "forge " + base + " " + release, cache: c}, err
}
func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string, mods []resolved) error {
@@ -536,7 +702,10 @@ func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string,
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 {
wctx, end := d.phase(ctx, "env.worktree")
_, err := d.git(wctx, mirror, "worktree", "add", "--detach", "-q", "--", target, sha)
end()
if err != nil {
return err
}
root, err := os.OpenRoot(target)
@@ -545,7 +714,10 @@ func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string,
}
defer func() { _ = root.Close() }()
for _, mod := range mods {
if err := linkModule(root, mod.path, mod.dir); err != nil {
_, end := d.phase(ctx, "module.link", "module", mod.name, "cache", mod.cache)
err := linkModule(root, mod.path, mod.dir)
end()
if err != nil {
return err
}
}
@@ -567,17 +739,22 @@ func linkModule(root *os.Root, rel, dir string) error {
}
// 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, name string, ref envRef, checksum, target string, mods []resolved, started time.Time) (string, error) {
func (d *Deployer) prepare(ctx context.Context, s *Source, name string, ref envRef, checksum, target string, mods []resolved, started time.Time) (string, error) {
var skipped []error
if d.cfg.W10k.GenerateTypes {
var err error
if skipped, err = gentypes.Generate(target, d.path("modules"), d.path("forge")); err != nil {
_, end := d.phase(ctx, "env.generate_types")
st, err := gentypes.Generate(target, d.path("modules"), d.path("forge"))
end("generated", st.Generated, "skipped", len(st.Skipped), "up_to_date", st.UpToDate)
if err != nil {
return "", fmt.Errorf("generate types: %w", err)
}
skipped = st.Skipped
for _, e := range skipped {
log.Printf("error: environment %s: generate types: skipped %v", name, e)
}
}
_, end := d.phase(ctx, "env.marker")
defer end()
r := deployResult{
Name: ref.branch,
Signature: ref.sha,
@@ -656,13 +833,23 @@ func Swap(target, link string) error {
return os.Rename(tmp, link)
}
func (d *Deployer) purge(s *Source, envs map[string]envRef, skipped map[string]bool) error {
// purge removes owned envs no branch claims; a name only skipped branches claim keeps its live env.
func (d *Deployer) purge(s *Source, envs map[string]envRef, skipped map[string]error) error {
entries, err := os.ReadDir(s.Basedir)
if err != nil {
return err
}
keep := map[string]bool{}
for name := range envs {
keep[name] = true
}
for b := range skipped {
if name, _, err := s.EnvName(b); err == nil {
keep[name] = true
}
}
for _, e := range entries {
if _, ok := envs[e.Name()]; ok || skipped[e.Name()] {
if keep[e.Name()] {
continue
}
link := filepath.Join(s.Basedir, e.Name())
@@ -672,6 +859,7 @@ func (d *Deployer) purge(s *Source, envs map[string]envRef, skipped map[string]b
if err := os.Remove(link); err != nil {
return err
}
d.count("removed")
log.Printf("environment %s removed", e.Name())
}
return nil
@@ -696,11 +884,14 @@ func (d *Deployer) Live(s *Source) (map[string]string, error) {
}
type gcRun struct {
d *Deployer
ctx context.Context
marks map[string]time.Time
seen map[string]bool
errs []error
d *Deployer
ctx context.Context
marks map[string]time.Time
seen map[string]bool
errs []error
marked int
removed int
delDur time.Duration
}
// collect marks p on first sight and removes it only once a previous run's mark is older than the grace period.
@@ -709,16 +900,21 @@ func (g *gcRun) collect(p string, remove func() error) {
t, ok := g.marks[p]
if !ok {
g.marks[p] = g.d.now()
g.marked++
log.Printf("gc: marked %s", p)
return
}
if g.d.now().Sub(t) < g.d.grace {
return
}
if err := remove(); err != nil {
rt := time.Now()
err := remove()
g.delDur += time.Since(rt)
if err != nil {
g.errs = append(g.errs, err)
return
}
g.removed++
delete(g.marks, p)
log.Printf("gc: removed %s", p)
}
@@ -757,6 +953,7 @@ 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) {
start := time.Now()
g := &gcRun{d: d, ctx: ctx, marks: d.loadMarks(), seen: map[string]bool{}}
defer func() {
for p := range g.marks {
@@ -765,6 +962,8 @@ func (d *Deployer) gc(ctx context.Context, sweep bool) (err error) {
}
}
err = errors.Join(append(g.errs, d.saveMarks(g.marks))...)
d.emit(ctx, "gc.mark", time.Since(start)-g.delDur, "marked", g.marked, "pending", len(g.marks))
d.emit(ctx, "gc.delete", g.delDur, "removed", g.removed)
}()
liveEnv := map[string]bool{}
+465
View File
@@ -6,6 +6,8 @@ import (
"encoding/json"
"fmt"
"log"
"log/slog"
"maps"
"net"
"net/http"
"net/http/cgi"
@@ -13,8 +15,11 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
@@ -792,6 +797,312 @@ func TestGCKeepsModulesOfRemovedSource(t *testing.T) {
}
}
func TestNamedDeployTouchesOnlyNamed(t *testing.T) {
f := newFixture(t)
old := commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile(), "manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "gone")
commit(t, f.control, map[string]string{"manifests/site.pp": "node other {}\n"})
gitT(t, f.control, "branch", "gone2")
commit(t, f.control, map[string]string{"manifests/site.pp": "node default { }\n"})
gitT(t, f.control, "branch", "benvin/foo-bar")
f.mustDeploy(false)
gone, gone2 := f.env("gone"), f.env("gone2")
gitT(t, f.control, "branch", "-D", "gone", "gone2")
f.mustDeploy(false)
f.clock = f.clock.Add(11 * time.Minute)
marks := func() map[string]time.Time {
m := map[string]time.Time{}
if err := json.Unmarshal([]byte(readFileT(t, f.cache(gcStateFile))), &m); err != nil {
t.Fatal(err)
}
return m
}
before := marks()
if _, ok := before[gone2]; !ok {
t.Fatalf("gone2 must be marked: %v", before)
}
gitT(t, f.control, "branch", "-f", "benvin/foo-bar", old)
main := f.env("main")
if err := f.deploy(false, "benvin/foo-bar"); err != nil {
t.Fatal(err)
}
if f.env("benvin_foo_bar") != gone {
t.Fatal("a raw branch name deploys its sanitised env, reviving the matching worktree")
}
delete(before, gone)
if f.env("main") != main || !exists(gone2) || !maps.Equal(marks(), before) {
t.Fatalf("a named deploy must clear only the marks of what it revives: %v", marks())
}
sha := commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"})
if err := f.deploy(false, "main"); err != nil || !strings.HasPrefix(filepath.Base(f.env("main")), sha+"-") {
t.Fatalf("env name deploys: %v", err)
}
if err := f.deploy(false, "main", "nope"); err == nil || !strings.Contains(err.Error(), "nope not found") {
t.Fatalf("unknown env must error: %v", err)
}
if !exists(gone2) {
t.Fatal("named deploys never GC")
}
}
func TestNamedDeployCollisionLoserKeepsOut(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", "a_b")
win := commit(t, f.control, map[string]string{"manifests/site.pp": "node a {}\n"})
gitT(t, f.control, "checkout", "-q", "-b", "a-b")
commit(t, f.control, map[string]string{"manifests/site.pp": "node b {}\n"})
_ = f.deploy(false)
err := f.deploy(false, "a-b")
if !strings.HasPrefix(filepath.Base(f.env("a_b")), win+"-") {
t.Fatalf("named deploy of collision loser a-b took env a_b: %s", f.env("a_b"))
}
if err == nil || !strings.Contains(err.Error(), "a-b collides") {
t.Fatalf("want collision error for a-b, got %v", err)
}
if err := f.deploy(false, "a_b"); err != nil || !strings.HasPrefix(filepath.Base(f.env("a_b")), win+"-") {
t.Fatalf("named deploy of a_b must keep the full-deploy winner: %v", err)
}
}
func TestNamedDeployCorrectedCollisionSkipsAll(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "a-b")
gitT(t, f.control, "branch", "a.b")
for _, arg := range []string{"a.b", "a_b"} {
err := f.deploy(false, arg)
if exists(filepath.Join(f.basedir, "a_b")) {
t.Fatalf("deploy %s built a_b, which a full deploy skips", arg)
}
if err == nil || !strings.Contains(err.Error(), "a-b") || !strings.Contains(err.Error(), "a.b") {
t.Fatalf("deploy %s: want collision error naming both branches, got %v", arg, err)
}
}
}
func TestNamedDeployPrefixedSources(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "benvin/x")
pbase := filepath.Join(f.root, "code", "penvs")
p := &Source{Name: "p", Remote: f.control, Basedir: pbase, Prefix: "p", InvalidBranches: "correct_and_warn"}
f.cfg.Sources["p"] = p
penv := func(name string) string { return f.deployer().owned(p, filepath.Join(pbase, name)) }
var logs bytes.Buffer
log.SetOutput(&logs)
defer log.SetOutput(os.Stderr)
if err := f.deploy(false, "main"); err != nil || f.env("main") == "" {
t.Fatalf("deploy main: %v", err)
}
if strings.Contains(logs.String(), "benvin/x") {
t.Fatalf("named deploy warned about a branch it did not deploy:\n%s", logs.String())
}
if penv("p_main") != "" {
t.Fatal("env name main also deployed branch main of source p as p_main")
}
if err := f.deploy(false, "p_main"); err != nil || penv("p_main") == "" {
t.Fatalf("deploy p_main: %v", err)
}
if err := f.deploy(false, "benvin/x"); err != nil || f.env("benvin_x") == "" || penv("p_benvin_x") == "" {
t.Fatalf("raw branch benvin/x must deploy in every source: %v", err)
}
}
func TestNamedDeployIgnoresUnrelatedInvalid(t *testing.T) {
f := newFixture(t)
f.cfg.Sources["unkin"].InvalidBranches = "error"
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "bad-name")
if err := f.deploy(false, "main"); err != nil {
t.Fatalf("unrelated invalid branch failed named deploy: %v", err)
}
if err := f.deploy(false, "bad-name"); err == nil || !strings.Contains(err.Error(), "not a valid environment name") {
t.Fatalf("named invalid branch must error: %v", err)
}
}
func timingLines(s string) []map[string]string {
var out []map[string]string
for line := range strings.Lines(s) {
kv := map[string]string{}
for _, f := range strings.Fields(line) {
k, v, _ := strings.Cut(f, "=")
kv[k] = v
}
out = append(out, kv)
}
return out
}
func TestTimingsPhases(t *testing.T) {
f := newFixture(t)
f.cfg.W10k.GenerateTypes = true
commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()})
var buf bytes.Buffer
d := f.deployer()
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
unlock, err := d.Lock()
if err != nil {
t.Fatal(err)
}
unlock()
src := map[string]string{"source.fetch": "", "source.branches": "", "env.resolve": "", "gc.mark": "", "gc.delete": "", "run": ""}
with := func(m map[string]string) map[string]string {
for k, v := range src {
m[k] = v
}
return m
}
runs := []struct {
modules bool
want map[string]string
}{
{false, with(map[string]string{
"lock": "", "env.puppetfile": "", "module.resolve": ",,miss", "module.fetch": "miss,shared", "module.worktree": "miss,shared",
"module.download": "miss,miss", "module.extract": "miss,miss", "module.link": "miss,miss,miss,shared",
"env.worktree": "", "env.generate_types": "", "env.marker": "", "env.swap": "", "env.total": "created",
})},
{false, with(map[string]string{"env.skip": "unchanged", "env.total": "unchanged"})},
{true, with(map[string]string{
"env.puppetfile": "", "module.resolve": ",,miss", "module.fetch": "miss,shared", "module.worktree": "hit,hit",
"module.download": "hit,hit", "module.extract": "hit,hit", "env.skip": "modules_unchanged", "env.total": "unchanged",
})},
}
var all strings.Builder
for i, r := range runs {
if err := d.Deploy(context.Background(), nil, r.modules); err != nil {
t.Fatal(err)
}
labels := map[string][]string{}
for _, kv := range timingLines(buf.String()) {
labels[kv["phase"]] = append(labels[kv["phase"]], kv["cache"]+kv["outcome"]+kv["reason"])
if strings.HasPrefix(kv["phase"], "module.") && (kv["source"] != "unkin" || kv["env"] != "main") {
t.Errorf("run %d: module phase lacks inherited source/env: %v", i, kv)
}
}
got := map[string]string{}
for k, v := range labels {
slices.Sort(v)
got[k] = strings.Join(v, ",")
}
if !maps.Equal(got, r.want) {
t.Errorf("run %d labels:\n got %v\nwant %v", i, got, r.want)
}
all.WriteString(buf.String())
buf.Reset()
}
out := all.String()
for _, want := range []string{
" dur=", " wait=", " source=unkin", " env=main", " module=bind", " module=acme-thing",
" generated=", " up_to_date=", " skipped=", " marked=", " removed=", " created=1", " updated=", " unchanged=1", " failed=",
} {
if !strings.Contains(out, want) {
t.Errorf("timings lack %q", want)
}
}
if t.Failed() {
t.Log(out)
}
}
func TestTimingsColdCacheHasNoHits(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()})
var buf bytes.Buffer
d := f.deployer()
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
if err := d.Deploy(context.Background(), nil, false); err != nil {
t.Fatal(err)
}
for _, kv := range timingLines(buf.String()) {
if kv["cache"] == "hit" {
t.Errorf("cold cachedir reports %s module=%s cache=hit dur=%s", kv["phase"], kv["module"], kv["dur"])
}
}
}
func TestTimingsCacheLabels(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()})
for run, want := range []string{"miss", "hit"} {
var buf bytes.Buffer
d := f.deployer()
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
if err := d.Deploy(context.Background(), nil, true); err != nil {
t.Fatal(err)
}
misses := 0
for _, kv := range timingLines(buf.String()) {
switch kv["phase"] {
case "module.download":
if kv["module"] == "acme-thing" && kv["cache"] != want {
t.Errorf("run %d: acme-thing download cache=%s, want %s", run, kv["cache"], want)
}
case "module.worktree":
if kv["cache"] == "miss" {
misses++
}
}
}
if (run == 0) != (misses > 0) {
t.Errorf("run %d: module.worktree misses=%d", run, misses)
}
}
}
func TestTimingsWaitWithinDur(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()})
for _, b := range []string{"a", "b", "c", "d", "e", "f", "g", "h"} {
gitT(t, f.control, "branch", b)
}
var buf bytes.Buffer
d := New(f.cfg, 1, 10*time.Minute)
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
if err := d.Deploy(context.Background(), nil, false); err != nil {
t.Fatal(err)
}
contended := false
for _, kv := range timingLines(buf.String()) {
if kv["phase"] == "run" || kv["phase"] == "env.total" {
if _, ok := kv["wait"]; ok {
t.Errorf("aggregate phase reports wait: %v", kv)
}
}
w, ok := kv["wait"]
if !ok {
continue
}
wd, err1 := time.ParseDuration(w)
dd, err2 := time.ParseDuration(kv["dur"])
if err1 != nil || err2 != nil || wd > dd {
t.Errorf("wait must not exceed dur: %v", kv)
}
if wd > 0 && kv["phase"] != "module.download" {
contended = true
}
}
if !contended {
t.Fatalf("-j1 with 9 envs reports no wait on any phase() leaf:\n%s", buf.String())
}
}
func TestTimingsOffEmitsNothing(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()})
var buf bytes.Buffer
prev := slog.Default()
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, nil)))
defer slog.SetDefault(prev)
f.mustDeploy(false)
f.mustDeploy(false)
if strings.Contains(buf.String(), "phase=") {
t.Fatalf("timings off must emit nothing:\n%s", buf.String())
}
}
func TestPuppetfileLocalRepoRejected(t *testing.T) {
f := newFixture(t)
secret := filepath.Join(f.root, "secret")
@@ -903,10 +1214,20 @@ func TestPanicFailsOnlyItsEnv(t *testing.T) {
}
return runGit(ctx, dir, args...)
}
var buf bytes.Buffer
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
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)
}
for _, kv := range timingLines(buf.String()) {
if kv["phase"] == "env.total" && kv["env"] == "bad" && kv["outcome"] != "failed" {
t.Errorf("panicking env outcome=%s, want failed", kv["outcome"])
}
}
if !strings.Contains(buf.String(), " created=1 updated=0 unchanged=0 failed=1 ") {
t.Errorf("summary must count the panic as failed:\n%s", buf.String())
}
if f.env("main") == "" || f.env("bad") != "" {
t.Fatalf("main=%q bad=%q", f.env("main"), f.env("bad"))
}
@@ -915,6 +1236,26 @@ func TestPanicFailsOnlyItsEnv(t *testing.T) {
}
}
func TestSourceErrorsCountFailed(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "\n"})
gitT(t, f.control, "branch", "bad-name")
cfg, err := ParseConfig(fmt.Appendf(nil, "cachedir: %s\nsources:\n unkin:\n remote: %s\n basedir: %s\n invalid_branches: error\n gone:\n remote: %s\n basedir: %s\n",
f.cfg.Cachedir, f.control, f.basedir, filepath.Join(f.root, "missing"), filepath.Join(f.root, "gone-envs")))
if err != nil {
t.Fatal(err)
}
var buf bytes.Buffer
d := New(cfg, 4, 10*time.Minute)
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
if err := d.Deploy(context.Background(), nil, false); err == nil {
t.Fatal("source errors not returned")
}
if !strings.Contains(buf.String(), " created=1 updated=0 unchanged=0 failed=2 ") {
t.Errorf("summary must count the fetch and branch errors as failed:\n%s", buf.String())
}
}
func TestConcurrentWorktreeAddsOneMirror(t *testing.T) {
f := newFixture(t)
for i := range 40 {
@@ -1181,3 +1522,127 @@ func TestCorrectedBranchCollisionKeepsLiveEnv(t *testing.T) {
t.Fatal("live feature_x worktree must survive GC past grace")
}
}
func TestConcurrentDeploySharesInFlightFetch(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()})
d := f.deployer()
var srcFetches, modFetches atomic.Int32
bStarted := make(chan struct{})
var once sync.Once
d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) {
if slices.Contains(args, "fetch") {
switch {
case slices.Contains(args, f.control):
if srcFetches.Add(1) == 2 {
once.Do(func() { close(bStarted) })
}
case slices.Contains(args, f.mod):
if modFetches.Add(1) == 1 {
<-bStarted
}
}
}
return runGit(ctx, dir, args...)
}
errc := make(chan error, 2)
go func() { errc <- d.Deploy(context.Background(), nil, false) }()
for modFetches.Load() == 0 {
runtime.Gosched()
}
go func() { errc <- d.Deploy(context.Background(), nil, false) }()
<-errc
<-errc
if n := modFetches.Load(); n != 1 {
t.Fatalf("module mirror fetched %d times; the second Deploy dropped the first's in-flight fetch", n)
}
}
func TestTimingsRemovalCounts(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "\n"})
gitT(t, f.control, "checkout", "-q", "-b", "x")
commit(t, f.control, map[string]string{"manifests/site.pp": "# x\n"})
gitT(t, f.control, "checkout", "-q", "main")
f.mustDeploy(false)
gitT(t, f.control, "branch", "-D", "x")
run := func() map[string]map[string]string {
t.Helper()
var buf bytes.Buffer
d := f.deployer()
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
if err := d.Deploy(context.Background(), nil, false); err != nil {
t.Fatal(err)
}
got := map[string]map[string]string{}
for _, kv := range timingLines(buf.String()) {
got[kv["phase"]] = kv
}
return got
}
got := run()
if got["run"]["removed"] != "1" || got["gc.mark"]["marked"] != "1" || got["gc.delete"]["removed"] != "0" {
t.Errorf("removal run: run=%v gc.mark=%v gc.delete=%v", got["run"], got["gc.mark"], got["gc.delete"])
}
f.clock = f.clock.Add(11 * time.Minute)
got = run()
if got["run"]["removed"] != "0" || got["gc.mark"]["marked"] != "0" || got["gc.delete"]["removed"] != "1" {
t.Errorf("past grace: run=%v gc.mark=%v gc.delete=%v", got["run"], got["gc.mark"], got["gc.delete"])
}
}
func TestTimingsPanickingFlightIsMiss(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()})
d := f.deployer()
d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) {
if slices.Contains(args, "fetch") && slices.Contains(args, f.mod) {
panic("boom")
}
return runGit(ctx, dir, args...)
}
var buf bytes.Buffer
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
if err := d.Deploy(context.Background(), nil, false); err == nil || !strings.Contains(err.Error(), "panic: boom") {
t.Fatalf("panic not reported: %v", err)
}
var got []string
for _, kv := range timingLines(buf.String()) {
if kv["phase"] == "module.fetch" {
got = append(got, kv["cache"])
}
}
slices.Sort(got)
if !slices.Equal(got, []string{"miss", "shared"}) {
t.Errorf("panicking fetch cache labels %v, want [miss shared]\n%s", got, buf.String())
}
}
func TestTimingsWorktreeLockWait(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "\n"})
d := f.deployer()
var buf bytes.Buffer
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) {
if slices.Contains(args, "remove") {
mu := &sync.Mutex{}
mu.Lock()
d.wtLocks.Store(dir, mu)
time.AfterFunc(50*time.Millisecond, mu.Unlock)
}
return runGit(ctx, dir, args...)
}
if err := d.Deploy(context.Background(), nil, false); err != nil {
t.Fatal(err)
}
for _, kv := range timingLines(buf.String()) {
if kv["phase"] == "env.worktree" {
if w, err := time.ParseDuration(kv["wait"]); err != nil || w < 25*time.Millisecond {
t.Errorf("env.worktree wait=%s, want the worktree lock wait", kv["wait"])
}
return
}
}
t.Fatalf("no env.worktree line:\n%s", buf.String())
}
+10 -7
View File
@@ -73,24 +73,27 @@ func forgeLatest(ctx context.Context, base, slug string) (string, error) {
return r.CurrentRelease.Version, nil
}
func forgeInstall(ctx context.Context, base, release, dir string) error {
// forgeInstall returns the time spent reading the download, so the rest of the call is extraction.
func forgeInstall(ctx context.Context, base, release, dir string) (time.Duration, error) {
start := time.Now()
body, err := forgeGet(ctx, base+"/v3/files/"+release+".tar.gz")
if err != nil {
return err
return 0, err
}
defer func() { _ = body.Close() }()
if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil {
return err
return 0, err
}
tmp, err := os.MkdirTemp(filepath.Dir(dir), ".tmp-")
if err != nil {
return err
return 0, err
}
if err := extract(&capReader{r: body, n: maxForgeDownload}, tmp, maxForgeExtracted); err != nil {
tr := &timedReader{r: &capReader{r: body, n: maxForgeDownload}, d: time.Since(start)}
if err := extract(tr, tmp, maxForgeExtracted); err != nil {
_ = os.RemoveAll(tmp)
return fmt.Errorf("%s: %w", release, err)
return tr.d, fmt.Errorf("%s: %w", release, err)
}
return os.Rename(tmp, dir)
return tr.d, os.Rename(tmp, dir)
}
// capReader fails once more than n bytes are read, so an oversized stream errors instead of being truncated silently.
+4 -2
View File
@@ -30,14 +30,16 @@ func runGit(ctx context.Context, dir string, args ...string) (string, error) {
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.
// 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, and both waits count as wait.
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{})
t := time.Now()
mu.(*sync.Mutex).Lock()
addWait(ctx, time.Since(t))
defer mu.(*sync.Mutex).Unlock()
}
err = d.limit(func() error {
err = d.limit(ctx, func() error {
ctx, cancel := context.WithTimeout(ctx, d.gitTimeout)
defer cancel()
out, err = d.runGit(ctx, dir, args...)
+72
View File
@@ -0,0 +1,72 @@
package deploy
import (
"context"
"io"
"slices"
"sync/atomic"
"time"
)
type spanKey struct{}
type span struct {
parent *span
attrs []any
wait atomic.Int64
kids atomic.Bool
}
func spanOf(ctx context.Context) *span {
s, _ := ctx.Value(spanKey{}).(*span)
return s
}
func addWait(ctx context.Context, w time.Duration) {
if s := spanOf(ctx); s != nil {
s.wait.Add(int64(w))
}
}
// phase times one unit of work; nested phases inherit attrs, and leaf phases report their -j slot and worktree lock waits as wait.
func (d *Deployer) phase(ctx context.Context, name string, attrs ...any) (context.Context, func(more ...any)) {
if d.Timings == nil {
return ctx, func(...any) {}
}
s := &span{parent: spanOf(ctx), attrs: attrs}
if s.parent != nil {
s.parent.kids.Store(true)
s.attrs = append(slices.Clip(s.parent.attrs), attrs...)
}
start := time.Now()
ctx = context.WithValue(ctx, spanKey{}, s)
return ctx, func(more ...any) {
if !s.kids.Load() {
more = append(more, "wait", time.Duration(s.wait.Load()).Round(time.Microsecond))
}
d.emit(ctx, name, time.Since(start), more...)
}
}
func (d *Deployer) emit(ctx context.Context, name string, dur time.Duration, args ...any) {
if d.Timings == nil {
return
}
line := []any{"phase", name, "dur", dur.Round(time.Microsecond)}
if s := spanOf(ctx); s != nil {
line = append(line, s.attrs...)
}
d.Timings.Info("timing", append(line, args...)...)
}
type timedReader struct {
r io.Reader
d time.Duration
}
func (t *timedReader) Read(p []byte) (int, error) {
s := time.Now()
n, err := t.r.Read(p)
t.d += time.Since(s)
return n, err
}
+41 -33
View File
@@ -42,9 +42,14 @@ type gen struct {
roots []string
}
// Stats counts Generate's inputs; Skipped holds inputs that failed to parse and keep any previous output.
type Stats struct {
Generated, UpToDate int
Skipped []error
}
// Generate writes <env>/.resource_types; every file it reads must resolve inside env or one of roots.
// Inputs that fail to parse are returned as skipped and keep any previous output.
func Generate(env string, roots ...string) (skipped []error, err error) {
func Generate(env string, roots ...string) (st Stats, err error) {
g := &gen{}
for i, r := range append([]string{env}, roots...) {
real, err := filepath.EvalSymlinks(r)
@@ -52,31 +57,31 @@ func Generate(env string, roots ...string) (skipped []error, err error) {
continue
}
if err != nil {
return nil, err
return st, err
}
g.roots = append(g.roots, real)
}
g.env = g.roots[0]
mods, err := g.modules()
if err != nil {
return nil, err
return st, err
}
var inputs []string
providers := map[string][]string{}
for _, m := range mods {
files, err := g.glob(filepath.Join(m, "lib", "puppet", "type"))
if err != nil {
return nil, err
return st, err
}
inputs = append(inputs, files...)
dirs, err := g.list(filepath.Join(m, "lib", "puppet", "provider"))
if err != nil {
return nil, err
return st, err
}
for _, d := range dirs {
files, err := g.glob(d)
if err != nil {
return nil, err
return st, err
}
for _, f := range files {
typ := filepath.Base(d)
@@ -89,7 +94,7 @@ func Generate(env string, roots ...string) (skipped []error, err error) {
sort.Strings(inputs)
out, err := openOut(g.env)
if err != nil {
return nil, err
return st, err
}
defer func() { _ = out.Close() }()
keep := map[string]bool{}
@@ -98,32 +103,35 @@ func Generate(env string, roots ...string) (skipped []error, err error) {
}
dir, err := out.Open(".")
if err != nil {
return nil, err
return st, err
}
entries, err := dir.ReadDir(-1)
_ = dir.Close()
if err != nil {
return nil, err
return st, err
}
for _, e := range entries {
if !keep[e.Name()] && (e.Type().IsRegular() || e.Type()&fs.ModeSymlink != 0) {
if err := out.Remove(e.Name()); err != nil {
return nil, err
return st, err
}
}
}
var errs []error
for _, in := range inputs {
if err := generateOne(in, out, providers[strings.TrimSuffix(filepath.Base(in), ".rb")], g.libs(mods, in)); err != nil {
err = fmt.Errorf("%s: %w", strings.TrimPrefix(in, g.env+"/"), err)
if errors.As(err, new(skipErr)) {
skipped = append(skipped, err)
} else {
errs = append(errs, err)
}
wrote, err := generateOne(in, out, providers[strings.TrimSuffix(filepath.Base(in), ".rb")], g.libs(mods, in))
switch {
case err == nil && wrote:
st.Generated++
case err == nil:
st.UpToDate++
case errors.As(err, new(skipErr)):
st.Skipped = append(st.Skipped, fmt.Errorf("%s: %w", strings.TrimPrefix(in, g.env+"/"), err))
default:
errs = append(errs, fmt.Errorf("%s: %w", strings.TrimPrefix(in, g.env+"/"), err))
}
}
return skipped, errors.Join(errs...)
return st, errors.Join(errs...)
}
// openOut returns an os.Root on <env>/.resource_types, refusing anything but a real directory there.
@@ -148,7 +156,7 @@ func openOut(env string) (*os.Root, error) {
}
// generateOne writes the type defined by in; providers are the first-found provider files the autoloader loads for it.
func generateOne(in string, out *os.Root, providers []string, resolve Resolver) (err error) {
func generateOne(in string, out *os.Root, providers []string, resolve Resolver) (wrote bool, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v", r)
@@ -156,20 +164,20 @@ func generateOne(in string, out *os.Root, providers []string, resolve Resolver)
}()
ifi, err := os.Stat(in)
if err != nil {
return err
return false, err
}
name := strings.TrimSuffix(filepath.Base(in), ".rb")
dst := name + ".pp"
if ofi, err := out.Lstat(dst); err == nil && ofi.Mode().IsRegular() && ofi.ModTime().Equal(ifi.ModTime()) {
return nil
return false, nil
}
src, err := os.ReadFile(in)
if err != nil {
return err
return false, err
}
types, err := parseFile(string(src), resolve)
if err != nil {
return unparsed(err)
return false, unparsed(err)
}
var t *rtype
for _, c := range types {
@@ -178,36 +186,36 @@ func generateOne(in string, out *os.Root, providers []string, resolve Resolver)
}
}
if t == nil {
return skipErr{fmt.Errorf("custom type %q was not defined", name)}
return false, skipErr{fmt.Errorf("custom type %q was not defined", name)}
}
names, err := providerNames(t, providers)
if err != nil {
return err
return false, err
}
body, err := render(t, names, time.Now())
if err != nil {
return unparsed(err)
return false, unparsed(err)
}
tmp := "." + dst + ".tmp"
if err := out.RemoveAll(tmp); err != nil {
return err
return false, err
}
f, err := out.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
if err != nil {
return err
return false, err
}
defer func() { _ = out.Remove(tmp) }()
if _, err := f.WriteString(body); err != nil {
_ = f.Close()
return err
return false, err
}
if err := f.Close(); err != nil {
return err
return false, err
}
if err := out.Chtimes(tmp, ifi.ModTime(), ifi.ModTime()); err != nil {
return err
return false, err
}
return out.Rename(tmp, dst)
return true, out.Rename(tmp, dst)
}
// providerNames returns the providers puppet registers for t, or a skip when a provider file is not a recognised provide call.
+19 -15
View File
@@ -83,12 +83,12 @@ func TestReviewSkips(t *testing.T) {
if err := os.CopyFS(work, os.DirFS("testdata/env")); err != nil {
t.Fatal(err)
}
skipped, err := Generate(work)
st, err := Generate(work)
if err != nil {
t.Fatal(err)
}
got := map[string]string{}
for _, s := range skipped {
for _, s := range st.Skipped {
file, why, _ := strings.Cut(s.Error(), ": ")
got[strings.TrimSuffix(filepath.Base(file), ".rb")] = why
}
@@ -415,17 +415,21 @@ func TestGenerateFiles(t *testing.T) {
if err := os.Chtimes(bar, in.ModTime(), in.ModTime()); err != nil {
t.Fatal(err)
}
if _, err := Generate(env, cache); err != nil {
st, err := Generate(env, cache)
if err != nil {
t.Fatal(err)
}
if st.Generated != 0 || st.UpToDate != 2 {
t.Fatalf("unchanged inputs must count as up to date: %+v", st)
}
if readFile(t, bar) != "edited" {
t.Fatal("output with the input's mtime is up to date and must be kept")
}
if err := os.Chtimes(bar, in.ModTime(), in.ModTime().Add(-time.Hour)); err != nil {
t.Fatal(err)
}
if _, err := Generate(env, cache); err != nil {
t.Fatal(err)
if st, err = Generate(env, cache); err != nil || st.Generated != 1 || st.UpToDate != 1 {
t.Fatalf("got %v, %+v", err, st)
}
if readFile(t, bar) == "edited" {
t.Fatal("output with a different mtime must be regenerated")
@@ -456,9 +460,9 @@ func TestGenerateErrors(t *testing.T) {
if err := os.Chtimes(filepath.Join(env, OutDir, "bad.pp"), old, old); err != nil {
t.Fatal(err)
}
skipped, err := Generate(env)
if err != nil || len(skipped) != 1 || !strings.Contains(skipped[0].Error(), "modules/m/lib/puppet/type/bad.rb: line 2:") {
t.Fatalf("got %v, skipped %v", err, skipped)
st, err := Generate(env)
if err != nil || len(st.Skipped) != 1 || !strings.Contains(st.Skipped[0].Error(), "modules/m/lib/puppet/type/bad.rb: line 2:") {
t.Fatalf("got %v, skipped %v", err, st.Skipped)
}
if !exists(filepath.Join(env, OutDir, "good.pp")) || readFile(t, filepath.Join(env, OutDir, "bad.pp")) != "previous" {
t.Fatal("good inputs still generate; a failing input's old output is kept")
@@ -467,22 +471,22 @@ func TestGenerateErrors(t *testing.T) {
t.Run("wrong type name", func(t *testing.T) {
env := t.TempDir()
writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/a.rb"), strings.ReplaceAll(simpleType, "%s", "b"))
if skipped, err := Generate(env); err != nil || len(skipped) != 1 || !strings.Contains(skipped[0].Error(), `"a" was not defined`) {
t.Fatalf("got %v, skipped %v", err, skipped)
if st, err := Generate(env); err != nil || len(st.Skipped) != 1 || !strings.Contains(st.Skipped[0].Error(), `"a" was not defined`) {
t.Fatalf("got %v, skipped %v", err, st.Skipped)
}
})
t.Run("parser limit fails the env", func(t *testing.T) {
env := t.TempDir()
writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/deep.rb"), "Puppet::Type.newtype(:deep) do\n newparam(:a) do\n newvalues("+strings.Repeat("[", 300)+strings.Repeat("]", 300)+")\n end\nend\n")
if skipped, err := Generate(env); !errors.Is(err, errLimit) || len(skipped) != 0 {
t.Fatalf("got %v, skipped %v", err, skipped)
if st, err := Generate(env); !errors.Is(err, errLimit) || len(st.Skipped) != 0 {
t.Fatalf("got %v, skipped %v", err, st.Skipped)
}
})
t.Run("missing mixin is skipped", func(t *testing.T) {
env := t.TempDir()
writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/mix.rb"), "Puppet::Type.newtype(:mix) do\n include PuppetX::Nope\nend\n")
if skipped, err := Generate(env); err != nil || len(skipped) != 1 {
t.Fatalf("got %v, skipped %v", err, skipped)
if st, err := Generate(env); err != nil || len(st.Skipped) != 1 {
t.Fatalf("got %v, skipped %v", err, st.Skipped)
}
})
t.Run("output dir symlink", func(t *testing.T) {
@@ -755,7 +759,7 @@ func TestGeneratePanicFailsTheEnv(t *testing.T) {
t.Fatal(err)
}
defer func() { _ = out.Close() }()
err = generateOne(in, out, nil, func(string, bool) ([]string, error) { panic("boom") })
_, err = generateOne(in, out, nil, func(string, bool) ([]string, error) { panic("boom") })
if err == nil || !strings.Contains(err.Error(), "panic: boom") || errors.As(err, new(skipErr)) {
t.Fatalf("a panic must be a hard error, got %v", err)
}
+42 -18
View File
@@ -3,10 +3,12 @@ package main
import (
"context"
"fmt"
"log/slog"
"maps"
"os"
"os/signal"
"path/filepath"
"sort"
"slices"
"strings"
"syscall"
"time"
@@ -29,6 +31,7 @@ func rootCmd() *cobra.Command {
var cfgPath string
var jobs int
var grace time.Duration
var timings bool
var root *cobra.Command
load := func() (*deploy.Deployer, error) {
cfg, err := deploy.LoadConfig(cfgPath)
@@ -42,7 +45,29 @@ func rootCmd() *cobra.Command {
if g < 0 {
return nil, fmt.Errorf("--gc-grace must not be negative")
}
return deploy.New(cfg, jobs, g), nil
d := deploy.New(cfg, jobs, g)
if timings {
d.Timings = slog.Default()
}
return d, nil
}
live := func() ([][3]string, error) {
d, err := load()
if err != nil {
return nil, err
}
var rows [][3]string
for _, s := range d.Sources() {
live, err := d.Live(s)
if err != nil {
return nil, err
}
for _, e := range slices.Sorted(maps.Keys(live)) {
sha, _, _ := strings.Cut(filepath.Base(live[e]), "-")
rows = append(rows, [3]string{s.Name, e, sha})
}
}
return rows, nil
}
locked := func(fn func(*deploy.Deployer) error) error {
d, err := load()
@@ -65,15 +90,26 @@ func rootCmd() *cobra.Command {
}
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().BoolVar(&timings, "timings", false, "log one timing line per deploy phase")
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",
Short: "Deploy all environments, or only the named ones (env or branch names)",
RunE: func(cmd *cobra.Command, args []string) error {
return locked(func(d *deploy.Deployer) error { return d.Deploy(cmd.Context(), args, modules) })
},
ValidArgsFunction: func(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) {
rows, _ := live()
var envs []string
for _, r := range rows {
if !slices.Contains(args, r[1]) && !slices.Contains(envs, r[1]) {
envs = append(envs, r[1])
}
}
return envs, cobra.ShellCompDirectiveNoFileComp
},
}
deployCmd.Flags().BoolVarP(&modules, "modules", "m", false, "re-resolve Puppetfile modules for unchanged environments")
@@ -82,24 +118,12 @@ func rootCmd() *cobra.Command {
Short: "List deployed environments",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
d, err := load()
rows, err := live()
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)
}
for _, r := range rows {
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\n", r[0], r[1], r[2])
}
return nil
},
+38
View File
@@ -0,0 +1,38 @@
package main
import (
"bytes"
"fmt"
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
)
func TestTimingsFlag(t *testing.T) {
root := t.TempDir()
cfg := filepath.Join(root, "r10k.yaml")
body := fmt.Sprintf("cachedir: %s\nsources:\n s:\n remote: %s\n basedir: %s\n", filepath.Join(root, "cache"), filepath.Join(root, "control"), filepath.Join(root, "envs"))
if err := os.WriteFile(cfg, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
prev := slog.Default()
defer slog.SetDefault(prev)
for _, on := range []bool{false, true} {
var buf bytes.Buffer
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, nil)))
args := []string{"gc", "-c", cfg}
if on {
args = append(args, "--timings")
}
cmd := rootCmd()
cmd.SetArgs(args)
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if got := strings.Contains(buf.String(), "phase=gc.mark"); got != on {
t.Errorf("--timings=%v: gc.mark emitted=%v\n%s", on, got, buf.String())
}
}
}