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 0d5238c
Show file tree
Hide file tree
Showing 31 changed files with 79 additions and 86 deletions.
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
8 changes: 4 additions & 4 deletions datadog/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import (
"log"
"net"
"os"
"syscall"
"time"

"github.com/segmentio/stats/v4"
"golang.org/x/sys/unix"
)

const (
Expand Down Expand Up @@ -158,7 +158,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 +169,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 +194,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
}
8 changes: 3 additions & 5 deletions datadog/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,15 @@ package datadog
import (
"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 @@ -117,7 +115,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 +134,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
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)
}
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
4 changes: 2 additions & 2 deletions field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func BenchmarkAssign40BytesStruct(b *testing.B) {
c int
}

s := S{}
s := S{b: "", c: 0}

Check failure on line 20 in field_test.go

View workflow job for this annotation

GitHub Actions / lint

ineffectual assignment to s (ineffassign)

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

Check failure on line 31 in field_test.go

View workflow job for this annotation

GitHub Actions / lint

field `b` is unused (unused)
}

s := S{}
var s S

for i := 0; i != b.N; i++ {
s = S{a: "hello"}
Expand Down
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
)
4 changes: 2 additions & 2 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 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
4 changes: 2 additions & 2 deletions grafana/search_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 Down Expand Up @@ -44,7 +44,7 @@ func TestSearchHandler(t *testing.T) {
}
defer r.Body.Close()

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

if s := string(found); s != expect {
Expand Down
2 changes: 1 addition & 1 deletion handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,4 @@ var Discard = &discard{}

type discard struct{}

func (*discard) HandleMeasures(time time.Time, measures ...Measure) {}
func (*discard) HandleMeasures(time.Time, ...Measure) {}
3 changes: 2 additions & 1 deletion httpstats/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ func TestRequestContextTagPropegation(t *testing.T) {
assert.Equal(t, 0, len(RequestTags(x)), "Original request should have no tags (because no context with key)")

// create a child request which creates a child context
z := y.WithContext(context.WithValue(y.Context(), interface{}("not"), "important"))
type contextVal struct{}
z := y.WithContext(context.WithValue(y.Context(), contextVal{}, "important"))
assert.Equal(t, 1, len(RequestTags(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
4 changes: 2 additions & 2 deletions httpstats/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,14 @@ type nullBody struct{}

func (n *nullBody) Close() error { return nil }

func (n *nullBody) Read(b []byte) (int, error) { return 0, io.EOF }
func (n *nullBody) Read([]byte) (int, error) { return 0, io.EOF }

type requestBody struct {
body io.ReadCloser
eng *stats.Engine
req *http.Request
metrics *metrics
bytes int
req *http.Request
op string
once sync.Once
}
Expand Down
6 changes: 3 additions & 3 deletions procstats/delaystats_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@ package procstats

import (
"errors"
"syscall"

"github.com/mdlayher/taskstats"
"golang.org/x/sys/unix"
)

func collectDelayInfo(pid int) DelayInfo {
client, err := taskstats.New()
if err == syscall.ENOENT {
if err == unix.ENOENT {
err = errors.New("failed to communicate with taskstats Netlink family, ensure this program is not running in a network namespace")
}
check(err)

stats, err := client.TGID(pid)
if err == syscall.EPERM {
if err == unix.EPERM {
err = errors.New("failed to open Netlink socket: permission denied, ensure CAP_NET_RAW is enabled for this process, or run it with root privileges")
}
check(err)
Expand Down
9 changes: 5 additions & 4 deletions procstats/linux/memory_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import (
"path/filepath"
"strconv"
"strings"
"syscall"

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

func readMemoryLimit(pid int) (limit uint64, err error) {
Expand Down Expand Up @@ -54,10 +55,10 @@ func readMemoryCGroupMemoryLimitFilePath(cgroupPath string) string {
}

func readSysinfoMemoryLimit() (limit uint64, err error) {
var sysinfo syscall.Sysinfo_t
var sysinfo unix.Sysinfo_t

if err = syscall.Sysinfo(&sysinfo); err == nil {
// syscall.Sysinfo returns an uint32 on linux/arm, but uint64 otherwise
if err = unix.Sysinfo(&sysinfo); err == nil {
// unix.Sysinfo returns an uint32 on linux/arm, but uint64 otherwise
limit = uint64(sysinfo.Unit) * uint64(sysinfo.Totalram)
}

Expand Down
7 changes: 4 additions & 3 deletions procstats/linux/stat.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ const (
TracingStop ProcState = 't'
Paging ProcState = 'P'
Dead ProcState = 'X'
Dead_ ProcState = 'x'
Wakekill ProcState = 'W'
Parked ProcState = 'P'
//revive:disable-next-line
Dead_ ProcState = 'x'
Wakekill ProcState = 'W'
Parked ProcState = 'P'
)

// Scan updates the ProcState for a process.
Expand Down
2 changes: 1 addition & 1 deletion procstats/proc.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ func (p *ProcMetrics) Collect() {
now := time.Now()

if !p.lastTime.IsZero() {
ratio := 1.0
var ratio float64
switch {
case m.CPU.Period > 0 && m.CPU.Quota > 0:
ratio = float64(m.CPU.Quota) / float64(m.CPU.Period)
Expand Down
Loading

0 comments on commit 0d5238c

Please sign in to comment.