-
Notifications
You must be signed in to change notification settings - Fork 6
/
running_job.go
202 lines (170 loc) · 4.89 KB
/
running_job.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
package lrmr
import (
"context"
"os"
"strings"
"sync/atomic"
"syscall"
"time"
"github.com/ab180/lrmr/cluster"
"github.com/ab180/lrmr/driver"
"github.com/ab180/lrmr/internal/errchannel"
"github.com/ab180/lrmr/internal/util"
"github.com/ab180/lrmr/job"
lrmrmetric "github.com/ab180/lrmr/metric"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
)
// abortTimeout specifies how long it need to be waited for actual job abort.
const abortTimeout = 5 * time.Second
type RunningJob struct {
*job.Job
jobErrChan *errchannel.ErrChannel
driver driver.Driver
statusManager job.Manager
finalStatus atomic.Value
startedAt time.Time
}
func startTrackingDetachedJob(j *job.Job, c cluster.State, drv driver.Driver) *RunningJob {
runningJob := &RunningJob{
Job: j,
jobErrChan: errchannel.New(),
driver: drv,
statusManager: job.NewDistributedManager(c, j),
startedAt: time.Now(),
}
runningJob.statusManager.OnStageCompletion(func(stageName string, stageStatus *job.StageStatus) {
log.Info().
Str("jobID", j.ID).
Str("stageName", stageName).
Str("status", string(stageStatus.Status)).
Msg("stage completed")
})
runningJob.statusManager.OnJobCompletion(func(status *job.Status) {
log.Info().
Str("jobID", j.ID).
Str("status", string(status.Status)).
Dur("elapsed", time.Since(runningJob.startedAt)).
Msg("job completed")
groupTasksByError := make(map[string][]string)
for _, errDesc := range status.Errors {
simpleTaskID := strings.ReplaceAll(errDesc.Task, j.ID+"/", "")
groupTasksByError[errDesc.Message] = append(groupTasksByError[errDesc.Message], simpleTaskID)
}
for errMsg, tasks := range groupTasksByError {
log.Info().
Str("jobID", j.ID).
Interface("tasks", tasks).
Str("error", errMsg).
Msg("error occurred")
}
runningJob.finalStatus.Store(status)
runningJob.logMetrics()
if status.Status == job.Failed {
runningJob.jobErrChan.Send(status.Errors[0])
return
}
runningJob.jobErrChan.Send(nil)
})
return runningJob
}
func (r *RunningJob) Status() job.RunningState {
status := r.finalStatus.Load()
if status == nil {
return job.Running
}
return status.(*job.Status).Status
}
func (r *RunningJob) Metrics() (lrmrmetric.Metrics, error) {
return r.statusManager.CollectMetrics(context.Background())
}
func (r *RunningJob) Wait() error {
ctx, cancel := util.ContextWithSignal(context.Background(), os.Interrupt, os.Kill, syscall.SIGTERM)
defer cancel()
return r.WaitWithContext(ctx)
}
func (r *RunningJob) WaitWithContext(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
select {
case err := <-r.jobErrChan.Recv():
return err
case <-ctx.Done():
log.Debug().Msg("context cancelled while waiting. aborting...")
abortCtx, abortCancel := context.WithTimeout(ctx, abortTimeout)
defer abortCancel()
if err := r.AbortWithContext(abortCtx); err != nil {
return errors.Wrap(err, "during abort")
}
return ctx.Err()
}
}
func (r *RunningJob) Abort() error {
ctx, cancel := util.ContextWithSignal(context.Background(), os.Interrupt, os.Kill, syscall.SIGTERM)
defer cancel()
return r.AbortWithContext(ctx)
}
func (r *RunningJob) AbortWithContext(ctx context.Context) error {
ref := job.TaskID{
JobID: r.Job.ID,
StageName: "master",
PartitionID: "_",
}
if err := r.statusManager.Abort(ctx, ref); err != nil {
return errors.Wrap(err, "abort")
}
select {
case <-ctx.Done():
return ctx.Err()
case <-r.jobErrChan.Recv():
return nil
}
}
func (r *RunningJob) logMetrics() {
jobDuration := time.Since(r.startedAt)
lrmrmetric.JobDurationSummary.Observe(jobDuration.Seconds())
lrmrmetric.RunningJobsGauge.Dec()
}
// AbortDetachedJob stops a job's execution.
func AbortDetachedJob(ctx context.Context, cluster cluster.Cluster, jobID string) error {
ref := job.TaskID{
JobID: jobID,
StageName: "master",
PartitionID: "_",
}
jobErrChan := errchannel.New()
defer jobErrChan.Close()
jobManager := job.NewDistributedManager(cluster.States(), &job.Job{ID: jobID})
defer jobManager.Close()
jobManager.OnJobCompletion(func(*job.Status) {
jobErrChan.Send(nil)
})
if err := jobManager.Abort(ctx, ref); err != nil {
return errors.Wrap(err, "abort")
}
// wait until the job to be cancelled
for {
select {
case <-jobErrChan.Recv():
return nil
case <-ctx.Done():
return ctx.Err()
default:
js, err := jobManager.FetchStatus(ctx)
if err != nil {
return err
}
if js.Status == job.Failed {
return nil
}
log.Debug().Msg("waiting for job to be canceled...")
time.Sleep(time.Second)
}
}
}
// FetchDetatchedJobStatus fetches the status of a job.
func FetchDetatchedJobStatus(ctx context.Context, cluster cluster.Cluster, jobID string) (*job.Status, error) {
jobManager := job.NewDistributedManager(cluster.States(), &job.Job{ID: jobID})
defer jobManager.Close()
return jobManager.FetchStatus(ctx)
}