未验证 提交 559c1fcf 编写于 作者: R runzexia

clean old devops code

todo impl use informer
Signed-off-by: Nrunzexia <runzexia@yunify.com>
上级 c80a17f4
......@@ -17,7 +17,6 @@ import (
"kubesphere.io/kubesphere/pkg/simple/client/ldap"
esclient "kubesphere.io/kubesphere/pkg/simple/client/logging/elasticsearch"
"kubesphere.io/kubesphere/pkg/simple/client/monitoring/prometheus"
"kubesphere.io/kubesphere/pkg/simple/client/mysql"
"kubesphere.io/kubesphere/pkg/simple/client/openpitrix"
"kubesphere.io/kubesphere/pkg/simple/client/s3"
fakes3 "kubesphere.io/kubesphere/pkg/simple/client/s3/fake"
......@@ -44,7 +43,6 @@ func NewServerRunOptions() *ServerRunOptions {
DevopsOptions: jenkins.NewDevopsOptions(),
SonarQubeOptions: sonarqube.NewSonarQubeOptions(),
ServiceMeshOptions: servicemesh.NewServiceMeshOptions(),
MySQLOptions: mysql.NewMySQLOptions(),
MonitoringOptions: prometheus.NewPrometheusOptions(),
S3Options: s3.NewS3Options(),
OpenPitrixOptions: openpitrix.NewOptions(),
......@@ -64,7 +62,6 @@ func (s *ServerRunOptions) Flags() (fss cliflag.NamedFlagSets) {
s.GenericServerRunOptions.AddFlags(fs, s.GenericServerRunOptions)
s.KubernetesOptions.AddFlags(fss.FlagSet("kubernetes"), s.KubernetesOptions)
s.AuthenticationOptions.AddFlags(fss.FlagSet("authentication"), s.AuthenticationOptions)
s.MySQLOptions.AddFlags(fss.FlagSet("mysql"), s.MySQLOptions)
s.DevopsOptions.AddFlags(fss.FlagSet("devops"), s.DevopsOptions)
s.SonarQubeOptions.AddFlags(fss.FlagSet("sonarqube"), s.SonarQubeOptions)
s.LdapOptions.AddFlags(fss.FlagSet("ldap"), s.LdapOptions)
......@@ -167,14 +164,6 @@ func (s *ServerRunOptions) NewAPIServer(stopCh <-chan struct{}) (*apiserver.APIS
}
}
if s.MySQLOptions.Host != "" {
dbClient, err := mysql.NewMySQLClient(s.MySQLOptions, stopCh)
if err != nil {
return nil, err
}
apiServer.DBClient = dbClient
}
server := &http.Server{
Addr: fmt.Sprintf(":%d", s.GenericServerRunOptions.InsecurePort),
}
......
......@@ -8,7 +8,6 @@ func (s *ServerRunOptions) Validate() []error {
errors = append(errors, s.GenericServerRunOptions.Validate()...)
errors = append(errors, s.DevopsOptions.Validate()...)
errors = append(errors, s.KubernetesOptions.Validate()...)
errors = append(errors, s.MySQLOptions.Validate()...)
errors = append(errors, s.ServiceMeshOptions.Validate()...)
errors = append(errors, s.MonitoringOptions.Validate()...)
errors = append(errors, s.SonarQubeOptions.Validate()...)
......
......@@ -46,7 +46,6 @@ import (
"kubesphere.io/kubesphere/pkg/simple/client/ldap"
"kubesphere.io/kubesphere/pkg/simple/client/logging"
"kubesphere.io/kubesphere/pkg/simple/client/monitoring"
"kubesphere.io/kubesphere/pkg/simple/client/mysql"
"kubesphere.io/kubesphere/pkg/simple/client/openpitrix"
"kubesphere.io/kubesphere/pkg/simple/client/s3"
"kubesphere.io/kubesphere/pkg/simple/client/sonarqube"
......@@ -106,9 +105,6 @@ type APIServer struct {
//
S3Client s3.Interface
//
DBClient *mysql.Client
//
LdapClient ldap.Interface
......@@ -150,9 +146,9 @@ func (s *APIServer) installKubeSphereAPIs() {
urlruntime.Must(oauth.AddToContainer(s.container, token.NewJwtTokenIssuer(token.DefaultIssuerName, s.Config.AuthenticationOptions, s.CacheClient), s.Config.AuthenticationOptions))
urlruntime.Must(servicemeshv1alpha2.AddToContainer(s.container))
devopsv1alpha2Service := ksruntime.NewWebService(devopsv1alpha2.GroupVersion)
urlruntime.Must(devopsv1alpha2.AddPipelineToWebService(devopsv1alpha2Service, s.DevopsClient, s.DBClient.Database()))
urlruntime.Must(devopsv1alpha2.AddPipelineToWebService(devopsv1alpha2Service, s.DevopsClient))
urlruntime.Must(devopsv1alpha2.AddS2IToWebService(devopsv1alpha2Service, s.KubernetesClient.KubeSphere(), s.InformerFactory.KubeSphereSharedInformerFactory(), s.S3Client))
urlruntime.Must(devopsv1alpha2.AddSonarToWebService(devopsv1alpha2Service, s.DevopsClient, s.DBClient.Database(), s.SonarClient))
urlruntime.Must(devopsv1alpha2.AddSonarToWebService(devopsv1alpha2Service, s.DevopsClient, s.SonarClient))
s.container.Add(devopsv1alpha2Service)
}
......
......@@ -14,7 +14,6 @@ import (
"kubesphere.io/kubesphere/pkg/simple/client/ldap"
"kubesphere.io/kubesphere/pkg/simple/client/logging/elasticsearch"
"kubesphere.io/kubesphere/pkg/simple/client/monitoring/prometheus"
"kubesphere.io/kubesphere/pkg/simple/client/mysql"
"kubesphere.io/kubesphere/pkg/simple/client/notification"
"kubesphere.io/kubesphere/pkg/simple/client/openpitrix"
"kubesphere.io/kubesphere/pkg/simple/client/s3"
......@@ -62,7 +61,6 @@ const (
// Config defines everything needed for apiserver to deal with external services
type Config struct {
MySQLOptions *mysql.Options `json:"mysql,omitempty" yaml:"mysql,omitempty" mapstructure:"mysql"`
DevopsOptions *jenkins.Options `json:"devops,omitempty" yaml:"devops,omitempty" mapstructure:"devops"`
SonarQubeOptions *sonarqube.Options `json:"sonarqube,omitempty" yaml:"sonarQube,omitempty" mapstructure:"sonarqube"`
KubernetesOptions *k8s.KubernetesOptions `json:"kubernetes,omitempty" yaml:"kubernetes,omitempty" mapstructure:"kubernetes"`
......@@ -83,7 +81,6 @@ type Config struct {
// newConfig creates a default non-empty Config
func New() *Config {
return &Config{
MySQLOptions: mysql.NewMySQLOptions(),
DevopsOptions: jenkins.NewDevopsOptions(),
SonarQubeOptions: sonarqube.NewSonarQubeOptions(),
KubernetesOptions: k8s.NewKubernetesOptions(),
......@@ -176,9 +173,6 @@ func (conf *Config) ToMap() map[string]bool {
// Remove invalid options before serializing to json or yaml
func (conf *Config) stripEmptyOptions() {
if conf.MySQLOptions != nil && conf.MySQLOptions.Host == "" {
conf.MySQLOptions = nil
}
if conf.RedisOptions != nil && conf.RedisOptions.Host == "" {
conf.RedisOptions = nil
......
......@@ -14,7 +14,6 @@ import (
"kubesphere.io/kubesphere/pkg/simple/client/ldap"
"kubesphere.io/kubesphere/pkg/simple/client/logging/elasticsearch"
"kubesphere.io/kubesphere/pkg/simple/client/monitoring/prometheus"
"kubesphere.io/kubesphere/pkg/simple/client/mysql"
"kubesphere.io/kubesphere/pkg/simple/client/notification"
"kubesphere.io/kubesphere/pkg/simple/client/openpitrix"
"kubesphere.io/kubesphere/pkg/simple/client/s3"
......@@ -28,14 +27,6 @@ import (
func newTestConfig() (*Config, error) {
var conf = &Config{
MySQLOptions: &mysql.Options{
Host: "10.68.96.5:3306",
Username: "root",
Password: "admin",
MaxIdleConnections: 10,
MaxOpenConnections: 20,
MaxConnectionLifeTime: time.Duration(10) * time.Second,
},
DevopsOptions: &jenkins.Options{
Host: "http://ks-devops.kubesphere-devops-system.svc",
Username: "jenkins",
......
......@@ -5,28 +5,22 @@ import (
"kubesphere.io/kubesphere/pkg/client/informers/externalversions"
"kubesphere.io/kubesphere/pkg/models/devops"
devopsClient "kubesphere.io/kubesphere/pkg/simple/client/devops"
"kubesphere.io/kubesphere/pkg/simple/client/mysql"
"kubesphere.io/kubesphere/pkg/simple/client/s3"
"kubesphere.io/kubesphere/pkg/simple/client/sonarqube"
)
type ProjectPipelineHandler struct {
projectMemberOperator devops.ProjectMemberOperator
devopsOperator devops.DevopsOperator
projectOperator devops.ProjectOperator
projectCredentialGetter devops.ProjectCredentialGetter
}
type PipelineSonarHandler struct {
pipelineSonarGetter devops.PipelineSonarGetter
projectOperator devops.ProjectOperator
}
func NewProjectPipelineHandler(devopsClient devopsClient.Interface, dbClient *mysql.Database) ProjectPipelineHandler {
func NewProjectPipelineHandler(devopsClient devopsClient.Interface) ProjectPipelineHandler {
return ProjectPipelineHandler{
projectMemberOperator: devops.NewProjectMemberOperator(devopsClient, dbClient),
devopsOperator: devops.NewDevopsOperator(devopsClient),
projectOperator: devops.NewProjectOperator(dbClient),
projectCredentialGetter: devops.NewProjectCredentialOperator(devopsClient),
}
}
......
/*
Copyright 2019 The KubeSphere Authors.
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 v1alpha2
import (
"fmt"
"github.com/asaskevich/govalidator"
"github.com/emicklei/go-restful"
"k8s.io/klog"
"kubesphere.io/kubesphere/pkg/api"
"kubesphere.io/kubesphere/pkg/constants"
"kubesphere.io/kubesphere/pkg/server/params"
"kubesphere.io/kubesphere/pkg/simple/client/devops"
"kubesphere.io/kubesphere/pkg/utils/reflectutils"
)
func (h ProjectPipelineHandler) GetDevOpsProjectMembersHandler(request *restful.Request, resp *restful.Response) {
projectId := request.PathParameter("devops")
orderBy := request.QueryParameter(params.OrderByParam)
reverse := params.GetBoolValueWithDefault(request, params.ReverseParam, false)
limit, offset := params.ParsePaging(request)
conditions, err := params.ParseConditions(request)
project, err := h.projectMemberOperator.GetProjectMembers(projectId, conditions, orderBy, reverse, limit, offset)
if err != nil {
klog.Errorf("%+v", err)
api.HandleInternalError(resp, nil, err)
return
}
resp.WriteAsJson(project)
return
}
func (h ProjectPipelineHandler) GetDevOpsProjectMemberHandler(request *restful.Request, resp *restful.Response) {
projectId := request.PathParameter("devops")
member := request.PathParameter("member")
project, err := h.projectMemberOperator.GetProjectMember(projectId, member)
if err != nil {
klog.Errorf("%+v", err)
api.HandleInternalError(resp, nil, err)
return
}
resp.WriteAsJson(project)
return
}
func (h ProjectPipelineHandler) AddDevOpsProjectMemberHandler(request *restful.Request, resp *restful.Response) {
projectId := request.PathParameter("devops")
username := request.HeaderParameter(constants.UserNameHeader)
member := &devops.ProjectMembership{}
err := request.ReadEntity(&member)
if err != nil {
klog.Errorf("%+v", err)
api.HandleBadRequest(resp, request, err)
return
}
if govalidator.IsNull(member.Username) {
err := fmt.Errorf("error need username")
klog.Errorf("%+v", err)
api.HandleBadRequest(resp, request, err)
return
}
if !reflectutils.In(member.Role, devops.AllRoleSlice) {
err := fmt.Errorf("err role [%s] not in [%s]", member.Role,
devops.AllRoleSlice)
klog.Errorf("%+v", err)
api.HandleBadRequest(resp, request, err)
return
}
member.GrantBy = username
project, err := h.projectMemberOperator.AddProjectMember(projectId, member)
if err != nil {
klog.Errorf("%+v", err)
api.HandleInternalError(resp, nil, err)
return
}
resp.WriteAsJson(project)
return
}
func (h ProjectPipelineHandler) UpdateDevOpsProjectMemberHandler(request *restful.Request, resp *restful.Response) {
projectId := request.PathParameter("devops")
username := request.HeaderParameter(constants.UserNameHeader)
member := &devops.ProjectMembership{}
err := request.ReadEntity(&member)
if err != nil {
klog.Errorf("%+v", err)
api.HandleBadRequest(resp, request, err)
return
}
member.Username = request.PathParameter("member")
if govalidator.IsNull(member.Username) {
err := fmt.Errorf("error need username")
klog.Errorf("%+v", err)
api.HandleBadRequest(resp, request, err)
return
}
if username == member.Username {
err := fmt.Errorf("you can not change your role")
klog.Errorf("%+v", err)
api.HandleBadRequest(resp, request, err)
return
}
if !reflectutils.In(member.Role, devops.AllRoleSlice) {
err := fmt.Errorf("err role [%s] not in [%s]", member.Role,
devops.AllRoleSlice)
klog.Errorf("%+v", err)
api.HandleBadRequest(resp, request, err)
return
}
project, err := h.projectMemberOperator.UpdateProjectMember(projectId, member)
if err != nil {
klog.Errorf("%+v", err)
api.HandleInternalError(resp, nil, err)
return
}
resp.WriteAsJson(project)
return
}
func (h ProjectPipelineHandler) DeleteDevOpsProjectMemberHandler(request *restful.Request, resp *restful.Response) {
projectId := request.PathParameter("devops")
username := request.HeaderParameter(constants.UserNameHeader)
member := request.PathParameter("member")
username, err := h.projectMemberOperator.DeleteProjectMember(projectId, member)
if err != nil {
klog.Errorf("%+v", err)
api.HandleInternalError(resp, nil, err)
return
}
resp.WriteAsJson(struct {
Username string `json:"username"`
}{Username: username})
return
}
/*
Copyright 2019 The KubeSphere Authors.
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 v1alpha2
import (
"github.com/emicklei/go-restful"
"k8s.io/klog"
"kubesphere.io/kubesphere/pkg/api"
"kubesphere.io/kubesphere/pkg/api/devops/v1alpha2"
"kubesphere.io/kubesphere/pkg/simple/client/devops"
)
func (h ProjectPipelineHandler) GetDevOpsProjectHandler(request *restful.Request, resp *restful.Response) {
projectId := request.PathParameter("devops")
project, err := h.projectOperator.GetProject(projectId)
if err != nil {
klog.Errorf("%+v", err)
api.HandleInternalError(resp, nil, err)
return
}
resp.WriteAsJson(project)
return
}
func (h ProjectPipelineHandler) UpdateProjectHandler(request *restful.Request, resp *restful.Response) {
projectId := request.PathParameter("devops")
var project *v1alpha2.DevOpsProject
err := request.ReadEntity(&project)
if err != nil {
klog.Errorf("%+v", err)
api.HandleBadRequest(resp, request, err)
return
}
project.ProjectId = projectId
project, err = h.projectOperator.UpdateProject(project)
if err != nil {
klog.Errorf("%+v", err)
api.HandleInternalError(resp, nil, err)
return
}
resp.WriteAsJson(project)
return
}
func GetDevOpsProjectDefaultRoles(request *restful.Request, resp *restful.Response) {
resp.WriteAsJson(devops.DefaultRoles)
return
}
......@@ -22,19 +22,16 @@ import (
"github.com/emicklei/go-restful"
"github.com/emicklei/go-restful-openapi"
"k8s.io/apimachinery/pkg/runtime/schema"
"kubesphere.io/kubesphere/pkg/api/devops/v1alpha2"
devopsv1alpha1 "kubesphere.io/kubesphere/pkg/apis/devops/v1alpha1"
"kubesphere.io/kubesphere/pkg/client/clientset/versioned"
"kubesphere.io/kubesphere/pkg/client/informers/externalversions"
"kubesphere.io/kubesphere/pkg/constants"
"kubesphere.io/kubesphere/pkg/simple/client/mysql"
"kubesphere.io/kubesphere/pkg/simple/client/s3"
"kubesphere.io/kubesphere/pkg/simple/client/sonarqube"
//"kubesphere.io/kubesphere/pkg/models/devops"
"kubesphere.io/kubesphere/pkg/simple/client/devops"
"kubesphere.io/kubesphere/pkg/server/params"
"net/http"
)
......@@ -45,89 +42,12 @@ const (
var GroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha2"}
func AddPipelineToWebService(webservice *restful.WebService, devopsClient devops.Interface,
dbClient *mysql.Database) error {
func AddPipelineToWebService(webservice *restful.WebService, devopsClient devops.Interface) error {
projectPipelineEnable := devopsClient != nil && dbClient != nil
projectPipelineEnable := devopsClient != nil
if projectPipelineEnable {
projectPipelineHandler := NewProjectPipelineHandler(devopsClient, dbClient)
webservice.Route(webservice.GET("/devops/{devops}").
To(projectPipelineHandler.GetDevOpsProjectHandler).
Doc("Get the specified DevOps Project").
Metadata(restfulspec.KeyOpenAPITags, []string{constants.DevOpsProjectTag}).
Param(webservice.PathParameter("devops", "DevOps project's ID, e.g. project-RRRRAzLBlLEm")).
Returns(http.StatusOK, RespOK, v1alpha2.DevOpsProject{}).
Writes(v1alpha2.DevOpsProject{}))
webservice.Route(webservice.PATCH("/devops/{devops}").
To(projectPipelineHandler.UpdateProjectHandler).
Doc("Update the specified DevOps Project").
Metadata(restfulspec.KeyOpenAPITags, []string{constants.DevOpsProjectTag}).
Param(webservice.PathParameter("devops", "DevOps project's ID, e.g. project-RRRRAzLBlLEm")).
Reads(v1alpha2.DevOpsProject{}).
Returns(http.StatusOK, RespOK, v1alpha2.DevOpsProject{}).
Writes(v1alpha2.DevOpsProject{}))
webservice.Route(webservice.GET("/devops/{devops}/defaultroles").
To(GetDevOpsProjectDefaultRoles).
Doc("Get the build-in roles info of the specified DevOps project").
Metadata(restfulspec.KeyOpenAPITags, []string{constants.DevOpsProjectMemberTag}).
Param(webservice.PathParameter("devops", "DevOps project's ID, e.g. project-RRRRAzLBlLEm")).
Returns(http.StatusOK, RespOK, []devops.Role{}).
Writes([]devops.Role{}))
webservice.Route(webservice.GET("/devops/{devops}/members").
To(projectPipelineHandler.GetDevOpsProjectMembersHandler).
Doc("Get the members of the specified DevOps project").
Metadata(restfulspec.KeyOpenAPITags, []string{constants.DevOpsProjectMemberTag}).
Param(webservice.PathParameter("devops", "DevOps project's ID, e.g. project-RRRRAzLBlLEm")).
Param(webservice.QueryParameter(params.PagingParam, "page").
Required(false).
DataFormat("limit=%d,page=%d").
DefaultValue("limit=10,page=1")).
Param(webservice.QueryParameter(params.ConditionsParam, "query conditions, support using key-value pairs separated by comma to search, like 'conditions:somekey=somevalue,anotherkey=anothervalue'").
Required(false).
DataFormat("key=%s,key~%s")).
Returns(http.StatusOK, RespOK, []devops.ProjectMembership{}).
Writes([]devops.ProjectMembership{}))
webservice.Route(webservice.GET("/devops/{devops}/members/{member}").
To(projectPipelineHandler.GetDevOpsProjectMemberHandler).
Doc("Get the specified member of the DevOps project").
Metadata(restfulspec.KeyOpenAPITags, []string{constants.DevOpsProjectMemberTag}).
Param(webservice.PathParameter("devops", "DevOps project's ID, e.g. project-RRRRAzLBlLEm")).
Param(webservice.PathParameter("member", "member's username, e.g. admin")).
Returns(http.StatusOK, RespOK, devops.ProjectMembership{}).
Writes(devops.ProjectMembership{}))
webservice.Route(webservice.POST("/devops/{devops}/members").
To(projectPipelineHandler.AddDevOpsProjectMemberHandler).
Doc("Add a member to the specified DevOps project").
Metadata(restfulspec.KeyOpenAPITags, []string{constants.DevOpsProjectMemberTag}).
Param(webservice.PathParameter("devops", "DevOps project's ID, e.g. project-RRRRAzLBlLEm")).
Returns(http.StatusOK, RespOK, devops.ProjectMembership{}).
Writes(devops.ProjectMembership{}).
Reads(devops.ProjectMembership{}))
webservice.Route(webservice.PATCH("/devops/{devops}/members/{member}").
To(projectPipelineHandler.UpdateDevOpsProjectMemberHandler).
Doc("Update the specified member of the DevOps project").
Metadata(restfulspec.KeyOpenAPITags, []string{constants.DevOpsProjectMemberTag}).
Param(webservice.PathParameter("devops", "DevOps project's ID, e.g. project-RRRRAzLBlLEm")).
Param(webservice.PathParameter("member", "member's username, e.g. admin")).
Returns(http.StatusOK, RespOK, devops.ProjectMembership{}).
Reads(devops.ProjectMembership{}).
Writes(devops.ProjectMembership{}))
webservice.Route(webservice.DELETE("/devops/{devops}/members/{member}").
To(projectPipelineHandler.DeleteDevOpsProjectMemberHandler).
Doc("Delete the specified member of the DevOps project").
Metadata(restfulspec.KeyOpenAPITags, []string{constants.DevOpsProjectMemberTag}).
Param(webservice.PathParameter("devops", "DevOps project's ID, e.g. project-RRRRAzLBlLEm")).
Param(webservice.PathParameter("member", "member's username, e.g. admin")).
Writes(devops.ProjectMembership{}))
projectPipelineHandler := NewProjectPipelineHandler(devopsClient)
webservice.Route(webservice.GET("/devops/{devops}/credentials/{credential}/usage").
To(projectPipelineHandler.GetProjectCredentialUsage).
......@@ -137,7 +57,7 @@ func AddPipelineToWebService(webservice *restful.WebService, devopsClient devops
Param(webservice.PathParameter("credential", "credential's ID, e.g. dockerhub-id")).
Returns(http.StatusOK, RespOK, devops.Credential{}))
// match Jenkisn api "/blue/rest/organizations/jenkins/pipelines/{devops}/{pipeline}"
// match Jenkins api "/blue/rest/organizations/jenkins/pipelines/{devops}/{pipeline}"
webservice.Route(webservice.GET("/devops/{devops}/pipelines/{pipeline}").
To(projectPipelineHandler.GetPipeline).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.DevOpsPipelineTag}).
......@@ -147,7 +67,7 @@ func AddPipelineToWebService(webservice *restful.WebService, devopsClient devops
Returns(http.StatusOK, RespOK, devops.Pipeline{}).
Writes(devops.Pipeline{}))
// match Jenkisn api: "jenkins_api/blue/rest/search"
// match Jenkins api: "jenkins_api/blue/rest/search"
webservice.Route(webservice.GET("/search").
To(projectPipelineHandler.ListPipelines).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.DevOpsPipelineTag}).
......@@ -178,7 +98,7 @@ func AddPipelineToWebService(webservice *restful.WebService, devopsClient devops
Returns(http.StatusOK, RespOK, devops.PipelineRun{}).
Writes(devops.PipelineRun{}))
// match Jenkisn api "/blue/rest/organizations/jenkins/pipelines/{devops}/{pipeline}/runs/"
// match Jenkins api "/blue/rest/organizations/jenkins/pipelines/{devops}/{pipeline}/runs/"
webservice.Route(webservice.GET("/devops/{devops}/pipelines/{pipeline}/runs").
To(projectPipelineHandler.ListPipelineRuns).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.DevOpsPipelineTag}).
......@@ -689,7 +609,7 @@ func AddPipelineToWebService(webservice *restful.WebService, devopsClient devops
return nil
}
func AddSonarToWebService(webservice *restful.WebService, devopsClient devops.Interface, dbClient *mysql.Database, sonarClient sonarqube.SonarInterface) error {
func AddSonarToWebService(webservice *restful.WebService, devopsClient devops.Interface, sonarClient sonarqube.SonarInterface) error {
sonarEnable := devopsClient != nil && sonarClient != nil
if sonarEnable {
sonarHandler := NewPipelineSonarHandler(devopsClient, sonarClient)
......
......@@ -190,7 +190,7 @@ func (h *tenantHandler) ListDevopsProjects(req *restful.Request, resp *restful.R
}
conditions.Match["workspace"] = workspace
result, err := h.tenant.ListDevopsProjects(username, conditions, orderBy, reverse, limit, offset)
result, err := h.tenant.ListDevopsProjects(conditions, orderBy, reverse, limit, offset)
if err != nil {
api.HandleInternalError(resp, nil, err)
......@@ -199,41 +199,3 @@ func (h *tenantHandler) ListDevopsProjects(req *restful.Request, resp *restful.R
resp.WriteEntity(result)
}
func (h *tenantHandler) GetDevOpsProjectsCount(req *restful.Request, resp *restful.Response) {
username := req.HeaderParameter(constants.UserNameHeader)
result, err := h.tenant.ListDevopsProjects(username, nil, "", false, 1, 0)
if err != nil {
api.HandleInternalError(resp, nil, err)
return
}
resp.WriteEntity(struct {
Count int `json:"count"`
}{Count: result.TotalCount})
}
func (h *tenantHandler) DeleteDevopsProject(req *restful.Request, resp *restful.Response) {
projectId := req.PathParameter("devops")
workspace := req.PathParameter("workspace")
username := req.HeaderParameter(constants.UserNameHeader)
_, err := h.tenant.DescribeWorkspace("", workspace)
if err != nil {
api.HandleInternalError(resp, req, err)
return
}
err = h.tenant.DeleteDevOpsProject(username, projectId)
if err != nil {
api.HandleInternalError(resp, nil, err)
return
}
resp.WriteEntity(apierr.None)
}
func (h *tenantHandler) CreateDevopsProject(req *restful.Request, resp *restful.Response) {
}
......@@ -23,7 +23,6 @@ import (
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"kubesphere.io/kubesphere/pkg/api"
devopsv1alpha2 "kubesphere.io/kubesphere/pkg/api/devops/v1alpha2"
"kubesphere.io/kubesphere/pkg/apis/tenant/v1alpha1"
"kubesphere.io/kubesphere/pkg/apiserver/runtime"
"kubesphere.io/kubesphere/pkg/constants"
......@@ -97,41 +96,6 @@ func AddToContainer(c *restful.Container, k8sClient k8s.Client, factory informer
DataFormat("key=%s,key~%s")).
Doc("List devops projects for the current user").
Metadata(restfulspec.KeyOpenAPITags, []string{constants.TenantResourcesTag}))
ws.Route(ws.GET("/workspaces/{workspace}/members/{member}/devops").
To(handler.ListDevopsProjects).
Param(ws.PathParameter("workspace", "workspace name")).
Param(ws.PathParameter("member", "workspace member's username")).
Param(ws.QueryParameter(params.PagingParam, "page").
Required(false).
DataFormat("limit=%d,page=%d").
DefaultValue("limit=10,page=1")).
Param(ws.QueryParameter(params.ConditionsParam, "query conditions").
Required(false).
DataFormat("key=%s,key~%s")).
Returns(http.StatusOK, api.StatusOK, models.PageableResponse{}).
Doc("List the devops projects for the workspace member").
Metadata(restfulspec.KeyOpenAPITags, []string{constants.TenantResourcesTag}))
ws.Route(ws.GET("/devopscount").
To(handler.GetDevOpsProjectsCount).
Returns(http.StatusOK, api.StatusOK, struct {
Count uint32 `json:"count"`
}{}).
Doc("Get the devops projects count for the member").
Metadata(restfulspec.KeyOpenAPITags, []string{constants.TenantResourcesTag}))
ws.Route(ws.POST("/workspaces/{workspace}/devops").
To(handler.CreateDevopsProject).
Param(ws.PathParameter("workspace", "workspace name")).
Doc("Create a devops project in the specified workspace").
Reads(devopsv1alpha2.DevOpsProject{}).
Returns(http.StatusOK, api.StatusOK, devopsv1alpha2.DevOpsProject{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.TenantResourcesTag}))
ws.Route(ws.DELETE("/workspaces/{workspace}/devops/{devops}").
To(handler.DeleteDevopsProject).
Param(ws.PathParameter("workspace", "workspace name")).
Param(ws.PathParameter("devops", "devops project ID")).
Doc("Delete the specified devops project from the workspace").
Returns(http.StatusOK, api.StatusOK, devopsv1alpha2.DevOpsProject{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.TenantResourcesTag}))
c.Add(ws)
return nil
......
/*
Copyright 2019 The KubeSphere Authors.
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 devops
import "kubesphere.io/kubesphere/pkg/simple/client/devops"
const (
ProjectMembershipTableName = "project_membership"
ProjectMembershipUsernameColumn = "project_membership.username"
ProjectMembershipProjectIdColumn = "project_membership.project_id"
ProjectMembershipRoleColumn = "project_membership.role"
)
var ProjectMembershipColumns = GetColumnsFromStruct(&devops.ProjectMembership{})
func NewDevOpsProjectMemberShip(username, projectId, role, grantBy string) *devops.ProjectMembership {
return &devops.ProjectMembership{
Username: username,
ProjectId: projectId,
Role: role,
Status: StatusActive,
GrantBy: grantBy,
}
}
/*
Copyright 2019 The KubeSphere Authors.
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 devops
import (
"fmt"
"github.com/asaskevich/govalidator"
"github.com/emicklei/go-restful"
"github.com/gocraft/dbr"
"k8s.io/klog"
"kubesphere.io/kubesphere/pkg/api/devops/v1alpha2"
"kubesphere.io/kubesphere/pkg/db"
"kubesphere.io/kubesphere/pkg/simple/client/devops"
"kubesphere.io/kubesphere/pkg/simple/client/mysql"
"kubesphere.io/kubesphere/pkg/utils/reflectutils"
"net/http"
)
type ProjectOperator interface {
GetProject(projectId string) (*v1alpha2.DevOpsProject, error)
UpdateProject(project *v1alpha2.DevOpsProject) (*v1alpha2.DevOpsProject, error)
}
type projectOperator struct {
db *mysql.Database
}
func NewProjectOperator(dbClient *mysql.Database) ProjectOperator {
return &projectOperator{db: dbClient}
}
func (o *projectOperator) GetProject(projectId string) (*v1alpha2.DevOpsProject, error) {
project := &v1alpha2.DevOpsProject{}
err := o.db.Select(DevOpsProjectColumns...).
From(DevOpsProjectTableName).
Where(db.Eq(DevOpsProjectIdColumn, projectId)).
LoadOne(project)
if err != nil && err != dbr.ErrNotFound {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusInternalServerError, err.Error())
}
if err == dbr.ErrNotFound {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusNotFound, err.Error())
}
return project, nil
}
func (o *projectOperator) UpdateProject(project *v1alpha2.DevOpsProject) (*v1alpha2.DevOpsProject, error) {
query := o.db.Update(DevOpsProjectTableName)
if !govalidator.IsNull(project.Description) {
query.Set(DevOpsProjectDescriptionColumn, project.Description)
}
if !govalidator.IsNull(project.Extra) {
query.Set(DevOpsProjectExtraColumn, project.Extra)
}
if !govalidator.IsNull(project.Name) {
query.Set(DevOpsProjectNameColumn, project.Name)
}
if len(query.UpdateStmt.Value) > 0 {
_, err := query.
Where(db.Eq(DevOpsProjectIdColumn, project.ProjectId)).Exec()
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusInternalServerError, err.Error())
}
}
newProject := &v1alpha2.DevOpsProject{}
err := o.db.Select(DevOpsProjectColumns...).
From(DevOpsProjectTableName).
Where(db.Eq(DevOpsProjectIdColumn, project.ProjectId)).
LoadOne(newProject)
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusInternalServerError, err.Error())
}
return newProject, nil
}
func (o *projectOperator) CheckProjectUserInRole(username, projectId string, roles []string) error {
if username == KS_ADMIN {
return nil
}
membership := &devops.ProjectMembership{}
err := o.db.Select(ProjectMembershipColumns...).
From(ProjectMembershipTableName).
Where(db.And(
db.Eq(ProjectMembershipUsernameColumn, username),
db.Eq(ProjectMembershipProjectIdColumn, projectId))).LoadOne(membership)
if err != nil {
return err
}
if !reflectutils.In(membership.Role, roles) {
return fmt.Errorf("user [%s] in project [%s] role is not in %s", username, projectId, roles)
}
return nil
}
/*
Copyright 2018 The KubeSphere Authors.
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 devops
import (
"fmt"
"k8s.io/klog"
"kubesphere.io/kubesphere/pkg/simple/client/devops"
"kubesphere.io/kubesphere/pkg/simple/client/mysql"
"net/http"
"github.com/emicklei/go-restful"
"github.com/gocraft/dbr"
"kubesphere.io/kubesphere/pkg/db"
"kubesphere.io/kubesphere/pkg/models"
"kubesphere.io/kubesphere/pkg/server/params"
)
type ProjectMemberOperator interface {
GetProjectMembers(projectId string, conditions *params.Conditions, orderBy string, reverse bool, limit int, offset int) (*models.PageableResponse, error)
GetProjectMember(projectId, username string) (*devops.ProjectMembership, error)
AddProjectMember(projectId string, membership *devops.ProjectMembership) (*devops.ProjectMembership, error)
UpdateProjectMember(projectId string, membership *devops.ProjectMembership) (*devops.ProjectMembership, error)
DeleteProjectMember(projectId, username string) (string, error)
}
type projectMemberOperator struct {
db *mysql.Database
projectMemberOperator devops.ProjectMemberOperator
}
func NewProjectMemberOperator(devopsClient devops.ProjectMemberOperator, dbClient *mysql.Database) ProjectMemberOperator {
return &projectMemberOperator{
db: dbClient,
projectMemberOperator: devopsClient,
}
}
func (o *projectMemberOperator) GetProjectMembers(projectId string, conditions *params.Conditions, orderBy string, reverse bool, limit int, offset int) (*models.PageableResponse, error) {
memberships := make([]*devops.ProjectMembership, 0)
var sqconditions []dbr.Builder
sqconditions = append(sqconditions, db.Eq(ProjectMembershipProjectIdColumn, projectId))
if keyword := conditions.Match["keyword"]; keyword != "" {
sqconditions = append(sqconditions, db.Like(ProjectMembershipUsernameColumn, keyword))
}
query := *o.db.Select(ProjectMembershipColumns...).
From(ProjectMembershipTableName)
switch orderBy {
case "name":
if reverse {
query.OrderDesc(ProjectMembershipUsernameColumn)
} else {
query.OrderAsc(ProjectMembershipUsernameColumn)
}
default:
if reverse {
query.OrderDesc(ProjectMembershipRoleColumn)
} else {
query.OrderAsc(ProjectMembershipRoleColumn)
}
}
query.Limit(uint64(limit))
query.Offset(uint64(offset))
if len(sqconditions) > 1 {
query.Where(db.And(sqconditions...))
} else {
query.Where(sqconditions[0])
}
_, err := query.Load(&memberships)
if err != nil && err != dbr.ErrNotFound {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusInternalServerError, err.Error())
}
count, err := query.Count()
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusInternalServerError, err.Error())
}
result := make([]interface{}, 0)
for _, v := range memberships {
result = append(result, v)
}
return &models.PageableResponse{Items: result, TotalCount: int(count)}, nil
}
func (o *projectMemberOperator) GetProjectMember(projectId, username string) (*devops.ProjectMembership, error) {
member := &devops.ProjectMembership{}
err := o.db.Select(ProjectMembershipColumns...).
From(ProjectMembershipTableName).
Where(db.And(db.Eq(ProjectMembershipProjectIdColumn, projectId),
db.Eq(ProjectMembershipUsernameColumn, username))).
LoadOne(&member)
if err != nil && err != dbr.ErrNotFound {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusInternalServerError, err.Error())
}
if err == dbr.ErrNotFound {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusNotFound, err.Error())
}
return member, nil
}
func (o *projectMemberOperator) AddProjectMember(projectId string, membership *devops.ProjectMembership) (*devops.ProjectMembership, error) {
dbmembership := &devops.ProjectMembership{}
err := o.db.Select(ProjectMembershipColumns...).
From(ProjectMembershipTableName).
Where(db.And(
db.Eq(ProjectMembershipUsernameColumn, membership.Username),
db.Eq(ProjectMembershipProjectIdColumn, projectId))).LoadOne(dbmembership)
// if user could be founded in db, user have been added to project
if err == nil {
err = fmt.Errorf("user [%s] have been added to project", membership.Username)
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusBadRequest, err.Error())
}
if err != db.ErrNotFound {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusInternalServerError, err.Error())
}
_, err = o.projectMemberOperator.AddProjectMember(membership)
if err != nil {
klog.Errorf("%+v", err)
return nil, err
}
projectMembership := NewDevOpsProjectMemberShip(membership.Username, projectId, membership.Role, membership.GrantBy)
_, err = o.db.
InsertInto(ProjectMembershipTableName).
Columns(ProjectMembershipColumns...).
Record(projectMembership).Exec()
if err != nil {
klog.Errorf("%+v", err)
_, err = o.projectMemberOperator.DeleteProjectMember(membership)
if err != nil {
klog.Errorf("%+v", err)
return nil, err
}
return nil, restful.NewError(http.StatusInternalServerError, err.Error())
}
return projectMembership, nil
}
func (o *projectMemberOperator) UpdateProjectMember(projectId string, membership *devops.ProjectMembership) (*devops.ProjectMembership, error) {
oldMembership := &devops.ProjectMembership{}
err := o.db.Select(ProjectMembershipColumns...).
From(ProjectMembershipTableName).
Where(db.And(
db.Eq(ProjectMembershipUsernameColumn, membership.Username),
db.Eq(ProjectMembershipProjectIdColumn, projectId),
)).LoadOne(oldMembership)
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusBadRequest, err.Error())
}
_, err = o.projectMemberOperator.UpdateProjectMember(oldMembership, membership)
if err != nil {
klog.Errorf("%+v", err)
return nil, err
}
_, err = o.db.Update(ProjectMembershipTableName).
Set(ProjectMembershipRoleColumn, membership.Role).
Where(db.And(
db.Eq(ProjectMembershipProjectIdColumn, projectId),
db.Eq(ProjectMembershipUsernameColumn, membership.Username),
)).Exec()
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusInternalServerError, err.Error())
}
responseMembership := &devops.ProjectMembership{}
err = o.db.Select(ProjectMembershipColumns...).
From(ProjectMembershipTableName).
Where(db.And(
db.Eq(ProjectMembershipUsernameColumn, membership.Username),
db.Eq(ProjectMembershipProjectIdColumn, projectId),
)).LoadOne(responseMembership)
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusInternalServerError, err.Error())
}
return responseMembership, nil
}
func (o *projectMemberOperator) DeleteProjectMember(projectId, username string) (string, error) {
oldMembership := &devops.ProjectMembership{}
err := o.db.Select(ProjectMembershipColumns...).
From(ProjectMembershipTableName).
Where(db.And(
db.Eq(ProjectMembershipUsernameColumn, username),
db.Eq(ProjectMembershipProjectIdColumn, projectId),
)).LoadOne(oldMembership)
if err != nil {
if err != db.ErrNotFound {
klog.Errorf("%+v", err)
return "", restful.NewError(http.StatusInternalServerError, err.Error())
} else if err == db.ErrNotFound {
klog.Warningf("user [%s] not found in project", username)
return username, nil
}
}
if oldMembership.Role == devops.ProjectOwner {
count, err := o.db.Select(ProjectMembershipProjectIdColumn).
From(ProjectMembershipTableName).
Where(db.And(
db.Eq(ProjectMembershipProjectIdColumn, projectId),
db.Eq(ProjectMembershipRoleColumn, devops.ProjectOwner))).Count()
if err != nil {
klog.Errorf("%+v", err)
return "", restful.NewError(http.StatusInternalServerError, err.Error())
}
if count == 1 {
err = fmt.Errorf("project must has at least one admin")
klog.Errorf("%+v", err)
return "", restful.NewError(http.StatusBadRequest, err.Error())
}
}
_, err = o.projectMemberOperator.DeleteProjectMember(oldMembership)
if err != nil {
klog.Error(err)
return "", err
}
_, err = o.db.DeleteFrom(ProjectMembershipTableName).
Where(db.And(
db.Eq(ProjectMembershipProjectIdColumn, projectId),
db.Eq(ProjectMembershipUsernameColumn, username),
)).Exec()
if err != nil {
klog.Errorf("%+v", err)
return "", restful.NewError(http.StatusInternalServerError, err.Error())
}
return username, nil
}
......@@ -18,202 +18,26 @@
package tenant
import (
"fmt"
"github.com/emicklei/go-restful"
"github.com/gocraft/dbr"
"k8s.io/klog"
"kubesphere.io/kubesphere/pkg/api/devops/v1alpha2"
"kubesphere.io/kubesphere/pkg/db"
"kubesphere.io/kubesphere/pkg/models"
"kubesphere.io/kubesphere/pkg/models/devops"
"kubesphere.io/kubesphere/pkg/server/params"
dsClient "kubesphere.io/kubesphere/pkg/simple/client/devops"
"kubesphere.io/kubesphere/pkg/simple/client/mysql"
"net/http"
)
type DevOpsProjectOperator interface {
ListDevOpsProjects(workspace, username string, conditions *params.Conditions, orderBy string, reverse bool, limit int, offset int) (*models.PageableResponse, error)
CreateDevOpsProject(username string, workspace string, req *v1alpha2.DevOpsProject) (*v1alpha2.DevOpsProject, error)
GetDevOpsProjectsCount(username string) (uint32, error)
DeleteDevOpsProject(projectId, username string) error
type DevOpsProjectLister interface {
ListDevOpsProjects(workspace string, conditions *params.Conditions, orderBy string, reverse bool, limit int, offset int) (*models.PageableResponse, error)
}
type devopsProjectOperator struct {
ksProjectOperator devops.ProjectOperator
db *mysql.Database
dsProject dsClient.ProjectOperator
type devopsProjectLister struct {
dsProject dsClient.ProjectOperator
}
func newProjectOperator(operator devops.ProjectOperator, db *mysql.Database, client dsClient.ProjectOperator) DevOpsProjectOperator {
return &devopsProjectOperator{
ksProjectOperator: operator,
db: db,
dsProject: client,
func newProjectLister(client dsClient.ProjectOperator) DevOpsProjectLister {
return &devopsProjectLister{
dsProject: client,
}
}
func (o *devopsProjectOperator) ListDevOpsProjects(workspace, username string, conditions *params.Conditions, orderBy string, reverse bool, limit int, offset int) (*models.PageableResponse, error) {
query := o.db.Select(devops.GetColumnsFromStructWithPrefix(devops.DevOpsProjectTableName, v1alpha2.DevOpsProject{})...).
From(devops.DevOpsProjectTableName)
var sqconditions []dbr.Builder
sqconditions = append(sqconditions, db.Eq(devops.DevOpsProjectWorkSpaceColumn, workspace))
switch username {
case devops.KS_ADMIN:
default:
onCondition := fmt.Sprintf("%s = %s", devops.ProjectMembershipProjectIdColumn, devops.DevOpsProjectIdColumn)
query.Join(devops.ProjectMembershipTableName, onCondition)
sqconditions = append(sqconditions, db.Eq(devops.ProjectMembershipUsernameColumn, username))
sqconditions = append(sqconditions, db.Eq(
devops.ProjectMembershipTableName+"."+devops.StatusColumn, devops.StatusActive))
}
sqconditions = append(sqconditions, db.Eq(
devops.DevOpsProjectTableName+"."+devops.StatusColumn, devops.StatusActive))
if keyword := conditions.Match["keyword"]; keyword != "" {
sqconditions = append(sqconditions, db.Like(devops.DevOpsProjectNameColumn, keyword))
}
projects := make([]*v1alpha2.DevOpsProject, 0)
if len(sqconditions) > 0 {
query.Where(db.And(sqconditions...))
}
switch orderBy {
case "name":
if reverse {
query.OrderDesc(devops.DevOpsProjectNameColumn)
} else {
query.OrderAsc(devops.DevOpsProjectNameColumn)
}
default:
if reverse {
query.OrderAsc(devops.DevOpsProjectCreateTimeColumn)
} else {
query.OrderDesc(devops.DevOpsProjectCreateTimeColumn)
}
}
query.Limit(uint64(limit))
query.Offset(uint64(offset))
_, err := query.Load(&projects)
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusInternalServerError, err.Error())
}
count, err := query.Count()
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusInternalServerError, err.Error())
}
result := make([]interface{}, 0)
for _, v := range projects {
result = append(result, v)
}
return &models.PageableResponse{Items: result, TotalCount: int(count)}, nil
}
func (o *devopsProjectOperator) GetDevOpsProjectsCount(username string) (uint32, error) {
query := o.db.Select(devops.GetColumnsFromStructWithPrefix(devops.DevOpsProjectTableName, v1alpha2.DevOpsProject{})...).
From(devops.DevOpsProjectTableName)
var sqconditions []dbr.Builder
if username != devops.KS_ADMIN {
onCondition := fmt.Sprintf("%s = %s", devops.ProjectMembershipProjectIdColumn, devops.DevOpsProjectIdColumn)
query.Join(devops.ProjectMembershipTableName, onCondition)
sqconditions = append(sqconditions, db.Eq(devops.ProjectMembershipUsernameColumn, username))
sqconditions = append(sqconditions, db.Eq(
devops.ProjectMembershipTableName+"."+devops.StatusColumn, devops.StatusActive))
}
sqconditions = append(sqconditions, db.Eq(
devops.DevOpsProjectTableName+"."+devops.StatusColumn, devops.StatusActive))
if len(sqconditions) > 0 {
query.Where(db.And(sqconditions...))
}
count, err := query.Count()
if err != nil {
klog.Errorf("%+v", err)
return 0, restful.NewError(http.StatusInternalServerError, err.Error())
}
return count, nil
}
func (o *devopsProjectOperator) DeleteDevOpsProject(projectId, username string) error {
err := o.dsProject.DeleteDevOpsProject(projectId)
if err != nil {
klog.Errorf("%+v", err)
return err
}
_, err = o.db.DeleteFrom(devops.ProjectMembershipTableName).
Where(db.Eq(devops.ProjectMembershipProjectIdColumn, projectId)).Exec()
if err != nil {
klog.Errorf("%+v", err)
return err
}
_, err = o.db.Update(devops.DevOpsProjectTableName).
Set(devops.StatusColumn, devops.StatusDeleted).
Where(db.Eq(devops.DevOpsProjectIdColumn, projectId)).Exec()
if err != nil {
klog.Errorf("%+v", err)
return err
}
project := &v1alpha2.DevOpsProject{}
err = o.db.Select(devops.DevOpsProjectColumns...).
From(devops.DevOpsProjectTableName).
Where(db.Eq(devops.DevOpsProjectIdColumn, projectId)).
LoadOne(project)
if err != nil {
klog.Errorf("%+v", err)
return err
}
return nil
}
func (o *devopsProjectOperator) CreateDevOpsProject(username string, workspace string, req *v1alpha2.DevOpsProject) (*v1alpha2.DevOpsProject, error) {
project := devops.NewDevOpsProject(req.Name, req.Description, username, req.Extra, workspace)
_, err := o.dsProject.CreateDevOpsProject(project.ProjectId)
if err != nil {
klog.Error(err)
return nil, err
}
_, err = o.db.InsertInto(devops.DevOpsProjectTableName).
Columns(devops.DevOpsProjectColumns...).Record(project).Exec()
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusInternalServerError, err.Error())
}
projectMembership := devops.NewDevOpsProjectMemberShip(username, project.ProjectId, dsClient.ProjectOwner, username)
_, err = o.db.InsertInto(devops.ProjectMembershipTableName).
Columns(devops.ProjectMembershipColumns...).Record(projectMembership).Exec()
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(http.StatusInternalServerError, err.Error())
}
return project, nil
}
func (o *devopsProjectOperator) getProjectUserRole(username, projectId string) (string, error) {
if username == devops.KS_ADMIN {
return dsClient.ProjectOwner, nil
}
membership := &dsClient.ProjectMembership{}
err := o.db.Select(devops.ProjectMembershipColumns...).
From(devops.ProjectMembershipTableName).
Where(db.And(
db.Eq(devops.ProjectMembershipUsernameColumn, username),
db.Eq(devops.ProjectMembershipProjectIdColumn, projectId))).LoadOne(membership)
if err != nil {
return "", err
}
return membership.Role, nil
func (o *devopsProjectLister) ListDevOpsProjects(workspace string, conditions *params.Conditions, orderBy string, reverse bool, limit int, offset int) (*models.PageableResponse, error) {
//TODO: @runzexia use informer to impl it
return nil, nil
}
......@@ -35,32 +35,18 @@ type Interface interface {
DescribeWorkspace(username, workspace string) (*v1alpha1.Workspace, error)
ListWorkspaces(username string, conditions *params.Conditions, orderBy string, reverse bool, limit, offset int) (*models.PageableResponse, error)
ListNamespaces(username string, conditions *params.Conditions, orderBy string, reverse bool, limit, offset int) (*models.PageableResponse, error)
ListDevopsProjects(username string, conditions *params.Conditions, orderBy string, reverse bool, limit int, offset int) (*models.PageableResponse, error)
CountDevOpsProjects(username string) (uint32, error)
DeleteDevOpsProject(username, projectId string) error
ListDevopsProjects(conditions *params.Conditions, orderBy string, reverse bool, limit int, offset int) (*models.PageableResponse, error)
}
type tenantOperator struct {
workspaces WorkspaceInterface
namespaces NamespaceInterface
am am.AccessManagementInterface
devops DevOpsProjectOperator
devops DevOpsProjectLister
}
func (t *tenantOperator) CountDevOpsProjects(username string) (uint32, error) {
return t.devops.GetDevOpsProjectsCount(username)
}
func (t *tenantOperator) DeleteDevOpsProject(username, projectId string) error {
return t.devops.DeleteDevOpsProject(projectId, username)
}
func (t *tenantOperator) GetUserDevopsSimpleRules(username string, projectId string) (interface{}, error) {
panic("implement me")
}
func (t *tenantOperator) ListDevopsProjects(username string, conditions *params.Conditions, orderBy string, reverse bool, limit int, offset int) (*models.PageableResponse, error) {
return t.devops.ListDevOpsProjects(conditions.Match["workspace"], username, conditions, orderBy, reverse, limit, offset)
func (t *tenantOperator) ListDevopsProjects(conditions *params.Conditions, orderBy string, reverse bool, limit int, offset int) (*models.PageableResponse, error) {
return t.devops.ListDevOpsProjects(conditions.Match["workspace"], conditions, orderBy, reverse, limit, offset)
}
func (t *tenantOperator) DeleteNamespace(workspace, namespace string) error {
......
......@@ -25,8 +25,6 @@ import (
"kubesphere.io/kubesphere/pkg/apis/tenant/v1alpha1"
"kubesphere.io/kubesphere/pkg/client/informers/externalversions"
"kubesphere.io/kubesphere/pkg/constants"
"kubesphere.io/kubesphere/pkg/db"
"kubesphere.io/kubesphere/pkg/models/devops"
"kubesphere.io/kubesphere/pkg/models/iam/am"
"kubesphere.io/kubesphere/pkg/models/resources/v1alpha2"
"kubesphere.io/kubesphere/pkg/server/params"
......@@ -115,17 +113,8 @@ func (w *workspaceOperator) AddUser(workspaceName string, user *InWorkspaceUser)
}
func (w *workspaceOperator) CountDevopsProjectsInWorkspace(workspaceName string) (int, error) {
query := w.db.Select(devops.DevOpsProjectIdColumn).
From(devops.DevOpsProjectTableName).
Where(db.And(db.Eq(devops.DevOpsProjectWorkSpaceColumn, workspaceName),
db.Eq(devops.StatusColumn, devops.StatusActive)))
devOpsProjects := make([]string, 0)
if _, err := query.Load(&devOpsProjects); err != nil {
return 0, err
}
return len(devOpsProjects), nil
//TODO:runzexia use informer to impl it
return 0, nil
}
func (w *workspaceOperator) CountUsersInWorkspace(workspace string) (int, error) {
......
......@@ -417,17 +417,6 @@ func (d *Devops) GetMultiBranchPipelineBuildByType(projectId, pipelineId, branch
return nil, nil
}
// ProjectMemberOperator
func (d *Devops) AddProjectMember(membership *devops.ProjectMembership) (*devops.ProjectMembership, error) {
return nil, nil
}
func (d *Devops) UpdateProjectMember(oldMembership, newMembership *devops.ProjectMembership) (*devops.ProjectMembership, error) {
return nil, nil
}
func (d *Devops) DeleteProjectMember(membership *devops.ProjectMembership) (*devops.ProjectMembership, error) {
return nil, nil
}
// ProjectPipelineOperator
func (d *Devops) CreateProjectPipeline(projectId string, pipeline *devopsv1alpha3.Pipeline) (string, error) {
if _, ok := d.Pipelines[projectId][pipeline.Name]; ok {
......
......@@ -14,8 +14,6 @@ type Interface interface {
PipelineOperator
ProjectMemberOperator
ProjectPipelineOperator
ProjectOperator
......
package jenkins
import (
"fmt"
"github.com/emicklei/go-restful"
"k8s.io/klog"
"kubesphere.io/kubesphere/pkg/simple/client/devops"
)
const (
JenkinsAllUserRoleName = "kubesphere-user"
)
func GetProjectRoleName(projectId, role string) string {
return fmt.Sprintf("%s-%s-project", projectId, role)
}
func GetPipelineRoleName(projectId, role string) string {
return fmt.Sprintf("%s-%s-pipeline", projectId, role)
}
func GetProjectRolePattern(projectId string) string {
return fmt.Sprintf("^%s$", projectId)
}
func GetPipelineRolePattern(projectId string) string {
return fmt.Sprintf("^%s/.*", projectId)
}
var JenkinsOwnerProjectPermissionIds = &ProjectPermissionIds{
CredentialCreate: true,
CredentialDelete: true,
CredentialManageDomains: true,
CredentialUpdate: true,
CredentialView: true,
ItemBuild: true,
ItemCancel: true,
ItemConfigure: true,
ItemCreate: true,
ItemDelete: true,
ItemDiscover: true,
ItemMove: true,
ItemRead: true,
ItemWorkspace: true,
RunDelete: true,
RunReplay: true,
RunUpdate: true,
SCMTag: true,
}
var JenkinsProjectPermissionMap = map[string]ProjectPermissionIds{
devops.ProjectOwner: {
CredentialCreate: true,
CredentialDelete: true,
CredentialManageDomains: true,
CredentialUpdate: true,
CredentialView: true,
ItemBuild: true,
ItemCancel: true,
ItemConfigure: true,
ItemCreate: true,
ItemDelete: true,
ItemDiscover: true,
ItemMove: true,
ItemRead: true,
ItemWorkspace: true,
RunDelete: true,
RunReplay: true,
RunUpdate: true,
SCMTag: true,
},
devops.ProjectMaintainer: {
CredentialCreate: true,
CredentialDelete: true,
CredentialManageDomains: true,
CredentialUpdate: true,
CredentialView: true,
ItemBuild: true,
ItemCancel: true,
ItemConfigure: false,
ItemCreate: true,
ItemDelete: false,
ItemDiscover: true,
ItemMove: false,
ItemRead: true,
ItemWorkspace: true,
RunDelete: true,
RunReplay: true,
RunUpdate: true,
SCMTag: true,
},
devops.ProjectDeveloper: {
CredentialCreate: false,
CredentialDelete: false,
CredentialManageDomains: false,
CredentialUpdate: false,
CredentialView: false,
ItemBuild: true,
ItemCancel: true,
ItemConfigure: false,
ItemCreate: false,
ItemDelete: false,
ItemDiscover: true,
ItemMove: false,
ItemRead: true,
ItemWorkspace: true,
RunDelete: true,
RunReplay: true,
RunUpdate: true,
SCMTag: false,
},
devops.ProjectReporter: {
CredentialCreate: false,
CredentialDelete: false,
CredentialManageDomains: false,
CredentialUpdate: false,
CredentialView: false,
ItemBuild: false,
ItemCancel: false,
ItemConfigure: false,
ItemCreate: false,
ItemDelete: false,
ItemDiscover: true,
ItemMove: false,
ItemRead: true,
ItemWorkspace: false,
RunDelete: false,
RunReplay: false,
RunUpdate: false,
SCMTag: false,
},
}
var JenkinsPipelinePermissionMap = map[string]ProjectPermissionIds{
devops.ProjectOwner: {
CredentialCreate: true,
CredentialDelete: true,
CredentialManageDomains: true,
CredentialUpdate: true,
CredentialView: true,
ItemBuild: true,
ItemCancel: true,
ItemConfigure: true,
ItemCreate: true,
ItemDelete: true,
ItemDiscover: true,
ItemMove: true,
ItemRead: true,
ItemWorkspace: true,
RunDelete: true,
RunReplay: true,
RunUpdate: true,
SCMTag: true,
},
devops.ProjectMaintainer: {
CredentialCreate: true,
CredentialDelete: true,
CredentialManageDomains: true,
CredentialUpdate: true,
CredentialView: true,
ItemBuild: true,
ItemCancel: true,
ItemConfigure: true,
ItemCreate: true,
ItemDelete: true,
ItemDiscover: true,
ItemMove: true,
ItemRead: true,
ItemWorkspace: true,
RunDelete: true,
RunReplay: true,
RunUpdate: true,
SCMTag: true,
},
devops.ProjectDeveloper: {
CredentialCreate: false,
CredentialDelete: false,
CredentialManageDomains: false,
CredentialUpdate: false,
CredentialView: false,
ItemBuild: true,
ItemCancel: true,
ItemConfigure: false,
ItemCreate: false,
ItemDelete: false,
ItemDiscover: true,
ItemMove: false,
ItemRead: true,
ItemWorkspace: true,
RunDelete: true,
RunReplay: true,
RunUpdate: true,
SCMTag: false,
},
devops.ProjectReporter: {
CredentialCreate: false,
CredentialDelete: false,
CredentialManageDomains: false,
CredentialUpdate: false,
CredentialView: false,
ItemBuild: false,
ItemCancel: false,
ItemConfigure: false,
ItemCreate: false,
ItemDelete: false,
ItemDiscover: true,
ItemMove: false,
ItemRead: true,
ItemWorkspace: false,
RunDelete: false,
RunReplay: false,
RunUpdate: false,
SCMTag: false,
},
}
func (j *Jenkins) AddProjectMember(membership *devops.ProjectMembership) (*devops.ProjectMembership, error) {
globalRole, err := j.GetGlobalRole(JenkinsAllUserRoleName)
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
if globalRole == nil {
_, err := j.AddGlobalRole(JenkinsAllUserRoleName, GlobalPermissionIds{
GlobalRead: true,
}, true)
if err != nil {
klog.Errorf("failed to create jenkins global role %+v", err)
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
}
err = globalRole.AssignRole(membership.Username)
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
projectRole, err := j.GetProjectRole(GetProjectRoleName(membership.ProjectId, membership.Role))
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
err = projectRole.AssignRole(membership.Username)
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
pipelineRole, err := j.GetProjectRole(GetPipelineRoleName(membership.ProjectId, membership.Role))
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
err = pipelineRole.AssignRole(membership.Username)
if err != nil {
klog.Errorf("%+v", err)
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
return membership, nil
}
func (j *Jenkins) UpdateProjectMember(oldMembership, newMembership *devops.ProjectMembership) (*devops.ProjectMembership, error) {
oldProjectRole, err := j.GetProjectRole(GetProjectRoleName(oldMembership.ProjectId, oldMembership.Role))
if err != nil {
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
err = oldProjectRole.UnAssignRole(newMembership.Username)
if err != nil {
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
oldPipelineRole, err := j.GetProjectRole(GetPipelineRoleName(oldMembership.ProjectId, oldMembership.Role))
if err != nil {
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
err = oldPipelineRole.UnAssignRole(newMembership.Username)
if err != nil {
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
projectRole, err := j.GetProjectRole(GetProjectRoleName(oldMembership.ProjectId, newMembership.Role))
if err != nil {
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
err = projectRole.AssignRole(newMembership.Username)
if err != nil {
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
pipelineRole, err := j.GetProjectRole(GetPipelineRoleName(oldMembership.ProjectId, newMembership.Role))
if err != nil {
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
err = pipelineRole.AssignRole(newMembership.Username)
if err != nil {
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
return newMembership, nil
}
func (j *Jenkins) DeleteProjectMember(membership *devops.ProjectMembership) (*devops.ProjectMembership, error) {
oldProjectRole, err := j.GetProjectRole(GetProjectRoleName(membership.ProjectId, membership.Role))
if err != nil {
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
err = oldProjectRole.UnAssignRole(membership.Username)
if err != nil {
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
oldPipelineRole, err := j.GetProjectRole(GetPipelineRoleName(membership.ProjectId, membership.Role))
if err != nil {
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
err = oldPipelineRole.UnAssignRole(membership.Username)
if err != nil {
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
}
return membership, nil
}
package devops
type ProjectMembership struct {
Username string `json:"username" description:"Member's username,username can uniquely identify a user"`
ProjectId string `json:"project_id" db:"project_id" description:"the DevOps Projects which project membership belongs to"`
Role string `json:"role" description:"DevOps Project membership's role type. e.g. owner '"`
Status string `json:"status" description:"Deprecated, Status of project membership. e.g. active "`
GrantBy string `json:"grand_by,omitempty" description:"Username of the user who assigned the role"`
}
type ProjectMemberOperator interface {
AddProjectMember(membership *ProjectMembership) (*ProjectMembership, error)
UpdateProjectMember(oldMembership, newMembership *ProjectMembership) (*ProjectMembership, error)
DeleteProjectMember(membership *ProjectMembership) (*ProjectMembership, error)
}
var DefaultRoles = []*Role{
{
Name: ProjectOwner,
Description: "Owner have access to do all the operations of a DevOps project and own the highest permissions as well.",
},
{
Name: ProjectMaintainer,
Description: "Maintainer have access to manage pipeline and credential configuration in a DevOps project.",
},
{
Name: ProjectDeveloper,
Description: "Developer is able to view and trigger the pipeline.",
},
{
Name: ProjectReporter,
Description: "Reporter is only allowed to view the status of the pipeline.",
},
}
var AllRoleSlice = []string{ProjectDeveloper, ProjectReporter, ProjectMaintainer, ProjectOwner}
const (
ProjectOwner = "owner"
ProjectMaintainer = "maintainer"
ProjectDeveloper = "developer"
ProjectReporter = "reporter"
)
type Role struct {
Name string `json:"name" description:"role's name e.g. owner'"`
Description string `json:"description" description:"role 's description'"`
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册