Skip to content

Commit

Permalink
all: fix lint issues
Browse files Browse the repository at this point in the history
We turned on the linter to lint the "main" branch and any release
branches, but we never actually fixed any of the issues reported by
the linter. This is an attempt to do so. A lot of red herrings but
some legitimate errors.

Not strictly reported by the linter, but replace "syscall" uses with
"x/sys/unix", as is recommended.
  • Loading branch information
kevinburkesegment committed Jun 21, 2024
1 parent 982af24 commit 59b8039
Show file tree
Hide file tree
Showing 41 changed files with 117 additions and 110 deletions.
6 changes: 3 additions & 3 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
run:
deadline: 5m
skip-files:
# Skip autogenerated files.
- ^.*\.(pb|y)\.go$

output:
sort-results: true
Expand All @@ -20,6 +17,9 @@ linters:
- misspell

issues:
exclude-files:
# Skip autogenerated files.
- ^.*\.(pb|y)\.go$
exclude-rules:
- path: _test.go
linters:
Expand Down
2 changes: 1 addition & 1 deletion buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ func (b *buffer) len() int {
}

func (b *buffer) flush(w io.Writer, n int) {
w.Write(b.data[:n])
_, _ = w.Write(b.data[:n])
n = copy(b.data, b.data[n:])
b.data = b.data[:n]
}
14 changes: 5 additions & 9 deletions cmd/dogstatsd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func client(cmd string, args ...string) {
args, extra = split(args, "--")
fset.StringVar(&addr, "addr", "localhost:8125", "The network address where a dogstatsd server is listening for incoming UDP datagrams")
fset.Var(&tags, "tags", "A comma-separated list of tags to set on the metric")
fset.Parse(args)
_ = fset.Parse(args)
args = fset.Args()

if len(args) == 0 {
Expand All @@ -74,17 +74,13 @@ func client(cmd string, args ...string) {
value = 1.0
} else if value, err = strconv.ParseFloat(args[0], 64); err != nil {
errorf("bad metric value: %s", args[0])
} else {
args = args[1:]
}

case "set":
if len(args) == 0 {
errorf("missing metric value")
} else if value, err = strconv.ParseFloat(args[0], 64); err != nil {
errorf("bad metric value: %s", args[0])
} else {
args = args[1:]
}
}

Expand All @@ -110,19 +106,19 @@ func server(args ...string) {
var bind string

fset.StringVar(&bind, "bind", ":8125", "The network address to listen on for incoming UDP datagrams")
fset.Parse(args)
_ = fset.Parse(args)
log.Printf("listening for incoming UDP datagram on %s", bind)

datadog.ListenAndServe(bind, handlers{})
_ = datadog.ListenAndServe(bind, handlers{})
}

type handlers struct{}

func (h handlers) HandleMetric(m datadog.Metric, a net.Addr) {
func (h handlers) HandleMetric(m datadog.Metric, _ net.Addr) {
log.Print(m)
}

func (h handlers) HandleEvent(e datadog.Event, a net.Addr) {
func (h handlers) HandleEvent(e datadog.Event, _ net.Addr) {
log.Print(e)
}

Expand Down
3 changes: 2 additions & 1 deletion context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ func TestContextTags(t *testing.T) {
assert.Equal(t, 0, len(ContextTags(x)), "Original context should have no tags (because no context with key)")

// create a child context which creates a child context
z := context.WithValue(y, interface{}("not"), "important")
type unimportant struct{}
z := context.WithValue(y, unimportant{}, "important")
assert.Equal(t, 1, len(ContextTags(z)), "We should still be able to see original tags")

// Add tags to the child context's reference to the original tag slice
Expand Down
2 changes: 1 addition & 1 deletion datadog/append_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import "testing"

func TestAppendMetric(t *testing.T) {
for _, test := range testMetrics {
t.Run(test.m.Name, func(b *testing.T) {
t.Run(test.m.Name, func(t *testing.T) {
if s := string(appendMetric(nil, test.m)); s != test.s {
t.Errorf("\n<<< %#v\n>>> %#v", test.s, s)
}
Expand Down
9 changes: 5 additions & 4 deletions datadog/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import (
"log"
"net"
"os"
"syscall"
"time"

"github.com/segmentio/stats/v4"

"golang.org/x/sys/unix"
)

const (
Expand Down Expand Up @@ -158,7 +159,7 @@ func dial(address string, sizehint int) (conn net.Conn, bufsize int, err error)
// sent in one batch we attempt to attempt to adjust the kernel buffer size
// to accept larger datagrams, or fallback to the default socket buffer size
// if it failed.
if bufsize, err = syscall.GetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_SNDBUF); err != nil {
if bufsize, err = unix.GetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_SNDBUF); err != nil {
conn.Close()
return
}
Expand All @@ -169,7 +170,7 @@ func dial(address string, sizehint int) (conn net.Conn, bufsize int, err error)
bufsize /= 2

for sizehint > bufsize && sizehint > 0 {
if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, sizehint); err == nil {
if err := unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_SNDBUF, sizehint); err == nil {
bufsize = sizehint
break
}
Expand All @@ -194,6 +195,6 @@ func dial(address string, sizehint int) (conn net.Conn, bufsize int, err error)
}

// Creating the file put the socket in blocking mode, reverting.
syscall.SetNonblock(fd, true)
_ = unix.SetNonblock(fd, true)
return
}
28 changes: 19 additions & 9 deletions datadog/client_test.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
package datadog

import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"strings"
"sync/atomic"
"testing"
"time"

"github.com/stretchr/testify/assert"

"github.com/segmentio/stats/v4"

"github.com/stretchr/testify/assert"
)

func TestClient(t *testing.T) {
Expand Down Expand Up @@ -72,7 +72,7 @@ func TestClientWithUseDistributions(t *testing.T) {
UseDistributions: true,
})

testMeassure := stats.Measure{
testMeasure := stats.Measure{
Name: "request",
Fields: []stats.Field{
{Name: "count", Value: stats.ValueOf(5)},
Expand All @@ -83,14 +83,14 @@ func TestClientWithUseDistributions(t *testing.T) {
stats.T("hello", "world"),
},
}
client.HandleMeasures(time.Time{}, testMeassure)
client.HandleMeasures(time.Time{}, testMeasure)
client.Flush()

expectedPacket1 := "request.count:5|c|#answer:42,hello:world\nrequest.dist_rtt:0.1|d|#answer:42,hello:world\n"
assert.EqualValues(t, expectedPacket1, string(<-packets))

client.useDistributions = false
client.HandleMeasures(time.Time{}, testMeassure)
client.HandleMeasures(time.Time{}, testMeasure)
client.Flush()

expectedPacket2 := "request.count:5|c|#answer:42,hello:world\nrequest.dist_rtt:0.1|h|#answer:42,hello:world\n"
Expand All @@ -117,7 +117,7 @@ main.http.rtt.seconds:0.001215296|h|#http_req_content_charset:,http_req_content_
count := int32(0)
expect := int32(strings.Count(data, "\n"))

addr, closer := startTestServer(t, HandlerFunc(func(m Metric, _ net.Addr) {
addr, closer := startTestServer(t, HandlerFunc(func(_ Metric, _ net.Addr) {
atomic.AddInt32(&count, 1)
}))
defer closer.Close()
Expand All @@ -136,7 +136,7 @@ main.http.rtt.seconds:0.001215296|h|#http_req_content_charset:,http_req_content_
}

func BenchmarkClient(b *testing.B) {
log.SetOutput(ioutil.Discard)
log.SetOutput(io.Discard)

for _, N := range []int{1, 10, 100} {
b.Run(fmt.Sprintf("write a batch of %d measures to a client", N), func(b *testing.B) {
Expand Down Expand Up @@ -169,6 +169,14 @@ func BenchmarkClient(b *testing.B) {
}
}

func isClosedNetworkConnectionErr(err error) bool {
var netErr *net.OpError
if errors.As(err, &netErr) {
return strings.Contains(netErr.Err.Error(), "use of closed network connection")
}
return false
}

// startUDPListener starts a goroutine listening for UDP packets on 127.0.0.1 and an available port.
// The address listened to is returned as `addr`. The payloads of packets received are copied to `packets`.
func startUDPListener(t *testing.T, packets chan []byte) (addr string, closer io.Closer) {
Expand All @@ -186,7 +194,9 @@ func startUDPListener(t *testing.T, packets chan []byte) (addr string, closer io
}

if err != nil {
t.Log(err)
if !isClosedNetworkConnectionErr(err) {
fmt.Println("err reading from UDP connection in goroutine:", err)
}
return
}
}
Expand Down
2 changes: 1 addition & 1 deletion datadog/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,6 @@ func (e Event) String() string {
func (e Event) Format(f fmt.State, _ rune) {
buf := bufferPool.Get().(*buffer)
buf.b = appendEvent(buf.b[:0], e)
f.Write(buf.b)
_, _ = f.Write(buf.b)
bufferPool.Put(buf)
}
2 changes: 1 addition & 1 deletion datadog/metric.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (m Metric) String() string {
func (m Metric) Format(f fmt.State, _ rune) {
buf := bufferPool.Get().(*buffer)
buf.b = appendMetric(buf.b[:0], m)
f.Write(buf.b)
_, _ = f.Write(buf.b)
bufferPool.Put(buf)
}

Expand Down
4 changes: 1 addition & 3 deletions datadog/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ func (f HandlerFunc) HandleMetric(m Metric, a net.Addr) {
}

// HandleEvent is a no-op for backwards compatibility.
func (f HandlerFunc) HandleEvent(Event, net.Addr) {
return
}
func (f HandlerFunc) HandleEvent(Event, net.Addr) {}

// ListenAndServe starts a new dogstatsd server, listening for UDP datagrams on
// addr and forwarding the metrics to handler.
Expand Down
5 changes: 5 additions & 0 deletions engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ func TestEngine(t *testing.T) {
scenario: "calling Engine.Clock produces expected metrics",
function: testEngineClock,
},
{
scenario: "calling Engine.WithTags produces expected tags",
function: testEngineWithTags,
},
}

for _, test := range tests {
Expand Down Expand Up @@ -307,6 +311,7 @@ func checkMeasuresEqual(t *testing.T, eng *stats.Engine, expected ...stats.Measu
}

func measures(t *testing.T, eng *stats.Engine) []stats.Measure {
t.Helper()
return eng.Handler.(*statstest.Handler).Measures()
}

Expand Down
8 changes: 4 additions & 4 deletions field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ func BenchmarkAssign40BytesStruct(b *testing.B) {
c int
}

s := S{}
var s S

for i := 0; i != b.N; i++ {
s = S{a: "hello"}
s = S{a: "hello", b: "", c: 0}
_ = s
}
}
Expand All @@ -31,10 +31,10 @@ func BenchmarkAssign32BytesStruct(b *testing.B) {
b string
}

s := S{}
var s S

for i := 0; i != b.N; i++ {
s = S{a: "hello"}
s = S{a: "hello", b: ""}
_ = s
}
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ require (
github.com/stretchr/testify v1.8.4
golang.org/x/exp v0.0.0-20231206192017-f3f8817b8deb
golang.org/x/sync v0.3.0
golang.org/x/sys v0.12.0
)

require github.com/davecgh/go-spew v1.1.1 // indirect
Expand All @@ -20,7 +21,6 @@ require (
github.com/mdlayher/netlink v0.0.0-20190313131330-258ea9dff42c // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/net v0.7.0 // indirect
golang.org/x/sys v0.12.0 // indirect
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
2 changes: 1 addition & 1 deletion grafana/annotations.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ type annotationsResponse struct {
}

func (res *annotationsResponse) WriteAnnotation(a Annotation) {
res.enc.Encode(annotationInfo{
_ = res.enc.Encode(annotationInfo{
Annotation: annotation{
Name: res.name,
Datasource: res.datasource,
Expand Down
6 changes: 3 additions & 3 deletions grafana/annotations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"testing"
Expand All @@ -28,7 +28,7 @@ func TestAnnotationsHandler(t *testing.T) {

client := http.Client{}
server := httptest.NewServer(NewAnnotationsHandler(
AnnotationsHandlerFunc(func(ctx context.Context, res AnnotationsResponse, req *AnnotationsRequest) error {
AnnotationsHandlerFunc(func(_ context.Context, res AnnotationsResponse, req *AnnotationsRequest) error {
if !req.From.Equal(ar.Range.From) {
t.Error("bad 'from' time:", req.From, ar.Range.From)
}
Expand Down Expand Up @@ -79,7 +79,7 @@ func TestAnnotationsHandler(t *testing.T) {
}
defer r.Body.Close()

found, _ := ioutil.ReadAll(r.Body)
found, _ := io.ReadAll(r.Body)
expect := annotationsResult

if s := string(found); s != expect {
Expand Down
2 changes: 1 addition & 1 deletion grafana/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func Handle(mux *http.ServeMux, prefix string, handler Handler) {
if _, pattern := mux.Handler(&http.Request{
URL: &url.URL{Path: root},
}); len(pattern) == 0 {
mux.HandleFunc(root, func(res http.ResponseWriter, req *http.Request) {
mux.HandleFunc(root, func(res http.ResponseWriter, _ *http.Request) {
setResponseHeaders(res)
})
}
Expand Down
4 changes: 2 additions & 2 deletions grafana/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,13 +191,13 @@ func (res *queryResponse) close() error {

func (res *queryResponse) flush() {
if res.timeserie != nil {
res.enc.Encode(res.timeserie)
_ = res.enc.Encode(res.timeserie)
res.timeserie.closed = true
res.timeserie = nil
}

if res.table != nil {
res.enc.Encode(res.table)
_ = res.enc.Encode(res.table)
res.table.closed = true
res.table = nil
}
Expand Down
2 changes: 1 addition & 1 deletion grafana/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func TestQueryHandler(t *testing.T) {

client := http.Client{}
server := httptest.NewServer(NewQueryHandler(
QueryHandlerFunc(func(ctx context.Context, res QueryResponse, req *QueryRequest) error {
QueryHandlerFunc(func(_ context.Context, res QueryResponse, req *QueryRequest) error {
if !req.From.Equal(t0) {
t.Error("bad 'from' time:", req.From, "!=", t0)
}
Expand Down
Loading

0 comments on commit 59b8039

Please sign in to comment.