/
jobs.go
823 lines (754 loc) · 25.1 KB
/
jobs.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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
package api
import (
"context"
"fmt"
"log"
"reflect"
"time"
"github.com/brigadecore/brigade/v2/apiserver/internal/meta"
"github.com/pkg/errors"
)
// JobKind represents the canonical Job kind string
const JobKind = "Job"
// OSFamily represents a type of operating system.
type OSFamily string
const (
// OSFamilyLinux represents a Linux-based OS.
OSFamilyLinux OSFamily = "linux"
// OSFamilyWindows represents a Windows-based OS.
OSFamilyWindows OSFamily = "windows"
)
// JobPhase represents where a Job is within its lifecycle.
type JobPhase string
const (
// JobPhaseAborted represents the state wherein a Job was forcefully
// stopped during execution.
JobPhaseAborted JobPhase = "ABORTED"
// JobPhaseCanceled represents the state wherein a pending Job was
// canceled prior to execution.
JobPhaseCanceled JobPhase = "CANCELED"
// JobPhaseFailed represents the state wherein a Job has run to
// completion but experienced errors.
JobPhaseFailed JobPhase = "FAILED"
// JobPhasePending represents the state wherein a Job is awaiting
// execution.
JobPhasePending JobPhase = "PENDING"
// JobPhaseRunning represents the state wherein a Job is currently
// being executed.
JobPhaseRunning JobPhase = "RUNNING"
// JobPhaseSchedulingFailed represents the state wherein a Job was not
// scheduled due to some unexpected and unrecoverable error encountered by the
// scheduler.
JobPhaseSchedulingFailed JobPhase = "SCHEDULING_FAILED"
// JobPhaseStarting represents the state wherein a Job is starting on the
// substrate but isn't running yet.
JobPhaseStarting JobPhase = "STARTING"
// JobPhaseSucceeded represents the state where a Job has run to
// completion without error.
JobPhaseSucceeded JobPhase = "SUCCEEDED"
// JobPhaseTimedOut represents the state wherein a Job has has not completed
// within a designated timeframe.
JobPhaseTimedOut JobPhase = "TIMED_OUT"
// JobPhaseUnknown represents the state wherein a Job's state is unknown. Note
// that this is possible if and only if the underlying Job execution substrate
// (Kubernetes), for some unanticipated, reason does not know the Job's
// (Pod's) state.
JobPhaseUnknown JobPhase = "UNKNOWN"
)
// IsTerminal returns a bool indicating whether the JobPhase is terminal.
func (j JobPhase) IsTerminal() bool {
switch j {
case JobPhaseAborted:
fallthrough
case JobPhaseCanceled:
fallthrough
case JobPhaseFailed:
fallthrough
case JobPhaseSchedulingFailed:
fallthrough
case JobPhaseSucceeded:
fallthrough
case JobPhaseTimedOut:
return true
}
return false
}
// Job represents a component spawned by a Worker to complete a single task
// in the course of handling an Event.
type Job struct {
// Name is the Job's name. It should be unique among a given Worker's Jobs.
Name string `json:"name" bson:"name"`
// Created indicates the time at which a Job was created.
Created *time.Time `json:"created,omitempty"`
// Spec is the technical blueprint for the Job.
Spec JobSpec `json:"spec" bson:"spec"`
// Status contains details of the Job's current state.
Status *JobStatus `json:"status" bson:"status"`
}
// UsesWorkspace returns a boolean value indicating whether or not the job
// uses a shared workspace.
func (j Job) UsesWorkspace() bool {
if j.Spec.PrimaryContainer.WorkspaceMountPath != "" {
return true
}
for _, sidecarContainer := range j.Spec.SidecarContainers {
if sidecarContainer.WorkspaceMountPath != "" {
return true
}
}
return false
}
// JobSpec is the technical blueprint for a Job.
type JobSpec struct {
// PrimaryContainer specifies the details of an OCI container that forms the
// cornerstone of the Job. Job success or failure is tied to completion and
// exit code of this container.
PrimaryContainer JobContainerSpec `json:"primaryContainer" bson:"primaryContainer"` // nolint: lll
// SidecarContainers specifies the details of supplemental, "sidecar"
// containers. Their completion and exit code do not directly impact Job
// status. Brigade does not understand dependencies between a Job's multiple
// containers and cannot enforce any specific startup or shutdown order. When
// such dependencies exist (for instance, a primary container than cannot
// proceed with a suite of tests until a database is launched and READY in a
// sidecar container), then logic within those containers must account for
// these constraints.
SidecarContainers map[string]JobContainerSpec `json:"sidecarContainers,omitempty" bson:"sidecarContainers,omitempty"` // nolint: lll
// TimeoutDuration specifies the time duration that must elapse before a
// running Job should be considered to have timed out. This duration string
// is a sequence of decimal numbers, each with optional fraction and a unit
// suffix, such as "300ms", "3.14s" or "2h45m".
// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
TimeoutDuration string `json:"timeoutDuration,omitempty" bson:"timeoutDuration,omitempty"` // nolint: lll
// Host specifies criteria for selecting a suitable host (substrate node) for
// the Job. This is useful in cases where a Job requires a specific,
// non-default operating system (i.e. Windows) or specific hardware (e.g. a
// GPU.)
Host *JobHost `json:"host,omitempty" bson:"host,omitempty"`
// Fallible specifies whether the job is permitted to fail WITHOUT causing the
// worker process to fail. The API server does not use this field directly,
// but it is information that may be valuable to gateways that report job
// success/failure upstream to original event sources.
Fallible bool `json:"fallible" bson:"fallible"`
}
func (js JobSpec) EqualTo(js2 JobSpec) bool {
// Compare PrimaryContainers; if equivalent, nil out
if !js.PrimaryContainer.EqualTo(js2.PrimaryContainer) {
return false
}
js.PrimaryContainer, js2.PrimaryContainer =
JobContainerSpec{}, JobContainerSpec{}
// Compare SidecarContainers maps; if equivalent, nil out
if len(js.SidecarContainers) != len(js2.SidecarContainers) {
return false
}
for name, sidecarContainer := range js.SidecarContainers {
if !sidecarContainer.EqualTo(js2.SidecarContainers[name]) {
return false
}
}
js.SidecarContainers, js2.SidecarContainers = nil, nil
// Compare Host; if equivalent, nil out
if js.Host == nil || js2.Host == nil {
if js.Host == nil && js2.Host == nil {
return reflect.DeepEqual(js, js2)
}
return false
}
js.Host, js2.Host = nil, nil
return reflect.DeepEqual(js, js2)
}
// JobContainerSpec amends the ContainerSpec type with additional Job-specific
// fields.
type JobContainerSpec struct {
// ContainerSpec encapsulates generic specifications for an OCI container.
ContainerSpec `json:",inline" bson:",inline"`
// WorkingDirectory specifies the OCI container's working directory.
WorkingDirectory string `json:"workingDirectory,omitempty" bson:"workingDirectory,omitempty"` // nolint: lll
// WorkspaceMountPath specifies the path in the OCI container's file system
// where, if applicable, the Worker's shared workspace should be mounted. If
// left blank, the Job implicitly does not use the Worker's shared workspace.
WorkspaceMountPath string `json:"workspaceMountPath,omitempty" bson:"workspaceMountPath,omitempty"` // nolint: lll
// SourceMountPath specifies the path in the OCI container's file system
// where, if applicable, source code retrieved from a VCS repository should be
// mounted. If left blank, the Job implicitly does not use source code
// retrieved from a VCS repository.
SourceMountPath string `json:"sourceMountPath,omitempty" bson:"sourceMountPath,omitempty"` // nolint: lll
// Privileged indicates whether the OCI container should operate in a
// "privileged" (relaxed permissions) mode. This is commonly used to effect
// "Docker-in-Docker" ("DinD") scenarios wherein one of a Job's OCI containers
// must run its own Docker daemon. Note this field REQUESTS privileged status
// for the container, but that may be disallowed by Project-level
// configuration.
Privileged bool `json:"privileged" bson:"privileged"`
// UseHostDockerSocket indicates whether the OCI container should mount the
// host's Docker socket into its own file system. This is commonly used to
// effect "Docker-out-of-Docker" ("DooD") scenarios wherein one of a Job's OCI
// containers must utilize the host's Docker daemon. GENERALLY, THIS IS HIGHLY
// DISCOURAGED. Note this field REQUESTS to mount the host's Docker socket
// into the container, but that may be disallowed by Project-level
// configuration.
//
// Note: This is being removed for the 2.0.0 release because of security
// issues AND declining usefulness. (Many Kubernetes distros now use
// containerd instead of Docker.) This can be put back in the future if the
// need is proven AND if it can be done safely.
//
// For more details, see https://github.com/brigadecore/brigade/issues/1666
//
// nolint: lll
// UseHostDockerSocket bool `json:"useHostDockerSocket" bson:"useHostDockerSocket"`
}
func (jcs JobContainerSpec) EqualTo(jcs2 JobContainerSpec) bool {
// Compare ContainerSpecs; if equivalent, nil out
if !jcs.ContainerSpec.EqualTo(jcs2.ContainerSpec) {
return false
}
jcs.ContainerSpec, jcs2.ContainerSpec = ContainerSpec{}, ContainerSpec{}
return reflect.DeepEqual(jcs, jcs2)
}
// JobHost represents criteria for selecting a suitable host (substrate node)
// for a Job.
type JobHost struct {
// OS specifies which "family" of operating system is required on a substrate
// node to host a Job. Valid values are "linux" and "windows". When empty,
// Brigade assumes "linux".
OS OSFamily `json:"os,omitempty" bson:"os,omitempty"`
// NodeSelector specifies labels that must be present on the substrate node to
// host a Job. This provides an opaque mechanism for communicating Job needs
// such as specific hardware like an SSD or GPU.
NodeSelector map[string]string `json:"nodeSelector,omitempty" bson:"nodeSelector,omitempty"` // nolint: lll
}
func (jh *JobHost) EqualTo(jh2 *JobHost) bool {
// Compare NodeSelector maps; if equivalent, nil out
if len(jh.NodeSelector) != len(jh2.NodeSelector) {
return false
}
for k, v := range jh.NodeSelector {
if v != jh2.NodeSelector[k] {
return false
}
}
jh.NodeSelector, jh2.NodeSelector = nil, nil
return reflect.DeepEqual(jh, jh2)
}
// JobStatus represents the status of a Job.
type JobStatus struct {
// Started indicates the time the Job began execution.
Started *time.Time `json:"started,omitempty" bson:"started,omitempty"`
// Ended indicates the time the Job concluded execution. It will be nil
// for a Job that is not done executing.
Ended *time.Time `json:"ended,omitempty" bson:"ended,omitempty"`
// Phase indicates where the Job is in its lifecycle.
Phase JobPhase `json:"phase,omitempty" bson:"phase,omitempty"`
// LogsEventID indicates which event ID the job logs are associated with.
// This is useful for looking up logs for an inherited job associated with
// retry events.
LogsEventID string `json:"logsEventID,omitempty" bson:"logsEventID,omitempty"`
}
// JobsService is the specialized interface for managing Jobs. It's
// decoupled from underlying technology choices (e.g. data store, message bus,
// etc.) to keep business logic reusable and consistent while the underlying
// tech stack remains free to change.
type JobsService interface {
// Create, given an Event identifier and Job, creates a new Job and schedules
// it on Brigade's workload execution substrate. If the specified Event does
// not exist, implementations MUST return a *meta.ErrNotFound error. If the
// specified Event already has a Job with the specified name, implementations
// MUST return a *meta.ErrConflict error.
Create(ctx context.Context, eventID string, job Job) error
// Start, given an Event identifier and Job name, starts that Job on
// Brigade's workload execution substrate. If the specified Event or specified
// Job thereof does not exist, implementations MUST return a *meta.ErrNotFound
// error.
Start(ctx context.Context, eventID string, jobName string) error
// GetStatus, given an Event identifier and Job name, returns the Job's
// status. If the specified Event or specified Job thereof does not exist,
// implementations MUST return a *meta.ErrNotFound error.
GetStatus(
ctx context.Context,
eventID string,
jobName string,
) (JobStatus, error)
// WatchStatus, given an Event identifier and Job name, returns a channel over
// which the Job's status is streamed. The channel receives a new JobStatus
// every time there is any change in that status. If the specified Event or
// specified Job thereof does not exist, implementations MUST return a
// *meta.ErrNotFound error.
WatchStatus(
ctx context.Context,
eventID string,
jobName string,
) (<-chan JobStatus, error)
// UpdateStatus, given an Event identifier and Job name, updates the status of
// that Job. If the specified Event or specified Job thereof does not exist,
// implementations MUST return a *meta.ErrNotFound error.
UpdateStatus(
ctx context.Context,
eventID string,
jobName string,
status JobStatus,
) error
// Cleanup removes Job-related resources from the substrate, presumably
// upon completion, without deleting the Job from the data store.
Cleanup(ctx context.Context, eventID, jobName string) error
// Timeout updates a Job's status to indicate it has timed out and proceeds
// to cleanup Job-related resources from the substrate.
Timeout(ctx context.Context, eventID, jobName string) error
}
type jobsService struct {
authorize AuthorizeFn
projectsStore ProjectsStore
eventsStore EventsStore
jobsStore JobsStore
substrate Substrate
}
// NewJobsService returns a specialized interface for managing Jobs.
func NewJobsService(
authorizeFn AuthorizeFn,
projectsStore ProjectsStore,
eventsStore EventsStore,
jobsStore JobsStore,
substrate Substrate,
) JobsService {
return &jobsService{
authorize: authorizeFn,
projectsStore: projectsStore,
eventsStore: eventsStore,
jobsStore: jobsStore,
substrate: substrate,
}
}
// nolint: gocyclo
func (j *jobsService) Create(
ctx context.Context,
eventID string,
job Job,
) error {
if err := j.authorize(ctx, RoleWorker, eventID); err != nil {
return err
}
event, err := j.eventsStore.Get(ctx, eventID)
if err != nil {
return errors.Wrapf(err, "error retrieving event %q from store", eventID)
}
if originalJob, ok := event.Worker.Job(job.Name); ok {
// If this is not a retry event, return ErrConflict.
if event.Labels == nil || event.Labels[RetryLabelKey] == "" {
return &meta.ErrConflict{
Type: JobKind,
ID: job.Name,
Reason: fmt.Sprintf(
"Event %q already has a job named %q.",
eventID,
job.Name,
),
}
}
// Else, check to see if the job configurations match.
// If they do, return and inherit the original's results.
// Otherwise, proceed with the re-creation of the job *if* it has
// been inherited previously (LogsEventID field non-empty) -- return
// ErrConflict if it hasn't been inherited.
if originalJob.Spec.EqualTo(job.Spec) {
return nil
} else if originalJob.Status == nil ||
originalJob.Status.LogsEventID == "" {
return &meta.ErrConflict{
Type: JobKind,
ID: job.Name,
Reason: fmt.Sprintf(
"Event %q already has a non-inherited job named %q.",
eventID,
job.Name,
),
}
}
}
// Perform some validations...
// Determine if ANY of the job's containers:
// 1. Use shared workspace
// 2. Run in privileged mode
// 3. Mount the host's Docker socket
var useWorkspace = job.Spec.PrimaryContainer.WorkspaceMountPath != ""
var usePrivileged = job.Spec.PrimaryContainer.Privileged
// var useDockerSocket = job.Spec.PrimaryContainer.UseHostDockerSocket
for _, sidecarContainer := range job.Spec.SidecarContainers {
if sidecarContainer.WorkspaceMountPath != "" {
useWorkspace = true
}
if sidecarContainer.Privileged {
usePrivileged = true
}
// if sidecarContainer.UseHostDockerSocket {
// useDockerSocket = true
// }
}
// Fail quickly if any job is trying to run privileged or use the host's
// Docker socket, but isn't allowed to per worker configuration.
if usePrivileged &&
(event.Worker.Spec.JobPolicies == nil ||
!event.Worker.Spec.JobPolicies.AllowPrivileged) {
return &meta.ErrAuthorization{
Reason: "Worker configuration forbids jobs from utilizing privileged " +
"containers.",
}
}
// if useDockerSocket &&
// (event.Worker.Spec.JobPolicies == nil ||
// !event.Worker.Spec.JobPolicies.AllowDockerSocketMount) {
// return &meta.ErrAuthorization{
// Reason: "Worker configuration forbids jobs from mounting the Docker " +
// "socket.",
// }
// }
// Fail quickly if the job needs to use shared workspace, but the worker
// doesn't have any shared workspace.
if useWorkspace && !event.Worker.Spec.UseWorkspace {
return &meta.ErrConflict{
Reason: "The job requested access to the shared workspace, but Worker " +
"configuration has not enabled this feature.",
}
}
now := time.Now().UTC()
job.Created = &now
// Set the initial status
job.Status = &JobStatus{
Phase: JobPhasePending,
}
project, err := j.projectsStore.Get(ctx, event.ProjectID)
if err != nil {
return errors.Wrapf(
err,
"error retrieving project %q from store",
event.ProjectID,
)
}
// Redact the values of the Job's environment variables in the job we persist
// because they are likely to contain secrets.
jobCopy := job
// This needs to be a NEW map, otherwise as we mess with it, we're messing
// with the original since maps are references.
jobCopy.Spec.PrimaryContainer.Environment = map[string]string{}
for k := range job.Spec.PrimaryContainer.Environment {
jobCopy.Spec.PrimaryContainer.Environment[k] = "*** REDACTED ***"
}
// This needs to be a NEW map, otherwise as we mess with it, we're messing
// with the original since maps are references.
jobCopy.Spec.SidecarContainers = map[string]JobContainerSpec{}
for sidecarName, sidecar := range job.Spec.SidecarContainers {
// This needs to be a NEW map, otherwise as we mess with it, we're messing
// with the original since maps are references.
sidecar.Environment = map[string]string{}
for k := range job.Spec.SidecarContainers[sidecarName].Environment {
sidecar.Environment[k] = "*** REDACTED ***"
}
jobCopy.Spec.SidecarContainers[sidecarName] = sidecar
}
if err = j.jobsStore.Create(ctx, eventID, jobCopy); err != nil {
return errors.Wrapf(
err, "error saving event %q job %q in store",
eventID,
eventID,
)
}
// Securely store the Job's environment variables
if err = j.substrate.StoreJobEnvironment(
ctx,
project,
event.ID,
job.Name,
job.Spec,
); err != nil {
return errors.Wrapf(
err,
"error storing event %q job %q environment on the substrate",
event.ID,
job.Name,
)
}
return errors.Wrapf(
j.substrate.ScheduleJob(ctx, project, event, job.Name),
"error scheduling event %q job %q on the substrate",
event.ID,
job.Name,
)
}
func (j *jobsService) Start(
ctx context.Context,
eventID string,
jobName string,
) error {
if err := j.authorize(ctx, RoleScheduler, ""); err != nil {
return err
}
event, err := j.eventsStore.Get(ctx, eventID)
if err != nil {
return errors.Wrapf(err, "error retrieving event %q from store", eventID)
}
job, ok := event.Worker.Job(jobName)
if !ok {
return &meta.ErrNotFound{
Type: JobKind,
ID: jobName,
}
}
if job.Status.Phase != JobPhasePending {
return &meta.ErrConflict{
Type: JobKind,
ID: jobName,
Reason: fmt.Sprintf(
"Event %q job %q has already been started.",
eventID,
jobName,
),
}
}
project, err := j.projectsStore.Get(ctx, event.ProjectID)
if err != nil {
return errors.Wrapf(
err,
"error retrieving project %q from store",
event.ProjectID,
)
}
if err = j.jobsStore.UpdateStatus(
ctx,
eventID,
jobName,
JobStatus{
Phase: JobPhaseStarting,
},
); err != nil {
return errors.Wrapf(
err,
"error updating status of event %q worker job %q in store",
eventID,
jobName,
)
}
if err = j.substrate.StartJob(ctx, project, event, jobName); err != nil {
return errors.Wrapf(
err,
"error starting event %q job %q",
event.ID,
jobName,
)
}
return nil
}
func (j *jobsService) GetStatus(
ctx context.Context,
eventID string,
jobName string,
) (JobStatus, error) {
if err := j.authorize(ctx, RoleReader, ""); err != nil {
return JobStatus{}, err
}
event, err := j.eventsStore.Get(ctx, eventID)
if err != nil {
return JobStatus{},
errors.Wrapf(err, "error retrieving event %q from store", eventID)
}
job, ok := event.Worker.Job(jobName)
if !ok {
return JobStatus{}, &meta.ErrNotFound{
Type: JobKind,
ID: jobName,
}
}
return *job.Status, nil
}
func (j *jobsService) WatchStatus(
ctx context.Context,
eventID string,
jobName string,
) (<-chan JobStatus, error) {
if err := j.authorize(ctx, RoleReader, ""); err != nil {
return nil, err
}
// Read the event and job up front to confirm they both exists.
event, err := j.eventsStore.Get(ctx, eventID)
if err != nil {
return nil,
errors.Wrapf(err, "error retrieving event %q from store", eventID)
}
if _, ok := event.Worker.Job(jobName); !ok {
return nil, &meta.ErrNotFound{
Type: JobKind,
ID: jobName,
}
}
statusCh := make(chan JobStatus)
go func() {
defer close(statusCh)
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
case <-ctx.Done():
return
}
event, err := j.eventsStore.Get(ctx, eventID)
if err != nil {
log.Printf("error retrieving event %q from store: %s", eventID, err)
return
}
job, _ := event.Worker.Job(jobName)
select {
case statusCh <- *job.Status:
case <-ctx.Done():
return
}
}
}()
return statusCh, nil
}
func (j *jobsService) UpdateStatus(
ctx context.Context,
eventID string,
jobName string,
status JobStatus,
) error {
if err := j.authorize(ctx, RoleObserver, ""); err != nil {
return err
}
// Check current phase of the job
event, err := j.eventsStore.Get(ctx, eventID)
if err != nil {
return errors.Wrapf(err, "error retrieving event %q from store", eventID)
}
return j.updateStatus(ctx, event, jobName, status)
}
func (j *jobsService) Cleanup(
ctx context.Context,
eventID string,
jobName string,
) error {
if err := j.authorize(ctx, RoleObserver, ""); err != nil {
return err
}
event, err := j.eventsStore.Get(ctx, eventID)
if err != nil {
return errors.Wrapf(err, "error retrieving event %q from store", eventID)
}
return j.cleanup(ctx, event, jobName)
}
func (j *jobsService) Timeout(
ctx context.Context,
eventID string,
jobName string,
) error {
if err := j.authorize(ctx, RoleObserver, ""); err != nil {
return err
}
event, err := j.eventsStore.Get(ctx, eventID)
if err != nil {
return errors.Wrapf(err, "error retrieving event %q from store", eventID)
}
job, ok := event.Worker.Job(jobName)
if !ok {
return &meta.ErrNotFound{
Type: JobKind,
ID: jobName,
}
}
// Update job status
now := time.Now()
status := *job.Status
status.Phase = JobPhaseTimedOut
status.Ended = &now
if err := j.updateStatus(ctx, event, jobName, status); err != nil {
return errors.Wrapf(
err,
"error updating status for event %q job %q",
event.ID,
jobName,
)
}
return j.cleanup(ctx, event, jobName)
}
// updateStatus is an internal helper func created so that multiple exported
// functions can share this logic after they've retrieved specified events.
func (j *jobsService) updateStatus(
ctx context.Context,
event Event,
jobName string,
status JobStatus,
) error {
job, ok := event.Worker.Job(jobName)
if !ok {
return &meta.ErrNotFound{
Type: JobKind,
ID: jobName,
}
}
// We have a conflict if the job's phase is already terminal
if job.Status.Phase.IsTerminal() {
return &meta.ErrConflict{
Type: JobKind,
ID: job.Name,
Reason: fmt.Sprintf(
"Event %q job %q has already reached a terminal phase.",
event.ID,
job.Name,
),
}
}
return errors.Wrapf(
j.jobsStore.UpdateStatus(
ctx,
event.ID,
jobName,
status,
),
"error updating status of event %q worker job %q in store",
event.ID,
jobName,
)
}
// cleanup is an internal helper func created so that multiple exported
// functions can share this logic after they've retrieved specified events.
func (j *jobsService) cleanup(
ctx context.Context,
event Event,
jobName string,
) error {
job, ok := event.Worker.Job(jobName)
if !ok {
return &meta.ErrNotFound{
Type: JobKind,
ID: jobName,
}
}
project, err := j.projectsStore.Get(ctx, event.ProjectID)
if err != nil {
return errors.Wrapf(
err,
"error retrieving project %q from store",
event.ProjectID,
)
}
return errors.Wrapf(
j.substrate.DeleteJob(ctx, project, event, job.Name),
"error deleting event %q jobs %q from the substrate",
event.ID,
jobName,
)
}
// JobsStore is an interface for components that implement Job persistence
// concerns.
type JobsStore interface {
// Create persists a new Job for the specified Event in the underlying data
// store.
Create(ctx context.Context, eventID string, job Job) error
// UpdateStatus updates the status of the specified Job in the underlying data
// store. If the specified job is not found, implementations MUST return a
// *meta.ErrNotFound error.
UpdateStatus(
ctx context.Context,
eventID string,
jobName string,
status JobStatus,
) error
}