Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion pkg/appStore/installedApp/read/InstalledAppReadService.go
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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
Expand Down
117 changes: 58 additions & 59 deletions pkg/eventProcessor/in/DeployedApplicationEventProcessorService.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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) {

Check failure on line 39 in pkg/eventProcessor/in/DeployedApplicationEventProcessorService_test.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 17 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=devtron-labs_devtron&issues=AaH3TPod0xKWwBM5aky5&open=AaH3TPod0xKWwBM5aky5&pullRequest=7096
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
}