Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 3 additions & 0 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
155 changes: 155 additions & 0 deletions internal/api/blobref_race_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
36 changes: 36 additions & 0 deletions internal/api/blobrefs.go
Original file line number Diff line number Diff line change
@@ -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
}
21 changes: 9 additions & 12 deletions internal/api/cookbook_artifacts.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}
Expand Down
Loading