-
Notifications
You must be signed in to change notification settings - Fork 1
/
locality_exp.py
252 lines (208 loc) · 8.67 KB
/
locality_exp.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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#!/usr/bin/env python3
import argparse
import docker
import math
import os
import random
import shlex
import signal
import subprocess
import time
import pprint as pp
from datetime import datetime
from pathlib import Path
NUM_PUBLISHERS = 1
NUMBER_SIMULATIONS = 1
qos_list = [0, 1, 2]
topic_name = "topic"
message_delay = 1
#CLUSTER_SIZE = 5
MESSAGE_TIME = 51
CLIENTS_CREATION = 5
DELAY = 10
def get_cluster_size():
client = docker.from_env()
clients = client.containers.list()
size = 0
for container in clients:
if not any(x in container.attrs['Name'] for x in ['pub', 'sub']):
size += 1
return size
def arg_parse():
parser = argparse.ArgumentParser(description='Locality experiment', add_help=False)
parser.add_argument('-m', '--messages', dest='NUM_MESSAGES', default=5,
help='number of published messages', type=int)
parser.add_argument('-s', '--subscribers', dest="NUM_SUBSCRIBERS", default=15,
help='number of subscribers', type=int)
parser.add_argument('-t', '--type', dest='BROKER_TYPE', required=True,
help='Cluster type')
parser.add_argument('-p', '--port', dest='port', default='1883',
help='mqtt broker port')
parser.add_argument('-n', '--sim-number', dest='SIMULATIONS', default=1,
help='number of iterations', type=int)
parser.add_argument('--speed', dest='DELAY', default=10,
help='sleep between stuff', type=int)
parser.add_argument('--no-messages', dest='no_messages', default=False, action='store_true',
help='do not send messages')
parser.add_argument('--no-clients', dest='no_clients', default=False, action='store_true',
help='do not load pubs and subs')
parser.add_argument('-b', '--brokers', dest='num_broker', default=get_cluster_size(),
help='cluster size', type=int)
return parser.parse_args()
def select_pub_sub():
pub_sub = {
0: {
'pub': random.randint(0, CLUSTER_SIZE - 1),
'sub': None},
50: {
'pub': random.randint(0, CLUSTER_SIZE - 1),
'sub': [i for i in range(0, CLUSTER_SIZE)]},
100: {
'pub': random.randint(0, CLUSTER_SIZE - 1),
'sub': None}
}
pub_sub[0]['sub'] = [random.choice(
[i for i in range(0, CLUSTER_SIZE) if i not in [pub_sub[0]['pub']]])] * CLUSTER_SIZE
pub_sub[100]['sub'] = [pub_sub[100]['pub']] * CLUSTER_SIZE
return pub_sub
def print_details():
print()
print("-" * 20)
# pp.pprint(locality_dict)
print("._" * 10)
print("Cluster size: {}".format(CLUSTER_SIZE))
print("# of subscribers: {}".format(NUM_SUBSCRIBERS))
print("# of publishers: {}".format(NUM_PUBLISHERS))
print("# of messages: {}".format(NUM_MESSAGES))
print()
def start_statistics(_path):
f = open(_path + "/stats.txt", "w")
cmd_stats = 'exec docker stats --format "{{.ID}},{{.Name}},{{.CPUPerc}},{{.MemUsage}},{{.MemPerc}},{{' \
'.NetIO}},{{.BlockIO}},{{.PIDs}}" | ts "%F-%H:%M:%S,"'
process_stats = subprocess.Popen(cmd_stats, stdout=f, shell=True, preexec_fn=os.setsid)
print("Logging stats...")
return process_stats
def start_tcpdump(_path):
_tcp_pid = []
for b_id in range(0, CLUSTER_SIZE):
cmd_tcpdump = "tcpdump -i s{broker_id}-eth1 src 10.0.{broker_id}.100 -w {folder}tcp{broker_id}.pcap -q".format(
broker_id=b_id, folder=os.path.expanduser(_path))
_tcp_pid.append(subprocess.Popen(shlex.split(cmd_tcpdump), stderr=subprocess.DEVNULL))
print("Logging tcpdump...")
return _tcp_pid
def start_clients(_subscribers, _publisher, _port, _qos, _path, _file_name):
if args.no_clients:
print("no clients, waiting...")
time.sleep(CLIENTS_CREATION)
else:
random.shuffle(_subscribers)
for indx, sub in enumerate(_subscribers):
subscriber_cmd = "docker exec -d mn.sub{id} python3 mosquitto_sub.py -h 10.0.{id}.100 " \
"-t {topic} -p {port} -q {qos} -m {msg} -c {clients} --folder {folder} --file-name {name}".format(
id=sub,
port=_port,
topic=topic_name,
qos=_qos,
msg=NUM_MESSAGES,
clients=math.floor(NUM_SUBSCRIBERS / len(_subscribers)),
folder=_path,
name="{}_{}".format(_file_name, indx))
subprocess.Popen(subscriber_cmd, shell=True)
print("Subscriber {index} created. Broker {id}".format(index=indx, id=sub))
time.sleep(DELAY)
print("Creating publisher {id}...".format(id=_publisher))
publisher_cmd = "docker exec -t mn.pub{id_pub} mqtt-benchmark --broker tcp://10.0.{id_pub}.100:{port} " \
"--topic {topic} --clients {clients} --count {msg} --qos {qos} --delay {rate} " \
"--folder {folder} --file-name {name}".format(
id_pub=_publisher,
port=_port,
topic=topic_name,
qos=_qos,
msg=NUM_MESSAGES,
clients=NUM_PUBLISHERS,
rate=message_delay,
folder=_path,
name=_file_name)
if args.no_messages or args.no_clients:
print("no messages, waiting...")
time.sleep(MESSAGE_TIME)
else:
os.system(publisher_cmd)
def simulation(sim_num):
for q in qos_list:
locality_dict = select_pub_sub()
pp.pprint(locality_dict)
for loc, clients in locality_dict.items():
path = "experiments/{day}/{type}/{minute}/{sim}/{qos}qos/{local}locality/".format(
day=START_DAY,
type=BROKER_TYPE,
minute=START_MINUTE,
sim=sim_num,
qos=q,
local=loc)
Path(path).mkdir(parents=True, exist_ok=True)
file_name = "{}sub{}pub".format(NUM_SUBSCRIBERS, NUM_PUBLISHERS)
print()
print("-" * 80)
print("++ Directory path: {}".format(path))
print("-" * 80)
print()
print("Sim num {}".format(sim_num))
print("Locality: {}%".format(loc))
print("QoS: {}".format(q))
for key, client in clients.items():
if key == 'sub':
sub_list = client
else:
publisher = client
# start loggers
stats_pid = start_statistics(path)
tcpdump_pid = start_tcpdump(path)
time.sleep(DELAY / 5)
start_clients(sub_list, publisher, args.port, q, path, file_name)
print("\n>>> Simulation number {}. {}% locality - {} qos - pub {} - sub {}... DONE\n".format(
sim_num, loc, q, NUM_PUBLISHERS, NUM_SUBSCRIBERS))
time.sleep(DELAY / 2)
# kill mosquitto_sub pids
print("Killing in the name! (subscribers)")
for sub_id in sub_list:
ps_cmd = "docker exec -t mn.sub{} ps | grep python3 | awk '{{print $1}}'".format(sub_id)
sub_pid = subprocess.getoutput(ps_cmd)
sub_pid = [int(x) for x in sub_pid.split("\n") if x]
for pid in sub_pid:
cmd = "docker exec -t mn.sub{} kill -2 {}".format(sub_id, int(pid))
print("-- {}".format(cmd))
subprocess.getoutput(cmd)
# if needed cat e2e_* > e2e_all.txt
print("Creating single e2e file...")
subprocess.getoutput("cat {path}/e2e_* > {path}/delay_e2e_all.txt".format(path=path))
subprocess.getoutput("mkdir {path}/e2e_raw".format(path=path))
subprocess.getoutput("mv {path}/e2e_* {path}/e2e_raw".format(path=path))
# kill other processes
os.killpg(os.getpgid(stats_pid.pid), signal.SIGTERM)
for pid in tcpdump_pid:
pid.kill()
time.sleep(DELAY / 4)
time.sleep(DELAY / 2)
def main():
print_details()
for sim in range(1, NUMBER_SIMULATIONS + 1):
simulation(sim)
print()
print("-" * 50)
print("Simulation level {} done".format(sim))
print("-" * 50)
time.sleep(DELAY * 2)
if __name__ == "__main__":
print(">>> Experiments, software version 7.0 <<<")
print("Looking at life through the eyes of a tired hub...")
START_DAY = datetime.now().strftime("%m-%d")
START_MINUTE = datetime.now().strftime("%H%M%S")
args = arg_parse()
NUM_MESSAGES = args.NUM_MESSAGES
BROKER_TYPE = args.BROKER_TYPE
NUM_SUBSCRIBERS = args.NUM_SUBSCRIBERS
NUMBER_SIMULATIONS = args.SIMULATIONS
CLUSTER_SIZE = args.num_broker
DELAY = args.DELAY
main()