Skip to content

Commit 17efa94

Browse files
committed
fix: add golangci-lint and fix lints
1 parent 5d3bfa0 commit 17efa94

File tree

7 files changed

+160
-75
lines changed

7 files changed

+160
-75
lines changed

.github/workflows/pr-build.yaml

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ jobs:
1919
- name: Setup Go
2020
uses: actions/setup-go@d0a58c1c4d2b25278816e339b944508c875f3613 #v3.4.0
2121
with:
22-
go-version: 1.18.x
22+
go-version: 1.19.x
2323
- name: Restore Go cache
2424
uses: actions/cache@9b0c1fce7a93df8e3bb8926b0d6e9d89e92f20a7 #v3.0.11
2525
with:
@@ -32,18 +32,26 @@ jobs:
3232
with:
3333
version: v0.11.1
3434
image: kindest/node:v1.21.1@sha256:69860bda5563ac81e3c0057d654b5253219618a22ec3a346306239bba8cfa1a6
35-
- name: Setup Kustomize
36-
uses: fluxcd/pkg/actions/kustomize@main
37-
- name: Setup envtest
38-
uses: fluxcd/pkg/actions/envtest@main
39-
with:
40-
version: "1.21.2"
41-
- name: Setup Helm
42-
uses: fluxcd/pkg/actions/helm@main
35+
- name: Setup kustomize
36+
shell: bash
37+
run: |
38+
curl --silent --location --remote-name "https://github.com/kubernetes-sigs/kustomize/releases/download/kustomize%2Fv4.5.7/kustomize_v4.5.7_linux_amd64.tar.gz"
39+
tar xvzf kustomize_v4.5.7_linux_amd64.tar.gz
40+
sudo mv kustomize /usr/local/bin/kustomize
41+
rm -rfv *.tar.gz
42+
kustomize version
43+
- name: Install Helm
44+
uses: azure/setup-helm@f382f75448129b3be48f8121b9857be18d815a82 #v3.4
45+
- name: fmt
46+
run: make fmt
47+
- name: vet
48+
run: make vet
49+
- name: lint
50+
run: make lint
4351
- name: Run tests
4452
run: make test
4553
- name: Send go coverage report
46-
uses: shogo82148/actions-goveralls@v1
54+
uses: shogo82148/actions-goveralls@31ee804b8576ae49f6dc3caa22591bc5080e7920 #v1.6.0
4755
with:
4856
path-to-profile: coverage.out
4957
- name: Check if working tree is dirty

.github/workflows/release.yaml

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ jobs:
1818
uses: actions/checkout@755da8c3cf115ac066823e79a1e1788f8940201b #v3
1919
- uses: actions/setup-go@d0a58c1c4d2b25278816e339b944508c875f3613 #v3.4.0
2020
with:
21-
go-version: '1.18'
21+
go-version: '1.19'
2222
- name: Docker Login
23-
uses: docker/login-action@v2
23+
uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a #v2.1.0
2424
with:
2525
registry: ghcr.io
2626
username: ${{ github.actor }}
@@ -35,5 +35,4 @@ jobs:
3535
version: latest
3636
args: release --rm-dist --skip-validate
3737
env:
38-
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
39-
REPO_TOKEN: ${{ secrets.REPO_TOKEN }}
38+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Makefile

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,14 @@ integrations := $(shell $(GO) list ./... | grep cmd)
2222
PREFIX ?= $(shell pwd)
2323
BIN_DIR ?= $(shell pwd)
2424

25+
# Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set)
26+
ifeq (,$(shell go env GOBIN))
27+
GOBIN=$(shell go env GOPATH)/bin
28+
else
29+
GOBIN=$(shell go env GOBIN)
30+
endif
2531

26-
all: deps vet fmt test build
32+
all: deps vet fmt lint test build
2733

2834
style:
2935
@echo ">> checking code style"
@@ -39,6 +45,15 @@ integrationtest:
3945
@echo ">> running integration tests"
4046
@$(GO) test -short -race -v $(integrations)
4147

48+
GOLANGCI_LINT = $(GOBIN)/golangci-lint
49+
.PHONY: golangci-lint
50+
golangci-lint: ## Download golint locally if necessary
51+
$(call go-install-tool,$(GOLANGCI_LINT),github.com/golangci/golangci-lint/cmd/golangci-lint@v1.49.0)
52+
53+
.PHONY: lint
54+
lint: golangci-lint ## Run golangci-lint against code
55+
$(GOLANGCI_LINT) run ./...
56+
4257
deps:
4358
@echo ">> install dependencies"
4459
@$(GO) mod download
@@ -86,3 +101,16 @@ undeploy-test: ## Undeploy exporter from the K8s cluster specified in ~/.kube/co
86101
$(KUSTOMIZE) build config/test | kubectl delete --ignore-not-found=$(ignore-not-found) -f -
87102

88103
.PHONY: all style fmt build test vet
104+
105+
# go-install-tool will 'go install' any package $2 and install it to $1
106+
define go-install-tool
107+
@[ -f $(1) ] || { \
108+
set -e ;\
109+
TMP_DIR=$$(mktemp -d) ;\
110+
cd $$TMP_DIR ;\
111+
go mod init tmp ;\
112+
echo "Downloading $(2)" ;\
113+
env -i bash -c "GOBIN=$(GOBIN) PATH=$(PATH) GOPATH=$(shell go env GOPATH) GOCACHE=$(shell go env GOCACHE) go install $(2)" ;\
114+
rm -rf $$TMP_DIR ;\
115+
}
116+
endef

cmd/integration_test.go

Lines changed: 84 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,10 @@ func executeIntegrationTest(t *testing.T, test integrationTest) {
7878
container, err := setupMongoDBContainer(context.TODO(), test.mongodbImage)
7979
assert.NoError(t, err)
8080
opts := options.Client().ApplyURI(container.URI)
81-
defer container.Terminate(context.TODO())
81+
82+
defer func() {
83+
assert.NoError(t, container.Terminate(context.TODO()))
84+
}()
8285

8386
client, err := mongo.Connect(context.TODO(), opts)
8487
assert.NoError(t, err)
@@ -92,7 +95,10 @@ func executeIntegrationTest(t *testing.T, test integrationTest) {
9295
b := bytes.NewBufferString("")
9396
rootCmd.SetOut(b)
9497
rootCmd.SetArgs(args)
95-
go rootCmd.Execute()
98+
99+
go func() {
100+
assert.NoError(t, rootCmd.Execute())
101+
}()
96102

97103
//binding is blocking, do this async but wait 200ms for tcp port to be open
98104
time.Sleep(200 * time.Millisecond)
@@ -118,7 +124,7 @@ func executeIntegrationTest(t *testing.T, test integrationTest) {
118124
assert.Len(t, test.expectedMetrics, found)
119125

120126
//tear down http server and unregister collector
121-
srv.Shutdown(context.TODO())
127+
assert.NoError(t, srv.Shutdown(context.TODO()))
122128
prometheus.Unregister(promCollector)
123129
}
124130

@@ -156,40 +162,84 @@ func setupMongoDBContainer(ctx context.Context, image string) (*mongodbContainer
156162
return &mongodbContainer{Container: container, URI: uri}, nil
157163
}
158164

165+
type testRecord struct {
166+
document bson.M
167+
database string
168+
collection string
169+
}
170+
159171
func setupTestData(t *testing.T, client *mongo.Client) {
160172
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
161173
defer cancel()
162174

163-
_, err := client.Database("mydb").Collection("objects").InsertOne(ctx, bson.M{
164-
"foo": "bar",
165-
})
166-
assert.NoError(t, err)
175+
testData := []testRecord{
176+
{
177+
database: "mydb",
178+
collection: "objects",
179+
document: bson.M{
180+
"foo": "bar",
181+
},
182+
},
183+
{
184+
database: "mydb",
185+
collection: "objects",
186+
document: bson.M{
187+
"foo": "foo",
188+
},
189+
},
190+
{
191+
database: "mydb",
192+
collection: "queue",
193+
document: bson.M{
194+
"class": "foobar",
195+
"status": 1,
196+
},
197+
},
198+
{
199+
database: "mydb",
200+
collection: "queue",
201+
document: bson.M{
202+
"class": "foobar",
203+
"status": 1,
204+
},
205+
},
206+
{
207+
database: "mydb",
208+
collection: "queue",
209+
document: bson.M{
210+
"class": "bar",
211+
"status": 2,
212+
},
213+
},
214+
{
215+
database: "mydb",
216+
collection: "events",
217+
document: bson.M{
218+
"type": "bar",
219+
"created": time.Now(),
220+
},
221+
},
222+
{
223+
database: "mydb",
224+
collection: "events",
225+
document: bson.M{
226+
"type": "bar",
227+
"created": time.Now(),
228+
},
229+
},
230+
{
231+
database: "mydb",
232+
collection: "events",
233+
document: bson.M{
234+
"type": "foo",
235+
"created": time.Now(),
236+
},
237+
},
238+
}
239+
240+
for _, record := range testData {
241+
_, err := client.Database(record.database).Collection(record.collection).InsertOne(ctx, record.document)
242+
assert.NoError(t, err)
243+
}
167244

168-
client.Database("mydb").Collection("objects").InsertOne(ctx, bson.M{
169-
"foo": "foo",
170-
})
171-
client.Database("mydb").Collection("queue").InsertOne(ctx, bson.M{
172-
"class": "foobar",
173-
"status": 1,
174-
})
175-
client.Database("mydb").Collection("queue").InsertOne(ctx, bson.M{
176-
"class": "foobar",
177-
"status": 1,
178-
})
179-
client.Database("mydb").Collection("queue").InsertOne(ctx, bson.M{
180-
"class": "bar",
181-
"status": 2,
182-
})
183-
client.Database("mydb").Collection("events").InsertOne(ctx, bson.M{
184-
"type": "bar",
185-
"created": time.Now(),
186-
})
187-
client.Database("mydb").Collection("events").InsertOne(ctx, bson.M{
188-
"type": "bar",
189-
"created": time.Now(),
190-
})
191-
client.Database("mydb").Collection("events").InsertOne(ctx, bson.M{
192-
"type": "foo",
193-
"created": time.Now(),
194-
})
195245
}

cmd/root.go

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ var (
4444
//reg := prometheus.NewRegistry()
4545
prometheus.MustRegister(c)
4646
promCollector = c
47-
c.StartCacheInvalidator()
47+
_ = c.StartCacheInvalidator()
4848
srv = buildHTTPServer(prometheus.DefaultGatherer, conf)
4949
err = srv.ListenAndServe()
5050

@@ -114,7 +114,7 @@ func buildHTTPServer(reg prometheus.Gatherer, conf config.Config) *http.Server {
114114
}
115115

116116
func main() {
117-
rootCmd.Execute()
117+
_ = rootCmd.Execute()
118118
}
119119

120120
func init() {
@@ -126,18 +126,18 @@ func init() {
126126
rootCmd.PersistentFlags().StringVarP(&bind, "bind", "b", config.DefaultBindAddr, "Address to bind http server (default is :9412)")
127127
rootCmd.PersistentFlags().StringVarP(&metricsPath, "path", "p", config.DefaultMetricsPath, "Metric path (default is /metrics)")
128128
rootCmd.PersistentFlags().DurationVarP(&queryTimeout, "query-timeout", "t", config.DefaultQueryTimeout, "Timeout for MongoDB queries")
129-
viper.BindPFlag("log.level", rootCmd.PersistentFlags().Lookup("log-level"))
130-
viper.BindPFlag("log.encoding", rootCmd.PersistentFlags().Lookup("log-encoding"))
131-
viper.BindPFlag("bind", rootCmd.PersistentFlags().Lookup("bind"))
132-
viper.BindPFlag("metricsPath", rootCmd.PersistentFlags().Lookup("path"))
133-
viper.BindPFlag("mongodb.uri", rootCmd.PersistentFlags().Lookup("uri"))
134-
viper.BindPFlag("mongodb.queryTimeout", rootCmd.PersistentFlags().Lookup("query-timeout"))
135-
viper.BindEnv("mongodb.uri", "MDBEXPORTER_MONGODB_URI")
136-
viper.BindEnv("global.queryTimeout", "MDBEXPORTER_MONGODB_QUERY_TIMEOUT")
137-
viper.BindEnv("log.level", "MDBEXPORTER_LOG_LEVEL")
138-
viper.BindEnv("log.encoding", "MDBEXPORTER_LOG_ENCODING")
139-
viper.BindEnv("bind", "MDBEXPORTER_BIND")
140-
viper.BindEnv("metricsPath", "MDBEXPORTER_METRICSPATH")
129+
_ = viper.BindPFlag("log.level", rootCmd.PersistentFlags().Lookup("log-level"))
130+
_ = viper.BindPFlag("log.encoding", rootCmd.PersistentFlags().Lookup("log-encoding"))
131+
_ = viper.BindPFlag("bind", rootCmd.PersistentFlags().Lookup("bind"))
132+
_ = viper.BindPFlag("metricsPath", rootCmd.PersistentFlags().Lookup("path"))
133+
_ = viper.BindPFlag("mongodb.uri", rootCmd.PersistentFlags().Lookup("uri"))
134+
_ = viper.BindPFlag("mongodb.queryTimeout", rootCmd.PersistentFlags().Lookup("query-timeout"))
135+
_ = viper.BindEnv("mongodb.uri", "MDBEXPORTER_MONGODB_URI")
136+
_ = viper.BindEnv("global.queryTimeout", "MDBEXPORTER_MONGODB_QUERY_TIMEOUT")
137+
_ = viper.BindEnv("log.level", "MDBEXPORTER_LOG_LEVEL")
138+
_ = viper.BindEnv("log.encoding", "MDBEXPORTER_LOG_ENCODING")
139+
_ = viper.BindEnv("bind", "MDBEXPORTER_BIND")
140+
_ = viper.BindEnv("metricsPath", "MDBEXPORTER_METRICSPATH")
141141
}
142142

143143
func initConfig() {

collector/collector.go

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ type Collector struct {
1919
servers []*server
2020
logger Logger
2121
config *Config
22-
metrics []*Metric
2322
aggregations []*Aggregation
2423
counter *prometheus.CounterVec
2524
cache map[string]*cacheEntry
@@ -59,7 +58,6 @@ type Aggregation struct {
5958
Pipeline string
6059
Metrics []*Metric
6160
pipeline bson.A
62-
validUntil time.Time
6361
}
6462

6563
// A metric defines how a certain value is exported from a MongoDB aggregation
@@ -445,18 +443,17 @@ func createMetric(metric *Metric, result AggregationResult) (prometheus.Metric,
445443

446444
func (metric *Metric) getValue(result AggregationResult) (float64, error) {
447445
if val, ok := result[metric.Value]; ok {
448-
switch val.(type) {
446+
switch v := val.(type) {
449447
case float32:
450-
value := float64(val.(float32))
448+
value := float64(v)
451449
return value, nil
452450
case float64:
453-
value := val.(float64)
454-
return value, nil
451+
return v, nil
455452
case int32:
456-
value := float64(val.(int32))
453+
value := float64(v)
457454
return value, nil
458455
case int64:
459-
value := float64(val.(int64))
456+
value := float64(v)
460457
return value, nil
461458
default:
462459
return 0, fmt.Errorf("provided value taken from the aggregation result has to be a number, type %T given", val)
@@ -471,9 +468,9 @@ func (metric *Metric) getLabels(result AggregationResult) ([]string, error) {
471468

472469
for _, label := range metric.Labels {
473470
if val, ok := result[label]; ok {
474-
switch val.(type) {
471+
switch v := val.(type) {
475472
case string:
476-
labels = append(labels, val.(string))
473+
labels = append(labels, v)
477474
default:
478475
return labels, fmt.Errorf("provided label value taken from the aggregation result has to be a string, type %T given", val)
479476
}

x/zap/zap.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ func NewConfig() Config {
3333
// Initializes zap logger with environment variable configuration LOG_LEVEL and LOG_FORMAT.
3434
func New(config Config) (*zap.Logger, error) {
3535
var c zap.Config
36-
if config.Development == true {
36+
if config.Development {
3737
c = zap.NewDevelopmentConfig()
3838
c.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
3939
} else {
@@ -58,6 +58,9 @@ func New(config Config) (*zap.Logger, error) {
5858
return nil, err
5959
}
6060

61-
defer logger.Sync()
61+
defer func() {
62+
_ = logger.Sync()
63+
}()
64+
6265
return logger, nil
6366
}

0 commit comments

Comments
 (0)