Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Avoid trimming characters incorrectly from ProcStatus #469

Merged
merged 1 commit into from
Oct 11, 2022

Conversation

irvinlim
Copy link
Contributor

@irvinlim irvinlim commented Oct 7, 2022

Hello, thank you for the wonderful library!

We found some issues in parsing ProcStatus, in particular those whose Name starts with a k. For a simple repro (I copied out the existing code from https://github.com/prometheus/procfs/blob/bf361025088d9df7a76662269f07facf20f8711e/proc_status.go):

package main

import (
	"bytes"
	"fmt"
	"strconv"
	"strings"

	"github.com/prometheus/procfs"
)

const (
	pid  = 6187
	data = `Name:   kube-proxy`
)

func main() {
	s := procfs.ProcStatus{PID: pid}

	lines := strings.Split(data, "\n")
	for _, line := range lines {
		if !bytes.Contains([]byte(line), []byte(":")) {
			continue
		}

		kv := strings.SplitN(line, ":", 2)

		// removes spaces
		k := string(strings.TrimSpace(kv[0]))
		v := string(strings.TrimSpace(kv[1]))
		// removes "kB"
		v = string(bytes.Trim([]byte(v), " kB"))

		// value to int when possible
		// we can skip error check here, 'cause vKBytes is not used when value is a string
		vKBytes, _ := strconv.ParseUint(v, 10, 64)
		// convert kB to B
		vBytes := vKBytes * 1024

		fillStatus(&s, k, v, vKBytes, vBytes)
	}

	fmt.Printf("%v\n", s.Name)
}

The output is as follows:

ube-proxy

The reason is because bytes.Trim takes in a cutSet, not a suffix that should be trimmed. As such, this PR modifies bytes.Trim to strings.TrimSuffix.

@irvinlim irvinlim marked this pull request as ready for review October 7, 2022 03:26
@irvinlim irvinlim force-pushed the irvinlim/fix/proc-status-trim branch from 666503a to 30a5423 Compare October 7, 2022 03:29
Copy link
Member

@discordianfish discordianfish left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks!

Copy link
Member

@SuperQ SuperQ left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@SuperQ SuperQ merged commit b3d77ec into prometheus:master Oct 11, 2022
remijouannet pushed a commit to remijouannet/procfs that referenced this pull request Oct 20, 2022
jritter pushed a commit to jritter/procfs that referenced this pull request Jul 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants