Skip to content

Commit 1e22102

Browse files
authored
Improve linting (#527)
* Print linter version only in CI * Update golangci-lint to v1.59.1 * Also lint code for build-flag 'tools' * Add linter config .golangci-lint.yml * Satisfy usestdlibvars linter * Satisfy testifylint linter * Satisfy perfsprint linter * Satisfy misspell linter * Satisfy whitespace linter * Satisfy bodyclose linter * Satisfy revive linter * Satisfy gosec linter * Satisfy dupl linter * Satisfy govet linter * Satisfy unparam linter * Satisfy musttag linter * Satisfy gocritic linter * Satisfy goimports linter
1 parent fe9de08 commit 1e22102

33 files changed

+404
-231
lines changed

.golangci.yml

+129
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
service:
2+
golangci-lint-version: 1.59.x
3+
4+
issues:
5+
exclude-dirs:
6+
- artifacts
7+
- build-targets
8+
- design
9+
- docker-images
10+
- docs
11+
- etc
12+
- experiments
13+
- infrastructure
14+
- legal
15+
- libpf-rs
16+
- mocks
17+
- pf-code-indexing-service/cibackend/gomock_*
18+
- pf-debug-metadata-service/dmsbackend/gomock_*
19+
- pf-host-agent/support/ci-kernels
20+
- pf-storage-backend/storagebackend/gomock_*
21+
- scratch
22+
- systemtests/benchmarks/_outdata
23+
- target
24+
- virt-tests
25+
- vm-images
26+
27+
linters:
28+
enable-all: true
29+
disable:
30+
# Disabled because of
31+
# - too many non-sensical warnings
32+
# - not relevant for us
33+
# - false positives
34+
#
35+
# "might be worth fixing" means we should investigate/fix in the mid term
36+
- canonicalheader
37+
- contextcheck # might be worth fixing
38+
- cyclop
39+
- depguard
40+
- dupword
41+
- err113
42+
- errorlint # might be worth fixing
43+
- exhaustive
44+
- exhaustruct
45+
- forbidigo
46+
- forcetypeassert # might be worth fixing
47+
- funlen
48+
- gci # might be worth fixing
49+
- gochecknoglobals
50+
- gochecknoinits
51+
- gocognit
52+
- goconst
53+
- gocyclo
54+
- godot
55+
- godox # complains about TODO etc
56+
- gofumpt
57+
- gomnd
58+
- gomoddirectives
59+
- inamedparam
60+
- interfacebloat
61+
- ireturn
62+
- lll
63+
- maintidx
64+
- makezero
65+
- mnd
66+
- nestif
67+
- nlreturn
68+
- noctx # might be worth fixing
69+
- nolintlint
70+
- nonamedreturns
71+
- paralleltest
72+
- protogetter
73+
- tagalign
74+
- tagliatelle
75+
- testpackage
76+
- thelper
77+
- varnamelen
78+
- wastedassign
79+
- wsl
80+
- wrapcheck
81+
# the following linters are deprecated
82+
- execinquery
83+
# we don't want to change code to Go 1.22+ yet
84+
- intrange
85+
- copyloopvar
86+
87+
linters-settings:
88+
goconst:
89+
min-len: 2
90+
min-occurrences: 2
91+
gocritic:
92+
enabled-tags:
93+
- diagnostic
94+
- experimental
95+
- opinionated
96+
- performance
97+
- style
98+
disabled-checks:
99+
- dupImport # https://github.com/go-critic/go-critic/issues/845
100+
- ifElseChain
101+
- octalLiteral
102+
- whyNoLint
103+
- wrapperFunc
104+
- sloppyReassign
105+
- uncheckedInlineErr # Experimental rule with high false positive rate.
106+
107+
# Broken with Go 1.18 feature (https://github.com/golangci/golangci-lint/issues/2649):
108+
- hugeParam
109+
- rangeValCopy
110+
- typeDefFirst
111+
- paramTypeCombine
112+
gocyclo:
113+
min-complexity: 15
114+
govet:
115+
enable-all: true
116+
disable:
117+
- fieldalignment
118+
settings:
119+
printf: # analyzer name, run `go tool vet help` to see all analyzers
120+
funcs: # run `go tool vet help printf` to see available settings for `printf` analyzer
121+
- debug,debugf,debugln
122+
- error,errorf,errorln
123+
- fatal,fatalf,fataln
124+
- info,infof,infoln
125+
- log,logf,logln
126+
- warn,warnf,warnln
127+
- print,printf,println,sprint,sprintf,sprintln,fprint,fprintf,fprintln
128+
misspell:
129+
locale: US

Makefile

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ SHELL = /bin/bash -eo pipefail
22

33
GORELEASER_VERSION = "v1.19.2"
44
GO_LICENSER_VERSION = "v0.4.0"
5-
GOLANGCI_LINT_VERSION = "v1.54.2"
5+
GOLANGCI_LINT_VERSION = "v1.59.1"
66
export DOCKER_IMAGE_NAME = observability/apm-lambda-extension
77
export DOCKER_REGISTRY = docker.elastic.co
88

@@ -39,8 +39,8 @@ lint-prep:
3939

4040
.PHONY: lint
4141
lint:
42-
@go run github.com/golangci/golangci-lint/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION) version
43-
@go run github.com/golangci/golangci-lint/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION) run
42+
@if [ "$(CI)" != "" ]; then go run github.com/golangci/golangci-lint/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION) version; fi
43+
@go run github.com/golangci/golangci-lint/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION) run --build-tags tools
4444

4545
NOTICE.txt: go.mod
4646
@bash ./scripts/notice.sh

accumulator/batch.go

+11-9
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ var (
3131
// ErrMetadataUnavailable is returned when a lambda data is added to
3232
// the batch without metadata being set.
3333
ErrMetadataUnavailable = errors.New("metadata is not yet available")
34-
// ErrBatchFull signfies that the batch has reached full capacity
34+
// ErrBatchFull signifies that the batch has reached full capacity
3535
// and cannot accept more entries.
3636
ErrBatchFull = errors.New("batch is full")
3737
// ErrInvalidEncoding is returned for any APMData that is encoded
@@ -184,7 +184,7 @@ func (b *Batch) AddAgentData(apmData APMData) error {
184184
return ErrBatchFull
185185
}
186186
if b.currentlyExecutingRequestID == "" {
187-
return fmt.Errorf("lifecycle error, currently executing requestID is not set")
187+
return errors.New("lifecycle error, currently executing requestID is not set")
188188
}
189189
inc, ok := b.invocations[b.currentlyExecutingRequestID]
190190
if !ok {
@@ -218,10 +218,10 @@ func (b *Batch) AddAgentData(apmData APMData) error {
218218
// OnLambdaLogRuntimeDone prepares the data for the invocation to be shipped
219219
// to APM Server. It accepts requestID and status of the invocation both of
220220
// which can be retrieved after parsing `platform.runtimeDone` event.
221-
func (b *Batch) OnLambdaLogRuntimeDone(reqID, status string, time time.Time) error {
221+
func (b *Batch) OnLambdaLogRuntimeDone(reqID, status string, endTime time.Time) error {
222222
b.mu.Lock()
223223
defer b.mu.Unlock()
224-
return b.finalizeInvocation(reqID, status, time)
224+
return b.finalizeInvocation(reqID, status, endTime)
225225
}
226226

227227
func (b *Batch) OnPlatformStart(reqID string) {
@@ -236,6 +236,8 @@ func (b *Batch) PlatformStartReqID() string {
236236
// platform.report event the batch will cleanup any datastructure for the request
237237
// ID. It will return some of the function metadata to allow the caller to enrich
238238
// the report metrics.
239+
//
240+
//nolint:gocritic
239241
func (b *Batch) OnPlatformReport(reqID string) (string, int64, time.Time, error) {
240242
b.mu.Lock()
241243
defer b.mu.Unlock()
@@ -249,7 +251,7 @@ func (b *Batch) OnPlatformReport(reqID string) (string, int64, time.Time, error)
249251

250252
// OnShutdown flushes the data for shipping to APM Server by finalizing all
251253
// the invocation in the batch. If we haven't received a platform.runtimeDone
252-
// event for an invocation so far we won't be able to recieve it in time thus
254+
// event for an invocation so far we won't be able to receive it in time thus
253255
// the status needs to be guessed based on the available information.
254256
func (b *Batch) OnShutdown(status string) error {
255257
b.mu.Lock()
@@ -259,8 +261,8 @@ func (b *Batch) OnShutdown(status string) error {
259261
// TODO: @lahsivjar Is it possible to tweak the extension lifecycle in
260262
// a way that we receive the platform.report metric for a invocation
261263
// consistently and enrich the metrics with reported values?
262-
time := time.Unix(0, inc.DeadlineMs*int64(time.Millisecond))
263-
if err := b.finalizeInvocation(inc.RequestID, status, time); err != nil {
264+
endTime := time.Unix(0, inc.DeadlineMs*int64(time.Millisecond))
265+
if err := b.finalizeInvocation(inc.RequestID, status, endTime); err != nil {
264266
return err
265267
}
266268
delete(b.invocations, inc.RequestID)
@@ -315,12 +317,12 @@ func (b *Batch) ToAPMData() APMData {
315317
}
316318
}
317319

318-
func (b *Batch) finalizeInvocation(reqID, status string, time time.Time) error {
320+
func (b *Batch) finalizeInvocation(reqID, status string, endTime time.Time) error {
319321
inc, ok := b.invocations[reqID]
320322
if !ok {
321323
return fmt.Errorf("invocation for requestID %s does not exist", reqID)
322324
}
323-
proxyTxn, err := inc.MaybeCreateProxyTxn(status, time)
325+
proxyTxn, err := inc.MaybeCreateProxyTxn(status, endTime)
324326
if err != nil {
325327
return err
326328
}

accumulator/batch_test.go

+5-5
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ const metadata = `{"metadata":{"service":{"agent":{"name":"apm-lambda-extension"
3232
func TestAdd(t *testing.T) {
3333
t.Run("empty-without-metadata", func(t *testing.T) {
3434
b := NewBatch(1, time.Hour)
35-
assert.Error(t, b.AddLambdaData([]byte(`{"log":{}}`)), ErrMetadataUnavailable)
35+
assert.ErrorIs(t, b.AddLambdaData([]byte(`{"log":{}}`)), ErrMetadataUnavailable)
3636
})
3737
t.Run("empty-with-metadata", func(t *testing.T) {
3838
b := NewBatch(1, time.Hour)
@@ -96,7 +96,7 @@ func TestLifecycle(t *testing.T) {
9696
reqID := "test-req-id"
9797
fnARN := "test-fn-arn"
9898
lambdaData := `{"log":{"message":"this is log"}}`
99-
txnData := fmt.Sprintf(`{"transaction":{"id":"%s"}}`, "023d90ff77f13b9f")
99+
txnData := `{"transaction":{"id":"023d90ff77f13b9f"}}`
100100
ts := time.Date(2022, time.October, 1, 1, 1, 1, 0, time.UTC)
101101
txnDur := time.Second
102102

@@ -276,12 +276,12 @@ func TestFindEventType(t *testing.T) {
276276
func generateCompleteTxn(t *testing.T, src, result, outcome string, d time.Duration) string {
277277
t.Helper()
278278
tmp, err := sjson.SetBytes([]byte(src), "transaction.result", result)
279-
assert.NoError(t, err)
279+
require.NoError(t, err)
280280
tmp, err = sjson.SetBytes(tmp, "transaction.duration", d.Milliseconds())
281-
assert.NoError(t, err)
281+
require.NoError(t, err)
282282
if outcome != "" {
283283
tmp, err = sjson.SetBytes(tmp, "transaction.outcome", outcome)
284-
assert.NoError(t, err)
284+
require.NoError(t, err)
285285
}
286286
return string(tmp)
287287
}

accumulator/invocation.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ func (inc *Invocation) NeedProxyTransaction() bool {
6363
// has not sent the corresponding transaction to the extension. The
6464
// proxy transaction will not be created if the invocation has
6565
// already been finalized or the agent has reported the transaction.
66-
func (inc *Invocation) MaybeCreateProxyTxn(status string, time time.Time) ([]byte, error) {
66+
func (inc *Invocation) MaybeCreateProxyTxn(status string, endTime time.Time) ([]byte, error) {
6767
if !inc.NeedProxyTransaction() {
6868
return nil, nil
6969
}
@@ -74,7 +74,7 @@ func (inc *Invocation) MaybeCreateProxyTxn(status string, time time.Time) ([]byt
7474
// Transaction duration cannot be known in partial transaction payload. Estimate
7575
// the duration based on the time provided. Time can be based on the runtimeDone
7676
// log record or function deadline.
77-
duration := time.Sub(inc.Timestamp)
77+
duration := endTime.Sub(inc.Timestamp)
7878
txn, err = sjson.SetBytes(txn, "transaction.duration", duration.Milliseconds())
7979
if err != nil {
8080
return nil, err

accumulator/invocation_test.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"time"
2424

2525
"github.com/stretchr/testify/assert"
26+
"github.com/stretchr/testify/require"
2627
)
2728

2829
func TestCreateProxyTransaction(t *testing.T) {
@@ -90,8 +91,8 @@ func TestCreateProxyTransaction(t *testing.T) {
9091
TransactionObserved: tc.txnObserved,
9192
}
9293
result, err := inc.MaybeCreateProxyTxn(tc.runtimeDoneStatus, ts.Add(txnDur))
93-
assert.Nil(t, err)
94-
if len(tc.output) > 0 {
94+
require.NoError(t, err)
95+
if tc.output != "" {
9596
assert.JSONEq(t, tc.output, string(result))
9697
} else {
9798
assert.Nil(t, result)

apmproxy/apmserver.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ func (c *Client) ForwardApmData(ctx context.Context) error {
5656
for {
5757
select {
5858
case <-ctx.Done():
59-
c.logger.Debug("Invocation context cancelled, not processing any more agent data")
59+
c.logger.Debug("Invocation context canceled, not processing any more agent data")
6060
return nil
6161
case data := <-c.AgentDataChannel:
6262
if err := c.forwardAgentData(ctx, data); err != nil {
@@ -312,11 +312,11 @@ func (c *Client) ComputeGracePeriod() time.Duration {
312312
// The grace period for the first reconnection count was 0 but that
313313
// leads to collisions with multiple environments.
314314
if c.ReconnectionCount == 0 {
315-
gracePeriod := rand.Float64() * 5
315+
gracePeriod := rand.Float64() * 5 //nolint:gosec
316316
return time.Duration(gracePeriod * float64(time.Second))
317317
}
318318
gracePeriodWithoutJitter := math.Pow(math.Min(float64(c.ReconnectionCount), 6), 2)
319-
jitter := rand.Float64()/5 - 0.1
319+
jitter := rand.Float64()/5 - 0.1 //nolint:gosec
320320
return time.Duration((gracePeriodWithoutJitter + jitter*gracePeriodWithoutJitter) * float64(time.Second))
321321
}
322322

@@ -334,7 +334,7 @@ func (c *Client) ResetFlush() {
334334
c.flushCh = make(chan struct{})
335335
}
336336

337-
// WaitForFlush returns a channel that is closed when the agent has signalled that
337+
// WaitForFlush returns a channel that is closed when the agent has signaled that
338338
// the Lambda invocation has completed, and there is no more APM data coming.
339339
func (c *Client) WaitForFlush() <-chan struct{} {
340340
c.flushMutex.Lock()

0 commit comments

Comments
 (0)