-
Notifications
You must be signed in to change notification settings - Fork 127
/
executions.go
340 lines (275 loc) · 9.86 KB
/
executions.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
package v1
import (
"bufio"
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/gofiber/fiber/v2"
"github.com/valyala/fasthttp"
"go.mongodb.org/mongo-driver/mongo"
"k8s.io/apimachinery/pkg/api/errors"
"github.com/kubeshop/testkube/pkg/api/v1/testkube"
"github.com/kubeshop/testkube/pkg/executor/client"
"github.com/kubeshop/testkube/pkg/rand"
"github.com/kubeshop/testkube/pkg/runner/output"
"github.com/kubeshop/testkube/pkg/secret"
)
// ExecuteScriptHandler calls particular executor based on execution request content and type
func (s TestKubeAPI) ExecuteScriptHandler() fiber.Handler {
return func(c *fiber.Ctx) error {
ctx := c.Context()
var request testkube.ExecutionRequest
err := c.BodyParser(&request)
if err != nil {
return s.Error(c, http.StatusBadRequest, fmt.Errorf("script request body invalid: %w", err))
}
scriptID := c.Params("id")
namespace := request.Namespace
// generate random execution name in case there is no one set
// like for docker images
if request.Name == "" {
request.Name = rand.Name()
}
// script name + script execution name should be unique
execution, _ := s.ExecutionResults.GetByNameAndScript(c.Context(), request.Name, scriptID)
if execution.Name == request.Name {
return s.Error(c, http.StatusBadRequest, fmt.Errorf("script execution with name %s already exists", request.Name))
}
// merge available data into execution options script spec, executor spec, request, script id
options, err := s.GetExecuteOptions(namespace, scriptID, request)
if err != nil {
return s.Error(c, http.StatusInternalServerError, fmt.Errorf("can't create valid execution options: %w", err))
}
execution = s.executeScript(ctx, options)
if execution.ExecutionResult.IsFailed() {
return s.Error(c, http.StatusInternalServerError, fmt.Errorf(execution.ExecutionResult.ErrorMessage))
}
return c.JSON(execution)
}
}
func (s TestKubeAPI) executeScript(ctx context.Context, options client.ExecuteOptions) (execution testkube.Execution) {
// store execution in storage, can be get from API now
execution = newExecutionFromExecutionOptions(options)
options.ID = execution.Id
execution.Tags = options.ScriptSpec.Tags
err := s.ExecutionResults.Insert(ctx, execution)
if err != nil {
return execution.Errw("can't create new script execution, can't insert into storage: %w", err)
}
s.Log.Infow("calling executor with options", "options", options.Request)
execution.Start()
err = s.ExecutionResults.StartExecution(ctx, execution.Id, execution.StartTime)
if err != nil {
return execution.Errw("can't execute script, can't insert into storage error: %w", err)
}
options.HasSecrets = true
if _, err = s.SecretClient.Get(secret.GetMetadataName(execution.ScriptName), options.Request.Namespace); err != nil {
if !errors.IsNotFound(err) {
return execution.Errw("can't get secrets: %w", err)
}
options.HasSecrets = false
}
var result testkube.ExecutionResult
// sync/async script execution
if options.Sync {
result, err = s.Executor.ExecuteSync(execution, options)
} else {
result, err = s.Executor.Execute(execution, options)
}
if uerr := s.ExecutionResults.UpdateResult(ctx, execution.Id, result); uerr != nil {
return execution.Errw("update execution error: %w", uerr)
}
// set execution result to one created
execution.ExecutionResult = &result
// metrics increase
s.Metrics.IncExecution(execution)
if err != nil {
return execution.Errw("script execution failed: %w", err)
}
s.Log.Infow("script executed", "executionId", execution.Id, "status", execution.ExecutionResult.Status)
return
}
// ListExecutionsHandler returns array of available script executions
func (s TestKubeAPI) ListExecutionsHandler() fiber.Handler {
return func(c *fiber.Ctx) error {
// TODO should we split this to separate endpoint? currently this one handles
// endpoints from /executions and from /scripts/{id}/executions
// or should scriptID be a query string as it's some kind of filter?
filter := getFilterFromRequest(c)
executions, err := s.ExecutionResults.GetExecutions(c.Context(), filter)
if err != nil {
return s.Error(c, http.StatusInternalServerError, err)
}
executionTotals, err := s.ExecutionResults.GetExecutionTotals(c.Context())
if err != nil {
return s.Error(c, http.StatusInternalServerError, err)
}
filteredTotals, err := s.ExecutionResults.GetExecutionTotals(c.Context(), filter)
if err != nil {
return s.Error(c, http.StatusInternalServerError, err)
}
results := testkube.ExecutionsResult{
Totals: &executionTotals,
Filtered: &filteredTotals,
Results: mapExecutionsToExecutionSummary(executions),
}
return c.JSON(results)
}
}
func (s TestKubeAPI) ExecutionLogsHandler() fiber.Handler {
return func(c *fiber.Ctx) error {
executionID := c.Params("executionID")
s.Log.Debug("getting logs", "executionID", executionID)
ctx := c.Context()
ctx.SetContentType("text/event-stream")
ctx.Response.Header.Set("Cache-Control", "no-cache")
ctx.Response.Header.Set("Connection", "keep-alive")
ctx.Response.Header.Set("Transfer-Encoding", "chunked")
ctx.SetBodyStreamWriter(fasthttp.StreamWriter(func(w *bufio.Writer) {
s.Log.Debug("starting stream writer")
w.Flush()
enc := json.NewEncoder(w)
// get logs from job executor pods
s.Log.Debug("getting logs")
var logs chan output.Output
var err error
logs, err = s.Executor.Logs(executionID)
s.Log.Debugw("waiting for jobs channel", "channelSize", len(logs))
if err != nil {
output.PrintError(err)
s.Log.Errorw("getting logs error", "error", err)
w.Flush()
return
}
// loop through pods log lines - it's blocking channel
// and pass single log output as sse data chunk
for out := range logs {
s.Log.Debugw("got log", "out", out)
fmt.Fprintf(w, "data: ")
enc.Encode(out)
// enc.Encode adds \n and we need \n\n after `data: {}` chunk
fmt.Fprintf(w, "\n")
w.Flush()
}
}))
return nil
}
}
// GetExecutionHandler returns script execution object for given script and execution id
func (s TestKubeAPI) GetExecutionHandler() fiber.Handler {
return func(c *fiber.Ctx) error {
ctx := c.Context()
scriptID := c.Params("id", "")
executionID := c.Params("executionID")
var execution testkube.Execution
var err error
if scriptID == "" {
execution, err = s.ExecutionResults.Get(ctx, executionID)
if err == mongo.ErrNoDocuments {
return s.Error(c, http.StatusNotFound, fmt.Errorf("script with execution id %s not found", executionID))
}
if err != nil {
return s.Error(c, http.StatusInternalServerError, err)
}
} else {
execution, err = s.ExecutionResults.GetByNameAndScript(ctx, executionID, scriptID)
if err == mongo.ErrNoDocuments {
return s.Error(c, http.StatusNotFound, fmt.Errorf("script %s/%s not found", scriptID, executionID))
}
if err != nil {
return s.Error(c, http.StatusInternalServerError, err)
}
}
s.Log.Infow("get script execution request", "id", scriptID, "executionID", executionID)
s.Log.Debugw("get script execution request - debug", "execution", execution)
return c.JSON(execution)
}
}
func (s TestKubeAPI) AbortExecutionHandler() fiber.Handler {
return func(c *fiber.Ctx) error {
id := c.Params("id")
return s.Executor.Abort(id)
}
}
func (s TestKubeAPI) GetArtifactHandler() fiber.Handler {
return func(c *fiber.Ctx) error {
executionID := c.Params("executionID")
fileName := c.Params("filename")
// TODO fix this someday :) we don't know 15 mins before release why it's working this way
unescaped, err := url.QueryUnescape(fileName)
if err == nil {
fileName = unescaped
}
unescaped, err = url.QueryUnescape(fileName)
if err == nil {
fileName = unescaped
}
//// quickfix end
file, err := s.Storage.DownloadFile(executionID, fileName)
if err != nil {
return s.Error(c, http.StatusInternalServerError, err)
}
defer file.Close()
return c.SendStream(file)
}
}
// GetArtifacts returns list of files in the given bucket
func (s TestKubeAPI) ListArtifactsHandler() fiber.Handler {
return func(c *fiber.Ctx) error {
executionID := c.Params("executionID")
files, err := s.Storage.ListFiles(executionID)
if err != nil {
return s.Error(c, http.StatusInternalServerError, err)
}
return c.JSON(files)
}
}
func (s TestKubeAPI) GetExecuteOptions(namespace, scriptID string, request testkube.ExecutionRequest) (options client.ExecuteOptions, err error) {
// get script content from kubernetes CRs
scriptCR, err := s.ScriptsClient.Get(namespace, scriptID)
if err != nil {
return options, fmt.Errorf("can't get script custom resource %w", err)
}
// get executor from kubernetes CRs
executorCR, err := s.ExecutorsClient.GetByType(scriptCR.Spec.Type_)
if err != nil {
return options, fmt.Errorf("can't get executor spec: %w", err)
}
return client.ExecuteOptions{
ScriptName: scriptID,
ScriptSpec: scriptCR.Spec,
ExecutorName: executorCR.ObjectMeta.Name,
ExecutorSpec: executorCR.Spec,
Request: request,
}, nil
}
func newExecutionFromExecutionOptions(options client.ExecuteOptions) testkube.Execution {
execution := testkube.NewExecution(
options.ScriptName,
options.Request.Name,
options.ScriptSpec.Type_,
options.ScriptSpec.Content,
testkube.NewPendingExecutionResult(),
options.Request.Params,
options.Request.Tags,
)
execution.Repository = (*testkube.Repository)(options.ScriptSpec.Repository)
return execution
}
func mapExecutionsToExecutionSummary(executions []testkube.Execution) []testkube.ExecutionSummary {
result := make([]testkube.ExecutionSummary, len(executions))
for i, execution := range executions {
result[i] = testkube.ExecutionSummary{
Id: execution.Id,
Name: execution.Name,
ScriptName: execution.ScriptName,
ScriptType: execution.ScriptType,
Status: execution.ExecutionResult.Status,
StartTime: execution.StartTime,
EndTime: execution.EndTime,
}
}
return result
}