From cb0a6c843017a21dfb08dc22bdaf4586e9502de4 Mon Sep 17 00:00:00 2001 From: evelynwei Date: Tue, 17 Dec 2024 15:50:30 +0800 Subject: [PATCH 1/3] refactor: fix golint --- cmd/polaris-controller/app/config.go | 4 +- cmd/polaris-controller/app/options/serve.go | 4 +- .../app/polaris-controller-manager.go | 6 +- cmd/polaris-controller/main.go | 2 +- common/log/config.go | 2 +- pkg/controller/apis.go | 8 +- pkg/controller/controller.go | 4 - pkg/controller/namespace.go | 2 +- pkg/inject/api/annotation/annotations.gen.go | 515 +++++++++--------- pkg/inject/pkg/config/mesh/mesh.go | 8 +- .../pkg/kube/inject/apply/javaagent/patch.go | 10 +- pkg/inject/pkg/kube/inject/inject.go | 2 + pkg/inject/pkg/kube/inject/webhook.go | 27 +- pkg/polarisapi/service_api.go | 21 +- pkg/util/flag/flags.go | 2 + pkg/util/helper.go | 33 +- pkg/util/scheduler.go | 3 + 17 files changed, 330 insertions(+), 323 deletions(-) diff --git a/cmd/polaris-controller/app/config.go b/cmd/polaris-controller/app/config.go index a2b3b581..2dfbd8da 100644 --- a/cmd/polaris-controller/app/config.go +++ b/cmd/polaris-controller/app/config.go @@ -16,7 +16,7 @@ package app import ( - "io/ioutil" + "os" "gopkg.in/yaml.v2" @@ -65,7 +65,7 @@ type controllerConfig struct { } func readConfFromFile() (*controllerConfig, error) { - buf, err := ioutil.ReadFile(MeshFile) + buf, err := os.ReadFile(MeshFile) if err != nil { log.Errorf("read file error, %v", err) return nil, err diff --git a/cmd/polaris-controller/app/options/serve.go b/cmd/polaris-controller/app/options/serve.go index 1ee5642f..cdedebf2 100644 --- a/cmd/polaris-controller/app/options/serve.go +++ b/cmd/polaris-controller/app/options/serve.go @@ -95,7 +95,9 @@ func RunServer( defer close(stoppedCh) <-stopCh ctx, cancel := context.WithTimeout(context.Background(), shutDownTimeout) - server.Shutdown(ctx) + if err := server.Shutdown(ctx); err != nil { + log.Warnf("server Shutdown error:%+v", err) + } cancel() }() diff --git a/cmd/polaris-controller/app/polaris-controller-manager.go b/cmd/polaris-controller/app/polaris-controller-manager.go index 835758d8..dafeb3aa 100644 --- a/cmd/polaris-controller/app/polaris-controller-manager.go +++ b/cmd/polaris-controller/app/polaris-controller-manager.go @@ -18,7 +18,7 @@ package app import ( "context" "fmt" - "io/ioutil" + "io" "math/rand" "net" "net/http" @@ -239,8 +239,8 @@ func assignFlags(rootCmd *cobra.Command) { func closeGrpcLog() { var ( - infoW = ioutil.Discard - warningW = ioutil.Discard + infoW = io.Discard + warningW = io.Discard errorW = os.Stderr ) grpclog.SetLoggerV2(grpclog.NewLoggerV2(infoW, warningW, errorW)) diff --git a/cmd/polaris-controller/main.go b/cmd/polaris-controller/main.go index f2993b51..679dd301 100644 --- a/cmd/polaris-controller/main.go +++ b/cmd/polaris-controller/main.go @@ -28,7 +28,7 @@ import ( ) func main() { - rand.Seed(time.Now().UnixNano()) + rand.New(rand.NewSource(time.Now().UnixNano())) command := app.NewPolarisControllerManagerCommand() logs.InitLogs() diff --git a/common/log/config.go b/common/log/config.go index 7e2d61f5..5b05e685 100644 --- a/common/log/config.go +++ b/common/log/config.go @@ -293,7 +293,7 @@ func Configure(optionsMap map[string]*Options) error { // capture gRPC logging if options.LogGrpc { - grpclog.SetLogger(zapgrpc.NewLogger(captureLogger.WithOptions(zap.AddCallerSkip(2)))) + grpclog.SetLoggerV2(zapgrpc.NewLogger(captureLogger.WithOptions(zap.AddCallerSkip(2)))) } } } diff --git a/pkg/controller/apis.go b/pkg/controller/apis.go index 7d196bdb..c55334f4 100644 --- a/pkg/controller/apis.go +++ b/pkg/controller/apis.go @@ -275,7 +275,8 @@ func (p *PolarisController) compareInstanceUpdate(service *v1.Service, spec *add // ttl 默认是5s ttl, err := strconv.Atoi(ttlStr) if err != nil { - ttl = 5 + log.SyncNamingScope().Errorf("annotation 'polarismesh.cn/ttl' value: %s, converted to type int error %v", + ttlStr, err) } else { if ttl > 0 && ttl <= 60 { healthCheck.Type = util.IntPtr(0) @@ -317,10 +318,7 @@ func (p *PolarisController) compareInstanceUpdate(service *v1.Service, spec *add } if newMetadataStr == "" { - if isPolarisInstanceHasCustomMeta(oldMetadata) { - return true - } - return false + return isPolarisInstanceHasCustomMeta(oldMetadata) } newMetaMap := make(map[string]string) err := json.Unmarshal([]byte(newMetadataStr), &newMetaMap) diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index e22b0642..4a6212f9 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -285,10 +285,6 @@ func (p *PolarisController) process(t *Task) error { return err } -func (p *PolarisController) handleErr(err error, task *Task) { - -} - // CounterPolarisService func (p *PolarisController) CounterPolarisService() { serviceList, err := p.serviceLister.List(labels.Everything()) diff --git a/pkg/controller/namespace.go b/pkg/controller/namespace.go index 008426b0..b03595bf 100644 --- a/pkg/controller/namespace.go +++ b/pkg/controller/namespace.go @@ -68,11 +68,11 @@ func (p *PolarisController) onNamespaceUpdate(old, cur interface{}) { // 3. 无 sync -> 有 sync,将 ns 下 service、configmap 加入队列,标志为 polaris 要处理的,即添加 // 4. 有 sync -> 无 sync,将 ns 下 service、configmap 加入队列,标志为 polaris 不需要处理的,即删除 - operation := OperationEmpty if !isOldSync && !isCurSync { // 情况 1 return } + var operation Operation if isCurSync { // 情况 2、3 operation = OperationAdd diff --git a/pkg/inject/api/annotation/annotations.gen.go b/pkg/inject/api/annotation/annotations.gen.go index fb5737a6..d531b1ba 100644 --- a/pkg/inject/api/annotation/annotations.gen.go +++ b/pkg/inject/api/annotation/annotations.gen.go @@ -1,4 +1,3 @@ - // GENERATED FILE -- DO NOT EDIT package annotation @@ -7,11 +6,11 @@ type ResourceTypes int const ( Unknown ResourceTypes = iota - Any - Ingress - Pod - Service - ServiceEntry + Any + Ingress + Pod + Service + ServiceEntry ) func (r ResourceTypes) String() string { @@ -49,256 +48,256 @@ type Instance struct { } var ( - SidecarStatusReadinessApplicationPorts = Instance { - Name: "readiness.status.sidecar.polarismesh.cn/applicationPorts", - Description: "Specifies the list of ports exposed by the application "+ - "container. Used by the Envoy sidecar readiness probe to "+ - "determine that Envoy is configured and ready to receive "+ - "traffic.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarStatusReadinessFailureThreshold = Instance { - Name: "readiness.status.sidecar.polarismesh.cn/failureThreshold", - Description: "Specifies the failure threshold for the Envoy sidecar "+ - "readiness probe.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarStatusReadinessInitialDelaySeconds = Instance { - Name: "readiness.status.sidecar.polarismesh.cn/initialDelaySeconds", - Description: "Specifies the initial delay (in seconds) for the Envoy "+ - "sidecar readiness probe.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarStatusReadinessPeriodSeconds = Instance { - Name: "readiness.status.sidecar.polarismesh.cn/periodSeconds", - Description: "Specifies the period (in seconds) for the Envoy sidecar "+ - "readiness probe.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SecurityAutoMTLS = Instance { - Name: "security.polarismesh.cn/autoMTLS", - Description: "Determines whether the client proxy uses auto mTLS. This "+ - "overrides the mesh default specified in "+ - "MeshConfig.enable_auto_mtls.", - Hidden: true, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarBootstrapOverride = Instance { - Name: "sidecar.polarismesh.cn/bootstrapOverride", - Description: "Specifies an alternative Envoy bootstrap configuration "+ - "file.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarDiscoveryAddress = Instance { - Name: "sidecar.polarismesh.cn/discoveryAddress", - Description: "Specifies the XDS discovery address to be used by the "+ - "Envoy sidecar.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarEnableCoreDump = Instance { - Name: "sidecar.polarismesh.cn/enableCoreDump", - Description: "Specifies whether or not an Envoy sidecar should enable "+ - "core dump.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarInject = Instance { - Name: "sidecar.polarismesh.cn/inject", - Description: "Specifies whether or not an Polaris sidecar should be "+ - "automatically injected into the workload.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarInterceptionMode = Instance { - Name: "sidecar.polarismesh.cn/interceptionMode", - Description: "Specifies the mode used to redirect inbound connections "+ - "to Envoy (REDIRECT or TPROXY).", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarLogLevel = Instance { - Name: "sidecar.polarismesh.cn/logLevel", - Description: "Specifies the log level for Envoy.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarProxyCPU = Instance { - Name: "sidecar.polarismesh.cn/proxyCPU", - Description: "Specifies the requested CPU setting for the Envoy "+ - "sidecar.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarProxyImage = Instance { - Name: "sidecar.polarismesh.cn/proxyImage", - Description: "Specifies the Docker image to be used by the Envoy "+ - "sidecar.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarProxyMemory = Instance { - Name: "sidecar.polarismesh.cn/proxyMemory", - Description: "Specifies the requested memory setting for the Envoy "+ - "sidecar.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarRewriteAppHTTPProbers = Instance { - Name: "sidecar.polarismesh.cn/rewriteAppHTTPProbers", - Description: "Rewrite HTTP readiness and liveness probes to be "+ - "redirected to the Envoy sidecar.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarStatsInclusionPrefixes = Instance { - Name: "sidecar.polarismesh.cn/statsInclusionPrefixes", - Description: "Specifies the comma separated list of prefixes of the "+ - "stats to be emitted by Envoy.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarStatsInclusionRegexps = Instance { - Name: "sidecar.polarismesh.cn/statsInclusionRegexps", - Description: "Specifies the comma separated list of regexes the stats "+ - "should match to be emitted by Envoy.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarStatsInclusionSuffixes = Instance { - Name: "sidecar.polarismesh.cn/statsInclusionSuffixes", - Description: "Specifies the comma separated list of suffixes of the "+ - "stats to be emitted by Envoy.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarStatus = Instance { - Name: "sidecar.polarismesh.cn/status", - Description: "Generated by Envoy sidecar injection that indicates the "+ - "status of the operation. Includes a version hash of the "+ - "executed template, as well as names of injected "+ - "resources.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarUserVolume = Instance { - Name: "sidecar.polarismesh.cn/userVolume", - Description: "Specifies one or more user volumes (as a JSON array) to "+ - "be added to the Envoy sidecar.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarUserVolumeMount = Instance { - Name: "sidecar.polarismesh.cn/userVolumeMount", - Description: "Specifies one or more user volume mounts (as a JSON "+ - "array) to be added to the Envoy sidecar.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarStatusPort = Instance { - Name: "status.sidecar.polarismesh.cn/port", - Description: "Specifies the HTTP status Port for the Envoy sidecar. If "+ - "zero, the sidecar will not provide status.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarTrafficExcludeInboundPorts = Instance { - Name: "traffic.sidecar.polarismesh.cn/excludeInboundPorts", - Description: "A comma separated list of inbound ports to be excluded "+ - "from redirection to Envoy. Only applies when all inbound "+ - "traffic (i.e. '*') is being redirected.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarTrafficExcludeOutboundIPRanges = Instance { - Name: "traffic.sidecar.polarismesh.cn/excludeOutboundIPRanges", - Description: "A comma separated list of IP ranges in CIDR form to be "+ - "excluded from redirection. Only applies when all outbound "+ - "traffic (i.e. '*') is being redirected.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarTrafficExcludeOutboundPorts = Instance { - Name: "traffic.sidecar.polarismesh.cn/excludeOutboundPorts", - Description: "A comma separated list of outbound ports to be excluded "+ - "from redirection to Envoy.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarTrafficIncludeInboundPorts = Instance { - Name: "traffic.sidecar.polarismesh.cn/includeInboundPorts", - Description: "A comma separated list of inbound ports for which traffic "+ - "is to be redirected to Envoy. The wildcard character '*' "+ - "can be used to configure redirection for all ports. An "+ - "empty list will disable all inbound redirection.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } - - SidecarTrafficIncludeOutboundIPRanges = Instance { - Name: "traffic.sidecar.polarismesh.cn/includeOutboundIPRanges", - Description: "A comma separated list of IP ranges in CIDR form to "+ - "redirect to Envoy (optional). The wildcard character '*' "+ - "can be used to redirect all outbound traffic. An empty "+ - "list will disable all outbound redirection.", - Hidden: false, - Deprecated: false, - Resources: []ResourceTypes{ Pod, }, - } + SidecarStatusReadinessApplicationPorts = Instance{ + Name: "readiness.status.sidecar.polarismesh.cn/applicationPorts", + Description: "Specifies the list of ports exposed by the application " + + "container. Used by the Envoy sidecar readiness probe to " + + "determine that Envoy is configured and ready to receive " + + "traffic.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarStatusReadinessFailureThreshold = Instance{ + Name: "readiness.status.sidecar.polarismesh.cn/failureThreshold", + Description: "Specifies the failure threshold for the Envoy sidecar " + + "readiness probe.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarStatusReadinessInitialDelaySeconds = Instance{ + Name: "readiness.status.sidecar.polarismesh.cn/initialDelaySeconds", + Description: "Specifies the initial delay (in seconds) for the Envoy " + + "sidecar readiness probe.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarStatusReadinessPeriodSeconds = Instance{ + Name: "readiness.status.sidecar.polarismesh.cn/periodSeconds", + Description: "Specifies the period (in seconds) for the Envoy sidecar " + + "readiness probe.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SecurityAutoMTLS = Instance{ + Name: "security.polarismesh.cn/autoMTLS", + Description: "Determines whether the client proxy uses auto mTLS. This " + + "overrides the mesh default specified in " + + "MeshConfig.enable_auto_mtls.", + Hidden: true, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarBootstrapOverride = Instance{ + Name: "sidecar.polarismesh.cn/bootstrapOverride", + Description: "Specifies an alternative Envoy bootstrap configuration " + + "file.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarDiscoveryAddress = Instance{ + Name: "sidecar.polarismesh.cn/discoveryAddress", + Description: "Specifies the XDS discovery address to be used by the " + + "Envoy sidecar.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarEnableCoreDump = Instance{ + Name: "sidecar.polarismesh.cn/enableCoreDump", + Description: "Specifies whether or not an Envoy sidecar should enable " + + "core dump.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarInject = Instance{ + Name: "sidecar.polarismesh.cn/inject", + Description: "Specifies whether or not an Polaris sidecar should be " + + "automatically injected into the workload.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarInterceptionMode = Instance{ + Name: "sidecar.polarismesh.cn/interceptionMode", + Description: "Specifies the mode used to redirect inbound connections " + + "to Envoy (REDIRECT or TPROXY).", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarLogLevel = Instance{ + Name: "sidecar.polarismesh.cn/logLevel", + Description: "Specifies the log level for Envoy.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarProxyCPU = Instance{ + Name: "sidecar.polarismesh.cn/proxyCPU", + Description: "Specifies the requested CPU setting for the Envoy " + + "sidecar.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarProxyImage = Instance{ + Name: "sidecar.polarismesh.cn/proxyImage", + Description: "Specifies the Docker image to be used by the Envoy " + + "sidecar.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarProxyMemory = Instance{ + Name: "sidecar.polarismesh.cn/proxyMemory", + Description: "Specifies the requested memory setting for the Envoy " + + "sidecar.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarRewriteAppHTTPProbers = Instance{ + Name: "sidecar.polarismesh.cn/rewriteAppHTTPProbers", + Description: "Rewrite HTTP readiness and liveness probes to be " + + "redirected to the Envoy sidecar.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarStatsInclusionPrefixes = Instance{ + Name: "sidecar.polarismesh.cn/statsInclusionPrefixes", + Description: "Specifies the comma separated list of prefixes of the " + + "stats to be emitted by Envoy.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarStatsInclusionRegexps = Instance{ + Name: "sidecar.polarismesh.cn/statsInclusionRegexps", + Description: "Specifies the comma separated list of regexes the stats " + + "should match to be emitted by Envoy.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarStatsInclusionSuffixes = Instance{ + Name: "sidecar.polarismesh.cn/statsInclusionSuffixes", + Description: "Specifies the comma separated list of suffixes of the " + + "stats to be emitted by Envoy.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarStatus = Instance{ + Name: "sidecar.polarismesh.cn/status", + Description: "Generated by Envoy sidecar injection that indicates the " + + "status of the operation. Includes a version hash of the " + + "executed template, as well as names of injected " + + "resources.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarUserVolume = Instance{ + Name: "sidecar.polarismesh.cn/userVolume", + Description: "Specifies one or more user volumes (as a JSON array) to " + + "be added to the Envoy sidecar.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarUserVolumeMount = Instance{ + Name: "sidecar.polarismesh.cn/userVolumeMount", + Description: "Specifies one or more user volume mounts (as a JSON " + + "array) to be added to the Envoy sidecar.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarStatusPort = Instance{ + Name: "status.sidecar.polarismesh.cn/port", + Description: "Specifies the HTTP status Port for the Envoy sidecar. If " + + "zero, the sidecar will not provide status.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarTrafficExcludeInboundPorts = Instance{ + Name: "traffic.sidecar.polarismesh.cn/excludeInboundPorts", + Description: "A comma separated list of inbound ports to be excluded " + + "from redirection to Envoy. Only applies when all inbound " + + "traffic (i.e. '*') is being redirected.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarTrafficExcludeOutboundIPRanges = Instance{ + Name: "traffic.sidecar.polarismesh.cn/excludeOutboundIPRanges", + Description: "A comma separated list of IP ranges in CIDR form to be " + + "excluded from redirection. Only applies when all outbound " + + "traffic (i.e. '*') is being redirected.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarTrafficExcludeOutboundPorts = Instance{ + Name: "traffic.sidecar.polarismesh.cn/excludeOutboundPorts", + Description: "A comma separated list of outbound ports to be excluded " + + "from redirection to Envoy.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarTrafficIncludeInboundPorts = Instance{ + Name: "traffic.sidecar.polarismesh.cn/includeInboundPorts", + Description: "A comma separated list of inbound ports for which traffic " + + "is to be redirected to Envoy. The wildcard character '*' " + + "can be used to configure redirection for all ports. An " + + "empty list will disable all inbound redirection.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } + + SidecarTrafficIncludeOutboundIPRanges = Instance{ + Name: "traffic.sidecar.polarismesh.cn/includeOutboundIPRanges", + Description: "A comma separated list of IP ranges in CIDR form to " + + "redirect to Envoy (optional). The wildcard character '*' " + + "can be used to redirect all outbound traffic. An empty " + + "list will disable all outbound redirection.", + Hidden: false, + Deprecated: false, + Resources: []ResourceTypes{Pod}, + } ) diff --git a/pkg/inject/pkg/config/mesh/mesh.go b/pkg/inject/pkg/config/mesh/mesh.go index 8dd5f603..835524f1 100644 --- a/pkg/inject/pkg/config/mesh/mesh.go +++ b/pkg/inject/pkg/config/mesh/mesh.go @@ -15,7 +15,7 @@ package mesh import ( - "io/ioutil" + "os" "github.com/hashicorp/go-multierror" "gopkg.in/yaml.v2" @@ -54,7 +54,9 @@ func DefaultMeshConfig() MeshConfig { // ApplyMeshConfig returns a new MeshConfig decoded from the // input YAML with the provided defaults applied to omitted configuration values. func ApplyMeshConfig(str string, defaultConfig MeshConfig) (*MeshConfig, error) { - yaml.Unmarshal([]byte(str), &defaultConfig) + if err := yaml.Unmarshal([]byte(str), &defaultConfig); err != nil { + return nil, err + } return &defaultConfig, nil } @@ -66,7 +68,7 @@ func ApplyMeshConfigDefaults(yaml string) (*MeshConfig, error) { // ReadMeshConfig gets mesh configuration from a config file func ReadMeshConfig(filename string) (*MeshConfig, error) { - yaml, err := ioutil.ReadFile(filename) + yaml, err := os.ReadFile(filename) if err != nil { return nil, multierror.Prefix(err, "cannot read mesh config file") } diff --git a/pkg/inject/pkg/kube/inject/apply/javaagent/patch.go b/pkg/inject/pkg/kube/inject/apply/javaagent/patch.go index ffd02d20..48235be4 100644 --- a/pkg/inject/pkg/kube/inject/apply/javaagent/patch.go +++ b/pkg/inject/pkg/kube/inject/apply/javaagent/patch.go @@ -24,14 +24,15 @@ import ( "strings" "text/template" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "github.com/polarismesh/polaris-controller/common/log" "github.com/polarismesh/polaris-controller/pkg/inject/pkg/kube/inject" "github.com/polarismesh/polaris-controller/pkg/inject/pkg/kube/inject/apply/base" "github.com/polarismesh/polaris-controller/pkg/polarisapi" "github.com/polarismesh/polaris-controller/pkg/util" utils "github.com/polarismesh/polaris-controller/pkg/util" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // Java Agent 场景下的特殊 annonations 信息 @@ -253,7 +254,10 @@ func (pb *PodPatchBuilder) updateContainer(opt *inject.PatchOptions, sidecarMode if properties, ok := annonations[customJavaAgentPluginConfig]; ok { customProperties := map[string]string{} if properties != "" { - json.Unmarshal([]byte(properties), &customProperties) + if err := json.Unmarshal([]byte(properties), &customProperties); err != nil { + log.InjectScope().Errorf("updateContainer for pod=[%s, %s] json error: %+v", pod.Namespace, + pod.Name, err) + } } // 先从 configmap 中获取 java-agent 不同 plugin-type 的默认配置信息 for k, v := range customProperties { diff --git a/pkg/inject/pkg/kube/inject/inject.go b/pkg/inject/pkg/kube/inject/inject.go index 5facb858..b22f6c94 100644 --- a/pkg/inject/pkg/kube/inject/inject.go +++ b/pkg/inject/pkg/kube/inject/inject.go @@ -255,6 +255,7 @@ func validateStatusPort(port string) error { return nil } +// nolint // validateUInt32 validates that the given annotation value is a positive integer. func validateUInt32(value string) error { _, err := strconv.ParseUint(value, 10, 32) @@ -825,6 +826,7 @@ func potentialPodName(metadata *metav1.ObjectMeta) string { return "" } +// nolint // rewriteCniPodSpec will check if values from the sidecar injector Helm // values need to be inserted as Pod annotations so the CNI will apply // the proper redirection rules. diff --git a/pkg/inject/pkg/kube/inject/webhook.go b/pkg/inject/pkg/kube/inject/webhook.go index 3c324f8d..4762d164 100644 --- a/pkg/inject/pkg/kube/inject/webhook.go +++ b/pkg/inject/pkg/kube/inject/webhook.go @@ -21,8 +21,9 @@ import ( "crypto/tls" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" + "os" "path/filepath" "sort" "strings" @@ -110,10 +111,10 @@ type InjectConfigInfo struct { // env will be used for other things besides meshConfig - when webhook is running in Istiod it can take advantage // of the config and endpoint cache. -// nolint directives: interfacer +// nolint func loadConfig(injectMeshFile, injectDnsFile, injectJavaFile, meshFile, valuesFile string) (*InjectConfigInfo, error) { // 处理 polaris-sidecar mesh 模式的注入 - meshData, err := ioutil.ReadFile(injectMeshFile) + meshData, err := os.ReadFile(injectMeshFile) if err != nil { return nil, err } @@ -124,7 +125,7 @@ func loadConfig(injectMeshFile, injectDnsFile, injectJavaFile, meshFile, valuesF } // 处理 polaris-sidecar dns 模式的注入 - dnsData, err := ioutil.ReadFile(injectDnsFile) + dnsData, err := os.ReadFile(injectDnsFile) if err != nil { return nil, err } @@ -135,7 +136,7 @@ func loadConfig(injectMeshFile, injectDnsFile, injectJavaFile, meshFile, valuesF } // 处理 java-agent 模式的注入 - javaAgentData, err := ioutil.ReadFile(injectJavaFile) + javaAgentData, err := os.ReadFile(injectJavaFile) if err != nil { return nil, err } @@ -145,7 +146,7 @@ func loadConfig(injectMeshFile, injectDnsFile, injectJavaFile, meshFile, valuesF return nil, err } - valuesConfig, err := ioutil.ReadFile(valuesFile) + valuesConfig, err := os.ReadFile(valuesFile) if err != nil { return nil, err } @@ -285,17 +286,15 @@ func NewWebhook(p WebhookParameters) (*Webhook, error) { defaultSidecarMode: p.DefaultSidecarMode, } - var mux *http.ServeMux if p.Mux != nil { p.Mux.HandleFunc("/inject", wh.serveInject) - mux = p.Mux } else { wh.server = &http.Server{ Addr: fmt.Sprintf(":%v", p.Port), // mtls disabled because apiserver webhook cert usage is still TBD. TLSConfig: &tls.Config{GetCertificate: wh.getCert}, } - mux = http.NewServeMux() + mux := http.NewServeMux() mux.HandleFunc("/inject", wh.serveInject) wh.server.Handler = mux } @@ -366,7 +365,7 @@ func (wh *Webhook) Run(stop <-chan struct{}) { log.InjectScope().Errorf("Watcher error: %v", err) case <-healthC: content := []byte(`ok`) - if err := ioutil.WriteFile(wh.healthCheckFile, content, 0o644); err != nil { + if err := os.WriteFile(wh.healthCheckFile, content, 0o644); err != nil { log.InjectScope().Errorf("Health check update of %q failed: %v", wh.healthCheckFile, err) } case <-stop: @@ -409,6 +408,7 @@ func enableMtls(pod *corev1.Pod) bool { return false } +// nolint // addPolarisConfigToInitContainerEnv 将polaris-sidecar 的配置注入到init container中 func (wh *Webhook) addPolarisConfigToInitContainerEnv(add *corev1.Container) error { cfgTpl, err := wh.k8sClient.CoreV1().ConfigMaps(common.PolarisControllerNamespace). @@ -447,9 +447,11 @@ func (wh *Webhook) addPolarisConfigToInitContainerEnv(add *corev1.Container) err return nil } +// nolint // currently we assume that polaris-security deploy into polaris-system namespace. const rootNamespace = "polaris-system" +// nolint // ensureRootCertExist ensure that we have rootca pem secret in current namespace func (wh *Webhook) ensureRootCertExist(pod *corev1.Pod) error { if !enableMtls(pod) { @@ -504,6 +506,7 @@ func escapeJSONPointerValue(in string) string { return strings.Replace(step, "/", "~1", -1) } +// nolint // adds labels to the target spec, will not overwrite label's value if it already exists func addLabels(target map[string]string, added map[string]string) []Rfc6902PatchOperation { patches := []Rfc6902PatchOperation{} @@ -854,7 +857,7 @@ func (wh *Webhook) injectV1beta1(ar *v1beta1.AdmissionReview) *v1beta1.Admission } proxyCfg := wh.meshConfig.DefaultConfig spec, annotations, iStatus, err := InjectionData(config.Template, wh.valuesConfig, tempVersion, typeMetadata, - deployMeta, &pod.Spec, &pod.ObjectMeta, proxyCfg) // nolint: lll + deployMeta, &pod.Spec, &pod.ObjectMeta, proxyCfg) if err != nil { handleError(fmt.Sprintf("Injection data: err=%v spec=%v\n", err, iStatus)) return toV1beta1AdmissionResponse(err) @@ -1028,7 +1031,7 @@ func (wh *Webhook) injectV1(ar *v1.AdmissionReview) *v1.AdmissionResponse { func (wh *Webhook) serveInject(w http.ResponseWriter, r *http.Request) { var body []byte if r.Body != nil { - if data, err := ioutil.ReadAll(r.Body); err == nil { + if data, err := io.ReadAll(r.Body); err == nil { body = data } } diff --git a/pkg/polarisapi/service_api.go b/pkg/polarisapi/service_api.go index 73241e7a..2fdf68a8 100644 --- a/pkg/polarisapi/service_api.go +++ b/pkg/polarisapi/service_api.go @@ -20,7 +20,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "math" "net/http" "strconv" @@ -92,8 +92,7 @@ func AddInstances(instances []Instance, size int, msg string) (err error) { return } - _, body, times, err := - polarisHttpRequest(requestID, http.MethodPost, url, requestByte) + _, body, times, err := polarisHttpRequest(requestID, http.MethodPost, url, requestByte) if err != nil { log.SyncNamingScope().Errorf("Failed request %s [%d/%d], err %v. (%s)", msg, i+1, page, err, requestID) polarisErrors.Append(PError{ @@ -207,8 +206,7 @@ func DeleteInstances(instances []Instance, size int, msg string) (err error) { return } var response AddResponse - statusCode, body, times, err := - polarisHttpRequest(requestID, http.MethodPost, url, requestByte) + statusCode, body, times, err := polarisHttpRequest(requestID, http.MethodPost, url, requestByte) if err != nil { log.SyncNamingScope().Errorf("Failed to request %s [%d/%d], err %v. (%s)", @@ -365,8 +363,7 @@ func UpdateInstances(instances []Instance, size int, msg string) (err error) { return polarisErrors.GetError() } -func dealUpdateInstanceResponse(response AddResponse, msg string, - i int, page int, polarisErrors *PErrors) { +func dealUpdateInstanceResponse(response AddResponse, msg string, i int, page int, polarisErrors *PErrors) { // 添加成功或者权限错误,都跳过 if response.Code == 200000 { log.SyncNamingScope().Infof("Success add all %s [%d/%d], info %s.", msg, i+1, page, response.Info) @@ -744,10 +741,8 @@ func splitArray(instances []Instance, size int) [][]Instance { } // polarisHttpRequest -func polarisHttpRequest( - requestID string, method string, - url string, requestByte []byte) (int, []byte, time.Duration, error) { - +func polarisHttpRequest(requestID string, method string, url string, requestByte []byte) (int, []byte, time.Duration, + error) { startTime := time.Now() req, err := http.NewRequest(method, url, bytes.NewReader(requestByte)) if err != nil { @@ -773,7 +768,7 @@ func polarisHttpRequest( defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { log.Errorf("Failed to get request %v", err) @@ -803,7 +798,7 @@ func lookAccessToken() (string, error) { return "", err } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { log.Errorf("Failed to get request %v", err) return "", err diff --git a/pkg/util/flag/flags.go b/pkg/util/flag/flags.go index de668bf1..ceadb6e8 100644 --- a/pkg/util/flag/flags.go +++ b/pkg/util/flag/flags.go @@ -47,6 +47,7 @@ type IPVar struct { Val *string } +// nolint // Set sets the flag value func (v IPVar) Set(s string) error { if len(s) == 0 { @@ -83,6 +84,7 @@ type IPPortVar struct { Val *string } +// nolint // Set sets the flag value func (v IPPortVar) Set(s string) error { if len(s) == 0 { diff --git a/pkg/util/helper.go b/pkg/util/helper.go index add00d9b..103bea84 100644 --- a/pkg/util/helper.go +++ b/pkg/util/helper.go @@ -47,22 +47,23 @@ const ( func WaitForAPIServer(client clientset.Interface, timeout time.Duration) error { var lastErr error - err := wait.PollImmediate(time.Second, timeout, func() (bool, error) { - healthStatus := 0 - result := client.Discovery().RESTClient().Get().AbsPath("/healthz").Do(context.TODO()).StatusCode(&healthStatus) - if result.Error() != nil { - lastErr = fmt.Errorf("failed to get apiserver /healthz status: %v", result.Error()) - return false, nil - } - if healthStatus != http.StatusOK { - content, _ := result.Raw() - lastErr = fmt.Errorf("APIServer isn't healthy: %v", string(content)) - log.Warnf("APIServer isn't healthy yet: %v. Waiting a little while.", string(content)) - return false, nil - } - - return true, nil - }) + err := wait.PollUntilContextTimeout(context.Background(), time.Second, timeout, true, + func(ctx context.Context) (bool, error) { + healthStatus := 0 + result := client.Discovery().RESTClient().Get().AbsPath("/healthz").Do(context.TODO()).StatusCode(&healthStatus) + if result.Error() != nil { + lastErr = fmt.Errorf("failed to get apiserver /healthz status: %v", result.Error()) + return false, nil + } + if healthStatus != http.StatusOK { + content, _ := result.Raw() + lastErr = fmt.Errorf("APIServer isn't healthy: %v", string(content)) + log.Warnf("APIServer isn't healthy yet: %v. Waiting a little while.", string(content)) + return false, nil + } + + return true, nil + }) if err != nil { return fmt.Errorf("%v: %v", err, lastErr) diff --git a/pkg/util/scheduler.go b/pkg/util/scheduler.go index eae2a417..8da4b7af 100644 --- a/pkg/util/scheduler.go +++ b/pkg/util/scheduler.go @@ -22,6 +22,8 @@ import ( "sync" "sync/atomic" "time" + + "github.com/polarismesh/polaris-controller/common/log" ) func NewExecutor(size int) *TaskExecutor { @@ -130,6 +132,7 @@ func (w *worker) addDelay(delay time.Duration, f func(), isInterval bool) { defer func() { if err := recover(); err != nil { // do nothing + log.Warnf("addDelay error:%+v", err) } }() f() From 355315d0beccadd626b5fd299df683bc39552ede Mon Sep 17 00:00:00 2001 From: evelynwei Date: Wed, 18 Dec 2024 11:50:20 +0800 Subject: [PATCH 2/3] chore: update image tag and add commands to of Makefile --- Makefile | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 5f2fcb55..630a6ce4 100644 --- a/Makefile +++ b/Makefile @@ -3,11 +3,11 @@ ORG = polarismesh REPO = polaris-controller SIDECAR_INIT_REPO = polaris-sidecar-init ENVOY_SIDECAR_INIT_REPO = polaris-envoy-bootstrap-generator -IMAGE_TAG = v1.7.1 +IMAGE_TAG = v1.7.2 PLATFORMS = linux/amd64,linux/arm64 .PHONY: all -all: build-amd64 build-arm64 build-multi-arch-image \ +all: fmt build-amd64 build-arm64 build-multi-arch-image \ build-sidecar-init build-envoy-sidecar-init push-image .PHONY: build-amd64 @@ -49,3 +49,20 @@ clean: rm -rf bin rm -rf polaris-controller-release* +.PHONY: fmt +fmt: ## Run go fmt against code. + go fmt ./... + +.PHONY: generate-multi-arch-image +generate-multi-arch-image: fmt build-amd64 build-arm64 + @echo "------------------" + @echo "--> Generate multi-arch docker image to registry for polaris-controller" + @echo "------------------" + @docker buildx build -f ./docker/Dockerfile --tag $(ORG)/$(REPO):$(IMAGE_TAG) --platform $(PLATFORMS) ./ + +.PHONY: push-multi-arch-image +push-multi-arch-image: generate-multi-arch-image + @echo "------------------" + @echo "--> Push multi-arch docker image to registry for polaris-controller" + @echo "------------------" + @docker image push $(ORG)/$(REPO):$(IMAGE_TAG) --platform $(PLATFORMS) \ No newline at end of file From 64ea3019f6aeed80a407789c976956f996a4e411 Mon Sep 17 00:00:00 2001 From: evelynwei Date: Wed, 18 Dec 2024 15:40:07 +0800 Subject: [PATCH 3/3] refactor: fix golint --- pkg/cache/config_cache.go | 4 ++-- pkg/cache/service_cache.go | 4 ++-- pkg/controller/endpoint.go | 2 +- pkg/polarisapi/config_api.go | 4 ++-- pkg/polarisapi/service_api.go | 8 ++++---- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/pkg/cache/config_cache.go b/pkg/cache/config_cache.go index 8df6efda..cb184de1 100644 --- a/pkg/cache/config_cache.go +++ b/pkg/cache/config_cache.go @@ -40,11 +40,11 @@ func (csm *CachedConfigFileMap) Delete(key string) { func (csm *CachedConfigFileMap) Load(key string) (value *v1.ConfigMap, ok bool) { v, ok := csm.sm.Load(key) if v != nil { - value, ok2 := v.(*v1.ConfigMap) + result, ok2 := v.(*v1.ConfigMap) if !ok2 { ok = false } - return value, ok + return result, ok } return value, ok } diff --git a/pkg/cache/service_cache.go b/pkg/cache/service_cache.go index a9f4f07e..e92f72a6 100644 --- a/pkg/cache/service_cache.go +++ b/pkg/cache/service_cache.go @@ -40,11 +40,11 @@ func (csm *CachedServiceMap) Delete(key string) { func (csm *CachedServiceMap) Load(key string) (value *v1.Service, ok bool) { v, ok := csm.sm.Load(key) if v != nil { - value, ok2 := v.(*v1.Service) + result, ok2 := v.(*v1.Service) if !ok2 { ok = false } - return value, ok + return result, ok } return value, ok } diff --git a/pkg/controller/endpoint.go b/pkg/controller/endpoint.go index eadef2de..813c4e35 100644 --- a/pkg/controller/endpoint.go +++ b/pkg/controller/endpoint.go @@ -192,7 +192,7 @@ func (p *PolarisController) processSyncInstance(service *v1.Service) (err error) fmt.Sprintf("%s Current polaris instance is %v", serviceMsg, currentIPs), fmt.Sprintf("%s addIns %v deleteIns %v updateIns %v", serviceMsg, addIns, deleteIns, updateIns), } - log.SyncNamingScope().Infof(strings.Join(msg, "\n")) + log.SyncNamingScope().Info(strings.Join(msg, "\n")) var addInsErr, deleteInsErr, updateInsErr error diff --git a/pkg/polarisapi/config_api.go b/pkg/polarisapi/config_api.go index 0b99a9df..894cfbc7 100644 --- a/pkg/polarisapi/config_api.go +++ b/pkg/polarisapi/config_api.go @@ -46,7 +46,7 @@ func CreateConfigMap(configMap *v1.ConfigMap) (ConfigResponse, error) { if err != nil { return ConfigResponse{}, err } - if err := releaseConfigMap(req); err != nil { + if err = releaseConfigMap(req); err != nil { return ConfigResponse{}, err } return resp, err @@ -62,7 +62,7 @@ func UpdateConfigMap(configMap *v1.ConfigMap) (ConfigResponse, error) { if err != nil { return ConfigResponse{}, err } - if err := releaseConfigMap(req); err != nil { + if err = releaseConfigMap(req); err != nil { return ConfigResponse{}, err } return resp, err diff --git a/pkg/polarisapi/service_api.go b/pkg/polarisapi/service_api.go index 2fdf68a8..a685c572 100644 --- a/pkg/polarisapi/service_api.go +++ b/pkg/polarisapi/service_api.go @@ -539,7 +539,7 @@ func CreateService(service *v1.Service) (CreateServicesResponse, error) { } if response.Code != ExistedResource { log.SyncNamingScope().Errorf("Failed to create service %s %v", serviceMsg, response.Info) - return response, fmt.Errorf("create namespace failed: " + response.Info) + return response, fmt.Errorf("create namespace failed: %s", response.Info) } } @@ -603,7 +603,7 @@ func CreateServiceAlias(service *v1.Service) (CreateServiceAliasResponse, error) } if response.Code != ExistedResource { log.SyncNamingScope().Errorf("Failed to create service alias %s %v", serviceAliasMsg, response.Info) - return response, fmt.Errorf("create service alias failed: " + response.Info) + return response, fmt.Errorf("create service alias failed: %s", response.Info) } } @@ -648,7 +648,7 @@ func UpdateService(service *v1.Service, request []Service) (int, PutServicesResp return statusCode, PutServicesResponse{}, err } log.SyncNamingScope().Errorf("Failed to update result %s %v", serviceMsg, response.Info) - return statusCode, response, fmt.Errorf("Put service failed: " + response.Info) + return statusCode, response, fmt.Errorf("Put service failed: %s ", response.Info) } return statusCode, response, nil @@ -697,7 +697,7 @@ func CreateNamespaces(namespace string) (CreateNamespacesResponse, error) { if response.Responses == nil || len(response.Responses) == 0 || response.Responses[0].Code != ExistedResource { log.SyncNamingScope().Errorf("Failed to create namespace %s ,error response: %v", namespace, response) - return response, fmt.Errorf("create namespace failed: " + response.Info) + return response, fmt.Errorf("create namespace failed: %s", response.Info) } }