-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop.go
More file actions
117 lines (103 loc) · 2.44 KB
/
loop.go
File metadata and controls
117 lines (103 loc) · 2.44 KB
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
/*
Copyright Scientific Ideas 2022. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package main
import (
"context"
"github.com/scientificideas/storm/runtime"
"github.com/sirupsen/logrus"
"math/rand"
"strings"
"time"
)
const (
stop = iota
start
stopAndStartImmediately
undefined
)
type LoopType int
func Loop(ctx context.Context, runtime runtime.Runtime, loop LoopType, stopped map[int]struct{}, targets string) {
if runtime.Type() == "k8s" {
loop = undefined
}
var (
msg string
actionFn func(ctx context.Context, name string) error
targetContainers []string
)
if targets != "" {
targetContainers = strings.Split(targets, ",")
}
switch {
case loop == stop || loop == stopAndStartImmediately:
msg = "stop"
actionFn = runtime.StopContainer
case loop == start:
msg = "start"
actionFn = runtime.StartContainer
default:
msg = "delete pod"
actionFn = runtime.RmContainer
}
var targetIndex int
for {
rand.Seed(time.Now().UnixNano())
time.Sleep(runtime.Chaos().Timeout())
containers, err := runtime.GetContainers(ctx, false)
if err != nil {
logrus.Fatal(err)
}
switch {
case loop == stop || loop == stopAndStartImmediately || loop == undefined:
if len(containers) == 0 {
continue
}
if len(targetContainers) != 0 {
targetIndex = rand.Intn(len(targetContainers))
} else {
targetIndex = rand.Intn(len(containers))
}
case loop == start:
containers, err = runtime.GetContainers(ctx, true)
if err != nil {
logrus.Fatal(err)
}
if len(stopped) == 0 {
if len(targetContainers) != 0 {
targetIndex = rand.Intn(len(targetContainers))
} else {
targetIndex = rand.Intn(len(containers))
}
} else {
targetIndex = rand.Intn(len(stopped))
if _, ok := stopped[targetIndex]; !ok {
continue
}
}
}
var selectedContainer string
if len(targetContainers) != 0 {
selectedContainer = targetContainers[targetIndex]
} else {
selectedContainer = containers[targetIndex].Name()
}
logrus.Infof("%s %s", msg, selectedContainer)
if err = actionFn(ctx, selectedContainer); err != nil {
logrus.Error(err)
}
switch loop {
case stop:
stopped[targetIndex] = struct{}{}
case start:
delete(stopped, targetIndex)
case stopAndStartImmediately:
logrus.Infof("start %s", selectedContainer)
if err = runtime.StartContainer(ctx, selectedContainer); err != nil {
logrus.Error(err)
}
default:
}
}
}