Skip to content

Commit

Permalink
Fixed almost all bugs found by LGTM analysis platform (#8240)
Browse files Browse the repository at this point in the history
  • Loading branch information
zak-pawel authored Oct 8, 2020
1 parent 5cc4387 commit c8e69ac
Show file tree
Hide file tree
Showing 27 changed files with 98 additions and 46 deletions.
3 changes: 2 additions & 1 deletion plugins/common/encoding/decoder_reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ func (r *Reader) Read(p []byte) (int, error) {
r.err = nil
r.transformComplete = false

n, err := 0, error(nil)
n := 0
for {
// Copy out any transformed bytes and return the final error if we are done.
if r.dst0 != r.dst1 {
Expand All @@ -131,6 +131,7 @@ func (r *Reader) Read(p []byte) (int, error) {
// As the io.Reader documentation says, "process the n > 0 bytes returned
// before considering the error".
if r.src0 != r.src1 || r.err != nil {
var err error
r.dst0 = 0
r.dst1, n, err = r.t.Transform(r.dst, r.src[r.src0:r.src1], r.err == io.EOF)
r.src0 += n
Expand Down
7 changes: 5 additions & 2 deletions plugins/inputs/bcache/bcache.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,11 @@ func prettyToBytes(v string) uint64 {
func (b *Bcache) gatherBcache(bdev string, acc telegraf.Accumulator) error {
tags := getTags(bdev)
metrics, err := filepath.Glob(bdev + "/stats_total/*")
if len(metrics) < 0 {
return errors.New("Can't read any stats file")
if err != nil {
return err
}
if len(metrics) == 0 {
return errors.New("can't read any stats file")
}
file, err := ioutil.ReadFile(bdev + "/dirty_data")
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/github/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func (g *GitHub) createGitHubClient(ctx context.Context) (*github.Client, error)
&oauth2.Token{AccessToken: g.AccessToken},
)
oauthClient := oauth2.NewClient(ctx, tokenSource)
ctx = context.WithValue(ctx, oauth2.HTTPClient, oauthClient)
_ = context.WithValue(ctx, oauth2.HTTPClient, oauthClient)

g.obfuscatedToken = g.AccessToken[0:4] + "..." + g.AccessToken[len(g.AccessToken)-3:]

Expand Down
7 changes: 4 additions & 3 deletions plugins/inputs/graylog/graylog.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,11 +169,12 @@ func (h *GrayLog) gatherServer(
return err
}
requestURL, err := url.Parse(serverURL)
host, port, _ := net.SplitHostPort(requestURL.Host)
var dat ResponseMetrics
if err != nil {
return err
return fmt.Errorf("unable to parse address '%s': %s", serverURL, err)
}

host, port, _ := net.SplitHostPort(requestURL.Host)
var dat ResponseMetrics
if err := json.Unmarshal([]byte(resp), &dat); err != nil {
return err
}
Expand Down
13 changes: 8 additions & 5 deletions plugins/inputs/haproxy/haproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,10 +162,13 @@ func (g *haproxy) gatherServer(addr string, acc telegraf.Accumulator) error {

u, err := url.Parse(addr)
if err != nil {
return fmt.Errorf("Unable parse server address '%s': %s", addr, err)
return fmt.Errorf("unable parse server address '%s': %s", addr, err)
}

req, err := http.NewRequest("GET", addr, nil)
if err != nil {
return fmt.Errorf("unable to create new request '%s': %s", addr, err)
}
if u.User != nil {
p, _ := u.User.Password()
req.SetBasicAuth(u.User.Username(), p)
Expand All @@ -179,16 +182,16 @@ func (g *haproxy) gatherServer(addr string, acc telegraf.Accumulator) error {

res, err := g.client.Do(req)
if err != nil {
return fmt.Errorf("Unable to connect to haproxy server '%s': %s", addr, err)
return fmt.Errorf("unable to connect to haproxy server '%s': %s", addr, err)
}
defer res.Body.Close()

if res.StatusCode != 200 {
return fmt.Errorf("Unable to get valid stat result from '%s', http response code : %d", addr, res.StatusCode)
return fmt.Errorf("unable to get valid stat result from '%s', http response code : %d", addr, res.StatusCode)
}

if err := g.importCsvResult(res.Body, acc, u.Host); err != nil {
return fmt.Errorf("Unable to parse stat result from '%s': %s", addr, err)
return fmt.Errorf("unable to parse stat result from '%s': %s", addr, err)
}

return nil
Expand Down Expand Up @@ -271,7 +274,7 @@ func (g *haproxy) importCsvResult(r io.Reader, acc telegraf.Accumulator, host st
if err != nil {
return fmt.Errorf("unable to parse type value '%s'", v)
}
if int(vi) >= len(typeNames) {
if vi >= int64(len(typeNames)) {
return fmt.Errorf("received unknown type value: %d", vi)
}
tags[fieldName] = typeNames[vi]
Expand Down
3 changes: 1 addition & 2 deletions plugins/inputs/ipmi_sensor/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ func NewConnection(server string, privilege string) *Connection {
conn.Privilege = privilege
inx1 := strings.LastIndex(server, "@")
inx2 := strings.Index(server, "(")
inx3 := strings.Index(server, ")")

connstr := server

Expand All @@ -36,7 +35,7 @@ func NewConnection(server string, privilege string) *Connection {

if inx2 > 0 {
inx2 = strings.Index(connstr, "(")
inx3 = strings.Index(connstr, ")")
inx3 := strings.Index(connstr, ")")

conn.Interface = connstr[0:inx2]
conn.Hostname = connstr[inx2+1 : inx3]
Expand Down
4 changes: 3 additions & 1 deletion plugins/inputs/jolokia/jolokia.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,9 +234,11 @@ func (j *Jolokia) prepareRequest(server Server, metrics []Metric) (*http.Request
}

requestBody, err := json.Marshal(bulkBodyContent)
if err != nil {
return nil, err
}

req, err := http.NewRequest("POST", jolokiaUrl.String(), bytes.NewBuffer(requestBody))

if err != nil {
return nil, err
}
Expand Down
4 changes: 4 additions & 0 deletions plugins/inputs/jolokia2/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,10 @@ func (c *Client) read(requests []ReadRequest) ([]ReadResponse, error) {
}

req, err := http.NewRequest("POST", requestUrl, bytes.NewBuffer(requestBody))
if err != nil {
return nil, fmt.Errorf("unable to create new request '%s': %s", requestUrl, err)
}

req.Header.Add("Content-type", "application/json")

resp, err := c.client.Do(req)
Expand Down
4 changes: 3 additions & 1 deletion plugins/inputs/kibana/kibana.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,8 +238,10 @@ func (k *Kibana) gatherKibanaStatus(baseUrl string, acc telegraf.Accumulator) er
}

func (k *Kibana) gatherJsonData(url string, v interface{}) (host string, err error) {

request, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", fmt.Errorf("unable to create new request '%s': %v", url, err)
}

if (k.Username != "") || (k.Password != "") {
request.SetBasicAuth(k.Username, k.Password)
Expand Down
4 changes: 3 additions & 1 deletion plugins/inputs/mcrouter/mcrouter.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,11 @@ func (m *Mcrouter) gatherServer(ctx context.Context, address string, acc telegra
var dialer net.Dialer

address, protocol, err = m.ParseAddress(address)
if err != nil {
return err
}

conn, err = dialer.DialContext(ctx, protocol, address)

if err != nil {
return err
}
Expand Down
5 changes: 5 additions & 0 deletions plugins/inputs/net_response/net_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ func (n *NetResponse) UDPGather() (tags map[string]string, fields map[string]int
start := time.Now()
// Resolving
udpAddr, err := net.ResolveUDPAddr("udp", n.Address)
// Handle error
if err != nil {
setResult(ConnectionFailed, fields, tags, n.Expect)
return tags, fields
}
// Connecting
conn, err := net.DialUDP("udp", nil, udpAddr)
// Handle error
Expand Down
4 changes: 4 additions & 0 deletions plugins/inputs/openldap/openldap.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ func (o *Openldap) Gather(acc telegraf.Accumulator) error {
return nil
}
err = l.StartTLS(tlsConfig)
if err != nil {
acc.AddError(err)
return nil
}
} else {
acc.AddError(fmt.Errorf("Invalid setting for ssl: %s", o.TLS))
return nil
Expand Down
19 changes: 10 additions & 9 deletions plugins/inputs/phpfpm/phpfpm.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,29 +198,30 @@ func (p *phpfpm) gatherFcgi(fcgi *conn, statusPath string, acc telegraf.Accumula
func (p *phpfpm) gatherHttp(addr string, acc telegraf.Accumulator) error {
u, err := url.Parse(addr)
if err != nil {
return fmt.Errorf("Unable parse server address '%s': %s", addr, err)
return fmt.Errorf("unable parse server address '%s': %v", addr, err)
}

req, err := http.NewRequest("GET", fmt.Sprintf("%s://%s%s", u.Scheme, u.Host, u.Path), nil)
if err != nil {
return fmt.Errorf("unable to create new request '%s': %v", addr, err)
}

req, err := http.NewRequest("GET", fmt.Sprintf("%s://%s%s", u.Scheme,
u.Host, u.Path), nil)
res, err := p.client.Do(req)
if err != nil {
return fmt.Errorf("Unable to connect to phpfpm status page '%s': %v",
addr, err)
return fmt.Errorf("unable to connect to phpfpm status page '%s': %v", addr, err)
}
defer res.Body.Close()

if res.StatusCode != 200 {
return fmt.Errorf("Unable to get valid stat result from '%s': %v",
addr, err)
return fmt.Errorf("unable to get valid stat result from '%s': %v", addr, err)
}

importMetric(res.Body, acc, addr)
return nil
}

// Import stat data into Telegraf system
func importMetric(r io.Reader, acc telegraf.Accumulator, addr string) (poolStat, error) {
func importMetric(r io.Reader, acc telegraf.Accumulator, addr string) poolStat {
stats := make(poolStat)
var currentPool string

Expand Down Expand Up @@ -273,7 +274,7 @@ func importMetric(r io.Reader, acc telegraf.Accumulator, addr string) (poolStat,
acc.AddFields("phpfpm", fields, tags)
}

return stats, nil
return stats
}

func expandUrls(urls []string) ([]string, error) {
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/phpfpm/phpfpm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ func TestPhpFpmGeneratesMetrics_Throw_Error_When_Fpm_Status_Is_Not_Responding(t

err = acc.GatherError(r.Gather)
require.Error(t, err)
assert.Contains(t, err.Error(), `Unable to connect to phpfpm status page 'http://aninvalidone'`)
assert.Contains(t, err.Error(), `unable to connect to phpfpm status page 'http://aninvalidone'`)
assert.Contains(t, err.Error(), `lookup aninvalidone`)
}

Expand Down
3 changes: 3 additions & 0 deletions plugins/inputs/processes/processes_notwindows.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ func (p *Processes) gatherFromProc(fields map[string]interface{}) error {

for _, filename := range filenames {
_, err := os.Stat(filename)
if err != nil {
return err
}
data, err := p.readProcFile(filename)
if err != nil {
return err
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/procstat/native_finder.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func (pg *NativeFinder) PidFile(path string) ([]PID, error) {
return pids, fmt.Errorf("Failed to read pidfile '%s'. Error: '%s'",
path, err)
}
pid, err := strconv.Atoi(strings.TrimSpace(string(pidString)))
pid, err := strconv.ParseInt(strings.TrimSpace(string(pidString)), 10, 32)
if err != nil {
return pids, err
}
Expand Down
8 changes: 3 additions & 5 deletions plugins/inputs/procstat/pgrep.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (pg *Pgrep) PidFile(path string) ([]PID, error) {
return pids, fmt.Errorf("Failed to read pidfile '%s'. Error: '%s'",
path, err)
}
pid, err := strconv.Atoi(strings.TrimSpace(string(pidString)))
pid, err := strconv.ParseInt(strings.TrimSpace(string(pidString)), 10, 32)
if err != nil {
return pids, err
}
Expand Down Expand Up @@ -80,13 +80,11 @@ func parseOutput(out string) ([]PID, error) {
pids := []PID{}
fields := strings.Fields(out)
for _, field := range fields {
pid, err := strconv.Atoi(field)
pid, err := strconv.ParseInt(field, 10, 32)
if err != nil {
return nil, err
}
if err == nil {
pids = append(pids, PID(pid))
}
pids = append(pids, PID(pid))
}
return pids, nil
}
4 changes: 2 additions & 2 deletions plugins/inputs/procstat/procstat.go
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ func (p *Procstat) systemdUnitPIDs() ([]PID, error) {
if len(kv[1]) == 0 || bytes.Equal(kv[1], []byte("0")) {
return nil, nil
}
pid, err := strconv.Atoi(string(kv[1]))
pid, err := strconv.ParseInt(string(kv[1]), 10, 32)
if err != nil {
return nil, fmt.Errorf("invalid pid '%s'", kv[1])
}
Expand All @@ -438,7 +438,7 @@ func (p *Procstat) cgroupPIDs() ([]PID, error) {
if len(pidBS) == 0 {
continue
}
pid, err := strconv.Atoi(string(pidBS))
pid, err := strconv.ParseInt(string(pidBS), 10, 32)
if err != nil {
return nil, fmt.Errorf("invalid pid '%s'", pidBS)
}
Expand Down
5 changes: 2 additions & 3 deletions plugins/inputs/prometheus/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,7 @@ func ParseV2(buf []byte, header http.Header) ([]telegraf.Metric, error) {
} else {
// standard metric
// reading fields
fields := make(map[string]interface{})
fields = getNameAndValueV2(m, metricName)
fields := getNameAndValueV2(m, metricName)
// converting to telegraf metric
if len(fields) > 0 {
var t time.Time
Expand Down Expand Up @@ -203,7 +202,7 @@ func Parse(buf []byte, header http.Header) ([]telegraf.Metric, error) {
// reading tags
tags := makeLabels(m)
// reading fields
fields := make(map[string]interface{})
var fields map[string]interface{}
if mf.GetType() == dto.MetricType_SUMMARY {
// summary metric
fields = makeQuantiles(m)
Expand Down
9 changes: 8 additions & 1 deletion plugins/inputs/prometheus/prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,11 @@ func (p *Prometheus) gatherURL(u URLAndAddress, acc telegraf.Accumulator) error
if path == "" {
path = "/metrics"
}
req, err = http.NewRequest("GET", "http://localhost"+path, nil)
addr := "http://localhost" + path
req, err = http.NewRequest("GET", addr, nil)
if err != nil {
return fmt.Errorf("unable to create new request '%s': %s", addr, err)
}

// ignore error because it's been handled before getting here
tlsCfg, _ := p.ClientConfig.TLSConfig()
Expand All @@ -285,6 +289,9 @@ func (p *Prometheus) gatherURL(u URLAndAddress, acc telegraf.Accumulator) error
u.URL.Path = "/metrics"
}
req, err = http.NewRequest("GET", u.URL.String(), nil)
if err != nil {
return fmt.Errorf("unable to create new request '%s': %s", u.URL.String(), err)
}
}

req.Header.Add("Accept", acceptHeader)
Expand Down
3 changes: 3 additions & 0 deletions plugins/inputs/proxmox/proxmox.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ func init() {
func getNodeSearchDomain(px *Proxmox) error {
apiUrl := "/nodes/" + px.hostname + "/dns"
jsonData, err := px.requestFunction(px, apiUrl, http.MethodGet, nil)
if err != nil {
return err
}

var nodeDns NodeDns
err = json.Unmarshal(jsonData, &nodeDns)
Expand Down
4 changes: 4 additions & 0 deletions plugins/inputs/rethinkdb/rethinkdb_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,10 @@ var TableTracking = []string{

func (s *Server) addTableStats(acc telegraf.Accumulator) error {
tablesCursor, err := gorethink.DB("rethinkdb").Table("table_status").Run(s.session)
if err != nil {
return fmt.Errorf("table stats query error, %s\n", err.Error())
}

defer tablesCursor.Close()
var tables []tableStatus
err = tablesCursor.All(&tables)
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/smart/smart.go
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ func (m *Smart) Gather(acc telegraf.Accumulator) error {

// if nvme-cli is present, vendor specific attributes can be gathered
if isVendorExtension && isNVMe {
scannedNVMeDevices, scannedNonNVMeDevices, err = m.scanAllDevices(true)
scannedNVMeDevices, _, err = m.scanAllDevices(true)
if err != nil {
return err
}
Expand Down
3 changes: 3 additions & 0 deletions plugins/inputs/snmp_legacy/snmp_legacy.go
Original file line number Diff line number Diff line change
Expand Up @@ -706,6 +706,9 @@ func (h *Host) GetSNMPClient() (*gosnmp.GoSNMP, error) {
}
// convert port_str to port in uint16
port_64, err := strconv.ParseUint(port_str, 10, 16)
if err != nil {
return nil, err
}
port := uint16(port_64)
// Get SNMP client
snmpClient := &gosnmp.GoSNMP{
Expand Down
Loading

0 comments on commit c8e69ac

Please sign in to comment.