oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package mac
2
3import (
4 "cmp"
5 "context"
6 "errors"
7 "io"
8 "os"
9 "os/exec"
10 "slices"
11 "strconv"
12 "strings"
13 "sync"
14 "syscall"
15 "time"
16
17 "amadan.net/oficina/equipo/internal/runner/containment"
18 "amadan.net/oficina/equipo/internal/runner/mac/proc"
19 "amadan.net/oficina/equipo/internal/runner/provider"
20 "amadan.net/oficina/equipo/internal/runner/provider/claude"
21)
22
23// The Mac's executor (spec §5 and §8.8): what a check, an Engineering
24// attempt, an ask, a token check, a sign-in or a probe launch starts,
25// and how its end is proven. The gate and the CLI launches share it.
26
27// ErrRecord says a process record could not be written: when it was the
28// marker, nothing started.
29var ErrRecord = errors.New("mac: the process record could not be written")
30
31// ErrUnproven says a process was started and stopped but its end is not
32// proven: the attempt stays unterminated (no Retry).
33var ErrUnproven = errors.New("mac: the end is not proven")
34
35// Executor starts an operation's processes and proves their end.
36type Executor struct {
37 // Turns is the Mac's turns: Start refuses unless ctx holds one
38 // (ErrNoTurn). nil holds no machine lock (the test build's fake
39 // worker on Linux).
40 Turns *Turns
41 // Procs is the process table; nil: the turns' sweep table, else the
42 // platform's.
43 Procs Procs
44 // Own is the runner's own processes; nil: this process's.
45 Own *Own
46 // Grace is SIGTERM to SIGKILL (10 s); Settle bounds the whole stop
47 // and its proof (30 s); Poll is how often the tree under the leader
48 // is read while it runs (250 ms); CleanLimit is how much longer than
49 // the stop's deadline the user-temp cleanup may take (3 minutes: a
50 // simulator shutdown).
51 Grace, Settle, Poll, CleanLimit time.Duration
52 // UserTemp is the runner user's T when the attempt may write it (a
53 // sandboxed check, Engineering with sandboxed Xcode access): what
54 // appears there while it runs is removed once its end is proven.
55 UserTemp string
56 // QuietSimulators runs once the end is proven, before T is cleaned
57 // (simctl shutdown all: every simulator of the runner user is its).
58 QuietSimulators func(context.Context)
59 // Unsandboxed: what this runs is repository or model-chosen code
60 // outside a sandbox (an unsandboxed check).
61 Unsandboxed bool
62}
63
64// Command is what to start: Argv with Env as its whole environment, in
65// Dir, Files as descriptors 3 and on. With Pipes the run offers its
66// stdin, stdout and stderr; otherwise Stdout and Stderr receive the
67// output and stdin is empty. TTY (a sign-in's) is the leader's stdin,
68// stdout, stderr and controlling terminal instead.
69type Command struct {
70 Argv, Env []string
71 Dir string
72 Files []*os.File
73 Pipes bool
74 Stdout, Stderr io.Writer
75 TTY *os.File
76}
77
78func (x *Executor) procs() Procs {
79 switch {
80 case x.Procs != nil:
81 return x.Procs
82 case x.Turns != nil && x.Turns.sweep != nil:
83 return x.Turns.sweep
84 }
85 return platformProcs
86}
87
88func (x *Executor) own() *Own {
89 if x.Own != nil {
90 return x.Own
91 }
92 return x.Turns.owned()
93}
94
95// cleanLimit bounds the user-temp cleanup (a simulator shutdown).
96func (x *Executor) cleanLimit() time.Duration { return cmp.Or(x.CleanLimit, 3*time.Minute) }
97
98// StopBudget is the most a stopped run's Wait takes: the proof, then the cleanup.
99func (x *Executor) StopBudget() time.Duration { return x.settleLimit() + x.cleanLimit() }
100
101func (x *Executor) settleLimit() time.Duration { return cmp.Or(max(x.Settle, 0), 30*time.Second) }
102
103// validMarker: a marker fits a record ("pg:<pgid>:<marker>") and a
104// ps -E word.
105func validMarker(m string) bool {
106 return m != "" && len(m) <= 128 && !strings.ContainsAny(m, " \t\n\r\x00:=")
107}
108
109// Start starts c as attempt marker, recorded in this order (record is
110// the step's or question's row): the marker on the turn's record and on
111// the row before anything starts (if either cannot be written nothing
112// starts: ErrRecord); the group once the leader exists (if that cannot
113// be written the group is stopped at once and Start fails, ErrUnproven
114// when that end is not proven either). The leader starts in a session
115// and group of its own.
116func (x *Executor) Start(ctx context.Context, c Command, marker string, record func(string) error) (*Run, error) {
117 var turn *Turn
118 if x.Turns != nil {
119 if turn = HeldTurn(ctx, x.Turns); turn == nil {
120 return nil, ErrNoTurn
121 }
122 if x.Unsandboxed {
123 // On record before anything of it starts.
124 if err := turn.markUnsandboxed(); err != nil {
125 return nil, errors.Join(ErrRecord, err)
126 }
127 }
128 }
129 if len(c.Argv) == 0 || !validMarker(marker) {
130 return nil, provider.ErrPolicy
131 }
132 r := &Run{x: x, turn: turn, marker: marker, procs: x.procs(), own: x.own(), exited: make(chan struct{}), stopPoll: make(chan struct{}), polled: make(chan struct{}), aborted: make(chan struct{})}
133 var before []ProcID
134 if turn != nil {
135 // A sweeping turn's table is the run's: the identities it read
136 // when the turn began are compared with the same clock.
137 if before = turn.before(); before != nil {
138 r.procs = x.Turns.sweep
139 }
140 }
141 r.scope = newScope(r.procs, []string{marker}, before)
142 var began time.Time
143 var bootID string
144 if turn != nil {
145 turn.mu.Lock()
146 began, bootID = turn.rec.Began, turn.rec.BootID
147 turn.mu.Unlock()
148 }
149 // What T holds before anything of the attempt starts, and the
150 // cleanup on record: a runner killed from here on leaves it to the
151 // next process (a restart), never to another turn of this one.
152 if x.UserTemp != "" {
153 if err := x.finishPending(ctx, turn, time.Now().Add(x.settleLimit()), time.Now().Add(x.settleLimit()+x.cleanLimit())); err != nil {
154 return nil, err
155 }
156 temp, err := openTemp(x.UserTemp, nil)
157 if err != nil {
158 return nil, err
159 }
160 r.temp = temp
161 if err := x.Turns.writePending(pendingRecord{Attempt: marker, Before: temp.before, Runner: proc.Self(), Began: began, BootID: bootID}); err != nil {
162 temp.close()
163 return nil, errors.Join(ErrRecord, err)
164 }
165 }
166 fail := func(err error) (*Run, error) {
167 if r.temp != nil {
168 r.temp.close()
169 }
170 return nil, err
171 }
172 if turn != nil {
173 if err := turn.launch(marker); err != nil {
174 return fail(errors.Join(ErrRecord, err))
175 }
176 }
177 if err := record(RecordID(0, marker)); err != nil {
178 return fail(errors.Join(ErrRecord, err))
179 }
180 cmd := exec.Command(c.Argv[0], c.Argv[1:]...)
181 cmd.Dir, cmd.Env, cmd.ExtraFiles = c.Dir, slices.Clone(c.Env), c.Files
182 if cmd.Env == nil {
183 cmd.Env = []string{}
184 }
185 if c.Pipes {
186 var err error
187 if r.stdin, err = cmd.StdinPipe(); err != nil {
188 return fail(err)
189 }
190 if r.stdout, err = cmd.StdoutPipe(); err != nil {
191 return fail(err)
192 }
193 if r.stderr, err = cmd.StderrPipe(); err != nil {
194 return fail(err)
195 }
196 } else {
197 cmd.Stdout, cmd.Stderr = c.Stdout, c.Stderr
198 // A child that keeps the output open must not hold the run: once
199 // the leader has gone the pipes close after a second, and the
200 // stop kills what is left.
201 cmd.WaitDelay = time.Second
202 }
203 cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: c.TTY != nil}
204 if c.TTY != nil {
205 cmd.Stdin, cmd.Stdout, cmd.Stderr = c.TTY, c.TTY, c.TTY
206 }
207 if err := cmd.Start(); err != nil {
208 return fail(err)
209 }
210 r.cmd, r.pgid = cmd, cmd.Process.Pid
211 go func() {
212 r.waitErr = cmd.Wait()
213 close(r.exited)
214 }()
215 // The leader, its group and its session are the attempt's from now:
216 // what has that id and started later is someone else's.
217 r.scope.Groups[r.pgid], r.scope.Sessions[r.pgid] = 0, 0
218 r.leaderPending = true
219 if leader, ok := r.procs.Lookup(r.pgid); ok {
220 r.adopt([]ProcInfo{leader})
221 }
222 if r.temp != nil {
223 _ = x.Turns.writePending(pendingRecord{Attempt: marker, PGID: r.pgid, Before: r.temp.before, Runner: proc.Self(), Began: began, BootID: bootID})
224 }
225 var noted error
226 if turn != nil {
227 noted = turn.note(r.scope.Groups, r.scope.Sessions)
228 }
229 if err := errors.Join(noted, record(RecordID(r.pgid, marker))); err != nil {
230 r.pollOnce.Do(func() { close(r.stopPoll) })
231 close(r.polled)
232 proven := r.stopWith(0)
233 r.stopOnce.Do(func() { r.proven = proven })
234 if !proven && turn != nil {
235 turn.unprovenEnd()
236 }
237 if !r.Finish(context.WithoutCancel(ctx)) {
238 proven = false
239 }
240 if !proven {
241 return nil, errors.Join(ErrRecord, ErrUnproven, err)
242 }
243 return nil, errors.Join(ErrRecord, err)
244 }
245 go r.poll()
246 return r, nil
247}
248
249// Run is one started attempt.
250type Run struct {
251 x *Executor
252 turn *Turn
253 marker string
254 cmd *exec.Cmd
255 pgid int
256 procs Procs
257 own *Own
258
259 mu sync.Mutex
260 scope *scope
261 // leaderPending: the leader's identity is not read yet (the kernel
262 // may show it a moment after the exec).
263 leaderPending bool
264
265 exited chan struct{}
266 waitErr error
267
268 stopPoll, polled chan struct{}
269 // unwritten is the turn record's last failed write: the operation is
270 // stopped and its proof withheld until a write succeeds.
271 unwritten error
272 abortOnce sync.Once
273 // aborted closes when the operation is stopped on its own (its
274 // turn's record could not be written).
275 aborted chan struct{}
276 pollOnce sync.Once
277 stopOnce sync.Once
278 proven bool
279
280 temp *tempState
281 finishOnce sync.Once
282 // cleaned: Finish's cleanup is done.
283 cleaned bool
284
285 stdin io.WriteCloser
286 stdout, stderr io.ReadCloser
287}
288
289// ID is the attempt's process record.
290func (r *Run) ID() string { return RecordID(r.pgid, r.marker) }
291
292// Exited is closed once the leader has exited (and been reaped).
293func (r *Run) Exited() <-chan struct{} { return r.exited }
294
295// Aborted is closed when the run stopped itself (its turn's record
296// could not be written).
297func (r *Run) Aborted() <-chan struct{} { return r.aborted }
298
299// ExitErr is the leader's exit (after Exited).
300func (r *Run) ExitErr() error { return r.waitErr }
301
302// adopt takes the leader's identity from list the first time it shows
303// (still unreaped: the pid is still the leader's), with its group and
304// session from its start. Under r.mu, or before the run is shared.
305func (r *Run) adopt(list []ProcInfo) {
306 if !r.leaderPending {
307 return
308 }
309 select {
310 case <-r.exited:
311 r.leaderPending = false
312 return
313 default:
314 }
315 for _, q := range list {
316 if q.PID == r.pgid {
317 r.scope.Seen[q.ID] = true
318 r.scope.Groups[r.pgid], r.scope.Sessions[r.pgid] = q.Start, q.Start
319 r.leaderPending = false
320 return
321 }
322 }
323}
324
325// poll is (a): while the attempt runs, the tree under its leader, and
326// every group and session it makes, onto the scope and the turn's record.
327func (r *Run) poll() {
328 defer close(r.polled)
329 every := r.x.Poll
330 if every <= 0 {
331 every = 250 * time.Millisecond
332 }
333 tick := time.NewTicker(every)
334 defer tick.Stop()
335 for {
336 list, own, err := r.own.Snapshot(time.Now().Add(every), r.procs, nil)
337 if err == nil {
338 r.mu.Lock()
339 r.adopt(list)
340 grew := r.scope.Track(list, own)
341 groups, sessions := r.scope.Groups.Clone(), r.scope.Sessions.Clone()
342 failed := r.unwritten != nil
343 r.mu.Unlock()
344 if (grew || failed) && r.turn != nil {
345 err := r.turn.note(groups, sessions)
346 r.mu.Lock()
347 r.unwritten = err
348 r.mu.Unlock()
349 if err != nil {
350 // What the attempt made is not on record for a
351 // restart: the attempt goes now.
352 r.abortOnce.Do(func() {
353 close(r.aborted)
354 go r.Stop()
355 })
356 }
357 }
358 }
359 select {
360 case <-r.stopPoll:
361 return
362 case <-tick.C:
363 }
364 }
365}
366
367// Stop ends the attempt and reports whether its end is proven (once;
368// later calls report the same): SIGTERM to everything in its scope
369// (its group, the groups and sessions it made, what descends from it,
370// what carries its marker and, on a Mac, every process of the runner
371// user started since the turn began but the runner's own and launchd's
372// system agents), Grace, then SIGKILL, each signal after the process's
373// identity is read again. Proven only when, within Settle, none of that
374// is left, the leader is reaped and every group it made is gone
375// (kill(-pgid, 0) is ESRCH). Unproven, the turn's record stays.
376func (r *Run) Stop() bool {
377 r.stopOnce.Do(func() {
378 r.pollOnce.Do(func() { close(r.stopPoll) })
379 <-r.polled
380 grace := r.x.Grace
381 if grace <= 0 {
382 grace = 10 * time.Second
383 }
384 r.proven = r.stopWith(grace)
385 if !r.proven && r.turn != nil {
386 r.turn.unprovenEnd()
387 }
388 })
389 return r.proven
390}
391
392func (r *Run) stopWith(grace time.Duration) bool {
393 reaped := func() bool {
394 select {
395 case <-r.exited:
396 return true
397 default:
398 return false
399 }
400 }
401 deadline := time.Now().Add(r.x.settleLimit())
402 out := r.scope.Settle(r.own, deadline, grace, reaped, r.adopt)
403 if r.turn == nil {
404 return out == proc.Proven && time.Now().Before(deadline)
405 }
406 // Proven only with everything it made durably on record (a restart
407 // must find the same).
408 killed := make([]ProcID, 0, len(r.scope.Killed))
409 for id := range r.scope.Killed {
410 killed = append(killed, id)
411 }
412 err := r.turn.finish(r.marker, r.scope.Groups, r.scope.Sessions, killed)
413 r.mu.Lock()
414 r.unwritten = err
415 r.mu.Unlock()
416 // The deadline covers the final note (its write and fsync) too.
417 if out != proc.Proven || err != nil || !time.Now().Before(deadline) {
418 r.turn.unprovenEnd()
419 return false
420 }
421 return true
422}
423
424// Finish is the user-temp cleanup once the end is proven: simulators
425// quieted, what appeared in T removed, then the record, within
426// CleanLimit read after the last; done (or nothing to clean) or not.
427// Failed or late, the pending and turn records stay for Verify.
428func (r *Run) Finish(ctx context.Context) bool {
429 r.finishOnce.Do(func() {
430 if r.temp == nil {
431 r.cleaned = true
432 return
433 }
434 defer r.temp.close()
435 if !r.proven {
436 return
437 }
438 by := time.Now().Add(r.x.cleanLimit())
439 qctx, cancel := context.WithDeadline(context.WithoutCancel(ctx), by)
440 defer cancel()
441 if r.x.QuietSimulators != nil {
442 r.x.QuietSimulators(qctx)
443 }
444 r.cleaned = r.temp.clean() == nil && time.Now().Before(by) && r.x.Turns.dropPending() == nil && time.Now().Before(by)
445 if !r.cleaned && r.turn != nil {
446 r.turn.unprovenEnd()
447 }
448 })
449 return r.cleaned
450}
451
452// finishPending finishes the user-temp cleanup an earlier attempt left,
453// only when it is turn's to finish (Turns.mayFinish: its owner, or a
454// restart): that attempt's end proven (proc.SettleMarked), its simulators
455// shut down, then T cleaned against what it held before. Another live
456// owner's: ErrPendingCleanup, nothing touched. The proof is due by
457// settleBy, the rest by cleanBy.
458func (x *Executor) finishPending(ctx context.Context, turn *Turn, settleBy, cleanBy time.Time) error {
459 r, ok, err := x.Turns.readPending()
460 if err != nil || !ok {
461 return err
462 }
463 if !x.Turns.mayFinish(turn, r) {
464 return ErrPendingCleanup
465 }
466 // SettleMarked refuses a proof once settleBy has passed (its last
467 // act): the cleanup's proof read is under the caller's deadline.
468 // An attempt of an earlier boot is over (its group id is this boot's
469 // to use); otherwise its end is proven first.
470 b, berr := x.Turns.bootNow()
471 if !proc.Rebooted(r.BootID, r.Began, b, berr) && !proc.SettleMarked(x.procs(), x.own(), r.PGID, r.Attempt, settleBy) {
472 // That attempt's end, not this one's: nothing of this one ran.
473 return errors.Join(ErrPendingCleanup, errors.New("mac: its end is not proven"))
474 }
475 // Bounded by cleanBy: past it the record stays and a later call
476 // continues (shutting simulators down and cleaning T again is safe).
477 qctx, cancel := context.WithDeadline(context.WithoutCancel(ctx), cleanBy)
478 defer cancel()
479 if x.QuietSimulators != nil {
480 x.QuietSimulators(qctx)
481 }
482 s, err := openTemp(x.UserTemp, r.Before)
483 if err != nil {
484 return err
485 }
486 defer s.close()
487 if err := s.clean(); err != nil {
488 return err
489 }
490 if !time.Now().Before(cleanBy) || x.Turns.dropPending() != nil || !time.Now().Before(cleanBy) {
491 return errors.Join(ErrPendingCleanup, errors.New("mac: the cleanup failed or outlasted its bound"))
492 }
493 return nil
494}
495
496// RecordID is the process record of an attempt: its group and marker.
497func RecordID(pgid int, attempt string) string { return "pg:" + strconv.Itoa(pgid) + ":" + attempt }
498
499// Verify reports whether a recorded attempt has ended for sure (after a
500// restart, or for a step whose end was not proven when it stopped):
501//
502// - if its turn's record is still unsettled, a turn is taken (only
503// if free now) and settles it first: everything that turn left, by
504// its sweep;
505//
506// - every process carrying its marker is killed, and its recorded
507// group only while a marked process is in it. A group alive with no
508// marked process (a child that scrubbed its environment, or the id
509// used again by someone else) is never killed and never proven over;
510//
511// - a user-temp cleanup the attempt owns is finished in that turn.
512//
513// - whatever its turn still owes (a group, session or process another
514// user now holds: never signalled) must be gone.
515//
516// Ended only when the group is gone (kill(-pgid, 0) is ESRCH), nothing
517// carries the marker, its turn is settled and owes nothing, and its
518// cleanup is done. It only reads what consumers rely on: after a
519// reboot it keeps a completion that every later proof of the
520// record reads, until each consumer has acknowledged it (Acknowledge).
521func (x *Executor) Verify(id string) bool {
522 pgid, attempt, ok := proc.ParseRecord(id)
523 if !ok {
524 return false
525 }
526 deadline := time.Now().Add(x.settleLimit())
527 var held *Turn
528 if x.Turns != nil {
529 r, pending, err := x.Turns.readPending()
530 owned := x.UserTemp != "" && (err != nil || pending && r.Attempt == attempt)
531 if x.Turns.unsettledFor(attempt) || owned || x.Turns.debts.Owes(attempt) {
532 u, ok := x.Turns.tryTakeBy(OpRecover, deadline)
533 if !ok {
534 return false
535 }
536 defer u.Give()
537 u.adopt(attempt)
538 held = u
539 }
540 }
541 // What the attempt owes: judged holding the turn, under the one
542 // deadline; nothing goes unless the whole proof holds.
543 rebooted, met := false, true
544 if held != nil {
545 var err error
546 if rebooted, met, err = x.Turns.clearOwed(held, attempt, deadline); err != nil {
547 return false
548 }
549 }
550 if held != nil && !rebooted {
551 // The pending cleanup's record keeps the attempt's boot when its
552 // turn's record is gone (settled, then the cleanup failed again).
553 r, pending, err := x.Turns.readPending()
554 b, berr := x.Turns.bootNow()
555 rebooted = err == nil && pending && r.Attempt == attempt && proc.Rebooted(r.BootID, r.Began, b, berr)
556 }
557 // A reboot is a boot-qualified clearance: the old boot's group id is
558 // this boot's to use, and nothing is signalled.
559 if !met || !rebooted && !proc.SettleMarked(x.procs(), x.own(), pgid, attempt, deadline) || !time.Now().Before(deadline) {
560 return false
561 }
562 if held != nil && x.UserTemp != "" {
563 r, pending, err := x.Turns.readPending()
564 if err != nil {
565 return false
566 }
567 if pending && r.Attempt == attempt {
568 // The cleanup's own bound, the final save's too.
569 cleanBy := time.Now().Add(x.cleanLimit())
570 if x.finishPending(context.Background(), held, deadline, cleanBy) != nil {
571 return false
572 }
573 deadline = cleanBy
574 }
575 }
576 if x.Turns == nil {
577 return true
578 }
579 var err error
580 if b, berr := x.Turns.bootNow(); rebooted {
581 // Kept for every consumer (and any later proof) of the record.
582 err = errors.Join(berr, x.Turns.debts.Complete(attempt, b.ID, deadline))
583 } else {
584 err = x.Turns.debts.Discharge(attempt, deadline)
585 }
586 return err == nil && time.Now().Before(deadline)
587}
588
589// Acknowledge: consumer (ConsumerStep, ConsumerKeychain) has durably
590// kept what Verify proved of id, so its share of a reboot's completion
591// may go. Call it only after that consumer's own result is committed.
592func (x *Executor) Acknowledge(id, consumer string) {
593 if _, attempt, ok := proc.ParseRecord(id); ok && x.Turns != nil {
594 _ = x.Turns.debts.Acknowledge(attempt, consumer, []string{ConsumerStep, ConsumerKeychain})
595 }
596}
597
598// The consumers of a record's proof (Acknowledge): the step's recovery
599// and the credential (Keychain) recovery.
600const (
601 ConsumerStep = "step"
602 ConsumerKeychain = "keychain"
603)
604
605// Marked lists this user's processes whose environment carries
606// EQUIPO_ATTEMPT=<attempt> where the kernel shows it (proc.Marked).
607func Marked(attempt string) ([]Proc, error) { return proc.Marked(attempt) }
608
609// Starter is thin's starter (containment.Manager's StartRecorded) for
610// one Mac launch of the pinned CLI: Engineering, an ask or a token
611// check. It runs LaunchEngineering with Exec as its executor, so the
612// marker is on record before the CLI starts and its group once it
613// exists. ctx must hold the Mac's turn (Turns.Take with the
614// operation's Op). Cancelling ctx stops the launch.
615type Starter struct {
616 Exec *Executor
617 CLI ClaudeCLI
618 Input EngineeringInput
619 // Token is the connection's token, cleared once handed over.
620 Token []byte
621}
622
623// StartRecorded starts the policy's CLI: argv must be the policy's own.
624func (s *Starter) StartRecorded(ctx context.Context, l provider.Launch, argv []string, record func(context.Context, containment.Record) error) (provider.Process, error) {
625 defer clear(s.Token)
626 if want := claude.DarwinArgv(l.Policy); want == nil || !slices.Equal(argv, want) {
627 return nil, provider.ErrPolicy
628 }
629 var run *Run
630 err := LaunchEngineering(ctx, s.CLI, s.Input, l.Policy, s.Token, func(ctx context.Context, c EngineeringCommand) error {
631 r, err := s.Exec.Start(ctx, Command{Argv: c.Argv, Env: c.Env, Dir: c.Dir, Files: c.Files, Pipes: true}, s.Input.Attempt, func(id string) error {
632 return record(context.WithoutCancel(ctx), containment.Record{ID: id})
633 })
634 run = r
635 return err
636 })
637 if err != nil {
638 return nil, err
639 }
640 p := &process{run: run}
641 p.stop = context.AfterFunc(ctx, func() { run.Stop() })
642 return p, nil
643}
644
645// process is a Run as thin's provider.Process: Wait returns once the
646// leader has exited or the launch's ctx was cancelled, and the end is
647// proven with the user-temp cleanup done (nil) or not (ErrUnproven).
648type process struct {
649 run *Run
650 stop func() bool
651}
652
653func (p *process) Stdin() io.WriteCloser { return p.run.stdin }
654func (p *process) Stdout() io.ReadCloser { return p.run.stdout }
655func (p *process) Stderr() io.ReadCloser { return p.run.stderr }
656func (p *process) ID() string { return p.run.ID() }
657func (p *process) Wait(ctx context.Context) (provider.Exit, error) {
658 select {
659 case <-p.run.exited:
660 case <-p.run.stopPoll:
661 case <-p.run.aborted:
662 case <-ctx.Done():
663 }
664 proven := p.run.Stop()
665 p.stop()
666 cleaned := p.run.Finish(ctx)
667 exit := provider.Exit{Code: exitCode(p.run.waitErr), ObservedAt: time.Now()}
668 if !proven || !cleaned {
669 return exit, ErrUnproven
670 }
671 return exit, nil
672}
673