@@ -12,9 +12,9 @@ import (
12
12
)
13
13
14
14
type Executor struct {
15
- ctx context. Context
16
- done chan os. Signal
17
- logger * slog. Logger
15
+ done chan os. Signal
16
+ logger * slog. Logger
17
+ isRunning bool
18
18
19
19
newCmd func (context.Context ) * exec.Cmd
20
20
mu sync.Mutex
@@ -25,7 +25,7 @@ type ExecutorArgs struct {
25
25
Command func (context.Context ) * exec.Cmd
26
26
}
27
27
28
- func NewExecutor (ctx context. Context , args ExecutorArgs ) * Executor {
28
+ func NewExecutor (args ExecutorArgs ) * Executor {
29
29
done := make (chan os.Signal , 1 )
30
30
signal .Notify (done , syscall .SIGTERM )
31
31
@@ -36,19 +36,24 @@ func NewExecutor(ctx context.Context, args ExecutorArgs) *Executor {
36
36
return & Executor {
37
37
done : done ,
38
38
logger : args .Logger ,
39
- ctx : ctx ,
40
39
newCmd : args .Command ,
41
40
mu : sync.Mutex {},
42
41
}
43
42
}
44
43
45
44
func (ex * Executor ) Exec () error {
45
+ ex .logger .Debug ("[exec:pre] starting process" )
46
46
ex .mu .Lock ()
47
- defer ex .mu .Unlock ()
47
+ ex .isRunning = true
48
+
49
+ defer func () {
50
+ ex .isRunning = false
51
+ ex .mu .Unlock ()
52
+ }()
48
53
49
54
ex .logger .Debug ("[exec] starting process" )
50
55
51
- ctx , cf := context .WithCancel (ex . ctx )
56
+ ctx , cf := context .WithCancel (context . TODO () )
52
57
defer cf ()
53
58
54
59
cmd := ex .newCmd (ctx )
@@ -65,22 +70,30 @@ func (ex *Executor) Exec() error {
65
70
case <- ex .done :
66
71
ex .logger .Debug ("executor terminated" , "pid" , cmd .Process .Pid )
67
72
}
73
+ for len (ex .done ) > 0 {
74
+ <- ex .done
75
+ }
76
+
68
77
ex .logger .Debug ("[exec] killing process" , "pid" , cmd .Process .Pid )
69
78
if err := syscall .Kill (- cmd .Process .Pid , syscall .SIGKILL ); err != nil {
70
- ex .logger .Error ("failed to kill process" , "pid" , cmd .Process .Pid , "err" , err )
79
+ if err .Error () != "no such process" {
80
+ ex .logger .Error ("failed to kill process" , "pid" , cmd .Process .Pid , "err" , err )
81
+ }
71
82
}
72
83
}()
73
84
74
85
if err := cmd .Wait (); err != nil {
75
86
if strings .HasPrefix (err .Error (), "signal:" ) {
76
87
ex .logger .Debug ("wait terminated, received" , "signal" , err .Error ())
77
88
}
78
- return err
89
+ ex . logger . Debug ( "while waiting, got" , " err" , err )
79
90
}
80
91
81
92
return nil
82
93
}
83
94
84
95
func (ex * Executor ) Kill () {
85
- ex .done <- os .Signal (syscall .SIGTERM )
96
+ if ex .isRunning {
97
+ ex .done <- os .Signal (syscall .SIGTERM )
98
+ }
86
99
}
0 commit comments