forked from bcicen/ctop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmocksource.go
125 lines (107 loc) · 2.35 KB
/
mocksource.go
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// +build !release
package main
import (
"math/rand"
"sort"
"strings"
"time"
"github.com/bcicen/ctop/metrics"
"github.com/jgautheron/codename-generator"
"github.com/nu7hatch/gouuid"
)
type MockContainerSource struct {
containers Containers
}
func NewMockContainerSource() *MockContainerSource {
cs := &MockContainerSource{}
go cs.Init()
go cs.Loop()
return cs
}
// Create Mock containers
func (cs *MockContainerSource) Init() {
rand.Seed(int64(time.Now().Nanosecond()))
for i := 0; i < 4; i++ {
cs.makeContainer(3)
}
for i := 0; i < 16; i++ {
cs.makeContainer(1)
}
}
func (cs *MockContainerSource) makeContainer(aggression int64) {
collector := metrics.NewMock(aggression)
c := NewContainer(makeID(), collector)
c.SetMeta("name", makeName())
c.SetState(makeState())
cs.containers = append(cs.containers, c)
}
func (cs *MockContainerSource) Loop() {
iter := 0
for {
// Change state for random container
if iter%5 == 0 && len(cs.containers) > 0 {
randC := cs.containers[rand.Intn(len(cs.containers))]
randC.SetState(makeState())
}
iter++
time.Sleep(3 * time.Second)
}
}
// Get a single container, by ID
func (cs *MockContainerSource) Get(id string) (*Container, bool) {
for _, c := range cs.containers {
if c.Id == id {
return c, true
}
}
return nil, false
}
// Return array of all containers, sorted by field
func (cs *MockContainerSource) All() Containers {
sort.Sort(cs.containers)
cs.containers.Filter()
return cs.containers
}
// Remove containers by ID
func (cs *MockContainerSource) delByID(id string) {
for n, c := range cs.containers {
if c.Id == id {
cs.del(n)
return
}
}
}
// Remove one or more containers by index
func (cs *MockContainerSource) del(idx ...int) {
for _, i := range idx {
cs.containers = append(cs.containers[:i], cs.containers[i+1:]...)
}
log.Infof("removed %d dead containers", len(idx))
}
func makeID() string {
u, err := uuid.NewV4()
if err != nil {
panic(err)
}
return strings.Replace(u.String(), "-", "", -1)[:12]
}
func makeName() string {
n, err := codename.Get(codename.Sanitized)
nsp := strings.Split(n, "-")
if len(nsp) > 2 {
n = strings.Join(nsp[:2], "-")
}
if err != nil {
panic(err)
}
return strings.Replace(n, "-", "_", -1)
}
func makeState() string {
switch rand.Intn(10) {
case 0, 1, 2:
return "exited"
case 3:
return "paused"
}
return "running"
}