From e222883b5037d1335ae445b2c203d2e1a652051e Mon Sep 17 00:00:00 2001 From: Bhupesh Varshney Date: Tue, 15 Sep 2026 13:41:24 +0530 Subject: [PATCH 1/2] feat: scoped variable support for git repo and container repo --- Wire.go | 6 + .../configure/BuildPipelineRestHandler.go | 28 ++-- .../ScopedVariableRestHandler.go | 44 ++++-- pkg/build/trigger/HandlerService.go | 24 +++- pkg/pipeline/CiCdPipelineOrchestrator.go | 91 ++++++++++-- .../GitMaterialVariableSyncService.go | 62 ++++++++ pkg/resourceQualifiers/constants.go | 11 ++ pkg/resourceQualifiers/constants_test.go | 42 ++++++ pkg/variables/RepoFieldVariableResolver.go | 98 +++++++++++++ .../RepoFieldVariableResolver_test.go | 134 ++++++++++++++++++ pkg/variables/VariableEntityMappingService.go | 13 ++ pkg/variables/repository/VariableEntityDTO.go | 3 + .../VariableEntityMappingRepository.go | 18 +++ wire_gen.go | 8 +- 14 files changed, 543 insertions(+), 39 deletions(-) create mode 100644 pkg/pipeline/GitMaterialVariableSyncService.go create mode 100644 pkg/resourceQualifiers/constants_test.go create mode 100644 pkg/variables/RepoFieldVariableResolver.go create mode 100644 pkg/variables/RepoFieldVariableResolver_test.go diff --git a/Wire.go b/Wire.go index 75264c635e..1015ce7788 100644 --- a/Wire.go +++ b/Wire.go @@ -345,6 +345,9 @@ func InitializeApp() (*App, error) { pipeline.NewCiCdPipelineOrchestrator, wire.Bind(new(pipeline.CiCdPipelineOrchestrator), new(*pipeline.CiCdPipelineOrchestratorImpl)), + pipeline.NewGitMaterialVariableSyncServiceImpl, + wire.Bind(new(pipeline.GitMaterialVariableSyncService), new(*pipeline.GitMaterialVariableSyncServiceImpl)), + // scoped variables start variables.NewScopedVariableServiceImpl, wire.Bind(new(variables.ScopedVariableService), new(*variables.ScopedVariableServiceImpl)), @@ -367,6 +370,9 @@ func InitializeApp() (*App, error) { variables.NewScopedVariableCMCSManagerImpl, wire.Bind(new(variables.ScopedVariableCMCSManager), new(*variables.ScopedVariableCMCSManagerImpl)), + variables.NewRepoFieldVariableResolverImpl, + wire.Bind(new(variables.RepoFieldVariableResolver), new(*variables.RepoFieldVariableResolverImpl)), + // end gitOpsConfig.NewDevtronAppGitOpConfigServiceImpl, diff --git a/api/restHandler/app/pipeline/configure/BuildPipelineRestHandler.go b/api/restHandler/app/pipeline/configure/BuildPipelineRestHandler.go index 4d2f0414cb..8cdc04422d 100644 --- a/api/restHandler/app/pipeline/configure/BuildPipelineRestHandler.go +++ b/api/restHandler/app/pipeline/configure/BuildPipelineRestHandler.go @@ -33,6 +33,7 @@ import ( bean2 "github.com/devtron-labs/devtron/pkg/build/pipeline/bean" eventProcessorBean "github.com/devtron-labs/devtron/pkg/eventProcessor/bean" constants2 "github.com/devtron-labs/devtron/pkg/pipeline/constants" + "github.com/devtron-labs/devtron/pkg/variables" "github.com/devtron-labs/devtron/util/stringsUtil" "golang.org/x/exp/maps" @@ -1363,6 +1364,11 @@ func (handler *PipelineConfigRestHandlerImpl) CreateMaterial(w http.ResponseWrit return } for _, gitMaterial := range createMaterialDto.Material { + // a @{{VAR_NAME}} reference isn't a real URL yet - skip the format check here, + // RepoFieldVariableResolver validates and resolves it before use + if variables.IsFullVariableReference(gitMaterial.Url) { + continue + } validationResult, err := handler.ValidateGitMaterialUrl(gitMaterial.GitProviderId, gitMaterial.Url) if err != nil { handler.Logger.Errorw("service err, CreateMaterial", "err", err, "CreateMaterial", createMaterialDto) @@ -1409,16 +1415,20 @@ func (handler *PipelineConfigRestHandlerImpl) UpdateMaterial(w http.ResponseWrit common.WriteJsonResp(w, err, nil, http.StatusBadRequest) return } - validationResult, err := handler.ValidateGitMaterialUrl(updateMaterialDto.Material.GitProviderId, updateMaterialDto.Material.Url) - if err != nil { - handler.Logger.Errorw("service err, UpdateMaterial", "err", err, "UpdateMaterial", updateMaterialDto) - common.WriteJsonResp(w, err, nil, http.StatusInternalServerError) - return - } else { - if !validationResult { - handler.Logger.Errorw("validation err, UpdateMaterial : invalid git material url", "err", err, "gitMaterialUrl", updateMaterialDto.Material.Url, "UpdateMaterial", updateMaterialDto) - common.WriteJsonResp(w, err, nil, http.StatusBadRequest) + // a @{{VAR_NAME}} reference isn't a real URL yet - skip the format check here, + // RepoFieldVariableResolver validates and resolves it before use + if !variables.IsFullVariableReference(updateMaterialDto.Material.Url) { + validationResult, err := handler.ValidateGitMaterialUrl(updateMaterialDto.Material.GitProviderId, updateMaterialDto.Material.Url) + if err != nil { + handler.Logger.Errorw("service err, UpdateMaterial", "err", err, "UpdateMaterial", updateMaterialDto) + common.WriteJsonResp(w, err, nil, http.StatusInternalServerError) return + } else { + if !validationResult { + handler.Logger.Errorw("validation err, UpdateMaterial : invalid git material url", "err", err, "gitMaterialUrl", updateMaterialDto.Material.Url, "UpdateMaterial", updateMaterialDto) + common.WriteJsonResp(w, err, nil, http.StatusBadRequest) + return + } } } resourceObject := handler.enforcerUtil.GetAppRBACNameByAppId(updateMaterialDto.AppId) diff --git a/api/restHandler/scopedVariable/ScopedVariableRestHandler.go b/api/restHandler/scopedVariable/ScopedVariableRestHandler.go index 5a8ed20c4d..e7779b85b3 100644 --- a/api/restHandler/scopedVariable/ScopedVariableRestHandler.go +++ b/api/restHandler/scopedVariable/ScopedVariableRestHandler.go @@ -23,6 +23,7 @@ import ( "net/http" "strconv" + "github.com/devtron-labs/common-lib/async" "github.com/devtron-labs/devtron/api/restHandler/common" "github.com/devtron-labs/devtron/pkg/auth/authorisation/casbin" "github.com/devtron-labs/devtron/pkg/auth/user" @@ -45,28 +46,32 @@ type ScopedVariableRestHandler interface { } type ScopedVariableRestHandlerImpl struct { - logger *zap.SugaredLogger - userAuthService user.UserService - validator *validator.Validate - pipelineBuilder pipeline.PipelineBuilder - enforcerUtil rbac.EnforcerUtil - enforcer casbin.Enforcer - scopedVariableService variables.ScopedVariableService + logger *zap.SugaredLogger + userAuthService user.UserService + validator *validator.Validate + pipelineBuilder pipeline.PipelineBuilder + enforcerUtil rbac.EnforcerUtil + enforcer casbin.Enforcer + scopedVariableService variables.ScopedVariableService + gitMaterialVariableSyncService pipeline.GitMaterialVariableSyncService + asyncRunnable *async.Runnable } type JsonResponse struct { Manifest *models.ScopedVariableManifest `json:"manifest"` JsonSchema string `json:"jsonSchema"` } -func NewScopedVariableRestHandlerImpl(logger *zap.SugaredLogger, userAuthService user.UserService, validator *validator.Validate, pipelineBuilder pipeline.PipelineBuilder, enforcerUtil rbac.EnforcerUtil, enforcer casbin.Enforcer, scopedVariableService variables.ScopedVariableService) *ScopedVariableRestHandlerImpl { +func NewScopedVariableRestHandlerImpl(logger *zap.SugaredLogger, userAuthService user.UserService, validator *validator.Validate, pipelineBuilder pipeline.PipelineBuilder, enforcerUtil rbac.EnforcerUtil, enforcer casbin.Enforcer, scopedVariableService variables.ScopedVariableService, gitMaterialVariableSyncService pipeline.GitMaterialVariableSyncService, asyncRunnable *async.Runnable) *ScopedVariableRestHandlerImpl { return &ScopedVariableRestHandlerImpl{ - logger: logger, - userAuthService: userAuthService, - validator: validator, - pipelineBuilder: pipelineBuilder, - enforcerUtil: enforcerUtil, - enforcer: enforcer, - scopedVariableService: scopedVariableService, + logger: logger, + userAuthService: userAuthService, + validator: validator, + pipelineBuilder: pipelineBuilder, + enforcerUtil: enforcerUtil, + enforcer: enforcer, + scopedVariableService: scopedVariableService, + gitMaterialVariableSyncService: gitMaterialVariableSyncService, + asyncRunnable: asyncRunnable, } } func (handler *ScopedVariableRestHandlerImpl) CreateVariables(w http.ResponseWriter, r *http.Request) { @@ -115,6 +120,15 @@ func (handler *ScopedVariableRestHandlerImpl) CreateVariables(w http.ResponseWri } return } + // CreateVariables replaces the entire variable set, so any Git Material referencing a + // scoped variable may need its git-sensor copy refreshed - run off-thread since each + // push to git-sensor can take up to its own timeout ceiling, and this must not block + // the response for a save that already succeeded above. + handler.asyncRunnable.Execute(func() { + if syncErr := handler.gitMaterialVariableSyncService.ResyncGitMaterialsForVariableChange(); syncErr != nil { + handler.logger.Errorw("error re-syncing git materials after variable change", "err", syncErr) + } + }) common.WriteJsonResp(w, nil, nil, http.StatusOK) } func (handler *ScopedVariableRestHandlerImpl) GetScopedVariables(w http.ResponseWriter, r *http.Request) { diff --git a/pkg/build/trigger/HandlerService.go b/pkg/build/trigger/HandlerService.go index a4b97ce611..ff015e8316 100644 --- a/pkg/build/trigger/HandlerService.go +++ b/pkg/build/trigger/HandlerService.go @@ -110,6 +110,7 @@ type HandlerServiceImpl struct { customTagService pipeline2.CustomTagService config *types.CiConfig scopedVariableManager variables.ScopedVariableManager + repoFieldVariableResolver variables.RepoFieldVariableResolver ciCdPipelineOrchestrator pipeline2.CiCdPipelineOrchestrator buildxGlobalFlags *BuildxGlobalFlags attributeService attributes.AttributesService @@ -138,6 +139,7 @@ func NewHandlerServiceImpl(Logger *zap.SugaredLogger, workflowService executor.W envRepository repository6.EnvironmentRepository, appRepository appRepository.AppRepository, scopedVariableManager variables.ScopedVariableManager, + repoFieldVariableResolver variables.RepoFieldVariableResolver, customTagService pipeline2.CustomTagService, ciCdPipelineOrchestrator pipeline2.CiCdPipelineOrchestrator, attributeService attributes.AttributesService, pluginInputVariableParser pipeline2.PluginInputVariableParser, @@ -171,6 +173,7 @@ func NewHandlerServiceImpl(Logger *zap.SugaredLogger, workflowService executor.W envRepository: envRepository, appRepository: appRepository, scopedVariableManager: scopedVariableManager, + repoFieldVariableResolver: repoFieldVariableResolver, customTagService: customTagService, ciCdPipelineOrchestrator: ciCdPipelineOrchestrator, buildxGlobalFlags: buildxCacheFlags, @@ -847,7 +850,7 @@ func (impl *HandlerServiceImpl) StartCiWorkflowAndPrepareWfRequest(trigger *type trigger.RuntimeParameters = trigger.RuntimeParameters.AddSystemVariable(k, v) } - workflowRequest, err := impl.buildWfRequestForCiPipeline(pipeline, trigger, ciMaterials, savedCiWf, ciWorkflowConfigNamespace, ciPipelineScripts, preCiSteps, postCiSteps, refPluginsData, isJob) + workflowRequest, err := impl.buildWfRequestForCiPipeline(pipeline, trigger, ciMaterials, savedCiWf, ciWorkflowConfigNamespace, ciPipelineScripts, preCiSteps, postCiSteps, refPluginsData, isJob, scope) if err != nil { impl.Logger.Errorw("make workflow req", "err", err) return nil, nil, nil, err @@ -1006,7 +1009,7 @@ func (impl *HandlerServiceImpl) buildDefaultArtifactLocation(savedWf *pipelineCo return ArtifactLocation } -func (impl *HandlerServiceImpl) buildWfRequestForCiPipeline(pipeline *pipelineConfig.CiPipeline, trigger *types.CiTriggerRequest, ciMaterials []*pipelineConfig.CiPipelineMaterial, savedWf *pipelineConfig.CiWorkflow, ciWorkflowConfigNamespace string, ciPipelineScripts []*pipelineConfig.CiPipelineScript, preCiSteps []*pipelineConfigBean.StepObject, postCiSteps []*pipelineConfigBean.StepObject, refPluginsData []*pipelineConfigBean.RefPluginObject, isJob bool) (*types.WorkflowRequest, error) { +func (impl *HandlerServiceImpl) buildWfRequestForCiPipeline(pipeline *pipelineConfig.CiPipeline, trigger *types.CiTriggerRequest, ciMaterials []*pipelineConfig.CiPipelineMaterial, savedWf *pipelineConfig.CiWorkflow, ciWorkflowConfigNamespace string, ciPipelineScripts []*pipelineConfig.CiPipelineScript, preCiSteps []*pipelineConfigBean.StepObject, postCiSteps []*pipelineConfigBean.StepObject, refPluginsData []*pipelineConfigBean.RefPluginObject, isJob bool, scope resourceQualifiers.Scope) (*types.WorkflowRequest, error) { var ciProjectDetails []pipelineConfigBean.CiProjectDetails commitHashes := trigger.CommitHashes for _, ciMaterial := range ciMaterials { @@ -1015,8 +1018,15 @@ func (impl *HandlerServiceImpl) buildWfRequestForCiPipeline(pipeline *pipelineCo continue } commitHashForPipelineId := commitHashes[ciMaterial.Id] + // git_material.url may hold a @{{VAR_NAME}} reference (never resolved into the DB, see + // RepoFieldVariableResolver) - resolve it fresh here rather than at Git Material save time + gitRepository, _, err := impl.repoFieldVariableResolver.ResolveRepoFieldValue(scope, ciMaterial.GitMaterial.Url) + if err != nil { + impl.Logger.Errorw("error resolving git material url", "gitMaterialId", ciMaterial.GitMaterial.Id, "err", err) + return nil, err + } ciProjectDetail := pipelineConfigBean.CiProjectDetails{ - GitRepository: ciMaterial.GitMaterial.Url, + GitRepository: gitRepository, MaterialName: ciMaterial.GitMaterial.Name, CheckoutPath: ciMaterial.GitMaterial.CheckoutPath, FetchSubmodules: ciMaterial.GitMaterial.FetchSubmodules, @@ -1040,7 +1050,6 @@ func (impl *HandlerServiceImpl) buildWfRequestForCiPipeline(pipeline *pipelineCo CaCert: ciMaterial.GitMaterial.GitProvider.CaCert, }, } - var err error ciProjectDetail, err = impl.updateCIProjectDetailWithCloningMode(pipeline.AppId, ciMaterial, ciProjectDetail) if err != nil { impl.Logger.Errorw("error, updateCIProjectDetailWithCloningMode", "pipelineId", pipeline.Id, "err", err) @@ -1147,6 +1156,13 @@ func (impl *HandlerServiceImpl) buildWfRequestForCiPipeline(pipeline *pipelineCo } } + // ci_template(_override).docker_repository may hold a @{{VAR_NAME}} reference (never + // resolved at save time, so a variable value update takes effect on the next build) + dockerRepository, _, err = impl.repoFieldVariableResolver.ResolveRepoFieldValue(scope, dockerRepository) + if err != nil { + impl.Logger.Errorw("error resolving container repository", "pipelineId", pipeline.Id, "err", err) + return nil, err + } if checkoutPath == "" { checkoutPath = "./" } diff --git a/pkg/pipeline/CiCdPipelineOrchestrator.go b/pkg/pipeline/CiCdPipelineOrchestrator.go index 82222aaffd..7c38abce3c 100644 --- a/pkg/pipeline/CiCdPipelineOrchestrator.go +++ b/pkg/pipeline/CiCdPipelineOrchestrator.go @@ -40,6 +40,9 @@ import ( "github.com/devtron-labs/devtron/pkg/deployment/gitOps/config" util4 "github.com/devtron-labs/devtron/pkg/pipeline/util" "github.com/devtron-labs/devtron/pkg/plugin" + "github.com/devtron-labs/devtron/pkg/resourceQualifiers" + "github.com/devtron-labs/devtron/pkg/variables" + variableEntity "github.com/devtron-labs/devtron/pkg/variables/repository" "github.com/devtron-labs/devtron/util/beHelper" "github.com/devtron-labs/devtron/util/sliceUtil" "golang.org/x/exp/slices" @@ -92,6 +95,9 @@ type CiCdPipelineOrchestrator interface { DeleteApp(appId int, userId int32) error CreateMaterials(createMaterialRequest *bean.CreateMaterialDTO) (*bean.CreateMaterialDTO, error) UpdateMaterial(updateMaterialRequest *bean.UpdateMaterialDTO) (*bean.UpdateMaterialDTO, error) + // ResyncGitMaterialToSensor re-resolves the material's @{{VAR_NAME}} URL (if any) and + // pushes the refreshed value to git-sensor - used after a scoped variable's value changes. + ResyncGitMaterialToSensor(materialId int) error CreateCiConf(createRequest *bean.CiConfigRequest, templateId int) (*bean.CiConfigRequest, error) CreateCDPipelines(pipelineRequest *bean.CDPipelineConfigObject, appId int, userId int32, tx *pg.Tx, appName string) (pipelineId int, err error) UpdateCDPipeline(pipelineRequest *bean.CDPipelineConfigObject, userId int32, tx *pg.Tx) (pipeline *pipelineConfig.Pipeline, err error) @@ -155,6 +161,8 @@ type CiCdPipelineOrchestratorImpl struct { workflowCacheConfig types.WorkflowCacheConfig chartReadService read2.ChartReadService globalEnvVariables *util2.GlobalEnvVariables + repoFieldVariableResolver variables.RepoFieldVariableResolver + variableEntityMappingService variables.VariableEntityMappingService } func NewCiCdPipelineOrchestrator( @@ -187,7 +195,9 @@ func NewCiCdPipelineOrchestrator( deploymentConfigService common.DeploymentConfigService, deploymentConfigReadService read.DeploymentConfigReadService, chartReadService read2.ChartReadService, - envVariables *util2.EnvironmentVariables) *CiCdPipelineOrchestratorImpl { + envVariables *util2.EnvironmentVariables, + repoFieldVariableResolver variables.RepoFieldVariableResolver, + variableEntityMappingService variables.VariableEntityMappingService) *CiCdPipelineOrchestratorImpl { _, workflowCacheConfig, err := types.GetCiConfigWithWorkflowCacheConfig() if err != nil { logger.Errorw("Error in getting workflow cache config, continuing with default values", "err", err) @@ -226,6 +236,8 @@ func NewCiCdPipelineOrchestrator( workflowCacheConfig: workflowCacheConfig, chartReadService: chartReadService, globalEnvVariables: envVariables.GlobalEnvVariables, + repoFieldVariableResolver: repoFieldVariableResolver, + variableEntityMappingService: variableEntityMappingService, } } @@ -1365,7 +1377,8 @@ func (impl CiCdPipelineOrchestratorImpl) DeleteApp(appId int, userId int32) erro impl.logger.Debug("deleting materials in git_sensor") for _, m := range materials { - err = impl.updateRepositoryToGitSensor(m, "", false) + // m.Active is already false above, so updateRepositoryToGitSensor skips URL resolution - scope is unused here + err = impl.updateRepositoryToGitSensor(m, "", false, resourceQualifiers.Scope{}) if err != nil { impl.logger.Errorw("error in updating to git-sensor", "err", err) return err @@ -1464,7 +1477,7 @@ func (impl CiCdPipelineOrchestratorImpl) CreateMaterials(createMaterialRequest * impl.logger.Errorw("error in committing tx Create material", "err", err, "materials", materials) return nil, err } - err = impl.addRepositoryToGitSensor(materials, "") + err = impl.addRepositoryToGitSensor(materials, "", resourceQualifiers.Scope{AppId: createMaterialRequest.AppId}) if err != nil { impl.logger.Errorw("error in updating to sensor", "err", err) return nil, err @@ -1491,7 +1504,7 @@ func (impl CiCdPipelineOrchestratorImpl) UpdateMaterial(updateMaterialDTO *bean. } err = impl.updateRepositoryToGitSensor(updatedMaterial, "", - updateMaterialDTO.Material.CreateBackup) + updateMaterialDTO.Material.CreateBackup, resourceQualifiers.Scope{AppId: updateMaterialDTO.AppId}) if err != nil { impl.logger.Errorw("error in updating to git-sensor", "err", err) return nil, err @@ -1499,11 +1512,60 @@ func (impl CiCdPipelineOrchestratorImpl) UpdateMaterial(updateMaterialDTO *bean. return updateMaterialDTO, nil } +// resolveGitMaterialUrl resolves a possible @{{VAR_NAME}} reference in the git material URL. +// git_material.url in the DB always stays as the user typed it - only the value sent to +// git-sensor is resolved, so Application Templates keep the placeholder intact on clone. +func (impl CiCdPipelineOrchestratorImpl) resolveGitMaterialUrl(scope resourceQualifiers.Scope, url string) (string, error) { + resolvedUrl, _, err := impl.repoFieldVariableResolver.ResolveRepoFieldValue(scope, url) + if err != nil { + return "", fmt.Errorf("error resolving git material url: %w", err) + } + return resolvedUrl, nil +} + +// trackRepoFieldVariableMapping records (or clears) which scoped variable a Git Material's +// URL references, so a variable value change can find and re-sync every affected material. +func (impl CiCdPipelineOrchestratorImpl) trackRepoFieldVariableMapping(tx *pg.Tx, materialId int, url string, userId int32) error { + var variableNames []string + if variableName, ok := variables.ExtractVariableName(url); ok { + variableNames = []string{variableName} + } + entity := variableEntity.Entity{EntityType: variableEntity.EntityTypeGitMaterial, EntityId: materialId} + err := impl.variableEntityMappingService.UpdateVariablesForEntity(variableNames, entity, userId, tx) + if err != nil { + impl.logger.Errorw("error in tracking repo field variable mapping", "materialId", materialId, "err", err) + return err + } + return nil +} + +func (impl CiCdPipelineOrchestratorImpl) ResyncGitMaterialToSensor(materialId int) error { + material, err := impl.materialRepository.FindById(materialId) + if err != nil { + impl.logger.Errorw("error in finding material for resync", "materialId", materialId, "err", err) + return err + } + if !material.Active { + return nil + } + scope := resourceQualifiers.Scope{AppId: material.AppId} + return impl.updateRepositoryToGitSensor(material, "", false, scope) +} + func (impl CiCdPipelineOrchestratorImpl) updateRepositoryToGitSensor(material *repository6.GitMaterial, - cloningMode string, createBackup bool) error { + cloningMode string, createBackup bool, scope resourceQualifiers.Scope) error { + // deletion only needs the Deleted flag - skip resolution so a since-deleted variable can't block a delete + resolvedUrl := material.Url + var err error + if material.Active { + resolvedUrl, err = impl.resolveGitMaterialUrl(scope, material.Url) + if err != nil { + return err + } + } sensorMaterial := &gitSensor.GitMaterial{ Name: material.Name, - Url: material.Url, + Url: resolvedUrl, Id: material.Id, GitProviderId: material.GitProviderId, CheckoutLocation: material.CheckoutPath, @@ -1523,12 +1585,16 @@ func (impl CiCdPipelineOrchestratorImpl) updateRepositoryToGitSensor(material *r return impl.GitSensorClient.UpdateRepo(ctx, sensorMaterial) } -func (impl CiCdPipelineOrchestratorImpl) addRepositoryToGitSensor(materials []*bean.GitMaterial, cloningMode string) error { +func (impl CiCdPipelineOrchestratorImpl) addRepositoryToGitSensor(materials []*bean.GitMaterial, cloningMode string, scope resourceQualifiers.Scope) error { var sensorMaterials []*gitSensor.GitMaterial for _, material := range materials { + resolvedUrl, err := impl.resolveGitMaterialUrl(scope, material.Url) + if err != nil { + return err + } sensorMaterial := &gitSensor.GitMaterial{ Name: material.Name, - Url: material.Url, + Url: resolvedUrl, Id: material.Id, GitProviderId: material.GitProviderId, Deleted: false, @@ -1690,6 +1756,11 @@ func (impl CiCdPipelineOrchestratorImpl) updateMaterial(tx *pg.Tx, updateMateria return nil, err } + err = impl.trackRepoFieldVariableMapping(tx, currentMaterial.Id, currentMaterial.Url, updateMaterialDTO.UserId) + if err != nil { + return nil, err + } + err = impl.gitMaterialHistoryService.CreateMaterialHistory(tx, currentMaterial) return currentMaterial, nil @@ -1714,6 +1785,10 @@ func (impl CiCdPipelineOrchestratorImpl) createMaterial(tx *pg.Tx, inputMaterial impl.logger.Errorw("error in saving material", "material", material, "err", err) return nil, err } + err = impl.trackRepoFieldVariableMapping(tx, material.Id, material.Url, userId) + if err != nil { + return nil, err + } err = impl.gitMaterialHistoryService.CreateMaterialHistory(tx, material) return material, err } diff --git a/pkg/pipeline/GitMaterialVariableSyncService.go b/pkg/pipeline/GitMaterialVariableSyncService.go new file mode 100644 index 0000000000..ab307e5c94 --- /dev/null +++ b/pkg/pipeline/GitMaterialVariableSyncService.go @@ -0,0 +1,62 @@ +/* + * Copyright (c) 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 pipeline + +import ( + "github.com/devtron-labs/devtron/pkg/variables" + variableEntity "github.com/devtron-labs/devtron/pkg/variables/repository" + "go.uber.org/zap" +) + +// GitMaterialVariableSyncService re-syncs every Git Material whose URL references a scoped +// variable to git-sensor. Called after the variable set changes (CreateVariables does a full +// delete-then-recreate of all variables, so any of them could be the one a material uses). +type GitMaterialVariableSyncService interface { + ResyncGitMaterialsForVariableChange() error +} + +type GitMaterialVariableSyncServiceImpl struct { + logger *zap.SugaredLogger + variableEntityMappingService variables.VariableEntityMappingService + ciCdPipelineOrchestrator CiCdPipelineOrchestrator +} + +func NewGitMaterialVariableSyncServiceImpl(logger *zap.SugaredLogger, + variableEntityMappingService variables.VariableEntityMappingService, + ciCdPipelineOrchestrator CiCdPipelineOrchestrator) *GitMaterialVariableSyncServiceImpl { + return &GitMaterialVariableSyncServiceImpl{ + logger: logger, + variableEntityMappingService: variableEntityMappingService, + ciCdPipelineOrchestrator: ciCdPipelineOrchestrator, + } +} + +func (impl *GitMaterialVariableSyncServiceImpl) ResyncGitMaterialsForVariableChange() error { + materialIds, err := impl.variableEntityMappingService.GetDistinctEntityIdsByType(variableEntity.EntityTypeGitMaterial) + if err != nil { + impl.logger.Errorw("error in finding git materials referencing scoped variables", "err", err) + return err + } + for _, materialId := range materialIds { + err = impl.ciCdPipelineOrchestrator.ResyncGitMaterialToSensor(materialId) + if err != nil { + // keep re-syncing the rest - one bad/stale mapping shouldn't block the others + impl.logger.Errorw("error re-syncing git material after variable change", "materialId", materialId, "err", err) + } + } + return nil +} diff --git a/pkg/resourceQualifiers/constants.go b/pkg/resourceQualifiers/constants.go index bcc16eb45a..6427f017cb 100644 --- a/pkg/resourceQualifiers/constants.go +++ b/pkg/resourceQualifiers/constants.go @@ -38,3 +38,14 @@ var SystemVariables = []SystemVariableName{ const AllExistingAndFutureNonProdEnvsInt = -1 const AllExistingAndFutureProdEnvsInt = -2 + +// IsSystemVariable reports whether name refers to a system variable, as opposed to a +// user-defined variable. +func IsSystemVariable(name string) bool { + for _, systemVariable := range SystemVariables { + if name == string(systemVariable) { + return true + } + } + return false +} diff --git a/pkg/resourceQualifiers/constants_test.go b/pkg/resourceQualifiers/constants_test.go new file mode 100644 index 0000000000..5d9b2ee017 --- /dev/null +++ b/pkg/resourceQualifiers/constants_test.go @@ -0,0 +1,42 @@ +/* + * Copyright (c) 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 resourceQualifiers + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestIsSystemVariable(t *testing.T) { + cases := []struct { + name string + variable string + want bool + }{ + {"fixed system variable", "DEVTRON_APP_NAME", true}, + {"another fixed system variable", "DEVTRON_ENV_NAME", true}, + {"user-defined variable", "FULL_GIT_URL", false}, + {"user-defined variable starting with DEVTRON", "DEVTRON_CUSTOM_THING", false}, + {"empty string", "", false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + assert.Equal(t, c.want, IsSystemVariable(c.variable)) + }) + } +} diff --git a/pkg/variables/RepoFieldVariableResolver.go b/pkg/variables/RepoFieldVariableResolver.go new file mode 100644 index 0000000000..fc36a9bc74 --- /dev/null +++ b/pkg/variables/RepoFieldVariableResolver.go @@ -0,0 +1,98 @@ +/* + * Copyright (c) 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 variables + +import ( + "fmt" + "regexp" + "strings" + + "github.com/devtron-labs/devtron/pkg/resourceQualifiers" + "go.uber.org/zap" +) + +// fullVariableReferenceRegex matches a field value that is exactly one @{{VAR_NAME}} token and nothing else. +var fullVariableReferenceRegex = regexp.MustCompile(`^@\{\{([A-Za-z0-9_]+)\}\}$`) + +// IsFullVariableReference reports whether fieldValue is exactly one @{{VAR_NAME}} token, so +// callers (e.g. request validation) can skip literal-value format checks without a DB lookup. +func IsFullVariableReference(fieldValue string) bool { + return fullVariableReferenceRegex.MatchString(fieldValue) +} + +// ExtractVariableName returns the variable name if fieldValue is a full @{{VAR_NAME}} +// reference, without doing any DB lookup - used to track which entities (e.g. Git Materials) +// reference which variables, independent of whether the reference currently resolves. +func ExtractVariableName(fieldValue string) (string, bool) { + matches := fullVariableReferenceRegex.FindStringSubmatch(fieldValue) + if matches == nil { + return "", false + } + return matches[1], true +} + +// RepoFieldVariableResolver resolves a single, full @{{VAR_NAME}} reference used in the Git +// Repository URL and Container Repository fields. Only user-defined variables are supported - +// scoped variables in this version only support Global scope, which fits these fields anyway +// since neither has any app/env/cluster context at its resolution point. +type RepoFieldVariableResolver interface { + // ResolveRepoFieldValue returns fieldValue unchanged if it isn't a variable reference, + // or its resolved value if it is a valid one. variableName is empty when nothing was resolved. + ResolveRepoFieldValue(scope resourceQualifiers.Scope, fieldValue string) (resolvedValue string, variableName string, err error) +} + +type RepoFieldVariableResolverImpl struct { + logger *zap.SugaredLogger + scopedVariableService ScopedVariableService +} + +func NewRepoFieldVariableResolverImpl(logger *zap.SugaredLogger, scopedVariableService ScopedVariableService) *RepoFieldVariableResolverImpl { + return &RepoFieldVariableResolverImpl{ + logger: logger, + scopedVariableService: scopedVariableService, + } +} + +func (impl *RepoFieldVariableResolverImpl) ResolveRepoFieldValue(scope resourceQualifiers.Scope, fieldValue string) (string, string, error) { + // plain literal value, nothing to resolve + if !strings.Contains(fieldValue, "@{{") { + return fieldValue, "", nil + } + + matches := fullVariableReferenceRegex.FindStringSubmatch(fieldValue) + if matches == nil { + // contains "@{{" but isn't a single, full @{{VAR_NAME}} token - not supported here + return "", "", fmt.Errorf("only a single full variable reference like @{{VAR_NAME}} is supported, not partial text or multiple variables") + } + variableName := matches[1] + + if resourceQualifiers.IsSystemVariable(variableName) { + return "", "", fmt.Errorf("system variable %q is not supported here, only user-defined variables are allowed", variableName) + } + + scopedVariables, err := impl.scopedVariableService.GetScopedVariables(scope, []string{variableName}, true) + if err != nil { + impl.logger.Errorw("error resolving repo field variable", "variableName", variableName, "scope", scope, "err", err) + return "", "", fmt.Errorf("error resolving variable %q: %w", variableName, err) + } + if len(scopedVariables) == 0 { + return "", "", fmt.Errorf("variable %q not found, or has no value defined", variableName) + } + + resolvedValue := scopedVariables[0].VariableValue.StringValue() + return resolvedValue, variableName, nil +} diff --git a/pkg/variables/RepoFieldVariableResolver_test.go b/pkg/variables/RepoFieldVariableResolver_test.go new file mode 100644 index 0000000000..be5f99d6ce --- /dev/null +++ b/pkg/variables/RepoFieldVariableResolver_test.go @@ -0,0 +1,134 @@ +/* + * Copyright (c) 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 variables + +import ( + "errors" + "testing" + + "github.com/devtron-labs/devtron/internal/util" + "github.com/devtron-labs/devtron/pkg/resourceQualifiers" + "github.com/devtron-labs/devtron/pkg/variables/models" + "github.com/stretchr/testify/assert" +) + +// fakeScopedVariableService resolves variables from a canned name->value map, and records +// the exact scope it was last called with so tests can assert env/cluster context is stripped. +type fakeScopedVariableService struct { + ScopedVariableService + definedVariables map[string]string + err error + lastScope resourceQualifiers.Scope +} + +func (f *fakeScopedVariableService) GetScopedVariables(scope resourceQualifiers.Scope, varNames []string, unmaskSensitiveData bool) ([]*models.ScopedVariableData, error) { + f.lastScope = scope + if f.err != nil { + return nil, f.err + } + scopedVariableData := make([]*models.ScopedVariableData, 0) + for _, name := range varNames { + if value, ok := f.definedVariables[name]; ok { + scopedVariableData = append(scopedVariableData, &models.ScopedVariableData{ + VariableName: name, + VariableValue: &models.VariableValue{Value: value}, + }) + } + } + return scopedVariableData, nil +} + +func newResolverForTest(t *testing.T, svc ScopedVariableService) *RepoFieldVariableResolverImpl { + logger, err := util.NewSugardLogger() + assert.Nil(t, err) + return NewRepoFieldVariableResolverImpl(logger, svc) +} + +func TestResolveRepoFieldValue(t *testing.T) { + svc := &fakeScopedVariableService{ + definedVariables: map[string]string{ + "FULL_GIT_URL": "https://github.com/org/repo.git", + }, + } + resolver := newResolverForTest(t, svc) + scope := resourceQualifiers.Scope{AppId: 1} + + t.Run("plain literal passes through unchanged", func(t *testing.T) { + resolved, varName, err := resolver.ResolveRepoFieldValue(scope, "https://github.com/org/literal.git") + assert.Nil(t, err) + assert.Equal(t, "https://github.com/org/literal.git", resolved) + assert.Empty(t, varName) + }) + + t.Run("full match resolves to defined value", func(t *testing.T) { + resolved, varName, err := resolver.ResolveRepoFieldValue(scope, "@{{FULL_GIT_URL}}") + assert.Nil(t, err) + assert.Equal(t, "https://github.com/org/repo.git", resolved) + assert.Equal(t, "FULL_GIT_URL", varName) + }) + + t.Run("undefined variable is rejected", func(t *testing.T) { + _, _, err := resolver.ResolveRepoFieldValue(scope, "@{{NOT_DEFINED}}") + assert.NotNil(t, err) + assert.Contains(t, err.Error(), "not found") + }) + + t.Run("partial match with surrounding text is rejected", func(t *testing.T) { + _, _, err := resolver.ResolveRepoFieldValue(scope, "https://github.com/@{{FULL_GIT_URL}}/repo.git") + assert.NotNil(t, err) + assert.Contains(t, err.Error(), "single full variable reference") + }) + + t.Run("multiple tokens in one field is rejected", func(t *testing.T) { + _, _, err := resolver.ResolveRepoFieldValue(scope, "@{{A}}@{{FULL_GIT_URL}}") + assert.NotNil(t, err) + assert.Contains(t, err.Error(), "single full variable reference") + }) + + t.Run("fixed system variable is rejected", func(t *testing.T) { + _, _, err := resolver.ResolveRepoFieldValue(scope, "@{{DEVTRON_APP_NAME}}") + assert.NotNil(t, err) + assert.Contains(t, err.Error(), "system variable") + }) + + t.Run("underlying resolution error is propagated", func(t *testing.T) { + failingSvc := &fakeScopedVariableService{err: errors.New("db unavailable")} + failingResolver := newResolverForTest(t, failingSvc) + _, _, err := failingResolver.ResolveRepoFieldValue(scope, "@{{FULL_GIT_URL}}") + assert.NotNil(t, err) + assert.Contains(t, err.Error(), "db unavailable") + }) +} + +func TestIsFullVariableReference(t *testing.T) { + assert.True(t, IsFullVariableReference("@{{FULL_GIT_URL}}")) + assert.False(t, IsFullVariableReference("https://github.com/@{{GIT_ORG}}/repo.git")) + assert.False(t, IsFullVariableReference("https://github.com/org/repo.git")) + assert.False(t, IsFullVariableReference("@{{A}}@{{B}}")) +} + +func TestExtractVariableName(t *testing.T) { + name, ok := ExtractVariableName("@{{FULL_GIT_URL}}") + assert.True(t, ok) + assert.Equal(t, "FULL_GIT_URL", name) + + _, ok = ExtractVariableName("https://github.com/org/repo.git") + assert.False(t, ok) + + _, ok = ExtractVariableName("https://github.com/@{{GIT_ORG}}/repo.git") + assert.False(t, ok) +} diff --git a/pkg/variables/VariableEntityMappingService.go b/pkg/variables/VariableEntityMappingService.go index 8835e2a514..804fc896e5 100644 --- a/pkg/variables/VariableEntityMappingService.go +++ b/pkg/variables/VariableEntityMappingService.go @@ -30,6 +30,10 @@ type VariableEntityMappingService interface { UpdateVariablesForEntity(variableNames []string, entity repository.Entity, userId int32, tx *pg.Tx) error GetAllMappingsForEntities(entities []repository.Entity) (map[repository.Entity][]string, error) DeleteMappingsForEntities(entities []repository.Entity, userId int32, tx *pg.Tx) error + // GetDistinctEntityIdsByType returns every entity id of entityType that references any + // variable - e.g. every Git Material with a @{{VAR_NAME}} URL, for re-sync after a + // variable value changes. + GetDistinctEntityIdsByType(entityType repository.EntityType) ([]int, error) } type VariableEntityMappingServiceImpl struct { @@ -135,6 +139,15 @@ func (impl VariableEntityMappingServiceImpl) GetAllMappingsForEntities(entities return entityIdToVariableNames, nil } +func (impl VariableEntityMappingServiceImpl) GetDistinctEntityIdsByType(entityType repository.EntityType) ([]int, error) { + entityIds, err := impl.variableEntityMappingRepository.GetDistinctEntityIdsByType(entityType) + if err != nil { + impl.logger.Errorw("error in getting distinct entity ids by type", "entityType", entityType, "err", err) + return nil, err + } + return entityIds, nil +} + func (impl VariableEntityMappingServiceImpl) DeleteMappingsForEntities(entities []repository.Entity, userId int32, tx *pg.Tx) error { err := impl.variableEntityMappingRepository.DeleteAllVariablesForEntities(tx, entities, userId) if err != nil { diff --git a/pkg/variables/repository/VariableEntityDTO.go b/pkg/variables/repository/VariableEntityDTO.go index d9eacf705e..400eb8bc48 100644 --- a/pkg/variables/repository/VariableEntityDTO.go +++ b/pkg/variables/repository/VariableEntityDTO.go @@ -45,6 +45,9 @@ const ( EntityTypeConfigMapEnvLevel EntityType = 5 EntityTypeSecretAppLevel EntityType = 6 EntityTypeSecretEnvLevel EntityType = 7 + // EntityTypeGitMaterial tracks which Git Materials reference a scoped variable in their + // URL, so a variable value change can re-sync the affected materials to git-sensor. + EntityTypeGitMaterial EntityType = 9 ) func GetEntity(entityId int, entityType EntityType) Entity { diff --git a/pkg/variables/repository/VariableEntityMappingRepository.go b/pkg/variables/repository/VariableEntityMappingRepository.go index ddbf2cb0c1..14e64dc495 100644 --- a/pkg/variables/repository/VariableEntityMappingRepository.go +++ b/pkg/variables/repository/VariableEntityMappingRepository.go @@ -30,6 +30,10 @@ type VariableEntityMappingRepository interface { SaveVariableEntityMappings(tx *pg.Tx, mappings []*VariableEntityMapping) error DeleteAllVariablesForEntities(tx *pg.Tx, entities []Entity, userId int32) error DeleteVariablesForEntity(tx *pg.Tx, variableIDs []string, entity Entity, userId int32) error + // GetDistinctEntityIdsByType returns every non-deleted entity id of entityType that + // references any variable - used to find every Git Material that needs re-syncing + // after a scoped variable's value changes. + GetDistinctEntityIdsByType(entityType EntityType) ([]int, error) } func NewVariableEntityMappingRepository(logger *zap.SugaredLogger, dbConnection *pg.DB, TransactionUtilImpl *sql.TransactionUtilImpl) *VariableEntityMappingRepositoryImpl { @@ -90,6 +94,20 @@ func (impl *VariableEntityMappingRepositoryImpl) DeleteVariablesForEntity(tx *pg return nil } +func (impl *VariableEntityMappingRepositoryImpl) GetDistinctEntityIdsByType(entityType EntityType) ([]int, error) { + var entityIds []int + err := impl.dbConnection.Model((*VariableEntityMapping)(nil)). + ColumnExpr("DISTINCT entity_id"). + Where("entity_type = ?", entityType). + Where("is_deleted = ?", false). + Select(&entityIds) + if err != nil && err != pg.ErrNoRows { + impl.logger.Errorw("err in getting distinct entity ids by type", "entityType", entityType, "err", err) + return nil, err + } + return entityIds, nil +} + func (impl *VariableEntityMappingRepositoryImpl) DeleteAllVariablesForEntities(tx *pg.Tx, entities []Entity, userId int32) error { var connection orm.DB diff --git a/wire_gen.go b/wire_gen.go index e3518a51bb..fd4f87b12c 100644 --- a/wire_gen.go +++ b/wire_gen.go @@ -672,6 +672,7 @@ func InitializeApp() (*App, error) { materialRepositoryImpl := repository23.NewMaterialRepositoryImpl(db) gitMaterialReadServiceImpl := read15.NewGitMaterialReadServiceImpl(sugaredLogger, materialRepositoryImpl) appCrudOperationServiceImpl := app2.NewAppCrudOperationServiceImpl(appLabelRepositoryImpl, sugaredLogger, appRepositoryImpl, userRepositoryImpl, installedAppRepositoryImpl, genericNoteServiceImpl, installedAppDBServiceImpl, crudOperationServiceConfig, dbMigrationServiceImpl, gitMaterialReadServiceImpl) + repoFieldVariableResolverImpl := variables.NewRepoFieldVariableResolverImpl(sugaredLogger, scopedVariableServiceImpl) imageTagRepositoryImpl := repository2.NewImageTagRepository(db, sugaredLogger) customTagServiceImpl := pipeline.NewCustomTagService(sugaredLogger, imageTagRepositoryImpl) clientConfig, err := gitSensor.GetConfig() @@ -699,7 +700,7 @@ func InitializeApp() (*App, error) { deploymentTemplateHistoryServiceImpl := deploymentTemplate.NewDeploymentTemplateHistoryServiceImpl(sugaredLogger, deploymentTemplateHistoryRepositoryImpl, pipelineRepositoryImpl, chartRepositoryImpl, userServiceImpl, cdWorkflowRepositoryImpl, scopedVariableManagerImpl, deployedAppMetricsServiceImpl, chartRefServiceImpl) chartReadServiceImpl := read16.NewChartReadServiceImpl(sugaredLogger, chartRepositoryImpl, deploymentConfigServiceImpl, deployedAppMetricsServiceImpl, gitOpsConfigReadServiceImpl, chartRefReadServiceImpl) chartServiceImpl := chart.NewChartServiceImpl(chartRepositoryImpl, sugaredLogger, chartTemplateServiceImpl, chartRepoRepositoryImpl, appRepositoryImpl, mergeUtil, envConfigOverrideRepositoryImpl, pipelineConfigRepositoryImpl, environmentRepositoryImpl, deploymentTemplateHistoryServiceImpl, scopedVariableManagerImpl, deployedAppMetricsServiceImpl, chartRefServiceImpl, gitOpsConfigReadServiceImpl, deploymentConfigServiceImpl, envConfigOverrideReadServiceImpl, chartReadServiceImpl) - ciCdPipelineOrchestratorImpl := pipeline.NewCiCdPipelineOrchestrator(appRepositoryImpl, sugaredLogger, materialRepositoryImpl, pipelineRepositoryImpl, ciPipelineRepositoryImpl, ciPipelineMaterialRepositoryImpl, cdWorkflowRepositoryImpl, clientImpl, ciCdConfig, appWorkflowRepositoryImpl, environmentRepositoryImpl, attributesServiceImpl, appCrudOperationServiceImpl, userAuthServiceImpl, prePostCdScriptHistoryServiceImpl, pipelineStageServiceImpl, gitMaterialHistoryServiceImpl, ciPipelineHistoryServiceImpl, ciTemplateReadServiceImpl, ciTemplateServiceImpl, dockerArtifactStoreRepositoryImpl, ciArtifactRepositoryImpl, configMapServiceImpl, customTagServiceImpl, genericNoteServiceImpl, chartServiceImpl, transactionUtilImpl, gitOpsConfigReadServiceImpl, deploymentConfigServiceImpl, deploymentConfigReadServiceImpl, chartReadServiceImpl, environmentVariables) + ciCdPipelineOrchestratorImpl := pipeline.NewCiCdPipelineOrchestrator(appRepositoryImpl, sugaredLogger, materialRepositoryImpl, pipelineRepositoryImpl, ciPipelineRepositoryImpl, ciPipelineMaterialRepositoryImpl, cdWorkflowRepositoryImpl, clientImpl, ciCdConfig, appWorkflowRepositoryImpl, environmentRepositoryImpl, attributesServiceImpl, appCrudOperationServiceImpl, userAuthServiceImpl, prePostCdScriptHistoryServiceImpl, pipelineStageServiceImpl, gitMaterialHistoryServiceImpl, ciPipelineHistoryServiceImpl, ciTemplateReadServiceImpl, ciTemplateServiceImpl, dockerArtifactStoreRepositoryImpl, ciArtifactRepositoryImpl, configMapServiceImpl, customTagServiceImpl, genericNoteServiceImpl, chartServiceImpl, transactionUtilImpl, gitOpsConfigReadServiceImpl, deploymentConfigServiceImpl, deploymentConfigReadServiceImpl, chartReadServiceImpl, environmentVariables, repoFieldVariableResolverImpl, variableEntityMappingServiceImpl) pluginInputVariableParserImpl := pipeline.NewPluginInputVariableParserImpl(sugaredLogger, dockerRegistryConfigImpl, customTagServiceImpl) ciServiceImpl := pipeline.NewCiServiceImpl(sugaredLogger, workFlowStageStatusServiceImpl, eventRESTClientImpl, eventSimpleFactoryImpl, ciWorkflowRepositoryImpl, ciPipelineRepositoryImpl, transactionUtilImpl, workflowStatusLatestServiceImpl) ciLogServiceImpl, err := pipeline.NewCiLogServiceImpl(sugaredLogger, k8sServiceImpl) @@ -707,7 +708,7 @@ func InitializeApp() (*App, error) { return nil, err } blobStorageConfigServiceImpl := pipeline.NewBlobStorageConfigServiceImpl(sugaredLogger, k8sServiceImpl, ciCdConfig) - handlerServiceImpl := trigger.NewHandlerServiceImpl(sugaredLogger, workflowServiceImpl, ciPipelineMaterialRepositoryImpl, ciPipelineRepositoryImpl, ciArtifactRepositoryImpl, pipelineStageServiceImpl, userServiceImpl, ciTemplateReadServiceImpl, appCrudOperationServiceImpl, environmentRepositoryImpl, appRepositoryImpl, scopedVariableManagerImpl, customTagServiceImpl, ciCdPipelineOrchestratorImpl, attributesServiceImpl, pluginInputVariableParserImpl, globalPluginServiceImpl, ciServiceImpl, ciWorkflowRepositoryImpl, clientImpl, ciLogServiceImpl, blobStorageConfigServiceImpl, clusterServiceImplExtended, environmentServiceImpl, k8sServiceImpl, runnable, workflowTriggerAuditServiceImpl) + handlerServiceImpl := trigger.NewHandlerServiceImpl(sugaredLogger, workflowServiceImpl, ciPipelineMaterialRepositoryImpl, ciPipelineRepositoryImpl, ciArtifactRepositoryImpl, pipelineStageServiceImpl, userServiceImpl, ciTemplateReadServiceImpl, appCrudOperationServiceImpl, environmentRepositoryImpl, appRepositoryImpl, scopedVariableManagerImpl, repoFieldVariableResolverImpl, customTagServiceImpl, ciCdPipelineOrchestratorImpl, attributesServiceImpl, pluginInputVariableParserImpl, globalPluginServiceImpl, ciServiceImpl, ciWorkflowRepositoryImpl, clientImpl, ciLogServiceImpl, blobStorageConfigServiceImpl, clusterServiceImplExtended, environmentServiceImpl, k8sServiceImpl, runnable, workflowTriggerAuditServiceImpl) gitWebhookServiceImpl := gitWebhook.NewGitWebhookServiceImpl(sugaredLogger, gitWebhookRepositoryImpl, handlerServiceImpl) gitWebhookRestHandlerImpl := restHandler.NewGitWebhookRestHandlerImpl(sugaredLogger, gitWebhookServiceImpl) ecrConfig, err := pipeline.GetEcrConfig() @@ -1075,7 +1076,8 @@ func InitializeApp() (*App, error) { rbacRoleServiceImpl := user.NewRbacRoleServiceImpl(sugaredLogger, rbacRoleDataRepositoryImpl) rbacRoleRestHandlerImpl := user2.NewRbacRoleHandlerImpl(sugaredLogger, validate, rbacRoleServiceImpl, userServiceImpl, enforcerImpl, enforcerUtilImpl) rbacRoleRouterImpl := user2.NewRbacRoleRouterImpl(sugaredLogger, validate, rbacRoleRestHandlerImpl) - scopedVariableRestHandlerImpl := scopedVariable.NewScopedVariableRestHandlerImpl(sugaredLogger, userServiceImpl, validate, pipelineBuilderImpl, enforcerUtilImpl, enforcerImpl, scopedVariableServiceImpl) + gitMaterialVariableSyncServiceImpl := pipeline.NewGitMaterialVariableSyncServiceImpl(sugaredLogger, variableEntityMappingServiceImpl, ciCdPipelineOrchestratorImpl) + scopedVariableRestHandlerImpl := scopedVariable.NewScopedVariableRestHandlerImpl(sugaredLogger, userServiceImpl, validate, pipelineBuilderImpl, enforcerUtilImpl, enforcerImpl, scopedVariableServiceImpl, gitMaterialVariableSyncServiceImpl, runnable) scopedVariableRouterImpl := router.NewScopedVariableRouterImpl(scopedVariableRestHandlerImpl) ciTriggerCronConfig, err := cron2.GetCiTriggerCronConfig() if err != nil { From de5cb540996c6b66689679abb3d9bee874b7d9eb Mon Sep 17 00:00:00 2001 From: Bhupesh Varshney Date: Wed, 16 Sep 2026 13:24:53 +0530 Subject: [PATCH 2/2] fix: resolve scoped variables before ECR repo creation and git-sensor sync --- pkg/pipeline/CiCdPipelineOrchestrator.go | 55 +++++++++++++++++++++--- 1 file changed, 48 insertions(+), 7 deletions(-) diff --git a/pkg/pipeline/CiCdPipelineOrchestrator.go b/pkg/pipeline/CiCdPipelineOrchestrator.go index 7c38abce3c..2c757bc348 100644 --- a/pkg/pipeline/CiCdPipelineOrchestrator.go +++ b/pkg/pipeline/CiCdPipelineOrchestrator.go @@ -627,9 +627,14 @@ func (impl CiCdPipelineOrchestratorImpl) PatchMaterialValue(createRequest *bean. } savedTemplateOverride := savedTemplateOverrideBean.CiTemplateOverride - err = impl.createDockerRepoIfNeeded(createRequest.DockerConfigOverride.DockerRegistry, createRequest.DockerConfigOverride.DockerRepository) + resolvedDockerRepository, err := impl.resolveDockerRepositoryForEcr(resourceQualifiers.Scope{AppId: createRequest.AppId}, createRequest.DockerConfigOverride.DockerRepository) if err != nil { - impl.logger.Errorw("error, createDockerRepoIfNeeded", "err", err, "dockerRegistryId", createRequest.DockerConfigOverride.DockerRegistry, "dockerRegistry", createRequest.DockerConfigOverride.DockerRepository) + impl.logger.Errorw("error resolving docker repository", "err", err, "dockerRepository", createRequest.DockerConfigOverride.DockerRepository) + return nil, err + } + err = impl.createDockerRepoIfNeeded(createRequest.DockerConfigOverride.DockerRegistry, resolvedDockerRepository) + if err != nil { + impl.logger.Errorw("error, createDockerRepoIfNeeded", "err", err, "dockerRegistryId", createRequest.DockerConfigOverride.DockerRegistry, "dockerRegistry", resolvedDockerRepository) return nil, err } if savedTemplateOverride != nil && savedTemplateOverride.Id > 0 { @@ -932,6 +937,7 @@ func (impl CiCdPipelineOrchestratorImpl) deleteCiEnvMapping(tx *pg.Tx, ciPipelin return nil } func (impl CiCdPipelineOrchestratorImpl) CreateCiConf(createRequest *bean.CiConfigRequest, templateId int) (*bean.CiConfigRequest, error) { + repoFieldScope := resourceQualifiers.Scope{AppId: createRequest.AppId} //save pipeline in db start for _, ciPipeline := range createRequest.CiPipelines { argByte, err := json.Marshal(ciPipeline.DockerArgs) @@ -1133,10 +1139,16 @@ func (impl CiCdPipelineOrchestratorImpl) CreateCiConf(createRequest *bean.CiConf UserId: createRequest.UserId, } if !ciPipeline.IsExternal { //pipeline is not [linked, webhook] and overridden, then create template override - err = impl.createDockerRepoIfNeeded(ciPipeline.DockerConfigOverride.DockerRegistry, ciPipeline.DockerConfigOverride.DockerRepository) + resolvedDockerRepository, resolveErr := impl.resolveDockerRepositoryForEcr(repoFieldScope, ciPipeline.DockerConfigOverride.DockerRepository) // silently ignoring the error, since we don't want to fail the pipeline creation - if err != nil { - impl.logger.Warnw("error, createDockerRepoIfNeeded", "err", err, "dockerRegistryId", ciPipeline.DockerConfigOverride.DockerRegistry, "dockerRegistry", ciPipeline.DockerConfigOverride.DockerRepository) + if resolveErr != nil { + impl.logger.Warnw("error resolving docker repository", "err", resolveErr, "dockerRepository", ciPipeline.DockerConfigOverride.DockerRepository) + } else { + err = impl.createDockerRepoIfNeeded(ciPipeline.DockerConfigOverride.DockerRegistry, resolvedDockerRepository) + // silently ignoring the error, since we don't want to fail the pipeline creation + if err != nil { + impl.logger.Warnw("error, createDockerRepoIfNeeded", "err", err, "dockerRegistryId", ciPipeline.DockerConfigOverride.DockerRegistry, "dockerRegistry", resolvedDockerRepository) + } } err := impl.ciTemplateService.Save(ciTemplateBean) if err != nil { @@ -1470,6 +1482,15 @@ func (impl CiCdPipelineOrchestratorImpl) CreateMaterials(createMaterialRequest * } materials = append(materials, inputMaterial) } + repoFieldScope := resourceQualifiers.Scope{AppId: createMaterialRequest.AppId} + // validate every @{{VAR_NAME}} reference resolves before committing, so a typo'd/undefined + // variable can't leave a Git Material row with no matching git-sensor entry + for _, material := range materials { + if _, err = impl.resolveGitMaterialUrl(repoFieldScope, material.Url); err != nil { + impl.logger.Errorw("error validating git material url", "err", err) + return nil, err + } + } // moving transaction before addRepositoryToGitSensor as commiting transaction after addRepositoryToGitSensor was causing problems // in case request was cancelled data was getting saved in git sensor but not getting saved in orchestrator db. Same is done in update flow. err = impl.transactionManager.CommitTx(tx) @@ -1477,7 +1498,7 @@ func (impl CiCdPipelineOrchestratorImpl) CreateMaterials(createMaterialRequest * impl.logger.Errorw("error in committing tx Create material", "err", err, "materials", materials) return nil, err } - err = impl.addRepositoryToGitSensor(materials, "", resourceQualifiers.Scope{AppId: createMaterialRequest.AppId}) + err = impl.addRepositoryToGitSensor(materials, "", repoFieldScope) if err != nil { impl.logger.Errorw("error in updating to sensor", "err", err) return nil, err @@ -1497,6 +1518,15 @@ func (impl CiCdPipelineOrchestratorImpl) UpdateMaterial(updateMaterialDTO *bean. impl.logger.Errorw("err", "err", err) return nil, err } + repoFieldScope := resourceQualifiers.Scope{AppId: updateMaterialDTO.AppId} + // validate the @{{VAR_NAME}} reference resolves before committing, so a typo'd/undefined + // variable can't leave a Git Material row with no matching git-sensor entry + if updatedMaterial.Active { + if _, err = impl.resolveGitMaterialUrl(repoFieldScope, updatedMaterial.Url); err != nil { + impl.logger.Errorw("error validating git material url", "err", err) + return nil, err + } + } err = impl.transactionManager.CommitTx(tx) if err != nil { impl.logger.Errorw("error in committing tx Create material", "err", err) @@ -1504,7 +1534,7 @@ func (impl CiCdPipelineOrchestratorImpl) UpdateMaterial(updateMaterialDTO *bean. } err = impl.updateRepositoryToGitSensor(updatedMaterial, "", - updateMaterialDTO.Material.CreateBackup, resourceQualifiers.Scope{AppId: updateMaterialDTO.AppId}) + updateMaterialDTO.Material.CreateBackup, repoFieldScope) if err != nil { impl.logger.Errorw("error in updating to git-sensor", "err", err) return nil, err @@ -1512,6 +1542,17 @@ func (impl CiCdPipelineOrchestratorImpl) UpdateMaterial(updateMaterialDTO *bean. return updateMaterialDTO, nil } +// resolveDockerRepositoryForEcr resolves a possible @{{VAR_NAME}} reference in the Container +// Repository field, for the AWS ECR repo-creation call only - the DB column always keeps +// whatever the user typed, resolution happens fresh at every trigger (see HandlerService.go). +func (impl CiCdPipelineOrchestratorImpl) resolveDockerRepositoryForEcr(scope resourceQualifiers.Scope, dockerRepository string) (string, error) { + resolvedDockerRepository, _, err := impl.repoFieldVariableResolver.ResolveRepoFieldValue(scope, dockerRepository) + if err != nil { + return "", fmt.Errorf("error resolving docker repository: %w", err) + } + return resolvedDockerRepository, nil +} + // resolveGitMaterialUrl resolves a possible @{{VAR_NAME}} reference in the git material URL. // git_material.url in the DB always stays as the user typed it - only the value sent to // git-sensor is resolved, so Application Templates keep the placeholder intact on clone.