-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.go
More file actions
979 lines (856 loc) · 22.4 KB
/
service.go
File metadata and controls
979 lines (856 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
package process
import (
"bufio"
"context"
"os"
"os/exec"
"slices"
"sync"
"syscall"
"time"
"dappco.re/go/core"
coreerr "dappco.re/go/core/log"
goio "io"
)
// Default buffer size for process output (1MB).
const DefaultBufferSize = 1024 * 1024
// Errors
var (
ErrProcessNotFound = coreerr.E("", "process not found", nil)
ErrProcessNotRunning = coreerr.E("", "process is not running", nil)
ErrStdinNotAvailable = coreerr.E("", "stdin not available", nil)
ErrContextRequired = coreerr.E("", "context is required", nil)
)
// Service manages process execution with Core IPC integration.
type Service struct {
*core.ServiceRuntime[Options]
processes map[string]*Process
mu sync.RWMutex
bufSize int
registrations sync.Once
}
// coreApp returns the attached Core runtime, if one exists.
func (s *Service) coreApp() *core.Core {
if s == nil || s.ServiceRuntime == nil {
return nil
}
return s.ServiceRuntime.Core()
}
// Options configures the process service.
//
// Example:
//
// svc := process.NewService(process.Options{BufferSize: 2 * 1024 * 1024})
type Options struct {
// BufferSize is the ring buffer size for output capture.
// Default: 1MB (1024 * 1024 bytes).
BufferSize int
}
// NewService creates a process service factory for Core registration.
//
// core, _ := core.New(
// core.WithName("process", process.NewService(process.Options{})),
// )
//
// Example:
//
// factory := process.NewService(process.Options{})
func NewService(opts Options) func(*core.Core) (any, error) {
return func(c *core.Core) (any, error) {
if opts.BufferSize == 0 {
opts.BufferSize = DefaultBufferSize
}
svc := &Service{
ServiceRuntime: core.NewServiceRuntime(c, opts),
processes: make(map[string]*Process),
bufSize: opts.BufferSize,
}
return svc, nil
}
}
// OnStartup implements core.Startable.
//
// Example:
//
// _ = svc.OnStartup(ctx)
func (s *Service) OnStartup(context.Context) core.Result {
s.registrations.Do(func() {
if c := s.coreApp(); c != nil {
c.Action("process.run", s.handleRun)
c.Action("process.start", s.handleStart)
c.Action("process.kill", s.handleKill)
c.Action("process.list", s.handleList)
c.Action("process.get", s.handleGet)
c.RegisterAction(s.handleTask)
}
})
return core.Result{OK: true}
}
// OnShutdown implements core.Stoppable.
// Immediately kills all running processes to avoid shutdown stalls.
//
// Example:
//
// _ = svc.OnShutdown(ctx)
func (s *Service) OnShutdown(context.Context) core.Result {
s.mu.RLock()
procs := make([]*Process, 0, len(s.processes))
for _, p := range s.processes {
if p.IsRunning() {
procs = append(procs, p)
}
}
s.mu.RUnlock()
for _, p := range procs {
_, _ = p.killTree()
}
return core.Result{OK: true}
}
// Start spawns a new process with the given command and args.
//
// Example:
//
// proc, err := svc.Start(ctx, "echo", "hello")
func (s *Service) Start(ctx context.Context, command string, args ...string) (*Process, error) {
return s.StartWithOptions(ctx, RunOptions{
Command: command,
Args: args,
})
}
// StartWithOptions spawns a process with full configuration.
//
// Example:
//
// proc, err := svc.StartWithOptions(ctx, process.RunOptions{Command: "pwd", Dir: "/tmp"})
func (s *Service) StartWithOptions(ctx context.Context, opts RunOptions) (*Process, error) {
if opts.Command == "" {
return nil, ServiceError("command is required", nil)
}
if ctx == nil {
return nil, ServiceError("context is required", ErrContextRequired)
}
id := core.ID()
startedAt := time.Now()
if opts.KillGroup && !opts.Detach {
return nil, coreerr.E("Service.StartWithOptions", "KillGroup requires Detach", nil)
}
// Detached processes use Background context so they survive parent death
parentCtx := ctx
if opts.Detach {
parentCtx = context.Background()
}
procCtx, cancel := context.WithCancel(parentCtx)
cmd := exec.CommandContext(procCtx, opts.Command, opts.Args...)
if opts.Dir != "" {
cmd.Dir = opts.Dir
}
if len(opts.Env) > 0 {
cmd.Env = append(cmd.Environ(), opts.Env...)
}
// Put every subprocess in its own process group so shutdown can terminate
// the full tree without affecting the parent process.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
// Set up pipes
stdout, err := cmd.StdoutPipe()
if err != nil {
cancel()
return nil, coreerr.E("Service.StartWithOptions", "failed to create stdout pipe", err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
cancel()
return nil, coreerr.E("Service.StartWithOptions", "failed to create stderr pipe", err)
}
stdin, err := cmd.StdinPipe()
if err != nil {
cancel()
return nil, coreerr.E("Service.StartWithOptions", "failed to create stdin pipe", err)
}
// Create output buffer (enabled by default)
var output *RingBuffer
if !opts.DisableCapture {
output = NewRingBuffer(s.bufSize)
}
proc := &Process{
ID: id,
Command: opts.Command,
Args: append([]string(nil), opts.Args...),
Dir: opts.Dir,
Env: append([]string(nil), opts.Env...),
StartedAt: startedAt,
Status: StatusPending,
cmd: cmd,
ctx: procCtx,
cancel: cancel,
output: output,
stdin: stdin,
done: make(chan struct{}),
gracePeriod: opts.GracePeriod,
killGroup: opts.KillGroup && opts.Detach,
}
// Start the process
if err := cmd.Start(); err != nil {
startErr := coreerr.E("Service.StartWithOptions", "failed to start process", err)
proc.mu.Lock()
proc.Status = StatusFailed
proc.ExitCode = -1
proc.Duration = time.Since(startedAt)
proc.mu.Unlock()
s.mu.Lock()
s.processes[id] = proc
s.mu.Unlock()
close(proc.done)
cancel()
if c := s.coreApp(); c != nil {
_ = c.ACTION(ActionProcessExited{
ID: id,
ExitCode: -1,
Duration: proc.Duration,
Error: startErr,
})
}
return proc, startErr
}
proc.mu.Lock()
proc.Status = StatusRunning
proc.mu.Unlock()
// Store process
s.mu.Lock()
s.processes[id] = proc
s.mu.Unlock()
// Start timeout watchdog if configured
if opts.Timeout > 0 {
go func() {
select {
case <-proc.done:
// Process exited before timeout
case <-time.After(opts.Timeout):
proc.Shutdown()
}
}()
}
// Broadcast start
if c := s.coreApp(); c != nil {
_ = c.ACTION(ActionProcessStarted{
ID: id,
Command: opts.Command,
Args: opts.Args,
Dir: opts.Dir,
PID: cmd.Process.Pid,
})
}
// Stream output in goroutines
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
s.streamOutput(proc, stdout, StreamStdout)
}()
go func() {
defer wg.Done()
s.streamOutput(proc, stderr, StreamStderr)
}()
// Wait for process completion
go func() {
// Wait for output streaming to complete
wg.Wait()
// Wait for process exit
err := cmd.Wait()
duration := time.Since(proc.StartedAt)
status, exitCode, exitErr, signalName := classifyProcessExit(err)
proc.mu.Lock()
proc.Duration = duration
proc.ExitCode = exitCode
proc.Status = status
proc.mu.Unlock()
close(proc.done)
if status == StatusKilled {
s.emitKilledAction(proc, signalName)
}
exitAction := ActionProcessExited{
ID: id,
ExitCode: exitCode,
Duration: duration,
Error: exitErr,
}
if c := s.coreApp(); c != nil {
_ = c.ACTION(exitAction)
}
}()
return proc, nil
}
// streamOutput reads from a pipe and broadcasts lines via ACTION.
func (s *Service) streamOutput(proc *Process, r goio.Reader, stream Stream) {
scanner := bufio.NewScanner(r)
// Increase buffer for long lines
scanner.Buffer(make([]byte, 64*1024), 1024*1024)
for scanner.Scan() {
line := scanner.Text()
// Write to ring buffer
if proc.output != nil {
_, _ = proc.output.Write([]byte(line + "\n"))
}
// Broadcast output
if c := s.coreApp(); c != nil {
_ = c.ACTION(ActionProcessOutput{
ID: proc.ID,
Line: line,
Stream: stream,
})
}
}
}
// Get returns a process by ID.
//
// Example:
//
// proc, err := svc.Get("proc-1")
func (s *Service) Get(id string) (*Process, error) {
s.mu.RLock()
defer s.mu.RUnlock()
proc, ok := s.processes[id]
if !ok {
return nil, ErrProcessNotFound
}
return proc, nil
}
// List returns all processes.
//
// Example:
//
// for _, proc := range svc.List() { _ = proc }
func (s *Service) List() []*Process {
s.mu.RLock()
defer s.mu.RUnlock()
result := make([]*Process, 0, len(s.processes))
for _, p := range s.processes {
result = append(result, p)
}
sortProcesses(result)
return result
}
// Running returns all currently running processes.
//
// Example:
//
// running := svc.Running()
func (s *Service) Running() []*Process {
s.mu.RLock()
defer s.mu.RUnlock()
var result []*Process
for _, p := range s.processes {
if p.IsRunning() {
result = append(result, p)
}
}
sortProcesses(result)
return result
}
// Kill terminates a process by ID.
//
// Example:
//
// _ = svc.Kill("proc-1")
func (s *Service) Kill(id string) error {
proc, err := s.Get(id)
if err != nil {
return err
}
sent, err := proc.kill()
if err != nil {
return err
}
if sent {
s.emitKilledAction(proc, "SIGKILL")
}
return nil
}
// KillPID terminates a process by operating-system PID.
//
// Example:
//
// _ = svc.KillPID(1234)
func (s *Service) KillPID(pid int) error {
if pid <= 0 {
return ServiceError("pid must be positive", nil)
}
if proc := s.findByPID(pid); proc != nil {
sent, err := proc.kill()
if err != nil {
return err
}
if sent {
s.emitKilledAction(proc, "SIGKILL")
}
return nil
}
if err := syscall.Kill(pid, syscall.SIGKILL); err != nil {
return coreerr.E("Service.KillPID", core.Sprintf("failed to signal pid %d", pid), err)
}
return nil
}
// Signal sends a signal to a process by ID.
//
// Example:
//
// _ = svc.Signal("proc-1", syscall.SIGTERM)
func (s *Service) Signal(id string, sig os.Signal) error {
proc, err := s.Get(id)
if err != nil {
return err
}
return proc.Signal(sig)
}
// SignalPID sends a signal to a process by operating-system PID.
//
// Example:
//
// _ = svc.SignalPID(1234, syscall.SIGTERM)
func (s *Service) SignalPID(pid int, sig os.Signal) error {
if pid <= 0 {
return ServiceError("pid must be positive", nil)
}
if proc := s.findByPID(pid); proc != nil {
return proc.Signal(sig)
}
target, err := os.FindProcess(pid)
if err != nil {
return coreerr.E("Service.SignalPID", core.Sprintf("failed to find pid %d", pid), err)
}
if err := target.Signal(sig); err != nil {
return coreerr.E("Service.SignalPID", core.Sprintf("failed to signal pid %d", pid), err)
}
return nil
}
// Remove removes a completed process from the list.
//
// Example:
//
// _ = svc.Remove("proc-1")
func (s *Service) Remove(id string) error {
s.mu.Lock()
defer s.mu.Unlock()
proc, ok := s.processes[id]
if !ok {
return ErrProcessNotFound
}
if proc.IsRunning() {
return coreerr.E("Service.Remove", "cannot remove running process", nil)
}
delete(s.processes, id)
return nil
}
// Clear removes all completed processes.
//
// Example:
//
// svc.Clear()
func (s *Service) Clear() {
s.mu.Lock()
defer s.mu.Unlock()
for id, p := range s.processes {
if !p.IsRunning() {
delete(s.processes, id)
}
}
}
// Output returns the captured output of a process.
//
// Example:
//
// out, err := svc.Output("proc-1")
func (s *Service) Output(id string) (string, error) {
proc, err := s.Get(id)
if err != nil {
return "", err
}
return proc.Output(), nil
}
// Input writes data to the stdin of a managed process.
//
// Example:
//
// _ = svc.Input("proc-1", "hello\n")
func (s *Service) Input(id string, input string) error {
proc, err := s.Get(id)
if err != nil {
return err
}
return proc.SendInput(input)
}
// CloseStdin closes the stdin pipe of a managed process.
//
// Example:
//
// _ = svc.CloseStdin("proc-1")
func (s *Service) CloseStdin(id string) error {
proc, err := s.Get(id)
if err != nil {
return err
}
return proc.CloseStdin()
}
// Wait blocks until a managed process exits and returns its final snapshot.
//
// Example:
//
// info, err := svc.Wait("proc-1")
func (s *Service) Wait(id string) (Info, error) {
proc, err := s.Get(id)
if err != nil {
return Info{}, err
}
if err := proc.Wait(); err != nil {
return proc.Info(), err
}
return proc.Info(), nil
}
// findByPID locates a managed process by operating-system PID.
func (s *Service) findByPID(pid int) *Process {
s.mu.RLock()
defer s.mu.RUnlock()
for _, proc := range s.processes {
proc.mu.RLock()
matches := proc.cmd != nil && proc.cmd.Process != nil && proc.cmd.Process.Pid == pid
proc.mu.RUnlock()
if matches {
return proc
}
}
return nil
}
// Run executes a command and waits for completion.
// Returns the combined output and any error.
//
// Example:
//
// out, err := svc.Run(ctx, "echo", "hello")
func (s *Service) Run(ctx context.Context, command string, args ...string) (string, error) {
proc, err := s.Start(ctx, command, args...)
if err != nil {
return "", err
}
<-proc.Done()
output := proc.Output()
if proc.Status == StatusKilled {
return output, coreerr.E("Service.Run", "process was killed", nil)
}
if proc.ExitCode != 0 {
return output, coreerr.E("Service.Run", core.Sprintf("process exited with code %d", proc.ExitCode), nil)
}
return output, nil
}
// RunWithOptions executes a command with options and waits for completion.
//
// Example:
//
// out, err := svc.RunWithOptions(ctx, process.RunOptions{Command: "echo", Args: []string{"hello"}})
func (s *Service) RunWithOptions(ctx context.Context, opts RunOptions) (string, error) {
proc, err := s.StartWithOptions(ctx, opts)
if err != nil {
return "", err
}
<-proc.Done()
output := proc.Output()
if proc.Status == StatusKilled {
return output, coreerr.E("Service.RunWithOptions", "process was killed", nil)
}
if proc.ExitCode != 0 {
return output, coreerr.E("Service.RunWithOptions", core.Sprintf("process exited with code %d", proc.ExitCode), nil)
}
return output, nil
}
func (s *Service) handleRun(ctx context.Context, opts core.Options) core.Result {
parsed, err := parseProcessActionInput(opts, true)
if err != nil {
return core.Result{Value: err, OK: false}
}
output, runErr := s.RunWithOptions(ctx, runOptionsFromAction(parsed))
if runErr != nil {
return core.Result{Value: runErr, OK: false}
}
return core.Result{Value: output, OK: true}
}
func (s *Service) handleStart(ctx context.Context, opts core.Options) core.Result {
parsed, err := parseProcessActionInput(opts, true)
if err != nil {
return core.Result{Value: err, OK: false}
}
proc, startErr := s.StartWithOptions(ctx, startRunOptionsFromAction(parsed))
if startErr != nil {
return core.Result{Value: startErr, OK: false}
}
return core.Result{Value: proc.ID, OK: true}
}
func (s *Service) handleKill(ctx context.Context, opts core.Options) core.Result {
_ = ctx
id, pid, err := parseProcessActionTarget(opts)
if err != nil {
return core.Result{Value: err, OK: false}
}
switch {
case id != "":
if err := s.Kill(id); err != nil {
return core.Result{Value: err, OK: false}
}
case pid > 0:
if err := s.KillPID(pid); err != nil {
return core.Result{Value: err, OK: false}
}
}
return core.Result{OK: true}
}
func (s *Service) handleList(ctx context.Context, opts core.Options) core.Result {
_ = ctx
runningOnly := opts.Bool("runningOnly")
procs := s.List()
if runningOnly {
procs = s.Running()
}
ids := make([]string, 0, len(procs))
for _, proc := range procs {
ids = append(ids, proc.ID)
}
return core.Result{Value: ids, OK: true}
}
func (s *Service) handleGet(ctx context.Context, opts core.Options) core.Result {
_ = ctx
id := core.Trim(opts.String("id"))
if id == "" {
return core.Result{Value: coreerr.E("Service.handleGet", "id is required", nil), OK: false}
}
proc, err := s.Get(id)
if err != nil {
return core.Result{Value: err, OK: false}
}
return core.Result{Value: proc.Info(), OK: true}
}
func runOptionsFromAction(input processActionInput) RunOptions {
return RunOptions{
Command: input.Command,
Args: append([]string(nil), input.Args...),
Dir: input.Dir,
Env: append([]string(nil), input.Env...),
DisableCapture: input.DisableCapture,
Detach: input.Detach,
Timeout: input.Timeout,
GracePeriod: input.GracePeriod,
KillGroup: input.KillGroup,
}
}
func startRunOptionsFromAction(input processActionInput) RunOptions {
opts := runOptionsFromAction(input)
// RFC semantics: process.start is background execution and must not be
// coupled to the caller context unless the caller bypasses the action layer.
opts.Detach = true
return opts
}
// handleTask dispatches Core.PERFORM messages for the process service.
func (s *Service) handleTask(c *core.Core, task core.Message) core.Result {
switch m := task.(type) {
case TaskProcessStart:
proc, err := s.StartWithOptions(c.Context(), startRunOptionsFromAction(processActionInput{
Command: m.Command,
Args: m.Args,
Dir: m.Dir,
Env: m.Env,
DisableCapture: m.DisableCapture,
Detach: m.Detach,
Timeout: m.Timeout,
GracePeriod: m.GracePeriod,
KillGroup: m.KillGroup,
}))
if err != nil {
return core.Result{Value: err, OK: false}
}
return core.Result{Value: proc.Info(), OK: true}
case TaskProcessRun:
output, err := s.RunWithOptions(c.Context(), RunOptions{
Command: m.Command,
Args: m.Args,
Dir: m.Dir,
Env: m.Env,
DisableCapture: m.DisableCapture,
Detach: m.Detach,
Timeout: m.Timeout,
GracePeriod: m.GracePeriod,
KillGroup: m.KillGroup,
})
if err != nil {
return core.Result{Value: err, OK: false}
}
return core.Result{Value: output, OK: true}
case TaskProcessKill:
switch {
case m.ID != "":
if err := s.Kill(m.ID); err != nil {
return core.Result{Value: err, OK: false}
}
return core.Result{OK: true}
case m.PID > 0:
if err := s.KillPID(m.PID); err != nil {
return core.Result{Value: err, OK: false}
}
return core.Result{OK: true}
default:
return core.Result{Value: coreerr.E("Service.handleTask", "task process kill requires an id or pid", nil), OK: false}
}
case TaskProcessSignal:
switch {
case m.ID != "":
if err := s.Signal(m.ID, m.Signal); err != nil {
return core.Result{Value: err, OK: false}
}
return core.Result{OK: true}
case m.PID > 0:
if err := s.SignalPID(m.PID, m.Signal); err != nil {
return core.Result{Value: err, OK: false}
}
return core.Result{OK: true}
default:
return core.Result{Value: coreerr.E("Service.handleTask", "task process signal requires an id or pid", nil), OK: false}
}
case TaskProcessGet:
if m.ID == "" {
return core.Result{Value: coreerr.E("Service.handleTask", "task process get requires an id", nil), OK: false}
}
proc, err := s.Get(m.ID)
if err != nil {
return core.Result{Value: err, OK: false}
}
return core.Result{Value: proc.Info(), OK: true}
case TaskProcessWait:
if m.ID == "" {
return core.Result{Value: coreerr.E("Service.handleTask", "task process wait requires an id", nil), OK: false}
}
info, err := s.Wait(m.ID)
if err != nil {
return core.Result{
Value: &TaskProcessWaitError{
Info: info,
Err: err,
},
OK: true,
}
}
return core.Result{Value: info, OK: true}
case TaskProcessOutput:
if m.ID == "" {
return core.Result{Value: coreerr.E("Service.handleTask", "task process output requires an id", nil), OK: false}
}
output, err := s.Output(m.ID)
if err != nil {
return core.Result{Value: err, OK: false}
}
return core.Result{Value: output, OK: true}
case TaskProcessInput:
if m.ID == "" {
return core.Result{Value: coreerr.E("Service.handleTask", "task process input requires an id", nil), OK: false}
}
proc, err := s.Get(m.ID)
if err != nil {
return core.Result{Value: err, OK: false}
}
if err := proc.SendInput(m.Input); err != nil {
return core.Result{Value: err, OK: false}
}
return core.Result{OK: true}
case TaskProcessCloseStdin:
if m.ID == "" {
return core.Result{Value: coreerr.E("Service.handleTask", "task process close stdin requires an id", nil), OK: false}
}
proc, err := s.Get(m.ID)
if err != nil {
return core.Result{Value: err, OK: false}
}
if err := proc.CloseStdin(); err != nil {
return core.Result{Value: err, OK: false}
}
return core.Result{OK: true}
case TaskProcessList:
procs := s.List()
if m.RunningOnly {
procs = s.Running()
}
infos := make([]Info, 0, len(procs))
for _, proc := range procs {
infos = append(infos, proc.Info())
}
return core.Result{Value: infos, OK: true}
case TaskProcessRemove:
if m.ID == "" {
return core.Result{Value: coreerr.E("Service.handleTask", "task process remove requires an id", nil), OK: false}
}
if err := s.Remove(m.ID); err != nil {
return core.Result{Value: err, OK: false}
}
return core.Result{OK: true}
case TaskProcessClear:
s.Clear()
return core.Result{OK: true}
default:
return core.Result{}
}
}
// classifyProcessExit maps a command completion error to lifecycle state.
func classifyProcessExit(err error) (Status, int, error, string) {
if err == nil {
return StatusExited, 0, nil, ""
}
var exitErr *exec.ExitError
if core.As(err, &exitErr) {
if ws, ok := exitErr.Sys().(syscall.WaitStatus); ok && ws.Signaled() {
signalName := ws.Signal().String()
if signalName == "" {
signalName = "signal"
}
return StatusKilled, -1, coreerr.E("Service.StartWithOptions", "process was killed", nil), signalName
}
exitCode := exitErr.ExitCode()
return StatusExited, exitCode, coreerr.E("Service.StartWithOptions", core.Sprintf("process exited with code %d", exitCode), nil), ""
}
return StatusFailed, 0, err, ""
}
// emitKilledAction broadcasts a kill event once for the given process.
func (s *Service) emitKilledAction(proc *Process, signalName string) {
if proc == nil {
return
}
proc.mu.Lock()
if proc.killNotified {
proc.mu.Unlock()
return
}
proc.killNotified = true
if signalName != "" {
proc.killSignal = signalName
} else if proc.killSignal == "" {
proc.killSignal = "SIGKILL"
}
signal := proc.killSignal
proc.mu.Unlock()
if c := s.coreApp(); c != nil {
_ = c.ACTION(ActionProcessKilled{
ID: proc.ID,
Signal: signal,
})
}
}
// sortProcesses orders processes by start time, then ID for stable output.
func sortProcesses(procs []*Process) {
slices.SortFunc(procs, func(a, b *Process) int {
if a.StartedAt.Equal(b.StartedAt) {
if a.ID < b.ID {
return -1
}
if a.ID > b.ID {
return 1
}
return 0
}
if a.StartedAt.Before(b.StartedAt) {
return -1
}
return 1
})
}