package deploy import ( "bytes" "context" "encoding/json" "fmt" "log" "log/slog" "maps" "net" "net/http" "net/http/cgi" "net/http/httptest" "os" "os/exec" "path/filepath" "slices" "strings" "sync" "testing" "time" ) func mkdirs(t *testing.T, paths ...string) { t.Helper() for _, p := range paths { if err := os.MkdirAll(p, 0o755); err != nil { t.Fatal(err) } } } func TestSwapOverSymlinkAbsolute(t *testing.T) { dir := t.TempDir() a, b := filepath.Join(dir, "cache", "a"), filepath.Join(dir, "cache", "b") mkdirs(t, a, b, filepath.Join(dir, "envs")) link := filepath.Join(dir, "envs", "develop") for _, target := range []string{a, b, b} { if err := Swap(target, link); err != nil { t.Fatal(err) } if got, err := os.Readlink(link); err != nil || got != target { t.Fatalf("link -> %q (%v), want absolute %q", got, err, target) } } if _, err := os.Stat(a); err != nil { t.Fatal("swap must not touch the previous target") } if entries, _ := os.ReadDir(filepath.Dir(link)); len(entries) != 1 { t.Fatalf("leftover temp files: %v", entries) } } func TestSwapDirectoryCutover(t *testing.T) { dir := t.TempDir() target := filepath.Join(dir, "cache", "a") link := filepath.Join(dir, "envs", "develop") mkdirs(t, target, link) if err := os.WriteFile(filepath.Join(link, "site.pp"), []byte("old"), 0o644); err != nil { t.Fatal(err) } if err := Swap(target, link); err != nil { t.Fatal(err) } if got, _ := os.Readlink(link); got != target { t.Fatalf("link -> %q", got) } matches, _ := filepath.Glob(filepath.Join(dir, "envs", ".develop"+asideTag+"*", "site.pp")) if len(matches) != 1 { t.Fatalf("old g10k directory should be moved aside intact, got %v", matches) } } func TestGCGrace(t *testing.T) { root := t.TempDir() cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": {Name: "s", Basedir: filepath.Join(root, "envs")}}} clock := time.Unix(1_700_000_000, 0) gc := func() { d := New(cfg, 1, 10*time.Minute) d.now = func() time.Time { return clock } if err := d.GC(context.Background()); err != nil { t.Fatal(err) } } d := New(cfg, 1, 0) old, cur := filepath.Join(d.srcWorktrees(cfg.Sources["s"]), "old"), filepath.Join(d.srcWorktrees(cfg.Sources["s"]), "cur") aside := filepath.Join(cfg.Sources["s"].Basedir, ".develop"+asideTag+"1") mkdirs(t, old, cur, aside) mkdirs(t, filepath.Dir(d.doneFile(old))) for _, p := range []string{old, cur} { if err := os.WriteFile(d.doneFile(p), []byte(`{"modules":[]}`), 0o644); err != nil { t.Fatal(err) } } if err := Swap(cur, filepath.Join(cfg.Sources["s"].Basedir, "develop")); err != nil { t.Fatal(err) } gc() if !exists(old) || !exists(aside) { t.Fatal("first sight must only mark") } clock = clock.Add(9 * time.Minute) gc() if !exists(old) || !exists(aside) { t.Fatal("inside grace must keep") } if err := Swap(old, filepath.Join(cfg.Sources["s"].Basedir, "develop")); err != nil { t.Fatal(err) } gc() clock = clock.Add(2 * time.Minute) gc() if !exists(old) || exists(aside) { t.Fatal("re-referenced worktree must be unmarked; aside dir past grace removed") } if !exists(cur) { t.Fatal("newly unreferenced worktree must get a fresh mark, not inherit an old one") } clock = clock.Add(11 * time.Minute) gc() if exists(cur) || !exists(old) { t.Fatal("past grace must remove only the unreferenced worktree") } } func TestLockExcludes(t *testing.T) { d := New(&Config{Cachedir: t.TempDir()}, 1, 0) unlock, err := d.Lock() if err != nil { t.Fatal(err) } got := make(chan struct{}) go func() { u, err := d.Lock() if err == nil { u() } close(got) }() select { case <-got: t.Fatal("second lock acquired while first held") case <-time.After(100 * time.Millisecond): } unlock() select { case <-got: case <-time.After(5 * time.Second): t.Fatal("second lock never acquired") } } func gitT(t *testing.T, dir string, args ...string) string { t.Helper() cmd := exec.Command("git", append([]string{"-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false"}, args...)...) cmd.Dir = dir out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("git %v: %v\n%s", args, err, out) } return strings.TrimSpace(string(out)) } func commit(t *testing.T, dir string, files map[string]string) string { t.Helper() for p, c := range files { full := filepath.Join(dir, p) if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { t.Fatal(err) } if err := os.WriteFile(full, []byte(c), 0o644); err != nil { t.Fatal(err) } } gitT(t, dir, "add", "-A") gitT(t, dir, "commit", "-q", "-m", "c") return gitT(t, dir, "rev-parse", "HEAD") } func newRepo(t *testing.T, dir string) { t.Helper() if err := os.MkdirAll(dir, 0o755); err != nil { t.Fatal(err) } gitT(t, dir, "init", "-q", "-b", "main") } func readMarker(t *testing.T, env string) deployResult { t.Helper() b, err := os.ReadFile(filepath.Join(env, markerFile)) if err != nil { t.Fatal(err) } var m deployResult if err := json.Unmarshal(b, &m); err != nil { t.Fatal(err) } return m } func exists(p string) bool { _, err := os.Lstat(p) return err == nil } func dirCount(t *testing.T, p string) int { t.Helper() e, err := os.ReadDir(p) if err != nil && !os.IsNotExist(err) { t.Fatal(err) } return len(e) } type fixture struct { t *testing.T root string control string mod string modDir string gitURL string basedir string cfg *Config clock time.Time forgeURL string hit func(string) int } func newFixture(t *testing.T) *fixture { f := &fixture{t: t, root: t.TempDir(), clock: time.Unix(1_700_000_000, 0)} var mu sync.Mutex hits := map[string]int{} forge := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mu.Lock() hits[r.URL.Path]++ mu.Unlock() switch r.URL.Path { case "/v3/modules/acme-latest": _, _ = fmt.Fprint(w, `{"current_release":{"version":"2.0.0"}}`) case "/v3/files/acme-thing-1.0.0.tar.gz", "/v3/files/acme-latest-2.0.0.tar.gz": top := strings.TrimSuffix(filepath.Base(r.URL.Path), ".tar.gz") _, _ = w.Write(tarball(t, entry{name: top + "/metadata.json", body: `{"name":"` + top + `"}`, mode: 0o644})) default: http.NotFound(w, r) } })) t.Cleanup(forge.Close) f.forgeURL = forge.URL f.hit = func(p string) int { mu.Lock(); defer mu.Unlock(); return hits[p] } gitBin, err := exec.LookPath("git") if err != nil { t.Fatal(err) } gitSrv := httptest.NewServer(&cgi.Handler{Path: gitBin, Args: []string{"http-backend"}, Env: []string{"GIT_PROJECT_ROOT=" + f.root, "GIT_HTTP_EXPORT_ALL=1"}}) t.Cleanup(gitSrv.Close) f.gitURL = gitSrv.URL f.modDir = filepath.Join(f.root, "mod") f.mod = f.url(f.modDir) newRepo(t, f.modDir) commit(t, f.modDir, map[string]string{"manifests/init.pp": "class bind {}\n"}) gitT(t, f.modDir, "tag", "1.0") f.control = filepath.Join(f.root, "control") newRepo(t, f.control) f.basedir = filepath.Join(f.root, "code", "environments") cfg, err := ParseConfig([]byte(fmt.Sprintf("cachedir: %s\nsources:\n unkin:\n remote: %s\n basedir: %s\n", filepath.Join(f.root, "code", "cache"), f.control, f.basedir))) if err != nil { t.Fatal(err) } f.cfg = cfg return f } // url serves a repo under f.root over git smart HTTP; module sources must be remote. func (f *fixture) url(dir string) string { rel, err := filepath.Rel(f.root, dir) if err != nil { f.t.Fatal(err) } return f.gitURL + "/" + filepath.ToSlash(rel) } func (f *fixture) puppetfile() string { return fmt.Sprintf(`forge '%s' moduledir 'external_modules' mod 'acme-thing', '1.0.0' mod 'acme-latest', :latest mod 'bind', :git => '%s', :tag => '1.0' mod 'tracker', :git => '%s', :branch => 'main' `, f.forgeURL, f.mod, f.mod) } func (f *fixture) deployer() *Deployer { d := New(f.cfg, 4, 10*time.Minute) d.now = func() time.Time { return f.clock } return d } func (f *fixture) deploy(modules bool, only ...string) error { return f.deployer().Deploy(context.Background(), only, modules) } func (f *fixture) mustDeploy(modules bool) { f.t.Helper() if err := f.deploy(modules); err != nil { f.t.Fatal(err) } } func (f *fixture) settle() { f.t.Helper() for range 2 { f.clock = f.clock.Add(11 * time.Minute) f.mustDeploy(false) } } func (f *fixture) env(name string) string { return f.deployer().owned(f.cfg.Sources["unkin"], filepath.Join(f.basedir, name)) } func (f *fixture) cache(parts ...string) string { return filepath.Join(append([]string{f.cfg.Cachedir}, parts...)...) } func (f *fixture) forgeDir(release string) string { return f.cache("forge", release+"-"+shortHash(f.forgeURL)) } func TestDeployIntegration(t *testing.T) { f := newFixture(t) sha1 := commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile(), "manifests/site.pp": "node default {}\n"}) gitT(t, f.control, "branch", "benvin/foo-bar") f.mustDeploy(false) main1, foo1 := f.env("main"), f.env("benvin_foo_bar") if main1 == "" || main1 != foo1 || !strings.HasPrefix(filepath.Base(main1), sha1+"-") { t.Fatalf("envs not deployed as shared sha worktree: main=%q foo=%q", main1, foo1) } if l, _ := os.Readlink(filepath.Join(f.basedir, "main")); !filepath.IsAbs(l) { t.Fatalf("env link must be absolute: %s", l) } if l, _ := os.Readlink(filepath.Join(main1, "external_modules", "bind")); !filepath.IsAbs(l) { t.Fatalf("module link must be absolute: %s", l) } if m := readMarker(t, main1); m.Signature != sha1 || !m.DeploySuccess || len(m.Modules) != 4 || len(m.PuppetfileChecksum) != 64 || m.GitURL != f.control { t.Fatalf("deploy file %+v", m) } for _, p := range []string{"manifests/site.pp", "external_modules/thing/metadata.json", "external_modules/latest/metadata.json", "external_modules/bind/manifests/init.pp", "external_modules/tracker/manifests/init.pp"} { if _, err := os.Stat(filepath.Join(f.basedir, "main", p)); err != nil { t.Errorf("missing %s: %v", p, err) } } if f.hit("/v3/files/acme-thing-1.0.0.tar.gz") != 1 || f.hit("/v3/modules/acme-latest") != 1 { t.Fatal("forge modules should be fetched once") } if dirCount(t, f.cache("modules", urlKey(f.mod))) != 1 { t.Fatal("tag and branch at the same sha should share one module worktree") } f.mustDeploy(false) if f.env("main") != main1 || f.hit("/v3/files/acme-thing-1.0.0.tar.gz") != 1 || f.hit("/v3/modules/acme-latest") != 1 { t.Fatal("unchanged sha must be a no-op") } sha2 := commit(t, f.control, map[string]string{"manifests/site.pp": "node default { }\n"}) f.mustDeploy(false) main2 := f.env("main") if !strings.HasPrefix(filepath.Base(main2), sha2+"-") || f.env("benvin_foo_bar") != main1 { t.Fatalf("moved branch: main=%s foo=%s", main2, f.env("benvin_foo_bar")) } gitT(t, f.control, "branch", "-D", "benvin/foo-bar") f.mustDeploy(false) if exists(filepath.Join(f.basedir, "benvin_foo_bar")) { t.Fatal("deleted branch must remove the env link") } if !exists(main1) { t.Fatal("worktree must never be deleted in the run that unreferenced it") } f.settle() if exists(main1) || dirCount(t, f.cache("worktrees", "unkin")) != 1 { t.Fatal("unreferenced worktree must be GC'd after grace") } if wl := gitT(t, f.cache("sources", "unkin.git"), "worktree", "list"); strings.Contains(wl, filepath.Base(main1)) { t.Fatalf("worktree not pruned:\n%s", wl) } commit(t, f.modDir, map[string]string{"manifests/init.pp": "class tracker {}\n"}) f.mustDeploy(false) if f.env("main") != main2 { t.Fatal("module branch move must not redeploy without --modules") } f.mustDeploy(true) main3 := f.env("main") if main3 == main2 { t.Fatal("--modules should rebuild when a module ref moved") } f.settle() if exists(main2) || dirCount(t, f.cache("modules", urlKey(f.mod))) != 2 { t.Fatal("old env GC'd; bind (tag) and tracker (moved branch) are distinct module worktrees") } commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("forge '%s'\nmoduledir 'external_modules'\nmod 'acme-latest', :latest\n", f.forgeURL)}) f.mustDeploy(false) if dirCount(t, f.cache("modules", urlKey(f.mod))) != 2 || !exists(f.forgeDir("acme-thing-1.0.0")) { t.Fatal("modules still referenced by a worktree awaiting GC must be kept") } f.settle() f.settle() if dirCount(t, f.cache("modules", urlKey(f.mod))) != 0 || exists(f.forgeDir("acme-thing-1.0.0")) || !exists(f.forgeDir("acme-latest-2.0.0")) { t.Fatal("dropped modules must be GC'd, kept ones retained") } if err := f.deploy(false, "nope"); err == nil || !strings.Contains(err.Error(), "nope not found") { t.Fatalf("unknown env: %v", err) } if !exists(filepath.Join(f.basedir, "main")) { t.Fatal("filtered deploy must not purge other envs") } commit(t, f.control, map[string]string{"Puppetfile": "mod 'broken', :svn => 'x'\n"}) if err := f.deploy(false); err == nil { t.Fatal("bad Puppetfile must fail") } if f.env("main") == "" || !exists(f.env("main")) { t.Fatal("failed build must leave the live env untouched") } } func TestInFlightCompileSurvivesSwap(t *testing.T) { f := newFixture(t) commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile(), "manifests/site.pp": "node default {}\n"}) f.mustDeploy(false) resolved, err := os.Readlink(filepath.Join(f.basedir, "main")) if err != nil { t.Fatal(err) } var files []string var walk func(string) walk = func(dir string) { entries, err := os.ReadDir(dir) if err != nil { t.Fatal(err) } for _, e := range entries { p := filepath.Join(dir, e.Name()) if fi, err := os.Stat(p); err == nil && fi.IsDir() { walk(p) } else if e.Name() != ".git" { files = append(files, p) } } } walk(resolved) joined := strings.Join(files, "\n") for _, want := range []string{"manifests/site.pp", "external_modules/bind/manifests/init.pp", "external_modules/thing/metadata.json", markerFile} { if !strings.Contains(joined, filepath.Join(resolved, want)) { t.Fatalf("walk missed %s in:\n%s", want, joined) } } commit(t, f.control, map[string]string{"Puppetfile": "", "manifests/site.pp": "node default { }\n"}) f.clock = f.clock.Add(time.Minute) f.mustDeploy(false) if f.env("main") == resolved { t.Fatal("branch move must swap the env") } f.clock = f.clock.Add(8 * time.Minute) f.mustDeploy(false) for _, p := range files { if _, err := os.ReadFile(p); err != nil { t.Fatalf("in-flight compile lost %s: %v", p, err) } } f.clock = f.clock.Add(3 * time.Minute) f.mustDeploy(false) if exists(resolved) { t.Fatal("old worktree must be removed once grace has passed") } } func TestGitURLOptionInjection(t *testing.T) { f := newFixture(t) pwned := filepath.Join(f.root, "pwned") commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'evil', :git => '--upload-pack=touch %s;'\n", pwned)}) if err := f.deploy(false); err == nil { t.Fatal("option-like :git must be rejected") } if exists(pwned) { t.Fatal("injected --upload-pack ran") } } func TestInstallPathThroughCommittedSymlink(t *testing.T) { f := newFixture(t) victim := filepath.Join(f.root, "victim") mkdirs(t, filepath.Join(victim, "bind", "keep")) commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'bind', :git => '%s', :tag => '1.0', :install_path => 'escape'\n", f.mod)}) if err := os.Symlink(victim, filepath.Join(f.control, "escape")); err != nil { t.Fatal(err) } gitT(t, f.control, "add", "-A") gitT(t, f.control, "commit", "-q", "-m", "link") if err := f.deploy(false); err == nil { t.Fatal("install_path through a committed symlink must fail") } if !exists(filepath.Join(victim, "bind", "keep")) { t.Fatal("deploy wrote outside the worktree") } if f.env("main") != "" { t.Fatal("failed build must not go live") } } func TestNestedInstallPathSharedModule(t *testing.T) { f := newFixture(t) commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("forge '%s'\nmod 'acme-thing', '1.0.0'\n", f.forgeURL)}) f.mustDeploy(false) gitT(t, f.control, "checkout", "-q", "-b", "attacker") commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("forge '%s'\nmod 'acme-thing', '1.0.0'\nmod 'metadata', :git => '%s', :tag => '1.0', :install_path => 'modules/thing'\n", f.forgeURL, f.mod)}) if err := f.deploy(false); err == nil { t.Fatal("nested install_path must fail") } if exists(filepath.Join(f.forgeDir("acme-thing-1.0.0"), "metadata")) { t.Fatal("shared forge cache dir mutated by another branch") } } func TestCommittedMarkerDoesNotCompleteWorktree(t *testing.T) { f := newFixture(t) commit(t, f.control, map[string]string{ "Puppetfile": fmt.Sprintf("mod 'bind', :git => '%s', :tag => '1.0'\n", f.mod), markerFile: `{"modules":[]}`, "modules": "a file, so the module link fails", }) for range 2 { if err := f.deploy(false); err == nil { t.Fatal("broken build must fail") } if f.env("main") != "" { t.Fatal("incomplete worktree went live") } } } func TestMirrorKeyDistinctURLs(t *testing.T) { f := newFixture(t) other, victim := filepath.Join(f.root, "m_od"), filepath.Join(f.root, "m", "od") if urlKey(f.url(other)) == urlKey(f.url(victim)) { t.Fatal("distinct URLs share a mirror key") } newRepo(t, other) commit(t, other, map[string]string{"manifests/init.pp": "class evil {}\n"}) gitT(t, other, "tag", "1.0") newRepo(t, victim) commit(t, victim, map[string]string{"manifests/init.pp": "class good {}\n"}) gitT(t, victim, "tag", "1.0") commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'x', :git => '%s', :tag => '1.0'\n", f.url(victim))}) gitT(t, f.control, "checkout", "-q", "-b", "attacker") commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'x', :git => '%s', :tag => '1.0'\n", f.url(other))}) for range 5 { f.mustDeploy(true) b, _ := os.ReadFile(filepath.Join(f.env("main"), "modules", "x", "manifests", "init.pp")) if !strings.Contains(string(b), "good") { t.Fatalf("main got another branch's module: %q", b) } } } func TestForgeCacheKeyedByBase(t *testing.T) { f := newFixture(t) gitT(t, f.control, "checkout", "-q", "-b", "a") commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("forge '%s'\nmod 'acme-thing', '1.0.0'\n", f.forgeURL)}) f.mustDeploy(false) gitT(t, f.control, "checkout", "-q", "-b", "b") commit(t, f.control, map[string]string{"Puppetfile": "forge 'http://127.0.0.1:1'\nmod 'acme-thing', '1.0.0'\n"}) if err := f.deploy(false); err == nil { t.Fatal("release cached from one forge was served for another") } } func TestJobsBoundGitProcesses(t *testing.T) { f := newFixture(t) var pf strings.Builder for i := range 6 { repo := filepath.Join(f.root, fmt.Sprintf("r%d", i)) newRepo(t, repo) commit(t, repo, map[string]string{"manifests/init.pp": "class m {}\n"}) fmt.Fprintf(&pf, "mod 'm%d', :git => '%s'\n", i, f.url(repo)) } commit(t, f.control, map[string]string{"Puppetfile": pf.String()}) for i := range 4 { gitT(t, f.control, "branch", fmt.Sprintf("b%d", i)) } const jobs = 2 var mu sync.Mutex cur, peak := 0, 0 d := New(f.cfg, jobs, 10*time.Minute) d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) { mu.Lock() cur++ peak = max(peak, cur) mu.Unlock() defer func() { mu.Lock(); cur--; mu.Unlock() }() time.Sleep(time.Millisecond) return runGit(ctx, dir, args...) } if err := d.Deploy(context.Background(), nil, true); err != nil { t.Fatal(err) } if peak > jobs { t.Fatalf("%d concurrent git processes with -j %d", peak, jobs) } } func TestGenerateTypesBeforeSwap(t *testing.T) { f := newFixture(t) f.cfg.W10k.GenerateTypes = true typed := filepath.Join(f.root, "typed") newRepo(t, typed) commit(t, typed, map[string]string{ "lib/puppet/type/typed.rb": "Puppet::Type.newtype(:typed) do\n newparam(:name, namevar: true)\nend\n", "lib/puppet/provider/typed/posix.rb": "Puppet::Type.type(:typed).provide(:posix) do\nend\n", }) commit(t, f.control, map[string]string{ "Puppetfile": fmt.Sprintf("moduledir 'external_modules'\nmod 'typed', :git => '%s'\n", f.url(typed)), "environment.conf": "modulepath = site:external_modules:$basemodulepath\n", "site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n ensurable\n newparam(:name)\nend\n", }) f.mustDeploy(false) live := f.env("main") pp := readFileT(t, filepath.Join(f.basedir, "main", ".resource_types", "typed.pp")) if !strings.Contains(pp, "Puppet::Resource::Param(Any, 'provider')") || !exists(filepath.Join(live, ".resource_types", "local.pp")) { t.Fatalf("types not generated:\n%s", pp) } commit(t, f.control, map[string]string{"site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n newparam(dynamic)\nend\n"}) var logs bytes.Buffer log.SetOutput(&logs) defer log.SetOutput(os.Stderr) f.mustDeploy(false) skipped := f.env("main") if skipped == live || !exists(filepath.Join(skipped, ".resource_types", "typed.pp")) || exists(filepath.Join(skipped, ".resource_types", "local.pp")) { t.Fatal("an unparseable type is skipped while the env still deploys its other types") } for _, want := range []string{"environment main: generate types: skipped site/local/lib/puppet/type/local.rb: line 2:", "environment main: 1 types skipped"} { if !strings.Contains(logs.String(), want) { t.Fatalf("log lacks %q:\n%s", want, logs.String()) } } live = skipped commit(t, f.control, map[string]string{"site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n newparam(:name) do\n newvalues(" + strings.Repeat("[", 300) + strings.Repeat("]", 300) + ")\n end\nend\n"}) if err := f.deploy(false); err == nil || !strings.Contains(err.Error(), "deeper than") || !strings.Contains(err.Error(), "site/local/lib/puppet/type/local.rb") { t.Fatalf("a parser limit must fail the deploy naming the file: %v", err) } if f.env("main") != live { t.Fatal("failed generation must leave the live env untouched") } commit(t, f.control, map[string]string{"site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n newparam(:name)\nend\n"}) if err := os.Symlink("/tmp", filepath.Join(f.control, ".resource_types")); err != nil { t.Fatal(err) } gitT(t, f.control, "add", "-A") gitT(t, f.control, "commit", "-q", "-m", "link") if err := f.deploy(false); err == nil || !strings.Contains(err.Error(), "not a directory") { t.Fatalf("committed .resource_types symlink must fail: %v", err) } if f.env("main") != live { t.Fatal("failed generation must leave the live env untouched") } } func TestGenerateTypesToggleRedeploys(t *testing.T) { f := newFixture(t) commit(t, f.control, map[string]string{ "environment.conf": "modulepath = site:$basemodulepath\n", "site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n newparam(:name)\nend\n", }) f.mustDeploy(false) plain := f.env("main") if exists(filepath.Join(plain, ".resource_types")) { t.Fatal("types generated while generate_types is off") } f.cfg.W10k.GenerateTypes = true f.mustDeploy(false) typed := f.env("main") if typed == plain || !exists(filepath.Join(typed, ".resource_types", "local.pp")) { t.Fatalf("enabling generate_types must deploy a new worktree with types: %s", typed) } f.mustDeploy(false) if f.env("main") != typed { t.Fatal("an unchanged typed env must not be redeployed") } f.cfg.W10k.GenerateTypes = false f.mustDeploy(false) if f.env("main") != plain { t.Fatalf("disabling generate_types must return to the untyped worktree, got %s", f.env("main")) } } func readFileT(t *testing.T, p string) string { t.Helper() b, err := os.ReadFile(p) if err != nil { t.Fatal(err) } return string(b) } func TestCommittedMarkerTmpSymlinkWritesOutside(t *testing.T) { f := newFixture(t) commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) f.mustDeploy(false) victim := filepath.Join(f.basedir, "main", "manifests", "site.pp") gitT(t, f.control, "checkout", "-q", "-b", "attacker") if err := os.Symlink(victim, filepath.Join(f.control, markerFile+".tmp")); err != nil { t.Fatal(err) } gitT(t, f.control, "add", "-f", "-A") gitT(t, f.control, "commit", "-q", "-m", "link") _ = f.deploy(false) if b, _ := os.ReadFile(victim); string(b) != "node default {}\n" { t.Fatalf("branch overwrote a live env file via committed symlink:\n%s", b) } } func TestStalledGitRemoteFailsOnlyItsEnv(t *testing.T) { f := newFixture(t) ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = ln.Close() }) go func() { for { c, err := ln.Accept() if err != nil { return } t.Cleanup(func() { _ = c.Close() }) } }() timeout := 2 * time.Second f.cfg.W10k.GitTimeout = &timeout commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) gitT(t, f.control, "checkout", "-q", "-b", "slow") commit(t, f.control, map[string]string{"Puppetfile": "mod 'slow', :git => 'http://" + ln.Addr().String() + "/x.git'\n"}) done := make(chan error, 1) go func() { done <- f.deploy(false) }() select { case err := <-done: if err == nil || !strings.Contains(err.Error(), "environment slow") { t.Fatalf("stalled remote must fail its env, got %v", err) } case <-time.After(20 * time.Second): t.Fatal("deploy still blocked on a stalled :git remote after 20s") } if f.env("main") == "" || f.env("slow") != "" { t.Fatalf("main=%q slow=%q", f.env("main"), f.env("slow")) } } func TestGCKeepsModulesOfRemovedSource(t *testing.T) { f := newFixture(t) commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'bind', :git => '%s', :tag => '1.0'\n", f.mod)}) f.mustDeploy(false) site := filepath.Join(f.basedir, "main", "modules", "bind", "manifests", "init.pp") if !exists(site) { t.Fatal("module not deployed") } other := filepath.Join(f.root, "other") newRepo(t, other) commit(t, other, map[string]string{"manifests/site.pp": "node default {}\n"}) cfg, err := ParseConfig(fmt.Appendf(nil, "cachedir: %s\nsources:\n other:\n remote: %s\n basedir: %s\n", f.cfg.Cachedir, other, filepath.Join(f.root, "other-envs"))) if err != nil { t.Fatal(err) } f.cfg = cfg f.settle() if _, err := os.Stat(site); err != nil { t.Fatalf("GC deleted a module still linked from a removed source's live env: %v", err) } } func 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"]) } 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") newRepo(t, secret) commit(t, secret, map[string]string{"manifests/init.pp": "# private\n"}) for _, g := range []string{"file://" + secret, secret} { commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'loot', :git => '%s'\n", g)}) if err := f.deploy(false); err == nil { t.Fatalf(":git %s accepted", g) } if p := filepath.Join(f.basedir, "main", "modules", "loot", "manifests", "init.pp"); exists(p) { t.Fatalf("untrusted Puppetfile cloned a local repo into the env: %s", p) } } } func TestModuleFetchRefusesFileProtocol(t *testing.T) { f := newFixture(t) d := f.deployer() if err := d.syncMirror(context.Background(), filepath.Join(f.root, "m.git"), "file://"+f.modDir, modFetchOpts, modRefspecs); err == nil || !strings.Contains(err.Error(), "transport 'file' not allowed") { t.Fatalf("module fetch over file:// not refused: %v", err) } } func TestInterruptedModuleGCNotReused(t *testing.T) { f := newFixture(t) pf := fmt.Sprintf("mod 'bind', :git => '%s', :tag => '1.0'\n", f.mod) commit(t, f.control, map[string]string{"Puppetfile": pf}) f.mustDeploy(false) commit(t, f.control, map[string]string{"Puppetfile": "\n"}) f.mustDeploy(false) f.clock = f.clock.Add(11 * time.Minute) f.mustDeploy(false) f.clock = f.clock.Add(11 * time.Minute) d := f.deployer() crashed := false d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) { if len(args) > 1 && args[0] == "worktree" && args[1] == "remove" && strings.Contains(args[len(args)-1], "/modules/") { _ = os.Remove(filepath.Join(args[len(args)-1], "manifests", "init.pp")) crashed = true panic("crash mid-removal") } return runGit(ctx, dir, args...) } func() { defer func() { _ = recover() }() _ = d.GC(context.Background()) }() if !crashed { t.Fatal("GC never reached module removal") } commit(t, f.control, map[string]string{"Puppetfile": pf + "# again\n"}) f.mustDeploy(false) if p := filepath.Join(f.basedir, "main", "modules", "bind", "manifests", "init.pp"); !exists(p) { t.Fatalf("env went live with a half-deleted module dir reused from cache: %s missing", p) } if n := dirCount(t, f.cache("modules", urlKey(f.mod))); n != 1 { t.Fatalf("interrupted GC leftover not removed: %d entries", n) } } func TestUnmarkedCacheDirsRebuilt(t *testing.T) { f := newFixture(t) pf := fmt.Sprintf("forge '%s'\nmod 'acme-thing', '1.0.0'\nmod 'bind', :git => '%s', :tag => '1.0'\n", f.forgeURL, f.mod) commit(t, f.control, map[string]string{"Puppetfile": pf}) f.mustDeploy(false) d := f.deployer() forge := f.forgeDir("acme-thing-1.0.0") mods, _ := os.ReadDir(f.cache("modules", urlKey(f.mod))) mod := f.cache("modules", urlKey(f.mod), mods[0].Name()) for _, dir := range []string{forge, mod} { if err := os.Remove(d.doneFile(dir)); err != nil { t.Fatal(err) } } mustRemove(t, filepath.Join(forge, "metadata.json"), filepath.Join(mod, "manifests", "init.pp")) leftover := f.cache("forge", "x"+gcTag+strings.Repeat("A", 26)) mkdirs(t, leftover) commit(t, f.control, map[string]string{"Puppetfile": pf + "# again\n"}) f.mustDeploy(false) for _, p := range []string{"modules/thing/metadata.json", "modules/bind/manifests/init.pp"} { if !exists(filepath.Join(f.env("main"), p)) { t.Fatalf("unmarked cache dir reused: %s missing", p) } } if exists(leftover) { t.Fatal("gc leftover not removed") } } func mustRemove(t *testing.T, paths ...string) { t.Helper() for _, p := range paths { if err := os.Remove(p); err != nil { t.Fatal(err) } } } func TestPanicFailsOnlyItsEnv(t *testing.T) { f := newFixture(t) commit(t, f.control, map[string]string{"manifests/site.pp": "\n"}) gitT(t, f.control, "checkout", "-q", "-b", "bad") bad := commit(t, f.control, map[string]string{"manifests/site.pp": "# bad\n"}) d := f.deployer() d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) { if len(args) > 2 && args[0] == "cat-file" && strings.HasPrefix(args[2], bad) { panic("boom") } return runGit(ctx, dir, args...) } 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")) } if !exists(f.cache(gcStateFile)) { t.Fatal("GC skipped after a panicking env") } } 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 { gitT(t, f.control, "checkout", "-q", "-B", fmt.Sprintf("b%d", i)) commit(t, f.control, map[string]string{"n": fmt.Sprint(i)}) } d := New(f.cfg, 16, 10*time.Minute) d.now = func() time.Time { return f.clock } if err := d.Deploy(context.Background(), nil, false); err != nil { t.Fatal(err) } } func TestGCRefsErrorDropsMarkOfLiveWorktree(t *testing.T) { root := t.TempDir() s := &Source{Name: "s", Basedir: filepath.Join(root, "envs")} cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": s}} clock := time.Unix(1_700_000_000, 0) gc := func() error { d := New(cfg, 1, 10*time.Minute) d.now = func() time.Time { return clock } return d.GC(context.Background()) } d := New(cfg, 1, 0) old, cur, broken := filepath.Join(d.srcWorktrees(s), "old"), filepath.Join(d.srcWorktrees(s), "cur"), filepath.Join(d.srcWorktrees(s), "broken") mkdirs(t, old, cur, broken, s.Basedir, filepath.Dir(d.doneFile(old))) for _, p := range []string{old, cur} { if err := os.WriteFile(d.doneFile(p), []byte(`{"modules":[]}`), 0o644); err != nil { t.Fatal(err) } } link := filepath.Join(s.Basedir, "develop") if err := Swap(cur, link); err != nil { t.Fatal(err) } if err := gc(); err != nil { t.Fatal(err) } clock = clock.Add(time.Hour) if err := Swap(old, link); err != nil { t.Fatal(err) } if err := Swap(broken, filepath.Join(s.Basedir, "other")); err != nil { t.Fatal(err) } if err := gc(); err == nil { t.Fatal("want moduleRefs error from live worktree without done file") } if err := os.WriteFile(d.doneFile(broken), []byte(`{"modules":[]}`), 0o644); err != nil { t.Fatal(err) } if err := Swap(cur, link); err != nil { t.Fatal(err) } _ = gc() if !exists(old) { t.Fatal("worktree unreferenced this run was deleted in the same run via a stale mark kept while it was live") } } func TestDeployOnlyLeavesLaterSourceAlone(t *testing.T) { f := newFixture(t) commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) gitT(t, f.control, "branch", "production") other := filepath.Join(f.root, "other") newRepo(t, other) commit(t, other, map[string]string{"manifests/site.pp": "node default {}\n"}) otherBase := filepath.Join(f.root, "other-envs") cfg, err := ParseConfig(fmt.Appendf(nil, "cachedir: %s\nsources:\n aaa:\n remote: %s\n basedir: %s\n zzz:\n remote: %s\n basedir: %s\n", f.cfg.Cachedir, f.control, f.basedir, other, otherBase)) if err != nil { t.Fatal(err) } f.cfg = cfg if err := f.deploy(false, "production"); err != nil { t.Fatal(err) } if exists(filepath.Join(otherBase, "main")) { t.Fatal("deploy production also deployed every env of the next source") } } func TestDeployMarkerNameIsBranch(t *testing.T) { f := newFixture(t) commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) gitT(t, f.control, "checkout", "-q", "-b", "feat/x") commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) if err := f.deploy(false, "feat_x"); err != nil { t.Fatal(err) } if m := readMarker(t, f.env("feat_x")); m.Name != "feat/x" { t.Fatalf("marker name %q, want branch feat/x", m.Name) } } func TestTargetedDeploySkipsGC(t *testing.T) { f := newFixture(t) commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) f.mustDeploy(false) old := f.env("main") commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) f.mustDeploy(false) f.clock = f.clock.Add(time.Hour) if err := f.deploy(false, "main"); err != nil { t.Fatal(err) } if !exists(old) { t.Fatalf("targeted deploy ran GC and removed %s", old) } } func TestTargetedDeployDropsMarkOfReusedWorktree(t *testing.T) { f := newFixture(t) sha1 := commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) f.mustDeploy(false) w1 := f.env("main") commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) f.mustDeploy(false) f.clock = f.clock.Add(time.Hour) gitT(t, f.control, "reset", "-q", "--hard", sha1) if err := f.deploy(false, "main"); err != nil || f.env("main") != w1 { t.Fatalf("targeted deploy did not reuse %s: %v", w1, err) } commit(t, f.control, map[string]string{"manifests/site.pp": "node y {}\n"}) if err := f.deploy(false, "main"); err != nil { t.Fatal(err) } f.mustDeploy(false) if !exists(w1) { t.Fatal("worktree live during a targeted deploy kept its earlier mark and was deleted without grace") } } func TestGCLiveErrorDropsMarkOfLiveWorktree(t *testing.T) { root := t.TempDir() s := &Source{Name: "s", Basedir: filepath.Join(root, "envs")} u := &Source{Name: "u", Basedir: filepath.Join(root, "uenvs")} cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": s, "u": u}} clock := time.Unix(1_700_000_000, 0) gc := func() error { d := New(cfg, 1, 10*time.Minute) d.now = func() time.Time { return clock } return d.GC(context.Background()) } d := New(cfg, 1, 0) old, cur := filepath.Join(d.srcWorktrees(s), "old"), filepath.Join(d.srcWorktrees(s), "cur") mkdirs(t, old, cur, s.Basedir, filepath.Dir(d.doneFile(old))) for _, p := range []string{old, cur} { if err := os.WriteFile(d.doneFile(p), []byte(`{"modules":[]}`), 0o644); err != nil { t.Fatal(err) } } link := filepath.Join(s.Basedir, "develop") if err := Swap(cur, link); err != nil { t.Fatal(err) } if err := gc(); err != nil { t.Fatal(err) } clock = clock.Add(time.Hour) if err := Swap(old, link); err != nil { t.Fatal(err) } if err := os.WriteFile(u.Basedir, nil, 0o644); err != nil { t.Fatal(err) } if err := gc(); err == nil { t.Fatal("want Live error") } if err := os.Remove(u.Basedir); err != nil { t.Fatal(err) } if err := Swap(cur, link); err != nil { t.Fatal(err) } _ = gc() if !exists(old) { t.Fatal("worktree unreferenced this run was deleted in the same run via a mark kept by GC's early return") } } func TestGCCorruptStateTreatedAsEmpty(t *testing.T) { root := t.TempDir() s := &Source{Name: "s", Basedir: filepath.Join(root, "envs")} cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": s}} d := New(cfg, 1, 10*time.Minute) old := filepath.Join(d.srcWorktrees(s), "old") mkdirs(t, old, s.Basedir) state := d.path(gcStateFile) if err := os.WriteFile(state, []byte("{not json"), 0o644); err != nil { t.Fatal(err) } if err := d.GC(context.Background()); err != nil { t.Fatalf("corrupt state wedged GC: %v", err) } b, err := os.ReadFile(state) if err != nil { t.Fatal(err) } var marks map[string]time.Time if err := json.Unmarshal(b, &marks); err != nil { t.Fatalf("state not rewritten: %v", err) } if _, ok := marks[old]; !ok || !exists(old) { t.Fatal("unreferenced worktree must be freshly marked, not deleted") } } func TestExactBranchWinsEnvName(t *testing.T) { f := newFixture(t) commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) gitT(t, f.control, "checkout", "-q", "-b", "feature_x") legit := commit(t, f.control, map[string]string{"manifests/site.pp": "node legit {}\n"}) gitT(t, f.control, "checkout", "-q", "-b", "feature-x") commit(t, f.control, map[string]string{"manifests/site.pp": "node evil {}\n"}) err := f.deploy(false) if got := f.env("feature_x"); !strings.HasPrefix(filepath.Base(got), legit+"-") { t.Fatalf("env feature_x -> %s, want branch feature_x (%s); a pushed feature-x took it over", filepath.Base(got), legit) } if err == nil || !strings.Contains(err.Error(), "feature-x") { t.Fatalf("want collision error naming feature-x, got %v", err) } } func TestCorrectedBranchCollisionSkipsAll(t *testing.T) { f := newFixture(t) commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) gitT(t, f.control, "branch", "feature-x") gitT(t, f.control, "branch", "feature.x") err := f.deploy(false) if exists(filepath.Join(f.basedir, "feature_x")) { t.Fatal("colliding corrected branches must not deploy feature_x") } if err == nil || !strings.Contains(err.Error(), "feature-x") || !strings.Contains(err.Error(), "feature.x") { t.Fatalf("want collision error naming both branches, got %v", err) } if f.env("main") == "" { t.Fatal("collision must not block other envs") } }