carlos / platform Public

db forward task 13: carlos-dbread units, the db-reads loop armed dark, db-read-1 published while the probe passes

host_test.go's expectedUnits names the two new units (TestUnitsEmbedComplete
is the contract for the embed set; the plan did not list it).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 9f9b8fc295f7ccd6ebbd296ef031dc516caf29e3 parent bdbea70
11 files changed, +474 −11
  • internal/host/agent.go +6 −0
  • internal/host/dbreads.go +147 −0
  • internal/host/dbreads_linux.go +35 −0
  • internal/host/dbreads_other.go +17 −0
  • internal/host/dbreads_test.go +172 −0
  • internal/host/edgesfile.go +7 −2
  • internal/host/host_test.go +2 −0
  • internal/host/systemunits.go +11 −5
  • internal/host/systemunits_test.go +4 −4
  • internal/host/units/carlos-dbread.socket +18 −0
  • internal/host/units/carlos-dbread@.service +55 −0
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 3229da5c2..5bd766e61 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -610,6 +610,10 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// stopped a previous agent's leftover units, the cmd units
// among them.
armRunsPass(svc, reg, dd, rolloutSink)
+ // The db-reads loop (db region forward spec §7.1): armed
+ // only on a box that can serve; it takes nothing until a
+ // console asks.
+ armDBReads(*cfg)
},
Ready: func() {
close(started)
@@ -2818,6 +2822,8 @@ func fastConvergeLoop(reg *registry.Registry, svc *activator.Service, sd *schedu
mark("moves")
runRunsPass(ctx)
mark("runs")
+ // A serial move may be a forwarded db read: list the queue now.
+ nudgeDBReads()
// Folded once per pass and handed in, never re-read inside the
// loop: this leg runs on every serial bump (a seconds cadence),
// and the fold is a LoadBoxes plus a List plus one Get per edges
diff --git a/internal/host/dbreads.go b/internal/host/dbreads.go
new file mode 100644
index 000000000..85416a670
--- /dev/null
+++ b/internal/host/dbreads.go
@@ -0,0 +1,147 @@
+package host
+
+import (
+ "context"
+ "crypto/ed25519"
+ "log"
+ "os"
+ "slices"
+ "strconv"
+ "strings"
+ "sync/atomic"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/dbreads"
+ "github.com/carlosframework/platform/internal/hostwrite"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const (
+ dbReadSocketUnit = "carlos-dbread.socket"
+ dbReadSocketPath = "/run/carlos-dbread/worker.sock"
+ dbReadMaxBytesEnv = "CARLOS_DB_READ_MAX_BYTES"
+ dbReadsSwitchEnv = "CARLOS_DB_READS"
+)
+
+type dbReadsEnv struct {
+ region string
+ pub ed25519.PublicKey
+ maxRestored int64
+}
+
+// dbReadsSettings is the environment half of spec §7.1's conditions:
+// hibernation configured, CARLOS_REGION a region, CARLOS_RELEASE_PUBKEY
+// set, CARLOS_DB_READS not 0, CARLOS_HOST_CLAIM not set. The other half,
+// a running loop whose last probe passed, is the agent's. why is "" when
+// the loop may be armed.
+func dbReadsSettings(getenv func(string) string) (dbReadsEnv, string) {
+ switch {
+ case !hibernationConfigured(getenv):
+ return dbReadsEnv{}, "hibernation is not configured (CARLOS_HIBERNATE_BUCKET)"
+ case hostwrite.Enabled(getenv):
+ return dbReadsEnv{}, "CARLOS_HOST_CLAIM is set"
+ case strings.TrimSpace(getenv(dbReadsSwitchEnv)) == "0":
+ return dbReadsEnv{}, dbReadsSwitchEnv + " is 0"
+ }
+ region := strings.TrimSpace(getenv("CARLOS_REGION"))
+ if !dbreads.ValidRegion(region) {
+ return dbReadsEnv{}, "CARLOS_REGION is not a region"
+ }
+ pub, err := release.ParsePublicKey(getenv("CARLOS_RELEASE_PUBKEY"), "CARLOS_RELEASE_PUBKEY")
+ if err != nil {
+ return dbReadsEnv{}, err.Error()
+ }
+ env := dbReadsEnv{region: region, pub: pub, maxRestored: dbreads.DefaultMaxRestored}
+ if raw := strings.TrimSpace(getenv(dbReadMaxBytesEnv)); raw != "" {
+ n, err := strconv.ParseInt(raw, 10, 64)
+ if err != nil || n <= 0 {
+ return dbReadsEnv{}, dbReadMaxBytesEnv + " is not a whole number of bytes"
+ }
+ env.maxRestored = n
+ }
+ return env, ""
+}
+
+// armedDBReads is the armed loop; nil on a box that cannot serve.
+var armedDBReads atomic.Pointer[dbreads.Agent]
+
+// dbReadsNudge is the serial pass's word to the loop: list the queue now.
+var dbReadsNudge = make(chan struct{}, 1)
+
+// dbReadsDraining is the draining flag this box last published in its edges
+// file, which the edges loop stores on every pass. The agent reads the same
+// value the console's evidence rule reads, so the two never disagree (spec
+// §7.1). Nothing on main sets an edges file's Draining yet (region HA's
+// placer will); until then it is false.
+var dbReadsDraining atomic.Bool
+
+func nudgeDBReads() {
+ select {
+ case dbReadsNudge <- struct{}{}:
+ default:
+ }
+}
+
+// dbReadsCapable is whether this box publishes db-read-1: the loop is armed
+// and its last readiness probe passed (spec §7.1).
+func dbReadsCapable() bool {
+ a := armedDBReads.Load()
+ return a != nil && a.Capable()
+}
+
+// withDBReadCapability is caps with db-read-1 when capable; caps is not
+// modified.
+func withDBReadCapability(caps []string, capable bool) []string {
+ if !capable {
+ return caps
+ }
+ return append(slices.Clone(caps), dbreads.Capability)
+}
+
+// countDBReadUnits reads `systemctl list-units --plain --no-legend` output:
+// carlos-dbread@ units that are active, activating or deactivating. A
+// stopped unit's scratch is gone; any other state may still hold it.
+func countDBReadUnits(out string) int {
+ n := 0
+ for _, line := range strings.Split(out, "\n") {
+ f := strings.Fields(line)
+ if len(f) < 3 || !strings.HasPrefix(f[0], "carlos-dbread@") {
+ continue
+ }
+ switch f[2] {
+ case "active", "activating", "deactivating", "reloading", "refreshing":
+ n++
+ }
+ }
+ return n
+}
+
+// armDBReads arms the db-reads loop on a box that can serve (spec §7.1).
+// Thin, like armRunsPass: the behaviour is dbreads.Agent's, tested there.
+func armDBReads(hib activator.Config) {
+ env, why := dbReadsSettings(os.Getenv)
+ if why != "" {
+ log.Printf("agent: db reads not armed: %s", why)
+ return
+ }
+ ctx := context.Background()
+ store, err := openDeployStore(ctx)
+ if err != nil {
+ log.Printf("agent: db reads not armed: %v", err)
+ return
+ }
+ a := dbreads.NewAgent(dbreads.AgentConfig{
+ Store: store, Region: env.region, Box: BoxLabel(), Boot: newBootID(), Pub: env.pub,
+ HibernatePrefix: hib.Prefix,
+ OpenReplica: func(ctx context.Context, prefix string) (dbdoor.ReplicaReader, error) {
+ return lease.ReadReplicaClient(ctx, hib.Bucket, prefix, hib.Region)
+ },
+ DialWorker: dialDBReadWorker, Units: dbReadUnits, Free: varTmpFree,
+ MaxRestored: env.maxRestored, Logf: log.Printf, Draining: dbReadsDraining.Load,
+ })
+ armedDBReads.Store(a)
+ go a.Run(ctx, dbReadsNudge)
+ log.Printf("agent: db reads armed (region %s)", env.region)
+}
diff --git a/internal/host/dbreads_linux.go b/internal/host/dbreads_linux.go
new file mode 100644
index 000000000..e58f7c232
--- /dev/null
+++ b/internal/host/dbreads_linux.go
@@ -0,0 +1,35 @@
+//go:build linux
+
+package host
+
+import (
+ "context"
+ "net"
+ "os/exec"
+
+ "golang.org/x/sys/unix"
+)
+
+func dialDBReadWorker(ctx context.Context) (net.Conn, error) {
+ var d net.Dialer
+ return d.DialContext(ctx, "unix", dbReadSocketPath)
+}
+
+// dbReadUnits lists carlos-dbread@ units, readable without privilege.
+func dbReadUnits(ctx context.Context) (int, error) {
+ out, err := exec.CommandContext(ctx, "systemctl", "list-units", "--all", "--plain", "--no-legend", "--no-pager", "carlos-dbread@*.service").Output()
+ if err != nil {
+ return 0, err
+ }
+ return countDBReadUnits(string(out)), nil
+}
+
+// varTmpFree is the filesystem holding /var/tmp, where every worker's
+// private /var/tmp lives.
+func varTmpFree() (uint64, uint64, error) {
+ var st unix.Statfs_t
+ if err := unix.Statfs("/var/tmp", &st); err != nil {
+ return 0, 0, err
+ }
+ return st.Bavail * uint64(st.Bsize), st.Blocks * uint64(st.Bsize), nil
+}
diff --git a/internal/host/dbreads_other.go b/internal/host/dbreads_other.go
new file mode 100644
index 000000000..df54ef2b2
--- /dev/null
+++ b/internal/host/dbreads_other.go
@@ -0,0 +1,17 @@
+//go:build !linux
+
+package host
+
+import (
+ "context"
+ "errors"
+ "net"
+)
+
+var errDBReadsUnsupported = errors.New("db reads run only on Linux")
+
+func dialDBReadWorker(context.Context) (net.Conn, error) { return nil, errDBReadsUnsupported }
+
+func dbReadUnits(context.Context) (int, error) { return 0, errDBReadsUnsupported }
+
+func varTmpFree() (uint64, uint64, error) { return 0, 0, errDBReadsUnsupported }
diff --git a/internal/host/dbreads_test.go b/internal/host/dbreads_test.go
new file mode 100644
index 000000000..80f85314a
--- /dev/null
+++ b/internal/host/dbreads_test.go
@@ -0,0 +1,172 @@
+package host
+
+import (
+ "bufio"
+ "bytes"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/base64"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/dbreads"
+)
+
+func TestDBReadsSettingsAreSpec71(t *testing.T) {
+ t.Parallel()
+ pub, _, _ := ed25519.GenerateKey(rand.Reader)
+ good := map[string]string{
+ "CARLOS_HIBERNATE_BUCKET": "data-uk", "CARLOS_REGION": "uk",
+ "CARLOS_RELEASE_PUBKEY": base64.StdEncoding.EncodeToString(pub),
+ }
+ env := func(over map[string]string) func(string) string {
+ return func(k string) string {
+ if v, ok := over[k]; ok {
+ return v
+ }
+ return good[k]
+ }
+ }
+ got, why := dbReadsSettings(env(nil))
+ if why != "" || got.region != "uk" || got.maxRestored != dbreads.DefaultMaxRestored {
+ t.Fatalf("a capable box: %+v %q", got, why)
+ }
+ if got, why := dbReadsSettings(env(map[string]string{"CARLOS_DB_READ_MAX_BYTES": "1073741824"})); why != "" || got.maxRestored != 1<<30 {
+ t.Fatalf("the size cap: %+v %q", got, why)
+ }
+ for name, over := range map[string]map[string]string{
+ "no hibernation": {"CARLOS_HIBERNATE_BUCKET": ""},
+ "no region": {"CARLOS_REGION": ""},
+ "a fleet placement": {"CARLOS_REGION": "fleet/acme"},
+ "no release key": {"CARLOS_RELEASE_PUBKEY": ""},
+ "switched off": {"CARLOS_DB_READS": "0"},
+ "host claims": {"CARLOS_HOST_CLAIM": "1"},
+ "a cap that is not a number": {"CARLOS_DB_READ_MAX_BYTES": "2GB"},
+ } {
+ if _, why := dbReadsSettings(env(over)); why == "" {
+ t.Errorf("%s: armed", name)
+ }
+ }
+}
+
+func TestCountDBReadUnits(t *testing.T) {
+ t.Parallel()
+ out := strings.Join([]string{
+ "carlos-dbread@0-1234-999.service loaded active running carlos db-read worker",
+ "carlos-dbread@1-1235-999.service loaded activating start carlos db-read worker",
+ "carlos-dbread@2-1236-999.service loaded deactivating stop-sigterm carlos db-read worker",
+ "carlos-dbread@3-1237-999.service loaded failed failed carlos db-read worker",
+ "carlos-dbread@4-1238-999.service loaded inactive dead carlos db-read worker",
+ "",
+ }, "\n")
+ if n := countDBReadUnits(out); n != 3 {
+ t.Fatalf("counted %d units, want active, activating and deactivating: 3", n)
+ }
+}
+
+func TestWithDBReadCapability(t *testing.T) {
+ t.Parallel()
+ base := []string{"region-ha-1"}
+ if got := withDBReadCapability(base, false); !slices.Equal(got, base) {
+ t.Fatalf("incapable: %v", got)
+ }
+ if got := withDBReadCapability(base, true); !slices.Equal(got, []string{"region-ha-1", dbreads.Capability}) || len(base) != 1 {
+ t.Fatalf("capable: %v (base %v)", got, base)
+ }
+}
+
+func unitLines(t *testing.T, name string) []string {
+ t.Helper()
+ b, err := unitsFS.ReadFile("units/" + name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var lines []string
+ sc := bufio.NewScanner(bytes.NewReader(b))
+ for sc.Scan() {
+ if l := strings.TrimSpace(sc.Text()); l != "" && !strings.HasPrefix(l, "#") {
+ lines = append(lines, l)
+ }
+ }
+ return lines
+}
+
+// The sandbox is the unit file (spec §8.3): every line the spec names is
+// there, and nothing loosens it.
+func TestDBReadUnitsCarryTheSandbox(t *testing.T) {
+ t.Parallel()
+ sock := unitLines(t, "carlos-dbread.socket")
+ for _, want := range []string{"ListenStream=/run/carlos-dbread/worker.sock", "SocketUser=carlos", "SocketMode=0600", "Accept=yes", "MaxConnections=3"} {
+ if !slices.Contains(sock, want) {
+ t.Errorf("the socket lacks %q", want)
+ }
+ }
+ svc := unitLines(t, "carlos-dbread@.service")
+ for _, want := range []string{
+ "ExecStart=/opt/carlos/carlos system db-worker",
+ "StandardInput=socket", "StandardOutput=socket", "StandardError=journal",
+ "DynamicUser=yes", "PrivateNetwork=yes", "RestrictAddressFamilies=AF_UNIX",
+ "TemporaryFileSystem=/data:ro /var/lib:ro /opt/carlos:ro /run/carlos:ro",
+ "BindReadOnlyPaths=/opt/carlos/carlos",
+ "InaccessiblePaths=/etc/carlos -/run/carlos-control",
+ "PrivateTmp=yes", "MemoryMax=512M", "CPUQuota=100%", "TasksMax=16",
+ "LimitFSIZE=2147483648", "RuntimeMaxSec=20min",
+ "SystemCallFilter=@system-service", "NoNewPrivileges=yes", "CapabilityBoundingSet=", "ProtectProc=invisible",
+ "ProtectSystem=strict",
+ } {
+ if !slices.Contains(svc, want) {
+ t.Errorf("the service lacks %q", want)
+ }
+ }
+ for _, l := range svc {
+ for _, bad := range []string{"User=", "StandardOutput=file:", "IPAddressAllow=", "ReadWritePaths=", "AmbientCapabilities=CAP"} {
+ if strings.HasPrefix(l, bad) {
+ t.Errorf("the service loosens its sandbox: %q", l)
+ }
+ }
+ }
+}
+
+func TestEnsureSystemUnitsInstallsTheDBReadUnits(t *testing.T) {
+ t.Parallel()
+ etc := t.TempDir()
+ os.MkdirAll(filepath.Join(etc, "systemd", "system"), 0o755)
+ var calls []string
+ systemctl := func(args ...string) (string, error) {
+ calls = append(calls, strings.Join(args, " "))
+ return "", nil
+ }
+ probe := func(args ...string) (string, error) {
+ calls = append(calls, strings.Join(args, " "))
+ if args[0] == "is-active" {
+ return "inactive\n", systemctlExit(3)
+ }
+ return "disabled\n", systemctlExit(1)
+ }
+ ensureSystemUnits(etc, filepath.Join(t.TempDir(), "lock"), systemctl, probe, t.Logf)
+ for _, u := range []string{"carlos-dbread.socket", "carlos-dbread@.service"} {
+ got, err := os.ReadFile(filepath.Join(etc, "systemd", "system", u))
+ want, _ := unitsFS.ReadFile("units/" + u)
+ if err != nil || !bytes.Equal(got, want) {
+ t.Errorf("%s not installed as embedded: %v", u, err)
+ }
+ }
+ joined := strings.Join(calls, "\n")
+ for _, want := range []string{"is-active carlos-dbread.socket", "carlos-dbread.socket"} {
+ if !strings.Contains(joined, want) {
+ t.Errorf("calls lack %q:\n%s", want, joined)
+ }
+ }
+ // systemctlPlan starts every armed unit (sockets, paths, timers, mounts)
+ // in the order passed (bootstrap.go armedUnits), and the service
+ // template never.
+ if !strings.Contains(joined, "start carlos-system-update.path carlos-instance-control.socket carlos-dbread.socket") {
+ t.Errorf("the socket was not armed:\n%s", joined)
+ }
+ if strings.Contains(joined, "start carlos-dbread@") {
+ t.Fatal("a worker service was started")
+ }
+}
diff --git a/internal/host/edgesfile.go b/internal/host/edgesfile.go
index e30d70329..c51489b2f 100644
--- a/internal/host/edgesfile.go
+++ b/internal/host/edgesfile.go
@@ -841,7 +841,11 @@ func edgesFileLoop(reg *registry.Registry) {
Capabilities: edgesFileCapabilities(os.Getenv),
}
// The flag-derived capabilities; offline-move-1 joins them on each pass
- // once the moves worker is armed and capable.
+ // once the moves worker is armed and capable, and db-read-1 joins them
+ // on each pass while the armed db-reads loop's last readiness probe
+ // passed (db region forward spec §7.1). The db-reads agent's draining
+ // check reads the draining flag this file publishes, stored on each
+ // pass, so the box and the console's evidence rule read one value.
baseCaps := ident.Capabilities
dataDir := provisionTickConfig(os.Getenv).DataDir
optDir := release.OptDir()
@@ -887,7 +891,8 @@ func edgesFileLoop(reg *registry.Registry) {
if state.timed() {
eip = readPublicIP()
}
- ident.Capabilities = withOfflineCapability(baseCaps, armedOfflineCapable())
+ ident.Capabilities = withDBReadCapability(withOfflineCapability(baseCaps, armedOfflineCapable()), dbReadsCapable())
+ dbReadsDraining.Store(ident.Draining)
ident.Headroom = headroomFor(headroomCapabilities(ident.Capabilities), dataDir, reg)
ident = withMovesFields(ident, dataDir, optDir)
ident = withSeedsFields(ident, dataDir, optDir)
diff --git a/internal/host/host_test.go b/internal/host/host_test.go
index c269f4fee..e1154574e 100644
--- a/internal/host/host_test.go
+++ b/internal/host/host_test.go
@@ -37,6 +37,8 @@ var expectedUnits = []string{
"carlos-app@.service",
"carlos-app@.socket",
"carlos-config-sync.service",
+ "carlos-dbread.socket",
+ "carlos-dbread@.service",
"carlos-edge.service",
"carlos-hibernate-verify.service",
"carlos-hibernate-verify.timer",
diff --git a/internal/host/systemunits.go b/internal/host/systemunits.go
index 2f97f0098..bca16b8a5 100644
--- a/internal/host/systemunits.go
+++ b/internal/host/systemunits.go
@@ -19,7 +19,10 @@ const systemRecoverUnit = "carlos-system-recover.service"
// control channel at all.
const instanceControlSocket = "carlos-instance-control.socket"
-var systemUnitFiles = []string{"carlos-system-update.path", "carlos-system-update.service", systemRecoverUnit, instanceControlSocket, "carlos-instance-control.service"}
+// carlos-dbread.socket and its service template are the db-read worker's
+// (db region forward spec §8.3): installed and the socket armed here, the
+// template never started.
+var systemUnitFiles = []string{"carlos-system-update.path", "carlos-system-update.service", systemRecoverUnit, instanceControlSocket, "carlos-instance-control.service", dbReadSocketUnit, "carlos-dbread@.service"}
// ensureSystemUnits is the second belt of spec §7: a box the roll script
// forgot to arm is armed within the hour by the root adopt pass. It
@@ -77,6 +80,8 @@ func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...st
// path unit's: the same silent-systemctl-vs-unarmed-unit question, one
// more unit wide (design §5.2).
ctlActiveOut, ctlActiveErr := probe("is-active", instanceControlSocket)
+ // And the db-read worker's socket (db region forward spec §8.3).
+ dbrActiveOut, dbrActiveErr := probe("is-active", dbReadSocketUnit)
// The is-enabled error is dropped on purpose: its cases are the words
// parseIsEnabled reads, and "no such unit file" is a perfectly good
// "not enabled" on the box we are here to fix.
@@ -87,8 +92,9 @@ func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...st
// binary, or an exec that failed outright.
isActive := parseIsActive(active)
ctlActive := parseIsActive(ctlActiveOut)
- if isActive == nil || ctlActive == nil {
- logf("adopt: system units: systemctl said nothing; not touching the self-update units: %v / %v", activeErr, ctlActiveErr)
+ dbrActive := parseIsActive(dbrActiveOut)
+ if isActive == nil || ctlActive == nil || dbrActive == nil {
+ logf("adopt: system units: systemctl said nothing; not touching the self-update units: %v / %v / %v", activeErr, ctlActiveErr, dbrActiveErr)
return
}
isEnabled := parseIsEnabled(enabled)
@@ -109,7 +115,7 @@ func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...st
return
}
controlChanged := settingsErr == nil && (claimSettings.enabled || bytes.Contains(installed, []byte(claimControlEnvironment))) && (err != nil || !bytes.Equal(installed, claimUnitContent(claimControlUnit, control, claimSettings)))
- if !missing && !controlChanged && *isActive && isEnabled != nil && *isEnabled && *ctlActive {
+ if !missing && !controlChanged && *isActive && isEnabled != nil && *isEnabled && *ctlActive && *dbrActive {
return
}
if err := os.MkdirAll(unitDir, 0o755); err != nil {
@@ -132,7 +138,7 @@ func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...st
return
}
}
- for _, args := range systemctlPlan([]string{systemUpdatePathUnit, systemRecoverUnit, instanceControlSocket}) {
+ for _, args := range systemctlPlan([]string{systemUpdatePathUnit, systemRecoverUnit, instanceControlSocket, dbReadSocketUnit}) {
if _, err := systemctl(args...); err != nil {
logf("adopt: system units: systemctl %s: %v", strings.Join(args, " "), err)
return
diff --git a/internal/host/systemunits_test.go b/internal/host/systemunits_test.go
index eb003b870..770e07f1c 100644
--- a/internal/host/systemunits_test.go
+++ b/internal/host/systemunits_test.go
@@ -51,9 +51,9 @@ func TestEnsureSystemUnitsInstallsAndArmsWhatIsMissing(t *testing.T) {
if strings.Contains(joined, "start carlos-system-recover.service") || strings.Contains(joined, "start carlos-system-update.service") {
t.Fatal("a service was started")
}
- // All present and armed: no writes, no systemctl beyond the three checks
- // (is-active x2 — the self-update path unit and the control socket —
- // plus is-enabled).
+ // All present and armed: no writes, no systemctl beyond the four checks
+ // (is-active x3: the self-update path unit, the control socket and the
+ // db-read socket, plus is-enabled).
calls = nil
probe2 := func(args ...string) (string, error) {
calls = append(calls, strings.Join(args, " "))
@@ -66,7 +66,7 @@ func TestEnsureSystemUnitsInstallsAndArmsWhatIsMissing(t *testing.T) {
return "", nil
}
ensureSystemUnits(etc, lockPath, systemctl, probe2, t.Logf)
- if len(calls) != 3 {
+ if len(calls) != 4 {
t.Fatalf("an armed box got %v", calls)
}
}
diff --git a/internal/host/units/carlos-dbread.socket b/internal/host/units/carlos-dbread.socket
new file mode 100644
index 000000000..4bfb12f53
--- /dev/null
+++ b/internal/host/units/carlos-dbread.socket
@@ -0,0 +1,18 @@
+# The db-read worker's socket (db region forward spec §8.3). Bound by root
+# systemd and owned by carlos, so the agent connects with no privilege of
+# its own. Each connection starts one carlos-dbread@ instance with the
+# connection as its stdin and stdout. Three connections at most: two reads
+# and the readiness probe (spec §7.1).
+[Unit]
+Description=carlos db-read worker socket
+
+[Socket]
+ListenStream=/run/carlos-dbread/worker.sock
+SocketUser=carlos
+SocketGroup=carlos
+SocketMode=0600
+Accept=yes
+MaxConnections=3
+
+[Install]
+WantedBy=sockets.target
diff --git a/internal/host/units/carlos-dbread@.service b/internal/host/units/carlos-dbread@.service
new file mode 100644
index 000000000..03284ae8a
--- /dev/null
+++ b/internal/host/units/carlos-dbread@.service
@@ -0,0 +1,55 @@
+# The db-read worker (db region forward spec §8.3): one instance per
+# connection to carlos-dbread.socket. It writes one forwarded read's planned
+# LTX files into its own private /var/tmp, restores them, checks the copy,
+# and runs the member's one read-only statement. Everything that decodes
+# tenant bytes runs here, as a DynamicUser with no network; the agent only
+# moves bytes. systemd removes /tmp and /var/tmp when the unit stops,
+# however it stops.
+#
+# StandardInput/StandardOutput=socket: with Accept=yes systemd passes the
+# connection as a descriptor and puts it on stdin only when told to. The
+# claim-bound template's StandardOutput=file: line is deliberately absent.
+#
+# LimitFSIZE is the default restored-size cap (CARLOS_DB_READ_MAX_BYTES,
+# 2 GiB). A box that raises the cap needs a drop-in raising this too.
+[Unit]
+Description=carlos db-read worker
+
+[Service]
+ExecStart=/opt/carlos/carlos system db-worker
+StandardInput=socket
+StandardOutput=socket
+StandardError=journal
+DynamicUser=yes
+PrivateNetwork=yes
+RestrictAddressFamilies=AF_UNIX
+TemporaryFileSystem=/data:ro /var/lib:ro /opt/carlos:ro /run/carlos:ro
+BindReadOnlyPaths=/opt/carlos/carlos
+InaccessiblePaths=/etc/carlos -/run/carlos-control
+PrivateTmp=yes
+ProtectSystem=strict
+ProtectHome=yes
+PrivateDevices=yes
+ProtectProc=invisible
+ProcSubset=pid
+ProtectKernelTunables=yes
+ProtectKernelModules=yes
+ProtectKernelLogs=yes
+ProtectClock=yes
+ProtectHostname=yes
+ProtectControlGroups=yes
+RemoveIPC=yes
+LockPersonality=yes
+RestrictRealtime=yes
+RestrictNamespaces=yes
+RestrictSUIDSGID=yes
+NoNewPrivileges=yes
+CapabilityBoundingSet=
+SystemCallFilter=@system-service
+SystemCallArchitectures=native
+MemoryDenyWriteExecute=yes
+MemoryMax=512M
+CPUQuota=100%
+TasksMax=16
+LimitFSIZE=2147483648
+RuntimeMaxSec=20min