-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.da_deadlock_imp.da
551 lines (452 loc) · 20.8 KB
/
main.da_deadlock_imp.da
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
import sys
import time
import random
import heapq
import signal
import os
import csv
import timeit
config(channel is fifo, clock is lamport)
class StatMonitor(process):
def setup(totalRuns:int ,algo):
self.curRun = 0
self.sendQueue = None
self.csQueue = None
self.startTest = None
self.parent = None
self.startTest = False
self.totalProcs = None
self.totalRequests = None
print("Monitor is setup for algorithm: ", algo)
# We must bind the start and end calls to a parent process. As only parent should
# have the priviledge to start/end monitoring services
def receive(msg= ('startTest', nprocs, nreqs ,tnum, p)):
print("Monitor:: Recieved startTest command for test number: ", tnum)
startTest = True
curRun = curRun + 1
assert(tnum == curRun)
totalProcs = nprocs
totalRequests = nreqs
print(totalRequests)
parent = p
csQueue = []
sendQueue = []
def receive(msg= ('endTest', tnum, p)):
if p != parent:
return
#print("Monitor:: Recieved endTest command")
assert(tnum == curRun)
endTest = True
startTest = False
validate()
reset()
def receive(msg= ('send', c, p)):
#print("Monitor:: Recieved send command timestamped: ", c)
heapq.heappush(sendQueue,(c, p, 'send'))
def receive(msg= ('enterCS', c, p)):
#print("Monitor:: Recieved enterCS command timestamped: ", c)
heapq.heappush(csQueue,(c, p,'enterCS'))
def receive(msg= ('exitCS', c, p)):
#print("Monitor:: Recieved exitCS command timestamped: ", c)
heapq.heappush(csQueue,(c, p,'exitCS'))
def reset():
self.curRun = 0
self.sendQueue = None
self.csQueue = None
self.startTest = None
self.parent = None
self.startTest = False
## This function iterates over the entire history of messages collected by the monitor
## process and chacks if there has been a condition where more than one process are in
## critical section based on the Lamport's clock value and CS request ordering in the
## CS request queue
def validate_safety():
length = len(csQueue)
if(length&1):
return False;
prevclk = None
prevps = None
for idx in range(0,length):
if(idx&1):
clk , ps, tag = heapq.heappop(csQueue)
if prevclk > clk or tag != 'exitCS' or ps != prevps:
return False
else:
prevclk,prevps,prevtag = heapq.heappop(csQueue)
if(prevtag != 'enterCS'):
return False;
return True
def validate_liveliness():
# if there is a deadlock we output it in the file and just kill the processes from the signal handler
# and expect for a restart.
# if this call is made then for sure the process is not in deadlock
return True
def validate():
## 1. Check for safety
## 2. Check for liveliness
#print("------Send Queue------")
heapq.heapify(sendQueue)
#print(sendQueue)
#print("------Send Queue------")
#print("-------CS Queue------")
heapq.heapify(csQueue)
#print(csQueue)
#print("--------CS Queue------")
sResult = validate_safety()
lResult = validate_liveliness()
print("**************Safety Result for TC: ",curRun, " ", sResult,"******************")
print("**************Liveliness Result for TC: ",curRun, " ", lResult,"******************")
with open('Correctness.csv', mode='a') as corr_file:
writer = csv.writer(corr_file)
writer.writerow([curRun,totalProcs,totalRequests,sResult,lResult])
def deadlock_handler(signum, frame):
output("LIVELINESS FAILED :: DeadLock detected")
with open('Correctness.csv', mode='a') as corr_file:
writer = csv.writer(corr_file)
writer.writerow([curRun,totalProcs,totalRequests,False,False])
os.kill(os.getppid(), signal.SIGTERM)
def wait_wrapper():
signal.signal(signal.SIGALRM, deadlock_handler)
signal.alarm(30)
await(received(('done',), from_=parent))
signal.alarm(0)
# Checking for various properties of algorithm code goes in here..
# Output results in a form of a table/csv format
def run():
print("Monitor Process is running")
wait_wrapper()
-- yield2
if curRun == totalRuns:
output("MONITOR :: Shutting Down!")
send(('terminate', algo, self), to=parent)
else:
print("Sanity is broken...BEWARE!!!")
# We have recieved the request to start Test now.
class OrigP(process):
def setup(s:set, nrequests:int, monitor:Monitor = None): # s is set of all other processes
self.q = set()
self.monitor = monitor
def mutex(task):
-- request
c = logical_clock()
send(('request', c, self), to= s)
q.add(('request', c, self))
await(each(('request', c2, p) in q,
has= (c2, p)==(c, self) or (c, self) < (c2, p)) and
each(p in s, has= some(received(('ack', c2, _p)), has= c2 > c)))
-- critical_section
task()
-- release
q.remove(('request', c, self))
send(('release', logical_clock(), self), to= s)
def receive(msg= ('request', c2, p)):
q.add(('request', c2, p))
send(('ack', logical_clock(), self), to= p)
def receive(msg= ('release', _, p)):
# q.remove(('request', _, p)) # pattern matching needed for _
# q.remove(anyof(setof(('request', c, p), ('request', c, _p) in q)))
for x in setof(('request', c, p), ('request', c, _p) in q):
q.remove(x)
break
# for ('request', c, _p) in q: q.remove('request', c, p); break
# for (tag, c, p2) in q:
# if tag == 'request' and p2 == p:
# q.remove((tag, c, p2)); break
def run():
def task():
output('in cs')
for i in range(nrequests):
mutex(task)
send(('done', self), to= parent())
await(received(('done',), from_=parent()))
output('terminating')
class SpecP(process):
def setup(s:set, nrequests:int, monitor:Monitor=None): # s is set of all other processes
self.monitor = monitor
def mutex(task):
-- request
c = logical_clock()
if monitor != None:
send(('send', logical_clock(), self), to= monitor)
send(('request', c, self), to= s)
await(each(received(('request', c2, p)),
has= received(('release', c2, p)) or (c, self) < (c2, p))
and each(p in s, has= received(('ack', c, p))))
-- critical_section
if monitor != None:
send(('enterCS', logical_clock(), self), to= monitor)
task()
-- release
if monitor != None:
send(('exitCS', logical_clock(), self), to= monitor)
send(('release', c, self), to= s)
def receive(msg= ('request', c, p)):
send(('ack', c, self), to= p)
def run():
def task():
output('in cs')
output('releasing cs')
for i in range(nrequests):
mutex(task)
send(('done', self), to= s)
await(each(p in s, has= received(('done', p))))
send(('done', self), to= parent())
await(received(('done',), from_=parent()))
output('terminating')
class MainP(process):
def setup(s:set, nrequests:int, monitor:Monitor = None): # s is set of all other processes
self.q = set()
self.requestsToSend = nrequests
self.requestsToProcess = 0
self.requestsToRelease = 0
#############################################################################################
## As per Lamport's RULE 5: Process Pi is granted a resource when
## (i) There is a Tm:Pi requests resource message in its request queue which is ordered
## before any other request in its queue
## (ii) Pi has received a message from every other process time-stamped later than Tm
##
## The function get_request_to_process() and get_request_to_release()
## will act as place holder on deciding the interpretation of 'any' in
## Lamport's clock paper.By changing the implementation of this method, we can have different
## implementation of any 'one' in lamport's paper. In the below implemetation the process Pi
## will always release the request which it finished processing rather than any 'one'.
## But, when this request reaches the other processes, there we just remove any 'one' request
## of Pi from the queue without checking for the earliest one.
##
#############################################################################################
def get_request_to_process():
min = 0xFFFFFFFF
req = None
for (tag , c, p) in q:
if(tag == 'request' and (p == self) and (c < min)):
min = c
req = ('request', c, self)
return req
def get_request_to_release():
min = 0xFFFFFFFF
req = None
for (tag , c, p) in q:
if(tag == 'request' and (p == self) and (c < min)):
min = c
req = ('request', c, self)
return req
def send_request():
if requestsToSend > 0:
-- request
c = logical_clock()
if monitor != None:
send(('send', logical_clock(), self), to= monitor)
#output("SEND_REQUEST() :: Request generated at clock ", c)
send(('request', c, self), to= s)
q.add(('request', c, self))
requestsToSend = requestsToSend - 1
requestsToProcess = requestsToProcess + 1
def enter_CS(task):
--cs
if(requestsToProcess > 0):
curReq = get_request_to_process()
#output("ENTER_CS() :: Wait on current request: ", curReq)
if(each(('request', c2, p) in q,
has= (c2, p)==(curReq[1], self) or (curReq[1], self) < (c2, p))):
if(each(p in s, has= some(received(('ack', c2, _p)), has= c2 > curReq[1]))):
if monitor != None:
send(('enterCS', logical_clock(), self), to= monitor)
#output("ENTER_CS() :: Request ", curReq, "is entering CS now at clk = ", logical_clock())
-- critical_section
task()
requestsToProcess = requestsToProcess - 1
requestsToRelease = requestsToRelease + 1
def release():
-- release
if(requestsToRelease > 0):
curReq = get_request_to_release()
q.remove(curReq)
if monitor != None:
send(('exitCS', logical_clock(), self), to= monitor)
#output("RELEASE() :: ", curReq, " is released now at clk = ", logical_clock())
send(('release', logical_clock(), self), to= s)
requestsToRelease = requestsToRelease - 1
def receive(msg= ('request', c2, p)):
#output("Received request message from ", p, "timestamped: ", c2)
q.add(('request', c2, p))
send(('ack', logical_clock(), self), to= p)
## Note:: Definition of 'any' is now changed to the oldest request that is received from a process Pi,
## rather than chosing any 'one'
def receive(msg= ('release', c1, p)):
##Releasing any request from the queue on receiving release request as per
# ##Lamport's 5 rules. But with this we see both safety and liveliness problem
for x in setof(('request', c, p), ('request', c, _p) in q):
q.remove(x)
break
# min = 0xFFFFFFFF
# req = None
# for (tag , c, p1) in q:
# if(tag == 'request' and (p1 == p) and (c < min)):
# min = c
# req = ('request', c, p)
# q.remove(req)
if monitor == None:
pass
#output("Received release message from ", p," for request timestamped: ", req[1], "at LC: ", logical_clock())
# Test code for handling Ack messages in handlers as well
# def receive(msg= ('ack', c, p)):
# output(self," Received ack from ", p)
# ackQ.add(('ack', c, p))
def run():
def task():
output('in cs')
while(requestsToSend or requestsToProcess or requestsToRelease ):
send_request()
enter_CS(task)
release()
# output(requestsToSend, requestsToProcess, requestsToRelease)
send(('done', self), to= parent())
await(received(('done',), from_=parent()))
output('terminating')
def main():
output("---------------------Main Begins-----------------------")
nprocs = int(sys.argv[1]) if len(sys.argv) > 1 else 10
nreqs = int(sys.argv[2]) if len(sys.argv) > 2 else 1
nruns = int(sys.argv[3]) if len(sys.argv) > 3 else 1
nparams = int(sys.argv[4]) if len(sys.argv) > 4 else 1
nreps = int(sys.argv[5]) if len(sys.argv) > 5 else 1
algorithms = ('MyLamport','OrigLamport','SpecLamport')
perform_correctness = True
perform_performance = True
# checkCorrectness for each algorithm and save the statistics in a seperate file
if(perform_correctness):
print("*******************CORRECTNESS VALIDATION START**********************")
print("")
if os.path.exists("Correctness.csv"):
os.remove("Correctness.csv")
with open('Correctness.csv', mode='a') as corr_file:
writer = csv.writer(corr_file)
writer.writerow(["Correctness Comparision w.r.t Algorithms"])
for algo in algorithms:
algoToRun = None
resultList = None
if algo == 'MyLamport' :
algoToRun = MainP
elif algo == 'OrigLamport':
algoToRun = OrigP
elif algo == 'SpecLamport':
algoToRun = SpecP
with open('Correctness.csv', mode='a') as corr_file:
writer = csv.writer(corr_file)
writer.writerow(["Algorithm: " + algo])
writer.writerow(['Run Sequence:', 'Number of Processes', 'Number of Requests', 'Safety', 'Liveliness'])
print("*********************************************************************")
print ("NumProcs: ", nprocs, " NumRequests: ", nreqs, " Num Runs: ", nruns,)
print("*********************************************************************")
mp = new(StatMonitor)
setup(mp,(nruns,algo))
start(mp)
for i in range(1,nruns+1):
procs = random.randint(1, nprocs)
reqs = random.randint(1, nreqs)
print ("Run Seq : ", i, " NumProcs: ", procs, " NumRequests: ", reqs)
send(('startTest', procs, reqs, i, self), to= mp)
ps = new(algoToRun, num=procs)
for p in ps: setup(p, (ps-{p}, reqs, mp))
start(ps)
await(each(proc in ps, has=received(('done', proc))))
send(('done',), to= ps)
print (algo,":: Run Seq:: ", i, " Completed!!")
send(('endTest', i, self), to= mp)
send(('done',), to= mp)
await(received(('terminate', algo, mp), from_= mp))
print("*******************CORRECTNESS VALIDATION ENDS**********************")
if(perform_performance):
if os.path.exists("Performance_varyingReqs.csv"):
os.remove("Performance_varyingReqs.csv")
if os.path.exists("Performance_varyingProcs.csv"):
os.remove("Performance_varyingProcs.csv")
print("*******************PERFORMANCE VALIDATION STARTS**********************")
# Run with varying number of requests first keeping procs = nprocs
with open('Performance_varyingReqs.csv', mode='a') as perf1_file:
writer = csv.writer(perf1_file)
writer.writerow(["Performance Comparision With Varying Requests"])
for algo in algorithms:
algoToRun = None
if algo == 'MyLamport' :
algoToRun = MainP
elif algo == 'OrigLamport':
algoToRun = OrigP
elif algo == 'SpecLamport':
algoToRun = SpecP
with open('Performance_varyingReqs.csv', mode='a') as perf1_file:
writer = csv.writer(perf1_file)
subHeading = "Algorithm: " + algo + " Procs: " + str(nprocs) + " Reps: " + str(nreps)
writer.writerow([subHeading])
writer.writerow(['Run Seq:', 'Number of Requests', 'Execution Time (s)'])
procs = nprocs
reqs = dr = (int)(nreqs/nparams)
runSeq = 1
for req in range(reqs, nreqs+1, dr):
print("*********************************************************************")
print ("Num Runs: ", nreps, " NumProcs: ", procs, " NumRequests: ", reqs)
print("*********************************************************************")
runTime = 0.0
for i in range(1,nreps+1):
ps = new(algoToRun, num=procs)
for p in ps: setup(p, (ps-{p}, reqs))
startTime = timeit.default_timer()
start(ps)
await(each(proc in ps, has=received(('done', proc))))
runTime = runTime + (timeit.default_timer() - startTime)
send(('done',), to= ps)
print (algo, ":: Run Seq:: ", i, " Completed!!")
runTime = runTime/nreps
with open('Performance_varyingReqs.csv', mode='a') as perf1_file:
writer = csv.writer(perf1_file)
writer.writerow([runSeq, req, runTime])
runSeq = runSeq + 1
#print("Procs: ", procs, " Req: ", req, "RunTime: " , runTime)
# Run with varying number of procs first keeping request = nreqs
with open('Performance_varyingProcs.csv', mode='a') as perf1_file:
writer = csv.writer(perf1_file)
writer.writerow(["Performance Comparision With Varying Processes"])
for algo in algorithms:
algoToRun = None
if algo == 'MyLamport' :
algoToRun = MainP
elif algo == 'OrigLamport':
algoToRun = OrigP
elif algo == 'SpecLamport':
algoToRun = SpecP
with open('Performance_varyingProcs.csv', mode='a') as perf1_file:
writer = csv.writer(perf1_file)
subHeading = "Algorithm: " + algo + " Reqs: " + str(nreqs) + " Reps: " + str(nreps)
writer.writerow([subHeading])
writer.writerow(['Run Seq:', 'Number of Processes', 'Execution Time (s)'])
procs = dp = int(nprocs/nparams)
reqs = nreqs
runSeq = 1
for procs in range(procs, nprocs+1, dp):
print("*********************************************************************")
print ("Num Runs: ", nreps, " NumProcs: ", procs, " NumRequests: ", reqs)
print("*********************************************************************")
runTime = 0.0
for i in range(1, nreps+1):
ps = new(algoToRun, num=procs)
for p in ps: setup(p, (ps-{p}, reqs))
startTime = timeit.default_timer()
start(ps)
await(each(proc in ps, has=received(('done', proc))))
runTime = runTime + (timeit.default_timer() - startTime)
send(('done',), to= ps)
print (algo, ":: Run Seq:: ", i, " Completed!!")
runTime = runTime/nreps
with open('Performance_varyingProcs.csv', mode='a') as perf1_file:
writer = csv.writer(perf1_file)
writer.writerow([runSeq, procs, runTime])
runSeq = runSeq + 1
print("*******************PERFORMANCE VALIDATION ENDS**********************")
output("----------------------Main Ends-----------------------")
# This is an executable specification of the algorithm described in
# Lamport, L. (1978). "Time, clocks, and the ordering of events in a
# distributed system". Communications of the ACM, 21(7):558-565.
# This code includes setup and termination for serving a given number of
# requests per process.
# All labels are not needed,
# leaving 14 or 15 lines total for the algorithm body and message handlers.