carlos / platform Public

edge: record lock for running sweeps, pin a request's tree, previous first

claude pushed by paul@keymail.dev b4a8cbbacdb6c4e8be9d9ce277261d8807087bd8 parent 3fef5d6
6 files changed, +214 −47
  • internal/edge/static.go +22 −0
  • internal/edge/static_periodic_sweep_test.go +94 −22
  • internal/edge/static_recordlock_linux.go +26 −0
  • internal/edge/static_recordlock_other.go +13 −0
  • internal/edge/static_sweep_unix.go +25 −23
  • internal/edge/static_trees.go +34 −2

CI cancelled — superseded by a newer push — run details

diff --git a/internal/edge/static.go b/internal/edge/static.go
index 221c54b28..997e835ca 100644
--- a/internal/edge/static.go
+++ b/internal/edge/static.go
@@ -181,6 +181,7 @@ func newStaticHandler(rt registry.Route, store release.Store, pub ed25519.Public
func (s *staticSite) ServeHTTP(w http.ResponseWriter, r *http.Request) {
tree, err := s.currentDir(r.Context())
+ defer tree.release()
if err != nil {
// Nothing has ever resolved here, so there is no version to name:
// this 502 stays unstamped rather than claiming a build it isn't
@@ -225,6 +226,15 @@ type servedTree struct {
dir, version string
redirects *redirectRules
headers *headerRules
+ // unpin ends the tree's hold against the sweep (staticTrees.pin).
+ unpin func()
+}
+
+// release ends the tree's hold against the sweep, once the request is done.
+func (t servedTree) release() {
+ if t.unpin != nil {
+ t.unpin()
+ }
}
// dir is where the tree named name lives once extracted.
@@ -256,9 +266,21 @@ func (s *staticSite) appDir() string {
// without the window in between, where a concurrent resolve could swap
// s.version and make the header describe a different tree than the one served).
// The tree's redirect rules come back with it for the same reason.
+//
+// The tree comes back pinned against the sweep, taken while mu is held so
+// it is one this handler still names; the caller releases it when done.
func (s *staticSite) currentDir(ctx context.Context) (servedTree, error) {
s.mu.Lock()
defer s.mu.Unlock()
+ tree, err := s.resolveLocked(ctx)
+ if err == nil {
+ tree.unpin = s.trees.pin(tree.dir)
+ }
+ return tree, err
+}
+
+// resolveLocked is currentDir's work. The caller holds mu.
+func (s *staticSite) resolveLocked(ctx context.Context) (servedTree, error) {
if s.version != "" && s.recheck > 0 && time.Since(s.checkedAt) < s.recheck {
// Inside the trust window: this request is answered from the cached
// version, and stamping that version is honest by construction — the
diff --git a/internal/edge/static_periodic_sweep_test.go b/internal/edge/static_periodic_sweep_test.go
index 7e667ec00..fff4e7c7f 100644
--- a/internal/edge/static_periodic_sweep_test.go
+++ b/internal/edge/static_periodic_sweep_test.go
@@ -95,24 +95,21 @@ func TestStaticPeriodicSweepSkipsAnAppMidResolve(t *testing.T) {
}
}
-// Another edge process using the cache holds its shared lock: the running
-// edge sweeps nothing. flock(2) drops a shared lock whose conversion to
-// exclusive fails, so the sweep must take it back: once the other process
-// lets go, no third process may take the cache exclusively.
-func TestStaticPeriodicSweepSkipsWhileAnotherEdgeServesAndKeepsItsLock(t *testing.T) {
+// Another edge using the cache (one that started beside this one) makes
+// the running edge sweep nothing. The refused attempt drops nothing either:
+// once the other edge has gone, no third may take the cache exclusively,
+// at start (flock) or for a running sweep (the record lock).
+func TestStaticPeriodicSweepSkipsWhileAnotherEdgeServesAndKeepsItsLocks(t *testing.T) {
cache := t.TempDir()
tr := openTrees(t, cache)
for _, v := range []string{"v1", "v2", "v3"} {
cacheTree(t, cache, "bab", "apt", tree(v))
}
pointAt(t, cache, "bab", "apt", tree("v3"))
- other, err := os.OpenFile(filepath.Join(cache, staticLockName), os.O_RDWR, 0o600)
- if err != nil {
- t.Fatal(err)
- }
- defer other.Close()
- if err := syscall.Flock(int(other.Fd()), syscall.LOCK_SH); err != nil {
- t.Fatal(err)
+ other, done := openStaticTrees(cache)
+ <-done
+ if other.periodic {
+ t.Fatal("an edge that started beside another may sweep while running")
}
tr.sweepOnce()
@@ -120,17 +117,69 @@ func TestStaticPeriodicSweepSkipsWhileAnotherEdgeServesAndKeepsItsLock(t *testin
if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 4 {
t.Errorf("bab/apt = %v, want everything kept while another edge serves", got)
}
- if err := syscall.Flock(int(other.Fd()), syscall.LOCK_UN); err != nil {
- t.Fatal(err)
- }
+ other.lock.Close()
probe, err := os.OpenFile(filepath.Join(cache, staticLockName), os.O_RDWR, 0o600)
if err != nil {
t.Fatal(err)
}
defer probe.Close()
if err := syscall.Flock(int(probe.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err == nil {
- t.Fatal("the running edge lost its shared lock after a refused sweep")
+ t.Fatal("the running edge lost its shared flock after a refused sweep")
+ }
+ if err := recordLock(probe, false, false); err == nil {
+ t.Fatal("the running edge lost its shared record lock after a refused sweep")
+ }
+ // With the other edge gone, the running one sweeps again.
+ tr.sweepOnce()
+ if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 3 {
+ t.Errorf("bab/apt = %v, want current + previous once the other edge has gone", got)
+ }
+}
+
+// A request holds the tree it was given until it is done: a handler that
+// swaps twice meanwhile no longer names it, and it is neither current nor
+// previous, but a sweep leaves it.
+func TestStaticPeriodicSweepKeepsATreeARequestHolds(t *testing.T) {
+ cache := t.TempDir()
+ tr := openTrees(t, cache)
+ for i, v := range []string{"v1", "v2", "v3"} {
+ cacheTree(t, cache, "bab", "apt", tree(v))
+ madeCurrentAt(t, cache, "bab", "apt", tree(v), time.Now().Add(time.Duration(i-10)*time.Minute))
+ }
+ pointAt(t, cache, "bab", "apt", tree("v3"))
+ release := tr.pin(filepath.Join(cache, "bab", "apt", tree("v1")))
+
+ tr.sweepOnce()
+ if got := entries(t, filepath.Join(cache, "bab", "apt")); len(got) != 4 {
+ t.Errorf("bab/apt = %v, want the held tree kept", got)
+ }
+ release()
+ tr.sweepOnce()
+ if got := joined(t, filepath.Join(cache, "bab", "apt")); got != "current|"+tree("v2")+"|"+tree("v3") {
+ t.Errorf("bab/apt = %v, want the tree swept once the request is done", got)
+ }
+}
+
+// The previous tree is chosen before the trees handlers serve are set
+// apart: a handler serving the previous tree keeps no third one.
+func TestStaticPeriodicSweepPreviousIsChosenFromEveryTree(t *testing.T) {
+ cache := t.TempDir()
+ tr := openTrees(t, cache)
+ for i, v := range []string{"v1", "v2", "v3"} {
+ cacheTree(t, cache, "bab", "apt", tree(v))
+ madeCurrentAt(t, cache, "bab", "apt", tree(v), time.Now().Add(time.Duration(i-10)*time.Minute))
}
+ pointAt(t, cache, "bab", "apt", tree("v3"))
+ beta := &staticSite{acct: "bab", app: "apt", cacheDir: cache}
+ beta.serving.Store(new(tree("v2")))
+ tr.register(beta)
+
+ tr.sweepOnce()
+
+ if got := joined(t, filepath.Join(cache, "bab", "apt")); got != "current|"+tree("v2")+"|"+tree("v3") {
+ t.Errorf("bab/apt = %v, want v1 swept", got)
+ }
+ runtime.KeepAlive(beta)
}
// The first lock-aware start may share the cache with an edge that takes no
@@ -177,10 +226,11 @@ func TestStaticTreesMeasureTheLargestKeptTree(t *testing.T) {
}
}
-// End to end through the serving handler: four releases promoted one after
+// End to end through the serving handler: releases promoted one after
// another leave the two newest on disk after a sweep, the site keeps
-// serving, every swap asks for a sweep, and a rollback to a swept release
-// extracts it again.
+// serving, every swap asks for a sweep, a request's tree outlives swaps
+// while it is answered, and a rollback to a swept release extracts it
+// again.
func TestStaticPeriodicSweepThroughTheHandler(t *testing.T) {
storeRoot := filepath.Join(t.TempDir(), "store")
store := release.NewDirStore(storeRoot)
@@ -215,6 +265,28 @@ func TestStaticPeriodicSweepThroughTheHandler(t *testing.T) {
time.Sleep(20 * time.Millisecond) // mtimes order the trees
}
+ // A request that took v4's tree is still being answered while v5 and v6
+ // ship and a sweep runs: its tree stays until it is done.
+ held, err := h.currentDir(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, v := range []string{"v5", "v6"} {
+ shipSite(t, store, "site", v, map[string]string{"index.html": "home " + v})
+ if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "stable", v); err != nil {
+ t.Fatalf("Promote %s: %v", v, err)
+ }
+ if code, body := getPath(t, srv.URL, "site.example.com", "/"); code != http.StatusOK || body != "home "+v {
+ t.Fatalf("GET / after %s = %d %q", v, code, body)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ tr.sweepOnce()
+ if _, err := os.Stat(filepath.Join(held.dir, "index.html")); err != nil {
+ t.Fatalf("a held tree was swept: %v", err)
+ }
+ held.release()
+
tr.sweepOnce()
appDir := filepath.Join(cache, h.acct, "site")
@@ -224,10 +296,10 @@ func TestStaticPeriodicSweepThroughTheHandler(t *testing.T) {
trees = append(trees, m[1])
}
}
- if got := strings.Join(trees, ","); got != "v3,v4" {
- t.Errorf("trees after the sweep = %s, want v3,v4", got)
+ if got := strings.Join(trees, ","); got != "v5,v6" {
+ t.Errorf("trees after the sweep = %s, want v5,v6", got)
}
- if code, body := getPath(t, srv.URL, "site.example.com", "/"); code != http.StatusOK || body != "home v4" {
+ if code, body := getPath(t, srv.URL, "site.example.com", "/"); code != http.StatusOK || body != "home v6" {
t.Fatalf("GET / after the sweep = %d %q", code, body)
}
if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "stable", "v1"); err != nil {
diff --git a/internal/edge/static_recordlock_linux.go b/internal/edge/static_recordlock_linux.go
new file mode 100644
index 000000000..7007114dc
--- /dev/null
+++ b/internal/edge/static_recordlock_linux.go
@@ -0,0 +1,26 @@
+//go:build linux
+
+package edge
+
+import (
+ "os"
+
+ "golang.org/x/sys/unix"
+)
+
+// recordLock sets this open file's record lock on the lock file's first
+// byte: shared or exclusive, waiting for it or not. An open-file-description
+// lock, unlike flock(2), changes mode in one step: a refused change leaves
+// the lock already held exactly as it was, so a running edge can ask
+// whether it is alone without ever letting go (staticTrees.sweepCache).
+func recordLock(f *os.File, shared, wait bool) error {
+ lk := unix.Flock_t{Type: unix.F_WRLCK, Whence: 0, Start: 0, Len: 1}
+ if shared {
+ lk.Type = unix.F_RDLCK
+ }
+ cmd := unix.F_OFD_SETLK
+ if wait {
+ cmd = unix.F_OFD_SETLKW
+ }
+ return unix.FcntlFlock(f.Fd(), cmd, &lk)
+}
diff --git a/internal/edge/static_recordlock_other.go b/internal/edge/static_recordlock_other.go
new file mode 100644
index 000000000..5dba378cc
--- /dev/null
+++ b/internal/edge/static_recordlock_other.go
@@ -0,0 +1,13 @@
+//go:build unix && !linux
+
+package edge
+
+import (
+ "errors"
+ "os"
+)
+
+// recordLock has no open-file-description locks to use here, so a running
+// edge never sweeps (static_recordlock_linux.go); the startup sweep still
+// runs.
+func recordLock(*os.File, bool, bool) error { return errors.ErrUnsupported }
diff --git a/internal/edge/static_sweep_unix.go b/internal/edge/static_sweep_unix.go
index 814804670..9114ec71c 100644
--- a/internal/edge/static_sweep_unix.go
+++ b/internal/edge/static_sweep_unix.go
@@ -23,9 +23,15 @@ import (
// too (staticTrees.run). Who may sweep is decided across processes by a
// lock:
// - Every running edge holds a shared flock on staticLockName for its
-// life. An edge sweeps only while it can hold it exclusively: at start,
-// and on each later sweep by converting its own shared hold, which it
-// takes back straight after.
+// life. A starting edge sweeps only if it can take it exclusively.
+// - A running edge cannot ask that again without letting go of its own
+// hold, which flock(2) does on a refused conversion (Astra review of
+// this change). So every edge also holds a shared record lock on the
+// file's first byte (recordLock, Linux only), taken before its startup
+// check, and a running sweep converts that one to exclusive, which
+// either succeeds or leaves the shared lock as it was. Only an edge
+// whose startup check found it alone sweeps while running: an edge from
+// before the record lock holds only the flock.
// - An edge from before the lock takes none, so the first edge to create
// the lock file never sweeps, at start or later: from the next start on,
// every edge using the cache is known to take the lock. That rests on the
@@ -39,7 +45,8 @@ import (
// keeps every tree a live handler serves and leaves alone an app directory
// a handler is choosing a tree in (begin). In each app it also keeps the
// tree current names and the previous one, the newest other tree by mtime,
-// which pointCurrent sets when a tree becomes current.
+// which pointCurrent sets when a tree becomes current, and every tree a
+// request is still being answered from (staticTrees.pin).
//
// Only entries the edge itself made are touched, recognised by name:
// release trees (<version>@<digest>, siteDirName), temp extractions
@@ -115,6 +122,9 @@ func openStaticTrees(cacheDir string) (*staticTrees, <-chan struct{}) {
if err != nil {
return fail(nil, err)
}
+ // Before the startup check, so a running edge's sweep sees this one
+ // from here on. It waits out a sweep in progress, which is brief.
+ recorded := recordLock(lock, true, true) == nil
fd := int(lock.Fd())
measured := func() (*staticTrees, <-chan struct{}) {
t.lock = lock
@@ -128,7 +138,6 @@ func openStaticTrees(cacheDir string) (*staticTrees, <-chan struct{}) {
}
return measured()
}
- t.periodic = true
if err := syscall.Flock(fd, syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
log.Printf("edge: static cache %s: another edge process serves from it; not swept this start", cacheDir)
if err := reshare(fd); err != nil {
@@ -136,6 +145,7 @@ func openStaticTrees(cacheDir string) (*staticTrees, <-chan struct{}) {
}
return measured()
}
+ t.periodic = recorded
doomed := t.setAside()
if err := reshare(fd); err != nil {
return fail(lock, err)
@@ -175,26 +185,20 @@ func removeAll(doomed []string) int {
return removed
}
-// sweepCache is a running edge's sweep: only while no other edge process
-// holds the lock, and never on the first lock-aware start. It reports how
-// many entries it removed.
+// sweepCache is a running edge's sweep: only while no other edge holds the
+// record lock, and only if this edge's startup check found it alone. It
+// reports how many entries it removed.
func (t *staticTrees) sweepCache() int {
if t.lock == nil || !t.periodic {
return 0
}
- fd := int(t.lock.Fd())
- if err := syscall.Flock(fd, syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
- // A refused conversion has dropped the shared hold (flock(2)):
- // take it back before anything else.
- log.Printf("edge: static cache %s: another edge process serves from it; not swept", t.cacheDir)
- if err := reshare(fd); err != nil {
- log.Printf("ALERT: edge: static cache %s: shared lock not taken back (%v): a second edge starting beside this one could sweep trees it serves", t.cacheDir, err)
- }
+ if err := recordLock(t.lock, false, false); err != nil {
+ log.Printf("edge: static cache %s: another edge process serves from it; not swept (%v)", t.cacheDir, err)
return 0
}
doomed := t.setAside()
- if err := reshare(fd); err != nil {
- log.Printf("ALERT: edge: static cache %s: shared lock not taken back (%v): a second edge starting beside this one could sweep trees it serves", t.cacheDir, err)
+ if err := recordLock(t.lock, true, false); err != nil {
+ log.Printf("ALERT: edge: static cache %s: record lock not made shared again (%v): no other edge can start a sweep check until this one exits", t.cacheDir, err)
}
return removeAll(doomed)
}
@@ -238,9 +242,7 @@ func (t *staticTrees) setAsideAppLocked(appDir string, stamp int64) []string {
if busy {
return nil
}
- if cur, err := os.Readlink(filepath.Join(appDir, "current")); err == nil {
- keep[cur] = true
- }
+ cur, _ := os.Readlink(filepath.Join(appDir, "current"))
names, err := os.ReadDir(appDir)
if err != nil {
return nil
@@ -252,7 +254,7 @@ func (t *staticTrees) setAsideAppLocked(appDir string, stamp int64) []string {
name := n.Name()
path := filepath.Join(appDir, name)
fi, err := os.Lstat(path)
- if err != nil || !fi.IsDir() || keep[name] {
+ if err != nil || !fi.IsDir() || name == cur {
continue
}
switch classifyStaticEntry(name) {
@@ -266,7 +268,7 @@ func (t *staticTrees) setAsideAppLocked(appDir string, stamp int64) []string {
}
}
for _, name := range trees {
- if name == prev {
+ if name == prev || keep[name] {
continue
}
path := filepath.Join(appDir, name)
diff --git a/internal/edge/static_trees.go b/internal/edge/static_trees.go
index 10699f6ab..62da41eb3 100644
--- a/internal/edge/static_trees.go
+++ b/internal/edge/static_trees.go
@@ -42,6 +42,9 @@ type staticTrees struct {
// busy counts, per app directory, the handlers choosing a tree there
// (begin). The sweep leaves such a directory alone.
busy map[string]int
+ // pins counts, per tree path, the requests being answered from it
+ // (pin): a handler that has swapped since no longer names their tree.
+ pins map[string]int
// sizes caches each kept tree's byte count by path: a tree never changes
// once extracted.
sizes map[string]int64
@@ -62,6 +65,7 @@ func newStaticTrees(cacheDir string) *staticTrees {
return &staticTrees{
cacheDir: cacheDir,
busy: map[string]int{},
+ pins: map[string]int{},
sizes: map[string]int64{},
kick: make(chan struct{}, 1),
}
@@ -110,6 +114,28 @@ func (t *staticTrees) begin(appDir string) func() {
}
}
+// pin holds the tree at path out of every sweep until the returned func
+// is called. A handler pins while it holds its own lock, so the tree is
+// one it still names when the pin is taken.
+func (t *staticTrees) pin(path string) func() {
+ if t == nil {
+ return func() {}
+ }
+ t.mu.Lock()
+ t.pins[path]++
+ t.mu.Unlock()
+ var once sync.Once
+ return func() {
+ once.Do(func() {
+ t.mu.Lock()
+ if t.pins[path]--; t.pins[path] <= 0 {
+ delete(t.pins, path)
+ }
+ t.mu.Unlock()
+ })
+ }
+}
+
// swapped asks for a sweep: a handler has just moved to another tree.
func (t *staticTrees) swapped() {
if t == nil {
@@ -122,8 +148,9 @@ func (t *staticTrees) swapped() {
}
// keepLocked is what the sweep must leave in appDir besides current and
-// previous: every tree a live handler serves there. The caller holds mu, and
-// a busy directory is not swept at all.
+// previous: every tree a live handler serves there and every tree a request
+// is being answered from. The caller holds mu, and a busy directory is not
+// swept at all.
func (t *staticTrees) keepLocked(appDir string) (keep map[string]bool, busy bool) {
if t.busy[appDir] > 0 {
return nil, true
@@ -138,6 +165,11 @@ func (t *staticTrees) keepLocked(appDir string) (keep map[string]bool, busy bool
keep[*name] = true
}
}
+ for p := range t.pins {
+ if filepath.Dir(p) == appDir {
+ keep[filepath.Base(p)] = true
+ }
+ }
return keep, false
}