-
Notifications
You must be signed in to change notification settings - Fork 0
/
CmdInterpreter.py
executable file
·312 lines (289 loc) · 8.81 KB
/
CmdInterpreter.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
#!/usr/bin/env python
import cmd
import socket
import thread
import threading
import time
log = []
IP = ["0.0.0.0", "54.67.122.117", "54.94.225.51", "54.169.32.184", "54.86.55.27"]
PORT = [12000, 12345, 12335, 12334, 12333]
pid = 1
#comm vars
mutex = threading.Lock()
OUT_SOCK = [None] * len(IP)
IN_SOCK = [None] * len(IP)
CONN = [None] * len(IP)
POLL_RATE = 0.1
#Cross instance vars
BUFFER_SIZE = 2048
majority = 3
live = 0
liveness = [False] * len(IP)
halt = False
Sync = False
#PAXOS instance vars
BallotNum = (0, pid)
AcceptNum = (0, 0)
AcceptVal = 0
AckNum = 0
AccNum = 0
AckHighVal = 0
AckHighBal = (0, 0)
InitVal = 0
AccSent = False
DecSent = False
def queryServer(index):
retry = 0
global Sync, live, mutex
while True:
try:
#print ("Querying server %s" % IP[index])
OUT_SOCK[index].connect((IP[index], PORT[index]))
#print ("Connect established with server %s" % IP[index])
liveness[index] = True
mutex.acquire()
live += 1
print "# of live server: %d" % live
if (Sync is False) and (index != 0):
Sync = True
mutex.release()
#print "SYNC: %s" % IP[index]
send2Server("syncreq", index)
else:
mutex.release()
break;
except:
#retry += 1
#print ("QueryServer Exception, retry %d" % retry)
time.sleep(1)
def waitForClient(index):
global mutex, halt, live, liveness, BallotNum, AcceptNum, AcceptVal, AckNum, AccNum, AccSent, DecSent, AckHighBal, AckHighVal, AccepctVal, InitVal
IN_SOCK[index].setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#print "binding socket %d to server %d" % (index, index)
IN_SOCK[index].bind(('0.0.0.0', PORT[index]))
# daemon loop
while True:
if halt:
IN_SOCK[index].close()
if liveness[index]:
liveness[index] = False
live = live - 1
break
#print ("Waiting for client %d" % index)
IN_SOCK[index].listen(0)
CONN[index], addr = IN_SOCK[index].accept()
liveness[index] = True
CONN[index].setblocking(0)
print addr
# listen loop
while True:
# unblocking loop
while True:
if halt:
break
try:
raw_data = CONN[index].recv(BUFFER_SIZE)
break
except:
time.sleep(float(1/POLL_RATE))
# end of unblockign loop
if halt:
print "CLOSE %d" % index
CONN[index].close()
if liveness[index]:
OUT_SOCK[index].close()
break
# if client dies
if not raw_data:
CONN[index].close()
OUT_SOCK[index] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Server %s is dead!" % IP[index]
liveness[index] = False
live = live - 1
print "# of live server: %d" % live
if live < majority:
print "Warning: not enough live servers!"
thread.start_new_thread(queryServer, (index, ))
break
for data in raw_data.split('|'):
if data == str(''):
continue
mutex.acquire()
print "recieved data %s from server %s: " % (data.split('#'), index)
# if client asks for sync
if data.split('#')[0] == 'syncreq':
msg = 'syncack'
for item in log:
if len(msg) + len(str(item)) + 1 > BUFFER_SIZE:
send2Server(msg, index)
msg = 'syncack'
msg += '#'
msg += str(item)
send2Server(msg, index)
mutex.release()
# if client answers for sync
elif data.split('#')[0] == 'syncack':
for item in data.split('#'):
if item == 'syncack':
continue
log.append(float(item))
mutex.release()
# PAXOS msg
# if the msg is withdraw and is stale
elif not data.split('#')[len(data.split('#'))-1] == str(len(log)):
print "Sequence num %d not match %d! Aborting msg!" % (int(data.rsplit('#')[len(data.split('#'))-1]), len(log))
mutex.release()
else:
seqNum = data.split('#')[len(data.split('#'))-1]
if data.split('#')[0] == 'prepare':
bal = data.split('#')[1]
rid = data.split('#')[2]
# if Ballot < bal, set ballot, join
print "bal: %s, rid: %s" % (bal, rid)
if (AcceptNum <= (bal, rid)):
AcceptNum = (bal, rid)
msg = "ack#" + bal + '#' + rid + '#' + str(AcceptNum[0]) + '#' + str(AcceptNum[1]) + '#' + str(AcceptVal) + '#' + str(seqNum)
print "ACK: %s to server %d" % (msg, index)
send2Server(msg, index)
elif data.split('#')[0] == "ack":
if not AccSent:
AckNum += 1
bal = data.split('#')[3]
rid = data.split('#')[4]
if (AckHighBal <= (bal, rid)):
AckHighBal = (bal, rid)
AckHighVal = data.split('#')[5]
if (AckNum >= majority):
AcceptVal = AckHighVal
if (str(AcceptVal) == str(0)):
AcceptVal = InitVal
msg = "accept#" + str(BallotNum[0]) + '#' + str(BallotNum[1]) + '#' + str(AcceptVal) + '#' + str(seqNum)
print "ACC: %s to all" % msg
send2All(msg)
AccSent = True
elif data.split('#')[0] == "accept":
if not DecSent:
AccNum += 1
bal = data.split('#')[1]
rid = data.split('#')[2]
if (AcceptNum <= (bal, rid)):
AcceptNum = (bal, rid)
AcceptVal = data.split('#')[3]
if not AccSent:
AccSent = True
send2All(data)
#if get accept from majority
if (AccNum >= majority):
msg = "decide#" + AcceptVal + '#' + str(seqNum)
print "DEC: %s to all" % msg
send2All(msg)
DecSent = True
elif data.split('#')[0] == "decide":
if InitVal != 0:
if float(InitVal) == float(data.split('#')[1]):
print "SUCCESS"
else:
print "FAILURE"
log.append(float(data.split('#')[1]))
reset_local_state()
else:
print "Unknown Msg!"
print data
mutex.release()
def init_conn():
print ("Initializing connection...")
index = 0
while index < len(IP):
OUT_SOCK[index] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
IN_SOCK[index] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
index += 1
for i in range(0, len(IP)):
thread.start_new_thread(waitForClient, (i, ))
for i in range(0, len(IP)):
thread.start_new_thread(queryServer, (i, ))
while (live < majority):
time.sleep(1)
def send2Server(msg, index):
while liveness[index]:
try:
OUT_SOCK[index].send(msg + '|')
break
except:
continue
def send2All(msg):
for i in range(0, len(IP)):
if liveness[i]:
#print "sending msg to server %d" % i
send2Server(msg, i)
def reset_local_state():
global AcceptNum, AcceptVal, AckNum, AccNum, AckHighVal, AckHighBal, InitVal, AccSent, DecSent
print "reseting local state"
AcceptNum = (0, 0)
AcceptVal = 0
AckNum = 0
AccNum = 0
AckHighVal = 0
AckHighBal = (0, 0)
InitVal = 0
AccSent = False
DecSent = False
def init_paxos(val):
global BallotNum, InitVal
BallotNum = (BallotNum[0] + 1, BallotNum[1])
InitVal = val
# attach with seq num
msg = "prepare#" + str(BallotNum[0]) + '#' + str(BallotNum[1]) + '#' + str(len(log))
print msg
send2All(msg)
def get_balance():
global log
curBallance = 0
for item in log:
curBallance += float(item)
print curBallance
class CmdInterpreter(cmd.Cmd):
def do_deposit(self, arg):
global halt
if not halt:
init_paxos(float(arg))
def do_withdraw(self, arg):
global halt
if not halt:
init_paxos(-1.0*float(arg))
def do_balance(self, arg):
global halt
if not halt:
get_balance()
def do_print(self, arg):
for item in log:
if float(item) >= 0:
print "Deposit ", item
else:
print "Withdraw", str(-1.0*float(item))
def do_fail(self, arg):
global halt
if not halt:
halt = True
del log[:]
print ("Oops! This server is not working!")
def do_unfail(self, arg):
global halt, Sync
if halt:
for i in liveness:
i = False
live = 0
Sync = False
reset_local_state()
halt = False
init_conn()
print ("Wala! This server recovered!")
def do_EOF(self, arg):
return (True)
def postloop(self):
print ("Goodbye!")
if __name__ == '__main__':
#thread.start_new_thread(init_paxos, (20, ))
init_conn()
#send2Server("prepare#0#100", 0)
CmdInterp = CmdInterpreter()
CmdInterp.cmdloop("Please enter cmd: \n\tdeposit [number] \n\twithdraw [number] \n\tbalance \n\tfail \n\tunfail \n\tprint \npress CTRL+D to quit.")