Skip to content

Commit 20fac2d

Browse files
fix: Api optimization fixes (#3292)
* query fix * creating V2 api * env,namespace and cluster meta info added in appListing * sending unique envids * fix * fix * backward compatibility for wf status api * external link v2 * fix for ci template history * wip * info log * rbac fix * ciGitconfiguredId added in app grouping * changed wf version to v2 --------- Co-authored-by: ayushmaheshwari <[email protected]>
1 parent 6b684f0 commit 20fac2d

File tree

10 files changed

+157
-4
lines changed

10 files changed

+157
-4
lines changed

api/externalLink/ExternalLinkRestHandler.go

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ type ExternalLinkRestHandler interface {
3737
CreateExternalLinks(w http.ResponseWriter, r *http.Request)
3838
GetExternalLinkMonitoringTools(w http.ResponseWriter, r *http.Request)
3939
GetExternalLinks(w http.ResponseWriter, r *http.Request)
40+
GetExternalLinksV2(w http.ResponseWriter, r *http.Request)
4041
UpdateExternalLink(w http.ResponseWriter, r *http.Request)
4142
DeleteExternalLink(w http.ResponseWriter, r *http.Request) // Update is_active to false link
4243
}
@@ -134,6 +135,7 @@ func (impl ExternalLinkRestHandlerImpl) GetExternalLinkMonitoringTools(w http.Re
134135
}
135136
common.WriteJsonResp(w, err, res, http.StatusOK)
136137
}
138+
137139
func (impl ExternalLinkRestHandlerImpl) GetExternalLinks(w http.ResponseWriter, r *http.Request) {
138140
userId, err := impl.userService.GetLoggedInUser(r)
139141
if userId == 0 || err != nil {
@@ -146,6 +148,65 @@ func (impl ExternalLinkRestHandlerImpl) GetExternalLinks(w http.ResponseWriter,
146148
linkType := v.Get("type")
147149
identifier := v.Get("identifier")
148150

151+
token := r.Header.Get("token")
152+
if len(identifier) == 0 && len(linkType) == 0 && len(clusterId) == 0 {
153+
if ok := impl.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionGet, "*"); !ok {
154+
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
155+
return
156+
}
157+
clusterIdNumber := 0
158+
res, err := impl.externalLinkService.FetchAllActiveLinksByLinkIdentifier(nil, clusterIdNumber)
159+
if err != nil {
160+
impl.logger.Errorw("service err, FetchAllActive", "err", err)
161+
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
162+
return
163+
}
164+
common.WriteJsonResp(w, err, res, http.StatusOK)
165+
return
166+
167+
} else if len(identifier) != 0 && len(linkType) != 0 { //api to get external links from app-level external links tab and from app-details page
168+
clusterIdNumber := 0
169+
if len(clusterId) != 0 { //api call from app-detail page
170+
clusterIdNumber, err = strconv.Atoi(clusterId)
171+
if err != nil {
172+
impl.logger.Errorw("error occurred while parsing cluster_id", "clusterId", clusterId, "err", err)
173+
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
174+
return
175+
}
176+
}
177+
linkIdentifier := &externalLink.LinkIdentifier{
178+
Type: linkType,
179+
Identifier: identifier,
180+
ClusterId: 0,
181+
}
182+
res, err := impl.externalLinkService.FetchAllActiveLinksByLinkIdentifier(linkIdentifier, clusterIdNumber)
183+
if err != nil {
184+
impl.logger.Errorw("service err, FetchAllActive", "err", err)
185+
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
186+
return
187+
}
188+
common.WriteJsonResp(w, err, res, http.StatusOK)
189+
return
190+
}
191+
192+
impl.logger.Errorw("invalid request, FetchAllActive external links", "err", err)
193+
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
194+
return
195+
196+
}
197+
198+
func (impl ExternalLinkRestHandlerImpl) GetExternalLinksV2(w http.ResponseWriter, r *http.Request) {
199+
userId, err := impl.userService.GetLoggedInUser(r)
200+
if userId == 0 || err != nil {
201+
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
202+
return
203+
}
204+
205+
v := r.URL.Query()
206+
clusterId := v.Get("clusterId")
207+
linkType := v.Get("type")
208+
identifier := v.Get("identifier")
209+
149210
externalLinkAndMonitoringTools := externalLink.ExternalLinkAndMonitoringToolDTO{}
150211
externalLinks := []*externalLink.ExternalLinkDto{}
151212

api/externalLink/ExternalLinkRouter.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ func (impl ExternalLinkRouterImpl) InitExternalLinkRouter(configRouter *mux.Rout
1919
configRouter.Path("").HandlerFunc(impl.externalLinkRestHandler.CreateExternalLinks).Methods("POST")
2020
configRouter.Path("/tools").HandlerFunc(impl.externalLinkRestHandler.GetExternalLinkMonitoringTools).Methods("GET")
2121
configRouter.Path("").HandlerFunc(impl.externalLinkRestHandler.GetExternalLinks).Methods("GET")
22+
configRouter.Path("/v2").HandlerFunc(impl.externalLinkRestHandler.GetExternalLinksV2).Methods("GET")
2223
configRouter.Path("").HandlerFunc(impl.externalLinkRestHandler.UpdateExternalLink).Methods("PUT")
2324
configRouter.Path("").HandlerFunc(impl.externalLinkRestHandler.DeleteExternalLink).Queries("id", "{id}").Methods("DELETE")
2425
}

api/restHandler/AppListingRestHandler.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -868,7 +868,7 @@ func (handler AppListingRestHandlerImpl) FetchOverviewAppsByEnvironment(w http.R
868868
rbacObjectsWithAppId := handler.enforcerUtil.GetRbacObjectsByAppIds(appIds)
869869
rbacObjects := make([]string, len(rbacObjectsWithAppId))
870870
itr := 0
871-
for _, object := range rbacObjects {
871+
for _, object := range rbacObjectsWithAppId {
872872
rbacObjects[itr] = object
873873
itr++
874874
}

api/restHandler/app/PipelineConfigRestHandler.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -521,6 +521,7 @@ func (handler PipelineConfigRestHandlerImpl) FetchAppWorkflowStatusForTriggerVie
521521
}
522522
//RBAC CHECK
523523

524+
apiVersion := vars["version"]
524525
triggerWorkflowStatus := pipelineConfig.TriggerWorkflowStatus{}
525526
var ciWorkflowStatus []*pipelineConfig.CiWorkflowStatus
526527
var err1 error
@@ -529,7 +530,11 @@ func (handler PipelineConfigRestHandlerImpl) FetchAppWorkflowStatusForTriggerVie
529530
wg := sync.WaitGroup{}
530531
wg.Add(2)
531532
go func() {
532-
ciWorkflowStatus, err = handler.ciHandler.FetchCiStatusForTriggerView(appId)
533+
if apiVersion == "v2" {
534+
ciWorkflowStatus, err = handler.ciHandler.FetchCiStatusForTriggerViewV1(appId)
535+
} else {
536+
ciWorkflowStatus, err = handler.ciHandler.FetchCiStatusForTriggerView(appId)
537+
}
533538
wg.Done()
534539
}()
535540

api/router/PipelineConfigRouter.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,7 @@ func (router PipelineConfigRouterImpl) initPipelineConfigRouter(configRouter *mu
152152
configRouter.Path("/cd/configmap-secrets/{pipelineId}").HandlerFunc(router.restHandler.GetConfigmapSecretsForDeploymentStages).Methods("GET")
153153

154154
configRouter.Path("/workflow/status/{appId}").HandlerFunc(router.restHandler.FetchAppWorkflowStatusForTriggerView).Methods("GET")
155+
configRouter.Path("/workflow/status/{appId}/{version}").HandlerFunc(router.restHandler.FetchAppWorkflowStatusForTriggerView).Methods("GET")
155156

156157
configRouter.Path("/material-info/{appId}/{ciArtifactId}").HandlerFunc(router.restHandler.FetchMaterialInfo).Methods("GET")
157158
configRouter.Path("/ci-pipeline/webhook-payload/{pipelineMaterialId}").HandlerFunc(router.webhookDataRestHandler.GetWebhookPayloadDataForPipelineMaterialId).Methods("GET")

pkg/app/AppListingService.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,35 @@ func (impl AppListingServiceImpl) FetchAppsByEnvironmentV2(fetchAppListingReques
386386
impl.Logger.Errorw("error in fetching app list", "error", err, "filter", appListingFilter)
387387
return []*bean.AppEnvironmentContainer{}, appSize, err
388388
}
389+
390+
envContainersMap := make(map[int][]*bean.AppEnvironmentContainer)
391+
envIds := make([]int, 0)
392+
envsSet := make(map[int]bool)
393+
394+
for _, container := range envContainers {
395+
if container.EnvironmentId != 0 {
396+
if _, ok := envContainersMap[container.EnvironmentId]; !ok {
397+
envContainersMap[container.EnvironmentId] = make([]*bean.AppEnvironmentContainer, 0)
398+
}
399+
envContainersMap[container.EnvironmentId] = append(envContainersMap[container.EnvironmentId], container)
400+
if _, ok := envsSet[container.EnvironmentId]; !ok {
401+
envIds = append(envIds, container.EnvironmentId)
402+
envsSet[container.EnvironmentId] = true
403+
}
404+
}
405+
}
406+
envClusterInfos, err := impl.environmentRepository.FindEnvClusterInfosByIds(envIds)
407+
if err != nil {
408+
impl.Logger.Errorw("error in envClusterInfos list", "error", err, "envIds", envIds)
409+
return []*bean.AppEnvironmentContainer{}, appSize, err
410+
}
411+
for _, info := range envClusterInfos {
412+
for _, container := range envContainersMap[info.Id] {
413+
container.Namespace = info.Namespace
414+
container.ClusterName = info.ClusterName
415+
container.EnvironmentName = info.Name
416+
}
417+
}
389418
return envContainers, appSize, nil
390419
}
391420

pkg/bean/app.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,7 @@ type CiConfigRequest struct {
299299
UpdatedOn time.Time `sql:"updated_on,type:timestamptz"`
300300
UpdatedBy int32 `sql:"updated_by,type:integer"`
301301
IsJob bool `json:"-"`
302+
CiGitMaterialId int `json:"ciGitConfiguredId"`
302303
}
303304

304305
type TestExecutorImageProperties struct {

pkg/cluster/repository/EnvironmentRepository.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,21 @@
1818
package repository
1919

2020
import (
21+
"fmt"
2122
"github.com/devtron-labs/devtron/internal/sql/repository/appStatus"
23+
"github.com/devtron-labs/devtron/internal/sql/repository/helper"
2224
"github.com/devtron-labs/devtron/pkg/sql"
2325
"github.com/go-pg/pg"
2426
"github.com/go-pg/pg/orm"
2527
"go.uber.org/zap"
2628
)
2729

30+
type EnvCluserInfo struct {
31+
Id int `sql:"id"`
32+
ClusterName string `sql:"cluster_name"`
33+
Namespace string `sql:"namespace"`
34+
Name string `sql:"name"`
35+
}
2836
type Environment struct {
2937
tableName struct{} `sql:"environment" pg:",discard_unknown_columns"`
3038
Id int `sql:"id,pk"`
@@ -66,6 +74,7 @@ type EnvironmentRepository interface {
6674
FindByEnvNameAndClusterIds(envName string, clusterIds []int) ([]*Environment, error)
6775
FindByClusterIdsWithFilter(clusterIds []int) ([]*Environment, error)
6876
FindAllActiveWithFilter() ([]*Environment, error)
77+
FindEnvClusterInfosByIds([]int) ([]*EnvCluserInfo, error)
6978
}
7079

7180
func NewEnvironmentRepositoryImpl(dbConnection *pg.DB, logger *zap.SugaredLogger, appStatusRepository appStatus.AppStatusRepository) *EnvironmentRepositoryImpl {
@@ -96,6 +105,17 @@ func (repositoryImpl EnvironmentRepositoryImpl) FindOne(environment string) (*En
96105
return environmentCluster, err
97106
}
98107

108+
func (repositoryImpl EnvironmentRepositoryImpl) FindEnvClusterInfosByIds(envIds []int) ([]*EnvCluserInfo, error) {
109+
query := "SELECT env.id as id,cluster.cluster_name,env.environment_name as name,env.namespace " +
110+
" FROM environment env INNER JOIN cluster ON env.cluster_id = cluster.id "
111+
if len(envIds) > 0 {
112+
query += fmt.Sprintf(" WHERE env.id IN (%s)", helper.GetCommaSepratedString(envIds))
113+
}
114+
res := make([]*EnvCluserInfo, 0)
115+
_, err := repositoryImpl.dbConnection.Query(&res, query)
116+
return res, err
117+
}
118+
99119
func (repositoryImpl EnvironmentRepositoryImpl) FindByNamespaceAndClusterName(namespaces string, clusterName string) (*Environment, error) {
100120
environmentCluster := &Environment{}
101121
err := repositoryImpl.dbConnection.

pkg/pipeline/CiHandler.go

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ type CiHandler interface {
6767
UpdateWorkflow(workflowStatus v1alpha1.WorkflowStatus) (int, error)
6868

6969
FetchCiStatusForTriggerView(appId int) ([]*pipelineConfig.CiWorkflowStatus, error)
70+
FetchCiStatusForTriggerViewV1(appId int) ([]*pipelineConfig.CiWorkflowStatus, error)
7071
RefreshMaterialByCiPipelineMaterialId(gitMaterialId int) (refreshRes *gitSensor.RefreshGitMaterialResponse, err error)
7172
FetchMaterialInfoByArtifactId(ciArtifactId int) (*GitTriggerInfoResponse, error)
7273
WriteToCreateTestSuites(pipelineId int, buildId int, triggeredBy int)
@@ -1022,7 +1023,7 @@ func (impl *CiHandlerImpl) getLastSeenCommit(ciMaterialId int) (bean.GitCommit,
10221023
return gitCommit, nil
10231024
}
10241025

1025-
func (impl *CiHandlerImpl) FetchCiStatusForTriggerView(appId int) ([]*pipelineConfig.CiWorkflowStatus, error) {
1026+
func (impl *CiHandlerImpl) FetchCiStatusForTriggerViewV1(appId int) ([]*pipelineConfig.CiWorkflowStatus, error) {
10261027
ciWorkflowStatuses, err := impl.ciWorkflowRepository.FIndCiWorkflowStatusesByAppId(appId)
10271028
if err != nil && !util.IsErrNoRows(err) {
10281029
impl.Logger.Errorw("err in fetching ciWorkflowStatuses from ciWorkflowRepository", "appId", appId, "err", err)
@@ -1032,6 +1033,39 @@ func (impl *CiHandlerImpl) FetchCiStatusForTriggerView(appId int) ([]*pipelineCo
10321033
return ciWorkflowStatuses, err
10331034
}
10341035

1036+
func (impl *CiHandlerImpl) FetchCiStatusForTriggerView(appId int) ([]*pipelineConfig.CiWorkflowStatus, error) {
1037+
var ciWorkflowStatuses []*pipelineConfig.CiWorkflowStatus
1038+
1039+
pipelines, err := impl.ciPipelineRepository.FindByAppId(appId)
1040+
if err != nil && err != pg.ErrNoRows {
1041+
impl.Logger.Errorw("error in fetching ci pipeline", "appId", appId, "err", err)
1042+
return ciWorkflowStatuses, err
1043+
}
1044+
for _, pipeline := range pipelines {
1045+
pipelineId := 0
1046+
if pipeline.ParentCiPipeline == 0 {
1047+
pipelineId = pipeline.Id
1048+
} else {
1049+
pipelineId = pipeline.ParentCiPipeline
1050+
}
1051+
workflow, err := impl.ciWorkflowRepository.FindLastTriggeredWorkflow(pipelineId)
1052+
if err != nil && !util.IsErrNoRows(err) {
1053+
impl.Logger.Errorw("err", "pipelineId", pipelineId, "err", err)
1054+
return ciWorkflowStatuses, err
1055+
}
1056+
ciWorkflowStatus := &pipelineConfig.CiWorkflowStatus{}
1057+
ciWorkflowStatus.CiPipelineId = pipeline.Id
1058+
if workflow.Id > 0 {
1059+
ciWorkflowStatus.CiPipelineName = workflow.CiPipeline.Name
1060+
ciWorkflowStatus.CiStatus = workflow.Status
1061+
} else {
1062+
ciWorkflowStatus.CiStatus = "Not Triggered"
1063+
}
1064+
ciWorkflowStatuses = append(ciWorkflowStatuses, ciWorkflowStatus)
1065+
}
1066+
return ciWorkflowStatuses, nil
1067+
}
1068+
10351069
func (impl *CiHandlerImpl) FetchMaterialInfoByArtifactId(ciArtifactId int) (*GitTriggerInfoResponse, error) {
10361070

10371071
ciArtifact, err := impl.ciArtifactRepository.Get(ciArtifactId)

pkg/pipeline/PipelineBuilder.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1154,7 +1154,7 @@ func (impl PipelineBuilderImpl) UpdateCiTemplate(updateRequest *bean.CiConfigReq
11541154
CreatedOn: originalCiConf.CreatedOn,
11551155
CreatedBy: originalCiConf.CreatedBy,
11561156
UpdatedOn: time.Now(),
1157-
UpdatedBy: updateRequest.UpdatedBy,
1157+
UpdatedBy: updateRequest.UserId,
11581158
},
11591159
}
11601160

@@ -4069,6 +4069,7 @@ func (impl PipelineBuilderImpl) GetCiPipelineByEnvironment(envId int, emailId st
40694069
//parentCiPipelineIds = append(parentCiPipelineIds, pipeline.ParentCiPipeline)
40704070
}
40714071
ciPipelinesConfigByApp.CiPipelines = ciPipelineResp
4072+
ciPipelinesConfigByApp.CiGitMaterialId = ciPipelinesConfigByApp.CiBuildConfig.GitMaterialId
40724073
ciPipelinesConfigByApps = append(ciPipelinesConfigByApps, ciPipelinesConfigByApp)
40734074
}
40744075

0 commit comments

Comments
 (0)