diff --git a/bcs-common/common/bcs-health/utils/type.go b/bcs-common/common/bcs-health/utils/type.go index a1b13815d5..9fa5576cd7 100644 --- a/bcs-common/common/bcs-health/utils/type.go +++ b/bcs-common/common/bcs-health/utils/type.go @@ -36,7 +36,7 @@ const ( DefaultBcsEndpoints = "bcsdefault" // EndpointsEventKindLabelKey xxx // values should be AlarmType's values - EndpointsEventKindLabelKey = "bcs-endpoints-event-kind" + EndpointsEventKindLabelKey = "bcs-endpoints-event-kind" // nolint // DataIDLabelKey xxx DataIDLabelKey = "bcs-health-dataid" ) diff --git a/bcs-common/common/tcp/protocol/protocol_buffer.go b/bcs-common/common/tcp/protocol/protocol_buffer.go index 1439639b05..fd9a53385e 100644 --- a/bcs-common/common/tcp/protocol/protocol_buffer.go +++ b/bcs-common/common/tcp/protocol/protocol_buffer.go @@ -15,8 +15,9 @@ package protocol import ( "bytes" "fmt" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "io" + + "github.com/Tencent/bk-bcs/bcs-common/common/blog" ) // protocolBuffer 网络数据解析 diff --git a/bcs-common/pkg/bcsapi/storage/pod.go b/bcs-common/pkg/bcsapi/storage/pod.go index 10b7b830bb..2ffdbba2c5 100644 --- a/bcs-common/pkg/bcsapi/storage/pod.go +++ b/bcs-common/pkg/bcsapi/storage/pod.go @@ -13,8 +13,9 @@ package storage import ( - mesostype "github.com/Tencent/bk-bcs/bcs-common/common/types" core "k8s.io/api/core/v1" + + mesostype "github.com/Tencent/bk-bcs/bcs-common/common/types" ) // Pod information from diff --git a/bcs-common/pkg/bcsapiv4/http.go b/bcs-common/pkg/bcsapiv4/http.go index b1f156b90f..b1f40c5ec7 100644 --- a/bcs-common/pkg/bcsapiv4/http.go +++ b/bcs-common/pkg/bcsapiv4/http.go @@ -16,9 +16,8 @@ import ( "fmt" "net/http" - "github.com/parnurzeal/gorequest" - restclient "github.com/Tencent/bk-bcs/bcs-common/pkg/esb/client" + "github.com/parnurzeal/gorequest" ) func configureRequest(r *gorequest.SuperAgent, config *Config) *gorequest.SuperAgent { // nolint diff --git a/bcs-common/pkg/bcsapiv4/mesosdriver.go b/bcs-common/pkg/bcsapiv4/mesosdriver.go index 3f1e7ba8ee..7a481a0558 100644 --- a/bcs-common/pkg/bcsapiv4/mesosdriver.go +++ b/bcs-common/pkg/bcsapiv4/mesosdriver.go @@ -17,13 +17,12 @@ import ( "fmt" "net/http" - blog "k8s.io/klog/v2" - "github.com/Tencent/bk-bcs/bcs-common/common/http/httpclient" commtypes "github.com/Tencent/bk-bcs/bcs-common/common/types" moduleDiscovery "github.com/Tencent/bk-bcs/bcs-common/pkg/module-discovery" "github.com/Tencent/bk-bcs/bcs-common/pkg/networkdetection/types" schedtypes "github.com/Tencent/bk-bcs/bcs-common/pkg/scheduler/types" + blog "k8s.io/klog/v2" ) // MesosDriver http API SDK definition diff --git a/bcs-common/pkg/bcsapiv4/netservice.go b/bcs-common/pkg/bcsapiv4/netservice.go index fc1271e491..4c0b56d866 100644 --- a/bcs-common/pkg/bcsapiv4/netservice.go +++ b/bcs-common/pkg/bcsapiv4/netservice.go @@ -27,11 +27,11 @@ import ( "strings" "time" - blog "k8s.io/klog/v2" - "github.com/Tencent/bk-bcs/bcs-common/common/ssl" bcstypes "github.com/Tencent/bk-bcs/bcs-common/common/types" "github.com/Tencent/bk-bcs/bcs-common/common/zkclient" + blog "k8s.io/klog/v2" + types "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4/netservice" ) @@ -222,7 +222,7 @@ func (nc *NetserviceCli) UpdatePool(pool *types.NetPool) error { blog.Info("udpate pool string:%s", reqDatas) seq := nc.random.Perm(len(nc.netSvrs)) httpClient, prefix := nc.getHTTPClient(nc.httpClientTimeout) - uri := prefix + nc.netSvrs[seq[0]] + "/v1/pool/" + pool.Cluster + "/" + pool.Net + uri := prefix + nc.netSvrs[seq[0]] + "/v1/pool/" + pool.Cluster + "/" + pool.Net // nolint request, err := http.NewRequest("PUT", uri, bytes.NewBuffer(reqDatas)) if err != nil { return fmt.Errorf("update pool create http request failed, %s", err.Error()) diff --git a/bcs-common/pkg/bcsapiv4/storage.go b/bcs-common/pkg/bcsapiv4/storage.go index c3bfe86228..6c76625640 100644 --- a/bcs-common/pkg/bcsapiv4/storage.go +++ b/bcs-common/pkg/bcsapiv4/storage.go @@ -17,14 +17,14 @@ import ( "fmt" "strings" - blog "k8s.io/klog/v2" - "github.com/Tencent/bk-bcs/bcs-common/common/types" "github.com/Tencent/bk-bcs/bcs-common/common/version" - "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4/storage" restclient "github.com/Tencent/bk-bcs/bcs-common/pkg/esb/client" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/drivers" registry "github.com/Tencent/bk-bcs/bcs-common/pkg/registryv4" + blog "k8s.io/klog/v2" + + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4/storage" ) const ( @@ -119,7 +119,7 @@ type StorageCli struct { // QueryK8sReplicaSet query k8s replicaset in specified cluster and namespace func (c *StorageCli) QueryK8sReplicaSet(cluster, namespace, name string) ([]*storage.ReplicaSet, error) { - subPath := "/k8s/dynamic/namespace_resources/clusters/%s/namespaces/" + namespace + "/ReplicaSet?" + subPath := "/k8s/dynamic/namespace_resources/clusters/%s/namespaces/" + namespace + "/ReplicaSet?" // nolint if name != "" { subPath += "resourceName=" + name + "&" } diff --git a/bcs-common/pkg/bcsapiv4/storage/object.go b/bcs-common/pkg/bcsapiv4/storage/object.go index 93e20ba0c0..fb691345a9 100644 --- a/bcs-common/pkg/bcsapiv4/storage/object.go +++ b/bcs-common/pkg/bcsapiv4/storage/object.go @@ -15,16 +15,16 @@ package storage import ( "time" + commtypes "github.com/Tencent/bk-bcs/bcs-common/common/types" + schedtype "github.com/Tencent/bk-bcs/bcs-common/pkg/scheduler/types" appv1 "k8s.io/api/apps/v1" autoscalingv1 "k8s.io/api/autoscaling/v1" corev1 "k8s.io/api/core/v1" storagev1 "k8s.io/api/storage/v1" - commtypes "github.com/Tencent/bk-bcs/bcs-common/common/types" gdv1alpha1 "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4/storage/tkex/gamedeployment/v1alpha1" gsv1alpha1 "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4/storage/tkex/gamestatefulset/v1alpha1" gpav1alpha1 "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4/storage/tkex/generalpodautoscaler/v1alpha1" - schedtype "github.com/Tencent/bk-bcs/bcs-common/pkg/scheduler/types" ) // Namespace is k8s namespace diff --git a/bcs-common/pkg/bcsapiv4/storage/pod.go b/bcs-common/pkg/bcsapiv4/storage/pod.go index 2ffdbba2c5..10b7b830bb 100644 --- a/bcs-common/pkg/bcsapiv4/storage/pod.go +++ b/bcs-common/pkg/bcsapiv4/storage/pod.go @@ -13,9 +13,8 @@ package storage import ( - core "k8s.io/api/core/v1" - mesostype "github.com/Tencent/bk-bcs/bcs-common/common/types" + core "k8s.io/api/core/v1" ) // Pod information from diff --git a/bcs-common/pkg/msgqueue/broker.go b/bcs-common/pkg/msgqueue/broker.go index db67af8c64..90714c6622 100644 --- a/bcs-common/pkg/msgqueue/broker.go +++ b/bcs-common/pkg/msgqueue/broker.go @@ -17,8 +17,8 @@ import ( "time" "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-plugins/broker/rabbitmq/v2" - "github.com/micro/go-plugins/broker/stan/v2" + rabbitmqv2 "github.com/micro/go-plugins/broker/rabbitmq/v2" + stanv2 "github.com/micro/go-plugins/broker/stan/v2" "github.com/pkg/errors" ) @@ -26,18 +26,18 @@ import ( // rabbitmq broker init: brokerOptions/init/connect func rabbitmqBroker(q *QueueOptions) (broker.Broker, error) { var brokerOpts []broker.Option - brokerOpts = append(brokerOpts, broker.Addrs(q.CommonOptions.Address), rabbitmq.ExchangeName(q.Exchange.Name), - rabbitmq.PrefetchCount(q.Exchange.PrefetchCount)) + brokerOpts = append(brokerOpts, broker.Addrs(q.CommonOptions.Address), rabbitmqv2.ExchangeName(q.Exchange.Name), + rabbitmqv2.PrefetchCount(q.Exchange.PrefetchCount)) // exchange durable feature if q.Exchange.Durable { - brokerOpts = append(brokerOpts, rabbitmq.DurableExchange()) + brokerOpts = append(brokerOpts, rabbitmqv2.DurableExchange()) } // prefetchGlobal feature if q.Exchange.PrefetchGlobal { - brokerOpts = append(brokerOpts, rabbitmq.PrefetchGlobal()) + brokerOpts = append(brokerOpts, rabbitmqv2.PrefetchGlobal()) } - brokerRabbit := rabbitmq.NewBroker(brokerOpts...) + brokerRabbit := rabbitmqv2.NewBroker(brokerOpts...) // init rabbitmq broker err := brokerRabbit.Init() @@ -56,13 +56,13 @@ func rabbitmqBroker(q *QueueOptions) (broker.Broker, error) { // natstreamingBroker broker init: natsreaming options/init/connect func natstreamingBroker(q *QueueOptions) (broker.Broker, error) { var brokerOpts []broker.Option - brokerOpts = append(brokerOpts, stan.ClusterID(q.NatsOptions.ClusterID), broker.Addrs(q.CommonOptions.Address)) + brokerOpts = append(brokerOpts, stanv2.ClusterID(q.NatsOptions.ClusterID), broker.Addrs(q.CommonOptions.Address)) // exchange durable feature if q.NatsOptions.ConnectRetry { - brokerOpts = append(brokerOpts, stan.ConnectTimeout(time.Minute*5), stan.ConnectRetry(true)) + brokerOpts = append(brokerOpts, stanv2.ConnectTimeout(time.Minute*5), stanv2.ConnectRetry(true)) } - brokerNatstreaming := stan.NewBroker(brokerOpts...) + brokerNatstreaming := stanv2.NewBroker(brokerOpts...) // init natstreaming broker err := brokerNatstreaming.Init() diff --git a/bcs-common/pkg/msgqueue/queue.go b/bcs-common/pkg/msgqueue/queue.go index 525c23f173..3d86421702 100644 --- a/bcs-common/pkg/msgqueue/queue.go +++ b/bcs-common/pkg/msgqueue/queue.go @@ -17,8 +17,8 @@ import ( "fmt" "github.com/micro/go-micro/v2/broker" - "github.com/micro/go-plugins/broker/rabbitmq/v2" - "github.com/micro/go-plugins/broker/stan/v2" + rabbitmqv2 "github.com/micro/go-plugins/broker/rabbitmq/v2" + stanv2 "github.com/micro/go-plugins/broker/stan/v2" natstan "github.com/nats-io/stan.go" "github.com/pkg/errors" @@ -99,7 +99,7 @@ func (mq *MsgQueue) Publish(data *broker.Message) error { switch mq.queueOptions.CommonOptions.QueueKind { case RABBITMQ: - err = mq.broker.Publish(queueName, data, rabbitmq.DeliveryMode(mq.queueOptions.PublishOptions.DeliveryMode)) + err = mq.broker.Publish(queueName, data, rabbitmqv2.DeliveryMode(mq.queueOptions.PublishOptions.DeliveryMode)) case NATSTREAMING: err = mq.broker.Publish(queueName, data) default: @@ -191,19 +191,19 @@ func (mq *MsgQueue) getSubOptions(queueName string) ([]broker.SubscribeOption, e subOptions = append(subOptions, broker.DisableAutoAck()) } if mq.queueOptions.SubscribeOptions.AckOnSuccess { - subOptions = append(subOptions, rabbitmq.AckOnSuccess()) + subOptions = append(subOptions, rabbitmqv2.AckOnSuccess()) } switch mq.queueOptions.CommonOptions.QueueKind { case RABBITMQ: if mq.queueOptions.SubscribeOptions.Durable { - subOptions = append(subOptions, rabbitmq.DurableQueue()) + subOptions = append(subOptions, rabbitmqv2.DurableQueue()) } if mq.queueOptions.SubscribeOptions.RequeueOnError { - subOptions = append(subOptions, rabbitmq.RequeueOnError()) + subOptions = append(subOptions, rabbitmqv2.RequeueOnError()) } if len(mq.queueOptions.SubscribeOptions.QueueArguments) > 0 { - subOptions = append(subOptions, rabbitmq.QueueArguments(mq.queueOptions.SubscribeOptions.QueueArguments)) + subOptions = append(subOptions, rabbitmqv2.QueueArguments(mq.queueOptions.SubscribeOptions.QueueArguments)) } case NATSTREAMING: var natsopts []natstan.SubscriptionOption @@ -222,7 +222,7 @@ func (mq *MsgQueue) getSubOptions(queueName string) ([]broker.SubscribeOption, e if mq.queueOptions.SubscribeOptions.MaxInFlight != 0 { natsopts = append(natsopts, natstan.MaxInflight(mq.queueOptions.SubscribeOptions.MaxInFlight)) } - subOptions = append(subOptions, stan.SubscribeOption(natsopts...)) + subOptions = append(subOptions, stanv2.SubscribeOption(natsopts...)) default: return nil, errors.New("unsupported queue kind") } diff --git a/bcs-common/pkg/registryv4/etcd.go b/bcs-common/pkg/registryv4/etcd.go index 0f9e283ea3..5055ca4a2a 100644 --- a/bcs-common/pkg/registryv4/etcd.go +++ b/bcs-common/pkg/registryv4/etcd.go @@ -30,19 +30,19 @@ import ( // NewEtcdRegistry create etcd registry instance func NewEtcdRegistry(option *Options) Registry { - //setting default options + // setting default options if option.TTL == time.Duration(0) { - option.TTL = time.Duration(time.Second * 40) + option.TTL = time.Second * 40 } if option.Interval == time.Duration(0) { - option.Interval = time.Duration(time.Second * 30) + option.Interval = time.Second * 30 } - //create etcd registry + // create etcd registry r := etcd.NewRegistry( registry.Addrs(option.RegistryAddr...), registry.TLSConfig(option.Config), ) - //creat local service + // creat local service option.id = uuid.New().String() if option.Meta == nil { option.Meta = make(map[string]string) @@ -69,15 +69,15 @@ func NewEtcdRegistry(option *Options) Registry { localCache: make(map[string]*registry.Service), registered: false, } - //check event handler + // check event handler if len(option.Modules) != 0 { - //setting module that watch + // setting module that watch e.localModules = make(map[string]bool) for _, name := range option.Modules { e.localModules[name] = true _, _ = e.innerGet(name) } - //start to watch all event + // start to watch all event go e.innerWatch(e.ctx) } return e @@ -107,7 +107,7 @@ func (e *etcdRegister) Register() error { return err } e.registered = true - //start background goroutine for interval keep alive + // start background goroutine for interval keep alive // because we setting ttl for register go func() { tick := time.NewTicker(e.option.Interval) @@ -115,7 +115,7 @@ func (e *etcdRegister) Register() error { for { select { case <-tick.C: - //ready to keepAlive registered node information + // ready to keepAlive registered node information if err := e.innerRegister(); err != nil { blog.Errorf("register %s information %++v failed, %s", e.localService.Name, e.localService, err.Error()) blog.Warnf("try register next tick...") @@ -131,13 +131,13 @@ func (e *etcdRegister) Register() error { func (e *etcdRegister) innerRegister() (err error) { for i := 0; i < 3; i++ { if err = e.etcdregistry.Register(e.localService, registry.RegisterTTL(e.option.TTL)); err != nil { - //try again until max failed + // try again until max failed roption := e.etcdregistry.Options() blog.Errorf("etcd registry register err, %s, options: %+v\n", err.Error(), roption) time.Sleep(backoff.Do(i + 1)) continue } - //register success, clean error + // register success, clean error err = nil break } @@ -146,9 +146,9 @@ func (e *etcdRegister) innerRegister() (err error) { // Deregister clean service information from registry func (e *etcdRegister) Deregister() error { - //stop background keepalive goroutine + // stop background keepalive goroutine e.stop() - //clean registered node information + // clean registered node information if err := e.etcdregistry.Deregister(e.localService); err != nil { blog.Warnf("Deregister %s information %++v failed, %s", e.localService.Name, e.localService, err.Error()) } @@ -171,8 +171,9 @@ func (e *etcdRegister) Get(name string) (*registry.Service, error) { return svc, nil } +// nolint func (e *etcdRegister) innerGet(name string) (*registry.Service, error) { - //first, get details from registry + // first, get details from registry svcs, err := e.etcdregistry.GetService(name) if err == registry.ErrNotFound { blog.Warnf("registry found no module %s under registry, clean local cache.", name) @@ -207,7 +208,7 @@ func (e *etcdRegister) innerGet(name string) (*registry.Service, error) { } func (e *etcdRegister) innerWatch(ctx context.Context) { - //check if discovery is stopped + // check if discovery is stopped select { case <-ctx.Done(): blog.Infof("registry is ready to exit...") @@ -219,7 +220,7 @@ func (e *etcdRegister) innerWatch(ctx context.Context) { watcher, err := e.etcdregistry.Watch(registry.WatchContext(ctx)) if err != nil { blog.Errorf("registry create watcher for all registry modules failed, %s. retry after a tick", err.Error()) - //retry after + // retry after <-time.After(time.Second * 3) go e.innerWatch(ctx) return @@ -261,7 +262,7 @@ func (e *etcdRegister) handleEvent(r *registry.Result) { blog.Errorf("registry get module %s information failed, %s", fullName, err.Error()) return } - //check event handler + // check event handler if e.option.EvtHandler != nil { e.option.EvtHandler(fullName) } diff --git a/bcs-common/pkg/registryv4/registry.go b/bcs-common/pkg/registryv4/registry.go index ac8d263b22..3626411c9f 100644 --- a/bcs-common/pkg/registryv4/registry.go +++ b/bcs-common/pkg/registryv4/registry.go @@ -16,29 +16,29 @@ import ( "crypto/tls" "time" - //microRegistry "github.com/micro/go-micro/v2/registry" + // microRegistry "github.com/micro/go-micro/v2/registry" "go-micro.dev/v4/registry" ) // Options registry options type Options struct { - //UUID for registry + // UUID for registry id string - //Registry address, formation like ip:port + // Registry address, formation like ip:port RegistryAddr []string - //register name, like $module.bkbcs.tencent.com + // register name, like $module.bkbcs.tencent.com Name string - //bkbcs version information + // bkbcs version information Version string - //Meta info for go-micro registry + // Meta info for go-micro registry Meta map[string]string - //Address information for other module discovery + // Address information for other module discovery // format likes ip:port RegAddr string Config *tls.Config TTL time.Duration Interval time.Duration - //EventHandler & modules that registry watchs + // EventHandler & modules that registry watchs EvtHandler EventHandler Modules []string } @@ -48,14 +48,14 @@ type EventHandler func(name string) // Registry interface for go-micro etcd discovery type Registry interface { - //Register service information to registry + // Register service information to registry // register do not block, if module want to // clean registe information, call Deregister Register() error - //Deregister clean service information from registry + // Deregister clean service information from registry // it means that registry is ready to exit Deregister() error - //Get get specified service by name in local cache - //Get(name string) (*microRegistry.Service, error) + // Get get specified service by name in local cache + // Get(name string) (*microRegistry.Service, error) Get(name string) (*registry.Service, error) } diff --git a/bcs-common/pkg/storage/http/client.go b/bcs-common/pkg/storage/http/client.go index b8e19686d6..3025979828 100644 --- a/bcs-common/pkg/storage/http/client.go +++ b/bcs-common/pkg/storage/http/client.go @@ -41,7 +41,7 @@ const ( var ( // PrevDataErr this error means operation success, but got previous data failed - PrevDataErr = errors.New("Previous data err") + PrevDataErr = errors.New("Previous data err") // nolint ) // Config etcd storage config @@ -247,7 +247,7 @@ func (s *Client) Watch(_ context.Context, key, _ string, selector storage.Select // fullPath = fullPath + "?labelSelector=" + selector.String() + "&watch=true" fullPath = fullPath + "?" + selector.String() + "&watch=true" } else { - fullPath = fullPath + "?watch=true" + fullPath += "?watch=true" } request, err := syshttp.NewRequest("GET", fullPath, nil) if err != nil { diff --git a/bcs-common/pkg/storage/interface.go b/bcs-common/pkg/storage/interface.go index 5c242ff0c9..ef30c7180a 100644 --- a/bcs-common/pkg/storage/interface.go +++ b/bcs-common/pkg/storage/interface.go @@ -16,10 +16,10 @@ package storage import ( "errors" + "golang.org/x/net/context" + "github.com/Tencent/bk-bcs/bcs-common/pkg/meta" "github.com/Tencent/bk-bcs/bcs-common/pkg/watch" - - "golang.org/x/net/context" ) var ( diff --git a/bcs-common/pkg/storage/zookeeper/util.go b/bcs-common/pkg/storage/zookeeper/util.go index 6e65b184ba..f0cde06a76 100644 --- a/bcs-common/pkg/storage/zookeeper/util.go +++ b/bcs-common/pkg/storage/zookeeper/util.go @@ -158,6 +158,7 @@ func (n *Node) Stop() { // selfLoop check self node & ends // for zookeeper, it's not easy to iterate all data when Synchronization, // so after watch data nodes, we decide to force sync datas every 45 seconds +// nolint func (n *Node) selfLoop() { if n.isStopped { return diff --git a/bcs-common/pkg/tracing/otgrpc/server.go b/bcs-common/pkg/tracing/otgrpc/server.go index 46a045fa23..420136393b 100644 --- a/bcs-common/pkg/tracing/otgrpc/server.go +++ b/bcs-common/pkg/tracing/otgrpc/server.go @@ -27,7 +27,7 @@ import ( var ( // gRPCComponentTag component tag: grpc - gRPCComponentTag = opentrace.Tag{string(ext.Component), "gRPC"} + gRPCComponentTag = opentrace.Tag{Key: string(ext.Component), Value: "gRPC"} ) // OpenTracingServerInterceptor returns a grpc.UnaryServerInterceptor suitable for use in a grpc.NewServer call. diff --git a/bcs-scenarios/bcs-gitops-manager/cmd/gitgenerator-webhook/main.go b/bcs-scenarios/bcs-gitops-manager/cmd/gitgenerator-webhook/main.go index b3383e6bd6..b552d21b2f 100644 --- a/bcs-scenarios/bcs-gitops-manager/cmd/gitgenerator-webhook/main.go +++ b/bcs-scenarios/bcs-gitops-manager/cmd/gitgenerator-webhook/main.go @@ -8,14 +8,15 @@ * 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 xxx package main import ( "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/common/conf" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/cmd/gitgenerator-webhook/options" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/cmd/gitgenerator-webhook/webhook" ) 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 588474922b..6f8726b933 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 @@ -8,7 +8,6 @@ * 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 options xxx 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 946508cf9d..b86c2b6648 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 @@ -8,7 +8,6 @@ * 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 webhook xxx @@ -22,6 +21,7 @@ import ( "net/http" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" clusterclient "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster" "github.com/argoproj/argo-cd/v2/pkg/apis/application" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" @@ -31,7 +31,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/cmd/gitgenerator-webhook/options" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/store" ) @@ -81,7 +80,7 @@ func (s *AdmissionWebhookServer) Run() error { srv := &http.Server{ Addr: fmt.Sprintf("%s:%d", s.cfg.ListenAddr, s.cfg.ListenPort), Handler: s.HttpHandler, - TLSConfig: &tls.Config{ + TLSConfig: &tls.Config{ // nolint Certificates: []tls.Certificate{pair}, }, } @@ -117,14 +116,13 @@ func (s *AdmissionWebhookServer) check(ctx *gin.Context) { } // Check request whether is nil. req := ar.Request - if req != nil { - blog.Infof("Received request. UID: %s, Name: %s, Operation: %s, Kind: %v.", req.UID, req.Name, - req.Operation, req.Kind) - } else { + if req == nil { blog.Errorf("request is nil") s.webhookAllow(ctx, true, "", "") return } + blog.Infof("Received request. UID: %s, Name: %s, Operation: %s, Kind: %v.", req.UID, req.Name, + req.Operation, req.Kind) switch req.Kind.Kind { case application.ApplicationKind: @@ -143,6 +141,7 @@ var ( defaultTimeout = 15 * time.Second ) +// nolint funlen func (s *AdmissionWebhookServer) checkApplication(ctx context.Context, bs []byte) error { app := new(v1alpha1.Application) if err := json.Unmarshal(bs, app); err != nil { diff --git a/bcs-scenarios/bcs-gitops-manager/cmd/manager/cmd.go b/bcs-scenarios/bcs-gitops-manager/cmd/manager/cmd.go index fa9af3b1c9..0955f597ac 100644 --- a/bcs-scenarios/bcs-gitops-manager/cmd/manager/cmd.go +++ b/bcs-scenarios/bcs-gitops-manager/cmd/manager/cmd.go @@ -10,15 +10,16 @@ * limitations under the License. */ +// Package manager xxx package manager import ( "fmt" "os" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/spf13/cobra" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" ) @@ -36,7 +37,7 @@ func NewCommand() *cobra.Command { Short: "bcs-gitops-manager is a bcs-service for gitops", Long: `bcs-gitops-manager integrates gitops sulotion into bcs-services.`, RunE: func(cmd *cobra.Command, args []string) error { // nolint - //loading configuration file for options + // loading configuration file for options if err := common.LoadConfigFile(configFile, option); err != nil { fmt.Fprintf(os.Stderr, "server load json config file failure, %s\n", err.Error()) return err @@ -62,7 +63,7 @@ func NewCommand() *cobra.Command { return serv.Run() }, } - //setting server configuration flag + // setting server configuration flag cmd.Flags().StringVarP(&configFile, "config", "c", configFile, "manager configuration json file") return cmd } diff --git a/bcs-scenarios/bcs-gitops-manager/cmd/manager/options.go b/bcs-scenarios/bcs-gitops-manager/cmd/manager/options.go index f2c7cd6546..6e741e3be3 100644 --- a/bcs-scenarios/bcs-gitops-manager/cmd/manager/options.go +++ b/bcs-scenarios/bcs-gitops-manager/cmd/manager/options.go @@ -17,6 +17,7 @@ import ( "strings" "github.com/Tencent/bk-bcs/bcs-common/common/conf" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/store/secretstore" ) diff --git a/bcs-scenarios/bcs-gitops-manager/cmd/manager/server.go b/bcs-scenarios/bcs-gitops-manager/cmd/manager/server.go index e4b509add1..e5bc203eb7 100644 --- a/bcs-scenarios/bcs-gitops-manager/cmd/manager/server.go +++ b/bcs-scenarios/bcs-gitops-manager/cmd/manager/server.go @@ -26,6 +26,10 @@ import ( ossync "sync" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/common/version" + "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" + "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/jwt" etcdsync "github.com/asim/go-micro/plugins/sync/etcd/v4" grpccli "github.com/go-micro/plugins/v4/client/grpc" "github.com/go-micro/plugins/v4/registry/etcd" @@ -34,18 +38,13 @@ import ( "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus/promhttp" + "go-micro.dev/v4" "go-micro.dev/v4/registry" "go-micro.dev/v4/sync" "go-micro.dev/v4/util/file" "google.golang.org/grpc" "google.golang.org/grpc/credentials" - "go-micro.dev/v4" - - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/common/version" - "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" - "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/jwt" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/handler" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/internal/component" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/internal/dao" @@ -585,7 +584,6 @@ func (s *Server) startAnalysis() { blog.Fatalf("start analysis failed: %s", err.Error()) } blog.Infof("analysis started") - return } func (s *Server) startSignalHandler() { diff --git a/bcs-scenarios/bcs-gitops-manager/cmd/proxy/main.go b/bcs-scenarios/bcs-gitops-manager/cmd/proxy/main.go index a290d7a5fb..bfe6ddf18d 100644 --- a/bcs-scenarios/bcs-gitops-manager/cmd/proxy/main.go +++ b/bcs-scenarios/bcs-gitops-manager/cmd/proxy/main.go @@ -10,6 +10,7 @@ * limitations under the License. */ +// Package main xxx package main import ( diff --git a/bcs-scenarios/bcs-gitops-manager/cmd/proxy/server/cmd.go b/bcs-scenarios/bcs-gitops-manager/cmd/proxy/server/cmd.go index 49427efaa6..4cdf19c69f 100644 --- a/bcs-scenarios/bcs-gitops-manager/cmd/proxy/server/cmd.go +++ b/bcs-scenarios/bcs-gitops-manager/cmd/proxy/server/cmd.go @@ -10,15 +10,16 @@ * limitations under the License. */ +// Package server xxx package server import ( "fmt" "os" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/spf13/cobra" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" ) @@ -36,7 +37,7 @@ func NewCommand() *cobra.Command { Short: "bcs-gitops-proxy is a proxy for gitops-manager", Long: `bcs-gitops-proxy integrates BKIAM and websocket tunnel for gitops-manager.`, RunE: func(cmd *cobra.Command, args []string) error { // nolint - //loading configuration file for options + // loading configuration file for options if err := common.LoadConfigFile(configFile, option); err != nil { fmt.Fprintf(os.Stderr, "proxy load json config file failure, %s\n", err.Error()) return err @@ -62,7 +63,7 @@ func NewCommand() *cobra.Command { return proxy.Run() }, } - //setting server configuration flag + // setting server configuration flag cmd.Flags().StringVarP(&configFile, "config", "c", configFile, "proxy configuration json file") return cmd } diff --git a/bcs-scenarios/bcs-gitops-manager/cmd/proxy/server/options.go b/bcs-scenarios/bcs-gitops-manager/cmd/proxy/server/options.go index ba1373a341..aaccb08ecc 100644 --- a/bcs-scenarios/bcs-gitops-manager/cmd/proxy/server/options.go +++ b/bcs-scenarios/bcs-gitops-manager/cmd/proxy/server/options.go @@ -16,6 +16,7 @@ import ( "fmt" "github.com/Tencent/bk-bcs/bcs-common/common/conf" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" ) diff --git a/bcs-scenarios/bcs-gitops-manager/cmd/proxy/server/proxy.go b/bcs-scenarios/bcs-gitops-manager/cmd/proxy/server/proxy.go index 5ee5157530..195612bf83 100644 --- a/bcs-scenarios/bcs-gitops-manager/cmd/proxy/server/proxy.go +++ b/bcs-scenarios/bcs-gitops-manager/cmd/proxy/server/proxy.go @@ -19,6 +19,8 @@ import ( "strings" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/common/version" grpccli "github.com/go-micro/plugins/v4/client/grpc" "github.com/go-micro/plugins/v4/registry/etcd" grpcsvr "github.com/go-micro/plugins/v4/server/grpc" @@ -26,8 +28,6 @@ import ( "go-micro.dev/v4" "go-micro.dev/v4/registry" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/common/version" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/tunnel" diff --git a/bcs-scenarios/bcs-gitops-manager/cmd/webhook/main.go b/bcs-scenarios/bcs-gitops-manager/cmd/webhook/main.go index 6a5525c444..d097ccd7e7 100644 --- a/bcs-scenarios/bcs-gitops-manager/cmd/webhook/main.go +++ b/bcs-scenarios/bcs-gitops-manager/cmd/webhook/main.go @@ -8,9 +8,9 @@ * 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 xxx package main import ( @@ -21,6 +21,7 @@ import ( "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/common/conf" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/cmd/webhook/options" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/webhook" ) @@ -39,6 +40,7 @@ func main() { go func() { interrupt := make(chan os.Signal, 10) + // nolint signal.Notify(interrupt, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM, syscall.SIGUSR1, syscall.SIGUSR2) for s := range interrupt { blog.Infof("Received signal %v from system. Exit!", s) @@ -48,6 +50,6 @@ func main() { }() if err := srv.Run(); err != nil { - os.Exit(1) + os.Exit(1) // nolint } } diff --git a/bcs-scenarios/bcs-gitops-manager/cmd/webhook/options/options.go b/bcs-scenarios/bcs-gitops-manager/cmd/webhook/options/options.go index 162af0ca95..f24eb7bcfb 100644 --- a/bcs-scenarios/bcs-gitops-manager/cmd/webhook/options/options.go +++ b/bcs-scenarios/bcs-gitops-manager/cmd/webhook/options/options.go @@ -8,7 +8,6 @@ * 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 options defines the options of webhook server diff --git a/bcs-scenarios/bcs-gitops-manager/handler/handler.go b/bcs-scenarios/bcs-gitops-manager/handler/handler.go index f8334d677c..9a3f05a74e 100644 --- a/bcs-scenarios/bcs-gitops-manager/handler/handler.go +++ b/bcs-scenarios/bcs-gitops-manager/handler/handler.go @@ -18,11 +18,12 @@ import ( "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/jwt" + "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth/project" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/controller" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/store" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/store/secretstore" pb "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/proto" - "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth/project" ) // Options for Handler diff --git a/bcs-scenarios/bcs-gitops-manager/handler/project.go b/bcs-scenarios/bcs-gitops-manager/handler/project.go index 31c532b376..7beaff0aa3 100644 --- a/bcs-scenarios/bcs-gitops-manager/handler/project.go +++ b/bcs-scenarios/bcs-gitops-manager/handler/project.go @@ -16,13 +16,13 @@ import ( "context" "fmt" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4/bcsproject" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/grpc-ecosystem/go-grpc-middleware/util/metautils" "github.com/pkg/errors" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4/bcsproject" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/utils" @@ -71,7 +71,7 @@ func (e *BcsGitopsHandler) StartupProject(ctx context.Context, req *pb.ProjectSy errors.Wrapf(err, "request project '%s' from bcs-project failed", req.GetProjectCode())) } // check the user whether have the project edit permission - if err := e.checkStartupProjectPermission(ctx, project.ProjectID); err != nil { + if err = e.checkStartupProjectPermission(ctx, project.ProjectID); err != nil { return e.startProjectResult(resp, failedCode, "", errors.Wrapf(err, "check startup project '%s' permission failed", req.GetProjectCode())) } diff --git a/bcs-scenarios/bcs-gitops-manager/internal/component/audit.go b/bcs-scenarios/bcs-gitops-manager/internal/component/audit.go index a7b7b53d35..23b4fd114c 100644 --- a/bcs-scenarios/bcs-gitops-manager/internal/component/audit.go +++ b/bcs-scenarios/bcs-gitops-manager/internal/component/audit.go @@ -8,9 +8,9 @@ * 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 component xxx package component import ( diff --git a/bcs-scenarios/bcs-gitops-manager/internal/dao/interface.go b/bcs-scenarios/bcs-gitops-manager/internal/dao/interface.go index 651ba1ce82..f3116ac023 100644 --- a/bcs-scenarios/bcs-gitops-manager/internal/dao/interface.go +++ b/bcs-scenarios/bcs-gitops-manager/internal/dao/interface.go @@ -8,9 +8,9 @@ * 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 dao xxx package dao import ( @@ -39,6 +39,7 @@ type SyncInfo struct { } const ( + // PreferenceTypeApplication xxx PreferenceTypeApplication = "application" ) @@ -56,20 +57,20 @@ type ApplicationHistoryManifest struct { ID int64 `json:"id" gorm:"column:id;primaryKey;type:int(11) AUTO_INCREMENT NOT NULL"` Project string `json:"project" gorm:"index:idx_proj;column:project;type:varchar(256) NOT NULL"` Name string `json:"name" gorm:"index:idx_name;column:name;type:varchar(128) NOT NULL"` - ApplicationUID string `json:"applicationUID" gorm:"index:idx_uid;column:applicationUID;type:varchar(64) NOT NULL"` + ApplicationUID string `json:"applicationUID" gorm:"index:idx_uid;column:applicationUID;type:varchar(64) NOT NULL"` // nolint ApplicationYaml string `json:"applicationYaml" gorm:"column:applicationYaml;type:longtext NOT NULL"` Revision string `json:"revision" gorm:"column:revision;type:varchar(256) DEFAULT NULL"` Revisions string `json:"revisions" gorm:"column:revisions;type:varchar(512) DEFAULT NULL"` ManagedResources string `json:"managedResources" gorm:"column:managedResources;type:longtext NOT NULL"` HistoryID int64 `json:"historyID" gorm:"column:historyID;type:int(11) NOT NULL"` - HistoryDeployStartedAt time.Time `json:"historyDeployStartedAt" gorm:"column:historyDeployStartedAt;type:datetime NOT NULL"` + HistoryDeployStartedAt time.Time `json:"historyDeployStartedAt" gorm:"column:historyDeployStartedAt;type:datetime NOT NULL"` // nolint HistoryDeployedAt time.Time `json:"historyDeployedAt" gorm:"column:historyDeployedAt;type:datetime NOT NULL"` HistorySource string `json:"historySource" gorm:"column:historySource;type:longtext NOT NULL"` HistorySources string `json:"historySources" gorm:"column:historySources;type:longtext NOT NULL"` } const ( - tableActivityUser = "bcs_gitops_activity_user" + tableActivityUser = "bcs_gitops_activity_user" // nolint tableSyncInfo = "bcs_gitops_sync_info" tableResourcePreference = "bcs_gitops_resource_preference" tableHistoryManifest = "bcs_gitops_app_history_manifest" diff --git a/bcs-scenarios/bcs-gitops-manager/internal/dao/mysql.go b/bcs-scenarios/bcs-gitops-manager/internal/dao/mysql.go index bae1d12ac7..29ed021aff 100644 --- a/bcs-scenarios/bcs-gitops-manager/internal/dao/mysql.go +++ b/bcs-scenarios/bcs-gitops-manager/internal/dao/mysql.go @@ -8,7 +8,6 @@ * 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 dao @@ -17,12 +16,12 @@ import ( "fmt" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" _ "github.com/go-sql-driver/mysql" // nolint "github.com/pkg/errors" "gorm.io/driver/mysql" "gorm.io/gorm" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/internal/dao/mysqlrate" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" ) @@ -111,7 +110,7 @@ func (d *driver) ListActivityUser(project string) ([]ActivityUser, error) { if err != nil { return nil, errors.Wrapf(err, "query activity users failed") } - defer rows.Close() + defer rows.Close() // nolint result := make([]ActivityUser, 0) for rows.Next() { @@ -136,7 +135,7 @@ func (d *driver) GetActivityUser(project, user string) (*ActivityUser, error) { if err != nil { return nil, errors.Wrapf(err, "get activity user failed") } - defer rows.Close() + defer rows.Close() // nolint result := make([]*ActivityUser, 0) for rows.Next() { @@ -169,7 +168,7 @@ func (d *driver) ListSyncInfosForProject(project string) ([]SyncInfo, error) { if err != nil { return nil, errors.Wrapf(err, "query resource preferences failed") } - defer rows.Close() + defer rows.Close() // nolint result := make([]SyncInfo, 0) for rows.Next() { @@ -191,7 +190,7 @@ func (d *driver) GetSyncInfo(project, cluster, app, phase string) (*SyncInfo, er if err != nil { return nil, errors.Wrapf(err, "get syncinfo failed") } - defer rows.Close() + defer rows.Close() // nolint result := make([]SyncInfo, 0) for rows.Next() { @@ -244,7 +243,7 @@ func (d *driver) ListResourcePreferences(project, resourceType string) ([]Resour if err != nil { return nil, errors.Wrapf(err, "query resource preferences failed") } - defer rows.Close() + defer rows.Close() // nolint result := make([]ResourcePreference, 0) for rows.Next() { @@ -271,7 +270,7 @@ func (d *driver) GetApplicationHistoryManifest(appName, appUID string, if err != nil { return nil, errors.Wrapf(err, "get application history manifest failed") } - defer rows.Close() + defer rows.Close() // nolint result := make([]ApplicationHistoryManifest, 0) for rows.Next() { diff --git a/bcs-scenarios/bcs-gitops-manager/internal/dao/mysqlrate/rate.go b/bcs-scenarios/bcs-gitops-manager/internal/dao/mysqlrate/rate.go index 5a4f322eff..435c9ce550 100644 --- a/bcs-scenarios/bcs-gitops-manager/internal/dao/mysqlrate/rate.go +++ b/bcs-scenarios/bcs-gitops-manager/internal/dao/mysqlrate/rate.go @@ -8,17 +8,16 @@ * 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 mysqlrate xxx package mysqlrate import ( "sync" - "gorm.io/gorm" - "github.com/Tencent/bk-bcs/bcs-common/pkg/throttle" + "gorm.io/gorm" ) var ( diff --git a/bcs-scenarios/bcs-gitops-manager/main.go b/bcs-scenarios/bcs-gitops-manager/main.go index 06133e5728..c186af8175 100644 --- a/bcs-scenarios/bcs-gitops-manager/main.go +++ b/bcs-scenarios/bcs-gitops-manager/main.go @@ -10,6 +10,7 @@ * limitations under the License. */ +// Package main xxx package main import ( diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/analysis/analysis.go b/bcs-scenarios/bcs-gitops-manager/pkg/analysis/analysis.go index b289374932..2eed37c059 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/analysis/analysis.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/analysis/analysis.go @@ -8,7 +8,6 @@ * 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 analysis xxx @@ -21,18 +20,19 @@ import ( "strings" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/pkg/errors" monitoring "github.com/prometheus-operator/prometheus-operator/pkg/client/versioned" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/internal/dao" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/metric" ) // AnalysisInterface defines the analysis data interface +// nolint type AnalysisInterface interface { Init() error Start(ctx context.Context) error @@ -48,6 +48,7 @@ type AnalysisInterface interface { } // AnalysisClient defines the client that to handle analysis data +// nolint type AnalysisClient struct { db dao.Interface metricConfig *common.MetricConfig @@ -192,6 +193,7 @@ var ( // parseAppMetrics will get the argocd application-controller's metrics, and then parse // them to get the sync info of every application and cluster +// nolint funlen func (c *AnalysisClient) parseAppMetrics(ctx context.Context) []*dao.SyncInfo { ns := c.metricConfig.AppMetricNamespace name := c.metricConfig.AppMetricName diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/common/const.go b/bcs-scenarios/bcs-gitops-manager/pkg/common/const.go index 76a9a94415..7b1b0fbdca 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/common/const.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/common/const.go @@ -10,6 +10,7 @@ * limitations under the License. */ +// Package common xxx package common const ( @@ -23,7 +24,7 @@ const ( ServiceName = "gitopsmanager.bkbcs.tencent.com" // MetaHTTPKey key for http port MetaHTTPKey = "httpport" - // ConnectURL for peer interconnection + // ConnectURI for peer interconnection ConnectURI = "/gitopsmanager/websocket/connect" // GatewayURL for gitops manager connect through bcs gateway GatewayURL = "/bcsapi/v4" + ConnectURI @@ -32,7 +33,7 @@ const ( GitOpsProxyURL = "/gitopsmanager/proxy" // HeaderServerAddressKey header key for cluster info in websocket tunnel - HeaderServerAddressKey = "BCS-GITOPS-ServerAddress" + HeaderServerAddressKey = "BCS-GITOPS-ServerAddress" // nolint // HeaderBCSClient header for bcs client HeaderBCSClient = "X-BCS-Client" // ServiceNameShort used for bcs-client header @@ -60,5 +61,5 @@ const ( // SecretKey defines the secretManager k8s secret namespace:name // NOCC:gas/crypto(工具误报) - SecretKey = "bkbcs.tencent.com/secretManager" + SecretKey = "bkbcs.tencent.com/secretManager" // nolint ) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/controller/cluster.go b/bcs-scenarios/bcs-gitops-manager/pkg/controller/cluster.go index b60b7e59a1..0612de4a5c 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/controller/cluster.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/controller/cluster.go @@ -10,6 +10,7 @@ * limitations under the License. */ +// Package controller xxx package controller import ( @@ -18,18 +19,16 @@ import ( "sync" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4/clustermanager" + cm "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4/clustermanager" + clusterclient "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster" + "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/pkg/errors" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" - "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - - clusterclient "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster" - - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4/clustermanager" - cm "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4/clustermanager" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/utils" ) @@ -64,9 +63,9 @@ func (control *cluster) Init() error { if control.option == nil { return fmt.Errorf("cluster controller lost options") } - //if control.option.Mode == common.ModeService { + // if control.option.Mode == common.ModeService { // return fmt.Errorf("service mode is not implenmented") - //} + // } // init with raw grpc connection if err := control.initClient(); err != nil { return err @@ -107,6 +106,7 @@ func (control *cluster) SingleStart(ctx context.Context) { } // ForceSync specified cluster information +// nolint funlen func (control *cluster) ForceSync(projectCode, clusterID string) { control.Lock() defer control.Unlock() @@ -161,7 +161,7 @@ func (control *cluster) ForceSync(projectCode, clusterID string) { } func (control *cluster) initClient() error { - //create grpc connection + // create grpc connection header := map[string]string{ "x-content-type": "application/grpc+proto", "Content-Type": "application/grpc", @@ -204,9 +204,9 @@ func (control *cluster) innerLoop(ctx context.Context) error { // list all cluster for every project for proID, appPro := range controlledProjects { blog.Infof("syncing clusters for project [%s]%s", appPro.Name, proID) - if err := control.syncClustersByProject(ctx, proID, appPro); err != nil { + if err = control.syncClustersByProject(ctx, proID, appPro); err != nil { blog.Errorf("sync clusters for project [%s]%s failed: %s", appPro.Name, proID, err.Error()) - //continue + // continue } blog.Infof("sync clusters for project [%s]%s complete, next...", appPro.Name, proID) @@ -221,7 +221,7 @@ func (control *cluster) innerLoop(ctx context.Context) error { blog.Infof("init project [%s]%s secrets complete", appPro.Name, proID) // sync secret info to pro annotations - //secretVal := vaultcommon.GetVaultSecForProAnno(appPro.Name) + // secretVal := vaultcommon.GetVaultSecForProAnno(appPro.Name) secretVal, err := control.option.Secret.GetProjectSecret(ctx, appPro.Name) if err != nil { blog.Errorf("[getErr]sync secret info to pro annotations [%s]%s failed: %s", appPro.Name, proID, err.Error()) @@ -233,12 +233,10 @@ func (control *cluster) innerLoop(ctx context.Context) error { if err := control.option.Storage.UpdateProject(ctx, appPro); err != nil { blog.Errorf("[existErr]sync secret info to pro annotations [%s]%s failed: %s", appPro.Name, proID, err.Error()) } - } else { - if secretVal != actualVal { - appPro.Annotations[common.SecretKey] = secretVal - if err := control.option.Storage.UpdateProject(ctx, appPro); err != nil { - blog.Errorf("[valErr]sync secret info to pro annotations [%s]%s failed: %s", appPro.Name, proID, err.Error()) - } + } else if secretVal != actualVal { + appPro.Annotations[common.SecretKey] = secretVal + if err := control.option.Storage.UpdateProject(ctx, appPro); err != nil { + blog.Errorf("[valErr]sync secret info to pro annotations [%s]%s failed: %s", appPro.Name, proID, err.Error()) } } blog.Infof("sync secret info to pro annotations[val:%s] [%s]%s complete. next...", secretVal, appPro.Name, proID) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/controller/project.go b/bcs-scenarios/bcs-gitops-manager/pkg/controller/project.go index 2c91ad24b6..7e7f907d43 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/controller/project.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/controller/project.go @@ -16,12 +16,11 @@ import ( "context" "fmt" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4/bcsproject" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" - - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4/bcsproject" ) // ProjectControl for bcs project data sync @@ -48,9 +47,9 @@ type project struct { // Init controller func (control *project) Init() error { - //if control.option.Mode == common.ModeService { + // if control.option.Mode == common.ModeService { // return fmt.Errorf("service mode is not implenmented") - //} + // } // init with raw grpc connection if err := control.initClient(); err != nil { return err @@ -93,7 +92,7 @@ func (control *project) GetProject(ctx context.Context, projectCode string) (*bc } func (control *project) initClient() error { - //create grpc connection + // create grpc connection header := map[string]string{ "x-content-type": "application/grpc+proto", "Content-Type": "application/grpc", diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/metric/metric.go b/bcs-scenarios/bcs-gitops-manager/pkg/metric/metric.go index 294c09cf54..e5fc577fd1 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/metric/metric.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/metric/metric.go @@ -8,7 +8,6 @@ * 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 metric defines the metric info of gitops @@ -54,6 +53,7 @@ var ( once sync.Once ) +// nolint func init() { once.Do(func() { ManagerTunnelConnectStatus = prometheus.NewGaugeVec(prometheus.GaugeOpts{ diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/metric/metric_query.go b/bcs-scenarios/bcs-gitops-manager/pkg/metric/metric_query.go index 2cd9a55e9b..4d2692236b 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/metric/metric_query.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/metric/metric_query.go @@ -8,7 +8,6 @@ * 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 metric @@ -20,14 +19,13 @@ import ( "net/http" "strings" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/pkg/errors" monitoring "github.com/prometheus-operator/prometheus-operator/pkg/client/versioned" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/kubernetes" - - "github.com/Tencent/bk-bcs/bcs-common/common/blog" ) // ServiceMonitorQuery defines the query client for service monitor 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..6e01137b9e 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/analysis.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/analysis.go @@ -8,7 +8,6 @@ * 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 argocd @@ -19,14 +18,14 @@ import ( "net/http" "strconv" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" appclient "github.com/argoproj/argo-cd/v2/pkg/apiclient/application" appsetpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/applicationset" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/gorilla/mux" "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/analysis" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy" @@ -137,6 +136,7 @@ func (plugin *AnalysisPlugin) analysis(r *http.Request) (*http.Request, *mw.Http }) } +// nolint func (plugin *AnalysisPlugin) handleProject(ctx context.Context, argoProj *v1alpha1.AppProject) (*ProjectAnalysis, error) { var bizID int64 diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/application.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/application.go index 3885a32e2c..f81ebb2e67 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/application.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/application.go @@ -21,14 +21,15 @@ import ( "strconv" "strings" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" + bcsapi "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4" + iamnamespace "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/namespace" appclient "github.com/argoproj/argo-cd/v2/pkg/apiclient/application" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/gorilla/mux" "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" - bcsapi "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/internal/dao" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/analysis" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" @@ -36,7 +37,6 @@ import ( "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/resources" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/store" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/utils/jsonq" - iamnamespace "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/namespace" ) // AppPlugin for internal project authorization @@ -538,7 +538,7 @@ func setParameterOverrides(app *v1alpha1.Application, parameters []string, actio helmParams := source.Helm.Parameters for i, p := range helmParams { if p.Name == paramStr { - source.Helm.Parameters = append(helmParams[0:i], helmParams[i+1:]...) + source.Helm.Parameters = append(helmParams[0:i], helmParams[i+1:]...) // nolint gocritic break } } 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 68e9944bfc..ba47f646c0 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 @@ -8,7 +8,6 @@ * 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 argocd @@ -21,6 +20,8 @@ import ( "net/http" "strings" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + iamnamespace "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/namespace" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/argoproj/argo-cd/v2/reposerver/apiclient" "github.com/pkg/errors" @@ -34,9 +35,6 @@ import ( "k8s.io/client-go/dynamic" "k8s.io/client-go/rest" - iamnamespace "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/namespace" - - "github.com/Tencent/bk-bcs/bcs-common/common/blog" mw "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" ) @@ -209,6 +207,7 @@ func buildDiffOrDryRunRequest(r *http.Request) (*ApplicationDiffOrDryRunRequest, return req, nil } +// nolint func (plugin *AppPlugin) compareApplicationManifests(ctx context.Context, req *ApplicationDiffOrDryRunRequest, application *v1alpha1.Application, isDryRun bool) ([]*Manifest, error) { originalApplication := application.DeepCopy() @@ -333,6 +332,7 @@ func decodeManifest(application *v1alpha1.Application, // manifestDryRun will check every resource's manifest existed in Kubernetes cluster. // If not exist, just save the manifest and no need to compare. If existed, there need // to compare with live. +// nolint func (plugin *AppPlugin) manifestDryRun(ctx context.Context, app *v1alpha1.Application, manifests []*Manifest) ([]*Manifest, error) { clusterServer := app.Spec.Destination.Server 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 7dc8827b8e..8139172f6d 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 @@ -8,7 +8,6 @@ * 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 argocd @@ -19,13 +18,13 @@ import ( "net/http" "strconv" + iamnamespace "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/namespace" argoappv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/gorilla/mux" "github.com/pkg/errors" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" mw "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" - iamnamespace "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/namespace" ) // ApplicationHistoryManifestResponse defines the response for get history manifests of application diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/applicationset.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/applicationset.go index 5e9296e091..4efc54de73 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/applicationset.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/applicationset.go @@ -8,7 +8,6 @@ * 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 argocd @@ -21,12 +20,12 @@ import ( "net/http" "strconv" + "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" "github.com/argoproj/argo-cd/v2/pkg/apiclient/applicationset" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/gorilla/mux" "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" mw "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/store" diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/argocd.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/argocd.go index 6bae9e6e35..2c45f61bdb 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/argocd.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/argocd.go @@ -18,11 +18,11 @@ import ( "fmt" "net/http" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + bcsapi "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4" "github.com/gorilla/mux" "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - bcsapi "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/internal/dao" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/analysis" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" @@ -41,6 +41,7 @@ func NewGitOpsProxy(opt *proxy.GitOpsOptions) proxy.GitOpsProxy { // ArgocdProxy simple revese proxy for argocd according kubernetes service. // gitops proxy implements http.Handler interface. +// nolint type ArgocdProxy struct { *mux.Router // for http handler implementation @@ -73,6 +74,7 @@ func (ops *ArgocdProxy) Stop() { } // initArgoPathHandler +// nolint func (ops *ArgocdProxy) initArgoPathHandler() error { argoSession := session.NewArgoSession(ops.option) secretSession := session.NewSecretSession(ops.option.SecretOption) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/cluster.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/cluster.go index 6ec610b7f6..7e48020b65 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/cluster.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/cluster.go @@ -15,12 +15,12 @@ package argocd import ( "net/http" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" clusterclient "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster" "github.com/gorilla/mux" "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" mw "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" ) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/grpc.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/grpc.go index 9c702a1cdb..11ff223376 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/grpc.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/grpc.go @@ -21,6 +21,9 @@ import ( "strconv" "strings" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" + iamnamespace "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/namespace" "github.com/argoproj/argo-cd/v2/pkg/apiclient/application" "github.com/argoproj/argo-cd/v2/pkg/apiclient/applicationset" "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster" @@ -32,13 +35,10 @@ import ( "google.golang.org/grpc/encoding" "google.golang.org/grpc/encoding/proto" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" mw "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" - iamnamespace "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/namespace" ) var ( @@ -65,10 +65,10 @@ func (plugin *GrpcPlugin) Init() error { "/repository.RepositoryService/ValidateAccess": plugin.handleRepoAccess, "/repository.RepositoryService/CreateRepository": plugin.handleRepoCreate, "/repository.RepositoryService/DeleteRepository": plugin.handleRepoDelete, - //"/repository.RepositoryService/ListRefs": nil, - //"/repository.RepositoryService/ListApps": nil, - //"/repository.RepositoryService/GetAppDetails": nil, - //"/repository.RepositoryService/GetHelmCharts": nil, + // "/repository.RepositoryService/ListRefs": nil, + // "/repository.RepositoryService/ListApps": nil, + // "/repository.RepositoryService/GetAppDetails": nil, + // "/repository.RepositoryService/GetHelmCharts": nil, "/cluster.ClusterService/List": plugin.handleClusterList, "/cluster.SettingsService/Get": plugin.handleClusterSettingGet, @@ -186,7 +186,8 @@ func (plugin *GrpcPlugin) handleProjectGet(r *http.Request) (*http.Request, *mw. } _, statusCode, err := plugin.middleware.CheckProjectPermission(r.Context(), query.Name, iam.ProjectView) if statusCode != http.StatusOK { - return r, mw.ReturnGRPCErrorResponse(statusCode, errors.Wrapf(err, "check project '%s' view permission failed", query.Name)) + return r, mw.ReturnGRPCErrorResponse(statusCode, errors.Wrapf(err, + "check project '%s' view permission failed", query.Name)) } return r, mw.ReturnArgoReverse() } @@ -276,6 +277,7 @@ func (plugin *GrpcPlugin) handleRepoDelete(r *http.Request) (*http.Request, *mw. } // handleRepoListRefs will list repo refs from argocd +// nolint unused func (plugin *GrpcPlugin) handleRepoListRefs(r *http.Request) (*http.Request, *mw.HttpResponse) { query := &argorepo.RepoQuery{} if err := plugin.readRequestBody(r, query); err != nil { @@ -293,6 +295,7 @@ func (plugin *GrpcPlugin) handleRepoListRefs(r *http.Request) (*http.Request, *m } // handleRepoListApps will handle repo list apps +// nolint unused func (plugin *GrpcPlugin) handleRepoListApps(r *http.Request) (*http.Request, *mw.HttpResponse) { query := &argorepo.RepoAppsQuery{} if err := plugin.readRequestBody(r, query); err != nil { @@ -310,6 +313,7 @@ func (plugin *GrpcPlugin) handleRepoListApps(r *http.Request) (*http.Request, *m } // handleRepoGetAppDetails will handle repo get application details +// nolint unused func (plugin *GrpcPlugin) handleRepoGetAppDetails(r *http.Request) (*http.Request, *mw.HttpResponse) { query := &argorepo.RepoAppDetailsQuery{} if err := plugin.readRequestBody(r, query); err != nil { @@ -327,6 +331,7 @@ func (plugin *GrpcPlugin) handleRepoGetAppDetails(r *http.Request) (*http.Reques } // handleRepoGetHelmCharts will handle repo get helm charts +// nolint unused func (plugin *GrpcPlugin) handleRepoGetHelmCharts(r *http.Request) (*http.Request, *mw.HttpResponse) { query := &argorepo.RepoQuery{} if err := plugin.readRequestBody(r, query); err != nil { @@ -361,6 +366,7 @@ func (plugin *GrpcPlugin) handleClusterList(r *http.Request) (*http.Request, *mw } // parseClusterName will parse cluster name and check it +// nolint unused func (plugin *GrpcPlugin) parseClusterName(server string) (string, error) { arr := strings.Split(server, "/") clusterID := arr[len(arr)-1] @@ -378,7 +384,8 @@ func (plugin *GrpcPlugin) handleClusterGet(r *http.Request) (*http.Request, *mw. } statusCode, err := plugin.middleware.CheckClusterPermission(r.Context(), query, iam.ClusterView) if err != nil { - return r, mw.ReturnGRPCErrorResponse(statusCode, errors.Wrapf(err, "check application '%s' permission failed", query.Name)) + return r, mw.ReturnGRPCErrorResponse(statusCode, + errors.Wrapf(err, "check application '%s' permission failed", query.Name)) } return r, mw.ReturnArgoReverse() } @@ -396,7 +403,7 @@ func (plugin *GrpcPlugin) handleAppSetList(r *http.Request) (*http.Request, *mw. return r, mw.ReturnGRPCErrorResponse(statusCode, errors.Wrapf(err, "list projects failed")) } query := new(applicationset.ApplicationSetListQuery) - if err := plugin.readRequestBody(r, query); err != nil { + if err = plugin.readRequestBody(r, query); err != nil { return r, mw.ReturnGRPCErrorResponse(http.StatusBadRequest, err) } names := make([]string, 0, len(projectList.Items)) @@ -424,10 +431,7 @@ func (plugin *GrpcPlugin) handleAppSetList(r *http.Request) (*http.Request, *mw. errors.Wrapf(err, "list applicationsets by project '%s' from storage failed", names)) } result := make([]v1alpha1.ApplicationSet, 0, len(appsetList.Items)) - for i := range appsetList.Items { - item := appsetList.Items[i] - result = append(result, item) - } + result = append(result, appsetList.Items...) appsetList.Items = result return r, mw.ReturnGRPCResponse(appsetList) } @@ -487,7 +491,7 @@ func (plugin *GrpcPlugin) handleAppList(r *http.Request) (*http.Request, *mw.Htt return r, mw.ReturnGRPCErrorResponse(statusCode, errors.Wrapf(err, "list projects failed")) } query := new(application.ApplicationQuery) - if err := plugin.readRequestBody(r, query); err != nil { + if err = plugin.readRequestBody(r, query); err != nil { return r, mw.ReturnGRPCErrorResponse(http.StatusBadRequest, err) } names := make([]string, 0, len(projectList.Items)) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/metricproxy.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/metricproxy.go index 99413efc36..623cb81d25 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/metricproxy.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/metricproxy.go @@ -8,7 +8,6 @@ * 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 argocd @@ -18,14 +17,13 @@ import ( "net/http" "strings" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/gorilla/mux" "github.com/pkg/errors" + monitoring "github.com/prometheus-operator/prometheus-operator/pkg/client/versioned" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" - monitoring "github.com/prometheus-operator/prometheus-operator/pkg/client/versioned" - - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/metric" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy" mw "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/audit.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/audit.go index fdf3793c8e..cb5d812595 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/audit.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/audit.go @@ -8,7 +8,6 @@ * 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 middleware @@ -18,40 +17,62 @@ import ( "net/http" "time" - "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/pkg/audit" + "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/internal/component" ) var ( - ApplicationCreate = "application_create" - ApplicationUpdate = "application_update" - ApplicationSync = "application_sync" - ApplicationRollback = "application_rollback" - ApplicationDelete = "application_delete" - ApplicationPatchResource = "application_patch_resource" - ApplicationDeleteResource = "application_resource_delete" - ApplicationClean = "application_clean" + // ApplicationCreate xxx + ApplicationCreate = "application_create" + // ApplicationUpdate xxx + ApplicationUpdate = "application_update" + // ApplicationSync xxx + ApplicationSync = "application_sync" + // ApplicationRollback xxx + ApplicationRollback = "application_rollback" + // ApplicationDelete xxx + ApplicationDelete = "application_delete" + // ApplicationPatchResource xxx + ApplicationPatchResource = "application_patch_resource" + // ApplicationDeleteResource xxx + ApplicationDeleteResource = "application_resource_delete" + // ApplicationClean xxx + ApplicationClean = "application_clean" + // ApplicationDeleteResources xxx ApplicationDeleteResources = "application_multiple_resources_delete" - ApplicationGRPCOperate = "application_grpc_operate" + // ApplicationGRPCOperate xxx + ApplicationGRPCOperate = "application_grpc_operate" + // ApplicationSetCreateOrUpdate xxx ApplicationSetCreateOrUpdate = "applicationset_create_or_update" - ApplicationSetDelete = "applicationset_delete" - ApplicationSetGenerate = "applicationset_generate" + // ApplicationSetDelete xxx + ApplicationSetDelete = "applicationset_delete" + // ApplicationSetGenerate xxx + ApplicationSetGenerate = "applicationset_generate" + // ProjectOpen xxx ProjectOpen = "project_open" + // RepositoryCreate xxx RepositoryCreate = "repository_create" + // RepositoryDelete xxx RepositoryDelete = "repository_delete" + // RepositoryUpdate xxx RepositoryUpdate = "repository_update" - SecretCreate = "secret_create" - SecretUpdate = "secret_update" - SecretDelete = "secret_delete" + // SecretCreate xxx + SecretCreate = "secret_create" + // SecretUpdate xxx + SecretUpdate = "secret_update" + // SecretDelete xxx + SecretDelete = "secret_delete" + // SecretRollback xxx SecretRollback = "secret_rollback" + // WebhookTriggered xxx WebhookTriggered = "webhook_triggered" ) @@ -78,6 +99,7 @@ func getRequestSourceIP(req *http.Request) string { return ip } +// nolint func handleAudit(req *http.Request, resp *HttpResponse, start, end time.Time) { method := req.Method if method != http.MethodPost && method != http.MethodPut && method != http.MethodDelete { 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 160698898d..5725575874 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 @@ -8,7 +8,6 @@ * 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 middleware @@ -22,9 +21,16 @@ import ( "sort" "strings" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" + "github.com/Tencent/bk-bcs/bcs-common/pkg/otel/trace" + "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/cluster" + "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/namespace" + iamnamespace "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/namespace" + "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/project" appclient "github.com/argoproj/argo-cd/v2/pkg/apiclient/application" appsetpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/applicationset" - + argocluster "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster" clusterclient "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/pkg/errors" @@ -32,23 +38,15 @@ import ( "go.opentelemetry.io/otel/attribute" "golang.org/x/exp/slices" - argocluster "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster" - - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" - "github.com/Tencent/bk-bcs/bcs-common/pkg/otel/trace" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/internal/dao" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/analysis" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/session" - "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/cluster" - "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/namespace" - iamnamespace "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/namespace" - "github.com/Tencent/bk-bcs/bcs-services/pkg/bcs-auth-v4/project" ) // MiddlewareInterface defines the middleware interface +// nolint type MiddlewareInterface interface { Init() error @@ -378,7 +376,7 @@ func (h *handler) CheckApplicationPermission(ctx context.Context, appName string projectID := common.GetBCSProjectID(app.Annotations) if projectID != "" { // CheckProjectPermissionByID 检查登录态用户对于项目的权限 - statusCode, err := h.CheckProjectPermissionByID(ctx, app.Spec.Project, projectID, iam.ProjectView) + statusCode, err := h.CheckProjectPermissionByID(ctx, app.Spec.Project, projectID, iam.ProjectView) // nolint if err != nil { return nil, statusCode, errors.Wrapf(err, "check project '%s' permission failed", projectID) } @@ -443,20 +441,18 @@ func (h *handler) CheckCreateApplication(ctx context.Context, app *v1alpha1.Appl } blog.Infof("RequestID[%s] check multi-source repo '%s' success", RequestID(ctx), repoUrl) } - } else { - if app.Spec.Source != nil { - repoUrl := app.Spec.Source.RepoURL - var repoBelong bool - repoBelong, err = h.checkRepositoryBelongProject(ctx, repoUrl, projectName) - if err != nil { - return http.StatusBadRequest, errors.Wrapf(err, "check repository permission failed") - } - if !repoBelong { - return http.StatusForbidden, errors.Errorf("repo '%s' not belong to project '%s'", - repoUrl, projectName) - } - blog.Infof("RequestID[%s] check source repo '%s' success", RequestID(ctx), repoUrl) + } else if app.Spec.Source != nil { + repoUrl := app.Spec.Source.RepoURL + var repoBelong bool + repoBelong, err = h.checkRepositoryBelongProject(ctx, repoUrl, projectName) + if err != nil { + return http.StatusBadRequest, errors.Wrapf(err, "check repository permission failed") + } + if !repoBelong { + return http.StatusForbidden, errors.Errorf("repo '%s' not belong to project '%s'", + repoUrl, projectName) } + blog.Infof("RequestID[%s] check source repo '%s' success", RequestID(ctx), repoUrl) } clusterQuery := clusterclient.ClusterQuery{ 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 c57d8a0985..a4c42413f5 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 @@ -8,7 +8,6 @@ * 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 middleware @@ -19,6 +18,8 @@ import ( "net/http" "strings" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" "github.com/argoproj/argo-cd/v2/applicationset/generators" "github.com/argoproj/argo-cd/v2/applicationset/services" "github.com/argoproj/argo-cd/v2/applicationset/utils" @@ -27,8 +28,6 @@ import ( "github.com/argoproj/argo-cd/v2/reposerver/apiclient" "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" ) @@ -69,7 +68,8 @@ func (h *handler) CheckCreateApplicationSet(ctx context.Context, 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 + // refer to: + // https://github.com/argoproj/argo-cd/blob/v2.8.2/applicationset/controllers/applicationset_controller.go#L499 results := make([]*v1alpha1.Application, 0) for i := range appset.Spec.Generators { generator := appset.Spec.Generators[i] @@ -171,7 +171,8 @@ func (h *handler) checkApplicationSetGenerator(ctx context.Context, appset *v1al return nil } -// refer to: https://github.com/argoproj/argo-cd/blob/v2.8.2/applicationset/controllers/applicationset_controller.go#L487 +// refer to: +// https://github.com/argoproj/argo-cd/blob/v2.8.2/applicationset/controllers/applicationset_controller.go#L487 func getTempApplication(applicationSetTemplate v1alpha1.ApplicationSetTemplate) *v1alpha1.Application { var tmplApplication v1alpha1.Application tmplApplication.Annotations = applicationSetTemplate.Annotations diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/middleware.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/middleware.go index c6408c013d..19a0454fa4 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/middleware.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/middleware.go @@ -8,7 +8,6 @@ * 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 middleware defines the middleware for gitops @@ -20,18 +19,19 @@ import ( "strings" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + traceconst "github.com/Tencent/bk-bcs/bcs-common/pkg/otel/trace/constants" + "github.com/Tencent/bk-bcs/bcs-services/cluster-resources/pkg/tracing" "github.com/google/uuid" "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - traceconst "github.com/Tencent/bk-bcs/bcs-common/pkg/otel/trace/constants" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/metric" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/session" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/utils" - "github.com/Tencent/bk-bcs/bcs-services/cluster-resources/pkg/tracing" ) +// HttpHandler xxx type HttpHandler func(r *http.Request) (*http.Request, *HttpResponse) type httpWrapper struct { @@ -76,7 +76,7 @@ func (p *httpWrapper) setContext(rw http.ResponseWriter, r *http.Request) (conte } else { requestID = uuid.New().String() } - ctx := context.WithValue(r.Context(), traceconst.RequestIDHeaderKey, requestID) + ctx := context.WithValue(r.Context(), traceconst.RequestIDHeaderKey, requestID) // nolint staticcheck ctx = tracing.ContextWithRequestID(ctx, requestID) rw.Header().Set(traceconst.RequestIDHeaderKey, requestID) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/sort.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/sort.go index 9722ea940f..edbaf2ad11 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/sort.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware/sort.go @@ -8,7 +8,6 @@ * 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 middleware diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/monitor.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/monitor.go index 4fd702a672..5346131339 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/monitor.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/monitor.go @@ -8,7 +8,6 @@ * 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 argocd @@ -17,10 +16,10 @@ import ( "fmt" "net/http" - "github.com/gorilla/mux" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" + "github.com/gorilla/mux" + mw "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" ) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/project.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/project.go index 37ddc58b0a..f25f134cec 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/project.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/project.go @@ -15,11 +15,11 @@ package argocd import ( "net/http" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" "github.com/gorilla/mux" "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/analysis" mw "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" ) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/repository.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/repository.go index 933774846d..c1571a2b50 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/repository.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/repository.go @@ -20,12 +20,12 @@ import ( "net/http" "net/url" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/gorilla/mux" "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" mw "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" ) @@ -78,6 +78,7 @@ func (plugin *RepositoryPlugin) listRepositoryHandler(r *http.Request) (*http.Re } // repository only for local json parse +// nolint unused type repository struct { // Repo contains the URL to the remote repository Repo string `json:"repo"` 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 2fa19fad2f..3cd9cf1d99 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 @@ -8,7 +8,6 @@ * 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 resources xxx @@ -18,12 +17,12 @@ import ( "context" "strings" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + bcsapi "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - bcsapi "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapiv4" mw "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/store" ) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/secret.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/secret.go index 21d2d4c9c6..75e2b2345a 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/secret.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/secret.go @@ -17,11 +17,11 @@ import ( "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" - "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" - mw "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" - "github.com/gorilla/mux" "github.com/pkg/errors" + + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" + mw "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" ) // SecretPlugin for internal project authorization diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/session/argocd.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/session/argocd.go index b16ab9201f..2a9dd7eb04 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/session/argocd.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/session/argocd.go @@ -8,9 +8,9 @@ * 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 session xxx package session import ( @@ -23,6 +23,7 @@ import ( "github.com/Tencent/bk-bcs/bcs-common/common/blog" traceconst "github.com/Tencent/bk-bcs/bcs-common/pkg/otel/trace/constants" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/metric" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy" diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/session/monitor.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/session/monitor.go index 07f48943e3..53509b9466 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/session/monitor.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/session/monitor.go @@ -8,7 +8,6 @@ * 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 session @@ -23,6 +22,7 @@ import ( "github.com/Tencent/bk-bcs/bcs-common/common/blog" traceconst "github.com/Tencent/bk-bcs/bcs-common/pkg/otel/trace/constants" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/utils" @@ -60,7 +60,7 @@ func (s *MonitorSession) ServeHTTP(rw http.ResponseWriter, req *http.Request) { request.URL = newURL }, ErrorHandler: func(res http.ResponseWriter, request *http.Request, e error) { - if !utils.IsContextCanceled(e) { + if !utils.IsContextCanceled(e) { // nolint empty branch (staticcheck) // metric.ManagerSecretProxyFailed.WithLabelValues().Inc() } blog.Errorf("RequestID[%s] monitor session proxy '%s' with header '%s' failure: %s", diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/session/secret.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/session/secret.go index 5283517224..8eed65562c 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/session/secret.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/session/secret.go @@ -8,7 +8,6 @@ * 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 session @@ -21,10 +20,10 @@ import ( "net/url" "strings" - "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" traceconst "github.com/Tencent/bk-bcs/bcs-common/pkg/otel/trace/constants" + "github.com/pkg/errors" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/metric" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy" diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/stream.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/stream.go index 02deb82a4a..5404133746 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/stream.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/stream.go @@ -16,11 +16,11 @@ import ( "fmt" "net/http" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" "github.com/gorilla/mux" "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" mw "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" ) 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 1143c4c51a..3a1b125da3 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/webhook.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/webhook.go @@ -8,7 +8,6 @@ * 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 argocd @@ -18,9 +17,9 @@ import ( "net/http" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/gorilla/mux" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" mw "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" ) @@ -47,6 +46,7 @@ func (plugin *WebhookPlugin) executeWebhook(r *http.Request) (*http.Request, *mw return r, mw.ReturnArgoReverse() } +// nolint unused func (plugin *WebhookPlugin) forwardToApplicationSet(r *http.Request, requestID string) { ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/proxy.go b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/proxy.go index 8bcd8a292d..0251a45a39 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/proxy/proxy.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/proxy/proxy.go @@ -22,14 +22,14 @@ import ( "strconv" "strings" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" + "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/jwt" "github.com/pkg/errors" "google.golang.org/grpc/codes" "google.golang.org/grpc/encoding" grpcproto "google.golang.org/grpc/encoding/proto" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" - "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/jwt" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/internal/dao" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/store" @@ -113,8 +113,10 @@ func (user *UserInfo) GetUser() string { const ( headerBKUserName = "bkUserName" - AdminClientUser = "admin" - AdminGitOpsUser = "bcs-gitops-manager" + // AdminClientUser xxx + AdminClientUser = "admin" + // AdminGitOpsUser xxx + AdminGitOpsUser = "bcs-gitops-manager" ) // GetJWTInfo from request 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 15331ce452..7b0787c111 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/store/app_history.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/store/app_history.go @@ -8,7 +8,6 @@ * 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 store @@ -19,11 +18,11 @@ import ( "strings" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" applicationpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/application" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/internal/dao" ) @@ -54,6 +53,7 @@ func (s *appHistoryStore) handle(ch chan *v1alpha1.Application) { } } +// nolint funlen func (s *appHistoryStore) handleApplication(item *v1alpha1.Application) error { if len(item.Status.History) == 0 { blog.Warnf("[HistoryStore] application '%s' have not history", item.Name) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/store/argocd.go b/bcs-scenarios/bcs-gitops-manager/pkg/store/argocd.go index d8cbfc542d..b99726ab64 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/store/argocd.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/store/argocd.go @@ -26,12 +26,20 @@ import ( "sync/atomic" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + traceconst "github.com/Tencent/bk-bcs/bcs-common/pkg/otel/trace/constants" api "github.com/argoproj/argo-cd/v2/pkg/apiclient" appclient "github.com/argoproj/argo-cd/v2/pkg/apiclient/application" + applicationpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/application" + appsetpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/applicationset" "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster" + clusterpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster" "github.com/argoproj/argo-cd/v2/pkg/apiclient/project" + projectpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/project" "github.com/argoproj/argo-cd/v2/pkg/apiclient/repository" + repositorypkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/repository" "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1" + "github.com/argoproj/argo-cd/v2/reposerver/apiclient" argoutil "github.com/argoproj/argo-cd/v2/util/argo" utilargo "github.com/argoproj/argo-cd/v2/util/argo" "github.com/argoproj/argo-cd/v2/util/argo/normalizers" @@ -46,16 +54,6 @@ import ( "k8s.io/apimachinery/pkg/watch" "k8s.io/kubernetes/pkg/kubelet/util/sliceutils" - applicationpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/application" - appsetpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/applicationset" - clusterpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster" - projectpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/project" - repositorypkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/repository" - - "github.com/argoproj/argo-cd/v2/reposerver/apiclient" - - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - traceconst "github.com/Tencent/bk-bcs/bcs-common/pkg/otel/trace/constants" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/internal/dao" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/metric" @@ -448,7 +446,7 @@ func (cd *argo) GetApplicationRevisionsMetadata(ctx context.Context, repos, if err != nil { return nil, errors.Wrapf(err, "create reposerver client failed") } - defer repoCloser.Close() + defer repoCloser.Close() // nolint result := make([]*v1alpha1.RevisionMetadata, 0, len(repos)) for i, repo := range repos { @@ -470,7 +468,8 @@ func (cd *argo) GetApplicationRevisionsMetadata(ctx context.Context, repos, } // UpdateApplicationSpec will return application by name -func (cd *argo) UpdateApplicationSpec(ctx context.Context, spec *applicationpkg.ApplicationUpdateSpecRequest) (*v1alpha1.ApplicationSpec, error) { +func (cd *argo) UpdateApplicationSpec( + ctx context.Context, spec *applicationpkg.ApplicationUpdateSpecRequest) (*v1alpha1.ApplicationSpec, error) { resp, err := cd.appClient.UpdateSpec(ctx, spec) if err != nil { return nil, errors.Wrapf(err, "update application spec '%s' failed", *spec.Name) @@ -490,7 +489,8 @@ func (cd *argo) GetApplicationResourceTree(ctx context.Context, name string) (*v } // GetApplicationManifests returns the manifests result of application -func (cd *argo) GetApplicationManifests(ctx context.Context, name, revision string) (*apiclient.ManifestResponse, error) { +func (cd *argo) GetApplicationManifests( + ctx context.Context, name, revision string) (*apiclient.ManifestResponse, error) { resp, err := cd.appClient.GetManifests(ctx, &appclient.ApplicationManifestQuery{ Name: &name, Revision: &revision, @@ -603,10 +603,8 @@ func (cd *argo) ListApplications(ctx context.Context, query *appclient.Applicati if !consistent { continue } - } else { - if queryRepo != v.Spec.Source.RepoURL { - continue - } + } else if queryRepo != v.Spec.Source.RepoURL { + continue } } if query.AppNamespace != nil && (*query.AppNamespace != "" && *query.AppNamespace != @@ -642,6 +640,7 @@ type ApplicationDeleteResourceResult struct { ErrMessage string `json:"errMessage"` } +// nolint unused func buildResourceKeyWithResourceStatus(resource *v1alpha1.ResourceStatus) string { return strings.Join([]string{resource.Kind, resource.Namespace, resource.Group, resource.Version, resource.Name}, "/") @@ -709,6 +708,7 @@ func (cd *argo) deleteApplicationResource(ctx context.Context, application *v1al }) if err != nil { if resource.Status != v1alpha1.SyncStatusCodeSynced { + // nolint goconst blog.Warnf("RequestID[%s], delete resource '%s/%s/%s' for cluster '%s' with application '%s' "+ "with status '%s', noneed care: %s", requestID, resource.Group, resource.Kind, resource.Name, @@ -785,7 +785,7 @@ func (cd *argo) initAppHistoryStore() error { func (cd *argo) initToken() error { // authorization doc: https://argo-cd.readthedocs.io/en/stable/developer-guide/api-docs/ - //$ curl $ARGOCD_SERVER/api/v1/session -d $'{"username":"admin","password":"password"}' + // $ curl $ARGOCD_SERVER/api/v1/session -d $'{"username":"admin","password":"password"}' // {"token":"...jwttoken info..."} // set token to http request header req := map[string]string{ diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/store/argoconn/conn.go b/bcs-scenarios/bcs-gitops-manager/pkg/store/argoconn/conn.go index 77d2c52d98..3e7d921d4b 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/store/argoconn/conn.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/store/argoconn/conn.go @@ -8,9 +8,9 @@ * 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 argoconn xxx package argoconn import ( @@ -69,8 +69,7 @@ func NewConn(op *api.ClientOptions) (*grpc.ClientConn, io.Closer, error) { serverAddr := op.ServerAddr network := "tcp" - var creds credentials.TransportCredentials - creds = credentials.NewTLS(&tls.Config{ + var creds = credentials.NewTLS(&tls.Config{ InsecureSkipVerify: true, // nolint }) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/store/secretstore/secret.go b/bcs-scenarios/bcs-gitops-manager/pkg/store/secretstore/secret.go index ba4bb6d728..5386e3bc28 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/store/secretstore/secret.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/store/secretstore/secret.go @@ -8,7 +8,6 @@ * 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 secretstore defines the function for vaultplugin @@ -39,6 +38,7 @@ type secretStore struct { } // SecretStoreOptions defines the options of secret store +// nolint type SecretStoreOptions struct { Address string `json:"address"` Port string `json:"port"` diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/store/store.go b/bcs-scenarios/bcs-gitops-manager/pkg/store/store.go index 79edc26a45..b405179104 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/store/store.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/store/store.go @@ -26,7 +26,6 @@ import ( settings_util "github.com/argoproj/argo-cd/v2/util/settings" "github.com/pkg/errors" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" ) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/tunnel/client.go b/bcs-scenarios/bcs-gitops-manager/pkg/tunnel/client.go index b61826511a..2600e740e1 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/tunnel/client.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/tunnel/client.go @@ -10,6 +10,7 @@ * limitations under the License. */ +// Package tunnel xxx package tunnel import ( @@ -21,6 +22,7 @@ import ( "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/common/websocketDialer" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/metric" ) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/tunnel/peermanager.go b/bcs-scenarios/bcs-gitops-manager/pkg/tunnel/peermanager.go index 793649c84b..b46c2eec1c 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/tunnel/peermanager.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/tunnel/peermanager.go @@ -21,10 +21,10 @@ import ( "sync" "time" - "go-micro.dev/v4/registry" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/common/websocketDialer" + "go-micro.dev/v4/registry" + localcommon "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" ) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/tunnel/tunnelmanager.go b/bcs-scenarios/bcs-gitops-manager/pkg/tunnel/tunnelmanager.go index ca3755231e..4c25e164d9 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/tunnel/tunnelmanager.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/tunnel/tunnelmanager.go @@ -23,14 +23,14 @@ import ( "sync" "time" - "go-micro.dev/v4/registry" - "k8s.io/apimachinery/pkg/util/proxy" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/common/websocketDialer" + "go-micro.dev/v4/registry" + "k8s.io/apimachinery/pkg/util/proxy" ) // TunnelOptions for manage tunnel server +// nolint type TunnelOptions struct { Context context.Context // ID to identify tunnel instance @@ -87,7 +87,7 @@ func NewTunnelManager(opt *TunnelOptions) *TunnelManager { } // TunnelManager holds tunnel and manage tunnel entry points(tranport). -// +// nolint type TunnelManager struct { option *TunnelOptions // peer manager handle proxy mutual discovery @@ -141,7 +141,7 @@ func (tm *TunnelManager) GetTunnelServer() *websocketDialer.Server { // ServeHTTP proxy specific flow to tunnel func (tm *TunnelManager) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - //feature(DeveloperJim): ClusterID indexer for multiple cluster selection + // feature(DeveloperJim): ClusterID indexer for multiple cluster selection clusterID, err := tm.option.Indexer(req) if err != nil { blog.Errorf("TunnelManager indexer clusterID failed, %s", err.Error()) @@ -176,7 +176,7 @@ func (tm *TunnelManager) lookupBackendEntryPoint(clusterID string) (*proxy.Upgra if !ok { return nil, fmt.Errorf("no session proxy in tunnel") } - //check transport in cache, build it if transport lost + // check transport in cache, build it if transport lost if cluster.MiddleTransport == nil { dialer := tm.tunnelSvr.Dialer(clusterID, time.Second*15) transport := &http.Transport{ @@ -193,7 +193,7 @@ func (tm *TunnelManager) lookupBackendEntryPoint(clusterID string) (*proxy.Upgra // wrap transport with UpgradeHandler reqLocation := cluster.ServerAddress if !strings.HasSuffix(reqLocation, "/") { - reqLocation = reqLocation + "/" + reqLocation += "/" } reqURL, err := url.Parse(reqLocation) if err != nil { diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/utils/ctx.go b/bcs-scenarios/bcs-gitops-manager/pkg/utils/ctx.go index 86994f6dda..45d82b1c00 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/utils/ctx.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/utils/ctx.go @@ -8,9 +8,9 @@ * 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 utils xxx package utils import ( diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/utils/jsonq/jsonq.go b/bcs-scenarios/bcs-gitops-manager/pkg/utils/jsonq/jsonq.go index 6eb5508125..65456bc086 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/utils/jsonq/jsonq.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/utils/jsonq/jsonq.go @@ -1,5 +1,5 @@ /* - * Tencent is pleased to support the open source community by making Blueking container Service available. + * 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 @@ -8,7 +8,6 @@ * 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 jsonq used to reserve some field from object diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/utils/tools.go b/bcs-scenarios/bcs-gitops-manager/pkg/utils/tools.go index d3cb3d9e21..b4653cdd3d 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/utils/tools.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/utils/tools.go @@ -22,9 +22,8 @@ import ( "syscall" "time" - "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/pkg/errors" ) // StopFunc define subsystem graceful stop interface diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/webhook/handler.go b/bcs-scenarios/bcs-gitops-manager/pkg/webhook/handler.go index 69904897d3..e1eaa86b5a 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/webhook/handler.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/webhook/handler.go @@ -8,7 +8,6 @@ * 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 webhook @@ -19,10 +18,10 @@ import ( "io" "net/http" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/pkg/errors" "go-micro.dev/v4/metadata" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" pb "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/proto" ) @@ -52,7 +51,8 @@ func (s *Server) TGitWebhook(ctx context.Context, req *pb.TGitWebhookRequest, re } // GeneralWebhook defines the handler of general webhook, it will add the authorization header -func (s *Server) GeneralWebhook(ctx context.Context, req *pb.GeneralWebhookRequest, resp *pb.GeneralWebhookResponse) error { +func (s *Server) GeneralWebhook( + ctx context.Context, req *pb.GeneralWebhookRequest, resp *pb.GeneralWebhookResponse) error { _, span := s.tracer.Start(ctx, "general") defer span.End() diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/webhook/homepage/homepage.go b/bcs-scenarios/bcs-gitops-manager/pkg/webhook/homepage/homepage.go index 35d9c25061..3260debf71 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/webhook/homepage/homepage.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/webhook/homepage/homepage.go @@ -8,7 +8,6 @@ * 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 homepage used to recorder the commit message @@ -21,11 +20,11 @@ import ( "net/http" "strings" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/pkg/errors" "gopkg.in/go-playground/webhooks.v5/github" "gopkg.in/go-playground/webhooks.v5/gitlab" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" ) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/webhook/jsonpb.go b/bcs-scenarios/bcs-gitops-manager/pkg/webhook/jsonpb.go index 6b4423f3dd..760a24592f 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/webhook/jsonpb.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/webhook/jsonpb.go @@ -8,7 +8,6 @@ * 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 webhook diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/webhook/transfer/tgit.go b/bcs-scenarios/bcs-gitops-manager/pkg/webhook/transfer/tgit.go index 9b3297d5ff..156befb046 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/webhook/transfer/tgit.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/webhook/transfer/tgit.go @@ -8,7 +8,6 @@ * 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 transfer @@ -18,13 +17,14 @@ import ( "encoding/json" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" ) const ( + // nolint unused tgitTraceID = "X-TRACE-ID" ) diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/webhook/transfer/transfer.go b/bcs-scenarios/bcs-gitops-manager/pkg/webhook/transfer/transfer.go index 52bdcdd8b9..a12e22976a 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/webhook/transfer/transfer.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/webhook/transfer/transfer.go @@ -8,7 +8,6 @@ * 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 transfer will transfer the webhook diff --git a/bcs-scenarios/bcs-gitops-manager/pkg/webhook/webhook.go b/bcs-scenarios/bcs-gitops-manager/pkg/webhook/webhook.go index 03b9fab4d2..1381454946 100644 --- a/bcs-scenarios/bcs-gitops-manager/pkg/webhook/webhook.go +++ b/bcs-scenarios/bcs-gitops-manager/pkg/webhook/webhook.go @@ -1,14 +1,13 @@ /* -* 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. -* + * 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 webhook defines the handle of webhook @@ -25,30 +24,29 @@ import ( "strings" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/common/ssl" + "github.com/Tencent/bk-bcs/bcs-common/common/static" + "github.com/Tencent/bk-bcs/bcs-common/pkg/otel/trace" + traceconst "github.com/Tencent/bk-bcs/bcs-common/pkg/otel/trace/constants" grpccli "github.com/go-micro/plugins/v4/client/grpc" "github.com/go-micro/plugins/v4/registry/etcd" grpcsvr "github.com/go-micro/plugins/v4/server/grpc" "github.com/google/uuid" + "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/pkg/errors" + "github.com/prometheus/client_golang/prometheus/promhttp" "go-micro.dev/v4" "go-micro.dev/v4/metadata" "go-micro.dev/v4/registry" "go-micro.dev/v4/server" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" + oteltrace "go.opentelemetry.io/otel/trace" "google.golang.org/grpc" grpccred "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" - "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" - "github.com/prometheus/client_golang/prometheus/promhttp" - oteltrace "go.opentelemetry.io/otel/trace" - - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/common/ssl" - "github.com/Tencent/bk-bcs/bcs-common/common/static" - "github.com/Tencent/bk-bcs/bcs-common/pkg/otel/trace" - traceconst "github.com/Tencent/bk-bcs/bcs-common/pkg/otel/trace/constants" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/cmd/webhook/options" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/webhook/homepage" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/webhook/transfer" @@ -56,14 +54,21 @@ import ( ) const ( + // ServiceName service name ServiceName = "gitopswebhook.bkbcs.tencent.com" - RetryTimes = 30 - RetryDuration = 10 - RpcDialTimeout = 20 + // RetryTimes xxx + RetryTimes = 30 + // RetryDuration xxx + RetryDuration = 10 + // RpcDialTimeout xxx + RpcDialTimeout = 20 + // RpcRequestTimeout xxx RpcRequestTimeout = 20 - RegisterTTL = 20 + // RegisterTTL xxx + RegisterTTL = 20 + // RegisterInterval xxx RegisterInterval = 10 ) @@ -202,12 +207,12 @@ func (s *Server) initMetricServer() { } func (s *Server) initPProf(mux *http.ServeMux) { - //blog.Infof("pprof is enabled") - //mux.HandleFunc("/debug/pprof/", pprof.Index) - //mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline) - //mux.HandleFunc("/debug/pprof/profile", pprof.Profile) - //mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol) - //mux.HandleFunc("/debug/pprof/trace", pprof.Trace) + // blog.Infof("pprof is enabled") + // mux.HandleFunc("/debug/pprof/", pprof.Index) + // mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline) + // mux.HandleFunc("/debug/pprof/profile", pprof.Profile) + // mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol) + // mux.HandleFunc("/debug/pprof/trace", pprof.Trace) } func (s *Server) initMetric(mux *http.ServeMux) { @@ -247,7 +252,7 @@ func (s *Server) initRpcServer() error { if !ok { requestID = uuid.New().String() } - ctx = context.WithValue(ctx, traceconst.RequestIDHeaderKey, requestID) + ctx = context.WithValue(ctx, traceconst.RequestIDHeaderKey, requestID) // nolint staticcheck return handlerFunc(ctx, req, rsp) } }), diff --git a/bcs-scenarios/bcs-gitops-vaultplugin-server/main.go b/bcs-scenarios/bcs-gitops-vaultplugin-server/main.go index 7812707b61..2f696693cc 100644 --- a/bcs-scenarios/bcs-gitops-vaultplugin-server/main.go +++ b/bcs-scenarios/bcs-gitops-vaultplugin-server/main.go @@ -8,9 +8,9 @@ * 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 xxx package main import ( @@ -21,6 +21,7 @@ import ( "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/common/conf" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/options" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server" ) @@ -42,6 +43,7 @@ func main() { go func() { interrupt := make(chan os.Signal, 10) + // nolint signal.Notify(interrupt, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM, syscall.SIGUSR1, syscall.SIGUSR2) for s := range interrupt { blog.Infof("Received signal %v from system. Exit!", s) @@ -51,6 +53,6 @@ func main() { }() if err := srv.Run(); err != nil { - os.Exit(1) + os.Exit(1) // nolint } } diff --git a/bcs-scenarios/bcs-gitops-vaultplugin-server/options/options.go b/bcs-scenarios/bcs-gitops-vaultplugin-server/options/options.go index b7fe366a3f..c050e8058f 100644 --- a/bcs-scenarios/bcs-gitops-vaultplugin-server/options/options.go +++ b/bcs-scenarios/bcs-gitops-vaultplugin-server/options/options.go @@ -8,7 +8,6 @@ * 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 options define the options of vaultplugin diff --git a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/argoplugin/plugin.go b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/argoplugin/plugin.go index 4ef595f0f4..65dd3f0ee2 100644 --- a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/argoplugin/plugin.go +++ b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/argoplugin/plugin.go @@ -8,19 +8,19 @@ * 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 argoplugin xxx package argoplugin import ( "context" "fmt" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/argoproj-labs/argocd-vault-plugin/pkg/types" "github.com/hashicorp/vault/api" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/secret" ) @@ -72,7 +72,8 @@ func (v *VaultArgoPlugin) GetSecrets(kvpath string, version string, } // GetIndividualSecret will get the specific secret (placeholder) from the SM backend -// For Vault, we only support placeholders replaced from the k/v pairs of a secret which cannot be individually addressed +// For Vault, +// we only support placeholders replaced from the k/v pairs of a secret which cannot be individually addressed // So, we use GetSecrets and extract the specific placeholder we want func (v *VaultArgoPlugin) GetIndividualSecret(kvpath, secret, version string, annotations map[string]string) (interface{}, error) { diff --git a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/common/const.go b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/common/const.go index 89f3bb8e75..d9fbcacbc8 100644 --- a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/common/const.go +++ b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/common/const.go @@ -10,6 +10,7 @@ * limitations under the License. */ +// Package common xxx package common const ( @@ -20,38 +21,38 @@ const ( } ` - //VaultVersion vault engine version, for secret version management and control. + // VaultVersion vault engine version, for secret version management and control. VaultVersion = "2" // default secret plugin type - secretTypeEnvKey = "secretType" - defaultSecretType = "vault" + secretTypeEnvKey = "secretType" // nolint unused + defaultSecretType = "vault" // nolint unused // default secret plugin addr - secretEndpointEnvKey = "secretEndpoints" + secretEndpointEnvKey = "secretEndpoints" // nolint unused // NOCC:gas/crypto(工具误报) - defaultSecretEndpoint = "https://bcs-gitops-vault.default.svc.cluster.local:8200" + defaultSecretEndpoint = "https://bcs-gitops-vault.default.svc.cluster.local:8200" // nolint unused // default secret car dir - secretCaDirEnvKey = "vaultCacert" - defaultSecretCaDir = "/data/bcs/certs/vaultca" + secretCaDirEnvKey = "vaultCacert" // nolint unused + defaultSecretCaDir = "/data/bcs/certs/vaultca" // nolint // default vault secret namespace - vaultSecretNamespaceEnvKey = "vaultSecretNamespace" - defaultVaultSecretNamespace = "default" + vaultSecretNamespaceEnvKey = "vaultSecretNamespace" // nolint unused + defaultVaultSecretNamespace = "default" // nolint unused defaultProjectSecretName = "vault-secret-%s" // VaultSecretPattern vault token info for project, mounts, token, ca VaultSecretPattern = "%s:%s" - vaultTokenForServerEnvKey = "secretToken" + vaultTokenForServerEnvKey = "secretToken" // nolint unused // GitopsServiceEnvKey gitops service name environment - GitopsServiceEnvKey = "GITOPS_SERVICE" + GitopsServiceEnvKey = "GITOPS_SERVICE" // nolint unused // GitopsUser gitops service user name environment - GitopsUser = "GITOPS_USER" + GitopsUser = "GITOPS_USER" // nolint unused // GitopsPassword gitops service password environment - GitopsPassword = "GITOPS_PASSWORD" + GitopsPassword = "GITOPS_PASSWORD" // nolint unused // GitopsAdminNamespace gitops service namespace environment - GitopsAdminNamespace = "GITOPS_ADMIN_NAMESPACE" + GitopsAdminNamespace = "GITOPS_ADMIN_NAMESPACE" // nolint unused ) diff --git a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/metric/metric.go b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/metric/metric.go index 8c675631c1..755942cd17 100644 --- a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/metric/metric.go +++ b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/metric/metric.go @@ -8,7 +8,6 @@ * 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 metric defines the metric info of vaultplugin diff --git a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/secret/interface.go b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/secret/interface.go index 898cd5a214..4988e93254 100644 --- a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/secret/interface.go +++ b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/secret/interface.go @@ -10,6 +10,7 @@ * limitations under the License. */ +// Package secret xxx package secret import ( @@ -23,6 +24,7 @@ import ( // project 是项目根路径,作为项目入口,来实现不同项目的软隔离隔离,通过token-policy-project来保证项目的认证 // path 是密钥存储路径,方便区分管理密钥,实现不同环境不同路径等。 类似文件系统,每个path下有目录和文件,文件里保存具体data密钥 // data 是具体密钥数据,由多个键值对组成,结构是一个 map[string]interface{} +// nolint type SecretRequest struct { Project string `json:"project"` Path string `json:"path"` @@ -30,6 +32,7 @@ type SecretRequest struct { } // SecretMetadata secret metadata +// nolint type SecretMetadata struct { CreateTime time.Time `json:"CreatedTime"` UpdatedTime time.Time `json:"UpdatedTime"` @@ -38,6 +41,7 @@ type SecretMetadata struct { } // SecretVersion secret version +// nolint type SecretVersion struct { Version int `mapstructure:"version"` CreatedTime time.Time `mapstructure:"created_time"` @@ -46,6 +50,7 @@ type SecretVersion struct { } // SecretManager secret interface +// nolint type SecretManager interface { // Init init client Init() error @@ -77,10 +82,12 @@ type SecretManager interface { UpdateSecret(ctx context.Context, req *SecretRequest) error // DeleteSecret 完全移除文件或目录的data和metadata + // nolint DeleteSecret(ctx context.Context, req *SecretRequest) error } // SecretManagerWithVersion 基于SecretManager实现版本控制管理 +// nolint type SecretManagerWithVersion interface { SecretManager diff --git a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/secret/vault.go b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/secret/vault.go index 8c5e1bbc32..ed3e24bf42 100644 --- a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/secret/vault.go +++ b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/secret/vault.go @@ -18,6 +18,7 @@ import ( "fmt" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/avast/retry-go" vault "github.com/hashicorp/vault/api" "github.com/pkg/errors" @@ -26,7 +27,6 @@ import ( "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/options" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/common" ) @@ -210,7 +210,7 @@ func (m *VaultSecretManager) GetMetadata(ctx context.Context, req *SecretRequest s, err := json.Marshal(meta) if err != nil { - return nil, errors.Wrapf(err, "json marshal failed.") + return nil, errors.Wrap(err, "json marshal failed") } data := &SecretMetadata{} if err := json.Unmarshal(s, data); err != nil { @@ -266,7 +266,8 @@ func (m *VaultSecretManager) DeleteSecret(ctx context.Context, req *SecretReques } // GetSecretWithVersion interface -func (m *VaultSecretManager) GetSecretWithVersion(ctx context.Context, req *SecretRequest, version int) (map[string]interface{}, error) { +func (m *VaultSecretManager) GetSecretWithVersion( + ctx context.Context, req *SecretRequest, version int) (map[string]interface{}, error) { secret, err := m.client.KVv2(req.Project).GetVersion(ctx, req.Path, version) if err != nil { return nil, err @@ -283,7 +284,7 @@ func (m *VaultSecretManager) GetVersionsAsList(ctx context.Context, req *SecretR s, err := json.Marshal(version) if err != nil { - return nil, errors.Wrapf(err, "json marshal failed.") + return nil, errors.Wrap(err, "json marshal failed") } var data []*SecretVersion if err = json.Unmarshal(s, &data); err != nil { diff --git a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/decryption.go b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/decryption.go index 3bbd3c8da0..7ecc9be79e 100644 --- a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/decryption.go +++ b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/decryption.go @@ -8,7 +8,6 @@ * 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 server @@ -19,6 +18,8 @@ import ( "net/http" "regexp" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/argoproj-labs/argocd-vault-plugin/pkg/auth/vault" "github.com/argoproj-labs/argocd-vault-plugin/pkg/config" "github.com/argoproj-labs/argocd-vault-plugin/pkg/kube" @@ -29,8 +30,6 @@ import ( "github.com/spf13/viper" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/argoplugin" ) diff --git a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/handler.go b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/handler.go index fd94df57f7..33cffbe946 100644 --- a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/handler.go +++ b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/handler.go @@ -8,7 +8,6 @@ * 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 server @@ -18,6 +17,7 @@ import ( "net/http" "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/metric" ) diff --git a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/secret.go b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/secret.go index 5234b388a2..fa383a7b80 100644 --- a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/secret.go +++ b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/secret.go @@ -8,7 +8,6 @@ * 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 server @@ -20,10 +19,10 @@ import ( "net/url" "strconv" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/gorilla/mux" "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/secret" ) @@ -69,7 +68,6 @@ func (s *Server) routerSaveOrUpdateSecret(w http.ResponseWriter, r *http.Request s.responseSuccess(w, nil) return } - return } func (s *Server) routerDeleteSecret(w http.ResponseWriter, r *http.Request) { @@ -92,7 +90,6 @@ func (s *Server) routerDeleteSecret(w http.ResponseWriter, r *http.Request) { return } s.responseSuccess(w, nil) - return } func (s *Server) routerGetSecret(w http.ResponseWriter, r *http.Request) { @@ -123,7 +120,6 @@ func (s *Server) routerGetSecret(w http.ResponseWriter, r *http.Request) { return } s.responseSuccess(w, sec) - return } func (s *Server) routerListSecret(w http.ResponseWriter, r *http.Request) { @@ -141,7 +137,6 @@ func (s *Server) routerListSecret(w http.ResponseWriter, r *http.Request) { return } s.responseSuccess(w, secretList) - return } func (s *Server) routerGetMetadata(w http.ResponseWriter, r *http.Request) { @@ -164,7 +159,6 @@ func (s *Server) routerGetMetadata(w http.ResponseWriter, r *http.Request) { return } s.responseSuccess(w, metadata) - return } func (s *Server) routerGetVersion(w http.ResponseWriter, r *http.Request) { @@ -188,7 +182,6 @@ func (s *Server) routerGetVersion(w http.ResponseWriter, r *http.Request) { return } s.responseSuccess(w, version) - return } func (s *Server) routerRollback(w http.ResponseWriter, r *http.Request) { @@ -208,7 +201,7 @@ func (s *Server) routerRollback(w http.ResponseWriter, r *http.Request) { v, err := strconv.Atoi(version) if err != nil { s.responseError(r, w, http.StatusBadRequest, - errors.Wrapf(err, "version %d not int format for '%s/%s'", version, opt.Project, path)) + errors.Wrapf(err, "version %s not int format for '%s/%s'", version, opt.Project, path)) return } @@ -219,7 +212,6 @@ func (s *Server) routerRollback(w http.ResponseWriter, r *http.Request) { return } s.responseSuccess(w, nil) - return } func (s *Server) routerInitProject(w http.ResponseWriter, r *http.Request) { @@ -241,7 +233,6 @@ func (s *Server) routerInitProject(w http.ResponseWriter, r *http.Request) { } blog.Infof("init project '%s' success", project) s.responseSuccess(w, nil) - return } func (s *Server) routerGetSecretAnnotation(w http.ResponseWriter, r *http.Request) { @@ -249,5 +240,4 @@ func (s *Server) routerGetSecretAnnotation(w http.ResponseWriter, r *http.Reques anno := s.secretManager.GetSecretAnnotation(project) s.responseSuccess(w, anno) - return } diff --git a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/server.go b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/server.go index 04ac22ff1a..9c4ecedb13 100644 --- a/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/server.go +++ b/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/server/server.go @@ -8,7 +8,6 @@ * 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 server defines the vaultplugin server @@ -24,14 +23,14 @@ import ( "strconv" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + traceconst "github.com/Tencent/bk-bcs/bcs-common/pkg/otel/trace/constants" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/store" "github.com/google/uuid" "github.com/gorilla/mux" "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus/promhttp" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - traceconst "github.com/Tencent/bk-bcs/bcs-common/pkg/otel/trace/constants" - "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/store" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/options" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/metric" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/secret" @@ -130,7 +129,7 @@ func (s *Server) initHTTPService() error { if requestID == "" { requestID = uuid.New().String() } - r = r.WithContext(context.WithValue(r.Context(), traceconst.RequestIDHeaderKey, requestID)) + r = r.WithContext(context.WithValue(r.Context(), traceconst.RequestIDHeaderKey, requestID)) // nolint next.ServeHTTP(w, r) endTime := time.Now() cost := endTime.Sub(startTime).Seconds() diff --git a/bcs-scenarios/bcs-monitor-controller/api/v1/appmonitor_types.go b/bcs-scenarios/bcs-monitor-controller/api/v1/appmonitor_types.go index 6694b297d9..0c1916a17c 100644 --- a/bcs-scenarios/bcs-monitor-controller/api/v1/appmonitor_types.go +++ b/bcs-scenarios/bcs-monitor-controller/api/v1/appmonitor_types.go @@ -8,7 +8,6 @@ * 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 v1 @@ -22,7 +21,7 @@ type Rule struct { Rule string `json:"rule" yaml:"rule,omitempty"` Threshold *Algorithm `json:"threshold,omitempty" yaml:"threshold,omitempty"` NoticeGroup []string `json:"noticeGroup,omitempty" yaml:"noticeGroup,omitempty"` - Trigger string `json:"trigger,omitempty" yaml:"trigger,omitempty"` // 触发配置,如 1/5/6表示5个周期内满足1次则告警,连续6个周期内不满足条件则表示恢复 + Trigger string `json:"trigger,omitempty" yaml:"trigger,omitempty"` // nolint 触发配置,如 1/5/6表示5个周期内满足1次则告警,连续6个周期内不满足条件则表示恢复 } // NoticeGroupConfig 告警组配置 diff --git a/bcs-scenarios/bcs-monitor-controller/api/v1/base.go b/bcs-scenarios/bcs-monitor-controller/api/v1/base.go index 865e442f9d..a09d8d9317 100644 --- a/bcs-scenarios/bcs-monitor-controller/api/v1/base.go +++ b/bcs-scenarios/bcs-monitor-controller/api/v1/base.go @@ -8,7 +8,6 @@ * 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 v1 diff --git a/bcs-scenarios/bcs-monitor-controller/api/v1/groupversion_info.go b/bcs-scenarios/bcs-monitor-controller/api/v1/groupversion_info.go index 907227e97c..1ea363c8ae 100644 --- a/bcs-scenarios/bcs-monitor-controller/api/v1/groupversion_info.go +++ b/bcs-scenarios/bcs-monitor-controller/api/v1/groupversion_info.go @@ -8,7 +8,6 @@ * 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 v1 contains API Schema definitions for the monitorextension.bkbcs.tencent.com v1 API group diff --git a/bcs-scenarios/bcs-monitor-controller/api/v1/monitorrule_types.go b/bcs-scenarios/bcs-monitor-controller/api/v1/monitorrule_types.go index 22fa536ac8..37790a0744 100644 --- a/bcs-scenarios/bcs-monitor-controller/api/v1/monitorrule_types.go +++ b/bcs-scenarios/bcs-monitor-controller/api/v1/monitorrule_types.go @@ -8,7 +8,6 @@ * 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 v1 @@ -25,7 +24,7 @@ import ( type Detect struct { Algorithm *Algorithm `json:"algorithm" yaml:"algorithm"` // 告警检测算法 Nodata *Nodata `json:"nodata,omitempty" yaml:"nodata,omitempty"` // 无数据告警配置 - Trigger string `json:"trigger" yaml:"trigger"` // 触发配置,如 1/5/6表示5个周期内满足1次则告警,连续6个周期内不满足条件则表示恢复 + Trigger string `json:"trigger" yaml:"trigger"` // nolint 触发配置,如 1/5/6表示5个周期内满足1次则告警,连续6个周期内不满足条件则表示恢复 } // Algorithm 告警检测算法 @@ -40,7 +39,7 @@ type Algorithm struct { type AlgorithmConfig struct { ConfigStr string `json:"config,omitempty" yaml:"-"` // 告警检测配置,仅当检测算法为Threshold时使用 ConfigObj AlgorithmConfigStruct `json:"configObj,omitempty" yaml:"-"` // 告警检测配置 - Type string `json:"type,omitempty" yaml:"type,omitempty"` // 告警检测算法, 如Threshold/ RingRatioAmplitude/ YearRoundRange... + Type string `json:"type,omitempty" yaml:"type,omitempty"` // nolint 告警检测算法, 如Threshold/ RingRatioAmplitude/ YearRoundRange... } // AlgorithmConfigStruct 检测算法详细配置 @@ -133,7 +132,7 @@ type Notice struct { UserGroups []string `json:"user_groups,omitempty" yaml:"user_groups,omitempty"` // 告警用户组 NoiseReduce NoiseReduce `json:"noise_reduce,omitempty" yaml:"noise_reduce,omitempty"` // 降噪配置 Interval int `json:"interval,omitempty" yaml:"interval,omitempty"` // 通知间隔(分钟),默认120 - Template NoticeTemplate `json:"template,omitempty" yaml:"template,omitempty"` // 告警通知模板,非必填,默认使用默认模板 + Template NoticeTemplate `json:"template,omitempty" yaml:"template,omitempty"` // 告警通知模板,非必填,默认使用默认模板 nolint } // NoiseReduce 降噪配置 diff --git a/bcs-scenarios/bcs-monitor-controller/api/v1/noticegroup_types.go b/bcs-scenarios/bcs-monitor-controller/api/v1/noticegroup_types.go index 8db47cb662..3532ca583d 100644 --- a/bcs-scenarios/bcs-monitor-controller/api/v1/noticegroup_types.go +++ b/bcs-scenarios/bcs-monitor-controller/api/v1/noticegroup_types.go @@ -8,7 +8,6 @@ * 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 v1 diff --git a/bcs-scenarios/bcs-monitor-controller/api/v1/panel_types.go b/bcs-scenarios/bcs-monitor-controller/api/v1/panel_types.go index 1956ec78e7..523a5b8363 100644 --- a/bcs-scenarios/bcs-monitor-controller/api/v1/panel_types.go +++ b/bcs-scenarios/bcs-monitor-controller/api/v1/panel_types.go @@ -8,7 +8,6 @@ * 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 v1 diff --git a/bcs-scenarios/bcs-monitor-controller/main.go b/bcs-scenarios/bcs-monitor-controller/main.go index f0ea537d5b..ee4cc2ac4c 100644 --- a/bcs-scenarios/bcs-monitor-controller/main.go +++ b/bcs-scenarios/bcs-monitor-controller/main.go @@ -8,9 +8,9 @@ * 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 xxx package main import ( @@ -19,22 +19,20 @@ import ( "os" "strconv" - corev1 "k8s.io/api/core/v1" - "sigs.k8s.io/controller-runtime/pkg/manager" - // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) // to ensure that exec-entrypoint and run can make use of them. - _ "k8s.io/client-go/plugin/pkg/client/auth" - + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/common/http/httpserver" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" + _ "k8s.io/client-go/plugin/pkg/client/auth" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/healthz" "sigs.k8s.io/controller-runtime/pkg/log/zap" + "sigs.k8s.io/controller-runtime/pkg/manager" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-common/common/http/httpserver" monitorextensionv1 "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/api/v1" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/apiclient" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/controllers" @@ -59,6 +57,7 @@ func init() { // +kubebuilder:scaffold:scheme } +// nolint funlen func main() { opts := &option.ControllerOption{} opts.BindFromCommandLine() diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/apiclient/bcsservice_apiclient.go b/bcs-scenarios/bcs-monitor-controller/pkg/apiclient/bcsservice_apiclient.go index dea55453ae..2b10f7923f 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/apiclient/bcsservice_apiclient.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/apiclient/bcsservice_apiclient.go @@ -8,9 +8,9 @@ * 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 apiclient xxx package apiclient import ( @@ -25,6 +25,7 @@ import ( ) const ( + // APIPathListCluster xxx APIPathListCluster = "clustermanager/v1/cluster" ) @@ -79,7 +80,7 @@ func (c *BcsServiceApiClient) ListCluster() { } log.Printf("%d", len(listClusterResp.Data)) - log.Printf(string(res)) + log.Print(string(res)) } func (c *BcsServiceApiClient) doRequest(urlStr string, params url.Values, diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/apiclient/bkmapiclient.go b/bcs-scenarios/bcs-monitor-controller/pkg/apiclient/bkmapiclient.go index a6783e2e02..ab53b35577 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/apiclient/bkmapiclient.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/apiclient/bkmapiclient.go @@ -8,7 +8,6 @@ * 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 apiclient @@ -27,6 +26,7 @@ import ( "time" "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/option" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/utils" ) @@ -41,7 +41,7 @@ const ( ) const ( - envNameBKMFullAuthToken = "BKM_FULL_AUTH_TOKEN" + envNameBKMFullAuthToken = "BKM_FULL_AUTH_TOKEN" // nolint envNameBKMAPIDomain = "BKM_API_DOMAIN" ) @@ -152,16 +152,16 @@ func (b *BkmApiClient) UploadConfig(bizID, bizToken, configPath, app string, ove body := &bytes.Buffer{} writer := multipart.NewWriter(body) - part, err := writer.CreateFormFile("file", filepath.Base(configPath)) + part, _ := writer.CreateFormFile("file", filepath.Base(configPath)) _, _ = io.Copy(part, request) _ = writer.WriteField(fieldBkBizID, bizID) _ = writer.WriteField(fieldApp, app) _ = writer.WriteField(fieldOverwrite, strconv.FormatBool(overwrite)) - writer.Close() + writer.Close() // nolint not checked url := fmt.Sprintf("%s/rest/v2/as_code/import_config_file/", b.MonitorURL) - req, err := http.NewRequest("POST", url, body) + req, _ := http.NewRequest("POST", url, body) req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", bizToken)) req.Header.Add("Content-Type", writer.FormDataContentType()) req.Header.Add("X-Async-Task", "True") @@ -236,7 +236,7 @@ func (b *BkmApiClient) DownloadConfig(bizID, bizToken string) error { mf(StatusErr) return fmt.Errorf("json marshal failed, raw value: %s, err: %w", string(respBody), err) } - if downloadConfigResp.Code != http.StatusOK || downloadConfigResp.Result != true { + if downloadConfigResp.Code != http.StatusOK || !downloadConfigResp.Result { mf(StatusErr) return fmt.Errorf("error status, resp: %s", string(respBody)) } diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/apiclient/metric.go b/bcs-scenarios/bcs-monitor-controller/pkg/apiclient/metric.go index 98c95f1390..472f365074 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/apiclient/metric.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/apiclient/metric.go @@ -8,7 +8,6 @@ * 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 apiclient diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/controllers/appmonitor_controller.go b/bcs-scenarios/bcs-monitor-controller/pkg/controllers/appmonitor_controller.go index 9a73c85c2d..03ac85fb4e 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/controllers/appmonitor_controller.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/controllers/appmonitor_controller.go @@ -8,9 +8,9 @@ * 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 controllers xxx package controllers import ( @@ -20,6 +20,7 @@ import ( "reflect" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/pkg/errors" v1 "k8s.io/api/core/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" @@ -32,7 +33,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/event" "sigs.k8s.io/controller-runtime/pkg/predicate" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" monitorextensionv1 "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/api/v1" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/render" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/repo" @@ -124,7 +124,9 @@ func (r *AppMonitorReconciler) eventPredicate() predicate.Predicate { CreateFunc: func(createEvent event.CreateEvent) bool { monitor := createEvent.Object.(*monitorextensionv1.AppMonitor) // if appMonitor open IgnoreChange, do not retry when state is completed - if monitor.DeletionTimestamp == nil && monitor.Status.SyncStatus.State == monitorextensionv1.SyncStateCompleted && monitor.Spec.IgnoreChange == true { + if monitor.DeletionTimestamp == nil && + monitor.Status.SyncStatus.State == monitorextensionv1.SyncStateCompleted && + monitor.Spec.IgnoreChange { blog.V(3).Infof("appMonitor '%s/%s' got create event, but is synced and ignore change", monitor.GetNamespace(), monitor.GetName()) return false @@ -147,7 +149,9 @@ func (r *AppMonitorReconciler) eventPredicate() predicate.Predicate { return false } // if appMonitor open IgnoreChange, do not retry when state is completed - if newMonitor.DeletionTimestamp == nil && newMonitor.Status.SyncStatus.State == monitorextensionv1.SyncStateCompleted && newMonitor.Spec.IgnoreChange == true { + if newMonitor.DeletionTimestamp == nil && + newMonitor.Status.SyncStatus.State == monitorextensionv1.SyncStateCompleted && + newMonitor.Spec.IgnoreChange { blog.V(3).Infof("appMonitor '%s/%s' updated, but is synced and ignore change", newMonitor.GetNamespace(), newMonitor.GetName()) return false @@ -447,6 +451,7 @@ func (r *AppMonitorReconciler) deleteNoticeGroup(monitor *monitorextensionv1.App } // deleteConfigMap delete related configmap +// nolint unused func (r *AppMonitorReconciler) deleteConfigmap(monitor *monitorextensionv1.AppMonitor) error { configmap := &v1.ConfigMap{} selector, err := metav1.LabelSelectorAsSelector(metav1.SetAsLabelSelector(map[string]string{ diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/controllers/constant.go b/bcs-scenarios/bcs-monitor-controller/pkg/controllers/constant.go index 4a6ba73b5d..5f45c10233 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/controllers/constant.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/controllers/constant.go @@ -8,7 +8,6 @@ * 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 controllers diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/controllers/monitorrule_controller.go b/bcs-scenarios/bcs-monitor-controller/pkg/controllers/monitorrule_controller.go index 14da62bac2..a7b84f90fa 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/controllers/monitorrule_controller.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/controllers/monitorrule_controller.go @@ -8,7 +8,6 @@ * 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 controllers @@ -23,6 +22,7 @@ import ( "strings" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -33,7 +33,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/event" "sigs.k8s.io/controller-runtime/pkg/predicate" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" monitorextensionv1 "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/api/v1" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/apiclient" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/fileoperator" @@ -56,11 +55,13 @@ type MonitorRuleReconciler struct { Opts *option.ControllerOption } -// +kubebuilder:rbac:groups=monitorextension.bkbcs.tencent.com,resources=monitorrules,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups=monitorextension.bkbcs.tencent.com,resources=monitorrules, +// verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=monitorextension.bkbcs.tencent.com,resources=monitorrules/status,verbs=get;update;patch // +kubebuilder:rbac:groups=monitorextension.bkbcs.tencent.com,resources=monitorrules/finalizers,verbs=update // Reconcile monitor rule +// nolint funlen func (r *MonitorRuleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { blog.Infof("MonitorRule '%s' triggered", req.NamespacedName) @@ -190,8 +191,8 @@ func (r *MonitorRuleReconciler) eventPredicate() predicate.Predicate { return predicate.Funcs{ CreateFunc: func(createEvent event.CreateEvent) bool { mr := createEvent.Object.(*monitorextensionv1.MonitorRule) - if mr.DeletionTimestamp == nil && mr.Status.SyncStatus.State == monitorextensionv1.SyncStateCompleted && - mr.Spec.IgnoreChange == true { + if mr.DeletionTimestamp == nil && + mr.Status.SyncStatus.State == monitorextensionv1.SyncStateCompleted && mr.Spec.IgnoreChange { blog.V(3).Infof("monitor rule '%s/%s' got create event, but is synced and ignore change", mr.GetNamespace(), mr.GetName()) return false @@ -212,7 +213,7 @@ func (r *MonitorRuleReconciler) eventPredicate() predicate.Predicate { return false } if newMr.DeletionTimestamp == nil && newMr.Status.SyncStatus. - State == monitorextensionv1.SyncStateCompleted && newMr.Spec.IgnoreChange == true { + State == monitorextensionv1.SyncStateCompleted && newMr.Spec.IgnoreChange { blog.V(3).Infof("monitor rule '%s/%s' updated, but is synced and ignore change", newMr.GetNamespace(), newMr.GetName()) return false @@ -245,7 +246,8 @@ func (r *MonitorRuleReconciler) updateSyncStatus(monitorRule *monitorextensionv1 if inErr := retry.RetryOnConflict(retry.DefaultRetry, func() error { return r.Client.Status().Update(r.Ctx, monitorRule) }); inErr != nil { - blog.Warnf("update monitorRule'%s/%s' failed, err: %s", monitorRule.GetNamespace(), monitorRule.GetName(), inErr.Error()) + blog.Warnf("update monitorRule'%s/%s' failed, err: %s", monitorRule.GetNamespace(), + monitorRule.GetName(), inErr.Error()) return inErr } diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/controllers/noticegroup_controller.go b/bcs-scenarios/bcs-monitor-controller/pkg/controllers/noticegroup_controller.go index aa038f13e0..bcdad9fa9d 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/controllers/noticegroup_controller.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/controllers/noticegroup_controller.go @@ -8,7 +8,6 @@ * 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 controllers @@ -20,6 +19,7 @@ import ( "reflect" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -29,7 +29,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/event" "sigs.k8s.io/controller-runtime/pkg/predicate" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" monitorextensionv1 "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/api/v1" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/apiclient" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/fileoperator" @@ -46,7 +45,8 @@ type NoticeGroupReconciler struct { MonitorApiCli apiclient.IMonitorApiClient } -// +kubebuilder:rbac:groups=monitorextension.bkbcs.tencent.com,resources=noticegroups,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups=monitorextension.bkbcs.tencent.com, +// resources=noticegroups,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=monitorextension.bkbcs.tencent.com,resources=noticegroups/status,verbs=get;update;patch // +kubebuilder:rbac:groups=monitorextension.bkbcs.tencent.com,resources=noticegroups/finalizers,verbs=update @@ -114,7 +114,7 @@ func (r *NoticeGroupReconciler) eventPredicate() predicate.Predicate { CreateFunc: func(createEvent event.CreateEvent) bool { ng := createEvent.Object.(*monitorextensionv1.NoticeGroup) if ng.DeletionTimestamp == nil && ng.Status.SyncStatus.State == monitorextensionv1.SyncStateCompleted && - ng.Spec.IgnoreChange == true { + ng.Spec.IgnoreChange { blog.V(3).Infof("notice group '%s/%s' got create event, but is synced and ignore change", ng.GetNamespace(), ng.GetName()) return false @@ -135,7 +135,7 @@ func (r *NoticeGroupReconciler) eventPredicate() predicate.Predicate { return false } if newNg.DeletionTimestamp == nil && newNg.Status.SyncStatus. - State == monitorextensionv1.SyncStateCompleted && newNg.Spec.IgnoreChange == true { + State == monitorextensionv1.SyncStateCompleted && newNg.Spec.IgnoreChange { blog.V(3).Infof("noticeGroup '%s/%s' updated, but is synced and ignore change", newNg.GetNamespace(), newNg.GetName()) return false @@ -169,7 +169,8 @@ func (r *NoticeGroupReconciler) updateSyncStatus(noticeGroup *monitorextensionv1 if inErr := retry.RetryOnConflict(retry.DefaultRetry, func() error { return r.Client.Status().Update(r.Ctx, noticeGroup) }); inErr != nil { - blog.Warnf("update noticeGroup'%s/%s' failed, err: %s", noticeGroup.GetNamespace(), noticeGroup.GetName(), inErr.Error()) + blog.Warnf("update noticeGroup'%s/%s' failed, err: %s", noticeGroup.GetNamespace(), + noticeGroup.GetName(), inErr.Error()) return inErr } diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/controllers/panel_controller.go b/bcs-scenarios/bcs-monitor-controller/pkg/controllers/panel_controller.go index 703b19a96c..db5713249c 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/controllers/panel_controller.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/controllers/panel_controller.go @@ -8,7 +8,6 @@ * 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 controllers @@ -20,6 +19,7 @@ import ( "reflect" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" v1 "k8s.io/api/core/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -34,7 +34,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" monitorextensionv1 "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/api/v1" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/apiclient" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/fileoperator" @@ -51,7 +50,8 @@ type PanelReconciler struct { MonitorApiCli apiclient.IMonitorApiClient } -// +kubebuilder:rbac:groups=monitorextension.bkbcs.tencent.com,resources=panels,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups=monitorextension.bkbcs.tencent.com, +// resources=panels,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=monitorextension.bkbcs.tencent.com,resources=panels/status,verbs=get;update;patch // +kubebuilder:rbac:groups=monitorextension.bkbcs.tencent.com,resources=panels/finalizers,verbs=update @@ -120,7 +120,8 @@ func (r *PanelReconciler) eventPredicate() predicate.Predicate { if !ok { return true } - if panel.DeletionTimestamp == nil && panel.Status.SyncStatus.State == monitorextensionv1.SyncStateCompleted && panel.Spec.IgnoreChange == true { + if panel.DeletionTimestamp == nil && + panel.Status.SyncStatus.State == monitorextensionv1.SyncStateCompleted && panel.Spec.IgnoreChange { blog.V(3).Infof("panel '%s/%s' got create event, but is synced and ignore change", panel.GetNamespace(), panel.GetName()) return false @@ -141,7 +142,7 @@ func (r *PanelReconciler) eventPredicate() predicate.Predicate { return false } if newPanel.DeletionTimestamp == nil && newPanel.Status. - SyncStatus.State == monitorextensionv1.SyncStateCompleted && newPanel.Spec.IgnoreChange == true { + SyncStatus.State == monitorextensionv1.SyncStateCompleted && newPanel.Spec.IgnoreChange { blog.V(3).Infof("panel '%s/%s' updated, but is synced and ignore change", newPanel.GetNamespace(), newPanel.GetName()) return false @@ -239,7 +240,6 @@ type configmapFilter struct { // Create implement EventFilter func (cf *configmapFilter) Create(e event.CreateEvent, q workqueue.RateLimitingInterface) { - return } // Update implement EventFilter @@ -288,10 +288,8 @@ func (cf *configmapFilter) Update(e event.UpdateEvent, q workqueue.RateLimitingI // Delete implement EventFilter func (cf *configmapFilter) Delete(e event.DeleteEvent, q workqueue.RateLimitingInterface) { - return } // Generic implement EventFilter func (cf *configmapFilter) Generic(e event.GenericEvent, q workqueue.RateLimitingInterface) { - return } diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/fileoperator.go b/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/fileoperator.go index 7fb00d9d31..dd07b45f2f 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/fileoperator.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/fileoperator.go @@ -8,7 +8,6 @@ * 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 fileoperator xxx @@ -23,12 +22,11 @@ import ( "os" "path/filepath" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/mholt/archiver/v3" "gopkg.in/yaml.v3" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/mholt/archiver/v3" - - "github.com/Tencent/bk-bcs/bcs-common/common/blog" v1 "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/api/v1" ) @@ -77,6 +75,7 @@ func (f *FileOperator) Compress(objList ...interface{}) (string, error) { return outputPath, nil } +// Decompress xxx func (f *FileOperator) Decompress(path, outputDir string) error { // 打开已下载的 tar.gz 文件 file, err := os.Open(path) @@ -90,7 +89,7 @@ func (f *FileOperator) Decompress(path, outputDir string) error { if err != nil { return fmt.Errorf("create gzip reader failed, err: %w", err) } - defer gzipReader.Close() + defer gzipReader.Close() // nolint tarReader := tar.NewReader(gzipReader) @@ -116,13 +115,13 @@ func (f *FileOperator) createDirectoriesAndFile(obj interface{}, basePath string blog.Errorf("mkdir failed, err: %s", err.Error()) return err } - switch obj.(type) { + switch v := obj.(type) { case *v1.NoticeGroup: - ng := obj.(*v1.NoticeGroup) - for _, group := range ng.Spec.Groups { + for _, group := range v.Spec.Groups { yamlData, err := yaml.Marshal(group) if err != nil { - blog.Errorf("transfer yaml failed, notice group: %s/%s, err: %s", ng.Namespace, ng.Name, err.Error()) + blog.Errorf("transfer yaml failed, notice group: %s/%s, err: %s", v.Namespace, v.Name, + err.Error()) return err } @@ -135,11 +134,10 @@ func (f *FileOperator) createDirectoriesAndFile(obj interface{}, basePath string } return nil case *v1.MonitorRule: - mr := obj.(*v1.MonitorRule) - for _, rule := range mr.Spec.Rules { + for _, rule := range v.Spec.Rules { yamlData, err := yaml.Marshal(rule) if err != nil { - blog.Errorf("transfer yaml failed, monitor rule: %s/%s, err: %s", mr.GetNamespace(), mr.GetName(), + blog.Errorf("transfer yaml failed, monitor rule: %s/%s, err: %s", v.GetNamespace(), v.GetName(), err.Error()) return err } @@ -153,12 +151,11 @@ func (f *FileOperator) createDirectoriesAndFile(obj interface{}, basePath string } return nil case *v1.Panel: - panel := obj.(*v1.Panel) - for _, board := range panel.Spec.DashBoard { + for _, board := range v.Spec.DashBoard { var data []byte var err error - ns := panel.Namespace + ns := v.Namespace if board.ConfigMapNs != "" { ns = board.ConfigMapNs } @@ -168,13 +165,13 @@ func (f *FileOperator) createDirectoriesAndFile(obj interface{}, basePath string return err } - if err = os.MkdirAll(filepath.Join(dest, panel.Spec.Scenario), 0700); err != nil { + if err = os.MkdirAll(filepath.Join(dest, v.Spec.Scenario), 0700); err != nil { blog.Errorf("mkdir failed, err: %s", err.Error()) return err } fileName := board.Board + ".json" - filePath := filepath.Join(dest, panel.Spec.Scenario, fileName) + filePath := filepath.Join(dest, v.Spec.Scenario, fileName) if err = ioutil.WriteFile(filePath, data, 0644); err != nil { blog.Errorf("write file to path: %s failed, board %+v, err: %s", filePath, board, err.Error()) diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/fileoperator_test.go b/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/fileoperator_test.go index 1e160bdd69..a24655fa0b 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/fileoperator_test.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/fileoperator_test.go @@ -8,7 +8,6 @@ * 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 fileoperator @@ -123,11 +122,13 @@ func TestCompress(t *testing.T) { // }, // } + enable := true + unable := false mr1 := v1.MonitorRuleSpec{ Rules: []*v1.MonitorRuleDetail{ { Name: "a", - Enabled: true, + Enabled: &enable, ActiveTime: "1234", Detect: &v1.Detect{ Algorithm: &v1.Algorithm{ @@ -150,7 +151,7 @@ func TestCompress(t *testing.T) { Rules: []*v1.MonitorRuleDetail{ { Name: "a", - Enabled: true, + Enabled: &enable, ActiveTime: "1234", Detect: &v1.Detect{ Algorithm: &v1.Algorithm{ @@ -174,7 +175,7 @@ func TestCompress(t *testing.T) { Rules: []*v1.MonitorRuleDetail{ { Name: "a", - Enabled: true, + Enabled: &enable, ActiveTime: "1234", Detect: &v1.Detect{ Algorithm: &v1.Algorithm{ @@ -193,7 +194,7 @@ func TestCompress(t *testing.T) { }, { Name: "b", - Enabled: false, + Enabled: &unable, ActiveTime: "1234", Detect: &v1.Detect{ Algorithm: &v1.Algorithm{ diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/loader.go b/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/loader.go index d4d7af6201..fd97c81cc3 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/loader.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/fileoperator/loader.go @@ -8,7 +8,6 @@ * 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 fileoperator @@ -19,11 +18,10 @@ import ( "io/ioutil" "net/http" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" v1 "k8s.io/api/core/v1" k8stypes "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - - "github.com/Tencent/bk-bcs/bcs-common/common/blog" ) // Loader load file info diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/httpserver.go b/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/httpserver.go index 16c7beeb26..45a0277cee 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/httpserver.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/httpserver.go @@ -8,9 +8,9 @@ * 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 httpsvr xxx package httpsvr import ( @@ -18,6 +18,7 @@ import ( "fmt" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/emicklei/go-restful" "gopkg.in/yaml.v3" k8smetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -25,7 +26,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/manager" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" monitorextensionv1 "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/api/v1" ) @@ -182,11 +182,11 @@ func (h *HttpServerClient) DeleteAppMonitor(request *restful.Request, response * return } _, _ = response.Write(CreateResponseData(nil, "success", struct{}{})) - return } // do Create Or Update App Monitor -func (h *HttpServerClient) doCreateOrUpdateAppMonitor(bizID, scenario, values string) (*k8stypes.NamespacedName, error) { +func (h *HttpServerClient) doCreateOrUpdateAppMonitor( + bizID, scenario, values string) (*k8stypes.NamespacedName, error) { var ( appMonitor *monitorextensionv1.AppMonitor foundPrevious bool diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/response.go b/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/response.go index 4cedc3b5a1..ac1fd82578 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/response.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/response.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. @@ -20,7 +20,7 @@ import ( "github.com/Tencent/bk-bcs/bcs-common/common/blog" ) -var unknownError = errors.New("unknown") +var unknownError = errors.New("unknown") // nolint // APIRespone response for api request type APIRespone struct { diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/utils.go b/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/utils.go index 74bb7c41cf..38ee3b9009 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/utils.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/httpsvr/utils.go @@ -8,7 +8,6 @@ * 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 httpsvr diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/option/option.go b/bcs-scenarios/bcs-monitor-controller/pkg/option/option.go index 10da044bd9..c3733eb7db 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/option/option.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/option/option.go @@ -8,7 +8,6 @@ * 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 option xxx diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/patch/threewaymerge.go b/bcs-scenarios/bcs-monitor-controller/pkg/patch/threewaymerge.go index cb6e41288c..1fab62de2d 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/patch/threewaymerge.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/patch/threewaymerge.go @@ -8,15 +8,15 @@ * 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 patch xxx package patch import ( + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/google/go-cmp/cmp" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" v1 "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/api/v1" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/utils" ) @@ -76,7 +76,8 @@ func ThreeWayMergeMonitorRule(original, current, modified []*v1.MonitorRuleDetai } blog.Infof("original rule: %s, \ncurrent rule: %s, \nmodified rule: %s, \nmerged rule: %s", - utils.ToJsonString(original), utils.ToJsonString(current), utils.ToJsonString(modified), utils.ToJsonString(mergeResult)) + utils.ToJsonString(original), utils.ToJsonString(current), utils.ToJsonString(modified), + utils.ToJsonString(mergeResult)) return mergeResult } diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/patch/threewaymerge_test.go b/bcs-scenarios/bcs-monitor-controller/pkg/patch/threewaymerge_test.go index 973d14f16f..ea8e5546b9 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/patch/threewaymerge_test.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/patch/threewaymerge_test.go @@ -8,7 +8,6 @@ * 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 patch diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/render/monitor_render.go b/bcs-scenarios/bcs-monitor-controller/pkg/render/monitor_render.go index f6d129eb53..ce5770412f 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/render/monitor_render.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/render/monitor_render.go @@ -8,20 +8,20 @@ * 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 render xxx package render import ( "fmt" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/serializer" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" monitorextensionv1 "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/api/v1" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/option" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/repo" @@ -237,7 +237,7 @@ func (r *MonitorRender) renderPanel(appMonitor *monitorextensionv1.AppMonitor, r for _, rawBoard := range panel.Spec.DashBoard { if rawBoard.Board == board.Board { find = true - boardList = append(boardList, rawBoard) + boardList = append(boardList, rawBoard) // nolint never used break } } diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/render/scenario_loader.go b/bcs-scenarios/bcs-monitor-controller/pkg/render/scenario_loader.go index 0edb6b25a6..e4d8866c47 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/render/scenario_loader.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/render/scenario_loader.go @@ -8,7 +8,6 @@ * 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 render @@ -20,19 +19,23 @@ import ( "path/filepath" "strings" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "gopkg.in/yaml.v3" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" monitorextensionv1 "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/api/v1" ) const ( - GenerateMonitorRuleName = "auto-generate-monitor-rule" - GeneratePanelName = "auto-generate-monitor-panel" - GenerateNoticeGroupName = "auto-generate-monitor-notice-group" + // GenerateMonitorRuleName xxx + GenerateMonitorRuleName = "auto-generate-monitor-rule" + // GeneratePanelName xxx + GeneratePanelName = "auto-generate-monitor-panel" + // GenerateNoticeGroupName xxx + GenerateNoticeGroupName = "auto-generate-monitor-notice-group" + // GenerateAppendNoticeGroupName xxx GenerateAppendNoticeGroupName = "auto-generate-monitor-append-ng" ) @@ -40,6 +43,7 @@ const ( // scenario支持两种配置方式 (允许同时存在) // 1. 蓝鲸监控导出 (通过文件夹名称区分不同YAML文件, 例如grafana下认为是告警面板配置) // 2. cr模式配置 (通过文件名称区分,例如monitorrule&mr开头文件认为是告警规则配置) +// nolint funlen func (r *MonitorRender) ReadScenario(repoKey, scenario string) (*Result, error) { res := &Result{} repo, ok := r.repoManager.GetRepo(repoKey) @@ -143,7 +147,8 @@ func (r *MonitorRender) ReadScenario(repoKey, scenario string) (*Result, error) } // LoadRule load rule from certain path, filterFunc 根据告警名判断 -func (r *MonitorRender) LoadRule(path string, filterFunc ...func(string) bool) (*monitorextensionv1.MonitorRule, error) { +func (r *MonitorRender) LoadRule( + path string, filterFunc ...func(string) bool) (*monitorextensionv1.MonitorRule, error) { if _, err := os.Stat(path); os.IsNotExist(err) { blog.Infof("empty raw rule, continue...") return nil, nil diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/repo/argo.go b/bcs-scenarios/bcs-monitor-controller/pkg/repo/argo.go index e9defd36ed..b43d96bc2a 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/repo/argo.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/repo/argo.go @@ -8,9 +8,9 @@ * 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 repo xxx package repo import ( diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/repo/git_repo.go b/bcs-scenarios/bcs-monitor-controller/pkg/repo/git_repo.go index 806d96e07c..dce6340057 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/repo/git_repo.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/repo/git_repo.go @@ -8,7 +8,6 @@ * 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 repo @@ -20,14 +19,13 @@ import ( "strings" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" "github.com/go-git/go-git/v5/plumbing/transport/http" "github.com/pkg/errors" "sigs.k8s.io/controller-runtime/pkg/client" - - "github.com/Tencent/bk-bcs/bcs-common/common/blog" ) // gitRepo clone git repo and pull in certain freq @@ -44,7 +42,7 @@ type gitRepo struct { // In case of Git, this can be commit, tag, or branch. If omitted, will equal to HEAD. TargetRevision string `json:"targetRevision,omitempty"` - cli client.Client + cli client.Client // nolint unused auth *http.BasicAuth } @@ -252,15 +250,13 @@ func compareCommitAndParent(commit *object.Commit) ([]string, error) { if !contains(changedDirs, dir) { changedDirs = append(changedDirs, dir) } - } else { - if file.Hash != parentFile.Hash { - dir, inErr := getTopDir(file.Name) - if inErr != nil { - return inErr - } - if !contains(changedDirs, dir) { - changedDirs = append(changedDirs, dir) - } + } else if file.Hash != parentFile.Hash { + dir, inErr := getTopDir(file.Name) + if inErr != nil { + return inErr + } + if !contains(changedDirs, dir) { + changedDirs = append(changedDirs, dir) } } return nil diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/repo/interface.go b/bcs-scenarios/bcs-monitor-controller/pkg/repo/interface.go index cecafb7289..4256ebf715 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/repo/interface.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/repo/interface.go @@ -8,7 +8,6 @@ * 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 repo diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/repo/manager.go b/bcs-scenarios/bcs-monitor-controller/pkg/repo/manager.go index 5c6ddcbb66..1e7e07da9b 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/repo/manager.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/repo/manager.go @@ -8,7 +8,6 @@ * 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 repo @@ -20,11 +19,11 @@ import ( "sync" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/argoproj/argo-cd/v2/util/db" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" monitorextensionv1 "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/api/v1" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/option" "github.com/Tencent/bk-bcs/bcs-runtime/bcs-k8s/bcs-component/bcs-monitor-controller/pkg/utils" diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/repo/uitls.go b/bcs-scenarios/bcs-monitor-controller/pkg/repo/uitls.go index 87a812d6c0..49411ba590 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/repo/uitls.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/repo/uitls.go @@ -8,7 +8,6 @@ * 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 repo diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/utils/common.go b/bcs-scenarios/bcs-monitor-controller/pkg/utils/common.go index 21094b1d2b..6deb121e5a 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/utils/common.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/utils/common.go @@ -8,9 +8,9 @@ * 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 utils xxx package utils import ( diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/utils/gen_path.go b/bcs-scenarios/bcs-monitor-controller/pkg/utils/gen_path.go index 1f8a006c3e..b0bd479f44 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/utils/gen_path.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/utils/gen_path.go @@ -8,7 +8,6 @@ * 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 utils diff --git a/bcs-scenarios/bcs-monitor-controller/pkg/utils/patch.go b/bcs-scenarios/bcs-monitor-controller/pkg/utils/patch.go index 48f3844426..71c74eb466 100644 --- a/bcs-scenarios/bcs-monitor-controller/pkg/utils/patch.go +++ b/bcs-scenarios/bcs-monitor-controller/pkg/utils/patch.go @@ -8,7 +8,6 @@ * 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 utils diff --git a/bcs-scenarios/bcs-terraform-controller/api/v1/groupversion_info.go b/bcs-scenarios/bcs-terraform-controller/api/v1/groupversion_info.go index 348bd2a8e1..8d8f9db78c 100644 --- a/bcs-scenarios/bcs-terraform-controller/api/v1/groupversion_info.go +++ b/bcs-scenarios/bcs-terraform-controller/api/v1/groupversion_info.go @@ -8,7 +8,6 @@ * 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 v1 contains API Schema definitions for the terraformextesions v1 API group diff --git a/bcs-scenarios/bcs-terraform-controller/api/v1/terraform_types.go b/bcs-scenarios/bcs-terraform-controller/api/v1/terraform_types.go index 3ad7970377..a10ffdde9d 100644 --- a/bcs-scenarios/bcs-terraform-controller/api/v1/terraform_types.go +++ b/bcs-scenarios/bcs-terraform-controller/api/v1/terraform_types.go @@ -8,7 +8,6 @@ * 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 v1 diff --git a/bcs-scenarios/bcs-terraform-controller/controllers/terraform_controller.go b/bcs-scenarios/bcs-terraform-controller/controllers/terraform_controller.go index 634f784452..3377582158 100644 --- a/bcs-scenarios/bcs-terraform-controller/controllers/terraform_controller.go +++ b/bcs-scenarios/bcs-terraform-controller/controllers/terraform_controller.go @@ -8,7 +8,6 @@ * 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 controllers @@ -19,6 +18,7 @@ import ( "reflect" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/google/uuid" k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -30,7 +30,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/event" "sigs.k8s.io/controller-runtime/pkg/predicate" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" tfv1 "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/api/v1" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/pkg/core" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/pkg/option" @@ -48,7 +47,8 @@ type TerraformReconciler struct { } // Reconcile reconcile terraform -// +kubebuilder:rbac:groups=terraformextesions.bkbcs.tencent.com,resources=terraforms,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups=terraformextesions.bkbcs.tencent.com, +// resources=terraforms,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=terraformextesions.bkbcs.tencent.com,resources=terraforms/status,verbs=get;update;patch // +kubebuilder:rbac:groups=terraformextesions.bkbcs.tencent.com,resources=terraforms/finalizers,verbs=update func (r *TerraformReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { @@ -64,16 +64,16 @@ func (r *TerraformReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( blog.Infof("reconcile receive terraform, tf: %s, trace-id: %s", nn, traceId) if terraform.DeletionTimestamp != nil { // note: 禁用删除功能 - //blog.Infof("delete terraform: %s, trace-id: %s", utils.ToJsonString(terraform), traceId) - //if err := handler.Init(); err != nil { + // blog.Infof("delete terraform: %s, trace-id: %s", utils.ToJsonString(terraform), traceId) + // if err := handler.Init(); err != nil { // blog.Errorf("core handler init failed, err: %s", err.Error()) // return ctrl.Result{Requeue: true, RequeueAfter: 5 * time.Second}, err - //} - //if err := handler.Delete(); err != nil { + // } + // if err := handler.Delete(); err != nil { // blog.Errorf("core handler delete terraform resource failed, err: %s", err.Error()) // return ctrl.Result{Requeue: true, RequeueAfter: 5 * time.Second}, err - //} - ////defer r.clean(handler) + // } + // //defer r.clean(handler) terraform.Finalizers = utils.RemoveString(terraform.Finalizers, tfv1.TerraformFinalizer) if err := r.Client.Update(ctx, &terraform, &client.UpdateOptions{}); err != nil { blog.Errorf("remove finalizer for terraform failed, terraform: %s, trace-id: %s, err: %s", @@ -97,6 +97,7 @@ func (r *TerraformReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( } // handler 核心逻辑 +// nolint funlen func (r *TerraformReconciler) handler(ctx context.Context, traceId string, tf *tfv1.Terraform) (ctrl.Result, error) { currentCommitId, currentCommitIdOk := tf.Annotations[tfv1.TerraformManualAnnotation] if utils.RemoveManualAnnotation(tf) { @@ -220,7 +221,7 @@ func (r *TerraformReconciler) handler(ctx context.Context, traceId string, tf *t func (r *TerraformReconciler) finish(ctx context.Context, traceId string, tf *tfv1.Terraform) { 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)) + // 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) @@ -232,7 +233,7 @@ func (r *TerraformReconciler) finish(ctx context.Context, traceId string, tf *tf // updateAnnotations 更新注解 func (r *TerraformReconciler) updateAnnotations(ctx context.Context, traceId, id string, tf *tfv1.Terraform) error { nn := apitypes.NamespacedName{Namespace: tf.Namespace, Name: tf.Name} - //blog.Infof("updateAnnotations to tf, trace-id: %s, tf-json: %s,", traceId, utils.ToJsonString(tf)) + // blog.Infof("updateAnnotations to tf, trace-id: %s, tf-json: %s,", traceId, utils.ToJsonString(tf)) if err := r.Client.Update(ctx, tf); err != nil { // 移除annotations失败 @@ -311,8 +312,9 @@ func (r *TerraformReconciler) SetupWithManager(mgr ctrl.Manager) error { Complete(r) } -//// noChanges 没有变化, 执行完成, 进入收尾 -//func (r *TerraformReconciler) noChanges(ctx context.Context, traceId string, tf *tfv1.Terraform) (ctrl.Result, error) { +// // noChanges 没有变化, 执行完成, 进入收尾 +// func (r *TerraformReconciler) noChanges( +// ctx context.Context, traceId string, tf *tfv1.Terraform) (ctrl.Result, error) { // if !utils.RemoveManualAnnotation(tf) { // 没有annotations // return ctrl.Result{Requeue: true, RequeueAfter: 180 * time.Second}, nil // } @@ -329,4 +331,4 @@ func (r *TerraformReconciler) SetupWithManager(mgr ctrl.Manager) error { // tf.Namespace, tf.Name, traceId) // // return ctrl.Result{Requeue: true, RequeueAfter: 180 * time.Second}, nil -//} +// } diff --git a/bcs-scenarios/bcs-terraform-controller/main.go b/bcs-scenarios/bcs-terraform-controller/main.go index 6a78281d90..986044bfa5 100644 --- a/bcs-scenarios/bcs-terraform-controller/main.go +++ b/bcs-scenarios/bcs-terraform-controller/main.go @@ -8,9 +8,9 @@ * 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 xxx package main import ( @@ -18,24 +18,23 @@ import ( "os" // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) - // to ensure that exec-entrypoint and run can make use of them. - _ "k8s.io/client-go/plugin/pkg/client/auth" - + // to ensure that exec-entrypoint and run can make use of them. nolint + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/go-git/go-git/v5/plumbing" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" + _ "k8s.io/client-go/plugin/pkg/client/auth" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/healthz" "sigs.k8s.io/controller-runtime/pkg/log/zap" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" + // +kubebuilder:scaffold:imports nolint tfv1 "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/api/v1" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/controllers" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/pkg/option" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/pkg/server" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/pkg/utils" - // +kubebuilder:scaffold:imports ) var ( @@ -121,7 +120,7 @@ func main() { }) if err != nil { setupLog.Error(err, "unable to start manager") - os.Exit(1) + os.Exit(1) // nolint } svr := server.NewHandler("0.0.0.0", "8080", mgr.GetClient()) diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/core/task.go b/bcs-scenarios/bcs-terraform-controller/pkg/core/task.go index 13f698c901..4ae5956663 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/core/task.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/core/task.go @@ -8,18 +8,19 @@ * 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 core xxx package core import ( "context" "fmt" - "io/ioutil" + "os" "path/filepath" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/pkg/errors" "github.com/spf13/afero" corev1 "k8s.io/api/core/v1" @@ -28,7 +29,6 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" tfv1 "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/api/v1" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/pkg/repository" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/pkg/runner" @@ -266,13 +266,13 @@ func (h *task) Plan() (string, error) { return logs, nil } -// saveTfPlanToSecret 保存结果到 secret +// saveTfPlanToSecret 保存结果到 secret func (h *task) saveTfPlanToSecret() error { - tfPlanBytes, err := ioutil.ReadFile(h.runner.GetPlanOutFile()) + tfPlanBytes, err := os.ReadFile(h.runner.GetPlanOutFile()) if err != nil { return errors.Wrapf(err, "read tf plan failed, tf: %s, trace-id: %s", h.nn, h.traceId) } - //blog.Infof("tfPlanBytes: %d", len(tfPlanBytes)) // + // blog.Infof("tfPlanBytes: %d", len(tfPlanBytes)) // tfplanSecretExists := true tfplanSecret := new(corev1.Secret) @@ -282,12 +282,11 @@ func (h *task) saveTfPlanToSecret() error { defer cancel() if err = h.client.Get(ctx, tfplanObjectKey, tfplanSecret); err != nil { - if apierrors.IsNotFound(err) { - tfplanSecretExists = false - //blog.Info("secret not exists, name: %s", secretName) - } else { + if !apierrors.IsNotFound(err) { return errors.Wrapf(err, "unable to get the plan secret, tf: %s, trace-id: %s", h.nn, h.traceId) } + tfplanSecretExists = false + // blog.Info("secret not exists, name: %s", secretName) } if tfplanSecretExists { ctx, cancel := context.WithTimeout(h.rootCtx, 15*time.Second) @@ -337,7 +336,7 @@ func (h *task) saveTfPlanToSecret() error { return nil } -// saveTfPlanToConfigMap 保存明文结果到configmap +// saveTfPlanToConfigMap 保存明文结果到configmap func (h *task) saveTfPlanToConfigMap(raw string) error { tfplanCMExists := true tfplanCM := new(corev1.ConfigMap) @@ -347,11 +346,10 @@ func (h *task) saveTfPlanToConfigMap(raw string) error { defer cancel() if err := h.client.Get(ctx, tfplanObjectKey, tfplanCM); err != nil { - if apierrors.IsNotFound(err) { - tfplanCMExists = false - } else { + if !apierrors.IsNotFound(err) { return errors.Wrapf(err, "unable to get the plan configmap, tf: %s, trace-id: %s", h.nn, h.traceId) } + tfplanCMExists = false } if tfplanCMExists { @@ -444,11 +442,10 @@ func (h *task) SaveApplyOutputToConfigMap(raw string) error { defer cancel() if err := h.client.Get(ctx, tfplanObjectKey, tfplanCM); err != nil { - if apierrors.IsNotFound(err) { - tfplanCMExists = false - } else { + if !apierrors.IsNotFound(err) { return errors.Wrapf(err, "unable to get the plan configmap, tf: %s, trace-id: %s", h.nn, h.traceId) } + tfplanCMExists = false } if tfplanCMExists { @@ -496,9 +493,9 @@ func (h *task) SaveApplyOutputToConfigMap(raw string) error { // Clean repository func (h *task) Clean() { // note: 调试过程中,先注释掉 - //if err := h.repo.Clean(); err != nil { + // if err := h.repo.Clean(); err != nil { // blog.Errorf("core handler clean repository failed, err: %s", err.Error()) - //} + // } } // Stop 停止执行 @@ -550,7 +547,7 @@ func (h *task) getRepoToken() error { //// Delete terraform //// 1. new terraform //// 1. destroy terraform -//func (h *task) Delete() error { +// func (h *task) Delete() error { // req := &runner.DestroyRequest{ // TfInstance: h.traceId, // Targets: h.terraform.Spec.Targets, @@ -561,4 +558,4 @@ func (h *task) getRepoToken() error { // blog.Info("destroy terraform success, terraform: %s", h.nn) // // return nil -//} +// } diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/core/types.go b/bcs-scenarios/bcs-terraform-controller/pkg/core/types.go index f9eb8d51c3..668e7e2c8d 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/core/types.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/core/types.go @@ -8,7 +8,6 @@ * 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 core diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/option/option.go b/bcs-scenarios/bcs-terraform-controller/pkg/option/option.go index 244af3d537..912a598dce 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/option/option.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/option/option.go @@ -8,7 +8,6 @@ * 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 option include controller options from command line and env @@ -16,12 +15,12 @@ package option import ( "fmt" - "github.com/hashicorp/terraform-exec/tfexec" - "github.com/pkg/errors" "path" "github.com/Tencent/bk-bcs/bcs-common/common/conf" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/store" + "github.com/hashicorp/terraform-exec/tfexec" + "github.com/pkg/errors" ) var ( diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/option/types.go b/bcs-scenarios/bcs-terraform-controller/pkg/option/types.go index 92bc0c4451..3fa510eb77 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/option/types.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/option/types.go @@ -8,7 +8,6 @@ * 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 option diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/repository/repository.go b/bcs-scenarios/bcs-terraform-controller/pkg/repository/repository.go index db9af05cbc..f9f277ca76 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/repository/repository.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/repository/repository.go @@ -8,7 +8,6 @@ * 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 repository xxx @@ -20,7 +19,10 @@ import ( "path" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/store" "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" @@ -28,8 +30,6 @@ import ( "github.com/pkg/errors" apiv1 "k8s.io/apimachinery/pkg/types" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/store" tfv1 "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/api/v1" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/pkg/option" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/pkg/utils" @@ -79,7 +79,8 @@ type handler struct { } // NewHandler new handler obj -func NewHandler(ctx context.Context, config tfv1.GitRepository, token, traceId string, nn apiv1.NamespacedName) Handler { +func NewHandler( + ctx context.Context, config tfv1.GitRepository, token, traceId string, nn apiv1.NamespacedName) Handler { return &handler{ nn: nn, ctx: ctx, diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/runner/local_runner.go b/bcs-scenarios/bcs-terraform-controller/pkg/runner/local_runner.go index 3eaa5b2152..00c11a61d2 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/runner/local_runner.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/runner/local_runner.go @@ -8,7 +8,6 @@ * 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 runner @@ -22,17 +21,17 @@ import ( "strings" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/store" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/options" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/secret" "github.com/hashicorp/terraform-exec/tfexec" "github.com/pkg/errors" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/common" - "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/store" - "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/options" - "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/secret" tfv1 "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/api/v1" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/pkg/option" ) @@ -191,7 +190,7 @@ func (t *terraformLocalRunner) ExecPlan(ctx context.Context, req *PlanRequest) ( blog.Info("backend seems to be disabled completely, so there will be no plan output file") } - if req.Refresh == false { + if !req.Refresh { planOpt = append(planOpt, tfexec.Refresh(req.Refresh)) } @@ -218,20 +217,20 @@ func (t *terraformLocalRunner) ExecPlan(ctx context.Context, req *PlanRequest) ( if req.Out != "" { planCreated = true - //plan, err := t.exec.ShowPlanFile(ctx, req.Out) - //if err != nil { - // return nil, err - //} - ////blog.Infof("plan output: %s", utils.ToJsonString(plan)) + // plan, err := t.exec.ShowPlanFile(ctx, req.Out) + // if err != nil { + // return nil, err + // } + // //blog.Infof("plan output: %s", utils.ToJsonString(plan)) // - //// This is the case when the plan is empty. - //if plan.PlannedValues.Outputs == nil && - // plan.PlannedValues.RootModule.Resources == nil && - // plan.ResourceChanges == nil && - // plan.PriorState == nil && - // plan.OutputChanges == nil { - // planCreated = false - //} + // // This is the case when the plan is empty. + // if plan.PlannedValues.Outputs == nil && + // plan.PlannedValues.RootModule.Resources == nil && + // plan.ResourceChanges == nil && + // plan.PriorState == nil && + // plan.OutputChanges == nil { + // planCreated = false + // } } blog.Infof("terraform plan end up, instance-id: %s", t.instanceID) @@ -283,13 +282,13 @@ func (t *terraformLocalRunner) ExecApply(ctx context.Context, req *ApplyRequest) // ExecDestroy terraform destroy命令可以用来销毁并回收所有Terraform管理的基础设施资源。 // Terraform管理的资源会被销毁,在执行销毁动作前会通过交互式界面征求用户的确认。 // -//该命令可以接收所有apply命令的参数,除了不可以指定plan文件。 +// 该命令可以接收所有apply命令的参数,除了不可以指定plan文件。 // -//如果-auto-approve参数被设置为true,那么将不会征求用户确认直接销毁。 +// 如果-auto-approve参数被设置为true,那么将不会征求用户确认直接销毁。 // -//如果用-target参数指定了某项资源,那么不但会销毁该资源,同时也会销毁一切依赖于该资源的资源。我们会在随后介绍plan命令时详细介绍。 +// 如果用-target参数指定了某项资源,那么不但会销毁该资源,同时也会销毁一切依赖于该资源的资源。我们会在随后介绍plan命令时详细介绍。 // -//terraform destroy将执行的所有操作都可以随时通过执行terraform plan -destroy命令来预览。 +// terraform destroy将执行的所有操作都可以随时通过执行terraform plan -destroy命令来预览。 func (t *terraformLocalRunner) ExecDestroy(ctx context.Context, req *DestroyRequest) (*DestroyReply, error) { defer t.outTfExecLog(DestroyAction) blog.Infof("running destroy, instance-id: %s", t.instanceID) diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/runner/local_runner_test.go b/bcs-scenarios/bcs-terraform-controller/pkg/runner/local_runner_test.go index 63bfcd9cb5..816ce85280 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/runner/local_runner_test.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/runner/local_runner_test.go @@ -8,9 +8,7 @@ * 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 runner import ( diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/runner/server_cover_backend.go b/bcs-scenarios/bcs-terraform-controller/pkg/runner/server_cover_backend.go index 52e1a294b5..af1f6a06c6 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/runner/server_cover_backend.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/runner/server_cover_backend.go @@ -8,7 +8,6 @@ * 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 runner @@ -44,7 +43,7 @@ func (t *terraformLocalRunner) forceUpdateBackendConfig(content []byte) ([]byte, // 解析文件内容 file, diags := parser.ParseHCL(content, fmt.Sprintf("%s-example.tf", t.instanceID)) // 名称任意即可 if diags.HasErrors() { - return nil, errors.Errorf("failed to parse HCL: %s\n", diags.Error()) + return nil, errors.Errorf("failed to parse HCL: %s", diags.Error()) } // 类型转换 body, err := typeConversion(file.Body) 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 cad5f3a877..b8bc585a1d 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 @@ -8,7 +8,6 @@ * 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 runner @@ -20,16 +19,16 @@ import ( "regexp" "strings" - "github.com/pkg/errors" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-vaultplugin-server/pkg/secret" + "github.com/pkg/errors" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/pkg/utils" ) // var genericPlaceholder, _ = regexp.Compile(`(?mU)<(.*)>`) -var specificPathPlaceholder, _ = regexp.Compile(`(?mU)`) -var indivPlaceholderSyntax, _ = regexp.Compile(`(?mU)path:(?P[^/]+)/data/(?P[^#]+?)#(?P[^#]+?)(?:#(?P.+?))??`) +var specificPathPlaceholder, _ = regexp.Compile(`(?mU)`) // nolint +var indivPlaceholderSyntax, _ = regexp.Compile(`(?mU)path:(?P[^/]+)/data/(?P[^#]+?)#(?P[^#]+?)(?:#(?P.+?))??`) // nolint // GenerateSecretForTF 通过GitOps密钥管理接口渲染provider声明的vault格式AKSK func (t *terraformLocalRunner) GenerateSecretForTF(ctx context.Context, workdir string) error { diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/runner/types.go b/bcs-scenarios/bcs-terraform-controller/pkg/runner/types.go index cd9614c0e8..2fc8532e3a 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/runner/types.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/runner/types.go @@ -8,7 +8,6 @@ * 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 runner @@ -17,6 +16,7 @@ import ( "fmt" "github.com/Tencent/bk-bcs/bcs-common/common/blog" + tfv1 "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/api/v1" ) @@ -41,7 +41,7 @@ type InitRequest struct { // InitReply terraform init reply type InitReply struct { Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` - StateLockIdentifier string `protobuf:"bytes,2,opt,name=stateLockIdentifier,proto3" json:"stateLockIdentifier,omitempty"` + StateLockIdentifier string `protobuf:"bytes,2,opt,name=stateLockIdentifier,proto3" json:"stateLockIdentifier,omitempty"` // nolint } // NewTerraformRequest new terraform request @@ -71,7 +71,7 @@ type PlanRequest struct { type PlanReply struct { Drifted bool `protobuf:"varint,1,opt,name=drifted,proto3" json:"drifted,omitempty"` Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` - StateLockIdentifier string `protobuf:"bytes,3,opt,name=stateLockIdentifier,proto3" json:"stateLockIdentifier,omitempty"` + StateLockIdentifier string `protobuf:"bytes,3,opt,name=stateLockIdentifier,proto3" json:"stateLockIdentifier,omitempty"` // nolint PlanCreated bool `protobuf:"varint,4,opt,name=planCreated,proto3" json:"planCreated,omitempty"` } @@ -79,7 +79,7 @@ type PlanReply struct { type ApplyRequest struct { TfInstance string `protobuf:"bytes,1,opt,name=tfInstance,proto3" json:"tfInstance,omitempty"` DirOrPlan string `protobuf:"bytes,2,opt,name=dirOrPlan,proto3" json:"dirOrPlan,omitempty"` - RefreshBeforeApply bool `protobuf:"varint,3,opt,name=refreshBeforeApply,proto3" json:"refreshBeforeApply,omitempty"` + RefreshBeforeApply bool `protobuf:"varint,3,opt,name=refreshBeforeApply,proto3" json:"refreshBeforeApply,omitempty"` // nolint Targets []string `protobuf:"bytes,4,rep,name=targets,proto3" json:"targets,omitempty"` Parallelism int32 `protobuf:"varint,5,opt,name=parallelism,proto3" json:"parallelism,omitempty"` } @@ -87,7 +87,7 @@ type ApplyRequest struct { // ApplyReply apply terraform reply type ApplyReply struct { Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` - StateLockIdentifier string `protobuf:"bytes,2,opt,name=stateLockIdentifier,proto3" json:"stateLockIdentifier,omitempty"` + StateLockIdentifier string `protobuf:"bytes,2,opt,name=stateLockIdentifier,proto3" json:"stateLockIdentifier,omitempty"` // nolint } // DestroyRequest destroy terraform request @@ -99,7 +99,7 @@ type DestroyRequest struct { // DestroyReply destroy terraform reply type DestroyReply struct { Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` - StateLockIdentifier string `protobuf:"bytes,2,opt,name=stateLockIdentifier,proto3" json:"stateLockIdentifier,omitempty"` + StateLockIdentifier string `protobuf:"bytes,2,opt,name=stateLockIdentifier,proto3" json:"stateLockIdentifier,omitempty"` // nolint } // localPrintfer 本地化的输出对象 diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/server/handler.go b/bcs-scenarios/bcs-terraform-controller/pkg/server/handler.go index 21ebe4e953..6aa95c1c58 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/server/handler.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/server/handler.go @@ -8,7 +8,6 @@ * 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 server xxx @@ -17,16 +16,16 @@ package server import ( "context" "fmt" - "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/pkg/core" - "github.com/google/uuid" "net/http" "time" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/gin-gonic/gin" + "github.com/google/uuid" "k8s.io/apimachinery/pkg/types" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" tfv1 "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/api/v1" + "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-terraform-controller/pkg/core" ) // Apply 执行tf apply命令 @@ -57,8 +56,8 @@ func (h *handler) Apply(ctx *gin.Context) { return } - traceId := uuid.NewString() // tf-cr实例、tf-cr代码路径 - task := core.NewTask(nil, traceId, tf, h.client) + traceId := uuid.NewString() // tf-cr实例、tf-cr代码路径 + task := core.NewTask(nil, traceId, tf, h.client) // nolint do not pass a nil Context if err := task.Init(); err != nil { text := fmt.Sprintf("init task failed, req: %s, err: %s", req, err.Error()) blog.Error(text) @@ -80,8 +79,8 @@ func (h *handler) Apply(ctx *gin.Context) { return } // note: 事件、状态 - //task.SyncEvent() - //task.SyncStatus() + // task.SyncEvent() + // task.SyncStatus() detail := new(TaskApplyResult) detail.Result = true @@ -124,10 +123,10 @@ func (h *handler) CreatePlan(ctx *gin.Context) { return } - //task := core.NewTask(req.ID, tf, h.client) - //task.SetHook(req.Hook) - //go task.Handler() - //h.pool.Store(req.ID, task) + // task := core.NewTask(req.ID, tf, h.client) + // task.SetHook(req.Hook) + // go task.Handler() + // h.pool.Store(req.ID, task) reply(ctx, nil) } diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/server/server.go b/bcs-scenarios/bcs-terraform-controller/pkg/server/server.go index e1054a4a96..ac046f813d 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/server/server.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/server/server.go @@ -8,7 +8,6 @@ * 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 server implements a http server for bcs-terraform-controller @@ -18,10 +17,9 @@ import ( "net" "net/http" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/gin-gonic/gin" "sigs.k8s.io/controller-runtime/pkg/client" - - "github.com/Tencent/bk-bcs/bcs-common/common/blog" ) // Handler server diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/server/server_test.go b/bcs-scenarios/bcs-terraform-controller/pkg/server/server_test.go index d8ca9fc7b7..4dcb4f0629 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/server/server_test.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/server/server_test.go @@ -8,9 +8,7 @@ * 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 server import ( diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/server/types.go b/bcs-scenarios/bcs-terraform-controller/pkg/server/types.go index ae1754ff19..247801218e 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/server/types.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/server/types.go @@ -8,7 +8,6 @@ * 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 server diff --git a/bcs-scenarios/bcs-terraform-controller/pkg/utils/utils.go b/bcs-scenarios/bcs-terraform-controller/pkg/utils/utils.go index 8a558e870b..6537fdccc4 100644 --- a/bcs-scenarios/bcs-terraform-controller/pkg/utils/utils.go +++ b/bcs-scenarios/bcs-terraform-controller/pkg/utils/utils.go @@ -8,7 +8,6 @@ * 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 utils implement simple utils diff --git a/bcs-services/bcs-bkcmdb-synchronizer/cmd/synchronizer/main.go b/bcs-services/bcs-bkcmdb-synchronizer/cmd/synchronizer/main.go index fd9f155453..f691215bd6 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/cmd/synchronizer/main.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/cmd/synchronizer/main.go @@ -10,6 +10,7 @@ * limitations under the License. */ +// Package main xxx package main import ( @@ -25,6 +26,7 @@ import ( ) var ( + // BkcmdbSynchronizerOption xxx BkcmdbSynchronizerOption = &option.BkcmdbSynchronizerOption{} ) diff --git a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/bcsstorage/bcsstorage.go b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/bcsstorage/bcsstorage.go index 81126debc7..0d3a7637b8 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/bcsstorage/bcsstorage.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/bcsstorage/bcsstorage.go @@ -15,6 +15,7 @@ package bcsstorage import ( "context" + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi" pmp "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/bcsproject" cmp "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/clustermanager" @@ -29,68 +30,68 @@ type bcsStorageClient struct { // GetCMDBClient returns a CMDB client instance. func (bsc *bcsStorageClient) GetCMDBClient() (client.CMDBClient, error) { - //implement me + // implement me panic("implement me") } // GetProjectManagerConnWithURL get a project manager grpc connection with url func (bsc *bcsStorageClient) GetProjectManagerConnWithURL() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } // GetProjectManagerClient get a project manager grpc client func (bsc *bcsStorageClient) GetProjectManagerClient() (pmp.BCSProjectClient, error) { - //implement me + // implement me panic("implement me") } // GetProjectManagerConn get a project manager grpc connection func (bsc *bcsStorageClient) GetProjectManagerConn() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } // NewPMGrpcClientWithHeader create a project manager grpc client with header func (bsc *bcsStorageClient) NewPMGrpcClientWithHeader(ctx context.Context, conn *grpc.ClientConn) *client.ProjectManagerClientWithHeader { - //implement me + // implement me panic("implement me") } // GetDataManagerConnWithURL get a data manager grpc connection with url func (bsc *bcsStorageClient) GetDataManagerConnWithURL() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } func (bsc *bcsStorageClient) GetDataManagerConn() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } // GetClusterManagerConnWithURL get a cluster manager grpc connection with url func (bsc *bcsStorageClient) GetClusterManagerConnWithURL() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } // GetClusterManagerClient get a cluster manager grpc client func (bsc *bcsStorageClient) GetClusterManagerClient() (cmp.ClusterManagerClient, error) { - //implement me + // implement me panic("implement me") } // GetClusterManagerConn get a cluster manager grpc connection func (bsc *bcsStorageClient) GetClusterManagerConn() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } // NewCMGrpcClientWithHeader create a cluster manager grpc client with header func (bsc *bcsStorageClient) NewCMGrpcClientWithHeader(ctx context.Context, conn *grpc.ClientConn) *client.ClusterManagerClientWithHeader { - //implement me + // implement me panic("implement me") } diff --git a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/client.go b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/client.go index 8702f5d5ce..645a77da09 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/client.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/client.go @@ -16,7 +16,7 @@ package client import ( "context" - bkcmdbkube "configcenter/src/kube/types" + bkcmdbkube "configcenter/src/kube/types" // nolint "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi" pmp "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/bcsproject" cmp "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/clustermanager" diff --git a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/clustermanager/clustermanager.go b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/clustermanager/clustermanager.go index 4b0e7e06fb..c85772f2b8 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/clustermanager/clustermanager.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/clustermanager/clustermanager.go @@ -136,50 +136,50 @@ type clusterManagerClient struct { // GetCMDBClient returns a CMDB client instance. func (cm *clusterManagerClient) GetCMDBClient() (client.CMDBClient, error) { - //implement me + // implement me panic("implement me") } // GetProjectManagerConnWithURL returns a gRPC client connection with URL. func (cm *clusterManagerClient) GetProjectManagerConnWithURL() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } // GetProjectManagerClient returns a project manager client instance. func (cm *clusterManagerClient) GetProjectManagerClient() (pmp.BCSProjectClient, error) { - //implement me + // implement me panic("implement me") } // GetProjectManagerConn returns a gRPC client connection for project manager. func (cm *clusterManagerClient) GetProjectManagerConn() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } // NewPMGrpcClientWithHeader creates a new project manager gRPC client with header. func (cm *clusterManagerClient) NewPMGrpcClientWithHeader(ctx context.Context, conn *grpc.ClientConn) *client.ProjectManagerClientWithHeader { - //implement me + // implement me panic("implement me") } // GetStorageClient returns a storage client instance. func (cm *clusterManagerClient) GetStorageClient() (bcsapi.Storage, error) { - //implement me + // implement me panic("implement me") } // GetDataManagerConnWithURL returns a gRPC client connection with URL for data manager. func (cm *clusterManagerClient) GetDataManagerConnWithURL() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } // GetDataManagerConn returns a gRPC client connection for data manager. func (cm *clusterManagerClient) GetDataManagerConn() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } @@ -285,7 +285,7 @@ func NewClusterManager(config *client.Config) cmp.ClusterManagerClient { //! pay more attention for nil return return nil } - //create grpc connection + // create grpc connection header := map[string]string{ "x-content-type": "application/grpc+proto", "Content-Type": "application/grpc", @@ -305,7 +305,7 @@ func NewClusterManager(config *client.Config) cmp.ClusterManagerClient { var err error maxTries := 3 for i := 0; i < maxTries; i++ { - selected := rand.Intn(1024) % len(config.Hosts) + selected := rand.Intn(1024) % len(config.Hosts) // nolint addr := config.Hosts[selected] conn, err = grpc.Dial(addr, opts...) if err != nil { @@ -320,7 +320,7 @@ func NewClusterManager(config *client.Config) cmp.ClusterManagerClient { blog.Errorf("create no cluster manager client after all instance tries") return nil } - //init cluster manager client + // init cluster manager client return cmp.NewClusterManagerClient(conn) } 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 e302a7143b..3337e224fb 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 @@ -20,7 +20,7 @@ import ( "fmt" "time" - bkcmdbkube "configcenter/src/kube/types" + bkcmdbkube "configcenter/src/kube/types" // nolint "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi" pmp "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/bcsproject" @@ -87,69 +87,69 @@ type cmdbClient struct { // GetDataManagerConnWithURL returns a gRPC client connection with URL for data manager. func (c *cmdbClient) GetDataManagerConnWithURL() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } // GetDataManagerConn returns a gRPC client connection for data manager. func (c *cmdbClient) GetDataManagerConn() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } // GetClusterManagerConnWithURL returns a gRPC client connection with URL for cluster manager. func (c *cmdbClient) GetClusterManagerConnWithURL() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } // GetClusterManagerClient returns a cluster manager client instance. func (c *cmdbClient) GetClusterManagerClient() (cmp.ClusterManagerClient, error) { - //implement me + // implement me panic("implement me") } // GetClusterManagerConn returns a gRPC client connection for cluster manager. func (c *cmdbClient) GetClusterManagerConn() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } // NewCMGrpcClientWithHeader creates a new cluster manager gRPC client with header. func (c *cmdbClient) NewCMGrpcClientWithHeader(ctx context.Context, conn *grpc.ClientConn) *client.ClusterManagerClientWithHeader { - //implement me + // implement me panic("implement me") } // GetProjectManagerConnWithURL returns a gRPC client connection with URL for project manager. func (c *cmdbClient) GetProjectManagerConnWithURL() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } // GetProjectManagerClient returns a project manager client instance. func (c *cmdbClient) GetProjectManagerClient() (pmp.BCSProjectClient, error) { - //implement me + // implement me panic("implement me") } // GetProjectManagerConn returns a gRPC client connection for project manager. func (c *cmdbClient) GetProjectManagerConn() (*grpc.ClientConn, error) { - //implement me + // implement me panic("implement me") } // NewPMGrpcClientWithHeader creates a new project manager gRPC client with header. func (c *cmdbClient) NewPMGrpcClientWithHeader(ctx context.Context, conn *grpc.ClientConn) *client.ProjectManagerClientWithHeader { - //implement me + // implement me panic("implement me") } // GetStorageClient returns a storage client instance. func (c *cmdbClient) GetStorageClient() (bcsapi.Storage, error) { - //implement me + // implement me panic("implement me") } @@ -207,7 +207,7 @@ func (c *cmdbClient) GetBS2IDByBizID(bizID int64) (int, error) { blog.Errorf("call api GetBS2IDByBizID failed: %v", respData.Message) return 0, fmt.Errorf(respData.Message) } - //successfully request + // successfully request blog.Infof("call api GetBS2IDByBizID with url(%s) successfully", reqURL) if len(respData.Data.Info) > 0 { @@ -253,7 +253,7 @@ func (c *cmdbClient) GetBizInfo(bizID int64) (*client.Business, error) { blog.Errorf("call api GetBizInfo failed: %v", respData.Message) return nil, fmt.Errorf(respData.Message) } - //successfully request + // successfully request blog.Infof("call api GetBizInfo with url(%s) successfully", reqURL) if len(respData.Data.Data) > 0 { @@ -331,7 +331,7 @@ func (c *cmdbClient) GetHostInfo(hostIP []string) (*[]client.HostData, error) { blog.Errorf("call api QueryHost failed: %v", respData.Message) return nil, fmt.Errorf(respData.Message) } - //successfully request + // successfully request blog.Infof("call api QueryHost with url(%s) successfully", reqURL) hostData = append(hostData, respData.Data.Info...) diff --git a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/cmdb/utils.go b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/cmdb/utils.go index 40d6268bc6..2af7b79dd7 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/cmdb/utils.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/cmdb/utils.go @@ -18,6 +18,7 @@ import ( "github.com/Tencent/bk-bcs/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client" ) +// nolint unused func splitCountToPage(counts int, pageLimit int) []client.Page { var pages = make([]client.Page, 0) diff --git a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/projectmanager/projectmanager.go b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/projectmanager/projectmanager.go index 16cd1dd6fd..8e224cda0d 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/projectmanager/projectmanager.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/projectmanager/projectmanager.go @@ -18,11 +18,11 @@ import ( "crypto/tls" "errors" "fmt" - "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi" "math/rand" "time" "github.com/Tencent/bk-bcs/bcs-common/common/blog" + "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi" pmp "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/bcsproject" cmp "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/clustermanager" "github.com/micro/go-micro/v2/registry" @@ -288,7 +288,7 @@ func NewProjectManager(config *client.Config) pmp.BCSProjectClient { //! pay more attention for nil return return nil } - //create grpc connection + // create grpc connection header := map[string]string{ "x-content-type": "application/grpc+proto", "Content-Type": "application/grpc", @@ -309,7 +309,7 @@ func NewProjectManager(config *client.Config) pmp.BCSProjectClient { var err error maxTries := 3 for i := 0; i < maxTries; i++ { - selected := rand.Intn(1024) % len(config.Hosts) + selected := rand.Intn(1024) % len(config.Hosts) // nolint math/rand instead of crypto/rand addr := config.Hosts[selected] conn, err = grpc.Dial(addr, opts...) if err != nil { @@ -324,7 +324,7 @@ func NewProjectManager(config *client.Config) pmp.BCSProjectClient { blog.Errorf("create no project manager client after all instance tries") return nil } - //init cluster manager client + // init cluster manager client return pmp.NewBCSProjectClient(conn) } 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 56cfe5aa3a..a4d896f3c5 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/types.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/client/types.go @@ -16,7 +16,7 @@ import ( "context" "crypto/tls" - bkcmdbkube "configcenter/src/kube/types" + bkcmdbkube "configcenter/src/kube/types" // nolint pmp "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/bcsproject" cmp "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/clustermanager" bcsregistry "github.com/Tencent/bk-bcs/bcs-common/pkg/registry" @@ -109,13 +109,16 @@ type HostData struct { } const ( - KeyBizID = "BsiId" - methodBusiness = "Business" - methodServer = "Server" + // KeyBizID xxx + KeyBizID = "BsiId" + methodBusiness = "Business" + methodServer = "Server" + // MethodBusinessRaw xxx MethodBusinessRaw = "BusinessRaw" ) var ( + // ReqColumns xxx ReqColumns = []string{"BsiId", "BsipId", "BsiProductName", "BsiProductId", "BsiName", "BsiL1", "BsiL2"} ) @@ -233,9 +236,9 @@ type CreateBcsClusterRequest struct { Network *[]string `json:"network"` Type *string `json:"type"` Environment *string `json:"environment"` - //BKProjectID *string `json:"bk_project_id"` - //BKProjectName *string `json:"bk_project_name"` - //BKProjectCode *string `json:"bk_project_code"` + // BKProjectID *string `json:"bk_project_id"` + // BKProjectName *string `json:"bk_project_name"` + // BKProjectCode *string `json:"bk_project_code"` } // CreateBcsClusterResponse defines the response structure for creating a BCS cluster. @@ -364,7 +367,7 @@ type GetBcsNamespaceResponseData struct { // CreateBcsNamespaceRequest represents the request for creating a BCS namespace type CreateBcsNamespaceRequest struct { BKBizID *int64 `json:"bk_biz_id"` - //Data []CreateBcsNamespaceRequestData `json:"data"` + // Data []CreateBcsNamespaceRequestData `json:"data"` Data *[]bkcmdbkube.Namespace `json:"data"` } @@ -413,7 +416,7 @@ type CreateBcsWorkloadRequestData struct { Replicas *int64 `json:"replicas,omitempty" bson:"replicas"` MinReadySeconds *int64 `json:"min_ready_seconds,omitempty" bson:"min_ready_seconds"` StrategyType *string `json:"strategy_type,omitempty" bson:"strategy_type"` - RollingUpdateStrategy *map[string]interface{} `json:"rolling_update_strategy,omitempty" bson:"rolling_update_strategy"` + RollingUpdateStrategy *map[string]interface{} `json:"rolling_update_strategy,omitempty" bson:"rolling_update_strategy"` // nolint } // CreateBcsWorkloadResponse defines the structure of the response for creating a BCS workload. @@ -442,7 +445,7 @@ type UpdateBcsWorkloadRequestData struct { Replicas *int64 `json:"replicas,omitempty" bson:"replicas"` MinReadySeconds *int64 `json:"min_ready_seconds,omitempty" bson:"min_ready_seconds"` StrategyType *string `json:"strategy_type,omitempty" bson:"strategy_type"` - RollingUpdateStrategy *map[string]interface{} `json:"rolling_update_strategy,omitempty" bson:"rolling_update_strategy"` + RollingUpdateStrategy *map[string]interface{} `json:"rolling_update_strategy,omitempty" bson:"rolling_update_strategy"` // nolint } // UpdateBcsWorkloadResponse defines the structure of the response for updating a BCS workload. 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 ed469e55eb..30c4cbbd16 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/common/common.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/common/common.go @@ -31,12 +31,12 @@ func InArray(val interface{}, array interface{}) (exists bool, index int) { exists = false index = -1 - switch reflect.TypeOf(array).Kind() { + switch reflect.TypeOf(array).Kind() { // nolint case reflect.Slice: s := reflect.ValueOf(array) for i := 0; i < s.Len(); i++ { - if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + if reflect.DeepEqual(val, s.Index(i).Interface()) { index = i exists = true return 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 dc31ced368..7f77eb018c 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/handler/handler.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/handler/handler.go @@ -23,8 +23,7 @@ import ( "strings" "time" - bkcmdbkube "configcenter/src/kube/types" - + bkcmdbkube "configcenter/src/kube/types" // nolint "github.com/Tencent/bk-bcs/bcs-common/common/blog" pmp "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/bcsproject" cmp "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi/clustermanager" @@ -50,7 +49,7 @@ type ClusterList []string // BcsBkcmdbSynchronizerHandler is the handler of bcs-bkcmdb-synchronizer type BcsBkcmdbSynchronizerHandler struct { - //BkcmdbSynchronizerOption *option.BkcmdbSynchronizerOption + // BkcmdbSynchronizerOption *option.BkcmdbSynchronizerOption Syncer *syncer.Syncer BkCluster *bkcmdbkube.Cluster Chn *amqp.Channel @@ -82,8 +81,8 @@ func NewBcsBkcmdbSynchronizerHandler(sync *syncer.Syncer) *BcsBkcmdbSynchronizer func (b *BcsBkcmdbSynchronizerHandler) HandleMsg(chn *amqp.Channel, messages <-chan amqp.Delivery) { b.Chn = chn for msg := range messages { - //blog.Infof("Received a message") - //blog.Infof("Message: %v", msg.Headers) + // blog.Infof("Received a message") + // blog.Infof("Message: %v", msg.Headers) err := b.handleCluster(msg) if err != nil { @@ -124,6 +123,7 @@ func (b *BcsBkcmdbSynchronizerHandler) HandleMsg(chn *amqp.Channel, messages <-c } // handle cluster +// nolint funlen func (b *BcsBkcmdbSynchronizerHandler) handleCluster(msg amqp.Delivery) error { if b.BkCluster != nil { return nil @@ -332,7 +332,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handlePodDelete(pod *corev1.Pod) error { bkPod := (*bkPods)[0] - //b.Syncer.DeleteBkPods(b.BkCluster.BizID, &[]int64{bkPod.ID}) + // b.Syncer.DeleteBkPods(b.BkCluster.BizID, &[]int64{bkPod.ID}) err = retry.Do( func() error { return b.Syncer.DeleteBkPods(b.BkCluster, &[]int64{bkPod.ID}) @@ -346,6 +346,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handlePodDelete(pod *corev1.Pod) error { } // handle pod create +// nolint funlen func (b *BcsBkcmdbSynchronizerHandler) handlePodCreate(pod *corev1.Pod) error { var operator []string cmCli, err := b.getClusterManagerGrpcGwClient() @@ -833,7 +834,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleDeploymentDelete(deployment *appv1. return err } - //err = b.Syncer.DeleteBkWorkloads(b.BkCluster.BizID, "deployment", &[]int64{bkDeployment.ID}) + // err = b.Syncer.DeleteBkWorkloads(b.BkCluster.BizID, "deployment", &[]int64{bkDeployment.ID}) err = retry.Do( func() error { return b.Syncer.DeleteBkWorkloads(b.BkCluster, "deployment", &[]int64{bkDeployment.ID}) @@ -1007,7 +1008,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleStatefulSetDelete(statefulSet *appv return err } - //err = b.Syncer.DeleteBkWorkloads(b.BkCluster.BizID, "statefulSet", &[]int64{bkStatefulSet.ID}) + // err = b.Syncer.DeleteBkWorkloads(b.BkCluster.BizID, "statefulSet", &[]int64{bkStatefulSet.ID}) err = retry.Do( func() error { return b.Syncer.DeleteBkWorkloads(b.BkCluster, "statefulSet", &[]int64{bkStatefulSet.ID}) @@ -1181,7 +1182,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleDaemonSetDelete(daemonSet *appv1.Da return err } - //err = b.Syncer.DeleteBkWorkloads(b.BkCluster.BizID, "daemonSet", &[]int64{bkDaemonSet.ID}) + // err = b.Syncer.DeleteBkWorkloads(b.BkCluster.BizID, "daemonSet", &[]int64{bkDaemonSet.ID}) err = retry.Do( func() error { return b.Syncer.DeleteBkWorkloads(b.BkCluster, "daemonSet", &[]int64{bkDaemonSet.ID}) @@ -1304,7 +1305,8 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameDeploymentUpdate(gameDeployment } gameDeploymentToUpdate := make(map[int64]*client.UpdateBcsWorkloadRequestData, 0) - needToUpdate, updateData := b.Syncer.CompareGameDeployment(&bkGameDeployment, &storage.GameDeployment{Data: gameDeployment}) + needToUpdate, updateData := b.Syncer.CompareGameDeployment(&bkGameDeployment, + &storage.GameDeployment{Data: gameDeployment}) if needToUpdate { gameDeploymentToUpdate[bkGameDeployment.ID] = updateData b.Syncer.UpdateBkWorkloads(b.BkCluster, "gameDeployment", &gameDeploymentToUpdate) @@ -1357,7 +1359,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameDeploymentDelete(gameDeployment return err } - //err = b.Syncer.DeleteBkWorkloads(b.BkCluster.BizID, "gameDeployment", &[]int64{bkGameDeployment.ID}) + // err = b.Syncer.DeleteBkWorkloads(b.BkCluster.BizID, "gameDeployment", &[]int64{bkGameDeployment.ID}) err = retry.Do( func() error { return b.Syncer.DeleteBkWorkloads(b.BkCluster, "gameDeployment", &[]int64{bkGameDeployment.ID}) @@ -1483,7 +1485,8 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameStatefulSetUpdate(gameStatefulS } gameStatefulSetToUpdate := make(map[int64]*client.UpdateBcsWorkloadRequestData, 0) - needToUpdate, updateData := b.Syncer.CompareGameStatefulSet(&bkGameStatefulSet, &storage.GameStatefulSet{Data: gameStatefulSet}) + needToUpdate, updateData := b.Syncer.CompareGameStatefulSet(&bkGameStatefulSet, + &storage.GameStatefulSet{Data: gameStatefulSet}) if needToUpdate { gameStatefulSetToUpdate[bkGameStatefulSet.ID] = updateData b.Syncer.UpdateBkWorkloads(b.BkCluster, "gameStatefulSet", &gameStatefulSetToUpdate) @@ -1536,7 +1539,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleGameStatefulSetDelete(gameStatefulS return err } - //err = b.Syncer.DeleteBkWorkloads(b.BkCluster.BizID, "gameStatefulSet", &[]int64{bkGameStatefulSet.ID}) + // err = b.Syncer.DeleteBkWorkloads(b.BkCluster.BizID, "gameStatefulSet", &[]int64{bkGameStatefulSet.ID}) err = retry.Do( func() error { return b.Syncer.DeleteBkWorkloads(b.BkCluster, "gameStatefulSet", &[]int64{bkGameStatefulSet.ID}) @@ -1704,7 +1707,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNamespaceDelete(namespace *corev1.N bkNamespace := (*bkNamespaces)[0] - //err = b.Syncer.DeleteBkNamespaces(b.BkCluster.BizID, &[]int64{bkNamespace.ID}) + // err = b.Syncer.DeleteBkNamespaces(b.BkCluster.BizID, &[]int64{bkNamespace.ID}) err = retry.Do( func() error { // DeleteBkNamespaces delete bknamespaces @@ -1874,7 +1877,7 @@ func (b *BcsBkcmdbSynchronizerHandler) handleNodeDelete(node *corev1.Node) error bkNode := (*bkNodes)[0] - //b.Syncer.DeleteBkNodes(b.BkCluster.BizID, &[]int64{bkNode.ID}) + // b.Syncer.DeleteBkNodes(b.BkCluster.BizID, &[]int64{bkNode.ID}) err = retry.Do( func() error { return b.Syncer.DeleteBkNodes(b.BkCluster, &[]int64{bkNode.ID}) @@ -1917,13 +1920,12 @@ func (b *BcsBkcmdbSynchronizerHandler) PublishMsg(msg amqp.Delivery) error { msg.Headers["republish"] = 1 } else { // If it has been republished before, check if the republish count is less than 100. - if republish.(int32) < 100 { - // If it is, increment the republish count. - msg.Headers["republish"] = republish.(int32) + 1 - } else { + if !(republish.(int32) < 100) { // If it has been republished more than 100 times, return an error. return errors.New("no need to publish") } + // If it is, increment the republish count. + msg.Headers["republish"] = republish.(int32) + 1 } // Publish the message to the exchange with the specified routing key. @@ -1949,7 +1951,8 @@ func (b *BcsBkcmdbSynchronizerHandler) PublishMsg(msg amqp.Delivery) error { return err } -func (b *BcsBkcmdbSynchronizerHandler) getClusterManagerGrpcGwClient() (cmCli *client.ClusterManagerClientWithHeader, err error) { +func (b *BcsBkcmdbSynchronizerHandler) getClusterManagerGrpcGwClient() ( + cmCli *client.ClusterManagerClientWithHeader, err error) { opts := &cm.Options{ Module: cm.ModuleClusterManager, Address: b.Syncer.BkcmdbSynchronizerOption.Bcsapi.GrpcAddr, diff --git a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/mq/rabbitmq/rabbitmq.go b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/mq/rabbitmq/rabbitmq.go index da3c36a878..ae9128409f 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/mq/rabbitmq/rabbitmq.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/mq/rabbitmq/rabbitmq.go @@ -90,7 +90,7 @@ func (r *RabbitMQ) EnsureExchange(chn *amqp.Channel) error { return err } - err = chn.ExchangeBind( + _ = chn.ExchangeBind( exchangeName, "*", r.config.SourceExchange, @@ -114,7 +114,7 @@ func (r *RabbitMQ) DeclareQueue(chn *amqp.Channel, queueName string, args amqp.T true, false, args, - //amqp.Table{"x-expires": 60000}, + // amqp.Table{"x-expires": 60000}, ) if err != nil { fmt.Printf("Error creating queue with name: %s, err: %s", queueName, err.Error()) 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 05c023df66..93122100dd 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/syncer/syncer.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/pkg/syncer/syncer.go @@ -21,8 +21,7 @@ import ( "fmt" "strconv" - bkcmdbkube "configcenter/src/kube/types" - + bkcmdbkube "configcenter/src/kube/types" // nolint "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/common/ssl" "github.com/Tencent/bk-bcs/bcs-common/pkg/bcsapi" @@ -43,7 +42,7 @@ import ( type Syncer struct { BkcmdbSynchronizerOption *option.BkcmdbSynchronizerOption ClientTls *tls.Config - //Rabbit mq.MQ + // Rabbit mq.MQ CMDBClient client.CMDBClient } @@ -84,7 +83,7 @@ func (s *Syncer) initTlsConfig() error { s.BkcmdbSynchronizerOption.Client.ClientKey, s.BkcmdbSynchronizerOption.Client.ClientCrtPwd, ) - //static.ClientCertPwd) + // static.ClientCertPwd) if err != nil { blog.Errorf("init tls config failed, err: %s", err.Error()) return err @@ -97,6 +96,7 @@ func (s *Syncer) initTlsConfig() error { } // init CMDB Client +// nolint (error) is always nil func (s *Syncer) initCMDBClient() error { blog.Infof("init cmdb client") cmdbCli := cmdb.NewCmdbClient(&cmdb.Options{ @@ -133,8 +133,8 @@ func (s *Syncer) SyncCluster(cluster *cmp.Cluster) error { clusterType = "SHARE_CLUSTER" } - if err != nil { - if err.Error() == "cluster not found" { + if err != nil { // nolint + if err.Error() == "cluster not found" { // nolint var clusterBkBizID int64 if bkBizID == 0 { clusterBkBizID, err = strconv.ParseInt(cluster.BusinessID, 10, 64) @@ -147,7 +147,7 @@ func (s *Syncer) SyncCluster(cluster *cmp.Cluster) error { clusterBkBizID = bkBizID } // CreateBcsCluster creates a new BCS cluster with the given request. - _, err := s.CMDBClient.CreateBcsCluster(&client.CreateBcsClusterRequest{ + _, err = s.CMDBClient.CreateBcsCluster(&client.CreateBcsClusterRequest{ BKBizID: &clusterBkBizID, Name: &cluster.ClusterID, SchedulingEngine: &cluster.EngineType, @@ -271,13 +271,14 @@ func (s *Syncer) SyncNodes(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) } s.CreateBkNodes(bkCluster, &nodeToAdd) - s.DeleteBkNodes(bkCluster, &nodeToDelete) + s.DeleteBkNodes(bkCluster, &nodeToDelete) // nolint not checked s.UpdateBkNodes(bkCluster, &nodeToUpdate) return err } // SyncNamespaces sync namespaces +// nolint funlen 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() @@ -374,7 +375,7 @@ func (s *Syncer) SyncNamespaces(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Clus } } - s.DeleteBkNamespaces(bkCluster, &nsToDelete) + s.DeleteBkNamespaces(bkCluster, &nsToDelete) // nolint not checked s.CreateBkNamespaces(bkCluster, nsToAdd) s.UpdateBkNamespaces(bkCluster, &nsToUpdate) @@ -423,6 +424,7 @@ func (s *Syncer) SyncWorkloads(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Clust } // syncDeployments sync deployments +// nolint funlen func (s *Syncer) syncDeployments(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) error { kind := "deployment" // GetBcsStorageClient is a function that returns a BCS storage client. @@ -534,7 +536,7 @@ func (s *Syncer) syncDeployments(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Clu } } - s.DeleteBkWorkloads(bkCluster, kind, &deploymentToDelete) + s.DeleteBkWorkloads(bkCluster, kind, &deploymentToDelete) // nolint not checked s.CreateBkWorkloads(bkCluster, kind, deploymentToAdd) s.UpdateBkWorkloads(bkCluster, kind, &deploymentToUpdate) @@ -542,6 +544,7 @@ func (s *Syncer) syncDeployments(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Clu } // syncStatefulSets sync statefulsets +// nolint funlen func (s *Syncer) syncStatefulSets(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) error { kind := "statefulSet" // GetBcsStorageClient is a function that returns a BCS storage client. @@ -650,7 +653,7 @@ func (s *Syncer) syncStatefulSets(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cl } } - s.DeleteBkWorkloads(bkCluster, kind, &statefulSetToDelete) + s.DeleteBkWorkloads(bkCluster, kind, &statefulSetToDelete) // nolint not checked s.CreateBkWorkloads(bkCluster, kind, statefulSetToAdd) s.UpdateBkWorkloads(bkCluster, kind, &statefulSetToUpdate) @@ -658,6 +661,7 @@ func (s *Syncer) syncStatefulSets(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cl } // syncDaemonSets sync daemonsets +// nolint funlen func (s *Syncer) syncDaemonSets(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) error { kind := "daemonSet" // GetBcsStorageClient is a function that returns a BCS storage client. @@ -765,7 +769,7 @@ func (s *Syncer) syncDaemonSets(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Clus } } - s.DeleteBkWorkloads(bkCluster, kind, &daemonSetToDelete) + s.DeleteBkWorkloads(bkCluster, kind, &daemonSetToDelete) // nolint not checked s.CreateBkWorkloads(bkCluster, kind, daemonSetToAdd) s.UpdateBkWorkloads(bkCluster, kind, &daemonSetToUpdate) @@ -773,6 +777,7 @@ func (s *Syncer) syncDaemonSets(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Clus } // syncGameDeployments sync gamedeployments +// nolint funlen func (s *Syncer) syncGameDeployments(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) error { kind := "gameDeployment" storageCli, err := s.GetBcsStorageClient() @@ -805,7 +810,7 @@ func (s *Syncer) syncGameDeployments(cluster *cmp.Cluster, bkCluster *bkcmdbkube bkGameDeploymentList := make([]bkcmdbkube.GameDeployment, 0) for _, ns := range *bkNamespaceList { - gameDeployments, err := storageCli.QueryK8SGameDeployment(cluster.ClusterID, ns.Name) + gameDeployments, err := storageCli.QueryK8SGameDeployment(cluster.ClusterID, ns.Name) // nolint if err != nil { blog.Errorf("query k8s gamedeployment failed, err: %s", err.Error()) return err @@ -863,9 +868,11 @@ func (s *Syncer) syncGameDeployments(cluster *cmp.Cluster, bkCluster *bkcmdbkube toAddData := s.GenerateBkGameDeployment(bkNamespaceMap[v.Data.Namespace], v) if toAddData != nil { if _, ok = gameDeploymentToAdd[bkNamespaceMap[v.Data.Namespace].BizID]; ok { - gameDeploymentToAdd[bkNamespaceMap[v.Data.Namespace].BizID] = append(gameDeploymentToAdd[bkNamespaceMap[v.Data.Namespace].BizID], *toAddData) + gameDeploymentToAdd[bkNamespaceMap[v.Data.Namespace].BizID] = + append(gameDeploymentToAdd[bkNamespaceMap[v.Data.Namespace].BizID], *toAddData) } else { - gameDeploymentToAdd[bkNamespaceMap[v.Data.Namespace].BizID] = []client.CreateBcsWorkloadRequestData{*toAddData} + gameDeploymentToAdd[bkNamespaceMap[v.Data.Namespace].BizID] = + []client.CreateBcsWorkloadRequestData{*toAddData} } } } else { @@ -876,7 +883,7 @@ func (s *Syncer) syncGameDeployments(cluster *cmp.Cluster, bkCluster *bkcmdbkube } } - s.DeleteBkWorkloads(bkCluster, kind, &gameDeploymentToDelete) + s.DeleteBkWorkloads(bkCluster, kind, &gameDeploymentToDelete) // nolint not checked s.CreateBkWorkloads(bkCluster, kind, gameDeploymentToAdd) s.UpdateBkWorkloads(bkCluster, kind, &gameDeploymentToUpdate) @@ -884,6 +891,7 @@ func (s *Syncer) syncGameDeployments(cluster *cmp.Cluster, bkCluster *bkcmdbkube } // syncGameStatefulSets sync gamestatefulsets +// nolint funlen func (s *Syncer) syncGameStatefulSets(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) error { kind := "gameStatefulSet" storageCli, err := s.GetBcsStorageClient() @@ -988,7 +996,7 @@ func (s *Syncer) syncGameStatefulSets(cluster *cmp.Cluster, bkCluster *bkcmdbkub } } - s.DeleteBkWorkloads(bkCluster, kind, &gameStatefulSetToDelete) + s.DeleteBkWorkloads(bkCluster, kind, &gameStatefulSetToDelete) // nolint not checked s.CreateBkWorkloads(bkCluster, kind, gameStatefulSetToAdd) s.UpdateBkWorkloads(bkCluster, kind, &gameStatefulSetToUpdate) @@ -996,6 +1004,7 @@ func (s *Syncer) syncGameStatefulSets(cluster *cmp.Cluster, bkCluster *bkcmdbkub } // syncWorkloadPods sync workloadPods +// nolint func (s *Syncer) syncWorkloadPods(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) error { kind := "pods" // nolint bkNamespaceList, err := s.GetBkNamespaces(bkCluster.BizID, &client.PropertyFilter{ @@ -1074,14 +1083,16 @@ func (s *Syncer) syncWorkloadPods(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cl } } - s.DeleteBkWorkloads(bkCluster, kind, &workloadPodsToDelete) + s.DeleteBkWorkloads(bkCluster, kind, &workloadPodsToDelete) // nolint not checked s.CreateBkWorkloads(bkCluster, kind, workloadPodsToAdd) s.UpdateBkWorkloads(bkCluster, kind, &workloadPodsToUpdate) return nil } -func (s *Syncer) getBkNsMap(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) (map[string]*bkcmdbkube.Namespace, error) { +// nolint +func (s *Syncer) getBkNsMap( + cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) (map[string]*bkcmdbkube.Namespace, error) { bkNamespaceList, err := s.GetBkNamespaces(bkCluster.BizID, &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -1105,7 +1116,9 @@ func (s *Syncer) getBkNsMap(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) return bkNsMap, nil } -func (s *Syncer) getBkDeploymentMap(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) (map[string]*bkcmdbkube.Deployment, error) { +// nolint +func (s *Syncer) getBkDeploymentMap( + cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) (map[string]*bkcmdbkube.Deployment, error) { bkDeploymentList := make([]bkcmdbkube.Deployment, 0) bkDeployments, err := s.GetBkWorkloads(bkCluster.BizID, "deployment", &client.PropertyFilter{ @@ -1142,7 +1155,9 @@ func (s *Syncer) getBkDeploymentMap(cluster *cmp.Cluster, bkCluster *bkcmdbkube. return bkDeploymentMap, nil } -func (s *Syncer) getBkStatefulSetMap(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) (map[string]*bkcmdbkube.StatefulSet, error) { +// nolint +func (s *Syncer) getBkStatefulSetMap( + cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) (map[string]*bkcmdbkube.StatefulSet, error) { bkStatefulSetList := make([]bkcmdbkube.StatefulSet, 0) bkStatefulSets, err := s.GetBkWorkloads(bkCluster.BizID, "statefulSet", &client.PropertyFilter{ @@ -1178,7 +1193,9 @@ func (s *Syncer) getBkStatefulSetMap(cluster *cmp.Cluster, bkCluster *bkcmdbkube return bkStatefulSetMap, nil } -func (s *Syncer) getBkDaemonSetMap(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) (map[string]*bkcmdbkube.DaemonSet, error) { +// nolint +func (s *Syncer) getBkDaemonSetMap( + cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) (map[string]*bkcmdbkube.DaemonSet, error) { bkDaemonSetList := make([]bkcmdbkube.DaemonSet, 0) bkDaemonSets, err := s.GetBkWorkloads(bkCluster.BizID, "daemonSet", &client.PropertyFilter{ @@ -1214,7 +1231,9 @@ func (s *Syncer) getBkDaemonSetMap(cluster *cmp.Cluster, bkCluster *bkcmdbkube.C return bkDaemonSetMap, nil } -func (s *Syncer) getBkGameDeploymentMap(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) (map[string]*bkcmdbkube.GameDeployment, error) { +// nolint +func (s *Syncer) getBkGameDeploymentMap( + cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) (map[string]*bkcmdbkube.GameDeployment, error) { bkGameDeploymentList := make([]bkcmdbkube.GameDeployment, 0) bkGameDeployments, err := s.GetBkWorkloads(bkCluster.BizID, "gameDeployment", &client.PropertyFilter{ @@ -1250,7 +1269,9 @@ func (s *Syncer) getBkGameDeploymentMap(cluster *cmp.Cluster, bkCluster *bkcmdbk return bkGameDeploymentMap, nil } -func (s *Syncer) getBkGameStatefulSetMap(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) (map[string]*bkcmdbkube.GameStatefulSet, error) { +// nolint +func (s *Syncer) getBkGameStatefulSetMap( + cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) (map[string]*bkcmdbkube.GameStatefulSet, error) { bkGameStatefulSetList := make([]bkcmdbkube.GameStatefulSet, 0) bkGameStatefulSets, err := s.GetBkWorkloads(bkCluster.BizID, "gameStatefulSet", &client.PropertyFilter{ @@ -1286,7 +1307,9 @@ func (s *Syncer) getBkGameStatefulSetMap(cluster *cmp.Cluster, bkCluster *bkcmdb return bkGameStatefulSetMap, nil } -func (s *Syncer) getBkNodeMap(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) (map[string]*bkcmdbkube.Node, error) { +// nolint +func (s *Syncer) getBkNodeMap( + cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) (map[string]*bkcmdbkube.Node, error) { bkNodeList, err := s.GetBkNodes(bkCluster.BizID, &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -1309,7 +1332,9 @@ func (s *Syncer) getBkNodeMap(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluste return bkNodeMap, nil } -func (s *Syncer) getBkWorkloadPods(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster, pod *storage.Pod) (*bkcmdbkube.PodsWorkload, error) { +// nolint +func (s *Syncer) getBkWorkloadPods( + cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster, pod *storage.Pod) (*bkcmdbkube.PodsWorkload, error) { bkWorkloadPods, err := s.GetBkWorkloads(bkCluster.BizID, "pods", &client.PropertyFilter{ Condition: "AND", Rules: []client.Rule{ @@ -1451,7 +1476,7 @@ func (s *Syncer) getPodWordloadInfo( break } rsOwnerRef := rs.Data.OwnerReferences[0] - switch rsOwnerRef.Kind { + switch rsOwnerRef.Kind { // nolint case "Deployment": workloadKind = "deployment" workloadName = rsOwnerRef.Name @@ -1467,6 +1492,7 @@ func (s *Syncer) getPodWordloadInfo( } // SyncPods sync pods +// nolint funlen func (s *Syncer) SyncPods(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) error { storageCli, err := s.GetBcsStorageClient() if err != nil { @@ -1696,7 +1722,7 @@ func (s *Syncer) SyncPods(cluster *cmp.Cluster, bkCluster *bkcmdbkube.Cluster) e } s.CreateBkPods(bkCluster, podToAdd) - s.DeleteBkPods(bkCluster, &podToDelete) + s.DeleteBkPods(bkCluster, &podToDelete) // nolint not checked return err } @@ -1854,22 +1880,23 @@ func (s *Syncer) CreateBkNodes(bkCluster *bkcmdbkube.Cluster, toCreate *[]client } // CompareNode compare bknode and k8snode -func (s *Syncer) CompareNode(bkNode *bkcmdbkube.Node, k8sNode *storage.K8sNode) (needToUpdate bool, updateData *client.UpdateBcsNodeRequestData) { +func (s *Syncer) CompareNode(bkNode *bkcmdbkube.Node, k8sNode *storage.K8sNode) ( + needToUpdate bool, updateData *client.UpdateBcsNodeRequestData) { updateData = &client.UpdateBcsNodeRequestData{} needToUpdate = false labelsEmpty := map[string]string{} - //var updateDataIDs []int64 - //updateData.IDs = &updateDataIDs - //var updateDataNode client.UpdateBcsNodeRequestDataNode - //updateData.Node = &updateDataNode + // var updateDataIDs []int64 + // updateData.IDs = &updateDataIDs + // var updateDataNode client.UpdateBcsNodeRequestDataNode + // updateData.Node = &updateDataNode - taints := make(map[string]string) + taints := make(map[string]string) // nolint for _, taint := range k8sNode.Data.Spec.Taints { taints[taint.Key] = taint.Value } - if taints == nil { + if taints == nil { // nolint this nil check is never true if bkNode.Taints != nil { updateData.Taints = &taints needToUpdate = true @@ -1892,21 +1919,17 @@ func (s *Syncer) CompareNode(bkNode *bkcmdbkube.Node, k8sNode *storage.K8sNode) if bkNode.Unschedulable == nil { updateData.Unschedulable = &k8sNode.Data.Spec.Unschedulable needToUpdate = true - } else { - if *bkNode.Unschedulable != k8sNode.Data.Spec.Unschedulable { - updateData.Unschedulable = &k8sNode.Data.Spec.Unschedulable - needToUpdate = true - } + } else if *bkNode.Unschedulable != k8sNode.Data.Spec.Unschedulable { + updateData.Unschedulable = &k8sNode.Data.Spec.Unschedulable + needToUpdate = true } if bkNode.PodCidr == nil { updateData.PodCidr = &k8sNode.Data.Spec.PodCIDR needToUpdate = true - } else { - if *bkNode.PodCidr != k8sNode.Data.Spec.PodCIDR { - updateData.PodCidr = &k8sNode.Data.Spec.PodCIDR - needToUpdate = true - } + } else if *bkNode.PodCidr != k8sNode.Data.Spec.PodCIDR { + updateData.PodCidr = &k8sNode.Data.Spec.PodCIDR + needToUpdate = true } if *bkNode.RuntimeComponent != k8sNode.Data.Status.NodeInfo.ContainerRuntimeVersion { @@ -1922,7 +1945,8 @@ func (s *Syncer) CompareNode(bkNode *bkcmdbkube.Node, k8sNode *storage.K8sNode) } // GenerateBkNodeData generate bknode data from k8snode -func (s *Syncer) GenerateBkNodeData(bkCluster *bkcmdbkube.Cluster, k8sNode *storage.K8sNode) client.CreateBcsNodeRequestData { +func (s *Syncer) GenerateBkNodeData( + bkCluster *bkcmdbkube.Cluster, k8sNode *storage.K8sNode) client.CreateBcsNodeRequestData { taints := make(map[string]string) for _, taint := range k8sNode.Data.Spec.Taints { taints[taint.Key] = taint.Value @@ -2057,15 +2081,16 @@ func (s *Syncer) GetBkNamespaces(bkBizID int64, filter *client.PropertyFilter) ( } // CompareNamespace compare bkns and k8sns -func (s *Syncer) CompareNamespace(bkNs *bkcmdbkube.Namespace, k8sNs *storage.Namespace) (needToUpdate bool, updateData *client.UpdateBcsNamespaceRequestData) { +func (s *Syncer) CompareNamespace(bkNs *bkcmdbkube.Namespace, k8sNs *storage.Namespace) ( + needToUpdate bool, updateData *client.UpdateBcsNamespaceRequestData) { updateData = &client.UpdateBcsNamespaceRequestData{} needToUpdate = false labelsEmpty := map[string]string{} - //var updateDataIDs []int64 - //updateData.IDs = &updateDataIDs - //var updateDataInfo client.UpdateBcsNamespaceRequestDataInfo - //updateData.Info = &updateDataInfo + // var updateDataIDs []int64 + // updateData.IDs = &updateDataIDs + // var updateDataInfo client.UpdateBcsNamespaceRequestDataInfo + // updateData.Info = &updateDataInfo if k8sNs.Data.Labels == nil { if bkNs.Labels != nil { @@ -2233,7 +2258,8 @@ func (s *Syncer) DeleteBkNamespaces(bkCluster *bkcmdbkube.Cluster, toDelete *[]i } // GetBkWorkloads get bkworkloads -func (s *Syncer) GetBkWorkloads(bkBizID int64, workloadType string, filter *client.PropertyFilter) (*[]interface{}, error) { +func (s *Syncer) GetBkWorkloads( + bkBizID int64, workloadType string, filter *client.PropertyFilter) (*[]interface{}, error) { bkWorkloadList := make([]interface{}, 0) pageStart := 0 @@ -2246,7 +2272,7 @@ func (s *Syncer) GetBkWorkloads(bkBizID int64, workloadType string, filter *clie Start: 100 * pageStart, }, Filter: filter, - //Filter: &client.PropertyFilter{ + // Filter: &client.PropertyFilter{ // Condition: "OR", // Rules: []client.Rule{ // { @@ -2255,9 +2281,9 @@ func (s *Syncer) GetBkWorkloads(bkBizID int64, workloadType string, filter *clie // Value: []string{bkCluster.Uid}, // }, // }, - //}, + // }, }, - //ClusterUID: bkCluster.Uid, + // ClusterUID: bkCluster.Uid, Kind: workloadType, }) @@ -2277,7 +2303,8 @@ func (s *Syncer) GetBkWorkloads(bkBizID int64, workloadType string, filter *clie } // CreateBkWorkloads create bkworkloads -func (s *Syncer) CreateBkWorkloads(bkCluster *bkcmdbkube.Cluster, kind string, toCreate map[int64][]client.CreateBcsWorkloadRequestData) { +func (s *Syncer) CreateBkWorkloads( + bkCluster *bkcmdbkube.Cluster, kind string, toCreate map[int64][]client.CreateBcsWorkloadRequestData) { if len(toCreate) > 0 { for bizid, workloads := range toCreate { if len(workloads) > 0 { @@ -2315,7 +2342,10 @@ func (s *Syncer) CreateBkWorkloads(bkCluster *bkcmdbkube.Cluster, kind string, t } // CompareDeployment compare bkdeployment and k8sdeployment -func (s *Syncer) CompareDeployment(bkDeployment *bkcmdbkube.Deployment, k8sDeployment *storage.Deployment) (needToUpdate bool, updateData *client.UpdateBcsWorkloadRequestData) { +// nolint funlen +func (s *Syncer) CompareDeployment( + bkDeployment *bkcmdbkube.Deployment, k8sDeployment *storage.Deployment) ( + needToUpdate bool, updateData *client.UpdateBcsWorkloadRequestData) { updateData = &client.UpdateBcsWorkloadRequestData{} needToUpdate = false labelsEmpty := map[string]string{} @@ -2425,7 +2455,8 @@ func (s *Syncer) CompareDeployment(bkDeployment *bkcmdbkube.Deployment, k8sDeplo } // GenerateBkDeployment generate bkdeployment from k8sdeployment -func (s *Syncer) GenerateBkDeployment(bkNs *bkcmdbkube.Namespace, k8sDeployment *storage.Deployment) *client.CreateBcsWorkloadRequestData { +func (s *Syncer) GenerateBkDeployment( + bkNs *bkcmdbkube.Namespace, k8sDeployment *storage.Deployment) *client.CreateBcsWorkloadRequestData { me := make([]bkcmdbkube.LabelSelectorRequirement, 0) for _, m := range k8sDeployment.Data.Spec.Selector.MatchExpressions { me = append(me, bkcmdbkube.LabelSelectorRequirement{ @@ -2464,7 +2495,7 @@ func (s *Syncer) GenerateBkDeployment(bkNs *bkcmdbkube.Namespace, k8sDeployment } rudMap := make(map[string]interface{}) - err = json.Unmarshal(jsonBytes, &rudMap) + _ = json.Unmarshal(jsonBytes, &rudMap) replicas := int64(*k8sDeployment.Data.Spec.Replicas) minReadySeconds := int64(k8sDeployment.Data.Spec.MinReadySeconds) strategyType := string(k8sDeployment.Data.Spec.Strategy.Type) @@ -2485,7 +2516,10 @@ func (s *Syncer) GenerateBkDeployment(bkNs *bkcmdbkube.Namespace, k8sDeployment } // CompareStatefulSet compare bkstatefulset and k8sstatefulset -func (s *Syncer) CompareStatefulSet(bkStatefulSet *bkcmdbkube.StatefulSet, k8sStatefulSet *storage.StatefulSet) (needToUpdate bool, updateData *client.UpdateBcsWorkloadRequestData) { +// nolint funlen +func (s *Syncer) CompareStatefulSet( + bkStatefulSet *bkcmdbkube.StatefulSet, k8sStatefulSet *storage.StatefulSet) ( + needToUpdate bool, updateData *client.UpdateBcsWorkloadRequestData) { needToUpdate = false updateData = &client.UpdateBcsWorkloadRequestData{} labelsEmpty := map[string]string{} @@ -2500,7 +2534,8 @@ func (s *Syncer) CompareStatefulSet(bkStatefulSet *bkcmdbkube.StatefulSet, k8sSt updateData.Labels = &labelsEmpty needToUpdate = true } - } else if bkStatefulSet.Labels == nil || fmt.Sprint(k8sStatefulSet.Data.Labels) != fmt.Sprint(*bkStatefulSet.Labels) { + } else if bkStatefulSet.Labels == nil || + fmt.Sprint(k8sStatefulSet.Data.Labels) != fmt.Sprint(*bkStatefulSet.Labels) { updateData.Labels = &k8sStatefulSet.Data.Labels needToUpdate = true } @@ -2510,7 +2545,8 @@ func (s *Syncer) CompareStatefulSet(bkStatefulSet *bkcmdbkube.StatefulSet, k8sSt updateData.Selector = nil needToUpdate = true } - } else if bkStatefulSet.Selector == nil || fmt.Sprint(k8sStatefulSet.Data.Spec.Selector) != fmt.Sprint(*bkStatefulSet.Selector) { + } else if bkStatefulSet.Selector == nil || + fmt.Sprint(k8sStatefulSet.Data.Spec.Selector) != fmt.Sprint(*bkStatefulSet.Selector) { me := make([]bkcmdbkube.LabelSelectorRequirement, 0) for _, m := range k8sStatefulSet.Data.Spec.Selector.MatchExpressions { me = append(me, bkcmdbkube.LabelSelectorRequirement{ @@ -2540,7 +2576,8 @@ func (s *Syncer) CompareStatefulSet(bkStatefulSet *bkcmdbkube.StatefulSet, k8sSt needToUpdate = true } - if *bkStatefulSet.StrategyType != bkcmdbkube.StatefulSetUpdateStrategyType(k8sStatefulSet.Data.Spec.UpdateStrategy.Type) { + if *bkStatefulSet.StrategyType != + bkcmdbkube.StatefulSetUpdateStrategyType(k8sStatefulSet.Data.Spec.UpdateStrategy.Type) { strategyType := string(k8sStatefulSet.Data.Spec.UpdateStrategy.Type) updateData.StrategyType = &strategyType needToUpdate = true @@ -2551,7 +2588,8 @@ func (s *Syncer) CompareStatefulSet(bkStatefulSet *bkcmdbkube.StatefulSet, k8sSt updateData.RollingUpdateStrategy = nil needToUpdate = true } - } else if fmt.Sprint(k8sStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate) != fmt.Sprint(*bkStatefulSet.RollingUpdateStrategy) { + } else if fmt.Sprint(k8sStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate) != + fmt.Sprint(*bkStatefulSet.RollingUpdateStrategy) { rus := bkcmdbkube.RollingUpdateStatefulSetStrategy{} if k8sStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate != nil { @@ -2572,7 +2610,7 @@ func (s *Syncer) CompareStatefulSet(bkStatefulSet *bkcmdbkube.StatefulSet, k8sSt } rusMap := make(map[string]interface{}) - err = json.Unmarshal(jsonBytes, &rusMap) + _ = json.Unmarshal(jsonBytes, &rusMap) updateData.RollingUpdateStrategy = &rusMap needToUpdate = true @@ -2586,7 +2624,8 @@ func (s *Syncer) CompareStatefulSet(bkStatefulSet *bkcmdbkube.StatefulSet, k8sSt } // GenerateBkStatefulSet generate bkstatefulset from k8sstatefulset -func (s *Syncer) GenerateBkStatefulSet(bkNs *bkcmdbkube.Namespace, k8sStatefulSet *storage.StatefulSet) *client.CreateBcsWorkloadRequestData { +func (s *Syncer) GenerateBkStatefulSet( + bkNs *bkcmdbkube.Namespace, k8sStatefulSet *storage.StatefulSet) *client.CreateBcsWorkloadRequestData { me := make([]bkcmdbkube.LabelSelectorRequirement, 0) for _, m := range k8sStatefulSet.Data.Spec.Selector.MatchExpressions { me = append(me, bkcmdbkube.LabelSelectorRequirement{ @@ -2598,7 +2637,8 @@ func (s *Syncer) GenerateBkStatefulSet(bkNs *bkcmdbkube.Namespace, k8sStatefulSe rus := bkcmdbkube.RollingUpdateStatefulSetStrategy{} - if k8sStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate != nil && k8sStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable != nil { + if k8sStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate != nil && + k8sStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable != nil { if k8sStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable != nil { rus.MaxUnavailable = &bkcmdbkube.IntOrString{ Type: bkcmdbkube.Type(k8sStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable.Type), @@ -2616,7 +2656,7 @@ func (s *Syncer) GenerateBkStatefulSet(bkNs *bkcmdbkube.Namespace, k8sStatefulSe } rusMap := make(map[string]interface{}) - err = json.Unmarshal(jsonBytes, &rusMap) + _ = json.Unmarshal(jsonBytes, &rusMap) replicas := int64(*k8sStatefulSet.Data.Spec.Replicas) minReadySeconds := int64(k8sStatefulSet.Data.Spec.MinReadySeconds) @@ -2638,7 +2678,10 @@ func (s *Syncer) GenerateBkStatefulSet(bkNs *bkcmdbkube.Namespace, k8sStatefulSe } // CompareDaemonSet compare bkdaemonset and k8sdaemonset -func (s *Syncer) CompareDaemonSet(bkDaemonSet *bkcmdbkube.DaemonSet, k8sDaemonSet *storage.DaemonSet) (needToUpdate bool, updateData *client.UpdateBcsWorkloadRequestData) { +// nolint funlen +func (s *Syncer) CompareDaemonSet( + bkDaemonSet *bkcmdbkube.DaemonSet, k8sDaemonSet *storage.DaemonSet) ( + needToUpdate bool, updateData *client.UpdateBcsWorkloadRequestData) { needToUpdate = false updateData = &client.UpdateBcsWorkloadRequestData{} labelsEmpty := map[string]string{} @@ -2663,7 +2706,8 @@ func (s *Syncer) CompareDaemonSet(bkDaemonSet *bkcmdbkube.DaemonSet, k8sDaemonSe updateData.Selector = nil needToUpdate = true } - } else if bkDaemonSet.Selector == nil || fmt.Sprint(k8sDaemonSet.Data.Spec.Selector) != fmt.Sprint(*bkDaemonSet.Selector) { + } else if bkDaemonSet.Selector == nil || + fmt.Sprint(k8sDaemonSet.Data.Spec.Selector) != fmt.Sprint(*bkDaemonSet.Selector) { me := make([]bkcmdbkube.LabelSelectorRequirement, 0) for _, m := range k8sDaemonSet.Data.Spec.Selector.MatchExpressions { me = append(me, bkcmdbkube.LabelSelectorRequirement{ @@ -2698,7 +2742,8 @@ func (s *Syncer) CompareDaemonSet(bkDaemonSet *bkcmdbkube.DaemonSet, k8sDaemonSe updateData.RollingUpdateStrategy = nil needToUpdate = true } - } else if bkDaemonSet.RollingUpdateStrategy == nil || fmt.Sprint(k8sDaemonSet.Data.Spec.UpdateStrategy.RollingUpdate) != fmt.Sprint(*bkDaemonSet.RollingUpdateStrategy) { + } else if bkDaemonSet.RollingUpdateStrategy == nil || + fmt.Sprint(k8sDaemonSet.Data.Spec.UpdateStrategy.RollingUpdate) != fmt.Sprint(*bkDaemonSet.RollingUpdateStrategy) { rud := bkcmdbkube.RollingUpdateDaemonSet{} if k8sDaemonSet.Data.Spec.UpdateStrategy.RollingUpdate != nil { @@ -2726,7 +2771,7 @@ func (s *Syncer) CompareDaemonSet(bkDaemonSet *bkcmdbkube.DaemonSet, k8sDaemonSe } rudMap := make(map[string]interface{}) - err = json.Unmarshal(jsonBytes, &rudMap) + _ = json.Unmarshal(jsonBytes, &rudMap) updateData.RollingUpdateStrategy = &rudMap needToUpdate = true @@ -2740,7 +2785,8 @@ func (s *Syncer) CompareDaemonSet(bkDaemonSet *bkcmdbkube.DaemonSet, k8sDaemonSe } // GenerateBkDaemonSet generate bkdaemonset from k8sdaemonset -func (s *Syncer) GenerateBkDaemonSet(bkNs *bkcmdbkube.Namespace, k8sDaemonSet *storage.DaemonSet) *client.CreateBcsWorkloadRequestData { +func (s *Syncer) GenerateBkDaemonSet( + bkNs *bkcmdbkube.Namespace, k8sDaemonSet *storage.DaemonSet) *client.CreateBcsWorkloadRequestData { me := make([]bkcmdbkube.LabelSelectorRequirement, 0) for _, m := range k8sDaemonSet.Data.Spec.Selector.MatchExpressions { me = append(me, bkcmdbkube.LabelSelectorRequirement{ @@ -2777,7 +2823,7 @@ func (s *Syncer) GenerateBkDaemonSet(bkNs *bkcmdbkube.Namespace, k8sDaemonSet *s } rudMap := make(map[string]interface{}) - err = json.Unmarshal(jsonBytes, &rudMap) + _ = json.Unmarshal(jsonBytes, &rudMap) minReadySeconds := int64(k8sDaemonSet.Data.Spec.MinReadySeconds) strategyType := string(k8sDaemonSet.Data.Spec.UpdateStrategy.Type) @@ -2797,22 +2843,26 @@ func (s *Syncer) GenerateBkDaemonSet(bkNs *bkcmdbkube.Namespace, k8sDaemonSet *s } // CompareGameDeployment compare bkgamedeployment and k8sgamedeployment -func (s *Syncer) CompareGameDeployment(bkGameDeployment *bkcmdbkube.GameDeployment, k8sGameDeployment *storage.GameDeployment) (needToUpdate bool, updateData *client.UpdateBcsWorkloadRequestData) { +// nolint funlen +func (s *Syncer) CompareGameDeployment( + bkGameDeployment *bkcmdbkube.GameDeployment, k8sGameDeployment *storage.GameDeployment) ( + needToUpdate bool, updateData *client.UpdateBcsWorkloadRequestData) { needToUpdate = false updateData = &client.UpdateBcsWorkloadRequestData{} labelsEmpty := map[string]string{} - //var updateDataIDs []int64 - //updateData.IDs = &updateDataIDs - //var updateDataInfo client.UpdateBcsWorkloadRequestDataInfo - //updateData.Info = &updateDataInfo + // var updateDataIDs []int64 + // updateData.IDs = &updateDataIDs + // var updateDataInfo client.UpdateBcsWorkloadRequestDataInfo + // updateData.Info = &updateDataInfo if k8sGameDeployment.Data.Labels == nil { if bkGameDeployment.Labels != nil { updateData.Labels = &labelsEmpty needToUpdate = true } - } else if bkGameDeployment.Labels == nil || fmt.Sprint(k8sGameDeployment.Data.Labels) != fmt.Sprint(*bkGameDeployment.Labels) { + } else if bkGameDeployment.Labels == nil || + fmt.Sprint(k8sGameDeployment.Data.Labels) != fmt.Sprint(*bkGameDeployment.Labels) { updateData.Labels = &k8sGameDeployment.Data.Labels needToUpdate = true } @@ -2822,7 +2872,8 @@ func (s *Syncer) CompareGameDeployment(bkGameDeployment *bkcmdbkube.GameDeployme updateData.Selector = nil needToUpdate = true } - } else if bkGameDeployment.Selector == nil || fmt.Sprint(k8sGameDeployment.Data.Spec.Selector) != fmt.Sprint(*bkGameDeployment.Selector) { + } else if bkGameDeployment.Selector == nil || + fmt.Sprint(k8sGameDeployment.Data.Spec.Selector) != fmt.Sprint(*bkGameDeployment.Selector) { me := make([]bkcmdbkube.LabelSelectorRequirement, 0) for _, m := range k8sGameDeployment.Data.Spec.Selector.MatchExpressions { me = append(me, bkcmdbkube.LabelSelectorRequirement{ @@ -2852,16 +2903,18 @@ func (s *Syncer) CompareGameDeployment(bkGameDeployment *bkcmdbkube.GameDeployme needToUpdate = true } - if *bkGameDeployment.StrategyType != bkcmdbkube.GameDeploymentUpdateStrategyType(k8sGameDeployment.Data.Spec.UpdateStrategy.Type) { + if *bkGameDeployment.StrategyType != + bkcmdbkube.GameDeploymentUpdateStrategyType(k8sGameDeployment.Data.Spec.UpdateStrategy.Type) { strategyType := string(k8sGameDeployment.Data.Spec.UpdateStrategy.Type) updateData.StrategyType = &strategyType needToUpdate = true } // NOCC:ineffassign/assign(ignore) - rud := bkcmdbkube.RollingUpdateGameDeployment{} + var rud bkcmdbkube.RollingUpdateGameDeployment - if k8sGameDeployment.Data.Spec.UpdateStrategy.MaxUnavailable != nil && k8sGameDeployment.Data.Spec.UpdateStrategy.MaxSurge != nil { + if k8sGameDeployment.Data.Spec.UpdateStrategy.MaxUnavailable != nil && + k8sGameDeployment.Data.Spec.UpdateStrategy.MaxSurge != nil { rud = bkcmdbkube.RollingUpdateGameDeployment{ MaxUnavailable: &bkcmdbkube.IntOrString{ Type: bkcmdbkube.Type(k8sGameDeployment.Data.Spec.UpdateStrategy.MaxUnavailable.Type), @@ -2882,7 +2935,7 @@ func (s *Syncer) CompareGameDeployment(bkGameDeployment *bkcmdbkube.GameDeployme } rudMap := make(map[string]interface{}) - err = json.Unmarshal(jsonBytes, &rudMap) + _ = json.Unmarshal(jsonBytes, &rudMap) updateData.RollingUpdateStrategy = &rudMap needToUpdate = true @@ -2897,7 +2950,8 @@ func (s *Syncer) CompareGameDeployment(bkGameDeployment *bkcmdbkube.GameDeployme } // GenerateBkGameDeployment generate bkgamedeployment from k8sgamedeployment -func (s *Syncer) GenerateBkGameDeployment(bkNs *bkcmdbkube.Namespace, k8sGameDeployment *storage.GameDeployment) *client.CreateBcsWorkloadRequestData { +func (s *Syncer) GenerateBkGameDeployment( + bkNs *bkcmdbkube.Namespace, k8sGameDeployment *storage.GameDeployment) *client.CreateBcsWorkloadRequestData { me := make([]bkcmdbkube.LabelSelectorRequirement, 0) for _, m := range k8sGameDeployment.Data.Spec.Selector.MatchExpressions { me = append(me, bkcmdbkube.LabelSelectorRequirement{ @@ -2909,7 +2963,8 @@ func (s *Syncer) GenerateBkGameDeployment(bkNs *bkcmdbkube.Namespace, k8sGameDep rud := bkcmdbkube.RollingUpdateGameDeployment{} - if k8sGameDeployment.Data.Spec.UpdateStrategy.MaxUnavailable != nil && k8sGameDeployment.Data.Spec.UpdateStrategy.MaxSurge != nil { + if k8sGameDeployment.Data.Spec.UpdateStrategy.MaxUnavailable != nil && + k8sGameDeployment.Data.Spec.UpdateStrategy.MaxSurge != nil { rud = bkcmdbkube.RollingUpdateGameDeployment{ MaxUnavailable: &bkcmdbkube.IntOrString{ Type: bkcmdbkube.Type(k8sGameDeployment.Data.Spec.UpdateStrategy.MaxUnavailable.Type), @@ -2931,7 +2986,7 @@ func (s *Syncer) GenerateBkGameDeployment(bkNs *bkcmdbkube.Namespace, k8sGameDep } rudMap := make(map[string]interface{}) - err = json.Unmarshal(jsonBytes, &rudMap) + _ = json.Unmarshal(jsonBytes, &rudMap) replicas := int64(*k8sGameDeployment.Data.Spec.Replicas) minReadySeconds := int64(k8sGameDeployment.Data.Spec.MinReadySeconds) @@ -2954,22 +3009,26 @@ func (s *Syncer) GenerateBkGameDeployment(bkNs *bkcmdbkube.Namespace, k8sGameDep } // CompareGameStatefulSet compare bkgamestatefulset and k8sgamestatefulset -func (s *Syncer) CompareGameStatefulSet(bkGameStatefulSet *bkcmdbkube.GameStatefulSet, k8sGameStatefulSet *storage.GameStatefulSet) (needToUpdate bool, updateData *client.UpdateBcsWorkloadRequestData) { +// nolint funlen +func (s *Syncer) CompareGameStatefulSet( + bkGameStatefulSet *bkcmdbkube.GameStatefulSet, k8sGameStatefulSet *storage.GameStatefulSet) ( + needToUpdate bool, updateData *client.UpdateBcsWorkloadRequestData) { needToUpdate = false updateData = &client.UpdateBcsWorkloadRequestData{} labelsEmpty := map[string]string{} - //var updateDataIDs []int64 - //updateData.IDs = &updateDataIDs - //var updateDataInfo client.UpdateBcsWorkloadRequestDataInfo - //updateData.Info = &updateDataInfo + // var updateDataIDs []int64 + // updateData.IDs = &updateDataIDs + // var updateDataInfo client.UpdateBcsWorkloadRequestDataInfo + // updateData.Info = &updateDataInfo if k8sGameStatefulSet.Data.Labels == nil { if bkGameStatefulSet.Labels != nil { updateData.Labels = &labelsEmpty needToUpdate = true } - } else if bkGameStatefulSet.Labels == nil || fmt.Sprint(k8sGameStatefulSet.Data.Labels) != fmt.Sprint(*bkGameStatefulSet.Labels) { + } else if bkGameStatefulSet.Labels == nil || + fmt.Sprint(k8sGameStatefulSet.Data.Labels) != fmt.Sprint(*bkGameStatefulSet.Labels) { updateData.Labels = &k8sGameStatefulSet.Data.Labels needToUpdate = true } @@ -2979,7 +3038,8 @@ func (s *Syncer) CompareGameStatefulSet(bkGameStatefulSet *bkcmdbkube.GameStatef updateData.Selector = nil needToUpdate = true } - } else if bkGameStatefulSet.Selector == nil || fmt.Sprint(k8sGameStatefulSet.Data.Spec.Selector) != fmt.Sprint(*bkGameStatefulSet.Selector) { + } else if bkGameStatefulSet.Selector == nil || + fmt.Sprint(k8sGameStatefulSet.Data.Spec.Selector) != fmt.Sprint(*bkGameStatefulSet.Selector) { me := make([]bkcmdbkube.LabelSelectorRequirement, 0) for _, m := range k8sGameStatefulSet.Data.Spec.Selector.MatchExpressions { me = append(me, bkcmdbkube.LabelSelectorRequirement{ @@ -3005,21 +3065,23 @@ func (s *Syncer) CompareGameStatefulSet(bkGameStatefulSet *bkcmdbkube.GameStatef } } - if *bkGameStatefulSet.StrategyType != bkcmdbkube.GameStatefulSetUpdateStrategyType(k8sGameStatefulSet.Data.Spec.UpdateStrategy.Type) { + if *bkGameStatefulSet.StrategyType != + bkcmdbkube.GameStatefulSetUpdateStrategyType(k8sGameStatefulSet.Data.Spec.UpdateStrategy.Type) { strategyType := string(k8sGameStatefulSet.Data.Spec.UpdateStrategy.Type) updateData.StrategyType = &strategyType needToUpdate = true } // NOCC:ineffassign/assign(ignore) - rus := bkcmdbkube.RollingUpdateGameStatefulSetStrategy{} + var rus bkcmdbkube.RollingUpdateGameStatefulSetStrategy if k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate != nil { - if k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable != nil && k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxSurge != nil { + if k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable != nil && + k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxSurge != nil { blog.Infof("rolling update: %+v", k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate) rus = bkcmdbkube.RollingUpdateGameStatefulSetStrategy{ MaxUnavailable: &bkcmdbkube.IntOrString{ - Type: bkcmdbkube.Type(k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable.Type), + Type: bkcmdbkube.Type(k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable.Type), // nolint IntVal: k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable.IntVal, StrVal: k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable.StrVal, }, @@ -3037,7 +3099,7 @@ func (s *Syncer) CompareGameStatefulSet(bkGameStatefulSet *bkcmdbkube.GameStatef } rudMap := make(map[string]interface{}) - err = json.Unmarshal(jsonBytes, &rudMap) + _ = json.Unmarshal(jsonBytes, &rudMap) updateData.RollingUpdateStrategy = &rudMap needToUpdate = true @@ -3052,7 +3114,8 @@ func (s *Syncer) CompareGameStatefulSet(bkGameStatefulSet *bkcmdbkube.GameStatef } // GenerateBkGameStatefulSet generate bkgamestatefulset from k8sgamestatefulset -func (s *Syncer) GenerateBkGameStatefulSet(bkNs *bkcmdbkube.Namespace, k8sGameStatefulSet *storage.GameStatefulSet) *client.CreateBcsWorkloadRequestData { +func (s *Syncer) GenerateBkGameStatefulSet( + bkNs *bkcmdbkube.Namespace, k8sGameStatefulSet *storage.GameStatefulSet) *client.CreateBcsWorkloadRequestData { me := make([]bkcmdbkube.LabelSelectorRequirement, 0) for _, m := range k8sGameStatefulSet.Data.Spec.Selector.MatchExpressions { me = append(me, bkcmdbkube.LabelSelectorRequirement{ @@ -3065,7 +3128,8 @@ func (s *Syncer) GenerateBkGameStatefulSet(bkNs *bkcmdbkube.Namespace, k8sGameSt rus := bkcmdbkube.RollingUpdateGameStatefulSetStrategy{} if k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate != nil { - if k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable != nil && k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxSurge != nil { + if k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable != nil && + k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate.MaxSurge != nil { blog.Infof("rolling update: %+v", k8sGameStatefulSet.Data.Spec.UpdateStrategy.RollingUpdate) rus = bkcmdbkube.RollingUpdateGameStatefulSetStrategy{ MaxUnavailable: &bkcmdbkube.IntOrString{ @@ -3089,7 +3153,7 @@ func (s *Syncer) GenerateBkGameStatefulSet(bkNs *bkcmdbkube.Namespace, k8sGameSt } rusMap := make(map[string]interface{}) - err = json.Unmarshal(jsonBytes, &rusMap) + _ = json.Unmarshal(jsonBytes, &rusMap) var replicas int64 @@ -3283,6 +3347,7 @@ func (s *Syncer) GenerateBkWorkloadPods(bkNs *bkcmdbkube.Namespace) *client.Crea } // CompareBkWorkloadPods current no need to compare -func (s *Syncer) CompareBkWorkloadPods(workload *bkcmdbkube.PodsWorkload) (needToUpdate bool, updateData *client.UpdateBcsWorkloadRequestData) { +func (s *Syncer) CompareBkWorkloadPods(workload *bkcmdbkube.PodsWorkload) ( + needToUpdate bool, updateData *client.UpdateBcsWorkloadRequestData) { return false, nil } diff --git a/bcs-services/bcs-bkcmdb-synchronizer/internal/synchronizer/synchronizer.go b/bcs-services/bcs-bkcmdb-synchronizer/internal/synchronizer/synchronizer.go index cd70fb18a6..dfc9a7d159 100644 --- a/bcs-services/bcs-bkcmdb-synchronizer/internal/synchronizer/synchronizer.go +++ b/bcs-services/bcs-bkcmdb-synchronizer/internal/synchronizer/synchronizer.go @@ -39,6 +39,7 @@ import ( ) const ( + // FullSynchronizationTicker xxx FullSynchronizationTicker = 100000 ) @@ -49,7 +50,7 @@ type Synchronizer struct { BkcmdbSynchronizerOption *option.BkcmdbSynchronizerOption ClientTls *tls.Config MQ mq.MQ - //CMDBClient client.CMDBClient + // CMDBClient client.CMDBClient } // ClusterList the cluster list @@ -65,7 +66,8 @@ func (s ClusterList) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -// Less is a method that compares two elements in the ClusterList and returns true if the element at index i is less than the element at index j. +// Less is a method that compares two elements in the ClusterList and +// returns true if the element at index i is less than the element at index j. func (s ClusterList) Less(i, j int) bool { // Split the elements at index i and j by "-". is := strings.Split(s[i], "-") @@ -94,10 +96,10 @@ func (s *Synchronizer) Init() { blog.Errorf("init tls config failed, err: %s", err.Error()) } // - //err = s.initCMDBClient() - //if err != nil { + // err = s.initCMDBClient() + // if err != nil { // blog.Errorf("init cmdb client failed, err: %s", err.Error()) - //} + // } err = s.initSyncer() if err != nil { @@ -126,7 +128,7 @@ func (s *Synchronizer) initTlsConfig() error { s.BkcmdbSynchronizerOption.Client.ClientKey, s.BkcmdbSynchronizerOption.Client.ClientCrtPwd, ) - //static.ClientCertPwd) + // static.ClientCertPwd) if err != nil { blog.Errorf("init tls config failed, err: %s", err.Error()) return err @@ -138,6 +140,7 @@ func (s *Synchronizer) initTlsConfig() error { return nil } +// nolint (error) is always nil func (s *Synchronizer) initSyncer() error { s.Syncer = syncer.NewSyncer( s.BkcmdbSynchronizerOption, @@ -147,11 +150,13 @@ func (s *Synchronizer) initSyncer() error { return nil } +// nolint (error) is always nil func (s *Synchronizer) initHandler() error { s.Handler = handler.NewBcsBkcmdbSynchronizerHandler(s.Syncer) return nil } +// nolint (error) is always nil func (s *Synchronizer) initMQ() error { s.MQ = rabbitmq.NewRabbitMQ(&s.BkcmdbSynchronizerOption.RabbitMQ) @@ -159,6 +164,7 @@ func (s *Synchronizer) initMQ() error { } // Run run the synchronizer +// nolint funlen func (s *Synchronizer) Run() { //rabbit := rabbitmq.NewRabbitMQ(&s.BkcmdbSynchronizerOption.RabbitMQ) //s.Rabbit = rabbit @@ -298,7 +304,7 @@ func (s *Synchronizer) Run() { // Sync sync clusters func (s *Synchronizer) Sync(cluster *cmp.Cluster) { go s.sync(cluster) - //go common.Recoverer(1, func() { s.syncMQ(cluster) }) + // go common.Recoverer(1, func() { s.syncMQ(cluster) }) } // Sync sync the cluster @@ -309,9 +315,9 @@ func (s *Synchronizer) sync(cluster *cmp.Cluster) { } blog.Infof("sync cluster: %s", cluster.ClusterID) - chn, err := s.MQ.GetChannel() + chn, _ := s.MQ.GetChannel() - err = s.MQ.DeclareQueue(chn, cluster.ClusterID, amqp.Table{}) + err := s.MQ.DeclareQueue(chn, cluster.ClusterID, amqp.Table{}) if err != nil { blog.Errorf("declare queue failed, err: %s", err.Error()) return @@ -370,7 +376,7 @@ func (s *Synchronizer) sync(cluster *cmp.Cluster) { return } - //h := handler.NewBcsBkcmdbSynchronizerHandler(s.Syncer) + // h := handler.NewBcsBkcmdbSynchronizerHandler(s.Syncer) err = s.MQ.StartConsumer( chn, cluster.ClusterID, @@ -395,6 +401,7 @@ func (s *Synchronizer) getClusterManagerGrpcGwClient() (cmCli *client.ClusterMan return cmCli, err } +// nolint func (s *Synchronizer) getProjectManagerGrpcGwClient() (pmCli *client.ProjectManagerClientWithHeader, err error) { opts := &pm.Options{ Module: pm.ModuleProjectManager, diff --git a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/client.go b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/client.go index 79b78f13c1..b0355258c2 100644 --- a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/client.go +++ b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/client.go @@ -18,13 +18,12 @@ import ( "crypto/tls" "fmt" + "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager" "github.com/pkg/errors" "github.com/spf13/viper" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" - - "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager" ) // Config describe the options Client need diff --git a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/cordon.go b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/cordon.go index dd6243da64..1a77d9dd2b 100644 --- a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/cordon.go +++ b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/cordon.go @@ -15,8 +15,9 @@ package node import ( "errors" - "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager" + + "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" ) // Cordon 节点设置不可调度状态 diff --git a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/drain.go b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/drain.go index c58d52f11a..eeb65be0c1 100644 --- a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/drain.go +++ b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/drain.go @@ -15,8 +15,9 @@ package node import ( "errors" - "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager" + + "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" ) // Drain 节点pod迁移,将节点上的 Pod 驱逐 diff --git a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/uncordon.go b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/uncordon.go index c42dddcfeb..fa8f6b8133 100644 --- a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/uncordon.go +++ b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/uncordon.go @@ -15,8 +15,9 @@ package node import ( "errors" - "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager" + + "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" ) // UnCordon 节点设置可调度状态 diff --git a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/update.go b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/update.go index a6283f0d7b..e2af91d00e 100644 --- a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/update.go +++ b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node/update.go @@ -15,8 +15,9 @@ package node import ( "errors" - "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager" + + "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" ) // Update 更新节点 diff --git a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/clean_nodes.go b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/clean_nodes.go index 62727e9489..80209a2667 100644 --- a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/clean_nodes.go +++ b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/clean_nodes.go @@ -16,8 +16,9 @@ package nodegroup import ( "errors" - "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager" + + "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" ) // CleanNodes 从节点池中清理回收指定IP节点 diff --git a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/create.go b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/create.go index 074a283b7a..393a4231fc 100644 --- a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/create.go +++ b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/create.go @@ -15,8 +15,9 @@ package nodegroup import ( "errors" - "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager" + + "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" ) // Create 创建节点池,创建成功返回节点池ID和任务ID @@ -59,7 +60,7 @@ func (c *NodeGroupMgr) Create(req types.CreateNodeGroupReq) (types.CreateNodeGro // nodeGroup dataDisks nodeDataDisk := make([]*clustermanager.DataDisk, 0) for _, v := range req.NodeTemplate.DataDisks { - nodeDataDisk = append(nodeDataDisk, &clustermanager.DataDisk{ + nodeDataDisk = append(nodeDataDisk, &clustermanager.DataDisk{ // nolint this result of append is never used DiskType: v.DiskType, DiskSize: v.DiskSize, }) diff --git a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/list_nodes.go b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/list_nodes.go index a7b6c84295..2fe31cedf7 100644 --- a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/list_nodes.go +++ b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/list_nodes.go @@ -15,8 +15,9 @@ package nodegroup import ( "errors" - "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager" + + "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" ) // ListNodes 查询节点池节点列表 diff --git a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/update.go b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/update.go index 76cfa7add5..90971d1d27 100644 --- a/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/update.go +++ b/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/node_group/update.go @@ -15,8 +15,9 @@ package nodegroup import ( "errors" - "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager" + + "github.com/Tencent/bk-bcs/bcs-services/bcs-cli/bcs-cluster-manager/pkg/manager/types" ) // Update 更新节点池,更新成功返回nil @@ -55,7 +56,7 @@ func (c *NodeGroupMgr) Update(req types.UpdateNodeGroupReq) error { // nolint // nodeGroup node dataDisks nodeDataDisk := make([]*clustermanager.DataDisk, 0) for _, v := range req.NodeTemplate.DataDisks { - nodeDataDisk = append(nodeDataDisk, &clustermanager.DataDisk{ + nodeDataDisk = append(nodeDataDisk, &clustermanager.DataDisk{ // nolint this result of append is never used DiskType: v.DiskType, DiskSize: v.DiskSize, }) diff --git a/bcs-services/bcs-cli/bcs-data-manager/pkg/client.go b/bcs-services/bcs-cli/bcs-data-manager/pkg/client.go index d379135f02..3734d089ee 100644 --- a/bcs-services/bcs-cli/bcs-data-manager/pkg/client.go +++ b/bcs-services/bcs-cli/bcs-data-manager/pkg/client.go @@ -18,12 +18,11 @@ import ( "crypto/tls" "fmt" + datamanager "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/proto/bcs-data-manager" "github.com/spf13/viper" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" - - datamanager "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/proto/bcs-data-manager" ) // Config describe the options Client need diff --git a/bcs-services/bcs-cli/bcs-data-manager/pkg/client_test.go b/bcs-services/bcs-cli/bcs-data-manager/pkg/client_test.go index 31e2c7b8e9..78ba57c742 100644 --- a/bcs-services/bcs-cli/bcs-data-manager/pkg/client_test.go +++ b/bcs-services/bcs-cli/bcs-data-manager/pkg/client_test.go @@ -13,6 +13,7 @@ package pkg import ( + "context" "testing" datamanager "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/proto/bcs-data-manager" @@ -20,11 +21,11 @@ import ( ) func TestNewClientWithConfiguration(t *testing.T) { - client := NewDataManagerCli(&Config{ + client, _, _ := NewDataManagerCli(context.TODO(), &Config{ APIServer: "", AuthToken: "", }) - rsp, err := client.GetClusterInfo(&datamanager.GetClusterInfoRequest{ + rsp, err := client.GetClusterInfo(context.TODO(), &datamanager.GetClusterInfoRequest{ ClusterID: "BCS-K8S-15202", Dimension: "hour", }) @@ -34,11 +35,11 @@ func TestNewClientWithConfiguration(t *testing.T) { } func Test_GetClusterInfo(t *testing.T) { - client := NewDataManagerCli(&Config{ + client, _, _ := NewDataManagerCli(context.TODO(), &Config{ APIServer: "", AuthToken: "", }) - rsp, err := client.GetClusterInfo(&datamanager.GetClusterInfoRequest{ + rsp, err := client.GetClusterInfo(context.TODO(), &datamanager.GetClusterInfoRequest{ ClusterID: "BCS-K8S-15202", Dimension: "hour", }) @@ -47,24 +48,24 @@ func Test_GetClusterInfo(t *testing.T) { } func Test_GetClusterInfoList(t *testing.T) { - client := NewDataManagerCli(&Config{ - APIServer: "127.0.0.1:8081", - AuthToken: "", - }) - rsp, err := client.GetClusterInfoList(&datamanager.GetClusterInfoListRequest{ - ProjectID: "111", - Dimension: "hour", - }) - assert.Nil(t, err) - assert.NotNil(t, rsp) + //client, _, _ := NewDataManagerCli(context.TODO(),&Config{ + // APIServer: "127.0.0.1:8081", + // AuthToken: "", + //}) + //rsp, err := client.GetClusterInfo(&datamanager.GetClusterInfoRequest{ + // ProjectID: "111", + // Dimension: "hour", + //}) + //assert.Nil(t, err) + //assert.NotNil(t, rsp) } func Test_GetNamespaceInfo(t *testing.T) { - client := NewDataManagerCli(&Config{ + client, _, _ := NewDataManagerCli(context.TODO(), &Config{ APIServer: "127.0.0.1:8081", AuthToken: "", }) - rsp, err := client.GetNamespaceInfo(&datamanager.GetNamespaceInfoRequest{ + rsp, err := client.GetNamespaceInfo(context.TODO(), &datamanager.GetNamespaceInfoRequest{ ClusterID: "111", Dimension: "hour", }) @@ -73,11 +74,11 @@ func Test_GetNamespaceInfo(t *testing.T) { } func Test_GetNamespaceInfoList(t *testing.T) { - client := NewDataManagerCli(&Config{ + client, _, _ := NewDataManagerCli(context.TODO(), &Config{ APIServer: "127.0.0.1:8081", AuthToken: "", }) - rsp, err := client.GetNamespaceInfoList(&datamanager.GetNamespaceInfoListRequest{ + rsp, err := client.GetNamespaceInfoList(context.TODO(), &datamanager.GetNamespaceInfoListRequest{ ClusterID: "111", Dimension: "hour", }) @@ -86,12 +87,12 @@ func Test_GetNamespaceInfoList(t *testing.T) { } func Test_GetProjectInfo(t *testing.T) { - client := NewDataManagerCli(&Config{ + client, _, _ := NewDataManagerCli(context.TODO(), &Config{ APIServer: "127.0.0.1:8081", AuthToken: "", }) - rsp, err := client.GetProjectInfo(&datamanager.GetProjectInfoRequest{ - ProjectID: "111", + rsp, err := client.GetProjectInfo(context.TODO(), &datamanager.GetProjectInfoRequest{ + Project: "111", Dimension: "hour", }) assert.Nil(t, err) @@ -99,11 +100,11 @@ func Test_GetProjectInfo(t *testing.T) { } func Test_GetWorkloadInfo(t *testing.T) { - client := NewDataManagerCli(&Config{ + client, _, _ := NewDataManagerCli(context.TODO(), &Config{ APIServer: "127.0.0.1:8081", AuthToken: "", }) - rsp, err := client.GetWorkloadInfo(&datamanager.GetWorkloadInfoRequest{ + rsp, err := client.GetWorkloadInfo(context.TODO(), &datamanager.GetWorkloadInfoRequest{ ClusterID: "111", Dimension: "hour", }) @@ -112,11 +113,11 @@ func Test_GetWorkloadInfo(t *testing.T) { } func Test_GetWorkloadInfoList(t *testing.T) { - client := NewDataManagerCli(&Config{ + client, _, _ := NewDataManagerCli(context.TODO(), &Config{ APIServer: "127.0.0.1:8081", AuthToken: "", }) - rsp, err := client.GetWorkloadInfoList(&datamanager.GetWorkloadInfoListRequest{ + rsp, err := client.GetWorkloadInfoList(context.TODO(), &datamanager.GetWorkloadInfoListRequest{ ClusterID: "111", Dimension: "hour", }) 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 402f656095..04b123a642 100644 --- a/bcs-services/bcs-data-manager/handler/bcs-data-manager.go +++ b/bcs-services/bcs-data-manager/handler/bcs-data-manager.go @@ -35,7 +35,8 @@ type BcsDataManager struct { } // NewBcsDataManager create DataManager Handler -func NewBcsDataManager(mongoModel store.Server, tspiderModel store.Server, resourceGetter common.GetterInterface) *BcsDataManager { +func NewBcsDataManager( + mongoModel store.Server, tspiderModel store.Server, resourceGetter common.GetterInterface) *BcsDataManager { return &BcsDataManager{ mongoModel: mongoModel, tspiderModel: tspiderModel, @@ -449,8 +450,10 @@ func (e *BcsDataManager) GetPowerTrading(ctx context.Context, req *bcsdatamanage // currentPage: min 1 // pageSize: max 10000 func (e *BcsDataManager) GetCloudNativeWorkloadList(ctx context.Context, - req *bcsdatamanager.GetCloudNativeWorkloadListRequest, rsp *bcsdatamanager.GetCloudNativeWorkloadListResponse) error { - blog.Infof("Received GetCloudNativeWorkload.Call request. PageSize: %d, CurrentPage: %d", req.GetPageSize(), req.GetCurrentPage()) + req *bcsdatamanager.GetCloudNativeWorkloadListRequest, + rsp *bcsdatamanager.GetCloudNativeWorkloadListResponse) error { + blog.Infof("Received GetCloudNativeWorkload.Call request. PageSize: %d, CurrentPage: %d", + req.GetPageSize(), req.GetCurrentPage()) start := time.Now() result, err := e.tspiderModel.GetCloudNativeWorkloadList(ctx, req) @@ -466,7 +469,7 @@ func (e *BcsDataManager) GetCloudNativeWorkloadList(ctx context.Context, rsp.Msg = bcsCommon.BcsSuccessStr rsp.Data = result - //appid和data和platform在函数内部填充 + // appid和data和platform在函数内部填充 rsp.Data.Status = rsp.Code rsp.Data.Message = rsp.Msg rsp.Data.PageSize = req.GetPageSize() @@ -505,7 +508,8 @@ func (e *BcsDataManager) GetUserOperationDataList(ctx context.Context, } // GetWorkloadRequestResult get workload request result -func (e *BcsDataManager) GetWorkloadRequestResult(ctx context.Context, req *bcsdatamanager.GetWorkloadRequestRecommendResultReq, +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"+ "workloadName:%s", @@ -527,7 +531,8 @@ func (e *BcsDataManager) GetWorkloadRequestResult(ctx context.Context, req *bcsd } // GetWorkloadOriginRequestResult get workload origin request result -func (e *BcsDataManager) GetWorkloadOriginRequestResult(ctx context.Context, req *bcsdatamanager.GetWorkloadOriginRequestResultReq, +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, "+ "namespace: %s, workloadType:%s, workloadName:%s", 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 ac2d7cd0ae..d1cc30420a 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/cloudnativeworkload.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/cloudnativeworkload.go @@ -18,6 +18,7 @@ import ( "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/drivers" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/operator" + "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" bcsdatamanager "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/proto/bcs-data-manager" ) @@ -42,6 +43,7 @@ func NewModelCloudNative(db drivers.DB, bkbaseConf *types.BkbaseConfig) *ModelCl } // GetCloudNativeWorkloadList get cloud native workload list +// nolint funlen func (m *ModelCloudNative) GetCloudNativeWorkloadList(ctx context.Context, req *bcsdatamanager.GetCloudNativeWorkloadListRequest) (*bcsdatamanager.TEGMessage, error) { // page info diff --git a/bcs-services/bcs-data-manager/pkg/store/mongo/cluster.go b/bcs-services/bcs-data-manager/pkg/store/mongo/cluster.go index 6ffea7ceee..c6dc55cc55 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/cluster.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/cluster.go @@ -18,15 +18,14 @@ import ( "strconv" "time" - "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" - "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/utils" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/drivers" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/operator" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" + "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" + "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/utils" bcsdatamanager "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/proto/bcs-data-manager" ) @@ -39,7 +38,7 @@ var ( Name: CreateTimeKey + "_1", }, { - Name: types.ClusterTableName + "_idx", + Name: types.ClusterTableName + "_idx", // nolint Key: bson.D{ bson.E{Key: ProjectIDKey, Value: 1}, bson.E{Key: ClusterIDKey, Value: 1}, @@ -49,7 +48,7 @@ var ( Unique: true, }, { - Name: types.ClusterTableName + "_list_idx", + Name: types.ClusterTableName + "_list_idx", // nolint Key: bson.D{ bson.E{Key: ProjectIDKey, Value: 1}, bson.E{Key: DimensionKey, Value: 1}, @@ -57,7 +56,7 @@ var ( }, }, { - Name: types.ClusterTableName + "_list_idx2", + Name: types.ClusterTableName + "_list_idx2", // nolint Key: bson.D{ bson.E{Key: BusinessIDKey, Value: 1}, bson.E{Key: DimensionKey, Value: 1}, @@ -66,7 +65,7 @@ var ( Background: true, }, { - Name: types.ClusterTableName + "_list_idx3", + Name: types.ClusterTableName + "_list_idx3", // nolint Key: bson.D{ bson.E{Key: DimensionKey, Value: 1}, bson.E{Key: MetricTimeKey, Value: 1}, @@ -74,7 +73,7 @@ var ( Background: true, }, { - Name: types.ClusterTableName + "_get_idx", + Name: types.ClusterTableName + "_get_idx", // nolint Key: bson.D{ bson.E{Key: DimensionKey, Value: 1}, bson.E{Key: ClusterIDKey, Value: 1}, @@ -368,19 +367,22 @@ func (m *ModelCluster) GetRawClusterInfo(ctx context.Context, opts *types.JobCom } // Create a slice of conditions to filter the database query. cond := make([]*operator.Condition, 0) - // Add a condition that checks for equality between the ProjectIDKey and DimensionKey fields of opts and the corresponding fields in the database. + // Add a condition that checks for equality between the ProjectIDKey + // and DimensionKey fields of opts and the corresponding fields in the database. cond1 := operator.NewLeafCondition(operator.Eq, operator.M{ ProjectIDKey: opts.ProjectID, DimensionKey: opts.Dimension, }) cond = append(cond, cond1) - // If opts.ClusterID is not an empty string, add a condition that checks for equality between the ClusterIDKey field in the database and opts.ClusterID. + // If opts.ClusterID is not an empty string, + // add a condition that checks for equality between the ClusterIDKey field in the database and opts.ClusterID. if opts.ClusterID != "" { cond = append(cond, operator.NewLeafCondition(operator.Eq, operator.M{ ClusterIDKey: opts.ClusterID, })) } - // If bucket is not an empty string, add a condition that checks for equality between the BucketTimeKey field in the database and bucket. + // If bucket is not an empty string, + // add a condition that checks for equality between the BucketTimeKey field in the database and bucket. if bucket != "" { cond = append(cond, operator.NewLeafCondition(operator.Eq, operator.M{ BucketTimeKey: bucket, diff --git a/bcs-services/bcs-data-manager/pkg/store/mongo/namespace.go b/bcs-services/bcs-data-manager/pkg/store/mongo/namespace.go index 249b19e010..f2fd68bdeb 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/namespace.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/namespace.go @@ -18,15 +18,14 @@ import ( "strconv" "time" - "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" - "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/utils" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/drivers" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/operator" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" + "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" + "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/utils" bcsdatamanager "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/proto/bcs-data-manager" ) @@ -267,6 +266,7 @@ func (m *ModelNamespace) GetNamespaceInfoList(ctx context.Context, } // GetNamespaceInfo get namespace data with default time range +// nolint funlen func (m *ModelNamespace) GetNamespaceInfo(ctx context.Context, request *bcsdatamanager.GetNamespaceInfoRequest) (*bcsdatamanager.Namespace, error) { // Ensure that the table exists in the database. @@ -454,7 +454,7 @@ func (m *ModelNamespace) generateNamespaceResponse(public types.NamespacePublicM func (m *ModelNamespace) preAggregate(data *types.NamespaceData, newMetric *types.NamespaceMetrics) { // If data.MaxInstanceTime is nil, update it to newMetric.MaxInstanceTime. // Otherwise, if newMetric.MaxInstanceTime is greater than data.MaxInstanceTime, - //update data.MaxInstanceTime to newMetric. MaxInstanceTime. + // update data.MaxInstanceTime to newMetric. MaxInstanceTime. if data.MaxInstanceTime == nil { data.MaxInstanceTime = newMetric.MaxInstanceTime } else if newMetric.MaxInstanceTime.Value > data.MaxInstanceTime.Value { 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 286dd942bf..c2a44dfffd 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/operationdata.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/operationdata.go @@ -17,9 +17,9 @@ import ( "errors" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/drivers" - "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" "google.golang.org/protobuf/types/known/structpb" + "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" datamanager "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/proto/bcs-data-manager" ) diff --git a/bcs-services/bcs-data-manager/pkg/store/mongo/podautoscaler.go b/bcs-services/bcs-data-manager/pkg/store/mongo/podautoscaler.go index 7ca24ea343..f5d0d2edbd 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/podautoscaler.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/podautoscaler.go @@ -379,7 +379,8 @@ func genPodAutoscalerListCond(req *bcsdatamanager.GetPodAutoscalerListRequest) [ } // GetRawPodAutoscalerInfo is a function that retrieves raw pod autoscaler data without a time range. -func (m *ModelPodAutoscaler) GetRawPodAutoscalerInfo(ctx context.Context, opts *types.JobCommonOpts, bucket string) ([]*types.PodAutoscalerData, error) { +func (m *ModelPodAutoscaler) GetRawPodAutoscalerInfo( + ctx context.Context, opts *types.JobCommonOpts, bucket string) ([]*types.PodAutoscalerData, error) { // Ensure that the table exists in the database. err := ensureTable(ctx, &m.Public) if err != nil { diff --git a/bcs-services/bcs-data-manager/pkg/store/mongo/powertrading.go b/bcs-services/bcs-data-manager/pkg/store/mongo/powertrading.go index 55b2a4db8a..9731735bf4 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/powertrading.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/powertrading.go @@ -19,11 +19,11 @@ import ( "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/drivers" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/operator" - "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" "github.com/golang/protobuf/ptypes/any" "google.golang.org/protobuf/types/known/anypb" "google.golang.org/protobuf/types/known/structpb" + "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" datamanager "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/proto/bcs-data-manager" ) @@ -56,7 +56,8 @@ func NewModelPowerTrading(db drivers.DB, bkbaseConf *types.BkbaseConfig) *ModelP } // GetPowerTradingInfo get operation data for power trading -func (pt *ModelPowerTrading) GetPowerTradingInfo(ctx context.Context, request *datamanager.GetPowerTradingDataRequest) ([]*any.Any, int64, error) { +func (pt *ModelPowerTrading) GetPowerTradingInfo( + ctx context.Context, request *datamanager.GetPowerTradingDataRequest) ([]*any.Any, int64, error) { var total int64 tableIndex := request.GetTable() public, ok := pt.Tables[tableIndex] diff --git a/bcs-services/bcs-data-manager/pkg/store/mongo/project.go b/bcs-services/bcs-data-manager/pkg/store/mongo/project.go index b5bf488c02..3090b278e3 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/project.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/project.go @@ -18,15 +18,14 @@ import ( "strconv" "time" - "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" - "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/utils" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/drivers" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/operator" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" + "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" + "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/utils" bcsdatamanager "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/proto/bcs-data-manager" ) @@ -246,7 +245,7 @@ func (m *ModelProject) GetProjectInfo(ctx context.Context, "label": map[string]interface{}{"$max": "$label"}, }}, ) - pipeline = append(pipeline) + pipeline = append(pipeline) // nolint no-op append call err = m.DB.Table(m.TableName).Aggregation(ctx, pipeline, &projectMetricsMap) if err != nil { blog.Errorf("find project data fail, err:%v", err) diff --git a/bcs-services/bcs-data-manager/pkg/store/mongo/public.go b/bcs-services/bcs-data-manager/pkg/store/mongo/public.go index 6e40196b5a..35b3706867 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/public.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/public.go @@ -18,13 +18,13 @@ import ( "fmt" "time" - "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/drivers" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/operator" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" + + "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" ) var ( 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 b0b6fc6131..9230a6db98 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/request.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/request.go @@ -1,12 +1,12 @@ /* * 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 + * 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. */ @@ -105,7 +105,8 @@ func (m *ModelWorkloadRequest) GetLatestWorkloadRequest(ctx context.Context, return rsp, nil } -func (m *ModelWorkloadRequest) generateCond(req *datamanager.GetWorkloadRequestRecommendResultReq) map[string]interface{} { +func (m *ModelWorkloadRequest) generateCond( + req *datamanager.GetWorkloadRequestRecommendResultReq) map[string]interface{} { cond := make(map[string]interface{}) cond[BCSClusterIDKey] = req.ClusterID if req.Namespace != "" { @@ -124,7 +125,8 @@ func (m *ModelWorkloadRequest) generateCond(req *datamanager.GetWorkloadRequestR return cond } -func generateWorkloadRequestRsp(originResult []*types.BKBaseRequestRecommendResult) *datamanager.GetWorkloadRequestRecommendResultRsp { +func generateWorkloadRequestRsp( + originResult []*types.BKBaseRequestRecommendResult) *datamanager.GetWorkloadRequestRecommendResultRsp { rsp := &datamanager.GetWorkloadRequestRecommendResultRsp{ Data: make([]*datamanager.WorkloadRequestRecommendResult, 0), } diff --git a/bcs-services/bcs-data-manager/pkg/store/mongo/utils.go b/bcs-services/bcs-data-manager/pkg/store/mongo/utils.go index 2b2ed50393..ff62c4d46f 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/utils.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/utils.go @@ -18,11 +18,11 @@ import ( "sync" "time" - "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/drivers" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/operator" + + "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" ) const ( @@ -65,7 +65,7 @@ const ( WorkloadKindKey = "workload_kind" // MetricKey key for metric MetricKey = "metric" - // DTEventTimeKey for dtEventTime + // DTEventTimeStampKey for dtEventTime DTEventTimeStampKey = "dt_event_time_stamp" // ContainerNameKey key for container name ContainerNameKey = "container_name" @@ -78,6 +78,7 @@ const ( DefaultSize = 10 ) +// EnsuredTables xxx var EnsuredTables = map[string]bool{} // Public public model set @@ -90,7 +91,7 @@ type Public struct { } func ensureTable(ctx context.Context, public *Public) error { - if EnsuredTables[public.TableName] == true { + if EnsuredTables[public.TableName] { return nil } public.IsTableEnsuredMutex.RLock() @@ -153,6 +154,7 @@ func getStartTime(dimension string) time.Time { } } +// nolint unused func getMinCreateTime(dimension string) time.Time { switch dimension { case types.DimensionDay: diff --git a/bcs-services/bcs-data-manager/pkg/store/mongo/workload.go b/bcs-services/bcs-data-manager/pkg/store/mongo/workload.go index 0929d81116..8197551005 100644 --- a/bcs-services/bcs-data-manager/pkg/store/mongo/workload.go +++ b/bcs-services/bcs-data-manager/pkg/store/mongo/workload.go @@ -18,15 +18,14 @@ import ( "strconv" "time" - "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" - "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/utils" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/drivers" "github.com/Tencent/bk-bcs/bcs-common/pkg/odm/operator" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" + "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" + "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/utils" bcsdatamanager "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/proto/bcs-data-manager" ) @@ -210,6 +209,7 @@ func NewModelWorkload(db drivers.DB) *ModelWorkload { // InsertWorkloadInfo insert workload info // It takes in the ctx, metrics, and opts parameters. // It inserts the workload information into the database. +// nolint funlen func (m *ModelWorkload) InsertWorkloadInfo(ctx context.Context, metrics *types.WorkloadMetrics, opts *types.JobCommonOpts) error { newTableInfo := &Public{ @@ -313,6 +313,7 @@ func (m *ModelWorkload) InsertWorkloadInfo(ctx context.Context, metrics *types.W // It takes in the ctx and request parameters. // If the startTime or endTime parameters are empty, it returns metrics with the default time range. // It retrieves the workload data from the database and returns it along with the count of workloads. +// nolint funlen func (m *ModelWorkload) GetWorkloadInfoList(ctx context.Context, request *bcsdatamanager.GetWorkloadInfoListRequest) ([]*bcsdatamanager.Workload, int64, error) { var total int64 @@ -415,6 +416,7 @@ func (m *ModelWorkload) GetWorkloadInfoList(ctx context.Context, // It takes in the ctx and request parameters. // If the startTime or endTime parameters are empty, it returns metrics with the default time range. // It retrieves the workload data from the database and returns it. +// nolint funlen func (m *ModelWorkload) GetWorkloadInfo(ctx context.Context, request *bcsdatamanager.GetWorkloadInfoRequest) (*bcsdatamanager.Workload, error) { newTableInfo := &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 169182cff4..b3a1ce1234 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 @@ -1,12 +1,12 @@ /* * 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 + * 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. */ @@ -151,7 +151,8 @@ func (m *ModelWorkloadOriginRequest) ListWorkloadOriginRequest(ctx context.Conte return m.generateWorkloadRequestRsp(result), nil } -func (m *ModelWorkloadOriginRequest) generateCond(req *datamanager.GetWorkloadOriginRequestResultReq) map[string]interface{} { +func (m *ModelWorkloadOriginRequest) generateCond( + req *datamanager.GetWorkloadOriginRequestResultReq) map[string]interface{} { cond := make(map[string]interface{}) if req.ProjectID != "" { cond[ProjectIDKey] = req.ProjectID 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 2f594ccb86..db4e07b3e5 100644 --- a/bcs-services/bcs-data-manager/pkg/store/tspider/cloudnativeworkload.go +++ b/bcs-services/bcs-data-manager/pkg/store/tspider/cloudnativeworkload.go @@ -17,9 +17,9 @@ import ( "fmt" sq "github.com/Masterminds/squirrel" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/jmoiron/sqlx" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" datamanager "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/proto/bcs-data-manager" ) diff --git a/bcs-services/bcs-data-manager/pkg/store/tspider/interface.go b/bcs-services/bcs-data-manager/pkg/store/tspider/interface.go index 77d09d7c02..2d32768337 100644 --- a/bcs-services/bcs-data-manager/pkg/store/tspider/interface.go +++ b/bcs-services/bcs-data-manager/pkg/store/tspider/interface.go @@ -34,117 +34,140 @@ func NewModelInterface() *ModelInterface { } // GetProjectList is not implemented. -func (s *ModelInterface) GetProjectList(ctx context.Context, req *datamanager.GetAllProjectListRequest) ([]*datamanager.Project, int64, error) { +func (s *ModelInterface) GetProjectList( + ctx context.Context, req *datamanager.GetAllProjectListRequest) ([]*datamanager.Project, int64, error) { return nil, 0, ErrNotImplemented } // GetProjectInfo is not implemented. -func (s *ModelInterface) GetProjectInfo(ctx context.Context, req *datamanager.GetProjectInfoRequest) (*datamanager.Project, error) { +func (s *ModelInterface) GetProjectInfo( + ctx context.Context, req *datamanager.GetProjectInfoRequest) (*datamanager.Project, error) { return nil, ErrNotImplemented } // GetClusterInfoList is not implemented. -func (s *ModelInterface) GetClusterInfoList(ctx context.Context, req *datamanager.GetClusterListRequest) ([]*datamanager.Cluster, int64, error) { +func (s *ModelInterface) GetClusterInfoList( + ctx context.Context, req *datamanager.GetClusterListRequest) ([]*datamanager.Cluster, int64, error) { return nil, 0, ErrNotImplemented } // GetClusterInfo is not implemented. -func (s *ModelInterface) GetClusterInfo(ctx context.Context, req *datamanager.GetClusterInfoRequest) (*datamanager.Cluster, error) { +func (s *ModelInterface) GetClusterInfo( + ctx context.Context, req *datamanager.GetClusterInfoRequest) (*datamanager.Cluster, error) { return nil, ErrNotImplemented } // GetNamespaceInfoList is not implemented. -func (s *ModelInterface) GetNamespaceInfoList(ctx context.Context, req *datamanager.GetNamespaceInfoListRequest) ([]*datamanager.Namespace, int64, error) { +func (s *ModelInterface) GetNamespaceInfoList( + ctx context.Context, req *datamanager.GetNamespaceInfoListRequest) ([]*datamanager.Namespace, int64, error) { return nil, 0, ErrNotImplemented } // GetNamespaceInfo is not implemented. -func (s *ModelInterface) GetNamespaceInfo(ctx context.Context, req *datamanager.GetNamespaceInfoRequest) (*datamanager.Namespace, error) { +func (s *ModelInterface) GetNamespaceInfo( + ctx context.Context, req *datamanager.GetNamespaceInfoRequest) (*datamanager.Namespace, error) { return nil, ErrNotImplemented } // GetWorkloadInfoList is not implemented. -func (s *ModelInterface) GetWorkloadInfoList(ctx context.Context, req *datamanager.GetWorkloadInfoListRequest) ([]*datamanager.Workload, int64, error) { +func (s *ModelInterface) GetWorkloadInfoList( + ctx context.Context, req *datamanager.GetWorkloadInfoListRequest) ([]*datamanager.Workload, int64, error) { return nil, 0, ErrNotImplemented } // GetWorkloadInfo is not implemented. -func (s *ModelInterface) GetWorkloadInfo(ctx context.Context, req *datamanager.GetWorkloadInfoRequest) (*datamanager.Workload, error) { +func (s *ModelInterface) GetWorkloadInfo( + ctx context.Context, req *datamanager.GetWorkloadInfoRequest) (*datamanager.Workload, error) { return nil, ErrNotImplemented } // GetRawPublicInfo is not implemented. -func (s *ModelInterface) GetRawPublicInfo(ctx context.Context, opts *types.JobCommonOpts) ([]*types.PublicData, error) { +func (s *ModelInterface) GetRawPublicInfo( + ctx context.Context, opts *types.JobCommonOpts) ([]*types.PublicData, error) { return nil, ErrNotImplemented } // GetRawProjectInfo is not implemented. -func (s *ModelInterface) GetRawProjectInfo(ctx context.Context, opts *types.JobCommonOpts, bucket string) ([]*types.ProjectData, error) { +func (s *ModelInterface) GetRawProjectInfo( + ctx context.Context, opts *types.JobCommonOpts, bucket string) ([]*types.ProjectData, error) { return nil, ErrNotImplemented } // GetRawClusterInfo is not implemented. -func (s *ModelInterface) GetRawClusterInfo(ctx context.Context, opts *types.JobCommonOpts, bucket string) ([]*types.ClusterData, error) { +func (s *ModelInterface) GetRawClusterInfo( + ctx context.Context, opts *types.JobCommonOpts, bucket string) ([]*types.ClusterData, error) { return nil, ErrNotImplemented } // GetRawNamespaceInfo is not implemented. -func (s *ModelInterface) GetRawNamespaceInfo(ctx context.Context, opts *types.JobCommonOpts, bucket string) ([]*types.NamespaceData, error) { +func (s *ModelInterface) GetRawNamespaceInfo( + ctx context.Context, opts *types.JobCommonOpts, bucket string) ([]*types.NamespaceData, error) { return nil, ErrNotImplemented } // GetRawWorkloadInfo is not implemented. -func (s *ModelInterface) GetRawWorkloadInfo(ctx context.Context, opts *types.JobCommonOpts, bucket string) ([]*types.WorkloadData, error) { +func (s *ModelInterface) GetRawWorkloadInfo( + ctx context.Context, opts *types.JobCommonOpts, bucket string) ([]*types.WorkloadData, error) { return nil, ErrNotImplemented } // InsertProjectInfo is not implemented. -func (s *ModelInterface) InsertProjectInfo(ctx context.Context, metrics *types.ProjectMetrics, opts *types.JobCommonOpts) error { +func (s *ModelInterface) InsertProjectInfo( + ctx context.Context, metrics *types.ProjectMetrics, opts *types.JobCommonOpts) error { return ErrNotImplemented } // InsertClusterInfo is not implemented. -func (s *ModelInterface) InsertClusterInfo(ctx context.Context, metrics *types.ClusterMetrics, opts *types.JobCommonOpts) error { +func (s *ModelInterface) InsertClusterInfo( + ctx context.Context, metrics *types.ClusterMetrics, opts *types.JobCommonOpts) error { return ErrNotImplemented } // InsertNamespaceInfo is not implemented. -func (s *ModelInterface) InsertNamespaceInfo(ctx context.Context, metrics *types.NamespaceMetrics, opts *types.JobCommonOpts) error { +func (s *ModelInterface) InsertNamespaceInfo( + ctx context.Context, metrics *types.NamespaceMetrics, opts *types.JobCommonOpts) error { return ErrNotImplemented } // InsertWorkloadInfo is not implemented. -func (s *ModelInterface) InsertWorkloadInfo(ctx context.Context, metrics *types.WorkloadMetrics, opts *types.JobCommonOpts) error { +func (s *ModelInterface) InsertWorkloadInfo( + ctx context.Context, metrics *types.WorkloadMetrics, opts *types.JobCommonOpts) error { return ErrNotImplemented } // GetWorkloadCount is not implemented. -func (s *ModelInterface) GetWorkloadCount(ctx context.Context, opts *types.JobCommonOpts, bucket string, after time.Time) (int64, error) { +func (s *ModelInterface) GetWorkloadCount( + ctx context.Context, opts *types.JobCommonOpts, bucket string, after time.Time) (int64, error) { return 0, ErrNotImplemented } // InsertPublicInfo is not implemented. -func (s *ModelInterface) InsertPublicInfo(ctx context.Context, metrics *types.PublicData, opts *types.JobCommonOpts) error { +func (s *ModelInterface) InsertPublicInfo( + ctx context.Context, metrics *types.PublicData, opts *types.JobCommonOpts) error { return ErrNotImplemented } // InsertPodAutoscalerInfo is not implemented. -func (s *ModelInterface) InsertPodAutoscalerInfo(ctx context.Context, metrics *types.PodAutoscalerMetrics, opts *types.JobCommonOpts) error { +func (s *ModelInterface) InsertPodAutoscalerInfo( + ctx context.Context, metrics *types.PodAutoscalerMetrics, opts *types.JobCommonOpts) error { return ErrNotImplemented } // GetPodAutoscalerList is not implemented. -func (s *ModelInterface) GetPodAutoscalerList(ctx context.Context, request *datamanager.GetPodAutoscalerListRequest) ([]*datamanager.PodAutoscaler, int64, error) { +func (s *ModelInterface) GetPodAutoscalerList( + ctx context.Context, request *datamanager.GetPodAutoscalerListRequest) ([]*datamanager.PodAutoscaler, int64, error) { return nil, 0, ErrNotImplemented } // GetPodAutoscalerInfo is not implemented. -func (s *ModelInterface) GetPodAutoscalerInfo(ctx context.Context, request *datamanager.GetPodAutoscalerRequest) (*datamanager.PodAutoscaler, error) { +func (s *ModelInterface) GetPodAutoscalerInfo( + ctx context.Context, request *datamanager.GetPodAutoscalerRequest) (*datamanager.PodAutoscaler, error) { return nil, ErrNotImplemented } // GetRawPodAutoscalerInfo is not implemented. -func (s *ModelInterface) GetRawPodAutoscalerInfo(ctx context.Context, opts *types.JobCommonOpts, bucket string) ([]*types.PodAutoscalerData, error) { +func (s *ModelInterface) GetRawPodAutoscalerInfo( + ctx context.Context, opts *types.JobCommonOpts, bucket string) ([]*types.PodAutoscalerData, error) { return nil, ErrNotImplemented } @@ -155,7 +178,8 @@ func (s *ModelInterface) GetLatestWorkloadRequest(ctx context.Context, } // CreateWorkloadOriginRequest is not implemented. -func (s *ModelInterface) CreateWorkloadOriginRequest(ctx context.Context, result *types.WorkloadOriginRequestResult) error { +func (s *ModelInterface) CreateWorkloadOriginRequest( + ctx context.Context, result *types.WorkloadOriginRequestResult) error { return ErrNotImplemented } 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 15c81f0738..6f7d9fe247 100644 --- a/bcs-services/bcs-data-manager/pkg/store/tspider/operationdata.go +++ b/bcs-services/bcs-data-manager/pkg/store/tspider/operationdata.go @@ -17,10 +17,10 @@ import ( "fmt" sq "github.com/Masterminds/squirrel" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/jmoiron/sqlx" "google.golang.org/protobuf/types/known/structpb" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" datamanager "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/proto/bcs-data-manager" ) @@ -30,7 +30,7 @@ const ( ProjectRequestType = "project" // ClusterRequestType type of operation data supportted ClusterRequestType = "cluster" - //NamespaceRequestType type of operation data supportted + // NamespaceRequestType type of operation data supportted NamespaceRequestType = "namespace" // ProjectCodeColumnKey column key for project type data diff --git a/bcs-services/bcs-data-manager/pkg/store/tspider/powertrading.go b/bcs-services/bcs-data-manager/pkg/store/tspider/powertrading.go index 9e6187a768..bebc940a5f 100644 --- a/bcs-services/bcs-data-manager/pkg/store/tspider/powertrading.go +++ b/bcs-services/bcs-data-manager/pkg/store/tspider/powertrading.go @@ -17,10 +17,10 @@ import ( "fmt" sq "github.com/Masterminds/squirrel" + "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/golang/protobuf/ptypes/any" "github.com/jmoiron/sqlx" - "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/types" datamanager "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/proto/bcs-data-manager" ) @@ -61,7 +61,8 @@ func NewModelPowerTrading(dbs map[string]*sqlx.DB, bkbaseConf *types.BkbaseConfi } // GetPowerTradingInfo get operation data ofr power trading -func (pt *ModelPowerTrading) GetPowerTradingInfo(ctx context.Context, request *datamanager.GetPowerTradingDataRequest) ([]*any.Any, int64, error) { +func (pt *ModelPowerTrading) GetPowerTradingInfo( + ctx context.Context, request *datamanager.GetPowerTradingDataRequest) ([]*any.Any, int64, error) { // validate params if err := pt.validate(request); err != nil { return nil, 0, err @@ -103,7 +104,8 @@ func (pt *ModelPowerTrading) validate(request *datamanager.GetPowerTradingDataRe // validate page info params page, size := request.GetPage(), request.GetSize() if (page == 0 && size != 0) || (page != 0 && size == 0) { - return fmt.Errorf("page and size should greater than 0 or both equal to 0, if both 0 return data will without page info") + return fmt.Errorf("page and size should greater than 0 or both equal to 0, " + + "if both 0 return data will without page info") } return nil 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 f19f4169a3..aa2087cc0b 100644 --- a/bcs-services/bcs-data-manager/pkg/store/tspider/public.go +++ b/bcs-services/bcs-data-manager/pkg/store/tspider/public.go @@ -17,11 +17,12 @@ import ( sq "github.com/Masterminds/squirrel" "github.com/Tencent/bk-bcs/bcs-common/common/blog" - "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/utils" "github.com/golang/protobuf/ptypes/any" "github.com/jmoiron/sqlx" "google.golang.org/protobuf/types/known/anypb" "google.golang.org/protobuf/types/known/structpb" + + "github.com/Tencent/bk-bcs/bcs-services/bcs-data-manager/pkg/utils" ) // Public public store for tspider db diff --git a/bcs-services/bcs-data-manager/pkg/store/tspider/utils.go b/bcs-services/bcs-data-manager/pkg/store/tspider/utils.go index fce5eb361e..472d95525d 100644 --- a/bcs-services/bcs-data-manager/pkg/store/tspider/utils.go +++ b/bcs-services/bcs-data-manager/pkg/store/tspider/utils.go @@ -25,9 +25,9 @@ const ( // DescendingFlag descending flag for query datas DescendingFlag = "DESC" - // SQL select all columns + // SqlSelectAll SQL select all columns SqlSelectAll = "*" - // SQL count all records + // SqlSelectCount SQL count all records SqlSelectCount = "COUNT(*)" ) diff --git a/bcs-services/bcs-data-manager/pkg/types/bkbase.go b/bcs-services/bcs-data-manager/pkg/types/bkbase.go index 384c1a5c2a..60b0401ddc 100644 --- a/bcs-services/bcs-data-manager/pkg/types/bkbase.go +++ b/bcs-services/bcs-data-manager/pkg/types/bkbase.go @@ -30,7 +30,7 @@ type BkbaseTable struct { // CloudNativeConfig config for cloud native score type CloudNativeConfig struct { - Bkbase BkbaseTable `json:"bkbase,omitepty"` + Bkbase BkbaseTable `json:"bkbase,omitempty"` Platform uint32 `json:"platform,omitempty"` AppId string `json:"appid,omitempty"` } diff --git a/bcs-services/bcs-data-manager/pkg/types/types.go b/bcs-services/bcs-data-manager/pkg/types/types.go index a6245b3a05..a040d7dad3 100644 --- a/bcs-services/bcs-data-manager/pkg/types/types.go +++ b/bcs-services/bcs-data-manager/pkg/types/types.go @@ -503,7 +503,7 @@ type BKBaseRequestRecommendResult struct { DTEventTimeStamp int64 `json:"dtEventTimeStamp" bson:"dt_event_time_stamp"` TheDate int64 `json:"thedate" bson:"the_date"` LocalTime string `json:"localTime" bson:"local_time"` - CreateAt time.Time `json:"createAt" json:"create_at"` + CreateAt time.Time `json:"createAt" bson:"create_at"` } // WorkloadOriginRequestContainer container request limit diff --git a/bcs-services/bcs-k8s-watch/app/k8s/watcher.go b/bcs-services/bcs-k8s-watch/app/k8s/watcher.go index 1f6f2c922c..61149eb312 100644 --- a/bcs-services/bcs-k8s-watch/app/k8s/watcher.go +++ b/bcs-services/bcs-k8s-watch/app/k8s/watcher.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.