-
Notifications
You must be signed in to change notification settings - Fork 523
/
Copy pathCoreAppRestHandler.go
2464 lines (2184 loc) · 95.4 KB
/
CoreAppRestHandler.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
/*
* Copyright (c) 2020-2024. Devtron Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package restHandler
import (
"context"
"encoding/json"
"errors"
"fmt"
app2 "github.com/devtron-labs/devtron/api/restHandler/app/pipeline/configure"
"github.com/devtron-labs/devtron/internal/sql/constants"
appWorkflowBean "github.com/devtron-labs/devtron/pkg/appWorkflow/bean"
read2 "github.com/devtron-labs/devtron/pkg/build/git/gitMaterial/read"
repository3 "github.com/devtron-labs/devtron/pkg/build/git/gitMaterial/repository"
"github.com/devtron-labs/devtron/pkg/build/git/gitProvider"
"github.com/devtron-labs/devtron/pkg/build/git/gitProvider/read"
pipelineBean "github.com/devtron-labs/devtron/pkg/build/pipeline/bean"
common2 "github.com/devtron-labs/devtron/pkg/build/pipeline/bean/common"
bean3 "github.com/devtron-labs/devtron/pkg/chart/bean"
read5 "github.com/devtron-labs/devtron/pkg/chart/read"
"github.com/devtron-labs/devtron/pkg/cluster/environment/repository"
read3 "github.com/devtron-labs/devtron/pkg/team/read"
"net/http"
"strconv"
"strings"
"time"
appBean "github.com/devtron-labs/devtron/api/appbean"
"github.com/devtron-labs/devtron/api/restHandler/common"
"github.com/devtron-labs/devtron/internal/sql/models"
appWorkflow2 "github.com/devtron-labs/devtron/internal/sql/repository/appWorkflow"
"github.com/devtron-labs/devtron/internal/sql/repository/chartConfig"
"github.com/devtron-labs/devtron/internal/sql/repository/pipelineConfig"
util2 "github.com/devtron-labs/devtron/internal/util"
"github.com/devtron-labs/devtron/pkg/app"
"github.com/devtron-labs/devtron/pkg/appWorkflow"
"github.com/devtron-labs/devtron/pkg/auth/authorisation/casbin"
"github.com/devtron-labs/devtron/pkg/auth/user"
"github.com/devtron-labs/devtron/pkg/bean"
"github.com/devtron-labs/devtron/pkg/chart"
chartRepoRepository "github.com/devtron-labs/devtron/pkg/chartRepo/repository"
"github.com/devtron-labs/devtron/pkg/pipeline"
bean2 "github.com/devtron-labs/devtron/pkg/pipeline/bean"
"github.com/devtron-labs/devtron/pkg/sql"
"github.com/devtron-labs/devtron/pkg/team"
"github.com/devtron-labs/devtron/util"
"github.com/devtron-labs/devtron/util/rbac"
"github.com/go-pg/pg"
"github.com/gorilla/mux"
"github.com/hashicorp/go-multierror"
"go.uber.org/zap"
"gopkg.in/go-playground/validator.v9"
"k8s.io/utils/strings/slices"
)
const (
APP_DELETE_FAILED_RESP = "App deletion failed, please try deleting from Devtron UI"
APP_CREATE_SUCCESSFUL_RESP = "App created successfully."
APP_WORKFLOW_CREATE_SUCCESSFUL_RESP = "App workflow created successfully."
)
type CoreAppRestHandler interface {
GetAppAllDetail(w http.ResponseWriter, r *http.Request)
CreateApp(w http.ResponseWriter, r *http.Request)
CreateAppWorkflow(w http.ResponseWriter, r *http.Request)
GetAppWorkflow(w http.ResponseWriter, r *http.Request)
GetAppWorkflowAndOverridesSample(w http.ResponseWriter, r *http.Request)
}
type CoreAppRestHandlerImpl struct {
logger *zap.SugaredLogger
userAuthService user.UserService
validator *validator.Validate
enforcerUtil rbac.EnforcerUtil
enforcer casbin.Enforcer
appCrudOperationService app.AppCrudOperationService
pipelineBuilder pipeline.PipelineBuilder
gitRegistryService gitProvider.GitRegistryConfig
gitProviderReadService read.GitProviderReadService
chartService chart.ChartService
configMapService pipeline.ConfigMapService
appListingService app.AppListingService
propertiesConfigService pipeline.PropertiesConfigService
appWorkflowService appWorkflow.AppWorkflowService
gitMaterialReadService read2.GitMaterialReadService
appWorkflowRepository appWorkflow2.AppWorkflowRepository
environmentRepository repository.EnvironmentRepository
configMapRepository chartConfig.ConfigMapRepository
chartRepo chartRepoRepository.ChartRepository
pipelineStageService pipeline.PipelineStageService
ciPipelineRepository pipelineConfig.CiPipelineRepository
teamReadService read3.TeamReadService
chartReadService read5.ChartReadService
}
func NewCoreAppRestHandlerImpl(logger *zap.SugaredLogger, userAuthService user.UserService, validator *validator.Validate, enforcerUtil rbac.EnforcerUtil,
enforcer casbin.Enforcer, appCrudOperationService app.AppCrudOperationService, pipelineBuilder pipeline.PipelineBuilder, gitRegistryService gitProvider.GitRegistryConfig,
chartService chart.ChartService, configMapService pipeline.ConfigMapService, appListingService app.AppListingService,
propertiesConfigService pipeline.PropertiesConfigService, appWorkflowService appWorkflow.AppWorkflowService,
appWorkflowRepository appWorkflow2.AppWorkflowRepository, environmentRepository repository.EnvironmentRepository, configMapRepository chartConfig.ConfigMapRepository,
chartRepo chartRepoRepository.ChartRepository, teamService team.TeamService,
pipelineStageService pipeline.PipelineStageService, ciPipelineRepository pipelineConfig.CiPipelineRepository,
gitProviderReadService read.GitProviderReadService,
gitMaterialReadService read2.GitMaterialReadService,
teamReadService read3.TeamReadService,
chartReadService read5.ChartReadService) *CoreAppRestHandlerImpl {
handler := &CoreAppRestHandlerImpl{
logger: logger,
userAuthService: userAuthService,
validator: validator,
enforcerUtil: enforcerUtil,
enforcer: enforcer,
appCrudOperationService: appCrudOperationService,
pipelineBuilder: pipelineBuilder,
gitRegistryService: gitRegistryService,
gitProviderReadService: gitProviderReadService,
chartService: chartService,
configMapService: configMapService,
appListingService: appListingService,
propertiesConfigService: propertiesConfigService,
appWorkflowService: appWorkflowService,
gitMaterialReadService: gitMaterialReadService,
appWorkflowRepository: appWorkflowRepository,
environmentRepository: environmentRepository,
configMapRepository: configMapRepository,
chartRepo: chartRepo,
pipelineStageService: pipelineStageService,
ciPipelineRepository: ciPipelineRepository,
teamReadService: teamReadService,
chartReadService: chartReadService,
}
return handler
}
func (handler CoreAppRestHandlerImpl) GetAppAllDetail(w http.ResponseWriter, r *http.Request) {
userId, err := handler.userAuthService.GetLoggedInUser(r)
if userId == 0 || err != nil {
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
vars := mux.Vars(r)
appId, err := strconv.Atoi(vars["appId"])
if err != nil {
handler.logger.Errorw("request err, GetAppAllDetail", "err", err, "appId", appId)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
//rbac implementation for app (user should be admin)
token := r.Header.Get("token")
object := handler.enforcerUtil.GetAppRBACNameByAppId(appId)
if ok := handler.enforcer.Enforce(token, casbin.ResourceApplications, casbin.ActionUpdate, object); !ok {
handler.logger.Errorw("Unauthorized User for app update action", "err", err, "appId", appId)
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusForbidden)
return
}
//rbac implementation ends here for app
handler.logger.Debugw("Getting app detail v2", "appId", appId)
//get/build app metadata starts
appMetadataResp, err, statusCode := handler.buildAppMetadata(appId)
if err != nil {
common.WriteJsonResp(w, err, nil, statusCode)
return
}
//get/build app metadata ends
//get/build git materials starts
gitMaterialsResp, err, statusCode := handler.buildAppGitMaterials(appId)
if err != nil {
common.WriteJsonResp(w, err, nil, statusCode)
return
}
//get/build git materials ends
//get/build docker config starts
dockerConfig, err, statusCode := handler.buildDockerConfig(appId)
if err != nil {
common.WriteJsonResp(w, err, nil, statusCode)
return
}
//get/build docker config ends
//get/build global deployment template starts
globalDeploymentTemplateResp, err, statusCode := handler.buildAppDeploymentTemplate(appId)
if err != nil {
common.WriteJsonResp(w, err, nil, statusCode)
return
}
//get/build global deployment template ends
//get/build app workflows starts
//using empty workflow name because it is optional, if not provided then workflows will be fetched on the basis of app
wfCloneRequest := &appWorkflowBean.WorkflowCloneRequest{AppId: appId}
appWorkflows, err, statusCode := handler.buildAppWorkflows(wfCloneRequest)
if err != nil {
common.WriteJsonResp(w, err, nil, statusCode)
return
}
//get/build app workflows ends
//get/build global config maps starts
globalConfigMapsResp, err, statusCode := handler.buildAppGlobalConfigMaps(appId)
if err != nil {
common.WriteJsonResp(w, err, nil, statusCode)
return
}
//get/build global config maps ends
//get/build global secrets starts
globalSecretsResp, err, statusCode := handler.buildAppGlobalSecrets(appId)
if err != nil {
common.WriteJsonResp(w, err, nil, statusCode)
return
}
//get/build global secrets ends
//get/build environment override starts
environmentOverrides, err, statusCode := handler.buildEnvironmentOverrides(r.Context(), appId, token)
if err != nil {
common.WriteJsonResp(w, err, nil, statusCode)
return
}
//get/build environment override ends
//build full object for response
appDetail := &appBean.AppDetail{
Metadata: appMetadataResp,
GitMaterials: gitMaterialsResp,
DockerConfig: dockerConfig,
GlobalDeploymentTemplate: globalDeploymentTemplateResp,
AppWorkflows: appWorkflows,
GlobalConfigMaps: globalConfigMapsResp,
GlobalSecrets: globalSecretsResp,
EnvironmentOverrides: environmentOverrides,
}
//end
common.WriteJsonResp(w, nil, appDetail, http.StatusOK)
}
func (handler CoreAppRestHandlerImpl) CreateApp(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
userId, err := handler.userAuthService.GetLoggedInUser(r)
if userId == 0 || err != nil {
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
token := r.Header.Get("token")
ctx := r.Context()
var createAppRequest appBean.AppDetail
err = decoder.Decode(&createAppRequest)
if err != nil {
handler.logger.Errorw("request err, CreateApp by API", "err", err, "CreateApp", createAppRequest)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
//to add more validations here
handler.logger.Infow("request payload, CreateApp by API", "CreateApp", createAppRequest)
err = handler.validator.Struct(createAppRequest)
if err != nil {
handler.logger.Errorw("validation err, CreateApp by API", "err", err, "CreateApp", createAppRequest)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
//rbac starts
team, err := handler.teamReadService.FindByTeamName(createAppRequest.Metadata.ProjectName)
if err != nil {
handler.logger.Errorw("Error in getting team", "err", err)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
if team == nil {
handler.logger.Errorw("no project found by name in CreateApp request by API")
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
// with admin roles, you have to access for all the apps of the project to create new app. (admin or manager with specific app permission can't create app.)
if ok := handler.enforcer.Enforce(token, casbin.ResourceApplications, casbin.ActionCreate, fmt.Sprintf("%s/%s", team.Name, "*")); !ok {
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusForbidden)
return
}
//rbac ends
handler.logger.Infow("creating app v2", "createAppRequest", createAppRequest)
// validate payload starts
createAppWorkflowReq := appBean.AppWorkflowCloneDto{
AppName: createAppRequest.Metadata.AppName,
AppWorkflows: createAppRequest.AppWorkflows,
EnvironmentOverrides: createAppRequest.EnvironmentOverrides,
}
err, statusCode := handler.ValidateAppWorkflowRequest(&createAppWorkflowReq, token)
if err != nil {
common.WriteJsonResp(w, err, nil, statusCode)
return
}
// validate payload ends
//creating blank app starts
createBlankAppResp, err, statusCode := handler.createBlankApp(createAppRequest.Metadata, userId)
if err != nil {
common.WriteJsonResp(w, err, nil, statusCode)
return
}
//creating blank app ends
//declaring appId for creating other components of app
appId := createBlankAppResp.Id
var errResp *multierror.Error
//creating git material starts
if createAppRequest.GitMaterials != nil {
err, statusCode = handler.createGitMaterials(appId, createAppRequest.GitMaterials, userId)
if err != nil {
errResp = multierror.Append(errResp, err)
errInAppDelete := handler.deleteApp(ctx, appId, userId)
if errInAppDelete != nil {
errResp = multierror.Append(errResp, fmt.Errorf("%s : %w", APP_DELETE_FAILED_RESP, errInAppDelete))
}
common.WriteJsonResp(w, errResp, nil, statusCode)
return
}
}
//creating git material ends
//creating docker config
if createAppRequest.DockerConfig != nil {
err, statusCode = handler.createDockerConfig(appId, createAppRequest.DockerConfig, userId)
if err != nil {
errResp = multierror.Append(errResp, err)
errInAppDelete := handler.deleteApp(ctx, appId, userId)
if errInAppDelete != nil {
errResp = multierror.Append(errResp, fmt.Errorf("%s : %w", APP_DELETE_FAILED_RESP, errInAppDelete))
}
common.WriteJsonResp(w, errResp, nil, statusCode)
return
}
}
//creating docker config ends
//creating deployment template starts
if createAppRequest.GlobalDeploymentTemplate != nil {
err, statusCode = handler.createDeploymentTemplate(ctx, appId, createAppRequest.GlobalDeploymentTemplate, userId)
if err != nil {
errResp = multierror.Append(errResp, err)
errInAppDelete := handler.deleteApp(ctx, appId, userId)
if errInAppDelete != nil {
errResp = multierror.Append(errResp, fmt.Errorf("%s : %w", APP_DELETE_FAILED_RESP, errInAppDelete))
}
common.WriteJsonResp(w, errResp, nil, statusCode)
return
}
}
//creating deployment template ends
//creating global configMaps starts
if createAppRequest.GlobalConfigMaps != nil {
err, statusCode = handler.createGlobalConfigMaps(appId, userId, createAppRequest.GlobalConfigMaps)
if err != nil {
errResp = multierror.Append(errResp, err)
errInAppDelete := handler.deleteApp(ctx, appId, userId)
if errInAppDelete != nil {
errResp = multierror.Append(errResp, fmt.Errorf("%s : %w", APP_DELETE_FAILED_RESP, errInAppDelete))
}
common.WriteJsonResp(w, errResp, nil, statusCode)
return
}
}
//creating global configMaps ends
//creating global secrets starts
if createAppRequest.GlobalSecrets != nil {
err, statusCode = handler.createGlobalSecrets(appId, userId, createAppRequest.GlobalSecrets)
if err != nil {
errResp = multierror.Append(errResp, err)
errInAppDelete := handler.deleteApp(ctx, appId, userId)
if errInAppDelete != nil {
errResp = multierror.Append(errResp, fmt.Errorf("%s : %w", APP_DELETE_FAILED_RESP, errInAppDelete))
}
common.WriteJsonResp(w, errResp, nil, statusCode)
return
}
}
//creating global secrets ends
//creating workflow starts
if createAppRequest.AppWorkflows != nil {
err, statusCode = handler.createWorkflows(ctx, appId, userId, createAppRequest.AppWorkflows)
if err != nil {
errResp = multierror.Append(errResp, err)
errInAppDelete := handler.deleteApp(ctx, appId, userId)
if errInAppDelete != nil {
errResp = multierror.Append(errResp, fmt.Errorf("%s : %w", APP_DELETE_FAILED_RESP, errInAppDelete))
}
common.WriteJsonResp(w, errResp, nil, statusCode)
return
}
}
//creating workflow ends
//creating environment override starts
if createAppRequest.EnvironmentOverrides != nil {
err, statusCode = handler.createEnvOverrides(ctx, appId, userId, createAppRequest.EnvironmentOverrides)
if err != nil {
errResp = multierror.Append(errResp, err)
errInAppDelete := handler.deleteApp(ctx, appId, userId)
if errInAppDelete != nil {
errResp = multierror.Append(errResp, fmt.Errorf("%s : %w", APP_DELETE_FAILED_RESP, errInAppDelete))
}
common.WriteJsonResp(w, errResp, nil, statusCode)
return
}
}
//creating environment override ends
common.WriteJsonResp(w, nil, APP_CREATE_SUCCESSFUL_RESP, http.StatusOK)
}
//GetApp related methods starts
// get/build app metadata
func (handler CoreAppRestHandlerImpl) buildAppMetadata(appId int) (*appBean.AppMetadata, error, int) {
handler.logger.Debugw("Getting app detail - meta data", "appId", appId)
appMetaInfo, err := handler.appCrudOperationService.GetAppMetaInfo(appId, app.ZERO_INSTALLED_APP_ID, app.ZERO_ENVIRONMENT_ID)
if err != nil {
handler.logger.Errorw("service err, GetAppMetaInfo in GetAppAllDetail", "err", err, "appId", appId)
return nil, err, http.StatusInternalServerError
}
if appMetaInfo == nil {
err = errors.New("invalid appId - appMetaInfo is null")
handler.logger.Errorw("Validation error ", "err", err, "appId", appId)
return nil, err, http.StatusBadRequest
}
var appLabelsRes []*appBean.AppLabel
if len(appMetaInfo.Labels) > 0 {
for _, label := range appMetaInfo.Labels {
appLabelsRes = append(appLabelsRes, &appBean.AppLabel{
Key: label.Key,
Value: label.Value,
Propagate: label.Propagate,
})
}
}
appMetadataResp := &appBean.AppMetadata{
AppName: appMetaInfo.AppName,
ProjectName: appMetaInfo.ProjectName,
Labels: appLabelsRes,
}
return appMetadataResp, nil, http.StatusOK
}
// get/build git materials
func (handler CoreAppRestHandlerImpl) buildAppGitMaterials(appId int) ([]*appBean.GitMaterial, error, int) {
handler.logger.Debugw("Getting app detail - git materials", "appId", appId)
gitMaterials := handler.pipelineBuilder.GetMaterialsForAppId(appId)
var gitMaterialsResp []*appBean.GitMaterial
if len(gitMaterials) > 0 {
for _, gitMaterial := range gitMaterials {
gitRegistry, err := handler.gitProviderReadService.FetchOneGitProvider(strconv.Itoa(gitMaterial.GitProviderId))
if err != nil {
handler.logger.Errorw("service err, getGitProvider in GetAppAllDetail", "err", err, "appId", appId)
return nil, err, http.StatusInternalServerError
}
gitMaterialsResp = append(gitMaterialsResp, &appBean.GitMaterial{
GitRepoUrl: gitMaterial.Url,
CheckoutPath: gitMaterial.CheckoutPath,
FetchSubmodules: gitMaterial.FetchSubmodules,
GitProviderUrl: gitRegistry.Url,
})
}
}
return gitMaterialsResp, nil, http.StatusOK
}
// get/build docker build config
func (handler CoreAppRestHandlerImpl) buildDockerConfig(appId int) (*appBean.DockerConfig, error, int) {
handler.logger.Debugw("Getting app detail - docker build", "appId", appId)
ciConfig, err := handler.pipelineBuilder.GetCiPipeline(appId)
if errResponse, ok := err.(*util2.ApiError); ok && errResponse.UserMessage == "no ci pipeline exists" {
handler.logger.Warnw("docker config not available for app, GetCiPipeline in GetAppAllDetail", "err", err, "appId", appId)
return nil, nil, http.StatusOK
}
if err != nil {
handler.logger.Errorw("service err, GetCiPipeline in GetAppAllDetail", "err", err, "appId", appId)
return nil, err, http.StatusInternalServerError
}
//getting gitMaterialUrl by id
gitMaterial, err := handler.gitMaterialReadService.FindById(ciConfig.CiBuildConfig.GitMaterialId)
if err != nil {
handler.logger.Errorw("error in fetching materialUrl by ID in GetAppAllDetail", "err", err, "gitMaterialId", ciConfig.CiBuildConfig.GitMaterialId)
return nil, err, http.StatusInternalServerError
}
dockerConfig := &appBean.DockerConfig{
DockerRegistry: ciConfig.DockerRegistry,
DockerRepository: ciConfig.DockerRepository,
CiBuildConfig: ciConfig.CiBuildConfig,
CheckoutPath: gitMaterial.CheckoutPath,
}
return dockerConfig, nil, http.StatusOK
}
// get/build global deployment template
func (handler CoreAppRestHandlerImpl) buildAppDeploymentTemplate(appId int) (*appBean.DeploymentTemplate, error, int) {
handler.logger.Debugw("Getting app detail - deployment template", "appId", appId)
//for global template, to bypass env overrides using envId = 0
return handler.buildAppEnvironmentDeploymentTemplate(appId, 0)
}
// get/build environment deployment template
// using this method for global as well, for global pass envId = 0
func (handler CoreAppRestHandlerImpl) buildAppEnvironmentDeploymentTemplate(appId int, envId int) (*appBean.DeploymentTemplate, error, int) {
handler.logger.Debugw("Getting app detail - environment deployment template", "appId", appId, "envId", envId)
chartRefData, err := handler.chartService.ChartRefAutocompleteForAppOrEnv(appId, envId)
if err != nil {
handler.logger.Errorw("service err, ChartRefAutocompleteForAppOrEnv in GetAppAllDetail", "err", err, "appId", appId, "envId", envId)
return nil, err, http.StatusInternalServerError
}
if chartRefData == nil {
err = errors.New("invalid appId/envId - chartRefData is null")
handler.logger.Errorw("Validation error ", "err", err, "appId", appId, "envId", envId)
return nil, err, http.StatusBadRequest
}
appDeploymentTemplate, err := handler.chartReadService.FindLatestChartForAppByAppId(appId)
if err != nil {
if err != pg.ErrNoRows {
handler.logger.Errorw("service err, GetDeploymentTemplate in GetAppAllDetail", "err", err, "appId", appId, "envId", envId)
return nil, err, http.StatusInternalServerError
} else {
handler.logger.Warnw("no charts configured for app, GetDeploymentTemplate in GetAppAllDetail", "err", err, "appId", appId, "envId", envId)
return nil, nil, http.StatusOK
}
}
if appDeploymentTemplate == nil {
err = errors.New("invalid appId - deploymentTemplate is null")
handler.logger.Errorw("Validation error ", "err", err, "appId", appId, "envId", envId)
return nil, err, http.StatusBadRequest
}
//set deployment template & showAppMetrics && isOverride
var showAppMetrics bool
var deploymentTemplateRaw json.RawMessage
var chartRefId int
var isOverride bool
var isBasicViewLocked bool
var currentViewEditor models.ChartsViewEditorType
if envId > 0 {
//on env level
env, err := handler.propertiesConfigService.GetEnvironmentProperties(appId, envId, chartRefData.LatestEnvChartRef)
if err != nil {
handler.logger.Errorw("service err, GetEnvironmentProperties in GetAppAllDetail", "err", err, "appId", appId, "envId", envId)
return nil, err, http.StatusInternalServerError
}
chartRefId = chartRefData.LatestEnvChartRef
if env.EnvironmentConfig.IsOverride {
deploymentTemplateRaw = env.EnvironmentConfig.EnvOverrideValues
showAppMetrics = *env.AppMetrics
isOverride = true
isBasicViewLocked = env.EnvironmentConfig.IsBasicViewLocked
currentViewEditor = env.EnvironmentConfig.CurrentViewEditor
} else {
showAppMetrics = appDeploymentTemplate.IsAppMetricsEnabled
deploymentTemplateRaw = appDeploymentTemplate.DefaultAppOverride
isBasicViewLocked = appDeploymentTemplate.IsBasicViewLocked
currentViewEditor = appDeploymentTemplate.CurrentViewEditor
}
} else {
//on app level
showAppMetrics = appDeploymentTemplate.IsAppMetricsEnabled
deploymentTemplateRaw = appDeploymentTemplate.DefaultAppOverride
chartRefId = chartRefData.LatestAppChartRef
isBasicViewLocked = appDeploymentTemplate.IsBasicViewLocked
currentViewEditor = appDeploymentTemplate.CurrentViewEditor
}
var deploymentTemplateObj map[string]interface{}
if deploymentTemplateRaw != nil {
err = json.Unmarshal([]byte(deploymentTemplateRaw), &deploymentTemplateObj)
if err != nil {
handler.logger.Errorw("service err, un-marshaling fail in deploymentTemplate", "err", err, "appId", appId)
return nil, err, http.StatusInternalServerError
}
}
deploymentTemplateResp := &appBean.DeploymentTemplate{
ChartRefId: chartRefId,
Template: deploymentTemplateObj,
ShowAppMetrics: showAppMetrics,
IsOverride: isOverride,
IsBasicViewLocked: isBasicViewLocked,
CurrentViewEditor: currentViewEditor,
}
return deploymentTemplateResp, nil, http.StatusOK
}
// validate and build workflows
func (handler CoreAppRestHandlerImpl) buildAppWorkflows(request *appWorkflowBean.WorkflowCloneRequest) ([]*appBean.AppWorkflow, error, int) {
handler.logger.Debugw("Getting app detail - workflows", "appId", request.AppId)
var workflowsList []appWorkflowBean.AppWorkflowDto
var err error
if len(request.WorkflowName) != 0 {
workflow, err := handler.appWorkflowService.FindAppWorkflowByName(request.WorkflowName, request.AppId)
if err != nil {
handler.logger.Errorw("error in fetching workflow by name", "err", err, "workflowName", request.WorkflowName, "appId", request.AppId)
return nil, err, http.StatusInternalServerError
}
workflowsList = []appWorkflowBean.AppWorkflowDto{workflow}
} else if request.WorkflowId > 0 {
workflow, err := handler.appWorkflowService.FindAppWorkflowById(request.WorkflowId, request.AppId)
if err != nil {
handler.logger.Errorw("error in fetching workflow by id", "err", err, "workflowName", request.WorkflowName, "appId", request.AppId)
return nil, err, http.StatusInternalServerError
}
workflowsList = []appWorkflowBean.AppWorkflowDto{workflow}
} else {
workflowsList, err = handler.appWorkflowService.FindAppWorkflows(request.AppId)
if err != nil {
handler.logger.Errorw("error in fetching workflows for app in GetAppAllDetail", "err", err)
return nil, err, http.StatusInternalServerError
}
}
var appWorkflowsResp []*appBean.AppWorkflow
for _, workflow := range workflowsList {
workflowResp := &appBean.AppWorkflow{
Name: workflow.Name,
}
var cdPipelinesResp []*appBean.CdPipelineDetails
for _, workflowMapping := range workflow.AppWorkflowMappingDto {
if workflowMapping.Type == appWorkflow2.CIPIPELINE {
ciPipeline, err := handler.pipelineBuilder.GetCiPipelineById(workflowMapping.ComponentId)
if err != nil {
handler.logger.Errorw("service err, GetCiPipelineById in GetAppAllDetail", "err", err, "appId", request.AppId)
return nil, err, http.StatusInternalServerError
}
ciPipelineResp, err := handler.buildCiPipelineResp(request.AppId, ciPipeline)
if err != nil {
handler.logger.Errorw("service err, buildCiPipelineResp in GetAppAllDetail", "err", err, "appId", request.AppId)
return nil, err, http.StatusInternalServerError
}
workflowResp.CiPipeline = ciPipelineResp
}
if workflowMapping.Type == appWorkflow2.CDPIPELINE {
cdPipeline, err := handler.pipelineBuilder.GetCdPipelineById(workflowMapping.ComponentId)
if err != nil {
handler.logger.Errorw("service err, GetCdPipelineById in GetAppAllDetail", "err", err, "appId", request.AppId)
return nil, err, http.StatusInternalServerError
}
if request.EnvironmentId > 0 && request.EnvironmentId != cdPipeline.EnvironmentId {
// if environment id present in request it should match cd pipeline, else skip
continue
}
cdPipelineResp, err := handler.buildCdPipelineResp(request.AppId, cdPipeline)
if err != nil {
handler.logger.Errorw("service err, buildCdPipelineResp in GetAppAllDetail", "err", err, "appId", request.AppId)
return nil, err, http.StatusInternalServerError
}
cdPipelinesResp = append(cdPipelinesResp, cdPipelineResp)
}
}
workflowResp.CdPipelines = cdPipelinesResp
appWorkflowsResp = append(appWorkflowsResp, workflowResp)
}
return appWorkflowsResp, nil, http.StatusOK
}
// build ci pipeline resp
func (handler CoreAppRestHandlerImpl) buildCiPipelineResp(appId int, ciPipeline *bean.CiPipeline) (*appBean.CiPipelineDetails, error) {
handler.logger.Debugw("Getting app detail - build ci pipeline resp", "appId", appId)
if ciPipeline == nil {
return nil, nil
}
ciPipelineResp := &appBean.CiPipelineDetails{
Name: ciPipeline.Name,
IsManual: ciPipeline.IsManual,
DockerBuildArgs: ciPipeline.DockerArgs,
VulnerabilityScanEnabled: ciPipeline.ScanEnabled,
IsExternal: ciPipeline.IsExternal,
ParentCiPipeline: ciPipeline.ParentCiPipeline,
ParentAppId: ciPipeline.ParentAppId,
LinkedCount: ciPipeline.LinkedCount,
PipelineType: string(ciPipeline.PipelineType),
}
//build ciPipelineMaterial resp
var ciPipelineMaterialsConfig []*appBean.CiPipelineMaterialConfig
for _, ciMaterial := range ciPipeline.CiMaterial {
gitMaterial, err := handler.gitMaterialReadService.FindById(ciMaterial.GitMaterialId)
if err != nil {
handler.logger.Errorw("service err, GitMaterialById in GetAppAllDetail", "err", err, "appId", appId)
return nil, err
}
ciPipelineMaterialConfig := &appBean.CiPipelineMaterialConfig{
Type: ciMaterial.Source.Type,
Value: ciMaterial.Source.Value,
CheckoutPath: gitMaterial.CheckoutPath,
GitMaterialId: gitMaterial.Id,
}
ciPipelineMaterialsConfig = append(ciPipelineMaterialsConfig, ciPipelineMaterialConfig)
}
ciPipelineResp.CiPipelineMaterialsConfig = ciPipelineMaterialsConfig
//build docker pre-build script
var beforeDockerBuildScriptsResp []*appBean.BuildScript
for _, beforeDockerBuildScript := range ciPipeline.BeforeDockerBuildScripts {
beforeDockerBuildScriptResp := &appBean.BuildScript{
Name: beforeDockerBuildScript.Name,
Index: beforeDockerBuildScript.Index,
Script: beforeDockerBuildScript.Script,
ReportDirectoryPath: beforeDockerBuildScript.OutputLocation,
}
beforeDockerBuildScriptsResp = append(beforeDockerBuildScriptsResp, beforeDockerBuildScriptResp)
}
ciPipelineResp.BeforeDockerBuildScripts = beforeDockerBuildScriptsResp
//build docker post build script
var afterDockerBuildScriptsResp []*appBean.BuildScript
for _, afterDockerBuildScript := range ciPipeline.AfterDockerBuildScripts {
afterDockerBuildScriptResp := &appBean.BuildScript{
Name: afterDockerBuildScript.Name,
Index: afterDockerBuildScript.Index,
Script: afterDockerBuildScript.Script,
ReportDirectoryPath: afterDockerBuildScript.OutputLocation,
}
afterDockerBuildScriptsResp = append(afterDockerBuildScriptsResp, afterDockerBuildScriptResp)
}
ciPipelineResp.AfterDockerBuildScripts = afterDockerBuildScriptsResp
//getting pre stage and post stage details
preStageDetail, postStageDetail, err := handler.pipelineStageService.GetCiPipelineStageDataDeepCopy(ciPipeline.Id)
if err != nil {
handler.logger.Errorw("error in getting pre & post stage detail by ciPipelineId", "err", err, "ciPipelineId", ciPipeline.Id)
return nil, err
}
ciPipelineResp.PreBuildStage = preStageDetail
ciPipelineResp.PostBuildStage = postStageDetail
return ciPipelineResp, nil
}
// build cd pipeline resp
func (handler CoreAppRestHandlerImpl) buildCdPipelineResp(appId int, cdPipeline *bean.CDPipelineConfigObject) (*appBean.CdPipelineDetails, error) {
handler.logger.Debugw("Getting app detail - build cd pipeline resp", "appId", appId)
if cdPipeline == nil {
return nil, nil
}
cdPipelineResp := &appBean.CdPipelineDetails{
Name: cdPipeline.Name,
EnvironmentName: cdPipeline.EnvironmentName,
TriggerType: cdPipeline.TriggerType,
DeploymentStrategyType: cdPipeline.DeploymentTemplate,
RunPreStageInEnv: cdPipeline.RunPreStageInEnv,
RunPostStageInEnv: cdPipeline.RunPostStageInEnv,
IsClusterCdActive: cdPipeline.CdArgoSetup,
}
//build DeploymentStrategies resp
var deploymentTemplateStrategiesResp []*appBean.DeploymentStrategy
for _, strategy := range cdPipeline.Strategies {
deploymentTemplateStrategyResp := &appBean.DeploymentStrategy{
DeploymentStrategyType: strategy.DeploymentTemplate,
IsDefault: strategy.Default,
}
var configObj map[string]interface{}
if strategy.Config != nil {
err := json.Unmarshal([]byte(strategy.Config), &configObj)
if err != nil {
handler.logger.Errorw("service err, un-marshaling fail in config object in cd", "err", err, "appId", appId)
return nil, err
}
}
deploymentTemplateStrategyResp.Config = configObj
deploymentTemplateStrategiesResp = append(deploymentTemplateStrategiesResp, deploymentTemplateStrategyResp)
}
cdPipelineResp.DeploymentStrategies = deploymentTemplateStrategiesResp
//set pre-deploy and post-deploy stage steps for multi step execution
cdPipelineMigrated, err := pipeline.ConvertStageYamlScriptsToPipelineStageSteps(cdPipeline)
if err != nil {
handler.logger.Errorw("service err, InitiateMigrationOfStageScriptsToPipelineStageSteps", "err", err, "appId", appId, "pipelineId", cdPipeline.Id)
return nil, err
}
cdPipelineResp.PreDeployStage = cdPipelineMigrated.PreDeployStage
cdPipelineResp.PostDeployStage = cdPipelineMigrated.PostDeployStage
//set pre stage config maps secret names
preStageConfigMapSecretNames := cdPipeline.PreStageConfigMapSecretNames
cdPipelineResp.PreStageConfigMapSecretNames = &appBean.CdStageConfigMapSecretNames{
ConfigMaps: preStageConfigMapSecretNames.ConfigMaps,
Secrets: preStageConfigMapSecretNames.Secrets,
}
//set post stage config maps secret names
postStageConfigMapSecretNames := cdPipeline.PostStageConfigMapSecretNames
cdPipelineResp.PostStageConfigMapSecretNames = &appBean.CdStageConfigMapSecretNames{
ConfigMaps: postStageConfigMapSecretNames.ConfigMaps,
Secrets: postStageConfigMapSecretNames.Secrets,
}
return cdPipelineResp, nil
}
// get/build global config maps
func (handler CoreAppRestHandlerImpl) buildAppGlobalConfigMaps(appId int) ([]*appBean.ConfigMap, error, int) {
handler.logger.Debugw("Getting app detail - global config maps", "appId", appId)
configMapData, err := handler.configMapService.CMGlobalFetch(appId)
if err != nil {
handler.logger.Errorw("service err, CMGlobalFetch in GetAppAllDetail", "err", err, "appId", appId)
return nil, err, http.StatusInternalServerError
}
return handler.buildAppConfigMaps(appId, 0, configMapData)
}
// get/build environment config maps
func (handler CoreAppRestHandlerImpl) buildAppEnvironmentConfigMaps(appId int, envId int) ([]*appBean.ConfigMap, error, int) {
handler.logger.Debugw("Getting app detail - environment config maps", "appId", appId, "envId", envId)
configMapData, err := handler.configMapService.CMEnvironmentFetch(appId, envId)
if err != nil {
handler.logger.Errorw("service err, CMEnvironmentFetch in GetAppAllDetail", "err", err, "appId", appId, "envId", envId)
return nil, err, http.StatusInternalServerError
}
return handler.buildAppConfigMaps(appId, envId, configMapData)
}
// get/build config maps
func (handler CoreAppRestHandlerImpl) buildAppConfigMaps(appId int, envId int, configMapData *bean2.ConfigDataRequest) ([]*appBean.ConfigMap, error, int) {
handler.logger.Debugw("Getting app detail - config maps", "appId", appId, "envId", envId)
var configMapsResp []*appBean.ConfigMap
if configMapData != nil && len(configMapData.ConfigData) > 0 {
for _, configMap := range configMapData.ConfigData {
//initialise
configMapRes := &appBean.ConfigMap{
Name: configMap.Name,
IsExternal: configMap.External,
UsageType: configMap.Type,
}
//set data
data := configMap.Data
if configMap.Data == nil {
//it means env cm is inheriting from base cm
data = configMap.DefaultData
}
var dataObj map[string]interface{}
if data != nil {
err := json.Unmarshal(data, &dataObj)
if err != nil {
handler.logger.Errorw("service err, un-marshaling of data fail in config map", "err", err, "appId", appId)
return nil, err, http.StatusInternalServerError
}
}
configMapRes.Data = dataObj
//set data volume usage type
if configMap.Type == util.ConfigMapSecretUsageTypeVolume {
dataVolumeUsageConfig := &appBean.ConfigMapSecretDataVolumeUsageConfig{
FilePermission: configMap.FilePermission,
SubPath: configMap.SubPath,
}
considerGlobalDefaultData := envId > 0 && configMap.Data == nil
if considerGlobalDefaultData {
dataVolumeUsageConfig.MountPath = configMap.DefaultMountPath
} else {
dataVolumeUsageConfig.MountPath = configMap.MountPath
}
configMapRes.DataVolumeUsageConfig = dataVolumeUsageConfig
}
configMapsResp = append(configMapsResp, configMapRes)
}
}
return configMapsResp, nil, http.StatusOK
}
// get/build global secrets
func (handler CoreAppRestHandlerImpl) buildAppGlobalSecrets(appId int) ([]*appBean.Secret, error, int) {
handler.logger.Debugw("Getting app detail - global secret", "appId", appId)
secretData, err := handler.configMapService.CSGlobalFetch(appId)
if err != nil {
handler.logger.Errorw("service err, CSGlobalFetch in GetAppAllDetail", "err", err, "appId", appId)
return nil, err, http.StatusInternalServerError
}
var secretsResp []*appBean.Secret
if secretData != nil && len(secretData.ConfigData) > 0 {
for _, secretConfig := range secretData.ConfigData {
secretDataWithData, err := handler.configMapService.CSGlobalFetchForEdit(secretConfig.Name, secretData.Id)
if err != nil {
handler.logger.Errorw("service err, CSGlobalFetch-CSGlobalFetchForEdit in GetAppAllDetail", "err", err, "appId", appId)
return nil, err, http.StatusInternalServerError
}
secretRes, err, statusCode := handler.buildAppSecrets(appId, 0, secretDataWithData)
if err != nil {
handler.logger.Errorw("service err, CSGlobalFetch-buildAppSecrets in GetAppAllDetail", "err", err, "appId", appId)
return nil, err, statusCode
}
for _, secret := range secretRes {
secretsResp = append(secretsResp, secret)
}
}
}
return secretsResp, nil, http.StatusOK
}
// get/build environment secrets
func (handler CoreAppRestHandlerImpl) buildAppEnvironmentSecrets(appId int, envId int) ([]*appBean.Secret, error, int) {
handler.logger.Debugw("Getting app detail - env secrets", "appId", appId, "envId", envId)
secretData, err := handler.configMapService.CSEnvironmentFetch(appId, envId)
if err != nil {
handler.logger.Errorw("service err, CSEnvironmentFetch in GetAppAllDetail", "err", err, "appId", appId, "envId", envId)
return nil, err, http.StatusInternalServerError
}
var secretsResp []*appBean.Secret
if secretData != nil && len(secretData.ConfigData) > 0 {
for _, secretConfig := range secretData.ConfigData {
secretDataWithData, err := handler.configMapService.CSEnvironmentFetchForEdit(secretConfig.Name, secretData.Id, appId, envId)
if err != nil {
handler.logger.Errorw("service err, CSEnvironmentFetchForEdit in GetAppAllDetail", "err", err, "appId", appId, "envId", envId)
return nil, err, http.StatusInternalServerError
}
secretDataWithData.ConfigData[0].DefaultData = secretConfig.DefaultData
secretRes, err, statusCode := handler.buildAppSecrets(appId, envId, secretDataWithData)
if err != nil {
handler.logger.Errorw("service err, CSGlobalFetch-buildAppSecrets in GetAppAllDetail", "err", err, "appId", appId)
return nil, err, statusCode
}
for _, secret := range secretRes {
secretsResp = append(secretsResp, secret)
}
}
}
return secretsResp, nil, http.StatusOK
}