-
Notifications
You must be signed in to change notification settings - Fork 2
/
scheduler.go
89 lines (71 loc) · 1.94 KB
/
scheduler.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
package main
import (
"time"
"fmt"
"strings"
"os/exec"
"os"
"syscall"
)
type CheckResult struct {
name string
output []byte
exitCode int
err error
}
type Scheduler struct {
checksByFrequency map[int][]Check
resultsChan chan CheckResult
}
func NewScheduler(checks []Check, resultsChan chan CheckResult) Scheduler {
checksByFrequency := make(map[int][]Check)
for _, check := range checks {
checksByFrequency[check.Frequency] = append(checksByFrequency[check.Frequency], check)
}
return Scheduler{checksByFrequency,resultsChan}
}
func (s *Scheduler) Run() {
tickChan := time.NewTicker(time.Second).C
for {
tick :=<- tickChan
for frequency := range s.checksByFrequency {
if tick.Unix() % int64(frequency) == 0 {
for _, check := range s.checksByFrequency[frequency] {
output, exitCode, err := s.execute(check)
fmt.Printf("[%s] %s Output : \n %s\n", tick, check.Name, string(output))
fmt.Printf("[%s] %s Exit Code: %d\n", tick, check.Name, exitCode)
if err != nil {
fmt.Printf("[%s] %s Error: %d\n", tick, check.Name, err)
}
s.resultsChan <- CheckResult{check.Name, output,exitCode, err}
}
}
}
}
}
func (s *Scheduler) execute(check Check) (output []byte, exitCode int, err error) {
commandList := strings.Split(check.Command, " ")
name := commandList[0]
args := commandList[1:]
cmd := exec.Command(name, args...)
cmdEnv := make([]string, len(check.Environment))
for envVar, value := range check.Environment {
cmdEnv = append(cmdEnv, envVar + "=" + value)
}
cmd.Env = append(os.Environ(), cmdEnv...)
output, err = cmd.CombinedOutput()
if err != nil {
exitErr, ok := err.(*exec.ExitError)
if !ok {
return
}
ws := exitErr.Sys().(syscall.WaitStatus)
exitCode = ws.ExitStatus()
return output, exitCode, nil
}
return output, 0, nil
}
func mainScheduler(checks []Check, resultsChan chan CheckResult) {
scheduler := NewScheduler(checks, resultsChan)
scheduler.Run()
}