Browse Source

Add basic memory reporting

Oz Tiram 5 years ago
parent
commit
31edda847b
3 changed files with 92 additions and 0 deletions
  1. 4 0
      cmd/main.go
  2. 37 0
      memory.go
  3. 51 0
      memory_test.go

+ 4 - 0
cmd/main.go

@@ -35,6 +35,7 @@ func main() {
 
 	fmt.Println(gupta.Hello())
 	r, _ := os.Open("/proc/stat")
+	m, _ := os.Open("/proc/meminfo")
 
 	for true {
 		line := readProcStatLine(r)
@@ -42,5 +43,8 @@ func main() {
 		lineNew := readProcStatLine(r)
 		cpustat := gupta.NewCPUStat(line, lineNew)
 		fmt.Printf("CPU usage %.2f%%\n", cpustat.CPUUsage())
+		mem := gupta.NewMemory(m)
+		fmt.Printf("Memory free %d\n", mem.Total())
+		m.Seek(0, 0)
 	}
 }

+ 37 - 0
memory.go

@@ -0,0 +1,37 @@
+package gupta
+
+import (
+	"bytes"
+	"io"
+	"strconv"
+	"strings"
+)
+
+type Memory struct {
+	total uint64
+	free  uint64
+}
+
+func (m *Memory) Free() uint64 {
+	return m.free
+}
+
+func (m *Memory) Total() uint64 {
+	return m.total
+}
+
+func (m *Memory) Used() uint64 {
+	return m.total - m.free
+}
+
+func NewMemory(r io.ReaderAt) Memory {
+	m := Memory{}
+	buf := make([]byte, 80)
+	r.ReadAt(buf, 0)
+	idx := bytes.Index(buf, []byte("MemAvailable"))
+	line := string(buf[:idx])
+	elements := strings.Fields(line)
+	m.total, _ = strconv.ParseUint(elements[1], 10, 64)
+	m.free, _ = strconv.ParseUint(elements[4], 10, 64)
+	return m
+}

+ 51 - 0
memory_test.go

@@ -0,0 +1,51 @@
+package gupta
+
+import (
+	"fmt"
+	"strings"
+	"testing"
+)
+
+func TestFreeMem(t *testing.T) {
+	m := Memory{}
+	m.free = uint64(1200)
+	got := m.Free()
+	want := uint64(1200)
+	name := "free"
+	if got != want {
+		t.Errorf("got %s %d want %d", name, got, want)
+	}
+}
+
+func TestTotalMem(t *testing.T) {
+	m := Memory{total: uint64(2400)}
+	got := m.Total()
+	want := uint64(2400)
+	name := "total"
+	if got != want {
+		t.Errorf("got %s %d want %d", name, got, want)
+	}
+}
+
+func TestUsedMem(t *testing.T) {
+	m := Memory{total: uint64(2400), free: uint64(1200)}
+	got := m.Used()
+	fmt.Println(got)
+	want := uint64(1200)
+	name := "used"
+	if got != want {
+		t.Errorf("got %s %d want %d", name, got, want)
+	}
+}
+
+func TestNewMemory(t *testing.T) {
+	//r, _ := os.open("/proc/meminfo")
+	r := strings.NewReader("MemTotal:       16080192 kB\nMemFree:         3617004 kB\nMemAvailable:   11258504 kB\nBuffers:         1814108 kB\n")
+	mem := NewMemory(r)
+	got := mem.total
+	want := uint64(16080192)
+	name := "memory total"
+	if got != want {
+		t.Errorf("got %s %d want %d", name, got, want)
+	}
+}