Browse Source

Parse all CPUStat fields from the file line

Oz Tiram 5 years ago
parent
commit
d288f4de5a
2 changed files with 54 additions and 16 deletions
  1. 51 13
      gupta.go
  2. 3 3
      gupta_test.go

+ 51 - 13
gupta.go

@@ -2,6 +2,7 @@ package gupta
 
 import (
 	"fmt"
+	"strconv"
 )
 
 const version = "0.0.1"
@@ -27,19 +28,56 @@ func (g *GuptaReport) GetCPULoad() string {
 	return fmt.Sprintf("%.2f", g.cpuLoad)
 }
 
-type CPULoad struct {
-	user       int
-	nice       int
-	system     int
-	idle       int
-	iowait     int
-	irq        int
-	softirq    int
-	steal      int
-	guest      int
-	guest_nice int
+// collect all CPU stat from /proc/cpustat
+type CPUStat struct {
+	user       int64
+	nice       int64
+	system     int64
+	idle       int64
+	iowait     int64
+	irq        int64
+	softirq    int64
+	steal      int64
+	guest      int64
+	guest_nice int64
 }
 
-func (c *CPULoad) ReadInfo(rawInfo []string) {
-	c.user = 1
+// parse the first line of /proc/cpustat
+func (c *CPUStat) ReadInfo(rawInfo []string) {
+	if s, err := strconv.ParseInt(rawInfo[0], 10, 64); err == nil {
+		c.user = s
+	}
+	if s, err := strconv.ParseInt(rawInfo[1], 10, 64); err == nil {
+		c.nice = s
+	}
+	if s, err := strconv.ParseInt(rawInfo[2], 10, 64); err == nil {
+		c.system = s
+	}
+	if s, err := strconv.ParseInt(rawInfo[3], 10, 64); err == nil {
+		c.idle = s
+	}
+	if s, err := strconv.ParseInt(rawInfo[4], 10, 64); err == nil {
+		c.idle = s
+	}
+	if s, err := strconv.ParseInt(rawInfo[5], 10, 64); err == nil {
+		c.iowait = s
+	}
+	if s, err := strconv.ParseInt(rawInfo[6], 10, 64); err == nil {
+		c.irq = s
+	}
+	if s, err := strconv.ParseInt(rawInfo[7], 10, 64); err == nil {
+		c.softirq = s
+	}
+	if s, err := strconv.ParseInt(rawInfo[8], 10, 64); err == nil {
+		c.softirq = s
+	}
+	if s, err := strconv.ParseInt(rawInfo[9], 10, 64); err == nil {
+		c.steal = s
+	}
+	if s, err := strconv.ParseInt(rawInfo[10], 10, 64); err == nil {
+		c.guest = s
+	}
+	if s, err := strconv.ParseInt(rawInfo[11], 10, 64); err == nil {
+		c.guest_nice = s
+	}
 }

+ 3 - 3
gupta_test.go

@@ -50,9 +50,9 @@ func TestGuptaHasReport(t *testing.T) {
 
 func TestGetCPULoad(t *testing.T) {
 	cpuload := CPULoad{}
-	cpuload.ReadInfo(make([]string, 3))
+	cpuload.ReadInfo([]string{"1234", "5678", "9101112"})
 
-	if cpuload.user != 1 {
-		t.Errorf("got %v want %v", cpuload.user, 1)
+	if cpuload.user != 1234 {
+		t.Errorf("got %v want %v", cpuload.user, 1234)
 	}
 }