diff --git a/Wire.go b/Wire.go index 9f122b29dc..024196a4ea 100644 --- a/Wire.go +++ b/Wire.go @@ -324,15 +324,16 @@ func InitializeApp() (*App, error) { restHandler.NewCDRestHandlerImpl, wire.Bind(new(restHandler.CDRestHandler), new(*restHandler.CDRestHandlerImpl)), - ArgoUtil.GetArgoConfig, + //ArgoUtil.GetArgoConfig, ArgoUtil.NewArgoSession, ArgoUtil.NewResourceServiceImpl, wire.Bind(new(ArgoUtil.ResourceService), new(*ArgoUtil.ResourceServiceImpl)), //ArgoUtil.NewApplicationServiceImpl, //wire.Bind(new(ArgoUtil.ApplicationService), new(ArgoUtil.ApplicationServiceImpl)), - //ArgoUtil.NewRepositoryService, - //wire.Bind(new(ArgoUtil.RepositoryService), new(ArgoUtil.RepositoryServiceImpl)), - + ArgoUtil.NewRepositoryService, + wire.Bind(new(ArgoUtil.RepositoryService), new(*ArgoUtil.RepositoryServiceImpl)), + ArgoUtil.NewArgoClusterServiceImpl, + wire.Bind(new(ArgoUtil.ArgoClusterService), new(*ArgoUtil.ArgoClusterServiceImpl)), pipelineConfig.NewDbMigrationConfigRepositoryImpl, wire.Bind(new(pipelineConfig.DbMigrationConfigRepository), new(*pipelineConfig.DbMigrationConfigRepositoryImpl)), pipeline.NewDbConfigService, diff --git a/api/appStore/deployment/AppStoreDeploymentRestHandler.go b/api/appStore/deployment/AppStoreDeploymentRestHandler.go index 68e9840f8e..49d1bd60c3 100644 --- a/api/appStore/deployment/AppStoreDeploymentRestHandler.go +++ b/api/appStore/deployment/AppStoreDeploymentRestHandler.go @@ -161,10 +161,11 @@ func (handler AppStoreDeploymentRestHandlerImpl) InstallApp(w http.ResponseWrite } }(ctx.Done(), cn.CloseNotify()) } + acdToken := "" if util2.IsBaseStack() || util2.IsHelmApp(request.AppOfferingMode) { ctx = context.WithValue(r.Context(), "token", token) } else { - acdToken, err := handler.argoUserService.GetLatestDevtronArgoCdUserToken() + acdToken, err = handler.argoUserService.GetLatestDevtronArgoCdUserToken() if err != nil { handler.Logger.Errorw("error in getting acd token", "err", err) common.WriteJsonResp(w, err, nil, http.StatusInternalServerError) @@ -174,6 +175,7 @@ func (handler AppStoreDeploymentRestHandlerImpl) InstallApp(w http.ResponseWrite } defer cancel() + request.AcdToken = acdToken res, err := handler.appStoreDeploymentService.InstallApp(&request, ctx) if err != nil { if strings.Contains(err.Error(), "application spec is invalid") { diff --git a/api/cluster/ClusterRestHandler.go b/api/cluster/ClusterRestHandler.go index 9b72614f61..30236bc15e 100644 --- a/api/cluster/ClusterRestHandler.go +++ b/api/cluster/ClusterRestHandler.go @@ -131,10 +131,11 @@ func (impl ClusterRestHandlerImpl) Save(w http.ResponseWriter, r *http.Request) } }(ctx.Done(), cn.CloseNotify()) } + acdToken := "" if util2.IsBaseStack() { ctx = context.WithValue(ctx, "token", token) } else { - acdToken, err := impl.argoUserService.GetLatestDevtronArgoCdUserToken() + acdToken, err = impl.argoUserService.GetLatestDevtronArgoCdUserToken() if err != nil { impl.logger.Errorw("error in getting acd token", "err", err) common.WriteJsonResp(w, err, nil, http.StatusInternalServerError) @@ -142,7 +143,7 @@ func (impl ClusterRestHandlerImpl) Save(w http.ResponseWriter, r *http.Request) } ctx = context.WithValue(ctx, "token", acdToken) } - bean, err = impl.clusterService.Save(ctx, bean, userId) + bean, err = impl.clusterService.Save(ctx, bean, userId, acdToken) if err != nil { impl.logger.Errorw("service err, Save", "err", err, "payload", bean) common.WriteJsonResp(w, err, nil, http.StatusInternalServerError) diff --git a/api/restHandler/app/DeploymentPipelineRestHandler.go b/api/restHandler/app/DeploymentPipelineRestHandler.go index 6dd48d38f2..1c5336fc82 100644 --- a/api/restHandler/app/DeploymentPipelineRestHandler.go +++ b/api/restHandler/app/DeploymentPipelineRestHandler.go @@ -202,6 +202,7 @@ func (handler PipelineConfigRestHandlerImpl) CreateCdPipeline(w http.ResponseWri } //RBAC acdToken, err := handler.argoUserService.GetLatestDevtronArgoCdUserToken() + cdPipeline.AcdToken = acdToken if err != nil { handler.Logger.Errorw("error in getting acd token", "err", err) common.WriteJsonResp(w, err, nil, http.StatusInternalServerError) diff --git a/internal/util/ArgoUtil/ArgoClient.go b/internal/util/ArgoUtil/ArgoClient.go index 26de17389c..01e1d202ad 100644 --- a/internal/util/ArgoUtil/ArgoClient.go +++ b/internal/util/ArgoUtil/ArgoClient.go @@ -19,6 +19,7 @@ package ArgoUtil import ( "bytes" + "crypto/tls" "encoding/json" "fmt" "github.com/caarlos0/env" @@ -43,6 +44,28 @@ type ArgoSession struct { logger *zap.SugaredLogger baseUrl *url.URL } + +func NewArgoSession(httpClient *http.Client, logger *zap.SugaredLogger) *ArgoSession { + tr := &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + } + cfg, err := GetArgoConfig() + if err != nil { + return nil + } + baseUrl := &url.URL{ + Scheme: "https", + Host: cfg.Url, + } + + client := &http.Client{Transport: tr} + return &ArgoSession{ + httpClient: client, + logger: logger, + baseUrl: baseUrl, + } +} + type StatusCode int func (code StatusCode) IsSuccess() bool { @@ -106,34 +129,79 @@ func (session *ArgoSession) DoRequest(clientRequest *ClientRequest) (resBody []b } return resBody, &status, err } - -func NewArgoSession(config *ArgoConfig, logger *zap.SugaredLogger) (session *ArgoSession, err error) { - /*location := "/api/v1/session" - baseUrl, err := url.Parse(config.Url) +func (session *ArgoSession) DoRequestForArgo(clientRequest *ClientRequest, acdToken string) (resBody []byte, resCode *StatusCode, err error) { + if clientRequest.ResponseBody == nil { + return nil, nil, fmt.Errorf("response body cant be nil") + } + if reflect.ValueOf(clientRequest.ResponseBody).Kind() != reflect.Ptr { + return nil, nil, fmt.Errorf("responsebody non pointer") + } + rel, err := session.baseUrl.Parse(clientRequest.Path) if err != nil { - return nil, err + return nil, nil, err } - rel, err := baseUrl.Parse(location) - param := map[string]string{} - param["username"] = "admin" - param["password"] = "argocd-server-6cd5bcffd4-j6kcx" - paramJson, err := json.Marshal(param) + var body io.Reader + if clientRequest.RequestBody != nil { + if req, err := json.Marshal(clientRequest.RequestBody); err != nil { + return nil, nil, err + } else { + session.logger.Debugw("argo req with body", "body", string(req)) + body = bytes.NewBuffer(req) + } + } + httpReq, err := http.NewRequest("POST", rel.String(), body) if err != nil { - return nil, err + return nil, nil, err } - req, _ := http.NewRequest("POST", rel.String(), bytes.NewBuffer(paramJson)) - transCfg := &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: config.InsecureSkipVerify}, + httpReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", acdToken)) + httpReq.Header.Set("Content-Type", "application/json") + httpRes, err := session.httpClient.Do(httpReq) + if err != nil { + return nil, nil, err } - cookieJar, err := cookiejar.New(nil) + defer httpRes.Body.Close() + resBody, err = ioutil.ReadAll(httpRes.Body) if err != nil { - return nil, err - } - client := &http.Client{Transport: transCfg, Jar: cookieJar, Timeout: time.Duration(config.Timeout)} - res, err := client.Do(req) - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return nil, err - }*/ - return &ArgoSession{}, nil + session.logger.Errorw("error in argocd communication ", "err", err) + return nil, nil, err + } + status := StatusCode(httpRes.StatusCode) + if status.IsSuccess() { + err = json.Unmarshal(resBody, clientRequest.ResponseBody) + } else { + session.logger.Errorw("api err", "res", string(resBody)) + return resBody, &status, fmt.Errorf("res not success, code: %d ", status) + } + return resBody, &status, err } + +//func NewArgoSession(config *ArgoConfig, logger *zap.SugaredLogger) (session *ArgoSession, err error) { +// /*location := "/api/v1/session" +// baseUrl, err := url.Parse(config.Url) +// if err != nil { +// return nil, err +// } +// rel, err := baseUrl.Parse(location) +// param := map[string]string{} +// param["username"] = "admin" +// param["password"] = "argocd-server-6cd5bcffd4-j6kcx" +// paramJson, err := json.Marshal(param) +// if err != nil { +// return nil, err +// } +// req, _ := http.NewRequest("POST", rel.String(), bytes.NewBuffer(paramJson)) +// transCfg := &http.Transport{ +// TLSClientConfig: &tls.Config{InsecureSkipVerify: config.InsecureSkipVerify}, +// } +// cookieJar, err := cookiejar.New(nil) +// if err != nil { +// return nil, err +// } +// client := &http.Client{Transport: transCfg, Jar: cookieJar, Timeout: time.Duration(config.Timeout)} +// res, err := client.Do(req) +// defer res.Body.Close() +// if res.StatusCode != http.StatusOK { +// return nil, err +// }*/ +// return &ArgoSession{}, nil +//} diff --git a/internal/util/ArgoUtil/ClusterService.go b/internal/util/ArgoUtil/ClusterService.go index bd04b5eaf2..bf9ea8bd14 100644 --- a/internal/util/ArgoUtil/ClusterService.go +++ b/internal/util/ArgoUtil/ClusterService.go @@ -21,28 +21,49 @@ import ( "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" ) -type ClusterService interface { +type ClusterConfig struct { + BearerToken string `json:"bearerToken"` + TLSClientConfig `json:"tlsClientConfig"` +} +type TLSClientConfig struct { + Insecure bool `json:"insecure"` +} +type ClusterRequest struct { + Name string `json:"name"` + Server string `json:"server"` + Config ClusterConfig `json:"config"` +} +type ClusterResponse struct { + Id string `json:"id"` + Server string `json:"server"` + Name string `json:"name"` + ServerVersion string `json:"serverVersion"` + Config ClusterConfig `json:"config"` +} + +type ArgoClusterService interface { GetClusterByServer(server string) (*v1alpha1.Cluster, error) ClusterList() (*v1alpha1.ClusterList, error) CreateCluster(cluster v1alpha1.Cluster) (*v1alpha1.Cluster, error) + CreateClusterWithGitOps(request *ClusterRequest, acdToken string) (*ClusterRequest, error) UpdateCluster(cluster v1alpha1.Cluster) (*v1alpha1.Cluster, error) DeleteCluster(server string) (string, error) } -type ClusterServiceImpl struct { +type ArgoClusterServiceImpl struct { *ArgoSession id int location string } -func NewClusterServiceImpl(session *ArgoSession) *ClusterServiceImpl { - return &ClusterServiceImpl{ +func NewArgoClusterServiceImpl(session *ArgoSession) *ArgoClusterServiceImpl { + return &ArgoClusterServiceImpl{ ArgoSession: session, - location: "/api/v1/clusters", + location: "/api/v1/clusters?upsert=true", } } -func (impl *ClusterServiceImpl) GetClusterByServer(server string) (*v1alpha1.Cluster, error) { +func (impl *ArgoClusterServiceImpl) GetClusterByServer(server string) (*v1alpha1.Cluster, error) { path := impl.location + "/" + server res := &v1alpha1.Cluster{} @@ -53,7 +74,7 @@ func (impl *ClusterServiceImpl) GetClusterByServer(server string) (*v1alpha1.Clu return res, nil } -func (impl *ClusterServiceImpl) ClusterList() (*v1alpha1.ClusterList, error) { +func (impl *ArgoClusterServiceImpl) ClusterList() (*v1alpha1.ClusterList, error) { path := impl.location res := &v1alpha1.ClusterList{} @@ -64,7 +85,7 @@ func (impl *ClusterServiceImpl) ClusterList() (*v1alpha1.ClusterList, error) { return res, nil } -func (impl *ClusterServiceImpl) CreateCluster(cluster v1alpha1.Cluster) (*v1alpha1.Cluster, error) { +func (impl *ArgoClusterServiceImpl) CreateCluster(cluster v1alpha1.Cluster) (*v1alpha1.Cluster, error) { path := impl.location res := &v1alpha1.Cluster{} @@ -75,8 +96,17 @@ func (impl *ClusterServiceImpl) CreateCluster(cluster v1alpha1.Cluster) (*v1alph } return res, nil } +func (impl *ArgoClusterServiceImpl) CreateClusterWithGitOps(request *ClusterRequest, acdToken string) (*ClusterRequest, error) { + path := impl.location + res := &ClusterRequest{} + _, _, err := impl.DoRequestForArgo(&ClientRequest{ResponseBody: res, Path: path, RequestBody: request, Method: "POST"}, acdToken) + if err != nil { + return nil, err + } + return res, nil +} -func (impl *ClusterServiceImpl) UpdateCluster(cluster v1alpha1.Cluster) (*v1alpha1.Cluster, error) { +func (impl *ArgoClusterServiceImpl) UpdateCluster(cluster v1alpha1.Cluster) (*v1alpha1.Cluster, error) { path := impl.location + "/" + cluster.Server res := &v1alpha1.Cluster{} @@ -87,7 +117,7 @@ func (impl *ClusterServiceImpl) UpdateCluster(cluster v1alpha1.Cluster) (*v1alph return res, nil } -func (impl *ClusterServiceImpl) DeleteCluster(server string) (string, error) { +func (impl *ArgoClusterServiceImpl) DeleteCluster(server string) (string, error) { res := "" path := impl.location + "/" + server _, _, err := impl.DoRequest(&ClientRequest{ResponseBody: &res, Path: path, Method: "DELETE"}) diff --git a/internal/util/ArgoUtil/RepositoryService.go b/internal/util/ArgoUtil/RepositoryService.go index 8de7f23c99..5bd8c076ef 100644 --- a/internal/util/ArgoUtil/RepositoryService.go +++ b/internal/util/ArgoUtil/RepositoryService.go @@ -17,10 +17,17 @@ package ArgoUtil -import "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" +import ( + "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" +) + +type Repository struct { + Repo string `json:"repo"` +} type RepositoryService interface { Create(repositoryRequest *v1alpha1.Repository) (repository *v1alpha1.Repository, err error) + CreateRepository(repositoryRequest *Repository, acdToken string) (repository *Repository, err error) } type RepositoryServiceImpl struct { @@ -31,7 +38,7 @@ type RepositoryServiceImpl struct { func NewRepositoryService(session *ArgoSession) *RepositoryServiceImpl { return &RepositoryServiceImpl{ ArgoSession: session, - location: "/api/v1/repositories", + location: "/api/v1/repositories?upsert=true", } } @@ -43,3 +50,12 @@ func (impl RepositoryServiceImpl) Create(repositoryRequest *v1alpha1.Repository) } return res, nil } +func (impl RepositoryServiceImpl) CreateRepository(repositoryRequest *Repository, acdToken string) (repository *Repository, err error) { + res := &Repository{} + _, _, err = impl.DoRequestForArgo(&ClientRequest{ResponseBody: res, Path: impl.location, Method: "POST", RequestBody: repositoryRequest}, acdToken) + if err != nil { + return nil, err + } + impl.logger.Errorw("failed to register on Argo", "err", err) + return res, nil +} diff --git a/internal/util/ArgoUtil/TestUtil.go b/internal/util/ArgoUtil/TestUtil_test.go similarity index 100% rename from internal/util/ArgoUtil/TestUtil.go rename to internal/util/ArgoUtil/TestUtil_test.go diff --git a/internal/util/ChartService.go b/internal/util/ChartService.go index cdbe42513a..c107f010bf 100644 --- a/internal/util/ChartService.go +++ b/internal/util/ChartService.go @@ -21,11 +21,10 @@ import ( "compress/gzip" "context" "fmt" - repository3 "github.com/argoproj/argo-cd/v2/pkg/apiclient/repository" - "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/devtron-labs/devtron/api/bean" repository4 "github.com/devtron-labs/devtron/client/argocdServer/repository" "github.com/devtron-labs/devtron/internal/sql/repository" + "github.com/devtron-labs/devtron/internal/util/ArgoUtil" appStoreBean "github.com/devtron-labs/devtron/pkg/appStore/bean" repository2 "github.com/devtron-labs/devtron/pkg/user/repository" "github.com/devtron-labs/devtron/util" @@ -64,7 +63,7 @@ type ChartTemplateService interface { GetGitOpsRepoName(appName string) string GetGitOpsRepoNameFromUrl(gitRepoUrl string) string CreateGitRepositoryForApp(gitOpsRepoName, baseTemplateName, version string, userId int32) (chartGitAttribute *ChartGitAttribute, err error) - RegisterInArgo(chartGitAttribute *ChartGitAttribute, ctx context.Context) error + RegisterInArgo(chartGitAttribute *ChartGitAttribute, ctx context.Context, acdToken string) error BuildChart(ctx context.Context, chartMetaData *chart.Metadata, referenceTemplatePath string) (string, error) PushChartToGitRepo(gitOpsRepoName, referenceTemplate, version, tempReferenceTemplateDir string, repoUrl string, userId int32) (err error) GetByteArrayRefChart(chartMetaData *chart.Metadata, referenceTemplatePath string) ([]byte, error) @@ -80,6 +79,7 @@ type ChartTemplateServiceImpl struct { gitOpsConfigRepository repository.GitOpsConfigRepository userRepository repository2.UserRepository repositoryService repository4.ServiceClient + ArgoRepositoryService ArgoUtil.RepositoryService } type ChartValues struct { @@ -96,7 +96,7 @@ func NewChartTemplateServiceImpl(logger *zap.SugaredLogger, client *http.Client, gitFactory *GitFactory, globalEnvVariables *util.GlobalEnvVariables, gitOpsConfigRepository repository.GitOpsConfigRepository, - userRepository repository2.UserRepository, repositoryService repository4.ServiceClient) *ChartTemplateServiceImpl { + userRepository repository2.UserRepository, repositoryService repository4.ServiceClient, ArgoRepositoryService ArgoUtil.RepositoryService) *ChartTemplateServiceImpl { return &ChartTemplateServiceImpl{ randSource: rand.NewSource(time.Now().UnixNano()), logger: logger, @@ -107,13 +107,16 @@ func NewChartTemplateServiceImpl(logger *zap.SugaredLogger, gitOpsConfigRepository: gitOpsConfigRepository, userRepository: userRepository, repositoryService: repositoryService, + ArgoRepositoryService: ArgoRepositoryService, } } -func (impl ChartTemplateServiceImpl) RegisterInArgo(chartGitAttribute *ChartGitAttribute, ctx context.Context) error { - repo := &v1alpha1.Repository{ + +func (impl ChartTemplateServiceImpl) RegisterInArgo(chartGitAttribute *ChartGitAttribute, ctx context.Context, acdToken string) error { + repo := &ArgoUtil.Repository{ Repo: chartGitAttribute.RepoUrl, } - repo, err := impl.repositoryService.Create(ctx, &repository3.RepoCreateRequest{Repo: repo, Upsert: true}) + repo, err := impl.ArgoRepositoryService.CreateRepository(repo, acdToken) + if err != nil { impl.logger.Errorw("error in creating argo Repository ", "err", err) return err diff --git a/pkg/appStore/bean/bean.go b/pkg/appStore/bean/bean.go index 927efd2002..d22fa4ee9d 100644 --- a/pkg/appStore/bean/bean.go +++ b/pkg/appStore/bean/bean.go @@ -98,6 +98,7 @@ type InstallAppVersionDTO struct { DeploymentAppType string `json:"deploymentAppType"` AcdPartialDelete bool `json:"acdPartialDelete"` AppStoreApplicationVersionId int + AcdToken string `json:"acdToken"` } type InstallAppVersionChartDTO struct { diff --git a/pkg/appStore/deployment/fullMode/AppStoreDeploymentFullModeService.go b/pkg/appStore/deployment/fullMode/AppStoreDeploymentFullModeService.go index 8e4e96e17f..04bd6097bc 100644 --- a/pkg/appStore/deployment/fullMode/AppStoreDeploymentFullModeService.go +++ b/pkg/appStore/deployment/fullMode/AppStoreDeploymentFullModeService.go @@ -40,8 +40,6 @@ import ( "time" "github.com/argoproj/argo-cd/v2/pkg/apiclient/application" - repository2 "github.com/argoproj/argo-cd/v2/pkg/apiclient/repository" - "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" application2 "github.com/devtron-labs/devtron/client/argocdServer/application" "github.com/devtron-labs/devtron/client/argocdServer/repository" "github.com/devtron-labs/devtron/internal/util" @@ -59,7 +57,6 @@ const ( type AppStoreDeploymentFullModeService interface { AppStoreDeployOperationGIT(installAppVersionRequest *appStoreBean.InstallAppVersionDTO, tx *pg.Tx) (*appStoreBean.InstallAppVersionDTO, *util.ChartGitAttribute, error) AppStoreDeployOperationACD(installAppVersionRequest *appStoreBean.InstallAppVersionDTO, chartGitAttr *util.ChartGitAttribute, ctx context.Context) (*appStoreBean.InstallAppVersionDTO, error) - RegisterInArgo(chartGitAttribute *util.ChartGitAttribute, ctx context.Context) error SyncACD(acdAppName string, ctx context.Context) UpdateValuesYaml(installAppVersionRequest *appStoreBean.InstallAppVersionDTO, tx *pg.Tx) (*appStoreBean.InstallAppVersionDTO, error) UpdateRequirementYaml(installAppVersionRequest *appStoreBean.InstallAppVersionDTO, appStoreAppVersion *appStoreDiscoverRepository.AppStoreApplicationVersion) error @@ -296,7 +293,8 @@ func (impl AppStoreDeploymentFullModeServiceImpl) AppStoreDeployOperationACD(ins ctx, cancel := context.WithTimeout(ctx, 1*time.Minute) defer cancel() //STEP 4: registerInArgo - err := impl.RegisterInArgo(chartGitAttr, ctx) + acdToken := installAppVersionRequest.AcdToken + err := impl.chartTemplateService.RegisterInArgo(chartGitAttr, ctx, acdToken) if err != nil { impl.logger.Errorw("error in argo registry", "err", err) return nil, err @@ -313,18 +311,6 @@ func (impl AppStoreDeploymentFullModeServiceImpl) AppStoreDeployOperationACD(ins return installAppVersionRequest, nil } -func (impl AppStoreDeploymentFullModeServiceImpl) RegisterInArgo(chartGitAttribute *util.ChartGitAttribute, ctx context.Context) error { - repo := &v1alpha1.Repository{ - Repo: chartGitAttribute.RepoUrl, - } - repo, err := impl.repositoryService.Create(ctx, &repository2.RepoCreateRequest{Repo: repo, Upsert: true}) - if err != nil { - impl.logger.Errorw("error in creating argo Repository ", "err", err) - } - impl.logger.Debugw("repo registered in argo", "name", chartGitAttribute.RepoUrl) - return err -} - func (impl AppStoreDeploymentFullModeServiceImpl) SyncACD(acdAppName string, ctx context.Context) { req := new(application.ApplicationSyncRequest) req.Name = &acdAppName diff --git a/pkg/appStore/deployment/tool/gitops/AppStoreDeploymentArgoCdService.go b/pkg/appStore/deployment/tool/gitops/AppStoreDeploymentArgoCdService.go index 3c8d4282d3..9037549ecc 100644 --- a/pkg/appStore/deployment/tool/gitops/AppStoreDeploymentArgoCdService.go +++ b/pkg/appStore/deployment/tool/gitops/AppStoreDeploymentArgoCdService.go @@ -562,7 +562,8 @@ func (impl AppStoreDeploymentArgoCdServiceImpl) patchAcdApp(ctx context.Context, ctx, cancel := context.WithTimeout(ctx, 1*time.Minute) defer cancel() //registerInArgo - err := impl.appStoreDeploymentFullModeService.RegisterInArgo(chartGitAttr, ctx) + acdToken := installAppVersionRequest.AcdToken + err := impl.chartTemplateService.RegisterInArgo(chartGitAttr, ctx, acdToken) if err != nil { impl.Logger.Errorw("error in argo registry", "err", err) return nil, err diff --git a/pkg/bean/app.go b/pkg/bean/app.go index 18c883ba26..3ea262eee1 100644 --- a/pkg/bean/app.go +++ b/pkg/bean/app.go @@ -531,6 +531,7 @@ type CdPipelines struct { Pipelines []*CDPipelineConfigObject `json:"pipelines,omitempty" validate:"dive"` AppId int `json:"appId,omitempty" validate:"number,required" ` UserId int32 `json:"-"` + AcdToken string `json:"acdToken"` } type CDPatchRequest struct { diff --git a/pkg/cluster/ClusterService.go b/pkg/cluster/ClusterService.go index c9cee9799a..dffb027c30 100644 --- a/pkg/cluster/ClusterService.go +++ b/pkg/cluster/ClusterService.go @@ -88,7 +88,7 @@ type DefaultClusterComponent struct { } type ClusterService interface { - Save(parent context.Context, bean *ClusterBean, userId int32) (*ClusterBean, error) + Save(parent context.Context, bean *ClusterBean, userId int32, acdToken string) (*ClusterBean, error) FindOne(clusterName string) (*ClusterBean, error) FindOneActive(clusterName string) (*ClusterBean, error) FindAll() ([]*ClusterBean, error) @@ -167,7 +167,7 @@ func (impl *ClusterServiceImpl) GetClusterConfig(cluster *ClusterBean) (*util.Cl return clusterCfg, nil } -func (impl *ClusterServiceImpl) Save(parent context.Context, bean *ClusterBean, userId int32) (*ClusterBean, error) { +func (impl *ClusterServiceImpl) Save(parent context.Context, bean *ClusterBean, userId int32, acdToken string) (*ClusterBean, error) { //validating config err := impl.CheckIfConfigIsValid(bean) if err != nil { diff --git a/pkg/cluster/ClusterServiceExtended.go b/pkg/cluster/ClusterServiceExtended.go index 512bfd5f4a..954ea279a1 100644 --- a/pkg/cluster/ClusterServiceExtended.go +++ b/pkg/cluster/ClusterServiceExtended.go @@ -6,6 +6,7 @@ import ( cluster3 "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" repository3 "github.com/devtron-labs/devtron/internal/sql/repository" + "github.com/devtron-labs/devtron/internal/util/ArgoUtil" repository4 "github.com/devtron-labs/devtron/pkg/user/repository" v12 "k8s.io/client-go/kubernetes/typed/core/v1" "k8s.io/client-go/rest" @@ -33,6 +34,7 @@ type ClusterServiceImplExtended struct { K8sInformerFactory informer.K8sInformerFactory gitOpsRepository repository3.GitOpsConfigRepository *ClusterServiceImpl + ArgoClusterService ArgoUtil.ArgoClusterService } func NewClusterServiceImplExtended(repository repository.ClusterRepository, environmentRepository repository.EnvironmentRepository, @@ -40,13 +42,14 @@ func NewClusterServiceImplExtended(repository repository.ClusterRepository, envi K8sUtil *util.K8sUtil, clusterServiceCD cluster2.ServiceClient, K8sInformerFactory informer.K8sInformerFactory, gitOpsRepository repository3.GitOpsConfigRepository, userAuthRepository repository4.UserAuthRepository, - userRepository repository4.UserRepository, roleGroupRepository repository4.RoleGroupRepository) *ClusterServiceImplExtended { + userRepository repository4.UserRepository, roleGroupRepository repository4.RoleGroupRepository, ArgoClusterService ArgoUtil.ArgoClusterService) *ClusterServiceImplExtended { clusterServiceExt := &ClusterServiceImplExtended{ environmentRepository: environmentRepository, grafanaClient: grafanaClient, installedAppRepository: installedAppRepository, clusterServiceCD: clusterServiceCD, gitOpsRepository: gitOpsRepository, + ArgoClusterService: ArgoClusterService, ClusterServiceImpl: &ClusterServiceImpl{ clusterRepository: repository, logger: logger, @@ -318,13 +321,13 @@ func (impl *ClusterServiceImplExtended) CreateGrafanaDataSource(clusterBean *Clu return grafanaDatasourceId, nil } -func (impl *ClusterServiceImplExtended) Save(ctx context.Context, bean *ClusterBean, userId int32) (*ClusterBean, error) { +func (impl *ClusterServiceImplExtended) Save(ctx context.Context, bean *ClusterBean, userId int32, acdToken string) (*ClusterBean, error) { isGitOpsConfigured, err := impl.gitOpsRepository.IsGitOpsConfigured() if err != nil { return nil, err } - clusterBean, err := impl.ClusterServiceImpl.Save(ctx, bean, userId) + clusterBean, err := impl.ClusterServiceImpl.Save(ctx, bean, userId, acdToken) if err != nil { return nil, err } @@ -338,21 +341,19 @@ func (impl *ClusterServiceImplExtended) Save(ctx context.Context, bean *ClusterB if configMap["bearer_token"] != "" { bearerToken = configMap["bearer_token"] } - tlsConfig := v1alpha1.TLSClientConfig{ + tlsConfig := ArgoUtil.TLSClientConfig{ Insecure: true, } - cdClusterConfig := v1alpha1.ClusterConfig{ + cdClusterConfig := ArgoUtil.ClusterConfig{ BearerToken: bearerToken, TLSClientConfig: tlsConfig, } - - cl := &v1alpha1.Cluster{ + cl := &ArgoUtil.ClusterRequest{ Name: bean.ClusterName, Server: serverUrl, Config: cdClusterConfig, } - - _, err = impl.clusterServiceCD.Create(ctx, &cluster3.ClusterCreateRequest{Upsert: true, Cluster: cl}) + _, err = impl.ArgoClusterService.CreateClusterWithGitOps(cl, acdToken) if err != nil { impl.logger.Errorw("service err, Save", "err", err, "payload", cl) err1 := impl.ClusterServiceImpl.Delete(bean, userId) //FIXME nishant call local diff --git a/pkg/pipeline/PipelineBuilder.go b/pkg/pipeline/PipelineBuilder.go index a1c0a571ab..1cb9a1983d 100644 --- a/pkg/pipeline/PipelineBuilder.go +++ b/pkg/pipeline/PipelineBuilder.go @@ -1686,7 +1686,8 @@ func (impl PipelineBuilderImpl) RegisterInACD(app *app2.App, pipelineCreateReque impl.logger.Errorw("error in pushing chart to git ", "path", chartGitAttr.ChartLocation, "err", err) return err } - err = impl.chartTemplateService.RegisterInArgo(chartGitAttr, ctx) + acdToken := pipelineCreateRequest.AcdToken + err = impl.chartTemplateService.RegisterInArgo(chartGitAttr, ctx, acdToken) if err != nil { impl.logger.Errorw("error while register git repo in argo", "err", err) emptyRepoErrorMessage := []string{"failed to get index: 404 Not Found", "remote repository is empty"} @@ -1698,7 +1699,7 @@ func (impl PipelineBuilderImpl) RegisterInACD(app *app2.App, pipelineCreateReque return err } // - retry register in argo - err = impl.chartTemplateService.RegisterInArgo(chartGitAttr, ctx) + err = impl.chartTemplateService.RegisterInArgo(chartGitAttr, ctx, acdToken) if err != nil { impl.logger.Errorw("error in re-try register in argo", "err", err) return err diff --git a/wire_gen.go b/wire_gen.go index 7d4a1a1419..214844eeb7 100644 --- a/wire_gen.go +++ b/wire_gen.go @@ -209,7 +209,9 @@ func InitializeApp() (*App, error) { userAuthRepositoryImpl := repository4.NewUserAuthRepositoryImpl(db, sugaredLogger, defaultAuthPolicyRepositoryImpl, defaultAuthRoleRepositoryImpl) userRepositoryImpl := repository4.NewUserRepositoryImpl(db, sugaredLogger) roleGroupRepositoryImpl := repository4.NewRoleGroupRepositoryImpl(db, sugaredLogger) - clusterServiceImplExtended := cluster2.NewClusterServiceImplExtended(clusterRepositoryImpl, environmentRepositoryImpl, grafanaClientImpl, sugaredLogger, installedAppRepositoryImpl, k8sUtil, serviceClientImpl, k8sInformerFactoryImpl, gitOpsConfigRepositoryImpl, userAuthRepositoryImpl, userRepositoryImpl, roleGroupRepositoryImpl) + argoSession := ArgoUtil.NewArgoSession(httpClient, sugaredLogger) + argoClusterServiceImpl := ArgoUtil.NewArgoClusterServiceImpl(argoSession) + clusterServiceImplExtended := cluster2.NewClusterServiceImplExtended(clusterRepositoryImpl, environmentRepositoryImpl, grafanaClientImpl, sugaredLogger, installedAppRepositoryImpl, k8sUtil, serviceClientImpl, k8sInformerFactoryImpl, gitOpsConfigRepositoryImpl, userAuthRepositoryImpl, userRepositoryImpl, roleGroupRepositoryImpl, argoClusterServiceImpl) helmClientConfig, err := client3.GetConfig() if err != nil { return nil, err @@ -310,7 +312,8 @@ func InitializeApp() (*App, error) { return nil, err } repositoryServiceClientImpl := repository7.NewServiceClientImpl(sugaredLogger, argoCDConnectionManagerImpl) - chartTemplateServiceImpl := util.NewChartTemplateServiceImpl(sugaredLogger, chartWorkingDir, httpClient, gitFactory, globalEnvVariables, gitOpsConfigRepositoryImpl, userRepositoryImpl, repositoryServiceClientImpl) + repositoryServiceImpl := ArgoUtil.NewRepositoryService(argoSession) + chartTemplateServiceImpl := util.NewChartTemplateServiceImpl(sugaredLogger, chartWorkingDir, httpClient, gitFactory, globalEnvVariables, gitOpsConfigRepositoryImpl, userRepositoryImpl, repositoryServiceClientImpl, repositoryServiceImpl) refChartDir := _wireRefChartDirValue chartRepoRepositoryImpl := chartRepoRepository.NewChartRepoRepositoryImpl(db) defaultChart := _wireDefaultChartValue @@ -504,14 +507,6 @@ func InitializeApp() (*App, error) { terminalSessionHandlerImpl := terminal.NewTerminalSessionHandlerImpl(environmentServiceImpl, clusterServiceImplExtended, sugaredLogger) argoApplicationRestHandlerImpl := restHandler.NewArgoApplicationRestHandlerImpl(applicationServiceClientImpl, pumpImpl, enforcerImpl, teamServiceImpl, environmentServiceImpl, sugaredLogger, enforcerUtilImpl, terminalSessionHandlerImpl, argoUserServiceImpl, k8sResourceHistoryServiceImpl, userServiceImpl) applicationRouterImpl := router.NewApplicationRouterImpl(argoApplicationRestHandlerImpl, sugaredLogger) - argoConfig, err := ArgoUtil.GetArgoConfig() - if err != nil { - return nil, err - } - argoSession, err := ArgoUtil.NewArgoSession(argoConfig, sugaredLogger) - if err != nil { - return nil, err - } resourceServiceImpl := ArgoUtil.NewResourceServiceImpl(argoSession) cdRestHandlerImpl := restHandler.NewCDRestHandlerImpl(sugaredLogger, resourceServiceImpl) cdRouterImpl := router.NewCDRouterImpl(sugaredLogger, cdRestHandlerImpl)