-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppService.go
1286 lines (1196 loc) · 49.3 KB
/
AppService.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 Devtron Labs
*
* 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 app
import (
"context"
"encoding/json"
"fmt"
application2 "github.com/argoproj/argo-cd/pkg/apiclient/application"
"github.com/argoproj/argo-cd/pkg/apis/application/v1alpha1"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/devtron-labs/devtron/api/bean"
"github.com/devtron-labs/devtron/client/argocdServer"
"github.com/devtron-labs/devtron/client/argocdServer/application"
"github.com/devtron-labs/devtron/client/events"
"github.com/devtron-labs/devtron/client/pubsub"
"github.com/devtron-labs/devtron/internal/middleware"
"github.com/devtron-labs/devtron/internal/sql/models"
"github.com/devtron-labs/devtron/internal/sql/repository"
"github.com/devtron-labs/devtron/internal/sql/repository/chartConfig"
"github.com/devtron-labs/devtron/internal/sql/repository/cluster"
"github.com/devtron-labs/devtron/internal/sql/repository/pipelineConfig"
"github.com/devtron-labs/devtron/internal/sql/repository/security"
. "github.com/devtron-labs/devtron/internal/util"
"github.com/devtron-labs/devtron/pkg/commonService"
"github.com/devtron-labs/devtron/pkg/user"
util2 "github.com/devtron-labs/devtron/util"
"github.com/devtron-labs/devtron/util/event"
"github.com/devtron-labs/devtron/util/rbac"
"github.com/go-pg/pg"
errors2 "github.com/juju/errors"
"github.com/pkg/errors"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"net/url"
"strconv"
"strings"
"time"
)
type AppServiceImpl struct {
environmentConfigRepository chartConfig.EnvConfigOverrideRepository
pipelineOverrideRepository chartConfig.PipelineOverrideRepository
mergeUtil *MergeUtil
logger *zap.SugaredLogger
ciArtifactRepository repository.CiArtifactRepository
pipelineRepository pipelineConfig.PipelineRepository
gitFactory *GitFactory
dbMigrationConfigRepository pipelineConfig.DbMigrationConfigRepository
eventClient client.EventClient
eventFactory client.EventFactory
acdClient application.ServiceClient
tokenCache *user.TokenCache
acdAuthConfig *user.ACDAuthConfig
enforcer rbac.Enforcer
enforcerUtil rbac.EnforcerUtil
user user.UserService
appListingRepository repository.AppListingRepository
appRepository pipelineConfig.AppRepository
envRepository cluster.EnvironmentRepository
pipelineConfigRepository chartConfig.PipelineConfigRepository
configMapRepository chartConfig.ConfigMapRepository
chartRepository chartConfig.ChartRepository
appRepo pipelineConfig.AppRepository
appLevelMetricsRepository repository.AppLevelMetricsRepository
envLevelMetricsRepository repository.EnvLevelAppMetricsRepository
ciPipelineMaterialRepository pipelineConfig.CiPipelineMaterialRepository
cdWorkflowRepository pipelineConfig.CdWorkflowRepository
commonService commonService.CommonService
imageScanDeployInfoRepository security.ImageScanDeployInfoRepository
imageScanHistoryRepository security.ImageScanHistoryRepository
ArgoK8sClient argocdServer.ArgoK8sClient
}
type AppService interface {
TriggerRelease(overrideRequest *bean.ValuesOverrideRequest, ctx context.Context) (id int, err error)
UpdateReleaseStatus(request *bean.ReleaseStatusUpdateRequest) (bool, error)
AppendCurrentApplicationStatus(application v1alpha1.Application) (bool, error)
TriggerCD(artifact *repository.CiArtifact, cdWorkflowId int, pipeline *pipelineConfig.Pipeline, async bool) error
GetConfigMapAndSecretJson(appId int, envId int, pipelineId int) ([]byte, error)
UpdateCdWorkflowRunnerByACDObject(app v1alpha1.Application) error
GetCmSecretNew(appId int, envId int) (*bean.ConfigMapJson, *bean.ConfigSecretJson, error)
MarkImageScanDeployed(appId int, envId int, imageDigest string, clusterId int) error
}
func NewAppService(
environmentConfigRepository chartConfig.EnvConfigOverrideRepository,
pipelineOverrideRepository chartConfig.PipelineOverrideRepository,
mergeUtil *MergeUtil,
logger *zap.SugaredLogger,
ciArtifactRepository repository.CiArtifactRepository,
pipelineRepository pipelineConfig.PipelineRepository,
dbMigrationConfigRepository pipelineConfig.DbMigrationConfigRepository,
eventClient client.EventClient,
eventFactory client.EventFactory, acdClient application.ServiceClient,
cache *user.TokenCache, authConfig *user.ACDAuthConfig,
enforcer rbac.Enforcer, enforcerUtil rbac.EnforcerUtil, user user.UserService,
appListingRepository repository.AppListingRepository,
appRepository pipelineConfig.AppRepository,
envRepository cluster.EnvironmentRepository,
pipelineConfigRepository chartConfig.PipelineConfigRepository, configMapRepository chartConfig.ConfigMapRepository,
appLevelMetricsRepository repository.AppLevelMetricsRepository, envLevelMetricsRepository repository.EnvLevelAppMetricsRepository,
chartRepository chartConfig.ChartRepository,
ciPipelineMaterialRepository pipelineConfig.CiPipelineMaterialRepository,
cdWorkflowRepository pipelineConfig.CdWorkflowRepository, commonService commonService.CommonService,
imageScanDeployInfoRepository security.ImageScanDeployInfoRepository, imageScanHistoryRepository security.ImageScanHistoryRepository,
ArgoK8sClient argocdServer.ArgoK8sClient,
gitFactory *GitFactory) *AppServiceImpl {
appServiceImpl := &AppServiceImpl{
environmentConfigRepository: environmentConfigRepository,
mergeUtil: mergeUtil,
pipelineOverrideRepository: pipelineOverrideRepository,
logger: logger,
ciArtifactRepository: ciArtifactRepository,
pipelineRepository: pipelineRepository,
dbMigrationConfigRepository: dbMigrationConfigRepository,
eventClient: eventClient,
eventFactory: eventFactory,
acdClient: acdClient,
tokenCache: cache,
acdAuthConfig: authConfig,
enforcer: enforcer,
enforcerUtil: enforcerUtil,
user: user,
appListingRepository: appListingRepository,
appRepository: appRepository,
envRepository: envRepository,
pipelineConfigRepository: pipelineConfigRepository,
configMapRepository: configMapRepository,
chartRepository: chartRepository,
appLevelMetricsRepository: appLevelMetricsRepository,
envLevelMetricsRepository: envLevelMetricsRepository,
ciPipelineMaterialRepository: ciPipelineMaterialRepository,
cdWorkflowRepository: cdWorkflowRepository,
commonService: commonService,
imageScanDeployInfoRepository: imageScanDeployInfoRepository,
imageScanHistoryRepository: imageScanHistoryRepository,
ArgoK8sClient: ArgoK8sClient,
gitFactory: gitFactory,
}
return appServiceImpl
}
func (impl AppServiceImpl) UpdateReleaseStatus(updateStatusRequest *bean.ReleaseStatusUpdateRequest) (bool, error) {
count, err := impl.pipelineOverrideRepository.UpdateStatusByRequestIdentifier(updateStatusRequest.RequestId, updateStatusRequest.NewStatus)
if err != nil {
impl.logger.Errorw("error in updating release status", "request", updateStatusRequest, "error", err)
return false, err
}
return count == 1, nil
}
func (impl AppServiceImpl) AppendCurrentApplicationStatus(app v1alpha1.Application) (bool, error) {
isHealthy := false
appName := app.Name[:strings.LastIndex(app.Name, "-")]
evnName := app.Name[strings.LastIndex(app.Name, "-")+1:]
dbApp, err := impl.appRepository.FindActiveByName(appName)
if err != nil && err != pg.ErrNoRows {
impl.logger.Errorw("error in fetching app name", "err", err, "appName", appName)
return isHealthy, err
}
if dbApp.Id > 0 && dbApp.AppStore == true {
impl.logger.Debugw("skipping application status update as this app is chart", "appName", appName)
return isHealthy, nil
}
deploymentStatus, err := impl.appListingRepository.FindLastDeployedStatus(app.Name)
if err != nil && !IsErrNoRows(err) {
impl.logger.Errorw("error in fetching deployment status", "err", err)
return isHealthy, err
}
if string(application.Healthy) != deploymentStatus.Status {
if deploymentStatus.Status == app.Status.Health.Status {
impl.logger.Debug("not updating same statuses from " + deploymentStatus.Status + " to " + app.Status.Health.Status)
return isHealthy, nil
}
gitHash := ""
if app.Operation != nil && app.Operation.Sync != nil {
gitHash = app.Operation.Sync.Revision
} else if app.Status.OperationState != nil && app.Status.OperationState.Operation.Sync != nil {
gitHash = app.Status.OperationState.Operation.Sync.Revision
}
pipelineOverride, err := impl.pipelineOverrideRepository.FindByPipelineTriggerGitHash(gitHash)
if err != nil {
return isHealthy, err
}
releaseCounter, err := impl.pipelineOverrideRepository.GetCurrentPipelineReleaseCounter(pipelineOverride.PipelineId)
if err != nil {
return isHealthy, err
}
if pipelineOverride.PipelineReleaseCounter == releaseCounter {
impl.logger.Debug("inserting new app status: " + string(app.Status.Health.Status))
newDeploymentStatus := &repository.DeploymentStatus{
AppName: app.Name,
AppId: deploymentStatus.AppId,
EnvId: deploymentStatus.EnvId,
Status: app.Status.Health.Status,
CreatedOn: time.Now(),
UpdatedOn: time.Now(),
}
err := impl.appListingRepository.SaveNewDeployment(newDeploymentStatus)
if err != nil {
impl.logger.Errorw("err", err)
return isHealthy, err
}
err = impl.UpdateCdWorkflowRunnerByACDObject(app)
if err != nil {
impl.logger.Errorw("err", err)
return isHealthy, err
}
if string(application.Healthy) == newDeploymentStatus.Status {
isHealthy = true
go impl.WriteCDSuccessEvent(newDeploymentStatus.AppId, appName, newDeploymentStatus.EnvId, evnName, pipelineOverride)
}
} else {
impl.logger.Debug("event received for older triggered revision: " + gitHash)
}
}
return isHealthy, nil
}
func (impl *AppServiceImpl) WriteCDSuccessEvent(appId int, appName string, envId int, envName string, override *chartConfig.PipelineOverride) {
event := impl.eventFactory.Build(util.Success, &override.PipelineId, appId, &envId, util.CD)
impl.logger.Debugw("event WriteCDSuccessEvent", "event", event)
event = impl.eventFactory.BuildExtraCDData(event, nil, override.Id, bean.CD_WORKFLOW_TYPE_DEPLOY)
_, evtErr := impl.eventClient.WriteEvent(event)
if evtErr != nil {
impl.logger.Errorw("error in writing event", "err", evtErr)
}
}
func (impl *AppServiceImpl) BuildCDSuccessPayload(appName string, environmentName string) *client.Payload {
payload := &client.Payload{}
payload.AppName = appName
payload.EnvName = environmentName
return payload
}
type EnvironmentOverride struct {
Enabled bool `json:"enabled"`
EnvValues []*KeyValue `json:"envValues"`
}
type KeyValue struct {
Key string `json:"key"`
Value string `json:"value"`
}
func (conf *EnvironmentOverride) appendEnvironmentVariable(key, value string) {
item := &KeyValue{Key: key, Value: value}
conf.EnvValues = append(conf.EnvValues, item)
}
func (impl *AppServiceImpl) TriggerCD(artifact *repository.CiArtifact, cdWorkflowId int, pipeline *pipelineConfig.Pipeline, async bool) error {
impl.logger.Debugw("automatic pipeline trigger attempt async", "artifactId", artifact.Id)
return impl.triggerReleaseAsync(artifact, cdWorkflowId, pipeline)
}
func (impl *AppServiceImpl) triggerReleaseAsync(artifact *repository.CiArtifact, cdWorkflowId int, pipeline *pipelineConfig.Pipeline) error {
err := impl.validateAndTrigger(pipeline, artifact, cdWorkflowId)
if err != nil {
impl.logger.Errorw("error in trigger for pipeline", "pipelineId", strconv.Itoa(pipeline.Id))
}
impl.logger.Debugw("trigger attempted for all pipeline ", "artifactId", artifact.Id)
return err
}
func (impl AppServiceImpl) validateAndTrigger(p *pipelineConfig.Pipeline, artifact *repository.CiArtifact, cdWorkflowId int) error {
object := impl.enforcerUtil.GetAppRBACNameByAppId(p.AppId)
envApp := strings.Split(object, "/")
if len(envApp) != 2 {
impl.logger.Error("invalid req, app and env not found from rbac")
return errors.New("invalid req, app and env not found from rbac")
}
err := impl.releasePipeline(p, artifact, cdWorkflowId)
return err
}
func (impl AppServiceImpl) releasePipeline(pipeline *pipelineConfig.Pipeline, artifact *repository.CiArtifact, cdWorkflowId int) error {
impl.logger.Debugw("triggering release for ", "cdPipelineId", pipeline.Id, "artifactId", artifact.Id)
//Iterate for each even if there is error in one
request := &bean.ValuesOverrideRequest{
PipelineId: pipeline.Id,
UserId: artifact.CreatedBy,
CiArtifactId: artifact.Id,
AppId: pipeline.AppId,
CdWorkflowId: cdWorkflowId,
ForceTrigger: true,
}
ctx, err := impl.buildACDSynchContext()
if err != nil {
impl.logger.Errorw("error in creating acd synch context", "pipelineId", pipeline.Id, "artifactId", artifact.Id, "err", err)
return err
}
id, err := impl.TriggerRelease(request, ctx)
if err != nil {
impl.logger.Errorw("error in auto cd pipeline trigger", "pipelineId", pipeline.Id, "artifactId", artifact.Id, "err", err)
} else {
impl.logger.Infow("pipeline successfully triggered ", "cdPipelineId", pipeline.Id, "artifactId", artifact.Id, "releaseId", id)
}
return err
}
func (impl AppServiceImpl) buildACDSynchContext() (acdContext context.Context, err error) {
return impl.tokenCache.BuildACDSynchContext()
/*token, found := impl.tokenCache.Cache.Get("token")
if !found {
token, err := impl.userAuthService.HandleLogin(impl.acdAuthConfig.ACDUsername, impl.acdAuthConfig.ACDPassword)
if err != nil {
impl.logger.Errorw("error while acd login", "err", err)
return nil, err
}
impl.tokenCache.Cache.Set("token", token, cache.NoExpiration)
}
token, _ = impl.tokenCache.Cache.Get("token")
ctx := context.Background()
ctx = context.WithValue(ctx, "token", token)
return ctx, nil*/
}
func (impl AppServiceImpl) getDbMigrationOverride(overrideRequest *bean.ValuesOverrideRequest, artifact *repository.CiArtifact, isRollback bool) (overrideJson []byte, err error) {
if isRollback {
return nil, fmt.Errorf("rollback not supported ye")
}
notConfigured := false
config, err := impl.dbMigrationConfigRepository.FindByPipelineId(overrideRequest.PipelineId)
if err != nil && !IsErrNoRows(err) {
impl.logger.Errorw("error in fetching pipeline override config", "req", overrideRequest, "err", err)
return nil, err
} else if IsErrNoRows(err) {
notConfigured = true
}
envVal := &EnvironmentOverride{}
if notConfigured {
impl.logger.Warnw("no active db migration found", "pipeline", overrideRequest.PipelineId)
envVal.Enabled = false
} else {
materialInfos, err := artifact.ParseMaterialInfo()
if err != nil {
return nil, err
}
hash, ok := materialInfos[config.GitMaterial.Url]
if !ok {
impl.logger.Errorf("wrong url map ", "map", materialInfos, "url", config.GitMaterial.Url)
return nil, fmt.Errorf("configured url not found in material %s", config.GitMaterial.Url)
}
envVal.Enabled = true
if config.GitMaterial.GitProvider.AuthMode != repository.AUTH_MODE_USERNAME_PASSWORD &&
config.GitMaterial.GitProvider.AuthMode != repository.AUTH_MODE_ACCESS_TOKEN &&
config.GitMaterial.GitProvider.AuthMode != repository.AUTH_MODE_ANONYMOUS {
return nil, fmt.Errorf("auth mode %s not supported for migration", config.GitMaterial.GitProvider.AuthMode)
}
envVal.appendEnvironmentVariable("GIT_REPO_URL", config.GitMaterial.Url)
envVal.appendEnvironmentVariable("GIT_USER", config.GitMaterial.GitProvider.UserName)
var password string
if config.GitMaterial.GitProvider.AuthMode == repository.AUTH_MODE_USERNAME_PASSWORD {
password = config.GitMaterial.GitProvider.Password
} else {
password = config.GitMaterial.GitProvider.AccessToken
}
envVal.appendEnvironmentVariable("GIT_AUTH_TOKEN", password)
// parse git-tag not required
//envVal.appendEnvironmentVariable("GIT_TAG", "")
envVal.appendEnvironmentVariable("GIT_HASH", hash)
envVal.appendEnvironmentVariable("SCRIPT_LOCATION", config.ScriptSource)
envVal.appendEnvironmentVariable("DB_TYPE", string(config.DbConfig.Type))
envVal.appendEnvironmentVariable("DB_USER_NAME", config.DbConfig.UserName)
envVal.appendEnvironmentVariable("DB_PASSWORD", config.DbConfig.Password)
envVal.appendEnvironmentVariable("DB_HOST", config.DbConfig.Host)
envVal.appendEnvironmentVariable("DB_PORT", config.DbConfig.Port)
envVal.appendEnvironmentVariable("DB_NAME", config.DbConfig.DbName)
//Will be used for rollback don't delete it
//envVal.appendEnvironmentVariable("MIGRATE_TO_VERSION", strconv.Itoa(overrideRequest.TargetDbVersion))
}
dbMigrationConfig := map[string]interface{}{"dbMigrationConfig": envVal}
confByte, err := json.Marshal(dbMigrationConfig)
if err != nil {
return nil, err
}
return confByte, nil
}
func (impl AppServiceImpl) TriggerRelease(overrideRequest *bean.ValuesOverrideRequest, ctx context.Context) (id int, err error) {
if overrideRequest.DeploymentType == models.DEPLOYMENTTYPE_UNKNOWN {
overrideRequest.DeploymentType = models.DEPLOYMENTTYPE_DEPLOY
}
pipeline, err := impl.pipelineRepository.FindById(overrideRequest.PipelineId)
if err != nil {
impl.logger.Errorf("invalid req", "err", err, "req", overrideRequest)
return 0, err
}
envOverride, err := impl.environmentConfigRepository.ActiveEnvConfigOverride(overrideRequest.AppId, pipeline.EnvironmentId)
if err != nil {
impl.logger.Errorf("invalid state", "err", err, "req", overrideRequest)
return 0, err
}
if envOverride.Id == 0 {
chart, err := impl.chartRepository.FindLatestChartForAppByAppId(overrideRequest.AppId)
if err != nil {
impl.logger.Errorf("invalid state", "err", err, "req", overrideRequest)
return 0, err
}
envOverride, err = impl.environmentConfigRepository.FindChartByAppIdAndEnvIdAndChartRefId(overrideRequest.AppId, pipeline.EnvironmentId, chart.ChartRefId)
if err != nil && !errors2.IsNotFound(err) {
impl.logger.Errorf("invalid state", "err", err, "req", overrideRequest)
return 0, err
}
//creating new env override config
if errors2.IsNotFound(err) || envOverride == nil {
environment, err := impl.envRepository.FindById(pipeline.EnvironmentId)
if err != nil && !IsErrNoRows(err) {
return 0, err
}
envOverride = &chartConfig.EnvConfigOverride{
Active: true,
ManualReviewed: true,
Status: models.CHARTSTATUS_SUCCESS,
TargetEnvironment: pipeline.EnvironmentId,
ChartId: chart.Id,
AuditLog: models.AuditLog{UpdatedBy: overrideRequest.UserId, UpdatedOn: time.Now(), CreatedOn: time.Now(), CreatedBy: overrideRequest.UserId},
Namespace: environment.Namespace,
IsOverride: false,
EnvOverrideValues: "{}",
Latest: false,
}
err = impl.environmentConfigRepository.Save(envOverride)
if err != nil {
impl.logger.Errorw("error in creating envconfig", "data", envOverride, "error", err)
return 0, err
}
}
env, err := impl.envRepository.FindById(envOverride.TargetEnvironment)
if err != nil {
impl.logger.Errorw("unable to find env", "err", err)
return 0, err
}
envOverride.Environment = env
envOverride.Chart = chart
} else if envOverride.Id > 0 && !envOverride.IsOverride {
chart, err := impl.chartRepository.FindLatestChartForAppByAppId(overrideRequest.AppId)
if err != nil {
impl.logger.Errorf("invalid state", "err", err, "req", overrideRequest)
return 0, err
}
envOverride.Chart = chart
}
artifact, err := impl.ciArtifactRepository.Get(overrideRequest.CiArtifactId)
if err != nil {
return 0, err
}
materialInfoMap, mErr := artifact.ParseMaterialInfo()
if mErr != nil {
impl.logger.Errorw("material info map error", mErr)
return 0, err
}
//FIXME: how to determine rollback
//we can't depend on ciArtifact ID because CI pipeline can be manually triggered in any order regardless of sourcecode status
dbMigrationOverride, err := impl.getDbMigrationOverride(overrideRequest, artifact, false)
if err != nil {
impl.logger.Errorw("error in fetching db migration config", "req", overrideRequest, "err", err)
return 0, err
}
//fetch pipeline config from strategy table, if pipeline is automatic fetch always default, else depends on request
var strategy *chartConfig.PipelineStrategy
//forceTrigger true if CD triggered Auto, triggered occurred from CI
if overrideRequest.ForceTrigger {
strategy, err = impl.pipelineConfigRepository.GetDefaultStrategyByPipelineId(overrideRequest.PipelineId)
} else {
var deploymentTemplate pipelineConfig.DeploymentTemplate
if overrideRequest.DeploymentTemplate == "ROLLING" {
deploymentTemplate = pipelineConfig.DEPLOYMENT_TEMPLATE_ROLLING
} else if overrideRequest.DeploymentTemplate == "BLUE-GREEN" {
deploymentTemplate = pipelineConfig.DEPLOYMENT_TEMPLATE_BLUE_GREEN
} else if overrideRequest.DeploymentTemplate == "CANARY" {
deploymentTemplate = pipelineConfig.DEPLOYMENT_TEMPLATE_CANARY
} else if overrideRequest.DeploymentTemplate == "RECREATE" {
deploymentTemplate = pipelineConfig.DEPLOYMENT_TEMPLATE_RECREATE
}
if len(deploymentTemplate) > 0 {
strategy, err = impl.pipelineConfigRepository.FindByStrategyAndPipelineId(deploymentTemplate, overrideRequest.PipelineId)
} else {
strategy, err = impl.pipelineConfigRepository.GetDefaultStrategyByPipelineId(overrideRequest.PipelineId)
}
}
if err != nil && errors2.IsNotFound(err) == false {
impl.logger.Errorf("invalid state", "err", err, "req", strategy)
return 0, err
}
valid, err := impl.validateVersionForStrategy(envOverride, strategy)
if err != nil || !valid {
impl.logger.Errorw("error in validating pipeline strategy ", "strategy", strategy.Strategy, "err", err)
return 0, err
}
chartVersion := envOverride.Chart.ChartVersion
configMapJson, err := impl.getConfigMapAndSecretJsonV2(overrideRequest.AppId, envOverride.TargetEnvironment, overrideRequest.PipelineId, chartVersion)
if err != nil {
impl.logger.Errorw("error in fetching config map n secret ", "err", err)
configMapJson = nil
}
releaseId, pipelineOverrideId, saveErr := impl.mergeAndSave(envOverride, overrideRequest, dbMigrationOverride, artifact, pipeline, configMapJson, strategy, ctx)
if releaseId != 0 {
flag, err := impl.updateArgoPipeline(overrideRequest.AppId, pipeline.Name, envOverride, ctx)
if err != nil {
impl.logger.Errorw("error in updating argocd app ", "err", err)
return 0, err
}
if flag {
impl.logger.Debug("argocd successfully updated")
} else {
impl.logger.Debug("argocd failed to update, ignoring it")
}
deploymentStatus := &repository.DeploymentStatus{
AppName: pipeline.App.AppName + "-" + envOverride.Environment.Name,
AppId: pipeline.AppId,
EnvId: pipeline.EnvironmentId,
Status: repository.NewDeployment,
CreatedOn: time.Now(),
UpdatedOn: time.Now(),
}
err = impl.appListingRepository.SaveNewDeployment(deploymentStatus)
if err != nil {
impl.logger.Errorw("error in saving new deployment history", "req", overrideRequest, "err", err)
return 0, err
}
impl.synchCD(pipeline, ctx, overrideRequest, envOverride)
go impl.WriteCDTriggerEvent(overrideRequest, pipeline, envOverride, materialInfoMap, artifact, releaseId, pipelineOverrideId)
if artifact.ScanEnabled {
_ = impl.MarkImageScanDeployed(overrideRequest.AppId, envOverride.TargetEnvironment, artifact.ImageDigest, pipeline.Environment.ClusterId)
}
}
middleware.CdTriggerCounter.WithLabelValues(strconv.Itoa(pipeline.AppId), strconv.Itoa(pipeline.EnvironmentId), strconv.Itoa(pipeline.Id)).Inc()
return releaseId, saveErr
}
func (impl AppServiceImpl) MarkImageScanDeployed(appId int, envId int, imageDigest string, clusterId int) error {
impl.logger.Debugw("mark image scan deployed for normal app, from cd auto or manual trigger", "imageDigest", imageDigest)
executionHistory, err := impl.imageScanHistoryRepository.FindByImageDigest(imageDigest)
if err != nil && err != pg.ErrNoRows {
impl.logger.Errorw("error in fetching execution history", "err", err)
return err
}
if executionHistory == nil || executionHistory.Id == 0 {
impl.logger.Errorw("no execution history found for digest", "digest", imageDigest)
return fmt.Errorf("no execution history found for digest - %s", imageDigest)
}
impl.logger.Debugw("mark image scan deployed for normal app, from cd auto or manual trigger", "executionHistory", executionHistory)
var ids []int
ids = append(ids, executionHistory.Id)
ot, err := impl.imageScanDeployInfoRepository.FindByTypeMetaAndTypeId(appId, security.ScanObjectType_APP) //todo insure this touple unique in db
if err != nil && err != pg.ErrNoRows {
return err
} else if err == pg.ErrNoRows {
imageScanDeployInfo := &security.ImageScanDeployInfo{
ImageScanExecutionHistoryId: ids,
ScanObjectMetaId: appId,
ObjectType: security.ScanObjectType_APP,
EnvId: envId,
ClusterId: clusterId,
AuditLog: models.AuditLog{
CreatedOn: time.Now(),
CreatedBy: 1,
UpdatedOn: time.Now(),
UpdatedBy: 1,
},
}
impl.logger.Debugw("mark image scan deployed for normal app, from cd auto or manual trigger", "imageScanDeployInfo", imageScanDeployInfo)
err = impl.imageScanDeployInfoRepository.Save(imageScanDeployInfo)
if err != nil {
impl.logger.Errorw("error in creating deploy info", "err", err)
}
} else {
impl.logger.Debugw("pt", "ot", ot)
}
return err
}
func (impl AppServiceImpl) validateVersionForStrategy(envOverride *chartConfig.EnvConfigOverride, strategy *chartConfig.PipelineStrategy) (bool, error) {
chartVersion := envOverride.Chart.ChartVersion
chartMajorVersion, err := strconv.Atoi(chartVersion[:1])
if err != nil {
impl.logger.Errorw("err", err)
return false, err
}
chartMinorVersion, err := strconv.Atoi(chartVersion[2:3])
if err != nil {
impl.logger.Errorw("err", err)
return false, err
}
if (chartMajorVersion <= 3 && chartMinorVersion < 2) &&
(strategy.Strategy == pipelineConfig.DEPLOYMENT_TEMPLATE_CANARY || strategy.Strategy == pipelineConfig.DEPLOYMENT_TEMPLATE_RECREATE) {
err = &ApiError{
Code: "422",
InternalMessage: "incompatible chart for selected cd strategy:" + string(strategy.Strategy),
UserMessage: "incompatible chart for selected cd strategy:" + string(strategy.Strategy),
}
return false, err
}
return true, nil
}
//FIXME tmp workaround
func (impl AppServiceImpl) GetCmSecretNew(appId int, envId int) (*bean.ConfigMapJson, *bean.ConfigSecretJson, error) {
var configMapJson string
var secretDataJson string
var configMapJsonApp string
var secretDataJsonApp string
var configMapJsonEnv string
var secretDataJsonEnv string
//var configMapJsonPipeline string
//var secretDataJsonPipeline string
configMapA, err := impl.configMapRepository.GetByAppIdAppLevel(appId)
if err != nil && pg.ErrNoRows != err {
return nil, nil, err
}
if configMapA != nil && configMapA.Id > 0 {
configMapJsonApp = configMapA.ConfigMapData
secretDataJsonApp = configMapA.SecretData
}
configMapE, err := impl.configMapRepository.GetByAppIdAndEnvIdEnvLevel(appId, envId)
if err != nil && pg.ErrNoRows != err {
return nil, nil, err
}
if configMapE != nil && configMapE.Id > 0 {
configMapJsonEnv = configMapE.ConfigMapData
secretDataJsonEnv = configMapE.SecretData
}
configMapJson, err = impl.mergeUtil.ConfigMapMerge(configMapJsonApp, configMapJsonEnv)
if err != nil {
return nil, nil, err
}
chart, err := impl.commonService.FetchLatestChart(appId, envId)
if err != nil {
return nil, nil, err
}
chartVersion := chart.ChartVersion
chartMajorVersion, chartMinorVersion, err := util2.ExtractChartVersion(chartVersion)
if err != nil {
impl.logger.Errorw("chart version parsing", "err", err)
return nil, nil, err
}
secretDataJson, err = impl.mergeUtil.ConfigSecretMerge(secretDataJsonApp, secretDataJsonEnv, chartMajorVersion, chartMinorVersion)
if err != nil {
return nil, nil, err
}
configResponse := bean.ConfigMapJson{}
if len(configMapJson) != 0 {
err = json.Unmarshal([]byte(configMapJson), &configResponse)
if err != nil {
return nil, nil, err
}
}
secretResponse := bean.ConfigSecretJson{}
if len(configMapJson) != 0 {
err = json.Unmarshal([]byte(secretDataJson), &secretResponse)
if err != nil {
return nil, nil, err
}
}
return &configResponse, &secretResponse, nil
}
//depricated
//TODO remove this method
func (impl AppServiceImpl) GetConfigMapAndSecretJson(appId int, envId int, pipelineId int) ([]byte, error) {
var configMapJson string
var secretDataJson string
merged := []byte("{}")
configMapA, err := impl.configMapRepository.GetByAppIdAppLevel(appId)
if err != nil && pg.ErrNoRows != err {
return []byte("{}"), err
}
if configMapA != nil && configMapA.Id > 0 {
configMapJson = configMapA.ConfigMapData
secretDataJson = configMapA.SecretData
if configMapJson == "" {
configMapJson = "{}"
}
if secretDataJson == "" {
secretDataJson = "{}"
}
config, err := impl.mergeUtil.JsonPatch([]byte(configMapJson), []byte(secretDataJson))
if err != nil {
return []byte("{}"), err
}
merged, err = impl.mergeUtil.JsonPatch(merged, config)
if err != nil {
return []byte("{}"), err
}
}
configMapE, err := impl.configMapRepository.GetByAppIdAndEnvIdEnvLevel(appId, envId)
if err != nil && pg.ErrNoRows != err {
return []byte("{}"), err
}
if configMapE != nil && configMapE.Id > 0 {
configMapJson = configMapE.ConfigMapData
secretDataJson = configMapE.SecretData
if configMapJson == "" {
configMapJson = "{}"
}
if secretDataJson == "" {
secretDataJson = "{}"
}
config, err := impl.mergeUtil.JsonPatch([]byte(configMapJson), []byte(secretDataJson))
if err != nil {
return []byte("{}"), err
}
merged, err = impl.mergeUtil.JsonPatch(merged, config)
if err != nil {
return []byte("{}"), err
}
}
return merged, nil
}
func (impl AppServiceImpl) getConfigMapAndSecretJsonV2(appId int, envId int, pipelineId int, chartVersion string) ([]byte, error) {
var configMapJson string
var secretDataJson string
var configMapJsonApp string
var secretDataJsonApp string
var configMapJsonEnv string
var secretDataJsonEnv string
//var configMapJsonPipeline string
//var secretDataJsonPipeline string
merged := []byte("{}")
configMapA, err := impl.configMapRepository.GetByAppIdAppLevel(appId)
if err != nil && pg.ErrNoRows != err {
return []byte("{}"), err
}
if configMapA != nil && configMapA.Id > 0 {
configMapJsonApp = configMapA.ConfigMapData
secretDataJsonApp = configMapA.SecretData
}
configMapE, err := impl.configMapRepository.GetByAppIdAndEnvIdEnvLevel(appId, envId)
if err != nil && pg.ErrNoRows != err {
return []byte("{}"), err
}
if configMapE != nil && configMapE.Id > 0 {
configMapJsonEnv = configMapE.ConfigMapData
secretDataJsonEnv = configMapE.SecretData
}
configMapJson, err = impl.mergeUtil.ConfigMapMerge(configMapJsonApp, configMapJsonEnv)
if err != nil {
return []byte("{}"), err
}
chartMajorVersion, chartMinorVersion, err := util2.ExtractChartVersion(chartVersion)
if err != nil {
impl.logger.Errorw("chart version parsing", "err", err)
return []byte("{}"), err
}
secretDataJson, err = impl.mergeUtil.ConfigSecretMerge(secretDataJsonApp, secretDataJsonEnv, chartMajorVersion, chartMinorVersion)
if err != nil {
return []byte("{}"), err
}
configResponseR := bean.ConfigMapRootJson{}
configResponse := bean.ConfigMapJson{}
if len(configMapJson) != 0 {
err = json.Unmarshal([]byte(configMapJson), &configResponse)
if err != nil {
return []byte("{}"), err
}
}
configResponseR.ConfigMapJson = configResponse
secretResponseR := bean.ConfigSecretRootJson{}
secretResponse := bean.ConfigSecretJson{}
if len(configMapJson) != 0 {
err = json.Unmarshal([]byte(secretDataJson), &secretResponse)
if err != nil {
return []byte("{}"), err
}
}
secretResponseR.ConfigSecretJson = secretResponse
configMapByte, err := json.Marshal(configResponseR)
if err != nil {
return []byte("{}"), err
}
secretDataByte, err := json.Marshal(secretResponseR)
if err != nil {
return []byte("{}"), err
}
merged, err = impl.mergeUtil.JsonPatch(configMapByte, secretDataByte)
if err != nil {
return []byte("{}"), err
}
return merged, nil
}
func (impl AppServiceImpl) synchCD(pipeline *pipelineConfig.Pipeline, ctx context.Context,
overrideRequest *bean.ValuesOverrideRequest, envOverride *chartConfig.EnvConfigOverride) {
req := new(application2.ApplicationSyncRequest)
pipelineName := pipeline.App.AppName + "-" + envOverride.Environment.Name
req.Name = &pipelineName
req.Prune = true
if ctx == nil {
impl.logger.Errorw("err in syncing ACD, ctx is NULL", "pipelineId", overrideRequest.PipelineId)
return
}
if _, err := impl.acdClient.Sync(ctx, req); err != nil {
impl.logger.Errorw("err in syncing ACD", "pipelineId", overrideRequest.PipelineId, "err", err)
}
}
func (impl *AppServiceImpl) WriteCDTriggerEvent(overrideRequest *bean.ValuesOverrideRequest, pipeline *pipelineConfig.Pipeline,
envOverride *chartConfig.EnvConfigOverride, materialInfoMap map[string]string, artifact *repository.CiArtifact, releaseId, pipelineOverrideId int) {
event := impl.eventFactory.Build(util.Trigger, &pipeline.Id, pipeline.AppId, &pipeline.EnvironmentId, util.CD)
impl.logger.Debugw("event WriteCDTriggerEvent", "event", event)
event = impl.eventFactory.BuildExtraCDData(event, nil, pipelineOverrideId, bean.CD_WORKFLOW_TYPE_DEPLOY)
_, evtErr := impl.eventClient.WriteEvent(event)
if evtErr != nil {
impl.logger.Errorw("CD trigger event not sent", "error", evtErr)
}
deploymentEvent := DeploymentEvent{
ApplicationId: pipeline.AppId,
EnvironmentId: pipeline.EnvironmentId, //check for production Environment
ReleaseId: releaseId,
PipelineOverrideId: pipelineOverrideId,
TriggerTime: time.Now(),
CiArtifactId: overrideRequest.CiArtifactId,
}
ciPipelineMaterials, err := impl.ciPipelineMaterialRepository.GetByPipelineId(artifact.PipelineId)
if err != nil {
impl.logger.Errorw("error in ")
}
for _, ciPipelineMaterial := range ciPipelineMaterials {
hash := materialInfoMap[ciPipelineMaterial.GitMaterial.Url]
pipelineMaterialInfo := &PipelineMaterialInfo{PipelineMaterialId: ciPipelineMaterial.Id, CommitHash: hash}
deploymentEvent.PipelineMaterials = append(deploymentEvent.PipelineMaterials, pipelineMaterialInfo)
}
impl.logger.Infow("triggering deployment event", "event", deploymentEvent)
err = impl.eventClient.WriteNatsEvent(pubsub.CD_SUCCESS, deploymentEvent)
if err != nil {
impl.logger.Errorw("error in writing cd trigger event", "err", err)
}
}
type DeploymentEvent struct {
ApplicationId int
EnvironmentId int
ReleaseId int
PipelineOverrideId int
TriggerTime time.Time
PipelineMaterials []*PipelineMaterialInfo
CiArtifactId int
}
type PipelineMaterialInfo struct {
PipelineMaterialId int
CommitHash string
}
func buildCDTriggerEvent(impl *AppServiceImpl, overrideRequest *bean.ValuesOverrideRequest, pipeline *pipelineConfig.Pipeline,
envOverride *chartConfig.EnvConfigOverride, materialInfo map[string]string, artifact *repository.CiArtifact) client.Event {
event := impl.eventFactory.Build(util.Trigger, &pipeline.Id, pipeline.AppId, &pipeline.EnvironmentId, util.CD)
return event
}
func (impl *AppServiceImpl) BuildPayload(overrideRequest *bean.ValuesOverrideRequest, pipeline *pipelineConfig.Pipeline,
envOverride *chartConfig.EnvConfigOverride, materialInfo map[string]string, artifact *repository.CiArtifact) *client.Payload {
payload := &client.Payload{}
payload.AppName = pipeline.App.AppName
payload.PipelineName = pipeline.Name
payload.EnvName = envOverride.Environment.Name
var revision string
for _, v := range materialInfo {
revision = v
break
}
payload.Source = url.PathEscape(revision)
payload.DockerImageUrl = artifact.Image
return payload
}
type ReleaseAttributes struct {
Name string
Tag string
PipelineName string
ReleaseVersion string
DeploymentType string
App string
Env string
AppMetrics *bool
}
func (impl AppServiceImpl) getReleaseOverride(envOverride *chartConfig.EnvConfigOverride,
overrideRequest *bean.ValuesOverrideRequest,
artifact *repository.CiArtifact,
pipeline *pipelineConfig.Pipeline,
pipelineOverride *chartConfig.PipelineOverride, strategy *chartConfig.PipelineStrategy) (releaseOverride string, err error) {
artifactImage := artifact.Image
imageTag := strings.Split(artifactImage, ":")
appId := strconv.Itoa(pipeline.App.Id)
envId := strconv.Itoa(pipeline.EnvironmentId)
var appMetrics *bool
appLevelMetrics, err := impl.appLevelMetricsRepository.FindByAppId(pipeline.AppId)
if err != nil && !IsErrNoRows(err) {
impl.logger.Errorw("err", err)
return "", &ApiError{InternalMessage: "unable to fetch app level metrics flag"}
}
appMetrics = &appLevelMetrics.AppMetrics
envLevelMetrics, err := impl.envLevelMetricsRepository.FindByAppIdAndEnvId(pipeline.AppId, pipeline.EnvironmentId)
if err != nil && !IsErrNoRows(err) {
impl.logger.Errorw("err", err)
return "", &ApiError{InternalMessage: "unable to fetch env level metrics flag"}
}
if envLevelMetrics.Id != 0 && envLevelMetrics.AppMetrics != nil {
appMetrics = envLevelMetrics.AppMetrics
}
releaseAttribute := ReleaseAttributes{
Name: imageTag[0],
Tag: imageTag[1],
PipelineName: pipeline.Name,
ReleaseVersion: strconv.Itoa(pipelineOverride.PipelineReleaseCounter),
DeploymentType: string(strategy.Strategy),
App: appId,
Env: envId,
AppMetrics: appMetrics,
}
override, err := Tprintf(envOverride.Chart.ImageDescriptorTemplate, releaseAttribute)
if err != nil {
return "", &ApiError{InternalMessage: "unable to render ImageDescriptorTemplate"}
}
if overrideRequest.AdditionalOverride != nil {
userOverride, err := overrideRequest.AdditionalOverride.MarshalJSON()
if err != nil {
return "", err
}
data, err := impl.mergeUtil.JsonPatch(userOverride, []byte(override))
if err != nil {
return "", err
}
override = string(data)
}
return override, nil
}
func (impl AppServiceImpl) mergeAndSave(envOverride *chartConfig.EnvConfigOverride,
overrideRequest *bean.ValuesOverrideRequest,
dbMigrationOverride []byte,
artifact *repository.CiArtifact,
pipeline *pipelineConfig.Pipeline, configMapJson []byte, strategy *chartConfig.PipelineStrategy, ctx context.Context) (releaseId int, overrideId int, err error) {
//register release , obtain release id TODO: populate releaseId to template
override, err := impl.savePipelineOverride(overrideRequest, envOverride.Id)
if err != nil {
return 0, 0, err
}
//TODO: check status and apply lock