diff --git a/README.md b/README.md index ae7fbe3..289ba3b 100644 --- a/README.md +++ b/README.md @@ -267,6 +267,16 @@ workload). It costs a few microseconds on a write that finds no batch to join, so a lone serialized writer (a CI fixture doing one thing at a time) can turn it off with `--sqlite-group-commit=false`. +**Unused cookbook files expire.** A sandbox (the handshake a client uploads +cookbook files through) expires two hours after it was created or, once +committed, two hours after the commit. Every ten minutes the server deletes +expired sandboxes and the files they announced that no cookbook or cookbook +artifact references and no open sandbox still names. Unlike Chef Infra Server, +which keeps such files (and uncommitted sandboxes) indefinitely, this means a +file uploaded and never used does not hold memory or disk for good, and +committing an expired sandbox answers `404`. `knife` and `chef` upload, commit +and write the manifest in one run, so they are unaffected. + The storage layer is pluggable behind a small `store.Backend` interface (`(org, collection, key) → bytes` plus a blob store), so PostgreSQL/RDS can be added later as a driver swap rather than a rewrite. diff --git a/internal/api/api.go b/internal/api/api.go index e1ed609..34813e4 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -69,6 +69,9 @@ type API struct { // membership orders group-membership changes against revocations; see // groupmembers.go. membership membershipLock + // blobRefs orders blob GC against the handlers that come to depend on a + // stored blob; see blobrefs.go. + blobRefs blobRefLocks } // Option configures an API at construction time. diff --git a/internal/api/blobref_race_test.go b/internal/api/blobref_race_test.go new file mode 100644 index 0000000..bcb3ce7 --- /dev/null +++ b/internal/api/blobref_race_test.go @@ -0,0 +1,155 @@ +package api + +import ( + "encoding/json" + "net/http" + "strings" + "sync" + "testing" + "time" +) + +// duringBlobGC runs req once, concurrently, while a blob GC sits between +// finding what is still referenced and deleting the rest, and lets the GC go on +// once req has finished or has been held back for a while. Without ordering +// between the two, req completes inside that window and the GC then deletes a +// blob req just came to depend on. It returns req's status and body. +func duringBlobGC(t *testing.T, req func() (int, string)) (wait func() (int, string)) { + t.Helper() + var once sync.Once + done := make(chan struct{}) + var code int + var body string + testHookBlobGC = func() { + once.Do(func() { + go func() { + code, body = req() + close(done) + }() + select { + case <-done: + case <-time.After(300 * time.Millisecond): + } + }) + } + t.Cleanup(func() { testHookBlobGC = nil }) + return func() (int, string) { + <-done + return code, body + } +} + +// A sandbox announced while a sweep is collecting an expired sandbox's files +// either keeps a file it is told needs no upload, or is told to upload it. +func TestSandboxCreateDuringSweepKeepsTheBlob(t *testing.T) { + for name, open := range sweepBackends { + t.Run(name, func(t *testing.T) { + a, base, clock := newSweepAPI(t, open(t)) + sum := md5hex("announced again") + openSandbox(t, base, sum) + uploadBlob(t, base, "announced again") + clock.advance(sandboxTTL + time.Minute) + + // Baseline: with nothing announcing it again, the sweep takes it. + if err := a.SweepSandboxes(); err != nil { + t.Fatal(err) + } + if got := fileStatus(t, base, sum); got != 404 { + t.Fatalf("baseline: swept file = %d, want 404", got) + } + uploadBlob(t, base, "announced again") + openSandbox(t, base, sum) + clock.advance(sandboxTTL + time.Minute) + + wait := duringBlobGC(t, func() (int, string) { + resp, body := doAt(t, "2", "POST", base+"/sandboxes", `{"checksums":{"`+sum+`":null}}`) + return resp.StatusCode, body + }) + if err := a.SweepSandboxes(); err != nil { + t.Fatal(err) + } + code, body := wait() + if code != 201 { + t.Fatalf("create sandbox = %d: %s", code, body) + } + var sb struct { + Checksums map[string]struct { + NeedsUpload bool `json:"needs_upload"` + } `json:"checksums"` + } + if err := json.Unmarshal([]byte(body), &sb); err != nil { + t.Fatal(err) + } + if !sb.Checksums[sum].NeedsUpload && fileStatus(t, base, sum) != 200 { + t.Fatal("sandbox was told the file needs no upload, then the sweep deleted it") + } + }) + } +} + +// A manifest written while a sweep is collecting an expired sandbox's files +// either is refused or keeps every file it references. +func TestManifestPutDuringSweepKeepsTheBlob(t *testing.T) { + for name, open := range sweepBackends { + t.Run(name, func(t *testing.T) { + a, base, clock := newSweepAPI(t, open(t)) + sum := md5hex("referenced late") + openSandbox(t, base, sum) + uploadBlob(t, base, "referenced late") + clock.advance(sandboxTTL + time.Minute) + + wait := duringBlobGC(t, func() (int, string) { + resp, body := doAt(t, "2", "PUT", base+"/cookbooks/late/1.0.0", manifest("late", "1.0.0", sum)) + return resp.StatusCode, body + }) + if err := a.SweepSandboxes(); err != nil { + t.Fatal(err) + } + assertManifestConsistent(t, base, sum, wait) + }) + } +} + +// A manifest written while overwriting another cookbook version collects that +// version's old files either is refused or keeps every file it references. +func TestManifestPutDuringOverwriteGCKeepsTheBlob(t *testing.T) { + for name, open := range sweepBackends { + t.Run(name, func(t *testing.T) { + _, base, _ := newSweepAPI(t, open(t)) + old := uploadBlob(t, base, "old content") + fresh := uploadBlob(t, base, "new content") + if resp, b := doAt(t, "2", "PUT", base+"/cookbooks/web/1.0.0", manifest("web", "1.0.0", old)); resp.StatusCode != 201 { + t.Fatalf("put v1 = %d: %s", resp.StatusCode, b) + } + + wait := duringBlobGC(t, func() (int, string) { + resp, body := doAt(t, "2", "PUT", base+"/cookbooks/other/1.0.0", manifest("other", "1.0.0", old)) + return resp.StatusCode, body + }) + // Overwrite v1 so it no longer references old; its GC runs the hook. + if resp, b := doAt(t, "2", "PUT", base+"/cookbooks/web/1.0.0", manifest("web", "1.0.0", fresh)); resp.StatusCode != 200 { + t.Fatalf("overwrite v1 = %d: %s", resp.StatusCode, b) + } + assertManifestConsistent(t, base, old, wait) + }) + } +} + +// assertManifestConsistent fails if the concurrent manifest PUT was stored +// while the blob it references is gone. +func assertManifestConsistent(t *testing.T, base, sum string, wait func() (int, string)) { + t.Helper() + code, body := wait() + switch code { + case http.StatusCreated: + if got := fileStatus(t, base, sum); got != 200 { + t.Fatalf("manifest stored (201) but its file = %d: GETs hand out a URL to a missing file", got) + } + case http.StatusBadRequest: + if !strings.Contains(body, "hasn't been uploaded") { + t.Fatalf("manifest refused for another reason: %s", body) + } + default: + t.Fatalf("manifest PUT = %d: %s", code, body) + } +} diff --git a/internal/api/blobrefs.go b/internal/api/blobrefs.go new file mode 100644 index 0000000..7674d40 --- /dev/null +++ b/internal/api/blobrefs.go @@ -0,0 +1,36 @@ +package api + +import "sync" + +// blobRefLocks orders, per org, the code that comes to depend on a stored +// blob against the code that deletes blobs nothing depends on. +// +// A handler that checks a blob exists and then records a dependence on it (a +// sandbox told the file needs no upload, a committed sandbox, a cookbook or +// artifact manifest) holds its org's lock shared from the check through the +// write. A blob GC (gcOrphanedBlobs, SweepSandboxes) holds it exclusively from +// finding what is still referenced through the deletes. Otherwise a GC could +// read the references, a handler could then pass its check and write, and the +// GC would delete a blob the new write needs. A handler that also runs a GC +// releases its shared hold first; a hold is never upgraded in place. +// +// putFile takes no lock: an upload can be slow, and the sweep never deletes a +// file an open sandbox names. It is independent of API.membership. +type blobRefLocks struct { + mu sync.Mutex // guards orgs + orgs map[string]*sync.RWMutex +} + +func (l *blobRefLocks) org(name string) *sync.RWMutex { + l.mu.Lock() + defer l.mu.Unlock() + if l.orgs == nil { + l.orgs = map[string]*sync.RWMutex{} + } + m, ok := l.orgs[name] + if !ok { + m = &sync.RWMutex{} + l.orgs[name] = m + } + return m +} diff --git a/internal/api/cookbook_artifacts.go b/internal/api/cookbook_artifacts.go index f86e99e..a366c88 100644 --- a/internal/api/cookbook_artifacts.go +++ b/internal/api/cookbook_artifacts.go @@ -133,19 +133,16 @@ func (a *API) putArtifactVersion(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusInternalServerError, err.Error()) return } - for _, sum := range manifestChecksums(m) { - has, err := org.HasBlob(sum) - if err != nil { - writeError(w, http.StatusInternalServerError, err.Error()) - return + if !a.withBlobRefs(org, func() bool { + if !requireBlobs(w, org, m) { + return false } - if !has { - writeError(w, http.StatusBadRequest, "Manifest has a checksum that hasn't been uploaded: "+sum) - return + if err := org.Put("cookbook_artifacts", cookbookKey(name, ident), raw); err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return false } - } - if err := org.Put("cookbook_artifacts", cookbookKey(name, ident), raw); err != nil { - writeError(w, http.StatusInternalServerError, err.Error()) + return true + }) { return } if err := a.grantCreatorIfNew(r, org, "cookbook_artifacts", name, isNew); err != nil { @@ -177,7 +174,7 @@ func (a *API) deleteArtifactVersion(w http.ResponseWriter, r *http.Request) { } var m map[string]any if json.Unmarshal(raw, &m) == nil { - if err := gcOrphanedBlobs(org, manifestChecksums(m)); err != nil { + if err := a.gcOrphanedBlobs(org, manifestChecksums(m)); err != nil { writeError(w, http.StatusInternalServerError, err.Error()) return } diff --git a/internal/api/cookbooks.go b/internal/api/cookbooks.go index 7a9beaf..23d319b 100644 --- a/internal/api/cookbooks.go +++ b/internal/api/cookbooks.go @@ -218,27 +218,33 @@ func (a *API) createSandbox(w http.ResponseWriter, r *http.Request) { id := sandboxID(sums) out := map[string]any{} - for _, sum := range sums { - has, err := org.HasBlob(sum) - if err != nil { - writeError(w, http.StatusInternalServerError, err.Error()) - return + // A file reported as needing no upload must survive until the sandbox is + // stored to protect it. + if !a.withBlobRefs(org, func() bool { + for _, sum := range sums { + has, err := org.HasBlob(sum) + if err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return false + } + if has { + out[sum] = map[string]any{"needs_upload": false} + } else { + out[sum] = map[string]any{"url": a.fileStoreURL(r, org.Name(), sum, auth.FileStorePut), "needs_upload": true} + } } - if has { - out[sum] = map[string]any{"needs_upload": false} - } else { - out[sum] = map[string]any{"url": a.fileStoreURL(r, org.Name(), sum, auth.FileStorePut), "needs_upload": true} + doc := map[string]any{ + "sandbox_id": id, + "checksums": sums, + "is_completed": false, + "create_time": a.now().UTC().Format(time.RFC3339), } - } - - doc := map[string]any{ - "sandbox_id": id, - "checksums": sums, - "is_completed": false, - "create_time": time.Now().UTC().Format(time.RFC3339), - } - if err := org.Put("sandboxes", id, mustEncode(doc)); err != nil { - writeError(w, http.StatusInternalServerError, err.Error()) + if err := org.Put("sandboxes", id, mustEncode(doc)); err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return false + } + return true + }) { return } @@ -299,6 +305,12 @@ func (a *API) commitSandbox(w http.ResponseWriter, r *http.Request) { if org == nil { return } + // From reading the sandbox through storing it committed, a sweep must + // neither delete it nor the files it checks. + a.withBlobRefs(org, func() bool { a.commitSandboxLocked(w, r, org); return true }) +} + +func (a *API) commitSandboxLocked(w http.ResponseWriter, r *http.Request, org *store.Org) { id := r.PathValue("id") raw, ok, err := org.Get("sandboxes", id) if err != nil { @@ -309,9 +321,7 @@ func (a *API) commitSandbox(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusNotFound, "Cannot find sandbox "+id) return } - var doc struct { - Checksums []string `json:"checksums"` - } + var doc storedSandbox if err := json.Unmarshal(raw, &doc); err != nil { writeError(w, http.StatusInternalServerError, err.Error()) return @@ -335,7 +345,18 @@ func (a *API) commitSandbox(w http.ResponseWriter, r *http.Request) { "checksums": doc.Checksums, "is_completed": true, } - if err := org.Put("sandboxes", id, mustEncode(committed)); err != nil { + // The stored form keeps when the sandbox was made and committed, which + // decides when SweepSandboxes may reclaim its files; the response is as + // before. + stored := map[string]any{ + "guid": id, + "name": id, + "checksums": doc.Checksums, + "is_completed": true, + "create_time": doc.CreateTime, + "commit_time": a.now().UTC().Format(time.RFC3339), + } + if err := org.Put("sandboxes", id, mustEncode(stored)); err != nil { writeError(w, http.StatusInternalServerError, err.Error()) return } @@ -626,21 +647,18 @@ func (a *API) putCookbookVersion(w http.ResponseWriter, r *http.Request) { return } - // Every referenced file must already be in the blob store. - for _, sum := range manifestChecksums(m) { - has, err := org.HasBlob(sum) - if err != nil { - writeError(w, http.StatusInternalServerError, err.Error()) - return + // Every referenced file must already be in the blob store, and stay there + // until the manifest that references it is stored. + if !a.withBlobRefs(org, func() bool { + if !requireBlobs(w, org, m) { + return false } - if !has { - writeError(w, http.StatusBadRequest, "Manifest has a checksum that hasn't been uploaded: "+sum) - return + if err := org.Put("cookbooks", cookbookKey(name, version), raw); err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return false } - } - - if err := org.Put("cookbooks", cookbookKey(name, version), raw); err != nil { - writeError(w, http.StatusInternalServerError, err.Error()) + return true + }) { return } if err := a.grantCreatorIfNew(r, org, "cookbooks", name, isNew); err != nil { @@ -654,7 +672,7 @@ func (a *API) putCookbookVersion(w http.ResponseWriter, r *http.Request) { if existed { var old map[string]any if json.Unmarshal(prev, &old) == nil { - if err := gcOrphanedBlobs(org, manifestChecksums(old)); err != nil { + if err := a.gcOrphanedBlobs(org, manifestChecksums(old)); err != nil { writeError(w, http.StatusInternalServerError, err.Error()) return } @@ -713,7 +731,7 @@ func (a *API) deleteCookbookVersion(w http.ResponseWriter, r *http.Request) { } var m map[string]any if json.Unmarshal(raw, &m) == nil { - if err := gcOrphanedBlobs(org, manifestChecksums(m)); err != nil { + if err := a.gcOrphanedBlobs(org, manifestChecksums(m)); err != nil { writeError(w, http.StatusInternalServerError, err.Error()) return } @@ -874,11 +892,51 @@ func referencedChecksums(org *store.Org) (map[string]bool, error) { return refs, nil } +// requireBlobs reports whether every file manifest m references is in the +// blob store, answering 400 (or 500) when one is not. The caller holds the +// org's blob-reference lock shared through the write that records m. +func requireBlobs(w http.ResponseWriter, org *store.Org, m map[string]any) bool { + for _, sum := range manifestChecksums(m) { + has, err := org.HasBlob(sum) + if err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return false + } + if !has { + writeError(w, http.StatusBadRequest, "Manifest has a checksum that hasn't been uploaded: "+sum) + return false + } + } + return true +} + +// withBlobRefs runs fn holding org's blob-reference lock shared (see +// blobRefLocks) and returns what fn does. +func (a *API) withBlobRefs(org *store.Org, fn func() bool) bool { + l := a.blobRefs.org(org.Name()) + l.RLock() + defer l.RUnlock() + return fn() +} + // gcOrphanedBlobs deletes each candidate checksum from the file store unless it // is still referenced by some remaining cookbook or artifact manifest. Call it // after removing a manifest so its now-orphaned content becomes unavailable, -// while content shared with another version/artifact survives. -func gcOrphanedBlobs(org *store.Org, candidates []string) error { +// while content shared with another version/artifact survives. It holds the +// org's blob-reference lock exclusively, so the caller must not hold it. +func (a *API) gcOrphanedBlobs(org *store.Org, candidates []string) error { + if len(candidates) == 0 { + return nil + } + l := a.blobRefs.org(org.Name()) + l.Lock() + defer l.Unlock() + return collectOrphanedBlobs(org, candidates) +} + +// collectOrphanedBlobs is gcOrphanedBlobs for a caller already holding the +// org's blob-reference lock exclusively. +func collectOrphanedBlobs(org *store.Org, candidates []string) error { if len(candidates) == 0 { return nil } @@ -886,6 +944,9 @@ func gcOrphanedBlobs(org *store.Org, candidates []string) error { if err != nil { return err } + if testHookBlobGC != nil { + testHookBlobGC() + } for _, sum := range candidates { if !referenced[sum] { if err := org.DeleteBlob(sum); err != nil { diff --git a/internal/api/sandbox_sweep.go b/internal/api/sandbox_sweep.go new file mode 100644 index 0000000..9115f58 --- /dev/null +++ b/internal/api/sandbox_sweep.go @@ -0,0 +1,129 @@ +package api + +import ( + "encoding/json" + "time" + + "github.com/cinc-project/cinc-server-ng/internal/store" +) + +// sandboxTTL is how long a sandbox, committed or not, keeps the files it +// announced. A file reaches the store only through the upload grant a sandbox +// hands out, so once every sandbox naming a file has expired and no cookbook or +// artifact manifest references it, nothing can use it and SweepSandboxes +// deletes it. It outlasts the upload grant (fileStoreGrantTTL), so a file +// cannot be uploaded after its sandbox stopped protecting it, and leaves the +// client time to commit and PUT the manifest. Committing restarts it. +// +// erchef keeps an uncommitted sandbox, and the files uploaded for it, forever, +// and keeps a committed checksum until a cookbook or artifact that referenced +// it is deleted; bookshelf reaps only uploads that never completed. With the +// memory backend that would let one org member hold any amount of the server's +// memory with files nothing uses, so these expire. +const sandboxTTL = 2 * fileStoreGrantTTL + +// storedSandbox is the stored form of a sandbox, as createSandbox and +// commitSandbox write it. +type storedSandbox struct { + Checksums []string `json:"checksums"` + CreateTime string `json:"create_time"` + CommitTime string `json:"commit_time"` +} + +// expired reports whether the sandbox stopped protecting its files by now. A +// sandbox with no readable timestamp (one committed by a version that did not +// keep it) has expired. +func (s storedSandbox) expired(now time.Time) bool { + stamp := s.CommitTime + if stamp == "" { + stamp = s.CreateTime + } + t, err := time.Parse(time.RFC3339, stamp) + return err != nil || !now.Before(t.Add(sandboxTTL)) +} + +// SweepSandboxes removes every org's expired sandboxes and the files they +// announced that no manifest references and no open sandbox still names. The +// server runs it periodically; a library user serving the API directly calls +// it on a schedule of their own. +func (a *API) SweepSandboxes() error { + names, err := a.store.ListOrgs() + if err != nil { + return err + } + now := a.now() + for _, name := range names { + org, ok, err := a.store.Org(name) + if err != nil { + return err + } + if !ok { + continue // deleted since it was listed + } + if err := a.sweepSandboxes(org, now); err != nil { + return err + } + } + return nil +} + +// sweepSandboxes holds org's blob-reference lock exclusively from reading the +// sandboxes through the deletes, so no sandbox, commit or manifest that comes +// to depend on a file can land in between (see blobRefLocks). +func (a *API) sweepSandboxes(org *store.Org, now time.Time) error { + l := a.blobRefs.org(org.Name()) + l.Lock() + defer l.Unlock() + ids, err := org.Keys("sandboxes") + if err != nil { + return err + } + var expired []string + candidates := map[string]bool{} + open := map[string]bool{} + for _, id := range ids { + raw, ok, err := org.Get("sandboxes", id) + if err != nil { + return err + } + if !ok { + continue + } + var sb storedSandbox + _ = json.Unmarshal(raw, &sb) // unreadable: no timestamp, so expired + if !sb.expired(now) { + for _, sum := range sb.Checksums { + open[sum] = true + } + continue + } + expired = append(expired, id) + for _, sum := range sb.Checksums { + candidates[sum] = true + } + } + if len(expired) == 0 { + return nil + } + var orphans []string + for sum := range candidates { + if !open[sum] { + orphans = append(orphans, sum) + } + } + // Files first: a sweep that fails part way leaves the sandboxes, and the + // next one finishes the job. + if err := collectOrphanedBlobs(org, orphans); err != nil { + return err + } + for _, id := range expired { + if _, _, err := org.Delete("sandboxes", id); err != nil { + return err + } + } + return nil +} + +// testHookBlobGC, when set, runs inside a blob GC after it has found which +// checksums are still referenced and before it deletes the rest. +var testHookBlobGC func() diff --git a/internal/api/sandbox_sweep_test.go b/internal/api/sandbox_sweep_test.go new file mode 100644 index 0000000..29c1eb2 --- /dev/null +++ b/internal/api/sandbox_sweep_test.go @@ -0,0 +1,213 @@ +package api + +import ( + "encoding/json" + "net/http/httptest" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/cinc-project/cinc-server-ng/internal/store" + "github.com/cinc-project/cinc-server-ng/internal/store/sqlite" +) + +// testClock is a settable clock for the sandbox sweep tests. +type testClock struct { + mu sync.Mutex + t time.Time +} + +func (c *testClock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *testClock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} + +// sweepBackends opens an "acme" store on each backend: the sweep reads and +// deletes blobs, which the two store differently. +var sweepBackends = map[string]func(t *testing.T) *store.Store{ + "memory": func(t *testing.T) *store.Store { return store.New() }, + "sqlite": func(t *testing.T) *store.Store { + be, err := sqlite.Open(filepath.Join(t.TempDir(), "sweep.db")) + if err != nil { + t.Fatal(err) + } + st := store.NewWithBackend(be) + t.Cleanup(func() { st.Close() }) + return st + }, +} + +func newSweepAPI(t *testing.T, st *store.Store) (*API, string, *testClock) { + t.Helper() + if _, err := st.CreateOrg("acme"); err != nil { + t.Fatal(err) + } + clock := &testClock{t: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)} + a := New(st, WithClock(clock.now)) + srv := httptest.NewServer(a.Handler()) + t.Cleanup(srv.Close) + return a, srv.URL + "/organizations/acme", clock +} + +// openSandbox announces sums and returns the sandbox id. +func openSandbox(t *testing.T, base string, sums ...string) string { + t.Helper() + parts := make([]string, len(sums)) + for i, s := range sums { + parts[i] = `"` + s + `":null` + } + resp, body := doAt(t, "2", "POST", base+"/sandboxes", `{"checksums":{`+strings.Join(parts, ",")+`}}`) + if resp.StatusCode != 201 { + t.Fatalf("create sandbox = %d: %s", resp.StatusCode, body) + } + var sb struct { + SandboxID string `json:"sandbox_id"` + } + if err := json.Unmarshal([]byte(body), &sb); err != nil { + t.Fatal(err) + } + return sb.SandboxID +} + +func commitStatus(t *testing.T, base, id string) int { + t.Helper() + resp, _ := doAt(t, "2", "PUT", base+"/sandboxes/"+id, `{"is_completed":true}`) + return resp.StatusCode +} + +// A file uploaded through a sandbox that no manifest came to reference is +// removed once the sandbox expires, committed or not; a referenced one stays. +func TestSandboxSweepCollectsUnreferencedUploads(t *testing.T) { + for name, open := range sweepBackends { + t.Run(name, func(t *testing.T) { + a, base, clock := newSweepAPI(t, open(t)) + + used, unused := md5hex("used file"), md5hex("committed, never used") + committed := openSandbox(t, base, used, unused) + uploadBlob(t, base, "used file") + uploadBlob(t, base, "committed, never used") + if got := commitStatus(t, base, committed); got != 200 { + t.Fatalf("commit = %d", got) + } + if resp, b := doAt(t, "2", "PUT", base+"/cookbooks/web/1.0.0", manifest("web", "1.0.0", used)); resp.StatusCode != 201 { + t.Fatalf("put cookbook = %d: %s", resp.StatusCode, b) + } + abandoned := md5hex("uploaded, never committed") + pending := openSandbox(t, base, abandoned) + uploadBlob(t, base, "uploaded, never committed") + + // Within the TTL a sweep keeps everything. + clock.advance(sandboxTTL - time.Minute) + if err := a.SweepSandboxes(); err != nil { + t.Fatal(err) + } + for _, sum := range []string{used, unused, abandoned} { + if got := fileStatus(t, base, sum); got != 200 { + t.Fatalf("before expiry: file %s = %d, want 200", sum, got) + } + } + + clock.advance(2 * time.Minute) + if err := a.SweepSandboxes(); err != nil { + t.Fatal(err) + } + if got := fileStatus(t, base, used); got != 200 { + t.Fatalf("referenced file = %d, want 200", got) + } + for _, sum := range []string{unused, abandoned} { + if got := fileStatus(t, base, sum); got != 404 { + t.Fatalf("unreferenced file %s = %d, want 404", sum, got) + } + } + if got := commitStatus(t, base, pending); got != 404 { + t.Fatalf("commit of an expired sandbox = %d, want 404", got) + } + }) + } +} + +// A file announced by a sandbox that is still open survives the expiry of an +// older sandbox that announced it too: the newer one told its client the file +// needs no upload. +func TestSandboxSweepKeepsFilesOfOpenSandboxes(t *testing.T) { + for name, open := range sweepBackends { + t.Run(name, func(t *testing.T) { + a, base, clock := newSweepAPI(t, open(t)) + + shared := md5hex("shared") + openSandbox(t, base, shared) + uploadBlob(t, base, "shared") + + clock.advance(sandboxTTL - 10*time.Minute) + other := md5hex("other") + newer := openSandbox(t, base, shared, other) + uploadBlob(t, base, "other") + + clock.advance(20 * time.Minute) // the first sandbox has expired + if err := a.SweepSandboxes(); err != nil { + t.Fatal(err) + } + if got := fileStatus(t, base, shared); got != 200 { + t.Fatalf("file of an open sandbox = %d, want 200", got) + } + if got := commitStatus(t, base, newer); got != 200 { + t.Fatalf("commit of the open sandbox = %d, want 200", got) + } + }) + } +} + +// Committing restarts the clock: a sandbox committed just before it would have +// expired keeps its files for the manifest that follows. +func TestSandboxSweepCountsFromCommit(t *testing.T) { + for name, open := range sweepBackends { + t.Run(name, func(t *testing.T) { + a, base, clock := newSweepAPI(t, open(t)) + + sum := md5hex("late commit") + id := openSandbox(t, base, sum) + uploadBlob(t, base, "late commit") + clock.advance(sandboxTTL - time.Minute) + if got := commitStatus(t, base, id); got != 200 { + t.Fatalf("commit = %d", got) + } + clock.advance(2 * time.Minute) + if err := a.SweepSandboxes(); err != nil { + t.Fatal(err) + } + if resp, b := doAt(t, "2", "PUT", base+"/cookbooks/late/1.0.0", manifest("late", "1.0.0", sum)); resp.StatusCode != 201 { + t.Fatalf("put cookbook after a late commit = %d: %s", resp.StatusCode, b) + } + }) + } +} + +// A sandbox stored without a timestamp (committed by an older version, which +// dropped it) counts as expired, so what it left unreferenced is reclaimed. +func TestSandboxSweepReclaimsUntimedSandboxes(t *testing.T) { + st := store.New() + a, base, _ := newSweepAPI(t, st) + sum := uploadBlob(t, base, "left over") + org, _, _ := st.Org("acme") + if err := org.Put("sandboxes", "old", []byte(`{"guid":"old","name":"old","checksums":["`+sum+`"],"is_completed":true}`)); err != nil { + t.Fatal(err) + } + if err := a.SweepSandboxes(); err != nil { + t.Fatal(err) + } + if got := fileStatus(t, base, sum); got != 404 { + t.Fatalf("file of an untimed sandbox = %d, want 404", got) + } + if _, ok, _ := org.Get("sandboxes", "old"); ok { + t.Fatal("untimed sandbox kept") + } +} diff --git a/server/sandbox_sweep_test.go b/server/sandbox_sweep_test.go new file mode 100644 index 0000000..a855ec7 --- /dev/null +++ b/server/sandbox_sweep_test.go @@ -0,0 +1,53 @@ +package server + +import ( + "net/http" + "strings" + "sync" + "testing" + "time" +) + +// The running server reclaims a file whose sandbox expired without any +// manifest referencing it, without a request asking it to. +func TestServerSweepsExpiredSandboxes(t *testing.T) { + var mu sync.Mutex + now := time.Now() + clock := func() time.Time { mu.Lock(); defer mu.Unlock(); return now } + srv := startServer(t, Options{ + Orgs: []string{"acme"}, + EnforceACL: true, + Now: clock, + sandboxSweepEvery: 10 * time.Millisecond, + }) + base := srv.URL() + "/organizations/acme" + + content := "never referenced" + sum := md5Hex(content) + sb := adminSandbox(t, srv, base, sum) + req, _ := http.NewRequest("PUT", sb.Checksums[sum].URL, strings.NewReader(content)) + if code, raw := doJSON(t, req); code != http.StatusOK { + t.Fatalf("upload = %d: %s", code, raw) + } + org, _, _ := srv.store.Org("acme") + + // Baseline: an open sandbox keeps its file through many sweeps. + time.Sleep(50 * time.Millisecond) + if ok, _ := org.HasBlob(sum); !ok { + t.Fatal("file of an open sandbox was swept") + } + + mu.Lock() + now = now.Add(3 * time.Hour) + mu.Unlock() + deadline := time.Now().Add(5 * time.Second) + for { + if ok, _ := org.HasBlob(sum); !ok { + return + } + if time.Now().After(deadline) { + t.Fatal("file of an expired sandbox was never swept") + } + time.Sleep(10 * time.Millisecond) + } +} diff --git a/server/server.go b/server/server.go index adc7ed9..bcd796e 100644 --- a/server/server.go +++ b/server/server.go @@ -97,6 +97,11 @@ type Options struct { // request failed to authenticate (the client is told only that it did). // Defaults to slog.Default(). Logger *slog.Logger + // sandboxSweepEvery is how often the running server reclaims expired + // sandboxes and the unreferenced files they announced + // (api.SweepSandboxes). Defaults to defaultSandboxSweepEvery; tests + // shorten it. + sandboxSweepEvery time.Duration // Storage selects the persistence backend: "memory" (default, ephemeral) or // "sqlite" (durable). Ignored when Backend is set. Storage string @@ -198,8 +203,15 @@ func (o *Options) withDefaults() { if o.BodyTimeout == 0 { o.BodyTimeout = DefaultBodyTimeout } + if o.sandboxSweepEvery == 0 { + o.sandboxSweepEvery = defaultSandboxSweepEvery + } } +// defaultSandboxSweepEvery is how often a running server sweeps expired +// sandboxes, as bookshelf's cleanup task runs on a timer. +const defaultSandboxSweepEvery = 10 * time.Minute + // bootstrapUser validates the Bootstrap* options and returns the user to // create, or nil when none is configured. Called after withDefaults, so // AdminName is set. @@ -311,6 +323,10 @@ type Server struct { // onVerify, when set (by tests), is called each time authMiddleware // checks a request's signature. onVerify func() + // stopSweep ends the sandbox sweep Start runs; sweepDone closes when it + // has. Both are nil until Start. + stopSweep chan struct{} + sweepDone chan struct{} } // upgradeOrgACLs brings every org in st to erchef's org ACL policy (see @@ -757,18 +773,45 @@ func (s *Server) Start() error { } }() + s.stopSweep, s.sweepDone = make(chan struct{}), make(chan struct{}) + go s.sweepSandboxes() + // Warm the serving path so the first real client request is not the one that // pays for cold connection handling, code paths, pools, and GC heap growth. s.prewarm() return nil } +// sweepSandboxes reclaims expired sandboxes and the files only they named, +// every Options.sandboxSweepEvery until Stop. A failed sweep is logged and +// retried on the next tick. +func (s *Server) sweepSandboxes() { + defer close(s.sweepDone) + tick := time.NewTicker(s.opts.sandboxSweepEvery) + defer tick.Stop() + for { + select { + case <-s.stopSweep: + return + case <-tick.C: + if err := s.api.SweepSandboxes(); err != nil { + s.opts.Logger.Warn("sandbox sweep failed", "error", err) + } + } + } +} + // Stop gracefully shuts the server down and releases the store backend (e.g. // closes the SQLite handle). func (s *Server) Stop(ctx context.Context) error { if s.httpSrv == nil { return s.store.Close() } + if s.stopSweep != nil { + close(s.stopSweep) + <-s.sweepDone + s.stopSweep = nil + } err := s.httpSrv.Shutdown(ctx) if err != nil { // The deadline passed with requests still in flight: cut them off rather