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.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 {
@ -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

View File

@ -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 {

View File

@ -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:]

View File

@ -169,11 +169,12 @@ func (h *GrayLog) gatherServer(
return err
}
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)
var dat ResponseMetrics
if err != nil {
return err
}
if err := json.Unmarshal([]byte(resp), &dat); err != nil {
return err
}

View File

@ -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)
@ -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
@ -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]

View File

@ -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
@ -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]

View File

@ -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
}

View File

@ -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)

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) {
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)

View File

@ -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
}

View File

@ -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

View File

@ -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

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 {
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)
@ -220,7 +221,7 @@ func (p *phpfpm) gatherHttp(addr string, acc telegraf.Accumulator) error {
}
// 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
@ -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) {

View File

@ -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`)
}

View File

@ -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

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'",
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
}

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'",
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
}
@ -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
}

View File

@ -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])
}
@ -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)
}

View File

@ -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
@ -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)

View File

@ -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()
@ -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)

View File

@ -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)

View File

@ -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)

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 isVendorExtension && isNVMe {
scannedNVMeDevices, scannedNonNVMeDevices, err = m.scanAllDevices(true)
scannedNVMeDevices, _, err = m.scanAllDevices(true)
if err != nil {
return err
}

View File

@ -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{

View File

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

View File

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

View File

@ -138,7 +138,12 @@ func (w *Warp10) Write(metrics []telegraf.Metric) error {
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("Content-Type", "text/plain")