carlos / platform Public

instancectl: re-assert egress every 30 s and on POST /egress; report on GET /egress (#328)

EgressAsserter.Sweep asserts every populated per-host slice (cgroupfs
read only; the source reads no store). A slice it cannot name gets its
allow reset, only when it holds one. Loop names slices from Hosts once,
sweeps at once and then every DiskEvery (30 s). A host failing three
sweeps in a row is logged every sweep while it fails. POST /egress and
GET /egress are served with claims on too. RunWithRegistry and
RunWithClaim take the asserter; the host passes nil until Tasks 5 and 6.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 82236ad2558d54bba26d19ed2493f93419f6212b parent 4895e59
9 files changed, +703 −19
  • internal/host/claimstop_run.go +2 −2
  • internal/instancectl/claim.go +4 −2
  • internal/instancectl/client.go +16 −0
  • internal/instancectl/client_test.go +38 −0
  • internal/instancectl/egress.go +209 −11
  • internal/instancectl/egress_cgroup_linux.go +44 −0
  • internal/instancectl/egress_cgroup_other.go +11 −0
  • internal/instancectl/egress_test.go +340 −0
  • internal/instancectl/server.go +39 −4
diff --git a/internal/host/claimstop_run.go b/internal/host/claimstop_run.go
index ed8b38c33..7a7e07ff5 100644
--- a/internal/host/claimstop_run.go
+++ b/internal/host/claimstop_run.go
@@ -33,7 +33,7 @@ func RunInstanceControl(args []string) {
log.Fatal(err)
}
if !hostwrite.Enabled(claimEntryEnv(ctx)) {
- instancectl.RunWithRegistry(args, instanceRegistryHostApp(nil))
+ instancectl.RunWithRegistry(args, instanceRegistryHostApp(nil), nil)
return
}
reg, err := openServiceRegistry(filepath.Join(dataDir(), "registry.db"))
@@ -84,7 +84,7 @@ func RunInstanceControl(args []string) {
fenceDone := make(chan struct{})
go func() { defer close(fenceDone); runHostFencePass(ctx) }()
defer func() { cancel(); <-fenceDone }()
- instancectl.RunWithClaim(args, handler, heldReleaseRouteHandler(handler, claimEntryEnv(ctx)), rootInstallationHostApp(entry.Assembly.Guard, entry.Assembly.Claims))
+ instancectl.RunWithClaim(args, handler, heldReleaseRouteHandler(handler, claimEntryEnv(ctx)), rootInstallationHostApp(entry.Assembly.Guard, entry.Assembly.Claims), nil)
}
func activateClaimRoot(ctx, startup context.Context, handler http.Handler) error {
diff --git a/internal/instancectl/claim.go b/internal/instancectl/claim.go
index bd829c6b9..57db7e56e 100644
--- a/internal/instancectl/claim.go
+++ b/internal/instancectl/claim.go
@@ -19,6 +19,8 @@ func requestConnContext(ctx context.Context, c net.Conn) context.Context {
// RunWithClaim serves the claim verbs through handler and, when
// heldRelease is not nil, the moves held-release route through it (the
// host passes it only with both flags on; nil leaves the route absent).
-func RunWithClaim(args []string, handler, heldRelease http.Handler, hostApp func(string) (string, string, error)) {
- runWithClaim(args, handler, heldRelease, hostApp)
+// egress is as for RunWithRegistry; under claims its source writes no
+// allow (ruling 9).
+func RunWithClaim(args []string, handler, heldRelease http.Handler, hostApp func(string) (string, string, error), egress *EgressAsserter) {
+ runWithClaim(args, handler, heldRelease, hostApp, egress)
}
diff --git a/internal/instancectl/client.go b/internal/instancectl/client.go
index 5b233fbf0..69d92e313 100644
--- a/internal/instancectl/client.go
+++ b/internal/instancectl/client.go
@@ -346,3 +346,19 @@ func (c *Client) Ready(ctx context.Context) error {
}
return nil
}
+
+// Egress asks root to re-assert host's egress allow now (#328), after
+// the agent changed the host's registry column. The request names only
+// the host: root reads the addresses from its own source. A 502 carries
+// root's error.
+func (c *Client) Egress(ctx context.Context, host string) error {
+ _, _, err := c.do(ctx, DeadlineControl, http.MethodPost, "/egress", url.Values{"host": {host}}, nil)
+ return err
+}
+
+// EgressStatus reads every host's last egress report from root.
+func (c *Client) EgressStatus(ctx context.Context) (EgressStatus, error) {
+ var out EgressStatus
+ _, _, err := c.do(ctx, DeadlineReady, http.MethodGet, "/egress", nil, &out)
+ return out, err
+}
diff --git a/internal/instancectl/client_test.go b/internal/instancectl/client_test.go
index a02f4e140..4837bd699 100644
--- a/internal/instancectl/client_test.go
+++ b/internal/instancectl/client_test.go
@@ -158,3 +158,41 @@ func TestClientReadyRefusesAControlServiceOfAnotherBuild(t *testing.T) {
t.Fatal("NewClient left Build empty; production would never check")
}
}
+
+func TestClientEgressVerbs(t *testing.T) {
+ ectl := newEgressCtl()
+ e := newEgressAsserter(ectl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20"}}, nil))
+ _, c := newClient(t, &fakeCtl{}, func(s *Server) { s.Egress = e })
+ ctx := context.Background()
+
+ st, err := c.EgressStatus(ctx)
+ if err != nil || st.Hosts == nil || len(st.Hosts) != 0 {
+ t.Fatalf("EgressStatus before any assert = %+v, %v", st, err)
+ }
+ if err := c.Egress(ctx, "shop-a.example.com"); err != nil {
+ t.Fatalf("Egress: %v", err)
+ }
+ if got := ectl.sets(); len(got) != 1 || !strings.HasSuffix(got[0], "IPAddressAllow=10.0.5.20/32") {
+ t.Fatalf("set-property calls = %q", got)
+ }
+ st, err = c.EgressStatus(ctx)
+ if err != nil {
+ t.Fatalf("EgressStatus: %v", err)
+ }
+ if got := st.Hosts["shop-a.example.com"]; len(got.Allowed) != 1 || got.Allowed[0] != "10.0.5.20" || got.State != "" {
+ t.Fatalf("EgressStatus = %+v", st)
+ }
+
+ if err := c.Egress(ctx, "../x"); err == nil || !strings.Contains(err.Error(), "400") {
+ t.Fatalf("Egress(bad host) = %v, want a 400", err)
+ }
+ ectl.ignore = true
+ ectl.setHeld(SliceName("shop-a.example.com"), "")
+ if err := c.Egress(ctx, "shop-a.example.com"); err == nil || !strings.Contains(err.Error(), "502") {
+ t.Fatalf("Egress(write does not hold) = %v, want a 502", err)
+ }
+ st, err = c.EgressStatus(ctx)
+ if err != nil || st.Hosts["shop-a.example.com"].State != EgressFailing {
+ t.Fatalf("EgressStatus after a failed write = %+v, %v", st, err)
+ }
+}
diff --git a/internal/instancectl/egress.go b/internal/instancectl/egress.go
index d0eacb674..048fc188d 100644
--- a/internal/instancectl/egress.go
+++ b/internal/instancectl/egress.go
@@ -27,6 +27,7 @@ import (
"slices"
"strings"
"sync"
+ "time"
"github.com/carlosframework/platform/internal/egressaddr"
"github.com/carlosframework/platform/internal/provision"
@@ -73,17 +74,30 @@ type EgressAsserter struct {
Systemctl func(context.Context, ...string) (string, error)
Source EgressSource
LocalAddrs func() ([]netip.Prefix, error)
- CgroupRoot string // Task 4's sweep
- Hosts func() ([]string, error) // Task 4: names for slices at start
+ CgroupRoot string // /sys/fs/cgroup; Sweep lists the populated host slices under it
+ Hosts func() ([]string, error) // names for slices, read once when Loop starts
Logf func(string, ...any)
mu sync.Mutex
last map[string]EgressPolicy // host -> the last policy Source read
reports map[string]EgressReport // host -> its last read-back
- names map[string]string // instance id -> host, for the sweep
- busy map[string]*sync.Mutex // host -> held for one whole Assert
+ names map[string]string // instance id -> host, for the sweep; "" is two hosts
+ busy map[string]*sync.Mutex // slice -> held for one whole Assert or reset
+ failing map[string]int // host -> sweeps in a row its Assert failed
}
+// EgressStatus is GET /egress's answer: every host's last report.
+type EgressStatus struct {
+ Hosts map[string]EgressReport `json:"hosts"`
+}
+
+// hostSlicePrefix starts every per-host slice's name (SliceName).
+const hostSlicePrefix = "carlos-instances-"
+
+// egressFailingSweeps is how many sweeps in a row a host's Assert fails
+// before every further failing sweep logs the streak.
+const egressFailingSweeps = 3
+
// Assert brings host's slice to its policy and records the report. It
// returns an error only when the slice could not be read or written, or
// a write did not hold: a start path refuses the start on it. A read
@@ -99,7 +113,8 @@ func (e *EgressAsserter) Assert(ctx context.Context, host string) error {
if !provision.ValidHostShape(host) {
return fmt.Errorf("%q is not a host", host)
}
- unlock := e.lockHost(host)
+ slice := SliceName(host)
+ unlock := e.lockSlice(slice)
defer unlock()
var rep EgressReport
@@ -131,7 +146,6 @@ func (e *EgressAsserter) Assert(ctx context.Context, host string) error {
}
}
- slice := SliceName(host)
held, readErr := e.readBack(ctx, slice)
if readErr == nil {
// The last successful read-back stands in the report until a
@@ -378,17 +392,19 @@ func (e *EgressAsserter) localAddrs() ([]netip.Prefix, error) {
return e.LocalAddrs()
}
-// lockHost serialises Asserts of one host, the source read included, so
-// the last write is always from the last read.
-func (e *EgressAsserter) lockHost(host string) func() {
+// lockSlice serialises Asserts of one host, the source read included, so
+// the last write is always from the last read. It is keyed by the slice,
+// not the host, so the sweep's reset of a slice it cannot name waits for
+// an Assert of that slice's host and sees the name that Assert recorded.
+func (e *EgressAsserter) lockSlice(slice string) func() {
e.mu.Lock()
if e.busy == nil {
e.busy = map[string]*sync.Mutex{}
}
- m := e.busy[host]
+ m := e.busy[slice]
if m == nil {
m = &sync.Mutex{}
- e.busy[host] = m
+ e.busy[slice] = m
}
e.mu.Unlock()
m.Lock()
@@ -417,12 +433,194 @@ func (e *EgressAsserter) record(host string, r EgressReport) {
defer e.mu.Unlock()
if e.reports == nil {
e.reports = map[string]EgressReport{}
+ }
+ if e.names == nil { // seedNames may have made it already
e.names = map[string]string{}
}
e.reports[host] = r
e.names[provision.InstanceID(host)] = host
}
+// Loop names slices from Hosts once (an error is logged, and the sweep
+// goes on with the names Assert records), sweeps at once, then sweeps
+// every `every` until ctx is done. Production's `every` is 30 s.
+func (e *EgressAsserter) Loop(ctx context.Context, every time.Duration) {
+ if e == nil {
+ return
+ }
+ e.seedNames()
+ e.Sweep(ctx)
+ if every <= 0 {
+ return
+ }
+ t := time.NewTicker(every)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ e.Sweep(ctx)
+ }
+ }
+}
+
+// seedNames records a host for each instance id Hosts lists. Two hosts
+// with one id are a conflict, never the same host: that id stays
+// unnamed until an Assert names it.
+func (e *EgressAsserter) seedNames() {
+ if e.Hosts == nil {
+ return
+ }
+ hosts, err := e.Hosts()
+ if err != nil {
+ e.logf("egress: naming slices: %v", err)
+ }
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ if e.names == nil {
+ e.names = map[string]string{}
+ }
+ seen := map[string]string{}
+ for _, h := range hosts {
+ if !provision.ValidHostShape(h) {
+ continue
+ }
+ id := provision.InstanceID(h)
+ if prev, ok := seen[id]; ok && prev != h {
+ seen[id] = ""
+ continue
+ }
+ seen[id] = h
+ }
+ for id, h := range seen {
+ if _, known := e.names[id]; !known {
+ e.names[id] = h
+ }
+ }
+}
+
+// Sweep asserts every populated per-host slice once. A slice is named
+// by its instance id: a host Assert or Hosts recorded for it, or, for an
+// id that is not hashed, the id itself. A slice it cannot name is
+// closed. It reads cgroupfs and asks Source, which reads no store.
+func (e *EgressAsserter) Sweep(ctx context.Context) {
+ if e == nil {
+ return
+ }
+ if e.CgroupRoot == "" {
+ e.logf("egress: sweep: no cgroup root")
+ return
+ }
+ populated, err := populatedHostSlices(e.CgroupRoot)
+ if err != nil {
+ e.logf("egress: sweep: %v", err)
+ return
+ }
+ swept := map[string]bool{}
+ for _, slice := range populated {
+ if ctx.Err() != nil {
+ return
+ }
+ host, ok := e.hostOf(slice)
+ if !ok {
+ if host, ok = e.closeUnnamed(ctx, slice); !ok {
+ continue
+ }
+ }
+ swept[host] = true
+ e.noteSweep(host, e.Assert(ctx, host))
+ }
+ e.mu.Lock()
+ for h := range e.failing {
+ if !swept[h] {
+ delete(e.failing, h)
+ }
+ }
+ e.mu.Unlock()
+}
+
+// hostOf names a slice, or reports false. The name must give the slice
+// back through SliceName, so an Assert of it acts on this slice.
+func (e *EgressAsserter) hostOf(slice string) (string, bool) {
+ esc, ok := strings.CutPrefix(slice, hostSlicePrefix)
+ if !ok {
+ return "", false
+ }
+ if esc, ok = strings.CutSuffix(esc, ".slice"); !ok {
+ return "", false
+ }
+ id, ok := Unescape(esc)
+ if !ok {
+ return "", false
+ }
+ e.mu.Lock()
+ host, known := e.names[id]
+ e.mu.Unlock()
+ if !known && !strings.HasPrefix(id, "_") {
+ host = id
+ }
+ if host == "" || !provision.ValidHostShape(host) || SliceName(host) != slice {
+ return "", false
+ }
+ return host, true
+}
+
+// closeUnnamed resets the allow of a slice no host is known for, and
+// only when it holds something: an allow is never left open on a guess,
+// and a slice holding nothing is never written. It holds the slice's
+// lock and names it again first, so an Assert that just named it wins:
+// then it returns that host for the sweep to assert.
+func (e *EgressAsserter) closeUnnamed(ctx context.Context, slice string) (string, bool) {
+ unlock := e.lockSlice(slice)
+ defer unlock()
+ if host, ok := e.hostOf(slice); ok {
+ return host, true
+ }
+ held, err := e.readBack(ctx, slice)
+ if err != nil {
+ e.logf("egress: %s: no host for this slice; read back: %v; nothing written", slice, err)
+ return "", false
+ }
+ if held.equal(nil) {
+ return "", false
+ }
+ if out, err := e.Systemctl(ctx, "set-property", "--runtime", slice, "IPAddressAllow="); err != nil {
+ e.logf("egress: %s: no host for this slice; closing its allow: set-property: %s: %v", slice, strings.TrimSpace(out), err)
+ return "", false
+ }
+ held, err = e.readBack(ctx, slice)
+ switch {
+ case err != nil:
+ e.logf("egress: %s: no host for this slice; read back after closing its allow: %v", slice, err)
+ case !held.equal(nil):
+ e.logf("egress: %s: no host for this slice; after closing its allow the slice holds %s", slice, held.text())
+ default:
+ e.logf("egress: %s: no host for this slice; its allow is closed", slice)
+ }
+ return "", false
+}
+
+// noteSweep counts a host's failing sweeps in a row and logs the streak
+// on every sweep from the third.
+func (e *EgressAsserter) noteSweep(host string, err error) {
+ e.mu.Lock()
+ if e.failing == nil {
+ e.failing = map[string]int{}
+ }
+ if err == nil {
+ delete(e.failing, host)
+ e.mu.Unlock()
+ return
+ }
+ e.failing[host]++
+ n := e.failing[host]
+ e.mu.Unlock()
+ if n >= egressFailingSweeps {
+ e.logf("egress: %s: failing for %d sweeps in a row: %v", host, n, err)
+ }
+}
+
func (e *EgressAsserter) logf(format string, args ...any) {
if e.Logf != nil {
e.Logf(format, args...)
diff --git a/internal/instancectl/egress_cgroup_linux.go b/internal/instancectl/egress_cgroup_linux.go
new file mode 100644
index 000000000..ebd13a7e2
--- /dev/null
+++ b/internal/instancectl/egress_cgroup_linux.go
@@ -0,0 +1,44 @@
+//go:build linux
+
+package instancectl
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+)
+
+// populatedHostSlices lists the per-host slices under
+// carlos.slice/carlos-instances.slice whose cgroup.events says
+// "populated 1": the slices something runs in now. It reads cgroupfs
+// only. A slice whose events file is gone (it emptied between the list
+// and the read) is skipped; any other read error fails the whole list,
+// so a sweep never mistakes an unreadable tree for an empty one.
+func populatedHostSlices(cgroupRoot string) ([]string, error) {
+ parent := filepath.Join(cgroupRoot, parentSlices)
+ entries, err := os.ReadDir(parent)
+ if err != nil {
+ return nil, err
+ }
+ var out []string
+ for _, ent := range entries {
+ name := ent.Name()
+ if !ent.IsDir() || !strings.HasPrefix(name, hostSlicePrefix) || !strings.HasSuffix(name, ".slice") {
+ continue
+ }
+ b, err := os.ReadFile(filepath.Join(parent, name, "cgroup.events"))
+ if errors.Is(err, os.ErrNotExist) {
+ continue
+ }
+ if err != nil {
+ return nil, fmt.Errorf("%s: %w", name, err)
+ }
+ if slices.Contains(strings.Split(string(b), "\n"), "populated 1") {
+ out = append(out, name)
+ }
+ }
+ return out, nil
+}
diff --git a/internal/instancectl/egress_cgroup_other.go b/internal/instancectl/egress_cgroup_other.go
new file mode 100644
index 000000000..b744eb93f
--- /dev/null
+++ b/internal/instancectl/egress_cgroup_other.go
@@ -0,0 +1,11 @@
+//go:build !linux
+
+package instancectl
+
+import "errors"
+
+// populatedHostSlices reads cgroupfs, which only linux has; the control
+// service runs on linux alone.
+func populatedHostSlices(string) ([]string, error) {
+ return nil, errors.New("per-host slices are a linux cgroup feature")
+}
diff --git a/internal/instancectl/egress_test.go b/internal/instancectl/egress_test.go
index b21d1e0f0..15e7f77fb 100644
--- a/internal/instancectl/egress_test.go
+++ b/internal/instancectl/egress_test.go
@@ -2,13 +2,21 @@ package instancectl
import (
"context"
+ "encoding/json"
"errors"
+ "fmt"
+ "io"
+ "net/http"
"net/netip"
+ "os"
+ "path/filepath"
"reflect"
+ "slices"
"strconv"
"strings"
"sync"
"testing"
+ "time"
)
const egressHost = "shop-a.example.com"
@@ -504,3 +512,335 @@ func TestEgressRefusesABadHost(t *testing.T) {
}
wantCalls(t, ctl.takeCalls())
}
+
+// cgroupSlice writes a per-host slice's cgroup.events into a fixture tree
+// laid out as /sys/fs/cgroup is (server_test.go's CgroupRoot).
+func cgroupSlice(t *testing.T, root, slice string, populated bool) {
+ t.Helper()
+ dir := filepath.Join(root, "carlos.slice", "carlos-instances.slice", slice)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ ev := "populated 0\nfrozen 0\n"
+ if populated {
+ ev = "populated 1\nfrozen 0\n"
+ }
+ if err := os.WriteFile(filepath.Join(dir, "cgroup.events"), []byte(ev), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// longEgressHost is longer than provision.MaxInstanceID, so its slice is
+// named by a hashed instance id ("_shop-a-long-...-<hash>").
+const longEgressHost = "shop-a-long-name-for-an-instance.example.com"
+
+func TestEgressSweepAssertsEveryPopulatedSlice(t *testing.T) {
+ root := t.TempDir()
+ cgroupSlice(t, root, SliceName("shop-a.example.com"), true)
+ cgroupSlice(t, root, SliceName("shop-b.example.com"), true)
+ cgroupSlice(t, root, SliceName("shop-c.example.com"), false)
+ // The parent's own files and a non-slice child are not host slices.
+ if err := os.WriteFile(filepath.Join(root, "carlos.slice", "carlos-instances.slice", "cgroup.events"), []byte("populated 1\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ cgroupSlice(t, root, "carlos-instance-probe.service", true)
+
+ ctl := newEgressCtl()
+ var asked []string
+ var mu sync.Mutex
+ e := newEgressAsserter(ctl, func(_ context.Context, host string) (EgressPolicy, error) {
+ mu.Lock()
+ asked = append(asked, host)
+ mu.Unlock()
+ return EgressPolicy{Allow: []string{"10.0.5.20"}}, nil
+ })
+ e.CgroupRoot = root
+ e.Sweep(context.Background())
+
+ wantCalls(t, ctl.takeCalls(),
+ showCall("shop-a.example.com"), setCall("shop-a.example.com", "10.0.5.20/32"), showCall("shop-a.example.com"),
+ showCall("shop-b.example.com"), setCall("shop-b.example.com", "10.0.5.20/32"), showCall("shop-b.example.com"),
+ )
+ if want := []string{"shop-a.example.com", "shop-b.example.com"}; !reflect.DeepEqual(asked, want) {
+ t.Fatalf("source asked for %q, want %q", asked, want)
+ }
+ reps := e.Reports()
+ if len(reps) != 2 || reps["shop-c.example.com"].Allowed != nil {
+ t.Fatalf("reports = %+v, want shop-a and shop-b only", reps)
+ }
+
+ // A second sweep with nothing changed reads each back and writes nothing.
+ e.Sweep(context.Background())
+ wantCalls(t, ctl.takeCalls(), showCall("shop-a.example.com"), showCall("shop-b.example.com"))
+}
+
+func TestEgressSweepResetsAnUnattributableSlice(t *testing.T) {
+ slice := SliceName(longEgressHost)
+ if !strings.HasPrefix(slice, "carlos-instances-_shop") {
+ t.Fatalf("fixture: %s is not a hashed slice name", slice)
+ }
+ t.Run("holds an allow", func(t *testing.T) {
+ root := t.TempDir()
+ cgroupSlice(t, root, slice, true)
+ ctl := newEgressCtl()
+ ctl.setHeld(slice, "10.0.5.20/32")
+ var logs []string
+ e := newEgressAsserter(ctl, func(context.Context, string) (EgressPolicy, error) {
+ t.Error("the source was asked for a slice with no host")
+ return EgressPolicy{Allow: []string{"10.0.5.20"}}, nil
+ })
+ e.CgroupRoot = root
+ e.Logf = func(f string, a ...any) { logs = append(logs, fmt.Sprintf(f, a...)) }
+ e.Sweep(context.Background())
+ show := "show -p IPAddressAllow --value " + slice
+ wantCalls(t, ctl.takeCalls(), show, "set-property --runtime "+slice+" IPAddressAllow=", show)
+ want := "egress: " + slice + ": no host for this slice; its allow is closed"
+ if !slices.Contains(logs, want) {
+ t.Fatalf("logs = %q, want %q", logs, want)
+ }
+ if len(e.Reports()) != 0 {
+ t.Fatalf("reports = %+v, want none", e.Reports())
+ }
+ })
+ t.Run("holds nothing", func(t *testing.T) {
+ root := t.TempDir()
+ cgroupSlice(t, root, slice, true)
+ ctl := newEgressCtl()
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20"}}, nil))
+ e.CgroupRoot = root
+ e.Sweep(context.Background())
+ wantCalls(t, ctl.takeCalls(), "show -p IPAddressAllow --value "+slice)
+ })
+ t.Run("named once an assert has seen the host", func(t *testing.T) {
+ root := t.TempDir()
+ cgroupSlice(t, root, slice, true)
+ ctl := newEgressCtl()
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20"}}, nil))
+ e.CgroupRoot = root
+ mustAssert(t, e, longEgressHost)
+ ctl.takeCalls()
+ ctl.setHeld(slice, "")
+ e.Sweep(context.Background())
+ wantCalls(t, ctl.takeCalls(), showCall(longEgressHost), setCall(longEgressHost, "10.0.5.20/32"), showCall(longEgressHost))
+ })
+}
+
+func TestEgressLoopSeedsNamesFromHosts(t *testing.T) {
+ root := t.TempDir()
+ slice := SliceName(longEgressHost)
+ cgroupSlice(t, root, slice, true)
+ ctl := newEgressCtl()
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20"}}, nil))
+ e.CgroupRoot = root
+ e.Hosts = func() ([]string, error) { return []string{"other.example.com", longEgressHost}, nil }
+ written := make(chan struct{})
+ var once sync.Once
+ e.Systemctl = func(ctx context.Context, args ...string) (string, error) {
+ out, err := ctl.run(ctx, args...)
+ if args[0] == "show" && strings.Contains(out, "10.0.5.20") {
+ once.Do(func() { close(written) })
+ }
+ return out, err
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan struct{})
+ go func() { defer close(done); e.Loop(ctx, time.Hour) }()
+ select {
+ case <-written: // the first sweep, at once
+ case <-time.After(10 * time.Second):
+ cancel()
+ <-done
+ t.Fatalf("Loop's first sweep did not write the allow: %q", ctl.takeCalls())
+ }
+ cancel()
+ <-done
+ wantCalls(t, ctl.takeCalls(), showCall(longEgressHost), setCall(longEgressHost, "10.0.5.20/32"), showCall(longEgressHost))
+}
+
+func TestEgressLoopLogsAHostsError(t *testing.T) {
+ root := t.TempDir()
+ cgroupSlice(t, root, SliceName("shop-a.example.com"), true)
+ ctl := newEgressCtl()
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{}, nil))
+ e.CgroupRoot = root
+ e.Hosts = func() ([]string, error) { return nil, errors.New("registry: locked") }
+ var mu sync.Mutex
+ var logs []string
+ e.Logf = func(f string, a ...any) { mu.Lock(); logs = append(logs, fmt.Sprintf(f, a...)); mu.Unlock() }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ e.Loop(ctx, time.Hour) // returns: the context is done
+ mu.Lock()
+ defer mu.Unlock()
+ if !slices.ContainsFunc(logs, func(l string) bool { return strings.Contains(l, "registry: locked") }) {
+ t.Fatalf("logs = %q, want the Hosts error", logs)
+ }
+}
+
+func TestEgressSweepLogsAHostFailingThreeSweeps(t *testing.T) {
+ root := t.TempDir()
+ cgroupSlice(t, root, SliceName(egressHost), true)
+ ctl := newEgressCtl()
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20"}}, nil))
+ e.CgroupRoot = root
+ ctl.ignore = true // every write leaves the slice as it was: Assert fails
+ var logs []string
+ e.Logf = func(f string, a ...any) { logs = append(logs, fmt.Sprintf(f, a...)) }
+ streak := func() int {
+ n := 0
+ for _, l := range logs {
+ if strings.Contains(l, "sweeps in a row") {
+ n++
+ }
+ }
+ return n
+ }
+ for i, want := range []int{0, 0, 1, 2} {
+ e.Sweep(context.Background())
+ if got := streak(); got != want {
+ t.Fatalf("after sweep %d: %d streak lines, want %d: %q", i+1, got, want, logs)
+ }
+ }
+ if !slices.ContainsFunc(logs, func(l string) bool {
+ return strings.Contains(l, "egress: "+egressHost+": failing for 4 sweeps in a row")
+ }) {
+ t.Fatalf("logs = %q, want the fourth sweep's count", logs)
+ }
+ ctl.ignore = false
+ e.Sweep(context.Background()) // holds now
+ ctl.ignore = true
+ ctl.setHeld(SliceName(egressHost), "") // and fails again from here
+ logs = nil
+ e.Sweep(context.Background())
+ e.Sweep(context.Background())
+ if got := streak(); got != 0 {
+ t.Fatalf("a success did not restart the count: %q", logs)
+ }
+ if !slices.ContainsFunc(logs, func(l string) bool { return strings.Contains(l, "egress: "+SliceName(egressHost)+": after the write") }) {
+ t.Fatalf("the two sweeps after the success did not fail: %q", logs)
+ }
+}
+
+func TestPopulatedHostSlicesMissingTreeIsAnError(t *testing.T) {
+ if _, err := populatedHostSlices(filepath.Join(t.TempDir(), "absent")); err == nil {
+ t.Fatal("populatedHostSlices(absent) = nil error")
+ }
+}
+
+// egressServer serves a Server whose Egress writes through ctl.
+func egressServer(t *testing.T, ectl *egressCtl, src EgressSource, configure ...func(*Server)) (*fakeCtl, *http.Client) {
+ t.Helper()
+ ctl := &fakeCtl{}
+ e := newEgressAsserter(ectl, src)
+ _, c := newServer(t, ctl, append([]func(*Server){func(s *Server) { s.Egress = e }}, configure...)...)
+ return ctl, c
+}
+
+func getEgress(t *testing.T, c *http.Client) EgressStatus {
+ t.Helper()
+ resp, err := c.Get("http://unix/egress")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("GET /egress = %d", resp.StatusCode)
+ }
+ var st EgressStatus
+ if err := json.NewDecoder(resp.Body).Decode(&st); err != nil {
+ t.Fatal(err)
+ }
+ return st
+}
+
+func TestEgressRouteAsserts(t *testing.T) {
+ ectl := newEgressCtl()
+ _, c := egressServer(t, ectl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20"}}, nil))
+ if st := getEgress(t, c); st.Hosts == nil || len(st.Hosts) != 0 {
+ t.Fatalf("GET /egress before any assert = %+v, want an empty hosts object", st)
+ }
+ resp := post(t, c, "/egress?host="+egressHost)
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusNoContent {
+ t.Fatalf("POST /egress = %d, want 204", resp.StatusCode)
+ }
+ wantCalls(t, ectl.takeCalls(), showCall(egressHost), setCall(egressHost, "10.0.5.20/32"), showCall(egressHost))
+ st := getEgress(t, c)
+ if want := (EgressReport{Allowed: []string{"10.0.5.20"}}); !reflect.DeepEqual(st.Hosts[egressHost], want) {
+ t.Fatalf("GET /egress = %+v, want %s: %+v", st, egressHost, want)
+ }
+
+ // A write that does not hold is a 502 carrying the error, and the
+ // report says failing.
+ ectl.ignore = true
+ ectl.setHeld(SliceName(egressHost), "")
+ resp = post(t, c, "/egress?host="+egressHost)
+ body, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusBadGateway || !strings.Contains(string(body), SliceName(egressHost)) {
+ t.Fatalf("POST /egress = %d %q, want 502 naming the slice", resp.StatusCode, body)
+ }
+ if st := getEgress(t, c); st.Hosts[egressHost].State != EgressFailing {
+ t.Fatalf("GET /egress = %+v, want failing", st)
+ }
+}
+
+func TestEgressRouteRefusesABadHost(t *testing.T) {
+ ectl := newEgressCtl()
+ _, c := egressServer(t, ectl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20"}}, nil))
+ for _, q := range []string{"", "?host=", "?host=..%2Fx", "?host=a%20b.example.com", "?host=" + egressHost + "&gen=1", "?host=" + egressHost + "&exe=%2Fx"} {
+ resp := post(t, c, "/egress"+q)
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusBadRequest {
+ t.Errorf("POST /egress%s = %d, want 400", q, resp.StatusCode)
+ }
+ }
+ wantCalls(t, ectl.takeCalls())
+}
+
+func TestEgressRoutesServedWithClaimsOn(t *testing.T) {
+ ectl := newEgressCtl()
+ ctl, c := egressServer(t, ectl, staticSource(EgressPolicy{Closed: EgressUnderClaims, Detail: "deferred"}, nil), func(s *Server) {
+ s.ClaimStop = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusTeapot) })
+ })
+ ectl.setHeld(SliceName(egressHost), "10.0.5.20/32")
+ resp := post(t, c, "/egress?host="+egressHost)
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusNoContent {
+ t.Fatalf("POST /egress with claims on = %d, want 204", resp.StatusCode)
+ }
+ wantCalls(t, ectl.sets(), setCall(egressHost))
+ st := getEgress(t, c)
+ if want := (EgressReport{State: EgressUnderClaims, Detail: "deferred"}); !reflect.DeepEqual(st.Hosts[egressHost], want) {
+ t.Fatalf("GET /egress = %+v, want %+v", st, want)
+ }
+ resp = post(t, c, "/start?host="+egressHost+"&role=run&memory_max=536870912")
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusServiceUnavailable {
+ t.Fatalf("POST /start with claims on = %d, want 503", resp.StatusCode)
+ }
+ if ctl.joined() != "" {
+ t.Fatalf("the legacy start reached systemctl: %s", ctl.joined())
+ }
+}
+
+func TestEgressSeededNamesOutliveAnAssert(t *testing.T) {
+ root := t.TempDir()
+ slice := SliceName(longEgressHost)
+ cgroupSlice(t, root, slice, true)
+ ctl := newEgressCtl()
+ ctl.setHeld(slice, "10.0.5.20/32")
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20"}}, nil))
+ e.CgroupRoot = root
+ e.Hosts = func() ([]string, error) { return []string{longEgressHost}, nil }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ e.Loop(ctx, time.Hour) // names from Hosts; the sweep stops at the done context
+ mustAssert(t, e, egressHost)
+ ctl.takeCalls()
+ e.Sweep(context.Background())
+ wantCalls(t, ctl.takeCalls(), showCall(longEgressHost))
+ if _, ok := e.Reports()[longEgressHost]; !ok {
+ t.Fatalf("reports = %+v, want %s asserted by name", e.Reports(), longEgressHost)
+ }
+}
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go
index f692f20d7..0af174bb8 100644
--- a/internal/instancectl/server.go
+++ b/internal/instancectl/server.go
@@ -163,13 +163,17 @@ const (
)
// Run is `carlos instance-control`.
-func Run(args []string) { runWithClaim(args, nil, nil, nil) }
+func Run(args []string) { runWithClaim(args, nil, nil, nil, nil) }
-func RunWithRegistry(args []string, hostApp func(string) (string, string, error)) {
- runWithClaim(args, nil, nil, hostApp)
+// RunWithRegistry is Run with the registry's host lookup and the egress
+// asserter (#328): the start paths and POST /egress assert through it,
+// and its Loop re-asserts every populated host slice every 30 s. A nil
+// egress is off.
+func RunWithRegistry(args []string, hostApp func(string) (string, string, error), egress *EgressAsserter) {
+ runWithClaim(args, nil, nil, hostApp, egress)
}
-func runWithClaim(args []string, claim, heldRelease http.Handler, hostApp func(string) (string, string, error)) {
+func runWithClaim(args []string, claim, heldRelease http.Handler, hostApp func(string) (string, string, error), egress *EgressAsserter) {
fs := flag.NewFlagSet("instance-control", flag.ExitOnError)
fs.Usage = cliflag.Usage(fs, "usage: carlos instance-control (socket-activated by carlos-instance-control.socket)")
_ = fs.Parse(args)
@@ -205,6 +209,7 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, hostApp func(s
DiskEvery: 30 * time.Second,
Build: version.Build,
ExeCurrent: installedBinaryCurrent,
+ Egress: egress,
}
ln, activated, err := activatedListener()
if err != nil {
@@ -223,6 +228,7 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, hostApp func(s
s.InspectMountpoints(ctx)
go s.probeLoop(ctx)
go s.diskLoop(ctx)
+ go s.Egress.Loop(ctx, s.DiskEvery)
if err := s.Serve(ctx, ln); err != nil {
log.Fatalf("instance-control: %v", err)
}
@@ -335,9 +341,38 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("POST /cmd", s.claimAwareLegacy(s.handleCmd))
mux.HandleFunc("GET /cmd/{host}", s.claimAwareLegacy(s.handleCmdStatus))
mux.HandleFunc("GET /ready", s.handleReady)
+ // Egress is root's own state, not a legacy unit verb: served with
+ // host claims on too, where the asserter writes no allow (ruling 9).
+ mux.HandleFunc("POST /egress", s.handleEgress)
+ mux.HandleFunc("GET /egress", s.handleEgressStatus)
return mux
}
+// handleEgress re-asserts one host's slice now (the agent's nudge after
+// its registry column changed). The request carries only a host; every
+// address written comes from the egress source.
+func (s *Server) handleEgress(w http.ResponseWriter, r *http.Request) {
+ req, err := parseRequest(r, verbShape{})
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ if err := s.Egress.Assert(r.Context(), req.host); err != nil {
+ http.Error(w, err.Error(), http.StatusBadGateway)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// handleEgressStatus answers every host's last egress report.
+func (s *Server) handleEgressStatus(w http.ResponseWriter, _ *http.Request) {
+ st := EgressStatus{Hosts: s.Egress.Reports()}
+ if st.Hosts == nil {
+ st.Hosts = map[string]EgressReport{}
+ }
+ writeJSON(w, http.StatusOK, st)
+}
+
// request is the validated form of a verb's query: nothing else reaches a
// unit name.
type request struct {