memory_test.go 2.2 KB
Newer Older
“李磊”'s avatar
“李磊” committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package fs

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"sort"
	"testing"
)

func TestGetMemoryLimit(t *testing.T) {
	tmpCgroupDir, err := ioutil.TempDir("/tmp", "cgroup-")
	if err != nil {
		t.Fatal("Cannot create temporary file", err)
	}
	defer os.RemoveAll(tmpCgroupDir)

	tmpMemLimitFile := filepath.Join(tmpCgroupDir, "memory.limit_in_bytes")
	DefaultMemLimit := float64(3 * 1024 * 1024 * 1024)

	type memTest struct {
		limitSet string
		limitGet float64
	}
	memTests := []memTest{
		{limitSet: defaultMem, limitGet: DefaultMemLimit},
		{limitSet: "1024000000", limitGet: float64(1024000000)},
		{limitSet: "0", limitGet: DefaultMemLimit},
	}
	for i, test := range memTests {
		err = ioutil.WriteFile(tmpMemLimitFile, []byte(test.limitSet), 0)
		if err != nil {
			t.Fatal(i, "Failed to write to temporary file", err)
		}

		memLimit := GetMemoryLimit(tmpCgroupDir, DefaultMemLimit)
		if memLimit != test.limitGet {
			t.Fatalf("%d memLimit(%f) != expected(%f)", i, memLimit, test.limitGet)
		}
	}
}

func TestGetMemoryUsage(t *testing.T) {
	usage, workingSet, err := GetMemoryUsage("../testdata/cg1_memory")
	if err != nil {
		t.Error("err:", err)
		return
	}
	if usage != 102400000 {
		t.Errorf("unexpected usage %d, should be %d", usage, 102400000)
		return
	}
	if workingSet != 100000000 {
		t.Errorf("unexpected usage %d, should be %d", workingSet, 100000000)
		return
	}
}

func TestGetKernelMemoryUsage(t *testing.T) {
	kmemUsage, err := GetKernelMemoryUsage("../testdata/cg1_memory")
	if err != nil {
		t.Error("err:", err)
		return
	}
	if kmemUsage != 10240000 {
		t.Errorf("unexpected kmem usage %d, should be %d", kmemUsage, 10240000)
		return
	}
}

func TestGetKernelMemorySlabInfo(t *testing.T) {
	slabInfo, err := GetKernelMemorySlabInfo("../testdata/cg1_memory")
	if err != nil {
		t.Error("err:", err)
		return
	}

	sort.Sort(slabInfo)
	if len(slabInfo.Slabs) < 2 {
		t.Error("unexpected slabInfo len", len(slabInfo.Slabs))
		return
	}
	if slabInfo.Slabs[0].Name != "proc_inode_cache" || slabInfo.Slabs[1].Name != "dentry" {
		t.Errorf("unexpected slabInfo sort, top1:%s, top2:%s", slabInfo.Slabs[0].Name, slabInfo.Slabs[1].Name)
		return
	}
}