forked from albrow/jobs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
job.go
473 lines (434 loc) · 14 KB
/
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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
// Copyright 2015 Alex Browne. All rights reserved.
// Use of this source code is governed by the MIT
// license, which can be found in the LICENSE file.
package jobs
import (
"fmt"
"github.com/garyburd/redigo/redis"
"time"
)
// Job represents a discrete piece of work to be done by a worker.
type Job struct {
id string
data []byte
typ *Type
status Status
time int64
freq int64
priority int
err error
retries uint
started int64
finished int64
poolId string
}
// ErrorJobNotFound is returned whenever a specific job is not found,
// e.g. from the FindById function.
type ErrorJobNotFound struct {
id string
}
func (e ErrorJobNotFound) Error() string {
if e.id == "" {
return fmt.Sprintf("jobs: Could not find job with the given criteria.")
}
return fmt.Sprintf("jobs: Could not find job with id: %s", e.id)
}
// Id returns the unique identifier used for the job. If the job has not yet
// been saved to the database, it may return an empty string.
func (j *Job) Id() string {
return j.id
}
// Data returns the gob-encoded data of the job
func (j *Job) Data() []byte {
return j.data
}
// Status returns the status of the job.
func (j *Job) Status() Status {
return j.status
}
// Time returns the time at which the job should be executed in UTC UNIX
// format with nanosecond precision.
func (j *Job) Time() int64 {
return j.time
}
// Freq returns the frequency at which the job should be executed. Specifically
// it returns the number of nanoseconds between each scheduled execution.
func (j *Job) Freq() int64 {
return j.freq
}
// Priority returns the job's priority.
func (j *Job) Priority() int {
return j.priority
}
// Error returns the last error that arose during execution of the job. It is
// only non-nil if the job has failed at some point.
func (j *Job) Error() error {
return j.err
}
// Retries returns the number of remaining retries for the job.
func (j *Job) Retries() uint {
return j.retries
}
// Started returns the time that the job started executing (in local time
// with nanosecond precision) or the zero time if the job has not started
// executing yet.
func (j *Job) Started() time.Time {
return time.Unix(0, j.started).Local()
}
// Finished returns the time that the job finished executing (in local
// time with nanosecond precision) or the zero time if the job has not
// finished executing yet.
func (j *Job) Finished() time.Time {
return time.Unix(0, j.finished).Local()
}
// PoolId returns the pool id of the job if it is currently being executed
// or has been executed and at some point has been assigned to a specific pool.
// Otherwise, it returns an empty string.
func (j *Job) PoolId() string {
return j.poolId
}
// Duration returns how long the job took to execute with nanosecond
// precision. I.e. the difference between j.Finished() and j.Started().
// It returns a duration of zero if the job has not finished yet.
func (j *Job) Duration() time.Duration {
if j.Finished().IsZero() {
return 0 * time.Second
}
return j.Finished().Sub(j.Started())
}
// Key returns the key used for the hash in redis which stores all the
// fields for this job.
func (j *Job) Key() string {
return "jobs:" + j.id
}
// IsRecurring returns true iff the job is recurring
func (j *Job) IsRecurring() bool {
return j.freq != 0
}
// NextTime returns the time (unix UTC with nanosecond precision) that the
// job should execute next, if it is a recurring job, and 0 if it is not.
func (j *Job) NextTime() int64 {
if !j.IsRecurring() {
return 0
}
// NOTE: is this the proper way to handle rescheduling?
// What if we schedule jobs faster than they can be executed?
// Should we just let them build up and expect the end user to
// allocate more workers? Or should we schedule for time.Now at
// the earliest to prevent buildup?
return j.time + j.freq
}
// save writes the job to the database and adds it to the appropriate indexes and status
// sets, but does not enqueue it. If you want to add it to the queue, use the enqueue method
// after save.
func (j *Job) save() error {
t := newTransaction()
t.saveJob(j)
if err := t.exec(); err != nil {
return err
}
return nil
}
// saveJob adds commands to the transaction to set all the fields for the main hash for the job,
// add the job to the time index, move the job to the appropriate status set. It will
// also mutate the job by 1) generating an id if the id is empty and 2) setting the status to
// StatusSaved if the status is empty.
func (t *transaction) saveJob(job *Job) {
// Generate id if needed
if job.id == "" {
job.id = generateRandomId()
}
// Set status to saved if needed
if job.status == "" {
job.status = StatusSaved
}
// Add the job attributes to a hash
t.command("HMSET", job.mainHashArgs(), nil)
// Add the job to the appropriate status set
t.setStatus(job, job.status)
// Add the job to the time index
t.addJobToTimeIndex(job)
}
// addJobToTimeIndex adds commands to the transaction which will, when executed,
// add the job id to the time index with a score equal to the job's time field.
// If the job has been destroyed, addJobToTimeIndex will have no effect.
func (t *transaction) addJobToTimeIndex(job *Job) {
t.addJobToSet(job, Keys.JobsTimeIndex, float64(job.time))
}
// Refresh mutates the job by setting its fields to the most recent data
// found in the database. It returns an error if there was a problem connecting
// to the database or if the job was destroyed.
func (j *Job) Refresh() error {
t := newTransaction()
t.scanJobById(j.id, j)
if err := t.exec(); err != nil {
return err
}
return nil
}
// enqueue adds the job to the queue and sets its status to StatusQueued. Queued jobs will
// be completed by workers in order of priority. Attempting to enqueue a destroyed job
// will have no effect.
func (j *Job) enqueue() error {
if err := j.setStatus(StatusQueued); err != nil {
return err
}
return nil
}
// Reschedule reschedules the job with the given time. It can be used to reschedule
// cancelled jobs. It may also be used to reschedule finished or failed jobs, however,
// in most cases if you want to reschedule finished jobs you should use the ScheduleRecurring
// method and if you want to reschedule failed jobs, you should set the number of retries > 0
// when registering the job type. Attempting to reschedule a destroyed job will have no effect.
// Reschedule returns an error if there was a problem connecting to the database.
func (j *Job) Reschedule(time time.Time) error {
t := newTransaction()
unixNanoTime := time.UTC().UnixNano()
t.setJobField(j, "time", unixNanoTime)
t.setStatus(j, StatusQueued)
j.time = unixNanoTime
t.addJobToTimeIndex(j)
if err := t.exec(); err != nil {
return err
}
j.status = StatusQueued
return nil
}
// Cancel cancels the job, but does not remove it from the database. It will be
// added to a list of cancelled jobs. If you wish to remove it from the database,
// use the Destroy method. Attempting to cancel a destroyed job will have no effect.
func (j *Job) Cancel() error {
if err := j.setStatus(StatusCancelled); err != nil {
return err
}
return nil
}
// setError sets the err property of j and adds it to the set of jobs which had errors.
// If the job has been destroyed, setError will have no effect.
func (j *Job) setError(err error) error {
j.err = err
t := newTransaction()
t.setJobField(j, "error", j.err.Error())
if err := t.exec(); err != nil {
return err
}
return nil
}
// Destroy removes all traces of the job from the database. If the job is currently
// being executed by a worker, the worker may still finish the job. Attempting to
// destroy a job that has already been destroyed will have no effect, so it is safe
// to call Destroy multiple times.
func (j *Job) Destroy() error {
if j.id == "" {
return fmt.Errorf("jobs: Cannot destroy job that doesn't have an id.")
}
// Start a new transaction
t := newTransaction()
// Call the script to destroy the job
t.destroyJob(j)
// Execute the transaction
if err := t.exec(); err != nil {
return err
}
j.status = StatusDestroyed
return nil
}
// setStatus updates the job's status in the database and moves it to the appropriate
// status set. Attempting to set the status of a job which has been destroyed will have
// no effect.
func (j *Job) setStatus(status Status) error {
if j.id == "" {
return fmt.Errorf("jobs: Cannot set status to %s because job doesn't have an id.", status)
}
if j.status == StatusDestroyed {
return fmt.Errorf("jobs: Cannot set job:%s status to %s because it was destroyed.", j.id, status)
}
// Use a transaction to move the job to the appropriate status set and set its status
t := newTransaction()
t.setStatus(j, status)
if err := t.exec(); err != nil {
return err
}
j.status = status
return nil
}
// mainHashArgs returns the args for the hash which will store the job data
func (j *Job) mainHashArgs() []interface{} {
hashArgs := []interface{}{j.Key(),
"data", string(j.data),
"type", j.typ.name,
"time", j.time,
"freq", j.freq,
"priority", j.priority,
"retries", j.retries,
"status", j.status,
"started", j.started,
"finished", j.finished,
"poolId", j.poolId,
}
if j.err != nil {
hashArgs = append(hashArgs, "error", j.err.Error())
}
return hashArgs
}
// scanJob scans the values of reply into job. reply should be the
// response of an HMGET or HGETALL query.
func scanJob(reply interface{}, job *Job) error {
fields, err := redis.Values(reply, nil)
if err != nil {
return err
} else if len(fields) == 0 {
return ErrorJobNotFound{}
} else if len(fields)%2 != 0 {
return fmt.Errorf("jobs: In scanJob: Expected length of fields to be even but got: %d", len(fields))
}
for i := 0; i < len(fields)-1; i += 2 {
fieldName, err := redis.String(fields[i], nil)
if err != nil {
return fmt.Errorf("jobs: In scanJob: Could not convert fieldName (fields[%d] = %v) of type %T to string.", i, fields[i], fields[i])
}
fieldValue := fields[i+1]
switch fieldName {
case "id":
if err := scanString(fieldValue, &(job.id)); err != nil {
return err
}
case "data":
if err := scanBytes(fieldValue, &(job.data)); err != nil {
return err
}
case "type":
typeName := ""
if err := scanString(fieldValue, &typeName); err != nil {
return err
}
Type, found := Types[typeName]
if !found {
return fmt.Errorf("jobs: In scanJob: Could not find Type with name = %s", typeName)
}
job.typ = Type
case "time":
if err := scanInt64(fieldValue, &(job.time)); err != nil {
return err
}
case "freq":
if err := scanInt64(fieldValue, &(job.freq)); err != nil {
return err
}
case "priority":
if err := scanInt(fieldValue, &(job.priority)); err != nil {
return err
}
case "retries":
if err := scanUint(fieldValue, &(job.retries)); err != nil {
return err
}
case "status":
status := ""
if err := scanString(fieldValue, &status); err != nil {
return err
}
job.status = Status(status)
case "started":
if err := scanInt64(fieldValue, &(job.started)); err != nil {
return err
}
case "finished":
if err := scanInt64(fieldValue, &(job.finished)); err != nil {
return err
}
case "poolId":
if err := scanString(fieldValue, &(job.poolId)); err != nil {
return err
}
}
}
return nil
}
// scanInt converts a reply from redis into an int and scans the value into v.
func scanInt(reply interface{}, v *int) error {
if v == nil {
return fmt.Errorf("jobs: In scanInt: argument v was nil")
}
val, err := redis.Int(reply, nil)
if err != nil {
return fmt.Errorf("jobs: In scanInt: Could not convert %v of type %T to int.", reply, reply)
}
(*v) = val
return nil
}
// scanUint converts a reply from redis into a uint and scans the value into v.
func scanUint(reply interface{}, v *uint) error {
if v == nil {
return fmt.Errorf("jobs: In scanUint: argument v was nil")
}
val, err := redis.Uint64(reply, nil)
if err != nil {
return fmt.Errorf("jobs: In scanUint: Could not convert %v of type %T to uint.", reply, reply)
}
(*v) = uint(val)
return nil
}
// scanInt64 converts a reply from redis into an int64 and scans the value into v.
func scanInt64(reply interface{}, v *int64) error {
if v == nil {
return fmt.Errorf("jobs: In scanInt64: argument v was nil")
}
val, err := redis.Int64(reply, nil)
if err != nil {
return fmt.Errorf("jobs: In scanInt64: Could not convert %v of type %T to int64.", reply, reply)
}
(*v) = val
return nil
}
// scanString converts a reply from redis into a string and scans the value into v.
func scanString(reply interface{}, v *string) error {
if v == nil {
return fmt.Errorf("jobs: In String: argument v was nil")
}
val, err := redis.String(reply, nil)
if err != nil {
return fmt.Errorf("jobs: In String: Could not convert %v of type %T to string.", reply, reply)
}
(*v) = val
return nil
}
// scanBytes converts a reply from redis into a slice of bytes and scans the value into v.
func scanBytes(reply interface{}, v *[]byte) error {
if v == nil {
return fmt.Errorf("jobs: In scanBytes: argument v was nil")
}
val, err := redis.Bytes(reply, nil)
if err != nil {
return fmt.Errorf("jobs: In scanBytes: Could not convert %v of type %T to []byte.", reply, reply)
}
(*v) = val
return nil
}
// scanJobById adds commands and a reply handler to the transaction which, when run,
// will scan the values of the job corresponding to id into job. It does not execute
// the transaction.
func (t *transaction) scanJobById(id string, job *Job) {
job.id = id
t.command("HGETALL", redis.Args{job.Key()}, newScanJobHandler(job))
}
// FindById returns the job with the given id or an error if the job cannot be found
// (in which case the error will have type ErrorJobNotFound) or there was a problem
// connecting to the database.
func FindById(id string) (*Job, error) {
job := &Job{}
t := newTransaction()
t.scanJobById(id, job)
if err := t.exec(); err != nil {
switch e := err.(type) {
case ErrorJobNotFound:
// If the job was not found, add the id to the error
// so that the caller can get a more useful error message.
e.id = id
return nil, e
default:
return nil, err
}
}
return job, nil
}