-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscheduler.go
297 lines (244 loc) · 7.48 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
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/boltdb/bolt"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"time"
)
type RunningMachine struct {
Id uint64
Name string
Path string
Input string
LastState string
NextState string
StatusMessage string
RunningStateCode bool
NextStateRun time.Time
}
type Scheduler struct {
SchedulerLock *sync.Mutex
RunningMachines []*RunningMachine
Database *bolt.DB
}
var globalScheduler Scheduler
func (s *Scheduler) GetRunningMachines() *[]*RunningMachine {
s.SchedulerLock.Lock()
runningMachines := s.RunningMachines
s.SchedulerLock.Unlock()
return &runningMachines
}
func (s *Scheduler) GetMachineRun(id string) (*RunningMachine, error) {
var machine RunningMachine
returnErr := s.Database.View(func(tx *bolt.Tx) error {
runsBucket := tx.Bucket([]byte("MachineRuns"))
if runsBucket == nil {
return fmt.Errorf("error getting database bucket")
}
machineJson := runsBucket.Get([]byte(id))
if machineJson == nil {
return fmt.Errorf("no running state machine with id %s found", id)
}
err := json.Unmarshal(machineJson, &machine)
if err != nil {
return fmt.Errorf("error deserializing machine run from persisted db: %s", err)
}
return nil
})
if returnErr != nil {
return nil, returnErr
} else {
return &machine, nil
}
}
func (s *Scheduler) UpdatePersistedMachine(machine *RunningMachine) (id uint64, returnErr error) {
returnErr = s.Database.Update(func(tx *bolt.Tx) error {
runningBucket := tx.Bucket([]byte("RunningMachines"))
runsBucket := tx.Bucket([]byte("MachineRuns"))
if runningBucket == nil || runsBucket == nil {
return fmt.Errorf("error getting database bucket")
}
if machine.Id == 0 {
var seqErr error
id, seqErr = runsBucket.NextSequence()
if seqErr != nil {
return fmt.Errorf("error getting next value in MachineRuns sequence: %s", seqErr)
}
machine.Id = id
} else {
id = machine.Id
}
machineJson, err := json.Marshal(machine)
if err != nil {
return fmt.Errorf("error serializing machine as json for persisting: %s", err)
}
idKey := []byte(fmt.Sprintf("%d", id))
err = runsBucket.Put(idKey, machineJson)
if err != nil {
return fmt.Errorf("error persisting machine run: %s", err)
}
err = runningBucket.Put(idKey, nil)
if err != nil {
return fmt.Errorf("error persisting machine run: %s", err)
}
return nil
})
return
}
func (s *Scheduler) ScheduleMachine(name string, path string, input string) (id uint64, returnErr error) {
machine := RunningMachine{Id: 0, Name: name, Path: path, Input: input, NextState: "start", RunningStateCode: false, NextStateRun: time.Time{}}
id, returnErr = s.UpdatePersistedMachine(&machine)
if returnErr == nil {
s.AddMachine(&machine)
}
return
}
func (s *Scheduler) AddMachine(machine *RunningMachine) {
s.SchedulerLock.Lock()
s.RunningMachines = append(s.RunningMachines, machine)
s.SchedulerLock.Unlock()
}
func (s *Scheduler) CancelMachineRun(id string) error {
return s.Database.Update(func(tx *bolt.Tx) error {
s.SchedulerLock.Lock()
machineIdx := -1
var machine *RunningMachine
var idx int
for idx, machine = range s.RunningMachines {
if fmt.Sprintf("%d", machine.Id) == id {
machineIdx = idx
break
}
}
if machineIdx == -1 {
s.SchedulerLock.Unlock()
return fmt.Errorf("state machine run with id %s is not currently active", id)
} else {
// Delete from in-memory representation right away so that we can drop lock
s.RunningMachines = append(s.RunningMachines[:machineIdx], s.RunningMachines[machineIdx+1:]...)
s.SchedulerLock.Unlock()
}
runningBucket := tx.Bucket([]byte("RunningMachines"))
runsBucket := tx.Bucket([]byte("MachineRuns"))
if runningBucket == nil || runsBucket == nil {
return fmt.Errorf("error getting database bucket")
}
err := runningBucket.Delete([]byte(id))
if err != nil {
return err
}
if machine.NextState != "stop" {
machine.StatusMessage = "State machine run cancelled manually"
machine.NextState = "stop"
machine.RunningStateCode = false
machineJson, jsonErr := json.Marshal(machine)
if jsonErr != nil {
return fmt.Errorf("error serializing machine as json for persisting: %s", err)
}
runsBucket.Put([]byte(id), machineJson)
}
return nil
})
}
func (s *Scheduler) ExecuteState(machine *RunningMachine) {
cmdPath := machine.Path + "/" + machine.NextState
cmd := exec.Command(cmdPath)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
cmd.Stdin = strings.NewReader(machine.Input)
err := cmd.Run()
if err != nil {
machine.StatusMessage = fmt.Sprintf("error executing state code at %s (will keep retrying): %s", cmdPath, err)
} else {
stderrStr := string(stderr.Bytes())
stderrLines := strings.Split(stderrStr, "\n")
if len(stderrLines) < 3 {
machine.StatusMessage = fmt.Sprintf("state code at %s didn't return at least 3 lines correctly at stderr (will keep retrying), stderr was: %s",
cmdPath, stderrStr)
} else {
machine.LastState = machine.NextState
machine.NextState = strings.TrimSpace(stderrLines[0])
numSeconds, intConvertError := strconv.Atoi(strings.TrimSpace(stderrLines[1]))
if intConvertError != nil || numSeconds <= 0 {
machine.NextStateRun = time.Time{}
} else {
machine.NextStateRun = time.Now().Add(time.Duration(numSeconds) * time.Second)
}
machine.Input = string(stdout.Bytes())
machine.StatusMessage = strings.TrimSpace(stderrLines[2])
}
}
machine.RunningStateCode = false
s.UpdatePersistedMachine(machine)
if machine.NextState == "stop" {
s.CancelMachineRun(fmt.Sprintf("%d", machine.Id))
}
}
func (s *Scheduler) HandleTick() {
s.SchedulerLock.Lock()
currentTime := time.Now()
for idx, machine := range s.RunningMachines {
if !machine.RunningStateCode && machine.NextState != "stop" && machine.NextStateRun.Before(currentTime) {
var machinePtr *RunningMachine = s.RunningMachines[idx]
machinePtr.RunningStateCode = true
s.UpdatePersistedMachine(machinePtr)
go s.ExecuteState(machinePtr)
}
}
s.SchedulerLock.Unlock()
}
func (s *Scheduler) SchedulerTick(ticker *time.Ticker, quitChannel chan struct{}) {
for {
select {
case <-ticker.C:
s.HandleTick()
case <-quitChannel:
ticker.Stop()
return
}
}
}
func (s *Scheduler) Init(db *bolt.DB) chan struct{} {
s.SchedulerLock = &sync.Mutex{}
s.Database = db
s.RunningMachines = make([]*RunningMachine, 0, 0)
// Initialize database
dbInitErr := db.Update(func(tx *bolt.Tx) error {
runningBucket, err := tx.CreateBucketIfNotExists([]byte("RunningMachines"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
var runsBucket *bolt.Bucket
runsBucket, err = tx.CreateBucketIfNotExists([]byte("MachineRuns"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
c := runningBucket.Cursor()
for k, _ := c.First(); k != nil; k, _ = c.Next() {
machineJson := runsBucket.Get(k)
var machine RunningMachine
err := json.Unmarshal(machineJson, &machine)
if err != nil {
return fmt.Errorf("error deserializing currently running machine from persisted db: %s", err)
}
s.AddMachine(&machine)
}
return nil
})
if dbInitErr != nil {
fmt.Printf("error initializing database: %s\n", dbInitErr)
os.Exit(1)
}
// Setup the timer that powers the scheduler
ticker := time.NewTicker(1 * time.Second)
stopSchedulerChannel := make(chan struct{})
go s.SchedulerTick(ticker, stopSchedulerChannel)
return stopSchedulerChannel
}