package runner import ( "context" "encoding/json" "errors" "time" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) type namespaceAdmissionKey struct{} type namespaceState struct { LaunchAcknowledged bool Owner string Record containment.Record Proof *containment.Proof } func (s *Supervisor) namespaceContext(ctx context.Context, r *attemptState) context.Context { owner := attemptKey(r.Claim.Scope, r.Claim.Handle) return context.WithValue(ctx, namespaceAdmissionKey{}, func(ctx context.Context, record containment.Record) error { if err := s.journal.saveState(ctx, "namespace", record.ID, namespaceState{Owner: owner, Record: record}); err != nil { return err } if record.HostPID == 0 { return nil } n := runnerproto.NamespaceLaunch{ID: record.ID, AttemptKey: record.AttemptKey, OwnerKey: owner, BootID: record.BootID, NamespaceID: record.NamespaceID, ManifestHash: record.ManifestHash, PolicyHash: record.PolicyHash, HostPID: record.HostPID, StartTicks: record.StartTicks} if err := s.namespaceEvent(ctx, r, "namespace.launch", record.AttemptKey, record.ID, n); err != nil { return err } return s.journal.saveState(ctx, "namespace", record.ID, namespaceState{Owner: owner, Record: record, LaunchAcknowledged: true}) }) } func (s *Supervisor) namespaceEvent(ctx context.Context, r *attemptState, kind, agent, session string, payload any) error { e := Event{Version: 2, ID: runnerproto.EventHash([]string{kind, agent, session}), TaskID: r.Claim.Assignment.TaskID, AssignmentID: r.Claim.Assignment.ID, Scope: r.Claim.Scope, Handle: r.Claim.Handle, ServerID: "direct", AgentID: agent, SessionID: session, Kind: kind, Payload: marshal(payload), SourceTime: time.Now().UTC(), Isolation: r.Claim.Assignment.Selection.Isolation} var old []byte if err := s.journal.db.QueryRowContext(ctx, "SELECT body FROM journal_events WHERE event_key=?", e.DedupKey()).Scan(&old); err == nil { var saved Event if json.Unmarshal(old, &saved) != nil { return ErrJournal } e.SourceTime = saved.SourceTime } pump := EventPump{Journal: s.journal, Contain: func(context.Context) error { return provider.ErrContainment }} if err := pump.Append(ctx, e, nil); err != nil { return err } q := r.request(e.ID) q.RequestID = e.ID q.Event, _ = runnerproto.Marshal(e) if err := s.api.Call(ctx, "events", q, nil); err != nil { return err } return s.journal.Ack(ctx, e.ID) } func (s *Supervisor) cleanupDirect(ctx context.Context, r *attemptState) (ContainmentProof, error) { proof := ContainmentProof{Version: 2, Scope: r.Claim.Scope, Handle: r.Claim.Handle, CheckedAt: time.Now().UTC()} if r.Phase == "contained" && r.Proof != nil { return *r.Proof, nil } if r.Rotation != nil { return s.finishRotation(ctx, r) } if r.Phase == "verified" && r.Proof != nil { return s.reportContainment(ctx, r) } if s.namespaces == nil { return proof, provider.ErrContainment } s.mu.Lock() proxy := s.activeProxy s.mu.Unlock() if proxy != nil { if err := proxy.Close(); err != nil { return proof, err } } var states []namespaceState if err := s.journal.readStates(ctx, "namespace", &states); err != nil { return proof, err } var failures error checkWorkspaces := map[string]bool{} for _, n := range states { if n.Owner != attemptKey(r.Claim.Scope, r.Claim.Handle) { continue } p, err := s.namespaces.Stop(ctx, n.Record.ID) if err != nil { p, err = s.namespaces.Recover(ctx, n.Record) } if err != nil || !p.Verified { failures = errors.Join(failures, provider.ErrContainment, err) continue } if err = s.journal.validateDirectRecord(ctx, p.Record); err != nil { failures = errors.Join(failures, err) continue } n.Proof = &p if err = s.journal.saveState(ctx, "namespace", n.Record.ID, n); err != nil { failures = errors.Join(failures, err) continue } if _, err = s.journal.db.ExecContext(ctx, "UPDATE direct_attempts SET contained=1 WHERE attempt=?", n.Record.AttemptKey); err != nil { failures = errors.Join(failures, err) continue } if s.workflow != nil { var raw []byte var launch provider.Launch if err = s.journal.db.QueryRowContext(ctx, "SELECT launch FROM direct_attempts WHERE attempt=?", n.Record.AttemptKey).Scan(&raw); err != nil { failures = errors.Join(failures, err) continue } if json.Unmarshal(raw, &launch) != nil { failures = errors.Join(failures, ErrJournal) continue } if launch.Policy.IsCheck() { checkWorkspaces[launch.Workspace] = true } } if n.Record.HostPID != 0 { exit := runnerproto.NamespaceExit{ID: p.Record.ID, AttemptKey: p.Record.AttemptKey, BootID: p.Record.BootID, NamespaceID: p.Record.NamespaceID, ManifestHash: p.Record.ManifestHash, HostPID: p.Record.HostPID, StartTicks: p.Record.StartTicks, ExitCode: p.Exit.Code, Signal: p.Exit.Signal, ObservedAt: p.Exit.ObservedAt} if n.LaunchAcknowledged { proof.Namespaces = append(proof.Namespaces, exit) } else { proof.Unstarted = append(proof.Unstarted, exit) id := runnerproto.EventHash([]string{"namespace.launch", n.Record.AttemptKey, n.Record.ID}) if err = s.journal.deadLetterLaunch(ctx, id); err != nil { failures = errors.Join(failures, err) } } } } if failures != nil { return proof, failures } for work := range checkWorkspaces { if err := s.workflow.cfg.Workspaces.RemoveCheck(work); err != nil { return proof, err } } if s.activeRelease != nil { if err := s.activeRelease(); err != nil { return proof, err } s.activeRelease = nil } if s.workflow != nil && r.WorkspacePath != "" { if err := s.workflow.cfg.Workspaces.Remove(ctx, r.Claim.Assignment, r.WorkspacePath); err != nil { return proof, err } } proof.CheckedAt = time.Now().UTC() r.Proof = &proof r.Phase = "verified" if err := s.save(ctx, r); err != nil { return proof, err } return s.reportContainment(ctx, r) } func (j *Journal) deadLetterLaunch(ctx context.Context, id string) error { tx, err := j.db.BeginTx(ctx, nil) if err != nil { return err } defer tx.Rollback() if _, err = tx.ExecContext(ctx, "INSERT OR IGNORE INTO journal_supervisor(kind,state_key,body) SELECT 'unstarted-launch',id,body FROM journal_events WHERE id=?", id); err != nil { return err } if _, err = tx.ExecContext(ctx, "UPDATE journal_events SET acked=1 WHERE id=?", id); err != nil { return err } return tx.Commit() }