/
job_runs_controller.go
239 lines (209 loc) · 6.38 KB
/
job_runs_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
package web
import (
"fmt"
"io/ioutil"
"net/http"
"github.com/GoPlugin/Plugin/core/services/chainlink"
"github.com/GoPlugin/Plugin/core/store/models"
"github.com/GoPlugin/Plugin/core/store/orm"
"github.com/GoPlugin/Plugin/core/store/presenters"
"github.com/GoPlugin/Plugin/core/utils"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
)
// JobRunsController manages JobRun requests in the node.
type JobRunsController struct {
App chainlink.Application
}
// Index returns paginated JobRuns for a given JobSpec
// Example:
// "<application>/runs?jobSpecId=:jobSpecId&size=1&page=2"
func (jrc *JobRunsController) Index(c *gin.Context, size, page, offset int) {
id := c.Query("jobSpecId")
order := orm.Ascending
if c.Query("sort") == "-createdAt" {
order = orm.Descending
}
store := jrc.App.GetStore()
var runs []models.JobRun
var count int
var completedCount int
var erroredCount int
var err error
if id == "" {
runs, count, err = store.JobRunsSorted(order, offset, size)
} else {
var runID models.JobID
runID, err = models.NewJobIDFromString(id)
if err != nil {
jsonAPIError(c, http.StatusUnprocessableEntity, err)
return
}
runs, count, completedCount, erroredCount, err = store.JobRunsSortedFor(runID, order, offset, size)
}
meta := make(map[string]interface{})
meta["completed"] = completedCount
meta["errored"] = erroredCount
paginatedResponseWithMeta(c, "JobRuns", size, page, runs, count, err, meta)
}
// Create starts a new Run for the requested JobSpec.
// Example:
// "<application>/specs/:SpecID/runs"
func (jrc *JobRunsController) Create(c *gin.Context) {
id, err := models.NewJobIDFromString(c.Param("SpecID"))
if err != nil {
jsonAPIError(c, http.StatusUnprocessableEntity, err)
return
}
j, err := jrc.App.GetStore().Unscoped().FindJobSpec(id)
if errors.Cause(err) == orm.ErrorNotFound {
jsonAPIError(c, http.StatusNotFound, errors.New("Job not found"))
return
}
if j.DeletedAt.Valid {
jsonAPIError(c, http.StatusGone, errors.New("Job spec not found"))
return
}
if err != nil {
jsonAPIError(c, http.StatusInternalServerError, err)
return
}
initiator, err := getAuthenticatedInitiator(c, j)
if err != nil {
jsonAPIError(c, http.StatusForbidden, err)
return
}
data, err := getRunData(c)
if err != nil {
jsonAPIError(c, http.StatusInternalServerError, err)
return
}
jr, err := jrc.App.Create(j.ID, initiator, nil, &models.RunRequest{RequestParams: data})
if errors.Cause(err) == orm.ErrorNotFound {
jsonAPIError(c, http.StatusNotFound, errors.New("Job not found"))
return
}
if err != nil {
jsonAPIError(c, http.StatusInternalServerError, err)
return
}
jsonAPIResponse(c, presenters.JobRun{JobRun: *jr}, "job run")
}
// getInitiator returns the Job Spec's initiator for the given web context.
func getAuthenticatedInitiator(c *gin.Context, js models.JobSpec) (*models.Initiator, error) {
if _, ok := authenticatedUser(c); ok {
webInitiators := js.InitiatorsFor(models.InitiatorWeb)
if len(webInitiators) == 0 {
return nil, errors.New("Job not available on web API, recreate with initiator type 'InitiatorWeb'")
}
return &webInitiators[0], nil
}
if ei, ok := authenticatedEI(c); ok {
initiator := js.InitiatorExternal(ei.Name)
if initiator == nil {
return nil, fmt.Errorf("job not available via External Initiator '%s'", ei.Name)
}
return initiator, nil
}
return nil, errors.New("authentication required")
}
func getRunData(c *gin.Context) (models.JSON, error) {
b, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
return models.JSON{}, err
}
return models.ParseJSON(b)
}
// Show returns the details of a JobRun.
// Example:
// "<application>/runs/:RunID"
func (jrc *JobRunsController) Show(c *gin.Context) {
id, err := models.NewJobIDFromString(c.Param("RunID"))
if err != nil {
jsonAPIError(c, http.StatusUnprocessableEntity, err)
return
}
jr, err := jrc.App.GetStore().FindJobRun(id.UUID())
if errors.Cause(err) == orm.ErrorNotFound {
jsonAPIError(c, http.StatusNotFound, errors.New("Job run not found"))
return
}
if err != nil {
jsonAPIError(c, http.StatusInternalServerError, err)
return
}
jsonAPIResponse(c, presenters.JobRun{JobRun: jr}, "job run")
}
// Update allows external adapters to resume a JobRun, reporting the result of
// the task and marking it no longer pending.
// Example:
// "<application>/runs/:RunID"
func (jrc *JobRunsController) Update(c *gin.Context) {
authToken := utils.StripBearer(c.Request.Header.Get("Authorization"))
runID, err := models.NewJobIDFromString(c.Param("RunID"))
if err != nil {
jsonAPIError(c, http.StatusUnprocessableEntity, err)
return
}
jr, err := jrc.App.GetStore().FindJobRunIncludingArchived(runID.UUID())
if errors.Cause(err) == orm.ErrorNotFound {
jsonAPIError(c, http.StatusNotFound, errors.New("Job Run not found"))
return
}
if err != nil {
jsonAPIError(c, http.StatusInternalServerError, err)
return
}
if !jr.GetStatus().PendingBridge() {
jsonAPIError(c, http.StatusMethodNotAllowed, errors.New("Cannot resume a job run that isn't pending"))
return
}
var brr models.BridgeRunResult
if e := c.ShouldBindJSON(&brr); e != nil {
jsonAPIError(c, http.StatusInternalServerError, e)
return
}
bt, err := jrc.App.GetStore().PendingBridgeType(jr)
if err != nil {
jsonAPIError(c, http.StatusInternalServerError, err)
return
}
ok, err := models.AuthenticateBridgeType(&bt, authToken)
if err != nil {
jsonAPIError(c, http.StatusInternalServerError, err)
return
}
if !ok {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
if err = jrc.App.ResumePendingBridge(runID.UUID(), brr); errors.Cause(err) == orm.ErrorNotFound {
jsonAPIError(c, http.StatusNotFound, errors.New("Job Run not found"))
return
}
if err != nil {
jsonAPIError(c, http.StatusInternalServerError, err)
return
}
jsonAPIResponse(c, jr, "job run")
}
// Cancel stops a Run from continuing.
// Example:
// "<application>/runs/:RunID/cancellation"
func (jrc *JobRunsController) Cancel(c *gin.Context) {
id, err := models.NewJobIDFromString(c.Param("RunID"))
if err != nil {
jsonAPIError(c, http.StatusUnprocessableEntity, err)
return
}
jr, err := jrc.App.Cancel(id.UUID())
if errors.Cause(err) == orm.ErrorNotFound {
jsonAPIError(c, http.StatusNotFound, errors.New("Job run not found"))
return
}
if err != nil {
jsonAPIError(c, http.StatusInternalServerError, err)
return
}
jsonAPIResponse(c, presenters.JobRun{JobRun: *jr}, "job run")
}