forked from viliproject/vili
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runner.go
340 lines (305 loc) · 7.08 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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
package api
import (
"fmt"
"time"
"github.com/CloudCom/firego"
"github.com/airware/vili/config"
"github.com/airware/vili/docker"
"github.com/airware/vili/errors"
"github.com/airware/vili/kube"
"github.com/airware/vili/kube/v1"
"github.com/airware/vili/log"
"github.com/airware/vili/redis"
"github.com/airware/vili/slack"
"github.com/airware/vili/templates"
)
const (
runTimeout = 5 * time.Minute
runPollPeriod = 1 * time.Second
)
// runner
type runnerSpec struct {
env string
job string
run *Run
db *firego.Firebase
// for all actions
pod *v1.Pod
// for resume
podTemplate templates.Template
variables map[string]string
lastPing time.Time
}
func makeRunner(env, job string, run *Run) (*runnerSpec, error) {
runner := &runnerSpec{
env: env,
job: job,
run: run,
db: runDB(env, job, run.ID),
lastPing: time.Now(),
}
return runner, nil
}
func (r *runnerSpec) addMessage(message, level string) error {
var logf func(...interface{})
switch level {
case "debug":
logf = log.Debug
case "info":
logf = log.Info
case "warn":
logf = log.Warn
case "error":
logf = log.Error
default:
return fmt.Errorf("Invalid level %s", level)
}
logf(message)
_, err := r.db.Child("log").Push(LogMessage{
Time: time.Now(),
Message: message,
Level: level,
})
if err != nil {
return err
}
if level != "debug" {
urlStr := fmt.Sprintf(
"%s/%s/jobs/%s/runs/%s",
config.GetString(config.URI),
r.env,
r.job,
r.run.ID,
)
slackMessage := fmt.Sprintf(
"*%s* - *%s* - <%s|%s> - %s",
r.env,
r.job,
urlStr,
r.run.ID,
message,
)
if level == "error" {
slackMessage += " <!channel>"
}
err := slack.PostLogMessage(slackMessage, level)
if err != nil {
return err
}
}
return nil
}
func (r *runnerSpec) start() error {
log.Infof("Starting run %s for job %s in env %s", r.run.ID, r.job, r.env)
body, err := templates.Pod(r.env, r.run.Branch, r.job)
if err != nil {
return err
}
r.podTemplate = body
err = r.acquireLock()
// return any lock errors synchronously
if err != nil {
return err
}
// if no problem fetching lock, run the rollout asynchronously
go func() {
defer r.releaseLock()
var state string
r.db.Child("state").Value(&state)
var message string
switch state {
case runStateNew:
message = fmt.Sprintf("Starting job run created by *%s* for tag *%s*", r.run.Username, r.run.Tag)
default:
log.Errorf("Cannot resume run from state %s", state)
return
}
r.db.Child("state").Set(runStateRunning)
r.run.State = runStateRunning
r.addMessage(message, "info")
stateNotifications := make(chan firego.Event)
stateRef := r.db.Child("state")
if err := stateRef.Watch(stateNotifications); err != nil {
log.Error(err)
return
}
defer stateRef.StopWatching()
go func() {
for event := range stateNotifications {
log.Debugf("Run state changed to %s", event.Data.(string))
r.run.State = event.Data.(string)
}
}()
// create pod, which starts the job
pod, err := r.createNewPod()
if err != nil {
log.Error(err)
return
}
r.pod = pod
r.run.UID = string(pod.ObjectMeta.UID)
r.db.Child("uid").Set(pod.ObjectMeta.UID)
// wait for completion
err = r.waitForPod()
if err != nil {
r.db.Child("state").Set(runStateTerminated)
switch e := err.(type) {
case runnerTerminated:
r.addMessage("Terminated run", "warn")
case runnerTimeout:
r.addMessage("Run timed out", "error")
default:
r.addMessage(fmt.Sprintf("Unexpected error %s", e), "error")
log.Error(e)
}
}
}()
return nil
}
func (r *runnerSpec) terminate() error {
log.Infof("Terminating run %s for job %s in env %s", r.run.ID, r.job, r.env)
var state string
var newState string
r.db.Child("state").Value(&state)
var message string
switch state {
case runStateRunning:
message = "Pausing run"
newState = runStateTerminating
case runStateTerminating:
message = "Force terminating run"
newState = runStateTerminated
default:
return errors.BadRequestError(fmt.Sprintf("Cannot terminate run from state %s", state))
}
r.addMessage(message, "warn")
r.db.Child("state").Set(newState)
return nil
}
// utils
func (r *runnerSpec) acquireLock() error {
locked, err := redis.GetClient().SetNX(
fmt.Sprintf("runlock:%s:%s", r.env, r.job),
true,
1*time.Hour,
).Result()
if err != nil {
return err
}
if !locked {
return errors.ConflictError("Failed to acquire run lock")
}
WaitGroup.Add(1)
return nil
}
func (r *runnerSpec) releaseLock() error {
WaitGroup.Done()
return redis.GetClient().Del(
fmt.Sprintf("runlock:%s:%s", r.env, r.job),
).Err()
}
// waitForPod waits until the pod exits
func (r *runnerSpec) waitForPod() error {
// try to set the number of replicas
elapsed := 0 * time.Second
ticker := time.NewTicker(runPollPeriod)
defer ticker.Stop()
WaitLoop:
for {
if err := r.ping(); err != nil {
return err
}
pod, _, err := kube.Pods.Get(r.env, r.pod.ObjectMeta.Name)
if err != nil {
return err
}
if pod != nil {
log, _, err := kube.Pods.GetLog(r.env, r.pod.ObjectMeta.Name)
if err != nil {
return err
}
if log != "" {
r.db.Child("output").Set(log)
}
switch pod.Status.Phase {
case v1.PodSucceeded:
r.db.Child("state").Set(runStateCompleted)
_, _, err := kube.Pods.Delete(r.env, r.pod.ObjectMeta.Name)
if err != nil {
return err
}
r.addMessage(fmt.Sprintf("Successfully completed job in %s", r.run.Clock.humanize()), "info")
break WaitLoop
case v1.PodFailed:
r.db.Child("state").Set(runStateFailed)
r.db.Child("stateReason").Set("Pod failed")
break WaitLoop
}
}
// tick
<-ticker.C
elapsed += runPollPeriod
if elapsed > runTimeout {
return runnerTimeout{}
}
}
return nil
}
// ping updates the run clock, and checks if the run should be terminated
func (r *runnerSpec) ping() error {
now := time.Now()
elapsed := Clock(now.Sub(r.lastPing))
if r.run.Clock == nil {
r.run.Clock = &elapsed
} else {
*r.run.Clock += elapsed
}
r.lastPing = now
r.db.Child("clock").Set(r.run.Clock)
if r.run.State == runStateTerminating ||
r.run.State == runStateTerminated {
return runnerTerminated{}
}
if Exiting {
log.Warn("Terminating run after server shutdown request")
return runnerTerminated{}
}
return nil
}
func (r *runnerSpec) createNewPod() (*v1.Pod, error) {
pod := &v1.Pod{}
err := r.podTemplate.Parse(pod)
if err != nil {
return nil, err
}
containers := pod.Spec.Containers
if len(containers) == 0 {
return nil, fmt.Errorf("no containers in pod")
}
imageName, err := docker.FullName(r.job, r.run.Branch, r.run.Tag)
if err != nil {
return nil, err
}
containers[0].Image = imageName
pod.ObjectMeta.Name = r.job + "-" + r.run.ID
pod.ObjectMeta.Labels = map[string]string{
"job": r.job,
"run": r.run.ID,
}
resp, status, err := kube.Pods.Create(r.env, pod)
if status != nil {
return nil, fmt.Errorf(status.Message)
}
return resp, err
}
type runnerException struct {
}
func (e *runnerException) Error() string {
return "Runner exception"
}
type runnerTerminated struct {
*runnerException
}
type runnerTimeout struct {
*runnerException
}