-
Notifications
You must be signed in to change notification settings - Fork 1
/
foreman.go
executable file
·223 lines (184 loc) · 5.25 KB
/
foreman.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
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
package foreman
import (
"errors"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/Eslam-Nawara/foreman/internal/depgraph"
parser "github.com/Eslam-Nawara/foreman/internal/procparser"
"gopkg.in/yaml.v3"
)
const interval = 50 * time.Millisecond
type Foreman struct {
services map[string]parser.Service
verbose bool
logger *log.Logger
servicesMutex sync.Mutex
}
func New(filePath string, verbose bool) (*Foreman, error) {
foreman := &Foreman{
services: map[string]parser.Service{},
servicesMutex: sync.Mutex{},
logger: log.New(os.Stdout, "INFO: ", log.Ldate|log.Ltime),
verbose: verbose,
}
yamlMap := make(map[string]map[string]any)
data, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
err = yaml.Unmarshal([]byte(data), yamlMap)
if err != nil {
return nil, err
}
for serviceName, serviceInfo := range yamlMap {
service := parser.ParseService(serviceInfo)
service.Name = serviceName
foreman.services[serviceName] = service
}
return foreman, nil
}
// start all services from yaml file
func (foreman *Foreman) Start() error {
var wg sync.WaitGroup
graph := foreman.BuildDepGraph()
if depgraph.IsCyclic(graph) {
return errors.New("Cyclic dependencies detected")
}
services := depgraph.TopSort(graph)
for _, serviceName := range services {
wg.Add(1)
go func(serviceName string) {
defer wg.Done()
foreman.runService(serviceName)
}(serviceName)
}
go func() {
sigChan := make(chan os.Signal)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
foreman.Exit(1)
}()
wg.Wait()
return nil
}
// start one service and wait for it
func (foreman *Foreman) runService(serviceName string) {
stopChecker := make(chan bool)
for {
foreman.servicesMutex.Lock()
service := foreman.services[serviceName]
foreman.servicesMutex.Unlock()
cmd := exec.Command("bash", "-c", service.Cmd)
cmd.Start()
foreman.vLog(fmt.Sprintf("%s service has been started\n", serviceName))
service.Process = cmd.Process
foreman.servicesMutex.Lock()
foreman.services[serviceName] = service
foreman.servicesMutex.Unlock()
go foreman.runChecker(service, stopChecker)
cmd.Wait()
stopChecker <- true
service.Process = nil
foreman.servicesMutex.Lock()
foreman.services[serviceName] = service
foreman.servicesMutex.Unlock()
foreman.vLog(fmt.Sprintf("%s service exited with status code %s\n", serviceName, cmd.ProcessState.String()))
if service.RunOnce {
break
}
}
}
func (foreman *Foreman) runChecker(service parser.Service, stopChecker chan bool) {
ticker := time.NewTicker(interval)
foreman.vLog(fmt.Sprintf("%s checks has been started\n", service.Name))
for {
select {
case <-stopChecker:
foreman.vLog(fmt.Sprintf("%s checks stopped\n", service.Name))
return
case <-ticker.C:
err := foreman.checkDeps(service)
if err != nil {
syscall.Kill(service.Process.Pid, syscall.SIGINT)
foreman.vLog(fmt.Sprintf("dependencies check for %s failed, services has been restarted\n", service.Name))
}
checkCmd := exec.Command("bash", "-c", service.Checks.Cmd)
err = checkCmd.Run()
if err != nil {
syscall.Kill(service.Process.Pid, syscall.SIGINT)
foreman.vLog(fmt.Sprintf("check for process %s failed, services has been restarted\n", service.Name))
}
err = foreman.checkPort(service, "tcp")
if err != nil {
syscall.Kill(service.Process.Pid, syscall.SIGINT)
foreman.vLog(fmt.Sprintf("tcp ports checking for process %s failed, services has been restarted\n", service.Name))
}
err = foreman.checkPort(service, "udp")
if err != nil {
syscall.Kill(service.Process.Pid, syscall.SIGINT)
foreman.vLog(fmt.Sprintf("udp ports checking for process %s failed, services has been restarted\n", service.Name))
}
}
}
}
func (foreman *Foreman) BuildDepGraph() map[string][]string {
graph := make(map[string][]string)
for serviceName, service := range foreman.services {
graph[serviceName] = service.Deps
}
return graph
}
func (f *Foreman) vLog(msg string) {
if f.verbose {
f.logger.Print(msg)
}
}
// ُExit kills all the running services and checkers.
// exits foreman with the given exit status.
func (f *Foreman) Exit(exitStatus int) {
f.servicesMutex.Lock()
for _, service := range f.services {
if service.Process != nil {
syscall.Kill(-service.Process.Pid, syscall.SIGINT)
}
}
f.servicesMutex.Unlock()
os.Exit(exitStatus)
}
func (foreman *Foreman) checkDeps(service parser.Service) error {
for _, dep := range service.Deps {
foreman.servicesMutex.Lock()
depService := foreman.services[dep]
foreman.servicesMutex.Unlock()
if depService.Process == nil {
return errors.New("Broken dependency")
}
}
return nil
}
func (foreman *Foreman) checkPort(service parser.Service, portType string) error {
var ports []string
switch portType {
case "tcp":
ports = service.Checks.TcpPorts
case "udp":
ports = service.Checks.UdpPorts
}
for _, port := range ports {
cmd := fmt.Sprintf("netstat -lnptu | grep %s | grep %s -m 1 | awk '{print $7}'", portType, port)
out, _ := exec.Command("bash", "-c", cmd).Output()
pid, err := strconv.Atoi(strings.Split(string(out), "/")[0])
if err != nil || pid != service.Process.Pid {
return err
}
}
return nil
}