-
Notifications
You must be signed in to change notification settings - Fork 3
/
job.go
582 lines (455 loc) · 12.6 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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
package eventline
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"time"
"github.com/exograd/eventline/pkg/utils"
"github.com/exograd/go-daemon/check"
"github.com/exograd/go-daemon/djson"
"github.com/exograd/go-daemon/pg"
"github.com/jackc/pgx/v4"
"gopkg.in/yaml.v3"
)
var JobSorts Sorts = Sorts{
Sorts: map[string]string{
"id": "id",
"name": "spec->>'name'",
},
Default: "name",
}
type JobPageOptions struct {
ExcludeFavouriteJobAccountId *Id
}
type UnknownJobError struct {
Id Id
}
func (err UnknownJobError) Error() string {
return fmt.Sprintf("unknown job %q", err.Id)
}
type UnknownJobNameError struct {
Name string
}
func (err UnknownJobNameError) Error() string {
return fmt.Sprintf("unknown job %q", err.Name)
}
type StepFailureAction string
const (
StepFailureActionAbort StepFailureAction = "abort"
StepFailureActionContinue StepFailureAction = "continue"
)
var StepFailureActionValues = []StepFailureAction{
StepFailureActionAbort,
StepFailureActionContinue,
}
type Job struct {
Id Id `json:"id"`
ProjectId Id `json:"project_id"`
CreationTime time.Time `json:"creation_time"`
UpdateTime time.Time `json:"update_time"`
Disabled bool `json:"disabled,omitempty"`
Spec *JobSpec `json:"spec"`
}
type Jobs []*Job
type JobSpec struct {
Name string `json:"name"`
Description string `json:"description"`
Trigger *Trigger `json:"trigger,omitempty"`
Parameters Parameters `json:"parameters,omitempty"`
Runner *JobRunner `json:"runner"`
Concurrent bool `json:"concurrent,omitempty"`
Retention int `json:"retention,omitempty"` // days
Identities []string `json:"identities,omitempty"`
Environment map[string]string `json:"environment,omitempty"`
Steps Steps `json:"steps"`
}
type JobSpecs []*JobSpec
type JobRunner struct {
Name string `json:"name"`
Parameters RunnerParameters `json:"-"`
RawParameters json.RawMessage `json:"parameters"`
Identity string `json:"identity,omitempty"`
}
type RunnerParameters interface {
check.Object
}
type Trigger struct {
Event EventRef `json:"event"`
Parameters SubscriptionParameters `json:"-"`
RawParameters json.RawMessage `json:"parameters,omitempty"`
Identity string `json:"identity,omitempty"`
Filters Filters `json:"filters,omitempty"`
}
type Step struct {
Label string `json:"label,omitempty"`
Code string `json:"code,omitempty"`
Command *StepCommand `json:"command,omitempty"`
Script *StepScript `json:"script,omitempty"`
OnFailure StepFailureAction `json:"on_failure,omitempty"`
}
type Steps []*Step
type StepCommand struct {
Name string `json:"name"`
Arguments []string `json:"arguments,omitempty"`
}
type StepScript struct {
Path string `json:"path"`
Arguments []string `json:"arguments,omitempty"`
Content string `json:"content,omitempty"` // content of the script file
}
func (j *Job) SortKey(sort string) (key string) {
switch sort {
case "id":
key = j.Id.String()
case "name":
key = j.Spec.Name
default:
utils.Panicf("unknown job sort %q", sort)
}
return
}
func (spec JobSpec) Check(c *check.Checker) {
CheckName(c, "name", spec.Name)
if spec.Description != "" {
CheckDescription(c, "description", spec.Description)
}
c.CheckOptionalObject("trigger", spec.Trigger)
c.CheckObjectArray("parameters", spec.Parameters)
c.CheckOptionalObject("runner", spec.Runner)
if spec.Retention != 0 {
c.CheckIntMin("retention", spec.Retention, 1)
}
c.WithChild("identities", func() {
for i, iname := range spec.Identities {
CheckName(c, i, iname)
}
})
c.CheckObjectArray("steps", spec.Steps)
for i, s := range spec.Steps {
if s.Label == "" {
s.Label = "Step " + strconv.Itoa(i+1)
}
}
}
func (r *JobRunner) Check(c *check.Checker) {
runnerNames := make([]string, 0, len(RunnerDefs))
for name := range RunnerDefs {
runnerNames = append(runnerNames, name)
}
if c.CheckStringValue("name", r.Name, runnerNames) {
c.CheckObject("parameters", r.Parameters)
}
}
func (pr *JobRunner) MarshalJSON() ([]byte, error) {
type JobRunner2 JobRunner
r := JobRunner2(*pr)
// Careful here: in evcli, we do not have access to runner definitions, so
// we cannot decode runner parameters. We want to be able to read them
// into RawParameters and send them as-is to the server.
if r.RawParameters == nil {
params, err := json.Marshal(r.Parameters)
if err != nil {
return nil, fmt.Errorf("cannot encode parameters: %w", err)
}
r.RawParameters = params
}
return json.Marshal(r)
}
func (pr *JobRunner) UnmarshalJSON(data []byte) error {
type JobRunner2 JobRunner
r := JobRunner2(*pr)
if err := json.Unmarshal(data, &r); err != nil {
return err
}
if def, found := RunnerDefs[r.Name]; found {
params := def.InstantiateParameters()
// Note that at this moment, Check has not been called yet, so the
// runner name may be invalid. It is better to let Check validate it
// so that users get full validation errors.
if r.RawParameters != nil {
d := json.NewDecoder(bytes.NewReader(r.RawParameters))
d.DisallowUnknownFields()
if err := d.Decode(params); err != nil {
return fmt.Errorf("invalid runner parameters: %w", err)
}
}
r.Parameters = params
}
*pr = JobRunner(r)
return nil
}
func (t *Trigger) Check(c *check.Checker) {
CheckEventRef(c, "event", t.Event)
c.CheckOptionalObject("parameters", t.Parameters)
c.CheckObjectArray("filters", t.Filters)
}
func (pt *Trigger) MarshalJSON() ([]byte, error) {
type Trigger2 Trigger
t := Trigger2(*pt)
if t.Parameters != nil {
parametersData, err := json.Marshal(t.Parameters)
if err != nil {
return nil, fmt.Errorf("cannot encode parameters: %w", err)
}
t.RawParameters = parametersData
}
return json.Marshal(t)
}
func (pt *Trigger) UnmarshalJSON(data []byte) error {
type Trigger2 Trigger
t := Trigger2(*pt)
if err := json.Unmarshal(data, &t); err != nil {
return err
}
// If the connector or event are invalid, let validation
// (Trigger.Check) signal the error.
if t.RawParameters != nil && EventDefExists(t.Event) {
edef := GetEventDef(t.Event)
parameters, err := edef.DecodeSubscriptionParameters(t.RawParameters)
if err != nil {
return fmt.Errorf("cannot decode parameters: %w", err)
}
t.Parameters = parameters
}
*pt = Trigger(t)
return nil
}
func (s *Step) Check(c *check.Checker) {
if s.Label != "" {
CheckLabel(c, "label", s.Label)
}
n := 0
if s.Code != "" {
n += 1
}
if s.Command != nil {
n += 1
}
if s.Script != nil {
n += 1
}
if n == 0 {
c.AddError(djson.Pointer{}, "missing_step_content",
"missing code, command or script member")
} else if n > 1 {
c.AddError(djson.Pointer{}, "multiple_step_contents",
"multiple code, command or script members")
}
c.CheckOptionalObject("command", s.Command)
c.CheckOptionalObject("script", s.Script)
}
func (s *StepCommand) Check(c *check.Checker) {
c.CheckStringNotEmpty("name", s.Name)
}
func (s *StepScript) Check(c *check.Checker) {
c.CheckStringNotEmpty("path", s.Path)
}
func (spec *JobSpec) ParseYAML(data []byte) error {
decoder := yaml.NewDecoder(bytes.NewReader(data))
var yamlValue interface{}
if err := decoder.Decode(&yamlValue); err != nil {
return err
}
jsonValue, err := utils.YAMLValueToJSONValue(yamlValue)
if err != nil {
return fmt.Errorf("invalid yaml data: %w", err)
}
jsonData, err := json.Marshal(jsonValue)
if err != nil {
return fmt.Errorf("cannot encode json data: %w", err)
}
d := json.NewDecoder(bytes.NewReader(jsonData))
d.DisallowUnknownFields()
if err := d.Decode(spec); err != nil {
return fmt.Errorf("cannot decode json data: %w", err)
}
return nil
}
func (spec *JobSpec) IdentityNames() []string {
var names []string
if spec.Trigger != nil && spec.Trigger.Identity != "" {
names = append(names, spec.Trigger.Identity)
}
if spec.Runner != nil && spec.Runner.Identity != "" {
names = append(names, spec.Runner.Identity)
}
names = append(names, spec.Identities...)
return names
}
func (j *Job) Load(conn pg.Conn, id Id, scope Scope) error {
query := fmt.Sprintf(`
SELECT id, project_id, creation_time, update_time, disabled, spec
FROM jobs
WHERE %s AND id = $1;
`, scope.SQLCondition())
err := pg.QueryObject(conn, j, query, id)
if errors.Is(err, pgx.ErrNoRows) {
return &UnknownJobError{Id: id}
}
return err
}
func (j *Job) LoadForUpdate(conn pg.Conn, id Id, scope Scope) error {
query := fmt.Sprintf(`
SELECT id, project_id, creation_time, update_time, disabled, spec
FROM jobs
WHERE %s AND id = $1
FOR UPDATE;
`, scope.SQLCondition())
err := pg.QueryObject(conn, j, query, id)
if errors.Is(err, pgx.ErrNoRows) {
return &UnknownJobError{Id: id}
}
return err
}
func (j *Job) LoadByName(conn pg.Conn, name string, scope Scope) error {
query := fmt.Sprintf(`
SELECT id, project_id, creation_time, update_time, disabled, spec
FROM jobs
WHERE %s AND spec->>'name' = $1;
`, scope.SQLCondition())
err := pg.QueryObject(conn, j, query, name)
if errors.Is(err, pgx.ErrNoRows) {
return &UnknownJobNameError{Name: name}
}
return err
}
func (js *Jobs) LoadByIdentityName(conn pg.Conn, name string, scope Scope) error {
query := fmt.Sprintf(`
SELECT id, project_id, creation_time, update_time, disabled, spec
FROM jobs
WHERE %s
AND (spec->'trigger'->>'identity' = $1
OR spec->'runner'->>'identity' = $1
OR spec->'identities' ? $1)
ORDER BY id
`, scope.SQLCondition())
return pg.QueryObjects(conn, js, query, name)
}
func LoadJobNamesById(conn pg.Conn, ids Ids) (map[Id]string, error) {
ctx := context.Background()
query := `
SELECT id, spec->>'name'
FROM jobs
WHERE id = ANY ($1)
`
rows, err := conn.Query(ctx, query, ids)
if err != nil {
return nil, err
}
names := make(map[Id]string)
for rows.Next() {
var id Id
var name string
if err := rows.Scan(&id, &name); err != nil {
return nil, err
}
names[id] = name
}
if err := rows.Err(); err != nil {
return nil, err
}
return names, nil
}
func LoadJobPage(conn pg.Conn, options JobPageOptions, cursor *Cursor, scope Scope) (*Page, error) {
favouriteJobsJoin := ``
favouriteJobsCond := `TRUE`
if options.ExcludeFavouriteJobAccountId != nil {
favouriteJobsJoin = fmt.Sprintf(`LEFT JOIN favourite_jobs AS fj
ON fj.job_id = j.id AND fj.account_id = %s
`, pg.QuoteString(options.ExcludeFavouriteJobAccountId.String()))
favouriteJobsCond = `fj.job_id IS NULL`
}
query := fmt.Sprintf(`
SELECT j.id, j.project_id, j.creation_time, j.update_time, j.disabled, j.spec
FROM jobs AS j
%s
WHERE %s AND %s AND %s;
`,
favouriteJobsJoin,
favouriteJobsCond,
scope.SQLCondition2("j"),
cursor.SQLConditionOrderLimit2(JobSorts, "j"))
var jobs Jobs
if err := pg.QueryObjects(conn, &jobs, query); err != nil {
return nil, err
}
return jobs.Page(cursor), nil
}
func (j *Job) Upsert(conn pg.Conn) (Id, error) {
ctx := context.Background()
query := `
INSERT INTO jobs
(id, project_id, creation_time, update_time, disabled, spec)
VALUES
($1, $2, $3, $4, $5, $6)
ON CONFLICT (project_id, (spec->>'name')) DO UPDATE SET
update_time = EXCLUDED.update_time,
disabled = EXCLUDED.disabled,
spec = EXCLUDED.spec
RETURNING id
`
var id Id
row := conn.QueryRow(ctx, query,
j.Id, j.ProjectId, j.CreationTime, j.UpdateTime, j.Disabled, j.Spec)
if err := row.Scan(&id); err != nil {
return ZeroId, err
}
return id, nil
}
func (j *Job) Update(conn pg.Conn, scope Scope) error {
query := fmt.Sprintf(`
UPDATE jobs SET
update_time = $2,
disabled = $3,
spec = $4
WHERE %s AND id = $1;
`, scope.SQLCondition())
return pg.Exec(conn, query,
j.Id, j.UpdateTime, j.Disabled, j.Spec)
}
func (j *Job) Delete(conn pg.Conn, scope Scope) error {
query := fmt.Sprintf(`
DELETE FROM jobs
WHERE %s AND id = $1;
`, scope.SQLCondition())
return pg.Exec(conn, query, j.Id)
}
func DeleteJobs(conn pg.Conn, scope Scope) error {
query := fmt.Sprintf(`
DELETE FROM jobs
WHERE %s
`, scope.SQLCondition())
return pg.Exec(conn, query)
}
func (js Jobs) Page(cursor *Cursor) *Page {
elements := make([]PageElement, len(js))
for i, j := range js {
elements[i] = j
}
return NewPage(cursor, elements, JobSorts)
}
func (j *Job) FromRow(row pgx.Row) error {
return row.Scan(&j.Id, &j.ProjectId, &j.CreationTime, &j.UpdateTime,
&j.Disabled, &j.Spec)
}
func (js *Jobs) AddFromRow(row pgx.Row) error {
var j Job
if err := j.FromRow(row); err != nil {
return err
}
*js = append(*js, &j)
return nil
}
func (s *Step) AbortOnFailure() bool {
switch s.OnFailure {
case StepFailureActionAbort:
return true
case StepFailureActionContinue:
return false
default:
return true
}
}