-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathload-befaas.py
277 lines (215 loc) · 6.75 KB
/
load-befaas.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#!/usr/bin/env python3
import base64
import datetime
import os
import random
import json
import sys
import typing
import urllib.request
import urllib.error
import uuid
import time
import threading
import multiprocessing as mp
import tqdm
THREADS = 10
OUTPUT = "output.txt"
DURATION = int(os.getenv("DURATION", 60))
def _getcurrtime() -> str:
return datetime.datetime.now(tz=datetime.timezone.utc).isoformat()
def trafficsensorfilter_getjson() -> typing.Dict[str, typing.Any]:
return {
"carDirection": {
"plate": "OD DI 98231",
"direction": 4,
# this was in the original workload, no idea what the intention is
"speed": random.choice([10, 800]),
}
}
def weathersensorfilter_getjson() -> typing.Dict[str, typing.Any]:
return {
"temperature": 10.0,
"humidity": 50.0,
"wind": 5.0,
"rain": random.choice([True, False]),
}
image_ambulance = base64.b64encode(open("image-ambulance.jpg", "rb").read()).decode(
"ascii"
)
image_noambulance = base64.b64encode(open("image-noambulance.jpg", "rb").read()).decode(
"ascii"
)
START_TIME = time.time()
def objectrecognition_getjson() -> typing.Dict[str, typing.Any]:
f = "placeholder"
# reasonable change every 20 seconds for 5 seconds
if time.time() - START_TIME % 20 < 5:
f = image_ambulance
else:
f = image_noambulance
return {
"image": f,
}
workload = {
"phases": [
{
"duration": DURATION,
"arrivalRate": 5,
}
],
"scenarios": [
{
"func": "trafficsensorfilter",
"getjson": trafficsensorfilter_getjson,
"async": False,
"name": "trafficsensorfilter",
"weight": 45,
},
{
"func": "weathersensorfilter",
"getjson": weathersensorfilter_getjson,
"async": False,
"name": "weatherSensorFilter",
"weight": 10,
},
{
"func": "objectrecognition",
"getjson": objectrecognition_getjson,
"async": False,
"name": "objectrecognition",
"weight": 45,
},
],
}
def worker(
task_queue: "mp.Queue[typing.Dict[str, typing.Any]]",
output_queue: "mp.Queue[str]",
pipe: "mp.connection.Connection",
) -> None:
while True:
# get the next task from the queue
try:
task = task_queue.get(timeout=5)
except:
# timeout
if pipe.poll():
# parent is done, we can exit
pipe.recv()
pipe.close()
return
continue
try:
r = urllib.request.Request(
task["endpoint"],
data=task["data"],
headers=task["headers"],
)
start = f"BEFAAS;{_getcurrtime()};client;{task['xpair']};{task['xpair']};{task['xcontext']};start-call-{task['function']}"
res = urllib.request.urlopen(r)
# get the result
except urllib.error.HTTPError as e:
print(e)
except Exception as e:
print(e)
end = f"BEFAAS;{_getcurrtime()};client;{task['xpair']};{task['xpair']};{task['xcontext']};end-call-{task['function']}"
output_queue.put(start)
output_queue.put(end)
return
def logger(
output: str,
output_queue: "mp.Queue[str]",
pipe: "mp.connection.Connection",
) -> None:
with open(output, "w") as f:
while True:
# get the next task from the queue
try:
entry = output_queue.get(timeout=5)
except:
# timeout
if pipe.poll():
# parent is done, we can exit
pipe.recv()
pipe.close()
return
continue
f.write(f"node=client handler=nil stream=stdout {_getcurrtime()} {entry}\n")
if __name__ == "__main__":
# no args, assume everything we need is in os.environ
task_queue: "mp.Queue[typing.Dict[str, typing.Any]]" = mp.Queue()
output_queue: "mp.Queue[str]" = mp.Queue()
# start the workers
p: typing.Dict[int, mp.Process] = {}
pipes = []
for i in range(THREADS):
pipe_parent, pipe_child = mp.Pipe()
p[i] = mp.Process(
target=worker,
args=(task_queue, output_queue, pipe_child),
)
p[i].start()
pipes.append(pipe_parent)
# start the logger
logger_pipe_parent, logger_pipe_child = mp.Pipe()
logger_proc = mp.Process(
target=logger, args=(OUTPUT, output_queue, logger_pipe_child)
)
logger_proc.start()
# start the task generator
for phase in workload["phases"]: # type: ignore
start = time.perf_counter()
end = start + phase["duration"]
weights = [s["weight"] for s in workload["scenarios"]] # type: ignore
while True:
if time.perf_counter() > end:
break
start_time = time.perf_counter()
selected_scenario = random.choices(workload["scenarios"], weights=weights)[ # type: ignore
0
]
# get the parameters
j = selected_scenario["getjson"]()
# generate xpair and xcontext
xpair = str(uuid.uuid4())
xcontext = str(uuid.uuid4())
data = {
"data": j,
"xpair": xpair,
"xcontext": xcontext,
}
headers = {
"Content-Type": "application/json",
}
if selected_scenario["async"]:
headers["X-tinyFaaS-Async"] = "True"
# generate the task
task = {
"desc": selected_scenario["name"],
"endpoint": os.getenv(f"ENDPOINT_{selected_scenario['func'].upper()}"),
"data": json.dumps(data).encode("utf-8"),
"headers": headers,
"xpair": xpair,
"xcontext": xcontext,
"function": selected_scenario["func"],
}
# put the task in the queue
task_queue.put(task)
# sleep
end_time = time.perf_counter()
took = end_time - start_time
st = 1 / selected_scenario["weight"] - took
time.sleep(max(st, 0))
# inform the workers that we are done
# wait that the queue is empty
while not task_queue.empty():
time.sleep(1)
for pipe in pipes:
pipe.send(True)
pipe.close()
logger_pipe_parent.send(True)
# wait for the workers to finish
for i in range(THREADS):
p[i].join()
logger_proc.join()
sys.exit(0)