diff --git a/go.mod b/go.mod index b588b9ba5..f2b462bfb 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,7 @@ require ( cel.dev/expr v0.26.0 // indirect github.com/Microsoft/go-winio v0.6.4 // indirect github.com/ProtonMail/go-crypto v1.5.2 // indirect + github.com/ai-openshell/sdk-go v0.1.8 // indirect github.com/antithesishq/antithesis-sdk-go v0.9.0 // indirect github.com/antlr4-go/antlr/v4 v4.13.1 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect diff --git a/go.sum b/go.sum index ef97177cd..3a79133a7 100644 --- a/go.sum +++ b/go.sum @@ -8,6 +8,8 @@ github.com/Microsoft/go-winio v0.6.4 h1:kJF2pamtYCWXf0xAT8sAkwKC0pMl2HYBrRPHAqyU github.com/Microsoft/go-winio v0.6.4/go.mod h1:1xl5JXG4ze/m74GH6Dc4Mwxfc3VL5siRVQjIAlHH07U= github.com/ProtonMail/go-crypto v1.5.2 h1:cucYnvqcY7UOXVD//mSyjeaPY0SSN3v5cDkYPxumINk= github.com/ProtonMail/go-crypto v1.5.2/go.mod h1:/RaSu30DaKO4RY+XdV/ACcCcZkGr7AhUIduq5sjzzCo= +github.com/ai-openshell/sdk-go v0.1.8 h1:p5i7VAZxlB/tzWy6KQWkdvX3cLIu8x0AinUx1X6wp+s= +github.com/ai-openshell/sdk-go v0.1.8/go.mod h1:nYYe/HYeEct0KG5YyF2dbLHjUWb7EEA+I1lLi6A8j14= github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8= github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4= github.com/antithesishq/antithesis-sdk-go v0.9.0 h1:JQpWOgYSYBb9HqgPtaXBswHxZFmOnXRsPFDI0yeCJWM= diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 3bf4535d9..19883df72 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -160,6 +160,9 @@ type boot struct { natsToken string containerPool *container.Pool + // taskRuntime is what task agents run in: the container pool, or an + // OpenShell gateway's sandboxes. Nil parks every task. + taskRuntime daemon.TaskRuntime // sandboxes provisions each task container's isolated network and runs // the egress relay that is its only way out. sandboxes *egress.Networks @@ -495,7 +498,18 @@ func (b *boot) setupContainers(ctx context.Context) func() { b.containerPool = containerPool b.sandboxes = sandboxes b.storeBackend = storeBackend - return closeDocker + b.taskRuntime = daemon.DockerRuntime(containerPool) + if b.cfg.Containers.Runtime != config.RuntimeOpenShell { + return closeDocker + } + rt, closeOpenShell, err := startOpenShell(ctx, b.cfgHolder, b.secrets, b.log) + if err != nil { + b.log.ErrorContext(ctx, "autonomous workflows unavailable: openshell runtime", "err", err) + b.taskRuntime = nil + return closeDocker + } + b.taskRuntime = daemon.OpenShellRuntime(rt) + return func() { closeOpenShell(); closeDocker() } } // setupGatewayClient dials the Gateway, which owns every model call. @@ -617,7 +631,7 @@ func (b *boot) buildDaemon(ctx context.Context) { Log: log, TaskTransport: b.natsClient, RunCredentials: b.stateStoreGrants, - Runtime: daemon.DockerRuntime(b.containerPool), + Runtime: b.taskRuntime, ModelEgress: b.modelEgress, TaskModels: b.taskModels, TaskInstructions: b.taskInstructions, diff --git a/internal/app/archied/control_plane.go b/internal/app/archied/control_plane.go index db2a90247..1a2c896e2 100644 --- a/internal/app/archied/control_plane.go +++ b/internal/app/archied/control_plane.go @@ -240,8 +240,10 @@ func (b *boot) startLiveSettings(ctx context.Context) error { // entries (boot.reconcileToolSettings, its consumer); a removed MCP server // really disconnects, because it is a child process with a Stop. ContainerRuntimePoliciesKind is on it because both consumers // re-read the published config: the container pool takes its image, pull -// policy, network, max-uptime and concurrency cap per acquire, and the daemon's -// dispatcher is resized after the publish (applyRuntimeResourceUpdate below). +// policy, max-uptime and concurrency cap per acquire, and the daemon's +// dispatcher is resized after the publish (applyRuntimeResourceUpdate below); +// a change to the task runtime itself is refused until restart +// (refuseRuntimeChange). // PluginSettingsKind is on the list because its only consumer is the directory // reconciliation, which reads the running config each tick; a removed plugin // or engine still cannot unload, so that kind reports the removal rather than @@ -366,6 +368,13 @@ func (b *boot) applyRuntimeResourceUpdate(ctx context.Context, kind string, upda return err } } + if kind == controlplanestore.ContainerRuntimePoliciesKind { + if err := b.refuseRuntimeChange(ctx); err != nil { + b.applyStatus.Report(ctx, kind, update.Version, err) + b.log.ErrorContext(ctx, "container runtime policies refused; the running settings stay", "version", update.Version, "err", err) + return err + } + } base := b.cfgHolder.Get() // Boot publishes before the model catalog is merged in, so the snapshot // this read returns can lack the catalog's model limits and discovered @@ -409,6 +418,38 @@ func (b *boot) resizeTaskDispatcher(maxConcurrency int) { } } +// refuseRuntimeChange refuses a stored container-runtime-policies document +// that changes the task runtime or its OpenShell gateway: the daemon chose and +// connected its runtime at boot, so such a change applies on restart. +func (b *boot) refuseRuntimeChange(ctx context.Context) error { + var stored struct { + Runtime string `json:"runtime"` + OpenShell config.OpenShellConfig `json:"openshell"` + } + _, found, err := b.controlPlane.Query(ctx, controlplanestore.ContainerRuntimePoliciesKind, func(value []byte) error { + return json.Unmarshal(value, &stored) + }) + if err != nil { + return fmt.Errorf("read container runtime policies: %w", err) + } + if !found { + return nil + } + running := b.cfgHolder.Get().Containers + if runtimeName(stored.Runtime) != runtimeName(running.Runtime) || stored.OpenShell != running.OpenShell { + return fmt.Errorf("the task runtime applies on restart: stored %q, running %q", runtimeName(stored.Runtime), runtimeName(running.Runtime)) + } + return nil +} + +// runtimeName is runtime with the empty default spelled out. +func runtimeName(runtime string) string { + if runtime == "" { + return config.RuntimeDocker + } + return runtime +} + // refuseSkillsDirChange refuses a stored plugin-settings document whose // skills_dir differs from the value in force. skills_dir is the one directory // with no live consumer, so a change to it stays a restart-scoped edit rather diff --git a/internal/app/archied/openshell.go b/internal/app/archied/openshell.go new file mode 100644 index 000000000..0bd9430b0 --- /dev/null +++ b/internal/app/archied/openshell.go @@ -0,0 +1,58 @@ +package archied + +import ( + "context" + "fmt" + "log/slog" + "time" + + v1 "github.com/ai-openshell/sdk-go/openshell/v1" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/openshell" + "github.com/samcharles93/archie-core/internal/secret" +) + +// startOpenShell connects to the OpenShell gateway task sandboxes run on and +// removes the sandboxes a previous daemon left. A gateway that is down only +// degrades: the runtime is returned, and each task parks on its failed +// acquire until the gateway answers. +func startOpenShell(ctx context.Context, cfgHolder *config.Holder, secrets *secret.Registry, log *slog.Logger) (*openshell.Runtime, func(), error) { + cfg := cfgHolder.Get() + settings := cfg.Containers.OpenShell + auth := v1.NoAuth() + if settings.Token != (config.SecretRef{}) { + if secrets == nil { + return nil, nil, fmt.Errorf("openshell gateway token: no secret engine is available") + } + token, err := secrets.Resolve(settings.Token) + if err != nil { + return nil, nil, fmt.Errorf("openshell gateway token: %w", err) + } + auth = v1.StaticToken(token) + } + client, err := v1.NewClient(v1.Config{Address: settings.Address, Auth: auth}) + if err != nil { + return nil, nil, fmt.Errorf("openshell gateway %s: %w", settings.Address, err) + } + rt := openshell.New(client, openshell.Options{ + Workspace: settings.Workspace, + Instance: cfg.Instance, + MaxUptime: func() time.Duration { return cfgHolder.Get().Containers.MaxUptime.Std() }, + Log: log, + }) + checkCtx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + if health, err := client.Health().Check(checkCtx); err != nil || !health.Healthy { + log.WarnContext(ctx, "openshell gateway unhealthy; tasks park until it answers", "gateway", settings.Address, "err", err) + } else if err := rt.Sweep(checkCtx); err != nil { + log.WarnContext(ctx, "openshell: orphaned sandboxes remain", "err", err) + } + closeClient := func() { + if err := client.Close(); err != nil { + log.WarnContext(ctx, "openshell client close failed", "err", err) + } + } + log.InfoContext(ctx, "task sandboxes run on openshell", "gateway", settings.Address, "workspace", settings.Workspace) + return rt, closeClient, nil +} diff --git a/internal/config/config.go b/internal/config/config.go index 657184337..83832dcde 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -695,6 +695,25 @@ type BindingsConfig struct { PreviousEncryptionKeys []SecretRef `toml:"previous_encryption_keys" yaml:"previous_encryption_keys"` } +// Task runtimes, the values of ContainerConfig.Runtime. +const ( + RuntimeDocker = "docker" + RuntimeOpenShell = "openshell" +) + +// OpenShellConfig locates the OpenShell gateway task sandboxes run on. +type OpenShellConfig struct { + // Address is the gateway, "http://host:port" for plaintext or + // "host:port" for TLS. + Address string `toml:"address" yaml:"address" json:"address"` + // Workspace is the gateway workspace sandboxes are created in. Empty + // means "default". + Workspace string `toml:"workspace" yaml:"workspace" json:"workspace"` + // Token resolves to the gateway's bearer token. Zero sends none, which + // only a gateway allowing unauthenticated users accepts. + Token SecretRef `toml:"token" yaml:"token" json:"token"` +} + // ContainerConfig configures Docker sandbox execution of archie-agent. type ContainerConfig struct { // Image is the Docker image to run (e.g. "git.catlow.cloud/sam/archie-agent:latest"). @@ -710,9 +729,15 @@ type ContainerConfig struct { VolumeTTL Duration `toml:"volume_ttl" yaml:"volume_ttl"` // PullPolicy controls image pulling: "missing" (default) or "always". PullPolicy string `toml:"pull_policy" yaml:"pull_policy"` - // Network is the Docker network agent containers join. Empty uses the + // Network is the Docker network the egress relay joins. Empty uses the // daemon's own network, then the default bridge. Network string `toml:"network" yaml:"network"` + // Runtime is what task agents run in: RuntimeDocker (the default when + // empty) or RuntimeOpenShell. Applies on restart. + Runtime string `toml:"runtime" yaml:"runtime"` + // OpenShell is the gateway task sandboxes run on when Runtime is + // RuntimeOpenShell. Applies on restart. + OpenShell OpenShellConfig `toml:"openshell" yaml:"openshell"` // Profiles are named agent profiles a workflow selects with `profile:`. // Stored as their own control-plane resource. Profiles map[string]AgentProfile `toml:"profiles" yaml:"profiles" json:"-"` diff --git a/internal/daemon/runtime.go b/internal/daemon/runtime.go index a6eb64952..243f74eaa 100644 --- a/internal/daemon/runtime.go +++ b/internal/daemon/runtime.go @@ -4,6 +4,7 @@ import ( "context" "github.com/samcharles93/archie-core/internal/container" + "github.com/samcharles93/archie-core/internal/infrastructure/openshell" "github.com/samcharles93/archie-core/internal/storage" ) @@ -57,3 +58,33 @@ func (r dockerRuntime) Release(ctx context.Context, c TaskContainer) { func (r dockerRuntime) Reown(ctx context.Context, dir string, uid, gid int) error { return r.pool.Reown(ctx, dir, uid, gid) } + +// OpenShellRuntime runs tasks as rt's OpenShell sandboxes. A nil rt is no +// runtime, as with DockerRuntime. +func OpenShellRuntime(rt *openshell.Runtime) TaskRuntime { + if rt == nil { + return nil + } + return openShellRuntime{rt: rt} +} + +type openShellRuntime struct{ rt *openshell.Runtime } + +func (r openShellRuntime) Acquire(ctx context.Context, image string, mounts []storage.Mount, env []string) (TaskContainer, error) { + sb, err := r.rt.Acquire(ctx, image, mounts, env) + if err != nil { + return nil, err + } + return sb, nil +} + +// Release releases a sandbox this runtime acquired. +func (r openShellRuntime) Release(ctx context.Context, c TaskContainer) { + if sb, ok := c.(*openshell.Sandbox); ok { + r.rt.Release(ctx, sb) + } +} + +func (r openShellRuntime) Reown(ctx context.Context, dir string, uid, gid int) error { + return r.rt.Reown(ctx, dir, uid, gid) +} diff --git a/internal/infrastructure/controlplanestore/container_settings.go b/internal/infrastructure/controlplanestore/container_settings.go index bed1f7b05..14157b8f9 100644 --- a/internal/infrastructure/controlplanestore/container_settings.go +++ b/internal/infrastructure/controlplanestore/container_settings.go @@ -12,12 +12,14 @@ import ( // containerRuntimePolicies is the container-runtime-policies document, with // snake_case JSON keys. type containerRuntimePolicies struct { - Image string `json:"image"` - MaxConcurrency int `json:"max_concurrency"` - MaxUptime config.Duration `json:"max_uptime"` - VolumeTTL config.Duration `json:"volume_ttl"` - PullPolicy string `json:"pull_policy"` - Network string `json:"network"` + Image string `json:"image"` + MaxConcurrency int `json:"max_concurrency"` + MaxUptime config.Duration `json:"max_uptime"` + VolumeTTL config.Duration `json:"volume_ttl"` + PullPolicy string `json:"pull_policy"` + Network string `json:"network"` + Runtime string `json:"runtime"` + OpenShell config.OpenShellConfig `json:"openshell"` } // agentProfile is one named execution environment as the document writes it. @@ -82,6 +84,7 @@ func (p containerRuntimePolicies) settings() config.ContainerConfig { return config.ContainerConfig{ Image: p.Image, MaxConcurrency: p.MaxConcurrency, MaxUptime: p.MaxUptime, VolumeTTL: p.VolumeTTL, PullPolicy: p.PullPolicy, Network: p.Network, + Runtime: p.Runtime, OpenShell: p.OpenShell, } } @@ -90,6 +93,7 @@ func seedContainerPolicies(cfg config.Config) any { return containerRuntimePolicies{ Image: containers.Image, MaxConcurrency: containers.MaxConcurrency, MaxUptime: containers.MaxUptime, VolumeTTL: containers.VolumeTTL, PullPolicy: containers.PullPolicy, Network: containers.Network, + Runtime: containers.Runtime, OpenShell: containers.OpenShell, } } @@ -107,6 +111,18 @@ func validateContainers(input []byte) error { if strings.TrimSpace(settings.Image) == "" { return fmt.Errorf("container image is required for autonomous workflow workers") } + switch settings.Runtime { + case "", config.RuntimeDocker: + case config.RuntimeOpenShell: + if strings.TrimSpace(settings.OpenShell.Address) == "" { + return fmt.Errorf("the openshell runtime needs a gateway address") + } + default: + return fmt.Errorf("runtime must be docker or openshell") + } + if (settings.OpenShell.Token.Engine == "") != (settings.OpenShell.Token.Key == "") { + return fmt.Errorf("the openshell token reference needs both an engine and a key") + } // Profiles is json:"-" on config.ContainerConfig: it is // AgentProfileKind's document now, validated there. return nil diff --git a/internal/infrastructure/openshell/runtime.go b/internal/infrastructure/openshell/runtime.go new file mode 100644 index 000000000..66c8cc84d --- /dev/null +++ b/internal/infrastructure/openshell/runtime.go @@ -0,0 +1,292 @@ +// Package openshell runs task agents as NVIDIA OpenShell sandboxes. A sandbox +// has no network of its own: every connection it makes passes the gateway's +// policy, and credentials reach it only as placeholders. +package openshell + +import ( + "context" + "errors" + "fmt" + "log/slog" + "slices" + "strings" + "sync" + "time" + + v1 "github.com/ai-openshell/sdk-go/openshell/v1" + + "github.com/samcharles93/archie-core/internal/storage" +) + +// instanceLabel marks the sandboxes one archie instance owns; its value is +// the instance name, so instances sharing a gateway never remove each +// other's. +const instanceLabel = "archie.instance" + +// agentCommand is the sandbox's main process. The image's own entrypoint is +// replaced by OpenShell's, so the agent is named here. +var agentCommand = []string{"archie-agent"} + +// writable are container paths tools write to inside the sandbox. They are +// the container's own layer, so writing them exposes nothing on the host. +var writable = []string{"/tmp", "/var/tmp", "/root", "/home"} + +// readOnly are the system paths the agent and its tools read. +var readOnly = []string{"/usr", "/lib", "/lib64", "/bin", "/sbin", "/etc", "/opt"} + +// Options configure a Runtime. +type Options struct { + // Workspace is the gateway workspace; empty means "default". + Workspace string + // Instance names this archie instance. It prefixes sandbox names and is + // the instance label's value. + Instance string + // MaxUptime returns the current lifetime cap; zero or a nil func means + // none. It is read per acquire, so a stored change reaches the next task. + MaxUptime func() time.Duration + // Poll is how often a running sandbox is checked for an exit; zero means + // two seconds. + Poll time.Duration + Log *slog.Logger +} + +// Runtime creates, watches and removes task sandboxes on one gateway. +type Runtime struct { + client v1.ClientInterface + workspace string + instance string + maxUptime func() time.Duration + poll time.Duration + log *slog.Logger +} + +// New returns a Runtime on client. +func New(client v1.ClientInterface, opts Options) *Runtime { + r := &Runtime{ + client: client, + workspace: opts.Workspace, + instance: opts.Instance, + maxUptime: opts.MaxUptime, + poll: opts.Poll, + log: opts.Log, + } + if r.workspace == "" { + r.workspace = "default" + } + if r.poll <= 0 { + r.poll = 2 * time.Second + } + if r.maxUptime == nil { + r.maxUptime = func() time.Duration { return 0 } + } + if r.log == nil { + r.log = slog.New(slog.DiscardHandler) + } + return r +} + +// Sandbox is one task's running sandbox. +type Sandbox struct { + name string + exited chan struct{} + // detail is written before exited closes, so a reader that saw the close + // may read it without a lock. + detail string + once sync.Once + stop context.CancelFunc + done chan struct{} +} + +// Exited closes when the agent stops running for any reason: it exited, the +// sandbox failed or was removed, or it reached its maximum uptime. +func (s *Sandbox) Exited() <-chan struct{} { return s.exited } + +// ExitDetail says how the sandbox ended. It is empty until Exited closes. +func (s *Sandbox) ExitDetail() string { + select { + case <-s.exited: + return s.detail + default: + return "" + } +} + +// Acquire creates a sandbox running the agent from image, with mounts bound +// in and env as its environment, and waits until it is ready. +func (r *Runtime) Acquire(ctx context.Context, image string, mounts []storage.Mount, env []string) (*Sandbox, error) { + name := fmt.Sprintf("%s-agent-%d", r.instance, time.Now().UnixNano()) + spec, err := r.spec(image, mounts, env) + if err != nil { + return nil, err + } + if _, err := r.client.Sandboxes().Create(ctx, r.workspace, name, spec); err != nil { + return nil, fmt.Errorf("create sandbox %s: %w", name, err) + } + if _, err := r.client.Sandboxes().WaitReady(ctx, r.workspace, name); err != nil { + r.remove(ctx, name) + return nil, fmt.Errorf("sandbox %s not ready: %w", name, err) + } + watchCtx, stop := context.WithCancel(context.WithoutCancel(ctx)) + s := &Sandbox{name: name, exited: make(chan struct{}), stop: stop, done: make(chan struct{})} + go r.watch(watchCtx, s, r.maxUptime()) + r.log.InfoContext(ctx, "sandbox started", "sandbox", name) + return s, nil +} + +// Release stops watching s and removes its sandbox. +func (r *Runtime) Release(ctx context.Context, s *Sandbox) { + if s == nil { + return + } + s.stop() + <-s.done + r.remove(ctx, s.name) + r.log.InfoContext(ctx, "sandbox released", "sandbox", s.name) +} + +// Reown is not available: the daemon cannot run a privileged container on +// the gateway to chown files back. +func (r *Runtime) Reown(context.Context, string, int, int) error { + return errors.New("the openshell runtime cannot repair file ownership; the sandbox user must match the daemon's") +} + +// Sweep removes the sandboxes a previous daemon of this instance left behind. +// Work interrupted by a restart is requeued, so none of them is still needed. +func (r *Runtime) Sweep(ctx context.Context) error { + pager, err := r.client.Sandboxes().List(r.workspace, v1.ListOptions{}) + if err != nil { + return fmt.Errorf("list sandboxes: %w", err) + } + all, err := pager.All(ctx) + if err != nil { + return fmt.Errorf("list sandboxes: %w", err) + } + var errs []error + for _, sb := range all { + if sb.Spec.Template == nil || sb.Spec.Template.Labels[instanceLabel] != r.instance { + continue + } + r.log.InfoContext(ctx, "removing orphaned sandbox", "sandbox", sb.Name) + if _, err := r.client.Sandboxes().Delete(ctx, r.workspace, sb.Name); err != nil && !v1.IsNotFound(err) { + errs = append(errs, fmt.Errorf("remove sandbox %s: %w", sb.Name, err)) + } + } + return errors.Join(errs...) +} + +// spec is the sandbox a task runs in. +func (r *Runtime) spec(image string, mounts []storage.Mount, env []string) (*v1.SandboxSpec, error) { + environment := make(map[string]string, len(env)) + for _, entry := range env { + key, value, ok := strings.Cut(entry, "=") + if !ok || key == "" { + return nil, fmt.Errorf("environment entry %q is not KEY=value", entry) + } + environment[key] = value + } + readWrite := slices.Clone(writable) + var driverMounts []any + for _, m := range mounts { + mount := map[string]any{"type": m.Type, "source": m.Source, "target": m.Destination, "read_only": m.ReadOnly} + if m.Type == storage.MountTypeBind { + // The same relabelling the Docker pool applies; Docker ignores + // it on a host without SELinux. + mount["selinux_label"] = "private" + if m.Shared { + mount["selinux_label"] = "shared" + } + } + driverMounts = append(driverMounts, mount) + if !m.ReadOnly { + readWrite = append(readWrite, m.Destination) + } + } + return &v1.SandboxSpec{ + Template: &v1.SandboxTemplate{ + Image: image, + Labels: map[string]string{instanceLabel: r.instance}, + DriverConfig: map[string]any{"docker": map[string]any{"mounts": driverMounts}}, + }, + Environment: environment, + Command: slices.Clone(agentCommand), + Policy: &v1.SandboxPolicy{ + Filesystem: &v1.FilesystemPolicy{IncludeWorkdir: true, ReadOnly: slices.Clone(readOnly), ReadWrite: readWrite}, + }, + }, nil +} + +// watch closes s.exited once the sandbox stops running or outlives maxUptime. +// A failed status read says nothing about the sandbox, so it never ends the +// watch: a gateway hiccup must not abort a live run. +func (r *Runtime) watch(ctx context.Context, s *Sandbox, maxUptime time.Duration) { + defer close(s.done) + var deadline <-chan time.Time + if maxUptime > 0 { + timer := time.NewTimer(maxUptime) + defer timer.Stop() + deadline = timer.C + } + ticker := time.NewTicker(r.poll) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-deadline: + r.log.WarnContext(ctx, "sandbox reached its maximum uptime", "sandbox", s.name, "max_uptime", maxUptime) + r.remove(ctx, s.name) + r.finish(s, fmt.Sprintf("killed at its maximum uptime of %s", maxUptime)) + return + case <-ticker.C: + } + sb, err := r.client.Sandboxes().Get(ctx, r.workspace, s.name) + if v1.IsNotFound(err) { + r.finish(s, "sandbox was removed") + return + } + if err != nil { + continue + } + if detail, ended := exitDetail(sb); ended { + r.finish(s, detail) + return + } + } +} + +// finish records how s ended and closes Exited, once. +func (r *Runtime) finish(s *Sandbox, detail string) { + s.once.Do(func() { + s.detail = detail + close(s.exited) + }) +} + +// exitDetail reports whether sb has stopped running and, if so, how. +func exitDetail(sb *v1.Sandbox) (string, bool) { + st := sb.Status + if st.ExitCode == nil && st.Phase != v1.SandboxError && st.Phase != v1.SandboxCompleted && st.Phase != v1.SandboxStopped { + return "", false + } + detail := fmt.Sprintf("sandbox %s", st.Phase) + if st.ExitCode != nil { + detail = fmt.Sprintf("exit code %d", *st.ExitCode) + } + for _, c := range st.Conditions { + if c.Type == "Ready" && c.Message != "" { + detail += ": " + c.Message + break + } + } + return detail, true +} + +// remove deletes a sandbox with a fresh deadline, so a cancelled task still +// cleans up. A sandbox already gone is not an error. +func (r *Runtime) remove(ctx context.Context, name string) { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) + defer cancel() + if _, err := r.client.Sandboxes().Delete(ctx, r.workspace, name); err != nil && !v1.IsNotFound(err) { + r.log.WarnContext(ctx, "sandbox remove failed", "sandbox", name, "err", err) + } +} diff --git a/internal/infrastructure/openshell/runtime_test.go b/internal/infrastructure/openshell/runtime_test.go new file mode 100644 index 000000000..46d432e57 --- /dev/null +++ b/internal/infrastructure/openshell/runtime_test.go @@ -0,0 +1,108 @@ +package openshell + +import ( + "context" + "slices" + "strings" + "testing" + "time" + + v1 "github.com/ai-openshell/sdk-go/openshell/v1" + "github.com/ai-openshell/sdk-go/openshell/v1/fake" +) + +// TestTaskSandboxEndsWithItsTask guards the sandbox lifecycle: a task sees its +// sandbox end however it ends (the agent exits, or it outlives its maximum +// uptime), and the sandbox is gone from the gateway once the task is done, so +// sandboxes never pile up. +func TestTaskSandboxEndsWithItsTask(t *testing.T) { + tests := []struct { + name string + maxUptime time.Duration + agentExits bool + wantExit bool + wantDetail string + }{ + {name: "released while running"}, + {name: "agent exits", agentExits: true, wantExit: true, wantDetail: "exit code 3"}, + {name: "outlives its maximum uptime", maxUptime: 30 * time.Millisecond, wantExit: true, wantDetail: "maximum uptime"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := fake.NewClient() + defer client.Close() + rt := New(client, Options{Instance: "archie", Poll: 5 * time.Millisecond, MaxUptime: func() time.Duration { return tt.maxUptime }}) + + sb, err := rt.Acquire(t.Context(), "agent:test", nil, []string{"NATS_URL=nats://nats.example:4222"}) + if err != nil { + t.Fatal(err) + } + if tt.agentExits { + got, err := client.Sandboxes().Get(t.Context(), "default", sb.name) + if err != nil { + t.Fatal(err) + } + code := int32(3) + got.Status.ExitCode = &code + got.Status.Phase = v1.SandboxError + client.AddSandbox("default", got) + } + wait := 2 * time.Second + if !tt.wantExit { + wait = 50 * time.Millisecond + } + select { + case <-sb.Exited(): + if !tt.wantExit { + t.Fatalf("sandbox reported an exit (%q) while still running", sb.ExitDetail()) + } + if !strings.Contains(sb.ExitDetail(), tt.wantDetail) { + t.Fatalf("exit detail = %q, want it to say %q", sb.ExitDetail(), tt.wantDetail) + } + case <-time.After(wait): + if tt.wantExit { + t.Fatal("sandbox exit never reported") + } + } + rt.Release(t.Context(), sb) + if _, err := client.Sandboxes().Get(t.Context(), "default", sb.name); !v1.IsNotFound(err) { + t.Fatalf("sandbox still on the gateway after release: err=%v", err) + } + }) + } +} + +// TestSweepRemovesOnlyThisInstancesSandboxes guards instances sharing a +// gateway: a restarted daemon removes the sandboxes it left, never another +// instance's or ones archie did not create. +func TestSweepRemovesOnlyThisInstancesSandboxes(t *testing.T) { + client := fake.NewClient() + defer client.Close() + for name, labels := range map[string]map[string]string{ + "archie-agent-1": {instanceLabel: "archie"}, + "staging-agent-1": {instanceLabel: "staging"}, + "someone-else": nil, + } { + client.AddSandbox("default", &v1.Sandbox{Name: name, Spec: v1.SandboxSpec{Template: &v1.SandboxTemplate{Labels: labels}}}) + } + rt := New(client, Options{Instance: "archie"}) + if err := rt.Sweep(context.Background()); err != nil { + t.Fatal(err) + } + pager, err := client.Sandboxes().List("default", v1.ListOptions{}) + if err != nil { + t.Fatal(err) + } + left, err := pager.All(context.Background()) + if err != nil { + t.Fatal(err) + } + var names []string + for _, sb := range left { + names = append(names, sb.Name) + } + slices.Sort(names) + if want := []string{"someone-else", "staging-agent-1"}; !slices.Equal(names, want) { + t.Fatalf("sandboxes left after sweep = %v, want %v", names, want) + } +} diff --git a/internal/storage/storage.go b/internal/storage/storage.go index f9aad8b18..f9e545795 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -17,6 +17,7 @@ import ( "encoding/json" "errors" "fmt" + "maps" "os" "path/filepath" "sort" @@ -238,6 +239,9 @@ func NewDockerBackend(cli *client.Client, instance string) *DockerBackend { return &DockerBackend{cli: cli, instance: instance} } +// openShellAttachableLabel marks a volume an OpenShell sandbox may mount. +const openShellAttachableLabel = "openshell.ai/sandbox-attachable" + // ensureVolume creates a Docker volume unless it exists. A nil client does // nothing. func (d *DockerBackend) ensureVolume(ctx context.Context, name string, labels map[string]string) error { @@ -250,6 +254,13 @@ func (d *DockerBackend) ensureVolume(ctx context.Context, name string, labels ma if err == nil { return nil // already exists } + // An OpenShell gateway mounts only volumes marked attachable, and labels + // cannot be added once a volume exists, so every volume carries it. + labels = maps.Clone(labels) + if labels == nil { + labels = map[string]string{} + } + labels[openShellAttachableLabel] = "true" _, err = d.cli.VolumeCreate(ctx, client.VolumeCreateOptions{ Name: name, Driver: "local", diff --git a/ui/src/settings/ContainerRuntimePage.vue b/ui/src/settings/ContainerRuntimePage.vue index 6456e1e6d..cbd0e5e1d 100644 --- a/ui/src/settings/ContainerRuntimePage.vue +++ b/ui/src/settings/ContainerRuntimePage.vue @@ -22,6 +22,7 @@ import { resourcesForPage, useSettingsStore } from "@/stores/settings"; import DraftHint from "./DraftHint.vue"; import HistoryLink from "./HistoryLink.vue"; import KindGate from "./KindGate.vue"; +import SecretRefField from "./SecretRefField.vue"; import { fieldInvalid } from "./settings-form"; const KIND = "container-runtime-policies"; @@ -38,6 +39,8 @@ interface ContainerRuntime { volume_ttl: string; pull_policy: string; network: string; + runtime: string; + openshell: { address: string; workspace: string; token: { engine: string; key: string } }; } const store = useSettingsStore(); @@ -49,6 +52,12 @@ const form = computed(() => store.formFor(KIND)); const runtime = computed(() => store.draftValue(KIND) as ContainerRuntime | undefined); const error = computed(() => store.pageErrorFor(KIND)); +const runtimes = [ + { value: "docker", label: "Docker" }, + { value: "openshell", label: "OpenShell" }, +]; +const onOpenShell = computed(() => runtime.value?.runtime === "openshell"); + const pullPolicies = [ { value: "missing", label: "If missing" }, { value: "always", label: "Always" }, @@ -81,6 +90,80 @@ function formatHours(seconds: number): string { {{ catalogError || error }} +
+ + + + + Runtime + Applies on restart. + +
+ + {{ option.label }} + + +
+
+
+
+ + + + + Gateway +
+ + +
+
+
+ + + + Workspace +
+ + +
+
+
+ + + + Token +
+ + +
+
+
+
+ @@ -189,5 +272,6 @@ function formatHours(seconds: number): string { +