-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchaos-monkey.py
executable file
·94 lines (75 loc) · 2.57 KB
/
chaos-monkey.py
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
#!/usr/bin/env python3
from argparse import ArgumentParser
from multiprocessing import Process
from random import randint, choice
from time import sleep
import docker
class ChaosMonkey(Process):
def __init__(self, amount, min_wait, max_wait):
super().__init__(target=self.work)
self.amount = amount
self.min_wait = min_wait
self.max_wait = max_wait
self.running = []
self.stopped = []
def work(self):
client = docker.from_env()
self.running = client.containers.list(filters={"name": "multiodoo-odoo", "status": "running"})
self.stopped = client.containers.list(filters={"name": "multiodoo-odoo", "status": "exited"})
if not self.running and not self.stopped:
print("No containers found. Stopping...")
return
if self.amount < 0:
self.amount = len(self.running) - 1
while True:
sleep(randint(self.min_wait, self.max_wait))
if len(self.stopped) == self.amount:
self.start_random_container()
stop = choice([True, False])
if self.running and stop:
self.kill_random_container()
else:
self.start_random_container()
def kill_random_container(self):
if not self.running:
return
index = randint(0, len(self.running) - 1)
container = self.running.pop(index)
print(f"Stopping {container.name}")
container.kill()
self.stopped.append(container)
def start_random_container(self):
if not self.stopped:
return
index = randint(0, len(self.stopped) - 1)
container = self.stopped.pop(index)
print(f"Starting {container.name}")
container.start()
self.running.append(container)
def main():
parser = ArgumentParser(description="This chaos monkey randomly turns off Odoo servers")
parser.add_argument(
"-n",
"--amount",
help="How many instances can be off at the same time",
default=-1,
)
parser.add_argument(
"--min-wait",
help="Minimum amount of seconds before causing more chaos",
default=3,
type=int,
)
parser.add_argument(
"--max-wait",
help="Maximum amount of seconds before causing more chaos",
default=10,
type=int,
)
args = parser.parse_args()
print("Starting Chaos Monkey")
monkey = ChaosMonkey(args.amount, args.min_wait, args.max_wait)
monkey.start()
monkey.join()
if __name__ == "__main__":
main()