From a7015f67c78b6429b5785942ffb65165bde58bd7 Mon Sep 17 00:00:00 2001 From: dove0012 Date: Fri, 5 Sep 2025 14:46:15 +0800 Subject: [PATCH 1/3] =?UTF-8?q?[=E5=B9=B3=E5=8F=B0=E7=AE=A1=E7=90=86]=201.?= =?UTF-8?q?=20=E6=B7=BB=E5=8A=A0vpc=E3=80=81cluster=E3=80=81task=E3=80=81t?= =?UTF-8?q?emplateconfig=E5=92=8Ccmdb=E6=8E=A5=E5=8F=A3=202.=20=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E5=AE=A2=E6=88=B7=E7=AB=AF=E8=BF=9E=E6=8E=A5=E6=96=B9?= =?UTF-8?q?=E5=BC=8F=E4=B8=BAgrpc?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bcs-services/bcs-platform-manager/cmd/api.go | 3 - bcs-services/bcs-platform-manager/go.mod | 74 +++- .../api/{pod/pod.go => cloudvpc/cloudvpc.go} | 42 +- .../pkg/api/cluster/cluster.go | 217 +++++++++ .../bcs-platform-manager/pkg/api/cmdb/cmdb.go | 325 ++++++++++++++ .../bcs-platform-manager/pkg/api/routes.go | 33 +- .../bcs-platform-manager/pkg/api/task/task.go | 133 ++++++ .../pkg/api/templateconfig/templateconfig.go | 63 +++ .../pkg/component/bcs/bcs.go | 177 -------- .../component/bcs/clustermanager/client.go | 75 ++++ .../component/bcs/clustermanager/cloudvpc.go | 63 +++ .../component/bcs/clustermanager/cluster.go | 85 ++++ .../pkg/component/bcs/clustermanager/task.go | 84 ++++ .../bcs/clustermanager/templateconfig.go | 63 +++ .../pkg/component/bcs/project.go | 80 ---- .../pkg/component/bcs/project_test.go | 31 -- .../component/bcs/projectmanager/client.go | 75 ++++ .../component/bcs/projectmanager/project.go | 63 +++ .../pkg/component/cmdb/cmdb.go | 419 ++++++++++++++++++ .../pkg/component/cmdb/types.go | 204 +++++++++ .../bcs-platform-manager/pkg/config/bcs.go | 1 + .../bcs/bcs_test.go => config/cmdb.go} | 18 +- .../bcs-platform-manager/pkg/config/config.go | 6 + .../bcs-platform-manager/pkg/config/env.go | 2 + .../bcs-platform-manager/pkg/rest/context.go | 4 - .../pkg/rest/middleware/auth.go | 6 +- .../pkg/rest/middleware/project.go | 12 +- 27 files changed, 2006 insertions(+), 352 deletions(-) rename bcs-services/bcs-platform-manager/pkg/api/{pod/pod.go => cloudvpc/cloudvpc.go} (50%) create mode 100644 bcs-services/bcs-platform-manager/pkg/api/cluster/cluster.go create mode 100644 bcs-services/bcs-platform-manager/pkg/api/cmdb/cmdb.go create mode 100644 bcs-services/bcs-platform-manager/pkg/api/task/task.go create mode 100644 bcs-services/bcs-platform-manager/pkg/api/templateconfig/templateconfig.go delete mode 100644 bcs-services/bcs-platform-manager/pkg/component/bcs/bcs.go create mode 100644 bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/client.go create mode 100644 bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/cloudvpc.go create mode 100644 bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/cluster.go create mode 100644 bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/task.go create mode 100644 bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/templateconfig.go delete mode 100644 bcs-services/bcs-platform-manager/pkg/component/bcs/project.go delete mode 100644 bcs-services/bcs-platform-manager/pkg/component/bcs/project_test.go create mode 100644 bcs-services/bcs-platform-manager/pkg/component/bcs/projectmanager/client.go create mode 100644 bcs-services/bcs-platform-manager/pkg/component/bcs/projectmanager/project.go create mode 100644 bcs-services/bcs-platform-manager/pkg/component/cmdb/cmdb.go create mode 100644 bcs-services/bcs-platform-manager/pkg/component/cmdb/types.go rename bcs-services/bcs-platform-manager/pkg/{component/bcs/bcs_test.go => config/cmdb.go} (67%) diff --git a/bcs-services/bcs-platform-manager/cmd/api.go b/bcs-services/bcs-platform-manager/cmd/api.go index ee2213ea71..ebb70ddc87 100644 --- a/bcs-services/bcs-platform-manager/cmd/api.go +++ b/bcs-services/bcs-platform-manager/cmd/api.go @@ -24,7 +24,6 @@ import ( "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/api" "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component" - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component/bcs" "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/discovery" "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/storage" @@ -81,7 +80,5 @@ func runAPIServer(ctx context.Context, g *run.Group, opt *option) error { g.Add(server.Run, func(err error) { _ = server.Close(); component.GetAuditClient().Close() }) g.Add(sd.Run, func(error) {}) - bcs.CacheListClusters() - return nil } diff --git a/bcs-services/bcs-platform-manager/go.mod b/bcs-services/bcs-platform-manager/go.mod index 2e670a68ab..9a6490256a 100644 --- a/bcs-services/bcs-platform-manager/go.mod +++ b/bcs-services/bcs-platform-manager/go.mod @@ -2,7 +2,13 @@ module github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager go 1.23.0 +replace ( + configcenter => github.com/Tencent/bk-cmdb v0.0.0-20220923072424-595387cbc3cb + k8s.io/client-go => k8s.io/client-go v0.32.2 +) + require ( + configcenter v0.0.0-00010101000000-000000000000 github.com/Tencent/bk-bcs/bcs-common v0.0.0-20250729093702-993155773a94 github.com/Tencent/bk-bcs/bcs-services/pkg v0.0.0-20250729093702-993155773a94 github.com/dustin/go-humanize v1.0.1 @@ -19,16 +25,16 @@ require ( github.com/google/uuid v1.6.0 github.com/mitchellh/go-homedir v1.1.0 github.com/oklog/run v1.1.0 + github.com/parnurzeal/gorequest v0.2.16 github.com/patrickmn/go-cache v2.1.0+incompatible github.com/pkg/errors v0.9.1 github.com/prometheus/prometheus v1.8.2-0.20220308163432-03831554a519 github.com/spf13/cobra v1.9.1 github.com/spf13/viper v1.20.1 - github.com/stretchr/testify v1.10.0 github.com/swaggo/http-swagger v1.3.4 go-micro.dev/v4 v4.10.2 - go.mongodb.org/mongo-driver v1.17.4 - go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/mongo/otelmongo v0.62.0 + go.mongodb.org/mongo-driver v1.9.1 + go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/mongo/otelmongo v0.33.0 go.opentelemetry.io/otel v1.37.0 go.opentelemetry.io/otel/trace v1.37.0 google.golang.org/grpc v1.74.2 @@ -40,44 +46,63 @@ require ( github.com/KyleBanks/depth v1.2.1 // indirect github.com/Microsoft/go-winio v0.6.1 // indirect github.com/ProtonMail/go-crypto v1.1.3 // indirect + github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/kubernetes/common v0.0.0-20220330120237-0bbed74dcf6d // indirect github.com/TencentBlueKing/bk-audit-go-sdk v0.0.6 // indirect github.com/TencentBlueKing/gopkg v1.1.0 // indirect github.com/TencentBlueKing/iam-go-sdk v0.1.6 // indirect github.com/ajg/form v1.5.1 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bitly/go-simplejson v0.5.0 // indirect + github.com/bytedance/sonic v1.9.1 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect github.com/cloudflare/circl v1.3.7 // indirect + github.com/coccyx/timeparser v0.0.0-20161029180942-5644122b3667 // indirect github.com/coreos/go-semver v0.3.0 // indirect github.com/coreos/go-systemd/v22 v22.3.2 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.6 // indirect github.com/cyphar/filepath-securejoin v0.2.5 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/emicklei/go-restful/v3 v3.11.0 // indirect github.com/emirpasic/gods v1.18.1 // indirect + github.com/envoyproxy/protoc-gen-validate v1.2.1 // indirect github.com/evanphx/json-patch/v5 v5.6.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect + github.com/fxamacker/cbor/v2 v2.7.0 // indirect github.com/gabriel-vasile/mimetype v1.4.8 // indirect github.com/ggicci/owl v0.8.2 // indirect + github.com/gin-gonic/gin v1.9.1 // indirect + github.com/go-acme/lego/v4 v4.4.0 // indirect github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect github.com/go-git/go-billy/v5 v5.6.0 // indirect github.com/go-git/go-git/v5 v5.13.0 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect - github.com/go-openapi/jsonpointer v0.19.5 // indirect - github.com/go-openapi/jsonreference v0.20.0 // indirect + github.com/go-openapi/jsonpointer v0.21.0 // indirect + github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/spec v0.20.9 // indirect - github.com/go-openapi/swag v0.21.1 // indirect + github.com/go-openapi/swag v0.23.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-sql-driver/mysql v1.7.1 // indirect + github.com/go-stack/stack v1.8.0 // indirect + github.com/gobwas/httphead v0.1.0 // indirect + github.com/gobwas/pool v0.2.1 // indirect + github.com/gobwas/ws v1.2.1 // indirect + github.com/goccy/go-json v0.10.2 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang-migrate/migrate/v4 v4.17.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.4 // indirect github.com/golang/snappy v1.0.0 // indirect + github.com/google/gnostic-models v0.6.8 // indirect + github.com/google/go-cmp v0.7.0 // indirect + github.com/google/gofuzz v1.2.0 // indirect + github.com/gorilla/handlers v1.5.1 // indirect + github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect @@ -85,13 +110,17 @@ require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect github.com/josharian/intern v1.0.0 // indirect + github.com/joyt/godate v0.0.0-20150226210126-7151572574a7 // indirect github.com/json-iterator/go v1.1.12 // indirect + github.com/juju/ratelimit v1.0.1 // indirect github.com/kevinburke/ssh_config v1.2.0 // indirect github.com/klauspost/compress v1.18.0 // indirect + github.com/klauspost/cpuid/v2 v2.2.4 // indirect github.com/labstack/echo/v4 v4.13.4 // indirect github.com/labstack/gommon v0.4.2 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect + github.com/mattbaird/jsonpatch v0.0.0-20200820163806-098863c1fc24 // indirect github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/miekg/dns v1.1.50 // indirect @@ -99,20 +128,21 @@ require ( github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect - github.com/montanaflynn/stats v0.7.1 // indirect + github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/nxadm/tail v1.4.8 // indirect github.com/openzipkin/zipkin-go v0.4.3 // indirect github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c // indirect - github.com/parnurzeal/gorequest v0.2.16 // indirect github.com/pelletier/go-toml/v2 v2.2.3 // indirect github.com/pjbgf/sha1cd v0.3.0 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_golang v1.19.0 // indirect github.com/prometheus/client_model v0.5.0 // indirect github.com/prometheus/common v0.48.0 // indirect github.com/prometheus/procfs v0.12.0 // indirect + github.com/rs/xid v1.4.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/sagikazarmark/locafero v0.7.0 // indirect + github.com/samuel/go-zookeeper v0.0.0-20201211165307-7117e9ea2414 // indirect github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/skeema/knownhosts v1.3.0 // indirect @@ -124,10 +154,15 @@ require ( github.com/subosito/gotenv v1.6.0 // indirect github.com/swaggo/files v0.0.0-20220610200504-28940afbdbfe // indirect github.com/swaggo/swag v1.8.1 // indirect + github.com/tidwall/gjson v1.14.1 // indirect + github.com/tidwall/match v1.1.1 // indirect + github.com/tidwall/pretty v1.2.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect github.com/urfave/cli/v2 v2.8.1 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasttemplate v1.2.2 // indirect + github.com/x448/float16 v0.8.4 // indirect github.com/xanzy/ssh-agent v0.3.3 // indirect github.com/xdg-go/pbkdf2 v1.0.0 // indirect github.com/xdg-go/scram v1.1.2 // indirect @@ -149,19 +184,34 @@ require ( go.uber.org/atomic v1.9.0 // indirect go.uber.org/multierr v1.9.0 // indirect go.uber.org/zap v1.24.0 // indirect + golang.org/x/arch v0.3.0 // indirect golang.org/x/crypto v0.40.0 // indirect golang.org/x/mod v0.25.0 // indirect golang.org/x/net v0.42.0 // indirect + golang.org/x/oauth2 v0.30.0 // indirect golang.org/x/sync v0.16.0 // indirect golang.org/x/sys v0.34.0 // indirect + golang.org/x/term v0.33.0 // indirect golang.org/x/text v0.27.0 // indirect + golang.org/x/time v0.11.0 // indirect golang.org/x/tools v0.34.0 // indirect + google.golang.org/genproto v0.0.0-20241118233622-e639e219e697 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20250728155136-f173205681a0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20250728155136-f173205681a0 // indirect google.golang.org/protobuf v1.36.6 // indirect + gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect + gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect - k8s.io/klog/v2 v2.100.1 // indirect + k8s.io/api v0.32.2 // indirect + k8s.io/apimachinery v0.32.2 // indirect + k8s.io/client-go v0.24.2 // indirect + k8s.io/klog v1.0.0 // indirect + k8s.io/klog/v2 v2.130.1 // indirect + k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f // indirect + k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 // indirect moul.io/http2curl v1.0.0 // indirect + sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.4.2 // indirect + sigs.k8s.io/yaml v1.4.0 // indirect ) diff --git a/bcs-services/bcs-platform-manager/pkg/api/pod/pod.go b/bcs-services/bcs-platform-manager/pkg/api/cloudvpc/cloudvpc.go similarity index 50% rename from bcs-services/bcs-platform-manager/pkg/api/pod/pod.go rename to bcs-services/bcs-platform-manager/pkg/api/cloudvpc/cloudvpc.go index ba5b2652d6..fe0b965290 100644 --- a/bcs-services/bcs-platform-manager/pkg/api/pod/pod.go +++ b/bcs-services/bcs-platform-manager/pkg/api/cloudvpc/cloudvpc.go @@ -10,37 +10,43 @@ * limitations under the License. */ -// Package pod pod operate -package pod +// Package cloudvpc cloudvpc operate +package cloudvpc import ( "context" - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/storage" - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/storage/entity" + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/clustermanager" + + clustermgr "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager" ) -// SampleRequset 示例请求 -type SampleRequset struct { - ProjectId string `json:"projectId" in:"path=projectId" validate:"required"` - ClusterId string `json:"clusterId" in:"path=clusterId" validate:"required"` -} +// CreateCloudVPC 创建VPC +// @Summary 创建VPC +// @Tags Logs +// @Produce json +// @Success 200 {array} k8sclient.Container +// @Router /cloudvpc [post] +func CreateCloudVPC(ctx context.Context, req *clustermanager.CreateCloudVPCRequest) (*bool, error) { + result, err := clustermgr.CreateCloudVPC(ctx, req) + if err != nil { + return nil, err + } -// SampleResponse 示例响应 -type SampleResponse struct { - Id string `json:"id"` + return &result, nil } -// GetPodContainers 获取 Pod 容器列表 -// @Summary 获取 Pod 容器列表 +// UpdateCloudVPC 更新VPC +// @Summary 更新VPC // @Tags Logs // @Produce json // @Success 200 {array} k8sclient.Container -// @Router /namespaces/:namespace/pods/:pod/containers [get] -func GetPodContainers(c context.Context, req *SampleRequset) (*entity.Audit, error) { - audit, err := storage.GlobalStorage.GetAudit(c, req.ProjectId, req.ClusterId) +// @Router /cloudvpc [put] +func UpdateCloudVPC(ctx context.Context, req *clustermanager.UpdateCloudVPCRequest) (*bool, error) { + result, err := clustermgr.UpdateCloudVPC(ctx, req) if err != nil { return nil, err } - return audit, nil + + return &result, nil } diff --git a/bcs-services/bcs-platform-manager/pkg/api/cluster/cluster.go b/bcs-services/bcs-platform-manager/pkg/api/cluster/cluster.go new file mode 100644 index 0000000000..d7a12c4788 --- /dev/null +++ b/bcs-services/bcs-platform-manager/pkg/api/cluster/cluster.go @@ -0,0 +1,217 @@ +/* + * Tencent is pleased to support the open source community by making Blueking Container Service available. + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * 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 cluster cluster operate +package cluster + +import ( + "context" + "fmt" + "sort" + + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/clustermanager" + + clustermgr "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager" + projectrmgr "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component/bcs/projectmanager" + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" +) + +// ListClusterReq list cluster request +type ListClusterReq struct { + ProjectID string `json:"projectID" in:"query=projectID"` + BusinessID string `json:"businessID" in:"query=businessID"` + Provider string `json:"provider" in:"query=provider"` + SortKey string `json:"sortKey" in:"query=sortKey"` + SortWay string `json:"sortWay" in:"query=sortWay"` // asc or desc +} + +// ListClusterRsp list cluster response +type ListClusterRsp struct { + ClusterID string `json:"clusterID"` + ClusterName string `json:"clusterName"` + Provider string `json:"provider"` + Region string `json:"region"` + VpcID string `json:"vpcID"` + ProjectID string `json:"projectID"` + BusinessID string `json:"businessID"` + Environment string `json:"environment"` + EngineType string `json:"engineType"` + ClusterType string `json:"clusterType"` + Label map[string]string `json:"label"` + Creator string `json:"creator"` + CreateTime string `json:"createTime"` + UpdateTime string `json:"updateTime"` + SystemID string `json:"systemID"` + ManageType string `json:"manageType"` + Status string `json:"status"` + Updater string `json:"updater"` + NetworkType string `json:"networkType"` + ModuleID string `json:"moduleID"` + IsCommonCluster bool `json:"isCommonCluster"` + Description string `json:"description"` + ClusterCategory string `json:"clusterCategory"` + IsShared bool `json:"isShared"` + Link string `json:"link"` + SortKey string `json:"-"` + SortWay string `json:"-"` +} + +// SortCluster 排序 +type SortCluster []*ListClusterRsp + +// Len 实现sort.Interface接口的Len方法 +func (a SortCluster) Len() int { return len(a) } + +// Less 实现sort.Interface接口的Less方法,这里我们先按Name排序,如果Name相同则按Age排序 +func (a SortCluster) Less(i, j int) bool { + sortKey := a[0].SortKey + sortWay := a[0].SortWay + + switch sortKey { + case "clusterID": + if sortWay == "desc" { + return a[i].ClusterID > a[j].ClusterID + } + return a[i].ClusterID < a[j].ClusterID + case "clusterName": + if sortWay == "desc" { + return a[i].ClusterName > a[j].ClusterName + } + return a[i].ClusterName < a[j].ClusterName + default: + return a[i].CreateTime > a[j].CreateTime + } +} + +// Swap 实现sort.Interface接口的Swap方法 +func (a SortCluster) Swap(i, j int) { a[i], a[j] = a[j], a[i] } + +// UpdateClusterOperatorReq update cluster operator request +type UpdateClusterOperatorReq struct { + ClusterID string `json:"clusterID" in:"path=clusterID"` + Creator string `json:"creator"` + Updater string `json:"updater"` +} + +// UpdateClusterProjectBusinessReq update cluster projectID or businessID request +type UpdateClusterProjectBusinessReq struct { + ClusterID string `json:"clusterID" in:"path=clusterID"` + ProjectID string `json:"projectID"` + BusinessID string `json:"businessID"` +} + +// ListCluster 获取cluster列表 +// @Summary 获取cluster列表 +// @Tags Logs +// @Produce json +// @Success 200 {array} k8sclient.Container +// @Router /cluster [get] +func ListCluster(ctx context.Context, req *ListClusterReq) (*[]*ListClusterRsp, error) { + projects, err := projectrmgr.ListProject(ctx) + if err != nil { + return nil, err + } + + clusters, err := clustermgr.ListCluster(ctx, &clustermanager.ListClusterV2Req{ + ProjectID: req.ProjectID, + BusinessID: req.BusinessID, + Provider: req.Provider, + }) + if err != nil { + return nil, err + } + + result := make([]*ListClusterRsp, 0) + for _, cluster := range clusters { + result = append(result, &ListClusterRsp{ + ClusterID: cluster.ClusterID, + ClusterName: cluster.ClusterName, + Provider: cluster.Provider, + Region: cluster.Region, + VpcID: cluster.VpcID, + ProjectID: cluster.ProjectID, + BusinessID: cluster.BusinessID, + Environment: cluster.Environment, + EngineType: cluster.EngineType, + ClusterType: cluster.ClusterType, + Creator: cluster.Creator, + CreateTime: cluster.CreateTime, + UpdateTime: cluster.UpdateTime, + ManageType: cluster.ManageType, + Status: cluster.Status, + Updater: cluster.Updater, + Description: cluster.Description, + ClusterCategory: cluster.ClusterCategory, + Link: func() string { + projectCode := "" + for _, project := range projects { + if project.ProjectID == cluster.ProjectID { + projectCode = project.ProjectCode + break + } + } + return fmt.Sprintf("%s/bcs/projects/%s/clusters?clusterId=%s", + config.G.BCS.Host, projectCode, cluster.ClusterID) + }(), + SortKey: req.SortKey, + SortWay: req.SortWay, + Label: cluster.Labels, + SystemID: cluster.SystemID, + NetworkType: cluster.NetworkType, + ModuleID: cluster.ModuleID, + IsCommonCluster: cluster.IsCommonCluster, + IsShared: cluster.IsShared, + }) + } + + sort.Sort(SortCluster(result)) + + return &result, nil +} + +// UpdateClusterOperator 更新cluster 创建人和更新人 +// @Summary 更新cluster 创建人和更新人 +// @Tags Logs +// @Produce json +// @Success 200 {array} k8sclient.Container +// @Router /cluster/{clusterID}/operator [put] +func UpdateClusterOperator(ctx context.Context, req *UpdateClusterOperatorReq) (*bool, error) { + result, err := clustermgr.UpdateCluster(ctx, &clustermanager.UpdateClusterReq{ + ClusterID: req.ClusterID, + Creator: req.Creator, + Updater: req.Updater, + }) + if err != nil { + return nil, err + } + + return &result, nil +} + +// UpdateClusterProjectBusiness 更新cluster 项目或业务ID +// @Summary 更新cluster 项目或业务ID +// @Tags Logs +// @Produce json +// @Success 200 {array} k8sclient.Container +// @Router /cluster/{clusterID}/projectidorbusinessid [put] +func UpdateClusterProjectBusiness(ctx context.Context, req *UpdateClusterProjectBusinessReq) (*bool, error) { + result, err := clustermgr.UpdateCluster(ctx, &clustermanager.UpdateClusterReq{ + ClusterID: req.ClusterID, + ProjectID: req.ProjectID, + BusinessID: req.BusinessID, + }) + if err != nil { + return nil, err + } + + return &result, nil +} diff --git a/bcs-services/bcs-platform-manager/pkg/api/cmdb/cmdb.go b/bcs-services/bcs-platform-manager/pkg/api/cmdb/cmdb.go new file mode 100644 index 0000000000..b6f8a2b002 --- /dev/null +++ b/bcs-services/bcs-platform-manager/pkg/api/cmdb/cmdb.go @@ -0,0 +1,325 @@ +/* + * Tencent is pleased to support the open source community by making Blueking Container Service available. + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * 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 cmdb cmdb operate +package cmdb + +import ( + "configcenter/src/common/blog" + "context" + + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component/cmdb" +) + +// DeleteAllByBkBizIDAndBkClusterIDReq delete all data by bk_biz_id and bk_cluster_id request +type DeleteAllByBkBizIDAndBkClusterIDReq struct { + BkBizID int64 `json:"bkBizID"` + BkClusterID []int64 `json:"bkClusterID"` +} + +// DeleteAllByBkBizIDAndBkClusterID 清理cmdb容器数据 +// @Summary 清理cmdb容器数据 +// @Tags Logs +// @Produce json +// @Success 200 {array} k8sclient.Container +// @Router /cmdb/delete_all [put] +func DeleteAllByBkBizIDAndBkClusterID(ctx context.Context, req *DeleteAllByBkBizIDAndBkClusterIDReq) (*bool, error) { + cmdbClient := cmdb.New() + + result := false + + err := deleteAll2IDPod(req.BkBizID, req.BkClusterID, cmdbClient) + if err != nil { + return &result, err + } + + err = deleteAll2IDWorkload(req.BkBizID, req.BkClusterID, cmdbClient) + if err != nil { + return &result, err + } + + deleteAll2IDNamespace(req.BkBizID, req.BkClusterID, cmdbClient) + deleteAll2IDIDNode(req.BkBizID, req.BkClusterID, cmdbClient) + deleteAll2IDCluster(req.BkBizID, req.BkClusterID, cmdbClient) + + result = true + return &result, nil +} + +func deleteAll2IDPod(bkBizID int64, bkClusterID []int64, c *cmdb.Client) error { + blog.Info("start delete all pod") + + for { + got, err := c.GetBcsPod(&cmdb.GetBcsPodReq{ + CommonReq: cmdb.CommonReq{ + BKBizID: bkBizID, + Fields: []string{"id"}, + Page: cmdb.Page{ + Start: 0, + Limit: 200, + }, + Filter: &cmdb.PropertyFilter{ + Condition: "AND", + Rules: []cmdb.Rule{ + { + Field: "bk_cluster_id", + Operator: "in", + Value: bkClusterID, + }, + }, + }, + }, + }) + if err != nil { + return err + } + + podToDelete := make([]int64, 0) + for _, pod := range *got { + podToDelete = append(podToDelete, pod.ID) + } + + if len(podToDelete) == 0 { + break + } + + blog.Info("delete pod %v", podToDelete) + err = c.DeleteBcsPod(&cmdb.DeleteBcsPodReq{ + Data: &[]cmdb.DeleteBcsPodReqData{ + { + BKBizID: &bkBizID, + IDs: &podToDelete, + }, + }, + }) + if err != nil { + blog.Errorf("DeleteBcsPod err: %v", err) + return err + } + } + + blog.Info("delete all pod success") + + return nil +} + +func deleteAll2IDWorkload(bkBizID int64, bkClusterID []int64, c *cmdb.Client) error { + blog.Info("start delete all workload") + + workloadTypes := []string{"deployment", "statefulSet", "daemonSet", "gameDeployment", "gameStatefulSet", "pods"} + for _, workloadType := range workloadTypes { + for { + got, err := c.GetBcsWorkload(&cmdb.GetBcsWorkloadReq{ + CommonReq: cmdb.CommonReq{ + BKBizID: bkBizID, + Fields: []string{"id"}, + Page: cmdb.Page{ + Start: 0, + Limit: 200, + }, + Filter: &cmdb.PropertyFilter{ + Condition: "AND", + Rules: []cmdb.Rule{ + { + Field: "bk_cluster_id", + Operator: "in", + Value: bkClusterID, + }, + }, + }, + }, + Kind: workloadType, + }) + if err != nil { + blog.Errorf("GetBcsWorkload err: %v", err) + return err + } + + workloadToDelete := make([]int64, 0) + for _, workload := range *got { + workloadToDelete = append(workloadToDelete, (int64)(workload.(map[string]interface{})["id"].(float64))) + } + + if len(workloadToDelete) == 0 { + break + } + + blog.Infof("delete workload: %v", workloadToDelete) + err = c.DeleteBcsWorkload(&cmdb.DeleteBcsWorkloadReq{ + BKBizID: &bkBizID, + Kind: &workloadType, + IDs: &workloadToDelete, + }) + if err != nil { + blog.Errorf("DeleteBcsWorkload err: %v", err) + return err + } + } + } + + blog.Info("delete all workload success") + + return nil +} + +func deleteAll2IDNamespace(bkBizID int64, bkClusterID []int64, c *cmdb.Client) { + blog.Info("start delete all namespace") + + for { + got, err := c.GetBcsNamespace(&cmdb.GetBcsNamespaceReq{ + CommonReq: cmdb.CommonReq{ + BKBizID: bkBizID, + Fields: []string{"id"}, + Page: cmdb.Page{ + Limit: 200, + Start: 0, + }, + Filter: &cmdb.PropertyFilter{ + Condition: "AND", + Rules: []cmdb.Rule{ + { + Field: "bk_cluster_id", + Operator: "in", + Value: bkClusterID, + }, + }, + }, + }, + }) + if err != nil { + blog.Errorf("GetBcsNamespace err: %v", err) + return + } + + namespaceToDelete := make([]int64, 0) + for _, namespace := range *got { + namespaceToDelete = append(namespaceToDelete, namespace.ID) + } + + if len(namespaceToDelete) == 0 { + break + } + + blog.Infof("delete namespace: %v", namespaceToDelete) + err = c.DeleteBcsNamespace(&cmdb.DeleteBcsNamespaceReq{ + BKBizID: &bkBizID, + IDs: &namespaceToDelete, + }) + if err != nil { + blog.Errorf("DeleteBcsNamespace() error = %v", err) + return + } + } + + blog.Info("delete all namespace success") +} + +func deleteAll2IDIDNode(bkBizID int64, bkClusterID []int64, c *cmdb.Client) { + blog.Info("start delete all node") + + for { + got, err := c.GetBcsNode(&cmdb.GetBcsNodeReq{ + CommonReq: cmdb.CommonReq{ + BKBizID: bkBizID, + Page: cmdb.Page{ + Limit: 100, + Start: 0, + }, + Filter: &cmdb.PropertyFilter{ + Condition: "AND", + Rules: []cmdb.Rule{ + { + Field: "bk_cluster_id", + Operator: "in", + Value: bkClusterID, + }, + }, + }, + }, + }) + if err != nil { + blog.Errorf("GetBcsNode err: %v", err) + return + } + nodeToDelete := make([]int64, 0) + for _, node := range *got { + nodeToDelete = append(nodeToDelete, node.ID) + } + + if len(nodeToDelete) == 0 { + break + } + + blog.Infof("delete node: %v", nodeToDelete) + err = c.DeleteBcsNode(&cmdb.DeleteBcsNodeReq{ + BKBizID: &bkBizID, + IDs: &nodeToDelete, + }) + if err != nil { + blog.Errorf("DeleteBcsNode err: %v", err) + return + } + } + + blog.Info("delete all node success") +} + +func deleteAll2IDCluster(bkBizID int64, bkClusterID []int64, c *cmdb.Client) { + blog.Info("start delete all cluster") + + for { + got, err := c.GetBcsCluster(&cmdb.GetBcsClusterReq{ + CommonReq: cmdb.CommonReq{ + BKBizID: bkBizID, + Fields: []string{"id"}, + Page: cmdb.Page{ + Limit: 10, + Start: 0, + }, + Filter: &cmdb.PropertyFilter{ + Condition: "AND", + Rules: []cmdb.Rule{ + { + Field: "id", + Operator: "in", + Value: bkClusterID, + }, + }, + }, + }, + }) + if err != nil { + blog.Errorf("GetBcsCluster err: %v", err) + return + } + clusterToDelete := make([]int64, 0) + for _, cluster := range *got { + clusterToDelete = append(clusterToDelete, cluster.ID) + } + + if len(clusterToDelete) == 0 { + break + } + + blog.Infof("delete cluster: %v", clusterToDelete) + err = c.DeleteBcsCluster(&cmdb.DeleteBcsClusterReq{ + BKBizID: &bkBizID, + IDs: &clusterToDelete, + }) + if err != nil { + blog.Errorf("DeleteBcsCluster err: %v", err) + return + } + } + + blog.Info("delete all cluster success") +} diff --git a/bcs-services/bcs-platform-manager/pkg/api/routes.go b/bcs-services/bcs-platform-manager/pkg/api/routes.go index b523f8ff02..a659caf2d4 100644 --- a/bcs-services/bcs-platform-manager/pkg/api/routes.go +++ b/bcs-services/bcs-platform-manager/pkg/api/routes.go @@ -23,7 +23,11 @@ import ( "github.com/go-chi/chi/v5" httpSwagger "github.com/swaggo/http-swagger" - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/api/pod" + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/api/cloudvpc" + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/api/cluster" + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/api/cmdb" + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/api/task" + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/api/templateconfig" "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/rest" "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/rest/middleware" @@ -111,12 +115,31 @@ func registerRoutes() http.Handler { r := chi.NewRouter() // 日志相关接口 - r.Route("/projects/{projectId}/clusters/{clusterId}", func(route chi.Router) { - route.Use(middleware.AuthenticationRequired, middleware.ProjectParse, middleware.ClusterAuthorization) - route.Use(middleware.VisitorsRequired, middleware.Tracing, middleware.Audit) + r.Route("/", func(route chi.Router) { + route.Use(middleware.AuthenticationRequired, middleware.Tracing, middleware.Audit) - route.Get("/containers", rest.Handle(pod.GetPodContainers)) + // vpc 相关接口 + route.Post("/cloudvpc", rest.Handle(cloudvpc.CreateCloudVPC)) + route.Put("/cloudvpc", rest.Handle(cloudvpc.UpdateCloudVPC)) + + // templateconfig 相关接口 + route.Post("/templateconfigs", rest.Handle(templateconfig.CreateTemplateConfig)) + route.Delete("/templateconfigs/{templateConfigID}", rest.Handle(templateconfig.DeleteTemplateConfig)) + + // cluster 相关接口 + route.Get("/cluster", rest.Handle(cluster.ListCluster)) + route.Put("/cluster/{clusterID}/operator", rest.Handle(cluster.UpdateClusterOperator)) + route.Put("/cluster/{clusterID}/project_business", rest.Handle(cluster.UpdateClusterProjectBusiness)) + + // task 相关接口 + route.Get("/task/{taskID}", rest.Handle(task.GetTask)) + route.Put("/task/{taskID}/retry", rest.Handle(task.RetryTask)) + route.Put("/task/{taskID}/skip", rest.Handle(task.SkipTask)) + + // cmdb 相关接口 + route.Put("/cmdb/delete_all", rest.Handle(cmdb.DeleteAllByBkBizIDAndBkClusterID)) }) + return r } diff --git a/bcs-services/bcs-platform-manager/pkg/api/task/task.go b/bcs-services/bcs-platform-manager/pkg/api/task/task.go new file mode 100644 index 0000000000..87f7023f3b --- /dev/null +++ b/bcs-services/bcs-platform-manager/pkg/api/task/task.go @@ -0,0 +1,133 @@ +/* + * Tencent is pleased to support the open source community by making Blueking Container Service available. + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * 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 task task operate +package task + +import ( + "context" + + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/clustermanager" + + clustermgr "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager" +) + +// GetTaskReq get task request +type GetTaskReq struct { + TaskID string `json:"taskID" in:"path=taskID"` +} + +// RetryTaskkReq retry task request +type RetryTaskkReq struct { + TaskID string `json:"taskID" in:"path=taskID"` + Updater string `json:"updater"` +} + +// SkipTaskReq skip task request +type SkipTaskReq struct { + TaskID string `json:"taskID" in:"path=taskID"` + Updater string `json:"updater"` +} + +// Task 任务详情 +type Task struct { + TaskID string `json:"taskID"` + TaskType string `json:"taskType"` + Status string `json:"status"` + Message string `json:"message"` + Start string `json:"start"` + End string `json:"end"` + ExecutionTime uint32 `json:"executionTime"` + CurrentStep string `json:"currentStep"` + StepSequence []string `json:"stepSequence"` + Steps map[string]*clustermanager.Step `json:"steps"` + ClusterID string `json:"clusterID"` + ProjectID string `json:"projectID"` + Creator string `json:"creator"` + LastUpdate string `json:"lastUpdate"` + Updater string `json:"updater"` + ForceTerminate bool `json:"forceTerminate"` + TaskName string `json:"taskName"` + NodeGroupID string `json:"nodeGroupID"` +} + +// GetTask 获取任务详情 +// @Summary 任务详情 +// @Tags Logs +// @Produce json +// @Success 200 {array} k8sclient.Container +// @Router /task/{taskID} [get] +func GetTask(ctx context.Context, req *GetTaskReq) (*Task, error) { + task, err := clustermgr.GetTask(ctx, &clustermanager.GetTaskRequest{ + TaskID: req.TaskID, + }) + if err != nil { + return nil, err + } + + return &Task{ + TaskID: task.TaskID, + TaskType: task.TaskType, + Status: task.Status, + Message: task.Message, + Start: task.Start, + End: task.End, + ExecutionTime: task.ExecutionTime, + CurrentStep: task.CurrentStep, + StepSequence: task.StepSequence, + Steps: task.Steps, + ClusterID: task.ClusterID, + ProjectID: task.ProjectID, + Creator: task.Creator, + LastUpdate: task.LastUpdate, + Updater: task.Updater, + ForceTerminate: task.ForceTerminate, + TaskName: task.TaskName, + NodeGroupID: task.NodeGroupID, + }, nil +} + +// RetryTask 任务重试 +// @Summary 任务重试 +// @Tags Logs +// @Produce json +// @Success 200 {array} k8sclient.Container +// @Router /task/{taskID}/retry [put] +func RetryTask(ctx context.Context, req *RetryTaskkReq) (*bool, error) { + result, err := clustermgr.RetryTask(ctx, &clustermanager.RetryTaskRequest{ + TaskID: req.TaskID, + Updater: req.Updater, + }) + if err != nil { + return nil, err + } + + return &result, nil +} + +// SkipTask 跳过当前任务 +// @Summary 跳过当前失败任务 +// @Tags Logs +// @Produce json +// @Success 200 {array} k8sclient.Container +// @Router /task/{taskID}/skip [put] +func SkipTask(ctx context.Context, req *SkipTaskReq) (*bool, error) { + result, err := clustermgr.SkipTask(ctx, &clustermanager.SkipTaskRequest{ + TaskID: req.TaskID, + Updater: req.Updater, + }) + if err != nil { + return nil, err + } + + return &result, nil +} diff --git a/bcs-services/bcs-platform-manager/pkg/api/templateconfig/templateconfig.go b/bcs-services/bcs-platform-manager/pkg/api/templateconfig/templateconfig.go new file mode 100644 index 0000000000..705a3f370a --- /dev/null +++ b/bcs-services/bcs-platform-manager/pkg/api/templateconfig/templateconfig.go @@ -0,0 +1,63 @@ +/* + * Tencent is pleased to support the open source community by making Blueking Container Service available. + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * 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 templateconfig templateconfig operate +package templateconfig + +import ( + "context" + + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/clustermanager" + + clustermgr "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager" +) + +// DeleteTemplateConfigReq delete template config request +type DeleteTemplateConfigReq struct { + TemplateConfigID string `json:"cloudID" in:"path=templateConfigID"` + BusinessID string `json:"businessID" in:"query=businessID"` + ProjectID string `json:"projectID" in:"query=projectID"` +} + +// CreateTemplateConfig 创建TemplateConfig +// @Summary 创建TemplateConfig +// @Tags Logs +// @Produce json +// @Success 200 {array} k8sclient.Container +// @Router /templateConfig [post] +func CreateTemplateConfig(ctx context.Context, req *clustermanager.CreateTemplateConfigRequest) (*bool, error) { + result, err := clustermgr.CreateTemplateConfig(ctx, req) + if err != nil { + return nil, err + } + + return &result, nil +} + +// DeleteTemplateConfig 删除TemplateConfig +// @Summary 删除TemplateConfig +// @Tags Logs +// @Produce json +// @Success 200 {array} k8sclient.Container +// @Router /templateConfig/{templateConfigID} [delete] +func DeleteTemplateConfig(ctx context.Context, req *DeleteTemplateConfigReq) (*bool, error) { + result, err := clustermgr.DeleteTemplateConfig(ctx, &clustermanager.DeleteTemplateConfigRequest{ + TemplateConfigID: req.TemplateConfigID, + BusinessID: req.BusinessID, + ProjectID: req.ProjectID, + }) + if err != nil { + return nil, err + } + + return &result, nil +} diff --git a/bcs-services/bcs-platform-manager/pkg/component/bcs/bcs.go b/bcs-services/bcs-platform-manager/pkg/component/bcs/bcs.go deleted file mode 100644 index 596d7ab633..0000000000 --- a/bcs-services/bcs-platform-manager/pkg/component/bcs/bcs.go +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making Blueking Container Service available. - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * Licensed under the MIT License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * http://opensource.org/licenses/MIT - * 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 bcs 集群操作 -package bcs - -import ( - "encoding/json" - "errors" - "fmt" - "time" - - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component" - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/storage" -) - -const ( - // VirtualClusterType vcluster - VirtualClusterType = "virtual" -) - -// Cluster 集群信息 -type Cluster struct { - ProjectID string `json:"projectID"` - ClusterID string `json:"clusterID"` - ClusterName string `json:"clusterName"` - BKBizID string `json:"businessID"` - Status string `json:"status"` - IsShared bool `json:"is_shared"` - ClusterType string `json:"clusterType"` - NetworkSettings struct { - MaxNodePodNum int `json:"maxNodePodNum"` - MaxServiceNum int `json:"maxServiceNum"` - } `json:"networkSettings"` - ExtraInfo struct { - NamespaceInfo string `json:"namespaceInfo"` - Provider string `json:"provider"` - VclusterNetwork string `json:"vclusterNetwork"` - } `json:"extraInfo"` - VclusterInfo VclusterInfo `json:"-"` -} - -// VclusterInfo vcluster info, parse from extraInfo.namespaceInfo -type VclusterInfo struct { - Name string `json:"name"` - Quota VclusterQuota `json:"quota"` -} - -// VclusterQuota vcluster quota, parse from extraInfo.namespaceInfo -type VclusterQuota struct { - CPURequests string `json:"cpuRequests"` - CPULimits string `json:"cpuLimits"` - MemoryRequests string `json:"MemoryRequests"` - MemoryLimits string `json:"memoryLimits"` -} - -// String : -func (c *Cluster) String() string { - return fmt.Sprintf("cluster<%s, %s>", c.ClusterName, c.ClusterID) -} - -// IsVirtual check cluster is vcluster -func (c *Cluster) IsVirtual() bool { - return c.ClusterType == VirtualClusterType -} - -// CacheListClusters 定时同步 cluster 列表 -func CacheListClusters() { - go func() { - ListClusters() - for range time.Tick(time.Minute * 1) { - blog.Infof("list clusters running") - ListClusters() - blog.Infof("list clusters end") - } - }() -} - -const listClustersCacheKey = "bcs.ListClusters" - -// ListClusters 获取集群列表 -func ListClusters() { - url := fmt.Sprintf("%s/bcsapi/v4/clustermanager/v1/cluster", config.G.BCS.Host) - - resp, err := component.GetClient().R(). - SetAuthToken(config.G.BCS.Token). - Get(url) - - if err != nil { - blog.Errorf("list clusters error, %s", err.Error()) - return - } - - var result []*Cluster - if err = component.UnmarshalBKResult(resp, &result); err != nil { - blog.Errorf("unmarshal clusters error, %s", err.Error()) - return - } - - clusterMap := map[string]*Cluster{} - for _, cluster := range result { - cls := cluster - if cls.IsVirtual() { - cls.VclusterInfo, err = parseVClusterInfo(cls.ExtraInfo.NamespaceInfo) - if err != nil { - blog.Errorf("parse clusters %s namespaceInfo %s error, %s", cls.ClusterID, cls.ExtraInfo.NamespaceInfo, - err.Error()) - } - } - clusterMap[cluster.ClusterID] = cls - } - - storage.LocalCache.Slot.Set(listClustersCacheKey, clusterMap, -1) -} - -func parseVClusterInfo(s string) (VclusterInfo, error) { - info := VclusterInfo{} - if s == "" { - return info, nil - } - err := json.Unmarshal([]byte(s), &info) - if err != nil { - return info, err - } - return info, nil -} - -// GetClusterMap 获取全部集群数据, map格式 -func GetClusterMap() (map[string]*Cluster, error) { - if cacheResult, ok := storage.LocalCache.Slot.Get(listClustersCacheKey); ok { - return cacheResult.(map[string]*Cluster), nil - } - return nil, errNotFoundCluster -} - -var errNotFoundCluster = errors.New("not found cluster") - -// GetCluster 获取集群详情 -func GetCluster(clusterID string) (*Cluster, error) { - getCluster := func() (*Cluster, error) { - var cacheResult interface{} - var ok bool - if cacheResult, ok = storage.LocalCache.Slot.Get(listClustersCacheKey); !ok { - return nil, errNotFoundCluster - } - if clusterMap, ok := cacheResult.(map[string]*Cluster); ok { - if cls, ok := clusterMap[clusterID]; ok { - return cls, nil - } - return nil, errNotFoundCluster - } - return nil, fmt.Errorf("cluster cache is invalid") - } - - cls, err := getCluster() - if err != nil { - // 新创建的集群,未在缓存中,刷新一下缓存 - if errors.Is(err, errNotFoundCluster) { - ListClusters() - return getCluster() - } - return nil, err - } - return cls, nil -} diff --git a/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/client.go b/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/client.go new file mode 100644 index 0000000000..423768fd02 --- /dev/null +++ b/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/client.go @@ -0,0 +1,75 @@ +/* + * Tencent is pleased to support the open source community by making Blueking Container Service available. + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * 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 clustermanager xxx +package clustermanager + +import ( + "context" + "crypto/tls" + "fmt" + + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/clustermanager" + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" + "github.com/pkg/errors" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/metadata" +) + +// Client xxx +type Client struct { + ctx context.Context + conn *grpc.ClientConn + clustermanager.ClusterManagerClient +} + +// New create client for bcs-Cluster +func New(ctx context.Context) (*Client, error) { + header := map[string]string{ + "x-content-type": "application/grpc+proto", + "Content-Type": "application/grpc", + } + + if len(config.G.BCS.Token) != 0 { + header["Authorization"] = fmt.Sprintf("Bearer %s", config.G.BCS.Token) + } + md := metadata.New(header) + + var opts []grpc.DialOption + opts = append(opts, grpc.WithDefaultCallOptions(grpc.Header(&md))) + opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{InsecureSkipVerify: true}))) + + conn, err := grpc.NewClient(config.G.BCS.Target, opts...) + if err != nil { + return nil, errors.Wrapf(err, "create grpc client with '%s' failed", config.G.BCS.Host) + } + + if conn == nil { + return nil, fmt.Errorf("conn is nil") + } + + return &Client{ + ctx: metadata.NewOutgoingContext(ctx, md), + conn: conn, + ClusterManagerClient: clustermanager.NewClusterManagerClient(conn), + }, nil +} + +// Close close client +func (c *Client) Close() { + err := c.conn.Close() + if err != nil { + blog.Errorf("grpc client close failed: %s", err) + } +} diff --git a/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/cloudvpc.go b/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/cloudvpc.go new file mode 100644 index 0000000000..51c82d4199 --- /dev/null +++ b/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/cloudvpc.go @@ -0,0 +1,63 @@ +/* + * Tencent is pleased to support the open source community by making Blueking Container Service available. + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * 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 clustermanager cloudvpc操作 +package clustermanager + +import ( + "context" + "fmt" + + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/clustermanager" +) + +// CreateCloudVPC 创建cloud vpc +func CreateCloudVPC(ctx context.Context, req *clustermanager.CreateCloudVPCRequest) (bool, error) { + cli, err := New(ctx) + if err != nil { + return false, err + } + + defer cli.Close() + + p, err := cli.CreateCloudVPC(cli.ctx, req) + if err != nil { + return false, fmt.Errorf("CreateCloudVPC error: %s", err) + } + + if p.Code != 0 { + return false, fmt.Errorf("CreateCloudVPC error, code: %d, message: %s", p.Code, p.GetMessage()) + } + + return p.Result, nil +} + +// UpdateCloudVPC 更新cloud vpc +func UpdateCloudVPC(ctx context.Context, req *clustermanager.UpdateCloudVPCRequest) (bool, error) { + cli, err := New(ctx) + if err != nil { + return false, err + } + + defer cli.Close() + + p, err := cli.UpdateCloudVPC(cli.ctx, req) + if err != nil { + return false, fmt.Errorf("UpdateCloudVPC error: %s", err) + } + + if p.Code != 0 { + return false, fmt.Errorf("UpdateCloudVPC error, code: %d, message: %s", p.Code, p.GetMessage()) + } + + return p.Result, nil +} diff --git a/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/cluster.go b/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/cluster.go new file mode 100644 index 0000000000..f539fd70dd --- /dev/null +++ b/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/cluster.go @@ -0,0 +1,85 @@ +/* + * Tencent is pleased to support the open source community by making Blueking Container Service available. + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * 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 clustermanager xxx +package clustermanager + +import ( + "context" + "fmt" + + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/clustermanager" +) + +// GetCluster get cluster from cluster manager +func GetCluster(ctx context.Context, clusterID string) (*clustermanager.Cluster, error) { + cli, err := New(ctx) + if err != nil { + return nil, err + } + + defer cli.Close() + + p, err := cli.GetCluster(cli.ctx, &clustermanager.GetClusterReq{ClusterID: clusterID}) + if err != nil { + return nil, fmt.Errorf("GetCluster error: %s", err) + } + + if p.Code != 0 { + return nil, fmt.Errorf("GetCluster error, code: %d, message: %s", p.Code, p.GetMessage()) + } + + return p.Data, nil +} + +// ListCluster list cluster from cluster manager +func ListCluster(ctx context.Context, req *clustermanager.ListClusterV2Req) ( + []*clustermanager.ClusterBasicInfo, error) { + cli, err := New(ctx) + if err != nil { + return nil, err + } + + defer cli.Close() + + p, err := cli.ListClusterV2(cli.ctx, req) + if err != nil { + return nil, fmt.Errorf("ListCluster error: %s", err) + } + + if p.Code != 0 { + return nil, fmt.Errorf("ListCluster error, code: %d, message: %s", p.Code, p.GetMessage()) + } + + return p.Data, nil +} + +// UpdateCluster update cluster from cluster manager +func UpdateCluster(ctx context.Context, req *clustermanager.UpdateClusterReq) (bool, error) { + cli, err := New(ctx) + if err != nil { + return false, err + } + + defer cli.Close() + + p, err := cli.UpdateCluster(cli.ctx, req) + if err != nil { + return false, fmt.Errorf("UpdateCluster error: %s", err) + } + + if p.Code != 0 { + return false, fmt.Errorf("UpdateCluster error, code: %d, message: %s", p.Code, p.GetMessage()) + } + + return p.Result, nil +} diff --git a/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/task.go b/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/task.go new file mode 100644 index 0000000000..b1850bde65 --- /dev/null +++ b/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/task.go @@ -0,0 +1,84 @@ +/* + * Tencent is pleased to support the open source community by making Blueking Container Service available. + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * 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 clustermanager cloudvpc操作 +package clustermanager + +import ( + "context" + "fmt" + + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/clustermanager" +) + +// GetTask 获取任务详情 +func GetTask(ctx context.Context, req *clustermanager.GetTaskRequest) (*clustermanager.Task, error) { + cli, err := New(ctx) + if err != nil { + return nil, err + } + + defer cli.Close() + + p, err := cli.GetTask(cli.ctx, req) + if err != nil { + return nil, fmt.Errorf("GetTask error: %s", err) + } + + if p.Code != 0 { + return nil, fmt.Errorf("GetTask error, code: %d, message: %s", p.Code, p.GetMessage()) + } + + return p.Data, nil +} + +// RetryTask 任务重试 +func RetryTask(ctx context.Context, req *clustermanager.RetryTaskRequest) (bool, error) { + cli, err := New(ctx) + if err != nil { + return false, err + } + + defer cli.Close() + + p, err := cli.RetryTask(cli.ctx, req) + if err != nil { + return false, fmt.Errorf("RetryTask error: %s", err) + } + + if p.Code != 0 { + return false, fmt.Errorf("RetryTask error, code: %d, message: %s", p.Code, p.GetMessage()) + } + + return p.Result, nil +} + +// SkipTask 跳过当前任务 +func SkipTask(ctx context.Context, req *clustermanager.SkipTaskRequest) (bool, error) { + cli, err := New(ctx) + if err != nil { + return false, err + } + + defer cli.Close() + + p, err := cli.SkipTask(cli.ctx, req) + if err != nil { + return false, fmt.Errorf("SkipTask error: %s", err) + } + + if p.Code != 0 { + return false, fmt.Errorf("SkipTask error, code: %d, message: %s", p.Code, p.GetMessage()) + } + + return p.Result, nil +} diff --git a/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/templateconfig.go b/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/templateconfig.go new file mode 100644 index 0000000000..d61cab158e --- /dev/null +++ b/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/templateconfig.go @@ -0,0 +1,63 @@ +/* + * Tencent is pleased to support the open source community by making Blueking Container Service available. + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * 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 clustermanager templateconfig操作 +package clustermanager + +import ( + "context" + "fmt" + + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/clustermanager" +) + +// CreateTemplateConfig 创建template config +func CreateTemplateConfig(ctx context.Context, req *clustermanager.CreateTemplateConfigRequest) (bool, error) { + cli, err := New(ctx) + if err != nil { + return false, err + } + + defer cli.Close() + + p, err := cli.CreateTemplateConfig(cli.ctx, req) + if err != nil { + return false, fmt.Errorf("CreateTemplateConfig error: %s", err) + } + + if p.Code != 0 { + return false, fmt.Errorf("CreateTemplateConfig error, code: %d, message: %s", p.Code, p.GetMessage()) + } + + return p.Result, nil +} + +// DeleteTemplateConfig 删除template config +func DeleteTemplateConfig(ctx context.Context, req *clustermanager.DeleteTemplateConfigRequest) (bool, error) { + cli, err := New(ctx) + if err != nil { + return false, err + } + + defer cli.Close() + + p, err := cli.DeleteTemplateConfig(cli.ctx, req) + if err != nil { + return false, fmt.Errorf("DeleteTemplateConfig error: %s", err) + } + + if p.Code != 0 { + return false, fmt.Errorf("DeleteTemplateConfig error, code: %d, message: %s", p.Code, p.GetMessage()) + } + + return p.Result, nil +} diff --git a/bcs-services/bcs-platform-manager/pkg/component/bcs/project.go b/bcs-services/bcs-platform-manager/pkg/component/bcs/project.go deleted file mode 100644 index c3c76bb952..0000000000 --- a/bcs-services/bcs-platform-manager/pkg/component/bcs/project.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making Blueking Container Service available. - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * Licensed under the MIT License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * http://opensource.org/licenses/MIT - * 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 bcs - -import ( - "context" - "fmt" - "time" - - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component" - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/storage" - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/utils" -) - -// Project 项目信息 -type Project struct { - Name string `json:"name"` - ProjectId string `json:"projectID"` - Code string `json:"projectCode"` - CcBizID string `json:"businessID"` - Creator string `json:"creator"` - Kind string `json:"kind"` - RawCreateTime string `json:"createTime"` -} - -// String : -func (p *Project) String() string { - var displayCode string - if p.Code == "" { - displayCode = "-" - } else { - displayCode = p.Code - } - return fmt.Sprintf("project<%s, %s|%s|%s>", p.Name, displayCode, p.ProjectId, p.CcBizID) -} - -// CreateTime xxx -func (p *Project) CreateTime() (time.Time, error) { - return time.ParseInLocation("2006-01-02T15:04:05Z", p.RawCreateTime, config.G.Base.Location) -} - -// GetProject 通过 project_id/code 获取项目信息 -func GetProject(ctx context.Context, bcsConf *config.BCSConf, projectIDOrCode string) (*Project, error) { - cacheKey := fmt.Sprintf("bcs.GetProject:%s", projectIDOrCode) - if cacheResult, ok := storage.LocalCache.Slot.Get(cacheKey); ok { - return cacheResult.(*Project), nil - } - - url := fmt.Sprintf("%s/bcsapi/v4/bcsproject/v1/projects/%s", bcsConf.Host, projectIDOrCode) - resp, err := component.GetClient().R(). - SetContext(ctx). - SetHeaders(utils.GetLaneIDByCtx(ctx)). // 泳道特性 - SetHeader("X-Project-Username", ""). // bcs_project 要求有这个header - SetAuthToken(bcsConf.Token). - Get(url) - - if err != nil { - return nil, err - } - - project := new(Project) - if err := component.UnmarshalBKResult(resp, project); err != nil { - return nil, err - } - - storage.LocalCache.Slot.Set(cacheKey, project, time.Hour*24) - - return project, nil -} diff --git a/bcs-services/bcs-platform-manager/pkg/component/bcs/project_test.go b/bcs-services/bcs-platform-manager/pkg/component/bcs/project_test.go deleted file mode 100644 index f06066f883..0000000000 --- a/bcs-services/bcs-platform-manager/pkg/component/bcs/project_test.go +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making Blueking Container Service available. - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * Licensed under the MIT License (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * http://opensource.org/licenses/MIT - * 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 bcs - -import ( - "context" - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" - bcstesting "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/testing" -) - -func TestGetProject(t *testing.T) { - ctx := context.Background() - - project, err := GetProject(ctx, config.G.BCS, bcstesting.GetTestProjectId()) - assert.NoError(t, err) - assert.Equal(t, project.ProjectId, bcstesting.GetTestProjectId()) -} diff --git a/bcs-services/bcs-platform-manager/pkg/component/bcs/projectmanager/client.go b/bcs-services/bcs-platform-manager/pkg/component/bcs/projectmanager/client.go new file mode 100644 index 0000000000..7757325052 --- /dev/null +++ b/bcs-services/bcs-platform-manager/pkg/component/bcs/projectmanager/client.go @@ -0,0 +1,75 @@ +/* + * Tencent is pleased to support the open source community by making Blueking Container Service available. + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * 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 projectmanager xxx +package projectmanager + +import ( + "context" + "crypto/tls" + "fmt" + + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/bcsproject" + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" + "github.com/pkg/errors" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/metadata" +) + +// Client xxx +type Client struct { + ctx context.Context + conn *grpc.ClientConn + bcsproject.BCSProjectClient +} + +// New create client for bcs-Cluster +func New(ctx context.Context) (*Client, error) { + header := map[string]string{ + "x-content-type": "application/grpc+proto", + "Content-Type": "application/grpc", + } + + if len(config.G.BCS.Token) != 0 { + header["Authorization"] = fmt.Sprintf("Bearer %s", config.G.BCS.Token) + } + md := metadata.New(header) + + var opts []grpc.DialOption + opts = append(opts, grpc.WithDefaultCallOptions(grpc.Header(&md))) + opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{InsecureSkipVerify: true}))) + + conn, err := grpc.NewClient(config.G.BCS.Target, opts...) + if err != nil { + return nil, errors.Wrapf(err, "create grpc client with '%s' failed", config.G.BCS.Host) + } + + if conn == nil { + return nil, fmt.Errorf("conn is nil") + } + + return &Client{ + ctx: metadata.NewOutgoingContext(ctx, md), + conn: conn, + BCSProjectClient: bcsproject.NewBCSProjectClient(conn), + }, nil +} + +// Close close client +func (c *Client) Close() { + err := c.conn.Close() + if err != nil { + blog.Errorf("grpc client close failed: %s", err) + } +} diff --git a/bcs-services/bcs-platform-manager/pkg/component/bcs/projectmanager/project.go b/bcs-services/bcs-platform-manager/pkg/component/bcs/projectmanager/project.go new file mode 100644 index 0000000000..d16114fc43 --- /dev/null +++ b/bcs-services/bcs-platform-manager/pkg/component/bcs/projectmanager/project.go @@ -0,0 +1,63 @@ +/* + * Tencent is pleased to support the open source community by making Blueking Container Service available. + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * 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 projectmanager xxx +package projectmanager + +import ( + "context" + "fmt" + + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/bcsproject" +) + +// GetProject get project from project manager +func GetProject(ctx context.Context, projectIDOrCode string) (*bcsproject.Project, error) { + cli, err := New(ctx) + if err != nil { + return nil, err + } + + defer cli.Close() + + p, err := cli.GetProject(cli.ctx, &bcsproject.GetProjectRequest{ProjectIDOrCode: projectIDOrCode}) + if err != nil { + return nil, fmt.Errorf("GetProject error: %s", err) + } + + if p.Code != 0 || p.Data == nil { + return nil, fmt.Errorf("GetProject error, code: %d, message: %s", p.Code, p.GetMessage()) + } + + return p.Data, nil +} + +// ListProject list project from project manager +func ListProject(ctx context.Context) ([]*bcsproject.Project, error) { + cli, err := New(ctx) + if err != nil { + return nil, err + } + + defer cli.Close() + + p, err := cli.ListProjects(cli.ctx, &bcsproject.ListProjectsRequest{All: true}) + if err != nil { + return nil, fmt.Errorf("ListProject error: %s", err) + } + + if p.Code != 0 || p.Data == nil { + return nil, fmt.Errorf("ListProject error, code: %d, message: %s", p.Code, p.GetMessage()) + } + + return p.Data.GetResults(), nil +} diff --git a/bcs-services/bcs-platform-manager/pkg/component/cmdb/cmdb.go b/bcs-services/bcs-platform-manager/pkg/component/cmdb/cmdb.go new file mode 100644 index 0000000000..90359d140b --- /dev/null +++ b/bcs-services/bcs-platform-manager/pkg/component/cmdb/cmdb.go @@ -0,0 +1,419 @@ +/* + * Tencent is pleased to support the open source community by making Blueking Container Service available. + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * 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 cmdb xxx +package cmdb + +import ( + "encoding/json" + "fmt" + "time" + + bkcmdbkube "configcenter/src/kube/types" + + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" + "github.com/parnurzeal/gorequest" +) + +var ( + defaultTimeOut = time.Second * 60 +) + +// Options for cmdb client +type Options struct { + AppCode string + AppSecret string + BKUserName string + Server string + Debug bool +} + +// client for cc +type Client struct { + config *Options + userAuth string +} + +// AuthInfo auth user +type AuthInfo struct { + BkAppCode string `json:"bk_app_code"` + BkAppSecret string `json:"bk_app_secret"` + BkUserName string `json:"bk_username"` +} + +// New create cmdb client +func New() *Client { + c := &Client{ + config: &Options{ + AppCode: config.G.Base.AppCode, + AppSecret: config.G.Base.AppSecret, + BKUserName: config.G.Base.BKUsername, + Server: config.G.Cmdb.Host, + Debug: config.G.Cmdb.Debug, + }, + } + + auth, err := c.generateGateWayAuth() + if err != nil { + return nil + } + c.userAuth = auth + return c +} + +func (c *Client) generateGateWayAuth() (string, error) { + auth := &AuthInfo{ + BkAppCode: c.config.AppCode, + BkAppSecret: c.config.AppSecret, + BkUserName: c.config.BKUserName, + } + + userAuth, err := json.Marshal(auth) + if err != nil { + return "", err + } + + return string(userAuth), nil +} + +// GetBcsPod get pod +func (c *Client) GetBcsPod(req *GetBcsPodReq) (*[]bkcmdbkube.Pod, error) { + reqURL := fmt.Sprintf("%s/api/v3/findmany/kube/pod", c.config.Server) + respData := &GetBcsPodResp{} + + resp, _, errs := gorequest.New(). + Timeout(defaultTimeOut). + Post(reqURL). + Set("Content-Type", "application/json"). + Set("Accept", "application/json"). + Set("X-Bkapi-Authorization", c.userAuth). + SetDebug(c.config.Debug). + Send(req). + Retry(3, 3*time.Second, 429). + EndStruct(&respData) + if len(errs) > 0 { + blog.Errorf("call api list_pod failed: %v", errs[0]) + return nil, errs[0] + } + + if !respData.Result { + blog.Errorf("call api list_pod failed: %v, rid: %s", + respData.Message, resp.Header.Get("X-Request-Id")) + return nil, fmt.Errorf(respData.Message) + } + + blog.Infof("call api list_pod with url(%s) (%v) successfully, X-Request-Id: %s", + reqURL, req, resp.Header.Get("X-Request-Id")) + + return respData.Data.Info, nil +} + +// DeleteBcsPod delete pod +func (c *Client) DeleteBcsPod(req *DeleteBcsPodReq) error { + reqURL := fmt.Sprintf("%s/api/v3/deletemany/kube/pod", c.config.Server) + respData := &DeleteBcsPodResp{} + + resp, _, errs := gorequest.New(). + Timeout(defaultTimeOut). + Delete(reqURL). + Set("Content-Type", "application/json"). + Set("Accept", "application/json"). + Set("X-Bkapi-Authorization", c.userAuth). + SetDebug(c.config.Debug). + Send(req). + Retry(3, 3*time.Second, 429). + EndStruct(&respData) + if len(errs) > 0 { + blog.Errorf("call api batch_delete_kube_pod failed: %v", errs[0]) + return errs[0] + } + + if !respData.Result { + blog.Errorf("call api batch_delete_kube_pod failed: %v, rid: %s", + respData.Message, resp.Header.Get("X-Request-Id")) + return fmt.Errorf(respData.Message) + } + + blog.Infof("call api batch_delete_kube_pod with url(%s) (%v) successfully, X-Request-Id: %s", + reqURL, req, resp.Header.Get("X-Request-Id")) + + return nil +} + +// GetBcsWorkload get workload +func (c *Client) GetBcsWorkload(req *GetBcsWorkloadReq) (*[]interface{}, error) { + reqURL := fmt.Sprintf("%s/api/v3/findmany/kube/workload/%s", c.config.Server, req.Kind) + respData := &GetBcsWorkloadResp{} + + resp, _, errs := gorequest.New(). + Timeout(defaultTimeOut). + Post(reqURL). + Set("Content-Type", "application/json"). + Set("Accept", "application/json"). + Set("X-Bkapi-Authorization", c.userAuth). + SetDebug(c.config.Debug). + Send(req). + Retry(3, 3*time.Second, 429). + EndStruct(&respData) + if len(errs) > 0 { + blog.Errorf("call api list_workload failed: %v, rid: %s", errs[0], respData.RequestID) + return nil, errs[0] + } + + if !respData.Result { + blog.Errorf("call api list_workload failed: %v, rid: %s", + respData.Message, resp.Header.Get("X-Request-Id")) + return nil, fmt.Errorf(respData.Message) + } + + blog.Infof("call api list_workload with url(%s) (%v) successfully, X-Request-Id: %s", + reqURL, req, resp.Header.Get("X-Request-Id")) + + return &respData.Data.Info, nil +} + +// DeleteBcsWorkload delete workload +func (c *Client) DeleteBcsWorkload(req *DeleteBcsWorkloadReq) error { + reqURL := fmt.Sprintf("%s/api/v3/deletemany/kube/workload/%s", c.config.Server, *req.Kind) + respData := &DeleteBcsWorkloadResp{} + + resp, _, errs := gorequest.New(). + Timeout(defaultTimeOut). + Delete(reqURL). + Set("Content-Type", "application/json"). + Set("Accept", "application/json"). + Set("X-Bkapi-Authorization", c.userAuth). + SetDebug(c.config.Debug). + Send(req). + Retry(3, 3*time.Second, 429). + EndStruct(&respData) + if len(errs) > 0 { + blog.Errorf("call api batch_delete_workload failed: %v", errs[0]) + return errs[0] + } + + if !respData.Result { + blog.Errorf( + "call api batch_delete_workload failed: %v, rid: %s, request: bkbizid: %d, kind: %s, ids: %v", + respData.Message, resp.Header.Get("X-Request-Id"), *req.BKBizID, *req.Kind, *req.IDs) + return fmt.Errorf(respData.Message) + } + + blog.Infof("call api batch_delete_workload with url(%s) (%v) successfully, X-Request-Id: %s", + reqURL, req, resp.Header.Get("X-Request-Id")) + + return nil +} + +// GetBcsNamespace get namespace +func (c *Client) GetBcsNamespace(req *GetBcsNamespaceReq) (*[]bkcmdbkube.Namespace, error) { + reqURL := fmt.Sprintf("%s/api/v3/findmany/kube/namespace", c.config.Server) + respData := &GetBcsNamespaceResp{} + + resp, _, errs := gorequest.New(). + Timeout(defaultTimeOut). + Post(reqURL). + Set("Content-Type", "application/json"). + Set("Accept", "application/json"). + Set("X-Bkapi-Authorization", c.userAuth). + SetDebug(c.config.Debug). + Send(req). + Retry(3, 3*time.Second, 429). + EndStruct(&respData) + if len(errs) > 0 { + blog.Errorf("call api list_namespace failed: %v", errs[0]) + return nil, errs[0] + } + + if !respData.Result { + blog.Errorf("call api list_namespace failed: %v, rid: %s", + respData.Message, resp.Header.Get("X-Request-Id")) + return nil, fmt.Errorf(respData.Message) + } + + blog.Infof("call api list_namespace with url(%s) (%v) successfully, X-Request-Id: %s", + reqURL, req, resp.Header.Get("X-Request-Id")) + + return respData.Data.Info, nil +} + +// DeleteBcsNamespace delete namespace +func (c *Client) DeleteBcsNamespace(req *DeleteBcsNamespaceReq) error { + reqURL := fmt.Sprintf("%s/api/v3/deletemany/kube/namespace", c.config.Server) + respData := &DeleteBcsNamespaceResp{} + + resp, _, errs := gorequest.New(). + Timeout(defaultTimeOut). + Delete(reqURL). + Set("Content-Type", "application/json"). + Set("Accept", "application/json"). + Set("X-Bkapi-Authorization", c.userAuth). + SetDebug(c.config.Debug). + Send(req). + Retry(3, 3*time.Second, 429). + EndStruct(&respData) + if len(errs) > 0 { + blog.Errorf("call api batch_delete_namespace failed: %v", errs[0]) + return errs[0] + } + + if !respData.Result { + blog.Errorf("call api batch_delete_namespace failed: %v, rid: %s", + respData.Message, resp.Header.Get("X-Request-Id")) + return fmt.Errorf(respData.Message) + } + + blog.Infof("call api batch_delete_namespace with url(%s) (%v) successfully, X-Request-Id: %s", + reqURL, req, resp.Header.Get("X-Request-Id")) + + return nil +} + +// GetBcsNode get node +func (c *Client) GetBcsNode(req *GetBcsNodeReq) (*[]bkcmdbkube.Node, error) { + reqURL := fmt.Sprintf("%s/api/v3/findmany/kube/node", c.config.Server) + respData := &GetBcsNodeResp{} + + resp, _, errs := gorequest.New(). + Timeout(defaultTimeOut). + Post(reqURL). + Set("Content-Type", "application/json"). + Set("Accept", "application/json"). + Set("X-Bkapi-Authorization", c.userAuth). + SetDebug(c.config.Debug). + Send(req). + Retry(3, 3*time.Second, 429). + EndStruct(&respData) + if len(errs) > 0 { + blog.Errorf("call api list_kube_node failed: %v", errs[0]) + return nil, errs[0] + } + + if !respData.Result { + blog.Errorf("call api list_kube_node failed: %v, rid: %s", + respData.Message, resp.Header.Get("X-Request-Id")) + return nil, fmt.Errorf(respData.Message) + } + + blog.Infof("call api list_kube_node with url(%s) (%v) successfully, X-Request-Id: %s", + reqURL, req, resp.Header.Get("X-Request-Id")) + + return respData.Data.Info, nil +} + +// DeleteBcsNode delete node +func (c *Client) DeleteBcsNode(req *DeleteBcsNodeReq) error { + reqURL := fmt.Sprintf("%s/api/v3/deletemany/kube/node", c.config.Server) + respData := &DeleteBcsNodeResp{} + + resp, _, errs := gorequest.New(). + Timeout(defaultTimeOut). + Delete(reqURL). + Set("Content-Type", "application/json"). + Set("Accept", "application/json"). + Set("X-Bkapi-Authorization", c.userAuth). + SetDebug(c.config.Debug). + Send(req). + Retry(3, 3*time.Second, 429). + EndStruct(&respData) + if len(errs) > 0 { + blog.Errorf("call api batch_delete_kube_node failed: %v", errs[0]) + return errs[0] + } + + if !respData.Result { + blog.Errorf("call api batch_delete_kube_node failed: %v, rid: %s", + respData.Message, resp.Header.Get("X-Request-Id")) + return fmt.Errorf(respData.Message) + } + + blog.Infof("call api batch_delete_kube_node with url(%s) (%v) successfully, X-Request-Id: %s", + reqURL, req, resp.Header.Get("X-Request-Id")) + + return nil +} + +// GetBcsCluster get cluster +func (c *Client) GetBcsCluster(req *GetBcsClusterReq) (*[]bkcmdbkube.Cluster, error) { + // 如果没有通过数据库查询,则通过API调用获取集群信息 + reqURL := fmt.Sprintf("%s/api/v3/findmany/kube/cluster", c.config.Server) + respData := &GetBcsClusterResp{} + // 使用gorequest库发送POST请求,并处理响应 + resp, _, errs := gorequest.New(). + Timeout(defaultTimeOut). + Post(reqURL). + Set("Content-Type", "application/json"). + Set("Accept", "application/json"). + Set("X-Bkapi-Authorization", c.userAuth). + SetDebug(c.config.Debug). + Send(req). + Retry(3, 3*time.Second, 429). + EndStruct(&respData) + // 检查是否有错误发生 + if len(errs) > 0 { + blog.Errorf("call api list_kube_cluster failed: %v", errs[0]) + return nil, errs[0] + } + + // 检查API响应是否成功 + if !respData.Result { + blog.Errorf("call api list_kube_cluster failed: %v, rid: %s", + respData.Message, resp.Header.Get("X-Request-Id")) + return nil, fmt.Errorf(respData.Message) + } + + blog.Infof("call api list_kube_cluster with url(%s) (%v) successfully, X-Request-Id: %s", + reqURL, req, resp.Header.Get("X-Request-Id")) + + return &respData.Data.Info, nil +} + +func (c *Client) DeleteBcsCluster(req *DeleteBcsClusterReq) error { + // 构造请求的 URL + reqURL := fmt.Sprintf("%s/api/v3/delete/kube/cluster", c.config.Server) + // 初始化响应数据结构 + respData := &DeleteBcsClusterResp{} + + // 使用 gorequest 库发送 HTTP DELETE 请求 + // 设置请求超时时间、内容类型、接受类型、授权头等信息 + // 发送请求体并尝试重试,最多重试3次,每次间隔3秒,如果遇到429状态码也会重试 + resp, _, errs := gorequest.New(). + Timeout(defaultTimeOut). + Delete(reqURL). + Set("Content-Type", "application/json"). + Set("Accept", "application/json"). + Set("X-Bkapi-Authorization", c.userAuth). + SetDebug(c.config.Debug). + Send(req). + Retry(3, 3*time.Second, 429). + EndStruct(&respData) + + // 如果请求过程中出现错误,则记录错误并返回 + if len(errs) > 0 { + blog.Errorf("call api batch_delete_kube_cluster failed: %v", errs[0]) + return errs[0] + } + + // 如果响应结果指示操作失败,则记录错误信息并返回错误 + if !respData.Result { + blog.Errorf("call api batch_delete_kube_cluster failed: %v, rid: %s", + respData.Message, resp.Header.Get("X-Request-Id")) + return fmt.Errorf(respData.Message) + } + + // 如果操作成功,则记录成功的日志信息 + blog.Infof("call api batch_delete_kube_cluster with url(%s) (%v) successfully, X-Request-Id: %s", + reqURL, req, resp.Header.Get("X-Request-Id")) + + return nil +} diff --git a/bcs-services/bcs-platform-manager/pkg/component/cmdb/types.go b/bcs-services/bcs-platform-manager/pkg/component/cmdb/types.go new file mode 100644 index 0000000000..b2fd4c6c89 --- /dev/null +++ b/bcs-services/bcs-platform-manager/pkg/component/cmdb/types.go @@ -0,0 +1,204 @@ +/* + * Tencent is pleased to support the open source community by making Blueking Container Service available. + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * 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 cmdb xxx +package cmdb + +import bkcmdbkube "configcenter/src/kube/types" + +// CommonReq defines the common request structure for BCS cluster operations. +type CommonReq struct { + BKBizID int64 `json:"bk_biz_id"` + Page Page `json:"page"` + Fields []string `json:"fields"` + Filter *PropertyFilter `json:"filter"` +} + +// CommonResp defines the common response structure for BCS cluster operations. +type CommonResp struct { + Code int64 `json:"code"` + Result bool `json:"result"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} + +// Page page +type Page struct { + Start int `json:"start"` + Limit int `json:"limit"` + Sort string `json:"sort"` +} + +// PropertyFilter property filter +type PropertyFilter struct { + Condition string `json:"condition"` + Rules []Rule `json:"rules"` +} + +// Rule rule +type Rule struct { + Field string `json:"field"` + Operator string `json:"operator"` + Value interface{} `json:"value"` +} + +// GetBcsPodReq defines the structure of the request for getting BCS pods. +type GetBcsPodReq struct { + CommonReq +} + +// GetBcsPodResp defines the structure of the response for getting BCS pods. +type GetBcsPodResp struct { + CommonResp + Data *GetBcsPodRespData `json:"data"` +} + +// GetBcsPodRespData defines the structure of the response data for getting BCS pods. +type GetBcsPodRespData struct { + Count int `json:"count"` + Info *[]bkcmdbkube.Pod `json:"info"` +} + +// DeleteBcsPodReq defines the request structure for deleting a BCS pod. +type DeleteBcsPodReq struct { + Data *[]DeleteBcsPodReqData `json:"data"` +} + +// DeleteBcsPodReqData defines the data structure in the DeleteBcsPodRequest. +type DeleteBcsPodReqData struct { + BKBizID *int64 `json:"bk_biz_id"` + IDs *[]int64 `json:"ids"` +} + +// DeleteBcsPodResp defines the response structure for deleting a BCS pod. +type DeleteBcsPodResp struct { + CommonResp + Data interface{} `json:"data"` +} + +// GetBcsWorkloadReq represents a request for getting BCS workload +type GetBcsWorkloadReq struct { + CommonReq + Kind string `json:"kind"` +} + +// GetBcsWorkloadResp represents a response for getting BCS workload +type GetBcsWorkloadResp struct { + CommonResp + Data *GetBcsWorkloadRespData `json:"data"` +} + +// GetBcsWorkloadRespData represents the data structure of the response for getting BCS workload +type GetBcsWorkloadRespData struct { + Count int64 `json:"count"` + Info []interface{} `json:"info"` +} + +// DeleteBcsWorkloadReq defines the structure of the request for deleting a BCS workload. +type DeleteBcsWorkloadReq struct { + BKBizID *int64 `json:"bk_biz_id"` + Kind *string `json:"kind"` + IDs *[]int64 `json:"ids"` +} + +// DeleteBcsWorkloadResp defines the structure of the response for deleting a BCS workload. +type DeleteBcsWorkloadResp struct { + CommonResp + Data interface{} `json:"data"` +} + +// GetBcsNamespaceReq represents the request for getting a BCS namespace +type GetBcsNamespaceReq struct { + CommonReq +} + +// GetBcsNamespaceResp represents the response for getting a BCS namespace +type GetBcsNamespaceResp struct { + CommonResp + Data *GetBcsNamespaceRespData `json:"data"` +} + +// GetBcsNamespaceRespData represents the data for getting a BCS namespace +type GetBcsNamespaceRespData struct { + Count int64 `json:"count"` + Info *[]bkcmdbkube.Namespace `json:"info"` +} + +// DeleteBcsNamespaceReq represents the request for deleting a BCS namespace +type DeleteBcsNamespaceReq struct { + BKBizID *int64 `json:"bk_biz_id"` + IDs *[]int64 `json:"ids"` +} + +// DeleteBcsNamespaceResp represents the response for deleting a BCS namespace +type DeleteBcsNamespaceResp struct { + CommonResp + Data interface{} `json:"data"` +} + +// GetBcsNodeReq defines the structure of the request for getting BCS nodes. +type GetBcsNodeReq struct { + CommonReq +} + +// DeleteBcsNodeReq defines the structure of the request for deleting BCS nodes. +type DeleteBcsNodeReq struct { + BKBizID *int64 `json:"bk_biz_id"` + IDs *[]int64 `json:"ids"` +} + +// GetBcsNodeResp defines the structure of the response for getting BCS nodes. +type GetBcsNodeResp struct { + CommonResp + Data *GetBcsNodeRespData `json:"data"` +} + +// GetBcsNodeRespData defines the structure of the response data for getting BCS nodes. +type GetBcsNodeRespData struct { + Count int64 `json:"count"` + Info *[]bkcmdbkube.Node `json:"info"` +} + +// DeleteBcsNodeResponse defines the structure of the response for deleting BCS nodes. +type DeleteBcsNodeResp struct { + CommonResp + Data interface{} `json:"data"` +} + +// GetBcsClusterReq defines the request structure for getting BCS cluster information. +type GetBcsClusterReq struct { + CommonReq +} + +// DeleteBcsClusterReq represents the request for deleting a BCS cluster +type DeleteBcsClusterReq struct { + BKBizID *int64 `json:"bk_biz_id"` + IDs *[]int64 `json:"ids"` +} + +// GetBcsClusterResp defines the response structure for getting BCS cluster information. +type GetBcsClusterResp struct { + CommonResp + Data GetBcsClusterRespData `json:"data"` +} + +// GetBcsClusterRespData defines the data structure for getting BCS cluster information. +type GetBcsClusterRespData struct { + Count int64 `json:"count"` + Info []bkcmdbkube.Cluster `json:"info"` +} + +// DeleteBcsClusterResp represents the response for deleting a BCS cluster +type DeleteBcsClusterResp struct { + CommonResp + Data interface{} `json:"data"` +} diff --git a/bcs-services/bcs-platform-manager/pkg/config/bcs.go b/bcs-services/bcs-platform-manager/pkg/config/bcs.go index b600183bef..0ff1313ab0 100644 --- a/bcs-services/bcs-platform-manager/pkg/config/bcs.go +++ b/bcs-services/bcs-platform-manager/pkg/config/bcs.go @@ -32,6 +32,7 @@ const ( // BCSConf : type BCSConf struct { + Target string `yaml:"target"` Host string `yaml:"host"` Token string `yaml:"token"` Verify bool `yaml:"verify"` diff --git a/bcs-services/bcs-platform-manager/pkg/component/bcs/bcs_test.go b/bcs-services/bcs-platform-manager/pkg/config/cmdb.go similarity index 67% rename from bcs-services/bcs-platform-manager/pkg/component/bcs/bcs_test.go rename to bcs-services/bcs-platform-manager/pkg/config/cmdb.go index 05530f9f55..010acb2dcd 100644 --- a/bcs-services/bcs-platform-manager/pkg/component/bcs/bcs_test.go +++ b/bcs-services/bcs-platform-manager/pkg/config/cmdb.go @@ -10,18 +10,10 @@ * limitations under the License. */ -package bcs +package config -import ( - "testing" - - "github.com/stretchr/testify/assert" - - bcstesting "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/testing" -) - -func TestGetCluster(t *testing.T) { - cluster, err := GetCluster(bcstesting.GetTestClusterId()) - assert.NoError(t, err) - assert.Equal(t, cluster.ProjectID, bcstesting.GetTestProjectId()) +// CmdbConf cmdb config +type CmdbConf struct { + Host string `json:"host"` + Debug bool `json:"debug"` } diff --git a/bcs-services/bcs-platform-manager/pkg/config/config.go b/bcs-services/bcs-platform-manager/pkg/config/config.go index f93261a81e..12b854214b 100644 --- a/bcs-services/bcs-platform-manager/pkg/config/config.go +++ b/bcs-services/bcs-platform-manager/pkg/config/config.go @@ -41,6 +41,7 @@ type Configuration struct { Credentials map[string][]*Credential `yaml:"-"` Web *WebConf `yaml:"web"` TracingConf *TracingConf `yaml:"tracing_conf"` + Cmdb *CmdbConf `yaml:"cmdb"` } // init 初始化 @@ -183,6 +184,11 @@ func (c *Configuration) ReadFrom(content []byte) error { c.Mongo.Password = MONGO_PASSWORD } + // cmdb + if c.Cmdb.Host == "" { + c.Cmdb.Host = BK_CMDB_HOST + } + if err := c.init(); err != nil { return err } diff --git a/bcs-services/bcs-platform-manager/pkg/config/env.go b/bcs-services/bcs-platform-manager/pkg/config/env.go index 7c4bfd0ddb..ee27fda302 100644 --- a/bcs-services/bcs-platform-manager/pkg/config/env.go +++ b/bcs-services/bcs-platform-manager/pkg/config/env.go @@ -47,4 +47,6 @@ var ( BK_LOG_HOST = os.Getenv("BK_LOG_HOST") // BK_BASE_HOST ... BK_BASE_HOST = os.Getenv("BK_BASE_HOST") + // BK_CMDB_HOST ... + BK_CMDB_HOST = os.Getenv("BK_CMDB_HOST") ) diff --git a/bcs-services/bcs-platform-manager/pkg/rest/context.go b/bcs-services/bcs-platform-manager/pkg/rest/context.go index 36f19d0d25..a9e160a35e 100644 --- a/bcs-services/bcs-platform-manager/pkg/rest/context.go +++ b/bcs-services/bcs-platform-manager/pkg/rest/context.go @@ -21,8 +21,6 @@ import ( httpin_integration "github.com/ggicci/httpin/integration" "github.com/go-chi/chi/v5" "github.com/golang-jwt/jwt/v4" - - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component/bcs" ) func init() { @@ -44,8 +42,6 @@ type Context struct { BindEnv *EnvToken `json:"bind_env"` BindBCS *UserClaimsInfo `json:"bind_bcs"` BindAPIGW *APIGWToken `json:"bind_apigw"` - BindCluster *bcs.Cluster `json:"bind_cluster"` - BindProject *bcs.Project `json:"bind_project"` } // WriteAttachment 提供附件下载能力 diff --git a/bcs-services/bcs-platform-manager/pkg/rest/middleware/auth.go b/bcs-services/bcs-platform-manager/pkg/rest/middleware/auth.go index bbb81e8b75..2cfc632721 100644 --- a/bcs-services/bcs-platform-manager/pkg/rest/middleware/auth.go +++ b/bcs-services/bcs-platform-manager/pkg/rest/middleware/auth.go @@ -24,7 +24,7 @@ import ( "github.com/golang-jwt/jwt/v4" "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component/bcs" + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager" "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component/iam" "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/rest" @@ -68,7 +68,7 @@ func ProjectAuthorization(next http.Handler) http.Handler { username := restContext.Username // check cluster - cls, err := bcs.GetCluster(clusterID) + cls, err := clustermanager.GetCluster(r.Context(), clusterID) if err != nil { _ = render.Render(w, r, rest.AbortWithWithForbiddenError(restContext, err)) return @@ -113,7 +113,7 @@ func ClusterAuthorization(next http.Handler) http.Handler { username := restContext.Username // check cluster - cls, err := bcs.GetCluster(clusterID) + cls, err := clustermanager.GetCluster(r.Context(), clusterID) if err != nil { _ = render.Render(w, r, rest.AbortWithWithForbiddenError(restContext, err)) return diff --git a/bcs-services/bcs-platform-manager/pkg/rest/middleware/project.go b/bcs-services/bcs-platform-manager/pkg/rest/middleware/project.go index 77d2eac8b2..69a7b35e1c 100644 --- a/bcs-services/bcs-platform-manager/pkg/rest/middleware/project.go +++ b/bcs-services/bcs-platform-manager/pkg/rest/middleware/project.go @@ -18,8 +18,8 @@ import ( "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/go-chi/render" - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component/bcs" - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager" + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component/bcs/projectmanager" "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/rest" "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/utils" ) @@ -41,17 +41,17 @@ func ProjectParse(next http.Handler) http.Handler { ctx := utils.WithLaneIdCtx(r.Context(), r.Header) r = r.WithContext(ctx) - project, err := bcs.GetProject(ctx, config.G.BCS, projectIDOrCode) + project, err := projectmanager.GetProject(ctx, projectIDOrCode) if err != nil { blog.Errorf("get project error for project %s, error: %s", projectIDOrCode, err.Error()) _ = render.Render(w, r, rest.AbortWithBadRequestError(restContext, err)) return } - restContext.ProjectId = project.ProjectId - restContext.ProjectCode = project.Code + restContext.ProjectId = project.ProjectID + restContext.ProjectCode = project.ProjectCode // get cluster info - cls, err := bcs.GetCluster(restContext.ClusterId) + cls, err := clustermanager.GetCluster(ctx, restContext.ClusterId) if err != nil { _ = render.Render(w, r, rest.AbortWithWithForbiddenError(restContext, err)) return From 212715265d81dc6bec973028de39734ce2a07fdb Mon Sep 17 00:00:00 2001 From: dove0012 Date: Fri, 5 Sep 2025 15:44:58 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dgolangci-lint=E8=A7=84?= =?UTF-8?q?=E8=8C=83=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bcs-services/bcs-platform-manager/pkg/api/cmdb/cmdb.go | 3 ++- .../pkg/component/bcs/clustermanager/client.go | 5 +++-- .../pkg/component/bcs/projectmanager/client.go | 5 +++-- .../bcs-platform-manager/pkg/component/cmdb/cmdb.go | 9 +++++---- .../bcs-platform-manager/pkg/component/cmdb/types.go | 2 +- 5 files changed, 14 insertions(+), 10 deletions(-) diff --git a/bcs-services/bcs-platform-manager/pkg/api/cmdb/cmdb.go b/bcs-services/bcs-platform-manager/pkg/api/cmdb/cmdb.go index b6f8a2b002..b0211317e0 100644 --- a/bcs-services/bcs-platform-manager/pkg/api/cmdb/cmdb.go +++ b/bcs-services/bcs-platform-manager/pkg/api/cmdb/cmdb.go @@ -14,9 +14,10 @@ package cmdb import ( - "configcenter/src/common/blog" "context" + "configcenter/src/common/blog" + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/component/cmdb" ) diff --git a/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/client.go b/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/client.go index 423768fd02..7f42d44da3 100644 --- a/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/client.go +++ b/bcs-services/bcs-platform-manager/pkg/component/bcs/clustermanager/client.go @@ -20,11 +20,12 @@ import ( "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/clustermanager" - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" "github.com/pkg/errors" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" + + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" ) // Client xxx @@ -48,7 +49,7 @@ func New(ctx context.Context) (*Client, error) { var opts []grpc.DialOption opts = append(opts, grpc.WithDefaultCallOptions(grpc.Header(&md))) - opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{InsecureSkipVerify: true}))) + opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{InsecureSkipVerify: true}))) // nolint conn, err := grpc.NewClient(config.G.BCS.Target, opts...) if err != nil { diff --git a/bcs-services/bcs-platform-manager/pkg/component/bcs/projectmanager/client.go b/bcs-services/bcs-platform-manager/pkg/component/bcs/projectmanager/client.go index 7757325052..fa8a28d5fe 100644 --- a/bcs-services/bcs-platform-manager/pkg/component/bcs/projectmanager/client.go +++ b/bcs-services/bcs-platform-manager/pkg/component/bcs/projectmanager/client.go @@ -20,11 +20,12 @@ import ( "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/bcsproject" - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" "github.com/pkg/errors" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" + + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" ) // Client xxx @@ -48,7 +49,7 @@ func New(ctx context.Context) (*Client, error) { var opts []grpc.DialOption opts = append(opts, grpc.WithDefaultCallOptions(grpc.Header(&md))) - opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{InsecureSkipVerify: true}))) + opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{InsecureSkipVerify: true}))) // nolint conn, err := grpc.NewClient(config.G.BCS.Target, opts...) if err != nil { diff --git a/bcs-services/bcs-platform-manager/pkg/component/cmdb/cmdb.go b/bcs-services/bcs-platform-manager/pkg/component/cmdb/cmdb.go index 90359d140b..a61459215e 100644 --- a/bcs-services/bcs-platform-manager/pkg/component/cmdb/cmdb.go +++ b/bcs-services/bcs-platform-manager/pkg/component/cmdb/cmdb.go @@ -18,11 +18,11 @@ import ( "fmt" "time" - bkcmdbkube "configcenter/src/kube/types" - + bkcmdbkube "configcenter/src/kube/types" // nolint "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" "github.com/parnurzeal/gorequest" + + "github.com/Tencent/bk-bcs/bcs-services/bcs-platform-manager/pkg/config" ) var ( @@ -38,7 +38,7 @@ type Options struct { Debug bool } -// client for cc +// Client for cc type Client struct { config *Options userAuth string @@ -378,6 +378,7 @@ func (c *Client) GetBcsCluster(req *GetBcsClusterReq) (*[]bkcmdbkube.Cluster, er return &respData.Data.Info, nil } +// DeleteBcsCluster delete bcs cluster func (c *Client) DeleteBcsCluster(req *DeleteBcsClusterReq) error { // 构造请求的 URL reqURL := fmt.Sprintf("%s/api/v3/delete/kube/cluster", c.config.Server) diff --git a/bcs-services/bcs-platform-manager/pkg/component/cmdb/types.go b/bcs-services/bcs-platform-manager/pkg/component/cmdb/types.go index b2fd4c6c89..f33958aa23 100644 --- a/bcs-services/bcs-platform-manager/pkg/component/cmdb/types.go +++ b/bcs-services/bcs-platform-manager/pkg/component/cmdb/types.go @@ -168,7 +168,7 @@ type GetBcsNodeRespData struct { Info *[]bkcmdbkube.Node `json:"info"` } -// DeleteBcsNodeResponse defines the structure of the response for deleting BCS nodes. +// DeleteBcsNodeResp defines the structure of the response for deleting BCS nodes. type DeleteBcsNodeResp struct { CommonResp Data interface{} `json:"data"` From 63a2fa26866e3d19657b499074b14b074e0194df Mon Sep 17 00:00:00 2001 From: dove0012 Date: Mon, 8 Sep 2025 10:20:54 +0800 Subject: [PATCH 3/3] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dcluster-manager=E7=9A=84g?= =?UTF-8?q?olangci-lint=E8=A7=84=E8=8C=83=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/actions/nodegroup/update.go | 2 +- .../cloudprovider/qcloud/business/tke.go | 29 ++++++++++--------- .../store/nodetemplate/nodetemplate.go | 5 ++-- 3 files changed, 20 insertions(+), 16 deletions(-) diff --git a/bcs-services/bcs-cluster-manager/internal/actions/nodegroup/update.go b/bcs-services/bcs-cluster-manager/internal/actions/nodegroup/update.go index d2eef1400e..2ceb2f8aeb 100644 --- a/bcs-services/bcs-cluster-manager/internal/actions/nodegroup/update.go +++ b/bcs-services/bcs-cluster-manager/internal/actions/nodegroup/update.go @@ -237,7 +237,7 @@ func (ua *UpdateAction) modifyNodeGroupLaunchTemplate(group *cmproto.NodeGroup) } // modifyNodeGroupNodeTemplate nodeTemplate field -func (ua *UpdateAction) modifyNodeGroupNodeTemplate(group *cmproto.NodeGroup) { +func (ua *UpdateAction) modifyNodeGroupNodeTemplate(group *cmproto.NodeGroup) { // nolint if ua.req.NodeTemplate != nil { if group.NodeTemplate == nil { group.NodeTemplate = &cmproto.NodeTemplate{} diff --git a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud/business/tke.go b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud/business/tke.go index 70fa32b638..d531fa4a0e 100644 --- a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud/business/tke.go +++ b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud/business/tke.go @@ -472,8 +472,8 @@ func GetClusterExternalNodeScript(ctx context.Context, info *cloudprovider.Cloud // GenerateNTAddExistedInstanceReq 生成上架节点请求. 节点模板抽象理论上需要用户保证节点配置高度一致, 若用户配置了多盘挂载, // 则使用用户配置选项若没有配置节点模板 或者 节点模板没有配置多盘选项, 则需要自动进行多盘挂载 -func GenerateNTAddExistedInstanceReq(ctx context.Context, info *cloudprovider.CloudDependBasicInfo, nodeIDs, nodeIPs []string, - passwd, operator string, options *NodeAdvancedOptions) *api.AddExistedInstanceReq { +func GenerateNTAddExistedInstanceReq(ctx context.Context, info *cloudprovider.CloudDependBasicInfo, nodeIDs, + nodeIPs []string, passwd, operator string, options *NodeAdvancedOptions) *api.AddExistedInstanceReq { req := &api.AddExistedInstanceReq{ ClusterID: info.Cluster.SystemID, InstanceIDs: nodeIDs, @@ -530,8 +530,8 @@ func GenerateNTAddExistedInstanceReq(ctx context.Context, info *cloudprovider.Cl } // genGpuAdvSettingOverride 生成GPU节点的节点定制化高级配置 -func genGpuAdvSettingOverride(req *api.AddExistedInstanceReq, info *cloudprovider.CloudDependBasicInfo, nodeIDs, nodeIPs []string, - operator string, options *NodeAdvancedOptions, gpuNodeTemplate *proto.NodeTemplate) { +func genGpuAdvSettingOverride(req *api.AddExistedInstanceReq, info *cloudprovider.CloudDependBasicInfo, nodeIDs, + nodeIPs []string, operator string, options *NodeAdvancedOptions, gpuNodeTemplate *proto.NodeTemplate) { // 未使用节点模板 或者 节点模板未配置磁盘格式化 if info.NodeTemplate == nil || len(info.NodeTemplate.DataDisks) == 0 { // 使用默认配置, 主要解决CVM多盘挂载问题 @@ -568,7 +568,8 @@ func genGpuAdvSettingOverride(req *api.AddExistedInstanceReq, info *cloudprovide } // gpuNodeTemplatesMapByNodeIDs get gpuNodeTemplatesMap by nodeIDs, map key: nodeId, value: gpuNodeTemplate -func getGPUNodeTemplatesMapByNodeIDs(nodeIDs []string, cmOption *cloudprovider.CommonOption) (map[string]*proto.NodeTemplate, error) { +func getGPUNodeTemplatesMapByNodeIDs(nodeIDs []string, cmOption *cloudprovider.CommonOption) ( + map[string]*proto.NodeTemplate, error) { gpuNodeTemplates := make(map[string]*proto.NodeTemplate) nodes, err := TransInstanceIDsToNodes(nodeIDs, &cloudprovider.ListNodesOption{ Common: cmOption, @@ -671,8 +672,9 @@ func skipValidateOption(cls *proto.Cluster) []string { } // GenerateGPUAddExistedInstanceReqs generate gpu add existed instance request -func GenerateGPUAddExistedInstanceReqs(ctx context.Context, info *cloudprovider.CloudDependBasicInfo, nodeIDs, nodeIPs []string, - idToIP map[string]string, passwd, operator string, options *NodeAdvancedOptions) []*api.AddExistedInstanceReq { +func GenerateGPUAddExistedInstanceReqs(ctx context.Context, info *cloudprovider.CloudDependBasicInfo, + nodeIDs, nodeIPs []string, idToIP map[string]string, passwd, operator string, + options *NodeAdvancedOptions) []*api.AddExistedInstanceReq { taskID, stepName := cloudprovider.GetTaskIDAndStepNameFromContext(ctx) reqs := make([]*api.AddExistedInstanceReq, 0) @@ -728,8 +730,8 @@ func GenerateGPUAddExistedInstanceReqs(ctx context.Context, info *cloudprovider. // NodeGroup生成上架节点请求, 解决多盘问题主要取决于用户是否配置 多盘挂载, 类比于qcloud产品 // GenerateNGAddExistedInstanceReq xxx -func GenerateNGAddExistedInstanceReq(ctx context.Context, info *cloudprovider.CloudDependBasicInfo, nodeIDs, nodeIPs []string, - passwd, operator string, options *NodeAdvancedOptions) *api.AddExistedInstanceReq { +func GenerateNGAddExistedInstanceReq(ctx context.Context, info *cloudprovider.CloudDependBasicInfo, nodeIDs, + nodeIPs []string, passwd, operator string, options *NodeAdvancedOptions) *api.AddExistedInstanceReq { req := &api.AddExistedInstanceReq{ ClusterID: info.Cluster.SystemID, InstanceIDs: nodeIDs, @@ -767,7 +769,7 @@ func generateGpuInfoInNGReq(ctx context.Context, req *api.AddExistedInstanceReq, isGpuNode := true for _, node := range nodes { if !node.GetIsGpuNode() { - isGpuNode = false + isGpuNode = false // nolint return } } @@ -1063,7 +1065,7 @@ type AddExistedInstanceResult struct { } // AddNodesToCluster add nodes to cluster and return nodes result -func AddNodesToCluster(ctx context.Context, info *cloudprovider.CloudDependBasicInfo, options *NodeAdvancedOptions, +func AddNodesToCluster(ctx context.Context, info *cloudprovider.CloudDependBasicInfo, options *NodeAdvancedOptions, // nolint nodeIDs []string, passwd string, isNodeGroup bool, idToIP map[string]string, operator string) (*AddExistedInstanceResult, error) { taskID, stepName := cloudprovider.GetTaskIDAndStepNameFromContext(ctx) @@ -1100,7 +1102,7 @@ func AddNodesToCluster(ctx context.Context, info *cloudprovider.CloudDependBasic } } - if addInstanceReqs == nil || len(addInstanceReqs) == 0 { + if len(addInstanceReqs) == 0 { return nil, fmt.Errorf("AddNodesToCluster[%s] addInstanceReqs is empty", taskID) } @@ -1178,7 +1180,8 @@ type gpuNodesInfo struct { } // getImagesToGpuNodesInfoMap get gpu nodes info map -func getImagesToGpuNodesInfoMap(nodeIds []string, info *cloudprovider.CloudDependBasicInfo) (map[string]*gpuNodesInfo, error) { +func getImagesToGpuNodesInfoMap(nodeIds []string, info *cloudprovider.CloudDependBasicInfo) ( + map[string]*gpuNodesInfo, error) { imageToGpuNodesInfo := make(map[string]*gpuNodesInfo) gpuNodeTemplatesMap, err := getGPUNodeTemplatesMapByNodeIDs(nodeIds, info.CmOption) if err != nil { diff --git a/bcs-services/bcs-cluster-manager/internal/store/nodetemplate/nodetemplate.go b/bcs-services/bcs-cluster-manager/internal/store/nodetemplate/nodetemplate.go index 24fa58fea8..82e5e4c950 100644 --- a/bcs-services/bcs-cluster-manager/internal/store/nodetemplate/nodetemplate.go +++ b/bcs-services/bcs-cluster-manager/internal/store/nodetemplate/nodetemplate.go @@ -34,8 +34,9 @@ const ( tableName = "nodetemplate" // ProjectIDKey xxx - ProjectIDKey = "projectid" - templateIDKey = "nodetemplateid" + ProjectIDKey = "projectid" + templateIDKey = "nodetemplateid" + // NameKey xxx NameKey = "name" defaultCloudAccountListLength = 4000 )