diff --git a/.github/workflows/check.yaml b/.github/workflows/check.yaml index 692d5ed5..e613c4ba 100644 --- a/.github/workflows/check.yaml +++ b/.github/workflows/check.yaml @@ -13,12 +13,10 @@ jobs: steps: - name: Checkout uses: actions/checkout@v4 - with: - fetch-depth: 0 - - name: Set up Go 1.19 + - name: Set up Go 1.22 uses: actions/setup-go@v5 with: - go-version: '1.19' + go-version: '1.22' - name: Running go tests with coverage env: GO111MODULE: on @@ -31,22 +29,24 @@ jobs: GolangLint: name: Golang Lint runs-on: ubuntu-latest + timeout-minutes: 15 steps: - name: Checkout uses: actions/checkout@v4 - with: - fetch-depth: 0 - - name: Set up Go 1.19 + - name: Set up Go 1.22 uses: actions/setup-go@v5 with: - go-version: '1.19' - # NOTE: This golangci-lint action MUST be specified as v2 version, otherwise an error will be reported: - # Running error: can't run linter goanalysis_metalinter\nbuildssa: failed to load package main: could - # not load export data: no export data for \"k8s.io/kube-aggregator\" + go-version: '1.22' - name: golangci-lint - uses: golangci/golangci-lint-action@v2 + uses: golangci/golangci-lint-action@v6 with: - version: v1.58.2 + version: v1.62.0 + skip-cache: true + args: > + --timeout=10m + --verbose + --max-issues-per-linter=0 + --max-same-issues=0 LicenseCheck: name: License Check diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 01f04888..5e63d48d 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -17,12 +17,10 @@ jobs: steps: - name: Checkout uses: actions/checkout@v4 + - name: Set up Go 1.22 + uses: actions/setup-go@v5 with: - fetch-depth: 0 - - name: Set up Go 1.19 - uses: actions/setup-go@v2 - with: - go-version: 1.19 + go-version: '1.22' - name: Running go tests with coverage env: GO111MODULE: on @@ -34,24 +32,25 @@ jobs: steps: - name: Checkout uses: actions/checkout@v4 - with: - fetch-depth: 0 - - name: Set up Go 1.19 + - name: Set up Go 1.22 uses: actions/setup-go@v5 with: - go-version: 1.19 - # NOTE: This golangci-lint action MUST be specified as v2 version, otherwise an error will be reported: - # Running error: can't run linter goanalysis_metalinter\nbuildssa: failed to load package main: could - # not load export data: no export data for \"k8s.io/kube-aggregator\" + go-version: '1.22' - name: golangci-lint - uses: golangci/golangci-lint-action@v2 + uses: golangci/golangci-lint-action@v6 with: - version: v1.58.2 + version: v1.62.0 + skip-cache: true + args: > + --timeout=10m + --verbose + --max-issues-per-linter=0 + --max-same-issues=0 - # # Lints Pull Request commits with commitlint. - # # - # # Rules can be referenced: - # # https://github.com/conventional-changelog/commitlint/tree/master/%40commitlint/config-conventional + # Lints Pull Request commits with commitlint. + # + # Rules can be referenced: + # https://github.com/conventional-changelog/commitlint/tree/master/%40commitlint/config-conventional CommitLint: name: Commit Lint runs-on: ubuntu-latest @@ -94,9 +93,9 @@ jobs: - name: Set up Docker Buildx uses: docker/setup-buildx-action@v2 - name: Set up Go - uses: actions/setup-go@v2 + uses: actions/setup-go@v5 with: - go-version: 1.19 + go-version: '1.22' - name: Set up Node.js uses: actions/setup-node@v2 with: diff --git a/.golangci.yml b/.golangci.yml index 01866a16..92c1b1b5 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -18,78 +18,179 @@ # options for analysis running run: - timeout: 10m - go: '1.19' + timeout: 8m + go: '1.22' linters: disable-all: true enable: # please keep this alphabetized - - bodyclose - - contextcheck - - depguard - - dogsled - - dupl - - errorlint - - errname - - exportloopref - - forbidigo - - gosimple - - gocritic - - goconst - - gofumpt - - govet - - ineffassign - - loggercheck - - misspell - - nolintlint - - nilerr - - nilnil - - prealloc - - predeclared - - staticcheck - - stylecheck - - tagliatelle - - tparallel - - typecheck - - unconvert - - unparam - - unused - - usestdlibvars - - wastedassign - - whitespace + - bodyclose # Checks whether HTTP response body is closed successfully + - contextcheck # Check whether the function uses a non-inherited context + - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) + - errorlint # Find code that will cause problems with the error wrapping scheme + - errname # Checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error + - copyloopvar # Checks for range loop variables that are used after the loop in goroutines + - forbidigo # Forbids identifiers + - gocritic # Provides diagnostics that check for bugs, performance and style issues + - goconst # Finds repeated strings that could be replaced by a constant + - gofumpt # Checks whether code was gofumpt-ed + - gosimple # Specializes in simplifying code + - ineffassign # Detects when assignments to existing variables are not used + - loggercheck # Checks key value pairs for common logger libraries + - misspell # Finds commonly misspelled English words + - nilerr # Finds the code that returns nil even if it checks that the error is not nil + - nilnil # Checks that there is no simultaneous return of nil error and an invalid value + - nolintlint # Reports ill-formed or insufficient nolint directives + - prealloc # Finds slice declarations that could potentially be pre-allocated + - predeclared # Finds code that shadows one of Go's predeclared identifiers + - staticcheck # Go static analysis + - stylecheck # Stylecheck is a replacement for golint + - tagliatelle # Checks the struct tags case + - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 + - thelper # thelper detects golang test helpers without t.Helper() call + - tparallel # Detects inappropriate usage of t.Parallel() method in your Go test codes + - unconvert # Remove unnecessary type conversions + - unparam # Reports unused function parameters + - unused # Checks Go code for unused constants, variables, functions and types + - usestdlibvars # Detects the possibility to use variables/constants from the Go standard library + - whitespace # Tool for detection of leading and trailing whitespace linters-settings: gofumpt: - # Choose whether or not to use the extra rules that are disabled - # by default extra-rules: false tagliatelle: - # Check the struck tag name case. case: - # Use the struct field name to check the name of the struct tag. - # Default: false use-field-name: true rules: - # Any struct tag type can be used. - # Support string case: `camel`, `pascal`, `kebab`, `snake`, `upperSnake`, `goCamel`, `goPascal`, `goKebab`, `goSnake`, `upper`, `lower`, `header`. + # Support string case: `camel`, `pascal`, `kebab`, `snake`, `upperSnake`, `goCamel`, `goPascal`, `goKebab`, `goSnake`, `upper`, `lower` json: goCamel yaml: goCamel xml: goCamel toml: goCamel errorlint: - # Check whether fmt.Errorf uses the %w verb for formatting errors. - # See the https://github.com/polyfloyd/go-errorlint for caveats. - # Default: true + # Check whether fmt.Errorf uses the %w verb for formatting errors errorf: false + govet: + enable: + - asmdecl + - assign + - atomic + - bools + - buildtag + - cgocall + - composites + - copylocks + - errorsas + - fieldalignment + - framepointer + - httpresponse + - ifaceassert + - loopclosure + - lostcancel + - nilfunc + - printf + - shift + - stdmethods + - stringintconv + - structtag + - testinggoroutine + - tests + - unmarshal + - unreachable + - unsafeptr + - unusedresult + disable: + - buildssa + - fieldalignment + settings: + printf: + funcs: + - (github.com/sirupsen/logrus.FieldLogger).Infof + - (github.com/sirupsen/logrus.FieldLogger).Warnf + - (github.com/sirupsen/logrus.FieldLogger).Errorf + - (github.com/sirupsen/logrus.FieldLogger).Fatalf issues: - exclude: - - "G306: Expect WriteFile permissions to be 0600 or less" - - "ST1018: string literal contains Unicode control characters, consider using escape sequences instead" - - "ifElseChain: rewrite if-else to switch statement" - - "S1000: should use for range instead of for { select {} }" - - "SA4004: the surrounding loop is unconditionally terminated" - - "copylocks: call of c\\.Post copies lock value: kusionstack\\.io/kclvm-go/pkg/spec/gpyrpc\\.Ping_Args contains google\\.golang\\.org/protobuf/internal/impl\\.MessageState contains sync\\.Mutex" + exclude-rules: + - path: _test\.go + linters: + - gocyclo + - errcheck + - dupl + - gosec + - path: \.pb\.go + linters: + - all + - path: \.gen\.go + linters: + - all + - path: pkg/kubernetes/.* + linters: + - goanalysis_metalinter + - path: pkg/kubernetes/internalimport/internal_import\.go$ + linters: + - all + - path: internal_import\.go$ + linters: + - typecheck + - govet + - text: "import .* is a program, not an importable package" + linters: + - typecheck + - text: "json\\(goCamel\\): got 'metadata'" # Allow 'metadata' as standard k8s field name + linters: + - tagliatelle + - path: pkg/syncer/source\.go + text: "return both a `nil` error and an invalid value" + linters: + - nilnil + - path: pkg/syncer/syncer\.go + text: "return both a `nil` error and an invalid value" + linters: + - nilnil + - path: pkg/syncer/jsonextracter/jsonpath\.go + text: "return both a `nil` error and an invalid value" + linters: + - nilnil + - path: pkg/syncer/jsonextracter/jsonpath\.go + text: "`\\(\\*JSONPath\\)\\.evalRecursive` - `node` is unused" + linters: + - unparam + - path: pkg/syncer/jsonextracter/fieldpath\.go + text: "return both a `nil` error and an invalid value" + linters: + - nilnil + - path: pkg/core/manager/cluster/manager_test\.go + text: "`newMockCluster` - `name` always receives" + linters: + - unparam + # Allow fmt.Println in version generation script + - path: pkg/version/scripts/gen/gen\.go + text: "use of `fmt.Println`" + linters: + - forbidigo + # Allow fmt.Println in version commands + - path: cmd/(cert-generator|karpor)/.* + text: "use of `fmt.Println`" + linters: + - forbidigo + - path: cmd/karpor/app/server\.go + linters: + - contextcheck + exclude-dirs: + - "pkg/kubernetes/generated" # Generated code + - "pkg/kubernetes/openapi" # Generated OpenAPI code + - "api/openapispec" # Generated API specs + - "hack" # Scripts and tools + - vendor # Third-party dependencies + - third_party # Third-party code + - test # Test files exclude-files: + - internal_import\.go$ - pkg/kubernetes/openapi/zz_generated.openapi.go - - pkg/kubernetes/internalimport/internal_import.go + exclude: + - "G306: Expect WriteFile permissions to be 0600 or less" # Security warning for file permissions + - "ST1018: string literal contains Unicode control characters" # Style issue for string literals + - "ifElseChain: rewrite if-else to switch statement" # Style suggestion + - "S1000: should use for range instead of for { select {} }" # Style suggestion + - "SA4004: the surrounding loop is unconditionally terminated" # Code structure warning diff --git a/Makefile b/Makefile index 83bf5f2a..7ee15c5a 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ include go.mk # Override the variables in the go.mk APPROOT=karpor -GOSOURCE_PATHS = ./pkg/... +GOSOURCE_PATHS = ./pkg/... ./cmd/... LICENSE_CHECKER ?= license-eye LICENSE_CHECKER_VERSION ?= main diff --git a/cmd/karpor/app/server.go b/cmd/karpor/app/server.go index 3f5e662e..17d57d57 100644 --- a/cmd/karpor/app/server.go +++ b/cmd/karpor/app/server.go @@ -47,9 +47,11 @@ import ( netutils "k8s.io/utils/net" ) -const defaultEtcdPathPrefix = "/registry/karpor" -const defaultTokenIssuer = "karpor" -const defaultTokenMaxExpiration = 8760 * time.Hour +const ( + defaultEtcdPathPrefix = "/registry/karpor" + defaultTokenIssuer = "karpor" + defaultTokenMaxExpiration = 8760 * time.Hour +) // Options contains state for master/api server type Options struct { diff --git a/cmd/karpor/app/syncer.go b/cmd/karpor/app/syncer.go index 5a5de5c6..90b07dd4 100644 --- a/cmd/karpor/app/syncer.go +++ b/cmd/karpor/app/syncer.go @@ -72,6 +72,7 @@ func run(ctx context.Context, options *syncerOptions) error { } // TODO: add startup parameters to change the type of storage + //nolint:contextcheck es, err := elasticsearch.NewStorage(esclient.Config{ Addresses: options.ElasticSearchAddresses, }) @@ -80,6 +81,7 @@ func run(ctx context.Context, options *syncerOptions) error { return err } + //nolint:contextcheck if err = syncer.NewSyncReconciler(es).SetupWithManager(mgr); err != nil { log.Error(err, "unable to create resource syncer") return err diff --git a/docs/contributor/code-contribute.md b/docs/contributor/code-contribute.md index e37f6255..caad90a0 100644 --- a/docs/contributor/code-contribute.md +++ b/docs/contributor/code-contribute.md @@ -16,18 +16,18 @@ This guide will help you get started with Karpor development. ### Prerequisites -* Golang version 1.19+ +* Golang version 1.22+
Installing Golang -1. Install go1.19 from the [official website](https://go.dev/dl/). Extract the binary files and place them at a location, assuming it is located under the home directory `~/go/`, here is an example command, you should choose the correct binary file for your system. +1. Install go1.22 from the [official website](https://go.dev/dl/). Extract the binary files and place them at a location, assuming it is located under the home directory `~/go/`, here is an example command, you should choose the correct binary file for your system. ``` wget https://go.dev/dl/go1.20.2.linux-amd64.tar.gz tar xzf go1.20.2.linux-amd64.tar.gz ``` -If you would like to maintain multiple versions of golang in your local development environment, you can download the package and extract it to a location, like `~/go/go1.19.1`, and then alter the path in the command below accordingly. +If you would like to maintain multiple versions of golang in your local development environment, you can download the package and extract it to a location, like `~/go/go1.22.1`, and then alter the path in the command below accordingly. 1. Set environment variables for Golang diff --git a/go.mk b/go.mk index 4c50f6c3..3debb2d7 100644 --- a/go.mk +++ b/go.mk @@ -15,7 +15,7 @@ COVERAGETMP ?= coverage.tmp GOFORMATER ?= gofumpt GOFORMATER_VERSION ?= v0.2.0 GOLINTER ?= golangci-lint -GOLINTER_VERSION ?= v1.58.2 +GOLINTER_VERSION ?= v1.62.0 # To generate help information @@ -33,12 +33,12 @@ cover-html: ## Generates coverage report and displays it in the browser .PHONY: lint lint: ## Lint, will not fix but sets exit code on error @which $(GOLINTER) > /dev/null || (echo "Installing $(GOLINTER)@$(GOLINTER_VERSION) ..."; go install github.com/golangci/golangci-lint/cmd/golangci-lint@$(GOLINTER_VERSION) && echo -e "Installation complete!\n") - $(GOLINTER) run --deadline=10m $(GOSOURCE_PATHS) + $(GOLINTER) run $(GOSOURCE_PATHS) --fast --verbose --print-resources-usage .PHONY: lint-fix lint-fix: ## Lint, will try to fix errors and modify code @which $(GOLINTER) > /dev/null || (echo "Installing $(GOLINTER)@$(GOLINTER_VERSION) ..."; go install github.com/golangci/golangci-lint/cmd/golangci-lint@$(GOLINTER_VERSION) && echo -e "Installation complete!\n") - $(GOLINTER) run --deadline=10m $(GOSOURCE_PATHS) --fix + $(GOLINTER) run $(GOSOURCE_PATHS) --fix .PHONY: doc doc: ## Start the documentation server with godoc diff --git a/go.mod b/go.mod index b062f4cd..0ca1836e 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/KusionStack/karpor -go 1.19 +go 1.22 require ( github.com/Masterminds/sprig/v3 v3.2.2 @@ -44,7 +44,6 @@ require ( k8s.io/dynamic-resource-allocation v0.26.1 k8s.io/klog/v2 v2.80.1 k8s.io/kms v0.26.1 - k8s.io/kube-aggregator v0.26.1 k8s.io/kube-controller-manager v0.26.1 k8s.io/kube-openapi v0.0.0-20230106171958-10e5f0effbd2 k8s.io/kube-proxy v0.26.1 @@ -56,7 +55,6 @@ require ( k8s.io/metrics v0.26.1 k8s.io/mount-utils v0.26.1 k8s.io/pod-security-admission v0.26.1 - k8s.io/sample-apiserver v0.26.1 k8s.io/utils v0.0.0-20221128185143-99ec85e7a448 sigs.k8s.io/controller-runtime v0.14.6 sigs.k8s.io/structured-merge-diff/v4 v4.2.3 diff --git a/go.sum b/go.sum index 3815e1b5..792ef9fe 100644 --- a/go.sum +++ b/go.sum @@ -14,6 +14,7 @@ cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZ cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= cloud.google.com/go v0.97.0 h1:3DXvAyifywvq64LfkKaMOmkWPS1CikIQdMe2lY9vxU8= +cloud.google.com/go v0.97.0/go.mod h1:GF7l59pYBVlXQIBLx3a761cZ41F9bBH3JUlihCt2Udc= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= @@ -57,6 +58,7 @@ github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kd github.com/antlr/antlr4/runtime/Go/antlr v1.4.10 h1:yL7+Jz0jTC6yykIK/Wh74gnTJnrGr5AyrNMXuA0gves= github.com/antlr/antlr4/runtime/Go/antlr v1.4.10/go.mod h1:F7bn7fEU90QkQ3tnmaTx3LTKLEDqnwWODIYppRQ5hnY= github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= +github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= @@ -136,6 +138,7 @@ github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk= github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/form3tech-oss/jwt-go v3.2.3+incompatible h1:7ZaBxOI7TMoYBfyA3cQHErNNyAWIKUMIwqxEtgHOs5c= +github.com/form3tech-oss/jwt-go v3.2.3+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= @@ -162,6 +165,7 @@ github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbV github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-logr/zapr v1.2.3 h1:a9vnzlIBPQBBkeaR9IuMUfmVOrQlkoC4YfPoFkX3T7A= +github.com/go-logr/zapr v1.2.3/go.mod h1:eIauM6P8qSvTw5o2ez6UEAfGjQKrxQTl5EoK+Qa2oG4= github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= @@ -217,6 +221,7 @@ github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiu github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.1 h1:gK4Kx5IaGY9CD5sPJ36FHiBJ6ZXl0kilRiiCj+jdYp4= +github.com/google/btree v1.0.1/go.mod h1:xXMiIv4Fb/0kKde4SpL7qlzvu5cMJDRkFDxJfI9uaxA= github.com/google/cel-go v0.12.6 h1:kjeKudqV0OygrAqA9fX6J55S8gj+Jre2tckIm5RoG4M= github.com/google/cel-go v0.12.6/go.mod h1:Jk7ljRzLBhkmiAwBoUxB1sZSCVBAzkqPF25olK/iRDw= github.com/google/gnostic v0.5.7-v3refs h1:FhTMOKj2VhjpouxvWJAV1TL304uMlb9zcDqkl6cEI54= @@ -256,7 +261,9 @@ github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5m github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 h1:+9834+KizmvFV7pXQGSXQTsaWhq2GjuNUt0aUU0YBYw= +github.com/grpc-ecosystem/go-grpc-middleware v1.3.0/go.mod h1:z0ButlSOZa5vEBq9m2m2hlwIgKw+rp3sdCBRoJY+30Y= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92BcuyuQ/YW4NSIpoGtfXNho= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= @@ -276,6 +283,7 @@ github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7P github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ= +github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= @@ -299,6 +307,7 @@ github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORN github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -338,7 +347,9 @@ github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLA github.com/oliveagle/jsonpath v0.0.0-20180606110733-2e52cf6e6852 h1:Yl0tPBa8QPjGmesFh1D0rDy+q1Twx6FyU7VWHi8wZbI= github.com/oliveagle/jsonpath v0.0.0-20180606110733-2e52cf6e6852/go.mod h1:eqOVx5Vwu4gd2mmMZvVZsgIqNSaW3xxRThUJ0k/TPk4= github.com/onsi/ginkgo/v2 v2.6.0 h1:9t9b9vRUbFq3C4qKFCGkVuq/fIHji802N1nrtkh1mNc= +github.com/onsi/ginkgo/v2 v2.6.0/go.mod h1:63DOGlLAH8+REH8jUGdL3YpCpu7JODesutUjdENfUAc= github.com/onsi/gomega v1.24.1 h1:KORJXNNTzJXzu4ScJWssJfJMnJ+2QJqhoQSRwNlze9E= +github.com/onsi/gomega v1.24.1/go.mod h1:3AOiACssS3/MajrniINInwbfOOtfZvplPzuRSmvt1jM= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/selinux v1.10.0 h1:rAiKF8hTcgLI3w0DHm6i0ylVVcOrlgR1kK99DRLDhyU= @@ -396,6 +407,7 @@ github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1 github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/soheilhy/cmux v0.1.5 h1:jjzc5WVemNEDTLwv9tlmemhC73tI08BNOIGwBOo10Js= +github.com/soheilhy/cmux v0.1.5/go.mod h1:T7TcVDs9LWfQgPlPsdngu6I6QIoyIFZDDC6sNE1GqG0= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= @@ -428,7 +440,9 @@ github.com/swaggo/http-swagger/v2 v2.0.2/go.mod h1:r7/GBkAWIfK6E/OLnE8fXnviHiDeA github.com/swaggo/swag v1.16.2 h1:28Pp+8DkQoV+HLzLx8RGJZXNGKbFqnuvSbAAtoxiY04= github.com/swaggo/swag v1.16.2/go.mod h1:6YzXnDcpr0767iOejs318CwYkCQqyGer6BizOg03f+E= github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802 h1:uruHq4dN7GR16kFc5fp3d1RIYzJW5onx8Ybykw2YQFA= +github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2 h1:eY9dn8+vbi4tKz5Qo6v2eYzo7kUS51QINcR5jNpbZS8= +github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xwb1989/sqlparser v0.0.0-20171128062118-da747e0c62c4 h1:w96oitIHwAbUymu2zUSla/82gOKNzpJYkFdwCHE/UOA= github.com/xwb1989/sqlparser v0.0.0-20171128062118-da747e0c62c4/go.mod h1:hzfGeIUDq/j97IG+FhNqkowIyEcD88LrW6fyU3K3WqY= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -437,16 +451,21 @@ github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.etcd.io/bbolt v1.3.6 h1:/ecaJf0sk1l4l6V4awd65v2C3ILy7MSj+s/x1ADCIMU= +go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4= go.etcd.io/etcd/api/v3 v3.5.5 h1:BX4JIbQ7hl7+jL+g+2j5UAr0o1bctCm6/Ct+ArBGkf0= go.etcd.io/etcd/api/v3 v3.5.5/go.mod h1:KFtNaxGDw4Yx/BA4iPPwevUTAuqcsPxzyX8PHydchN8= go.etcd.io/etcd/client/pkg/v3 v3.5.5 h1:9S0JUVvmrVl7wCF39iTQthdaaNIiAaQbmK75ogO6GU8= go.etcd.io/etcd/client/pkg/v3 v3.5.5/go.mod h1:ggrwbk069qxpKPq8/FKkQ3Xq9y39kbFR4LnKszpRXeQ= go.etcd.io/etcd/client/v2 v2.305.5 h1:DktRP60//JJpnPC0VBymAN/7V71GHMdjDCBt4ZPXDjI= +go.etcd.io/etcd/client/v2 v2.305.5/go.mod h1:zQjKllfqfBVyVStbt4FaosoX2iYd8fV/GRy/PbowgP4= go.etcd.io/etcd/client/v3 v3.5.5 h1:q++2WTJbUgpQu4B6hCuT7VkdwaTP7Qz6Daak3WzbrlI= go.etcd.io/etcd/client/v3 v3.5.5/go.mod h1:aApjR4WGlSumpnJ2kloS75h6aHUmAyaPLjHMxpc7E7c= go.etcd.io/etcd/pkg/v3 v3.5.5 h1:Ablg7T7OkR+AeeeU32kdVhw/AGDsitkKPl7aW73ssjU= +go.etcd.io/etcd/pkg/v3 v3.5.5/go.mod h1:6ksYFxttiUGzC2uxyqiyOEvhAiD0tuIqSZkX3TyPdaE= go.etcd.io/etcd/raft/v3 v3.5.5 h1:Ibz6XyZ60OYyRopu73lLM/P+qco3YtlZMOhnXNS051I= +go.etcd.io/etcd/raft/v3 v3.5.5/go.mod h1:76TA48q03g1y1VpTue92jZLr9lIHKUNcYdZOOGyx8rI= go.etcd.io/etcd/server/v3 v3.5.5 h1:jNjYm/9s+f9A9r6+SC4RvNaz6AqixpOvhrFdT0PvIj0= +go.etcd.io/etcd/server/v3 v3.5.5/go.mod h1:rZ95vDw/jrvsbj9XpTqPrTAB9/kzchVdhRirySPkUBc= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -476,6 +495,7 @@ go.opentelemetry.io/proto/otlp v0.19.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk= +go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo= go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= @@ -872,8 +892,6 @@ k8s.io/klog/v2 v2.80.1 h1:atnLQ121W371wYYFawwYx1aEY2eUfs4l3J72wtgAwV4= k8s.io/klog/v2 v2.80.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= k8s.io/kms v0.26.1 h1:JE0n4J4+8/Z+egvXz2BTJeJ9ecsm4ZSLKF7ttVXXm/4= k8s.io/kms v0.26.1/go.mod h1:ReC1IEGuxgfN+PDCIpR6w8+XMmDE7uJhxcCwMZFdIYc= -k8s.io/kube-aggregator v0.26.1 h1:TqDWwuaUJpyhWGWw4JrXR8ZAAaHa9qrsXxR41aR3igw= -k8s.io/kube-aggregator v0.26.1/go.mod h1:E6dnKoQ6f4eFl8QQXHxTASZKXBX6+XcjROWl7GRltl4= k8s.io/kube-controller-manager v0.26.1 h1:yq6177At/MHD/yKqfTj3cQI74SaA8o+yFCxw+FdEBkU= k8s.io/kube-controller-manager v0.26.1/go.mod h1:V0mR9yO6TLzv1xqFq2FNAQSM37JqpdD+dCPJMghHWPw= k8s.io/kube-openapi v0.0.0-20230106171958-10e5f0effbd2 h1:KYLG+YkfkVf4kdRVshpZZPHpiAyesloMrDE9k1B9Jaw= @@ -896,8 +914,6 @@ k8s.io/mount-utils v0.26.1 h1:deN1IBPyi5UFEAgQYXBEDUejzQUNzRC1ML7BUMWljzA= k8s.io/mount-utils v0.26.1/go.mod h1:au99w4FWU5ZWelLb3Yx6kJc8RZ387IyWVM9tN65Yhxo= k8s.io/pod-security-admission v0.26.1 h1:EDIxsYFeKMzNvN/JB0PgQcuwBP6fIkIG2O8ZWJhzOp4= k8s.io/pod-security-admission v0.26.1/go.mod h1:hCbYTG5UtLlivmukkMPjAWf23PUBUHzEvR60xNVWN4c= -k8s.io/sample-apiserver v0.26.1 h1:TgEpFTIo22keBrc1yV0m6ch01SyUiY/GBOhQIcZtdzc= -k8s.io/sample-apiserver v0.26.1/go.mod h1:NeTzOieGeGsBdDG2+eaOJdoLyaawIHard/wpORDHunA= k8s.io/utils v0.0.0-20221128185143-99ec85e7a448 h1:KTgPnR10d5zhztWptI952TNtt/4u5h3IzDXkdIMuo2Y= k8s.io/utils v0.0.0-20221128185143-99ec85e7a448/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= diff --git a/pkg/core/entity/resource_group_test.go b/pkg/core/entity/resource_group_test.go index e6179dde..3a3c6072 100644 --- a/pkg/core/entity/resource_group_test.go +++ b/pkg/core/entity/resource_group_test.go @@ -282,7 +282,7 @@ func TestNewResourceGroupFromQuery(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - r, err := http.NewRequest("GET", tt.query, nil) + r, err := http.NewRequest(http.MethodGet, tt.query, nil) if err != nil { t.Fatal(err) } diff --git a/pkg/core/handler/endpoint/endpoint.go b/pkg/core/handler/endpoint/endpoint.go index ba6d1546..04c0eba3 100644 --- a/pkg/core/handler/endpoint/endpoint.go +++ b/pkg/core/handler/endpoint/endpoint.go @@ -49,7 +49,7 @@ func listEndpoints(log logr.Logger, r chi.Router) []string { var endpoints []string // Walk through the routes to collect endpoints - walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error { + walkFunc := func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error { endpoint := fmt.Sprintf("%s\t%s", method, route) endpoints = append(endpoints, endpoint) return nil diff --git a/pkg/core/health/check.go b/pkg/core/health/check.go index cfd925e8..e512870d 100644 --- a/pkg/core/health/check.go +++ b/pkg/core/health/check.go @@ -17,9 +17,10 @@ limitations under the License. package health import ( + "net/http" + "github.com/KusionStack/karpor/pkg/infra/search/storage" "github.com/go-chi/chi/v5" - "net/http" ) // Register registers the livez and readyz handlers to the specified diff --git a/pkg/core/health/check_status_handler.go b/pkg/core/health/check_status_handler.go index a51491f8..ee6157e3 100644 --- a/pkg/core/health/check_status_handler.go +++ b/pkg/core/health/check_status_handler.go @@ -20,12 +20,13 @@ package health import ( "context" - "github.com/pkg/errors" - "golang.org/x/sync/errgroup" "net/http" "sort" "strings" "sync" + + "github.com/pkg/errors" + "golang.org/x/sync/errgroup" ) var ( @@ -65,13 +66,13 @@ func NewCheckStatuses(n int) *CheckStatuses { // FailureNotification represents the configuration for failure // notifications. type FailureNotification struct { - Threshold uint32 Chan chan error + Threshold uint32 } type CheckStatuses struct { - sync.RWMutex m map[string]bool + sync.RWMutex } // Get returns the value and existence status for the specified key. diff --git a/pkg/core/health/check_test.go b/pkg/core/health/check_test.go index 014ff991..b65af90f 100644 --- a/pkg/core/health/check_test.go +++ b/pkg/core/health/check_test.go @@ -85,7 +85,7 @@ func TestNewHandler(t *testing.T) { }, } - req, err := http.NewRequest("GET", "/health?"+tt.query, nil) + req, err := http.NewRequest(http.MethodGet, "/health?"+tt.query, nil) if err != nil { t.Fatal(err) } diff --git a/pkg/core/health/storage_check.go b/pkg/core/health/storage_check.go index af2af4ca..59717393 100644 --- a/pkg/core/health/storage_check.go +++ b/pkg/core/health/storage_check.go @@ -18,6 +18,7 @@ package health import ( "context" + "github.com/KusionStack/karpor/pkg/infra/search/storage" ) diff --git a/pkg/core/manager/cluster/manager.go b/pkg/core/manager/cluster/manager.go index aad4e1db..84faea32 100644 --- a/pkg/core/manager/cluster/manager.go +++ b/pkg/core/manager/cluster/manager.go @@ -432,7 +432,7 @@ func (c *ClusterManager) ValidateKubeConfigFor( return "", ErrBothInsecureAndCertificateAuthority } - if !cluster.Insecure && len(cluster.CertificateAuthorityData) <= 0 { + if !cluster.Insecure && len(cluster.CertificateAuthorityData) == 0 { // when insecure is false, CA is required. return "", ErrMissingCertificateAuthority } diff --git a/pkg/core/manager/insight/topology.go b/pkg/core/manager/insight/topology.go index ab94df76..8542598f 100644 --- a/pkg/core/manager/insight/topology.go +++ b/pkg/core/manager/insight/topology.go @@ -131,7 +131,7 @@ func (i *InsightManager) GetResourceRelationship(ctx context.Context, client *mu objGVKOnGraph, err := topology.FindNodeOnGraph(relationshipGraph, gv.Group, gv.Version, obj.GetKind()) // When obj GVK is not found on relationship graph, return an empty graph with no error if err != nil { - return nil, nil //nolint:nilerr + return nil, nil //nolint:nilnil,nilerr } // Recursively find parents diff --git a/pkg/core/manager/insight/util.go b/pkg/core/manager/insight/util.go index a372cf57..72a716ca 100644 --- a/pkg/core/manager/insight/util.go +++ b/pkg/core/manager/insight/util.go @@ -121,7 +121,7 @@ func GetTopResultsFromMap(m map[string]int) map[string]int { return s[i].value > s[j].value }) - index := min(len(s), 5) + index := minInt(len(s), 5) for _, kv := range s[:index] { res[kv.key] = kv.value } @@ -129,8 +129,8 @@ func GetTopResultsFromMap(m map[string]int) map[string]int { return res } -// min returns the smaller of two integers x and y. -func min(x, y int) int { +// minInt returns the smaller of two integers x and y. +func minInt(x, y int) int { if x < y { return x } diff --git a/pkg/core/route/route.go b/pkg/core/route/route.go index be4e336b..d172c984 100644 --- a/pkg/core/route/route.go +++ b/pkg/core/route/route.go @@ -16,6 +16,7 @@ package route import ( "expvar" + docs "github.com/KusionStack/karpor/api/openapispec" authnhandler "github.com/KusionStack/karpor/pkg/core/handler/authn" clusterhandler "github.com/KusionStack/karpor/pkg/core/handler/cluster" diff --git a/pkg/core/route/route_test.go b/pkg/core/route/route_test.go index 12aa6e3b..ef56c29c 100644 --- a/pkg/core/route/route_test.go +++ b/pkg/core/route/route_test.go @@ -104,7 +104,6 @@ func TestNewCoreRoute(t *testing.T) { // Assert status code is not 404 to ensure the route exists. require.NotEqual(t, http.StatusNotFound, rr.Code, "Route should exist: %s", route) } - } }) } diff --git a/pkg/infra/persistence/elasticsearch/client.go b/pkg/infra/persistence/elasticsearch/client.go index 8bc7b878..ab9a66d8 100644 --- a/pkg/infra/persistence/elasticsearch/client.go +++ b/pkg/infra/persistence/elasticsearch/client.go @@ -44,9 +44,6 @@ func NewClient(config elasticsearch.Config) (*Client, error) { if err != nil { return nil, err } - if err != nil { - return nil, err - } typed, err := elasticsearch.NewTypedClient(config) if err != nil { return nil, err @@ -139,7 +136,7 @@ func (cl *Client) UpdateDocument( } // DeleteDocument deletes a document with the specified ID -func (cl *Client) DeleteDocument(ctx context.Context, indexName string, documentID string) error { +func (cl *Client) DeleteDocument(ctx context.Context, indexName, documentID string) error { if _, err := cl.GetDocument(ctx, indexName, documentID); err != nil { return err } @@ -401,7 +398,7 @@ func (cl *Client) multiTermsAgg(ctx context.Context, index string, fields []stri } // termsAgg executes a single-term aggregation query on the specified field. -func (cl *Client) termsAgg(ctx context.Context, index string, field string) (*AggResults, error) { +func (cl *Client) termsAgg(ctx context.Context, index, field string) (*AggResults, error) { // Execute the search request with the single-term aggregation. resp, err := cl.typedClient. Search(). diff --git a/pkg/infra/search/storage/elasticsearch/client.go b/pkg/infra/search/storage/elasticsearch/client.go index a91feb1b..c2e5af5c 100644 --- a/pkg/infra/search/storage/elasticsearch/client.go +++ b/pkg/infra/search/storage/elasticsearch/client.go @@ -54,11 +54,11 @@ func NewStorage(cfg esv8.Config) (*Storage, error) { return nil, err } - if err = cl.CreateIndex(context.TODO(), defaultResourceIndexName, strings.NewReader(defaultResourceMapping)); err != nil { + if err = cl.CreateIndex(context.Background(), defaultResourceIndexName, strings.NewReader(defaultResourceMapping)); err != nil { return nil, err } - if err = cl.CreateIndex(context.TODO(), defaultResourceGroupRuleIndexName, strings.NewReader(defaultResourceGroupRuleMapping)); err != nil { + if err = cl.CreateIndex(context.Background(), defaultResourceGroupRuleIndexName, strings.NewReader(defaultResourceGroupRuleMapping)); err != nil { return nil, err } diff --git a/pkg/infra/search/storage/elasticsearch/search.go b/pkg/infra/search/storage/elasticsearch/search.go index d5dd919d..f5c141ac 100644 --- a/pkg/infra/search/storage/elasticsearch/search.go +++ b/pkg/infra/search/storage/elasticsearch/search.go @@ -37,7 +37,7 @@ type Pagination struct { } // Search performs a search operation with the given query string, pattern type, and pagination settings. -func (s *Storage) Search(ctx context.Context, queryStr string, patternType string, pagination *storage.Pagination) (*storage.SearchResult, error) { +func (s *Storage) Search(ctx context.Context, queryStr, patternType string, pagination *storage.Pagination) (*storage.SearchResult, error) { var sr *storage.SearchResult var err error diff --git a/pkg/kubernetes/apis/cluster/types.go b/pkg/kubernetes/apis/cluster/types.go index 0a46cdaf..3eb3b21e 100644 --- a/pkg/kubernetes/apis/cluster/types.go +++ b/pkg/kubernetes/apis/cluster/types.go @@ -35,7 +35,7 @@ const ( // Cluster is an extension type to access a cluster type Cluster struct { metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` //nolint:tagliatelle + metav1.ObjectMeta `json:"metadata,omitempty"` Spec ClusterSpec `json:"spec"` Status ClusterStatus `json:"status,omitempty"` @@ -46,7 +46,7 @@ type Cluster struct { // ClusterList is a list of Cluster objects. type ClusterList struct { metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` //nolint:tagliatelle + metav1.ListMeta `json:"metadata,omitempty"` Items []Cluster `json:"items"` } diff --git a/pkg/kubernetes/apis/cluster/v1beta1/types.go b/pkg/kubernetes/apis/cluster/v1beta1/types.go index 0a85f315..4a80096a 100644 --- a/pkg/kubernetes/apis/cluster/v1beta1/types.go +++ b/pkg/kubernetes/apis/cluster/v1beta1/types.go @@ -35,7 +35,7 @@ const ( // Cluster is an extension type to access a cluster type Cluster struct { metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` //nolint:tagliatelle + metav1.ObjectMeta `json:"metadata,omitempty"` Spec ClusterSpec `json:"spec"` // +optional @@ -47,7 +47,7 @@ type Cluster struct { // ClusterList is a list of Cluster objects. type ClusterList struct { metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` //nolint:tagliatelle + metav1.ListMeta `json:"metadata,omitempty"` Items []Cluster `json:"items"` } diff --git a/pkg/kubernetes/apis/search/v1beta1/types.go b/pkg/kubernetes/apis/search/v1beta1/types.go index 84f8a530..6c722392 100644 --- a/pkg/kubernetes/apis/search/v1beta1/types.go +++ b/pkg/kubernetes/apis/search/v1beta1/types.go @@ -26,7 +26,7 @@ import ( type SyncRegistry struct { metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` //nolint:tagliatelle + metav1.ObjectMeta `json:"metadata,omitempty"` // +optional Spec SyncRegistrySpec `json:"spec,omitempty"` @@ -57,7 +57,7 @@ type SyncRegistryList struct { metav1.TypeMeta `json:",inline"` // +optional - metav1.ListMeta `json:"metadata,omitempty"` //nolint:tagliatelle + metav1.ListMeta `json:"metadata,omitempty"` Items []SyncRegistry `json:"items"` } @@ -68,7 +68,7 @@ type SyncRegistryList struct { type SyncResources struct { metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` //nolint:tagliatelle + metav1.ObjectMeta `json:"metadata,omitempty"` Spec SyncResourcesSpec `json:"spec,omitempty"` } @@ -79,7 +79,7 @@ type SyncResourcesList struct { metav1.TypeMeta `json:",inline"` // +optional - metav1.ListMeta `json:"metadata,omitempty"` //nolint:tagliatelle + metav1.ListMeta `json:"metadata,omitempty"` Items []SyncResources `json:"items"` } @@ -145,7 +145,7 @@ type ResourceSyncRule struct { // informer memory by discarding redundant fields. type TrimRule struct { metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` //nolint:tagliatelle + metav1.ObjectMeta `json:"metadata,omitempty"` // +optional Spec TrimRuleSpec `json:"spec,omitempty"` @@ -170,7 +170,7 @@ type TrimRuleList struct { metav1.TypeMeta `json:",inline"` // +optional - metav1.ListMeta `json:"metadata,omitempty"` //nolint:tagliatelle + metav1.ListMeta `json:"metadata,omitempty"` Items []TrimRule `json:"items"` } @@ -183,7 +183,7 @@ type TrimRuleList struct { // target resource. type TransformRule struct { metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` //nolint:tagliatelle + metav1.ObjectMeta `json:"metadata,omitempty"` // +optional Spec TransformRuleSpec `json:"spec,omitempty"` @@ -205,7 +205,7 @@ type TransformRuleList struct { metav1.TypeMeta `json:",inline"` // +optional - metav1.ListMeta `json:"metadata,omitempty"` //nolint:tagliatelle + metav1.ListMeta `json:"metadata,omitempty"` Items []TransformRule `json:"items"` } diff --git a/pkg/kubernetes/internalimport/internal_import.go b/pkg/kubernetes/internalimport/internal_import.go index 595041ef..62fab0ee 100644 --- a/pkg/kubernetes/internalimport/internal_import.go +++ b/pkg/kubernetes/internalimport/internal_import.go @@ -32,7 +32,6 @@ import ( _ "k8s.io/csi-translation-lib" _ "k8s.io/dynamic-resource-allocation" _ "k8s.io/kms" - _ "k8s.io/kube-aggregator" _ "k8s.io/kube-controller-manager" _ "k8s.io/kube-proxy" _ "k8s.io/kube-scheduler" @@ -42,5 +41,4 @@ import ( _ "k8s.io/metrics" _ "k8s.io/mount-utils" _ "k8s.io/pod-security-admission" - _ "k8s.io/sample-apiserver" ) diff --git a/pkg/kubernetes/registry/core/storage_provider.go b/pkg/kubernetes/registry/core/storage_provider.go index 2f9720a0..5b9a4858 100644 --- a/pkg/kubernetes/registry/core/storage_provider.go +++ b/pkg/kubernetes/registry/core/storage_provider.go @@ -37,7 +37,8 @@ type RESTStorageProvider struct { } func NewRESTStorageProvider(serviceAccouuntIssuer serviceaccount.TokenGenerator, - serviceAccountMaxExpiration time.Duration) *RESTStorageProvider { + serviceAccountMaxExpiration time.Duration, +) *RESTStorageProvider { return &RESTStorageProvider{ ServiceAccountIssuer: serviceAccouuntIssuer, ServiceAccountMaxExpiration: serviceAccountMaxExpiration, diff --git a/pkg/syncer/jsonextracter/fieldpath_test.go b/pkg/syncer/jsonextracter/fieldpath_test.go index fa14fadd..7a2415bf 100644 --- a/pkg/syncer/jsonextracter/fieldpath_test.go +++ b/pkg/syncer/jsonextracter/fieldpath_test.go @@ -66,7 +66,7 @@ func TestFieldPath(t *testing.T) { got, err := NestedFieldNoCopy(tt.args.obj, tt.args.allowMissingKeys, tt.args.fields...) jpt := jsonPathTest{tt.name, fieldPathToJSONPath(tt.args.fields), tt.args.obj, tt.want, tt.wantErr} - testJSONPath([]jsonPathTest{jpt}, tt.args.allowMissingKeys, t) + testJSONPath(t, []jsonPathTest{jpt}, tt.args.allowMissingKeys) if (err != nil) != tt.wantErr { t.Errorf("NestedFieldNoCopy() error = %v, wantErr %v", err, tt.wantErr) diff --git a/pkg/syncer/jsonextracter/jsonpath.go b/pkg/syncer/jsonextracter/jsonpath.go index 923a600e..60adc25d 100644 --- a/pkg/syncer/jsonextracter/jsonpath.go +++ b/pkg/syncer/jsonextracter/jsonpath.go @@ -290,7 +290,6 @@ func (j *JSONPath) evalArray(input []reflect.Value, node *ArrayNode, setFn []set result := []reflect.Value{} nextFns := []setFieldFunc{} for k, value := range input { - value, isNil := template.Indirect(value) if isNil { continue diff --git a/pkg/syncer/jsonextracter/jsonpath_test.go b/pkg/syncer/jsonextracter/jsonpath_test.go index e19c044e..5bb27c35 100644 --- a/pkg/syncer/jsonextracter/jsonpath_test.go +++ b/pkg/syncer/jsonextracter/jsonpath_test.go @@ -33,7 +33,8 @@ func (t *jsonPathTest) Prepare(allowMissingKeys bool) (*JSONPath, error) { return jp, jp.Parse(t.template) } -func benchmarkJSONPath(test jsonPathTest, allowMissingKeys bool, b *testing.B) { +func benchmarkJSONPath(b *testing.B, test jsonPathTest, allowMissingKeys bool) { + b.Helper() jp, err := test.Prepare(allowMissingKeys) if err != nil { if !test.expectError { @@ -48,7 +49,8 @@ func benchmarkJSONPath(test jsonPathTest, allowMissingKeys bool, b *testing.B) { } } -func testJSONPath(tests []jsonPathTest, allowMissingKeys bool, t *testing.T) { +func testJSONPath(t *testing.T, tests []jsonPathTest, allowMissingKeys bool) { + t.Helper() for _, test := range tests { jp, err := test.Prepare(allowMissingKeys) if err != nil { @@ -152,7 +154,7 @@ func TestJSONPath(t *testing.T) { {"not exist label", `{.metadata.labels.xx.dd}`, podData, `null`, true}, } - testJSONPath(podTests, false, t) + testJSONPath(t, podTests, false) allowMissingTests := []jsonPathTest{ {"containers image", `{.spec.containers[*]['xname', 'image']}`, podData, `{"spec":{"containers":[{"image":"registry.k8s.io/pause:3.8"},{"image":"registry.k8s.io/pause:3.8"}]}}`, false}, @@ -160,10 +162,10 @@ func TestJSONPath(t *testing.T) { {"not exist label", `{.metadata.labels.xx.dd}`, podData, `{"metadata":{"labels":{}}}`, false}, } - testJSONPath(allowMissingTests, true, t) + testJSONPath(t, allowMissingTests, true) } func BenchmarkJSONPath(b *testing.B) { t := jsonPathTest{"range nodes capacity", `{.kind}`, podData, `{"kind":"Pod"}`, false} - benchmarkJSONPath(t, true, b) + benchmarkJSONPath(b, t, true) } diff --git a/pkg/syncer/single_cluster_sync_manager_test.go b/pkg/syncer/single_cluster_sync_manager_test.go index 4169cef7..6cfbde2c 100644 --- a/pkg/syncer/single_cluster_sync_manager_test.go +++ b/pkg/syncer/single_cluster_sync_manager_test.go @@ -17,12 +17,13 @@ package syncer import ( "context" - "github.com/KusionStack/karpor/pkg/infra/search/storage/elasticsearch" "sync" "sync/atomic" "testing" "time" + "github.com/KusionStack/karpor/pkg/infra/search/storage/elasticsearch" + searchv1beta1 "github.com/KusionStack/karpor/pkg/kubernetes/apis/search/v1beta1" "github.com/bytedance/mockey" "github.com/go-logr/logr" diff --git a/pkg/syncer/source.go b/pkg/syncer/source.go index 70a6cdb3..07600128 100644 --- a/pkg/syncer/source.go +++ b/pkg/syncer/source.go @@ -186,10 +186,10 @@ func (s *informerSource) createInformer(_ context.Context, handler ctrlhandler.E lw := &clientgocache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { - return s.client.Resource(gvr).Namespace(s.Namespace).List(context.TODO(), options) + return s.client.Resource(gvr).Namespace(s.Namespace).List(s.ctx, options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { - return s.client.Resource(gvr).Namespace(s.Namespace).Watch(context.TODO(), options) + return s.client.Resource(gvr).Namespace(s.Namespace).Watch(s.ctx, options) }, } diff --git a/pkg/syncer/transform/tmpl_funcs.go b/pkg/syncer/transform/tmpl_funcs.go index 5558425a..eaec3fca 100644 --- a/pkg/syncer/transform/tmpl_funcs.go +++ b/pkg/syncer/transform/tmpl_funcs.go @@ -24,7 +24,7 @@ var ( clusterTmplFuncsLock sync.RWMutex ) -func RegisterClusterTmplFunc(cluster, FuncName string, tmplFunc any) error { +func RegisterClusterTmplFunc(cluster, funcName string, tmplFunc any) error { clusterTmplFuncsLock.Lock() defer clusterTmplFuncsLock.Unlock() @@ -34,7 +34,7 @@ func RegisterClusterTmplFunc(cluster, FuncName string, tmplFunc any) error { clusterTmplFuncs[cluster] = make(template.FuncMap) } - clusterTmplFuncs[cluster][FuncName] = tmplFunc + clusterTmplFuncs[cluster][funcName] = tmplFunc return nil } diff --git a/pkg/syncer/utils/elasticsearch_getter_test.go b/pkg/syncer/utils/elasticsearch_getter_test.go index 2298f7f1..711989e4 100644 --- a/pkg/syncer/utils/elasticsearch_getter_test.go +++ b/pkg/syncer/utils/elasticsearch_getter_test.go @@ -68,12 +68,8 @@ func TestESListerGetter_ListKeys(t *testing.T) { esLister := NewESListerGetter("defalut", &elasticsearch.Storage{}, tc.gvr) keys := esLister.ListKeys() - // Check error expectation - if tc.expectError { - require.Len(t, keys, tc.expectedLength, "Expected nil result on error") - } else { - require.Len(t, keys, tc.expectedLength, "Expected nil result on error") - } + // Check the length of returned keys + require.Len(t, keys, tc.expectedLength, "Unexpected number of keys returned") }) } } diff --git a/pkg/syncer/utils/purger.go b/pkg/syncer/utils/purger.go index fff3ce9b..06e02055 100644 --- a/pkg/syncer/utils/purger.go +++ b/pkg/syncer/utils/purger.go @@ -73,7 +73,7 @@ func (e *ESPurger) Purge(ctx context.Context, syncBefore time.Time) error { esquery.Range("syncAt").Lte(syncBefore), ).Map() - sr, err := e.esClient.SearchByQuery(context.Background(), query, nil) + sr, err := e.esClient.SearchByQuery(ctx, query, nil) if err != nil { return err } diff --git a/pkg/syncer/utils/selector_test.go b/pkg/syncer/utils/selector_test.go index 4e766547..8524e9de 100644 --- a/pkg/syncer/utils/selector_test.go +++ b/pkg/syncer/utils/selector_test.go @@ -26,132 +26,132 @@ import ( ) // generate a test selectable object. -func createTestSelectable(labels map[string]interface{}, fields map[string]interface{}) Selectable { - return &selectableUnstructured{ - Unstructured: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "metadata": map[string]interface{}{ - "labels": labels, - }, - "spec": fields, - }, - }, - parser: jsonpath.DefaultJSONPathParser, - } +func createTestSelectable(labels, fields map[string]interface{}) Selectable { + return &selectableUnstructured{ + Unstructured: &unstructured.Unstructured{ + Object: map[string]interface{}{ + "metadata": map[string]interface{}{ + "labels": labels, + }, + "spec": fields, + }, + }, + parser: jsonpath.DefaultJSONPathParser, + } } func TestGetLabels(t *testing.T) { - expectedLabels := labels.Set{"app": "test"} - selectable := createTestSelectable(map[string]interface{}{"app": "test"}, nil) - require.Equal(t, expectedLabels, selectable.GetLabels()) + expectedLabels := labels.Set{"app": "test"} + selectable := createTestSelectable(map[string]interface{}{"app": "test"}, nil) + require.Equal(t, expectedLabels, selectable.GetLabels()) } func TestGetFields(t *testing.T) { - u := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec.replicas": "2", - }, - } - expectedFields := jsonpath.NewJSONPathFields(jsonpath.NewJSONPathParser(), u.Object) - label := selectableUnstructured{Unstructured: u, parser: jsonpath.DefaultJSONPathParser} - require.Equal(t, expectedFields, label.GetFields()) + u := &unstructured.Unstructured{ + Object: map[string]interface{}{ + "spec.replicas": "2", + }, + } + expectedFields := jsonpath.NewJSONPathFields(jsonpath.NewJSONPathParser(), u.Object) + label := selectableUnstructured{Unstructured: u, parser: jsonpath.DefaultJSONPathParser} + require.Equal(t, expectedFields, label.GetFields()) } func TestSelector_Matches(t *testing.T) { - labelSelector := labels.SelectorFromSet(labels.Set{"app": "test"}) - fieldSelector := fields.SelectorFromSet(fields.Set{"spec.replicas": "2"}) - selector := Selector{Label: labelSelector, Field: FieldsSelector{Selector: fieldSelector, ServerSupported: true}} - - testCases := []struct { - name string - labels map[string]interface{} - fields map[string]interface{} - expected bool - }{ - {"MatchBoth", map[string]interface{}{"app": "test"}, map[string]interface{}{"replicas": "2"}, true}, - {"MismatchLabel", map[string]interface{}{"app": "wrong"}, map[string]interface{}{"replicas": "2"}, false}, - {"MismatchField", map[string]interface{}{"app": "test"}, map[string]interface{}{"replicas": "3"}, false}, - {"NoFields", map[string]interface{}{"app": "test"}, nil, false}, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - selectable := createTestSelectable(tc.labels, tc.fields) - require.Equal(t, tc.expected, selector.Matches(selectable)) - }) - } + labelSelector := labels.SelectorFromSet(labels.Set{"app": "test"}) + fieldSelector := fields.SelectorFromSet(fields.Set{"spec.replicas": "2"}) + selector := Selector{Label: labelSelector, Field: FieldsSelector{Selector: fieldSelector, ServerSupported: true}} + + testCases := []struct { + name string + labels map[string]interface{} + fields map[string]interface{} + expected bool + }{ + {"MatchBoth", map[string]interface{}{"app": "test"}, map[string]interface{}{"replicas": "2"}, true}, + {"MismatchLabel", map[string]interface{}{"app": "wrong"}, map[string]interface{}{"replicas": "2"}, false}, + {"MismatchField", map[string]interface{}{"app": "test"}, map[string]interface{}{"replicas": "3"}, false}, + {"NoFields", map[string]interface{}{"app": "test"}, nil, false}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + selectable := createTestSelectable(tc.labels, tc.fields) + require.Equal(t, tc.expected, selector.Matches(selectable)) + }) + } } func TestMultiSelectors_Matches(t *testing.T) { - labelSelector := labels.SelectorFromSet(labels.Set{"app": "test"}) - fieldSelector := fields.SelectorFromSet(fields.Set{"spec.replicas": "2"}) - selector := Selector{Label: labelSelector, Field: FieldsSelector{Selector: fieldSelector, ServerSupported: true}} - selectors := MultiSelectors{selector} - - testCases := []struct { - name string - labels map[string]interface{} - fields map[string]interface{} - expected bool - }{ - {"MatchBoth", map[string]interface{}{"app": "test"}, map[string]interface{}{"replicas": "2"}, true}, - {"MismatchLabel", map[string]interface{}{"app": "wrong"}, map[string]interface{}{"replicas": "2"}, false}, - {"MismatchField", map[string]interface{}{"app": "test"}, map[string]interface{}{"replicas": "3"}, false}, - {"NoFields", map[string]interface{}{"app": "test"}, nil, false}, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - selectable := createTestSelectable(tc.labels, tc.fields) - require.Equal(t, tc.expected, selectors.Matches(selectable)) - }) - } + labelSelector := labels.SelectorFromSet(labels.Set{"app": "test"}) + fieldSelector := fields.SelectorFromSet(fields.Set{"spec.replicas": "2"}) + selector := Selector{Label: labelSelector, Field: FieldsSelector{Selector: fieldSelector, ServerSupported: true}} + selectors := MultiSelectors{selector} + + testCases := []struct { + name string + labels map[string]interface{} + fields map[string]interface{} + expected bool + }{ + {"MatchBoth", map[string]interface{}{"app": "test"}, map[string]interface{}{"replicas": "2"}, true}, + {"MismatchLabel", map[string]interface{}{"app": "wrong"}, map[string]interface{}{"replicas": "2"}, false}, + {"MismatchField", map[string]interface{}{"app": "test"}, map[string]interface{}{"replicas": "3"}, false}, + {"NoFields", map[string]interface{}{"app": "test"}, nil, false}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + selectable := createTestSelectable(tc.labels, tc.fields) + require.Equal(t, tc.expected, selectors.Matches(selectable)) + }) + } } func TestApplyToList(t *testing.T) { - labelSelector := labels.SelectorFromSet(labels.Set{"app": "test"}) - fieldSelector := fields.SelectorFromSet(fields.Set{"spec.replicas": "2"}) - selector := Selector{Label: labelSelector, Field: FieldsSelector{Selector: fieldSelector, ServerSupported: true}} - selectors := MultiSelectors{selector} + labelSelector := labels.SelectorFromSet(labels.Set{"app": "test"}) + fieldSelector := fields.SelectorFromSet(fields.Set{"spec.replicas": "2"}) + selector := Selector{Label: labelSelector, Field: FieldsSelector{Selector: fieldSelector, ServerSupported: true}} + selectors := MultiSelectors{selector} - meta := &metav1.ListOptions{} - selectors.ApplyToList(meta) + meta := &metav1.ListOptions{} + selectors.ApplyToList(meta) - require.Equal(t, "app=test", meta.LabelSelector) - require.Equal(t, "spec.replicas=2", meta.FieldSelector) + require.Equal(t, "app=test", meta.LabelSelector) + require.Equal(t, "spec.replicas=2", meta.FieldSelector) } func TestPredicate(t *testing.T) { - labelSelector := labels.SelectorFromSet(labels.Set{"app": "test"}) - fieldSelector := fields.SelectorFromSet(fields.Set{"spec.replicas": "2"}) - s1 := Selector{Label: labelSelector, Field: FieldsSelector{Selector: fieldSelector, ServerSupported: true}} - labelSelector = labels.SelectorFromSet(labels.Set{"app": "test"}) - fieldSelector = fields.SelectorFromSet(fields.Set{"spec.replicas": "4"}) - s2 := Selector{Label: labelSelector, Field: FieldsSelector{Selector: fieldSelector, ServerSupported: true}} - selectors := MultiSelectors{s1, s2} - - testCases := []struct { - name string - labels map[string]interface{} - fields map[string]interface{} - expected bool - }{ - {"MatchBoth", map[string]interface{}{"app": "test"}, map[string]interface{}{"replicas": "2"}, true}, - {"MismatchLabel", map[string]interface{}{"app": "wrong"}, map[string]interface{}{"replicas": "2"}, false}, - {"MismatchField", map[string]interface{}{"app": "test"}, map[string]interface{}{"replicas": "3"}, false}, - {"NoFields", map[string]interface{}{"app": "test"}, nil, false}, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - require.Equal(t, tc.expected, selectors.Predicate(&unstructured.Unstructured{ - Object: map[string]interface{}{ - "metadata": map[string]interface{}{ - "labels": tc.labels, - }, - "spec": tc.fields, - }, - })) - }) - } + labelSelector := labels.SelectorFromSet(labels.Set{"app": "test"}) + fieldSelector := fields.SelectorFromSet(fields.Set{"spec.replicas": "2"}) + s1 := Selector{Label: labelSelector, Field: FieldsSelector{Selector: fieldSelector, ServerSupported: true}} + labelSelector = labels.SelectorFromSet(labels.Set{"app": "test"}) + fieldSelector = fields.SelectorFromSet(fields.Set{"spec.replicas": "4"}) + s2 := Selector{Label: labelSelector, Field: FieldsSelector{Selector: fieldSelector, ServerSupported: true}} + selectors := MultiSelectors{s1, s2} + + testCases := []struct { + name string + labels map[string]interface{} + fields map[string]interface{} + expected bool + }{ + {"MatchBoth", map[string]interface{}{"app": "test"}, map[string]interface{}{"replicas": "2"}, true}, + {"MismatchLabel", map[string]interface{}{"app": "wrong"}, map[string]interface{}{"replicas": "2"}, false}, + {"MismatchField", map[string]interface{}{"app": "test"}, map[string]interface{}{"replicas": "3"}, false}, + {"NoFields", map[string]interface{}{"app": "test"}, nil, false}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.expected, selectors.Predicate(&unstructured.Unstructured{ + Object: map[string]interface{}{ + "metadata": map[string]interface{}{ + "labels": tc.labels, + }, + "spec": tc.fields, + }, + })) + }) + } } diff --git a/pkg/util/certgenerator/generator.go b/pkg/util/certgenerator/generator.go index 5cb5c7d8..2a1912ed 100644 --- a/pkg/util/certgenerator/generator.go +++ b/pkg/util/certgenerator/generator.go @@ -54,7 +54,7 @@ type Generator struct { kubeConfigName string } -func NewGenerator(cfg *rest.Config, namespace string, certName string, kubeConfigName string) (*Generator, error) { +func NewGenerator(cfg *rest.Config, namespace, certName, kubeConfigName string) (*Generator, error) { if cfg == nil { return nil, fmt.Errorf("cfg is required buit was nil") } diff --git a/pkg/util/clusterinstall/cluster_install_test.go b/pkg/util/clusterinstall/cluster_install_test.go index 1b203553..21f0dd8a 100644 --- a/pkg/util/clusterinstall/cluster_install_test.go +++ b/pkg/util/clusterinstall/cluster_install_test.go @@ -15,9 +15,10 @@ package clusterinstall import ( - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" "testing" + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" + clusterv1beta1 "github.com/KusionStack/karpor/pkg/kubernetes/apis/cluster/v1beta1" "github.com/stretchr/testify/require" "k8s.io/client-go/rest" @@ -103,8 +104,10 @@ func TestConvertKubeconfigToCluster(t *testing.T) { }, ExecProvider: &clientcmdapi.ExecConfig{ Command: "aws", - Args: []string{"--region", "xxx", "eks", "get-token", "--cluster-name", - "exec-cluster"}, + Args: []string{ + "--region", "xxx", "eks", "get-token", "--cluster-name", + "exec-cluster", + }, Env: nil, APIVersion: "client.authentication.k8s.io/v1beta1", InstallHint: "", diff --git a/pkg/util/sql2es/convert.go b/pkg/util/sql2es/convert.go index 8a56a811..776a3549 100644 --- a/pkg/util/sql2es/convert.go +++ b/pkg/util/sql2es/convert.go @@ -57,13 +57,13 @@ func applyDefaultFilter(sel *sqlparser.Select, filter sqlparser.Expr) *sqlparser return sel } -func Convert(sql string) (dsl string, table string, err error) { +func Convert(sql string) (dsl, table string, err error) { return ConvertWithDefaultFilter(sql, nil) } // ConvertWithDefaultFilter appends the filter to sql where clause if the // filter column names have no intersection with where clause. -func ConvertWithDefaultFilter(sql string, filter sqlparser.Expr) (dsl string, table string, err error) { +func ConvertWithDefaultFilter(sql string, filter sqlparser.Expr) (dsl, table string, err error) { stmt, err := sqlparser.Parse(sql) if err != nil { return "", "", err @@ -84,7 +84,7 @@ func ConvertWithDefaultFilter(sql string, filter sqlparser.Expr) (dsl string, ta return handleSelect(sel) } -func handleSelect(sel *sqlparser.Select) (dsl string, esType string, err error) { +func handleSelect(sel *sqlparser.Select) (dsl, esType string, err error) { var rootParent sqlparser.Expr queryMapStr, err := handleSelectWhere(&sel.Where.Expr, true, &rootParent) @@ -176,7 +176,7 @@ func buildNestedFuncStrValue(nestedFunc *sqlparser.FuncExpr) (string, error) { return "", fmt.Errorf("unsupported function " + nestedFunc.Name.String()) } -func handleSelectWhereAndExpr(expr *sqlparser.Expr, parent *sqlparser.Expr) (string, error) { +func handleSelectWhereAndExpr(expr, parent *sqlparser.Expr) (string, error) { andExpr := (*expr).(*sqlparser.AndExpr) leftExpr := andExpr.Left rightExpr := andExpr.Right @@ -204,7 +204,7 @@ func handleSelectWhereAndExpr(expr *sqlparser.Expr, parent *sqlparser.Expr) (str return fmt.Sprintf(`{"bool" : {"must" : [%v]}}`, resultStr), nil } -func handleSelectWhereOrExpr(expr *sqlparser.Expr, parent *sqlparser.Expr) (string, error) { +func handleSelectWhereOrExpr(expr, parent *sqlparser.Expr) (string, error) { orExpr := (*expr).(*sqlparser.OrExpr) leftExpr := orExpr.Left rightExpr := orExpr.Right diff --git a/pkg/version/scripts/gen/gen.go b/pkg/version/scripts/gen/gen.go index f99ce4f0..581a6da3 100644 --- a/pkg/version/scripts/gen/gen.go +++ b/pkg/version/scripts/gen/gen.go @@ -53,6 +53,10 @@ func calculateVersion() (string, error) { func main() { currentDir, err := os.Getwd() + if err != nil { + fmt.Println("Error getting current directory:", err) + os.Exit(1) + } versionStr, err := calculateVersion() if err != nil { fmt.Println("Error calculating version:", err) diff --git a/ui/embed.go b/ui/embed.go index ced8850f..685ab1c9 100644 --- a/ui/embed.go +++ b/ui/embed.go @@ -7,5 +7,4 @@ import ( // Embedded contains embedded UI resources // //go:embed build/* -//nolint:typecheck var Embedded embed.FS