-
Notifications
You must be signed in to change notification settings - Fork 414
/
workflow.go
1055 lines (889 loc) · 31.9 KB
/
workflow.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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package api
import (
"context"
"fmt"
"io"
"net/http"
"sort"
"strconv"
"strings"
"github.com/fsamin/go-dump"
"github.com/go-gorp/gorp"
"github.com/gorilla/mux"
"github.com/rockbears/log"
"github.com/ovh/cds/engine/api/application"
"github.com/ovh/cds/engine/api/environment"
"github.com/ovh/cds/engine/api/event"
"github.com/ovh/cds/engine/api/group"
"github.com/ovh/cds/engine/api/permission"
"github.com/ovh/cds/engine/api/pipeline"
"github.com/ovh/cds/engine/api/project"
"github.com/ovh/cds/engine/api/purge"
"github.com/ovh/cds/engine/api/services"
"github.com/ovh/cds/engine/api/workflow"
"github.com/ovh/cds/engine/service"
"github.com/ovh/cds/sdk"
"github.com/ovh/cds/sdk/exportentities"
)
// getWorkflowsHandler returns ID and name of workflows for a given project/user
func (api *API) getWorkflowsHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
filterByProject := vars[permProjectKey]
filterByRepo := r.FormValue("repo")
var dao workflow.WorkflowDAO
if filterByProject != "" {
dao.Filters.ProjectKey = filterByProject
}
if filterByRepo != "" {
dao.Filters.ApplicationRepository = filterByRepo
}
dao.Loaders.WithFavoritesForUserID = getUserConsumer(ctx).AuthConsumerUser.AuthentifiedUserID
groupIDS := getUserConsumer(ctx).GetGroupIDs()
dao.Filters.GroupIDs = groupIDS
if isMaintainer(ctx) {
dao.Filters.GroupIDs = nil
}
ws, err := dao.LoadAll(ctx, api.mustDBWithCtx(ctx))
if err != nil {
return err
}
ids := ws.IDs()
perms, err := permission.LoadWorkflowMaxLevelPermissionByWorkflowIDs(ctx, api.mustDB(), ids, groupIDS)
if err != nil {
return err
}
for i := range ws {
if isAdmin(ctx) {
ws[i].Permissions = sdk.Permissions{Readable: true, Writable: true, Executable: true}
} else {
idString := strconv.FormatInt(ws[i].ID, 10)
ws[i].Permissions = perms.Permissions(idString)
if isMaintainer(ctx) {
ws[i].Permissions.Readable = true
}
}
w1 := &ws[i]
api.setWorkflowURLs(w1)
}
return service.WriteJSON(w, ws, http.StatusOK)
}
}
func (api *API) setWorkflowURLs(w1 *sdk.Workflow) {
w1.URLs.APIURL = api.Config.URL.API + api.Router.GetRoute("GET", api.getWorkflowHandler, map[string]string{"key": w1.ProjectKey, "permWorkflowNameAdvanced": w1.Name})
w1.URLs.UIURL = api.Config.URL.UI + "/project/" + w1.ProjectKey + "/workflow/" + w1.Name
for j := range w1.Runs {
r1 := &w1.Runs[j]
api.setWorkflowRunURLs(r1)
}
}
func (api *API) setWorkflowRunURLs(r1 *sdk.WorkflowRun) {
r1.URLs.APIURL = api.Config.URL.API + api.Router.GetRoute("GET", api.getWorkflowRunHandler, map[string]string{"key": r1.Workflow.ProjectKey, "permWorkflowNameAdvanced": r1.Workflow.Name, "number": strconv.FormatInt(r1.Number, 10)})
r1.URLs.UIURL = api.Config.URL.UI + "/project/" + r1.Workflow.ProjectKey + "/workflow/" + r1.Workflow.Name + "/run/" + strconv.FormatInt(r1.Number, 10)
}
func (api *API) getRetentionPolicySuggestionHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars["key"]
name := vars["permWorkflowName"]
proj, err := project.Load(ctx, api.mustDBWithCtx(ctx), key, project.LoadOptions.WithIntegrations)
if err != nil {
return err
}
varsPayload := make(map[string]string, 0)
run, err := workflow.LoadLastRun(ctx, api.mustDB(), key, name, workflow.LoadRunOptions{DisableDetailledNodeRun: true})
if err != nil && !sdk.ErrorIs(err, sdk.ErrNotFound) {
return err
}
e := dump.NewDefaultEncoder()
e.Formatters = []dump.KeyFormatterFunc{dump.WithDefaultLowerCaseFormatter()}
e.ExtraFields.DetailedMap = false
e.ExtraFields.DetailedStruct = false
e.ExtraFields.Len = false
e.ExtraFields.Type = false
if run != nil && run.ToCraftOpts != nil {
if run.ToCraftOpts.Hook != nil {
varsPayload = run.ToCraftOpts.Hook.Payload
}
if run.ToCraftOpts.Manual != nil {
payload := run.ToCraftOpts.Manual.Payload
if payload != nil {
tmpVars, err := e.ToStringMap(payload)
if err != nil {
return sdk.WithStack(err)
}
for k, v := range tmpVars {
varsPayload[k] = v
}
}
}
}
if len(varsPayload) == 0 {
wf, err := workflow.Load(ctx, api.mustDBWithCtx(ctx), api.Cache, *proj, name, workflow.LoadOptions{})
if err != nil {
return err
}
if wf.WorkflowData.Node.Context.DefaultPayload != nil {
tmpVars, err := e.ToStringMap(wf.WorkflowData.Node.Context.DefaultPayload)
if err != nil {
return sdk.WithStack(err)
}
for k, v := range tmpVars {
varsPayload[k] = v
}
}
}
retentionPolicySuggestion := purge.GetRetentionPolicyVariables()
for k := range varsPayload {
retentionPolicySuggestion = append(retentionPolicySuggestion, k)
}
for i := range retentionPolicySuggestion {
v := retentionPolicySuggestion[i]
v = strings.Replace(v, ".", "_", -1)
retentionPolicySuggestion[i] = v
}
return service.WriteJSON(w, retentionPolicySuggestion, http.StatusOK)
}
}
func (api *API) postWorkflowRetentionPolicyDryRun() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars["key"]
name := vars["permWorkflowName"]
var request sdk.PurgeDryRunRequest
if err := service.UnmarshalBody(r, &request); err != nil {
return err
}
proj, err := project.Load(ctx, api.mustDBWithCtx(ctx), key, project.LoadOptions.WithIntegrations)
if err != nil {
return err
}
wf, err := workflow.Load(ctx, api.mustDBWithCtx(ctx), api.Cache, *proj, name, workflow.LoadOptions{})
if err != nil {
return err
}
wf.RetentionPolicy = request.RetentionPolicy
// Get the number of runs to analyze
_, _, _, count, err := workflow.LoadRunsSummaries(ctx, api.mustDB(), wf.ProjectKey, wf.Name, 0, 1, nil)
if err != nil {
return err
}
u := getUserConsumer(ctx)
api.GoRoutines.Exec(api.Router.Background, "workflow-retention-dryrun", func(ctx context.Context) {
if err := purge.ApplyRetentionPolicyOnWorkflow(ctx, api.Cache, api.mustDBWithCtx(ctx), *wf, purge.MarkAsDeleteOptions{DryRun: true}, u.AuthConsumerUser.AuthentifiedUser); err != nil {
ctx = sdk.ContextWithStacktrace(ctx, err)
log.Error(ctx, err.Error())
httpErr := sdk.ExtractHTTPError(err)
event.PublishWorkflowRetentionDryRun(ctx, key, name, "ERROR", httpErr.Error(), nil, nil, 0, u.AuthConsumerUser.AuthentifiedUser)
}
})
return service.WriteJSON(w, sdk.PurgeDryRunResponse{NbRunsToAnalize: int64(count)}, http.StatusOK)
}
}
// getWorkflowHandler returns a full workflow
func (api *API) getWorkflowHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars["key"]
name := vars["permWorkflowNameAdvanced"]
if name == "" {
name = vars["permWorkflowName"] // Useful for workflowv3 routes
}
withUsage := service.FormBool(r, "withUsage")
withAudits := service.FormBool(r, "withAudits")
withLabels := service.FormBool(r, "withLabels")
withDeepPipelines := service.FormBool(r, "withDeepPipelines")
withTemplate := service.FormBool(r, "withTemplate")
withAsCodeEvents := service.FormBool(r, "withAsCodeEvents")
minimal := service.FormBool(r, "minimal")
withoutIcons := service.FormBool(r, "withoutIcons")
proj, err := project.Load(ctx, api.mustDB(), key, project.LoadOptions.WithIntegrations)
if err != nil {
return sdk.WrapError(err, "unable to load projet")
}
opts := workflow.LoadOptions{
Minimal: minimal, // if true, load only data from table workflow, not pipelines, app, env...
DeepPipeline: withDeepPipelines,
WithIcon: !withoutIcons,
WithLabels: withLabels,
WithAsCodeUpdateEvent: withAsCodeEvents,
WithIntegrations: true,
WithTemplate: withTemplate,
WithFavoritesForUserID: getUserConsumer(ctx).AuthConsumerUser.AuthentifiedUserID,
}
w1, err := workflow.Load(ctx, api.mustDB(), api.Cache, *proj, name, opts)
if err != nil {
return sdk.WrapError(err, "cannot load workflow %s", name)
}
if withUsage {
usage, err := loadWorkflowUsage(ctx, api.mustDB(), w1.ID)
if err != nil {
return sdk.WrapError(err, "cannot load usage for workflow %s", name)
}
w1.Usage = &usage
}
if withAudits {
audits, err := workflow.LoadAudits(api.mustDB(), w1.ID)
if err != nil {
return sdk.WrapError(err, "cannot load audits for workflow %s", name)
}
w1.Audits = audits
}
if isAdmin(ctx) {
w1.Permissions = sdk.Permissions{Readable: true, Writable: true, Executable: true}
} else {
perms, err := permission.LoadWorkflowMaxLevelPermission(ctx, api.mustDB(), key, []string{w1.Name}, getUserConsumer(ctx).GetGroupIDs())
if err != nil {
return err
}
w1.Permissions = perms.Permissions(w1.Name)
if isMaintainer(ctx) {
w1.Permissions.Readable = true
}
}
api.setWorkflowURLs(w1)
//We filter project and workflow configuration key, because they are always set on insertHooks
w1.FilterHooksConfig(sdk.HookConfigProject, sdk.HookConfigWorkflow)
return service.WriteJSON(w, w1, http.StatusOK)
}
}
func loadWorkflowUsage(ctx context.Context, db gorp.SqlExecutor, workflowID int64) (sdk.Usage, error) {
usage := sdk.Usage{}
pips, errP := pipeline.LoadByWorkflowID(db, workflowID)
if errP != nil {
return usage, sdk.WrapError(errP, "Cannot load pipelines linked to a workflow id %d", workflowID)
}
usage.Pipelines = pips
envs, errE := environment.LoadByWorkflowID(db, workflowID)
if errE != nil {
return usage, sdk.WrapError(errE, "Cannot load environments linked to a workflow id %d", workflowID)
}
usage.Environments = envs
apps, errA := application.LoadByWorkflowID(ctx, db, workflowID)
if errA != nil {
return usage, sdk.WrapError(errA, "Cannot load applications linked to a workflow id %d", workflowID)
}
usage.Applications = apps
return usage, nil
}
// postWorkflowRollbackHandler rollback to a specific audit id
func (api *API) postWorkflowRollbackHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars["key"]
workflowName := vars["permWorkflowName"]
auditID, errConv := strconv.ParseInt(vars["auditID"], 10, 64)
if errConv != nil {
return sdk.WrapError(sdk.ErrWrongRequest, "Cannot convert auditID to int")
}
db := api.mustDB()
u := getUserConsumer(ctx)
proj, err := project.Load(ctx, db, key,
project.LoadOptions.WithGroups,
project.LoadOptions.WithApplications,
project.LoadOptions.WithEnvironments,
project.LoadOptions.WithPipelines,
project.LoadOptions.WithIntegrations,
project.LoadOptions.WithApplicationWithDeploymentStrategies,
)
if err != nil {
return sdk.WrapError(err, "cannot load project %s", key)
}
wf, err := workflow.Load(ctx, db, api.Cache, *proj, workflowName, workflow.LoadOptions{WithIcon: true})
if err != nil {
return sdk.WrapError(err, "cannot load workflow %s/%s", key, workflowName)
}
audit, err := workflow.LoadAudit(db, auditID, wf.ID)
if err != nil {
return sdk.WrapError(err, "cannot load workflow audit %s/%s", key, workflowName)
}
exportWf, err := exportentities.UnmarshalWorkflow([]byte(audit.DataBefore), exportentities.FormatYAML)
if err != nil {
return sdk.WrapError(err, "cannot unmarshal data before")
}
tx, err := db.Begin()
if err != nil {
return sdk.WrapError(err, "cannot begin transaction")
}
defer tx.Rollback() // nolint
newWf, _, errP := workflow.ParseAndImport(ctx, tx, api.Cache, *proj, wf, exportWf, u, workflow.ImportOptions{Force: true, WorkflowName: workflowName})
if errP != nil {
return sdk.WrapError(errP, "cannot parse and import previous workflow")
}
if err := tx.Commit(); err != nil {
return sdk.WithStack(err)
}
newWf.Permissions.Readable = true
newWf.Permissions.Executable = true
newWf.Permissions.Writable = true
event.PublishWorkflowUpdate(ctx, key, *wf, *newWf, getUserConsumer(ctx))
return service.WriteJSON(w, *newWf, http.StatusOK)
}
}
// postWorkflowLabelHandler handler to link a label to a workflow
func (api *API) postWorkflowLabelHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars["key"]
workflowName := vars["permWorkflowName"]
db := api.mustDB()
var label sdk.Label
if err := service.UnmarshalBody(r, &label); err != nil {
return err
}
if label.ID == 0 && label.Name == "" {
return sdk.NewErrorFrom(sdk.ErrWrongRequest, "label ID or label name should not be empty")
}
tx, err := db.Begin()
if err != nil {
return sdk.WrapError(err, "cannot create new transaction")
}
defer tx.Rollback() //nolint
proj, err := project.Load(ctx, tx, key)
if err != nil {
return sdk.WrapError(err, "cannot load project %s", key)
}
label.ProjectID = proj.ID
if label.ID == 0 {
existingLabel, err := project.LabelByName(ctx, tx, proj.ID, label.Name)
if err != nil && !sdk.ErrorIs(err, sdk.ErrNotFound) {
return err
}
if existingLabel == nil {
if err := project.InsertLabel(tx, &label); err != nil {
return sdk.WrapError(err, "cannot create new label")
}
} else {
label.ID = existingLabel.ID
}
}
wf, err := workflow.Load(ctx, tx, api.Cache, *proj, workflowName, workflow.LoadOptions{Minimal: true})
if err != nil {
return sdk.WrapError(err, "cannot load workflow %s/%s", key, workflowName)
}
if err := workflow.LabelWorkflow(tx, label.ID, wf.ID); err != nil {
return sdk.WrapError(err, "cannot link label %d to workflow %s", label.ID, wf.Name)
}
label.WorkflowID = wf.ID
if err := tx.Commit(); err != nil {
return sdk.WithStack(err)
}
return service.WriteJSON(w, label, http.StatusOK)
}
}
// deleteWorkflowLabelHandler handler to unlink a label to a workflow
func (api *API) deleteWorkflowLabelHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars["key"]
workflowName := vars["permWorkflowName"]
labelID, err := requestVarInt(r, "labelID")
if err != nil {
return sdk.WrapError(err, "cannot convert to int labelID")
}
db := api.mustDB()
proj, err := project.Load(ctx, db, key)
if err != nil {
return sdk.WrapError(err, "cannot load project %s", key)
}
wf, err := workflow.Load(ctx, db, api.Cache, *proj, workflowName, workflow.LoadOptions{Minimal: true})
if err != nil {
return sdk.WrapError(err, "cannot load workflow %s/%s", key, workflowName)
}
if err := workflow.UnLabelWorkflow(db, labelID, wf.ID); err != nil {
return sdk.WrapError(err, "cannot unlink label %d to workflow %s", labelID, wf.Name)
}
return service.WriteJSON(w, nil, http.StatusOK)
}
}
// postWorkflowHandler creates a new workflow
func (api *API) postWorkflowHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars[permProjectKey]
p, err := project.Load(ctx, api.mustDB(), key,
project.LoadOptions.WithGroups,
project.LoadOptions.WithIntegrations,
)
if err != nil {
return err
}
var data sdk.Workflow
if err := service.UnmarshalBody(r, &data); err != nil {
return err
}
if err := workflow.RenameNode(ctx, api.mustDB(), &data); err != nil {
return err
}
data.ProjectID = p.ID
data.ProjectKey = key
tx, err := api.mustDB().Begin()
if err != nil {
return sdk.WithStack(err)
}
defer tx.Rollback() // nolint
// Check group permissions if given for workflow and nodes
if err := group.CheckWorkflowGroups(ctx, tx, p, &data, getUserConsumer(ctx)); err != nil {
return err
}
if err := workflow.Insert(ctx, tx, api.Cache, *p, &data); err != nil {
return sdk.WrapError(err, "cannot insert workflow")
}
if err := tx.Commit(); err != nil {
return sdk.WithStack(err)
}
wf, err := workflow.LoadByID(ctx, api.mustDB(), api.Cache, *p, data.ID, workflow.LoadOptions{})
if err != nil {
return sdk.WrapError(err, "cannot load workflow")
}
event.PublishWorkflowAdd(ctx, p.Key, *wf, getUserConsumer(ctx))
wf.Permissions.Readable = true
wf.Permissions.Writable = true
wf.Permissions.Executable = true
//We filter project and workflow configurtaion key, because they are always set on insertHooks
wf.FilterHooksConfig(sdk.HookConfigProject, sdk.HookConfigWorkflow)
return service.WriteJSON(w, wf, http.StatusCreated)
}
}
// putWorkflowHandler updates a workflow
func (api *API) putWorkflowHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars["key"]
name := vars["permWorkflowNameAdvanced"]
if isHooks(ctx) {
return sdk.WithStack(sdk.ErrForbidden)
}
p, err := project.Load(ctx, api.mustDB(), key, project.LoadOptions.WithIntegrations)
if err != nil {
return sdk.WrapError(err, "cannot load Project %s", key)
}
oldW, err := workflow.Load(ctx, api.mustDB(), api.Cache, *p, name,
workflow.LoadOptions{WithIcon: true, WithIntegrations: true})
if err != nil {
return sdk.WrapError(err, "cannot load Workflow %s", key)
}
if oldW.FromRepository != "" {
return sdk.WithStack(sdk.ErrForbidden)
}
var wf sdk.Workflow
if err := service.UnmarshalBody(r, &wf); err != nil {
return sdk.WrapError(err, "cannot read body")
}
if err := workflow.RenameNode(ctx, api.mustDB(), &wf); err != nil {
return sdk.WrapError(err, "cannot check pipeline name")
}
wf.ID = oldW.ID
wf.ProjectID = p.ID
wf.ProjectKey = key
tx, err := api.mustDB().Begin()
if err != nil {
return sdk.WrapError(err, "cannot start transaction")
}
defer tx.Rollback() // nolint
// Update workflow do not handle workflow groups changes but only nodes groups
wf.Groups = nil
// Check group permissions if given for workflow and nodes
if err := group.CheckWorkflowGroups(ctx, tx, p, &wf, getUserConsumer(ctx)); err != nil {
return err
}
if err := workflow.Update(ctx, tx, api.Cache, *p, &wf, workflow.UpdateOptions{}); err != nil {
return sdk.WrapError(err, "cannot update workflow")
}
if defaultTags, ok := wf.Metadata["default_tags"]; wf.WorkflowData.Node.IsLinkedToRepo(&wf) && (!ok || defaultTags == "") {
if wf.Metadata == nil {
wf.Metadata = sdk.Metadata{}
}
wf.Metadata["default_tags"] = "git.branch,git.author"
if err := workflow.UpdateMetadata(tx, wf.ID, wf.Metadata); err != nil {
return sdk.WrapError(err, "cannot update metadata")
}
}
if err := tx.Commit(); err != nil {
return sdk.WithStack(err)
}
wf1, err := workflow.LoadByID(ctx, api.mustDB(), api.Cache, *p, wf.ID, workflow.LoadOptions{WithIntegrations: true})
if err != nil {
return sdk.WrapError(err, "cannot load workflow")
}
event.PublishWorkflowUpdate(ctx, p.Key, *wf1, *oldW, getUserConsumer(ctx))
wf1.Permissions.Readable = true
wf1.Permissions.Writable = true
wf1.Permissions.Executable = true
usage, err := loadWorkflowUsage(ctx, api.mustDB(), wf1.ID)
if err != nil {
return sdk.WrapError(err, "cannot load usage")
}
wf1.Usage = &usage
//We filter project and workflow configuration key, because they are always set on insertHooks
wf1.FilterHooksConfig(sdk.HookConfigProject, sdk.HookConfigWorkflow)
return service.WriteJSON(w, wf1, http.StatusOK)
}
}
// putWorkflowIconHandler updates a workflow
func (api *API) putWorkflowIconHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars["key"]
name := vars["permWorkflowName"]
p, errP := project.Load(ctx, api.mustDB(), key)
if errP != nil {
return errP
}
imageBts, errr := io.ReadAll(r.Body)
if errr != nil {
return sdk.NewError(sdk.ErrWrongRequest, errr)
}
defer r.Body.Close()
icon := string(imageBts)
if !strings.HasPrefix(icon, sdk.IconFormat) {
return sdk.WithStack(sdk.ErrIconBadFormat)
}
if len(icon) > sdk.MaxIconSize {
return sdk.WithStack(sdk.ErrIconBadSize)
}
wf, err := workflow.Load(ctx, api.mustDB(), api.Cache, *p, name, workflow.LoadOptions{
Minimal: true,
})
if err != nil {
return err
}
if err := workflow.UpdateIcon(api.mustDB(), wf.ID, icon); err != nil {
return err
}
return service.WriteJSON(w, nil, http.StatusOK)
}
}
// deleteWorkflowIconHandler updates a workflow
func (api *API) deleteWorkflowIconHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars["key"]
name := vars["permWorkflowName"]
p, errP := project.Load(ctx, api.mustDB(), key)
if errP != nil {
return errP
}
wf, err := workflow.Load(ctx, api.mustDB(), api.Cache, *p, name, workflow.LoadOptions{})
if err != nil {
return err
}
if err := workflow.UpdateIcon(api.mustDB(), wf.ID, ""); err != nil {
return err
}
return service.WriteJSON(w, nil, http.StatusOK)
}
}
// deleteWorkflowHandler deletes a workflow
func (api *API) deleteWorkflowHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars["key"]
name := vars["permWorkflowNameAdvanced"]
if isHooks(ctx) {
return sdk.WithStack(sdk.ErrForbidden)
}
p, errP := project.Load(ctx, api.mustDB(), key, project.LoadOptions.WithIntegrations)
if errP != nil {
return sdk.WrapError(errP, "Cannot load Project %s", key)
}
b, errW := workflow.Exists(ctx, api.mustDB(), key, name)
if errW != nil {
return sdk.WrapError(errW, "Cannot check Workflow %s", key)
}
if !b {
return sdk.WithStack(sdk.ErrNotFound)
}
wf, err := workflow.Load(ctx, api.mustDB(), api.Cache, *p, name, workflow.LoadOptions{})
if err != nil {
return err
}
tx, errT := api.mustDB().Begin()
if errT != nil {
return sdk.WrapError(errT, "Cannot start transaction")
}
defer tx.Rollback() // nolint
if service.FormBool(r, "withDependencies") {
if err := workflow.MarkAsDeleteWithDependencies(ctx, tx, api.Cache, *p, wf); err != nil {
return err
}
} else {
if err := workflow.MarkAsDelete(ctx, tx, api.Cache, *p, wf); err != nil {
return err
}
}
if err := tx.Commit(); err != nil {
return sdk.WrapError(errT, "Cannot commit transaction")
}
consumer := getUserConsumer(ctx)
api.GoRoutines.Exec(api.Router.Background, "deleteWorkflowHandler",
func(ctx context.Context) {
txg, err := api.mustDB().Begin()
if err != nil {
log.Error(ctx, "deleteWorkflowHandler> Cannot start transaction: %v", err)
return
}
defer txg.Rollback() // nolint
var dao workflow.WorkflowDAO
dao.Filters.ProjectKey = p.Key
dao.Filters.WorkflowName = name
dao.Filters.DisableFilterDeletedWorkflow = true
oldW, err := dao.Load(ctx, txg)
if err != nil {
log.Error(ctx, "deleteWorkflowHandler> unable to load workflow for deletion: %v", err)
return
}
if err := workflow.CompleteWorkflow(ctx, txg, &oldW, *p, workflow.LoadOptions{}); err != nil {
log.Error(ctx, "deleteWorkflowHandler> unable to load workflow: not found")
return
}
if err := workflow.Delete(ctx, txg, api.Cache, *p, &oldW); err != nil {
log.Error(ctx, "deleteWorkflowHandler> unable to delete workflow: %v", err)
return
}
if err := txg.Commit(); err != nil {
log.Error(ctx, "deleteWorkflowHandler> Cannot commit transaction: %v", err)
}
event.PublishWorkflowDelete(ctx, key, oldW, consumer)
})
return service.WriteJSON(w, nil, http.StatusOK)
}
}
// deleteWorkflowEventsIntegrationHandler deletes a workflow event integration
func (api *API) deleteWorkflowEventsIntegrationHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars["key"]
name := vars["permWorkflowName"]
prjIntegrationIDStr := vars["integrationID"]
db := api.mustDB()
prjIntegrationID, err := strconv.ParseInt(prjIntegrationIDStr, 10, 64)
if err != nil {
return sdk.WrapError(sdk.ErrInvalidID, "integration id is not correct (%s) : %v", prjIntegrationIDStr, err)
}
p, err := project.Load(ctx, db, key, project.LoadOptions.WithIntegrations)
if err != nil {
return sdk.WrapError(err, "cannot load Project %s", key)
}
wf, err := workflow.Load(ctx, db, api.Cache, *p, name, workflow.LoadOptions{WithIntegrations: true})
if err != nil {
return sdk.WrapError(err, "cannot load Workflow %s", key)
}
var integ *sdk.WorkflowProjectIntegration
for i := range wf.Integrations {
if wf.Integrations[i].ProjectIntegrationID == prjIntegrationID {
integ = &wf.Integrations[i]
}
}
if integ == nil {
return sdk.NewErrorFrom(sdk.ErrNotFound, "unable to find integration %d", prjIntegrationID)
}
if err := workflow.RemoveIntegrationFromWorkflow(db, *integ); err != nil {
return sdk.WrapError(err, "cannot remove integration id %d from workflow %s (id: %d)", prjIntegrationID, wf.Name, wf.ID)
}
return service.WriteJSON(w, nil, http.StatusOK)
}
}
func (api *API) getWorkflowHookHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars["key"]
name := vars["permWorkflowName"]
uuid := vars["uuid"]
proj, err := project.Load(ctx, api.mustDB(), key,
project.LoadOptions.WithIntegrations,
project.LoadOptions.WithApplicationWithDeploymentStrategies,
project.LoadOptions.WithPipelines,
project.LoadOptions.WithEnvironments)
if err != nil {
return sdk.WrapError(err, "cannot load Project %s", key)
}
wf, err := workflow.Load(ctx, api.mustDB(), api.Cache, *proj, name, workflow.LoadOptions{})
if err != nil {
return sdk.WrapError(err, "cannot load Workflow %s/%s", key, name)
}
whooks := wf.WorkflowData.GetHooks()
_, has := whooks[uuid]
if !has {
return sdk.WrapError(sdk.ErrNotFound, "cannot load Workflow %s/%s hook %s", key, name, uuid)
}
//Push the hook to hooks µService
//Load service "hooks"
srvs, err := services.LoadAllByType(ctx, api.mustDB(), sdk.TypeHooks)
if err != nil {
return sdk.WrapError(err, "unable to load hooks services")
}
path := fmt.Sprintf("/task/%s/execution", uuid)
task := sdk.Task{}
if _, _, err := services.NewClient(api.mustDB(), srvs).DoJSONRequest(ctx, "GET", path, nil, &task); err != nil {
return sdk.WrapError(err, "unable to get hook %s task and executions", uuid)
}
return service.WriteJSON(w, task, http.StatusOK)
}
}
func (api *API) getWorkflowNotificationsConditionsHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars["key"]
name := vars["permWorkflowName"]
data := struct {
Operators map[string]string `json:"operators"`
ConditionNames []string `json:"names"`
}{
Operators: sdk.WorkflowConditionsOperators,
}
wr, errr := workflow.LoadLastRun(ctx, api.mustDB(), key, name, workflow.LoadRunOptions{})
if errr != nil {
if !sdk.ErrorIs(errr, sdk.ErrNotFound) {
return sdk.WrapError(errr, "getWorkflowTriggerConditionHandler> Unable to load last run workflow")
}
}
params := []sdk.Parameter{}
var refNode *sdk.Node
if wr != nil {
refNode = &wr.Workflow.WorkflowData.Node
var errp error
params, errp = workflow.NodeBuildParametersFromRun(*wr, refNode.ID)
if errp != nil {
return sdk.WrapError(errp, "getWorkflowTriggerConditionHandler> Unable to load build parameters from workflow run")
}
if len(params) == 0 {
refNode = nil
}
} else {
data.ConditionNames = append(data.ConditionNames, sdk.BasicVariableNames...)
}
if sdk.ParameterFind(params, "git.repository") == nil {
data.ConditionNames = append(data.ConditionNames, sdk.BasicGitVariableNames...)
}
if sdk.ParameterFind(params, "git.tag") == nil {
data.ConditionNames = append(data.ConditionNames, "git.tag")
}
for _, p := range params {
data.ConditionNames = append(data.ConditionNames, p.Name)
}
sort.Strings(data.ConditionNames)
return service.WriteJSON(w, data, http.StatusOK)
}
}
func (api *API) getSearchWorkflowHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
var dao workflow.WorkflowDAO
dao.Filters.ProjectKey = FormString(r, "project")
dao.Filters.WorkflowName = FormString(r, "name")
dao.Filters.VCSServer = FormString(r, "vcs")
dao.Filters.ApplicationRepository = FormString(r, "repository")
dao.Filters.AsCode = service.FormBool(r, "ascode")
dao.Loaders.WithRuns = service.FormInt(r, "runs")
dao.Loaders.WithFavoritesForUserID = getUserConsumer(ctx).AuthConsumerUser.AuthentifiedUserID
groupIDS := getUserConsumer(ctx).GetGroupIDs()
dao.Filters.GroupIDs = groupIDS
if isMaintainer(ctx) {
dao.Filters.GroupIDs = nil
}
ws, err := dao.LoadAll(ctx, api.mustDBWithCtx(ctx))
if err != nil {
return err
}
ids := ws.IDs()
perms, err := permission.LoadWorkflowMaxLevelPermissionByWorkflowIDs(ctx, api.mustDB(), ids, groupIDS)
if err != nil {
return err
}
for i := range ws {
if isAdmin(ctx) {
ws[i].Permissions = sdk.Permissions{Readable: true, Writable: true, Executable: true}
} else {
idString := strconv.FormatInt(ws[i].ID, 10)
ws[i].Permissions = perms.Permissions(idString)
if isMaintainer(ctx) {
ws[i].Permissions.Readable = true
}
}
w1 := &ws[i]
api.setWorkflowURLs(w1)
}
return service.WriteJSON(w, ws, http.StatusOK)
}
}
func (api *API) getWorkflowDependenciesHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars["key"]
name := vars["permWorkflowName"]
proj, err := project.Load(ctx, api.mustDB(), key)
if err != nil {
return err
}
var opts = workflow.LoadOptions{Minimal: true}
wf, err := workflow.Load(ctx, api.mustDB(), api.Cache, *proj, name, opts)
if err != nil {
return err
}
usage, err := loadWorkflowUsage(ctx, api.mustDB(), wf.ID)
if err != nil {
return err
}
var pips []sdk.IDName
var pipAsCodeUnlinked []sdk.IDName
for _, pip := range usage.Pipelines {
log.Debug(ctx, "checking pipeline %d %q %q", pip.ID, pip.Name, pip.FromRepository)
allWfs, err := workflow.LoadByPipelineName(ctx, api.mustDB(), key, pip.Name)
if err != nil {
return err
}
if len(allWfs) == 1 {
pips = append(pips, sdk.IDName{ID: pip.ID, Name: pip.Name})
continue
}