Repository navigation
Expand file tree
/
Copy pathapplication.go
More file actions
676 lines (560 loc) · 21.1 KB
/
Copy pathapplication.go
File metadata and controls
676 lines (560 loc) · 21.1 KB
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
package api
import (
"context"
"database/sql"
"fmt"
"io"
"net/http"
"strings"
"github.com/go-gorp/gorp"
"github.com/gorilla/mux"
"github.com/ovh/cds/engine/api/application"
"github.com/ovh/cds/engine/api/ascode"
"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/keys"
"github.com/ovh/cds/engine/api/operation"
"github.com/ovh/cds/engine/api/permission"
"github.com/ovh/cds/engine/api/project"
"github.com/ovh/cds/engine/api/repositoriesmanager"
"github.com/ovh/cds/engine/api/user"
"github.com/ovh/cds/engine/api/workflow"
"github.com/ovh/cds/engine/cache"
"github.com/ovh/cds/engine/gorpmapper"
"github.com/ovh/cds/engine/service"
"github.com/ovh/cds/sdk"
"github.com/ovh/cds/sdk/exportentities"
)
func (api *API) getApplicationsHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
projectKey := vars[permProjectKey]
withUsage := service.FormBool(r, "withUsage")
withIcon := service.FormBool(r, "withIcon")
withPermissions := r.FormValue("permission")
loadOpts := []application.LoadOptionFunc{}
if withIcon {
loadOpts = append(loadOpts, application.LoadOptions.WithIcon)
}
requestedUserName := r.Header.Get("X-Cds-Username")
var requestedUser *sdk.AuthentifiedUser
if requestedUserName != "" && isMaintainer(ctx) {
var err error
requestedUser, err = user.LoadByUsername(ctx, api.mustDB(), requestedUserName)
if err != nil {
if sdk.Cause(err) == sql.ErrNoRows {
return sdk.WithStack(sdk.ErrUserNotFound)
}
return err
}
groups, err := group.LoadAllByUserID(context.TODO(), api.mustDB(), requestedUser.ID)
if err != nil {
return sdk.WrapError(err, "unable to load user '%s' groups", requestedUserName)
}
requestedUser.Groups = groups
projPerms, err := permission.LoadProjectMaxLevelPermission(ctx, api.mustDB(), []string{projectKey}, requestedUser.GetGroupIDs())
if err != nil {
return err
}
if projPerms.Level(projectKey) < sdk.PermissionRead {
return nil
}
}
applications, err := application.LoadAll(api.mustDB(), projectKey, loadOpts...)
if err != nil {
return sdk.WrapError(err, "Cannot load applications from db")
}
if strings.ToUpper(withPermissions) == "W" {
var groupIDs []int64
if requestedUser != nil {
groupIDs = requestedUser.GetGroupIDs()
} else {
groupIDs = getAPIConsumer(ctx).GetGroupIDs()
}
projectPerms, err := permission.LoadProjectMaxLevelPermission(ctx, api.mustDB(), []string{projectKey}, groupIDs)
if err != nil {
return err
}
res := make([]sdk.Application, 0, len(applications))
for _, a := range applications {
if projectPerms.Permissions(projectKey).Writable {
res = append(res, a)
}
}
applications = res
}
if withUsage {
for i := range applications {
usage, errU := loadApplicationUsage(ctx, api.mustDB(), projectKey, applications[i].Name)
if errU != nil {
return sdk.WrapError(errU, "getApplicationHandler> Cannot load application usage")
}
applications[i].Usage = &usage
}
}
return service.WriteJSON(w, applications, http.StatusOK)
}
}
func (api *API) getApplicationHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
projectKey := vars[permProjectKey]
applicationName := vars["applicationName"]
withKeys := service.FormBool(r, "withKeys")
withUsage := service.FormBool(r, "withUsage")
withIcon := service.FormBool(r, "withIcon")
withDeploymentStrategies := service.FormBool(r, "withDeploymentStrategies")
withVulnerabilities := service.FormBool(r, "withVulnerabilities")
loadOptions := []application.LoadOptionFunc{
application.LoadOptions.WithVariables,
}
if withKeys {
loadOptions = append(loadOptions, application.LoadOptions.WithKeys)
}
if withDeploymentStrategies {
loadOptions = append(loadOptions, application.LoadOptions.WithDeploymentStrategies)
}
if withVulnerabilities {
loadOptions = append(loadOptions, application.LoadOptions.WithVulnerabilities)
}
if withIcon {
loadOptions = append(loadOptions, application.LoadOptions.WithIcon)
}
app, errApp := application.LoadByName(api.mustDB(), projectKey, applicationName, loadOptions...)
if errApp != nil {
return sdk.WrapError(errApp, "getApplicationHandler: Cannot load application %s for project %s from db", applicationName, projectKey)
}
if withUsage {
usage, errU := loadApplicationUsage(ctx, api.mustDB(), projectKey, applicationName)
if errU != nil {
return sdk.WrapError(errU, "getApplicationHandler> Cannot load application usage")
}
app.Usage = &usage
}
if app.FromRepository != "" {
proj, err := project.Load(ctx, api.mustDB(), projectKey, project.LoadOptions.WithIntegrations)
if err != nil {
return err
}
wkAscodeHolder, err := workflow.LoadByRepo(ctx, api.mustDB(), *proj, app.FromRepository, workflow.LoadOptions{
WithTemplate: true,
})
if err != nil && !sdk.ErrorIs(err, sdk.ErrNotFound) {
return sdk.NewErrorFrom(err, "cannot found workflow holder of the application")
}
app.WorkflowAscodeHolder = wkAscodeHolder
// FIXME from_repository should never be set if the workflow holder was deleted
if app.WorkflowAscodeHolder == nil {
app.FromRepository = ""
}
}
return service.WriteJSON(w, app, http.StatusOK)
}
}
// loadApplicationUsage return usage of application
func loadApplicationUsage(ctx context.Context, db gorp.SqlExecutor, projKey, appName string) (sdk.Usage, error) {
usage := sdk.Usage{}
wf, errW := workflow.LoadByApplicationName(ctx, db, projKey, appName)
if errW != nil {
return usage, sdk.WrapError(errW, "loadApplicationUsage> Cannot load workflows linked to application %s in project %s", appName, projKey)
}
usage.Workflows = wf
return usage, nil
}
func (api *API) getApplicationVCSInfosHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
projectKey := vars[permProjectKey]
applicationName := vars["applicationName"]
remote := r.FormValue("remote")
tx, err := api.mustDB().Begin()
if err != nil {
return sdk.WithStack(err)
}
defer tx.Rollback() // nolint
app, err := application.LoadByName(tx, projectKey, applicationName, application.LoadOptions.Default)
if err != nil {
return sdk.WrapError(err, "Cannot load application %s for project %s from db", applicationName, projectKey)
}
resp := struct {
Branches []sdk.VCSBranch `json:"branches,omitempty"`
Remotes []sdk.VCSRepo `json:"remotes,omitempty"`
Tags []sdk.VCSTag `json:"tags,omitempty"`
}{}
if app.RepositoryFullname == "" || app.VCSServer == "" {
return service.WriteJSON(w, resp, http.StatusOK)
}
vcsServer, err := repositoriesmanager.LoadProjectVCSServerLinkByProjectKeyAndVCSServerName(ctx, tx, projectKey, app.VCSServer)
if err != nil {
return sdk.WrapError(sdk.ErrNoReposManagerClientAuth, "getApplicationVCSInfosHandler> Cannot get client got %s %s : %s", projectKey, app.VCSServer, err)
}
client, err := repositoriesmanager.AuthorizedClient(ctx, tx, api.Cache, projectKey, vcsServer)
if err != nil {
return sdk.WrapError(sdk.ErrNoReposManagerClientAuth, "getApplicationVCSInfosHandler> Cannot get client got %s %s : %s", projectKey, app.VCSServer, err)
}
if err := tx.Commit(); err != nil {
return sdk.WithStack(err)
}
repositoryFullname := app.RepositoryFullname
if remote != "" && remote != app.RepositoryFullname {
repositoryFullname = remote
}
branches, err := client.Branches(ctx, repositoryFullname, sdk.VCSBranchesFilter{Limit: 50})
if err != nil {
return err
}
resp.Branches = branches
tags, errt := client.Tags(ctx, repositoryFullname)
if errt != nil {
return sdk.WrapError(errt, "getApplicationVCSInfosHandler> Cannot get tags from repository %s", repositoryFullname)
}
resp.Tags = tags
remotes, errR := client.ListForks(ctx, repositoryFullname)
if errR != nil {
return sdk.WrapError(errR, "getApplicationVCSInfosHandler> Cannot get remotes from repository %s", repositoryFullname)
}
resp.Remotes = remotes
return service.WriteJSON(w, resp, http.StatusOK)
}
}
func (api *API) addApplicationHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
// Get project name in URL
vars := mux.Vars(r)
key := vars[permProjectKey]
proj, errl := project.Load(ctx, api.mustDB(), key)
if errl != nil {
return sdk.WrapError(errl, "addApplicationHandler> Cannot load %s", key)
}
var app sdk.Application
if err := service.UnmarshalBody(r, &app); err != nil {
return err
}
// check application name pattern
regexp := sdk.NamePatternRegex
if !regexp.MatchString(app.Name) {
return sdk.WrapError(sdk.ErrInvalidApplicationPattern, "addApplicationHandler: Application name %s do not respect pattern %s", app.Name, sdk.NamePattern)
}
tx, err := api.mustDB().Begin()
if err != nil {
return sdk.WrapError(err, "Cannot start transaction")
}
defer tx.Rollback() // nolint
if err := application.Insert(tx, *proj, &app); err != nil {
return sdk.WrapError(err, "Cannot insert pipeline")
}
if err := tx.Commit(); err != nil {
return sdk.WithStack(err)
}
event.PublishAddApplication(ctx, proj.Key, app, getAPIConsumer(ctx))
return service.WriteJSON(w, app, http.StatusOK)
}
}
func (api *API) deleteApplicationHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
// Get pipeline and action name in URL
vars := mux.Vars(r)
projectKey := vars[permProjectKey]
applicationName := vars["applicationName"]
proj, errP := project.Load(ctx, api.mustDB(), projectKey)
if errP != nil {
return sdk.WrapError(errP, "deleteApplicationHandler> Cannot laod project")
}
app, err := application.LoadByName(api.mustDB(), projectKey, applicationName)
if err != nil {
return err
}
tx, err := api.mustDB().Begin()
if err != nil {
return sdk.WrapError(err, "Cannot begin transaction")
}
defer tx.Rollback() // nolint
err = application.DeleteApplication(tx, app.ID)
if err != nil {
return sdk.WrapError(err, "Cannot delete application")
}
if err := tx.Commit(); err != nil {
return sdk.WithStack(err)
}
event.PublishDeleteApplication(ctx, proj.Key, *app, getAPIConsumer(ctx))
return nil
}
}
func (api *API) cloneApplicationHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
// Get pipeline and action name in URL
vars := mux.Vars(r)
projectKey := vars[permProjectKey]
applicationName := vars["applicationName"]
proj, errProj := project.Load(ctx, api.mustDB(), projectKey)
if errProj != nil {
return sdk.WrapError(sdk.ErrNoProject, "cloneApplicationHandler> Cannot load %s", projectKey)
}
envs, errE := environment.LoadEnvironments(api.mustDB(), projectKey)
if errE != nil {
return sdk.WrapError(errE, "cloneApplicationHandler> Cannot load Environments %s", projectKey)
}
proj.Environments = envs
var newApp sdk.Application
if err := service.UnmarshalBody(r, &newApp); err != nil {
return err
}
appToClone, errApp := application.LoadByName(api.mustDB(), projectKey, applicationName, application.LoadOptions.Default)
if errApp != nil {
return sdk.WrapError(errApp, "cloneApplicationHandler> Cannot load application %s", applicationName)
}
tx, errBegin := api.mustDB().Begin()
if errBegin != nil {
return sdk.WrapError(errBegin, "cloneApplicationHandler> Cannot start transaction")
}
defer tx.Rollback() // nolint
if err := cloneApplication(ctx, tx, api.Cache, *proj, &newApp, appToClone); err != nil {
return sdk.WrapError(err, "Cannot insert new application %s", newApp.Name)
}
if err := tx.Commit(); err != nil {
return sdk.WithStack(err)
}
return service.WriteJSON(w, newApp, http.StatusOK)
}
}
// cloneApplication Clone an application with all her dependencies: pipelines, permissions, triggers
func cloneApplication(ctx context.Context, db gorpmapper.SqlExecutorWithTx, store cache.Store, proj sdk.Project, newApp *sdk.Application, appToClone *sdk.Application) error {
// Create Application
if err := application.Insert(db, proj, newApp); err != nil {
return err
}
var variablesToDelete []string
for _, v := range newApp.Variables {
if v.Type == sdk.KeyVariable {
variablesToDelete = append(variablesToDelete, fmt.Sprintf("%s.pub", v.Name))
}
}
for _, vToDelete := range variablesToDelete {
for i := range newApp.Variables {
if vToDelete == newApp.Variables[i].Name {
newApp.Variables = append(newApp.Variables[:i], newApp.Variables[i+1:]...)
break
}
}
}
// Insert variables
for i := range newApp.Variables {
newVar := &newApp.Variables[i]
if !sdk.IsInArray(newVar.Type, sdk.AvailableVariableType) {
return sdk.WithStack(sdk.NewErrorFrom(sdk.ErrWrongRequest, "invalid variable type %s", newVar.Type))
}
if err := application.InsertVariable(db, newApp.ID, newVar, getAPIConsumer(ctx)); err != nil {
return sdk.WrapError(err, "cloneApplication> Cannot add variable %s in application %s", newVar.Name, newApp.Name)
}
}
event.PublishAddApplication(ctx, proj.Key, *newApp, getAPIConsumer(ctx))
return nil
}
func (api *API) updateAsCodeApplicationHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
key := vars[permProjectKey]
name := vars["applicationName"]
branch := FormString(r, "branch")
message := FormString(r, "message")
if branch == "" || message == "" {
return sdk.NewErrorFrom(sdk.ErrWrongRequest, "missing branch or message data")
}
var a sdk.Application
if err := service.UnmarshalBody(r, &a); err != nil {
return err
}
// check application name pattern
regexp := sdk.NamePatternRegex
if !regexp.MatchString(a.Name) {
return sdk.WrapError(sdk.ErrInvalidApplicationPattern, "Application name %s do not respect pattern", a.Name)
}
tx, err := api.mustDB().Begin()
if err != nil {
return sdk.WithStack(err)
}
defer tx.Rollback() // nolint
proj, err := project.Load(ctx, tx, key, project.LoadOptions.WithClearKeys)
if err != nil {
return err
}
appDB, err := application.LoadByName(tx, key, name)
if err != nil {
return sdk.WrapError(err, "cannot load application %s", name)
}
if appDB.FromRepository == "" {
return sdk.NewErrorFrom(sdk.ErrForbidden, "current application is not ascode")
}
if appDB.FromRepository != a.FromRepository {
return sdk.NewErrorFrom(sdk.ErrForbidden, "you can't use this repository to update your application: %s", a.FromRepository)
}
vcsServer, err := repositoriesmanager.LoadProjectVCSServerLinkByProjectKeyAndVCSServerName(ctx, tx, key, appDB.VCSServer)
if err != nil {
return sdk.WrapError(sdk.ErrNoReposManagerClientAuth, "updateAsCodeApplicationHandler> Cannot get client got %s %s : %v", key, appDB.VCSServer, err)
}
client, err := repositoriesmanager.AuthorizedClient(ctx, tx, api.Cache, key, vcsServer)
if err != nil {
return sdk.WrapError(sdk.ErrNoReposManagerClientAuth, "updateAsCodeApplicationHandler> Cannot get client got %s %s : %v", key, appDB.VCSServer, err)
}
b, err := client.Branch(ctx, appDB.RepositoryFullname, sdk.VCSBranchFilters{BranchName: branch})
if err != nil && !sdk.ErrorIs(err, sdk.ErrNotFound) {
return err
}
if b != nil && b.Default {
return sdk.NewErrorFrom(sdk.ErrForbidden, "cannot push the the default branch on your git repository")
}
wkHolder, err := workflow.LoadByRepo(ctx, tx, *proj, appDB.FromRepository, workflow.LoadOptions{
WithTemplate: true,
})
if err != nil {
return err
}
if wkHolder.TemplateInstance != nil {
return sdk.NewErrorFrom(sdk.ErrForbidden, "cannot edit an application that was generated by a template")
}
var rootApp *sdk.Application
if wkHolder.WorkflowData.Node.Context != nil && wkHolder.WorkflowData.Node.Context.ApplicationID != 0 {
rootApp, err = application.LoadByIDWithClearVCSStrategyPassword(tx, wkHolder.WorkflowData.Node.Context.ApplicationID)
if err != nil {
return err
}
}
if rootApp == nil {
return sdk.NewErrorFrom(sdk.ErrWrongRequest, "cannot find the root application of the workflow %s that hold the pipeline", wkHolder.Name)
}
// create keys
for i := range a.Keys {
k := &a.Keys[i]
newKey, err := keys.GenerateKey(k.Name, k.Type)
if err != nil {
return err
}
k.Public = newKey.Public
k.Private = newKey.Private
k.KeyID = newKey.KeyID
}
if a.RepositoryStrategy.ConnectionType == "https" && a.RepositoryStrategy.Password == sdk.PasswordPlaceholder {
a.RepositoryStrategy.Password = rootApp.RepositoryStrategy.Password
}
u := getAPIConsumer(ctx)
a.ProjectID = proj.ID
app, err := application.ExportApplication(ctx, tx, a, project.EncryptWithBuiltinKey, fmt.Sprintf("app:%d:%s", appDB.ID, branch))
if err != nil {
return sdk.WrapError(err, "unable to export app %s", a.Name)
}
wp := exportentities.WorkflowComponents{
Applications: []exportentities.Application{app},
}
ope, err := operation.PushOperationUpdate(ctx, tx, api.Cache, *proj, wp, rootApp.VCSServer, rootApp.RepositoryFullname, branch, message, a.RepositoryStrategy, u)
if err != nil {
return err
}
if err := tx.Commit(); err != nil {
return sdk.WithStack(err)
}
api.GoRoutines.Exec(context.Background(), fmt.Sprintf("UpdateAsCodeApplicationHandler-%s", ope.UUID), func(ctx context.Context) {
ed := ascode.EntityData{
FromRepo: appDB.FromRepository,
Type: ascode.ApplicationEvent,
ID: appDB.ID,
Name: appDB.Name,
OperationUUID: ope.UUID,
}
ascode.UpdateAsCodeResult(ctx, api.mustDB(), api.Cache, api.GoRoutines, *proj, *wkHolder, *rootApp, ed, u)
})
return service.WriteJSON(w, sdk.Operation{
UUID: ope.UUID,
Status: ope.Status,
}, http.StatusOK)
}
}
func (api *API) updateApplicationHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
projectKey := vars[permProjectKey]
applicationName := vars["applicationName"]
p, err := project.Load(ctx, api.mustDB(), projectKey, project.LoadOptions.Default)
if err != nil {
return sdk.WrapError(err, "cannot load project %s", projectKey)
}
app, err := application.LoadByNameWithClearVCSStrategyPassword(api.mustDB(), projectKey, applicationName, application.LoadOptions.Default)
if err != nil {
return sdk.WrapError(err, "cannot load application %s", applicationName)
}
if app.FromRepository != "" {
return sdk.WithStack(sdk.ErrForbidden)
}
var appPost sdk.Application
if err := service.UnmarshalBody(r, &appPost); err != nil {
return err
}
// check application name pattern
regexp := sdk.NamePatternRegex
if !regexp.MatchString(appPost.Name) {
return sdk.WrapError(sdk.ErrInvalidApplicationPattern, "updateApplicationHandler> Application name %s do not respect pattern %s", appPost.Name, sdk.NamePattern)
}
if appPost.RepositoryStrategy.Password == sdk.PasswordPlaceholder {
appPost.RepositoryStrategy.Password = app.RepositoryStrategy.Password
}
old := *app
//Update name and Metadata
app.Name = appPost.Name
app.Description = appPost.Description
if appPost.Icon != "" {
app.Icon = appPost.Icon
}
app.Metadata = appPost.Metadata
app.RepositoryStrategy = appPost.RepositoryStrategy
app.RepositoryStrategy.SSHKeyContent = ""
tx, err := api.mustDB().Begin()
if err != nil {
return sdk.WrapError(err, "Cannot start transaction")
}
defer tx.Rollback() // nolint
if err := application.Update(tx, app); err != nil {
return sdk.WrapError(err, "Cannot delete application %s", applicationName)
}
if err := tx.Commit(); err != nil {
return sdk.WithStack(err)
}
event.PublishUpdateApplication(ctx, p.Key, *app, old, getAPIConsumer(ctx))
return service.WriteJSON(w, app, http.StatusOK)
}
}
func (api *API) postApplicationMetadataHandler() service.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
// Get pipeline and action name in URL
vars := mux.Vars(r)
projectKey := vars[permProjectKey]
applicationName := vars["applicationName"]
app, err := application.LoadByName(api.mustDB(), projectKey, applicationName)
if err != nil {
return sdk.WrapError(err, "postApplicationMetadataHandler")
}
if app.FromRepository != "" {
return sdk.WithStack(sdk.ErrForbidden)
}
oldApp := *app
m := vars["metadata"]
v, err := io.ReadAll(r.Body)
if err != nil {
return sdk.WrapError(err, "postApplicationMetadataHandler")
}
defer r.Body.Close()
app.Metadata[m] = string(v)
tx, err := api.mustDB().Begin()
if err != nil {
return sdk.WrapError(err, "unable to start tx")
}
defer tx.Rollback() // nolint
if err := application.Update(tx, app); err != nil {
return sdk.WrapError(err, "unable to update application")
}
if err := tx.Commit(); err != nil {
return sdk.WrapError(err, "unable to commit tx")
}
event.PublishUpdateApplication(ctx, projectKey, *app, oldApp, getAPIConsumer(ctx))
return nil
}
}