Files
archie/internal/daemon/container_run.go
T

398 lines
15 KiB
Go

package daemon
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagation"
"github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/container"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/eventbus"
"github.com/samcharles93/archie-core/internal/events"
agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats"
"github.com/samcharles93/archie-core/internal/storage"
"github.com/samcharles93/archie-core/internal/taskrun"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// acquireTaskContainer prepares and acquires the sandbox container for a
// task, reporting false when it could not -- having already parked the
// task and logged why. The caller releases the container it returns.
func (d *Daemon) acquireTaskContainer(
ctx context.Context,
task *workflow.Task,
repo config.Repo,
workDir string,
image string,
) (*container.Container, string, func(), bool) {
park := func(reason string, err error) {
d.Log.ErrorContext(ctx, reason, "err", err)
d.parkBlockedTask(ctx, task, reason+": "+err.Error(), taskstate.ParkTransient, parkBlocker(err))
}
// Resolve the PR number from inputs before the brief is written.
if task.Workflow == "pr-review" {
task.PRNumber = task.EffectivePRNumber()
}
if err := writeTaskBrief(workDir, task); err != nil {
park("task.json write failed", err)
return nil, "", nil, false
}
// Fetch the pull request with the daemon's forge credential into workDir,
// so the container reads it without credentials.
if task.Workflow == "pr-review" {
if err := prefetchPRReview(ctx, d.forgeFor(ctx, task), task.Owner, task.Repo, task.PRNumber, workDir); err != nil {
park("pr-review prefetch failed", err)
return nil, "", nil, false
}
}
// Guard: Storage may be nil if the daemon was wired incorrectly. In
// normal operation, Storage is always set when ContainerPool is set.
if d.Storage == nil {
d.Log.ErrorContext(ctx, "storage backend is nil -- cannot acquire container")
d.parkRunningTask(ctx, task, "storage backend not configured", taskstate.ParkTransient)
return nil, "", nil, false
}
mounts, err := d.Storage.Setup(ctx, storage.TaskRef{
WorktreeDir: workDir,
Ecosystem: repo.Ecosystem,
PersistentStorage: repo.PersistentStorage,
Owner: task.Owner,
Repo: task.Repo,
})
if err != nil {
park("storage setup failed", err)
return nil, "", nil, false
}
credential, revokeCredential, err := d.runCredential(ctx, task)
if err != nil {
d.teardownStorage(ctx, task, repo, workDir)
park("run credential failed", err)
return nil, "", nil, false
}
model, closeModel, err := d.openModelEgress(ctx, task, credential)
if err != nil {
revokeCredential()
d.teardownStorage(ctx, task, repo, workDir)
park("model egress failed", err)
return nil, "", nil, false
}
revokeRun := revokeCredential
revokeCredential = func() { closeModel(); revokeRun() }
// The container lives in its own network namespace, so a loopback State
// Store target names the container itself. Give this task an address on
// the host bridge that forwards to it, closed with the task.
stateStoreURL, relay, release, err := d.taskStateStoreEndpoint(ctx, revokeCredential)
if err != nil {
revokeCredential()
d.teardownStorage(ctx, task, repo, workDir)
park("state store relay failed", err)
return nil, "", nil, false
}
revokeCredential = release
ctr, err := d.ContainerPool.Acquire(ctx, image, append(mounts, model.Mounts...), append(d.containerEnv(task, credential, stateStoreURL), model.Env...))
if err != nil {
revokeCredential()
// Roll back the storage we just set up: the mounts were created
// for this task but no container will use them. Leaking them until
// a later TTL sweep is not acceptable on a backend that allocates
// real resources (volumes, NFS leases).
d.teardownStorage(ctx, task, repo, workDir)
park("container acquire failed", err)
return nil, "", nil, false
}
d.admitToRelay(ctx, relay, task, ctr)
return ctr, credential, revokeCredential, true
}
// admitToRelay lets ctr, and only ctr, through relay. A container whose
// addresses cannot be read is refused rather than let anyone through.
func (d *Daemon) admitToRelay(ctx context.Context, relay *stateStoreRelay, task *workflow.Task, ctr *container.Container) {
if relay == nil {
return
}
addrs, err := d.ContainerPool.ContainerAddrs(ctx, ctr.ID)
if err != nil {
d.Log.WarnContext(ctx, "state store relay: container addresses unknown, refusing its connections", "task", task.ID, "err", err)
}
relay.Admit(addrs)
}
// taskStateStoreEndpoint is the State Store address one task container is
// handed, the relay carrying it (nil when none is needed) and the release that
// ends that relay. The container lives
// in its own network namespace, so a loopback target names the container
// itself; behind a relay, the address is the host bridge's.
func (d *Daemon) taskStateStoreEndpoint(ctx context.Context, release func()) (string, *stateStoreRelay, func(), error) {
relay, err := d.openTaskStateStoreRelay(ctx)
if err != nil {
return "", nil, release, err
}
if relay == nil {
return d.ConnectedStateStore.URL, nil, release, nil
}
return relay.Addr(), relay, func() { relay.Close(); release() }, nil
}
// openTaskStateStoreRelay starts the relay that carries one task container's
// State Store traffic to the daemon's target. The target stays bound where the
// operator put it; the container is handed an address on the host bridge, the
// same way it is handed NATS's. Nil when the target already reaches the
// containers, or when no bridge address is known.
func (d *Daemon) openTaskStateStoreRelay(ctx context.Context) (*stateStoreRelay, error) {
addr, loopback := loopbackStateStoreTarget(d.ConnectedStateStore.URL)
if !loopback {
return nil, nil
}
gateway := ""
if d.ContainerPool != nil {
gateway = d.ContainerPool.HostGateway()
}
if gateway == "" {
d.Log.WarnContext(ctx, "state store target is loopback and the container pool has no host bridge address; task containers cannot reach it",
"target", d.ConnectedStateStore.URL)
return nil, nil
}
return openStateStoreRelay(ctx, gateway, addr)
}
// containerEnv is the environment a task container starts with. stateStoreURL
// is the address the container can reach the State Store by, which is the
// relay's rather than the daemon's own target.
func (d *Daemon) containerEnv(task *workflow.Task, stateStoreToken, stateStoreURL string) []string {
var env []string
// The endpoint the daemon's own client connected with at startup, not
// the live config: a reloaded [nats] section must not point new
// containers at a server the daemon is not publishing on.
env = append(env, "NATS_URL="+d.ConnectedNATS.URL)
if token := d.ConnectedNATS.ContainerToken(); token != "" {
env = append(env, "NATS_TOKEN="+token)
}
// Pass the container-reachable endpoint with this task's scoped token,
// never the daemon's own.
if stateStoreURL != "" {
env = append(env, "STATE_STORE_URL="+stateStoreURL)
if len(d.ConnectedStateStore.CA) > 0 {
env = append(env, "STATE_STORE_CA="+string(d.ConnectedStateStore.CA))
}
if stateStoreToken != "" {
env = append(env, "STATE_STORE_TOKEN="+stateStoreToken)
}
}
// The agent runs as root in the container, so its commits land owned by
// UID 0 on the host. The daemon's UID/GID let the agent hand the worktree
// back before the daemon reads it to push.
env = append(env, fmt.Sprintf("WORKTREE_UID=%d", os.Getuid()))
env = append(env, fmt.Sprintf("WORKTREE_GID=%d", os.Getgid()))
return env
}
// runCredential issues the task's run credential, or "" when no State Store
// is configured.
func (d *Daemon) runCredential(ctx context.Context, task *workflow.Task) (string, func(), error) {
if d.ConnectedStateStore.URL == "" {
return "", func() {}, nil
}
return d.RunCredentials.Issue(ctx, task, d.configFor(task).Budgets.TaskWallClock.Std())
}
// runViaAgent hands a task to archie-agent and waits for its result. It parks
// the task only when the agent never answered or failed before recording an
// outcome.
//
// credential is the task's run credential; the agent presents it to push the
// task's branch.
func (d *Daemon) runViaAgent(ctx context.Context, task *workflow.Task, repo config.Repo, profile config.AgentProfile, credential string) {
cfg, err := d.taskConfig(ctx, task)
if err != nil {
d.parkRunningTask(ctx, task, err.Error(), taskstate.ParkTransient)
return
}
taskCfg := cfg.ForTask()
d.captureAttemptConfig(ctx, task, taskCfg)
var instructions workflow.Instructions
instructions.Instance, instructions.Organisation, err = d.TaskInstructions.TaskInstructions(ctx, task.ID)
if err != nil {
d.parkRunningTask(ctx, task, "resolve the task's instructions: "+err.Error(), taskstate.ParkTransient)
return
}
req := taskrun.Request{
Instructions: instructions,
Task: task,
Repo: repo,
Cfg: taskCfg,
Providers: agentexec.ProvidersFromConfig(cfg.Providers),
MCPServers: cfg.Tools.MCPServers,
RunCredential: credential,
WorkflowDefinition: task.WorkflowDefinitionYAML,
Tools: d.toolAllowlist(ctx, task, profile.Tools),
}
req.Trace = map[string]string{}
otel.GetTextMapPropagator().Inject(ctx, propagation.MapCarrier(req.Trace))
data, err := json.Marshal(req)
if err != nil {
d.Log.ErrorContext(ctx, "taskrun encode failed", "task", task.ID, "err", err)
d.parkRunningTask(ctx, task, "taskrun encode failed: "+err.Error(), taskstate.ParkTransient)
return
}
reply, err := d.requestTaskRun(ctx, task.ID, data)
if err != nil {
if stoppingOnly(ctx) {
d.Log.InfoContext(ctx, "daemon stopping; task left running for the next daemon to re-queue", "task", task.ID)
return
}
err = runFailure(ctx, err)
d.Log.ErrorContext(ctx, "taskrun request failed", "task", task.ID, "err", err)
d.parkRunningTask(ctx, task, "taskrun request failed: "+err.Error(), taskstate.ParkTransient)
return
}
var resp taskrun.Response
if err := json.Unmarshal(reply, &resp); err != nil {
d.Log.ErrorContext(ctx, "taskrun decode response failed", "task", task.ID, "err", err)
d.parkRunningTask(ctx, task, "taskrun decode response failed: "+err.Error(), taskstate.ParkTransient)
return
}
if resp.Error != "" {
d.Log.ErrorContext(ctx, "taskrun run failed", "task", task.ID, "err", resp.Error)
d.parkRunningTask(ctx, task, "taskrun run failed: "+resp.Error, taskstate.ParkTransient)
return
}
// The agent applies the task's own outcome transition, so a status the
// task cannot reach from running means nothing landed: empty, unknown, or
// still running. Transient, because the cause is environmental -- a State
// Store that refused the transition -- and a retry can record one.
if !taskstate.CanTransition(taskstate.Running, resp.Status) {
reason := noOutcomeReason(resp.Status)
d.Log.ErrorContext(ctx, "taskrun run recorded no outcome", "task", task.ID, "status", resp.Status)
d.parkRunningTask(ctx, task, reason, taskstate.ParkTransient)
return
}
// Reached only past every failure return above, so this is always a
// fully decoded, error-free response -- a version is never recorded off
// a request that never reached an agent, or a response describing a
// parked/errored task.
if resp.AgentVersion != "" {
d.AgentStatus.Observe(resp.AgentVersion, resp.AgentInstallType)
}
d.Log.InfoContext(ctx, "taskrun complete", "task", task.ID, "status", resp.Status)
}
// requestTaskRun publishes the taskrun request, retrying on
// nats.ErrNoResponders until the container subscribes. Other errors return
// at once.
func (d *Daemon) requestTaskRun(ctx context.Context, taskID int64, data []byte) ([]byte, error) {
subject := agentnats.SubjectForTask(taskID)
deadline := time.Now().Add(taskRunReadyTimeout)
backoff := taskRunRetryBackoff
for {
reply, err := d.TaskBus.Request(ctx, subject, data)
if err == nil {
return reply, nil
}
if !errors.Is(err, eventbus.ErrNoResponders) || !time.Now().Before(deadline) {
return nil, err
}
wait := min(backoff, time.Until(deadline))
if wait <= 0 {
return nil, err
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(wait):
}
}
}
// captureAttemptConfig records the attempt's effective configuration as an
// event. Failures are logged.
func (d *Daemon) captureAttemptConfig(ctx context.Context, task *workflow.Task, cfg config.TaskConfig) {
document, err := json.Marshal(cfg)
if err != nil {
d.Log.WarnContext(ctx, "attempt configuration not captured", "task", task.ID, "attempt", task.Attempt, "err", err)
return
}
event := events.Event{
At: time.Now().UTC(),
Kind: events.KindConfigCaptured,
TaskID: task.ID,
Repo: task.Owner + "/" + task.Repo,
Issue: task.IssueNumber,
Workflow: task.Workflow,
Attempt: task.Attempt,
Data: map[string]any{
"schema": events.ConfigCapturedSchema,
// Raw so the document is embedded once, as it was encoded, rather
// than as a string a reader would have to decode again.
"document": json.RawMessage(document),
},
}
id, err := d.Store.InsertEvent(ctx, event)
if err != nil {
d.Log.WarnContext(ctx, "attempt configuration not captured", "task", task.ID, "attempt", task.Attempt, "err", err)
return
}
// The assigned ID tells the event sink to broadcast without inserting a
// duplicate row.
event.ID = id
d.emit(ctx, event)
}
// writeTaskBrief writes task.json, the container's boot-time brief.
func writeTaskBrief(workDir string, task *workflow.Task) error {
return container.WriteTaskJSON(workDir, container.TaskPayload{
ID: task.ID, Owner: task.Owner, Repo: task.Repo,
Number: task.IssueNumber, Title: task.Title, Body: task.Body,
Labels: strings.Split(task.Labels, ","),
Workflow: task.Workflow, Branch: task.Branch, Plan: task.Plan,
Inputs: task.Inputs,
})
}
// noOutcomeReason names why a taskrun reply left the task without an outcome,
// quoting the status so the log line points at what the agent actually said.
func noOutcomeReason(status string) string {
if status == "" {
return "agent returned no status: the run could not record an outcome"
}
return fmt.Sprintf("agent returned unrecognised status %q: the run could not record an outcome", status)
}
const (
// taskRunReadyTimeout is how long requestTaskRun retries a
// nats.ErrNoResponders while a new container has not subscribed yet.
taskRunReadyTimeout = 20 * time.Second
// taskRunRetryBackoff is the delay between those retries.
taskRunRetryBackoff = 250 * time.Millisecond
)
// runFailure names why a taskrun request failed: the container's exit or the
// time limit when either cancelled it, else the request's own error.
func runFailure(ctx context.Context, err error) error {
if cause := context.Cause(ctx); errors.Is(cause, errContainerExited) || errors.Is(cause, errTaskTimeLimit) {
return cause
}
return err
}