diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 621446cd..7c855f7a 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -1,4 +1,4 @@ -# Tencent is pleased to support the open source community by making Polaris available. +# Tencent is pleased to support the open source community by making polaris-go available. # # Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. # diff --git a/.github/workflows/revive.yml b/.github/workflows/revive.yml index 35ffb27c..580cbc4c 100644 --- a/.github/workflows/revive.yml +++ b/.github/workflows/revive.yml @@ -1,4 +1,4 @@ -# Tencent is pleased to support the open source community by making Polaris available. +# Tencent is pleased to support the open source community by making polaris-go available. # # Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. # diff --git a/.github/workflows/testing.yml b/.github/workflows/testing.yml index 2a3f99f4..c058d99e 100644 --- a/.github/workflows/testing.yml +++ b/.github/workflows/testing.yml @@ -1,4 +1,4 @@ -# Tencent is pleased to support the open source community by making Polaris available. +# Tencent is pleased to support the open source community by making polaris-go available. # # Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. # diff --git a/.golangci.yml b/.golangci.yml index bea7aa3d..4ab1cd85 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,40 +1,65 @@ +## This file contains all available configuration options +## with their default values. + # See https://github.com/golangci/golangci-lint#config-file +# See https://golangci-lint.run/usage/configuration/ + +# Options for analysis running. run: - issues-exit-code: 1 #Default - tests: true #Default - skip-dirs: # 设置要忽略的目录 - - test + # Exit code when at least one issue was found. + # Default: 1 + issues-exit-code: 2 + + # Include test files or not. + # Default: true + tests: false + + # Which dirs to skip: issues from them won't be reported. + # Can use regexp here: `generated.*`, regexp is applied on full path. + # Default value is empty list, + # but default dirs are skipped independently of this option's value (see skip-dirs-use-default). + # "/" will be replaced by current OS file path separator to properly work on Windows. + skip-dirs: + - pkg/model/pb - .*~ - - api/swagger/docs - skip-files: # 设置不需要检查的go源码文件,支持正则匹配 - - ".*.my.go$" - - ".*.pb.go$" - - _test.go + - test + + # Which files to skip: they will be analyzed, but issues from them won't be reported. + # Default value is empty list, + # but there is no need to include all autogenerated files, + # we confidently recognize autogenerated files. + # If it's not please let us know. + # "/" will be replaced by current OS file path separator to properly work on Windows. + skip-files: + - ".*\\.my\\.go$" + - ".*\\.pb\\.go$" + - ".*_test\\.go$" + + +# Main linters configurations. +# See https://golangci-lint.run/usage/linters linters: - # Disable everything by default so upgrades to not include new "default - # enabled" linters. + # Disable all default enabled linters. disable-all: true - # Specifically enable linters we want to use. + # Custom enable linters we want to use. enable: -# - deadcode -# - errcheck - - funlen - - gocritic - - gocyclo - - gofmt - - goimports - - gosimple - - govet - - godot -# - ineffassign - - misspell - - revive -# - staticcheck -# - structcheck - - typecheck -# - unused -# - varcheck + - errcheck # Errcheck is a program for checking for unchecked errors in go programs. + - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted. + - funlen # Tool for detection of long functions + - gci # Gci controls golang package import order and makes it always deterministic. + - goconst # Finds repeated strings that could be replaced by a constant + - gocritic # Provides diagnostics that check for bugs, performance and style issues. + - gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification + - gosimple # Linter for Go source code that specializes in simplifying code + - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string + - misspell # Finds commonly misspelled English words in comments + - nolintlint # Reports ill-formed or insufficient nolint directives + - revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. + - staticcheck # It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary. + - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code + - usestdlibvars # A linter that detect the possibility to use variables/constants from the Go standard library. + - whitespace # Tool for detection of leading and trailing whitespace issues: @@ -44,56 +69,43 @@ issues: text: "context.Context should be the first parameter of a function" linters: - revive - - gomnd # Yes, they are, but it's okay in a test - path: _test\.go text: "exported func.*returns unexported type.*which can be annoying to use" linters: - revive - # https://github.com/go-critic/go-critic/issues/926 - linters: - gocritic text: "unnecessaryDefer:" + +# https://golangci-lint.run/usage/linters linters-settings: + # https://golangci-lint.run/usage/linters/#misspell misspell: locale: US ignore-words: - cancelled - goimports: - local-prefixes: github.com/polarismesh/polaris-go - godot: - # Comments to be checked: `declarations`, `toplevel`, or `all`. - # Default: declarations - scope: toplevel - exclude: - # Exclude sentence fragments for lists. - - '^[ ]*[-•]' - # Exclude sentences prefixing a list. - - ':$' - # Check that each sentence ends with a period. - # Default: true - period: false - # Check that each sentence starts with a capital letter. - # Default: false - capital: false + + # https://golangci-lint.run/usage/linters/#revive revive: ignore-generated-header: true - severity: warning + severity: error rules: - name: atomic - name: line-length-limit severity: error - arguments: [180] + arguments: [ 380 ] - name: unhandled-error - arguments : ["fmt.Printf", "myFunction", "builder.WriteString","buf.WriteByte","buf.WriteRune","buf.WriteString","buf.WriteTo","buf.Write","fmt.Println","iteratorInstancesProc","buffer.Write","buffer.WriteString","h.Write","fmt.Fprintf","io.WriteString","e.reportAPIStat","f.Close"] severity: warning + disabled: true + arguments: [ "fmt.Printf", "myFunction" ] - name: var-naming severity: warning disabled: true arguments: - - [ "ID","URL","IP","HTTP","JSON","API","UID","Id","Api","Uid","Http","Json","Ip","Url","maxQps","ErrorCodeRpcError","ErrorCodeRpcTimeout","Ttl"] # AllowList + - [ "ID","URL","IP","HTTP","JSON","API","UID","Id","Api","Uid","Http","Json","Ip","Url" ] # AllowList - [ "VM" ] # DenyList - name: string-format severity: warning @@ -112,15 +124,48 @@ linters-settings: severity: warning disabled: false arguments: [ 4 ] + - name: import-shadowing + severity: warning + disabled: false + arguments: [ "github.com/ory/x/logrusx" ] + - name: waitgroup-by-value + severity: warning + disabled: false + - name: max-public-structs + severity: warning + disabled: false + arguments: [ 35 ] + - name: indent-error-flow + severity: warning + disabled: false + - name: function-length + severity: warning + disabled: false + arguments: [ 70,0 ] + - name: file-header + arguments: ["Tencent is pleased to support the open source community by making polaris-go available."] + - name: exported + severity: warning + disabled: true + - name: errorf + severity: warning + disabled: false + - name: error-naming + severity: warning + disabled: false + + # https://golangci-lint.run/usage/linters/#funlen funlen: # Checks the number of lines in a function. # If lower than 0, disable the check. # Default: 60 - lines: 120 + lines: 330 # Checks the number of statements in a function. # If lower than 0, disable the check. # Default: 40 statements: -1 + + # https://golangci-lint.run/usage/linters/#goconst goconst: # Minimal length of string constant. # Default: 3 @@ -128,7 +173,7 @@ linters-settings: # Minimum occurrences of constant string count to trigger issue. # Default: 3 # For subsequent optimization, the value is reduced. - min-occurrences: 3 + min-occurrences: 30 # Ignore test files. # Default: false ignore-tests: true @@ -140,25 +185,27 @@ linters-settings: numbers: true # Minimum value, only works with goconst.numbers # Default: 3 - min: 3 + min: 5 # Maximum value, only works with goconst.numbers # Default: 3 - max: 3 + max: 20 # Ignore when constant is not used as function argument. # Default: true ignore-calls: false + + # https://golangci-lint.run/usage/linters/#gocritic gocritic: disabled-checks: - ifElseChain - assignOp - appendAssign - singleCaseSwitch + - regexpMust + - typeSwitchVar + - elseif - badCall - - underef - gocyclo: - # Minimal code complexity to report. - # Default: 30 (but we recommend 10-20) - min-complexity: 30 + + # https://golangci-lint.run/usage/linters/#gosimple gosimple: # Select the Go version to target. # Default: 1.13 @@ -166,4 +213,131 @@ linters-settings: go: "1.15" # Sxxxx checks in https://staticcheck.io/docs/configuration/options/#checks # Default: ["*"] - checks: ["all","-S1001","-S1000","-S1025"] \ No newline at end of file + checks: [ + "all", "-S1000", "-S1001", "-S1002", "-S1008", "-S1009", "-S1016", "-S1023", "-S1025", "-S1029", "-S1034", "-S1040","-S1019" + ] + + # https://golangci-lint.run/usage/linters/#govet + govet: + # Report about shadowed variables. + # Default: false + check-shadowing: true + # Settings per analyzer. + settings: + # Analyzer name, run `go tool vet help` to see all analyzers. + printf: + # Comma-separated list of print function names to check (in addition to default, see `go tool vet help printf`). + # Default: [] + funcs: + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf + # shadow: + # Whether to be strict about shadowing; can be noisy. + # Default: false + # strict: false + unusedresult: + # Comma-separated list of functions whose results must be used + # (in addition to defaults context.WithCancel,context.WithDeadline,context.WithTimeout,context.WithValue, + # errors.New,fmt.Errorf,fmt.Sprint,fmt.Sprintf,sort.Reverse) + # Default [] + funcs: + - pkg.MyFunc + - context.WithCancel + # Comma-separated list of names of methods of type func() string whose results must be used + # (in addition to default Error,String) + # Default [] + stringmethods: + - MyMethod + # Enable all analyzers. + # Default: false + enable-all: true + # Disable analyzers by name. + # Run `go tool vet help` to see all analyzers. + # Default: [] + disable: + - asmdecl + - assign + - atomic + - atomicalign + - bools + - buildtag + - cgocall + - composites + - copylocks + - deepequalerrors + - errorsas + - fieldalignment + - findcall + - framepointer + - httpresponse + - ifaceassert + - loopclosure + - lostcancel + - nilfunc + - nilness + - reflectvaluecompare + - shift + - shadow + - sigchanyzer + - sortslice + - stdmethods + - stringintconv + - structtag + - testinggoroutine + - tests + - unmarshal + - unreachable + - unsafeptr + - unusedwrite + + # https://golangci-lint.run/usage/linters/#staticcheck + staticcheck: + # Select the Go version to target. + # Default: "1.13" + # Deprecated: use the global `run.go` instead. + go: "1.15" + # SAxxxx checks in https://staticcheck.io/docs/configuration/options/#checks + # Default: ["*"] + checks: [ "all","-SA1019","-SA4015","-SA1029","-SA1016","-SA9003","-SA4006","-SA6003","-SA1004","-SA4009","-SA6002","-SA4017","-SA4021" ] + + # https://golangci-lint.run/usage/linters/#gofmt + gofmt: + # Simplify code: gofmt with `-s` option. + # Default: true + simplify: true + # Apply the rewrite rules to the source before reformatting. + # https://pkg.go.dev/cmd/gofmt + # Default: [] + rewrite-rules: [] + + #https://golangci-lint.run/usage/linters/#gci + gci: + # Section configuration to compare against. + # Section names are case-insensitive and may contain parameters in (). + # The default order of sections is `standard > default > custom > blank > dot`, + # If `custom-order` is `true`, it follows the order of `sections` option. + # Default: ["standard", "default"] + sections: + - standard # Standard section: captures all standard packages. + - default # Default section: contains all imports that could not be matched to another section type. + - prefix(github.com/polarismesh/polaris-go) # Custom section: groups all imports with the specified Prefix. + - blank # Blank section: contains all blank imports. This section is not present unless explicitly enabled. + - dot # Dot section: contains all dot imports. This section is not present unless explicitly enabled. + # Skip generated files. + # Default: true + skip-generated: true + # Enable custom order of sections. + # If `true`, make the section order the same as the order of `sections`. + # Default: false + custom-order: true + + # https://golangci-lint.run/usage/linters/#whitespace + whitespace: + # Enforces newlines (or comments) after every multi-line if statement. + # Default: false + multi-if: false + # Enforces newlines (or comments) after every multi-line function signature. + # Default: false + multi-func: false \ No newline at end of file diff --git a/api.go b/api.go index 737afbb8..f83e7c63 100644 --- a/api.go +++ b/api.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/api/config.go b/api/config.go index 20d24c7e..ceb0e1a8 100644 --- a/api/config.go +++ b/api/config.go @@ -38,8 +38,9 @@ import ( "github.com/polarismesh/polaris-go/pkg/network" "github.com/polarismesh/polaris-go/pkg/plugin" "github.com/polarismesh/polaris-go/pkg/plugin/common" - _ "github.com/polarismesh/polaris-go/pkg/plugin/register" "github.com/polarismesh/polaris-go/pkg/version" + + _ "github.com/polarismesh/polaris-go/pkg/plugin/register" ) const ( diff --git a/api/config_file.go b/api/config_file.go index b3306192..b68e7dbf 100644 --- a/api/config_file.go +++ b/api/config_file.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/api/config_file_impl.go b/api/config_file_impl.go index 8c3f20bf..42574eec 100644 --- a/api/config_file_impl.go +++ b/api/config_file_impl.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/api/consumer_impl.go b/api/consumer_impl.go index 8f2d3bf5..6d655702 100644 --- a/api/consumer_impl.go +++ b/api/consumer_impl.go @@ -26,6 +26,7 @@ import ( "github.com/polarismesh/polaris-go/pkg/config" "github.com/polarismesh/polaris-go/pkg/flow/data" "github.com/polarismesh/polaris-go/pkg/model" + _ "github.com/polarismesh/polaris-go/pkg/plugin/register" ) diff --git a/api/log.go b/api/log.go index f43786e9..e1d36130 100644 --- a/api/log.go +++ b/api/log.go @@ -24,6 +24,7 @@ import ( "github.com/hashicorp/go-multierror" "github.com/polarismesh/polaris-go/pkg/log" + _ "github.com/polarismesh/polaris-go/pkg/plugin/register" ) diff --git a/api/provider_impl.go b/api/provider_impl.go index 89e6d72e..c7b7b46b 100644 --- a/api/provider_impl.go +++ b/api/provider_impl.go @@ -20,6 +20,7 @@ package api import ( "github.com/polarismesh/polaris-go/pkg/config" "github.com/polarismesh/polaris-go/pkg/model" + _ "github.com/polarismesh/polaris-go/pkg/plugin/register" ) diff --git a/api_config.go b/api_config.go index a52d9a2d..ee675f05 100644 --- a/api_config.go +++ b/api_config.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/api_consumer.go b/api_consumer.go index 1f28896c..d04b2a0b 100644 --- a/api_consumer.go +++ b/api_consumer.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/api_limiter.go b/api_limiter.go index efccb451..4cf03327 100644 --- a/api_limiter.go +++ b/api_limiter.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/api_provider.go b/api_provider.go index 759645f0..458bef61 100644 --- a/api_provider.go +++ b/api_provider.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/api_router.go b/api_router.go index 2353efa7..33162c84 100644 --- a/api_router.go +++ b/api_router.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/benchmark/benchmain/main.go b/benchmark/benchmain/main.go index dd8c0a26..1b8f8772 100644 --- a/benchmark/benchmain/main.go +++ b/benchmark/benchmain/main.go @@ -363,7 +363,7 @@ func makeFuncSync(bf stats.Features) (rpcCallFunc, rpcCleanupFunc) { result := ctx.data[1].(*api.ServiceCallResult) result.CalledInstance = instance result.RetStatus = model.RetSuccess - tc.UpdateServiceCallResult(result) + _ = tc.UpdateServiceCallResult(result) }, cleanup } diff --git a/benchmark/stats/stats.go b/benchmark/stats/stats.go index c6a4a85c..1df265d7 100644 --- a/benchmark/stats/stats.go +++ b/benchmark/stats/stats.go @@ -132,13 +132,13 @@ type RunData struct { type durationSlice []time.Duration -// Len +// Len . func (a durationSlice) Len() int { return len(a) } -// Swap +// Swap . func (a durationSlice) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -// Less +// Less . func (a durationSlice) Less(i, j int) bool { return a[i] < a[j] } // Stats is a helper for gathering statistics about individual benchmark runs. diff --git a/pkg/algorithm/rand/scalable_rand.go b/pkg/algorithm/rand/scalable_rand.go index 92a0e67f..88708178 100644 --- a/pkg/algorithm/rand/scalable_rand.go +++ b/pkg/algorithm/rand/scalable_rand.go @@ -15,6 +15,7 @@ * specific language governing permissions and limitations under the License. */ +// Package rand random digit package rand import ( diff --git a/pkg/algorithm/search/search.go b/pkg/algorithm/search/search.go index 961bd5f7..bcf75cca 100644 --- a/pkg/algorithm/search/search.go +++ b/pkg/algorithm/search/search.go @@ -15,6 +15,7 @@ * specific language governing permissions and limitations under the License. */ +// Package search . package search // SearchableSlice 可搜索的数组 diff --git a/pkg/config/ratelimiter.go b/pkg/config/ratelimiter.go index cf4d21ff..bf12756e 100644 --- a/pkg/config/ratelimiter.go +++ b/pkg/config/ratelimiter.go @@ -38,7 +38,7 @@ type RateLimitConfigImpl struct { // LimiterNamespace 限流服务的命名空间 LimiterNamespace string `yaml:"limiterNamespace" json:"limiterNamespace"` // LimiterService 限流服务的服务名 - LimiterService string `yaml:"limiterService" json:"limiterService "` + LimiterService string `yaml:"limiterService" json:"limiterService"` } // IsEnable 是否启用限流能力. diff --git a/pkg/flow/configuration/factory.go b/pkg/flow/configuration/factory.go index 695b2b1f..53ea4cb6 100644 --- a/pkg/flow/configuration/factory.go +++ b/pkg/flow/configuration/factory.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/flow/configuration/manager.go b/pkg/flow/configuration/manager.go index 71172f84..ce55aa4b 100644 --- a/pkg/flow/configuration/manager.go +++ b/pkg/flow/configuration/manager.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/flow/configuration/model.go b/pkg/flow/configuration/model.go index 0360d527..06e62740 100644 --- a/pkg/flow/configuration/model.go +++ b/pkg/flow/configuration/model.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/flow/configuration/remote/config.go b/pkg/flow/configuration/remote/config.go index 0cf37987..db25797c 100644 --- a/pkg/flow/configuration/remote/config.go +++ b/pkg/flow/configuration/remote/config.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * @@ -36,7 +36,9 @@ const ( ) var configFileRepos []*ConfigFileRepo + var startCheckVersionOnce = new(sync.Once) + var stopCheckVersionTask context.CancelFunc // ConfigFileRepo 服务端配置文件代理类,从服务端拉取配置并同步数据 @@ -58,7 +60,6 @@ type ConfigFileRepoChangeListener func(configFileMetadata model.ConfigFileMetada func NewConfigFileRepo(metadata model.ConfigFileMetadata, connector configconnector.ConfigConnector, configuration config.Configuration) (*ConfigFileRepo, error) { - repo := &ConfigFileRepo{ connector: connector, configuration: configuration, diff --git a/pkg/flow/configuration/remote/polling.go b/pkg/flow/configuration/remote/polling.go index 7f3c0209..e7c95c37 100644 --- a/pkg/flow/configuration/remote/polling.go +++ b/pkg/flow/configuration/remote/polling.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/flow/configuration/remote/retry_policy.go b/pkg/flow/configuration/remote/retry_policy.go index 4ac4df49..2f456196 100644 --- a/pkg/flow/configuration/remote/retry_policy.go +++ b/pkg/flow/configuration/remote/retry_policy.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/flow/configuration/remote/type.go b/pkg/flow/configuration/remote/type.go index eaa70acf..441fd503 100644 --- a/pkg/flow/configuration/remote/type.go +++ b/pkg/flow/configuration/remote/type.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/flow/configuration/service.go b/pkg/flow/configuration/service.go index d77cf0ce..23103d18 100644 --- a/pkg/flow/configuration/service.go +++ b/pkg/flow/configuration/service.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * @@ -34,12 +34,12 @@ type ConfigFileService struct { } var configFileService *ConfigFileService + var once = new(sync.Once) // NewConfigFileService 创建配置中心服务 func NewConfigFileService(connector configconnector.ConfigConnector, configuration config.Configuration) *ConfigFileService { - once.Do(func() { configFileService = &ConfigFileService{ connector: connector, diff --git a/pkg/flow/configuration/util/cache_key.go b/pkg/flow/configuration/util/cache_key.go index b8bea1f7..9ecaf627 100644 --- a/pkg/flow/configuration/util/cache_key.go +++ b/pkg/flow/configuration/util/cache_key.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/flow/data/util.go b/pkg/flow/data/util.go index d9b64f65..3dcc94f0 100644 --- a/pkg/flow/data/util.go +++ b/pkg/flow/data/util.go @@ -21,8 +21,6 @@ import ( "fmt" "time" - "github.com/polarismesh/polaris-go/pkg/plugin/configconnector" - "github.com/polarismesh/polaris-go/pkg/clock" "github.com/polarismesh/polaris-go/pkg/config" "github.com/polarismesh/polaris-go/pkg/log" @@ -30,6 +28,7 @@ import ( "github.com/polarismesh/polaris-go/pkg/plugin" "github.com/polarismesh/polaris-go/pkg/plugin/circuitbreaker" "github.com/polarismesh/polaris-go/pkg/plugin/common" + "github.com/polarismesh/polaris-go/pkg/plugin/configconnector" "github.com/polarismesh/polaris-go/pkg/plugin/healthcheck" "github.com/polarismesh/polaris-go/pkg/plugin/loadbalancer" "github.com/polarismesh/polaris-go/pkg/plugin/localregistry" diff --git a/pkg/flow/impl.go b/pkg/flow/impl.go index 2ba9804c..ae095793 100644 --- a/pkg/flow/impl.go +++ b/pkg/flow/impl.go @@ -341,8 +341,7 @@ func (e *Engine) SyncReportStat(typ model.MetricType, stat model.InstanceGauge) } if len(e.reporterChain) > 0 { for _, reporter := range e.reporterChain { - err := reporter.ReportStat(typ, stat) - if err != nil { + if err := reporter.ReportStat(typ, stat); err != nil { return err } } diff --git a/pkg/flow/quota/remote.go b/pkg/flow/quota/remote.go index de565236..f0565d13 100644 --- a/pkg/flow/quota/remote.go +++ b/pkg/flow/quota/remote.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/flow/router_flow.go b/pkg/flow/router_flow.go index f3372ea9..b5b2ed74 100644 --- a/pkg/flow/router_flow.go +++ b/pkg/flow/router_flow.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/flow/sync_flow.go b/pkg/flow/sync_flow.go index af50cd2a..d6fd2ec9 100644 --- a/pkg/flow/sync_flow.go +++ b/pkg/flow/sync_flow.go @@ -364,7 +364,9 @@ func (e *Engine) doSyncRegister(instance *model.InstanceRegisterRequest, header }, RetStatus: model.RetSuccess, } - defer e.reportAPIStat(apiCallResult) + defer func() { + _ = e.reportAPIStat(apiCallResult) + }() param := &model.ControlParam{} data.BuildControlParam(instance, e.configuration, param) // 方法开始时间 @@ -399,7 +401,9 @@ func (e *Engine) SyncDeregister(instance *model.InstanceDeRegisterRequest) error }, RetStatus: model.RetSuccess, } - defer e.reportAPIStat(apiCallResult) + defer func() { + _ = e.reportAPIStat(apiCallResult) + }() param := &model.ControlParam{} data.BuildControlParam(instance, e.configuration, param) // 方法开始时间 @@ -427,7 +431,9 @@ func (e *Engine) SyncHeartbeat(instance *model.InstanceHeartbeatRequest) error { }, RetStatus: model.RetSuccess, } - defer e.reportAPIStat(apiCallResult) + defer func() { + _ = e.reportAPIStat(apiCallResult) + }() param := &model.ControlParam{} data.BuildControlParam(instance, e.configuration, param) // 方法开始时间 diff --git a/pkg/model/argument.go b/pkg/model/argument.go index 5dc1fe01..da1ff0a8 100644 --- a/pkg/model/argument.go +++ b/pkg/model/argument.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/model/config.go b/pkg/model/config.go index 5c80cade..c1a13e0f 100644 --- a/pkg/model/config.go +++ b/pkg/model/config.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/model/instance_impl.go b/pkg/model/instance_impl.go index cbfb0d91..a290346b 100644 --- a/pkg/model/instance_impl.go +++ b/pkg/model/instance_impl.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/model/pb/metric/polaris_metric.pb.go b/pkg/model/pb/metric/polaris_metric.pb.go index cdd389d0..153753c8 100644 --- a/pkg/model/pb/metric/polaris_metric.pb.go +++ b/pkg/model/pb/metric/polaris_metric.pb.go @@ -6,11 +6,13 @@ Package metric is a generated protocol buffer package. It is generated from these files: + polaris_metric.proto polaris_metric_api.proto polaris_ratelimit.proto It has these top-level messages: + MetricDimension MetricKey MetricInitRequest @@ -23,10 +25,13 @@ It has these top-level messages: */ package metric -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import google_protobuf "github.com/golang/protobuf/ptypes/wrappers" +import ( + "fmt" + "math" + + "github.com/golang/protobuf/proto" + google_protobuf "github.com/golang/protobuf/ptypes/wrappers" +) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal diff --git a/pkg/model/pb/metric/polaris_ratelimit.pb.go b/pkg/model/pb/metric/polaris_ratelimit.pb.go index 1b75253a..e64493c4 100644 --- a/pkg/model/pb/metric/polaris_ratelimit.pb.go +++ b/pkg/model/pb/metric/polaris_ratelimit.pb.go @@ -6,20 +6,25 @@ Package metric is a generated protocol buffer package. It is generated from these files: + polaris_ratelimit.proto It has these top-level messages: + RateLimitRequest RateLimitResponse Limiter */ package metric -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import google_protobuf "github.com/golang/protobuf/ptypes/wrappers" -import google_protobuf1 "github.com/golang/protobuf/ptypes/duration" +import ( + "fmt" + "math" + + "github.com/golang/protobuf/proto" + google_protobuf1 "github.com/golang/protobuf/ptypes/duration" + google_protobuf "github.com/golang/protobuf/ptypes/wrappers" +) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal diff --git a/pkg/model/router.go b/pkg/model/router.go index 89d309f8..7da7b802 100644 --- a/pkg/model/router.go +++ b/pkg/model/router.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/model/service_impl.go b/pkg/model/service_impl.go index 345df8a3..89f86480 100644 --- a/pkg/model/service_impl.go +++ b/pkg/model/service_impl.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/model/util.go b/pkg/model/util.go index c96a8a68..84fdd573 100644 --- a/pkg/model/util.go +++ b/pkg/model/util.go @@ -219,9 +219,7 @@ func ReplaceHomeVar(path string) string { // PathExist 查看文件路径是否存在 func PathExist(path string) bool { - _, err := os.Stat(path) - if err != nil { - + if _, err := os.Stat(path); err != nil { return os.IsExist(err) } return true diff --git a/pkg/model/util_test.go b/pkg/model/util_test.go index 7f9d2f59..54f2c91d 100644 --- a/pkg/model/util_test.go +++ b/pkg/model/util_test.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/plugin/configconnector/proxy.go b/pkg/plugin/configconnector/proxy.go index c8aa8f31..09fc39d8 100644 --- a/pkg/plugin/configconnector/proxy.go +++ b/pkg/plugin/configconnector/proxy.go @@ -31,8 +31,8 @@ type Proxy struct { } // SetRealPlugin set real plugin -func (p *Proxy) SetRealPlugin(plugin plugin.Plugin, engine model.Engine) { - p.ConfigConnector = plugin.(ConfigConnector) +func (p *Proxy) SetRealPlugin(pg plugin.Plugin, engine model.Engine) { + p.ConfigConnector = pg.(ConfigConnector) p.engine = engine } diff --git a/pkg/plugin/ratelimiter/model.go b/pkg/plugin/ratelimiter/model.go index dc421d4d..10b7892b 100644 --- a/pkg/plugin/ratelimiter/model.go +++ b/pkg/plugin/ratelimiter/model.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/pkg/plugin/register/plugins.go b/pkg/plugin/register/plugins.go index d90434ce..c377c11e 100644 --- a/pkg/plugin/register/plugins.go +++ b/pkg/plugin/register/plugins.go @@ -31,46 +31,4 @@ import ( _ "github.com/polarismesh/polaris-go/pkg/plugin/statreporter" _ "github.com/polarismesh/polaris-go/pkg/plugin/subscribe" _ "github.com/polarismesh/polaris-go/pkg/plugin/weightadjuster" - - // 注册具体插件实例 - _ "github.com/polarismesh/polaris-go/plugin/alarmreporter/file" - _ "github.com/polarismesh/polaris-go/plugin/circuitbreaker/errorcheck" - _ "github.com/polarismesh/polaris-go/plugin/circuitbreaker/errorcount" - _ "github.com/polarismesh/polaris-go/plugin/circuitbreaker/errorrate" - _ "github.com/polarismesh/polaris-go/plugin/configconnector/polaris" - _ "github.com/polarismesh/polaris-go/plugin/healthcheck/http" - _ "github.com/polarismesh/polaris-go/plugin/healthcheck/tcp" - _ "github.com/polarismesh/polaris-go/plugin/loadbalancer/hash" - _ "github.com/polarismesh/polaris-go/plugin/loadbalancer/maglev" - _ "github.com/polarismesh/polaris-go/plugin/loadbalancer/ringhash" - _ "github.com/polarismesh/polaris-go/plugin/loadbalancer/weightedrandom" - _ "github.com/polarismesh/polaris-go/plugin/localregistry/inmemory" - _ "github.com/polarismesh/polaris-go/plugin/logger/zaplog" - _ "github.com/polarismesh/polaris-go/plugin/ratelimiter/reject" - _ "github.com/polarismesh/polaris-go/plugin/ratelimiter/unirate" - _ "github.com/polarismesh/polaris-go/plugin/serverconnector/grpc" - - // 注册服务路由 servicerouter 插件 - _ "github.com/polarismesh/polaris-go/plugin/servicerouter/canary" - _ "github.com/polarismesh/polaris-go/plugin/servicerouter/dstmeta" - _ "github.com/polarismesh/polaris-go/plugin/servicerouter/filteronly" - _ "github.com/polarismesh/polaris-go/plugin/servicerouter/nearbybase" - _ "github.com/polarismesh/polaris-go/plugin/servicerouter/rulebase" - _ "github.com/polarismesh/polaris-go/plugin/servicerouter/setdivision" - - _ "github.com/polarismesh/polaris-go/plugin/subscribe/localchannel" - _ "github.com/polarismesh/polaris-go/plugin/weightadjuster/ratedelay" - - // 注册可观性 statreporter 插件 - // prometheus 插件 - _ "github.com/polarismesh/polaris-go/plugin/statreporter/prometheus" - - // 注册 report 插件 - _ "github.com/polarismesh/polaris-go/plugin/reporthandler/clientid" - _ "github.com/polarismesh/polaris-go/plugin/reporthandler/location" - _ "github.com/polarismesh/polaris-go/plugin/reporthandler/statreporter" - - // 注册 location 地址插件 - _ "github.com/polarismesh/polaris-go/plugin/cmdb/env" - _ "github.com/polarismesh/polaris-go/plugin/cmdb/tencent" ) diff --git a/pkg/plugin/register/plugins_implemente.go b/pkg/plugin/register/plugins_implemente.go new file mode 100644 index 00000000..45cfe96f --- /dev/null +++ b/pkg/plugin/register/plugins_implemente.go @@ -0,0 +1,50 @@ +/** + * Tencent is pleased to support the open source community by making polaris-go available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 register + +import ( + // 注册具体插件实例 + _ "github.com/polarismesh/polaris-go/plugin/alarmreporter/file" + _ "github.com/polarismesh/polaris-go/plugin/circuitbreaker/errorcheck" + _ "github.com/polarismesh/polaris-go/plugin/circuitbreaker/errorcount" + _ "github.com/polarismesh/polaris-go/plugin/circuitbreaker/errorrate" + _ "github.com/polarismesh/polaris-go/plugin/configconnector/polaris" + _ "github.com/polarismesh/polaris-go/plugin/healthcheck/http" + _ "github.com/polarismesh/polaris-go/plugin/healthcheck/tcp" + _ "github.com/polarismesh/polaris-go/plugin/loadbalancer/hash" + _ "github.com/polarismesh/polaris-go/plugin/loadbalancer/maglev" + _ "github.com/polarismesh/polaris-go/plugin/loadbalancer/ringhash" + _ "github.com/polarismesh/polaris-go/plugin/loadbalancer/weightedrandom" + _ "github.com/polarismesh/polaris-go/plugin/localregistry/inmemory" + _ "github.com/polarismesh/polaris-go/plugin/logger/zaplog" + _ "github.com/polarismesh/polaris-go/plugin/ratelimiter/reject" + _ "github.com/polarismesh/polaris-go/plugin/ratelimiter/unirate" + _ "github.com/polarismesh/polaris-go/plugin/reporthandler/clientid" + _ "github.com/polarismesh/polaris-go/plugin/reporthandler/location" + _ "github.com/polarismesh/polaris-go/plugin/reporthandler/statreporter" + _ "github.com/polarismesh/polaris-go/plugin/serverconnector/grpc" + _ "github.com/polarismesh/polaris-go/plugin/servicerouter/canary" + _ "github.com/polarismesh/polaris-go/plugin/servicerouter/dstmeta" + _ "github.com/polarismesh/polaris-go/plugin/servicerouter/filteronly" + _ "github.com/polarismesh/polaris-go/plugin/servicerouter/nearbybase" + _ "github.com/polarismesh/polaris-go/plugin/servicerouter/rulebase" + _ "github.com/polarismesh/polaris-go/plugin/servicerouter/setdivision" + _ "github.com/polarismesh/polaris-go/plugin/statreporter/prometheus" + _ "github.com/polarismesh/polaris-go/plugin/subscribe/localchannel" + _ "github.com/polarismesh/polaris-go/plugin/weightadjuster/ratedelay" +) diff --git a/pkg/plugin/register/plugins_location.go b/pkg/plugin/register/plugins_location.go new file mode 100644 index 00000000..ac890fd1 --- /dev/null +++ b/pkg/plugin/register/plugins_location.go @@ -0,0 +1,24 @@ +/** + * Tencent is pleased to support the open source community by making polaris-go available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 register + +import ( + // 注册 location 地址插件 + _ "github.com/polarismesh/polaris-go/plugin/cmdb/env" + _ "github.com/polarismesh/polaris-go/plugin/cmdb/tencent" +) diff --git a/pkg/plugin/servicerouter/proxy.go b/pkg/plugin/servicerouter/proxy.go index ed7af7a4..284247f9 100644 --- a/pkg/plugin/servicerouter/proxy.go +++ b/pkg/plugin/servicerouter/proxy.go @@ -93,7 +93,7 @@ func (p *Proxy) reportRouteStat(routeInfo *RouteInfo, errCode model.ErrCode, gauge.Status = res.Status } - p.engine.SyncReportStat(model.RouteStat, gauge) + _ = p.engine.SyncReportStat(model.RouteStat, gauge) poolPutRouteStat(gauge) } diff --git a/pkg/plugin/servicerouter/util.go b/pkg/plugin/servicerouter/util.go index 4cc299b5..6da90d08 100644 --- a/pkg/plugin/servicerouter/util.go +++ b/pkg/plugin/servicerouter/util.go @@ -141,7 +141,7 @@ func GetFilterCluster(ctx model.ValueContext, routers []ServiceRouter, routeInfo EventObject: result.OutputCluster, } for _, h := range handlers { - h.Callback(eventObj) + _ = h.Callback(eventObj) } } } diff --git a/plugin/configconnector/polaris/config_connector.go b/plugin/configconnector/polaris/config_connector.go index 143846b7..fa08ccca 100644 --- a/plugin/configconnector/polaris/config_connector.go +++ b/plugin/configconnector/polaris/config_connector.go @@ -94,7 +94,7 @@ func (c *Connector) Init(ctx *plugin.InitContext) error { // Destroy 销毁插件,可用于释放资源. func (c *Connector) Destroy() error { if nil != c.RunContext { - c.RunContext.Destroy() + _ = c.RunContext.Destroy() } if nil != c.connManager { c.connManager.Destroy() diff --git a/plugin/localregistry/inmemory/inmemory.go b/plugin/localregistry/inmemory/inmemory.go index 6ffae1ab..aa133eee 100644 --- a/plugin/localregistry/inmemory/inmemory.go +++ b/plugin/localregistry/inmemory/inmemory.go @@ -508,9 +508,11 @@ func (g *LocalCache) loadRemoteValue(svcKey *model.ServiceEventKey, handler Cach createHandlers := g.plugins.GetEventSubscribers(common.OnServiceLocalValueCreated) if len(createHandlers) > 0 { event := &common.PluginEvent{ - EventType: common.OnServiceLocalValueCreated, EventObject: actualSvcObject.svcLocalValue} + EventType: common.OnServiceLocalValueCreated, + EventObject: actualSvcObject.svcLocalValue, + } for _, h := range createHandlers { - h.Callback(event) + _ = h.Callback(event) } } } @@ -1088,9 +1090,11 @@ func (g *LocalCache) eliminateExpiredCache() { deleteHandlers := g.plugins.GetEventSubscribers(common.OnServiceDeleted) if len(deleteHandlers) > 0 && !reflect2.IsNil(oldValue) { event := &common.PluginEvent{ - EventType: common.OnServiceDeleted, EventObject: eventObject} + EventType: common.OnServiceDeleted, + EventObject: eventObject, + } for _, handler := range deleteHandlers { - handler.Callback(event) + _ = handler.Callback(event) } } return true diff --git a/plugin/localregistry/inmemory/model.go b/plugin/localregistry/inmemory/model.go index 89c52f46..9b762c9a 100644 --- a/plugin/localregistry/inmemory/model.go +++ b/plugin/localregistry/inmemory/model.go @@ -235,7 +235,7 @@ func (s *CacheObject) notifyServiceAdded(value interface{}) { event := &common.PluginEvent{ EventType: common.OnServiceAdded, EventObject: value} for _, handler := range addHandlers { - handler.Callback(event) + _ = handler.Callback(event) } } } @@ -266,7 +266,7 @@ func (s *CacheObject) OnServiceUpdate(event *serverconnector.ServiceEvent) bool dEvent := &common.PluginEvent{ EventType: common.OnServiceDeleted, EventObject: eventObject} for _, handler := range deleteHandlers { - handler.Callback(dEvent) + _ = handler.Callback(dEvent) } } svcDeleted = true @@ -298,7 +298,7 @@ func (s *CacheObject) OnServiceUpdate(event *serverconnector.ServiceEvent) bool if cachedStatus == CacheChanged && len(updateHandlers) > 0 { uEvent := &common.PluginEvent{EventType: common.OnServiceUpdated, EventObject: eventObject} for _, handler := range updateHandlers { - handler.Callback(uEvent) + _ = handler.Callback(uEvent) } } } else if cachedStatus == CacheEmptyButNoData { diff --git a/plugin/ratelimiter/common/ratelimit_slice_window.go b/plugin/ratelimiter/common/ratelimit_slice_window.go index 8b26c66e..7e9552af 100644 --- a/plugin/ratelimiter/common/ratelimit_slice_window.go +++ b/plugin/ratelimiter/common/ratelimit_slice_window.go @@ -15,6 +15,7 @@ * specific language governing permissions and limitations under the License. */ +// Package common . package common import ( diff --git a/plugin/ratelimiter/reject/bucket.go b/plugin/ratelimiter/reject/bucket.go index 31420e07..f058d254 100644 --- a/plugin/ratelimiter/reject/bucket.go +++ b/plugin/ratelimiter/reject/bucket.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/plugin/ratelimiter/reject/bucket_qps.go b/plugin/ratelimiter/reject/bucket_qps.go index 8d9be42b..8d5dee17 100644 --- a/plugin/ratelimiter/reject/bucket_qps.go +++ b/plugin/ratelimiter/reject/bucket_qps.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/plugin/ratelimiter/reject/reject.go b/plugin/ratelimiter/reject/reject.go index c4bc62c1..e92f9a06 100644 --- a/plugin/ratelimiter/reject/reject.go +++ b/plugin/ratelimiter/reject/reject.go @@ -53,11 +53,7 @@ func (g *RateLimiterReject) Destroy() error { // IsEnable enable func (g *RateLimiterReject) IsEnable(cfg config.Configuration) bool { - if cfg.GetGlobal().GetSystem().GetMode() == model.ModeWithAgent { - return false - } else { - return true - } + return cfg.GetGlobal().GetSystem().GetMode() != model.ModeWithAgent } // InitQuota 初始化并创建限流窗口 diff --git a/plugin/ratelimiter/unirate/bucket_leaky.go b/plugin/ratelimiter/unirate/bucket_leaky.go index e866f057..36d94c62 100644 --- a/plugin/ratelimiter/unirate/bucket_leaky.go +++ b/plugin/ratelimiter/unirate/bucket_leaky.go @@ -1,5 +1,5 @@ /** - * Tencent is pleased to support the open source community by making Polaris available. + * Tencent is pleased to support the open source community by making polaris-go available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * diff --git a/plugin/reporthandler/location/reporthandler.go b/plugin/reporthandler/location/reporthandler.go index 167bcaca..60e2c1fc 100644 --- a/plugin/reporthandler/location/reporthandler.go +++ b/plugin/reporthandler/location/reporthandler.go @@ -133,7 +133,6 @@ func (h *ReportHandler) updateLocation(location *model.Location, lastErr model.S // 等待地域信息就绪 func (h *ReportHandler) waitLocationInfo(event *common.PluginEvent) error { - if h.locationProvider == nil { return nil } diff --git a/plugin/serverconnector/common/discover.go b/plugin/serverconnector/common/discover.go index c0bcb577..65b09a25 100644 --- a/plugin/serverconnector/common/discover.go +++ b/plugin/serverconnector/common/discover.go @@ -811,7 +811,7 @@ func (g *DiscoverConnector) processUpdateTask( // Destroy 销毁插件,可用于释放资源 func (g *DiscoverConnector) Destroy() error { - g.RunContext.Destroy() + _ = g.RunContext.Destroy() return nil } diff --git a/plugin/serverconnector/grpc/operation_async.go b/plugin/serverconnector/grpc/operation_async.go index cc811f64..b5cbc42f 100644 --- a/plugin/serverconnector/grpc/operation_async.go +++ b/plugin/serverconnector/grpc/operation_async.go @@ -108,8 +108,8 @@ func (g *Connector) createDiscoverClient(reqID string, // Destroy 销毁插件,可用于释放资源 func (g *Connector) Destroy() error { - g.RunContext.Destroy() - g.discoverConnector.Destroy() + _ = g.RunContext.Destroy() + _ = g.discoverConnector.Destroy() g.connManager.Destroy() return nil } diff --git a/plugin/serverconnector/grpc/operation_sync.go b/plugin/serverconnector/grpc/operation_sync.go index f8c66141..8559d6e5 100644 --- a/plugin/serverconnector/grpc/operation_sync.go +++ b/plugin/serverconnector/grpc/operation_sync.go @@ -89,9 +89,8 @@ func (g *Connector) RegisterInstance(req *model.InstanceRegisterRequest, header } g.connManager.ReportSuccess(conn.ConnID, int32(serverCodeType), endTime.Sub(startTime)) return nil, model.NewSDKError(model.ErrCodeServerUserError, nil, errMsg) - } else { - g.connManager.ReportSuccess(conn.ConnID, int32(serverCodeType), endTime.Sub(startTime)) } + g.connManager.ReportSuccess(conn.ConnID, int32(serverCodeType), endTime.Sub(startTime)) resp := &model.InstanceRegisterResponse{InstanceID: pbResp.GetInstance().GetId().GetValue(), Existed: namingpb.ExistedResource == pbResp.GetCode().GetValue()} return resp, nil @@ -150,9 +149,8 @@ func (g *Connector) DeregisterInstance(req *model.InstanceDeRegisterRequest) err } g.connManager.ReportSuccess(conn.ConnID, int32(serverCodeType), endTime.Sub(startTime)) return model.NewSDKError(model.ErrCodeServerUserError, nil, errMsg) - } else { - g.connManager.ReportSuccess(conn.ConnID, int32(serverCodeType), endTime.Sub(startTime)) } + g.connManager.ReportSuccess(conn.ConnID, int32(serverCodeType), endTime.Sub(startTime)) return nil } @@ -209,9 +207,8 @@ func (g *Connector) Heartbeat(req *model.InstanceHeartbeatRequest) error { } g.connManager.ReportSuccess(conn.ConnID, int32(serverCodeType), endTime.Sub(startTime)) return model.NewSDKErrorWithServerInfo(model.ErrCodeServerUserError, nil, pbResp.GetCode().GetValue(), pbResp.GetInfo().GetValue(), errMsg) - } else { - g.connManager.ReportSuccess(conn.ConnID, int32(serverCodeType), endTime.Sub(startTime)) } + g.connManager.ReportSuccess(conn.ConnID, int32(serverCodeType), endTime.Sub(startTime)) return nil } @@ -294,9 +291,8 @@ func (g *Connector) ReportClient(req *model.ReportClientRequest) (*model.ReportC } g.connManager.ReportSuccess(conn.ConnID, int32(serverCodeType), endTime.Sub(startTime)) return nil, model.NewSDKError(model.ErrCodeServerUserError, nil, errMsg) - } else { - g.connManager.ReportSuccess(conn.ConnID, int32(serverCodeType), endTime.Sub(startTime)) } + g.connManager.ReportSuccess(conn.ConnID, int32(serverCodeType), endTime.Sub(startTime)) // 持久化本地信息 if nil != req.PersistHandler { if err = req.PersistHandler(pbResp); err != nil { diff --git a/plugin/serverconnector/sidecar/client/client.go b/plugin/serverconnector/sidecar/client/client.go index 0e90392d..d955f0ef 100644 --- a/plugin/serverconnector/sidecar/client/client.go +++ b/plugin/serverconnector/sidecar/client/client.go @@ -96,11 +96,7 @@ func (c *Connector) Init(ctx *plugin.InitContext) { // IsEnable enable func (c *Connector) IsEnable(cfg config.Configuration) bool { - if cfg.GetGlobal().GetSystem().GetMode() == model.ModeWithAgent { - return true - } else { - return false - } + return cfg.GetGlobal().GetSystem().GetMode() == model.ModeWithAgent } // 原子增加DnsID diff --git a/plugin/serverconnector/sidecar/dns/RR.go b/plugin/serverconnector/sidecar/dns/RR.go index f8375aad..dd45369a 100644 --- a/plugin/serverconnector/sidecar/dns/RR.go +++ b/plugin/serverconnector/sidecar/dns/RR.go @@ -235,7 +235,7 @@ func (rr *PolarisHeaderRR) PackData(buff *bytes.Buffer) (int, error) { } // UnPackData 反序列化RR data -func (rr *PolarisHeaderRR) UnPackData(msg []byte, off int) (int, error) { +func (rr *PolarisHeaderRR) UnPackData(_ []byte, off int) (int, error) { return off, nil } @@ -259,11 +259,11 @@ func (rr *LocationRR) Header() *RR_Header { // PackData 序列化 RR data func (rr *LocationRR) PackData(buff *bytes.Buffer) (int, error) { oldLen := buff.Len() - bytes, err := proto.Marshal(rr.SideCar) + marshal, err := proto.Marshal(rr.SideCar) if err != nil { return 0, err } - _, err = buff.Write(bytes) + _, err = buff.Write(marshal) if err != nil { return 0, err } @@ -332,11 +332,11 @@ func (rr *DetailErrInfoRR) Header() *RR_Header { func (rr *DetailErrInfoRR) PackData(buff *bytes.Buffer) (int, error) { oldLen := buff.Len() - bytes, err := proto.Marshal(rr.ErrInfo) + marshal, err := proto.Marshal(rr.ErrInfo) if err != nil { return 0, err } - _, err = buff.Write(bytes) + _, err = buff.Write(marshal) if err != nil { return 0, err } @@ -346,11 +346,11 @@ func (rr *DetailErrInfoRR) PackData(buff *bytes.Buffer) (int, error) { // UnPackData 反序列化RR data func (rr *DetailErrInfoRR) UnPackData(msg []byte, off int) (int, error) { length := rr.Hdr.Rdlength - bytes := msg[off : off+int(length)] + b := msg[off : off+int(length)] off += int(length) rr.ErrInfo = new(sidecarPb.DetailErrInfo) - err := proto.Unmarshal(bytes, rr.ErrInfo) + err := proto.Unmarshal(b, rr.ErrInfo) if err != nil { return off, err } @@ -378,11 +378,11 @@ func (rr *ResponseRR) Header() *RR_Header { func (rr *ResponseRR) PackData(buff *bytes.Buffer) (int, error) { oldLen := buff.Len() - bytes, err := proto.Marshal(rr.Response) + marshal, err := proto.Marshal(rr.Response) if err != nil { return 0, err } - _, err = buff.Write(bytes) + _, err = buff.Write(marshal) if err != nil { return 0, err } diff --git a/plugin/serverconnector/sidecar/model/pb/sidecar.pb.go b/plugin/serverconnector/sidecar/model/pb/sidecar.pb.go index a9529d9c..fd5907b6 100644 --- a/plugin/serverconnector/sidecar/model/pb/sidecar.pb.go +++ b/plugin/serverconnector/sidecar/model/pb/sidecar.pb.go @@ -6,9 +6,11 @@ Package pb is a generated protocol buffer package. It is generated from these files: + sidecar.proto It has these top-level messages: + GetOneInstanceRequest GetOneInstanceResponse Response diff --git a/plugin/servicerouter/canary/canary_router.go b/plugin/servicerouter/canary/canary_router.go index aaccb815..f13444bc 100644 --- a/plugin/servicerouter/canary/canary_router.go +++ b/plugin/servicerouter/canary/canary_router.go @@ -65,7 +65,6 @@ func (g *CanaryRouterFilter) Destroy() error { // GetFilteredInstances 插件模式进行服务实例过滤,并返回过滤后的实例列表 func (g *CanaryRouterFilter) GetFilteredInstances(routeInfo *servicerouter.RouteInfo, clusters model.ServiceClusters, withinCluster *model.Cluster) (*servicerouter.RouteResult, error) { - // enableCanary := clusters.IsCanaryEnabled() // if !enableCanary { // result := servicerouter.PoolGetRouteResult(g.valueCtx) @@ -73,9 +72,13 @@ func (g *CanaryRouterFilter) GetFilteredInstances(routeInfo *servicerouter.Route // result.OutputCluster = cls // return result, nil // } - canary := routeInfo.Canary - var result *servicerouter.RouteResult - var err error + + var ( + canary = routeInfo.Canary + result *servicerouter.RouteResult + err error + ) + if canary != "" { result, err = g.canaryFilter(canary, clusters, withinCluster) } else { @@ -91,10 +94,9 @@ func (g *CanaryRouterFilter) GetFilteredInstances(routeInfo *servicerouter.Route result.OutputCluster.HasLimitedInstances = true result.Status = servicerouter.DegradeToFilterOnly return result, nil - } else { - routeInfo.SetIgnoreFilterOnlyOnEndChain(true) - return result, nil } + routeInfo.SetIgnoreFilterOnlyOnEndChain(true) + return result, nil } // 带金丝雀标签的处理过滤 diff --git a/plugin/servicerouter/nearbybase/nearby.go b/plugin/servicerouter/nearbybase/nearby.go index e1a2ca18..3289f8c4 100644 --- a/plugin/servicerouter/nearbybase/nearby.go +++ b/plugin/servicerouter/nearbybase/nearby.go @@ -318,7 +318,7 @@ func (g *NearbyBasedInstancesFilter) misMatchError(location *model.Location, out // 等待地域信息就绪 func (g *NearbyBasedInstancesFilter) waitLocationInfo(event *common.PluginEvent) error { if !g.cfg.StrictNearby { - g.valueCtx.WaitLocationInfo(nil, model.LocationInit) + g.valueCtx.WaitLocationInfo(context.TODO(), model.LocationInit) return nil } ctx, cancel := context.WithTimeout(context.Background(), g.locationReadyTimeout) diff --git a/plugin/servicerouter/rulebase/base.go b/plugin/servicerouter/rulebase/base.go index 183d51ca..8e38248b 100644 --- a/plugin/servicerouter/rulebase/base.go +++ b/plugin/servicerouter/rulebase/base.go @@ -359,7 +359,6 @@ func (g *RuleBasedInstancesFilter) matchDstMetadata(routeInfo *servicerouter.Rou } var hasMatchedValue bool for value, composedValue := range metaValues { - m, err := regexObj.FindStringMatch(value) if err != nil { log.GetBaseLogger().Errorf("regex match dst metadata error. ruleMetaValueStr: %s, value: %s, errors: %s", ruleMetaValueStr, value, err) diff --git a/plugin/servicerouter/rulebase/rule.go b/plugin/servicerouter/rulebase/rule.go index 86e93a5c..54b8cac9 100644 --- a/plugin/servicerouter/rulebase/rule.go +++ b/plugin/servicerouter/rulebase/rule.go @@ -190,7 +190,10 @@ func getErrorRegexText(regexErrors map[string]string) string { if len(regexErrors) == 0 { return "{}" } - res, _ := json.Marshal(regexErrors) + res, err := json.Marshal(regexErrors) + if err != nil { + return "{}" + } return string(res) } diff --git a/plugin/statreporter/prometheus/prometheus_handler.go b/plugin/statreporter/prometheus/prometheus_handler.go index fe76b0ce..4c7727bf 100644 --- a/plugin/statreporter/prometheus/prometheus_handler.go +++ b/plugin/statreporter/prometheus/prometheus_handler.go @@ -144,7 +144,6 @@ func (p *PrometheusHandler) ReportStat(metricsType model.MetricType, metricsVal // runInnerMetricsWebServer 启动用于 prometheus 主动拉取的 http-server,如果端口设置为负数,则不启用 func (p *PrometheusHandler) runInnerMetricsWebServer() { - if p.port < 0 { return } @@ -190,7 +189,7 @@ func (p *PrometheusHandler) handleServiceGauge(metricsType model.MetricType, val delay := val.GetDelay() if delay != nil { - data := float64((*delay).Milliseconds()) + data := float64(delay.Milliseconds()) timeout := p.metricVecCaches[MetricsNameUpstreamRequestTimeout].(*prometheus.GaugeVec) timeout.With(labels).Add(data) diff --git a/test/all_suite_test.go b/test/all_suite_test.go index e217e550..74023a33 100644 --- a/test/all_suite_test.go +++ b/test/all_suite_test.go @@ -58,7 +58,7 @@ func init() { Suite(&discover.ProviderTestingSuite{}) // 负载均衡测试 Suite(&loadbalance.LBTestingSuite{}) - //缓存持久化测试 + // 缓存持久化测试 Suite(&stability.CacheTestingSuite{}) // 熔断测试 Suite(&circuitbreak.CircuitBreakSuite{}) @@ -86,7 +86,7 @@ func init() { Suite(&stability.ServerFailOverSuite{}) // 消息订阅 测试 Suite(&subscribe.EventSubscribeSuit{}) - //金丝雀路由测试 + // 金丝雀路由测试 Suite(&serviceroute.CanaryTestingSuite{}) // 内部服务结构测试 Suite(&loadbalance.InnerServiceLBTestingSuite{}) @@ -94,8 +94,8 @@ func init() { Suite(&ratelimit.LocalNormalTestingSuite{}) // ReportClient相关测试用例 Suite(&reporthandler.ReporthandlerTestingSuite{}) - //// 限流规则变更用例测试 - //Suite(&ratelimit.RuleChangeTestingSuite{}) - //// 基础远程限流用例测试 - //Suite(&ratelimit.RemoteNormalTestingSuite{}) + // // 限流规则变更用例测试 + // Suite(&ratelimit.RuleChangeTestingSuite{}) + // // 基础远程限流用例测试 + // Suite(&ratelimit.RemoteNormalTestingSuite{}) } diff --git a/test/circuitbreak/healthcheck_always_suite.go b/test/circuitbreak/healthcheck_always_suite.go index ac652ac2..732c484d 100644 --- a/test/circuitbreak/healthcheck_always_suite.go +++ b/test/circuitbreak/healthcheck_always_suite.go @@ -95,6 +95,7 @@ func (t *HealthCheckAlwaysTestingSuite) SetUpSuite(c *check.C) { namingpb.RegisterPolarisGRPCServer(t.grpcServer, mockServer) t.grpcListener, err = net.Listen("tcp", fmt.Sprintf("%s:%d", ipAddr, shopPort)) if err != nil { + _ = util.DeleteDir(util.BackupDir) log.Fatal(fmt.Sprintf("error listening appserver %v", err)) } log.Printf("appserver listening on %s:%d\n", ipAddr, shopPort) diff --git a/test/circuitbreak/healthcheck_suite.go b/test/circuitbreak/healthcheck_suite.go index b69bf387..599e6f15 100644 --- a/test/circuitbreak/healthcheck_suite.go +++ b/test/circuitbreak/healthcheck_suite.go @@ -97,6 +97,7 @@ func (t *HealthCheckTestingSuite) SetUpSuite(c *check.C) { namingpb.RegisterPolarisGRPCServer(t.grpcServer, mockServer) t.grpcListener, err = net.Listen("tcp", fmt.Sprintf("%s:%d", ipAddr, shopPort)) if err != nil { + _ = util.DeleteDir(util.BackupDir) log.Fatal(fmt.Sprintf("error listening appserver %v", err)) } log.Printf("appserver listening on %s:%d\n", ipAddr, shopPort) diff --git a/test/loadbalance/loadbalance_suite.go b/test/loadbalance/loadbalance_suite.go index b39ecbc4..29208577 100644 --- a/test/loadbalance/loadbalance_suite.go +++ b/test/loadbalance/loadbalance_suite.go @@ -626,7 +626,6 @@ func (t *LBTestingSuite) TestUserChooseLBAlgorithm(c *check.C) { } } c.Assert(allSame, check.Equals, true) - } // 测试获取备份节点 diff --git a/test/mock/namingserver.go b/test/mock/namingserver.go index 28448a66..2558e512 100644 --- a/test/mock/namingserver.go +++ b/test/mock/namingserver.go @@ -287,9 +287,6 @@ func (n *namingServer) SetMethodInterval(interval time.Duration) { // RegisterInstance 注册实例 func (n *namingServer) RegisterInstance(ctx context.Context, req *namingpb.Instance) (*namingpb.Response, error) { - // - // - // fmt.Printf("%v, RegisterInstance in server, %v\n", time.Now(), req) if n.skipRequest(OperationRegistry) { time.Sleep(syncWaitTime) @@ -340,9 +337,6 @@ func (n *namingServer) RegisterInstance(ctx context.Context, // DeregisterInstance 反注册实例 func (n *namingServer) DeregisterInstance(ctx context.Context, req *namingpb.Instance) (*namingpb.Response, error) { - // - // - // fmt.Printf("%v, DeregisterInstance in server, %v\n", time.Now(), req) if n.skipRequest(OperationDeRegistry) { time.Sleep(syncWaitTime) @@ -524,9 +518,7 @@ func (n *namingServer) RegisterAssistant(req *namingpb.DiscoverRequest) { if len(busis) == 3 { } - } - } // Discover 服务实例发现 diff --git a/test/serviceroute/canary_router_suite.go b/test/serviceroute/canary_router_suite.go index a6ca20a6..a77203c2 100644 --- a/test/serviceroute/canary_router_suite.go +++ b/test/serviceroute/canary_router_suite.go @@ -384,12 +384,12 @@ func SplitInstances(consumer api.ConsumerAPI, canaryVal string) map[int][]model. return RetMap } -func checkGetInstancesByCanaryType(consumer api.ConsumerAPI, instSize int, CType int, c *check.C) { +func checkGetInstancesByCanaryType(consumer api.ConsumerAPI, instSize int, cType int, c *check.C) { getInstancesReq1 := &api.GetInstancesRequest{} getInstancesReq1.FlowID = 1 getInstancesReq1.Namespace = canaryNamespace getInstancesReq1.Service = canaryService - if CType == CanaryInstance { + if cType == CanaryInstance { getInstancesReq1.Canary = "useV1" } resp, err := consumer.GetInstances(getInstancesReq1) @@ -398,7 +398,7 @@ func checkGetInstancesByCanaryType(consumer api.ConsumerAPI, instSize int, CType for _, v := range resp.GetInstances() { c.Assert(v.IsIsolated(), check.Equals, false) c.Assert(v.GetWeight() != 0, check.Equals, true) - c.Assert(CheckInstanceHasCanaryMeta(v, "useV1"), check.Equals, CType) + c.Assert(CheckInstanceHasCanaryMeta(v, "useV1"), check.Equals, cType) } } diff --git a/test/stability/cache_update_fast_suite.go b/test/stability/cache_update_fast_suite.go index 579480b9..3b70a956 100644 --- a/test/stability/cache_update_fast_suite.go +++ b/test/stability/cache_update_fast_suite.go @@ -54,7 +54,7 @@ var newCacheInstNums = []int{6, 10, 8, 5} var testServices = make([]*namingpb.Service, 4, 4) -// 缓存持久化测试套件 +// CacheFastUpdateSuite 缓存持久化测试套件 type CacheFastUpdateSuite struct { grpcServer *grpc.Server grpcListener net.Listener @@ -63,7 +63,7 @@ type CacheFastUpdateSuite struct { healthCheckInstances []model.Instance } -// 初始化测试套件 +// SetUpSuite 初始化测试套件 func (t *CacheFastUpdateSuite) SetUpSuite(c *check.C) { util.DeleteDir(util.BackupDir) diff --git a/test/stability/sdkcontext_destroy_suite.go b/test/stability/sdkcontext_destroy_suite.go index ac7f8060..65b93768 100644 --- a/test/stability/sdkcontext_destroy_suite.go +++ b/test/stability/sdkcontext_destroy_suite.go @@ -65,7 +65,7 @@ func parseRoutines(stack string) (int, int) { if !strings.HasPrefix(rawLine, "goroutine") { continue } - if strings.Index(rawLine, lumberJackPrefix) > -1 { + if strings.Contains(rawLine, lumberJackPrefix) { lumberjackCount++ } else { normalCount++