-
Notifications
You must be signed in to change notification settings - Fork 3
/
process.go
88 lines (78 loc) · 1.89 KB
/
process.go
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
package rtm2_sdk
import (
"context"
"fmt"
"go.uber.org/zap"
"os"
"os/exec"
"syscall"
"time"
)
type rtmSidecar struct {
ctx context.Context
cancel context.CancelFunc
cmd string
args []string
process *exec.Cmd
errChan chan error
lg *zap.Logger
}
func (s *rtmSidecar) Start() <-chan error {
p := exec.Command(s.cmd, s.args...)
s.process = p
// capture sub process std err and std out
p.Stderr = os.Stderr
p.Stdout = os.Stdout
go s.loop()
return s.errChan
}
func (s *rtmSidecar) StartV1() <-chan error {
p := exec.CommandContext(s.ctx, s.cmd, s.args...)
//p.Cancel = func() error {
// if err := p.Process.Signal(syscall.SIGTERM); err != nil {
// s.lg.Error("fail to sigterm sidecar, we should kill it", zap.Error(err))
// }
// return p.Process.Kill()
//}
err := p.Start()
if err != nil {
close(s.errChan)
} else {
}
s.process = p
go s.loop()
return s.errChan
}
func (s *rtmSidecar) Stop() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered:", r)
}
}()
if s.process.Process != nil {
if err := s.process.Process.Signal(syscall.SIGTERM); err != nil {
s.lg.Error("fail to sigterm sidecar, we should kill it", zap.Error(err))
if err = s.process.Process.Kill(); err != nil {
s.lg.Error("fail to kill process", zap.Error(err))
time.Sleep(5 * time.Second)
}
} else {
time.Sleep(time.Second)
}
}
}
func (s *rtmSidecar) loop() {
err := s.process.Run()
if err != nil {
s.lg.Error("process stopped, it should be a fatal error", zap.Error(err))
s.cancel()
s.errChan <- err
} else {
close(s.errChan)
}
}
func createSidecar(ctx context.Context, lg *zap.Logger, execPath string, port int32) *rtmSidecar {
c, cancel := context.WithCancel(ctx)
return &rtmSidecar{ctx: c, cancel: cancel, cmd: fmt.Sprintf("%s/rtm2-wrapper.exe", execPath),
args: []string{fmt.Sprintf("--port=%d", port), "--mode=1"}, errChan: make(chan error, 1), lg: lg}
}