Skip to content

Commit

Permalink
chore(linters): Fix remaining errcheck warnings (#15518)
Browse files Browse the repository at this point in the history
Co-authored-by: Joshua Powers <[email protected]>
  • Loading branch information
DStrand1 and powersj authored Jul 10, 2024
1 parent a8355c7 commit 19737fc
Show file tree
Hide file tree
Showing 141 changed files with 831 additions and 463 deletions.
10 changes: 2 additions & 8 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ linters-settings:
- "(*hash/maphash.Hash).Write"
- "(*hash/maphash.Hash).WriteByte"
- "(*hash/maphash.Hash).WriteString"
- "(*github.com/influxdata/telegraf/plugins/outputs/postgresql/sqltemplate.Template).UnmarshalText"
check-blank: true
gocritic:
# Disable all checks.
Expand Down Expand Up @@ -335,9 +336,6 @@ issues:
- package comment should be of the form "(.+)...
# EXC0015 revive: Annoying issue about not having a comment. The rare codebase has such comments
- should have a package comment
# nolintlint: directive `//nolint:errcheck` is unused for linter "errcheck"
# temporary while these are being fixed
- directive `//nolint:errcheck //.*` is unused for linter "errcheck"

# Excluding configuration per-path, per-linter, per-text and per-source
exclude-rules:
Expand All @@ -348,11 +346,7 @@ issues:
- path: cmd/telegraf/(main|printer|cmd_plugins).go
text: "Error return value of `outputBuffer.Write` is not checked" #errcheck

# temporary disabling of errcheck as this linter is gradually being applied across the codebase
- path: plugins/inputs/*
linters:
- errcheck
- path: plugins/outputs/*
- path: plugins/inputs/win_perf_counters/pdh.go
linters:
- errcheck

Expand Down
3 changes: 2 additions & 1 deletion plugins/inputs/aliyuncms/aliyuncms_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,8 @@ func TestPluginMetricsInitialize(t *testing.T) {
}

func TestUpdateWindow(t *testing.T) {
duration, _ := time.ParseDuration("1m")
duration, err := time.ParseDuration("1m")
require.NoError(t, err)
internalDuration := config.Duration(duration)

plugin := &AliyunCMS{
Expand Down
13 changes: 9 additions & 4 deletions plugins/inputs/amd_rocm_smi/amd_rocm_smi.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package amd_rocm_smi
import (
_ "embed"
"encoding/json"
"fmt"
"os"
"os/exec"
"strconv"
Expand Down Expand Up @@ -33,7 +34,10 @@ func (*ROCmSMI) SampleConfig() string {

// Gather implements the telegraf interface
func (rsmi *ROCmSMI) Gather(acc telegraf.Accumulator) error {
data := rsmi.pollROCmSMI()
data, err := rsmi.pollROCmSMI()
if err != nil {
return fmt.Errorf("failed to execute command in pollROCmSMI: %w", err)
}

return gatherROCmSMI(data, acc)
}
Expand Down Expand Up @@ -61,7 +65,7 @@ func init() {
})
}

func (rsmi *ROCmSMI) pollROCmSMI() []byte {
func (rsmi *ROCmSMI) pollROCmSMI() ([]byte, error) {
// Construct and execute metrics query, there currently exist (ROCm v4.3.x) a "-a" option
// that does not provide all the information, so each needed parameter is set manually
cmd := exec.Command(rsmi.BinPath,
Expand Down Expand Up @@ -104,8 +108,7 @@ func (rsmi *ROCmSMI) pollROCmSMI() []byte {
"--showtoponuma",
"--json")

ret, _ := internal.StdOutputTimeout(cmd, time.Duration(rsmi.Timeout))
return ret
return internal.StdOutputTimeout(cmd, time.Duration(rsmi.Timeout))
}

func gatherROCmSMI(ret []byte, acc telegraf.Accumulator) error {
Expand Down Expand Up @@ -145,7 +148,9 @@ func genTagsFields(gpus map[string]GPU, system map[string]sysInfo) []metric {
fields := map[string]interface{}{}

payload := gpus[cardID]
//nolint:errcheck // silently treat as zero if malformed
totVRAM, _ := strconv.ParseInt(payload.GpuVRAMTotalMemory, 10, 64)
//nolint:errcheck // silently treat as zero if malformed
usdVRAM, _ := strconv.ParseInt(payload.GpuVRAMTotalUsedMemory, 10, 64)
strFree := strconv.FormatInt(totVRAM-usdVRAM, 10)

Expand Down
12 changes: 9 additions & 3 deletions plugins/inputs/bcache/bcache.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,12 @@ type Bcache struct {
}

func getTags(bdev string) map[string]string {
//nolint:errcheck // unable to propagate
backingDevFile, _ := os.Readlink(bdev)
backingDevPath := strings.Split(backingDevFile, "/")
backingDev := backingDevPath[len(backingDevPath)-2]

//nolint:errcheck // unable to propagate
bcacheDevFile, _ := os.Readlink(bdev + "/dev")
bcacheDevPath := strings.Split(bcacheDevFile, "/")
bcacheDev := bcacheDevPath[len(bcacheDevPath)-1]
Expand All @@ -52,6 +54,7 @@ func prettyToBytes(v string) uint64 {
v = v[:len(v)-1]
factor = factors[prefix]
}
//nolint:errcheck // unable to propagate
result, _ := strconv.ParseFloat(v, 32)
result = result * float64(factor)

Expand Down Expand Up @@ -88,7 +91,10 @@ func (b *Bcache) gatherBcache(bdev string, acc telegraf.Accumulator) error {
value := prettyToBytes(rawValue)
fields[key] = value
} else {
value, _ := strconv.ParseUint(rawValue, 10, 64)
value, err := strconv.ParseUint(rawValue, 10, 64)
if err != nil {
return err
}
fields[key] = value
}
}
Expand All @@ -114,8 +120,8 @@ func (b *Bcache) Gather(acc telegraf.Accumulator) error {
if len(bcachePath) == 0 {
bcachePath = "/sys/fs/bcache"
}
bdevs, _ := filepath.Glob(bcachePath + "/*/bdev*")
if len(bdevs) < 1 {
bdevs, err := filepath.Glob(bcachePath + "/*/bdev*")
if len(bdevs) < 1 || err != nil {
return errors.New("can't find any bcache device")
}
for _, bdev := range bdevs {
Expand Down
15 changes: 9 additions & 6 deletions plugins/inputs/bind/bind_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import (
func TestBindJsonStats(t *testing.T) {
ts := httptest.NewServer(http.FileServer(http.Dir("testdata")))
url := ts.Listener.Addr().String()
host, port, _ := net.SplitHostPort(url)
host, port, err := net.SplitHostPort(url)
require.NoError(t, err)
defer ts.Close()

b := Bind{
Expand All @@ -28,7 +29,7 @@ func TestBindJsonStats(t *testing.T) {
}

var acc testutil.Accumulator
err := acc.GatherError(b.Gather)
err = acc.GatherError(b.Gather)

require.NoError(t, err)

Expand Down Expand Up @@ -188,7 +189,8 @@ func TestBindJsonStats(t *testing.T) {
func TestBindXmlStatsV2(t *testing.T) {
ts := httptest.NewServer(http.FileServer(http.Dir("testdata")))
url := ts.Listener.Addr().String()
host, port, _ := net.SplitHostPort(url)
host, port, err := net.SplitHostPort(url)
require.NoError(t, err)
defer ts.Close()

b := Bind{
Expand All @@ -201,7 +203,7 @@ func TestBindXmlStatsV2(t *testing.T) {
}

var acc testutil.Accumulator
err := acc.GatherError(b.Gather)
err = acc.GatherError(b.Gather)

require.NoError(t, err)

Expand Down Expand Up @@ -393,7 +395,8 @@ func TestBindXmlStatsV2(t *testing.T) {
func TestBindXmlStatsV3(t *testing.T) {
ts := httptest.NewServer(http.FileServer(http.Dir("testdata")))
url := ts.Listener.Addr().String()
host, port, _ := net.SplitHostPort(url)
host, port, err := net.SplitHostPort(url)
require.NoError(t, err)
defer ts.Close()

b := Bind{
Expand All @@ -406,7 +409,7 @@ func TestBindXmlStatsV3(t *testing.T) {
}

var acc testutil.Accumulator
err := acc.GatherError(b.Gather)
err = acc.GatherError(b.Gather)

require.NoError(t, err)

Expand Down
5 changes: 4 additions & 1 deletion plugins/inputs/bind/json_stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,10 @@ func (b *Bind) addStatsJSON(stats jsonStats, acc telegraf.Accumulator, urlTag st
grouper := metric.NewSeriesGrouper()
ts := time.Now()
tags := map[string]string{"url": urlTag}
host, port, _ := net.SplitHostPort(urlTag)
host, port, err := net.SplitHostPort(urlTag)
if err != nil {
acc.AddError(err)
}
tags["source"] = host
tags["port"] = port

Expand Down
5 changes: 4 additions & 1 deletion plugins/inputs/bind/xml_stats_v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,10 @@ func (b *Bind) readStatsXMLv2(addr *url.URL, acc telegraf.Accumulator) error {
}

tags := map[string]string{"url": addr.Host}
host, port, _ := net.SplitHostPort(addr.Host)
host, port, err := net.SplitHostPort(addr.Host)
if err != nil {
return fmt.Errorf("unable to parse address host %q: %w", addr.Host, err)
}
tags["source"] = host
tags["port"] = port

Expand Down
5 changes: 4 additions & 1 deletion plugins/inputs/bind/xml_stats_v3.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ type v3CounterGroup struct {
func (b *Bind) addStatsXMLv3(stats v3Stats, acc telegraf.Accumulator, hostPort string) {
grouper := metric.NewSeriesGrouper()
ts := time.Now()
host, port, _ := net.SplitHostPort(hostPort)
host, port, err := net.SplitHostPort(hostPort)
if err != nil {
acc.AddError(err)
}
// Counter groups
for _, cg := range stats.Server.CounterGroups {
for _, c := range cg.Counters {
Expand Down
4 changes: 3 additions & 1 deletion plugins/inputs/bond/bond.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,9 @@ func (bond *Bond) gatherSysDetails(bondName string, files sysFiles, acc telegraf
interacting with the upstream switch ports
a failed conversion can be treated as 0 ports
*/
adPortCount, _ = strconv.Atoi(strings.TrimSpace(files.ADPortsFile))
if pc, err := strconv.Atoi(strings.TrimSpace(files.ADPortsFile)); err == nil {
adPortCount = pc
}
} else {
adPortCount = len(slaves)
}
Expand Down
5 changes: 4 additions & 1 deletion plugins/inputs/burrow/burrow_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ func getResponseJSON(requestURI string) ([]byte, int) {
}

// respond with file
b, _ := os.ReadFile(jsonFile)
b, err := os.ReadFile(jsonFile)
if err != nil {
panic(err)
}
return b, code
}

Expand Down
16 changes: 8 additions & 8 deletions plugins/inputs/chrony/chrony_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -802,14 +802,14 @@ func (s *Server) serve(t *testing.T) {
t.Log("mock server [source stats]: successfully wrote reply")
}
case 44: // activity
_, err := s.conn.WriteTo(s.encodeActivityReply(seqno), addr)
_, err := s.conn.WriteTo(s.encodeActivityReply(seqno, t), addr)
if err != nil {
t.Logf("mock server [activity]: writing reply failed: %v", err)
} else {
t.Log("mock server [activity]: successfully wrote reply")
}
case 54: // server stats
_, err := s.conn.WriteTo(s.encodeServerStatsReply(seqno), addr)
_, err := s.conn.WriteTo(s.encodeServerStatsReply(seqno, t), addr)
if err != nil {
t.Logf("mock server [serverstats]: writing reply failed: %v", err)
} else {
Expand All @@ -833,13 +833,13 @@ func (s *Server) serve(t *testing.T) {
}
}

func (s *Server) encodeActivityReply(sequence uint32) []byte {
func (s *Server) encodeActivityReply(sequence uint32, t *testing.T) []byte {
// Encode the header
buf := encodeHeader(44, 12, 0, sequence) // activity request

// Encode data
b := bytes.NewBuffer(buf)
_ = binary.Write(b, binary.BigEndian, s.ActivityInfo)
require.NoError(t, binary.Write(b, binary.BigEndian, s.ActivityInfo))

return b.Bytes()
}
Expand Down Expand Up @@ -873,7 +873,7 @@ func (s *Server) encodeTrackingReply(sequence uint32) []byte {
return buf
}

func (s *Server) encodeServerStatsReply(sequence uint32) []byte {
func (s *Server) encodeServerStatsReply(sequence uint32, t *testing.T) []byte {
var b *bytes.Buffer
switch info := s.ServerStatInfo.(type) {
case *fbchrony.ServerStats:
Expand All @@ -882,21 +882,21 @@ func (s *Server) encodeServerStatsReply(sequence uint32) []byte {

// Encode data
b = bytes.NewBuffer(buf)
_ = binary.Write(b, binary.BigEndian, info)
require.NoError(t, binary.Write(b, binary.BigEndian, info))
case *fbchrony.ServerStats2:
// Encode the header
buf := encodeHeader(54, 22, 0, sequence) // activity request

// Encode data
b = bytes.NewBuffer(buf)
_ = binary.Write(b, binary.BigEndian, info)
require.NoError(t, binary.Write(b, binary.BigEndian, info))
case *fbchrony.ServerStats3:
// Encode the header
buf := encodeHeader(54, 24, 0, sequence) // activity request

// Encode data
b = bytes.NewBuffer(buf)
_ = binary.Write(b, binary.BigEndian, info)
require.NoError(t, binary.Write(b, binary.BigEndian, info))
}

return b.Bytes()
Expand Down
6 changes: 5 additions & 1 deletion plugins/inputs/clickhouse/clickhouse.go
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,10 @@ func (ch *ClickHouse) execQuery(address *url.URL, query string, i interface{}) e
q := address.Query()
q.Set("query", query+" FORMAT JSON")
address.RawQuery = q.Encode()
req, _ := http.NewRequest("GET", address.String(), nil)
req, err := http.NewRequest("GET", address.String(), nil)
if err != nil {
return err
}
if ch.Username != "" {
req.Header.Add("X-ClickHouse-User", ch.Username)
}
Expand All @@ -542,6 +545,7 @@ func (ch *ClickHouse) execQuery(address *url.URL, query string, i interface{}) e
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode >= 300 {
//nolint:errcheck // reading body for error reporting
body, _ := io.ReadAll(io.LimitReader(resp.Body, 200))
return &clickhouseError{
StatusCode: resp.StatusCode,
Expand Down
6 changes: 4 additions & 2 deletions plugins/inputs/cloud_pubsub/cloud_pubsub_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ func TestRunParse(t *testing.T) {
}
sub.receiver = testMessagesReceive(sub)

decoder, _ := internal.NewContentDecoder("identity")
decoder, err := internal.NewContentDecoder("identity")
require.NoError(t, err)

ps := &PubSub{
Log: testutil.Logger{},
Expand Down Expand Up @@ -74,7 +75,8 @@ func TestRunBase64(t *testing.T) {
}
sub.receiver = testMessagesReceive(sub)

decoder, _ := internal.NewContentDecoder("identity")
decoder, err := internal.NewContentDecoder("identity")
require.NoError(t, err)

ps := &PubSub{
Log: testutil.Logger{},
Expand Down
Loading

0 comments on commit 19737fc

Please sign in to comment.