-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
jobs_controller.go
258 lines (229 loc) · 8.31 KB
/
jobs_controller.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
package web
import (
"context"
"database/sql"
"encoding/json"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
uuid "github.com/satori/go.uuid"
"github.com/smartcontractkit/chainlink/v2/core/logger/audit"
"github.com/smartcontractkit/chainlink/v2/core/services/blockhashstore"
"github.com/smartcontractkit/chainlink/v2/core/services/blockheaderfeeder"
"github.com/smartcontractkit/chainlink/v2/core/services/chainlink"
"github.com/smartcontractkit/chainlink/v2/core/services/cron"
"github.com/smartcontractkit/chainlink/v2/core/services/directrequest"
"github.com/smartcontractkit/chainlink/v2/core/services/fluxmonitorv2"
"github.com/smartcontractkit/chainlink/v2/core/services/job"
"github.com/smartcontractkit/chainlink/v2/core/services/keeper"
"github.com/smartcontractkit/chainlink/v2/core/services/keystore"
"github.com/smartcontractkit/chainlink/v2/core/services/ocr"
"github.com/smartcontractkit/chainlink/v2/core/services/ocr2/validate"
"github.com/smartcontractkit/chainlink/v2/core/services/ocrbootstrap"
"github.com/smartcontractkit/chainlink/v2/core/services/pg"
"github.com/smartcontractkit/chainlink/v2/core/services/vrf"
"github.com/smartcontractkit/chainlink/v2/core/services/webhook"
"github.com/smartcontractkit/chainlink/v2/core/web/presenters"
)
// JobsController manages jobs
type JobsController struct {
App chainlink.Application
}
// Index lists all jobs
// Example:
// "GET <application>/jobs"
func (jc *JobsController) Index(c *gin.Context, size, page, offset int) {
// Temporary: if no size is passed in, use a large page size. Remove once frontend can handle pagination
if c.Query("size") == "" {
size = 1000
}
jobs, count, err := jc.App.JobORM().FindJobs(offset, size)
if err != nil {
jsonAPIError(c, http.StatusInternalServerError, err)
return
}
var resources []presenters.JobResource
for _, individualJob := range jobs {
resources = append(resources, *presenters.NewJobResource(individualJob))
}
paginatedResponse(c, "jobs", size, page, resources, count, err)
}
// Show returns the details of a job
// :ID could be both job ID and external job ID
// Example:
// "GET <application>/jobs/:ID"
func (jc *JobsController) Show(c *gin.Context) {
var err error
jobSpec := job.Job{}
if externalJobID, pErr := uuid.FromString(c.Param("ID")); pErr == nil {
// Find a job by external job ID
jobSpec, err = jc.App.JobORM().FindJobByExternalJobID(externalJobID, pg.WithParentCtx(c.Request.Context()))
} else if pErr = jobSpec.SetID(c.Param("ID")); pErr == nil {
// Find a job by job ID
jobSpec, err = jc.App.JobORM().FindJobTx(jobSpec.ID)
} else {
jsonAPIError(c, http.StatusUnprocessableEntity, pErr)
return
}
if err != nil {
if errors.Is(errors.Cause(err), sql.ErrNoRows) {
jsonAPIError(c, http.StatusNotFound, errors.New("job not found"))
} else {
jsonAPIError(c, http.StatusInternalServerError, err)
}
return
}
jsonAPIResponse(c, presenters.NewJobResource(jobSpec), "jobs")
}
// CreateJobRequest represents a request to create and start a job (V2).
type CreateJobRequest struct {
TOML string `json:"toml"`
}
// Create validates, saves and starts a new job.
// Example:
// "POST <application>/jobs"
func (jc *JobsController) Create(c *gin.Context) {
request := CreateJobRequest{}
if err := c.ShouldBindJSON(&request); err != nil {
jsonAPIError(c, http.StatusUnprocessableEntity, err)
return
}
jb, status, err := jc.validateJobSpec(request.TOML)
if err != nil {
jsonAPIError(c, status, err)
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
defer cancel()
err = jc.App.AddJobV2(ctx, &jb)
if err != nil {
if errors.Is(errors.Cause(err), job.ErrNoSuchKeyBundle) || errors.As(err, &keystore.KeyNotFoundError{}) || errors.Is(errors.Cause(err), job.ErrNoSuchTransmitterKey) {
jsonAPIError(c, http.StatusBadRequest, err)
return
}
jsonAPIError(c, http.StatusInternalServerError, err)
return
}
jbj, err := json.Marshal(jb)
if err == nil {
jc.App.GetAuditLogger().Audit(audit.JobCreated, map[string]interface{}{"job": string(jbj)})
} else {
jc.App.GetLogger().Errorf("Could not send audit log for JobCreation", "err", err)
}
jsonAPIResponse(c, presenters.NewJobResource(jb), jb.Type.String())
}
// Delete hard deletes a job spec.
// Example:
// "DELETE <application>/specs/:ID"
func (jc *JobsController) Delete(c *gin.Context) {
j := job.Job{}
err := j.SetID(c.Param("ID"))
if err != nil {
jsonAPIError(c, http.StatusUnprocessableEntity, err)
return
}
// Delete the job
err = jc.App.DeleteJob(c.Request.Context(), j.ID)
if errors.Is(err, sql.ErrNoRows) {
jsonAPIError(c, http.StatusNotFound, errors.New("JobSpec not found"))
return
}
if err != nil {
jsonAPIError(c, http.StatusInternalServerError, err)
return
}
jc.App.GetAuditLogger().Audit(audit.JobDeleted, map[string]interface{}{"id": j.ID})
jsonAPIResponseWithStatus(c, nil, "job", http.StatusNoContent)
}
// UpdateJobRequest represents a request to update a job with new toml and start a job (V2).
type UpdateJobRequest struct {
TOML string `json:"toml"`
}
// Update validates a new TOML for an existing job, stops and deletes existing job, saves and starts a new job.
// Example:
// "PUT <application>/jobs/:ID"
func (jc *JobsController) Update(c *gin.Context) {
request := UpdateJobRequest{}
if err := c.ShouldBindJSON(&request); err != nil {
jsonAPIError(c, http.StatusUnprocessableEntity, err)
return
}
jb, status, err := jc.validateJobSpec(request.TOML)
if err != nil {
jsonAPIError(c, status, err)
return
}
err = jb.SetID(c.Param("ID"))
if err != nil {
jsonAPIError(c, http.StatusUnprocessableEntity, err)
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
defer cancel()
// If the provided job id is not matching any job, delete will fail with 404 leaving state unchanged.
err = jc.App.DeleteJob(ctx, jb.ID)
// Error can be either come from ORM or from the activeJobs map.
if err != nil {
if errors.Is(err, sql.ErrNoRows) || strings.Contains(err.Error(), "job not found") {
jsonAPIError(c, http.StatusNotFound, errors.Wrap(err, "failed to update job"))
return
}
jsonAPIError(c, http.StatusInternalServerError, err)
return
}
err = jc.App.AddJobV2(ctx, &jb)
if err != nil {
if errors.Is(errors.Cause(err), job.ErrNoSuchKeyBundle) || errors.As(err, &keystore.KeyNotFoundError{}) || errors.Is(errors.Cause(err), job.ErrNoSuchTransmitterKey) {
jsonAPIError(c, http.StatusBadRequest, err)
return
}
jsonAPIError(c, http.StatusInternalServerError, err)
return
}
jsonAPIResponse(c, presenters.NewJobResource(jb), jb.Type.String())
}
func (jc *JobsController) validateJobSpec(tomlString string) (jb job.Job, statusCode int, err error) {
jobType, err := job.ValidateSpec(tomlString)
if err != nil {
return jb, http.StatusUnprocessableEntity, errors.Wrap(err, "failed to parse TOML")
}
config := jc.App.GetConfig()
switch jobType {
case job.OffchainReporting:
jb, err = ocr.ValidatedOracleSpecToml(jc.App.GetChains().EVM, tomlString)
if !config.Dev() && !config.FeatureOffchainReporting() {
return jb, http.StatusNotImplemented, errors.New("The Offchain Reporting feature is disabled by configuration")
}
case job.OffchainReporting2:
jb, err = validate.ValidatedOracleSpecToml(config, tomlString)
if !config.Dev() && !config.FeatureOffchainReporting2() {
return jb, http.StatusNotImplemented, errors.New("The Offchain Reporting 2 feature is disabled by configuration")
}
case job.DirectRequest:
jb, err = directrequest.ValidatedDirectRequestSpec(tomlString)
case job.FluxMonitor:
jb, err = fluxmonitorv2.ValidatedFluxMonitorSpec(config, tomlString)
case job.Keeper:
jb, err = keeper.ValidatedKeeperSpec(tomlString)
case job.Cron:
jb, err = cron.ValidatedCronSpec(tomlString)
case job.VRF:
jb, err = vrf.ValidatedVRFSpec(tomlString)
case job.Webhook:
jb, err = webhook.ValidatedWebhookSpec(tomlString, jc.App.GetExternalInitiatorManager())
case job.BlockhashStore:
jb, err = blockhashstore.ValidatedSpec(tomlString)
case job.BlockHeaderFeeder:
jb, err = blockheaderfeeder.ValidatedSpec(tomlString)
case job.Bootstrap:
jb, err = ocrbootstrap.ValidatedBootstrapSpecToml(tomlString)
default:
return jb, http.StatusUnprocessableEntity, errors.Errorf("unknown job type: %s", jobType)
}
if err != nil {
return jb, http.StatusBadRequest, err
}
return jb, 0, nil
}