...
1
2
3
4
19
20 package procfs
21
22 import (
23 "os"
24 "os/signal"
25 "path/filepath"
26 "regexp"
27 "runtime"
28 "syscall"
29 "testing"
30 "time"
31
32 "github.com/stretchr/testify/assert"
33 )
34
35 func verifyContainerName(procCgroupText, expectedName string, expectedErr bool, t *testing.T) {
36 name, err := containerNameFromProcCgroup(procCgroupText)
37 if expectedErr && err == nil {
38 t.Errorf("Expected error but did not get error in verifyContainerName")
39 return
40 } else if !expectedErr && err != nil {
41 t.Errorf("Expected no error, but got error %+v in verifyContainerName", err)
42 return
43 } else if expectedErr {
44 return
45 }
46 if name != expectedName {
47 t.Errorf("Expected container name %s but got name %s", expectedName, name)
48 }
49 }
50
51 func TestContainerNameFromProcCgroup(t *testing.T) {
52 procCgroupValid := "2:devices:docker/kubelet"
53 verifyContainerName(procCgroupValid, "docker/kubelet", false, t)
54
55 procCgroupEmpty := ""
56 verifyContainerName(procCgroupEmpty, "", true, t)
57
58 content, err := os.ReadFile("example_proc_cgroup")
59 if err != nil {
60 t.Errorf("Could not read example /proc cgroup file")
61 }
62 verifyContainerName(string(content), "/user/1000.user/c1.session", false, t)
63
64 procCgroupNoDevice := "2:freezer:docker/kubelet\n5:cpuacct:pkg/kubectl"
65 verifyContainerName(procCgroupNoDevice, "", true, t)
66
67 procCgroupInvalid := "devices:docker/kubelet\ncpuacct:pkg/kubectl"
68 verifyContainerName(procCgroupInvalid, "", true, t)
69 }
70
71 func TestPidOf(t *testing.T) {
72 if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
73 t.Skipf("not supported on GOOS=%s", runtime.GOOS)
74 }
75 pids, err := PidOf(filepath.Base(os.Args[0]))
76 assert.Empty(t, err)
77 assert.NotZero(t, pids)
78 assert.Contains(t, pids, os.Getpid())
79 }
80
81 func TestPKill(t *testing.T) {
82 if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
83 t.Skipf("not supported on GOOS=%s", runtime.GOOS)
84 }
85 sig := syscall.SIGCONT
86 c := make(chan os.Signal, 1)
87 signal.Notify(c, sig)
88 defer signal.Stop(c)
89 PKill(os.Args[0], sig)
90 select {
91 case s := <-c:
92 if s != sig {
93 t.Fatalf("signal was %v, want %v", s, sig)
94 }
95 case <-time.After(1 * time.Second):
96 t.Fatalf("timeout waiting for %v", sig)
97 }
98 }
99
100 func BenchmarkGetPids(b *testing.B) {
101 if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
102 b.Skipf("not supported on GOOS=%s", runtime.GOOS)
103 }
104
105 re, err := regexp.Compile("(^|/)" + filepath.Base(os.Args[0]) + "$")
106 assert.Empty(b, err)
107
108 for i := 0; i < b.N; i++ {
109 pids := getPids(re)
110
111 b.StopTimer()
112 assert.NotZero(b, pids)
113 assert.Contains(b, pids, os.Getpid())
114 b.StartTimer()
115 }
116 }
117
View as plain text