-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.da
278 lines (265 loc) · 12.4 KB
/
client.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
#!/usr/bin/python
import sys
import os
import time
import random
import string
from utils import Utils
from datetime import datetime
from operation import Operation
config(channel is {fifo,reliable}, clock is lamport)
class Client(process):
def setup(olympus, clientId, olympusPublicKey, workload_for_client, clientPrivateKey, client_timeout):
self.olympus = olympus
self.clientId = clientId
self.olympusPublicKey = olympusPublicKey
self.replicaPublicKeys = []
self.workload_for_client = workload_for_client
self.clientPrivateKey = clientPrivateKey
self.head = None
self.tail = None
self.client_timeout = client_timeout
self.requestId = -1
self.replicas = None
self.isValidConfigPresent = False
self.completedRequests = {}
self.requestToResult = {}
self.runningstate = {}
self.utils = Utils()
self.someRequestOutputFailed = False
self.periodic_interval = 2
self.errorresponsecode = False
self.distinct_replicas = []
def getResult(operation, key, value):
output = "None"
if operation == "put" :
self.runningstate[key] = value
output = "OK"
elif operation == "get":
if key in self.runningstate:
output = self.runningstate[key]
else:
output = ""
elif operation == "slice":
if key in self.runningstate:
(i,j) = value.split(':')
val = self.runningstate[key]
if int(j)<len(val) and int(i)>=0:
self.runningstate[key] = val[int(i):int(j)]
output = "OK"
else:
output = "Fail"
elif operation == "append":
if key in self.runningstate:
self.runningstate[key]+=str(value)
output = "OK"
else:
output = "Fail"
return output
def retry_for_current_configuration():
send(('Get Current Config', self.clientId), to = olympus)
await(some(received(('Config Response', _,_,_,_,_), from_ = olympus)))
while not self.isValidConfigPresent:
if await(self.isValidConfigPresent):
break
elif timeout(self.periodic_interval):
output("Client " + str(self) + "Periodically checking olympus if there is any new configuration")
send(('Get Current Config', self.clientId), to = olympus)
await(some(received(('Config Response', _,_,_,_,_), from_ = olympus)))
def execute_workload(operation, key, requestIdFinal, workload):
##Operation object created
operation_object = Operation()
operation_object.requestId = requestIdFinal
operation_object.command = operation
tempRequestId = requestIdFinal
output("-------------------------------------------------------------------------------------")
output("Executing New workoad from Client: " + str(self) + " for RequestId: " + requestIdFinal)
signed_workload = utils.getSignedStatement(self.clientPrivateKey, str(workload.replace(' ', '').strip()))
if len(key) == 1:
self.requestToResult[requestIdFinal] = getResult(operation, key[0], None)
operation_object.key = key[0]
operation_object.value = ""
send(('Execute Operation Of Client', operation_object , self, signed_workload), to = head)
if await(tempRequestId in self.completedRequests):
pass
elif timeout(client_timeout):
self.isValidConfigPresent = False
output("Client Timeout occured: " + str(self) + " for requestid: " + requestIdFinal)
self.distinct_replicas = []
retry_for_current_configuration()
send(('Retransmit Request To Replicas', operation_object, self, signed_workload), to = self.replicas)
while True: #await(some(received(('Retransmitted Response',_,_,_,_,_), from_ = p)))
if await(tempRequestId in self.completedRequests):
self.distinct_replicas = []
break
elif timeout(client_timeout):
self.distinct_replicas = []
retry_for_current_configuration()
send(('Retransmit Request To Replicas', operation_object, self, signed_workload), to = self.replicas)
else:
self.requestToResult[requestIdFinal] = getResult(operation, key[0], key[1])
operation_object.key = key[0]
operation_object.value = key[1]
send(('Execute Operation Of Client', operation_object, self, signed_workload), to = head)
if await(tempRequestId in self.completedRequests):
pass
elif timeout(client_timeout):
self.isValidConfigPresent = False
output("Client Timeout occured: " + str(self) + " for requestid: " + requestIdFinal)
self.distinct_replicas = []
retry_for_current_configuration()
send(('Retransmit Request To Replicas', operation_object, self, signed_workload), to = self.replicas)
while True: #await(some(received(('Retransmitted Response',_,_,_,_,_), from_ = p)))
if await(tempRequestId in self.completedRequests):
self.distinct_replicas = []
break
elif timeout(client_timeout):
self.distinct_replicas = []
retry_for_current_configuration()
send(('Retransmit Request To Replicas', operation_object, self, signed_workload), to = self.replicas)
def execute_pseudorandom_workloads(seed, workload_count):
random.seed(seed)
op = ['put', 'get', 'slice', 'append']
opp = ['get', 'slice', 'append']
workloads = []
keys = []
values = []
maxlength = 0
for i in range(workload_count):
temp = ''.join(random.choices(string.ascii_lowercase , k=random.randint(2,7)) + random.choices(string.ascii_uppercase , k=random.randint(3,7)))
values.append(temp)
maxlength = max(maxlength, len(temp))
putKeys = []
put_counts = 0
if workload_count%3==0:
put_counts = int(workload_count/3)
else:
put_counts = int(workload_count/3) + 1
for i in range(int(put_counts)):
key = ''.join(random.choices(string.ascii_uppercase , k=random.randint(3,8)) + random.choices(string.ascii_lowercase , k=random.randint(2,6)))
value = random.SystemRandom().choices(values)[0]
workloads.append("put(\'"+key+"\',\'"+value+"\')")
putKeys.append(key)
other_count = workload_count - put_counts
for i in range(int(other_count)):
operation = random.SystemRandom().choice(opp)
key = random.SystemRandom().choices(putKeys)[0]
value = random.SystemRandom().choices(values)[0]
if operation == "get":
workloads.append("get(\'"+key+"\')")
elif operation == "append":
workloads.append("append(\'"+key+"\',\'"+value+"\')")
elif operation == "slice":
start = random.randint(0,maxlength)
end = random.randint(start, maxlength)
workloads.append("slice(\'"+key+"\',\'"+str(start)+":"+str(end)+"\')")
for workload in workloads:
retry_for_current_configuration()
workload = workload.strip().replace("'","")
self.errorresponsecode = False
requestIdFinal = clientId+":"+str(self.requestId)
operation = workload.split('(')[0]
key_value = workload[workload.find('(')+1:workload.find(')')]
key = key_value.split(',')
execute_workload(operation, key, requestIdFinal, workload)
self.requestId += 1
def run():
output("********Starting Client" + str(self)+ "*****")
start_time = datetime.now()
output("Client " + str(self) + "Started: ", start_time.second)
workloads = workload_for_client.split(';')
output("Client " + str(self) + " workload ->" + str(workloads))
for workload in workloads:
retry_for_current_configuration()
workload = workload.strip().replace("'","")
self.errorresponsecode = False
self.requestId += 1
requestIdFinal = clientId+":"+str(self.requestId)
operation = workload.split('(')[0]
key_value = workload[workload.find('(')+1:workload.find(')')]
if operation == "pseudorandom":
key = key_value.split(',')
execute_pseudorandom_workloads(int(key[0]), int(key[1]))
else:
key = key_value.split(',')
execute_workload(operation, key, requestIdFinal, workload)
output("Checking Expected Dictionary Content at completion of all workloads for " + str(self) + ".........")
checkFlag = True
for key, value in self.requestToResult.items():
if key in self.completedRequests:
if value != self.completedRequests[key][0]:
checkFlag = False
self.someRequestOutputFailed = True
output("Workload with requestId: " + str(key) + " Failed for Client: " + str(self) + "Expected value is: " + str(value) + "Actual value is: " + str(self.completedRequests[key][0]))
else:
checkFlag = False
self.someRequestOutputFailed = True
output("Workload with requestId: " + str(key) + " Failed for Client: " + str(self) + "Expected value is: " + str(value))
if checkFlag == True:
output("Client " + str(self) + " finised executing all workloads successfully.")
else:
output("Client " + str(self) + " finised with some request failed.")
await(some(received(('Done'), from_ = tail)))
def receive(msg = ('Forward Result to Client', result, result_proof, reqId), from_ = tail):
output("Received result [" + result + "] at client " + str(self) + " from tail " + str(tail) + " for requestId = " + reqId)
if check_validity_of_result_proof(result, result_proof) == False:
output("Proof of Misbehaviour detected at client "+ str(self) + " because of invalid result proof of request: " + reqId)
output("Sending Reconfiguration Request to Olympus from Client: " + str(self))
send(('Reconfiguration request from client', result, result, result_proof, self), to = olympus)
else:
if self.requestToResult[reqId] == result:
if reqId not in self.completedRequests:
self.completedRequests[reqId] = (result, tail)
else:
output("Proof of Misbehaviour detected at client "+ str(self) + " because of invalid result of request: " + reqId)
output("Sending Reconfiguration Request to Olympus from Client: " + str(self))
send(('Reconfiguration request from client', self.requestToResult[reqId], result, result_proof, self), to = olympus)
def check_validity_of_result_proof(result, result_proof):
result_statements = result_proof
for i in range(0, len(self.replicas)):
try:
statement = utils.verifySignature(result_statements[i] , replicaPublicKeys[i])
hash = statement.decode('UTF-8').split(';')[-1]
if utils.verifyHash(result, hash.encode('utf-8')) == False:
return False
except:
return False
return True
def receive(msg = ('Config Response', replicas, head, tail, isValidConfigPresent, replicaPublicKeys), from_ = olympus):
output("Received configuration -> [ replicas:"+ str(replicas) + ", head:" + str(head) + ", tail:"+ str(tail) +"] from the olympus at the client " + str(self) + " with flag " + str(isValidConfigPresent))
self.head = head
self.tail = tail
self.replicas = replicas
self.replicaPublicKeys = replicaPublicKeys
self.isValidConfigPresent = isValidConfigPresent
def receive(msg = ('Retransmitted Response', result, operation_object, result_proof, replica, responseCode, signed_workload), from_ = p):
reqId = operation_object.requestId
output("Received retried operation response for RequestId [" + reqId + "] and result [" + str(result) +"] from the replica " + str(p) + " at the client " + str(self))
#if reqId not in self.completedRequests:
if responseCode == "VALID":
if result_proof != None:
if check_validity_of_result_proof(result, result_proof) == False:
output("Proof of Misbehaviour detected at client "+ str(self) + " because of invalid result proof of request: " + reqId)
output("Sending Reconfiguration Request to Olympus from Client: " + str(self))
send(('Reconfiguration request from client', result, result, result_proof, self), to = olympus)
else:
if self.requestToResult[reqId] == result:
if replica not in self.distinct_replicas:
self.distinct_replicas.append(replica)
if len(self.distinct_replicas) > len(self.replicas)/2:
if reqId not in self.completedRequests:
output("Got Response from Quorum of Replicas for Retransmitted Response for RequestId" + str(reqId))
self.completedRequests[reqId] = (result, replica)
else:
output("Proof of Misbehaviour detected at client "+ str(self) + " because of invalid result of request: " + reqId)
output("Sending Reconfiguration Request to Olympus from Client: " + str(self))
send(('Reconfiguration request from client', self.requestToResult[reqId], result, result_proof, self), to = olympus)
elif responseCode == "ERROR":
if self.errorresponsecode == False:
self.errorresponsecode = True
retry_for_current_configuration()
send(('Execute Operation Of Client', operation_object, self, signed_workload), to = head)
def receive(msg = ('Result from olympus', result, reqId), from_ = olympus):
output("Received result [" + result + "] at client " + str(self) + " from olympus " + str(olympus) + " for requestId = " + reqId)
if reqId not in self.completedRequests:
self.completedRequests[reqId] = (result, olympus)