-
Notifications
You must be signed in to change notification settings - Fork 28
/
cancel.go
229 lines (189 loc) · 6.15 KB
/
cancel.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
// SPDX-License-Identifier: Apache-2.0
package build
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/go-vela/server/database"
"github.com/go-vela/server/internal/token"
"github.com/go-vela/server/router/middleware/build"
"github.com/go-vela/server/router/middleware/executors"
"github.com/go-vela/server/router/middleware/org"
"github.com/go-vela/server/router/middleware/repo"
"github.com/go-vela/server/router/middleware/user"
"github.com/go-vela/server/util"
"github.com/go-vela/types/constants"
"github.com/sirupsen/logrus"
)
// swagger:operation DELETE /api/v1/repos/{org}/{repo}/builds/{build}/cancel builds CancelBuild
//
// Cancel a running build
//
// ---
// produces:
// - application/json
// parameters:
// - in: path
// name: repo
// description: Name of the repo
// required: true
// type: string
// - in: path
// name: org
// description: Name of the org
// required: true
// type: string
// - in: path
// name: build
// description: Build number to cancel
// required: true
// type: integer
// security:
// - ApiKeyAuth: []
// responses:
// '200':
// description: Successfully canceled the build
// schema:
// type: string
// '400':
// description: Unable to cancel build
// schema:
// "$ref": "#/definitions/Error"
// '404':
// description: Unable to cancel build
// schema:
// "$ref": "#/definitions/Error"
// '500':
// description: Unable to cancel build
// schema:
// "$ref": "#/definitions/Error"
// CancelBuild represents the API handler to cancel a running build.
//
//nolint:funlen // ignore statement count
func CancelBuild(c *gin.Context) {
// capture middleware values
b := build.Retrieve(c)
e := executors.Retrieve(c)
o := org.Retrieve(c)
r := repo.Retrieve(c)
user := user.Retrieve(c)
ctx := c.Request.Context()
entry := fmt.Sprintf("%s/%d", r.GetFullName(), b.GetNumber())
// update engine logger with API metadata
//
// https://pkg.go.dev/github.com/sirupsen/logrus?tab=doc#Entry.WithFields
logrus.WithFields(logrus.Fields{
"build": b.GetNumber(),
"org": o,
"repo": r.GetName(),
"user": user.GetName(),
}).Infof("canceling build %s", entry)
switch b.GetStatus() {
case constants.StatusRunning:
// retrieve the worker info
w, err := database.FromContext(c).GetWorkerForHostname(ctx, b.GetHost())
if err != nil {
retErr := fmt.Errorf("unable to get worker for build %s: %w", entry, err)
util.HandleError(c, http.StatusNotFound, retErr)
return
}
for _, executor := range e {
// check each executor on the worker running the build to see if it's running the build we want to cancel
if strings.EqualFold(executor.Repo.GetFullName(), r.GetFullName()) && *executor.GetBuild().Number == b.GetNumber() {
// prepare the request to the worker
client := http.DefaultClient
client.Timeout = 30 * time.Second
// set the API endpoint path we send the request to
u := fmt.Sprintf("%s/api/v1/executors/%d/build/cancel", w.GetAddress(), executor.GetID())
req, err := http.NewRequestWithContext(context.Background(), "DELETE", u, nil)
if err != nil {
retErr := fmt.Errorf("unable to form a request to %s: %w", u, err)
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
tm := c.MustGet("token-manager").(*token.Manager)
// set mint token options
mto := &token.MintTokenOpts{
Hostname: "vela-server",
TokenType: constants.WorkerAuthTokenType,
TokenDuration: time.Minute * 1,
}
// mint token
tkn, err := tm.MintToken(mto)
if err != nil {
retErr := fmt.Errorf("unable to generate auth token: %w", err)
util.HandleError(c, http.StatusInternalServerError, retErr)
return
}
// add the token to authenticate to the worker
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", tkn))
// perform the request to the worker
resp, err := client.Do(req)
if err != nil {
retErr := fmt.Errorf("unable to connect to %s: %w", u, err)
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
defer resp.Body.Close()
// Read Response Body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
retErr := fmt.Errorf("unable to read response from %s: %w", u, err)
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
err = json.Unmarshal(respBody, b)
if err != nil {
retErr := fmt.Errorf("unable to parse response from %s: %w", u, err)
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
b.SetError(fmt.Sprintf("build was canceled by %s", user.GetName()))
b, err = database.FromContext(c).UpdateBuild(ctx, b)
if err != nil {
retErr := fmt.Errorf("unable to update status for build %s: %w", entry, err)
util.HandleError(c, http.StatusInternalServerError, retErr)
return
}
c.JSON(resp.StatusCode, b)
return
}
}
case constants.StatusPending, constants.StatusPendingApproval:
break
default:
retErr := fmt.Errorf("found build %s but its status was %s", entry, b.GetStatus())
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
// build has been abandoned
// update the status in the build table
b.SetStatus(constants.StatusCanceled)
b.SetError(fmt.Sprintf("build was canceled by %s", user.GetName()))
b, err := database.FromContext(c).UpdateBuild(ctx, b)
if err != nil {
retErr := fmt.Errorf("unable to update status for build %s: %w", entry, err)
util.HandleError(c, http.StatusInternalServerError, retErr)
return
}
// remove build executable for clean up
_, err = database.FromContext(c).PopBuildExecutable(ctx, b.GetID())
if err != nil {
retErr := fmt.Errorf("unable to pop build %s from executables table: %w", entry, err)
util.HandleError(c, http.StatusInternalServerError, retErr)
return
}
// update component statuses to canceled
err = UpdateComponentStatuses(c, b, constants.StatusCanceled)
if err != nil {
retErr := fmt.Errorf("unable to update component statuses for build %s: %w", entry, err)
util.HandleError(c, http.StatusInternalServerError, retErr)
return
}
c.JSON(http.StatusOK, b)
}