Fixed almost all bugs found by LGTM analysis platform (#8240)

This commit is contained in:
Paweł Żak 2020-10-08 17:20:35 +02:00 committed by GitHub
parent 5cc43879e8
commit c8e69aca3c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 98 additions and 46 deletions

View File

@ -112,7 +112,7 @@ func (r *Reader) Read(p []byte) (int, error) {
r.err = nil r.err = nil
r.transformComplete = false r.transformComplete = false
n, err := 0, error(nil) n := 0
for { for {
// Copy out any transformed bytes and return the final error if we are done. // Copy out any transformed bytes and return the final error if we are done.
if r.dst0 != r.dst1 { if r.dst0 != r.dst1 {
@ -131,6 +131,7 @@ func (r *Reader) Read(p []byte) (int, error) {
// As the io.Reader documentation says, "process the n > 0 bytes returned // As the io.Reader documentation says, "process the n > 0 bytes returned
// before considering the error". // before considering the error".
if r.src0 != r.src1 || r.err != nil { if r.src0 != r.src1 || r.err != nil {
var err error
r.dst0 = 0 r.dst0 = 0
r.dst1, n, err = r.t.Transform(r.dst, r.src[r.src0:r.src1], r.err == io.EOF) r.dst1, n, err = r.t.Transform(r.dst, r.src[r.src0:r.src1], r.err == io.EOF)
r.src0 += n r.src0 += n

View File

@ -73,8 +73,11 @@ func prettyToBytes(v string) uint64 {
func (b *Bcache) gatherBcache(bdev string, acc telegraf.Accumulator) error { func (b *Bcache) gatherBcache(bdev string, acc telegraf.Accumulator) error {
tags := getTags(bdev) tags := getTags(bdev)
metrics, err := filepath.Glob(bdev + "/stats_total/*") metrics, err := filepath.Glob(bdev + "/stats_total/*")
if len(metrics) < 0 { if err != nil {
return errors.New("Can't read any stats file") return err
}
if len(metrics) == 0 {
return errors.New("can't read any stats file")
} }
file, err := ioutil.ReadFile(bdev + "/dirty_data") file, err := ioutil.ReadFile(bdev + "/dirty_data")
if err != nil { if err != nil {

View File

@ -74,7 +74,7 @@ func (g *GitHub) createGitHubClient(ctx context.Context) (*github.Client, error)
&oauth2.Token{AccessToken: g.AccessToken}, &oauth2.Token{AccessToken: g.AccessToken},
) )
oauthClient := oauth2.NewClient(ctx, tokenSource) 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:] g.obfuscatedToken = g.AccessToken[0:4] + "..." + g.AccessToken[len(g.AccessToken)-3:]

View File

@ -169,11 +169,12 @@ func (h *GrayLog) gatherServer(
return err return err
} }
requestURL, err := url.Parse(serverURL) requestURL, err := url.Parse(serverURL)
if err != nil {
return fmt.Errorf("unable to parse address '%s': %s", serverURL, err)
}
host, port, _ := net.SplitHostPort(requestURL.Host) host, port, _ := net.SplitHostPort(requestURL.Host)
var dat ResponseMetrics var dat ResponseMetrics
if err != nil {
return err
}
if err := json.Unmarshal([]byte(resp), &dat); err != nil { if err := json.Unmarshal([]byte(resp), &dat); err != nil {
return err return err
} }

View File

@ -162,10 +162,13 @@ func (g *haproxy) gatherServer(addr string, acc telegraf.Accumulator) error {
u, err := url.Parse(addr) u, err := url.Parse(addr)
if err != nil { 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) 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 { if u.User != nil {
p, _ := u.User.Password() p, _ := u.User.Password()
req.SetBasicAuth(u.User.Username(), p) req.SetBasicAuth(u.User.Username(), p)
@ -179,16 +182,16 @@ func (g *haproxy) gatherServer(addr string, acc telegraf.Accumulator) error {
res, err := g.client.Do(req) res, err := g.client.Do(req)
if err != nil { 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() defer res.Body.Close()
if res.StatusCode != 200 { 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 { 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 return nil
@ -271,7 +274,7 @@ func (g *haproxy) importCsvResult(r io.Reader, acc telegraf.Accumulator, host st
if err != nil { if err != nil {
return fmt.Errorf("unable to parse type value '%s'", v) 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) return fmt.Errorf("received unknown type value: %d", vi)
} }
tags[fieldName] = typeNames[vi] tags[fieldName] = typeNames[vi]

View File

@ -22,7 +22,6 @@ func NewConnection(server string, privilege string) *Connection {
conn.Privilege = privilege conn.Privilege = privilege
inx1 := strings.LastIndex(server, "@") inx1 := strings.LastIndex(server, "@")
inx2 := strings.Index(server, "(") inx2 := strings.Index(server, "(")
inx3 := strings.Index(server, ")")
connstr := server connstr := server
@ -36,7 +35,7 @@ func NewConnection(server string, privilege string) *Connection {
if inx2 > 0 { if inx2 > 0 {
inx2 = strings.Index(connstr, "(") inx2 = strings.Index(connstr, "(")
inx3 = strings.Index(connstr, ")") inx3 := strings.Index(connstr, ")")
conn.Interface = connstr[0:inx2] conn.Interface = connstr[0:inx2]
conn.Hostname = connstr[inx2+1 : inx3] conn.Hostname = connstr[inx2+1 : inx3]

View File

@ -234,9 +234,11 @@ func (j *Jolokia) prepareRequest(server Server, metrics []Metric) (*http.Request
} }
requestBody, err := json.Marshal(bulkBodyContent) requestBody, err := json.Marshal(bulkBodyContent)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", jolokiaUrl.String(), bytes.NewBuffer(requestBody)) req, err := http.NewRequest("POST", jolokiaUrl.String(), bytes.NewBuffer(requestBody))
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -131,6 +131,10 @@ func (c *Client) read(requests []ReadRequest) ([]ReadResponse, error) {
} }
req, err := http.NewRequest("POST", requestUrl, bytes.NewBuffer(requestBody)) 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") req.Header.Add("Content-type", "application/json")
resp, err := c.client.Do(req) resp, err := c.client.Do(req)

View File

@ -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) { func (k *Kibana) gatherJsonData(url string, v interface{}) (host string, err error) {
request, err := http.NewRequest("GET", url, nil) 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 != "") { if (k.Username != "") || (k.Password != "") {
request.SetBasicAuth(k.Username, k.Password) request.SetBasicAuth(k.Username, k.Password)

View File

@ -198,9 +198,11 @@ func (m *Mcrouter) gatherServer(ctx context.Context, address string, acc telegra
var dialer net.Dialer var dialer net.Dialer
address, protocol, err = m.ParseAddress(address) address, protocol, err = m.ParseAddress(address)
if err != nil {
return err
}
conn, err = dialer.DialContext(ctx, protocol, address) conn, err = dialer.DialContext(ctx, protocol, address)
if err != nil { if err != nil {
return err return err
} }

View File

@ -141,6 +141,11 @@ func (n *NetResponse) UDPGather() (tags map[string]string, fields map[string]int
start := time.Now() start := time.Now()
// Resolving // Resolving
udpAddr, err := net.ResolveUDPAddr("udp", n.Address) udpAddr, err := net.ResolveUDPAddr("udp", n.Address)
// Handle error
if err != nil {
setResult(ConnectionFailed, fields, tags, n.Expect)
return tags, fields
}
// Connecting // Connecting
conn, err := net.DialUDP("udp", nil, udpAddr) conn, err := net.DialUDP("udp", nil, udpAddr)
// Handle error // Handle error

View File

@ -123,6 +123,10 @@ func (o *Openldap) Gather(acc telegraf.Accumulator) error {
return nil return nil
} }
err = l.StartTLS(tlsConfig) err = l.StartTLS(tlsConfig)
if err != nil {
acc.AddError(err)
return nil
}
} else { } else {
acc.AddError(fmt.Errorf("Invalid setting for ssl: %s", o.TLS)) acc.AddError(fmt.Errorf("Invalid setting for ssl: %s", o.TLS))
return nil return nil

View File

@ -198,21 +198,22 @@ func (p *phpfpm) gatherFcgi(fcgi *conn, statusPath string, acc telegraf.Accumula
func (p *phpfpm) gatherHttp(addr string, acc telegraf.Accumulator) error { func (p *phpfpm) gatherHttp(addr string, acc telegraf.Accumulator) error {
u, err := url.Parse(addr) u, err := url.Parse(addr)
if err != nil { 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) res, err := p.client.Do(req)
if err != nil { if err != nil {
return fmt.Errorf("Unable to connect to phpfpm status page '%s': %v", return fmt.Errorf("unable to connect to phpfpm status page '%s': %v", addr, err)
addr, err)
} }
defer res.Body.Close() defer res.Body.Close()
if res.StatusCode != 200 { if res.StatusCode != 200 {
return fmt.Errorf("Unable to get valid stat result from '%s': %v", return fmt.Errorf("unable to get valid stat result from '%s': %v", addr, err)
addr, err)
} }
importMetric(res.Body, acc, addr) importMetric(res.Body, acc, addr)
@ -220,7 +221,7 @@ func (p *phpfpm) gatherHttp(addr string, acc telegraf.Accumulator) error {
} }
// Import stat data into Telegraf system // 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) stats := make(poolStat)
var currentPool string var currentPool string
@ -273,7 +274,7 @@ func importMetric(r io.Reader, acc telegraf.Accumulator, addr string) (poolStat,
acc.AddFields("phpfpm", fields, tags) acc.AddFields("phpfpm", fields, tags)
} }
return stats, nil return stats
} }
func expandUrls(urls []string) ([]string, error) { func expandUrls(urls []string) ([]string, error) {

View File

@ -301,7 +301,7 @@ func TestPhpFpmGeneratesMetrics_Throw_Error_When_Fpm_Status_Is_Not_Responding(t
err = acc.GatherError(r.Gather) err = acc.GatherError(r.Gather)
require.Error(t, err) 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`) assert.Contains(t, err.Error(), `lookup aninvalidone`)
} }

View File

@ -136,6 +136,9 @@ func (p *Processes) gatherFromProc(fields map[string]interface{}) error {
for _, filename := range filenames { for _, filename := range filenames {
_, err := os.Stat(filename) _, err := os.Stat(filename)
if err != nil {
return err
}
data, err := p.readProcFile(filename) data, err := p.readProcFile(filename)
if err != nil { if err != nil {
return err return err

View File

@ -48,7 +48,7 @@ func (pg *NativeFinder) PidFile(path string) ([]PID, error) {
return pids, fmt.Errorf("Failed to read pidfile '%s'. Error: '%s'", return pids, fmt.Errorf("Failed to read pidfile '%s'. Error: '%s'",
path, err) path, err)
} }
pid, err := strconv.Atoi(strings.TrimSpace(string(pidString))) pid, err := strconv.ParseInt(strings.TrimSpace(string(pidString)), 10, 32)
if err != nil { if err != nil {
return pids, err return pids, err
} }

View File

@ -30,7 +30,7 @@ func (pg *Pgrep) PidFile(path string) ([]PID, error) {
return pids, fmt.Errorf("Failed to read pidfile '%s'. Error: '%s'", return pids, fmt.Errorf("Failed to read pidfile '%s'. Error: '%s'",
path, err) path, err)
} }
pid, err := strconv.Atoi(strings.TrimSpace(string(pidString))) pid, err := strconv.ParseInt(strings.TrimSpace(string(pidString)), 10, 32)
if err != nil { if err != nil {
return pids, err return pids, err
} }
@ -80,13 +80,11 @@ func parseOutput(out string) ([]PID, error) {
pids := []PID{} pids := []PID{}
fields := strings.Fields(out) fields := strings.Fields(out)
for _, field := range fields { for _, field := range fields {
pid, err := strconv.Atoi(field) pid, err := strconv.ParseInt(field, 10, 32)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err == nil { pids = append(pids, PID(pid))
pids = append(pids, PID(pid))
}
} }
return pids, nil return pids, nil
} }

View File

@ -413,7 +413,7 @@ func (p *Procstat) systemdUnitPIDs() ([]PID, error) {
if len(kv[1]) == 0 || bytes.Equal(kv[1], []byte("0")) { if len(kv[1]) == 0 || bytes.Equal(kv[1], []byte("0")) {
return nil, nil return nil, nil
} }
pid, err := strconv.Atoi(string(kv[1])) pid, err := strconv.ParseInt(string(kv[1]), 10, 32)
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid pid '%s'", kv[1]) return nil, fmt.Errorf("invalid pid '%s'", kv[1])
} }
@ -438,7 +438,7 @@ func (p *Procstat) cgroupPIDs() ([]PID, error) {
if len(pidBS) == 0 { if len(pidBS) == 0 {
continue continue
} }
pid, err := strconv.Atoi(string(pidBS)) pid, err := strconv.ParseInt(string(pidBS), 10, 32)
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid pid '%s'", pidBS) return nil, fmt.Errorf("invalid pid '%s'", pidBS)
} }

View File

@ -74,8 +74,7 @@ func ParseV2(buf []byte, header http.Header) ([]telegraf.Metric, error) {
} else { } else {
// standard metric // standard metric
// reading fields // reading fields
fields := make(map[string]interface{}) fields := getNameAndValueV2(m, metricName)
fields = getNameAndValueV2(m, metricName)
// converting to telegraf metric // converting to telegraf metric
if len(fields) > 0 { if len(fields) > 0 {
var t time.Time var t time.Time
@ -203,7 +202,7 @@ func Parse(buf []byte, header http.Header) ([]telegraf.Metric, error) {
// reading tags // reading tags
tags := makeLabels(m) tags := makeLabels(m)
// reading fields // reading fields
fields := make(map[string]interface{}) var fields map[string]interface{}
if mf.GetType() == dto.MetricType_SUMMARY { if mf.GetType() == dto.MetricType_SUMMARY {
// summary metric // summary metric
fields = makeQuantiles(m) fields = makeQuantiles(m)

View File

@ -265,7 +265,11 @@ func (p *Prometheus) gatherURL(u URLAndAddress, acc telegraf.Accumulator) error
if path == "" { if path == "" {
path = "/metrics" 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 // ignore error because it's been handled before getting here
tlsCfg, _ := p.ClientConfig.TLSConfig() tlsCfg, _ := p.ClientConfig.TLSConfig()
@ -285,6 +289,9 @@ func (p *Prometheus) gatherURL(u URLAndAddress, acc telegraf.Accumulator) error
u.URL.Path = "/metrics" u.URL.Path = "/metrics"
} }
req, err = http.NewRequest("GET", u.URL.String(), nil) 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) req.Header.Add("Accept", acceptHeader)

View File

@ -79,6 +79,9 @@ func init() {
func getNodeSearchDomain(px *Proxmox) error { func getNodeSearchDomain(px *Proxmox) error {
apiUrl := "/nodes/" + px.hostname + "/dns" apiUrl := "/nodes/" + px.hostname + "/dns"
jsonData, err := px.requestFunction(px, apiUrl, http.MethodGet, nil) jsonData, err := px.requestFunction(px, apiUrl, http.MethodGet, nil)
if err != nil {
return err
}
var nodeDns NodeDns var nodeDns NodeDns
err = json.Unmarshal(jsonData, &nodeDns) err = json.Unmarshal(jsonData, &nodeDns)

View File

@ -164,6 +164,10 @@ var TableTracking = []string{
func (s *Server) addTableStats(acc telegraf.Accumulator) error { func (s *Server) addTableStats(acc telegraf.Accumulator) error {
tablesCursor, err := gorethink.DB("rethinkdb").Table("table_status").Run(s.session) 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() defer tablesCursor.Close()
var tables []tableStatus var tables []tableStatus
err = tablesCursor.All(&tables) err = tablesCursor.All(&tables)

View File

@ -393,7 +393,7 @@ func (m *Smart) Gather(acc telegraf.Accumulator) error {
// if nvme-cli is present, vendor specific attributes can be gathered // if nvme-cli is present, vendor specific attributes can be gathered
if isVendorExtension && isNVMe { if isVendorExtension && isNVMe {
scannedNVMeDevices, scannedNonNVMeDevices, err = m.scanAllDevices(true) scannedNVMeDevices, _, err = m.scanAllDevices(true)
if err != nil { if err != nil {
return err return err
} }

View File

@ -706,6 +706,9 @@ func (h *Host) GetSNMPClient() (*gosnmp.GoSNMP, error) {
} }
// convert port_str to port in uint16 // convert port_str to port in uint16
port_64, err := strconv.ParseUint(port_str, 10, 16) port_64, err := strconv.ParseUint(port_str, 10, 16)
if err != nil {
return nil, err
}
port := uint16(port_64) port := uint16(port_64)
// Get SNMP client // Get SNMP client
snmpClient := &gosnmp.GoSNMP{ snmpClient := &gosnmp.GoSNMP{

View File

@ -202,10 +202,12 @@ func (c *httpClient) Database() string {
// Note that some names are not allowed by the server, notably those with // Note that some names are not allowed by the server, notably those with
// non-printable characters or slashes. // non-printable characters or slashes.
func (c *httpClient) CreateDatabase(ctx context.Context, database string) error { func (c *httpClient) CreateDatabase(ctx context.Context, database string) error {
query := fmt.Sprintf(`CREATE DATABASE "%s"`, query := fmt.Sprintf(`CREATE DATABASE "%s"`, escapeIdentifier.Replace(database))
escapeIdentifier.Replace(database))
req, err := c.makeQueryRequest(query) req, err := c.makeQueryRequest(query)
if err != nil {
return err
}
resp, err := c.client.Do(req.WithContext(ctx)) resp, err := c.client.Do(req.WithContext(ctx))
if err != nil { if err != nil {

View File

@ -78,8 +78,9 @@ type DebugLogger struct {
func (*DebugLogger) Print(v ...interface{}) { func (*DebugLogger) Print(v ...interface{}) {
args := make([]interface{}, 0, len(v)+1) args := make([]interface{}, 0, len(v)+1)
args = append(args, "D! [sarama] ") args = append(append(args, "D! [sarama] "), v...)
log.Print(v...) log.Print(args...)
} }
func (*DebugLogger) Printf(format string, v ...interface{}) { func (*DebugLogger) Printf(format string, v ...interface{}) {
@ -88,7 +89,7 @@ func (*DebugLogger) Printf(format string, v ...interface{}) {
func (*DebugLogger) Println(v ...interface{}) { func (*DebugLogger) Println(v ...interface{}) {
args := make([]interface{}, 0, len(v)+1) args := make([]interface{}, 0, len(v)+1)
args = append(args, "D! [sarama] ") args = append(append(args, "D! [sarama] "), v...)
log.Println(args...) log.Println(args...)
} }

View File

@ -138,7 +138,12 @@ func (w *Warp10) Write(metrics []telegraf.Metric) error {
return nil return nil
} }
req, err := http.NewRequest("POST", w.WarpURL+"/api/v0/update", bytes.NewBufferString(payload)) addr := w.WarpURL + "/api/v0/update"
req, err := http.NewRequest("POST", addr, bytes.NewBufferString(payload))
if err != nil {
return fmt.Errorf("unable to create new request '%s': %s", addr, err)
}
req.Header.Set("X-Warp10-Token", w.Token) req.Header.Set("X-Warp10-Token", w.Token)
req.Header.Set("Content-Type", "text/plain") req.Header.Set("Content-Type", "text/plain")