| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "path/filepath" |
| 8 | "sync" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 12 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 15 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 16 | ) |
| 17 | |
| 18 | const leaseRenewInterval = 15 * time.Second |
| 19 | |
| 20 | type InstanceAPI interface { |
| 21 | Call(context.Context, string, runnerproto.RunnerRequest, any) error |
| 22 | } |
| 23 | type RunClaim struct { |
| 24 | Assignment runnerproto.Assignment |
| 25 | runnerproto.ClaimResponse |
| 26 | } |
| 27 | type attemptState struct { |
| 28 | Direct bool |
| 29 | Session provider.Session |
| 30 | WorkspacePath string |
| 31 | InFlightAction team.ActionID |
| 32 | Claim RunClaim |
| 33 | Owner ProcessOwner |
| 34 | Agent provider.Agent |
| 35 | Phase string |
| 36 | FailurePhase string |
| 37 | FailureDetail string |
| 38 | FailureReason string |
| 39 | ServiceInterrupted bool |
| 40 | StopError string |
| 41 | SocketPath, CapabilityPath string |
| 42 | Proof *ContainmentProof |
| 43 | Rotation *runnerproto.CredentialRotation |
| 44 | // Authority is deliberately not restored from this record. |
| 45 | } |
| 46 | type SupervisorConfig struct { |
| 47 | Namespaces *containment.Manager |
| 48 | Journal *Journal |
| 49 | API InstanceAPI |
| 50 | Workflow *BugWorkflow |
| 51 | CredentialsPath string |
| 52 | InstallCredentials func(context.Context, runnerproto.CredentialRotation, string) error |
| 53 | } |
| 54 | type Supervisor struct { |
| 55 | leaseDone <-chan struct{} |
| 56 | leaseStop context.CancelFunc |
| 57 | activeRelease func() error |
| 58 | namespaces *containment.Manager |
| 59 | activeProxy *ToolProxy |
| 60 | journal *Journal |
| 61 | api InstanceAPI |
| 62 | workflow *BugWorkflow |
| 63 | clock ElapsedClock |
| 64 | credentialsPath string |
| 65 | installCredentials func(context.Context, runnerproto.CredentialRotation, string) error |
| 66 | mu sync.Mutex |
| 67 | runMu sync.Mutex |
| 68 | activeKey string |
| 69 | activeCancel context.CancelCauseFunc |
| 70 | activeCurrent func(context.Context) error |
| 71 | activeStop runnerproto.RunnerRequest |
| 72 | states map[string]*attemptState |
| 73 | ready bool |
| 74 | } |
| 75 | |
| 76 | func NewSupervisor(c SupervisorConfig) (*Supervisor, error) { |
| 77 | if c.Journal == nil || c.Namespaces == nil || c.API == nil || c.Workflow == nil || !filepath.IsAbs(c.CredentialsPath) || filepath.Clean(c.CredentialsPath) != c.CredentialsPath || c.InstallCredentials == nil { |
| 78 | return nil, provider.ErrContract |
| 79 | } |
| 80 | if c.Workflow.cfg.Witness == nil || c.Workflow.cfg.Workspaces == nil || (c.Workflow.cfg.Namespaces != c.Namespaces || len(c.Workflow.cfg.Launchers) != 2 || c.Workflow.cfg.Launch == nil) || c.Workflow.cfg.Witness.journal != c.Journal { |
| 81 | return nil, provider.ErrContract |
| 82 | } |
| 83 | return &Supervisor{namespaces: c.Namespaces, journal: c.Journal, api: c.API, workflow: c.Workflow, clock: hostClock{}, credentialsPath: c.CredentialsPath, installCredentials: c.InstallCredentials, states: map[string]*attemptState{}}, nil |
| 84 | } |
| 85 | func attemptKey(scope team.Scope, h team.Handle) string { |
| 86 | return runnerproto.EventHash([]any{scope, h.Attempt, h.Fence, h.Runner}) |
| 87 | } |
| 88 | func (s *Supervisor) save(ctx context.Context, r *attemptState) error { |
| 89 | return s.journal.saveState(ctx, "attempt", attemptKey(r.Claim.Scope, r.Claim.Handle), r) |
| 90 | } |
| 91 | func (r *attemptState) request(op string) runnerproto.RunnerRequest { |
| 92 | return runnerproto.RunnerRequest{Version: 2, AssignmentID: r.Claim.Assignment.ID, Scope: r.Claim.Scope, Handle: r.Claim.Handle, RequestID: attemptKey(r.Claim.Scope, r.Claim.Handle) + "/" + op} |
| 93 | } |
| 94 | func (s *Supervisor) Run(ctx context.Context, claim RunClaim) error { |
| 95 | // One active attempt also serializes runner-wide credential rotation. |
| 96 | s.runMu.Lock() |
| 97 | defer s.runMu.Unlock() |
| 98 | if !s.ready || s.namespaces == nil { |
| 99 | return provider.ErrUncertain |
| 100 | } |
| 101 | key := attemptKey(claim.Scope, claim.Handle) |
| 102 | if _, exists := s.states[key]; exists { |
| 103 | return provider.ErrUncertain |
| 104 | } |
| 105 | if err := s.journal.AdmissionAllowed(ctx); err != nil { |
| 106 | return err |
| 107 | } |
| 108 | for _, old := range s.states { |
| 109 | if old.Phase != "contained" { |
| 110 | return provider.ErrUncertain |
| 111 | } |
| 112 | } |
| 113 | now, err := s.clock.Read() |
| 114 | if err != nil { |
| 115 | return err |
| 116 | } |
| 117 | lease, err := newLease(now, claim.LeaseDeadline, claim.AttemptDeadline) |
| 118 | if err != nil { |
| 119 | return err |
| 120 | } |
| 121 | r := &attemptState{Direct: s.namespaces != nil, Claim: claim, Phase: "claimed"} |
| 122 | raw, err := json.Marshal(r) |
| 123 | if err != nil { |
| 124 | return err |
| 125 | } |
| 126 | if _, err = s.journal.db.ExecContext(ctx, "INSERT INTO journal_supervisor(kind,state_key,body) VALUES('attempt',?,?)", key, raw); err != nil { |
| 127 | return provider.ErrUncertain |
| 128 | } |
| 129 | s.states[key] = r |
| 130 | active, cancel := context.WithCancelCause(ctx) |
| 131 | defer cancel(nil) |
| 132 | |
| 133 | s.mu.Lock() |
| 134 | s.activeKey = key |
| 135 | s.activeCancel = cancel |
| 136 | s.activeStop = r.request("stop") |
| 137 | s.mu.Unlock() |
| 138 | defer func() { |
| 139 | s.mu.Lock() |
| 140 | s.activeKey = "" |
| 141 | s.activeCancel = nil |
| 142 | s.activeProxy = nil |
| 143 | s.activeCurrent = nil |
| 144 | s.mu.Unlock() |
| 145 | }() |
| 146 | done := make(chan struct{}) |
| 147 | watchCtx, stopWatch := context.WithCancel(active) |
| 148 | s.leaseStop = stopWatch |
| 149 | s.leaseDone = done |
| 150 | defer stopWatch() |
| 151 | go s.watchLease(watchCtx, cancel, r, lease, done) |
| 152 | err = s.workflow.run(active, s, r, lease) |
| 153 | if err != nil { |
| 154 | err = errors.Join(err, context.Cause(active)) |
| 155 | r.FailurePhase = r.Phase |
| 156 | r.FailureDetail = err.Error() |
| 157 | } |
| 158 | r.ServiceInterrupted = ctx.Err() != nil |
| 159 | cancel(nil) |
| 160 | <-done |
| 161 | cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) |
| 162 | defer cleanupCancel() |
| 163 | return s.finishAttempt(cleanupCtx, r, err) |
| 164 | } |
| 165 | |
| 166 | func (s *Supervisor) finishAttempt(cleanupCtx context.Context, r *attemptState, err error) error { |
| 167 | if err != nil { |
| 168 | r.FailureReason = attemptFailureReason(err) |
| 169 | } |
| 170 | |
| 171 | outcome := "unprocessed" |
| 172 | if err != nil { |
| 173 | outcome = "rejected" |
| 174 | } |
| 175 | bookkeepingErr := s.journal.finishTools(cleanupCtx, r.Claim, outcome) |
| 176 | if err != nil { |
| 177 | if r.Direct && r.InFlightAction != 0 { |
| 178 | q := r.request("lost") |
| 179 | q.ActionID = r.InFlightAction |
| 180 | err = errors.Join(err, s.api.Call(cleanupCtx, "lost", q, nil)) |
| 181 | } else if infrastructureOnly(err, r) { |
| 182 | q := r.request("release") |
| 183 | q.Reason = team.WaitRunnerUnavailable |
| 184 | err = errors.Join(err, s.api.Call(cleanupCtx, "release", q, nil)) |
| 185 | } else { |
| 186 | q := r.request("failed") |
| 187 | q.Result = &team.AttemptResult{Outcome: team.OutcomeFailure, Detail: r.FailureReason} |
| 188 | err = errors.Join(err, s.api.Call(cleanupCtx, "complete", q, nil)) |
| 189 | } |
| 190 | } |
| 191 | _, cleanupErr := s.cleanup(cleanupCtx, r) |
| 192 | if err == nil && cleanupErr == nil && (r.Claim.Assignment.StepKey == "publish" || r.Claim.Brief.Target.Kind == team.TargetProjectRead) { |
| 193 | cleanupErr = s.api.Call(cleanupCtx, "conclude", r.request("conclude"), nil) |
| 194 | } |
| 195 | return errors.Join(err, bookkeepingErr, cleanupErr) |
| 196 | } |
| 197 | func (s *Supervisor) watchLease(ctx context.Context, cancel context.CancelCauseFunc, r *attemptState, l *leaseGuard, done chan struct{}) { |
| 198 | defer close(done) |
| 199 | tick := time.NewTicker(100 * time.Millisecond) |
| 200 | defer tick.Stop() |
| 201 | last, err := s.clock.Read() |
| 202 | if err != nil { |
| 203 | cancel(attemptCancellation{"watchLease.Read", err}) |
| 204 | return |
| 205 | } |
| 206 | renewAt := last.Elapsed + leaseRenewInterval |
| 207 | for { |
| 208 | select { |
| 209 | case <-ctx.Done(): |
| 210 | return |
| 211 | case <-tick.C: |
| 212 | now, err := l.checkClock(s.clock) |
| 213 | if err != nil { |
| 214 | cancel(attemptCancellation{"watchLease.check", err}) |
| 215 | return |
| 216 | } |
| 217 | if now.Elapsed < renewAt { |
| 218 | continue |
| 219 | } |
| 220 | // A blocked renewal never pauses the local lease watchdog. |
| 221 | reply := make(chan error, 1) |
| 222 | go func() { |
| 223 | err := retryAuthority(ctx, func() error { |
| 224 | sent, e := s.clock.Read() |
| 225 | if e != nil { |
| 226 | return e |
| 227 | } |
| 228 | var deadline time.Time |
| 229 | if e = s.api.Call(ctx, "renew", r.request("renew"), &deadline); e != nil { |
| 230 | return e |
| 231 | } |
| 232 | return l.renewClock(s.clock, sent, deadline) |
| 233 | }) |
| 234 | if err == nil { |
| 235 | s.mu.Lock() |
| 236 | current := s.activeCurrent |
| 237 | s.mu.Unlock() |
| 238 | if current != nil { |
| 239 | err = current(ctx) |
| 240 | } |
| 241 | } |
| 242 | reply <- err |
| 243 | }() |
| 244 | for { |
| 245 | select { |
| 246 | case <-ctx.Done(): |
| 247 | return |
| 248 | case err := <-reply: |
| 249 | if err != nil { |
| 250 | if ctx.Err() != nil { |
| 251 | return |
| 252 | } |
| 253 | cancel(attemptCancellation{"watchLease.renew", err}) |
| 254 | return |
| 255 | } |
| 256 | s.mu.Lock() |
| 257 | proxy := s.activeProxy |
| 258 | s.mu.Unlock() |
| 259 | if proxy != nil { |
| 260 | if err = proxy.RenewLease(ctx, l.bound()); err != nil { |
| 261 | cancel(err) |
| 262 | return |
| 263 | } |
| 264 | } |
| 265 | renewAt = now.Elapsed + leaseRenewInterval |
| 266 | goto renewed |
| 267 | case <-tick.C: |
| 268 | _, e := l.checkClock(s.clock) |
| 269 | if e != nil { |
| 270 | cancel(attemptCancellation{"watchLease.checkRenewal", e}) |
| 271 | return |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | renewed: |
| 276 | } |
| 277 | } |
| 278 | } |
| 279 | func (s *Supervisor) Cancel(ctx context.Context, scope team.Scope, h team.Handle) (ContainmentProof, error) { |
| 280 | key := attemptKey(scope, h) |
| 281 | s.mu.Lock() |
| 282 | active := s.activeKey == key && s.activeCancel != nil |
| 283 | cancel := s.activeCancel |
| 284 | stop := s.activeStop |
| 285 | s.mu.Unlock() |
| 286 | var stopErr error |
| 287 | if active { |
| 288 | stopErr = s.api.Call(ctx, "stop", stop, nil) |
| 289 | cancel(attemptCancellation{"Supervisor.Cancel", context.Canceled}) |
| 290 | } |
| 291 | s.runMu.Lock() |
| 292 | defer s.runMu.Unlock() |
| 293 | r := s.states[key] |
| 294 | if r == nil { |
| 295 | return ContainmentProof{}, provider.ErrIdentity |
| 296 | } |
| 297 | // Instance fences first; failure never prevents local stopping. |
| 298 | if !active { |
| 299 | stopErr = s.api.Call(ctx, "stop", r.request("stop"), nil) |
| 300 | } |
| 301 | proof, err := s.cleanup(ctx, r) |
| 302 | return proof, errors.Join(stopErr, err) |
| 303 | } |
| 304 | func (s *Supervisor) cleanup(ctx context.Context, r *attemptState) (ContainmentProof, error) { |
| 305 | if !r.Direct { |
| 306 | return ContainmentProof{}, provider.ErrContainment |
| 307 | } |
| 308 | return s.cleanupDirect(ctx, r) |
| 309 | } |
| 310 | |
| 311 | func (s *Supervisor) reportContainment(ctx context.Context, r *attemptState) (ContainmentProof, error) { |
| 312 | if r.Proof == nil || r.Proof.Version != 2 { |
| 313 | return ContainmentProof{}, provider.ErrUncertain |
| 314 | } |
| 315 | q := r.request("contained") |
| 316 | raw, err := json.Marshal(r.Proof) |
| 317 | if err != nil { |
| 318 | return *r.Proof, err |
| 319 | } |
| 320 | q.Proof = raw |
| 321 | if s.workflow != nil && s.workflow.cfg.Witness != nil { |
| 322 | if err = s.workflow.cfg.Witness.Containment(ctx, r.Claim.Assignment, q); err != nil { |
| 323 | return *r.Proof, err |
| 324 | } |
| 325 | } |
| 326 | var rotation runnerproto.CredentialRotation |
| 327 | if err = s.api.Call(ctx, "contained", q, &rotation); err != nil { |
| 328 | return *r.Proof, err |
| 329 | } |
| 330 | r.Rotation = &rotation |
| 331 | if err = s.save(ctx, r); err != nil { |
| 332 | return *r.Proof, err |
| 333 | } |
| 334 | return s.finishRotation(ctx, r) |
| 335 | } |
| 336 | func (s *Supervisor) finishRotation(ctx context.Context, r *attemptState) (ContainmentProof, error) { |
| 337 | if r.Proof == nil || r.Rotation == nil { |
| 338 | return ContainmentProof{}, provider.ErrUncertain |
| 339 | } |
| 340 | if r.Rotation.Bearer.Token != "" { |
| 341 | if s.credentialsPath == "" || s.installCredentials == nil { |
| 342 | return *r.Proof, provider.ErrContract |
| 343 | } |
| 344 | if err := runnerproto.JournalCredentials(s.credentialsPath, r.Rotation); err != nil { |
| 345 | return *r.Proof, err |
| 346 | } |
| 347 | if err := s.installCredentials(ctx, *r.Rotation, r.request("contained").RequestID); err != nil { |
| 348 | return *r.Proof, err |
| 349 | } |
| 350 | } |
| 351 | r.Phase = "contained" |
| 352 | return *r.Proof, s.save(ctx, r) |
| 353 | } |
| 354 | func (s *Supervisor) Recover(ctx context.Context) error { |
| 355 | s.runMu.Lock() |
| 356 | defer s.runMu.Unlock() |
| 357 | s.ready = false |
| 358 | if s.namespaces != nil { |
| 359 | if _, err := s.journal.ReconcileDirect(ctx, s.namespaces); err != nil { |
| 360 | return err |
| 361 | } |
| 362 | } |
| 363 | var states []attemptState |
| 364 | if err := s.journal.readStates(ctx, "attempt", &states); err != nil { |
| 365 | return err |
| 366 | } |
| 367 | var failures error |
| 368 | for i := range states { |
| 369 | r := &states[i] |
| 370 | if !r.Direct && r.Phase != "contained" { |
| 371 | failures = errors.Join(failures, s.api.Call(ctx, "stop", r.request("stop"), nil), provider.ErrContainment) |
| 372 | continue |
| 373 | } |
| 374 | failures = errors.Join(failures, s.journal.finishTools(ctx, r.Claim, "interrupted")) |
| 375 | s.states[attemptKey(r.Claim.Scope, r.Claim.Handle)] = r |
| 376 | if restore, ok := s.api.(interface{ RestoreClaim(RunClaim) error }); ok { |
| 377 | failures = errors.Join(failures, restore.RestoreClaim(r.Claim)) |
| 378 | } |
| 379 | if r.Claim.Brief.Target.Kind == team.TargetProjectRead && r.Phase == "delivering-answer" { |
| 380 | if err := s.recoverReadAnswer(ctx, r); err != nil { |
| 381 | failures = errors.Join(failures, err) |
| 382 | continue |
| 383 | } |
| 384 | } |
| 385 | if r.Phase != "contained" { |
| 386 | if r.Direct { |
| 387 | if r.InFlightAction != 0 { |
| 388 | q := r.request("lost") |
| 389 | q.ActionID = r.InFlightAction |
| 390 | failures = errors.Join(failures, s.api.Call(ctx, "lost", q, nil)) |
| 391 | } |
| 392 | } |
| 393 | if r.Phase != "completed" && r.Phase != "prepared" && r.Phase != "verified" { |
| 394 | stopErr := s.api.Call(ctx, "stop", r.request("stop"), nil) |
| 395 | if stopErr != nil { |
| 396 | r.StopError = stopErr.Error() |
| 397 | failures = errors.Join(failures, s.save(ctx, r)) |
| 398 | } |
| 399 | } |
| 400 | if _, err := s.cleanup(ctx, r); err != nil { |
| 401 | failures = errors.Join(failures, err) |
| 402 | continue |
| 403 | } |
| 404 | } |
| 405 | if (r.Claim.Assignment.StepKey == "publish" || r.Claim.Brief.Target.Kind == team.TargetProjectRead) && r.FailurePhase == "" { |
| 406 | failures = errors.Join(failures, s.api.Call(ctx, "conclude", r.request("conclude"), nil)) |
| 407 | } |
| 408 | } |
| 409 | for { |
| 410 | pending, err := s.journal.Pending(ctx, 128) |
| 411 | if err != nil { |
| 412 | failures = errors.Join(failures, err) |
| 413 | break |
| 414 | } |
| 415 | if len(pending) == 0 { |
| 416 | break |
| 417 | } |
| 418 | var batchErr error |
| 419 | for _, e := range pending { |
| 420 | raw, err := runnerproto.Marshal(e) |
| 421 | if err != nil { |
| 422 | batchErr = errors.Join(batchErr, err) |
| 423 | continue |
| 424 | } |
| 425 | q := runnerproto.RunnerRequest{Version: 2, AssignmentID: e.AssignmentID, Scope: e.Scope, Handle: e.Handle, RequestID: e.ID, ActionID: e.ActionID, Event: raw} |
| 426 | if err := s.api.Call(ctx, "events", q, nil); err != nil { |
| 427 | batchErr = errors.Join(batchErr, err) |
| 428 | continue |
| 429 | } |
| 430 | batchErr = errors.Join(batchErr, s.journal.Ack(ctx, e.ID)) |
| 431 | } |
| 432 | if batchErr != nil { |
| 433 | failures = errors.Join(failures, batchErr) |
| 434 | break |
| 435 | } |
| 436 | } |
| 437 | s.ready = failures == nil |
| 438 | return failures |
| 439 | } |
| 440 | |
| 441 | func (s *Supervisor) stopLeaseWatch() { |
| 442 | if s.leaseStop != nil { |
| 443 | s.leaseStop() |
| 444 | <-s.leaseDone |
| 445 | } |
| 446 | } |
| 447 | |