-
Notifications
You must be signed in to change notification settings - Fork 0
/
runner.go
102 lines (85 loc) · 1.78 KB
/
runner.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
101
102
package apprunner
import (
"bufio"
"context"
"fmt"
"io"
"log"
"os"
"os/exec"
"syscall"
"time"
)
func printOutput(cr *currentRun, rc io.ReadCloser) {
go func() {
scanner := bufio.NewScanner(rc)
for scanner.Scan() {
row := scanner.Text()
fmt.Fprintf(os.Stdout, "%-17s | %s\n", cr.appName, row)
}
rc.Close()
}()
}
// clean this
func RunApp(cr *currentRun) {
cr.Lock()
if cr.running {
cr.Unlock()
return
}
cr.running = true
cr.Unlock()
healthCheck := time.Tick(CmdHealthCheckInterval)
for {
select {
case <-cr.reload:
log.Printf("reload requested")
// makes sure the current process is stopped
cr.Stop()
cr.Lock()
ctx, cancel := context.WithCancel(context.Background())
c := exec.CommandContext(ctx, cr.Location)
cr.cmd = c
cr.ctx = ctx
cr.cancelFunc = cancel
c.WaitDelay = 5 * time.Second
c.Cancel = func() error {
log.Println("sending sigterm to process...")
c.Process.Signal(syscall.SIGTERM)
return nil
}
c.Env = append(os.Environ(), cr.Env...)
errPipe, err := c.StderrPipe()
if err != nil {
log.Fatalf("pipefailure: %s", err)
}
stdoutPipe, err := c.StdoutPipe()
if err != nil {
log.Fatalf("pipefailure: %s", err)
}
printOutput(cr, errPipe)
printOutput(cr, stdoutPipe)
log.Printf("running application...")
// this is non-blocking
err = c.Start()
if err == nil {
log.Printf("app started successfully, pid=%d", c.Process.Pid)
} else {
log.Printf("app startup failure: %s", err)
}
cr.Unlock()
case <-healthCheck:
log.Printf("healthchecking...")
cr.RLock()
if cr.cmd != nil && cr.cmd.ProcessState != nil {
if cr.cmd.ProcessState.Exited() {
select {
case cr.reload <- struct{}{}:
default:
}
}
}
cr.RUnlock()
}
}
}