-
Notifications
You must be signed in to change notification settings - Fork 0
/
process.go
100 lines (85 loc) · 1.68 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
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"context"
"fmt"
"log"
"os"
"os/exec"
"sync"
)
func NewPIDManager(runCmd []string, buildCmd string) *pidManager {
return &pidManager{runCmd: runCmd, buildCmd: buildCmd}
}
type pidManager struct {
runCmd []string
buildCmd string
command *exec.Cmd
}
func (p *pidManager) Start() {
err := p.execBuildCmd()
if err != nil {
logError("build cmd failed", err)
} else {
err = p.startRunCmd()
if err != nil {
logError("run cmd failed", err)
}
}
}
func (p *pidManager) Listen(ctx context.Context, wg *sync.WaitGroup, notify chan struct{}) {
defer wg.Done()
for {
select {
case <-ctx.Done():
p.stopRunCmd()
return
case <-notify:
p.stopRunCmd()
p.Start()
notify <- struct{}{}
}
}
log.Println("pidManager: stopped")
}
func logError(msg string, err error) {
log.Printf("REBUILD Error: %s: %s", msg, err)
}
func (p *pidManager) execBuildCmd() error {
if p.buildCmd == "" {
return nil
}
cmd := exec.Command("bash", "-c", p.buildCmd)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
return err
}
return nil
}
func (p *pidManager) startRunCmd() error {
if p.command != nil {
return fmt.Errorf("Failed to started command. p.command is not nil")
}
p.command = exec.Command(p.runCmd[0], p.runCmd[1:]...)
p.command.Stdout = os.Stdout
p.command.Stderr = os.Stderr
err := p.command.Start()
if err != nil {
p.command = nil
return err
}
return nil
}
func (p *pidManager) stopRunCmd() {
if p.command == nil {
log.Println("No process to kill. Returning")
return
}
p.command.Process.Kill()
err := p.command.Wait()
if err != nil {
log.Printf("Command stopped: %s\n", err)
}
p.command = nil
}