-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathworker.go
294 lines (251 loc) · 7.04 KB
/
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
package goworker
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/pkg/errors"
"github.com/redis/go-redis/v9"
)
const (
heartbeatInterval = time.Minute
heartbeatKey = "workers:heartbeat"
keyForWorkersPruning = "pruning_dead_workers_in_progress"
pruneInterval = heartbeatInterval * 5
)
type worker struct {
process
heartbeatTicker *time.Ticker
}
func newWorker(id string, queues []string) (*worker, error) {
process, err := newProcess(id, queues)
if err != nil {
return nil, err
}
return &worker{
process: *process,
heartbeatTicker: time.NewTicker(heartbeatInterval),
}, nil
}
func (w *worker) MarshalJSON() ([]byte, error) {
return json.Marshal(w.String())
}
func (w *worker) start(c *redis.Client, job *Job) error {
work := &work{
Queue: job.Queue,
RunAt: time.Now(),
Payload: job.Payload,
}
buffer, err := json.Marshal(work)
if err != nil {
return err
}
err = c.Set(ctx, fmt.Sprintf("%sworker:%s", workerSettings.Namespace, w.process.String()), buffer, 0).Err()
if err != nil {
return err
}
logger.Debugf("Processing %s since %s [%v]", work.Queue, work.RunAt, work.Payload.Class)
return w.process.start(c)
}
func (w *worker) startHeartbeat(c *redis.Client) {
go func() {
for {
select {
case <-w.heartbeatTicker.C:
err := c.HSet(ctx, fmt.Sprintf("%s%s", workerSettings.Namespace, heartbeatKey), w.process.String(), time.Now().Format(time.RFC3339)).Err()
if err != nil {
_ = logger.Errorf("Error on worker heartbeat %v: %v", w, err)
}
}
}
}()
}
func (w *worker) pruneDeadWorkers(c *redis.Client) {
// Block with set+nx+ex
ok, err := c.SetNX(ctx, fmt.Sprintf("%s%s", workerSettings.Namespace, keyForWorkersPruning), w.String(), heartbeatInterval.Truncate(time.Second)).Result()
if err != nil {
_ = logger.Criticalf("Error on setting lock to prune workers: %v", err)
return
}
if ok == false {
return
}
// Get all workers
workers, err := c.SMembers(ctx, fmt.Sprintf("%sworkers", workerSettings.Namespace)).Result()
if err != nil {
_ = logger.Criticalf("Error on getting list of all workers: %v", err)
return
}
// Get all workers that have sent a heartbeat and now is expired
heartbeatWorkers, err := c.HGetAll(ctx, fmt.Sprintf("%s%s", workerSettings.Namespace, heartbeatKey)).Result()
if err != nil {
_ = logger.Criticalf("Error on getting list of all workers with heartbeat: %v", err)
return
}
heartbeatExpiredWorkers := make(map[string]struct{})
for k, v := range heartbeatWorkers {
if v == "" {
continue
}
t, err := time.Parse(time.RFC3339, v)
if err != nil {
_ = logger.Criticalf("Error on parsing the time of %q: %v", v, err)
return
}
if time.Since(t) > pruneInterval {
heartbeatExpiredWorkers[k] = struct{}{}
}
}
// If a worker is on the expired list kill it
for _, w := range workers {
_, hbeok := heartbeatExpiredWorkers[w]
_, hbok := heartbeatWorkers[w]
// We want to prune workers that:
// * Are expired
// * Are not on the heartbeat set and ForcePrune is set
// If they are neither of those then we do not want to expire them
if hbeok || (!hbok && workerSettings.ForcePrune) {
logger.Infof("Pruning dead worker %q", w)
parts := strings.Split(w, ":")
pidAndID := strings.Split(parts[1], "-")
pid, _ := strconv.Atoi(pidAndID[0])
wp := process{
Hostname: parts[0],
Pid: pid,
ID: pidAndID[1],
Queues: strings.Split(parts[2], ","),
}
works, err := c.Get(ctx, fmt.Sprintf("%sworker:%s", workerSettings.Namespace, wp.String())).Result()
if err != nil && err != redis.Nil {
_ = logger.Criticalf("Error on getting worker for pruning: %v", err)
return
}
if works != "" {
var work = work{}
err = json.Unmarshal([]byte(works), &work)
if err != nil {
_ = logger.Criticalf("Error unmarshalling worker job: %v", err)
return
}
// If it has a job flag it as failed
wk := worker{process: wp}
err = wk.fail(c, &Job{
Queue: work.Queue,
Payload: work.Payload,
}, fmt.Errorf("worker %s did not gracefully exit while processing %s", wk.process.String(), work.Payload.Class))
if err != nil {
_ = logger.Criticalf("Error failing worker job: %v", err)
return
}
}
err = wp.close(c)
if err != nil {
_ = logger.Criticalf("Error closing connection to Redis: %v", err)
return
}
}
}
}
func (w *worker) fail(c *redis.Client, job *Job, err error) error {
_ = logger.Errorf("job failed with %+v;\npayload was %s\n", err, job.Payload)
failure := &failure{
FailedAt: time.Now(),
Payload: job.Payload,
Exception: "Error",
// %+v for errors with stack produces stack with file and method names and line numbers
Error: fmt.Sprintf("%+v", err),
Worker: w,
Queue: job.Queue,
}
buffer, err := json.Marshal(failure)
if err != nil {
return err
}
err = c.RPush(ctx, fmt.Sprintf("%sfailed", workerSettings.Namespace), buffer).Err()
if err != nil {
return err
}
return w.process.fail(c)
}
func (w *worker) succeed(c *redis.Client) error {
err := c.Incr(ctx, fmt.Sprintf("%sstat:processed", workerSettings.Namespace)).Err()
if err != nil {
return err
}
err = c.Incr(ctx, fmt.Sprintf("%sstat:processed:%s", workerSettings.Namespace, w)).Err()
if err != nil {
return err
}
return nil
}
func (w *worker) finish(c *redis.Client, job *Job, err error) error {
if err != nil {
err = w.fail(c, job, errors.WithStack(err))
if err != nil {
return errors.WithStack(err)
}
} else {
err = w.succeed(c)
if err != nil {
return err
}
}
return w.process.finish(c)
}
func (w *worker) work(jobs <-chan *Job, monitor *sync.WaitGroup) {
err := w.open(client)
if err != nil {
_ = logger.Criticalf("Error on opening worker %v: %v", w, err)
return
}
w.startHeartbeat(client)
defer w.heartbeatTicker.Stop()
monitor.Add(1)
go func() {
defer func() {
defer monitor.Done()
err := w.close(client)
if err != nil {
_ = logger.Criticalf("Error on closing worker %v: %v", w, err)
return
}
}()
for job := range jobs {
if workerFunc, ok := workers[job.Payload.Class]; ok {
w.run(job, workerFunc)
logger.Debugf("done: (Job{%s} | %s | %v)", job.Queue, job.Payload.Class, job.Payload.Args)
} else {
errorLog := fmt.Sprintf("No worker for %s in queue %s with args %v", job.Payload.Class, job.Queue, job.Payload.Args)
_ = logger.Critical(errorLog)
err := w.finish(client, job, errors.New(errorLog))
if err != nil {
_ = logger.Criticalf("Error on finishing worker %v: %v", w, err)
return
}
}
}
}()
}
func (w *worker) run(job *Job, workerFunc workerFunc) {
var err error
defer func() {
errFinish := w.finish(client, job, err)
if errFinish != nil {
_ = logger.Criticalf("Error on finishing worker %v: %v", w, errFinish)
return
}
}()
defer func() {
if r := recover(); r != nil {
err = errors.New(fmt.Sprint(r))
}
}()
errStart := w.start(client, job)
if errStart != nil {
_ = logger.Criticalf("Error on starting worker %v: %v", w, errStart)
return
}
err = workerFunc(job.Queue, job.Payload.Args...)
}