-
Notifications
You must be signed in to change notification settings - Fork 2
/
command_handler.go
633 lines (582 loc) · 20.7 KB
/
command_handler.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
package handlers
import (
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/labstack/echo/v4"
"github.com/rs/zerolog"
kerr "github.com/krok-o/krok/errors"
"github.com/krok-o/krok/pkg/krok/providers"
"github.com/krok-o/krok/pkg/models"
)
// CommandsHandlerDependencies defines the dependencies for the commands handler provider.
type CommandsHandlerDependencies struct {
Logger zerolog.Logger
CommandStorer providers.CommandStorer
Plugins providers.Plugins
}
// CommandsHandler is a handler taking care of commands related api calls.
type CommandsHandler struct {
CommandsHandlerDependencies
Client *http.Client
}
var _ providers.CommandHandler = &CommandsHandler{}
// NewCommandsHandler creates a new commands handler.
func NewCommandsHandler(deps CommandsHandlerDependencies) *CommandsHandler {
return &CommandsHandler{
CommandsHandlerDependencies: deps,
Client: http.DefaultClient,
}
}
// Delete deletes a command.
// swagger:operation DELETE /command/{id} deleteCommand
// Deletes given command.
// ---
// parameters:
// - name: id
// in: path
// description: 'The ID of the command to delete'
// required: true
// type: integer
// format: int
// responses:
// '200':
// description: 'OK in case the deletion was successful'
// '400':
// description: 'in case of missing user context or invalid ID'
// schema:
// "$ref": "#/responses/Message"
// '500':
// description: 'when the deletion operation failed'
// schema:
// "$ref": "#/responses/Message"
func (ch *CommandsHandler) Delete() echo.HandlerFunc {
return func(c echo.Context) error {
n, err := GetParamAsInt("id", c)
if err != nil {
apiError := kerr.APIError("invalid command id", http.StatusBadRequest, nil)
return c.JSON(http.StatusBadRequest, apiError)
}
ctx := c.Request().Context()
// Get first for the name
command, err := ch.CommandStorer.Get(ctx, n)
if err != nil {
if errors.Is(err, kerr.ErrNotFound) {
return c.JSON(http.StatusNotFound, kerr.APIError("command not found", http.StatusNotFound, err))
}
ch.Logger.Debug().Err(err).Msg("Command Get failed.")
return c.JSON(http.StatusBadRequest, kerr.APIError("failed to get command", http.StatusBadRequest, err))
}
// Delete from database
if err := ch.CommandStorer.Delete(ctx, command.ID); err != nil {
ch.Logger.Debug().Err(err).Msg("Command Delete failed.")
return c.JSON(http.StatusBadRequest, kerr.APIError("failed to delete command", http.StatusBadRequest, err))
}
// Delete from storage
if err := ch.Plugins.Delete(ctx, command.Name); err != nil {
ch.Logger.Debug().Err(err).Msg("Failed to delete file from permanent storage.")
return c.JSON(http.StatusInternalServerError, kerr.APIError("failed to delete file from permanent storage", http.StatusInternalServerError, err))
}
return c.NoContent(http.StatusOK)
}
}
// List lists commands.
// swagger:operation POST /commands listCommands
// List commands
// ---
// produces:
// - application/json
// parameters:
// - name: listOptions
// in: body
// required: false
// schema:
// "$ref": "#/definitions/ListOptions"
// responses:
// '200':
// schema:
// type: array
// items:
// "$ref": "#/definitions/Command"
// '500':
// description: 'failed to get user context'
// schema:
// "$ref": "#/responses/Message"
func (ch *CommandsHandler) List() echo.HandlerFunc {
return func(c echo.Context) error {
opts := &models.ListOptions{}
if err := c.Bind(opts); err != nil {
// if we don't have anything to bind, just ignore opts.
opts = nil
}
ctx := c.Request().Context()
list, err := ch.CommandStorer.List(ctx, opts)
if err != nil {
ch.Logger.Debug().Err(err).Msg("Command List failed.")
return c.JSON(http.StatusBadRequest, kerr.APIError("failed to list commands", http.StatusBadRequest, err))
}
return c.JSON(http.StatusOK, list)
}
}
// Get returns a specific command.
// swagger:operation GET /command/{id} getCommand
// Returns a specific command.
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// type: integer
// format: int
// required: true
// responses:
// '200':
// schema:
// "$ref": "#/definitions/Command"
// '400':
// description: 'invalid command id'
// schema:
// "$ref": "#/responses/Message"
// '500':
// description: 'failed to get user context'
// schema:
// "$ref": "#/responses/Message"
func (ch *CommandsHandler) Get() echo.HandlerFunc {
return func(c echo.Context) error {
n, err := GetParamAsInt("id", c)
if err != nil {
apiError := kerr.APIError("invalid command id", http.StatusBadRequest, nil)
return c.JSON(http.StatusBadRequest, apiError)
}
ctx := c.Request().Context()
repo, err := ch.CommandStorer.Get(ctx, n)
if err != nil {
if errors.Is(err, kerr.ErrNotFound) {
return c.JSON(http.StatusNotFound, kerr.APIError("command not found", http.StatusNotFound, err))
}
apiError := kerr.APIError("failed to get command", http.StatusBadRequest, err)
return c.JSON(http.StatusBadRequest, apiError)
}
return c.JSON(http.StatusOK, repo)
}
}
// Upload a command. To set up anything for the command, like schedules etc,
// the command has to be edited. We don't support uploading the same thing twice.
// If the command binary needs to be updated, delete the command and upload the
// new binary.
// swagger:operation PUT /command uploadCommand
// Upload a command. To set up anything for the command, like schedules etc,
// the command has to be edited. We don't support uploading the same thing twice.
// If the command binary needs to be updated, delete the command and upload the
// new binary.
// ---
// produces:
// - application/json
// responses:
// '201':
// description: 'in case of successful file upload'
// schema:
// "$ref": "#/definitions/Command"
// '400':
// description: 'invalid file format or command already exists'
// schema:
// "$ref": "#/responses/Message"
// '500':
// description: 'failed to upload file, create plugin, create command or copy operations'
// schema:
// "$ref": "#/responses/Message"
func (ch *CommandsHandler) Upload() echo.HandlerFunc {
return func(c echo.Context) error {
file, err := c.FormFile("file")
if err != nil {
return err
}
dots := strings.Split(file.Filename, ".")
if len(dots) == 0 {
return c.JSON(http.StatusBadRequest, kerr.APIError("file name does not contain a dot", http.StatusBadRequest, err))
}
name := dots[0]
ctx := c.Request().Context()
// check if name is already taken:
if _, err := ch.CommandStorer.GetByName(ctx, name); err == nil {
return c.JSON(http.StatusBadRequest, kerr.APIError("command with name already taken", http.StatusBadRequest, err))
}
src, err := file.Open()
if err != nil {
return err
}
defer func() {
if err := src.Close(); err != nil {
ch.Logger.Debug().Err(err).Msg("Failed to close src.")
}
}()
f, hash, err := ch.createCommand(c.Request().Context(), file.Filename, src)
if err != nil {
return c.JSON(http.StatusInternalServerError, kerr.APIError("failed to create command", http.StatusInternalServerError, err))
}
command := &models.Command{
Name: name,
Filename: filepath.Base(f),
Location: filepath.Dir(f),
Hash: hash,
Enabled: true,
}
command, err = ch.CommandStorer.Create(ctx, command)
if err != nil {
return c.JSON(http.StatusInternalServerError, kerr.APIError("failed to create command", http.StatusInternalServerError, err))
}
return c.JSON(http.StatusCreated, command)
}
}
// Create a command. This endpoint supports setting up a command with
// various settings including a URL field from which to download a command.
// This could be anything as long as it's accessible.
// swagger:operation POST /command createCommand
// Create a command. This endpoint supports settings up a command with
// various settings including a URL from which to download a command.
// ---
// produces:
// - application/json
// consumes:
// - application/json
// parameters:
// - name: command
// in: body
// required: true
// schema:
// "$ref": "#/definitions/Command"
// responses:
// '201':
// description: 'in case of successful create'
// schema:
// "$ref": "#/definitions/Command"
// '400':
// description: 'invalid file format or command already exists'
// schema:
// "$ref": "#/responses/Message"
// '500':
// description: 'failed to download file, create plugin, create command or copy operations'
// schema:
// "$ref": "#/responses/Message"
func (ch *CommandsHandler) Create() echo.HandlerFunc {
return func(c echo.Context) error {
command := &models.Command{}
if err := c.Bind(command); err != nil {
ch.Logger.Debug().Err(err).Msg("Failed to bind command.")
return c.JSON(http.StatusBadRequest, kerr.APIError("failed to bind command", http.StatusBadRequest, err))
}
if command.URL == "" {
ch.Logger.Error().Msg("In case of Create, a URL must be provided to download the command form.")
return c.JSON(http.StatusBadRequest, kerr.APIError("URL not defined", http.StatusBadRequest, errors.New("url not defined")))
}
if command.Name == "" {
return c.JSON(http.StatusBadRequest, kerr.APIError("name must be defined", http.StatusBadRequest, errors.New("name must be defined")))
}
// check if name is already taken:
if _, err := ch.CommandStorer.GetByName(c.Request().Context(), command.Name); err == nil {
return c.JSON(http.StatusBadRequest, kerr.APIError("command with name already taken", http.StatusBadRequest, err))
}
req, err := http.NewRequest("GET", command.URL, nil)
if err != nil {
return c.JSON(http.StatusBadRequest, kerr.APIError("failed to create HTTP request", http.StatusBadRequest, fmt.Errorf("failed to create HTTP request for %s, error: %w", command.URL, err)))
}
resp, err := ch.Client.Do(req.WithContext(c.Request().Context()))
if err != nil {
return c.JSON(http.StatusBadRequest, kerr.APIError("failed to download binary", http.StatusBadRequest, fmt.Errorf("failed to download binary from %s, error: %w", command.URL, err)))
}
defer func() {
if err := resp.Body.Close(); err != nil {
fmt.Println("Failed to close body reader.")
}
}()
if resp.StatusCode != http.StatusOK {
return c.JSON(http.StatusBadRequest, kerr.APIError("failed to download binary", http.StatusBadRequest, fmt.Errorf("failed to download binary from %s, status: %d", command.URL, resp.StatusCode)))
}
f, hash, err := ch.createCommand(c.Request().Context(), command.Name+".tar.gz", resp.Body)
if err != nil {
return c.JSON(http.StatusInternalServerError, kerr.APIError("failed to create command", http.StatusInternalServerError, err))
}
command.Filename = filepath.Base(f)
command.Location = filepath.Dir(f)
command.Hash = hash
command.Enabled = true
command, err = ch.CommandStorer.Create(c.Request().Context(), command)
if err != nil {
return c.JSON(http.StatusInternalServerError, kerr.APIError("failed to create command", http.StatusInternalServerError, err))
}
return c.JSON(http.StatusCreated, command)
}
}
// createCommand takes care of creating the plugin, the file and the hash for the file which
// was acquired either by uploading a command or downloaded via an external URL.
func (ch *CommandsHandler) createCommand(ctx context.Context, filename string, src io.Reader) (string, string, error) {
// Destination
tmp, err := ioutil.TempDir("", "upload_folder")
if err != nil {
return "", "", fmt.Errorf("failed to create upload folder: %w", err)
}
defer func() {
if err := os.RemoveAll(tmp); err != nil {
ch.Logger.Debug().Err(err).Msg("Warning, failed to clean up temporary folder. Please do that manually.")
}
}()
dst, err := os.Create(filepath.Join(tmp, filename))
if err != nil {
return "", "", fmt.Errorf("failed to create upload file: %w", err)
}
defer func() {
if err := dst.Close(); err != nil {
ch.Logger.Debug().Err(err).Msg("Failed to close destination file.")
}
}()
if _, err = io.Copy(dst, src); err != nil {
return "", "", fmt.Errorf("failed to copy over uploaded file: %w", err)
}
// Create the file first, then the command.
f, hash, err := ch.Plugins.Create(ctx, dst.Name())
if err != nil {
return "", "", fmt.Errorf("failed to create plugin: %w", err)
}
return f, hash, nil
}
// Update updates a command.
// swagger:operation POST /command/update updateCommand
// Updates a given command.
// ---
// produces:
// - application/json
// consumes:
// - application/json
// parameters:
// - name: command
// in: body
// required: true
// schema:
// "$ref": "#/definitions/Command"
// responses:
// '200':
// description: 'successfully updated command'
// schema:
// "$ref": "#/definitions/Command"
// '400':
// description: 'binding error'
// schema:
// "$ref": "#/responses/Message"
// '500':
// description: 'failed to update the command'
// schema:
// "$ref": "#/responses/Message"
func (ch *CommandsHandler) Update() echo.HandlerFunc {
return func(c echo.Context) error {
command := &models.Command{}
if err := c.Bind(command); err != nil {
ch.Logger.Debug().Err(err).Msg("Failed to bind command.")
return c.JSON(http.StatusBadRequest, kerr.APIError("failed to bind command", http.StatusBadRequest, err))
}
ctx := c.Request().Context()
updated, err := ch.CommandStorer.Update(ctx, command)
if err != nil {
if errors.Is(err, kerr.ErrNotFound) {
return c.JSON(http.StatusNotFound, kerr.APIError("command not found", http.StatusNotFound, err))
}
ch.Logger.Debug().Err(err).Msg("Command Update failed.")
return c.JSON(http.StatusInternalServerError, kerr.APIError("failed to update command", http.StatusInternalServerError, err))
}
return c.JSON(http.StatusOK, updated)
}
}
// AddCommandRelForRepository adds a command relationship to a repository.
// swagger:operation POST /command/add-command-rel-for-repository/{cmdid}/{repoid} addCommandRelForRepositoryCommand
// Add a connection to a repository. This will make this command to be executed for events for that repository.
// ---
// parameters:
// - name: cmdid
// in: path
// required: true
// type: integer
// format: int
// - name: repoid
// in: path
// required: true
// type: integer
// format: int
// responses:
// '200':
// description: 'successfully added relationship'
// '400':
// description: 'invalid ids or repositroy not found'
// schema:
// "$ref": "#/responses/Message"
// '500':
// description: 'failed to add relationship'
// schema:
// "$ref": "#/responses/Message"
func (ch *CommandsHandler) AddCommandRelForRepository() echo.HandlerFunc {
return func(c echo.Context) error {
cn, err := GetParamAsInt("cmdid", c)
if err != nil {
apiError := kerr.APIError("invalid command id", http.StatusBadRequest, nil)
return c.JSON(http.StatusBadRequest, apiError)
}
rn, err := GetParamAsInt("repoid", c)
if err != nil {
apiError := kerr.APIError("invalid repo id", http.StatusBadRequest, nil)
return c.JSON(http.StatusBadRequest, apiError)
}
ctx := c.Request().Context()
if err := ch.CommandStorer.AddCommandRelForRepository(ctx, cn, rn); err != nil {
ch.Logger.Debug().Err(err).Msg("AddCommandRelForRepository failed.")
return c.JSON(http.StatusInternalServerError, kerr.APIError("failed to add command relationship to repository", http.StatusInternalServerError, err))
}
return c.NoContent(http.StatusOK)
}
}
// RemoveCommandRelForRepository removes a relationship of a command from a repository.
// swagger:operation POST /command/remove-command-rel-for-repository/{cmdid}/{repoid} removeCommandRelForRepositoryCommand
// Remove a relationship to a repository. This command will no longer be running for that repository events.
// ---
// parameters:
// - name: cmdid
// in: path
// required: true
// type: integer
// format: int
// - name: repoid
// in: path
// required: true
// type: integer
// format: int
// responses:
// '200':
// description: 'successfully removed relationship'
// '400':
// description: 'invalid ids or repositroy not found'
// schema:
// "$ref": "#/responses/Message"
// '500':
// description: 'failed to add relationship'
// schema:
// "$ref": "#/responses/Message"
func (ch *CommandsHandler) RemoveCommandRelForRepository() echo.HandlerFunc {
return func(c echo.Context) error {
cn, err := GetParamAsInt("cmdid", c)
if err != nil {
apiError := kerr.APIError("invalid command id", http.StatusBadRequest, nil)
return c.JSON(http.StatusBadRequest, apiError)
}
rn, err := GetParamAsInt("repoid", c)
if err != nil {
apiError := kerr.APIError("invalid repo id", http.StatusBadRequest, nil)
return c.JSON(http.StatusBadRequest, apiError)
}
ctx := c.Request().Context()
if err := ch.CommandStorer.RemoveCommandRelForRepository(ctx, cn, rn); err != nil {
ch.Logger.Debug().Err(err).Msg("RemoveCommandRelForRepository failed.")
return c.JSON(http.StatusInternalServerError, kerr.APIError("failed to remove command relationship to repository", http.StatusInternalServerError, err))
}
return c.NoContent(http.StatusOK)
}
}
// AddCommandRelForPlatform adds a command relationship to a platform.
// swagger:operation POST /command/add-command-rel-for-platform/{cmdid}/{repoid} addCommandRelForPlatformCommand
// Adds a connection to a platform for a command. Defines what platform a command supports. These commands will only be able to run for those platforms.
// ---
// parameters:
// - name: cmdid
// in: path
// required: true
// type: integer
// format: int
// - name: repoid
// in: path
// required: true
// type: integer
// format: int
// responses:
// '200':
// description: 'successfully added relationship'
// '400':
// description: 'invalid ids or platform not found'
// schema:
// "$ref": "#/responses/Message"
// '500':
// description: 'failed to add command relationship to platform'
// schema:
// "$ref": "#/responses/Message"
func (ch *CommandsHandler) AddCommandRelForPlatform() echo.HandlerFunc {
return func(c echo.Context) error {
cn, err := GetParamAsInt("cmdid", c)
if err != nil {
apiError := kerr.APIError("invalid command id", http.StatusBadRequest, nil)
return c.JSON(http.StatusBadRequest, apiError)
}
pid, err := GetParamAsInt("pid", c)
if err != nil {
apiError := kerr.APIError("invalid platform id", http.StatusBadRequest, nil)
return c.JSON(http.StatusBadRequest, apiError)
}
if _, found := models.SupportedPlatforms[pid]; !found {
apiError := kerr.APIError("platform id not found in supported platforms", http.StatusBadRequest, nil)
return c.JSON(http.StatusBadRequest, apiError)
}
ctx := c.Request().Context()
if err := ch.CommandStorer.AddCommandRelForPlatform(ctx, cn, pid); err != nil {
ch.Logger.Debug().Err(err).Msg("AddCommandRelForPlatform failed.")
return c.JSON(http.StatusInternalServerError, kerr.APIError("failed to add command relationship to platform", http.StatusInternalServerError, err))
}
return c.NoContent(http.StatusOK)
}
}
// RemoveCommandRelForPlatform removes a relationship of a command from a platform.
// swagger:operation POST /command/remove-command-rel-for-platform/{cmdid}/{repoid} removeCommandRelForPlatformCommand
// Remove a relationship to a platform. This command will no longer be running for that platform events.
// ---
// parameters:
// - name: cmdid
// in: path
// required: true
// type: integer
// format: int
// - name: repoid
// in: path
// required: true
// type: integer
// format: int
// responses:
// '200':
// description: 'successfully removed relationship'
// '400':
// description: 'invalid ids or platform not found'
// schema:
// "$ref": "#/responses/Message"
// '500':
// description: 'failed to add relationship'
// schema:
// "$ref": "#/responses/Message"
func (ch *CommandsHandler) RemoveCommandRelForPlatform() echo.HandlerFunc {
return func(c echo.Context) error {
cn, err := GetParamAsInt("cmdid", c)
if err != nil {
apiError := kerr.APIError("invalid command id", http.StatusBadRequest, nil)
return c.JSON(http.StatusBadRequest, apiError)
}
pid, err := GetParamAsInt("pid", c)
if err != nil {
apiError := kerr.APIError("invalid platform id", http.StatusBadRequest, nil)
return c.JSON(http.StatusBadRequest, apiError)
}
ctx := c.Request().Context()
if err := ch.CommandStorer.RemoveCommandRelForPlatform(ctx, cn, pid); err != nil {
ch.Logger.Debug().Err(err).Msg("RemoveCommandRelForPlatform failed.")
return c.JSON(http.StatusInternalServerError, kerr.APIError("failed to remove command relationship to platform", http.StatusInternalServerError, err))
}
return c.NoContent(http.StatusOK)
}
}