diff --git a/pkg/appStore/installedApp/read/InstalledAppReadService.go b/pkg/appStore/installedApp/read/InstalledAppReadService.go index 19ba9ffe2a..037ef0f623 100644 --- a/pkg/appStore/installedApp/read/InstalledAppReadService.go +++ b/pkg/appStore/installedApp/read/InstalledAppReadService.go @@ -1,8 +1,11 @@ package read import ( + "errors" + "github.com/devtron-labs/devtron/pkg/appStore/installedApp/read/adapter" "github.com/devtron-labs/devtron/pkg/appStore/installedApp/read/bean" + "github.com/go-pg/pg" ) type InstalledAppReadService interface { @@ -40,7 +43,9 @@ func (impl *InstalledAppReadServiceImpl) GetInstalledAppByGitHash(gitHash string func (impl *InstalledAppReadServiceImpl) GetInstalledAppByGitOpsAppName(acdAppName string) (*bean.InstalledAppMin, error) { installedAppModel, err := impl.installedAppRepository.GetInstalledAppByGitOpsAppName(acdAppName) if err != nil { - impl.logger.Errorw("error while fetching installed app by GitOps app name", "acdAppName", acdAppName, "error", err) + if !errors.Is(err, pg.ErrNoRows) { + impl.logger.Errorw("error while fetching installed app by GitOps app name", "acdAppName", acdAppName, "error", err) + } return nil, err } return adapter.GetInstalledAppInternal(installedAppModel).GetInstalledAppMin(), nil diff --git a/pkg/eventProcessor/in/DeployedApplicationEventProcessorService.go b/pkg/eventProcessor/in/DeployedApplicationEventProcessorService.go index 7cd34c9963..2d72fcc233 100644 --- a/pkg/eventProcessor/in/DeployedApplicationEventProcessorService.go +++ b/pkg/eventProcessor/in/DeployedApplicationEventProcessorService.go @@ -88,86 +88,85 @@ func NewDeployedApplicationEventProcessorImpl(logger *zap.SugaredLogger, return deployedApplicationEventProcessorImpl } -func (impl *DeployedApplicationEventProcessorImpl) SubscribeArgoAppUpdate() error { - callback := func(msg *model.PubSubMsg) { - applicationDetail := bean3.ApplicationDetail{} - err := json.Unmarshal([]byte(msg.Data), &applicationDetail) - if err != nil { - impl.logger.Errorw("unmarshal error on app update status", "err", err) +func (impl *DeployedApplicationEventProcessorImpl) handleArgoAppUpdate(msg *model.PubSubMsg) { + applicationDetail := bean3.ApplicationDetail{} + err := json.Unmarshal([]byte(msg.Data), &applicationDetail) + if err != nil { + impl.logger.Errorw("unmarshal error on app update status", "err", err) + return + } + app := applicationDetail.Application + if app == nil { + return + } + if applicationDetail.StatusTime.IsZero() { + applicationDetail.StatusTime = time.Now() + } + isAppStoreApplication := false + pipelines, err := impl.pipelineRepository.GetArgoPipelineByArgoAppName(app.ObjectMeta.Name) + if err != nil { + impl.logger.Errorw("error in fetching pipeline from Pipeline Repository", "err", err, "appName", app.ObjectMeta.Name) + return + } + if len(pipelines) == 0 { + impl.logger.Infow("this app not found in pipeline table looking in installed_apps table", "appName", app.ObjectMeta.Name) + // if not found in pipeline table then search in installed_apps table + installedAppModel, err := impl.installedAppReadService.GetInstalledAppByGitOpsAppName(app.ObjectMeta.Name) + if errors.Is(err, pg.ErrNoRows) { + // Argo also publishes updates for applications that Devtron does not manage. return } - app := applicationDetail.Application - if app == nil { + if err != nil { + impl.logger.Errorw("error in getting all gitops deployment app names from installed_apps ", "err", err) return } - if applicationDetail.StatusTime.IsZero() { - applicationDetail.StatusTime = time.Now() - } - isAppStoreApplication := false - pipelines, err := impl.pipelineRepository.GetArgoPipelineByArgoAppName(app.ObjectMeta.Name) - if err != nil { - impl.logger.Errorw("error in fetching pipeline from Pipeline Repository", "err", err, "appName", app.ObjectMeta.Name) + if installedAppModel.Id > 0 { + // app found in installed_apps table hence setting flag to true + isAppStoreApplication = true + } else { + // app neither found in installed_apps nor in pipeline table hence returning return } - if len(pipelines) == 0 { - impl.logger.Infow("this app not found in pipeline table looking in installed_apps table", "appName", app.ObjectMeta.Name) - // if not found in pipeline table then search in installed_apps table - installedAppModel, err := impl.installedAppReadService.GetInstalledAppByGitOpsAppName(app.ObjectMeta.Name) - if err == pg.ErrNoRows { - // no installed_apps found - impl.logger.Errorw("no installed apps found", "err", err) - return - } + } + isSucceeded, _, pipelineOverride, err := impl.appService.UpdateDeploymentStatusForGitOpsPipelines(app, applicationDetail.ClusterId, applicationDetail.StatusTime, isAppStoreApplication) + if err != nil { + impl.logger.Errorw("error on application status update", "err", err, "msg", string(msg.Data)) + // TODO - check update for charts - fix this call + if err == pg.ErrNoRows { + // if not found in charts (which is for devtron apps) try to find in installed app (which is for devtron charts) + _, err := impl.installedAppService.UpdateInstalledAppVersionStatus(app) if err != nil { - impl.logger.Errorw("error in getting all gitops deployment app names from installed_apps ", "err", err) - return - } - if installedAppModel.Id > 0 { - // app found in installed_apps table hence setting flag to true - isAppStoreApplication = true - } else { - // app neither found in installed_apps nor in pipeline table hence returning + impl.logger.Errorw("error on application status update", "err", err, "msg", string(msg.Data)) return } } - isSucceeded, _, pipelineOverride, err := impl.appService.UpdateDeploymentStatusForGitOpsPipelines(app, applicationDetail.ClusterId, applicationDetail.StatusTime, isAppStoreApplication) + // return anyway whether updates or failure, no further processing for charts status update + return + } + + // invoke DagExecutor, for cd success which will trigger post stage if exist. + if isSucceeded { + impl.logger.Debugw("git hash history", "list", app.Status.History) + triggerContext := bean2.TriggerContext{ + ReferenceId: pointer.String(msg.MsgId), + } + err = impl.workflowDagExecutor.HandleDeploymentSuccessEvent(triggerContext, pipelineOverride) if err != nil { - impl.logger.Errorw("error on application status update", "err", err, "msg", string(msg.Data)) - // TODO - check update for charts - fix this call - if err == pg.ErrNoRows { - // if not found in charts (which is for devtron apps) try to find in installed app (which is for devtron charts) - _, err := impl.installedAppService.UpdateInstalledAppVersionStatus(app) - if err != nil { - impl.logger.Errorw("error on application status update", "err", err, "msg", string(msg.Data)) - return - } - } - // return anyway whether updates or failure, no further processing for charts status update + impl.logger.Errorw("deployment success event error", "pipelineOverride", pipelineOverride, "err", err) return } - - // invoke DagExecutor, for cd success which will trigger post stage if exist. - if isSucceeded { - impl.logger.Debugw("git hash history", "list", app.Status.History) - triggerContext := bean2.TriggerContext{ - ReferenceId: pointer.String(msg.MsgId), - } - err = impl.workflowDagExecutor.HandleDeploymentSuccessEvent(triggerContext, pipelineOverride) - if err != nil { - impl.logger.Errorw("deployment success event error", "pipelineOverride", pipelineOverride, "err", err) - return - } - } - impl.logger.Debugw("application status update completed", "app", app.Name) } + impl.logger.Debugw("application status update completed", "app", app.Name) +} +func (impl *DeployedApplicationEventProcessorImpl) SubscribeArgoAppUpdate() error { // add required logging here var loggerFunc pubsub.LoggerFunc = func(msg model.PubSubMsg) (string, []interface{}) { return "", nil } validations := impl.cdWorkflowCommonService.GetTriggerValidateFuncs() - err := impl.pubSubClient.Subscribe(pubsub.APPLICATION_STATUS_UPDATE_TOPIC, callback, loggerFunc, validations...) + err := impl.pubSubClient.Subscribe(pubsub.APPLICATION_STATUS_UPDATE_TOPIC, impl.handleArgoAppUpdate, loggerFunc, validations...) if err != nil { impl.logger.Error(err) return err diff --git a/pkg/eventProcessor/in/DeployedApplicationEventProcessorService_test.go b/pkg/eventProcessor/in/DeployedApplicationEventProcessorService_test.go new file mode 100644 index 0000000000..d7a778005b --- /dev/null +++ b/pkg/eventProcessor/in/DeployedApplicationEventProcessorService_test.go @@ -0,0 +1,117 @@ +/* + * 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 in + +import ( + "bytes" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1" + "github.com/devtron-labs/common-lib/pubsub-lib/model" + "github.com/devtron-labs/devtron/internal/sql/repository/chartConfig" + "github.com/devtron-labs/devtron/internal/sql/repository/pipelineConfig" + "github.com/devtron-labs/devtron/pkg/app" + "github.com/devtron-labs/devtron/pkg/appStore/installedApp/read" + "github.com/devtron-labs/devtron/pkg/appStore/installedApp/repository" + "github.com/go-pg/pg" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +func TestHandleArgoAppUpdateWithoutPipeline(t *testing.T) { + databaseErr := errors.New("database connection failed") + tests := []struct { + name string + installedApp *repository.InstalledApps + lookupErr error + wantError bool + }{ + {name: "unregistered application", lookupErr: pg.ErrNoRows}, + {name: "unregistered application with wrapped error", lookupErr: fmt.Errorf("lookup: %w", pg.ErrNoRows)}, + {name: "database failure", lookupErr: databaseErr, wantError: true}, + {name: "registered chart", installedApp: &repository.InstalledApps{Id: 1}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var logs bytes.Buffer + encoder := zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()) + logger := zap.New(zapcore.NewCore(encoder, zapcore.AddSync(&logs), zap.ErrorLevel)).Sugar() + appService := &argoAppStatusRecorder{} + processor := &DeployedApplicationEventProcessorImpl{ + logger: logger, + appService: appService, + pipelineRepository: &noArgoPipelineRepository{}, + installedAppReadService: read.NewInstalledAppReadServiceImpl(read.NewInstalledAppReadServiceEAImpl( + logger, &argoInstalledAppLookup{installedApp: tt.installedApp, err: tt.lookupErr}, + )), + } + + processor.handleArgoAppUpdate(&model.PubSubMsg{ + Data: `{"application":{"metadata":{"name":"demo"}}}`, + }) + + if tt.wantError { + if !strings.Contains(logs.String(), `"error":"`+databaseErr.Error()+`"`) { + t.Errorf("expected the lookup service to log the database failure: %v", logs.String()) + } + if !strings.Contains(logs.String(), `"err":"`+databaseErr.Error()+`"`) { + t.Errorf("expected the event processor to log the database failure: %v", logs.String()) + } + } else if logs.Len() != 0 { + t.Errorf("unexpected error logs: %v", logs.String()) + } + if want := tt.installedApp != nil; appService.updated != want || appService.updatedChart != want { + t.Errorf("updated = %t, updated chart = %t, want both %t", appService.updated, appService.updatedChart, want) + } + }) + } +} + +type noArgoPipelineRepository struct { + pipelineConfig.PipelineRepository +} + +func (*noArgoPipelineRepository) GetArgoPipelineByArgoAppName(string) ([]pipelineConfig.Pipeline, error) { + return nil, nil +} + +type argoInstalledAppLookup struct { + repository.InstalledAppRepository + installedApp *repository.InstalledApps + err error +} + +func (r *argoInstalledAppLookup) GetInstalledAppByGitOpsAppName(string) (*repository.InstalledApps, error) { + return r.installedApp, r.err +} + +type argoAppStatusRecorder struct { + app.AppService + updated bool + updatedChart bool +} + +func (s *argoAppStatusRecorder) UpdateDeploymentStatusForGitOpsPipelines(_ *v1alpha1.Application, _ int, _ time.Time, isAppStore bool) (bool, bool, *chartConfig.PipelineOverride, error) { + s.updated = true + s.updatedChart = isAppStore + return false, false, nil, nil +}