-
Notifications
You must be signed in to change notification settings - Fork 10
/
status_worker.go
382 lines (350 loc) · 11.2 KB
/
status_worker.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package worker
import (
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/go-redis/redis"
"github.com/pkg/errors"
"github.com/stitchfix/flotilla-os/clients/metrics"
"github.com/stitchfix/flotilla-os/config"
"github.com/stitchfix/flotilla-os/execution/engine"
flotillaLog "github.com/stitchfix/flotilla-os/log"
"github.com/stitchfix/flotilla-os/queue"
"github.com/stitchfix/flotilla-os/state"
"gopkg.in/tomb.v2"
"io/ioutil"
"math/rand"
"net/http"
"strings"
"time"
)
type statusWorker struct {
sm state.Manager
ee engine.Engine
conf config.Config
log flotillaLog.Logger
pollInterval time.Duration
t tomb.Tomb
engine *string
redisClient *redis.Client
workerId string
exceptionExtractorClient *http.Client
exceptionExtractorUrl string
emrEngine engine.Engine
}
func (sw *statusWorker) Initialize(conf config.Config, sm state.Manager, eksEngine engine.Engine, emrEngine engine.Engine, log flotillaLog.Logger, pollInterval time.Duration, qm queue.Manager) error {
sw.pollInterval = pollInterval
sw.conf = conf
sw.sm = sm
sw.ee = eksEngine
sw.log = log
sw.workerId = fmt.Sprintf("workerid:%d", rand.Int())
sw.engine = &state.EKSEngine
sw.emrEngine = emrEngine
if sw.conf.IsSet("eks_exception_extractor_url") {
sw.exceptionExtractorClient = &http.Client{
Timeout: time.Second * 5,
}
sw.exceptionExtractorUrl = sw.conf.GetString("eks_exception_extractor_url")
}
sw.setupRedisClient(conf)
_ = sw.log.Log("message", "initialized a status worker")
return nil
}
func (sw *statusWorker) setupRedisClient(conf config.Config) {
if *sw.engine == state.EKSEngine {
sw.redisClient = redis.NewClient(&redis.Options{Addr: conf.GetString("redis_address"), DB: conf.GetInt("redis_db")})
}
}
func (sw *statusWorker) GetTomb() *tomb.Tomb {
return &sw.t
}
// Run updates status of tasks
func (sw *statusWorker) Run() error {
for {
select {
case <-sw.t.Dying():
sw.log.Log("message", "A status worker was terminated")
return nil
default:
if *sw.engine == state.EKSEngine {
sw.runOnceEKS()
sw.runTimeouts()
time.Sleep(sw.pollInterval)
}
}
}
}
func (sw *statusWorker) runTimeouts() {
rl, err := sw.sm.ListRuns(1000, 0, "started_at", "asc", map[string][]string{
"queued_at_since": {
time.Now().AddDate(0, 0, -300).Format(time.RFC3339),
},
"task_type": {state.DefaultTaskType},
"status": {state.StatusNeedsRetry, state.StatusRunning, state.StatusQueued, state.StatusPending},
}, nil, state.Engines)
if err != nil {
_ = sw.log.Log("message", "unable to receive runs", "error", fmt.Sprintf("%+v", err))
return
}
runs := rl.Runs
sw.processTimeouts(runs)
}
func (sw *statusWorker) processTimeouts(runs []state.Run) {
for _, run := range runs {
if run.StartedAt != nil && run.ActiveDeadlineSeconds != nil {
runningDuration := time.Now().Sub(*run.StartedAt)
if int64(runningDuration.Seconds()) > *run.ActiveDeadlineSeconds {
if run.Engine != nil && *run.Engine == state.EKSSparkEngine {
_ = sw.emrEngine.Terminate(run)
} else {
_ = sw.ee.Terminate(run)
}
exitCode := int64(1)
finishedAt := time.Now()
_, _ = sw.sm.UpdateRun(run.RunID, state.Run{
Status: state.StatusStopped,
ExitReason: aws.String(fmt.Sprintf("JobRun exceeded specified timeout of %v seconds", *run.ActiveDeadlineSeconds)),
ExitCode: &exitCode,
FinishedAt: &finishedAt,
})
}
}
}
}
func (sw *statusWorker) runOnceEKS() {
rl, err := sw.sm.ListRuns(1000, 0, "started_at", "asc", map[string][]string{
"queued_at_since": {
time.Now().AddDate(0, 0, -300).Format(time.RFC3339),
},
"task_type": {state.DefaultTaskType},
"status": {state.StatusNeedsRetry, state.StatusRunning, state.StatusQueued, state.StatusPending},
}, nil, []string{state.EKSEngine})
if err != nil {
_ = sw.log.Log("message", "unable to receive runs", "error", fmt.Sprintf("%+v", err))
return
}
runs := rl.Runs
sw.processEKSRuns(runs)
}
func (sw *statusWorker) processEKSRuns(runs []state.Run) {
var lockedRuns []state.Run
for _, run := range runs {
duration := time.Duration(45) * time.Second
lock := sw.acquireLock(run, "status", duration)
if lock {
lockedRuns = append(lockedRuns, run)
}
}
_ = metrics.Increment(metrics.StatusWorkerLockedRuns, []string{sw.workerId}, float64(len(lockedRuns)))
for _, run := range lockedRuns {
start := time.Now()
go sw.processEKSRun(run)
_ = metrics.Timing(metrics.StatusWorkerProcessEKSRun, time.Since(start), []string{sw.workerId}, 1)
}
}
func (sw *statusWorker) acquireLock(run state.Run, purpose string, expiration time.Duration) bool {
start := time.Now()
key := fmt.Sprintf("%s-%s", run.RunID, purpose)
ttl, err := sw.redisClient.TTL(key).Result()
if err == nil && ttl.Nanoseconds() < 0 {
_, err = sw.redisClient.Del(key).Result()
}
set, err := sw.redisClient.SetNX(key, sw.workerId, expiration).Result()
if err != nil {
_ = sw.log.Log("message", "unable to set lock", "error", fmt.Sprintf("%+v", err))
return true
}
_ = metrics.Timing(metrics.StatusWorkerAcquireLock, time.Since(start), []string{sw.workerId}, 1)
return set
}
func (sw *statusWorker) processEKSRun(run state.Run) {
reloadRun, err := sw.sm.GetRun(run.RunID)
if err == nil && reloadRun.Status == state.StatusStopped {
// Run was updated by another worker process.
return
}
start := time.Now()
start = time.Now()
updatedRun, err := sw.ee.FetchUpdateStatus(reloadRun)
if err != nil {
_ = sw.log.Log("message", "fetch update status", "run", run.RunID, "error", fmt.Sprintf("%+v", err))
}
_ = metrics.Timing(metrics.StatusWorkerFetchUpdateStatus, time.Since(start), []string{sw.workerId}, 1)
if err == nil {
subRuns, err := sw.sm.ListRuns(1000, 0, "status", "desc", nil, map[string]string{"PARENT_FLOTILLA_RUN_ID": run.RunID}, state.Engines)
if err == nil && subRuns.Total > 0 {
var spawnedRuns state.SpawnedRuns
for _, subRun := range subRuns.Runs {
spawnedRuns = append(spawnedRuns, state.SpawnedRun{RunID: subRun.RunID})
}
updatedRun.SpawnedRuns = &spawnedRuns
}
}
if err != nil {
message := fmt.Sprintf("%+v", err)
minutesInQueue := time.Now().Sub(*run.QueuedAt).Minutes()
if strings.Contains(message, "not found") && minutesInQueue > float64(30) {
stoppedAt := time.Now()
reason := "Job either timed out or not found on the EKS cluster."
updatedRun.Status = state.StatusStopped
updatedRun.FinishedAt = &stoppedAt
updatedRun.ExitReason = &reason
_, err = sw.sm.UpdateRun(updatedRun.RunID, updatedRun)
}
} else {
fullUpdate := false
if run.PodName != nil {
if *run.PodName == *updatedRun.PodName && run.Status != updatedRun.Status {
fullUpdate = true
}
}
if fullUpdate {
sw.logStatusUpdate(updatedRun)
if updatedRun.ExitCode != nil {
go sw.cleanupRun(run.RunID)
}
_, err = sw.sm.UpdateRun(updatedRun.RunID, updatedRun)
if err != nil {
_ = sw.log.Log("message", "unable to save eks runs", "error", fmt.Sprintf("%+v", err))
}
if updatedRun.Status == state.StatusStopped {
//TODO - move to a separate worker.
//_ = sw.eksEngine.Terminate(run)
}
} else {
if updatedRun.MaxMemoryUsed != run.MaxMemoryUsed ||
updatedRun.MaxCpuUsed != run.MaxCpuUsed ||
updatedRun.Cpu != run.Cpu ||
updatedRun.PodName != run.PodName ||
updatedRun.Memory != run.Memory ||
updatedRun.PodEvents != run.PodEvents ||
updatedRun.SpawnedRuns != run.SpawnedRuns {
_, err = sw.sm.UpdateRun(updatedRun.RunID, updatedRun)
}
}
}
}
func (sw *statusWorker) cleanupRun(runID string) {
//Logs maybe delayed before being persisted to S3.
time.Sleep(120 * time.Second)
run, err := sw.sm.GetRun(runID)
if err == nil {
//Delete run from Kubernetes
_ = sw.ee.Terminate(run)
}
}
func (sw *statusWorker) extractExceptions(runID string) {
//Logs maybe delayed before being persisted to S3.
time.Sleep(60 * time.Second)
run, err := sw.sm.GetRun(runID)
if err == nil {
jobUrl := fmt.Sprintf("%s/extract/%s", sw.exceptionExtractorUrl, run.RunID)
res, err := sw.exceptionExtractorClient.Get(jobUrl)
if err == nil && res != nil && res.Body != nil {
body, err := ioutil.ReadAll(res.Body)
if body != nil {
defer res.Body.Close()
runExceptions := state.RunExceptions{}
err = json.Unmarshal(body, &runExceptions)
if err == nil {
run.RunExceptions = &runExceptions
}
}
_, _ = sw.sm.UpdateRun(run.RunID, run)
}
}
}
func (sw *statusWorker) processEKSRunMetrics(run state.Run) {
updatedRun, err := sw.ee.FetchPodMetrics(run)
if err == nil {
if updatedRun.MaxMemoryUsed != run.MaxMemoryUsed ||
updatedRun.MaxCpuUsed != run.MaxCpuUsed {
_, err = sw.sm.UpdateRun(updatedRun.RunID, updatedRun)
}
}
}
func (sw *statusWorker) logStatusUpdate(update state.Run) {
var err error
var startedAt, finishedAt time.Time
var duration float64
var env state.EnvList
var command string
if update.StartedAt != nil {
startedAt = *update.StartedAt
duration = time.Now().Sub(startedAt).Seconds()
}
if update.FinishedAt != nil {
finishedAt = *update.FinishedAt
duration = finishedAt.Sub(startedAt).Seconds()
}
if update.Env != nil {
env = *update.Env
}
if update.Command != nil {
command = *update.Command
}
if update.ExitCode != nil {
err = sw.log.Event("eventClassName", "FlotillaTaskStatus",
"run_id", update.RunID,
"definition_id", update.DefinitionID,
"alias", update.Alias,
"image", update.Image,
"cluster_name", update.ClusterName,
"command", command,
"exit_code", *update.ExitCode,
"status", update.Status,
"started_at", startedAt,
"finished_at", finishedAt,
"duration", duration,
"instance_id", update.InstanceID,
"instance_dns_name", update.InstanceDNSName,
"group_name", update.GroupName,
"user", update.User,
"task_type", update.TaskType,
"env", env,
"executable_id", update.ExecutableID,
"executable_type", update.ExecutableType)
} else {
err = sw.log.Event("eventClassName", "FlotillaTaskStatus",
"run_id", update.RunID,
"definition_id", update.DefinitionID,
"alias", update.Alias,
"image", update.Image,
"cluster_name", update.ClusterName,
"command", command,
"status", update.Status,
"started_at", startedAt,
"finished_at", finishedAt,
"duration", duration,
"instance_id", update.InstanceID,
"instance_dns_name", update.InstanceDNSName,
"group_name", update.GroupName,
"user", update.User,
"task_type", update.TaskType,
"env", env,
"executable_id", update.ExecutableID,
"executable_type", update.ExecutableType)
}
if err != nil {
sw.log.Log("message", "Failed to emit status event", "run_id", update.RunID, "error", err.Error())
}
}
func (sw *statusWorker) findRun(taskArn string) (state.Run, error) {
var engines []string
if sw.engine != nil {
engines = []string{*sw.engine}
} else {
engines = nil
}
runs, err := sw.sm.ListRuns(1, 0, "started_at", "asc", map[string][]string{
"task_arn": {taskArn},
}, nil, engines)
if err != nil {
return state.Run{}, errors.Wrapf(err, "problem finding run by task arn [%s]", taskArn)
}
if runs.Total > 0 && len(runs.Runs) > 0 {
return runs.Runs[0], nil
}
return state.Run{}, errors.Errorf("no run found for [%s]", taskArn)
}