forked from Gondolav/CS451-2020-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_final_FIFO.py
570 lines (455 loc) · 19.8 KB
/
test_final_FIFO.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
#!/usr/bin/env python3
import argparse
import os, atexit
import textwrap
import time
import tempfile
import threading, subprocess
import barrier, finishedSignal
import numpy as np
import sys
import signal
import random
import time
from enum import Enum
from collections import defaultdict, OrderedDict
BARRIER_IP = 'localhost'
BARRIER_PORT = 10000
SIGNAL_IP = 'localhost'
SIGNAL_PORT = 11000
PROCESSES_BASE_IP = 11000
# Do not run multiple validations concurrently!
class TC:
def __init__(self, losses, interface="lo", needSudo=True, sudoPassword="dcl"):
self.losses = losses
self.interface = interface
self.needSudo = needSudo
self.sudoPassword = sudoPassword
cmd1 = 'tc qdisc add dev {} root netem 2>/dev/null'.format(self.interface)
cmd2 = 'tc qdisc change dev {} root netem delay {} {} distribution normal loss {} {} reorder {} {}'.format(self.interface, *self.losses['delay'], *self.losses['loss'], *self.losses['reordering'])
if self.needSudo:
os.system("echo {} | sudo -S {}".format(self.sudoPassword, cmd1))
os.system("echo {} | sudo -S {}".format(self.sudoPassword, cmd2))
else:
os.system(cmd1)
os.system(cmd2)
atexit.register(self.cleanup)
def __str__(self):
ret = """\
Interface: {}
Distribution: Normal
Delay: {} {}
Loss: {} {}
Reordering: {} {}""".format(
self.interface,
*self.losses['delay'],
*self.losses['loss'],
*self.losses['reordering'])
return textwrap.dedent(ret)
def cleanup(self):
cmd = 'tc qdisc del dev {} root 2>/dev/null'.format(self.interface)
if self.needSudo:
os.system("echo '{}' | sudo -S {}".format(self.sudoPassword, cmd))
else:
os.system(cmd)
class ProcessState(Enum):
RUNNING = 1
STOPPED = 2
TERMINATED = 3
class ProcessInfo:
def __init__(self, handle):
self.lock = threading.Lock()
self.handle = handle
self.state = ProcessState.RUNNING
@staticmethod
def stateToSignal(state):
if state == ProcessState.RUNNING:
return signal.SIGCONT
if state == ProcessState.STOPPED:
return signal.SIGSTOP
if state == ProcessState.TERMINATED:
return signal.SIGTERM
@staticmethod
def stateToSignalStr(state):
if state == ProcessState.RUNNING:
return "SIGCONT"
if state == ProcessState.STOPPED:
return "SIGSTOP"
if state == ProcessState.TERMINATED:
return "SIGTERM"
@staticmethod
def validStateTransition(current, desired):
if current == ProcessState.TERMINATED:
return False
if current == ProcessState.RUNNING:
return desired == ProcessState.STOPPED or desired == ProcessState.TERMINATED
if current == ProcessState.STOPPED:
return desired == ProcessState.RUNNING
return False
class AtomicSaturatedCounter:
def __init__(self, saturation, initial=0):
self._saturation = saturation
self._value = initial
self._lock = threading.Lock()
def reserve(self):
with self._lock:
if self._value < self._saturation:
self._value += 1
return True
else:
return False
class Validation:
def __init__(self, processes, messages, outputDir):
self.processes = processes
self.messages = messages
self.outputDirPath = os.path.abspath(outputDir)
if not os.path.isdir(self.outputDirPath):
raise Exception("`{}` is not a directory".format(self.outputDirPath))
def generateConfig(self):
# Implement on the derived classes
pass
def checkProcess(self, pid):
# Implement on the derived classes
pass
def checkAll(self, continueOnError=True):
ok = True
for pid in range(1, self.processes+1):
ret = self.checkProcess(pid)
if not ret:
ok = False
if not ret and not continueOnError:
return False
return ok
class FifoBroadcastValidation(Validation):
def generateConfig(self):
hosts = tempfile.NamedTemporaryFile(mode='w')
config = tempfile.NamedTemporaryFile(mode='w')
for i in range(1, self.processes + 1):
hosts.write("{} 127.0.0.1 {}\n".format(i, PROCESSES_BASE_IP+i))
hosts.flush()
config.write("{}\n".format(self.messages))
config.flush()
return (hosts, config)
def checkProcess(self, pid):
filePath = os.path.join(self.outputDirPath, 'proc{:02d}.output'.format(pid))
i = 1
nextMessage = defaultdict(lambda : 1)
filename = os.path.basename(filePath)
with open(filePath) as f:
for lineNumber, line in enumerate(f):
tokens = line.split()
# Check broadcast
if tokens[0] == 'b':
msg = int(tokens[1])
if msg != i:
print("File {}, Line {}: Messages broadcast out of order. Expected message {} but broadcast message {}".format(filename, lineNumber, i, msg), flush=True)
return False
i += 1
# Check delivery
if tokens[0] == 'd':
sender = int(tokens[1])
msg = int(tokens[2])
if msg != nextMessage[sender]:
print("File {}, Line {}: Message delivered out of order. Expected message {}, but delivered message {}".format(filename, lineNumber, nextMessage[sender], msg), flush=True)
return False
else:
nextMessage[sender] = msg + 1
return True
class LCausalBroadcastValidation(Validation):
def __init__(self, processes, outputDir, causalRelationships):
super().__init__(processes, outputDir)
def generateConfig(self):
raise NotImplementedError()
def checkProcess(self, pid):
raise NotImplementedError()
class StressTest:
def __init__(self, procs, concurrency, attempts, attemptsRatio):
self.processes = len(procs)
self.processesInfo = dict()
for (logicalPID, handle) in procs:
self.processesInfo[logicalPID] = ProcessInfo(handle)
self.concurrency = concurrency
self.attempts = attempts
self.attemptsRatio = attemptsRatio
maxTerminatedProcesses = self.processes // 2 if self.processes % 2 == 1 else (self.processes - 1) // 2
self.terminatedProcs = AtomicSaturatedCounter(maxTerminatedProcesses)
def stress(self):
selectProc = list(range(1, self.processes+1))
random.shuffle(selectProc)
selectOp = [ProcessState.STOPPED] * int(1000 * self.attemptsRatio['STOP']) + \
[ProcessState.RUNNING] * int(1000 * self.attemptsRatio['CONT']) + \
[ProcessState.TERMINATED] * int(1000 * self.attemptsRatio['TERM'])
random.shuffle(selectOp)
successfulAttempts = 0
while successfulAttempts < self.attempts:
proc = random.choice(selectProc)
op = random.choice(selectOp)
info = self.processesInfo[proc]
with info.lock:
if ProcessInfo.validStateTransition(info.state, op):
if op == ProcessState.TERMINATED:
reserved = self.terminatedProcs.reserve()
if reserved:
selectProc.remove(proc)
else:
continue
time.sleep(float(random.randint(50, 500)) / 1000.0)
info.handle.send_signal(ProcessInfo.stateToSignal(op))
info.state = op
successfulAttempts += 1
print("Sending {} to process {}".format(ProcessInfo.stateToSignalStr(op), proc), flush=True)
# if op == ProcessState.TERMINATED and proc not in terminatedProcs:
# if len(terminatedProcs) < maxTerminatedProcesses:
# terminatedProcs.add(proc)
# if len(terminatedProcs) == maxTerminatedProcesses:
# break
def remainingUnterminatedProcesses(self):
remaining = []
for pid, info in self.processesInfo.items():
with info.lock:
if info.state != ProcessState.TERMINATED:
remaining.append(pid)
return None if len(remaining) == 0 else remaining
def terminateAllProcesses(self):
for _, info in self.processesInfo.items():
with info.lock:
if info.state != ProcessState.TERMINATED:
if info.state == ProcessState.STOPPED:
info.handle.send_signal(ProcessInfo.stateToSignal(ProcessState.RUNNING))
info.handle.send_signal(ProcessInfo.stateToSignal(ProcessState.TERMINATED))
return False
def continueStoppedProcesses(self):
for _, info in self.processesInfo.items():
with info.lock:
if info.state != ProcessState.TERMINATED:
if info.state == ProcessState.STOPPED:
info.handle.send_signal(ProcessInfo.stateToSignal(ProcessState.RUNNING))
def run(self):
if self.concurrency > 1:
threads = [threading.Thread(target=self.stress) for _ in range(self.concurrency)]
[p.start() for p in threads]
[p.join() for p in threads]
else:
self.stress()
def startProcesses(processes, runscript, hostsFilePath, configFilePath, outputDir, tent):
runscriptPath = os.path.abspath(runscript)
if not os.path.isfile(runscriptPath):
raise Exception("`{}` is not a file".format(runscriptPath))
if os.path.basename(runscriptPath) != 'run.sh':
raise Exception("`{}` is not a runscript".format(runscriptPath))
outputDirPath = os.path.abspath(outputDir)
if not os.path.isdir(outputDirPath):
raise Exception("`{}` is not a directory".format(outputDirPath))
baseDir, _ = os.path.split(runscriptPath)
bin_cpp = os.path.join(baseDir, "bin", "da_proc")
bin_java = os.path.join(baseDir, "bin", "da_proc.jar")
if os.path.exists(bin_cpp):
cmd = [bin_cpp]
elif os.path.exists(bin_java):
cmd = ['java', '-jar', bin_java]
else:
raise Exception("`{}` could not find a binary to execute. Make sure you build before validating".format(runscriptPath))
os.mkdir(outputDir + str(tent))
outputDirPath = os.path.abspath(outputDir + str(tent))
procs = []
for pid in range(1, processes+1):
cmd_ext = ['--id', str(pid),
'--hosts', hostsFilePath,
'--barrier', '{}:{}'.format(BARRIER_IP, BARRIER_PORT),
'--signal', '{}:{}'.format(SIGNAL_IP, SIGNAL_PORT),
'--output', os.path.join(outputDirPath, 'proc{:02d}.output'.format(pid)),
configFilePath]
stdoutFd = open(os.path.join(outputDirPath, 'proc{:02d}.stdout'.format(pid)), "w")
stderrFd = open(os.path.join(outputDirPath, 'proc{:02d}.stderr'.format(pid)), "w")
procs.append((pid, subprocess.Popen(cmd + cmd_ext, stdout=stdoutFd, stderr=stderrFd)))
return procs
def main(processes, messages_avoided, runscript, broadcastType, logsDir, testConfig):
# Set tc for loopback
# tc = TC(testConfig['TC'])
# print(tc)
# windowSize = [100, 500, 1000, 2500, 5000, 10000, 20000]
# initThresh = [100, 500, 1000, 5000, 10000, 50000]
messages_list = [100, 500, 1000, 3000, 5000, 10000, 15000, 30000, 100000, 1000000]
waiting_time = [60, 60, 300, 600, 600, 600, 1200, 1200, 300, 600]
for i, messages in enumerate(messages_list):
tot_finishes = []
tot_dels = []
print("tentative:", i)
print("Messages:", messages)
print("Will wait:", waiting_time[i])
# Start the barrier
initBarrier = barrier.Barrier(BARRIER_IP, BARRIER_PORT, processes)
initBarrier.listen()
startTimesFuture = initBarrier.startTimesFuture()
initBarrierThread = threading.Thread(target=initBarrier.wait)
initBarrierThread.start()
# Start the finish signal
finishSignal = finishedSignal.FinishedSignal(SIGNAL_IP, SIGNAL_PORT, processes)
finishSignal.listen()
finishSignalThread = threading.Thread(target=finishSignal.wait)
finishSignalThread.start()
if broadcastType == "fifo":
validation = FifoBroadcastValidation(processes, messages, logsDir)
else:
validation = LCausalBroadcastValidation(processes, messages, logsDir, None)
hostsFile, configFile = validation.generateConfig()
try:
# Start the processes and get their PIDs
procs = startProcesses(processes, runscript, hostsFile.name, configFile.name, logsDir, i)
# Create the stress test
st = StressTest(procs,
testConfig['ST']['concurrency'],
testConfig['ST']['attempts'],
testConfig['ST']['attemptsDistribution'])
for (logicalPID, procHandle) in procs:
print("Process with logicalPID {} has PID {}".format(logicalPID, procHandle.pid), flush=True)
initBarrierThread.join()
print("All processes have been initialized.", flush=True)
#st.run()
print("StressTest is complete.")
print("Resuming stopped processes.")
st.continueStoppedProcesses()
print("Waiting until all running processes have finished broadcasting.", flush=True)
finishSignalThread.join(1)
if(not finishSignalThread.is_alive()):
finishes = []
for pid, startTs in OrderedDict(sorted(startTimesFuture.items())).items():
print("Process {} finished broadcasting {} messages in {} ms".format(pid, messages, finishSignal.endTimestamps()[pid] - startTs), flush=True)
finishes.append(finishSignal.endTimestamps()[pid] - startTs)
avg_time = np.mean(np.array(finishes))
print("Average time to finished broadcast: {} ms".format(avg_time), flush=True)
tot_finishes.append(avg_time)
else:
tot_finishes.append(1000)
print("Average time to finished broadcast: > 1 seconds", flush=True)
numberDel = []
time.sleep(waiting_time[i])
st.terminateAllProcesses()
time.sleep(3)
for pid in range(1, processes+1):
filePath = os.path.join(logsDir, str(i), 'proc{:02d}.stdout'.format(pid))
with open(filePath) as f:
for line in f:
if "Total message delivered: " in line:
tot_del = line.split("Total message delivered: ")[-1].rstrip("\n").rstrip()
print("Process {} delivered {} messages".format(pid, tot_del), flush=True)
numberDel.append(int(tot_del))
break
avg_del = np.mean(np.array(numberDel))
print("Average number of delivered messages: {} ".format(avg_del), flush=True)
tot_dels.append(avg_del)
mutex = threading.Lock()
def waitForProcess(logicalPID, procHandle, mutex):
procHandle.wait()
with mutex:
print("Process {} exited with {}".format(logicalPID, procHandle.returncode), flush=True)
# Monitor which processes have exited
monitors = [threading.Thread(target=waitForProcess, args=(logicalPID, procHandle, mutex)) for (logicalPID, procHandle) in procs]
[p.start() for p in monitors]
[p.join() for p in monitors]
if procs is not None:
for _, p in procs:
p.kill()
# input('Hit `Enter` to validate the output')
# print("Result of validation: {}".format(validation.checkAll()))
finally:
if procs is not None:
for _, p in procs:
p.kill()
full_avg_del = np.mean(np.array(tot_dels))
print(full_avg_del, flush=True)
full_avg_finishes = np.mean(np.array(tot_finishes))
print(full_avg_finishes, flush=True)
if __name__ == "__main__":
sys.stdout = open("param.log", "w")
parser = argparse.ArgumentParser()
parser.add_argument(
"-r",
"--runscript",
required=True,
dest="runscript",
help="Path to run.sh",
)
parser.add_argument(
"-b",
"--broadcast",
choices=["fifo", "lcausal"],
required=True,
dest="broadcastType",
help="Which broadcast implementation to test",
)
parser.add_argument(
"-l",
"--logs",
required=True,
dest="logsDir",
help="Directory to store stdout, stderr and outputs generated by the processes",
)
parser.add_argument(
"-p",
"--processes",
required=True,
type=int,
dest="processes",
help="Number of processes that broadcast",
)
parser.add_argument(
"-m",
"--messages",
required=True,
type=int,
dest="messages",
help="Maximum number (because it can crash) of messages that each process can broadcast",
)
results = parser.parse_args()
testConfig = {
# # Network configuration using the tc command
# 'TC': {
# 'delay': ('100ms', '25ms'),
# 'loss': ('5%', '10%'),
# 'reordering': ('10%', '20%')
# },
# # StressTest configuration
# 'ST': {
# 'concurrency' : , # How many threads are interferring with the running processes
# 'attempts' : 8, # How many interferring attempts each threads does
# 'attemptsDistribution' : { # Probability with which an interferring thread will
# 'STOP': 0.48, # select an interferring action (make sure they add up to 1)
# 'CONT': 0.48,
# 'TERM':0.04
# }
# }
# No stress
#Network configuration using the tc command
'TC': {
'delay': ('0ms', '0ms'),
'loss': ('0%', '0%'),
'reordering': ('0%', '0%')
},
# StressTest configuration
'ST': {
'concurrency' : 0, # How many threads are interferring with the running processes
'attempts' : 0, # How many interferring attempts each threads does
'attemptsDistribution' : { # Probability with which an interferring thread will
'STOP': 0, # select an interferring action (make sure they add up to 1)
'CONT': 0,
'TERM':0
}
}
# 'TC': {
# 'delay': ('200ms', '50ms'),
# 'loss': ('10%', '25%'),
# 'reordering': ('25%', '50%')
# },
# # StressTest configuration
# 'ST': {
# 'concurrency' : 8, # How many threads are interferring with the running processes
# 'attempts' : 8, # How many interferring attempts each threads does
# 'attemptsDistribution' : { # Probability with which an interferring thread will
# 'STOP': 0.48, # select an interferring action (make sure they add up to 1)
# 'CONT': 0.48,
# 'TERM':0.04
# }
# }
}
main(results.processes, results.messages, results.runscript, results.broadcastType, results.logsDir, testConfig)