Browse Source

Read /proc/stat in the main program

Along the way fix the tests, since the field "cpu" was forgotten
in the dummy line.
Oz Tiram 5 years ago
parent
commit
f92c0151d3
4 changed files with 26 additions and 9 deletions
  1. 3 0
      Makefile
  2. 14 1
      cmd/main.go
  3. 3 4
      gupta.go
  4. 6 4
      gupta_test.go

+ 3 - 0
Makefile

@@ -8,6 +8,9 @@ build:
 	cd cmd
 	go build -o bin/gupta cmd/main.go
 
+run:
+	./bin/gupta -f 2
+
 install:
 	install -m 755 bin/gupta $(DEST)
 

+ 14 - 1
cmd/main.go

@@ -1,9 +1,12 @@
 package main
 
 import (
+	"bufio"
 	"flag"
 	"fmt"
 	"github.com/oz123/gupta"
+	"log"
+	"os"
 	"time"
 )
 
@@ -21,9 +24,19 @@ func main() {
 	flag.StringVar(&netInterface, "n", "", "Network usage (interface)")
 
 	flag.Parse()
+	f, err := os.Open("/proc/stat")
+	defer f.Close()
+	rd := bufio.NewReader(f)
+	line, err := rd.ReadString('\n')
+	if err != nil {
+		log.Fatalf("could not read /proc/stat, error: %v", err)
+	}
+
+	fmt.Println(gupta.Hello())
 
 	for true {
-		fmt.Println(gupta.Hello())
+		cpustat := gupta.NewCPUStat(line)
+		fmt.Printf("cpustat %d\n", cpustat.User)
 		time.Sleep(time.Duration(freq) * time.Second)
 	}
 }

+ 3 - 4
gupta.go

@@ -31,7 +31,7 @@ func (g *GuptaReport) GetCPULoad() string {
 
 // collect all CPU stat from /proc/cpustat
 type CPUStat struct {
-	user       uint64
+	User       uint64
 	nice       uint64
 	system     uint64
 	idle       uint64
@@ -46,7 +46,7 @@ type CPUStat struct {
 // parse the first line of /proc/cpustat
 func (c *CPUStat) ReadInfo(rawInfo []string) {
 	if s, err := strconv.ParseUint(rawInfo[0], 10, 64); err == nil {
-		c.user = s
+		c.User = s
 	}
 	if s, err := strconv.ParseUint(rawInfo[1], 10, 64); err == nil {
 		c.nice = s
@@ -80,7 +80,6 @@ func (c *CPUStat) ReadInfo(rawInfo []string) {
 func NewCPUStat(procstatline string) CPUStat {
 	cpustat := CPUStat{}
 	statline := strings.Fields(procstatline)
-	fmt.Println(statline)
-	cpustat.ReadInfo(statline)
+	cpustat.ReadInfo(statline[1:])
 	return cpustat
 }

+ 6 - 4
gupta_test.go

@@ -50,7 +50,9 @@ func TestGuptaHasReport(t *testing.T) {
 
 func TestGetCPULoad(t *testing.T) {
 	cpustat := CPUStat{}
-	cpustat.ReadInfo([]string{"4705",
+	cpustat.ReadInfo([]string{
+		"cpu",
+		"4705",
 		"356",
 		"584",
 		"3699",
@@ -67,9 +69,9 @@ func TestGetCPULoad(t *testing.T) {
 }
 
 func TestCalculateCPUUsage(t *testing.T) {
-	//                0    1     2     3     4      5     6       7     8     9
-	//               user nice system idle iowait  irq  softirq steal guest guest_nice
-	procstatLine := "4705 356  584    3699   23    23     0       0     0    0"
+	//               0    1    2     3     4     5      6     7       8     9     10
+	//               cpu user nice system idle iowait  irq  softirq steal guest guest_nice
+	procstatLine := "cpu 4705 356  584    3699   23    23     0       0     0    0"
 	cpustat := NewCPUStat(procstatLine)
 
 	if cpustat.user != 4705 {