feat(daemon): run a Kit profile's task in its Kit container on the egress path

This commit is contained in:
sam committed 2026-09-26 10:14:33 +10:00
1 parent 25f2299225
commit 70df8d1131
17 files changed
+734 -42

No files matched your search

+4
View File
@@ -40,6 +40,10 @@ type CA struct {
leaves map[string]*tls.Certificate
}
// CACertPath is where LoadOrCreateCA keeps the CA certificate in dir, the
// file a sandbox container mounts to trust the proxy.
func CACertPath(dir string) string { return filepath.Join(dir, caCertFile) }
// LoadOrCreateCA loads the CA from dir, creating it on first use. A CA that
// exists but will not load is an error: minting a replacement silently
// would break trust in every running container.
+10 -1
View File
@@ -129,10 +129,19 @@ func Admit(d *spec.Descriptor) (*Plan, error) {
// admits the result. archie drives a harness headlessly, so the composition
// must carry an agent-sessions prompt verb.
func Compose(contributions []spec.Contribution) (*Plan, error) {
merged, err := spec.Merge(contributions, spec.MergeOptions{ContextPath: contextPath})
merged, err := spec.Merge(contributions, MergeOptions)
if err != nil {
return nil, err
}
return FromMerge(merged)
}
// MergeOptions are the options every composition archie runs is merged with.
var MergeOptions = spec.MergeOptions{ContextPath: contextPath}
// FromMerge admits an already-merged composition, such as one the Kit spec's
// fetch package assembled from a registry.
func FromMerge(merged *spec.MergeResult) (*Plan, error) {
if merged.Descriptor.Kind != spec.KindWorkload {
return nil, errors.New("kit composition has no workload: a harness needs exactly one base kit")
}
+72
View File
@@ -0,0 +1,72 @@
package kitrun
import (
"fmt"
"net"
"net/url"
"strconv"
"strings"
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
)
// Endpoints are the host-reachable addresses a Kit task's worker needs,
// with the task's own credentials for them.
type Endpoints struct {
NATS string
NATSToken string
StateStore string
StateStoreToken string
}
// WorkerEnv is the worker's entire environment in a Kit container: NATS and
// the State Store at the relay's fixed ports, and the task's credentials.
// Nothing else crosses, so no model provider key enters the container.
func WorkerEnv(e Endpoints, uid, gid int) ([]string, error) {
u, err := url.Parse(e.NATS)
if err != nil || u.Scheme == "" {
return nil, fmt.Errorf("nats url %q: want scheme://host:port", e.NATS)
}
env := []string{"NATS_URL=" + u.Scheme + "://" + relayAddr(egress.RelayNATSPort)}
if e.NATSToken != "" {
env = append(env, "NATS_TOKEN="+e.NATSToken)
}
if e.StateStore != "" {
env = append(env, "STATE_STORE_URL="+relayAddr(egress.RelayStateStorePort))
if e.StateStoreToken != "" {
env = append(env, "STATE_STORE_TOKEN="+e.StateStoreToken)
}
}
return append(env, "WORKTREE_UID="+strconv.Itoa(uid), "WORKTREE_GID="+strconv.Itoa(gid)), nil
}
// relayTargets are the host:port addresses the relay forwards NATS and the
// State Store to.
func relayTargets(e Endpoints) (nats, stateStore string, err error) {
if strings.Contains(e.NATS, ",") {
return "", "", fmt.Errorf("nats url %q lists several servers; the relay forwards one", e.NATS)
}
u, err := url.Parse(e.NATS)
if err != nil || u.Host == "" {
return "", "", fmt.Errorf("nats url %q: want scheme://host:port", e.NATS)
}
stateStore = e.StateStore
if _, rest, ok := strings.Cut(stateStore, ":///"); ok {
stateStore = rest
}
return u.Host, stateStore, nil
}
func relayAddr(port int) string {
return net.JoinHostPort(egress.RelayAlias, strconv.Itoa(port))
}
// RelayCommand is the relay's archie-agent arguments, forwarding its fixed
// ports to the proxy and to the daemon's NATS and State Store.
func RelayCommand(proxy string, e Endpoints) ([]string, error) {
nats, stateStore, err := relayTargets(e)
if err != nil {
return nil, err
}
return egress.RelayArgs(proxy, nats, stateStore), nil
}
@@ -0,0 +1,44 @@
package kitrun
import (
"slices"
"testing"
)
func TestWorkerEnvReachesNATSAndTheStateStoreThroughTheRelay(t *testing.T) {
got, err := WorkerEnv(Endpoints{
NATS: "nats://172.17.0.1:4222", NATSToken: "nt",
StateStore: "10.0.0.5:7443", StateStoreToken: "st",
}, 1001, 1002)
if err != nil {
t.Fatal(err)
}
want := []string{
"NATS_URL=nats://archie-egress:4222", "NATS_TOKEN=nt",
"STATE_STORE_URL=archie-egress:50051", "STATE_STORE_TOKEN=st",
"WORKTREE_UID=1001", "WORKTREE_GID=1002",
}
if !slices.Equal(got, want) {
t.Fatalf("WorkerEnv = %q\nwant %q", got, want)
}
}
func TestWorkerEnvWithoutAStateStoreOmitsIt(t *testing.T) {
got, err := WorkerEnv(Endpoints{NATS: "tls://nats.internal:4222"}, 0, 0)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(got, []string{"NATS_URL=tls://archie-egress:4222", "WORKTREE_UID=0", "WORKTREE_GID=0"}) {
t.Fatalf("WorkerEnv = %q", got)
}
}
func TestRelayTargets(t *testing.T) {
nats, store, err := relayTargets(Endpoints{NATS: "nats://172.17.0.1:4222", StateStore: "dns:///store.lan:7443"})
if err != nil || nats != "172.17.0.1:4222" || store != "store.lan:7443" {
t.Fatalf("relayTargets = %q, %q, %v", nats, store, err)
}
if _, _, err := relayTargets(Endpoints{NATS: "nats://a:1,nats://b:2"}); err == nil {
t.Fatal("a NATS cluster URL list was accepted; the relay forwards one address")
}
}
+195
View File
@@ -0,0 +1,195 @@
// Package kitrun starts a Kit task: it composes the profile's Kits, opens
// the task's egress session and sandbox network, and starts the container
// with archie's worker as root and the harness spec the worker runs stages on.
package kitrun
import (
"context"
"errors"
"fmt"
"maps"
"slices"
"sync"
"github.com/docker/sandbox-kit-spec/v3/fetch"
"github.com/docker/sandbox-kit-spec/v3/spec"
"github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/container"
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
"github.com/samcharles93/archie-core/internal/infrastructure/kit"
)
const (
agentPath = "/opt/archie/archie-agent"
caPath = "/opt/archie/ca.pem"
)
// Launcher starts Kit task containers.
type Launcher struct {
Pool *container.Pool
Fetch *fetch.Client
Proxy *egress.Proxy
Networks *egress.Networks
// AgentBinary and CAFile are host paths mounted read-only into every
// Kit container: the worker's own binary and the egress CA.
AgentBinary string
CAFile string
mu sync.Mutex
started bool
}
// Request is one Kit task to start.
type Request struct {
// Execution keys the task's Kit volumes and names its container and
// network.
Execution string
Kit []string
Adapter string
WorkDir string
WorkerEnv []string
}
// Run is a started Kit task.
type Run struct {
Container *container.Container
Harness agentexec.HarnessSpec
// Volumes outlive the run; remove them with RemoveVolumes once the
// execution has ended.
Volumes []kit.Volume
network string
token string
}
// Launch composes the request's Kits and starts its container.
func (l *Launcher) Launch(ctx context.Context, req Request) (*Run, error) {
if len(req.Kit) == 0 {
return nil, errors.New("kit profile names no kit")
}
adapter, ok := agentexec.LookupHarnessAdapter(req.Adapter)
if req.Adapter != "" && !ok {
return nil, fmt.Errorf("harness output adapter %q is unknown", req.Adapter)
}
if err := l.startEgress(ctx); err != nil {
return nil, err
}
plan, img, err := l.compose(ctx, req.Kit)
if err != nil {
return nil, err
}
network, err := spec.NetworkPolicyOf(plan.Capabilities)
if err != nil {
return nil, err
}
creds, err := spec.CredentialsOf(plan.Capabilities)
if err != nil {
return nil, err
}
session, err := l.Proxy.Register(egress.SessionOptions{Run: req.Execution, Network: network, Credentials: creds})
if err != nil {
return nil, err
}
run := &Run{network: "archie-kit-" + req.Execution, token: session.Token()}
launch, err := kit.Assemble(plan, img, kit.LaunchParams{Execution: req.Execution, ProxyToken: session.Token(), CAPath: caPath})
if err != nil {
l.Proxy.Revoke(run.token)
return nil, err
}
launch.Harness.Adapter, launch.Harness.MCPConfig = req.Adapter, adapter.MCPConfig
run.Harness, run.Volumes = launch.Harness, launch.Volumes
if err := l.Networks.Create(ctx, run.network); err != nil {
l.Proxy.Revoke(run.token)
return nil, err
}
run.Container, err = l.Pool.AcquireKit(ctx, container.KitSpec{
Name: "archie-kit-" + req.Execution,
Image: req.Kit[0],
Network: run.network,
Worker: []string{agentPath},
WorkerEnv: req.WorkerEnv,
Binds: []string{
l.AgentBinary + ":" + agentPath + ":ro",
l.CAFile + ":" + caPath + ":ro",
req.WorkDir + ":" + kit.WorkspaceDir,
},
Launch: launch,
InstallDone: session.EnterRuntime,
})
if err != nil {
l.Proxy.Revoke(run.token)
return nil, errors.Join(err, l.Networks.Remove(context.WithoutCancel(ctx), run.network))
}
return run, nil
}
// compose assembles the profile's Kits and reads the workload image's
// config, the first Kit being the workload.
func (l *Launcher) compose(ctx context.Context, refs []string) (*kit.Plan, kit.ImageConfig, error) {
reqs := make([]fetch.Request, len(refs))
for i, ref := range refs {
reqs[i] = fetch.Request{Reference: ref}
}
merged, err := l.Fetch.Assemble(ctx, reqs, kit.MergeOptions)
if err != nil {
return nil, kit.ImageConfig{}, fmt.Errorf("assemble kits: %w", err)
}
plan, err := kit.FromMerge(merged.MergeResult)
if err != nil {
return nil, kit.ImageConfig{}, err
}
img, err := l.imageConfig(ctx, refs[0])
if err != nil {
return nil, kit.ImageConfig{}, err
}
for _, name := range slices.Sorted(maps.Keys(merged.Env)) {
img.Env = append(img.Env, name+"="+merged.Env[name])
}
return plan, img, nil
}
// Release stops the run's container, then removes its network and ends
// its egress session.
func (l *Launcher) Release(ctx context.Context, run *Run) error {
l.Pool.Release(ctx, run.Container)
l.Proxy.Revoke(run.token)
return l.Networks.Remove(context.WithoutCancel(ctx), run.network)
}
// RemoveVolumes removes an ended execution's Kit volumes.
func (l *Launcher) RemoveVolumes(ctx context.Context, volumes []kit.Volume) error {
return container.RemoveKitVolumes(ctx, l.Pool.Client(), volumes)
}
// startEgress starts the relay on first use, so a daemon with no Kit
// profile runs no relay.
func (l *Launcher) startEgress(ctx context.Context) error {
l.mu.Lock()
defer l.mu.Unlock()
if l.started {
return nil
}
if err := l.Networks.Start(ctx); err != nil {
return err
}
l.started = true
return nil
}
func (l *Launcher) imageConfig(ctx context.Context, ref string) (kit.ImageConfig, error) {
if err := l.Pool.EnsureImage(ctx, ref); err != nil {
return kit.ImageConfig{}, err
}
inspected, err := l.Pool.Client().ImageInspect(ctx, ref)
if err != nil {
return kit.ImageConfig{}, fmt.Errorf("inspect kit image %s: %w", ref, err)
}
cfg := inspected.Config
if cfg == nil {
return kit.ImageConfig{}, fmt.Errorf("kit image %s has no config", ref)
}
return kit.ImageConfig{
Entrypoint: slices.Clone(cfg.Entrypoint), Cmd: slices.Clone(cfg.Cmd),
Env: slices.Clone(cfg.Env), User: cfg.User,
}, nil
}