Add --timings phase logs and scope named deploys to their environments
This commit is contained in:
+180
-51
@@ -8,6 +8,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -45,6 +46,8 @@ type Deployer struct {
|
||||
mu sync.Mutex
|
||||
flights map[string]*flight
|
||||
skips map[string]int
|
||||
counts map[string]int
|
||||
Timings *slog.Logger
|
||||
}
|
||||
|
||||
type flight struct {
|
||||
@@ -66,9 +69,11 @@ type deployResult struct {
|
||||
}
|
||||
|
||||
type resolved struct {
|
||||
name string
|
||||
path string
|
||||
dir string
|
||||
key string
|
||||
hit bool
|
||||
}
|
||||
|
||||
func New(cfg *Config, jobs int, grace time.Duration) *Deployer {
|
||||
@@ -79,7 +84,7 @@ 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) {
|
||||
@@ -98,8 +103,10 @@ func (d *Deployer) once(key string, fn func() (string, error)) (string, error) {
|
||||
return f.val, 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()
|
||||
}
|
||||
@@ -136,6 +143,8 @@ func (d *Deployer) complete(worktree string) bool {
|
||||
|
||||
// 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
|
||||
}
|
||||
@@ -159,35 +168,60 @@ 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)
|
||||
clear(d.counts)
|
||||
d.mu.Unlock()
|
||||
found := map[string]bool{}
|
||||
var errs []error
|
||||
for _, s := range d.Sources() {
|
||||
if err := d.deploySource(ctx, s, want, modules); err != nil {
|
||||
if err := d.deploySource(ctx, s, only, found, modules); err != nil {
|
||||
errs = append(errs, fmt.Errorf("source %s: %w", s.Name, err))
|
||||
}
|
||||
}
|
||||
for e := range want {
|
||||
errs = append(errs, fmt.Errorf("environment %s not found", e))
|
||||
for _, e := range only {
|
||||
if !found[e] {
|
||||
errs = append(errs, fmt.Errorf("environment %s not found", e))
|
||||
}
|
||||
}
|
||||
if err := d.GC(ctx); err != nil {
|
||||
errs = append(errs, err)
|
||||
if len(only) == 0 {
|
||||
if err := d.GC(ctx); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
d.mu.Lock()
|
||||
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...)
|
||||
}
|
||||
|
||||
func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]string, []error) {
|
||||
func (d *Deployer) count(outcome string) {
|
||||
d.mu.Lock()
|
||||
d.counts[outcome]++
|
||||
d.mu.Unlock()
|
||||
}
|
||||
|
||||
// Matches reports whether arg names env, either directly or as a branch that sanitises to it.
|
||||
func (s *Source) Matches(arg, env string) bool {
|
||||
n, _, err := s.EnvName(arg)
|
||||
return arg == env || err == nil && n == env
|
||||
}
|
||||
|
||||
// Environments maps env name -> sha for every branch, or only the branches only names.
|
||||
func (d *Deployer) Environments(ctx context.Context, s *Source, only ...string) (map[string]string, []error) {
|
||||
wanted := func(branch, name string) bool {
|
||||
return len(only) == 0 || slices.ContainsFunc(only, func(a string) bool { return a == branch || name != "" && s.Matches(a, name) })
|
||||
}
|
||||
all, err := d.branches(ctx, d.srcMirror(s))
|
||||
if err != nil {
|
||||
return nil, []error{err}
|
||||
@@ -204,6 +238,9 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]stri
|
||||
continue
|
||||
}
|
||||
name, corrected, err := s.EnvName(b)
|
||||
if !wanted(b, name) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
continue
|
||||
@@ -220,25 +257,32 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]stri
|
||||
return envs, errs
|
||||
}
|
||||
|
||||
func (d *Deployer) deploySource(ctx context.Context, s *Source, want map[string]bool, modules bool) error {
|
||||
if err := d.syncMirror(ctx, d.srcMirror(s), s.Remote, envRefspecs...); err != nil {
|
||||
func (d *Deployer) deploySource(ctx context.Context, s *Source, only []string, found map[string]bool, modules bool) error {
|
||||
fctx, end := d.phase(ctx, "source.fetch", "source", s.Name)
|
||||
err := d.syncMirror(fctx, d.srcMirror(s), s.Remote, envRefspecs...)
|
||||
end()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
envs, errs := d.Environments(ctx, s)
|
||||
bctx, end := d.phase(ctx, "source.branches", "source", s.Name)
|
||||
envs, errs := d.Environments(bctx, s, only...)
|
||||
end("envs", len(envs))
|
||||
if envs == nil {
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
full := len(want) == 0
|
||||
for name := range envs {
|
||||
for _, a := range only {
|
||||
if s.Matches(a, name) {
|
||||
found[a] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := os.MkdirAll(s.Basedir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
for name, sha := range envs {
|
||||
if !full && !want[name] {
|
||||
continue
|
||||
}
|
||||
delete(want, name)
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
@@ -250,7 +294,7 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, want map[string]
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if full {
|
||||
if len(only) == 0 {
|
||||
errs = append(errs, d.purge(s, envs))
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
@@ -282,14 +326,31 @@ func (d *Deployer) worktreePrefix(sha string) string {
|
||||
return sha + "-"
|
||||
}
|
||||
|
||||
func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, modules bool) error {
|
||||
func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, modules bool) (err error) {
|
||||
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)
|
||||
}()
|
||||
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
|
||||
}
|
||||
@@ -303,6 +364,7 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, m
|
||||
}
|
||||
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) {
|
||||
@@ -313,14 +375,21 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, m
|
||||
if err := d.checkout(ctx, s, sha, target, mods); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return d.prepare(s, name, sha, checksum, target, mods, started)
|
||||
return d.prepare(ctx, s, name, sha, checksum, target, mods, started)
|
||||
})
|
||||
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
|
||||
@@ -374,9 +443,14 @@ 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, modRefspecs...)
|
||||
}); err != nil {
|
||||
pctx, end := d.phase(ctx, "module.fetch", "module", m.Name)
|
||||
fetched := false
|
||||
_, err := d.once("fetch:"+mirror, func() (string, error) {
|
||||
fetched = true
|
||||
return "", d.syncMirror(pctx, mirror, m.Git, modRefspecs...)
|
||||
})
|
||||
end("cache", cache(!fetched))
|
||||
if err != nil {
|
||||
return resolved{}, err
|
||||
}
|
||||
var cands []string
|
||||
@@ -392,37 +466,52 @@ 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("cache", cache(err == nil && present(dir)))
|
||||
if err != nil {
|
||||
return resolved{}, err
|
||||
}
|
||||
dir := d.path("modules", key, sha)
|
||||
pctx, end = d.phase(ctx, "module.worktree", "module", m.Name)
|
||||
added := false
|
||||
_, err = d.once("mod:"+dir, func() (string, error) {
|
||||
if _, err := os.Stat(dir); err == nil {
|
||||
if present(dir) {
|
||||
return "", nil
|
||||
}
|
||||
added = true
|
||||
tmp := dir + ".tmp"
|
||||
if err := d.removeWorktree(ctx, mirror, tmp); err != nil {
|
||||
if err := d.removeWorktree(pctx, mirror, tmp); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := d.git(ctx, mirror, "worktree", "add", "--detach", "-q", "--", tmp, sha); err != nil {
|
||||
if _, err := d.git(pctx, mirror, "worktree", "add", "--detach", "-q", "--", tmp, sha); err != nil {
|
||||
return "", err
|
||||
}
|
||||
_, err := d.git(ctx, mirror, "worktree", "move", "--", tmp, dir)
|
||||
_, err := d.git(pctx, mirror, "worktree", "move", "--", tmp, dir)
|
||||
return "", err
|
||||
})
|
||||
return resolved{dir: dir, key: "git " + m.Git + " " + sha}, err
|
||||
end("cache", cache(!added))
|
||||
return resolved{name: m.Name, dir: dir, key: "git " + m.Git + " " + sha, hit: !added}, err
|
||||
}
|
||||
|
||||
func present(p string) bool {
|
||||
_, err := os.Stat(p)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (resolved, error) {
|
||||
slug := m.Owner + "-" + m.Name
|
||||
version := m.Version
|
||||
if version == "" {
|
||||
pctx, end := d.phase(ctx, "module.resolve", "module", slug)
|
||||
called := false
|
||||
v, err := d.once("latest:"+base+" "+slug, func() (string, error) {
|
||||
called = true
|
||||
var v string
|
||||
err := d.limit(func() (err error) { v, err = forgeLatest(ctx, base, slug); return err })
|
||||
err := d.limit(pctx, func() (err error) { v, err = forgeLatest(ctx, base, slug); return err })
|
||||
return v, err
|
||||
})
|
||||
end("cache", cache(!called))
|
||||
if err != nil {
|
||||
return resolved{}, err
|
||||
}
|
||||
@@ -430,13 +519,30 @@ func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (reso
|
||||
}
|
||||
release := slug + "-" + version
|
||||
dir := d.path("forge", release+"-"+shortHash(base))
|
||||
start := time.Now()
|
||||
var dl, ex, wait time.Duration
|
||||
installed := false
|
||||
_, err := d.once("forge:"+dir, func() (string, error) {
|
||||
if _, err := os.Stat(dir); err == nil {
|
||||
if present(dir) {
|
||||
return "", nil
|
||||
}
|
||||
return "", d.limit(func() error { return forgeInstall(ctx, base, release, dir) })
|
||||
installed = true
|
||||
q := time.Now()
|
||||
return "", 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
|
||||
return err
|
||||
})
|
||||
})
|
||||
return resolved{dir: dir, key: "forge " + base + " " + release}, err
|
||||
if !installed {
|
||||
dl = time.Since(start)
|
||||
}
|
||||
d.emit(ctx, "module.download", dl, "module", slug, "cache", cache(!installed), "wait", wait)
|
||||
d.emit(ctx, "module.extract", ex, "module", slug, "cache", cache(!installed))
|
||||
return resolved{name: slug, dir: dir, key: "forge " + base + " " + release, hit: !installed}, err
|
||||
}
|
||||
|
||||
func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string, mods []resolved) error {
|
||||
@@ -450,7 +556,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)
|
||||
@@ -459,7 +568,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", cache(mod.hit))
|
||||
err := linkModule(root, mod.path, mod.dir)
|
||||
end()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -481,17 +593,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, sha, checksum, target string, mods []resolved, started time.Time) (string, error) {
|
||||
func (d *Deployer) prepare(ctx context.Context, s *Source, name, sha, 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: name,
|
||||
Signature: sha,
|
||||
@@ -590,6 +707,7 @@ func (d *Deployer) purge(s *Source, envs map[string]string) error {
|
||||
if err := os.Remove(link); err != nil {
|
||||
return err
|
||||
}
|
||||
d.count("removed")
|
||||
log.Printf("environment %s removed", e.Name())
|
||||
}
|
||||
return nil
|
||||
@@ -614,11 +732,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.
|
||||
@@ -627,16 +748,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)
|
||||
}
|
||||
@@ -666,6 +792,7 @@ func (g *gcRun) sweep(mirror, dir string, live map[string]bool, remove func(stri
|
||||
}
|
||||
|
||||
func (d *Deployer) GC(ctx context.Context) error {
|
||||
start := time.Now()
|
||||
g := &gcRun{d: d, ctx: ctx, marks: map[string]time.Time{}, seen: map[string]bool{}}
|
||||
statePath := d.path(gcStateFile)
|
||||
if b, err := os.ReadFile(statePath); err == nil {
|
||||
@@ -727,6 +854,8 @@ func (d *Deployer) GC(ctx context.Context) error {
|
||||
err = os.Rename(tmp, statePath)
|
||||
}
|
||||
}
|
||||
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)
|
||||
return errors.Join(append(g.errs, err)...)
|
||||
}
|
||||
|
||||
|
||||
@@ -66,24 +66,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(body, tmp); err != nil {
|
||||
tr := &timedReader{r: body, d: time.Since(start)}
|
||||
if err := extract(tr, tmp); 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)
|
||||
}
|
||||
|
||||
func extract(r io.Reader, dst string) error {
|
||||
|
||||
@@ -30,7 +30,7 @@ func runGit(ctx context.Context, dir string, args ...string) (string, error) {
|
||||
|
||||
// git holds a -j slot only for the subprocess itself, so callers never nest slots.
|
||||
func (d *Deployer) git(ctx context.Context, dir string, args ...string) (out string, err error) {
|
||||
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...)
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package deploy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"slices"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
type spanKey struct{}
|
||||
|
||||
type span struct {
|
||||
parent *span
|
||||
attrs []any
|
||||
wait atomic.Int64
|
||||
}
|
||||
|
||||
func spanOf(ctx context.Context) *span {
|
||||
s, _ := ctx.Value(spanKey{}).(*span)
|
||||
return s
|
||||
}
|
||||
|
||||
func addWait(ctx context.Context, w time.Duration) {
|
||||
for s := spanOf(ctx); s != nil; s = s.parent {
|
||||
s.wait.Add(int64(w))
|
||||
}
|
||||
}
|
||||
|
||||
// phase times one unit of work; nested phases inherit attrs, and -j slot waits are reported apart 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.attrs = append(slices.Clip(s.parent.attrs), attrs...)
|
||||
}
|
||||
start := time.Now()
|
||||
ctx = context.WithValue(ctx, spanKey{}, s)
|
||||
return ctx, func(more ...any) {
|
||||
d.emit(ctx, name, time.Since(start), append(more, "wait", time.Duration(s.wait.Load()).Round(time.Microsecond))...)
|
||||
}
|
||||
}
|
||||
|
||||
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...)...)
|
||||
}
|
||||
|
||||
func cache(hit bool) string {
|
||||
if hit {
|
||||
return "hit"
|
||||
}
|
||||
return "miss"
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -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, name := filepath.Base(d), strings.TrimSuffix(filepath.Base(f), ".rb")
|
||||
@@ -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, g.mixins(mods)); 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, g.mixins(mods))
|
||||
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.
|
||||
@@ -147,23 +155,23 @@ func openOut(env string) (*os.Root, error) {
|
||||
return root.OpenRoot(OutDir)
|
||||
}
|
||||
|
||||
func generateOne(in string, out *os.Root, providers map[string][]string, resolve Resolver) error {
|
||||
func generateOne(in string, out *os.Root, providers map[string][]string, resolve Resolver) (bool, error) {
|
||||
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 {
|
||||
@@ -172,32 +180,32 @@ func generateOne(in string, out *os.Root, providers map[string][]string, resolve
|
||||
}
|
||||
}
|
||||
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)}
|
||||
}
|
||||
body, err := render(t, providers[name], 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)
|
||||
}
|
||||
|
||||
var camel = regexp.MustCompile(`([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])`)
|
||||
|
||||
@@ -327,17 +327,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")
|
||||
@@ -368,9 +372,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")
|
||||
@@ -379,22 +383,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\nend\n"+strings.Repeat("module A\n", 300)+strings.Repeat("end\n", 300))
|
||||
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) {
|
||||
|
||||
@@ -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
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user