This repository has been archived on 2026-11-27. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
w10k/internal/deploy/deploy.go
T

1100 lines
29 KiB
Go

package deploy
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log"
"log/slog"
"maps"
"os"
"path/filepath"
"regexp"
"runtime/debug"
"slices"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"time"
"git.unkin.net/unkin/w10k/internal/gentypes"
)
const (
markerFile = ".g10k-deploy.json"
gcStateFile = "gc-state.json"
asideTag = ".w10k-old-"
gcTag = ".gc-"
)
var (
envRefspecs = []string{"+refs/heads/*:refs/heads/*"}
modFetchOpts = []string{"-c", "protocol.file.allow=never"}
modRefspecs = []string{"+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*", "+HEAD:refs/w10k/HEAD"}
unsafeChars = regexp.MustCompile(`[^A-Za-z0-9._-]`)
gcLeftover = regexp.MustCompile(`\.gc-[A-Z2-7]{26}$`)
)
type Deployer struct {
runGit func(ctx context.Context, dir string, args ...string) (string, error)
cfg *Config
grace time.Duration
gitTimeout time.Duration
now func() time.Time
sem chan struct{}
mu sync.Mutex
flights map[string]*flight
skips map[string]int
counts map[string]int
Timings *slog.Logger
wtLocks sync.Map
}
type flight struct {
done chan struct{}
val string
worked bool
err error
}
type deployResult struct {
Name string `json:"name"`
Signature string `json:"signature"`
StartedAt time.Time `json:"started_at"`
FinishedAt time.Time `json:"finished_at"`
DeploySuccess bool `json:"deploy_success"`
PuppetfileChecksum string `json:"puppetfile_checksum"`
GitDir string `json:"git_dir"`
GitURL string `json:"git_url"`
Modules []string `json:"modules"`
}
type resolved struct {
name string
path string
dir string
key string
cache string
}
func New(cfg *Config, jobs int, grace time.Duration) *Deployer {
if jobs < 1 {
jobs = 1
}
gt := defaultGitTimeout
if cfg.W10k.GitTimeout != nil {
gt = *cfg.W10k.GitTimeout
}
return &Deployer{runGit: runGit, cfg: cfg, grace: grace, gitTimeout: gt, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}, skips: map[string]int{}, counts: map[string]int{}}
}
// 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{}), worked: true}
d.flights[key] = f
}
d.mu.Unlock()
if !ok {
func() {
defer close(f.done)
defer recoverErr(&f.err, key)
f.val, f.worked, f.err = fn()
}()
}
<-f.done
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(ctx context.Context, fn func() error) error {
t := time.Now()
d.sem <- struct{}{}
addWait(ctx, time.Since(t))
defer func() { <-d.sem }()
return fn()
}
func (d *Deployer) path(parts ...string) string {
return filepath.Join(append([]string{d.cfg.Cachedir}, parts...)...)
}
func (d *Deployer) srcMirror(s *Source) string { return d.path("sources", s.Name+".git") }
func (d *Deployer) srcWorktrees(s *Source) string { return d.path("worktrees", s.Name) }
func shortHash(s string) string {
sum := sha256.Sum256([]byte(s))
return hex.EncodeToString(sum[:8])
}
func urlKey(url string) string {
k := unsafeChars.ReplaceAllString(url, "_")
if len(k) > 64 {
k = k[len(k)-64:]
}
return k + "-" + shortHash(url)
}
// doneFile is the out-of-tree completion marker for a cache dir; a branch can commit anything inside its own worktree.
func (d *Deployer) doneFile(dir string) string {
rel, _ := filepath.Rel(d.cfg.Cachedir, dir)
return d.path("state", rel+".done")
}
func (d *Deployer) complete(dir string) bool {
_, err := os.Stat(d.doneFile(dir))
_, derr := os.Stat(dir)
return err == nil && derr == nil
}
func (d *Deployer) markDone(dir string, b []byte) error {
done := d.doneFile(dir)
if err := os.MkdirAll(filepath.Dir(done), 0o755); err != nil {
return err
}
return writeAtomic(done, b)
}
// discard unmarks dir, renames it aside atomically and only then deletes it, so an interrupted GC never leaves a reusable half-deleted dir.
func (d *Deployer) discard(ctx context.Context, mirror, dir string) error {
if err := os.Remove(d.doneFile(dir)); err != nil && !os.IsNotExist(err) {
return err
}
gc := dir + gcTag + rand.Text()
if mirror == "" {
if err := os.Rename(dir, gc); err != nil {
return err
}
return os.RemoveAll(gc)
}
if _, err := d.git(ctx, mirror, "worktree", "move", "--", dir, gc); err != nil {
if err := os.Rename(dir, gc); err != nil {
return err
}
}
return d.removeWorktree(ctx, mirror, gc)
}
func recoverErr(err *error, what string) {
if r := recover(); r != nil {
log.Printf("%s: panic: %v\n%s", what, r, debug.Stack())
*err = fmt.Errorf("panic: %v", r)
}
}
// Lock takes an exclusive flock on the cachedir, released by the returned func.
func (d *Deployer) Lock() (func(), error) {
_, end := d.phase(context.Background(), "lock")
defer end()
if err := os.MkdirAll(d.cfg.Cachedir, 0o755); err != nil {
return nil, err
}
f, err := os.OpenFile(d.path(".lock"), os.O_CREATE|os.O_RDWR, 0o644)
if err != nil {
return nil, err
}
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
_ = f.Close()
return nil, err
}
return func() { _ = f.Close() }, nil
}
func (d *Deployer) Sources() []*Source {
var out []*Source
for _, s := range d.cfg.Sources {
out = append(out, s)
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
// 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 {
ctx, end := d.phase(ctx, "run")
d.mu.Lock()
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)
}
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))
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...)
}
// 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 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, err
}
names := make([]string, 0, len(all))
for b := range all {
names = append(names, b)
}
sort.Strings(names)
claims := map[string][]string{}
exact := map[string]string{}
skipped := map[string]error{}
for _, b := range names {
if s.Ignored(b) {
continue
}
name, corrected, err := s.EnvName(b)
if err != nil {
skipped[b] = err
continue
}
if !corrected {
exact[name] = b
}
claims[name] = append(claims[name], b)
}
envs := map[string]envRef{}
for _, name := range slices.Sorted(maps.Keys(claims)) {
bs := claims[name]
win, isExact := exact[name]
if !isExact && len(bs) == 1 {
win = bs[0]
}
if win == "" {
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 {
skipped[b] = fmt.Errorf("branch %s collides with environment %s, skipped", b, name)
}
}
envs[name] = envRef{win, all[win]}
}
return envs, skipped, nil
}
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
}
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")
}
}
if err := os.MkdirAll(s.Basedir, 0o755); err != nil {
return errors.Join(append(errs, err)...)
}
var mu sync.Mutex
var wg sync.WaitGroup
for _, name := range slices.Sorted(maps.Keys(p.envs)) {
ref := p.envs[name]
if !full && !p.want[name] {
continue
}
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()
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()
}
}()
}
wg.Wait()
if full {
errs = append(errs, d.purge(s, p.envs, p.skipped))
}
return errors.Join(errs...)
}
func linkTarget(link string) string {
t, err := os.Readlink(link)
if err != nil {
return ""
}
if !filepath.IsAbs(t) {
t = filepath.Join(filepath.Dir(link), t)
}
return filepath.Clean(t)
}
func (d *Deployer) owned(s *Source, link string) string {
if t := linkTarget(link); filepath.Dir(t) == d.srcWorktrees(s) {
return t
}
return ""
}
// worktreePrefix keys worktrees on everything besides modules that changes their content.
func (d *Deployer) worktreePrefix(sha string) string {
if d.cfg.W10k.GenerateTypes {
return sha + "-types" + gentypes.Version + "-"
}
return sha + "-"
}
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)
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
}
pctx, end := d.phase(ctx, "env.puppetfile")
pf, checksum, err := d.puppetfile(pctx, d.srcMirror(s), sha)
end()
if err != nil {
return err
}
mods, err := d.installModules(ctx, pf)
if err != nil {
return err
}
h := sha256.New()
for _, m := range mods {
_, _ = fmt.Fprintf(h, "%s %s\n", m.path, m.key)
}
target := filepath.Join(d.srcWorktrees(s), 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, bool, error) {
if d.complete(target) {
return "", false, nil
}
started := d.now().UTC()
if err := d.checkout(ctx, s, sha, target, mods); err != nil {
return "", true, err
}
v, err := d.prepare(ctx, s, name, ref, checksum, target, mods, started)
return v, true, err
})
if err != nil {
return err
}
_, 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
d.mu.Unlock()
}
log.Printf("environment %s -> %s", name, filepath.Base(target))
return nil
}
func (d *Deployer) puppetfile(ctx context.Context, mirror, sha string) (*Puppetfile, string, error) {
if _, err := d.git(ctx, mirror, "cat-file", "-e", sha+":Puppetfile"); err != nil {
return &Puppetfile{Moduledir: "modules"}, "", nil
}
src, err := d.git(ctx, mirror, "cat-file", "blob", sha+":Puppetfile")
if err != nil {
return nil, "", err
}
pf, err := ParsePuppetfile(src)
if err != nil {
return nil, "", fmt.Errorf("puppetfile: %w", err)
}
sum := sha256.Sum256([]byte(src))
return pf, hex.EncodeToString(sum[:]), nil
}
func (d *Deployer) installModules(ctx context.Context, pf *Puppetfile) ([]resolved, error) {
out := make([]resolved, len(pf.Modules))
errs := make([]error, len(pf.Modules))
var wg sync.WaitGroup
for i, m := range pf.Modules {
wg.Add(1)
go func() {
defer wg.Done()
var err error
defer func() {
if err != nil {
errs[i] = fmt.Errorf("module %s: %w", m.Name, err)
}
}()
defer recoverErr(&err, "module "+m.Name)
if m.Git != "" {
out[i], err = d.gitModule(ctx, m)
} else {
out[i], err = d.forgeModule(ctx, forgeURL(pf.Forge), m)
}
out[i].path = m.Path(pf)
}()
}
wg.Wait()
sort.Slice(out, func(i, j int) bool { return out[i].path < out[j].path })
return out, errors.Join(errs...)
}
func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) {
key := urlKey(m.Git)
mirror := d.path("git", key+".git")
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
switch m.RefKind {
case "tag":
cands = []string{"refs/tags/" + m.Ref}
case "branch":
cands = []string{"refs/heads/" + m.Ref}
case "commit":
cands = []string{m.Ref}
case "ref":
cands = []string{"refs/heads/" + m.Ref, "refs/tags/" + m.Ref, m.Ref}
default:
cands = []string{"refs/w10k/HEAD"}
}
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
}
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 "", false, nil
}
tmp := dir + ".tmp"
for _, p := range []string{tmp, dir} {
if err := d.removeWorktree(pctx, mirror, p); err != nil {
return "", true, err
}
}
if _, err := d.git(pctx, mirror, "worktree", "add", "--detach", "-q", "--", tmp, sha); err != nil {
return "", true, err
}
if _, err := d.git(pctx, mirror, "worktree", "move", "--", tmp, dir); err != nil {
return "", true, err
}
return "", true, d.markDone(dir, nil)
})
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 == "" {
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(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
}
version = v
}
release := slug + "-" + version
dir := d.path("forge", release+"-"+shortHash(base))
start := time.Now()
var dl, ex, wait time.Duration
_, c, err := d.once("forge:"+dir, func() (string, bool, error) {
if d.complete(dir) {
return "", false, nil
}
if err := os.RemoveAll(dir); err != nil {
return "", true, 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 "", true, d.markDone(dir, nil)
})
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 {
mirror := d.srcMirror(s)
if err := os.Remove(d.doneFile(target)); err != nil && !os.IsNotExist(err) {
return err
}
if err := d.removeWorktree(ctx, mirror, target); err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return err
}
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)
if err != nil {
return err
}
defer func() { _ = root.Close() }()
for _, mod := range mods {
_, 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
}
}
return nil
}
// linkModule creates rel -> dir inside root; os.Root refuses any committed symlink that leads outside.
func linkModule(root *os.Root, rel, dir string) error {
if !filepath.IsLocal(rel) {
return fmt.Errorf("module path %q escapes the environment", rel)
}
if err := root.MkdirAll(filepath.Dir(rel), 0o755); err != nil {
return fmt.Errorf("module path %s: %w", rel, err)
}
if err := root.RemoveAll(rel); err != nil {
return fmt.Errorf("module path %s: %w", rel, err)
}
return root.Symlink(dir, rel)
}
// prepare runs last before a worktree can be swapped in; its out-of-tree done file marks the worktree complete.
func (d *Deployer) prepare(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 {
_, 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,
StartedAt: started,
FinishedAt: d.now().UTC(),
DeploySuccess: true,
PuppetfileChecksum: checksum,
GitDir: d.srcMirror(s),
GitURL: s.Remote,
Modules: []string{},
}
for _, m := range mods {
r.Modules = append(r.Modules, m.dir)
}
b, err := json.MarshalIndent(r, "", " ")
if err != nil {
return "", err
}
b = append(b, '\n')
if err := writeMarker(target, b); err != nil {
return "", err
}
return strconv.Itoa(len(skipped)), d.markDone(target, b)
}
// writeMarker replaces whatever the branch committed at the marker paths without following it.
func writeMarker(dir string, b []byte) error {
root, err := os.OpenRoot(dir)
if err != nil {
return err
}
defer func() { _ = root.Close() }()
tmp := markerFile + ".tmp"
if err := root.RemoveAll(tmp); err != nil {
return err
}
f, err := root.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL|syscall.O_NOFOLLOW, 0o644)
if err != nil {
return err
}
if _, err := f.Write(b); err != nil {
_ = f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
if err := root.RemoveAll(markerFile); err != nil {
return err
}
return root.Rename(tmp, markerFile)
}
func writeAtomic(p string, b []byte) error {
tmp := p + ".tmp"
if err := os.WriteFile(tmp, b, 0o644); err != nil {
return err
}
return os.Rename(tmp, p)
}
// Swap points link at target via a temporary symlink renamed over it; a real directory is moved aside for GC.
func Swap(target, link string) error {
dir, base := filepath.Dir(link), filepath.Base(link)
tmp := filepath.Join(dir, "."+base+".w10k")
_ = os.Remove(tmp)
if err := os.Symlink(target, tmp); err != nil {
return err
}
if fi, err := os.Lstat(link); err == nil && fi.IsDir() {
aside := filepath.Join(dir, fmt.Sprintf(".%s%s%d", base, asideTag, time.Now().UnixNano()))
if err := os.Rename(link, aside); err != nil {
return err
}
}
return os.Rename(tmp, link)
}
// 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 keep[e.Name()] {
continue
}
link := filepath.Join(s.Basedir, e.Name())
if d.owned(s, link) == "" {
continue
}
if err := os.Remove(link); err != nil {
return err
}
d.count("removed")
log.Printf("environment %s removed", e.Name())
}
return nil
}
// Live returns env name -> worktree for every environment symlink owned by s.
func (d *Deployer) Live(s *Source) (map[string]string, error) {
entries, err := os.ReadDir(s.Basedir)
if os.IsNotExist(err) {
return nil, nil
}
if err != nil {
return nil, err
}
live := map[string]string{}
for _, e := range entries {
if t := d.owned(s, filepath.Join(s.Basedir, e.Name())); t != "" {
live[e.Name()] = t
}
}
return live, nil
}
type gcRun struct {
d *Deployer
ctx context.Context
marks map[string]time.Time
seen map[string]bool
errs []error
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.
func (g *gcRun) collect(p string, remove func() error) {
g.seen[p] = true
t, ok := g.marks[p]
if !ok {
g.marks[p] = g.d.now()
g.marked++
log.Printf("gc: marked %s", p)
return
}
if g.d.now().Sub(t) < g.d.grace {
return
}
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)
}
func (g *gcRun) sweep(mirror, dir string, live map[string]bool, remove func(string) error) {
entries, err := os.ReadDir(dir)
if err != nil {
if !os.IsNotExist(err) {
g.errs = append(g.errs, err)
}
return
}
for _, e := range entries {
p := filepath.Join(dir, e.Name())
if gcLeftover.MatchString(e.Name()) {
if err := os.RemoveAll(p); err != nil {
g.errs = append(g.errs, err)
}
continue
}
if live[p] {
continue
}
g.collect(p, func() error { return remove(p) })
}
if mirror != "" {
if _, err := os.Stat(mirror); err == nil {
if _, err := g.d.git(g.ctx, mirror, "worktree", "prune"); err != nil {
g.errs = append(g.errs, err)
}
}
}
}
func (d *Deployer) GC(ctx context.Context) error { return d.gc(ctx, true) }
// gc drops the mark of everything live this run; only a sweep may add marks or delete, and only where every live set it needs was computed.
func (d *Deployer) gc(ctx context.Context, sweep bool) (err error) {
start := time.Now()
g := &gcRun{d: d, ctx: ctx, marks: d.loadMarks(), seen: map[string]bool{}}
defer func() {
for p := range g.marks {
if !g.seen[p] {
delete(g.marks, p)
}
}
err = errors.Join(append(g.errs, d.saveMarks(g.marks))...)
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{}
var ok []*Source
for _, s := range d.Sources() {
live, err := d.Live(s)
if err != nil {
g.errs = append(g.errs, fmt.Errorf("gc: %w", err))
continue
}
ok = append(ok, s)
for _, t := range live {
liveEnv[t] = true
}
}
if !sweep {
liveMod, err := d.moduleRefs(liveEnv)
if err != nil || len(g.errs) > 0 {
g.errs = append(g.errs, err)
return nil
}
for p := range g.marks {
g.seen[p] = !liveEnv[p] && !liveMod[p]
}
return nil
}
for _, s := range ok {
mirror := d.srcMirror(s)
g.sweep(mirror, d.srcWorktrees(s), liveEnv, func(p string) error {
if err := os.Remove(d.doneFile(p)); err != nil && !os.IsNotExist(err) {
return err
}
return d.removeWorktree(ctx, mirror, p)
})
entries, _ := os.ReadDir(s.Basedir)
for _, e := range entries {
if p := filepath.Join(s.Basedir, e.Name()); strings.HasPrefix(e.Name(), ".") && strings.Contains(e.Name(), asideTag) {
g.collect(p, func() error { return os.RemoveAll(p) })
}
}
}
if len(ok) < len(d.cfg.Sources) {
return nil
}
liveMod, err := d.moduleRefs(liveEnv)
if err != nil {
g.errs = append(g.errs, err)
} else {
keys, _ := os.ReadDir(d.path("modules"))
for _, k := range keys {
mirror := d.path("git", k.Name()+".git")
g.sweep(mirror, d.path("modules", k.Name()), liveMod, func(p string) error { return d.discard(ctx, mirror, p) })
}
g.sweep("", d.path("forge"), liveMod, func(p string) error { return d.discard(ctx, "", p) })
}
return nil
}
// loadMarks treats an unreadable state file as empty, which only delays deletion.
func (d *Deployer) loadMarks() map[string]time.Time {
marks := map[string]time.Time{}
b, err := os.ReadFile(d.path(gcStateFile))
if err == nil {
err = json.Unmarshal(b, &marks)
}
if err != nil && !os.IsNotExist(err) {
log.Printf("gc: discarding unreadable %s: %v", gcStateFile, err)
marks = map[string]time.Time{}
}
return marks
}
func (d *Deployer) saveMarks(marks map[string]time.Time) error {
b, err := json.MarshalIndent(marks, "", " ")
if err != nil {
return err
}
return writeAtomic(d.path(gcStateFile), b)
}
// moduleRefs returns every module dir referenced by any source's env worktree on disk or by any link in a configured basedir.
func (d *Deployer) moduleRefs(liveEnv map[string]bool) (map[string]bool, error) {
wts := map[string]bool{}
for p := range liveEnv {
wts[p] = true
}
for _, s := range d.Sources() {
entries, err := os.ReadDir(s.Basedir)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
for _, e := range entries {
if t := linkTarget(filepath.Join(s.Basedir, e.Name())); filepath.Dir(filepath.Dir(t)) == d.path("worktrees") {
wts[t] = true
}
}
}
srcs, err := os.ReadDir(d.path("worktrees"))
if err != nil && !os.IsNotExist(err) {
return nil, err
}
for _, src := range srcs {
dir := d.path("worktrees", src.Name())
entries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
for _, e := range entries {
if p := filepath.Join(dir, e.Name()); !wts[p] {
wts[p] = false
}
}
}
refs := map[string]bool{}
for p, live := range wts {
b, err := os.ReadFile(d.doneFile(p))
if os.IsNotExist(err) && !live {
continue
}
var r deployResult
if err == nil {
err = json.Unmarshal(b, &r)
}
if err != nil {
return nil, fmt.Errorf("gc: module refs of %s: %w", p, err)
}
for _, m := range r.Modules {
refs[m] = true
}
}
return refs, nil
}