diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 23bb443f..3893ef86 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -33,7 +33,7 @@ jobs: run: sudo apt-get update && sudo apt-get -y install libsnmp-dev if: github.repository == 'prometheus/snmp_exporter' - name: Lint - uses: golangci/golangci-lint-action@4696ba8babb6127d732c3c6dde519db15edab9ea # v6.5.1 + uses: golangci/golangci-lint-action@1481404843c368bc19ca9406f87d6e0fc97bdcfd # v7.0.0 with: args: --verbose - version: v1.64.6 + version: v2.0.2 diff --git a/.golangci.yml b/.golangci.yml index 45c8684e..95114347 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,19 +1,124 @@ --- +version: "2" + +formatters: + enable: + - gci + - gofumpt + settings: + gci: + sections: + - standard + - prefix(github.com/prometheus-community/elasticsearch_exporter) + - default + linters: enable: + - depguard + # TODO(@sysadmind): Enable and fix the issues. + # - errorlint + - exptostd + # TODO(@sysadmind): Enable and fix the issues. + # - gocritic + # - godot + - loggercheck + # TODO(@sysadmind): Enable and fix the issues. + # - misspell + - nilnesserr + - nolintlint + # TODO(@sysadmind): Enable and fix the issues. + # - perfsprint + - predeclared - revive - sloglint + - testifylint + - unconvert + - unused + - usestdlibvars + - whitespace + exclusions: + rules: + # Disable errcheck for test files. + - linters: + - errcheck + path: _test.go -issues: - exclude-rules: - - path: _test.go - linters: - - errcheck + # Disable errcheck rule for some specific functions. + - linters: + - errcheck + # Taken from the default exclusions in v1. + text: Error return value of .((os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*print(f|ln)?|os\.(Un)?Setenv). is not checked -linters-settings: - revive: - rules: - # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unused-parameter - - name: unused-parameter - severity: warning - disabled: true + settings: + revive: + rules: + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md + - name: blank-imports + - name: comment-spacings + - name: context-as-argument + arguments: + # Allow functions with test or bench signatures. + - allowTypesBefore: '*testing.T,testing.TB' + - name: context-keys-type + - name: dot-imports + - name: early-return + arguments: + - "preserveScope" + # A lot of false positives: incorrectly identifies channel draining as "empty code block". + # See https://github.com/mgechev/revive/issues/386 + - name: empty-block + disabled: true + - name: error-naming + - name: error-return + - name: error-strings + - name: errorf + # TODO(@sysadmind): Enable and fix the issues. + # - name: exported + - name: increment-decrement + - name: indent-error-flow + arguments: + - "preserveScope" + - name: package-comments + # TODO(beorn7/sysadmind): Currently, we have a lot of missing package doc comments. Maybe we should have them. + disabled: true + - name: range + - name: receiver-naming + - name: redefines-builtin-id + - name: superfluous-else + arguments: + - "preserveScope" + - name: time-naming + # TODO(@sysadmind): Enable and fix the issues. + # - name: unexported-return + - name: unreachable-code + - name: unused-parameter + severity: warning + disabled: true + - name: var-declaration + - name: var-naming + + depguard: + rules: + main: + deny: + - pkg: "sync/atomic" + desc: "Use go.uber.org/atomic instead of sync/atomic" + - pkg: "github.com/stretchr/testify/assert" + desc: "Use github.com/stretchr/testify/require instead of github.com/stretchr/testify/assert" + - pkg: "github.com/go-kit/kit/log" + desc: "Use github.com/go-kit/log instead of github.com/go-kit/kit/log" + - pkg: "io/ioutil" + desc: "Use corresponding 'os' or 'io' functions instead." + - pkg: "regexp" + desc: "Use github.com/grafana/regexp instead of regexp" + - pkg: "github.com/pkg/errors" + desc: "Use 'errors' or 'fmt' instead of github.com/pkg/errors" + - pkg: "gzip" + desc: "Use github.com/klauspost/compress instead of gzip" + - pkg: "zlib" + desc: "Use github.com/klauspost/compress instead of zlib" + - pkg: "golang.org/x/exp/slices" + desc: "Use 'slices' instead." +issues: + max-issues-per-linter: 0 + max-same-issues: 0 diff --git a/Makefile.common b/Makefile.common index 8cb38385..81bad5f4 100644 --- a/Makefile.common +++ b/Makefile.common @@ -61,7 +61,7 @@ PROMU_URL := https://github.com/prometheus/promu/releases/download/v$(PROMU_ SKIP_GOLANGCI_LINT := GOLANGCI_LINT := GOLANGCI_LINT_OPTS ?= -GOLANGCI_LINT_VERSION ?= v1.64.6 +GOLANGCI_LINT_VERSION ?= v2.0.2 # golangci-lint only supports linux, darwin and windows platforms on i386/amd64/arm64. # windows isn't included here because of the path separator being different. ifeq ($(GOHOSTOS),$(filter $(GOHOSTOS),linux darwin)) diff --git a/collector/cluster_settings.go b/collector/cluster_settings.go index 35ee97f5..6e7cf174 100644 --- a/collector/cluster_settings.go +++ b/collector/cluster_settings.go @@ -151,7 +151,7 @@ func (c *ClusterSettingsCollector) Update(ctx context.Context, ch chan<- prometh q.Set("include_defaults", "true") u.RawQuery = q.Encode() - req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) if err != nil { return err } diff --git a/collector/data_stream.go b/collector/data_stream.go index ef67758e..8672c5a1 100644 --- a/collector/data_stream.go +++ b/collector/data_stream.go @@ -113,9 +113,7 @@ func (ds *DataStream) Update(ctx context.Context, ch chan<- prometheus.Metric) e float64(dataStream.StoreSizeBytes), dataStream.DataStream, ) - } return nil - } diff --git a/collector/data_stream_test.go b/collector/data_stream_test.go index c5e6853b..71324d5b 100644 --- a/collector/data_stream_test.go +++ b/collector/data_stream_test.go @@ -27,7 +27,6 @@ import ( ) func TestDataStream(t *testing.T) { - tests := []struct { name string file string diff --git a/collector/ilm.go b/collector/ilm.go index a8216a6d..7891e5d0 100644 --- a/collector/ilm.go +++ b/collector/ilm.go @@ -122,7 +122,6 @@ func (i *ILM) Update(ctx context.Context, ch chan<- prometheus.Metric) error { bool2Float(statusActive), status, ) - } return nil diff --git a/collector/ilm_test.go b/collector/ilm_test.go index 5775b0f5..11292aff 100644 --- a/collector/ilm_test.go +++ b/collector/ilm_test.go @@ -54,14 +54,12 @@ func TestILM(t *testing.T) { indexF, err := os.Open(path.Join("../fixtures/ilm_indices", tt.file)) if err != nil { t.Fatal(err) - } defer indexF.Close() statusF, err := os.Open(path.Join("../fixtures/ilm_status", tt.file)) if err != nil { t.Fatal(err) - } defer statusF.Close() @@ -75,7 +73,6 @@ func TestILM(t *testing.T) { }) sm.ServeHTTP(w, r) - })) defer ts.Close() diff --git a/collector/indices.go b/collector/indices.go index a3b2fdac..fcb3b771 100644 --- a/collector/indices.go +++ b/collector/indices.go @@ -22,8 +22,9 @@ import ( "sort" "strconv" - "github.com/prometheus-community/elasticsearch_exporter/pkg/clusterinfo" "github.com/prometheus/client_golang/prometheus" + + "github.com/prometheus-community/elasticsearch_exporter/pkg/clusterinfo" ) var ( @@ -448,7 +449,6 @@ type Indices struct { // NewIndices defines Indices Prometheus metrics func NewIndices(logger *slog.Logger, client *http.Client, url *url.URL, shards bool, includeAliases bool) *Indices { - indices := &Indices{ logger: logger, client: client, @@ -661,7 +661,6 @@ func (i *Indices) Collect(ch chan<- prometheus.Metric) { // Index stats for indexName, indexStats := range indexStatsResp.Indices { - ch <- prometheus.MustNewConstMetric( indicesDocsPrimary, prometheus.GaugeValue, diff --git a/collector/indices_mappings.go b/collector/indices_mappings.go index 21f119a1..0841825e 100644 --- a/collector/indices_mappings.go +++ b/collector/indices_mappings.go @@ -25,9 +25,7 @@ import ( "github.com/prometheus/client_golang/prometheus" ) -var ( - defaultIndicesMappingsLabels = []string{"index"} -) +var defaultIndicesMappingsLabels = []string{"index"} type indicesMappingsMetric struct { Type prometheus.ValueType @@ -72,7 +70,6 @@ func NewIndicesMappings(logger *slog.Logger, client *http.Client, url *url.URL) func countFieldsRecursive(properties IndexMappingProperties, fieldCounter float64) float64 { // iterate over all properties for _, property := range properties { - if property.Type != nil && *property.Type != "object" { // property has a type set - counts as a field unless the value is object // as the recursion below will handle counting that diff --git a/collector/indices_settings.go b/collector/indices_settings.go index 9bcc2d70..f27e4bce 100644 --- a/collector/indices_settings.go +++ b/collector/indices_settings.go @@ -39,8 +39,8 @@ type IndicesSettings struct { var ( defaultIndicesTotalFieldsLabels = []string{"index"} - defaultTotalFieldsValue = 1000 //es default configuration for total fields - defaultDateCreation = 0 //es index default creation date + defaultTotalFieldsValue = 1000 // es default configuration for total fields + defaultDateCreation = 0 // es index default creation date ) type indicesSettingsMetric struct { @@ -153,7 +153,6 @@ func (cs *IndicesSettings) getAndParseURL(u *url.URL, data interface{}) error { } func (cs *IndicesSettings) fetchAndDecodeIndicesSettings() (IndicesSettingsResponse, error) { - u := *cs.url u.Path = path.Join(u.Path, "/_all/_settings") var asr IndicesSettingsResponse diff --git a/collector/indices_test.go b/collector/indices_test.go index 9586fcfb..ebbc9bb1 100644 --- a/collector/indices_test.go +++ b/collector/indices_test.go @@ -2153,7 +2153,6 @@ func TestIndices(t *testing.T) { default: http.Error(w, "Not Found", http.StatusNotFound) } - })) defer ts.Close() diff --git a/collector/nodes.go b/collector/nodes.go index 2fb07693..527870f9 100644 --- a/collector/nodes.go +++ b/collector/nodes.go @@ -69,12 +69,10 @@ func getRoles(node NodeStatsNodeResponse) map[string]bool { return roles } -var ( - nodesRolesMetric = prometheus.NewDesc( - prometheus.BuildFQName(namespace, "nodes", "roles"), - "Node roles", - append(defaultRoleLabels, "role"), nil, - ) +var nodesRolesMetric = prometheus.NewDesc( + prometheus.BuildFQName(namespace, "nodes", "roles"), + "Node roles", + append(defaultRoleLabels, "role"), nil, ) var ( @@ -2012,6 +2010,5 @@ func (c *Nodes) Collect(ch chan<- prometheus.Metric) { ) } } - } } diff --git a/collector/shards.go b/collector/shards.go index d9b26820..d4483e38 100644 --- a/collector/shards.go +++ b/collector/shards.go @@ -21,9 +21,9 @@ import ( "net/url" "path" - "github.com/prometheus-community/elasticsearch_exporter/pkg/clusterinfo" - "github.com/prometheus/client_golang/prometheus" + + "github.com/prometheus-community/elasticsearch_exporter/pkg/clusterinfo" ) // ShardResponse has shard's node and index info @@ -66,7 +66,6 @@ type nodeShardMetric struct { // NewShards defines Shards Prometheus metrics func NewShards(logger *slog.Logger, client *http.Client, url *url.URL) *Shards { - nodeLabels := labels{ keys: func(...string) []string { return []string{"node", "cluster"} @@ -103,7 +102,8 @@ func NewShards(logger *slog.Logger, client *http.Client, url *url.URL) *Shards { return shards }, Labels: nodeLabels, - }}, + }, + }, jsonParseFailures: prometheus.NewCounter(prometheus.CounterOpts{ Name: prometheus.BuildFQName(namespace, "node_shards", "json_parse_failures"), @@ -164,7 +164,6 @@ func (s *Shards) getAndParseURL(u *url.URL) ([]ShardResponse, error) { } func (s *Shards) fetchAndDecodeShards() ([]ShardResponse, error) { - u := *s.url u.Path = path.Join(u.Path, "/_cat/shards") q := u.Query() @@ -179,7 +178,6 @@ func (s *Shards) fetchAndDecodeShards() ([]ShardResponse, error) { // Collect number of shards on each node func (s *Shards) Collect(ch chan<- prometheus.Metric) { - defer func() { ch <- s.jsonParseFailures }() diff --git a/collector/shards_test.go b/collector/shards_test.go index 14ba7a7b..f18b9973 100644 --- a/collector/shards_test.go +++ b/collector/shards_test.go @@ -79,6 +79,5 @@ func TestShards(t *testing.T) { t.Fatal(err) } }) - } } diff --git a/collector/slm.go b/collector/slm.go index 35aee9f2..3ac51f22 100644 --- a/collector/slm.go +++ b/collector/slm.go @@ -23,9 +23,7 @@ import ( "github.com/prometheus/client_golang/prometheus" ) -var ( - statuses = []string{"RUNNING", "STOPPING", "STOPPED"} -) +var statuses = []string{"RUNNING", "STOPPING", "STOPPED"} var ( slmRetentionRunsTotal = prometheus.NewDesc( @@ -173,7 +171,7 @@ func (s *SLM) Update(ctx context.Context, ch chan<- prometheus.Metric) error { } for _, status := range statuses { - var value float64 = 0 + var value float64 if slmStatusResp.OperationMode == status { value = 1 } @@ -253,9 +251,7 @@ func (s *SLM) Update(ctx context.Context, ch chan<- prometheus.Metric) error { float64(policy.SnapshotDeletionFailures), policy.Policy, ) - } return nil - } diff --git a/collector/slm_test.go b/collector/slm_test.go index 36e41328..9c4834a9 100644 --- a/collector/slm_test.go +++ b/collector/slm_test.go @@ -132,7 +132,5 @@ func TestSLM(t *testing.T) { t.Fatal(err) } }) - } - } diff --git a/collector/snapshots.go b/collector/snapshots.go index 42cfc50a..9482dbde 100644 --- a/collector/snapshots.go +++ b/collector/snapshots.go @@ -143,7 +143,6 @@ func (c *Snapshots) Update(ctx context.Context, ch chan<- prometheus.Metric) err // Snapshots stats for repositoryName, snapshotStats := range snapshotsStatsResp { - ch <- prometheus.MustNewConstMetric( numSnapshots, prometheus.GaugeValue, @@ -164,7 +163,7 @@ func (c *Snapshots) Update(ctx context.Context, ch chan<- prometheus.Metric) err latest := float64(0) for i := len(snapshotStats.Snapshots) - 1; i >= 0; i-- { - var snap = snapshotStats.Snapshots[i] + snap := snapshotStats.Snapshots[i] if snap.State == "SUCCESS" || snap.State == "PARTIAL" { latest = float64(snap.StartTimeInMillis / 1000) break diff --git a/main.go b/main.go index 77dc9d21..39d3a1cb 100644 --- a/main.go +++ b/main.go @@ -14,6 +14,7 @@ package main import ( + "context" "fmt" "io" "net/http" @@ -23,12 +24,7 @@ import ( "strings" "time" - "context" - "github.com/alecthomas/kingpin/v2" - "github.com/prometheus-community/elasticsearch_exporter/collector" - "github.com/prometheus-community/elasticsearch_exporter/pkg/clusterinfo" - "github.com/prometheus-community/elasticsearch_exporter/pkg/roundtripper" "github.com/prometheus/client_golang/prometheus" versioncollector "github.com/prometheus/client_golang/prometheus/collectors/version" "github.com/prometheus/client_golang/prometheus/promhttp" @@ -37,6 +33,10 @@ import ( "github.com/prometheus/common/version" "github.com/prometheus/exporter-toolkit/web" webflag "github.com/prometheus/exporter-toolkit/web/kingpinflag" + + "github.com/prometheus-community/elasticsearch_exporter/collector" + "github.com/prometheus-community/elasticsearch_exporter/pkg/clusterinfo" + "github.com/prometheus-community/elasticsearch_exporter/pkg/roundtripper" ) const name = "elasticsearch_exporter" diff --git a/pkg/clusterinfo/clusterinfo_test.go b/pkg/clusterinfo/clusterinfo_test.go index c1803cca..0593a5ed 100644 --- a/pkg/clusterinfo/clusterinfo_test.go +++ b/pkg/clusterinfo/clusterinfo_test.go @@ -25,9 +25,8 @@ import ( "testing" "time" - "github.com/prometheus/common/promslog" - "github.com/blang/semver/v4" + "github.com/prometheus/common/promslog" ) const ( @@ -45,7 +44,6 @@ const ( type mockES struct{} func (mockES) ServeHTTP(w http.ResponseWriter, _ *http.Request) { - fmt.Fprintf(w, `{ "name" : "%s", "cluster_name" : "%s", @@ -152,7 +150,7 @@ func TestRetriever_fetchAndDecodeClusterInfo(t *testing.T) { versionNumber, _ := semver.Make(versionNumber) luceneVersion, _ := semver.Make(luceneVersion) - var expected = &Response{ + expected := &Response{ Name: nodeName, ClusterName: clusterName, ClusterUUID: clusterUUID,