From d22ae8a3b4bacf98d0f980f2dc930f74ce09abc3 Mon Sep 17 00:00:00 2001 From: LidolLxf <130628034+LidolLxf@users.noreply.github.com> Date: Thu, 1 Feb 2024 14:49:13 +0800 Subject: [PATCH] =?UTF-8?q?fix=EF=BC=9A=E4=BB=A3=E7=A0=81=E8=A7=84?= =?UTF-8?q?=E8=8C=83=E9=97=AE=E9=A2=98=E5=A4=84=E7=90=86=20(#2939)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix:代码规范问题处理 * fix:代码规范问题处理优化 --- .../pkg/ipscheduler/v3/ipscheduler.go | 11 ++ .../internal/httpsvr/handler.go | 13 ++ .../internal/cloud/gcp/sdk.go | 4 + .../internal/metrics/portpool.go | 1 + .../internal/nodecache/nodecache.go | 2 +- .../internal/webhookserver/webhookserver.go | 2 +- .../portbindingcontroller.go | 2 +- .../exporter/node_exporter.go | 3 +- .../httpsvr/httpsvr.go | 7 +- .../options/options.go | 4 + .../gitgenerator-webhook/options/options.go | 1 + .../gitgenerator-webhook/webhook/webhook.go | 3 +- .../bcs-gitops-manager/handler/cluster.go | 1 + .../bcs-gitops-manager/handler/project.go | 4 +- .../internal/component/audit.go | 1 + .../internal/dao/interface.go | 1 + .../bcs-gitops-manager/internal/dao/mysql.go | 3 +- .../pkg/analysis/analysis.go | 5 +- .../pkg/proxy/argocd/analysis.go | 1 + .../pkg/proxy/argocd/application_dryrun.go | 10 +- .../pkg/proxy/argocd/application_history.go | 2 +- .../pkg/proxy/argocd/middleware/handler.go | 35 +++-- .../proxy/argocd/middleware/handler_appset.go | 2 +- .../pkg/proxy/argocd/resources/resources.go | 1 + .../pkg/proxy/argocd/webhook.go | 2 +- .../bcs-gitops-manager/pkg/proxy/proxy.go | 1 + .../pkg/store/app_history.go | 3 +- .../bcs-gitops-manager/pkg/store/argocd.go | 1 + .../bcs-gitops-manager/pkg/utils/ctx.go | 1 + .../bcs-gitops-manager/pkg/utils/tools.go | 1 + bcs-scenarios/bcs-monitor-controller/main.go | 6 +- .../pkg/fileoperator/fileoperator.go | 2 +- .../pkg/httpsvr/httpserver.go | 11 ++ .../pkg/httpsvr/response.go | 2 +- .../pkg/option/option.go | 1 + .../controllers/terraform_controller.go | 6 +- .../bcs-terraform-controller/main.go | 4 +- .../pkg/repository/repository.go | 3 +- .../pkg/runner/server_generate_secret.go | 4 +- .../pkg/server/handler.go | 9 +- .../internal/pkg/client/cmdb/cmdb.go | 1 + .../internal/pkg/client/cmdb/cmdb_test.go | 3 +- .../internal/pkg/client/types.go | 2 +- .../internal/pkg/common/common.go | 2 +- .../internal/pkg/handler/handler.go | 123 ++++++++++------- .../internal/pkg/syncer/syncer.go | 66 +++++++-- .../internal/synchronizer/synchronizer.go | 5 +- .../bcs-bscp/cmd/api-server/service/kv.go | 6 +- .../cmd/api-server/service/released_kv.go | 2 +- .../cmd/auth-server/service/service.go | 5 +- .../bcs-bscp/cmd/config-server/service/app.go | 1 + .../service/app_template_binding.go | 7 + .../cmd/config-server/service/template.go | 11 ++ .../migrations/20231123143015_modify_app.go | 4 +- .../bcs-bscp/cmd/data-service/service/hook.go | 10 ++ .../cmd/data-service/service/hook_revision.go | 10 +- .../bcs-bscp/cmd/data-service/service/kv.go | 12 +- .../cmd/data-service/service/template.go | 6 + .../vault-plugins/service/backend.go | 1 + bcs-services/bcs-bscp/pkg/audit/audit.go | 130 ++++++++++++++++++ .../bcs-bscp/pkg/dal/dao/credential.go | 4 +- bcs-services/bcs-bscp/pkg/dal/dao/kv.go | 2 +- bcs-services/bcs-bscp/pkg/dal/dao/lock.go | 1 + .../bcs-bscp/pkg/dal/dao/released_hooks.go | 1 + .../pkg/dal/dao/template_binding_relation.go | 2 + .../bcs-bscp/pkg/dal/dao/template_revision.go | 1 + bcs-services/bcs-bscp/pkg/dal/vault/kv.go | 4 +- .../bcs-bscp/pkg/dal/vault/released_kv.go | 2 +- .../bcs-bscp/pkg/runtime/credential/scope.go | 2 +- bcs-services/bcs-bscp/pkg/types/cache.go | 4 +- .../bcs-bscp/test/mock/repo/app/config.go | 2 +- .../bcs-cli/bcs-project-manager/pkg/client.go | 2 +- .../internal/actions/cluster/list.go | 4 +- .../internal/actions/cluster/update.go | 2 +- .../internal/actions/cluster/update_module.go | 3 +- .../internal/actions/cluster/utils.go | 6 +- .../internal/actions/nodegroup/create.go | 4 +- .../internal/actions/task/skip.go | 3 +- .../internal/actions/task/utils.go | 2 +- .../internal/actions/thirdparty/cc.go | 2 +- .../internal/cloudprovider/azure/cluster.go | 1 - .../cloudprovider/blueking/cluster.go | 1 - .../internal/cloudprovider/common/agent.go | 4 +- .../qcloud-public/business/network.go | 2 +- .../qcloud-public/business/tke.go | 1 + .../qcloud-public/business/utils.go | 2 +- .../cloudprovider/qcloud-public/clustermgr.go | 13 +- .../qcloud-public/tasks/createClusterTask.go | 16 ++- .../qcloud-public/tasks/deleteClusterTask.go | 1 + .../qcloud-public/tasks/utils.go | 1 + .../cloudprovider/qcloud-public/vpcmgr.go | 4 +- .../cloudprovider/qcloud/business/tke.go | 1 - .../cloudprovider/qcloud/clustermgr.go | 2 +- .../qcloud/tasks/addNodeToCluster.go | 4 +- .../internal/daemon/cluster_helath.go | 1 + .../internal/remote/cidrtree/cidr.go | 2 + .../internal/remote/cidrtree/interface.go | 2 +- .../internal/remote/cidrtree/utils.go | 2 +- .../internal/remote/nodeman/client_test.go | 7 +- .../internal/utils/audit.go | 24 ++++ .../cmd/options/options.go | 2 +- bcs-services/bcs-cluster-reporter/cmd/root.go | 13 +- .../internal/api/bcs/cluster.go | 19 ++- .../internal/api/bcs/clustermanager.go | 2 +- .../bcs-cluster-reporter/internal/k8s/get.go | 2 +- .../bcs-cluster-reporter/internal/k8s/pod.go | 15 +- .../internal/metric_manager/metric.go | 3 +- .../internal/metric_manager/metric_test.go | 2 + .../plugin/clustercheck/clustercheck.go | 45 +++--- .../internal/plugin/dnscheck/dnscheck.go | 4 +- .../plugin/eventrecorder/eventrecorder.go | 2 +- .../plugin/logrecorder/logrecorder.go | 7 +- .../plugin/masterpodcheck/masterpodcheck.go | 30 +++- .../internal/plugin/netcheck/netcheck.go | 10 +- .../plugin/systemappcheck/systemappcheck.go | 10 +- .../internal/plugin_manager/options.go | 3 +- .../internal/plugin_manager/plugin_manager.go | 12 +- .../internal/rest/rest.go | 2 +- .../internal/util/crypt.go | 6 +- bcs-services/bcs-cluster-reporter/main.go | 14 ++ bcs-services/bcs-data-manager/cmd/server.go | 10 +- .../handler/bcs-data-manager.go | 2 + .../bcs-data-manager/pkg/datajob/workload.go | 1 + .../pkg/store/mongo/cloudnativeworkload.go | 5 +- .../bcs-data-manager/pkg/store/mongo/mongo.go | 18 +-- .../pkg/store/mongo/operationdata.go | 2 +- .../pkg/store/mongo/request.go | 1 + .../pkg/store/mongo/workload_info.go | 1 + .../pkg/store/tspider/cloudnativeworkload.go | 4 +- .../pkg/store/tspider/operationdata.go | 4 +- .../pkg/store/tspider/public.go | 4 +- .../pkg/store/tspider/tspider.go | 2 + .../internal/wrapper/audit.go | 25 ++++ .../pkg/component/bk_log/bk_log.go | 13 ++ .../bcs-ipam/resource/interface.go | 2 +- .../pkg/resourcemgr/mocks/Client.go | 2 +- .../internal/clusterconfig/clusterconfig.go | 4 +- .../actions/v1http/clusterconfig/utils.go | 6 +- .../actions/v1http/dynamicquery/filter.go | 2 +- .../actions/v1http/dynamicquery/utils.go | 6 +- .../pkg/handler/multicluster/query.go | 2 + 141 files changed, 755 insertions(+), 291 deletions(-) diff --git a/bcs-runtime/bcs-k8s/bcs-component/bcs-k8s-custom-scheduler/pkg/ipscheduler/v3/ipscheduler.go b/bcs-runtime/bcs-k8s/bcs-component/bcs-k8s-custom-scheduler/pkg/ipscheduler/v3/ipscheduler.go index ecbb69f9c5..c5d3bcf8b8 100644 --- a/bcs-runtime/bcs-k8s/bcs-component/bcs-k8s-custom-scheduler/pkg/ipscheduler/v3/ipscheduler.go +++ b/bcs-runtime/bcs-k8s/bcs-component/bcs-k8s-custom-scheduler/pkg/ipscheduler/v3/ipscheduler.go @@ -231,6 +231,7 @@ func HandleIpSchedulerPredicate(extenderArgs schedulerapi.ExtenderArgs) (*schedu return scheduleResult, nil } +// get IP Claim func getIPClaim(namespace, claimKey string) (*BCSNetIPClaim, error) { claimUnstruct, err := DefaultIpScheduler.ClaimLister.Namespace(namespace).Get(claimKey) if err != nil { @@ -246,13 +247,17 @@ func getIPClaim(namespace, claimKey string) (*BCSNetIPClaim, error) { return claim, nil } +// get IP func getIP(ipName string) (*BCSNetIP, error) { + // Get retrieves a resource from the indexer with the given name ipUnstruct, err := DefaultIpScheduler.IPLister.Get(ipName) if err != nil { blog.Warnf("get BCSNetIP %s failed, err %s", ipName, err.Error()) return nil, fmt.Errorf("get BCSNetIP %s failed, err %s", ipName, err.Error()) } ip := &BCSNetIP{} + // FromUnstructured converts an object from map[string]interface{} representation into a concrete type. + // It uses encoding/json/Unmarshaler if object implements it or reflection if not. if err := runtime.DefaultUnstructuredConverter.FromUnstructured( ipUnstruct.UnstructuredContent(), ip); err != nil { blog.Warnf("failed to convert unstructured ip %s", ipName) @@ -261,6 +266,7 @@ func getIP(ipName string) (*BCSNetIP, error) { return ip, nil } +// get Pool func getPool(poolName string) (*BCSNetPool, error) { poolUnstruct, err := DefaultIpScheduler.PoolLister.Get(poolName) if err != nil { @@ -276,6 +282,7 @@ func getPool(poolName string) (*BCSNetPool, error) { return pool, nil } +// get Pool By Hostname func getPoolByHostname(hostName string) (*BCSNetPool, error) { node, err := getNode(hostName) if err != nil { @@ -303,6 +310,7 @@ func getPoolByHostname(hostName string) (*BCSNetPool, error) { return nil, fmt.Errorf("host %s is not in any net pool", hostName) } +// get Pod func getPod(ns, name string) (*v1.Pod, error) { podUnstruct, err := DefaultIpScheduler.PodLister.Namespace(ns).Get(name) if err != nil { @@ -318,6 +326,7 @@ func getPod(ns, name string) (*v1.Pod, error) { return pod, nil } +// get Node func getNode(name string) (*v1.Node, error) { nodeUnstruct, err := DefaultIpScheduler.NodeLister.Get(name) if err != nil { @@ -388,6 +397,7 @@ func checkNodeInHosts(node v1.Node, hosts []string) error { return fmt.Errorf("no available ip") } +// sync Cached Pool By IP func syncCachedPoolByIP(ip *BCSNetIP) { poolName, ok := ip.ObjectMeta.Labels[PodLabelKeyForPool] if !ok { @@ -397,6 +407,7 @@ func syncCachedPoolByIP(ip *BCSNetIP) { syncCachedPoolIPNum(poolName) } +// sync Cached Pool IP Num func syncCachedPoolIPNum(poolName string) { if DefaultIpScheduler == nil { blog.Warnf("default scheduler is nil, wait for creation") diff --git a/bcs-runtime/bcs-k8s/bcs-component/bcs-netservice-controller/internal/httpsvr/handler.go b/bcs-runtime/bcs-k8s/bcs-component/bcs-netservice-controller/internal/httpsvr/handler.go index 61151e23dc..1c3da3a485 100644 --- a/bcs-runtime/bcs-k8s/bcs-component/bcs-netservice-controller/internal/httpsvr/handler.go +++ b/bcs-runtime/bcs-k8s/bcs-component/bcs-netservice-controller/internal/httpsvr/handler.go @@ -109,6 +109,7 @@ func InitRouters(ws *restful.WebService, httpServerClient *HttpServerClient) { func (c *HttpServerClient) AllocateIP(request *restful.Request, response *restful.Response) { requestID := request.Request.Header.Get("X-Request-Id") netIPReq := &NetIPAllocateRequest{} + // ReadEntity checks the Accept header and reads the content into the entityPointer. if err := request.ReadEntity(netIPReq); err != nil { blog.Errorf("decode json request failed, %s", err.Error()) response.WriteErrorString(http.StatusBadRequest, err.Error()) @@ -223,6 +224,7 @@ func (c *HttpServerClient) AllocateIP(request *restful.Request, response *restfu response.WriteEntity(responseData(0, message, true, requestID, data)) } +// allocateNewIPForClaim xxx func (c *HttpServerClient) allocateNewIPForClaim( netIPReq *NetIPAllocateRequest, availableIP []*v1.BCSNetIP, ipClaim *v1.BCSNetIPClaim) ( *v1.BCSNetIP, *v1.BCSNetPool, error) { @@ -256,6 +258,7 @@ func (c *HttpServerClient) allocateNewIPForClaim( return targetIP, bcspool, nil } +// allocateIPByClaim xxx func (c *HttpServerClient) allocateIPByClaim( netIPReq *NetIPAllocateRequest, ipClaim *v1.BCSNetIPClaim) (*v1.BCSNetIP, *v1.BCSNetPool, error) { ipName := ipClaim.Status.BoundedIP @@ -284,6 +287,7 @@ func (c *HttpServerClient) allocateIPByClaim( return bcsNetIP, bcsNetPool, nil } +// update IP Status func (c *HttpServerClient) updateIPStatus(ip *v1.BCSNetIP, netIPReq *NetIPAllocateRequest, claimKey, duration string, fixed bool) error { ip.Status = v1.BCSNetIPStatus{ @@ -305,6 +309,7 @@ func (c *HttpServerClient) updateIPStatus(ip *v1.BCSNetIP, netIPReq *NetIPAlloca return nil } +// get Available IPs func (c *HttpServerClient) getAvailableIPs(netPoolList *v1.BCSNetPoolList, netIPReq *NetIPAllocateRequest) ( []*v1.BCSNetIP, error) { var availableIP []*v1.BCSNetIP @@ -333,6 +338,7 @@ func (c *HttpServerClient) getAvailableIPs(netPoolList *v1.BCSNetPoolList, netIP return availableIP, nil } +// get Pool By IP func (c *HttpServerClient) getPoolByIP(bcsip *v1.BCSNetIP) (*v1.BCSNetPool, error) { if len(bcsip.GetLabels()) == 0 { return nil, fmt.Errorf("BCSNetIP %s has no labels", bcsip.GetName()) @@ -349,6 +355,7 @@ func (c *HttpServerClient) getPoolByIP(bcsip *v1.BCSNetIP) (*v1.BCSNetPool, erro return netPool, nil } +// get Claim func (c *HttpServerClient) getClaim(ns, name string) (*v1.BCSNetIPClaim, error) { retClaim := &v1.BCSNetIPClaim{} if err := c.K8SClient.Get(context.Background(), types.NamespacedName{ @@ -361,6 +368,7 @@ func (c *HttpServerClient) getClaim(ns, name string) (*v1.BCSNetIPClaim, error) return retClaim, nil } +// bound Claim IP func (c *HttpServerClient) boundClaimIP(claim *v1.BCSNetIPClaim, netIP *v1.BCSNetIP) error { claim.Status.BoundedIP = netIP.Name claim.Status.Phase = constant.BCSNetIPClaimBoundedStatus @@ -409,6 +417,7 @@ func (c *HttpServerClient) DeleteIP(request *restful.Request, response *restful. claimKey := netIP.Status.IPClaimKey if len(claimKey) != 0 { claim := &v1.BCSNetIPClaim{} + // ParseNamespacedNameKey return key by namespace and name podNamespace, podName, err := utils.ParseNamespacedNameKey(claimKey) if err != nil { message := fmt.Sprintf("invalid IPClaimKey %s of BCSNetIP %s instance", claimKey, netIP.GetName()) @@ -446,6 +455,7 @@ func (c *HttpServerClient) DeleteIP(request *restful.Request, response *restful. response.WriteEntity(responseData(0, message, true, requestID, netIPReq)) } +// get IP And Pool func (c *HttpServerClient) getIPAndPool(ip string) (*v1.BCSNetIP, *v1.BCSNetPool, error) { bcsNetIP := &v1.BCSNetIP{} if err := c.K8SClient.Get(context.Background(), types.NamespacedName{Name: ip}, bcsNetIP); err != nil { @@ -458,6 +468,7 @@ func (c *HttpServerClient) getIPAndPool(ip string) (*v1.BCSNetIP, *v1.BCSNetPool return bcsNetIP, bcsNetPool, nil } +// get IP Claim And Duration func (c *HttpServerClient) getIPClaimAndDuration(namespace, name string) (string, string, error) { pod := &coreV1.Pod{} err := c.K8SClient.Get(context.Background(), types.NamespacedName{Name: name, Namespace: namespace}, pod) @@ -477,6 +488,7 @@ func (c *HttpServerClient) getIPClaimAndDuration(namespace, name string) (string return claimValue, claim.Spec.ExpiredDuration, nil } +// validate Allocate Net IP Req func validateAllocateNetIPReq(netIPReq *NetIPAllocateRequest) error { var message string if netIPReq == nil { @@ -497,6 +509,7 @@ func validateAllocateNetIPReq(netIPReq *NetIPAllocateRequest) error { return nil } +// validate Delete Net IP Req func validateDeleteNetIPReq(netIPReq *NetIPDeleteRequest) error { var message string if netIPReq == nil { diff --git a/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/cloud/gcp/sdk.go b/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/cloud/gcp/sdk.go index 129ff88fec..2b122606fa 100644 --- a/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/cloud/gcp/sdk.go +++ b/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/cloud/gcp/sdk.go @@ -92,6 +92,7 @@ func NewSdkWrapper() (*SdkWrapper, error) { return nil, err } + // NewTokenBucket create new token bucket ratelimiter sw.throttler = throttle.NewTokenBucket(sw.ratelimitqps, sw.ratelimitbucketSize) return sw, nil } @@ -100,6 +101,7 @@ func NewSdkWrapper() (*SdkWrapper, error) { func NewSdkWrapperWithSecretIDKey(credentials []byte) (*SdkWrapper, error) { sw := &SdkWrapper{} sw.credentials = credentials + // NewSdkWrapper create a new gcp sdk wrapper return NewSdkWrapper() } @@ -211,6 +213,8 @@ func (sw *SdkWrapper) CreateNetworkEndpointGroups(project, zone, name, network, "CreateNetworkEndpointGroups", ret, startTime) } sw.tryThrottle() + // Insert: Creates a network endpoint group in the specified project + // using the parameters that are included in the request. op, err := sw.computeService.NetworkEndpointGroups.Insert(project, zone, &compute.NetworkEndpointGroup{ Name: name, NetworkEndpointType: "GCE_VM_IP_PORT", diff --git a/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/metrics/portpool.go b/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/metrics/portpool.go index ecb65a8052..55cb1d79c7 100644 --- a/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/metrics/portpool.go +++ b/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/metrics/portpool.go @@ -56,6 +56,7 @@ func ReportPortAllocate(name, namespace string, allocateSuccess bool) { } } +// CleanPortAllocateMetric clean allocate metric func CleanPortAllocateMetric(name, namespace string) { portAllocateFailedGauge.Delete(prometheus.Labels{"name": name, "namespace": namespace}) } diff --git a/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/nodecache/nodecache.go b/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/nodecache/nodecache.go index 8f118d3161..73446dfb05 100644 --- a/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/nodecache/nodecache.go +++ b/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/nodecache/nodecache.go @@ -197,7 +197,7 @@ func (n *NodeCache) loadNodeInfoFromConfigmap() { node := &corev1.Node{} if err := n.k8sClient.Get(context.Background(), k8stypes.NamespacedName{Name: nodeName}, node); err != nil { - blog.Errorf("get node '%s' failed, err: %s", err.Error()) + blog.Errorf("get node failed, err: %s", err.Error()) continue } diff --git a/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/webhookserver/webhookserver.go b/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/webhookserver/webhookserver.go index b706fb7581..09c5f6f315 100644 --- a/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/webhookserver/webhookserver.go +++ b/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/internal/webhookserver/webhookserver.go @@ -439,7 +439,7 @@ func (s *Server) mutatingNodeWebhook(ar v1.AdmissionReview) (response *v1.Admiss } node := &k8scorev1.Node{} if err := json.Unmarshal(req.Object.Raw, node); err != nil { - blog.Errorf("decode %s to node failed, err %s", string(req.Object.Raw), err.Error) + blog.Errorf("decode %s to node failed, err %s", string(req.Object.Raw), err.Error()) return &v1.AdmissionResponse{Allowed: true} } if len(node.Namespace) == 0 { diff --git a/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/portbindingcontroller/portbindingcontroller.go b/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/portbindingcontroller/portbindingcontroller.go index 946f43ac00..30a24752b6 100644 --- a/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/portbindingcontroller/portbindingcontroller.go +++ b/bcs-runtime/bcs-k8s/bcs-network/bcs-ingress-controller/portbindingcontroller/portbindingcontroller.go @@ -124,7 +124,7 @@ func (pbr *PortBindingReconciler) Reconcile(req ctrl.Request) (ctrl.Result, erro // if entity not found and portbinding found, do clean portbinding blog.V(3).Infof("clean portbinding %v", req.NamespacedName) return pbr.cleanPortBinding(portBinding) - } else { + } else { // nolint // if both entity and portbinding are not found, just return return ctrl.Result{}, nil } diff --git a/bcs-runtime/bcs-k8s/bcs-network/bcs-node-external-worker/exporter/node_exporter.go b/bcs-runtime/bcs-k8s/bcs-network/bcs-node-external-worker/exporter/node_exporter.go index 8d04b78477..a8f7c4ee8b 100644 --- a/bcs-runtime/bcs-k8s/bcs-network/bcs-node-external-worker/exporter/node_exporter.go +++ b/bcs-runtime/bcs-k8s/bcs-network/bcs-node-external-worker/exporter/node_exporter.go @@ -99,6 +99,7 @@ func (n *NodeExporter) retrieveExternalIP() (string, error) { func (n *NodeExporter) isRealExternalIP(externalIP, uuid string) bool { // do connect check addr := net.JoinHostPort(externalIP, strconv.Itoa(int(n.Opts.ListenPort))) + // nolint // todo use bk internal service resp, err := n.HttpClient.Get("http://" + addr + "/node-external-worker/api/v1/health_check") if err != nil { @@ -114,7 +115,7 @@ func (n *NodeExporter) isRealExternalIP(externalIP, uuid string) bool { respBody, err := ioutil.ReadAll(resp.Body) if err != nil { - blog.Errorf("read body failed, err: %s") + blog.Errorf("read body failed, err: %s", err) return false } blog.Infof("resp: %s, respCode: %d", string(respBody), resp.StatusCode) diff --git a/bcs-runtime/bcs-k8s/bcs-network/bcs-node-external-worker/httpsvr/httpsvr.go b/bcs-runtime/bcs-k8s/bcs-network/bcs-node-external-worker/httpsvr/httpsvr.go index 8f08009ed7..fde5fa41f0 100644 --- a/bcs-runtime/bcs-k8s/bcs-network/bcs-node-external-worker/httpsvr/httpsvr.go +++ b/bcs-runtime/bcs-k8s/bcs-network/bcs-node-external-worker/httpsvr/httpsvr.go @@ -11,6 +11,7 @@ * */ +// Package httpsvr xxx package httpsvr import ( @@ -29,6 +30,7 @@ type HttpServerClient struct { UUID string } +// Init xxx func (server *HttpServerClient) Init() error { s := httpserver.NewHttpServer(server.Ops.ListenPort, "0.0.0.0", "") @@ -55,6 +57,7 @@ func (server *HttpServerClient) healthCheck(request *restful.Request, response * _, _ = response.Write(resp) } -func (server *HttpServerClient) SetUUID(UUID string) { - server.UUID = UUID +// SetUUID set uuid +func (server *HttpServerClient) SetUUID(uUID string) { + server.UUID = uUID } diff --git a/bcs-runtime/bcs-k8s/bcs-network/bcs-node-external-worker/options/options.go b/bcs-runtime/bcs-k8s/bcs-network/bcs-node-external-worker/options/options.go index 8f75b954d2..89e4abd7ff 100644 --- a/bcs-runtime/bcs-k8s/bcs-network/bcs-node-external-worker/options/options.go +++ b/bcs-runtime/bcs-k8s/bcs-network/bcs-node-external-worker/options/options.go @@ -11,6 +11,7 @@ * */ +// Package options xxx package options import ( @@ -26,6 +27,7 @@ const ( EnvNamePodNamespace = "POD_NAMESPACE" ) +// Options xxx type Options struct { // ExternalIPWebURL URL to get external IP ExternalIPWebURL string @@ -50,6 +52,7 @@ type Options struct { conf.LogConfig } +// BindFromCommandLine xxx func (op *Options) BindFromCommandLine() { var verbosity int @@ -75,6 +78,7 @@ func (op *Options) BindFromCommandLine() { } +// SetFromEnv set form env func (op *Options) SetFromEnv() { nodeName := os.Getenv(EnvNameNodeName) if len(nodeName) == 0 { diff --git a/bcs-scenarios/bcs-gitops-manager/cmd/gitgenerator-webhook/options/options.go b/bcs-scenarios/bcs-gitops-manager/cmd/gitgenerator-webhook/options/options.go index aacf3c6621..588474922b 100644 --- a/bcs-scenarios/bcs-gitops-manager/cmd/gitgenerator-webhook/options/options.go +++ b/bcs-scenarios/bcs-gitops-manager/cmd/gitgenerator-webhook/options/options.go @@ -11,6 +11,7 @@ * */ +// Package options xxx package options import ( diff --git a/bcs-scenarios/bcs-gitops-manager/cmd/gitgenerator-webhook/webhook/webhook.go b/bcs-scenarios/bcs-gitops-manager/cmd/gitgenerator-webhook/webhook/webhook.go index 8791a5d704..946508cf9d 100644 --- a/bcs-scenarios/bcs-gitops-manager/cmd/gitgenerator-webhook/webhook/webhook.go +++ b/bcs-scenarios/bcs-gitops-manager/cmd/gitgenerator-webhook/webhook/webhook.go @@ -11,6 +11,7 @@ * */ +// Package webhook xxx package webhook import ( @@ -110,7 +111,7 @@ func (s *AdmissionWebhookServer) registerRouter() { func (s *AdmissionWebhookServer) check(ctx *gin.Context) { ar := new(v1.AdmissionReview) if err := ctx.BindJSON(ar); err != nil { - blog.Errorf("marshal request body failed, err: ", err.Error()) + blog.Errorf("marshal request body failed, err: %s", err.Error()) s.webhookAllow(ctx, true, "", "") return } diff --git a/bcs-scenarios/bcs-gitops-manager/handler/cluster.go b/bcs-scenarios/bcs-gitops-manager/handler/cluster.go index 94b060c2d1..3fb28f982c 100644 --- a/bcs-scenarios/bcs-gitops-manager/handler/cluster.go +++ b/bcs-scenarios/bcs-gitops-manager/handler/cluster.go @@ -10,6 +10,7 @@ * limitations under the License. */ +// Package handler xxx package handler import ( diff --git a/bcs-scenarios/bcs-gitops-manager/handler/project.go b/bcs-scenarios/bcs-gitops-manager/handler/project.go index 13c152ad8d..31c532b376 100644 --- a/bcs-scenarios/bcs-gitops-manager/handler/project.go +++ b/bcs-scenarios/bcs-gitops-manager/handler/project.go @@ -96,11 +96,11 @@ func (e *BcsGitopsHandler) StartupProject(ctx context.Context, req *pb.ProjectSy destPro.ObjectMeta.Annotations[common.SecretKey] = secretAnnotation } - if err := e.option.Storage.CreateProject(ctx, destPro); err != nil { + if err = e.option.Storage.CreateProject(ctx, destPro); err != nil { return e.startProjectResult(resp, failedCode, "", errors.Wrapf(err, "create project '%s' to storage failed", project.ProjectCode)) } - if err := e.option.ClusterControl.SyncProject(ctx, project.ProjectCode); err != nil { + if err = e.option.ClusterControl.SyncProject(ctx, project.ProjectCode); err != nil { return e.startProjectResult(resp, failedCode, "", errors.Wrapf(err, "sync project '%s' clusters failed", project.ProjectCode)) } diff --git a/bcs-scenarios/bcs-gitops-manager/internal/component/audit.go b/bcs-scenarios/bcs-gitops-manager/internal/component/audit.go index cde077be6c..a7b7b53d35 100644 --- a/bcs-scenarios/bcs-gitops-manager/internal/component/audit.go +++ b/bcs-scenarios/bcs-gitops-manager/internal/component/audit.go @@ -19,6 +19,7 @@ import ( var auditClient *audit.Client +// Option gateway and token type Option struct { Gateway string Token string diff --git a/bcs-scenarios/bcs-gitops-manager/internal/dao/interface.go b/bcs-scenarios/bcs-gitops-manager/internal/dao/interface.go index 50d1190ec0..651ba1ce82 100644 --- a/bcs-scenarios/bcs-gitops-manager/internal/dao/interface.go +++ b/bcs-scenarios/bcs-gitops-manager/internal/dao/interface.go @@ -75,6 +75,7 @@ const ( tableHistoryManifest = "bcs_gitops_app_history_manifest" ) +// Interface xxx interface type Interface interface { Init() error diff --git a/bcs-scenarios/bcs-gitops-manager/internal/dao/mysql.go b/bcs-scenarios/bcs-gitops-manager/internal/dao/mysql.go index 80ab1cd354..bae1d12ac7 100644 --- a/bcs-scenarios/bcs-gitops-manager/internal/dao/mysql.go +++ b/bcs-scenarios/bcs-gitops-manager/internal/dao/mysql.go @@ -17,7 +17,7 @@ import ( "fmt" "time" - _ "github.com/go-sql-driver/mysql" + _ "github.com/go-sql-driver/mysql" // nolint "github.com/pkg/errors" "gorm.io/driver/mysql" "gorm.io/gorm" @@ -36,6 +36,7 @@ var ( globalDB *driver ) +// GlobalDB global db func GlobalDB() Interface { return globalDB } diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/analysis/analysis.go b/bcs-scenarios/bcs-gitops-manager/pkg/analysis/analysis.go index f99d7070c6..b289374932 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/analysis/analysis.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/analysis/analysis.go @@ -11,6 +11,7 @@ * */ +// Package analysis xxx package analysis import ( @@ -129,7 +130,7 @@ func (c *AnalysisClient) inClusterClient() error { func (c *AnalysisClient) handleActivityUser(item *activityUserItem) { activityUser, err := c.db.GetActivityUser(item.Project, item.User) if err != nil { - blog.Errorf("[analysis] get activity user '%s/%s' failed: %s", &item.Project, item.User, err.Error()) + blog.Errorf("[analysis] get activity user '%s/%s' failed: %s", item.Project, item.User, err.Error()) return } if activityUser == nil { @@ -288,7 +289,7 @@ func (c *AnalysisClient) ApplicationCollect(project, name string) error { // ApplicationCancelCollect will cancel collect application func (c *AnalysisClient) ApplicationCancelCollect(project, name string) error { if err := c.db.DeleteResourcePreference(project, dao.PreferenceTypeApplication, name); err != nil { - return errors.Wrapf(err, "aplication cancel collect '%s/%s' failed", project, name) + return errors.Wrapf(err, "application cancel collect '%s/%s' failed", project, name) } return nil } diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/analysis.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/analysis.go index 01583a4db9..78d48157af 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/analysis.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/analysis.go @@ -11,6 +11,7 @@ * */ +// Package argocd xxx package argocd import ( diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/application_dryrun.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/application_dryrun.go index 8161afecd0..68e9944bfc 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/application_dryrun.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/application_dryrun.go @@ -154,6 +154,7 @@ func (plugin *AppPlugin) applicationDryRun(r *http.Request) (*http.Request, *mw. return r, mw.ReturnJSONResponse(resp) } +// nolint func (plugin *AppPlugin) buildApplicationByDifOrDryRunRequest(ctx context.Context, req *ApplicationDiffOrDryRunRequest) (*v1alpha1.Application, error) { application := new(v1alpha1.Application) @@ -186,12 +187,11 @@ func (plugin *AppPlugin) buildApplicationByDifOrDryRunRequest(ctx context.Contex len(application.Spec.Sources), len(req.Revisions)) } return application, nil - } else { - if application.Spec.Source == nil { - return nil, errors.Errorf("application spec.source is nil") - } - return application, nil } + if application.Spec.Source == nil { + return nil, errors.Errorf("application spec.source is nil") + } + return application, nil } func buildDiffOrDryRunRequest(r *http.Request) (*ApplicationDiffOrDryRunRequest, error) { diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/application_history.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/application_history.go index 71e7ef7808..7dc8827b8e 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/application_history.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/application_history.go @@ -78,7 +78,7 @@ func (plugin *AppPlugin) applicationHistoryState(r *http.Request) (*http.Request } hm, err := plugin.db.GetApplicationHistoryManifest(appName, applicationUID, historyID) if err != nil { - return r, mw.ReturnErrorResponse(statusCode, errors.Wrapf(err, "get application history manfiest failed")) + return r, mw.ReturnErrorResponse(statusCode, errors.Wrapf(err, "get application history manifest failed")) } if hm == nil { return r, mw.ReturnErrorResponse(http.StatusNotFound, diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/handler.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/handler.go index 0e49cfc3d4..fcc76473b3 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/handler.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/handler.go @@ -124,6 +124,8 @@ func (h *handler) Init() error { attrs := make([]attribute.KeyValue, 0) attrs = append(attrs, attribute.String("bk.data.token", h.option.TraceOption.Token)) opts = append(opts, trace.ResourceAttrs(attrs)) + // InitTracingProvider Initializes an OTLP exporter, and configures the corresponding trace and + // metric providers. tracer, err := trace.InitTracingProvider("bcs-gitops-manager", opts...) if err != nil { return errors.Wrapf(err, "init tracer failed") @@ -151,6 +153,7 @@ func (h *handler) HttpWrapper(handler HttpHandler) http.Handler { func (h *handler) CheckMultiProjectsPermission(ctx context.Context, projectIDs []string, actions []string) (map[string]map[string]bool, error) { user := ctx.Value(ctxKeyUser).(*proxy.UserInfo) + // GetMultiProjectMultiActionPerm only support same instanceSelection result, err := h.projectPermission.GetMultiProjectMultiActionPerm( user.GetUser(), projectIDs, actions) if err != nil { @@ -163,6 +166,7 @@ func (h *handler) CheckMultiProjectsPermission(ctx context.Context, projectIDs [ func (h *handler) CheckMultiClustersPermission(ctx context.Context, projectID string, clusterIDs []string, actions []string) (map[string]map[string]bool, error) { user := ctx.Value(ctxKeyUser).(*proxy.UserInfo) + // GetMultiClusterMultiActionPerm only support same instanceSelection result, err := h.clusterPermission.GetMultiClusterMultiActionPerm(user.GetUser(), projectID, clusterIDs, actions) if err != nil { @@ -185,12 +189,14 @@ func (h *handler) CheckProjectPermission(ctx context.Context, projectName string if argoProject == nil { return nil, http.StatusNotFound, errors.Errorf("project '%s' not found", projectName) } + // GetBCSProjectID get projectID from annotations projectID := common.GetBCSProjectID(argoProject.Annotations) if projectID == "" { return nil, http.StatusForbidden, errors.Errorf("project '%s' got ID failed, not under control", projectName) } var statusCode int + // CheckProjectPermissionByID 检查登录态用户对于项目的权限 statusCode, err = h.CheckProjectPermissionByID(ctx, projectName, projectID, action) return argoProject, statusCode, err } @@ -206,9 +212,11 @@ func (h *handler) CheckBusinessPermission(ctx context.Context, bizID string, act } for _, proj := range projectList.Items { + // GetBCSProjectBusinessKey return the business id of project projectBizID := common.GetBCSProjectBusinessKey(proj.Annotations) if projectBizID == bizID { - statusCode, err = h.CheckProjectPermissionByID(ctx, proj.Name, + // CheckProjectPermissionByID 检查登录态用户对于项目的权限 + statusCode, _ = h.CheckProjectPermissionByID(ctx, proj.Name, common.GetBCSProjectID(proj.Annotations), action) // 只要拥有一个project的权限,则允许操作 if statusCode == http.StatusOK { @@ -220,6 +228,7 @@ func (h *handler) CheckBusinessPermission(ctx context.Context, bizID string, act } // CheckNamespaceScopedResourcePermission 检查 NamespaceScopedResource 的权限 +// nolint func (h *handler) CheckNamespaceScopedResourcePermission(ctx context.Context, projectName, projectID, clusterID, namespace string, action iam.ActionID) (int, error) { user := ctx.Value(ctxKeyUser).(*proxy.UserInfo) @@ -368,18 +377,20 @@ func (h *handler) CheckApplicationPermission(ctx context.Context, appName string // 检查是否具备 ProjectView 权限 projectID := common.GetBCSProjectID(app.Annotations) if projectID != "" { + // CheckProjectPermissionByID 检查登录态用户对于项目的权限 statusCode, err := h.CheckProjectPermissionByID(ctx, app.Spec.Project, projectID, iam.ProjectView) if err != nil { return nil, statusCode, errors.Wrapf(err, "check project '%s' permission failed", projectID) } return app, http.StatusOK, nil - } else { - argoProject, statusCode, err := h.CheckProjectPermission(ctx, app.Spec.Project, iam.ProjectView) - if err != nil { - return nil, statusCode, errors.Wrapf(err, "check project '%s' permission failed", app.Spec.Project) - } - projectID = common.GetBCSProjectID(argoProject.Annotations) } + argoProject, statusCode, err := h.CheckProjectPermission(ctx, app.Spec.Project, iam.ProjectView) + if err != nil { + return nil, statusCode, errors.Wrapf(err, "check project '%s' permission failed", app.Spec.Project) + } + // GetBCSProjectID get projectID from annotations + projectID = common.GetBCSProjectID(argoProject.Annotations) + // 获取集群信息 argoCluster, err := h.option.Storage.GetCluster(ctx, &argocluster.ClusterQuery{ Server: app.Spec.Destination.Server, @@ -393,9 +404,9 @@ func (h *handler) CheckApplicationPermission(ctx context.Context, appName string } // 检查是否具备 NamespaceScopedResource 权限 if app.Spec.Destination.Namespace == "" { - app.Spec.Destination.Namespace = "default" + app.Spec.Destination.Namespace = "default" // nolint } - statusCode, err := h.CheckNamespaceScopedResourcePermission(ctx, app.Spec.Project, projectID, argoCluster.Name, + statusCode, err = h.CheckNamespaceScopedResourcePermission(ctx, app.Spec.Project, projectID, argoCluster.Name, app.Spec.Destination.Namespace, action) if err != nil { return nil, statusCode, @@ -407,9 +418,10 @@ func (h *handler) CheckApplicationPermission(ctx context.Context, appName string // CheckCreateApplication 检查创建某个应用是否具备权限 func (h *handler) CheckCreateApplication(ctx context.Context, app *v1alpha1.Application) (int, error) { projectName := app.Spec.Project - if projectName == "" || projectName == "default" { + if projectName == "" || projectName == "default" { // nolint return http.StatusBadRequest, errors.Errorf("project information lost") } + // CheckProjectPermission 检查登录态用户对于项目的权限 argoProject, statusCode, err := h.CheckProjectPermission(ctx, projectName, iam.ProjectView) if statusCode != http.StatusOK { return statusCode, errors.Wrapf(err, "check application '%s' permission failed", projectName) @@ -458,8 +470,9 @@ func (h *handler) CheckCreateApplication(ctx context.Context, app *v1alpha1.Appl } // 检查是否具备 NamespaceScopedResource 权限 if app.Spec.Destination.Namespace == "" { - app.Spec.Destination.Namespace = "default" + app.Spec.Destination.Namespace = "default" // nolint } + // GetBCSProjectID get projectID from annotations projectID := common.GetBCSProjectID(argoProject.Annotations) statusCode, err = h.CheckNamespaceScopedResourcePermission(ctx, app.Spec.Project, projectID, argoCluster.Name, app.Spec.Destination.Namespace, iamnamespace.NameSpaceScopedCreate) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/handler_appset.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/handler_appset.go index 07011dbb15..c57d8a0985 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/handler_appset.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/handler_appset.go @@ -66,7 +66,7 @@ func (h *handler) CheckCreateApplicationSet(ctx context.Context, DisableTLS: false, StrictValidation: false, }) - argoCDService, err := services.NewArgoCDService(h.option.Storage.GetArgoDB(), + argoCDService, _ := services.NewArgoCDService(h.option.Storage.GetArgoDB(), true, repoClientSet, false) // this will render the Applications by ApplicationSet's generators // refer to: https://github.com/argoproj/argo-cd/blob/v2.8.2/applicationset/controllers/applicationset_controller.go#L499 diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/resources/resources.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/resources/resources.go index 0f9cf9c24b..2fa19fad2f 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/resources/resources.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/resources/resources.go @@ -11,6 +11,7 @@ * */ +// Package resources xxx package resources import ( diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/webhook.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/webhook.go index 0f846a064b..1143c4c51a 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/webhook.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/webhook.go @@ -57,7 +57,7 @@ func (plugin *WebhookPlugin) forwardToApplicationSet(r *http.Request, requestID return } if resp.StatusCode != http.StatusOK { - blog.Errorf("RequestID[%s] webhook forward to appset controller resp code %d: %s", + blog.Errorf("RequestID[%s] webhook forward to appset controller resp code %d", requestID, resp.StatusCode) return } diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/proxy.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/proxy.go index de3af80935..8bcd8a292d 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/proxy.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/proxy.go @@ -10,6 +10,7 @@ * limitations under the License. */ +// Package proxy xxx package proxy import ( diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/store/app_history.go b/bcs-scenarios/bcs-gitops-manager/pkg/store/app_history.go index f09116219a..01891f35de 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/store/app_history.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/store/app_history.go @@ -11,6 +11,7 @@ * */ +// Package store xxx package store import ( @@ -62,7 +63,7 @@ func (s *appHistoryStore) handleApplication(item *v1alpha1.Application) error { history := item.Status.History.LastRevisionHistory() hm, err := s.db.GetApplicationHistoryManifest(item.Name, string(item.UID), history.ID) if err != nil { - return errors.Wrapf(err, "get application history '%s/%s/%d' manfiest failed", + return errors.Wrapf(err, "get application history '%s/%s/%d' manifest failed", item.Name, item.UID, history.ID) } if hm != nil { diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/store/argocd.go b/bcs-scenarios/bcs-gitops-manager/pkg/store/argocd.go index efc9fc80f9..d8cbfc542d 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/store/argocd.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/store/argocd.go @@ -503,6 +503,7 @@ func (cd *argo) GetApplicationManifests(ctx context.Context, name, revision stri // GetApplicationManifestsFromRepoServerWithMultiSources returns the manifests result of application which not // created. This function will direct call reposerver of argocd +// nolint func (cd *argo) GetApplicationManifestsFromRepoServerWithMultiSources(ctx context.Context, application *v1alpha1.Application) ([]*apiclient.ManifestResponse, error) { repoUrl := application.Spec.Source.RepoURL diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/utils/ctx.go b/bcs-scenarios/bcs-gitops-manager/pkg/utils/ctx.go index 3bdf6865f4..86994f6dda 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/utils/ctx.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/utils/ctx.go @@ -17,6 +17,7 @@ import ( "strings" ) +// IsPermissionDenied permission func IsPermissionDenied(err error) bool { if err == nil { return false diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/utils/tools.go b/bcs-scenarios/bcs-gitops-manager/pkg/utils/tools.go index 677077684c..d3cb3d9e21 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/utils/tools.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/utils/tools.go @@ -61,6 +61,7 @@ func DeepCopyMap(m map[string]string) map[string]string { return r } +// DeepCopyHttpRequest Deep Copy Http Request func DeepCopyHttpRequest(r *http.Request, newUrl string) (*http.Request, error) { body, err := io.ReadAll(r.Body) if err != nil { diff --git a/bcs-scenarios/bcs-monitor-controller/main.go b/bcs-scenarios/bcs-monitor-controller/main.go index d205233b01..d96ecd0775 100644 --- a/bcs-scenarios/bcs-monitor-controller/main.go +++ b/bcs-scenarios/bcs-monitor-controller/main.go @@ -151,11 +151,11 @@ func main() { } // +kubebuilder:scaffold:builder - if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { + if err = mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { setupLog.Error(err, "unable to set up health check") os.Exit(1) } - if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil { + if err = mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil { setupLog.Error(err, "unable to set up ready check") os.Exit(1) } @@ -166,7 +166,7 @@ func main() { os.Exit(1) } setupLog.Info("starting manager") - if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { + if err = mgr.Start(ctrl.SetupSignalHandler()); err != nil { setupLog.Error(err, "problem running manager") os.Exit(1) } diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/fileoperator.go b/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/fileoperator.go index ef529ea314..b58a881576 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/fileoperator.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/fileoperator.go @@ -11,6 +11,7 @@ * */ +// Package fileoperator xxx package fileoperator import ( @@ -19,7 +20,6 @@ import ( "os" "path/filepath" - "github.com/mholt/archiver/v3" "gopkg.in/yaml.v3" "sigs.k8s.io/controller-runtime/pkg/client" diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/httpserver.go b/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/httpserver.go index 1a35d0e69a..806199ee71 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/httpserver.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/httpserver.go @@ -61,7 +61,9 @@ func InitRouters(ws *restful.WebService, httpServerClient *HttpServerClient) { // return // } +// ListAppMonitors list app monitor func (h *HttpServerClient) ListAppMonitors(request *restful.Request, response *restful.Response) { + // InstalledScenarioInfo install type InstalledScenarioInfo struct { Name string `json:"name"` Status string `json:"status"` @@ -72,6 +74,9 @@ func (h *HttpServerClient) ListAppMonitors(request *restful.Request, response *r } bizID := request.PathParameter("biz_id") appMonitorList := &monitorextensionv1.AppMonitorList{} + // LabelSelectorAsSelector converts the LabelSelector api type into a struct that implements + // labels.Selector + // Note: This function should be kept in sync with the selector methods in pkg/labels/selector.go selector, err := k8smetav1.LabelSelectorAsSelector(k8smetav1.SetAsLabelSelector(map[string]string{ monitorextensionv1.LabelKeyForBizID: bizID, })) @@ -97,7 +102,9 @@ func (h *HttpServerClient) ListAppMonitors(request *restful.Request, response *r _, _ = response.Write(CreateResponseData(nil, "", Resp{InstallScenario: infoList})) } +// CreateOrUpdateAppMonitor create or update app monitor func (h *HttpServerClient) CreateOrUpdateAppMonitor(request *restful.Request, response *restful.Response) { + // Req entityPointer req type Req struct { BizID string `json:"biz_id"` Scenario string `json:"scenario"` @@ -151,7 +158,9 @@ func (h *HttpServerClient) CreateOrUpdateAppMonitor(request *restful.Request, re } } +// DeleteAppMonitor delete app monitor func (h *HttpServerClient) DeleteAppMonitor(request *restful.Request, response *restful.Response) { + // Req request type Req struct { BizID string `json:"biz_id"` Scenario string `json:"scenario"` @@ -175,6 +184,7 @@ func (h *HttpServerClient) DeleteAppMonitor(request *restful.Request, response * return } +// do Create Or Update App Monitor func (h *HttpServerClient) doCreateOrUpdateAppMonitor(bizID, scenario, values string) (*k8stypes.NamespacedName, error) { var ( appMonitor *monitorextensionv1.AppMonitor @@ -237,6 +247,7 @@ func (h *HttpServerClient) doCreateOrUpdateAppMonitor(bizID, scenario, values st }, nil } +// do Delete App Monitor func (h *HttpServerClient) doDeleteAppMonitor(bizID, scenario string) error { appMonitorList := &monitorextensionv1.AppMonitorList{} selector, err := k8smetav1.LabelSelectorAsSelector(k8smetav1.SetAsLabelSelector(map[string]string{ diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/response.go b/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/response.go index 04f0e8f008..4cedc3b5a1 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/response.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/response.go @@ -31,7 +31,7 @@ type APIRespone struct { // CreateResponseData common response func CreateResponseData(err error, msg string, data interface{}) []byte { - resp := &APIRespone{} + var resp *APIRespone if err != nil { resp = errResponseDefault(err) diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/option/option.go b/bcs-scenarios/bcs-monitor-controller/pkg/option/option.go index 7ca1b20f2d..e6a61fb597 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/option/option.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/option/option.go @@ -11,6 +11,7 @@ * */ +// Package option xxx package option import ( diff --git a/bcs-scenarios/bcs-terraform-controller/controllers/terraform_controller.go b/bcs-scenarios/bcs-terraform-controller/controllers/terraform_controller.go index 7dd6223d0b..634f784452 100644 --- a/bcs-scenarios/bcs-terraform-controller/controllers/terraform_controller.go +++ b/bcs-scenarios/bcs-terraform-controller/controllers/terraform_controller.go @@ -148,6 +148,7 @@ func (r *TerraformReconciler) handler(ctx context.Context, traceId string, tf *t getTfPlanFlag = true // 假定执行apply失败, 需要进行apply重试, 获取tfplan, 再去执行apply if currentCommitId == "refresh" { + // nolint // todo: 手动刷新 or 强制刷新? // getTfPlanFlag = true } else if len(tf.Status.LastApplyError) == 0 { @@ -217,16 +218,15 @@ func (r *TerraformReconciler) handler(ctx context.Context, traceId string, tf *t // finish 更新tf status至api server func (r *TerraformReconciler) finish(ctx context.Context, traceId string, tf *tfv1.Terraform) { - tf.Status.ObservedGeneration += 1 + tf.Status.ObservedGeneration++ nn := apitypes.NamespacedName{Namespace: tf.Namespace, Name: tf.Name} //blog.Infof("update tf status before, trace-id: %s, tf-json: %s,", traceId, utils.ToJsonString(tf)) if err := r.Client.Status().Update(ctx, tf, &client.UpdateOptions{}); err != nil { blog.Errorf("update tf status failed(finish), tf: %s, trace-id: %s, err: %s", nn, traceId, err) return - } else { - blog.Infof("update tf status success, tf: %s, trace-id: %s", nn, traceId) } + blog.Infof("update tf status success, tf: %s, trace-id: %s", nn, traceId) } // updateAnnotations 更新注解 diff --git a/bcs-scenarios/bcs-terraform-controller/main.go b/bcs-scenarios/bcs-terraform-controller/main.go index 469718fade..6a78281d90 100644 --- a/bcs-scenarios/bcs-terraform-controller/main.go +++ b/bcs-scenarios/bcs-terraform-controller/main.go @@ -126,11 +126,11 @@ func main() { svr := server.NewHandler("0.0.0.0", "8080", mgr.GetClient()) go func() { - if err := svr.Init(); err != nil { + if err = svr.Init(); err != nil { blog.Fatalf("http server init failed, err: %s", err) return } - if err := svr.Run(); err != nil { + if err = svr.Run(); err != nil { blog.Fatalf("http server run terminated, err: %s", err) return } diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/repository/repository.go b/bcs-scenarios/bcs-terraform-controller/pkg/repository/repository.go index 870214c440..db9af05cbc 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/repository/repository.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/repository/repository.go @@ -11,6 +11,7 @@ * */ +// Package repository xxx package repository import ( @@ -20,7 +21,6 @@ import ( "time" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/config" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/transport/http" @@ -35,6 +35,7 @@ import ( "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/pkg/utils" ) +// Handler handle type Handler interface { // Init 初始化 Init() error diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/runner/server_generate_secret.go b/bcs-scenarios/bcs-terraform-controller/pkg/runner/server_generate_secret.go index ea7df87cc6..cad5f3a877 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/runner/server_generate_secret.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/runner/server_generate_secret.go @@ -67,10 +67,8 @@ func (t *terraformLocalRunner) GenerateSecretForTF(ctx context.Context, workdir } blog.Info("found placeholder `%s` and replace to `%s` \n", placeholder, string(secretVal)) return secretVal - } else { - blog.Errorf("not match placeholder: `%s` \n", placeholder) } - + blog.Errorf("not match placeholder: `%s` \n", placeholder) return match }) diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/server/handler.go b/bcs-scenarios/bcs-terraform-controller/pkg/server/handler.go index 9286837410..21ebe4e953 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/server/handler.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/server/handler.go @@ -11,6 +11,7 @@ * */ +// Package server xxx package server import ( @@ -32,7 +33,7 @@ import ( func (h *handler) Apply(ctx *gin.Context) { req := new(ApplyRequest) if err := ctx.BindJSON(req); err != nil { - blog.Errorf("marshal request body failed(ApplyRequest), err: ", err.Error()) + blog.Errorf("marshal request body failed(ApplyRequest), err: %s", err.Error()) errReply(ctx, "marshal request body failed(ApplyRequest)") return } @@ -100,7 +101,7 @@ func (h *handler) Apply(ctx *gin.Context) { func (h *handler) CreatePlan(ctx *gin.Context) { req := new(CreatePlanRequest) if err := ctx.BindJSON(req); err != nil { - blog.Errorf("marshal request body failed(CreatePlanRequest), err: ", err.Error()) + blog.Errorf("marshal request body failed(CreatePlanRequest), err: %s", err.Error()) errReply(ctx, "marshal request body failed(CreatePlanRequest)") return } @@ -117,7 +118,7 @@ func (h *handler) CreatePlan(ctx *gin.Context) { } tf := new(tfv1.Terraform) if err := h.client.Get(cc, key, tf); err != nil { - text := fmt.Sprintf("get tf resource failed, req: %s, err: %s", req, err.Error()) + text := fmt.Sprintf("get tf resource failed, req: %v, err: %s", req, err.Error()) blog.Error(text) errReply(ctx, text) return @@ -150,7 +151,7 @@ func (h *handler) ListTerraform(ctx *gin.Context) { func (h *handler) GetTerraform(ctx *gin.Context) { req := new(GetTerraformRequest) if err := ctx.BindJSON(req); err != nil { - blog.Errorf("marshal request body failed(GetTerraformRequest), err: ", err.Error()) + blog.Errorf("marshal request body failed(GetTerraformRequest), err: %s", err.Error()) errReply(ctx, "marshal request body failed(GetTerraformRequest)") return } diff --git a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/cmdb/cmdb.go b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/cmdb/cmdb.go index 5b613388c9..e302a7143b 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/cmdb/cmdb.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/cmdb/cmdb.go @@ -32,6 +32,7 @@ import ( ) // NewCmdbClient create cmdb client +// nolint func NewCmdbClient(options *Options) *cmdbClient { c := &cmdbClient{ config: &Options{ diff --git a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/cmdb/cmdb_test.go b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/cmdb/cmdb_test.go index c273645eb3..a0a2169dd5 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/cmdb/cmdb_test.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/cmdb/cmdb_test.go @@ -768,7 +768,7 @@ func Test_cmdbClient_CreateBcsWorkload(t *testing.T) { } rudMap := make(map[string]interface{}) - err = json.Unmarshal(jsonBytes, &rudMap) + _ = json.Unmarshal(jsonBytes, &rudMap) type fields struct { config *Options @@ -1808,6 +1808,7 @@ func Test_getAllByBkBizID(t *testing.T) { } // Test_cmdbClient_UpdateBcsClusterType tests the UpdateBcsClusterType method of the cmdbClient. +// nolint func Test_cmdbClient_UpdateBcsClusterType(t *testing.T) { id := int64(4583) clusterType := "SHARE_CLUSTER" diff --git a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/types.go b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/types.go index c901b025f7..56cfe5aa3a 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/types.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/types.go @@ -48,7 +48,7 @@ type SearchBusinessRequest struct { Operator string `json:"operator"` } -// SearchBusinessResponse search bussiness resp +// SearchBusinessResponse search business resp type SearchBusinessResponse struct { Code int `json:"code"` Result bool `json:"result"` diff --git a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/common/common.go b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/common/common.go index 8f797e7e61..ed469e55eb 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/common/common.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/common/common.go @@ -44,7 +44,7 @@ func InArray(val interface{}, array interface{}) (exists bool, index int) { } } - return + return exists, index } // DecryptCMOption decrypts the CostManagerOption diff --git a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/handler/handler.go b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/handler/handler.go index ad47f26477..2c630333ec 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/handler/handler.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/handler/handler.go @@ -119,6 +119,7 @@ func (b *BcsBkcmdbSynchronizerHandler) HandleMsg(chn *amqp.Channel, messages <-c } } +// handle cluster func (b *BcsBkcmdbSynchronizerHandler) handleCluster(msg amqp.Delivery) error { if b.BkCluster != nil { return nil @@ -226,12 +227,12 @@ func (b *BcsBkcmdbSynchronizerHandler) handlePod(msg amqp.Delivery) { } switch msgHeader.Event { - case "update": + case "update": // nolint err = b.handlePodUpdate(pod) if err != nil { blog.Errorf("handlePodUpdate err: %s", err.Error()) } - case "delete": + case "delete": // nolint err = b.handlePodDelete(pod) if err != nil { blog.Errorf("handlePodDelete err: %s", err.Error()) @@ -267,7 +268,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handlePodUpdate(pod *corev1.Pod) error { } if len(*bkPods) > 1 { - return errors.New(fmt.Sprintf("len(bkPods) = %d", len(*bkPods))) + return fmt.Errorf("len(bkPods) = %d", len(*bkPods)) } if len(*bkPods) == 0 { @@ -307,11 +308,11 @@ func (b *BcsBkcmdbSynchronizerHandler) handlePodDelete(pod *corev1.Pod) error { } if len(*bkPods) > 1 { - return errors.New(fmt.Sprintf("len(bkPods) = %d", len(*bkPods))) + return fmt.Errorf("len(bkPods) = %d", len(*bkPods)) } if len(*bkPods) == 0 { - return errors.New(fmt.Sprintf("pod %s not found", pod.Name)) + return fmt.Errorf("pod %s not found", pod.Name) } bkPod := (*bkPods)[0] @@ -369,7 +370,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handlePodCreate(pod *corev1.Pod) error { } if len(*bkNamespaces) != 1 { - return errors.New(fmt.Sprintf("len(bkNamespaces) = %d", len(*bkNamespaces))) + return fmt.Errorf("len(bkNamespaces) = %d", len(*bkNamespaces)) } bkNamespace := (*bkNamespaces)[0] @@ -396,7 +397,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handlePodCreate(pod *corev1.Pod) error { if len(*bkWorkloadPods) != 1 { blog.Errorf("get bk workload pods len is %d", len(*bkWorkloadPods)) - return errors.New(fmt.Sprintf("len(*bkWorkloadPods) = %d", len(*bkWorkloadPods))) + return fmt.Errorf("len(*bkWorkloadPods) = %d", len(*bkWorkloadPods)) } p := bkcmdbkube.PodsWorkload{} @@ -419,10 +420,10 @@ func (b *BcsBkcmdbSynchronizerHandler) handlePodCreate(pod *corev1.Pod) error { } rsList, err := storageCli.QueryK8sReplicaSet(b.BkCluster.Uid, pod.Namespace, ownerRef.Name) if err != nil { - return errors.New(fmt.Sprintf("query replicaSet %s failed, err: %s", ownerRef.Name, err.Error())) + return fmt.Errorf("query replicaSet %s failed, err: %s", ownerRef.Name, err.Error()) } if len(rsList) != 1 { - return errors.New(fmt.Sprintf("replicaSet %s not found", ownerRef.Name)) + return fmt.Errorf("replicaSet %s not found", ownerRef.Name) } rs := rsList[0] @@ -460,11 +461,11 @@ func (b *BcsBkcmdbSynchronizerHandler) handlePodCreate(pod *corev1.Pod) error { } if len(*bkWorkloads) == 0 { - return errors.New(fmt.Sprintf("no workload %s in %s", workloadName, bkNamespace.Name)) + return fmt.Errorf("no workload %s in %s", workloadName, bkNamespace.Name) } if len(*bkWorkloads) > 1 { - return errors.New(fmt.Sprintf("len(bkWorkloads) = %d", len(*bkWorkloads))) + return fmt.Errorf("len(bkWorkloads) = %d", len(*bkWorkloads)) } workloadID = (int64)((*bkWorkloads)[0].(map[string]interface{})["id"].(float64)) @@ -480,7 +481,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handlePodCreate(pod *corev1.Pod) error { } } default: - return errors.New(fmt.Sprintf("kind %s is not supported", rsOwnerRef.Kind)) + return fmt.Errorf("kind %s is not supported", rsOwnerRef.Kind) } } else if exist, _ := common.InArray(ownerRef.Kind, workloadKindList); exist { @@ -512,11 +513,11 @@ func (b *BcsBkcmdbSynchronizerHandler) handlePodCreate(pod *corev1.Pod) error { } if len(*bkWorkloads) == 0 { - return errors.New(fmt.Sprintf("no workload %s in %s", workloadName, bkNamespace.Name)) + return fmt.Errorf("no workload %s in %s", workloadName, bkNamespace.Name) } if len(*bkWorkloads) > 1 { - return errors.New(fmt.Sprintf("len(bkWorkloads) = %d", len(*bkWorkloads))) + return fmt.Errorf("len(bkWorkloads) = %d", len(*bkWorkloads)) } workloadID = (int64)((*bkWorkloads)[0].(map[string]interface{})["id"].(float64)) @@ -532,7 +533,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handlePodCreate(pod *corev1.Pod) error { } } } else { - return errors.New(fmt.Sprintf("kind %s is not supported", ownerRef.Kind)) + return fmt.Errorf("kind %s is not supported", ownerRef.Kind) } } @@ -560,7 +561,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handlePodCreate(pod *corev1.Pod) error { } if len(*bkNodes) != 1 { - return errors.New(fmt.Sprintf("len(bkNodes) = %d", len(*bkNodes))) + return fmt.Errorf("len(bkNodes) = %d", len(*bkNodes)) } bkNode := (*bkNodes)[0] @@ -706,12 +707,12 @@ func (b *BcsBkcmdbSynchronizerHandler) handleDeployment(msg amqp.Delivery) { } switch msgHeader.Event { - case "update": + case "update": // nolint err = b.handleDeploymentUpdate(deployment) if err != nil { blog.Errorf("handleDeploymentUpdate err: %s", err.Error()) } - case "delete": + case "delete": // nolint err = b.handleDeploymentDelete(deployment) if err != nil { blog.Errorf("handleDeploymentDelete err: %s", err.Error()) @@ -801,11 +802,11 @@ func (b *BcsBkcmdbSynchronizerHandler) handleDeploymentDelete(deployment *appv1. } if len(*bkDeployments) > 1 { - return errors.New(fmt.Sprintf("len(bkDeployments) = %d", len(*bkDeployments))) + return fmt.Errorf("len(bkDeployments) = %d", len(*bkDeployments)) } if len(*bkDeployments) == 0 { - return errors.New(fmt.Sprintf("deployment %s not found", deployment.Name)) + return fmt.Errorf("deployment %s not found", deployment.Name) } bd := (*bkDeployments)[0] @@ -850,7 +851,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleDeploymentCreate(deployment *appv1. } if len(*bkNamespaces) != 1 { - return errors.New(fmt.Sprintf("len(bkNamespaces) = %d", len(*bkNamespaces))) + return fmt.Errorf("len(bkNamespaces) = %d", len(*bkNamespaces)) } bkNamespace := (*bkNamespaces)[0] @@ -880,12 +881,12 @@ func (b *BcsBkcmdbSynchronizerHandler) handleStatefulSet(msg amqp.Delivery) { } switch msgHeader.Event { - case "update": + case "update": // nolint err = b.handleStatefulSetUpdate(statefulSet) if err != nil { blog.Errorf("handleStatefulSetUpdate err: %s", err.Error()) } - case "delete": + case "delete": // nolint err = b.handleStatefulSetDelete(statefulSet) if err != nil { blog.Errorf("handleStatefulSetDelete err: %s", err.Error()) @@ -975,11 +976,11 @@ func (b *BcsBkcmdbSynchronizerHandler) handleStatefulSetDelete(statefulSet *appv } if len(*bkStatefulSets) > 1 { - return errors.New(fmt.Sprintf("len(bkStatefulSets) = %d", len(*bkStatefulSets))) + return fmt.Errorf("len(bkStatefulSets) = %d", len(*bkStatefulSets)) } if len(*bkStatefulSets) == 0 { - return errors.New(fmt.Sprintf("statefulSet %s not found", statefulSet.Name)) + return fmt.Errorf("statefulSet %s not found", statefulSet.Name) } bs := (*bkStatefulSets)[0] @@ -1024,7 +1025,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleStatefulSetCreate(statefulSet *appv } if len(*bkNamespaces) != 1 { - return errors.New(fmt.Sprintf("len(bkNamespaces) = %d", len(*bkNamespaces))) + return fmt.Errorf("len(bkNamespaces) = %d", len(*bkNamespaces)) } bkNamespace := (*bkNamespaces)[0] @@ -1054,12 +1055,12 @@ func (b *BcsBkcmdbSynchronizerHandler) handleDaemonSet(msg amqp.Delivery) { } switch msgHeader.Event { - case "update": + case "update": // nolint err = b.handleDaemonSetUpdate(daemonSet) if err != nil { blog.Errorf("handleDaemonSetUpdate err: %s", err.Error()) } - case "delete": + case "delete": // nolint err = b.handleDaemonSetDelete(daemonSet) if err != nil { blog.Errorf("handleDaemonSetDelete err: %s", err.Error()) @@ -1149,11 +1150,11 @@ func (b *BcsBkcmdbSynchronizerHandler) handleDaemonSetDelete(daemonSet *appv1.Da } if len(*bkDaemonSets) > 1 { - return errors.New(fmt.Sprintf("len(bkDaemonSets) = %d", len(*bkDaemonSets))) + return fmt.Errorf("len(bkDaemonSets) = %d", len(*bkDaemonSets)) } if len(*bkDaemonSets) == 0 { - return errors.New(fmt.Sprintf("daemonSet %s not found", daemonSet.Name)) + return fmt.Errorf("daemonSet %s not found", daemonSet.Name) } bd := (*bkDaemonSets)[0] @@ -1198,7 +1199,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleDaemonSetCreate(daemonSet *appv1.Da } if len(*bkNamespaces) != 1 { - return errors.New(fmt.Sprintf("len(bkNamespaces) = %d", len(*bkNamespaces))) + return fmt.Errorf("len(bkNamespaces) = %d", len(*bkNamespaces)) } bkNamespace := (*bkNamespaces)[0] @@ -1228,12 +1229,12 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameDeployment(msg amqp.Delivery) { } switch msgHeader.Event { - case "update": + case "update": // nolint err = b.handleGameDeploymentUpdate(gameDeployment) if err != nil { blog.Errorf("handleGameDeploymentUpdate err: %s", err.Error()) } - case "delete": + case "delete": // nolint err = b.handleGameDeploymentDelete(gameDeployment) if err != nil { blog.Errorf("handleGameDeploymentDelete err: %s", err.Error()) @@ -1247,6 +1248,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameDeployment(msg amqp.Delivery) { } } +// handle GameDeployment Update func (b *BcsBkcmdbSynchronizerHandler) handleGameDeploymentUpdate(gameDeployment *gdv1alpha1.GameDeployment) error { bkGameDeployments, err := b.Syncer.GetBkWorkloads(b.BkCluster.BizID, "gameDeployment", &client.PropertyFilter{ Condition: "AND", @@ -1301,6 +1303,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameDeploymentUpdate(gameDeployment return nil } +// handle GameDeployment Delete func (b *BcsBkcmdbSynchronizerHandler) handleGameDeploymentDelete(gameDeployment *gdv1alpha1.GameDeployment) error { bkGameDeployments, err := b.Syncer.GetBkWorkloads(b.BkCluster.BizID, "gameDeployment", &client.PropertyFilter{ Condition: "AND", @@ -1323,11 +1326,11 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameDeploymentDelete(gameDeployment } if len(*bkGameDeployments) > 1 { - return errors.New(fmt.Sprintf("len(bkGameDeployments) = %d", len(*bkGameDeployments))) + return fmt.Errorf("len(bkGameDeployments) = %d", len(*bkGameDeployments)) } if len(*bkGameDeployments) == 0 { - return errors.New(fmt.Sprintf("gameDeployment %s not found", gameDeployment.Name)) + return fmt.Errorf("gameDeployment %s not found", gameDeployment.Name) } bgd := (*bkGameDeployments)[0] @@ -1351,6 +1354,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameDeploymentDelete(gameDeployment return err } +// handle GameDeployment Create func (b *BcsBkcmdbSynchronizerHandler) handleGameDeploymentCreate(gameDeployment *gdv1alpha1.GameDeployment) error { bkNamespaces, err := b.Syncer.GetBkNamespaces(b.BkCluster.BizID, &client.PropertyFilter{ Condition: "AND", @@ -1372,7 +1376,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameDeploymentCreate(gameDeployment } if len(*bkNamespaces) != 1 { - return errors.New(fmt.Sprintf("len(bkNamespaces) = %d", len(*bkNamespaces))) + return fmt.Errorf("len(bkNamespaces) = %d", len(*bkNamespaces)) } bkNamespace := (*bkNamespaces)[0] @@ -1385,6 +1389,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameDeploymentCreate(gameDeployment return nil } +// handle GameStateful Set func (b *BcsBkcmdbSynchronizerHandler) handleGameStatefulSet(msg amqp.Delivery) { blog.Infof("handleGameStatefulSet Message: %v", msg.Headers) msgHeader, err := getMsgHeader(&msg.Headers) @@ -1402,12 +1407,12 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameStatefulSet(msg amqp.Delivery) } switch msgHeader.Event { - case "update": + case "update": // nolint err = b.handleGameStatefulSetUpdate(gameStatefulSet) if err != nil { blog.Errorf("handleGameStatefulSetUpdate err: %s", err.Error()) } - case "delete": + case "delete": // nolint err = b.handleGameStatefulSetDelete(gameStatefulSet) if err != nil { blog.Errorf("handleGameStatefulSetDelete err: %s", err.Error()) @@ -1421,7 +1426,9 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameStatefulSet(msg amqp.Delivery) } } +// handle GameStateful Set Update func (b *BcsBkcmdbSynchronizerHandler) handleGameStatefulSetUpdate(gameStatefulSet *gsv1alpha1.GameStatefulSet) error { + // GetBkWorkloads get bkworkloads bkGameStatefulSets, err := b.Syncer.GetBkWorkloads(b.BkCluster.BizID, "gameStatefulSet", &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -1475,6 +1482,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameStatefulSetUpdate(gameStatefulS return nil } +// handle GameStateful Set Delete func (b *BcsBkcmdbSynchronizerHandler) handleGameStatefulSetDelete(gameStatefulSet *gsv1alpha1.GameStatefulSet) error { bkGameStatefulSets, err := b.Syncer.GetBkWorkloads(b.BkCluster.BizID, "gameStatefulSet", &client.PropertyFilter{ Condition: "AND", @@ -1497,11 +1505,11 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameStatefulSetDelete(gameStatefulS } if len(*bkGameStatefulSets) > 1 { - return errors.New(fmt.Sprintf("len(bkGameStatefulSets) = %d", len(*bkGameStatefulSets))) + return fmt.Errorf("len(bkGameStatefulSets) = %d", len(*bkGameStatefulSets)) } if len(*bkGameStatefulSets) == 0 { - return errors.New(fmt.Sprintf("gameStatefulSet %s not found", gameStatefulSet.Name)) + return fmt.Errorf("gameStatefulSet %s not found", gameStatefulSet.Name) } bgs := (*bkGameStatefulSets)[0] @@ -1525,7 +1533,9 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameStatefulSetDelete(gameStatefulS return err } +// handle GameStateful Set Create func (b *BcsBkcmdbSynchronizerHandler) handleGameStatefulSetCreate(gameStatefulSet *gsv1alpha1.GameStatefulSet) error { + // GetBkNamespaces get bknamespaces bkNamespaces, err := b.Syncer.GetBkNamespaces(b.BkCluster.BizID, &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -1546,15 +1556,17 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameStatefulSetCreate(gameStatefulS } if len(*bkNamespaces) != 1 { - return errors.New(fmt.Sprintf("len(bkNamespaces) = %d", len(*bkNamespaces))) + return fmt.Errorf("len(bkNamespaces) = %d", len(*bkNamespaces)) } bkNamespace := (*bkNamespaces)[0] gameStatefulSetToAdd := make(map[int64][]client.CreateBcsWorkloadRequestData, 0) + // GenerateBkGameStatefulSet generate bkgamestatefulset from k8sgamestatefulset toAddData := b.Syncer.GenerateBkGameStatefulSet(&bkNamespace, &storage.GameStatefulSet{Data: gameStatefulSet}) gameStatefulSetToAdd[bkNamespace.BizID] = []client.CreateBcsWorkloadRequestData{*toAddData} + // CreateBkWorkloads create bkworkloads b.Syncer.CreateBkWorkloads(b.BkCluster, "gameStatefulSet", gameStatefulSetToAdd) return nil } @@ -1576,12 +1588,12 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNamespace(msg amqp.Delivery) { } switch msgHeader.Event { - case "update": + case "update": // nolint err = b.handleNamespaceUpdate(namespace) if err != nil { blog.Errorf("handleNamespaceUpdate err: %s", err.Error()) } - case "delete": + case "delete": // nolint err = b.handleNamespaceDelete(namespace) if err != nil { blog.Errorf("handleNamespaceDelete err: %s", err.Error()) @@ -1596,6 +1608,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNamespace(msg amqp.Delivery) { } func (b *BcsBkcmdbSynchronizerHandler) handleNamespaceUpdate(namespace *corev1.Namespace) error { + // GetBkNamespaces get bknamespaces bkNamespaces, err := b.Syncer.GetBkNamespaces(b.BkCluster.BizID, &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -1627,6 +1640,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNamespaceUpdate(namespace *corev1.N if len(*bkNamespaces) == 1 { bkNamespace := (*bkNamespaces)[0] nsToUpdate := make(map[int64]*client.UpdateBcsNamespaceRequestData, 0) + // CompareNamespace compare bkns and k8sns needToUpdate, updateData := b.Syncer.CompareNamespace(&bkNamespace, &storage.Namespace{Data: namespace}) if needToUpdate { nsToUpdate[bkNamespace.ID] = updateData @@ -1643,6 +1657,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNamespaceUpdate(namespace *corev1.N } func (b *BcsBkcmdbSynchronizerHandler) handleNamespaceDelete(namespace *corev1.Namespace) error { + // GetBkNamespaces get bknamespaces bkNamespaces, err := b.Syncer.GetBkNamespaces(b.BkCluster.BizID, &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -1664,11 +1679,11 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNamespaceDelete(namespace *corev1.N } if len(*bkNamespaces) > 1 { - return errors.New(fmt.Sprintf("len(bkNamespaces) = %d", len(*bkNamespaces))) + return fmt.Errorf("len(bkNamespaces) = %d", len(*bkNamespaces)) } if len(*bkNamespaces) == 0 { - return errors.New(fmt.Sprintf("namespace %s not found", namespace.Name)) + return fmt.Errorf("namespace %s not found", namespace.Name) } bkNamespace := (*bkNamespaces)[0] @@ -1676,6 +1691,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNamespaceDelete(namespace *corev1.N //err = b.Syncer.DeleteBkNamespaces(b.BkCluster.BizID, &[]int64{bkNamespace.ID}) err = retry.Do( func() error { + // DeleteBkNamespaces delete bknamespaces return b.Syncer.DeleteBkNamespaces(b.BkCluster, &[]int64{bkNamespace.ID}) }, retry.Delay(time.Second*1), @@ -1686,7 +1702,9 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNamespaceDelete(namespace *corev1.N return err } +// handle Namespace Create func (b *BcsBkcmdbSynchronizerHandler) handleNamespaceCreate(namespace *corev1.Namespace) error { + // GetProjectManagerGrpcGwClient is a function that returns a project manager gRPC gateway client. pmCli, err := b.Syncer.GetProjectManagerGrpcGwClient() if err != nil { blog.Errorf("get project manager grpc gw client failed, err: %s", err.Error()) @@ -1717,10 +1735,12 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNamespaceCreate(namespace *corev1.N nsToAdd := make(map[int64][]bkcmdbkube.Namespace, 0) nsToAdd[bizid] = []bkcmdbkube.Namespace{b.Syncer.GenerateBkNsData(b.BkCluster, &storage.Namespace{Data: namespace})} + // CreateBkNamespaces create bknamespaces b.Syncer.CreateBkNamespaces(b.BkCluster, nsToAdd) return nil } +// Node handle func (b *BcsBkcmdbSynchronizerHandler) handleNode(msg amqp.Delivery) { blog.Infof("handleNode Message: %v", msg.Headers) msgHeader, err := getMsgHeader(&msg.Headers) @@ -1738,12 +1758,12 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNode(msg amqp.Delivery) { } switch msgHeader.Event { - case "update": + case "update": // nolint err = b.handleNodeUpdate(node) if err != nil { blog.Errorf("handleNodeUpdate err: %s", err.Error()) } - case "delete": + case "delete": // nolint err = b.handleNodeDelete(node) if err != nil { blog.Errorf("handleNodeDelete err: %s", err.Error()) @@ -1758,6 +1778,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNode(msg amqp.Delivery) { } func (b *BcsBkcmdbSynchronizerHandler) handleNodeUpdate(node *corev1.Node) error { + // GetBkNodes get bknodes bkNodes, err := b.Syncer.GetBkNodes(b.BkCluster.BizID, &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -1804,7 +1825,9 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNodeUpdate(node *corev1.Node) error return nil } +// handle Node Delete func (b *BcsBkcmdbSynchronizerHandler) handleNodeDelete(node *corev1.Node) error { + // GetBkNodes get bknodes bkNodes, err := b.Syncer.GetBkNodes(b.BkCluster.BizID, &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -1826,11 +1849,11 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNodeDelete(node *corev1.Node) error } if len(*bkNodes) > 1 { - return errors.New(fmt.Sprintf("len(bkNodes) = %d", len(*bkNodes))) + return fmt.Errorf("len(bkNodes) = %d", len(*bkNodes)) } if len(*bkNodes) == 0 { - return errors.New(fmt.Sprintf("node %s not found", node.Name)) + return fmt.Errorf("node %s not found", node.Name) } bkNode := (*bkNodes)[0] @@ -1848,6 +1871,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNodeDelete(node *corev1.Node) error return err } +// handle Node Create func (b *BcsBkcmdbSynchronizerHandler) handleNodeCreate(node *corev1.Node) error { nodeToAdd := make([]client.CreateBcsNodeRequestData, 0) nodeToAdd = append(nodeToAdd, b.Syncer.GenerateBkNodeData(b.BkCluster, &storage.K8sNode{Data: node})) @@ -1855,6 +1879,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNodeCreate(node *corev1.Node) error return nil } +// get MsgHeader func getMsgHeader(header *amqp.Table) (*MsgHeader, error) { var msgHeader MsgHeader if err := mapstructure.Decode(header, &msgHeader); err != nil { diff --git a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/syncer/syncer.go b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/syncer/syncer.go index f309de42da..70e1faf13b 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/syncer/syncer.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/syncer/syncer.go @@ -71,6 +71,7 @@ func (s *Syncer) Init() { hostID = s.BkcmdbSynchronizerOption.Synchronizer.HostID } +// init Tls Config func (s *Syncer) initTlsConfig() error { if len(s.BkcmdbSynchronizerOption.Client.ClientCrt) != 0 && len(s.BkcmdbSynchronizerOption.Client.ClientKey) != 0 && @@ -93,6 +94,7 @@ func (s *Syncer) initTlsConfig() error { return nil } +// init CMDB Client func (s *Syncer) initCMDBClient() error { blog.Infof("init cmdb client") cmdbCli := cmdb.NewCmdbClient(&cmdb.Options{ @@ -103,6 +105,7 @@ func (s *Syncer) initCMDBClient() error { Debug: s.BkcmdbSynchronizerOption.CMDB.Debug, }) + // GetCMDBClient get cmdb client cli, err := cmdbCli.GetCMDBClient() if err != nil { blog.Errorf("get cmdb client failed: %s", err.Error()) @@ -121,6 +124,7 @@ func (s *Syncer) SyncCluster(cluster *cmp.Cluster) error { clusterNetwork = append(clusterNetwork, cluster.NetworkSettings.MultiClusterCIDR...) } + // GetBkCluster get bkcluster bkCluster, err := s.GetBkCluster(cluster) clusterType := "INDEPENDENT_CLUSTER" if cluster.IsShared { @@ -140,6 +144,7 @@ func (s *Syncer) SyncCluster(cluster *cmp.Cluster) error { } else { clusterBkBizID = bkBizID } + // CreateBcsCluster creates a new BCS cluster with the given request. _, err := s.CMDBClient.CreateBcsCluster(&client.CreateBcsClusterRequest{ BKBizID: &clusterBkBizID, Name: &cluster.ClusterID, @@ -166,6 +171,7 @@ func (s *Syncer) SyncCluster(cluster *cmp.Cluster) error { blog.Infof("get bcs cluster success, cluster: %v", bkCluster) if bkCluster != nil { + // UpdateBcsCluster updates the BCS cluster with the given request. err = s.CMDBClient.UpdateBcsCluster(&client.UpdateBcsClusterRequest{ BKBizID: &bkCluster.BizID, IDs: &[]int64{bkCluster.ID}, @@ -182,6 +188,7 @@ func (s *Syncer) SyncCluster(cluster *cmp.Cluster) error { } if *bkCluster.Type != clusterType { + // UpdateBcsClusterType updates the BCS cluster type with the given request. err = s.CMDBClient.UpdateBcsClusterType(&client.UpdateBcsClusterTypeRequest{ BKBizID: &bkCluster.BizID, ID: &bkCluster.ID, @@ -199,6 +206,7 @@ func (s *Syncer) SyncCluster(cluster *cmp.Cluster) error { // SyncNodes sync nodes func (s *Syncer) SyncNodes(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) error { + // GetBcsStorageClient is a function that returns a BCS storage client. storageCli, err := s.GetBcsStorageClient() if err != nil { blog.Errorf("get bcs storage client failed, err: %s", err.Error()) @@ -211,6 +219,7 @@ func (s *Syncer) SyncNodes(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) } blog.Infof("query k8s node success, nodes: %v", nodeList) + // GetBkNodes get bknodes bkNodeList, err := s.GetBkNodes(bkCluster.BizID, &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -247,12 +256,14 @@ func (s *Syncer) SyncNodes(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) for k, v := range nodeMap { if _, ok := bkNodeMap[k]; ok { + // CompareNode compare bknode and k8snode needToUpdate, updateData := s.CompareNode(bkNodeMap[k], v) if needToUpdate { nodeToUpdate[bkNodeMap[k].ID] = updateData } } else { + // GenerateBkNodeData generate bknode data from k8snode nodeToAdd = append(nodeToAdd, s.GenerateBkNodeData(bkCluster, v)) } } @@ -266,6 +277,7 @@ func (s *Syncer) SyncNodes(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) // SyncNamespaces sync namespaces func (s *Syncer) SyncNamespaces(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) error { + // GetBcsStorageClient is a function that returns a BCS storage client. storageCli, err := s.GetBcsStorageClient() if err != nil { blog.Errorf("get bcs storage client failed, err: %s", err.Error()) @@ -279,6 +291,7 @@ func (s *Syncer) SyncNamespaces(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Clus } blog.Infof("query k8s namespace success, namespaces: %v", nsList) + // GetBkNamespaces get bknamespaces bkNamespaceList, err := s.GetBkNamespaces(bkCluster.BizID, &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -314,6 +327,7 @@ func (s *Syncer) SyncNamespaces(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Clus } } + // GetProjectManagerGrpcGwClient is a function that returns a project manager gRPC gateway client. pmCli, err := s.GetProjectManagerGrpcGwClient() if err != nil { blog.Errorf("get project manager grpc gw client failed, err: %s", err.Error()) @@ -322,6 +336,7 @@ func (s *Syncer) SyncNamespaces(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Clus for k, v := range nsMap { if _, ok := bkNsMap[k]; ok { + // CompareNamespace compare bkns and k8sns needToUpdate, updateData := s.CompareNamespace(bkNsMap[k], v) if needToUpdate { nsToUpdate[bkNsMap[k].ID] = updateData @@ -366,31 +381,37 @@ func (s *Syncer) SyncNamespaces(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Clus // SyncWorkloads sync workloads func (s *Syncer) SyncWorkloads(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) error { + // syncDeployments sync deployments err := s.syncDeployments(cluster, bkCluster) if err != nil { blog.Errorf("sync deployment failed, err: %s", err.Error()) } + // syncStatefulSets sync statefulsets err = s.syncStatefulSets(cluster, bkCluster) if err != nil { blog.Errorf("sync statefulset failed, err: %s", err.Error()) } + // syncDaemonSets sync daemonsets err = s.syncDaemonSets(cluster, bkCluster) if err != nil { blog.Errorf("sync daemonset failed, err: %s", err.Error()) } + // syncGameDeployments sync gamedeployments err = s.syncGameDeployments(cluster, bkCluster) if err != nil { blog.Errorf("sync gamedeployment failed, err: %s", err.Error()) } + // syncGameStatefulSets sync gamestatefulsets err = s.syncGameStatefulSets(cluster, bkCluster) if err != nil { blog.Errorf("sync gamestatefulset failed, err: %s", err.Error()) } + // syncWorkloadPods sync workloadPods err = s.syncWorkloadPods(cluster, bkCluster) if err != nil { blog.Errorf("sync workload pods failed, err: %s", err.Error()) @@ -402,11 +423,13 @@ func (s *Syncer) SyncWorkloads(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Clust // syncDeployments sync deployments func (s *Syncer) syncDeployments(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) error { kind := "deployment" + // GetBcsStorageClient is a function that returns a BCS storage client. storageCli, err := s.GetBcsStorageClient() if err != nil { blog.Errorf("get bcs storage client failed, err: %s", err.Error()) } + // GetBkNamespaces get bknamespaces bkNamespaceList, err := s.GetBkNamespaces(bkCluster.BizID, &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -442,6 +465,7 @@ func (s *Syncer) syncDeployments(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Clu } blog.Infof("query k8s deployment success, deployments: %v", deploymentList) + // GetBkWorkloads get bkworkloads bkDeployments, err := s.GetBkWorkloads(bkCluster.BizID, "deployment", &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -488,6 +512,7 @@ func (s *Syncer) syncDeployments(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Clu for k, v := range deploymentMap { if _, ok := bkDeploymentMap[k]; !ok { + // GenerateBkDeployment generate bkdeployment from k8sdeployment toAddData := s.GenerateBkDeployment(bkNamespaceMap[v.Data.Namespace], v) if toAddData != nil { @@ -498,6 +523,7 @@ func (s *Syncer) syncDeployments(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Clu } } } else { + // CompareDeployment compare bkdeployment and k8sdeployment needToUpdate, updateData := s.CompareDeployment(bkDeploymentMap[k], v) if needToUpdate { @@ -516,11 +542,13 @@ func (s *Syncer) syncDeployments(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Clu // syncStatefulSets sync statefulsets func (s *Syncer) syncStatefulSets(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) error { kind := "statefulSet" + // GetBcsStorageClient is a function that returns a BCS storage client. storageCli, err := s.GetBcsStorageClient() if err != nil { blog.Errorf("get bcs storage client failed, err: %s", err.Error()) } + // GetBkNamespaces get bknamespaces bkNamespaceList, err := s.GetBkNamespaces(bkCluster.BizID, &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -555,6 +583,7 @@ func (s *Syncer) syncStatefulSets(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cl } blog.Infof("get statefulset list success, len: %d", len(statefulSetList)) + // GetBkWorkloads get bkworkloads bkStatefulSets, err := s.GetBkWorkloads(bkCluster.BizID, "statefulSet", &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -629,11 +658,13 @@ func (s *Syncer) syncStatefulSets(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cl // syncDaemonSets sync daemonsets func (s *Syncer) syncDaemonSets(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) error { kind := "daemonSet" + // GetBcsStorageClient is a function that returns a BCS storage client. storageCli, err := s.GetBcsStorageClient() if err != nil { blog.Errorf("get bcs storage client failed, err: %s", err.Error()) } + // GetBkNamespaces get bknamespaces bkNamespaceList, err := s.GetBkNamespaces(bkCluster.BizID, &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -964,7 +995,7 @@ func (s *Syncer) syncGameStatefulSets(cluster *cmp.Cluster, bkCluster *bkcmdbkub // syncWorkloadPods sync workloadPods func (s *Syncer) syncWorkloadPods(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) error { - kind := "pods" + kind := "pods" // nolint bkNamespaceList, err := s.GetBkNamespaces(bkCluster.BizID, &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -1312,6 +1343,7 @@ func (s *Syncer) getBkWorkloadPods(cluster *cmp.Cluster, bkCluster *bkcmdbkube.C return &p, nil } +// nolint func (s *Syncer) getPodOperator(cluster *cmp.Cluster, workloadLabels, nsLabels *map[string]string) []string { var operator []string if workloadLabels != nil { @@ -1364,8 +1396,8 @@ func (s *Syncer) getPodWordloadInfo( bkDeploymentMap map[string]*bkcmdbkube.Deployment) ( workloadKind, workloadName string, workloadID int64, labels *map[string]string) { - workloadKind = "pods" - workloadName = "pods" + workloadKind = "pods" // nolint + workloadName = "pods" // nolint workloadID = bkWorkloadPods.ID if len(pod.Data.OwnerReferences) == 1 { @@ -1794,7 +1826,7 @@ func (s *Syncer) CreateBkNodes(bkCluster *bkcmdbkube.Cluster, toCreate *[]client Data: toCreate, }) if err != nil { - for i := 0; i < len(*toCreate); i += 1 { + for i := 0; i < len(*toCreate); i++ { var section []client.CreateBcsNodeRequestData if i+1 > len(*toCreate) { section = (*toCreate)[i:] @@ -1938,6 +1970,7 @@ func (s *Syncer) GenerateBkNodeData(bkCluster *bkcmdbkube.Cluster, k8sNode *stor } // UpdateBkNodes update bknodes +// nolint func (s *Syncer) UpdateBkNodes(bkCluster *bkcmdbkube.Cluster, toUpdate *map[int64]*client.UpdateBcsNodeRequestData) { if toUpdate == nil { return @@ -1964,7 +1997,7 @@ func (s *Syncer) DeleteBkNodes(bkCluster *bkcmdbkube.Cluster, toDelete *[]int64) IDs: toDelete, }) if err != nil { - for i := 0; i < len(*toDelete); i += 1 { + for i := 0; i < len(*toDelete); i++ { var section []int64 if i+1 > len(*toDelete) { section = (*toDelete)[i:] @@ -2051,7 +2084,7 @@ func (s *Syncer) CompareNamespace(bkNs *bkcmdbkube.Namespace, k8sNs *storage.Nam // GenerateBkNsData generate bknsdata from k8sns func (s *Syncer) GenerateBkNsData(bkCluster *bkcmdbkube.Cluster, k8sNs *storage.Namespace) bkcmdbkube.Namespace { - labels := &map[string]string{} + var labels *map[string]string if k8sNs.Data.Labels == nil { labels = nil } else { @@ -2073,7 +2106,7 @@ func (s *Syncer) CreateBkNamespaces(bkCluster *bkcmdbkube.Cluster, toCreate map[ if len(toCreate) > 0 { for bizid, bkNsList := range toCreate { if len(bkNsList) > 0 { - for i := 0; i < len(bkNsList); i += 1 { + for i := 0; i < len(bkNsList); i++ { var section []bkcmdbkube.Namespace if i+1 > len(bkNsList) { section = (bkNsList)[i:] @@ -2091,8 +2124,8 @@ func (s *Syncer) CreateBkNamespaces(bkCluster *bkcmdbkube.Cluster, toCreate map[ return } - podsKind := "pods" - podsName := "pods" + podsKind := "pods" // nolint + podsName := "pods" // nolint _, err = s.CMDBClient.CreateBcsWorkload(&client.CreateBcsWorkloadRequest{ BKBizID: &bizid, Kind: &podsKind, @@ -2114,6 +2147,7 @@ func (s *Syncer) CreateBkNamespaces(bkCluster *bkcmdbkube.Cluster, toCreate map[ } // UpdateBkNamespaces update bknamespaces +// nolint func (s *Syncer) UpdateBkNamespaces(bkCluster *bkcmdbkube.Cluster, toUpdate *map[int64]*client.UpdateBcsNamespaceRequestData) { if toUpdate == nil { return @@ -2135,7 +2169,7 @@ func (s *Syncer) UpdateBkNamespaces(bkCluster *bkcmdbkube.Cluster, toUpdate *map // DeleteBkNamespaces delete bknamespaces func (s *Syncer) DeleteBkNamespaces(bkCluster *bkcmdbkube.Cluster, toDelete *[]int64) error { if len(*toDelete) > 0 { - for i := 0; i < len(*toDelete); i += 1 { + for i := 0; i < len(*toDelete); i++ { var section []int64 if i+1 > len(*toDelete) { section = (*toDelete)[i:] @@ -2170,7 +2204,7 @@ func (s *Syncer) DeleteBkNamespaces(bkCluster *bkcmdbkube.Cluster, toDelete *[]i return err } - podsKind := "pods" + podsKind := "pods" // nolint err = s.CMDBClient.DeleteBcsWorkload(&client.DeleteBcsWorkloadRequest{ BKBizID: &bkCluster.BizID, @@ -3076,12 +3110,14 @@ func (s *Syncer) GenerateBkGameStatefulSet(bkNs *bkcmdbkube.Namespace, k8sGameSt } // UpdateBkWorkloads update bkworkloads +// nolint func (s *Syncer) UpdateBkWorkloads(bkCluster *bkcmdbkube.Cluster, kind string, toUpdate *map[int64]*client.UpdateBcsWorkloadRequestData) { if toUpdate == nil { return } for k, v := range *toUpdate { + // UpdateBcsWorkload updates the BCS workload with the given request. err := s.CMDBClient.UpdateBcsWorkload(&client.UpdateBcsWorkloadRequest{ BKBizID: &bkCluster.BizID, Kind: &kind, @@ -3111,6 +3147,7 @@ func (s *Syncer) DeleteBkWorkloads(bkCluster *bkcmdbkube.Cluster, kind string, t } else { section = (*toDelete)[i : i+1] } + // DeleteBcsWorkload deletes the BCS workload with the given request. err = s.CMDBClient.DeleteBcsWorkload(&client.DeleteBcsWorkloadRequest{ BKBizID: &bkCluster.BizID, Kind: &kind, @@ -3134,6 +3171,7 @@ func (s *Syncer) GetBkPods(bkBizID int64, filter *client.PropertyFilter) (*[]bkc pageStart := 0 for { + // GetBcsPod returns the BCS pod information for the given request. bkPods, err := s.CMDBClient.GetBcsPod(&client.GetBcsPodRequest{ CommonRequest: client.CommonRequest{ BKBizID: bkBizID, @@ -3173,6 +3211,7 @@ func (s *Syncer) CreateBkPods(bkCluster *bkcmdbkube.Cluster, toCreate map[int64] section = (pods)[i : i+100] } + // CreateBcsPod creates a new BCS pod with the given request. _, err := s.CMDBClient.CreateBcsPod(&client.CreateBcsPodRequest{ Data: &[]client.CreateBcsPodRequestData{ { @@ -3183,7 +3222,7 @@ func (s *Syncer) CreateBkPods(bkCluster *bkcmdbkube.Cluster, toCreate map[int64] }) if err != nil { - for j := 0; j < len(section); j += 1 { + for j := 0; j < len(section); j++ { sec := section[j : j+1] _, err = s.CMDBClient.CreateBcsPod(&client.CreateBcsPodRequest{ Data: &[]client.CreateBcsPodRequestData{ @@ -3211,6 +3250,7 @@ func (s *Syncer) CreateBkPods(bkCluster *bkcmdbkube.Cluster, toCreate map[int64] // DeleteBkPods delete bkpods func (s *Syncer) DeleteBkPods(bkCluster *bkcmdbkube.Cluster, toDelete *[]int64) error { if len(*toDelete) > 0 { + // DeleteBcsPod deletes the BCS pod with the given request. err := s.CMDBClient.DeleteBcsPod(&client.DeleteBcsPodRequest{ Data: &[]client.DeleteBcsPodRequestData{ { @@ -3230,7 +3270,7 @@ func (s *Syncer) DeleteBkPods(bkCluster *bkcmdbkube.Cluster, toDelete *[]int64) // GenerateBkWorkloadPods generate bkworkloadpods func (s *Syncer) GenerateBkWorkloadPods(bkNs *bkcmdbkube.Namespace) *client.CreateBcsWorkloadRequestData { - podsName := "pods" + podsName := "pods" // nolint return &client.CreateBcsWorkloadRequestData{ NamespaceID: &bkNs.ID, diff --git a/bcs-services/bcs-bkcmdb-synchronizer/internal/synchronizer/synchronizer.go b/bcs-services/bcs-bkcmdb-synchronizer/internal/synchronizer/synchronizer.go index fd4b037fc9..cd70fb18a6 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/synchronizer/synchronizer.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/synchronizer/synchronizer.go @@ -190,10 +190,9 @@ func (s *Synchronizer) Run() { if errr != nil { blog.Errorf("Error: %v\n", errr) return - } else { - podIndex = num - fmt.Printf("The number is %d\n", podIndex) } + podIndex = num + fmt.Printf("The number is %d\n", podIndex) } } diff --git a/bcs-services/bcs-bscp/cmd/api-server/service/kv.go b/bcs-services/bcs-bscp/cmd/api-server/service/kv.go index 40e73a4cbe..094aa0b92d 100644 --- a/bcs-services/bcs-bscp/cmd/api-server/service/kv.go +++ b/bcs-services/bcs-bscp/cmd/api-server/service/kv.go @@ -101,7 +101,7 @@ func (m *kvService) Import(w http.ResponseWriter, r *http.Request) { func handleKv(result map[string]interface{}) ([]*pbcs.BatchUpsertKvsReq_Kv, error) { kvMap := []*pbcs.BatchUpsertKvsReq_Kv{} for key, value := range result { - KVType := "" + var kVType string entry, ok := value.(map[string]interface{}) if !ok { // 判断是不是数值类型 @@ -112,11 +112,11 @@ func handleKv(result map[string]interface{}) ([]*pbcs.BatchUpsertKvsReq_Kv, erro KvType: string(table.KvNumber), }) } else { - KVType = determineType(value.(string)) + kVType = determineType(value.(string)) kvMap = append(kvMap, &pbcs.BatchUpsertKvsReq_Kv{ Key: key, Value: fmt.Sprintf("%v", value), - KvType: KVType, + KvType: kVType, }) } } else { diff --git a/bcs-services/bcs-bscp/cmd/api-server/service/released_kv.go b/bcs-services/bcs-bscp/cmd/api-server/service/released_kv.go index cc87032148..ae5dcea4b9 100644 --- a/bcs-services/bcs-bscp/cmd/api-server/service/released_kv.go +++ b/bcs-services/bcs-bscp/cmd/api-server/service/released_kv.go @@ -150,7 +150,7 @@ func (m *kvService) Export(w http.ResponseWriter, r *http.Request) { _, err = w.Write(content) if err != nil { - logs.Errorf("Error writing response:", err) + logs.Errorf("Error writing response:%s", err) _ = render.Render(w, r, rest.BadRequest(err)) } diff --git a/bcs-services/bcs-bscp/cmd/auth-server/service/service.go b/bcs-services/bcs-bscp/cmd/auth-server/service/service.go index 9fa4d9de8b..985c7913dd 100644 --- a/bcs-services/bcs-bscp/cmd/auth-server/service/service.go +++ b/bcs-services/bcs-bscp/cmd/auth-server/service/service.go @@ -215,14 +215,15 @@ func newClientSet(sd serviced.Discover, tls cc.TLSConfig, iamSettings cc.IAM, di ReportCaller: false, } bkiamlogger.SetLogger(log) - iam := bkiam.NewAPIGatewayIAM(sys.SystemIDBSCP, iamSettings.AppCode, iamSettings.AppSecret, iamSettings.APIURL) + apiGatewayIAM := bkiam.NewAPIGatewayIAM( + sys.SystemIDBSCP, iamSettings.AppCode, iamSettings.AppSecret, iamSettings.APIURL) cs := &ClientSet{ DS: ds, sys: iamSys, auth: authSdk, Esb: esbCli, - iamClient: iam, + iamClient: apiGatewayIAM, } logs.Infof("initialize the client set success.") return cs, nil diff --git a/bcs-services/bcs-bscp/cmd/config-server/service/app.go b/bcs-services/bcs-bscp/cmd/config-server/service/app.go index e1d84c73fd..016e17a040 100644 --- a/bcs-services/bcs-bscp/cmd/config-server/service/app.go +++ b/bcs-services/bcs-bscp/cmd/config-server/service/app.go @@ -182,6 +182,7 @@ func (s *Service) GetApp(ctx context.Context, req *pbcs.GetAppReq) (*pbapp.App, func (s *Service) GetAppByName(ctx context.Context, req *pbcs.GetAppByNameReq) (*pbapp.App, error) { kt := kit.FromGrpcContext(ctx) + // nolint // TODO: 暂不鉴权 // resp := new(pbapp.App) diff --git a/bcs-services/bcs-bscp/cmd/config-server/service/app_template_binding.go b/bcs-services/bcs-bscp/cmd/config-server/service/app_template_binding.go index 6a7fb65312..1bdfc39bf0 100644 --- a/bcs-services/bcs-bscp/cmd/config-server/service/app_template_binding.go +++ b/bcs-services/bcs-bscp/cmd/config-server/service/app_template_binding.go @@ -31,6 +31,7 @@ import ( // CreateAppTemplateBinding create an app template binding func (s *Service) CreateAppTemplateBinding(ctx context.Context, req *pbcs.CreateAppTemplateBindingReq) ( *pbcs.CreateAppTemplateBindingResp, error) { + // FromGrpcContext used only to obtain Kit through grpc context. grpcKit := kit.FromGrpcContext(ctx) // validate input param @@ -39,6 +40,7 @@ func (s *Service) CreateAppTemplateBinding(ctx context.Context, req *pbcs.Create logs.Errorf("create app template binding failed, parse bindings err: %v, rid: %s", err, grpcKit.Rid) return nil, err } + // SliceRepeatedElements get the repeated elements in a slice, and the keep the sequence of result repeatedTmplSetIDs := tools.SliceRepeatedElements(templateSetIDs) if len(repeatedTmplSetIDs) > 0 { return nil, fmt.Errorf("repeated template set ids: %v, id must be unique", repeatedTmplSetIDs) @@ -56,6 +58,8 @@ func (s *Service) CreateAppTemplateBinding(ctx context.Context, req *pbcs.Create {Basic: meta.Basic{Type: meta.Biz, Action: meta.FindBusinessResource}, BizID: req.BizId}, {Basic: meta.Basic{Type: meta.App, Action: meta.Update, ResourceID: req.AppId}, BizID: req.BizId}, } + // Authorize authorize if user has permission to the resources. + // If user is unauthorized, assign apply url and resources into error. if err = s.authorizer.Authorize(grpcKit, res...); err != nil { return nil, err } @@ -85,6 +89,7 @@ func (s *Service) CreateAppTemplateBinding(ctx context.Context, req *pbcs.Create // DeleteAppTemplateBinding delete an app template binding func (s *Service) DeleteAppTemplateBinding(ctx context.Context, req *pbcs.DeleteAppTemplateBindingReq) ( *pbcs.DeleteAppTemplateBindingResp, error) { + // FromGrpcContext used only to obtain Kit through grpc context. grpcKit := kit.FromGrpcContext(ctx) res := []*meta.ResourceAttribute{ @@ -113,6 +118,7 @@ func (s *Service) DeleteAppTemplateBinding(ctx context.Context, req *pbcs.Delete // UpdateAppTemplateBinding update an app template binding func (s *Service) UpdateAppTemplateBinding(ctx context.Context, req *pbcs.UpdateAppTemplateBindingReq) ( *pbcs.UpdateAppTemplateBindingResp, error) { + // FromGrpcContext used only to obtain Kit through grpc context. grpcKit := kit.FromGrpcContext(ctx) // validate input param @@ -121,6 +127,7 @@ func (s *Service) UpdateAppTemplateBinding(ctx context.Context, req *pbcs.Update logs.Errorf("update app template binding failed, parse bindings err: %v, rid: %s", err, grpcKit.Rid) return nil, err } + // SliceRepeatedElements get the repeated elements in a slice, and the keep the sequence of result repeatedTmplSetIDs := tools.SliceRepeatedElements(templateSetIDs) if len(repeatedTmplSetIDs) > 0 { return nil, fmt.Errorf("repeated template set ids: %v, id must be unique", repeatedTmplSetIDs) diff --git a/bcs-services/bcs-bscp/cmd/config-server/service/template.go b/bcs-services/bcs-bscp/cmd/config-server/service/template.go index 08daf0b432..73c0d4492c 100644 --- a/bcs-services/bcs-bscp/cmd/config-server/service/template.go +++ b/bcs-services/bcs-bscp/cmd/config-server/service/template.go @@ -33,11 +33,14 @@ import ( // CreateTemplate create a template func (s *Service) CreateTemplate(ctx context.Context, req *pbcs.CreateTemplateReq) (*pbcs.CreateTemplateResp, error) { + // FromGrpcContext used only to obtain Kit through grpc context. grpcKit := kit.FromGrpcContext(ctx) res := []*meta.ResourceAttribute{ {Basic: meta.Basic{Type: meta.Biz, Action: meta.FindBusinessResource}, BizID: req.BizId}, } + // Authorize authorize if user has permission to the resources. + // If user is unauthorized, assign apply url and resources into error. if err := s.authorizer.Authorize(grpcKit, res...); err != nil { return nil, err } @@ -96,6 +99,8 @@ func (s *Service) DeleteTemplate(ctx context.Context, req *pbcs.DeleteTemplateRe res := []*meta.ResourceAttribute{ {Basic: meta.Basic{Type: meta.Biz, Action: meta.FindBusinessResource}, BizID: req.BizId}, } + // Authorize authorize if user has permission to the resources. + // If user is unauthorized, assign apply url and resources into error. if err := s.authorizer.Authorize(grpcKit, res...); err != nil { return nil, err } @@ -157,11 +162,14 @@ func (s *Service) BatchDeleteTemplate(ctx context.Context, req *pbcs.BatchDelete // UpdateTemplate update a template func (s *Service) UpdateTemplate(ctx context.Context, req *pbcs.UpdateTemplateReq) (*pbcs.UpdateTemplateResp, error) { + // FromGrpcContext used only to obtain Kit through grpc context. grpcKit := kit.FromGrpcContext(ctx) res := []*meta.ResourceAttribute{ {Basic: meta.Basic{Type: meta.Biz, Action: meta.FindBusinessResource}, BizID: req.BizId}, } + // Authorize authorize if user has permission to the resources. + // If user is unauthorized, assign apply url and resources into error. if err := s.authorizer.Authorize(grpcKit, res...); err != nil { return nil, err } @@ -186,11 +194,14 @@ func (s *Service) UpdateTemplate(ctx context.Context, req *pbcs.UpdateTemplateRe // ListTemplates list templates func (s *Service) ListTemplates(ctx context.Context, req *pbcs.ListTemplatesReq) (*pbcs.ListTemplatesResp, error) { + // FromGrpcContext used only to obtain Kit through grpc context. grpcKit := kit.FromGrpcContext(ctx) res := []*meta.ResourceAttribute{ {Basic: meta.Basic{Type: meta.Biz, Action: meta.FindBusinessResource}, BizID: req.BizId}, } + // Authorize authorize if user has permission to the resources. + // If user is unauthorized, assign apply url and resources into error. if err := s.authorizer.Authorize(grpcKit, res...); err != nil { return nil, err } diff --git a/bcs-services/bcs-bscp/cmd/data-service/db-migration/migrations/20231123143015_modify_app.go b/bcs-services/bcs-bscp/cmd/data-service/db-migration/migrations/20231123143015_modify_app.go index 497c8c8061..181dd4aa53 100644 --- a/bcs-services/bcs-bscp/cmd/data-service/db-migration/migrations/20231123143015_modify_app.go +++ b/bcs-services/bcs-bscp/cmd/data-service/db-migration/migrations/20231123143015_modify_app.go @@ -35,7 +35,7 @@ func init() { // mig20231123143015Up for up migration func mig20231123143015Up(tx *gorm.DB) error { - // Applications: 服务 + // Applications : 服务 type Applications struct { Alias string `gorm:"type:varchar(255) not null;"` DataType string `gorm:"type:varchar(255) not null;"` @@ -68,7 +68,7 @@ func mig20231123143015Up(tx *gorm.DB) error { // mig20231123143015Down for down migration func mig20231123143015Down(tx *gorm.DB) error { - // Applications: 服务 + // Applications : 服务 type Applications struct { Alias string `gorm:"type:varchar(255) not null;"` DataType string `gorm:"type:varchar(255) not null;"` diff --git a/bcs-services/bcs-bscp/cmd/data-service/service/hook.go b/bcs-services/bcs-bscp/cmd/data-service/service/hook.go index 6809040c96..edfce32600 100644 --- a/bcs-services/bcs-bscp/cmd/data-service/service/hook.go +++ b/bcs-services/bcs-bscp/cmd/data-service/service/hook.go @@ -33,10 +33,12 @@ import ( func (s *Service) CreateHook(ctx context.Context, req *pbds.CreateHookReq) (*pbds.CreateResp, error) { kt := kit.FromGrpcContext(ctx) + // GetByName get hook by name if _, err := s.dao.Hook().GetByName(kt, req.Attachment.BizId, req.Spec.Name); err == nil { return nil, fmt.Errorf("hook name %s already exists", req.Spec.Name) } + // HookSpec convert pb HookSpec to table HookSpec spec, err := req.Spec.HookSpec() if err != nil { logs.Errorf("get hook spec from pb failed, err: %v, rid: %s", err, kt.Rid) @@ -56,6 +58,7 @@ func (s *Service) CreateHook(ctx context.Context, req *pbds.CreateHookReq) (*pbd Revision: res, } + // CreateWithTx create one hook instance with transaction. id, err := s.dao.Hook().CreateWithTx(kt, tx, hook) if err != nil { logs.Errorf("create hook failed, err: %v, rid: %s", err, kt.Rid) @@ -79,6 +82,7 @@ func (s *Service) CreateHook(ctx context.Context, req *pbds.CreateHookReq) (*pbd }, Revision: res, } + // CreateWithTx create hook revision instance with transaction. _, err = s.dao.HookRevision().CreateWithTx(kt, tx, revision) if err != nil { logs.Errorf("create hook revision failed, err: %v, rid: %s", err, kt.Rid) @@ -100,6 +104,7 @@ func (s *Service) CreateHook(ctx context.Context, req *pbds.CreateHookReq) (*pbd // ListHooks list hooks. func (s *Service) ListHooks(ctx context.Context, req *pbds.ListHooksReq) (*pbds.ListHooksResp, error) { + // FromGrpcContext used only to obtain Kit through grpc context. kt := kit.FromGrpcContext(ctx) page := &types.BasePage{Start: req.Start, Limit: uint(req.Limit)} @@ -120,6 +125,7 @@ func (s *Service) ListHooks(ctx context.Context, req *pbds.ListHooksReq) (*pbds. return nil, err } + // ListWithRefer hooks with refer info. details, count, err := s.dao.Hook().ListWithRefer(kt, opt) if err != nil { logs.Errorf("list hook failed, err: %v, rid: %s", err, kt.Rid) @@ -193,6 +199,7 @@ func (s *Service) DeleteHook(ctx context.Context, req *pbds.DeleteHookReq) (*pbb BizID: req.BizId, }, } + // DeleteWithTx delete hook instance with transaction. if e := s.dao.Hook().DeleteWithTx(kt, tx, hook); e != nil { logs.Errorf("delete hook failed, err: %v, rid: %s", e, kt.Rid) if rErr := tx.Rollback(); rErr != nil { @@ -211,8 +218,10 @@ func (s *Service) DeleteHook(ctx context.Context, req *pbds.DeleteHookReq) (*pbb // ListHookTags list tag func (s *Service) ListHookTags(ctx context.Context, req *pbds.ListHookTagReq) (*pbds.ListHookTagResp, error) { + // FromGrpcContext used only to obtain Kit through grpc context. kt := kit.FromGrpcContext(ctx) + // CountHookTag count hook tag ht, err := s.dao.Hook().CountHookTag(kt, req.BizId) if err != nil { logs.Errorf("list hook failed, err: %v, rid: %s", err, kt.Rid) @@ -234,6 +243,7 @@ func (s *Service) ListHookTags(ctx context.Context, req *pbds.ListHookTagReq) (* // GetHook get a hook func (s *Service) GetHook(ctx context.Context, req *pbds.GetHookReq) (*pbds.GetHookResp, error) { + // FromGrpcContext used only to obtain Kit through grpc context. kt := kit.FromGrpcContext(ctx) h, err := s.dao.Hook().GetByID(kt, req.BizId, req.HookId) diff --git a/bcs-services/bcs-bscp/cmd/data-service/service/hook_revision.go b/bcs-services/bcs-bscp/cmd/data-service/service/hook_revision.go index 023d137bc1..70cd42da39 100644 --- a/bcs-services/bcs-bscp/cmd/data-service/service/hook_revision.go +++ b/bcs-services/bcs-bscp/cmd/data-service/service/hook_revision.go @@ -210,7 +210,7 @@ func (s *Service) PublishHookRevision(ctx context.Context, req *pbds.PublishHook } // 2. 上线脚本版本 - hr, err := s.dao.HookRevision().Get(kt, req.BizId, req.HookId, req.Id) + hookRevision, err := s.dao.HookRevision().Get(kt, req.BizId, req.HookId, req.Id) if err != nil { logs.Errorf("get HookRevision failed, err: %v, rid: %s", err, kt.Rid) if rErr := tx.Rollback(); rErr != nil { @@ -218,9 +218,9 @@ func (s *Service) PublishHookRevision(ctx context.Context, req *pbds.PublishHook } return nil, err } - hr.Revision.Reviser = kt.User - hr.Spec.State = table.HookRevisionStatusDeployed - if e := s.dao.HookRevision().UpdatePubStateWithTx(kt, tx, hr); e != nil { + hookRevision.Revision.Reviser = kt.User + hookRevision.Spec.State = table.HookRevisionStatusDeployed + if e := s.dao.HookRevision().UpdatePubStateWithTx(kt, tx, hookRevision); e != nil { logs.Errorf("update HookRevision State failed, err: %v, rid: %s", e, kt.Rid) if rErr := tx.Rollback(); rErr != nil { logs.Errorf("transaction rollback failed, err: %v, rid: %s", rErr, kt.Rid) @@ -230,7 +230,7 @@ func (s *Service) PublishHookRevision(ctx context.Context, req *pbds.PublishHook // 3. 修改未命名版本绑定的脚本版本为上线版本 if e := s.dao.ReleasedHook().UpdateHookRevisionByReleaseIDWithTx(kt, tx, - req.BizId, 0, req.HookId, hr); e != nil { + req.BizId, 0, req.HookId, hookRevision); e != nil { logs.Errorf("update released hook failed, err: %v, rid: %s", e, kt.Rid) if rErr := tx.Rollback(); rErr != nil { logs.Errorf("transaction rollback failed, err: %v, rid: %s", rErr, kt.Rid) diff --git a/bcs-services/bcs-bscp/cmd/data-service/service/kv.go b/bcs-services/bcs-bscp/cmd/data-service/service/kv.go index 76084003f7..e2b7271f9d 100644 --- a/bcs-services/bcs-bscp/cmd/data-service/service/kv.go +++ b/bcs-services/bcs-bscp/cmd/data-service/service/kv.go @@ -35,6 +35,7 @@ func (s *Service) CreateKv(ctx context.Context, req *pbds.CreateKvReq) (*pbds.Cr kt := kit.FromGrpcContext(ctx) + // GetByKvState get kv by KvState. _, err := s.dao.Kv().GetByKvState(kt, req.Attachment.BizId, req.Attachment.AppId, req.Spec.Key, []string{string(table.KvStateAdd), string(table.KvStateUnchange), string(table.KvStateRevise)}) if err != nil && !errors.Is(gorm.ErrRecordNotFound, err) { @@ -45,7 +46,7 @@ func (s *Service) CreateKv(ctx context.Context, req *pbds.CreateKvReq) (*pbds.Cr logs.Errorf("get kv (%d) failed, err: %v, rid: %s", req.Spec.Key, err, kt.Rid) return nil, fmt.Errorf("kv same key %s already exists", req.Spec.Key) } - + // get app with id. app, err := s.dao.App().Get(kt, req.Attachment.BizId, req.Attachment.AppId) if err != nil { return nil, fmt.Errorf("get app fail,err : %v", req.Spec.Key) @@ -61,6 +62,7 @@ func (s *Service) CreateKv(ctx context.Context, req *pbds.CreateKvReq) (*pbds.Cr Value: req.Spec.Value, KvType: table.DataType(req.Spec.KvType), } + // UpsertKv 创建|更新kv version, err := s.vault.UpsertKv(kt, opt) if err != nil { logs.Errorf("create kv failed, err: %v, rid: %s", err, kt.Rid) @@ -77,6 +79,7 @@ func (s *Service) CreateKv(ctx context.Context, req *pbds.CreateKvReq) (*pbds.Cr } kv.Spec.Version = uint32(version) kv.KvState = table.KvStateAdd + // Create one kv instance id, err := s.dao.Kv().Create(kt, kv) if err != nil { logs.Errorf("create kv failed, err: %v, rid: %s", err, kt.Rid) @@ -88,6 +91,7 @@ func (s *Service) CreateKv(ctx context.Context, req *pbds.CreateKvReq) (*pbds.Cr } +// check KV Type Match func checkKVTypeMatch(kvType, appKvType table.DataType) bool { if appKvType == table.KvAny { return true @@ -100,6 +104,7 @@ func (s *Service) UpdateKv(ctx context.Context, req *pbds.UpdateKvReq) (*pbbase. kt := kit.FromGrpcContext(ctx) + // GetByKvState get kv by KvState. kv, err := s.dao.Kv().GetByKvState(kt, req.Attachment.BizId, req.Attachment.AppId, req.Spec.Key, []string{string(table.KvStateAdd), string(table.KvStateUnchange), string(table.KvStateRevise)}) if err != nil { @@ -114,6 +119,7 @@ func (s *Service) UpdateKv(ctx context.Context, req *pbds.UpdateKvReq) (*pbbase. Value: req.Spec.Value, KvType: kv.Spec.KvType, } + // UpsertKv 创建|更新kv version, err := s.vault.UpsertKv(kt, opt) if err != nil { logs.Errorf("update kv failed, err: %v, rid: %s", err, kt.Rid) @@ -142,6 +148,7 @@ func (s *Service) UpdateKv(ctx context.Context, req *pbds.UpdateKvReq) (*pbbase. // ListKvs is used to list key-value data. func (s *Service) ListKvs(ctx context.Context, req *pbds.ListKvsReq) (*pbds.ListKvsResp, error) { + // FromGrpcContext used only to obtain Kit through grpc context. kt := kit.FromGrpcContext(ctx) if len(req.Sort) == 0 { @@ -153,6 +160,7 @@ func (s *Service) ListKvs(ctx context.Context, req *pbds.ListKvsReq) (*pbds.List Sort: req.Sort, Order: types.Order(req.Order), } + // StrToUint32Slice the comma separated string goes to uint32 slice topIds, _ := tools.StrToUint32Slice(req.TopIds) opt := &types.ListKvOption{ BizID: req.BizId, @@ -189,6 +197,7 @@ func (s *Service) ListKvs(ctx context.Context, req *pbds.ListKvsReq) (*pbds.List } +// set Kv Type And Value func (s *Service) setKvTypeAndValue(kt *kit.Kit, details []*table.Kv) ([]*pbkv.Kv, error) { kvs := make([]*pbkv.Kv, 0) @@ -236,6 +245,7 @@ func (s *Service) DeleteKv(ctx context.Context, req *pbds.DeleteKvReq) (*pbbase. // BatchUpsertKvs is used to insert or update key-value data in bulk. func (s *Service) BatchUpsertKvs(ctx context.Context, req *pbds.BatchUpsertKvsReq) (*pbds.BatchUpsertKvsResp, error) { + // FromGrpcContext used only to obtain Kit through grpc context. kt := kit.FromGrpcContext(ctx) app, err := s.dao.App().Get(kt, req.BizId, req.AppId) diff --git a/bcs-services/bcs-bscp/cmd/data-service/service/template.go b/bcs-services/bcs-bscp/cmd/data-service/service/template.go index d9d04be126..e849369a42 100644 --- a/bcs-services/bcs-bscp/cmd/data-service/service/template.go +++ b/bcs-services/bcs-bscp/cmd/data-service/service/template.go @@ -39,11 +39,13 @@ import ( func (s *Service) CreateTemplate(ctx context.Context, req *pbds.CreateTemplateReq) (*pbds.CreateResp, error) { kt := kit.FromGrpcContext(ctx) + // GetByUniqueKey get template by unique key. if _, err := s.dao.Template().GetByUniqueKey(kt, req.Attachment.BizId, req.Attachment.TemplateSpaceId, req.Spec.Name, req.Spec.Path); err == nil { return nil, fmt.Errorf("config item's same name %s and path %s already exists", req.Spec.Name, req.Spec.Path) } if len(req.TemplateSetIds) > 0 { + // ValidateTmplSetsExist validate if template sets exists if err := s.dao.Validator().ValidateTmplSetsExist(kt, req.TemplateSetIds); err != nil { return nil, err } @@ -60,6 +62,7 @@ func (s *Service) CreateTemplate(ctx context.Context, req *pbds.CreateTemplateRe Reviser: kt.User, }, } + // CreateWithTx create one template instance with transaction. id, err := s.dao.Template().CreateWithTx(kt, tx, template) if err != nil { logs.Errorf("create template failed, err: %v, rid: %s", err, kt.Rid) @@ -83,6 +86,7 @@ func (s *Service) CreateTemplate(ctx context.Context, req *pbds.CreateTemplateRe Creator: kt.User, }, } + // CreateWithTx create one template revision instance with transaction. if _, err = s.dao.TemplateRevision().CreateWithTx(kt, tx, templateRevision); err != nil { logs.Errorf("create template revision failed, err: %v, rid: %s", err, kt.Rid) if rErr := tx.Rollback(); rErr != nil { @@ -145,6 +149,7 @@ func (s *Service) ListTemplates(ctx context.Context, req *pbds.ListTemplatesReq) return nil, err } topIds, _ := tools.StrToUint32Slice(req.Ids) + // List templates with options. details, count, err := s.dao.Template().List(kt, req.BizId, req.TemplateSpaceId, searcher, opt, topIds) if err != nil { @@ -171,6 +176,7 @@ func (s *Service) UpdateTemplate(ctx context.Context, req *pbds.UpdateTemplateRe Reviser: kt.User, }, } + // Update one template's info. if err := s.dao.Template().Update(kt, template); err != nil { logs.Errorf("update template failed, err: %v, rid: %s", err, kt.Rid) return nil, err diff --git a/bcs-services/bcs-bscp/cmd/vault-server/vault-plugins/service/backend.go b/bcs-services/bcs-bscp/cmd/vault-server/vault-plugins/service/backend.go index a8509353e4..1bec0f5078 100644 --- a/bcs-services/bcs-bscp/cmd/vault-server/vault-plugins/service/backend.go +++ b/bcs-services/bcs-bscp/cmd/vault-server/vault-plugins/service/backend.go @@ -40,6 +40,7 @@ type backend struct { } // Backend new backend +// nolint func Backend(ctx context.Context, conf *logical.BackendConfig) *backend { b := &backend{} diff --git a/bcs-services/bcs-bscp/pkg/audit/audit.go b/bcs-services/bcs-bscp/pkg/audit/audit.go index cacc9a4033..8e2312bb30 100644 --- a/bcs-services/bcs-bscp/pkg/audit/audit.go +++ b/bcs-services/bcs-bscp/pkg/audit/audit.go @@ -53,6 +53,7 @@ func GetRouteMatcher() *routematch.RouteMatcher { return routeMatcher } +// get Routes func getRoutes() []routematch.Route { rs := make([]routematch.Route, 0) for k := range auditHttpMap { @@ -63,6 +64,7 @@ func getRoutes() []routematch.Route { return rs } +// audit Param type auditParam struct { Username string SourceIP string @@ -78,6 +80,7 @@ type auditParam struct { // ignoredField means ignored fields for audit event , eg: all fields for activity const ignoredField string = "ignored" +// add Audit func addAudit(p auditParam) { auditCtx := audit.RecorderContext{ Username: p.Username, @@ -114,16 +117,19 @@ func addAudit(p auditParam) { var auditHttpMap = map[string]func() (audit.Resource, audit.Action){ // api-server api "PUT./api/v1/biz/{biz_id}/content/upload": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "upload_file"} }, "GET./api/v1/biz/{biz_id}/content/download": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "download_file"} }, "GET./api/v1/biz/{biz_id}/content/metadata": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "get_file_metadata"} }, @@ -132,498 +138,622 @@ var auditHttpMap = map[string]func() (audit.Resource, audit.Action){ var auditGrpcMap = map[string]func() (audit.Resource, audit.Action){ // config-server api, see pkg/protocol/config-server/config_service.proto "/pbcs.Config/CreateApp": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "create_app"} }, "/pbcs.Config/UpdateApp": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "update_app"} }, "/pbcs.Config/DeleteApp": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "delete_app"} }, "/pbcs.Config/GetApp": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "get_app"} }, "/pbcs.Config/GetAppByName": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "get_app_by_name"} }, "/pbcs.Config/ListAppsRest": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "list_apps_rest"} }, "/pbcs.Config/ListAppsBySpaceRest": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "list_apps_by_space_rest"} }, "/pbcs.Config/CreateConfigItem": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "create_config_item"} }, "/pbcs.Config/BatchUpsertConfigItems": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "batch_upsert_config_items"} }, "/pbcs.Config/DeleteConfigItem": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "delete_config_item"} }, "/pbcs.Config/GetConfigItem": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "get_config_item"} }, "/pbcs.Config/GetReleasedConfigItem": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "get_released_config_item"} }, "/pbcs.Config/ListConfigItems": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "list_config_items"} }, "/pbcs.Config/ListReleasedConfigItems": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "list_released_config_items"} }, "/pbcs.Config/ListConfigItemCount": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "list_config_item_count"} }, "/pbcs.Config/ListConfigItemByTuple": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "list_config_item_by_tuple"} }, "/pbcs.Config/GetReleasedKv": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "get_released_kv"} }, "/pbcs.Config/ListReleasedKvs": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "list_released_kvs"} }, "/pbcs.Config/UpdateConfigHook": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "update_config_hook"} }, "/pbcs.Config/CreateRelease": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "create_release"} }, "/pbcs.Config/ListReleases": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "list_releases"} }, "/pbcs.Config/GetReleaseByName": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "get_release_by_name"} }, "/pbcs.Config/DeprecateRelease": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "deprecate_release"} }, "/pbcs.Config/UnDeprecateRelease": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "undeprecate_release"} }, "/pbcs.Config/DeleteRelease": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "delete_release"} }, "/pbcs.Config/CreateHook": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "create_hook"} }, "/pbcs.Config/DeleteHook": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "delete_hook"} }, "/pbcs.Config/ListHooks": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_hooks"} }, "/pbcs.Config/ListHookTags": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_hook_tags"} }, "/pbcs.Config/GetHook": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "get_hook"} }, "/pbcs.Config/CreateHookRevision": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "create_hook_revision"} }, "/pbcs.Config/ListHookRevisions": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_hook_revisions"} }, "/pbcs.Config/DeleteHookRevision": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "delete_hook_revision"} }, "/pbcs.Config/PublishHookRevision": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "publish_hook_revision"} }, "/pbcs.Config/GetHookRevision": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "get_hook_revision"} }, "/pbcs.Config/UpdateHookRevision": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "update_hook_revision"} }, "/pbcs.Config/ListHookReferences": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_hook_references"} }, "/pbcs.Config/ListHookRevisionReferences": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_hook_revision_references"} }, "/pbcs.Config/GetReleaseHook": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "get_release_hook"} }, "/pbcs.Config/CreateTemplateSpace": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "create_template_space"} }, "/pbcs.Config/DeleteTemplateSpace": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "delete_template_space"} }, "/pbcs.Config/UpdateTemplateSpace": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "update_template_space"} }, "/pbcs.Config/ListTemplateSpaces": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_template_spaces"} }, "/pbcs.Config/GetAllBizsOfTmplSpaces": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "get_all_bizs_of_tmpl_spaces"} }, "/pbcs.Config/CreateDefaultTmplSpace": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "create_default_tmpl_space"} }, "/pbcs.Config/ListTmplSpacesByIDs": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_tmpl_spaces_by_ids"} }, "/pbcs.Config/CreateTemplate": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "create_template"} }, "/pbcs.Config/DeleteTemplate": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "delete_template"} }, "/pbcs.Config/BatchDeleteTemplate": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "batch_delete_template"} }, "/pbcs.Config/UpdateTemplate": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "update_template"} }, "/pbcs.Config/ListTemplates": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_templates"} }, "/pbcs.Config/BatchUpsertTemplates": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "batch_upsert_templates"} }, "/pbcs.Config/AddTmplsToTmplSets": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "add_tmpls_to_tmpl_sets"} }, "/pbcs.Config/DeleteTmplsFromTmplSets": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "delete_tmpls_from_tmpl_sets"} }, "/pbcs.Config/ListTemplatesByIDs": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_templates_by_ids"} }, "/pbcs.Config/ListTemplatesNotBound": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_templates_not_bound"} }, "/pbcs.Config/ListTemplateByTuple": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_template_by_tuple"} }, "/pbcs.Config/ListTmplsOfTmplSet": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_tmpls_of_tmpl_set"} }, "/pbcs.Config/CreateTemplateRevision": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "create_template_revision"} }, "/pbcs.Config/ListTemplateRevisions": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_template_revisions"} }, "/pbcs.Config/ListTemplateRevisionsByIDs": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_template_revisions_by_ids"} }, "/pbcs.Config/ListTmplRevisionNamesByTmplIDs": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_tmpl_revision_names_by_tmpl_ids"} }, "/pbcs.Config/CreateTemplateSet": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "create_template_set"} }, "/pbcs.Config/DeleteTemplateSet": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "delete_template_set"} }, "/pbcs.Config/UpdateTemplateSet": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "update_template_set"} }, "/pbcs.Config/ListTemplateSets": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_template_sets"} }, "/pbcs.Config/ListAppTemplateSets": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "list_app_template_sets"} }, "/pbcs.Config/ListTemplateSetsByIDs": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_template_sets_by_ids"} }, "/pbcs.Config/ListTmplSetsOfBiz": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_tmpl_sets_of_biz"} }, "/pbcs.Config/CreateAppTemplateBinding": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "create_app_template_binding"} }, "/pbcs.Config/DeleteAppTemplateBinding": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "delete_app_template_binding"} }, "/pbcs.Config/UpdateAppTemplateBinding": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "update_app_template_binding"} }, "/pbcs.Config/ListAppTemplateBindings": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "list_app_template_bindings"} }, "/pbcs.Config/ListAppBoundTmplRevisions": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "list_app_bound_tmpl_revisions"} }, "/pbcs.Config/ListReleasedAppBoundTmplRevisions": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "list_released_app_bound_tmpl_revisions"} }, "/pbcs.Config/GetReleasedAppBoundTmplRevision": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "get_released_app_bound_tmpl_revision"} }, "/pbcs.Config/UpdateAppBoundTmplRevisions": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "update_app_bound_tmpl_revisions"} }, "/pbcs.Config/DeleteAppBoundTmplSets": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "delete_app_bound_tmpl_sets"} }, "/pbcs.Config/CheckAppTemplateBinding": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "check_app_template_binding"} }, "/pbcs.Config/ListTmplBoundCounts": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_tmpl_bound_counts"} }, "/pbcs.Config/ListTmplRevisionBoundCounts": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_tmpl_revision_bound_counts"} }, "/pbcs.Config/ListTmplSetBoundCounts": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_tmpl_set_bound_counts"} }, "/pbcs.Config/ListTmplBoundUnnamedApps": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_tmpl_bound_unnamed_apps"} }, "/pbcs.Config/ListTmplBoundNamedApps": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_tmpl_bound_named_apps"} }, "/pbcs.Config/ListTmplBoundTmplSets": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_tmpl_bound_tmpl_sets"} }, "/pbcs.Config/ListMultiTmplBoundTmplSets": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_multi_tmpl_bound_tmpl_sets"} }, "/pbcs.Config/ListTmplRevisionBoundUnnamedApps": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_tmpl_revision_bound_unnamed_apps"} }, "/pbcs.Config/ListTmplRevisionBoundNamedApps": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_tmpl_revision_bound_named_apps"} }, "/pbcs.Config/ListTmplSetBoundUnnamedApps": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_tmpl_set_bound_unnamed_apps"} }, "/pbcs.Config/ListMultiTmplSetBoundUnnamedApps": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_multi_tmpl_set_bound_unnamed_apps"} }, "/pbcs.Config/ListTmplSetBoundNamedApps": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_tmpl_set_bound_named_apps"} }, "/pbcs.Config/ListLatestTmplBoundUnnamedApps": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_latest_tmpl_bound_unnamed_apps"} }, "/pbcs.Config/CreateTemplateVariable": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "create_template_variable"} }, "/pbcs.Config/DeleteTemplateVariable": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "delete_template_variable"} }, "/pbcs.Config/UpdateTemplateVariable": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "update_template_variable"} }, "/pbcs.Config/ListTemplateVariables": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_template_variables"} }, "/pbcs.Config/ImportTemplateVariables": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "import_template_variables"} }, "/pbcs.Config/ExtractAppTmplVariables": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "extract_app_tmpl_variables"} }, "/pbcs.Config/GetAppTmplVariableRefs": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "get_app_tmpl_variable_refs"} }, "/pbcs.Config/GetReleasedAppTmplVariableRefs": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "get_released_app_tmpl_variable_refs"} }, "/pbcs.Config/UpdateAppTmplVariables": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "update_app_tmpl_variables"} }, "/pbcs.Config/ListAppTmplVariables": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "list_app_tmpl_variables"} }, "/pbcs.Config/ListReleasedAppTmplVariables": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "list_released_app_tmpl_variables"} }, "/pbcs.Config/CreateGroup": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "create_group"} }, "/pbcs.Config/DeleteGroup": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "delete_group"} }, "/pbcs.Config/UpdateGroup": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "update_group"} }, "/pbcs.Config/ListAllGroups": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_all_groups"} }, "/pbcs.Config/ListAppGroups": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_app_groups"} }, "/pbcs.Config/ListGroupReleasedApps": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "list_group_released_apps"} }, "/pbcs.Config/GetGroupByName": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Business)}, audit.Action{ActionID: "get_group_by_name"} }, "/pbcs.Config/Publish": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "publish"} }, "/pbcs.Config/GenerateReleaseAndPublish": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "generate_release_and_publish"} }, "/pbcs.Config/CreateCredentials": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.AppCredential)}, audit.Action{ActionID: "create_credentials"} }, "/pbcs.Config/ListCredentials": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.AppCredential)}, audit.Action{ActionID: "list_credentials"} }, "/pbcs.Config/DeleteCredential": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.AppCredential)}, audit.Action{ActionID: "delete_credential"} }, "/pbcs.Config/UpdateCredential": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.AppCredential)}, audit.Action{ActionID: "update_credential"} }, "/pbcs.Config/ListCredentialScopes": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.AppCredential)}, audit.Action{ActionID: "list_credential_scopes"} }, "/pbcs.Config/UpdateCredentialScope": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.AppCredential)}, audit.Action{ActionID: "update_credential_scope"} }, "/pbcs.Config/CreateKv": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "create_kv"} }, "/pbcs.Config/UpdateKv": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "update_kv"} }, "/pbcs.Config/ListKvs": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "list_kvs"} }, "/pbcs.Config/DeleteKv": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "delete_kv"} }, "/pbcs.Config/BatchUpsertKvs": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "batch_upsert_kvs"} }, "/pbcs.Config/UnDeleteKv": func() (audit.Resource, audit.Action) { + // return the resource to be recorded. return audit.Resource{ResourceType: audit.ResourceType(sys.Application)}, audit.Action{ActionID: "undelete_kv"} }, diff --git a/bcs-services/bcs-bscp/pkg/dal/dao/credential.go b/bcs-services/bcs-bscp/pkg/dal/dao/credential.go index eebf7ab695..e2ed54f1ee 100644 --- a/bcs-services/bcs-bscp/pkg/dal/dao/credential.go +++ b/bcs-services/bcs-bscp/pkg/dal/dao/credential.go @@ -255,7 +255,7 @@ func (dao *credentialDao) DeleteWithTx(kit *kit.Kit, tx *gen.QueryTx, bizID, id } eDecorator := dao.event.Eventf(kit) if err = eDecorator.FireWithTx(tx, one); err != nil { - logs.Errorf("fire delete credential: %s event failed, err: %v, rid: %s", id, err, kit.Rid) + logs.Errorf("fire delete credential: %d event failed, err: %v, rid: %s", id, err, kit.Rid) return errors.New("fire event failed, " + err.Error()) } @@ -362,7 +362,7 @@ func (dao *credentialDao) UpdateRevisionWithTx(kit *kit.Kit, tx *gen.QueryTx, bi } eDecorator := dao.event.Eventf(kit) if err = eDecorator.FireWithTx(tx, one); err != nil { - logs.Errorf("fire update credential: %s event failed, err: %v, rid: %s", id, err, kit.Rid) + logs.Errorf("fire update credential: %d event failed, err: %v, rid: %s", id, err, kit.Rid) return errors.New("fire event failed, " + err.Error()) } diff --git a/bcs-services/bcs-bscp/pkg/dal/dao/kv.go b/bcs-services/bcs-bscp/pkg/dal/dao/kv.go index 375965abe9..c409491628 100644 --- a/bcs-services/bcs-bscp/pkg/dal/dao/kv.go +++ b/bcs-services/bcs-bscp/pkg/dal/dao/kv.go @@ -47,7 +47,7 @@ type Kv interface { // BatchUpdateWithTx batch create content instances with transaction. BatchUpdateWithTx(kit *kit.Kit, tx *gen.QueryTx, kvs []*table.Kv) error // ListAllByAppID list all Kv by appID - ListAllByAppID(kit *kit.Kit, appID uint32, bizID uint32, KvState []string) ([]*table.Kv, error) + ListAllByAppID(kit *kit.Kit, appID uint32, bizID uint32, kvState []string) ([]*table.Kv, error) // GetCount bizID config count GetCount(kit *kit.Kit, bizID uint32, appId []uint32) ([]*table.ListConfigItemCounts, error) // UpdateSelectedKVStates updates the states of selected kv pairs using a transaction diff --git a/bcs-services/bcs-bscp/pkg/dal/dao/lock.go b/bcs-services/bcs-bscp/pkg/dal/dao/lock.go index 08f8027647..2eca2f4dfb 100644 --- a/bcs-services/bcs-bscp/pkg/dal/dao/lock.go +++ b/bcs-services/bcs-bscp/pkg/dal/dao/lock.go @@ -95,6 +95,7 @@ func (dao *lockDao) IncreaseCount(kit *kit.Kit, tx *gen.Query, lock *table.Resou lock.ID = id if e := m.WithContext(kit.Ctx).Create(lock); e != nil { + // nolint // TODO: 压测看看并发插入时是否会导致死锁,再如果死锁是否需要重试事务 logs.Errorf("insert lock failed, lock: %v, err: %v, rid: %s", lock, err, kit.Rid) return 0, fmt.Errorf("insert lock failed, err: %v", err) diff --git a/bcs-services/bcs-bscp/pkg/dal/dao/released_hooks.go b/bcs-services/bcs-bscp/pkg/dal/dao/released_hooks.go index c88cde730a..3ad8a73458 100644 --- a/bcs-services/bcs-bscp/pkg/dal/dao/released_hooks.go +++ b/bcs-services/bcs-bscp/pkg/dal/dao/released_hooks.go @@ -281,6 +281,7 @@ func (dao *releasedHookDao) DeleteByHookIDAndReleaseIDWithTx(kit *kit.Kit, tx *g } // DeleteByHookRevisionIDAndReleaseIDWithTx deletes the released hook by hook revision id and release id with tx. +// nolint func (dao *releasedHookDao) DeleteByHookRevisionIDAndReleaseIDWithTx(kit *kit.Kit, tx *gen.QueryTx, bizID, hookID, hookRevisionID, releaseID uint32) error { if bizID == 0 { diff --git a/bcs-services/bcs-bscp/pkg/dal/dao/template_binding_relation.go b/bcs-services/bcs-bscp/pkg/dal/dao/template_binding_relation.go index 47b1978472..4b9589b9b7 100644 --- a/bcs-services/bcs-bscp/pkg/dal/dao/template_binding_relation.go +++ b/bcs-services/bcs-bscp/pkg/dal/dao/template_binding_relation.go @@ -124,6 +124,7 @@ func (dao *templateBindingRelationDao) GetTemplateBoundTemplateSetCount(kit *kit } // GetTemplateRevisionBoundUnnamedAppCount get bound unnamed app count of the target template release. +// nolint func (dao *templateBindingRelationDao) GetTemplateRevisionBoundUnnamedAppCount(kit *kit.Kit, bizID, templateRevisionID uint32) (uint32, error) { m := dao.genQ.AppTemplateBinding @@ -140,6 +141,7 @@ func (dao *templateBindingRelationDao) GetTemplateRevisionBoundUnnamedAppCount(k } // GetTemplateRevisionBoundNamedAppCount get bound named app count of the target template release. +// nolint func (dao *templateBindingRelationDao) GetTemplateRevisionBoundNamedAppCount(kit *kit.Kit, bizID, templateRevisionID uint32) (uint32, error) { m := dao.genQ.ReleasedAppTemplate diff --git a/bcs-services/bcs-bscp/pkg/dal/dao/template_revision.go b/bcs-services/bcs-bscp/pkg/dal/dao/template_revision.go index b9f9183636..21d4724747 100644 --- a/bcs-services/bcs-bscp/pkg/dal/dao/template_revision.go +++ b/bcs-services/bcs-bscp/pkg/dal/dao/template_revision.go @@ -289,6 +289,7 @@ func (dao *templateRevisionDao) BatchCreateWithTx(kit *kit.Kit, tx *gen.QueryTx, } // ListLatestRevisionsGroupByTemplateIds Lists the latest version groups by template ids +// nolint func (dao *templateRevisionDao) ListLatestRevisionsGroupByTemplateIds(kit *kit.Kit, templateIDs []uint32) ([]*table.TemplateRevision, error) { m := dao.genQ.TemplateRevision diff --git a/bcs-services/bcs-bscp/pkg/dal/vault/kv.go b/bcs-services/bcs-bscp/pkg/dal/vault/kv.go index fceaa7425c..edbf167e91 100644 --- a/bcs-services/bcs-bscp/pkg/dal/vault/kv.go +++ b/bcs-services/bcs-bscp/pkg/dal/vault/kv.go @@ -73,7 +73,7 @@ func (s *set) GetLastKv(kit *kit.Kit, opt *types.GetLastKvOpt) (kvType table.Dat return "", "", fmt.Errorf("value type assertion failed, err : %v", err) } - return + return kvType, value, nil } // GetKvByVersion 根据版本获取kv @@ -100,7 +100,7 @@ func (s *set) GetKvByVersion(kit *kit.Kit, opt *types.GetKvByVersion) (kvType ta return "", "", fmt.Errorf("value type assertion failed: err : %v", err) } - return + return kvType, value, nil } diff --git a/bcs-services/bcs-bscp/pkg/dal/vault/released_kv.go b/bcs-services/bcs-bscp/pkg/dal/vault/released_kv.go index 88452f0ca8..293433c48d 100644 --- a/bcs-services/bcs-bscp/pkg/dal/vault/released_kv.go +++ b/bcs-services/bcs-bscp/pkg/dal/vault/released_kv.go @@ -64,5 +64,5 @@ func (s *set) GetRKv(kit *kit.Kit, opt *types.GetRKvOption) (kvType table.DataTy return "", "", fmt.Errorf("value type assertion failed: err : %v", err) } - return + return kvType, value, nil } diff --git a/bcs-services/bcs-bscp/pkg/runtime/credential/scope.go b/bcs-services/bcs-bscp/pkg/runtime/credential/scope.go index 7cad786ea5..d1ee8bebf9 100644 --- a/bcs-services/bcs-bscp/pkg/runtime/credential/scope.go +++ b/bcs-services/bcs-bscp/pkg/runtime/credential/scope.go @@ -48,7 +48,7 @@ func (cs Scope) Split() (app string, scope string, err error) { app = string(cs[:index]) scope = string(cs[index:]) - return + return app, scope, nil } // MatchApp checks if the credential scope matches the app name. diff --git a/bcs-services/bcs-bscp/pkg/types/cache.go b/bcs-services/bcs-bscp/pkg/types/cache.go index 4f57a7c076..3f4f952c66 100644 --- a/bcs-services/bcs-bscp/pkg/types/cache.go +++ b/bcs-services/bcs-bscp/pkg/types/cache.go @@ -126,8 +126,8 @@ type FilePermissionCache struct { type CredentialCache struct { Enabled bool `json:"enabled"` Scope []string `json:"scope"` - scopeMap map[string][]string `json:"-"` // app:scope - isPreprocess bool `json:"-"` + scopeMap map[string][]string `json:"-"` // app:scope nolint + isPreprocess bool `json:"-"` // nolint } // preprocess 预处理数据结构, 格式化为app:scope, 方便鉴权处理 diff --git a/bcs-services/bcs-bscp/test/mock/repo/app/config.go b/bcs-services/bcs-bscp/test/mock/repo/app/config.go index e67d753d51..1c98b3cc73 100644 --- a/bcs-services/bcs-bscp/test/mock/repo/app/config.go +++ b/bcs-services/bcs-bscp/test/mock/repo/app/config.go @@ -181,7 +181,7 @@ func LoadSettings(sys *cc.SysOption) (*Setting, error) { } s := new(Setting) - if err := yaml.Unmarshal(file, s); err != nil { + if err = yaml.Unmarshal(file, s); err != nil { return nil, fmt.Errorf("unmarshal setting yaml from file: %s failed, err: %v", sys.ConfigFiles[0], err) } diff --git a/bcs-services/bcs-cli/bcs-project-manager/pkg/client.go b/bcs-services/bcs-cli/bcs-project-manager/pkg/client.go index 78905ac0a2..8c3187a7a6 100644 --- a/bcs-services/bcs-cli/bcs-project-manager/pkg/client.go +++ b/bcs-services/bcs-cli/bcs-project-manager/pkg/client.go @@ -61,7 +61,7 @@ func NewClientWithConfiguration(ctx context.Context) *ProjectManagerClient { } } -// NewClientWithConfiguration new client with config +// NewClient new client with config func NewClient(ctx context.Context, config *Config) *ProjectManagerClient { return &ProjectManagerClient{ ctx: ctx, diff --git a/bcs-services/bcs-cluster-manager/internal/actions/cluster/list.go b/bcs-services/bcs-cluster-manager/internal/actions/cluster/list.go index 6a49f96a38..f9ef6f2e71 100644 --- a/bcs-services/bcs-cluster-manager/internal/actions/cluster/list.go +++ b/bcs-services/bcs-cluster-manager/internal/actions/cluster/list.go @@ -714,7 +714,7 @@ func (la *ListNodesInClusterAction) Handle(ctx context.Context, func (la *ListNodesInClusterAction) appendCloudNodeInfo() { clsMgr, err := cloudprovider.GetClusterMgr(la.cloud.CloudProvider) if err != nil { - blog.Errorf("ListNodesInClusterAction[%s] GetClusterMgr failed, %s", la.cluster.ClusterID, + blog.Errorf("ListNodesInClusterAction[%s] %s GetClusterMgr failed, %s", la.cluster.ClusterID, la.cloud.CloudProvider, err.Error()) return } @@ -734,8 +734,6 @@ func (la *ListNodesInClusterAction) appendCloudNodeInfo() { blog.Errorf("ListNodesInClusterAction[%s] AppendCloudNodeInfo failed: %v", la.cluster.ClusterID, err) return } - - return } // nolint diff --git a/bcs-services/bcs-cluster-manager/internal/actions/cluster/update.go b/bcs-services/bcs-cluster-manager/internal/actions/cluster/update.go index 0f8116ff2d..5a20ab003b 100644 --- a/bcs-services/bcs-cluster-manager/internal/actions/cluster/update.go +++ b/bcs-services/bcs-cluster-manager/internal/actions/cluster/update.go @@ -208,7 +208,7 @@ func (ua *UpdateAction) updateCluster() error { ua.cluster.Master = make(map[string]*cmproto.Node) for _, ip := range ua.req.Master { - node, err := ua.transNodeIPToCloudNode(ip) + node, err := ua.transNodeIPToCloudNode(ip) // nolint if err != nil { blog.Errorf("updateCluster transNodeIPToCloudNode failed: %v", err) ua.cluster.Master[ip] = &cmproto.Node{ diff --git a/bcs-services/bcs-cluster-manager/internal/actions/cluster/update_module.go b/bcs-services/bcs-cluster-manager/internal/actions/cluster/update_module.go index 28df129b4d..b5887fab98 100644 --- a/bcs-services/bcs-cluster-manager/internal/actions/cluster/update_module.go +++ b/bcs-services/bcs-cluster-manager/internal/actions/cluster/update_module.go @@ -4,7 +4,7 @@ * 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, + * 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. @@ -17,6 +17,7 @@ import ( "time" "github.com/Tencent/bk-bcs/bcs-common/common/blog" + cmproto "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/common" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/store" diff --git a/bcs-services/bcs-cluster-manager/internal/actions/cluster/utils.go b/bcs-services/bcs-cluster-manager/internal/actions/cluster/utils.go index 74816500f5..6ba68a267a 100644 --- a/bcs-services/bcs-cluster-manager/internal/actions/cluster/utils.go +++ b/bcs-services/bcs-cluster-manager/internal/actions/cluster/utils.go @@ -772,8 +772,6 @@ func updateClusterModule(cluster *proto.Cluster, category, moduleID, moduleName cluster.GetClusterBasicSettings().GetModule().WorkerModuleName = cloudprovider.GetModuleName(bkBizID, bkModuleID) default: } - - return } func updateAutoScalingModule(cluster *proto.Cluster, option *proto.ClusterAutoScalingOption, @@ -794,8 +792,6 @@ func updateAutoScalingModule(cluster *proto.Cluster, option *proto.ClusterAutoSc } else { option.Module.ScaleOutModuleName = cloudprovider.GetModuleName(bkBizID, bkModuleID) } - - return } func transClusterNodes(model store.ClusterManagerModel, cluster *proto.Cluster, category, moduleID string) error { @@ -830,7 +826,7 @@ func transClusterNodes(model store.ClusterManagerModel, cluster *proto.Cluster, blog.Errorf("transClusterNodes[%s] nodeIps empty", cluster.ClusterID) return nil } - + err = provider.TransBizNodeModule(context.Background(), bkBizID, bkModuleID, nodeIps) if err != nil { blog.Errorf("transClusterNodes[%s] TransBizNodeModule failed: %v", cluster.ClusterID, err) diff --git a/bcs-services/bcs-cluster-manager/internal/actions/nodegroup/create.go b/bcs-services/bcs-cluster-manager/internal/actions/nodegroup/create.go index fa772c334d..1a71b445dc 100644 --- a/bcs-services/bcs-cluster-manager/internal/actions/nodegroup/create.go +++ b/bcs-services/bcs-cluster-manager/internal/actions/nodegroup/create.go @@ -98,10 +98,10 @@ func (ca *CreateAction) constructNodeGroup() *cmproto.NodeGroup { Creator: ca.req.Creator, CreateTime: timeStr, UpdateTime: timeStr, - //Area: &cmproto.CloudArea{ + // Area: &cmproto.CloudArea{ // BkCloudID: ca.req.BkCloudID, // BkCloudName: ca.req.CloudAreaName, - //}, + // }, NodeGroupType: func() string { // default cloud nodePool _, ok := common.NodeGroupTypeMap[common.NodeGroupType(ca.req.NodeGroupType)] diff --git a/bcs-services/bcs-cluster-manager/internal/actions/task/skip.go b/bcs-services/bcs-cluster-manager/internal/actions/task/skip.go index a424f4755b..268382b459 100644 --- a/bcs-services/bcs-cluster-manager/internal/actions/task/skip.go +++ b/bcs-services/bcs-cluster-manager/internal/actions/task/skip.go @@ -4,7 +4,7 @@ * 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, + * 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. @@ -17,6 +17,7 @@ import ( "fmt" "github.com/Tencent/bk-bcs/bcs-common/common/blog" + cmproto "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/actions/utils" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/cloudprovider" diff --git a/bcs-services/bcs-cluster-manager/internal/actions/task/utils.go b/bcs-services/bcs-cluster-manager/internal/actions/task/utils.go index 1ca88b2cd2..fc4c2e563f 100644 --- a/bcs-services/bcs-cluster-manager/internal/actions/task/utils.go +++ b/bcs-services/bcs-cluster-manager/internal/actions/task/utils.go @@ -39,7 +39,7 @@ func updateTaskDataStatus(model store.ClusterManagerModel, task *proto.Task) err strings.Contains(task.TaskType, cloudprovider.DeleteVirtualCluster.String()): err = updateClusterStatus(model, task.ClusterID, common.StatusDeleting) case strings.Contains(task.TaskType, cloudprovider.AddNodesToCluster.String()): - //err = updateNodeStatus(ua.model, ua.task.NodeIPList, common.StatusInitialization) + // err = updateNodeStatus(ua.model, ua.task.NodeIPList, common.StatusInitialization) err = updateNodeStatus(model, cloudprovider.ParseNodeIpOrIdFromCommonMap(task.CommonParams, cloudprovider.NodeIPsKey.String(), ","), common.StatusInitialization) case strings.Contains(task.TaskType, cloudprovider.RemoveNodesFromCluster.String()): diff --git a/bcs-services/bcs-cluster-manager/internal/actions/thirdparty/cc.go b/bcs-services/bcs-cluster-manager/internal/actions/thirdparty/cc.go index 3ab5c42f89..20eb963d43 100644 --- a/bcs-services/bcs-cluster-manager/internal/actions/thirdparty/cc.go +++ b/bcs-services/bcs-cluster-manager/internal/actions/thirdparty/cc.go @@ -65,7 +65,7 @@ func (la *ListCCTopologyAction) filterInter() bool { } func (la *ListCCTopologyAction) listTopology() error { - var bizID = "" + var bizID string cluster, err := la.model.GetCluster(la.ctx, la.req.ClusterID) if err == nil { bizID = cluster.BusinessID diff --git a/bcs-services/bcs-cluster-manager/internal/cloudprovider/azure/cluster.go b/bcs-services/bcs-cluster-manager/internal/cloudprovider/azure/cluster.go index 883b73434b..eee260bd2c 100644 --- a/bcs-services/bcs-cluster-manager/internal/cloudprovider/azure/cluster.go +++ b/bcs-services/bcs-cluster-manager/internal/cloudprovider/azure/cluster.go @@ -184,4 +184,3 @@ func (c *Cluster) CheckIfGetNodesFromCluster(ctx context.Context, cluster *proto nodes []*proto.ClusterNode) bool { return true } - diff --git a/bcs-services/bcs-cluster-manager/internal/cloudprovider/blueking/cluster.go b/bcs-services/bcs-cluster-manager/internal/cloudprovider/blueking/cluster.go index 6858ed8627..ee10287de0 100644 --- a/bcs-services/bcs-cluster-manager/internal/cloudprovider/blueking/cluster.go +++ b/bcs-services/bcs-cluster-manager/internal/cloudprovider/blueking/cluster.go @@ -275,4 +275,3 @@ func (c *Cluster) CheckIfGetNodesFromCluster(ctx context.Context, cluster *proto nodes []*proto.ClusterNode) bool { return true } - diff --git a/bcs-services/bcs-cluster-manager/internal/cloudprovider/common/agent.go b/bcs-services/bcs-cluster-manager/internal/cloudprovider/common/agent.go index a3a3ed8ede..b66761a64f 100644 --- a/bcs-services/bcs-cluster-manager/internal/cloudprovider/common/agent.go +++ b/bcs-services/bcs-cluster-manager/internal/cloudprovider/common/agent.go @@ -57,8 +57,8 @@ type GseInstallInfo struct { func BuildInstallGseAgentTaskStep(task *proto.Task, gseInfo *GseInstallInfo, options ...cloudprovider.StepOption) { installGseStep := cloudprovider.InitTaskStep(installGseAgentStep, options...) - installGseStep.Params[cloudprovider.ClusterIDKey.String()] = gseInfo.ClusterId - installGseStep.Params[cloudprovider.NodeGroupIDKey.String()] = gseInfo.NodeGroupId + installGseStep.Params[cloudprovider.ClusterIDKey.String()] = gseInfo.ClusterId // nolint + installGseStep.Params[cloudprovider.NodeGroupIDKey.String()] = gseInfo.NodeGroupId // nolint installGseStep.Params[cloudprovider.BKBizIDKey.String()] = gseInfo.BusinessId // nolint if gseInfo != nil && gseInfo.CloudArea != nil { // nolint diff --git a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/business/network.go b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/business/network.go index 3fb52457dc..1ee676b032 100644 --- a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/business/network.go +++ b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/business/network.go @@ -164,7 +164,7 @@ func AllocateClusterVpcCniSubnets(ctx context.Context, clusterId, vpcId string, subnetIDs := make([]string, 0) for i := range subnets { - mask := 0 + mask := 0 // nolint if subnets[i].Mask > 0 { mask = int(subnets[i].Mask) } else if subnets[i].IpCnt > 0 { diff --git a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/business/tke.go b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/business/tke.go index 1aef5ccb7f..80f5774100 100644 --- a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/business/tke.go +++ b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/business/tke.go @@ -918,6 +918,7 @@ func CheckClusterInstanceStatus(ctx context.Context, info *cloudprovider.CloudDe } // CheckClusterAllInstanceStatus 检测集群所有节点状态 +// nolint func CheckClusterAllInstanceStatus(ctx context.Context, info *cloudprovider.CloudDependBasicInfo) ([]InstanceInfo, []InstanceInfo, error) { taskID := cloudprovider.GetTaskIDFromContext(ctx) diff --git a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/business/utils.go b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/business/utils.go index f6e8578445..b525e30c2d 100644 --- a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/business/utils.go +++ b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/business/utils.go @@ -30,5 +30,5 @@ func GetMasterNodeTemplateConfig(instances []*proto.InstanceTemplateConfig) ( } } - return + return master, nodes } diff --git a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/clustermgr.go b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/clustermgr.go index b4320da7b3..ad76f37bfd 100644 --- a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/clustermgr.go +++ b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/clustermgr.go @@ -20,10 +20,10 @@ import ( "sync" "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/i18n" "github.com/avast/retry-go" tke "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/tke/v20180525" - "github.com/Tencent/bk-bcs/bcs-common/pkg/i18n" proto "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/cloudprovider" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/business" @@ -64,6 +64,7 @@ func (c *Cluster) CreateCluster(cls *proto.Cluster, opt *cloudprovider.CreateClu return nil, fmt.Errorf("%s CreateCluster opt lost valid crendential info", cloudName) } + // GetTaskManager for nodegroup manager initialization mgr, err := cloudprovider.GetTaskManager(opt.Cloud.CloudProvider) if err != nil { blog.Errorf("get cloud %s TaskManager when CreateCluster %d failed, %s", @@ -99,6 +100,7 @@ func (c *Cluster) CreateVirtualCluster(cls *proto.Cluster, return nil, fmt.Errorf("%s CreateVirtualCluster lost credential info", cloudName) } + // GetTaskManager for nodegroup manager initialization mgr, err := cloudprovider.GetTaskManager(opt.Cloud.CloudProvider) if err != nil { blog.Errorf("get cloud %s TaskManager when CreateVirtualCluster %d failed, %s", @@ -134,6 +136,7 @@ func (c *Cluster) DeleteVirtualCluster(cls *proto.Cluster, return nil, fmt.Errorf("%s DeleteVirtualCluster lost credential info", cloudName) } + // GetTaskManager for nodegroup manager initialization mgr, err := cloudprovider.GetTaskManager(opt.Cloud.CloudProvider) if err != nil { blog.Errorf("get cloud %s TaskManager when DeleteVirtualCluster %d failed, %s", @@ -169,6 +172,7 @@ func (c *Cluster) ImportCluster(cls *proto.Cluster, opt *cloudprovider.ImportClu return nil, fmt.Errorf("%s CreateCluster opt lost valid crendential info", cloudName) } + // GetTaskManager for nodegroup manager initialization mgr, err := cloudprovider.GetTaskManager(opt.Cloud.CloudProvider) if err != nil { blog.Errorf("get cloud %s TaskManager when ImportCluster %d failed, %s", @@ -177,6 +181,7 @@ func (c *Cluster) ImportCluster(cls *proto.Cluster, opt *cloudprovider.ImportClu return nil, err } + // get tke cluster masterIPs && nodeIPs _, nodeIPs, err := getClusterInstancesByClusterID(cls.SystemID, &opt.CommonOption) if err != nil { blog.Errorf("get cloud/cluster %s/%s nodes when ImportCluster %d failed, %s", @@ -206,6 +211,7 @@ func getClusterInstancesByClusterID(clusterID string, option *cloudprovider.Comm return nil, nil, err } + // QueryTkeClusterAllInstances query all cluster instances instancesList, err := tkeCli.QueryTkeClusterAllInstances(context.Background(), clusterID, nil) if err != nil { return nil, nil, err @@ -239,6 +245,7 @@ func (c *Cluster) DeleteCluster(cls *proto.Cluster, opt *cloudprovider.DeleteClu return nil, fmt.Errorf("%s DeleteCluster cluster lost oprion", cloudName) } + // GetTaskManager for nodegroup manager initialization mgr, err := cloudprovider.GetTaskManager(opt.Cloud.CloudProvider) if err != nil { blog.Errorf("get cloud %s TaskManager when DeleteCluster %d failed, %s", @@ -278,6 +285,7 @@ func getCloudCluster(cloudID string, opt *cloudprovider.CommonOption) (*tke.Clus blog.Errorf("%s getCloudCluster NewTkeClient failed: %v", cloudName, err) return nil, err } + // GetTKECluster get tke cluster info cls, err := cli.GetTKECluster(cloudID) if err != nil { blog.Errorf("%s getCloudCluster GetTKECluster failed: %v", cloudName, err) @@ -303,6 +311,7 @@ func checkClusterOsNameInWhiteImages(cls *proto.Cluster, opt *cloudprovider.Comm // osName maybe is imageID if osName != "" { nodeMgr := &NodeManager{} + // GetImageInfoByImageID get image by image image, errGet := nodeMgr.GetImageInfoByImageID(osName, opt) if errGet != nil { blog.Errorf("%s checkClusterOsNameInWhiteImages GetImageInfoByImageID failed: %v", cloudName, errGet) @@ -359,6 +368,7 @@ func checkIfWhiteImageOsNames(opt *cloudprovider.ClusterGroupOption) bool { return utils.StringInSlice(osName, utils.WhiteImageOsName) } +// update ClusterInfo func updateClusterInfo(cloudID string, opt *cloudprovider.GetClusterOption) (*proto.Cluster, error) { cls, err := getCloudCluster(cloudID, &opt.CommonOption) if err != nil { @@ -419,6 +429,7 @@ func (c *Cluster) ListCluster(opt *cloudprovider.ListClusterOption) ([]*proto.Cl return transTKEClusterToCloudCluster(opt.Region, tkeClusters), nil } +// trans TKEClusterToCloudCluster func transTKEClusterToCloudCluster(region string, clusters []*tke.Cluster) []*proto.CloudClusterInfo { cloudClusterList := make([]*proto.CloudClusterInfo, 0) for _, cls := range clusters { diff --git a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/tasks/createClusterTask.go b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/tasks/createClusterTask.go index be0c2fc0f5..463d315e18 100644 --- a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/tasks/createClusterTask.go +++ b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/tasks/createClusterTask.go @@ -16,13 +16,13 @@ import ( "context" "encoding/json" "fmt" - "github.com/avast/retry-go" "math/rand" "strconv" "strings" "time" "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/avast/retry-go" "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common" cvm "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm/v20170312" @@ -215,11 +215,13 @@ func handleClusterMasterNodes(ctx context.Context, req *api.CreateClusterRequest // generateMasterExistedInstance cluster master setting func generateMasterExistedInstance(role string, instanceIDs []string, manyDisk bool, cls *proto.Cluster) *api.ExistedInstancesForNode { + // ExistedInstancesForNode use existed nodes for create cluster or add node existedInstance := &api.ExistedInstancesForNode{ NodeRole: role, ExistedInstancesPara: &api.ExistedInstancesPara{ InstanceIDs: instanceIDs, LoginSettings: func() *api.LoginSettings { + // LoginSettings reset passwd return &api.LoginSettings{ Password: func() string { if len(cls.GetNodeSettings().GetMasterLogin().InitLoginPassword) > 0 { @@ -302,11 +304,13 @@ func handleClusterWorkerNodes(ctx context.Context, req *api.CreateClusterRequest // generateWorkerExistedInstance cluster worker setting func generateWorkerExistedInstance(info *cloudprovider.CloudDependBasicInfo, nodeIDs, nodeIPs []string, manyDisk bool, operator string) *api.ExistedInstancesForNode { + // ExistedInstancesForNode use existed nodes for create cluster or add node existedInstance := &api.ExistedInstancesForNode{ NodeRole: api.WORKER.String(), ExistedInstancesPara: &api.ExistedInstancesPara{ InstanceIDs: nodeIDs, LoginSettings: func() *api.LoginSettings { + // LoginSettings reset passwd return &api.LoginSettings{ Password: func() string { if len(info.Cluster.GetNodeSettings().GetWorkerLogin().InitLoginPassword) > 0 { @@ -620,6 +624,7 @@ func generateCreateClusterRequest(ctx context.Context, info *cloudprovider.Cloud blog.Errorf("generateIndependentClusterRequest[%s] trans2InsIdByInsIp masterIps failed: %v", taskID, err) return nil, err } + // handleClusterMasterNodes handle cluster master nodes err = handleClusterMasterNodes(ctx, req, info, masterIds) if err != nil { blog.Errorf("createTkeCluster[%s] handleClusterMasterNodes for cluster[%s] failed: %v", @@ -635,6 +640,7 @@ func generateCreateClusterRequest(ctx context.Context, info *cloudprovider.Cloud return nil, err } + // handleClusterWorkerNodes handle cluster worker nodes err = handleClusterWorkerNodes(ctx, req, info, workerIds, operator) if err != nil { blog.Errorf("createTkeCluster[%s] handleClusterWorkerNodes for cluster[%s] failed: %v", @@ -645,6 +651,7 @@ func generateCreateClusterRequest(ctx context.Context, info *cloudprovider.Cloud case icommon.ClusterManageTypeManaged: // 新增节点模式 if req.AddNodeMode { + // GetMasterNodeTemplateConfig masters/nodes _, workerNodesTpl := business.GetMasterNodeTemplateConfig(info.Cluster.Template) // worker nodes @@ -655,6 +662,7 @@ func generateCreateClusterRequest(ctx context.Context, info *cloudprovider.Cloud req.InstanceDataDiskMountSettings = make([]*api.InstanceDataDiskMountSetting, 0) } + // generateNewRunInstance run instances by instance template req.InstanceDataDiskMountSettings = generateNewInstanceForDisk(workerNodesTpl) return req, nil @@ -686,6 +694,7 @@ func generateCreateClusterRequest(ctx context.Context, info *cloudprovider.Cloud return req, nil } +// trans2InsIdByInsIp xxx func trans2InsIdByInsIp(ips []string, opt *cloudprovider.CommonOption) ([]string, error) { nodes, err := business.ListNodesByIP(ips, &cloudprovider.ListNodesOption{ Common: opt, @@ -1156,8 +1165,9 @@ func RegisterTkeClusterKubeConfigTask(taskID string, stepName string) error { // _ = state.UpdateStepFailure(start, stepName, retErr) step.Params[cloudprovider.ConnectClusterKey.String()] = icommon.True - _ = cloudprovider.UpdateClusterErrMessage(clusterID, fmt.Sprintf("RegisterClusterEndpointErr: register endpoint[%s] failed", - dependInfo.Cluster.GetSystemID())) + _ = cloudprovider.UpdateClusterErrMessage(clusterID, + fmt.Sprintf("RegisterClusterEndpointErr: register endpoint[%s] failed", + dependInfo.Cluster.GetSystemID())) return retErr } blog.Infof("RegisterTkeClusterKubeConfigTask[%s] registerTKEClusterEndpoint success", taskID) diff --git a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/tasks/deleteClusterTask.go b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/tasks/deleteClusterTask.go index 1a8c4121db..63f40b03d5 100644 --- a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/tasks/deleteClusterTask.go +++ b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/tasks/deleteClusterTask.go @@ -78,6 +78,7 @@ func DeleteTKEClusterTask(taskID string, stepName string) error { nodeIds = append(nodeIds, workerNodes[i].InstanceId) } + // nolint ids, err := business.DeleteClusterInstance(ctx, dependInfo, cloudprovider.Retain.String(), nodeIds) if err != nil { blog.Errorf("DeleteTKEClusterTask[%s] DeleteClusterInstance failed: %v", taskID, err) diff --git a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/tasks/utils.go b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/tasks/utils.go index 3d60f90dd9..08c27b600e 100644 --- a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/tasks/utils.go +++ b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/tasks/utils.go @@ -27,6 +27,7 @@ import ( ) // updateClusterSystemID set cluster systemID +// nolint func updateClusterSystemID(clusterID string, systemID string) error { cluster, err := cloudprovider.GetStorageModel().GetCluster(context.Background(), clusterID) if err != nil { diff --git a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/vpcmgr.go b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/vpcmgr.go index 5f39baec4a..8c8ed2cadb 100644 --- a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/vpcmgr.go +++ b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud-public/vpcmgr.go @@ -79,14 +79,14 @@ func (c *VPCManager) ListVpcs(vpcID string, opt *cloudprovider.CommonOption) ([] // get ip number freeIPNets, err := business.GetFreeIPNets(opt, vpcID) if err != nil { - blog.Errorf("vpc[%s] GetFreeIPNets failed: %v", err) + blog.Errorf("vpc GetFreeIPNets failed: %v", err) continue } var ipCnt uint32 for i := range freeIPNets { ipNum, err := cidrtree.GetIPNum(freeIPNets[i]) if err != nil { - blog.Errorf("vpc[%s] GetIPNum failed: %v", err) + blog.Errorf("vpc GetIPNum failed: %v", err) continue } ipCnt += ipNum 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 f1f2119f42..367d2cead9 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 @@ -879,4 +879,3 @@ func DeleteTkeClusterByClusterId(ctx context.Context, opt *cloudprovider.CommonO return nil } - diff --git a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud/clustermgr.go b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud/clustermgr.go index 5eb3ee3af2..acd3d28320 100644 --- a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud/clustermgr.go +++ b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud/clustermgr.go @@ -19,10 +19,10 @@ import ( "sync" "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/i18n" "github.com/avast/retry-go" tke "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/tke/v20180525" - "github.com/Tencent/bk-bcs/bcs-common/pkg/i18n" proto "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/cloudprovider" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud/api" diff --git a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud/tasks/addNodeToCluster.go b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud/tasks/addNodeToCluster.go index 8817c85c6f..bc6b011a5c 100644 --- a/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud/tasks/addNodeToCluster.go +++ b/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud/tasks/addNodeToCluster.go @@ -79,7 +79,7 @@ func ModifyInstancesVpcTask(taskID string, stepName string) error { // update step if err := state.UpdateStepSucc(start, stepName); err != nil { - blog.Errorf("ModifyInstancesVpcTask[%s] update to storage fatal", taskID, stepName) + blog.Errorf("ModifyInstancesVpcTask[%s] update to storage fatal: %s", taskID, stepName) return err } return nil @@ -152,7 +152,7 @@ func CheckInstanceStateTask(taskID string, stepName string) error { // update step if err := state.UpdateStepSucc(start, stepName); err != nil { - blog.Errorf("CheckCvmInstanceState[%s] update to storage fatal", taskID, stepName) + blog.Errorf("CheckCvmInstanceState[%s] update to storage fatal: %s", taskID, stepName) return err } return nil diff --git a/bcs-services/bcs-cluster-manager/internal/daemon/cluster_helath.go b/bcs-services/bcs-cluster-manager/internal/daemon/cluster_helath.go index 0cbddd5674..e3e3e787f9 100644 --- a/bcs-services/bcs-cluster-manager/internal/daemon/cluster_helath.go +++ b/bcs-services/bcs-cluster-manager/internal/daemon/cluster_helath.go @@ -65,6 +65,7 @@ func (d *Daemon) reportClusterHealthStatus(error chan<- error) { concurency.Wait() } +// nolint func (d *Daemon) updateClusterStatus(clusterId, status string) error { cluster, err := d.model.GetCluster(d.ctx, clusterId) if err != nil { diff --git a/bcs-services/bcs-cluster-manager/internal/remote/cidrtree/cidr.go b/bcs-services/bcs-cluster-manager/internal/remote/cidrtree/cidr.go index edcd70eff1..759ec7246f 100644 --- a/bcs-services/bcs-cluster-manager/internal/remote/cidrtree/cidr.go +++ b/bcs-services/bcs-cluster-manager/internal/remote/cidrtree/cidr.go @@ -94,11 +94,13 @@ type cidrTree struct { } // New create a new cidrTree +// nolint func New(cidrBlock *net.IPNet) *cidrTree { return &cidrTree{nil, &node{cidrBlock, NODE_UNUSED}, nil} } // Insert node to cidrTree +// nolint func Insert(t *cidrTree, subnet *net.IPNet) *cidrTree { if cidr.VerifyNoOverlap([]*net.IPNet{subnet}, t.Value.IPNet) != nil { return t diff --git a/bcs-services/bcs-cluster-manager/internal/remote/cidrtree/interface.go b/bcs-services/bcs-cluster-manager/internal/remote/cidrtree/interface.go index 9f3ed0f3f8..0fb83f3ade 100644 --- a/bcs-services/bcs-cluster-manager/internal/remote/cidrtree/interface.go +++ b/bcs-services/bcs-cluster-manager/internal/remote/cidrtree/interface.go @@ -50,5 +50,5 @@ func (c *Cidr) GetIPNum() (ipnum uint32, err error) { return } ipnum = uint32(math.Pow(2, float64(totalSize-prefixSize))) - return + return ipnum, nil } diff --git a/bcs-services/bcs-cluster-manager/internal/remote/cidrtree/utils.go b/bcs-services/bcs-cluster-manager/internal/remote/cidrtree/utils.go index 14d7c92ff7..042bbc56ca 100644 --- a/bcs-services/bcs-cluster-manager/internal/remote/cidrtree/utils.go +++ b/bcs-services/bcs-cluster-manager/internal/remote/cidrtree/utils.go @@ -110,5 +110,5 @@ func GetIPNum(ipnet *net.IPNet) (ipnum uint32, err error) { return } ipnum = uint32(math.Pow(2, float64(totalSize-prefixSize))) - return + return ipnum, nil } diff --git a/bcs-services/bcs-cluster-manager/internal/remote/nodeman/client_test.go b/bcs-services/bcs-cluster-manager/internal/remote/nodeman/client_test.go index 4c573d9996..2201444b78 100644 --- a/bcs-services/bcs-cluster-manager/internal/remote/nodeman/client_test.go +++ b/bcs-services/bcs-cluster-manager/internal/remote/nodeman/client_test.go @@ -12,7 +12,10 @@ package nodeman -import "testing" +import ( + "context" + "testing" +) // NewClient xxx func NewClient() *Client { @@ -29,7 +32,7 @@ func NewClient() *Client { func TestClient_CloudList(t *testing.T) { cli := NewClient() - cloudAreas, err := cli.CloudList() + cloudAreas, err := cli.CloudList(context.Background()) if err != nil { t.Fatal(err) } diff --git a/bcs-services/bcs-cluster-manager/internal/utils/audit.go b/bcs-services/bcs-cluster-manager/internal/utils/audit.go index 13971c7ecb..cae4668c68 100644 --- a/bcs-services/bcs-cluster-manager/internal/utils/audit.go +++ b/bcs-services/bcs-cluster-manager/internal/utils/audit.go @@ -33,6 +33,7 @@ import ( "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/types" ) +// resource 资源相关信息 type resource struct { BusinessID string `json:"businessID" yaml:"businessID"` // 业务ID ProjectID string `json:"projectID" yaml:"projectID"` // 项目ID @@ -101,6 +102,7 @@ func getResourceID(req server.Request) resource { var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.Resource, audit.Action){ "ClusterManager.CreateCluster": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.ClusterName, ResourceName: res.ClusterName, ResourceData: res.toMap(), @@ -109,6 +111,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.RetryCreateClusterTask": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.ClusterID, ResourceName: res.ClusterID, ResourceData: res.toMap(), @@ -117,6 +120,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.ImportCluster": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.ClusterName, ResourceName: res.ClusterName, ResourceData: res.toMap(), @@ -125,6 +129,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.UpdateCluster": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.ClusterID, ResourceName: res.ClusterID, ResourceData: res.toMap(), @@ -133,6 +138,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.DeleteCluster": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.ClusterID, ResourceName: res.ClusterID, ResourceData: res.toMap(), @@ -141,6 +147,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.AddNodesToCluster": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.ClusterID, ResourceName: res.ClusterID, ResourceData: res.toMap(), @@ -149,6 +156,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.DeleteNodesFromCluster": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.ClusterID, ResourceName: res.ClusterID, ResourceData: res.toMap(), @@ -157,6 +165,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.BatchDeleteNodesFromCluster": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.ClusterID, ResourceName: res.ClusterID, ResourceData: res.toMap(), @@ -165,6 +174,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.CreateNodeGroup": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -173,6 +183,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.UpdateNodeGroup": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.NodeGroupID, ResourceName: res.NodeGroupID, ResourceData: res.toMap(), @@ -181,6 +192,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.DeleteNodeGroup": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.NodeGroupID, ResourceName: res.NodeGroupID, ResourceData: res.toMap(), @@ -189,6 +201,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.RemoveNodesFromGroup": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.NodeGroupID, ResourceName: res.NodeGroupID, ResourceData: res.toMap(), @@ -197,6 +210,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.CleanNodesInGroup": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.NodeGroupID, ResourceName: res.NodeGroupID, ResourceData: res.toMap(), @@ -205,6 +219,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.CleanNodesInGroupV2": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.NodeGroupID, ResourceName: res.NodeGroupID, ResourceData: res.toMap(), @@ -213,6 +228,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.EnableNodeGroupAutoScale": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.NodeGroupID, ResourceName: res.NodeGroupID, ResourceData: res.toMap(), @@ -221,6 +237,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.DisableNodeGroupAutoScale": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.NodeGroupID, ResourceName: res.NodeGroupID, ResourceData: res.toMap(), @@ -229,6 +246,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.CreateNodeTemplate": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -237,6 +255,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.UpdateNodeTemplate": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.NodeTemplateID, ResourceName: res.NodeTemplateID, ResourceData: res.toMap(), @@ -245,6 +264,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.DeleteNodeTemplate": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.NodeTemplateID, ResourceName: res.NodeTemplateID, ResourceData: res.toMap(), @@ -253,6 +273,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.CreateCloudAccount": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.AccountName, ResourceName: res.AccountName, ResourceData: res.toMap(), @@ -261,6 +282,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.UpdateCloudAccount": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.AccountID, ResourceName: res.AccountID, ResourceData: res.toMap(), @@ -269,6 +291,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, "ClusterManager.DeleteCloudAccount": func(req server.Request, rsp interface{}) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded. return audit.Resource{ ResourceType: audit.ResourceTypeCluster, ResourceID: res.AccountID, ResourceName: res.AccountID, ResourceData: res.toMap(), @@ -277,6 +300,7 @@ var auditFuncMap = map[string]func(req server.Request, rsp interface{}) (audit.R }, } +// addAudit 添加审计 func addAudit(ctx context.Context, req server.Request, rsp interface{}, startTime, endTime time.Time) { // get method audit func fn, ok := auditFuncMap[req.Method()] diff --git a/bcs-services/bcs-cluster-reporter/cmd/options/options.go b/bcs-services/bcs-cluster-reporter/cmd/options/options.go index fcf386aace..26692f405f 100644 --- a/bcs-services/bcs-cluster-reporter/cmd/options/options.go +++ b/bcs-services/bcs-cluster-reporter/cmd/options/options.go @@ -10,7 +10,7 @@ * limitations under the License. */ -// Package options +// Package options xxx package options import ( diff --git a/bcs-services/bcs-cluster-reporter/cmd/root.go b/bcs-services/bcs-cluster-reporter/cmd/root.go index 4bb6f0b1b2..7cabc9759a 100644 --- a/bcs-services/bcs-cluster-reporter/cmd/root.go +++ b/bcs-services/bcs-cluster-reporter/cmd/root.go @@ -10,7 +10,7 @@ * limitations under the License. */ -// Package cmd +// Package cmd xxx package cmd import ( @@ -52,7 +52,7 @@ var ( Long: ` Basic Commands (Beginner): Get Create a resource from a file or from stdin -`, +`, // nolint Run: func(cmd *cobra.Command, args []string) { CheckErr(Complete(cmd, args)) metric_manager.MM.RunPrometheusMetricsServer() @@ -117,7 +117,7 @@ func Run() error { OnStoppedLeading: func() { klog.Infof("leader lost: %s", id) cancel() - ctx, cancel = context.WithCancel(context.Background()) + ctx, cancel = context.WithCancel(context.Background()) // nolint }, }, }) @@ -192,10 +192,9 @@ func Complete(cmd *cobra.Command, args []string) error { bcro.BcsGatewayToken == "" { return fmt.Errorf( "bcs config missing, BcsClusterManagerToken, BcsClusterManagerApiserver, BcsGatewayApiserver, BcsGatewayToken must be set") - } else { - bcro.BcsClusterManagerToken = util.Decode(bcro.BcsClusterManagerToken) - bcro.BcsGatewayToken = util.Decode(bcro.BcsGatewayToken) } + bcro.BcsClusterManagerToken = util.Decode(bcro.BcsClusterManagerToken) + bcro.BcsGatewayToken = util.Decode(bcro.BcsGatewayToken) } if (bcro.BcsGatewayApiserver != "" && bcro.BcsClusterManagerApiserver != "" && bcro.BcsGatewayToken != "" && @@ -274,7 +273,7 @@ func getClusters() { } else { if len(cluster.Master) > 0 { continueFlag := false - for masterName, _ := range cluster.Master { + for masterName := range cluster.Master { if strings.Contains(masterName, "127.0.0") { // 跳过算力集群 continueFlag = true diff --git a/bcs-services/bcs-cluster-reporter/internal/api/bcs/cluster.go b/bcs-services/bcs-cluster-reporter/internal/api/bcs/cluster.go index 650a652db9..5163fce4cb 100644 --- a/bcs-services/bcs-cluster-reporter/internal/api/bcs/cluster.go +++ b/bcs-services/bcs-cluster-reporter/internal/api/bcs/cluster.go @@ -10,7 +10,7 @@ * limitations under the License. */ -// Package bcs +// Package bcs xxx package bcs import ( @@ -65,7 +65,7 @@ func (cm *ClusterManager) GetClusters(clusterIds []string) ([]cmproto.Cluster, e } if !result.Result { - e := errors.New(fmt.Sprintf("cluster response result failed: %s", result.Msg)) + e := fmt.Errorf("cluster response result failed: %s", result.Msg) klog.V(3).Info(e.Error()) return nil, e } @@ -77,12 +77,11 @@ func (cm *ClusterManager) GetClusters(clusterIds []string) ([]cmproto.Cluster, e cluster := cmproto.Cluster{} err = json.Unmarshal(clusterData, &cluster) if err != nil { - e := errors.New(fmt.Sprintf("Unmarshal cluster response failed %s", err.Error())) + e := fmt.Errorf("unmarshal cluster response failed %s", err.Error()) klog.V(3).Info(e.Error()) return nil, e - } else { - clusterList = append(clusterList, cluster) } + clusterList = append(clusterList, cluster) } resultList = append(resultList, clusterList...) } @@ -118,7 +117,7 @@ func (cm *ClusterManager) GetNodesByClusterId(clusterId string) ([]cmproto.Node, } if !result.Result { - e := errors.New(fmt.Sprintf("cluster response result failed: %s", result.Msg)) + e := fmt.Errorf("cluster response result failed: %s", result.Msg) klog.V(3).Info(e.Error()) return nil, e } @@ -127,7 +126,7 @@ func (cm *ClusterManager) GetNodesByClusterId(clusterId string) ([]cmproto.Node, nodeList := make([]cmproto.Node, 0, 0) err = json.Unmarshal(nodeData, &nodeList) if err != nil { - e := errors.New(fmt.Sprintf("Unmarshal cluster response failed %s", err.Error())) + e := fmt.Errorf("unmarshal cluster response failed %s", err.Error()) klog.V(3).Info(e.Error()) return nil, e } @@ -160,7 +159,7 @@ func (cm *ClusterManager) GetNode(ip string) (*cmproto.Node, error) { } if !result.Result { - e := errors.New(fmt.Sprintf("getnode response result failed: %s", result.Msg)) + e := fmt.Errorf("getnode response result failed: %s", result.Msg) klog.V(3).Info(e.Error()) return nil, e } @@ -169,13 +168,13 @@ func (cm *ClusterManager) GetNode(ip string) (*cmproto.Node, error) { nodeList := make([]cmproto.Node, 0, 0) err = json.Unmarshal(nodeData, &nodeList) if err != nil { - e := errors.New(fmt.Sprintf("Unmarshal getnode response failed %s", err.Error())) + e := fmt.Errorf("Unmarshal getnode response failed %s", err.Error()) klog.V(3).Info(e.Error()) return nil, e } if len(nodeList) != 1 { - e := errors.New(fmt.Sprintf("getnode result num wrong %s", err.Error())) + e := fmt.Errorf("getnode result num wrong %s", err.Error()) klog.V(3).Info(e.Error()) return nil, e } diff --git a/bcs-services/bcs-cluster-reporter/internal/api/bcs/clustermanager.go b/bcs-services/bcs-cluster-reporter/internal/api/bcs/clustermanager.go index 5daa3d1578..b949fee864 100644 --- a/bcs-services/bcs-cluster-reporter/internal/api/bcs/clustermanager.go +++ b/bcs-services/bcs-cluster-reporter/internal/api/bcs/clustermanager.go @@ -50,7 +50,7 @@ func (t *BcsTransport) RoundTrip(req *http.Request) (*http.Response, error) { tr := &http.Transport{ TLSClientConfig: &tls.Config{ - InsecureSkipVerify: true, // 设置为 true 来禁用证书验证 + InsecureSkipVerify: true, // 设置为 true 来禁用证书验证 nolint }, } diff --git a/bcs-services/bcs-cluster-reporter/internal/k8s/get.go b/bcs-services/bcs-cluster-reporter/internal/k8s/get.go index 690d4cdd32..a20c8789aa 100644 --- a/bcs-services/bcs-cluster-reporter/internal/k8s/get.go +++ b/bcs-services/bcs-cluster-reporter/internal/k8s/get.go @@ -10,7 +10,7 @@ * limitations under the License. */ -// Package k8s +// Package k8s xxx package k8s import ( diff --git a/bcs-services/bcs-cluster-reporter/internal/k8s/pod.go b/bcs-services/bcs-cluster-reporter/internal/k8s/pod.go index f1511d880c..d39bb74884 100644 --- a/bcs-services/bcs-cluster-reporter/internal/k8s/pod.go +++ b/bcs-services/bcs-cluster-reporter/internal/k8s/pod.go @@ -33,14 +33,13 @@ func GetPods(clientSet *kubernetes.Clientset, namespace string, opts v1.ListOpti if nameRe == "" { return podList.Items, nil - } else { - re, _ := regexp.Compile(nameRe) - result := make([]corev1.Pod, 0, 0) - for _, pod := range podList.Items { - if re.MatchString(pod.Name) || strings.Contains(pod.Name, nameRe) { - result = append(result, pod) - } + } + re, _ := regexp.Compile(nameRe) + result := make([]corev1.Pod, 0, 0) + for _, pod := range podList.Items { + if re.MatchString(pod.Name) || strings.Contains(pod.Name, nameRe) { + result = append(result, pod) } - return result, nil } + return result, nil } diff --git a/bcs-services/bcs-cluster-reporter/internal/metric_manager/metric.go b/bcs-services/bcs-cluster-reporter/internal/metric_manager/metric.go index c38b83901f..8b3f07a67c 100644 --- a/bcs-services/bcs-cluster-reporter/internal/metric_manager/metric.go +++ b/bcs-services/bcs-cluster-reporter/internal/metric_manager/metric.go @@ -10,7 +10,8 @@ * limitations under the License. */ -// Package metric_manager +// Package metric_manager xxx +// nolint package metric_manager import ( diff --git a/bcs-services/bcs-cluster-reporter/internal/metric_manager/metric_test.go b/bcs-services/bcs-cluster-reporter/internal/metric_manager/metric_test.go index 6c44e936fb..f739118bd0 100644 --- a/bcs-services/bcs-cluster-reporter/internal/metric_manager/metric_test.go +++ b/bcs-services/bcs-cluster-reporter/internal/metric_manager/metric_test.go @@ -10,6 +10,7 @@ * limitations under the License. */ +// nolint package metric_manager import ( @@ -34,6 +35,7 @@ func TestSendMessage(t *testing.T) { }, }) + // nolint vec = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "cluster_availability", Help: "cluster_availability, 1 means OK", diff --git a/bcs-services/bcs-cluster-reporter/internal/plugin/clustercheck/clustercheck.go b/bcs-services/bcs-cluster-reporter/internal/plugin/clustercheck/clustercheck.go index da2ccd18df..c6a57ca72a 100644 --- a/bcs-services/bcs-cluster-reporter/internal/plugin/clustercheck/clustercheck.go +++ b/bcs-services/bcs-cluster-reporter/internal/plugin/clustercheck/clustercheck.go @@ -10,7 +10,7 @@ * limitations under the License. */ -// Package clustercheck +// Package clustercheck xxx package clustercheck import ( @@ -48,10 +48,14 @@ type Plugin struct { } var ( + // NewGaugeVec creates a new GaugeVec based on the provided GaugeOpts and + // partitioned by the given label names. clusterAvailability = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "cluster_availability", Help: "cluster_availability, 1 means OK", }, []string{"target", "target_biz", "status"}) + // NewGaugeVec creates a new GaugeVec based on the provided GaugeOpts and + // partitioned by the given label names. clusterCheckDuration = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "cluster_check_duration_seconds", Help: "cluster_check_duration_seconds, 1 means OK", @@ -167,11 +171,6 @@ func (p *Plugin) Check() { // 根据internal来调整超时时间的长短 interval := p.opt.Interval - namespace := unstructuredObj.GetNamespace() - if namespace == "" { - namespace = "default" - } - wg := sync.WaitGroup{} clusterChecktGaugeVecSetList := make([]*metric_manager.GaugeVecSet, 0, 0) clusterCheckDurationGaugeVecSetList := make([]*metric_manager.GaugeVecSet, 0, 0) @@ -186,6 +185,7 @@ func (p *Plugin) Check() { defer func() { if r := recover(); r != nil { klog.Errorf("%s clustercheck failed: %s, stack: %v\n", clusterId, r, string(debug.Stack())) + // GetClientsetByConfig cluster k8s client clientSet1, _ := k8s.GetClientsetByConfig(config) var responseContentType string body, _ := clientSet1.RESTClient().Get(). @@ -232,7 +232,7 @@ func (p *Plugin) Check() { Help: "cluster_check_duration_seconds", }, []string{"target", "target_biz", "step"})) - for index, _ := range clusterAvailabilityMap[clusterId] { + for index := range clusterAvailabilityMap[clusterId] { metric_manager.MM.RegisterSeperatedMetric(clusterId, clusterAvailabilityMap[clusterId][index]) } } @@ -262,7 +262,7 @@ func (p *Plugin) Check() { metric_manager.SetMetric(clusterCheckDuration, clusterCheckDurationGaugeVecSetList) // 去掉已经不存在的集群的指标 - for clusterId, _ := range clusterAvailabilityMap { + for clusterId := range clusterAvailabilityMap { deleted := true for _, cluster := range plugin_manager.Pm.GetConfig().ClusterConfigs { if clusterId == cluster.ClusterID { @@ -276,13 +276,15 @@ func (p *Plugin) Check() { } } +// test ClusterByCreateUnstructuredObj func testClusterByCreateUnstructuredObj(unstructuredObj *unstructured.Unstructured, config *rest.Config, status *string, interval int, clusterID string) ( workloadToScheduleCost, workloadToPodCost, worloadToRunningCost time.Duration, err error) { workloadToScheduleCost = time.Duration(0) workloadToPodCost = time.Duration(0) worloadToRunningCost = time.Duration(0) - ctx, _ := context.WithTimeout(context.Background(), time.Duration(interval/6)*time.Second) + ctx, cancelFunc := context.WithTimeout(context.Background(), time.Duration(interval/6)*time.Second) + defer cancelFunc() namespace := unstructuredObj.GetNamespace() if namespace == "" { namespace = "default" @@ -290,13 +292,13 @@ func testClusterByCreateUnstructuredObj(unstructuredObj *unstructured.Unstructur clientSet, err := k8s.GetClientsetByConfig(config) if err != nil { - *status = "配置失败" + *status = "配置失败" // nolint err = fmt.Errorf("GetClientsetByConfig failed: %s", err.Error()) return } if clientSet == nil { - *status = "配置失败" + *status = "配置失败" // nolint err = fmt.Errorf("Get clientSet failed %s", err.Error()) return } @@ -328,22 +330,25 @@ func testClusterByCreateUnstructuredObj(unstructuredObj *unstructured.Unstructur return } + // Returns copy of current discovery client that will only + // receive the legacy discovery format, or pointer to current + // discovery client if it does not support legacy-only discovery. discoveryInterface := clientSet.Discovery().WithLegacy() if discoveryInterface == nil { - *status = "配置失败" + *status = "配置失败" // nolint err = fmt.Errorf("Get discoveryInterface failed %s", err.Error()) return } // discoveryInterface.ServerGroupsAndResources() groupResource, err := restmapper.GetAPIGroupResources(discoveryInterface) if err != nil { - *status = "配置失败" + *status = "配置失败" // nolint err = fmt.Errorf("GetAPIGroupResources failed %s", err.Error()) } mapper := restmapper.NewDiscoveryRESTMapper(groupResource) mapping, err := mapper.RESTMapping(clusterGVK.GroupKind(), clusterGVK.Version) if err != nil { - *status = "配置失败" + *status = "配置失败" // nolint err = fmt.Errorf("RESTMapping failed %s", err.Error()) return } @@ -351,7 +356,7 @@ func testClusterByCreateUnstructuredObj(unstructuredObj *unstructured.Unstructur dynamicConfig, err := dynamic.NewForConfig(config) if err != nil { *status = "配置失败" - err = fmt.Errorf("%s Create dynamicConfig %s", err.Error()) + err = fmt.Errorf("create dynamicConfig %s", err.Error()) return } clusterUnstructuredObj.SetName("bcs-blackbox-job-" + time.Now().Format("150405")) @@ -409,9 +414,11 @@ func testClusterByCreateUnstructuredObj(unstructuredObj *unstructured.Unstructur *status, workloadToScheduleCost, workloadToPodCost, worloadToRunningCost, err = getWatchStatus(clientSet, clusterUnstructuredObj, dri, namespace, interval, clusterID, context.Background()) - return + return // nolint } +// get Watch Status +// nolint func getWatchStatus(clientSet *kubernetes.Clientset, clusterUnstructuredObj *unstructured.Unstructured, dri dynamic.ResourceInterface, namespace string, interval int, clusterID string, ctx context.Context) (status string, workloadToScheduleCost, workloadToPodCost, worloadToRunningCost time.Duration, err error) { @@ -518,6 +525,7 @@ func getWatchStatus(clientSet *kubernetes.Clientset, clusterUnstructuredObj *uns } } +// get Pod Life Cycle Time Point func getPodLifeCycleTimePoint(pod *v1.Pod, createStartTime time.Time) (workloadToScheduleCost, worloadToRunningCost time.Duration) { workloadToScheduleCost = 0 worloadToRunningCost = 0 @@ -542,12 +550,13 @@ func getPodLifeCycleTimePoint(pod *v1.Pod, createStartTime time.Time) (workloadT if worloadToRunningCost == 0 { worloadToRunningCost = time.Since(createStartTime) } - return + return workloadToScheduleCost, worloadToRunningCost } - return + return workloadToScheduleCost, worloadToRunningCost } +// update Nested Map func updateNestedMap(obj map[string]interface{}, keyPath []string, newValue interface{}) { if len(keyPath) == 1 { obj[keyPath[0]] = newValue diff --git a/bcs-services/bcs-cluster-reporter/internal/plugin/dnscheck/dnscheck.go b/bcs-services/bcs-cluster-reporter/internal/plugin/dnscheck/dnscheck.go index 3846f486c5..fd6a6163af 100644 --- a/bcs-services/bcs-cluster-reporter/internal/plugin/dnscheck/dnscheck.go +++ b/bcs-services/bcs-cluster-reporter/internal/plugin/dnscheck/dnscheck.go @@ -10,7 +10,7 @@ * limitations under the License. */ -// Package dnscheck +// Package dnscheck xxx package dnscheck import ( @@ -222,8 +222,6 @@ func (p *Plugin) checkDNSEndpoints(ctx context.Context, domainList []string) { if time.Since(start) < time.Second { <-time.After(time.Second - time.Since(start)) } - start = time.Now() - } } diff --git a/bcs-services/bcs-cluster-reporter/internal/plugin/eventrecorder/eventrecorder.go b/bcs-services/bcs-cluster-reporter/internal/plugin/eventrecorder/eventrecorder.go index 7af78f1526..328bde961e 100644 --- a/bcs-services/bcs-cluster-reporter/internal/plugin/eventrecorder/eventrecorder.go +++ b/bcs-services/bcs-cluster-reporter/internal/plugin/eventrecorder/eventrecorder.go @@ -10,7 +10,7 @@ * limitations under the License. */ -// Package eventrecorder +// Package eventrecorder xxx package eventrecorder import ( diff --git a/bcs-services/bcs-cluster-reporter/internal/plugin/logrecorder/logrecorder.go b/bcs-services/bcs-cluster-reporter/internal/plugin/logrecorder/logrecorder.go index 99665ec76d..dcd5814682 100644 --- a/bcs-services/bcs-cluster-reporter/internal/plugin/logrecorder/logrecorder.go +++ b/bcs-services/bcs-cluster-reporter/internal/plugin/logrecorder/logrecorder.go @@ -10,7 +10,7 @@ * limitations under the License. */ -// Package logrecorder +// Package logrecorder xxx package logrecorder import ( @@ -73,11 +73,6 @@ func (p *Plugin) Setup(configFilePath string) error { p.stopChan = make(chan int) - interval := p.opt.Interval - if interval == 0 { - interval = 60 - } - cluster := plugin_manager.Pm.GetConfig().InClusterConfig if cluster.Config == nil { klog.Fatalf("eventrecorder get incluster config failed") diff --git a/bcs-services/bcs-cluster-reporter/internal/plugin/masterpodcheck/masterpodcheck.go b/bcs-services/bcs-cluster-reporter/internal/plugin/masterpodcheck/masterpodcheck.go index 66ce9a9280..77f7cd74eb 100644 --- a/bcs-services/bcs-cluster-reporter/internal/plugin/masterpodcheck/masterpodcheck.go +++ b/bcs-services/bcs-cluster-reporter/internal/plugin/masterpodcheck/masterpodcheck.go @@ -10,7 +10,7 @@ * limitations under the License. */ -// Package masterpodcheck +// Package masterpodcheck xxx package masterpodcheck import ( @@ -44,6 +44,7 @@ import ( ) var ( + // master Pod Name List masterPodNameList = []string{ "kube-apiserver", "kube-controller-manager", @@ -61,6 +62,8 @@ type Plugin struct { } var ( + // NewGaugeVec creates a new GaugeVec based on the provided GaugeOpts and + // partitioned by the given label names. masterPodCheck = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "master_pod_check", Help: "the result of master pod configuration consistency check operation, 1 means ok", @@ -177,17 +180,20 @@ func (p *Plugin) Check() { plugin_manager.Pm.Done() }() klog.V(9).Infof("start masterpodcheck for %s", clusterId) + // GetClientsetByConfig cluster k8s client clientSet, err := k8s.GetClientsetByConfig(config) if err != nil { klog.Errorf("%s GetClientsetByClusterId failed: %s", clusterId, err.Error()) return } + // GetK8sVersion get cluster k8s version clusterVersion, err := k8s.GetK8sVersion(clientSet) if err != nil { klog.Errorf("%s GetK8sVersion failed: %s", clusterId, err.Error()) } + // GetPods get namespace pods ALLPodList, err := k8s.GetPods(clientSet, "kube-system", v1.ListOptions{}, "") if err != nil { klog.Errorf("%s GetPods failed: %s", clusterId, err.Error()) @@ -246,6 +252,7 @@ func (p *Plugin) Check() { metric_manager.SetMetric(masterPodCheck, masterPodCheckGaugeVecSetList) } +// check Master Pod func (p *Plugin) checkMasterPod(clientSet *kubernetes.Clientset, podList []corev1.Pod, podName string, nodeLabelSelector string, clusterId string, clusterBiz string, config *rest.Config) []*metric_manager.GaugeVecSet { result := make([]*metric_manager.GaugeVecSet, 0, 0) @@ -327,11 +334,13 @@ func (p *Plugin) checkMasterPod(clientSet *kubernetes.Clientset, podList []corev return result } +// check Pod Num func (p *Plugin) checkPodNum(clientSet *kubernetes.Clientset, nodeLabelSelector string, masterPodList []corev1.Pod, podName string) string { masterPodNum := len(masterPodList) // ensure number of master node + // nolint if podName != "etcd" { ctx := context.Background() nodeList, err := clientSet.CoreV1().Nodes().List(ctx, v1.ListOptions{ @@ -354,6 +363,7 @@ func (p *Plugin) checkPodNum(clientSet *kubernetes.Clientset, nodeLabelSelector return "ok" } +// check Static Pod Consistency func (p *Plugin) checkStaticPodConsistency(podList []corev1.Pod) string { podSpecList := make(map[string]corev1.PodSpec) argsList := make(map[string]map[string][]string) @@ -375,6 +385,7 @@ func (p *Plugin) checkStaticPodConsistency(podList []corev1.Pod) string { // 对比容器配置以外的spec是否一致 var sampleSpec corev1.PodSpec var sampleName string + // nolint for podName, spec := range podSpecList { if reflect.DeepEqual(sampleSpec, corev1.PodSpec{}) { sampleSpec = spec @@ -389,7 +400,7 @@ func (p *Plugin) checkStaticPodConsistency(podList []corev1.Pod) string { // 对比容器命令行参数是否一致 var samplePodName string - for podName, _ := range argsList { + for podName := range argsList { if samplePodName == "" { samplePodName = podName break @@ -404,6 +415,7 @@ func (p *Plugin) checkStaticPodConsistency(podList []corev1.Pod) string { continue } + // nolint for containerName, args := range containers { if sampleArgs, ok := argsList[samplePodName][containerName]; !ok { klog.Infof("pod %s doesn't have container %s", samplePodName, containerName) @@ -422,6 +434,7 @@ func (p *Plugin) checkStaticPodConsistency(podList []corev1.Pod) string { return "ok" } +// check Arguments func checkArguments(argList1 []string, argList2 []string) error { if len(argList1) != len(argList2) { return fmt.Errorf("length not equal") @@ -444,11 +457,12 @@ func checkArguments(argList1 []string, argList2 []string) error { return nil } +// check Scheduler Policy func (p *Plugin) checkSchedulerPolicy(clientSet *kubernetes.Clientset, restConfig *rest.Config, podList []corev1.Pod) (string, error) { if len(podList) == 0 { klog.Infof("no kube-scheduler pods were found") - return "访问集群失败", nil + return "访问集群失败", nil // nolint } else if len(podList) == 1 { return "单实例", nil } @@ -469,6 +483,7 @@ func (p *Plugin) checkSchedulerPolicy(clientSet *kubernetes.Clientset, restConfi return p.checkPodFileConsistency(restConfig, clientSet, podList, "kube-scheduler", filePath) } +// check Pod File Consistency func (p *Plugin) checkPodFileConsistency(restConfig *rest.Config, clientSet *kubernetes.Clientset, podList []corev1.Pod, containerName string, filePath string) (string, error) { ctx := context.Background() @@ -489,7 +504,7 @@ func (p *Plugin) checkPodFileConsistency(restConfig *rest.Config, clientSet *kub exec, err := remotecommand.NewSPDYExecutor(restConfig, "POST", req.URL()) if err != nil { - return "访问集群失败", fmt.Errorf("NewSPDYExecutor failed: %s", err.Error()) + return "访问集群失败", fmt.Errorf("NewSPDYExecutor failed: %s", err.Error()) // nolint } var stdout, stderr bytes.Buffer @@ -507,10 +522,10 @@ func (p *Plugin) checkPodFileConsistency(restConfig *rest.Config, clientSet *kub execMsg := stdout.String() if errMsg != "" { klog.Infof("Exec failed: %s", errMsg) - return "访问集群失败", nil + return "访问集群失败", nil // nolint } else if execMsg == "" { klog.Infof("%s is blank", filePath) - return "访问集群失败", nil + return "访问集群失败", nil // nolint } if sampleFile == "" { @@ -520,13 +535,14 @@ func (p *Plugin) checkPodFileConsistency(restConfig *rest.Config, clientSet *kub if sampleFile != execMsg { klog.Infof("pod %s policy %s doesn't equal pod %s policy %s", sampleName, sampleFile, pod.Name, execMsg) - return "配置不一致", nil + return "配置不一致", nil // nolint } } } return "ok", nil } +// check Pod Config func (p *Plugin) checkPodConfig(obj interface{}, path string, regex string) (bool, error) { value := reflect.ValueOf(obj) fields := strings.Split(path, ".") diff --git a/bcs-services/bcs-cluster-reporter/internal/plugin/netcheck/netcheck.go b/bcs-services/bcs-cluster-reporter/internal/plugin/netcheck/netcheck.go index dd9ae1028e..6005e06958 100644 --- a/bcs-services/bcs-cluster-reporter/internal/plugin/netcheck/netcheck.go +++ b/bcs-services/bcs-cluster-reporter/internal/plugin/netcheck/netcheck.go @@ -10,7 +10,7 @@ * limitations under the License. */ -// Package netcheck +// Package netcheck xxx package netcheck import ( @@ -53,22 +53,30 @@ type Plugin struct { } var ( + // NewGaugeVec creates a new GaugeVec based on the provided GaugeOpts and + // partitioned by the given label names. podNetAvailability = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "pod_net_availability", Help: "pod_net_availability, 1 means OK", }, []string{"target", "target_biz", "status"}) + // NewHistogramVec creates a new HistogramVec based on the provided HistogramOpts and + // partitioned by the given label names. podNetLatency = prometheus.NewHistogramVec(prometheus.HistogramOpts{ Name: "pod_net_latency", Help: "pod_net_latency", Buckets: []float64{0.001, 0.01, 0.1, 0.2, 0.4, 0.8, 1.6, 3.2}, }, []string{"target", "target_biz"}) + // NewGaugeVec creates a new GaugeVec based on the provided GaugeOpts and + // partitioned by the given label names. svcNetAvailability = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "svc_net_availability", Help: "svc_net_availability, 1 means OK", }, []string{"target", "target_biz", "status"}) + // NewHistogramVec creates a new HistogramVec based on the provided HistogramOpts and + // partitioned by the given label names. svcNetLatency = prometheus.NewHistogramVec(prometheus.HistogramOpts{ Name: "svc_net_latency", Help: "pod_net_latency", diff --git a/bcs-services/bcs-cluster-reporter/internal/plugin/systemappcheck/systemappcheck.go b/bcs-services/bcs-cluster-reporter/internal/plugin/systemappcheck/systemappcheck.go index 0ac75913bd..9bfd5451da 100644 --- a/bcs-services/bcs-cluster-reporter/internal/plugin/systemappcheck/systemappcheck.go +++ b/bcs-services/bcs-cluster-reporter/internal/plugin/systemappcheck/systemappcheck.go @@ -255,9 +255,10 @@ func (p *Plugin) Check() { kind := objMap["kind"].(string) name := objMap["metadata"].(map[interface{}]interface{})["name"].(string) - ctx, _ := context.WithTimeout(context.Background(), time.Duration(10)*time.Second) + ctx, _ := context.WithTimeout(context.Background(), time.Duration(10)*time.Second) // nolint var workload runtime.Object + // nolint switch kind { case "Deployment": deploy, err := clientSet.AppsV1().Deployments(namespace).Get(ctx, name, metav1.GetOptions{}) @@ -356,14 +357,12 @@ func (p *Plugin) Check() { goruntime.GC() } -// GetStatus +// GetStatus get status func GetStatus(updatedReplicas int, availableReplicas int, replicas int) string { if replicas > 0 && availableReplicas == replicas && updatedReplicas == replicas { return "ready" - } else { - return "notready" } - + return "notready" } // CheckComponents check specified component status @@ -374,6 +373,7 @@ func (p *Plugin) CheckComponents( for _, component := range componentList { var workload runtime.Object var err error + // nolint switch component.Resource { case "Deployment", "deployment": workload, err = clientSet.AppsV1().Deployments(component.Namespace).Get(context.Background(), component.Name, diff --git a/bcs-services/bcs-cluster-reporter/internal/plugin_manager/options.go b/bcs-services/bcs-cluster-reporter/internal/plugin_manager/options.go index 600a284470..b868815f09 100644 --- a/bcs-services/bcs-cluster-reporter/internal/plugin_manager/options.go +++ b/bcs-services/bcs-cluster-reporter/internal/plugin_manager/options.go @@ -10,7 +10,8 @@ * limitations under the License. */ -package plugin_manager +// Package plugin_manager xxx +package plugin_manager // nolint import ( "k8s.io/client-go/rest" diff --git a/bcs-services/bcs-cluster-reporter/internal/plugin_manager/plugin_manager.go b/bcs-services/bcs-cluster-reporter/internal/plugin_manager/plugin_manager.go index 7f90504714..2bfd61be92 100644 --- a/bcs-services/bcs-cluster-reporter/internal/plugin_manager/plugin_manager.go +++ b/bcs-services/bcs-cluster-reporter/internal/plugin_manager/plugin_manager.go @@ -10,8 +10,8 @@ * limitations under the License. */ -// Package plugin_manager -package plugin_manager +// Package plugin_manager xxx +package plugin_manager // nolint import ( "fmt" @@ -69,9 +69,8 @@ func (pm *pluginManager) Register(plugin Plugin) { func (pm *pluginManager) GetPlugin(plugin string) Plugin { if p, ok := pm.plugins[plugin]; ok { return p - } else { - return nil } + return nil } // SetConfig configure pluginmanager by config file @@ -95,6 +94,8 @@ func (pm *pluginManager) GetConfig() *Config { return pm.config } +// SetupPlugin setup plugin +// nolint func (pm *pluginManager) SetupPlugin(plugins string, pluginDir string) error { for _, plugin := range strings.Split(plugins, ",") { if p := pm.GetPlugin(plugin); p == nil { @@ -125,6 +126,8 @@ func (pm *pluginManager) Done() { pm.routinePool.Done() } +// StopPlugin stop plugin +// nolint func (pm *pluginManager) StopPlugin(plugins string) error { for _, plugin := range strings.Split(plugins, ",") { if p := pm.GetPlugin(plugin); p == nil { @@ -140,6 +143,7 @@ func (pm *pluginManager) StopPlugin(plugins string) error { } // NewPluginManager xxx +// nolint func NewPluginManager() *pluginManager { return &pluginManager{ routinePool: util.NewRoutinePool(40), diff --git a/bcs-services/bcs-cluster-reporter/internal/rest/rest.go b/bcs-services/bcs-cluster-reporter/internal/rest/rest.go index a7e0127888..c024e3d85e 100644 --- a/bcs-services/bcs-cluster-reporter/internal/rest/rest.go +++ b/bcs-services/bcs-cluster-reporter/internal/rest/rest.go @@ -10,7 +10,7 @@ * limitations under the License. */ -// Package rest +// Package rest xxx package rest import ( diff --git a/bcs-services/bcs-cluster-reporter/internal/util/crypt.go b/bcs-services/bcs-cluster-reporter/internal/util/crypt.go index 148f4dc894..5641a8f916 100644 --- a/bcs-services/bcs-cluster-reporter/internal/util/crypt.go +++ b/bcs-services/bcs-cluster-reporter/internal/util/crypt.go @@ -10,7 +10,7 @@ * limitations under the License. */ -// Package util +// Package util xxx package util import ( @@ -145,11 +145,11 @@ func (xmlp *XmlProcessor) serialize(msg4_send *WXBizMsg4Send) ([]byte, *CryptErr return xml_msg, nil } -// NewWXBizMsgCrypt +// NewWXBizMsgCrypt new WXBizMsgCrypt func NewWXBizMsgCrypt(token, encoding_aeskey, receiver_id string, protocol_type ProtocolType) *WXBizMsgCrypt { var protocol_processor ProtocolProcessor if protocol_type != XmlType { - panic("unsupport protocal") + panic("unsupport protocol") } else { protocol_processor = new(XmlProcessor) } diff --git a/bcs-services/bcs-cluster-reporter/main.go b/bcs-services/bcs-cluster-reporter/main.go index 068e398886..843979f367 100644 --- a/bcs-services/bcs-cluster-reporter/main.go +++ b/bcs-services/bcs-cluster-reporter/main.go @@ -1,3 +1,15 @@ +/* + * 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 main import ( @@ -16,8 +28,10 @@ import ( ) func main() { + // See SetMemoryLimit for more details. debug.SetGCPercent(100) cmd.Execute() + // Flush flushes all pending log I/O. defer klog.Flush() } diff --git a/bcs-services/bcs-data-manager/cmd/server.go b/bcs-services/bcs-data-manager/cmd/server.go index a5b336afba..e4fb32532d 100644 --- a/bcs-services/bcs-data-manager/cmd/server.go +++ b/bcs-services/bcs-data-manager/cmd/server.go @@ -35,7 +35,7 @@ import ( restclient "github.com/Tencent/bk-bcs/bcs-common/pkg/esb/client" "github.com/Tencent/bk-bcs/bcs-common/pkg/msgqueue" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/drivers/mongo" - _ "github.com/go-sql-driver/mysql" + _ "github.com/go-sql-driver/mysql" // nolint "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/jmoiron/sqlx" @@ -232,10 +232,10 @@ func (s *Server) initModel() error { tspiderDBs := make(map[string]*sqlx.DB, 0) for _, conf := range tspiderConfig { dsn := conf.Connection - db, err := sqlx.Connect("mysql", dsn) - if err != nil { - blog.Errorf("init tspider db(%s) failed, err %s", dsn, err.Error()) - return err + db, errSqlx := sqlx.Connect("mysql", dsn) + if errSqlx != nil { + blog.Errorf("init tspider db(%s) failed, err %s", dsn, errSqlx.Error()) + return errSqlx } tspiderDBs[conf.StoreName] = db diff --git a/bcs-services/bcs-data-manager/handler/bcs-data-manager.go b/bcs-services/bcs-data-manager/handler/bcs-data-manager.go index 47400690b2..402f656095 100644 --- a/bcs-services/bcs-data-manager/handler/bcs-data-manager.go +++ b/bcs-services/bcs-data-manager/handler/bcs-data-manager.go @@ -504,6 +504,7 @@ func (e *BcsDataManager) GetUserOperationDataList(ctx context.Context, return nil } +// GetWorkloadRequestResult get workload request result func (e *BcsDataManager) GetWorkloadRequestResult(ctx context.Context, req *bcsdatamanager.GetWorkloadRequestRecommendResultReq, rsp *bcsdatamanager.GetWorkloadRequestRecommendResultRsp) error { blog.Infof("Received GetWorkloadRequestResult.Call request. cluster id: %s, namespace: %s, workloadType:%s"+ @@ -525,6 +526,7 @@ func (e *BcsDataManager) GetWorkloadRequestResult(ctx context.Context, req *bcsd return nil } +// GetWorkloadOriginRequestResult get workload origin request result func (e *BcsDataManager) GetWorkloadOriginRequestResult(ctx context.Context, req *bcsdatamanager.GetWorkloadOriginRequestResultReq, rsp *bcsdatamanager.GetWorkloadOriginRequestResultRsp) error { blog.Infof("Received GetWorkloadOriginRequestResult.Call request. projectID:%s, cluster id: %s, "+ diff --git a/bcs-services/bcs-data-manager/pkg/datajob/workload.go b/bcs-services/bcs-data-manager/pkg/datajob/workload.go index 713d1d7107..62b9c80419 100644 --- a/bcs-services/bcs-data-manager/pkg/datajob/workload.go +++ b/bcs-services/bcs-data-manager/pkg/datajob/workload.go @@ -315,6 +315,7 @@ func (p *WorkloadMinutePolicy) ImplementPolicy(ctx context.Context, opts *types. } } +// ImplementPolicy implement policy func (p *WorkloadRequestPolicy) ImplementPolicy(ctx context.Context, opts *types.JobCommonOpts, clients *types.Clients) { if opts.ClusterType != types.Kubernetes { diff --git a/bcs-services/bcs-data-manager/pkg/store/mongo/cloudnativeworkload.go b/bcs-services/bcs-data-manager/pkg/store/mongo/cloudnativeworkload.go index 1674e5b1e3..1a913bf170 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/cloudnativeworkload.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/cloudnativeworkload.go @@ -10,6 +10,7 @@ * limitations under the License. */ +// Package mongo xxx package mongo import ( @@ -41,14 +42,14 @@ func NewModelCloudNative(db drivers.DB, bkbaseConf *types.BkbaseConfig) *ModelCl } -// GetCloudNativeWorkloadList +// GetCloudNativeWorkloadList get cloud native workload list func (m *ModelCloudNative) GetCloudNativeWorkloadList(ctx context.Context, req *bcsdatamanager.GetCloudNativeWorkloadListRequest) (*bcsdatamanager.TEGMessage, error) { // page info currentPage := int(req.GetCurrentPage()) pageSize := int(req.GetPageSize()) if pageSize > 10000 { - return nil, fmt.Errorf("The max pageSize currently supported is 10000.") + return nil, fmt.Errorf("the max pageSize currently supported is 10000") } if currentPage <= 0 { currentPage = 1 diff --git a/bcs-services/bcs-data-manager/pkg/store/mongo/mongo.go b/bcs-services/bcs-data-manager/pkg/store/mongo/mongo.go index f80191a5f4..b9c6d73611 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/mongo.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/mongo.go @@ -36,15 +36,15 @@ type server struct { // NewServer new db server func NewServer(db drivers.DB, bkbaseConf *types.BkbaseConfig) store.Server { return &server{ - ModelCluster: NewModelCluster(db), - ModelNamespace: NewModelNamespace(db), - ModelWorkload: NewModelWorkload(db), - ModelProject: NewModelProject(db), - ModelPublic: NewModelPublic(db), - ModelPodAutoscaler: NewModelPodAutoscaler(db), - ModelPowerTrading: NewModelPowerTrading(db, bkbaseConf), - ModelCloudNative: NewModelCloudNative(db, bkbaseConf), - ModelOperationData: NewModelOperationData(db, bkbaseConf), + ModelCluster: NewModelCluster(db), + ModelNamespace: NewModelNamespace(db), + ModelWorkload: NewModelWorkload(db), + ModelProject: NewModelProject(db), + ModelPublic: NewModelPublic(db), + ModelPodAutoscaler: NewModelPodAutoscaler(db), + ModelPowerTrading: NewModelPowerTrading(db, bkbaseConf), + ModelCloudNative: NewModelCloudNative(db, bkbaseConf), + ModelOperationData: NewModelOperationData(db, bkbaseConf), ModelWorkloadRequest: NewModelWorkloadRequest(db), ModelWorkloadOriginRequest: NewModelWorkloadOriginRequest(db), } diff --git a/bcs-services/bcs-data-manager/pkg/store/mongo/operationdata.go b/bcs-services/bcs-data-manager/pkg/store/mongo/operationdata.go index 490bbda5b0..286dd942bf 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/operationdata.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/operationdata.go @@ -29,7 +29,7 @@ type ModelOperationData struct { Tables map[string]*Public } -// NewModelUserOperationDataList new bcs user operation data model +// NewModelOperationData new bcs user operation data model func NewModelOperationData(db drivers.DB, bkbaseConf *types.BkbaseConfig) *ModelOperationData { return &ModelOperationData{} } diff --git a/bcs-services/bcs-data-manager/pkg/store/mongo/request.go b/bcs-services/bcs-data-manager/pkg/store/mongo/request.go index 476680eceb..b0b6fc6131 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/request.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/request.go @@ -51,6 +51,7 @@ func NewModelWorkloadRequest(db drivers.DB) *ModelWorkloadRequest { }} } +// GetLatestWorkloadRequest get latest workload request func (m *ModelWorkloadRequest) GetLatestWorkloadRequest(ctx context.Context, req *datamanager.GetWorkloadRequestRecommendResultReq) (*datamanager.GetWorkloadRequestRecommendResultRsp, error) { err := ensureTable(ctx, &m.Public) diff --git a/bcs-services/bcs-data-manager/pkg/store/mongo/workload_info.go b/bcs-services/bcs-data-manager/pkg/store/mongo/workload_info.go index e04698051f..169182cff4 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/workload_info.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/workload_info.go @@ -113,6 +113,7 @@ func (m *ModelWorkloadOriginRequest) CreateWorkloadOriginRequest(ctx context.Con return m.DB.Table(m.TableName).Upsert(ctx, cond, operator.M{"$set": result}) } +// ListWorkloadOriginRequest list workload origin request func (m *ModelWorkloadOriginRequest) ListWorkloadOriginRequest(ctx context.Context, req *datamanager.GetWorkloadOriginRequestResultReq) ([]*datamanager.WorkloadOriginRequestResult, error) { err := ensureTable(ctx, &m.Public) diff --git a/bcs-services/bcs-data-manager/pkg/store/tspider/cloudnativeworkload.go b/bcs-services/bcs-data-manager/pkg/store/tspider/cloudnativeworkload.go index 1a21941d98..2f594ccb86 100644 --- a/bcs-services/bcs-data-manager/pkg/store/tspider/cloudnativeworkload.go +++ b/bcs-services/bcs-data-manager/pkg/store/tspider/cloudnativeworkload.go @@ -70,7 +70,7 @@ func (m *ModelCloudNative) GetCloudNativeWorkloadList(ctx context.Context, // query for data workloads := make([]*types.TEGWorkload, 0) - if err := m.Public.QueryxToStruct(query, &workloads); err != nil { + if err = m.Public.QueryxToStruct(query, &workloads); err != nil { return nil, err } result := make([]*datamanager.TEGWorkload, 0) @@ -110,7 +110,7 @@ func (m *ModelCloudNative) GetCloudNativeWorkloadList(ctx context.Context, func (m *ModelCloudNative) validate(request *datamanager.GetCloudNativeWorkloadListRequest) error { pageSize := request.GetPageSize() if pageSize > 10000 { - return fmt.Errorf("The max pageSize currently supported is 10000.") + return fmt.Errorf("the max pageSize currently supported is 10000") } return nil diff --git a/bcs-services/bcs-data-manager/pkg/store/tspider/operationdata.go b/bcs-services/bcs-data-manager/pkg/store/tspider/operationdata.go index d431948200..15c81f0738 100644 --- a/bcs-services/bcs-data-manager/pkg/store/tspider/operationdata.go +++ b/bcs-services/bcs-data-manager/pkg/store/tspider/operationdata.go @@ -47,7 +47,7 @@ type ModelUserOperationData struct { Tables map[string]*Public } -// NewModelUserOperationDataList new bcs user operation data model +// NewModelUserOperationData new bcs user operation data model func NewModelUserOperationData(dbs map[string]*sqlx.DB, bkbaseConf *types.BkbaseConfig) *ModelUserOperationData { od := &ModelUserOperationData{ Tables: map[string]*Public{}, @@ -176,5 +176,5 @@ func (od *ModelUserOperationData) getBuilders( countBuilder = countBuilder.Where(sq.Eq{NamespaceColumnKey: request.GetNamespace()}) } - return + return queryBuilder, countBuilder } diff --git a/bcs-services/bcs-data-manager/pkg/store/tspider/public.go b/bcs-services/bcs-data-manager/pkg/store/tspider/public.go index 8907b918c8..f19f4169a3 100644 --- a/bcs-services/bcs-data-manager/pkg/store/tspider/public.go +++ b/bcs-services/bcs-data-manager/pkg/store/tspider/public.go @@ -62,7 +62,7 @@ func (p *Public) QueryxToStructpb(builder sq.SelectBuilder) ([]*structpb.Struct, return response, nil } -// QueryxToStruct query data and return struct +// QueryxToAny query data and return struct func (p *Public) QueryxToAny(builder sq.SelectBuilder) ([]*any.Any, error) { sql, args, err := builder.ToSql() if err != nil { @@ -101,7 +101,7 @@ func (p *Public) QueryxToAny(builder sq.SelectBuilder) ([]*any.Any, error) { return response, nil } -// QueryxToAny query data and return map[string]interface{} +// QueryxToMap query data and return map[string]interface{} func (p *Public) QueryxToMap(builder sq.SelectBuilder) ([]map[string]interface{}, error) { sql, args, err := builder.ToSql() if err != nil { diff --git a/bcs-services/bcs-data-manager/pkg/store/tspider/tspider.go b/bcs-services/bcs-data-manager/pkg/store/tspider/tspider.go index f21ff32c5c..f58cf2fb55 100644 --- a/bcs-services/bcs-data-manager/pkg/store/tspider/tspider.go +++ b/bcs-services/bcs-data-manager/pkg/store/tspider/tspider.go @@ -10,6 +10,7 @@ * limitations under the License. */ +// Package tspider xxx package tspider import ( @@ -26,6 +27,7 @@ type server struct { } // NewServer new db server +// nolint func NewServer(dbs map[string]*sqlx.DB, bkbaseConf *types.BkbaseConfig) *server { return &server{ ModelCloudNative: NewModelCloudNative(dbs, bkbaseConf), diff --git a/bcs-services/bcs-helm-manager/internal/wrapper/audit.go b/bcs-services/bcs-helm-manager/internal/wrapper/audit.go index a054f941da..91bd7eb115 100644 --- a/bcs-services/bcs-helm-manager/internal/wrapper/audit.go +++ b/bcs-services/bcs-helm-manager/internal/wrapper/audit.go @@ -33,6 +33,7 @@ func NewAuditWrapper(fn server.HandlerFunc) server.HandlerFunc { startTime := time.Now() err := fn(ctx, req, rsp) endTime := time.Now() + // 添加审计 go addAudit(ctx, req, rsp, startTime, endTime) return err } @@ -46,6 +47,7 @@ func (a actionDesc) String() string { // nolint return string(a) } +// resource 资源想关信息 type resource struct { RepoName string `json:"repoName" yaml:"repoName"` ClusterID string `json:"clusterID" yaml:"clusterID"` @@ -87,6 +89,7 @@ func (r resource) toMap() map[string]any { return result } +// getResourceID get resource id func getResourceID(req server.Request) resource { body := req.Body() b, _ := json.Marshal(body) @@ -96,9 +99,11 @@ func getResourceID(req server.Request) resource { return resourceID } +// method audit func var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Action){ "HelmManager.CreatePersonalRepo": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeHelm, ResourceID: res.ProjectCode, ResourceName: res.ProjectCode, ResourceData: res.toMap(), @@ -106,6 +111,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.GetChartDetailV1": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeChart, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -113,6 +119,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.GetVersionDetailV1": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeChart, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -120,6 +127,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.DeleteChart": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeChart, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -127,6 +135,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.DeleteChartVersion": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeChart, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -134,6 +143,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.GetChartRelease": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeChart, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -141,6 +151,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.GetReleaseDetailV1": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeHelm, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -148,6 +159,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.InstallReleaseV1": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeHelm, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -155,6 +167,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.UninstallReleaseV1": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeHelm, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -162,6 +175,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.UpgradeReleaseV1": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeHelm, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -169,6 +183,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.RollbackReleaseV1": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeHelm, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -176,6 +191,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.ReleasePreview": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeHelm, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -183,6 +199,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.GetReleaseHistory": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeHelm, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -190,6 +207,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.GetReleaseManifest": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeHelm, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -197,6 +215,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.GetReleaseStatus": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeHelm, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -204,6 +223,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.GetReleasePods": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeHelm, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -211,6 +231,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.GetAddonsDetail": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeAddons, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -218,6 +239,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.InstallAddons": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeAddons, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -225,6 +247,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.UpgradeAddons": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeAddons, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -232,6 +255,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, "HelmManager.UninstallAddons": func(req server.Request) (audit.Resource, audit.Action) { res := getResourceID(req) + // return the resource to be recorded return audit.Resource{ ResourceType: audit.ResourceTypeAddons, ResourceID: res.Name, ResourceName: res.Name, ResourceData: res.toMap(), @@ -239,6 +263,7 @@ var auditFuncMap = map[string]func(req server.Request) (audit.Resource, audit.Ac }, } +// 添加审计 func addAudit(ctx context.Context, req server.Request, rsp interface{}, startTime, endTime time.Time) { // get method audit func fn, ok := auditFuncMap[req.Method()] diff --git a/bcs-services/bcs-monitor/pkg/component/bk_log/bk_log.go b/bcs-services/bcs-monitor/pkg/component/bk_log/bk_log.go index 5f22c58ae9..dcab1df0f6 100644 --- a/bcs-services/bcs-monitor/pkg/component/bk_log/bk_log.go +++ b/bcs-services/bcs-monitor/pkg/component/bk_log/bk_log.go @@ -34,6 +34,7 @@ func ListLogCollectors(ctx context.Context, clusterID, spaceUID string) ([]ListB var result2 []ListBCSCollectorRespData g.Go(func() error { var err error + // list log collectors with bcsPath result1, err = ListLogCollectorsWithPath(ctx, clusterID, spaceUID, bcsPath) if err != nil { return err @@ -42,6 +43,7 @@ func ListLogCollectors(ctx context.Context, clusterID, spaceUID string) ([]ListB }) g.Go(func() error { var err error + // list log collectors without bcsPath result2, err = ListLogCollectorsWithPath(ctx, clusterID, spaceUID, withoutBcsPath) if err != nil { return err @@ -61,6 +63,7 @@ func ListLogCollectors(ctx context.Context, clusterID, spaceUID string) ([]ListB func ListLogCollectorsWithPath(ctx context.Context, clusterID, spaceUID string, path string) ([]ListBCSCollectorRespData, error) { url := fmt.Sprintf("%s/%s", config.G.BKLog.APIServer, path) + // generate bk api auth header, X-Bkapi-Authorization authInfo, err := component.GetBKAPIAuthorization() if err != nil { return nil, err @@ -96,6 +99,7 @@ func ListLogCollectorsWithPath(ctx context.Context, clusterID, spaceUID string, // CreateLogCollectors create log collectors func CreateLogCollectors(ctx context.Context, req *CreateBCSCollectorReq) (*CreateBCSCollectorRespData, error) { url := fmt.Sprintf("%s/create_bcs_collector", config.G.BKLog.APIServer) + // generate bk api auth header, X-Bkapi-Authorization authInfo, err := component.GetBKAPIAuthorization() if err != nil { return nil, err @@ -131,6 +135,7 @@ func CreateLogCollectors(ctx context.Context, req *CreateBCSCollectorReq) (*Crea func UpdateLogCollectors(ctx context.Context, ruleID int, req *UpdateBCSCollectorReq) (*UpdateBCSCollectoRespData, error) { url := fmt.Sprintf("%s/update_bcs_collector/%d", config.G.BKLog.APIServer, ruleID) + // generate bk api auth header, X-Bkapi-Authorization authInfo, err := component.GetBKAPIAuthorization() if err != nil { return nil, err @@ -165,6 +170,7 @@ func UpdateLogCollectors(ctx context.Context, ruleID int, req *UpdateBCSCollecto // DeleteLogCollectors delete log collectors func DeleteLogCollectors(ctx context.Context, ruleID int) error { url := fmt.Sprintf("%s/delete_bcs_collector/%d", config.G.BKLog.APIServer, ruleID) + // generate bk api auth header, X-Bkapi-Authorization authInfo, err := component.GetBKAPIAuthorization() if err != nil { return err @@ -198,6 +204,7 @@ func DeleteLogCollectors(ctx context.Context, ruleID int) error { // RetryLogCollectors retry log collectors func RetryLogCollectors(ctx context.Context, ruleID int) error { url := fmt.Sprintf("%s/retry_bcs_collector/%d", config.G.BKLog.APIServer, ruleID) + // generate bk api auth header, X-Bkapi-Authorization authInfo, err := component.GetBKAPIAuthorization() if err != nil { return err @@ -231,6 +238,7 @@ func RetryLogCollectors(ctx context.Context, ruleID int) error { // StartLogCollectors start log collectors func StartLogCollectors(ctx context.Context, ruleID int) error { url := fmt.Sprintf("%s/start_bcs_collector/%d", config.G.BKLog.APIServer, ruleID) + // generate bk api auth header, X-Bkapi-Authorization authInfo, err := component.GetBKAPIAuthorization() if err != nil { return err @@ -264,6 +272,7 @@ func StartLogCollectors(ctx context.Context, ruleID int) error { // StopLogCollectors stop log collectors func StopLogCollectors(ctx context.Context, ruleID int) error { url := fmt.Sprintf("%s/stop_bcs_collector/%d", config.G.BKLog.APIServer, ruleID) + // generate bk api auth header, X-Bkapi-Authorization authInfo, err := component.GetBKAPIAuthorization() if err != nil { return err @@ -297,6 +306,7 @@ func StopLogCollectors(ctx context.Context, ruleID int) error { // HasLog check indexSetID has log func HasLog(ctx context.Context, indexSetID int) (bool, error) { url := fmt.Sprintf("%s/esquery_search", config.G.BKLog.APIServer) + // generate bk api auth header, X-Bkapi-Authorization authInfo, err := component.GetBKAPIAuthorization() if err != nil { return false, err @@ -331,6 +341,7 @@ func HasLog(ctx context.Context, indexSetID int) (bool, error) { // GetStorageClusters get storage clusters func GetStorageClusters(ctx context.Context, spaceUID string) ([]GetStorageClustersRespData, error) { url := fmt.Sprintf("%s/databus_storage/cluster_groups", config.G.BKLog.APIServer) + // generate bk api auth header, X-Bkapi-Authorization authInfo, err := component.GetBKAPIAuthorization() if err != nil { return nil, err @@ -365,6 +376,7 @@ func GetStorageClusters(ctx context.Context, spaceUID string) ([]GetStorageClust // SwitchStorage switch storage func SwitchStorage(ctx context.Context, spaceUID, bcsClusterID string, storageClusterID int) error { url := fmt.Sprintf("%s/switch_bcs_collector_storage", config.G.BKLog.APIServer) + // generate bk api auth header, X-Bkapi-Authorization authInfo, err := component.GetBKAPIAuthorization() if err != nil { return err @@ -405,6 +417,7 @@ func SwitchStorage(ctx context.Context, spaceUID, bcsClusterID string, storageCl // GetBcsCollectorStorage get bcs collector storage func GetBcsCollectorStorage(ctx context.Context, spaceUID, clusterID string) (int, error) { url := fmt.Sprintf("%s/get_bcs_collector_storage", config.G.BKLog.APIServer) + // generate bk api auth header, X-Bkapi-Authorization authInfo, err := component.GetBKAPIAuthorization() if err != nil { return 0, err diff --git a/bcs-services/bcs-netservice/bcs-ipam/resource/interface.go b/bcs-services/bcs-netservice/bcs-ipam/resource/interface.go index c4fb478d00..5dbb232285 100644 --- a/bcs-services/bcs-netservice/bcs-ipam/resource/interface.go +++ b/bcs-services/bcs-netservice/bcs-ipam/resource/interface.go @@ -21,6 +21,6 @@ type IPDriver interface { GetIPAddr(host, containerID, requestIP string) (*types.IPInfo, error) // GetIPAddr get available ip resource for contaienr ReleaseIPAddr(host string, containerID string, - ipInfo *types.IPInfo) error // ReleaseIPAddr release ip address for container + ipInfo *types.IPInfo) error // ReleaseIPAddr release ip address for container GetHostInfo(host string) (*types.HostInfo, error) // Get host info from driver } diff --git a/bcs-services/bcs-nodegroup-manager/pkg/resourcemgr/mocks/Client.go b/bcs-services/bcs-nodegroup-manager/pkg/resourcemgr/mocks/Client.go index fada790177..9a7870c520 100644 --- a/bcs-services/bcs-nodegroup-manager/pkg/resourcemgr/mocks/Client.go +++ b/bcs-services/bcs-nodegroup-manager/pkg/resourcemgr/mocks/Client.go @@ -82,7 +82,7 @@ func (_m *Client) ListTasks(poolID string, consumerID string, option *resourcemg return r0, r1 } -func (_m *Client) GetTaskByID(recordID string, opt *resourcemgr.GetOptions) (*storage.ScaleDownTask, error){ +func (_m *Client) GetTaskByID(recordID string, opt *resourcemgr.GetOptions) (*storage.ScaleDownTask, error) { panic("not impleted") } diff --git a/bcs-services/bcs-storage/pkg/handler/internal/clusterconfig/clusterconfig.go b/bcs-services/bcs-storage/pkg/handler/internal/clusterconfig/clusterconfig.go index 8cc6bb0339..c5ddd9f115 100644 --- a/bcs-services/bcs-storage/pkg/handler/internal/clusterconfig/clusterconfig.go +++ b/bcs-services/bcs-storage/pkg/handler/internal/clusterconfig/clusterconfig.go @@ -298,7 +298,7 @@ func wrapIP(s []string, df string) (r []string) { } r = append(r, v) } - return + return r } func unwrapIP(s []string) (r []string) { @@ -309,5 +309,5 @@ func unwrapIP(s []string) (r []string) { } r = append(r, v) } - return + return r } diff --git a/bcs-services/bcs-storage/storage/actions/v1http/clusterconfig/utils.go b/bcs-services/bcs-storage/storage/actions/v1http/clusterconfig/utils.go index c8cfd80453..fcb4195889 100644 --- a/bcs-services/bcs-storage/storage/actions/v1http/clusterconfig/utils.go +++ b/bcs-services/bcs-storage/storage/actions/v1http/clusterconfig/utils.go @@ -98,7 +98,7 @@ func getSvcSet(ctx context.Context, resourceType string, opt *lib.StoreGetOption blog.Errorf("Failed to parse service configSet. err: %v", err) return } - return + return svcConfigSet, nil } func getClsSet(clsConfig []operator.M) (clusterSet []types.ClusterSet, err error) { @@ -234,7 +234,7 @@ func wrapIP(s []string, df string) (r []string) { } r = append(r, v) } - return + return r } func unwrapIP(s []string) (r []string) { @@ -245,5 +245,5 @@ func unwrapIP(s []string) (r []string) { } r = append(r, v) } - return + return r } diff --git a/bcs-services/bcs-storage/storage/actions/v1http/dynamicquery/filter.go b/bcs-services/bcs-storage/storage/actions/v1http/dynamicquery/filter.go index 2cd6345d4c..b8462a84e1 100644 --- a/bcs-services/bcs-storage/storage/actions/v1http/dynamicquery/filter.go +++ b/bcs-services/bcs-storage/storage/actions/v1http/dynamicquery/filter.go @@ -121,5 +121,5 @@ func getTime(timeStr, layout string) (r interface{}, err error) { } else { r = t.Format(layout) } - return + return r, nil } diff --git a/bcs-services/bcs-storage/storage/actions/v1http/dynamicquery/utils.go b/bcs-services/bcs-storage/storage/actions/v1http/dynamicquery/utils.go index 03ee378952..f7b925da01 100644 --- a/bcs-services/bcs-storage/storage/actions/v1http/dynamicquery/utils.go +++ b/bcs-services/bcs-storage/storage/actions/v1http/dynamicquery/utils.go @@ -137,7 +137,7 @@ func (rd *DynamicParams) getParam(key string) (r string) { } else { r = rd.req.QueryParameter(key) } - return + return r } func (rd *DynamicParams) getQueryParamJSON() []byte { @@ -266,7 +266,7 @@ func (rd *DynamicParams) get(condition *operator.Condition) (mList []operator.M, return nil, fmt.Errorf("failed to query. err: %v", err) } - return + return mList, nil } func getQueryJSON(s url.Values) (p []byte) { @@ -277,7 +277,7 @@ func getQueryJSON(s url.Values) (p []byte) { } } _ = codec.EncJson(r, &p) - return + return p } func urlPath(oldURL string) string { diff --git a/bcs-services/cluster-resources/pkg/handler/multicluster/query.go b/bcs-services/cluster-resources/pkg/handler/multicluster/query.go index 93fdede052..93d9cacb19 100644 --- a/bcs-services/cluster-resources/pkg/handler/multicluster/query.go +++ b/bcs-services/cluster-resources/pkg/handler/multicluster/query.go @@ -61,6 +61,7 @@ func NewStorageQuery(ns []*clusterRes.ClusterNamespaces, filter QueryFilter) Que // Fetch fetches multicluster resources. func (q *StorageQuery) Fetch(ctx context.Context, groupVersion, kind string) (map[string]interface{}, error) { + // nolint // TODO check access var err error if q.ClusterdNamespaces, err = checkMultiClusterAccess(ctx, kind, q.ClusterdNamespaces); err != nil { @@ -108,6 +109,7 @@ func NewAPIServerQuery(ns []*clusterRes.ClusterNamespaces, filter QueryFilter) Q // Fetch fetches multicluster resources. func (q *APIServerQuery) Fetch(ctx context.Context, groupVersion, kind string) (map[string]interface{}, error) { + // nolint // TODO check access var err error if q.ClusterdNamespaces, err = checkMultiClusterAccess(ctx, kind, q.ClusterdNamespaces); err != nil {