-
Notifications
You must be signed in to change notification settings - Fork 0
/
leader_election.py
305 lines (253 loc) · 11.5 KB
/
leader_election.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
import pickle
import socket
import sys
import logging
import threading
import time
import random
import Queue
class LeaderElection():
def __init__(self,mlist,elect_queue):
#super(master_node, self).__init__()
# Election messages are sent over below port
self.ehost = ''
self.eport = 10040
#Reference membership list
self.mlist = mlist
self.current_node = socket.gethostbyname(socket.gethostname())
#Elect Queue to send election result to other threads
self.elect_queue = elect_queue
#Use election_id to eliminate recurring election runs
self.election_id = None
#Node_id is last octect of IPv4 address
ip_split = self.current_node.split(".")
self.current_id = int(ip_split[len(ip_split)-1])
# To check if election is in progress
self.election_in_progress = False
#To check for election ack
self.election_ack = False
#To check for co-ordination message
self.rcvd_coordination = False
#Track current leader
self.leader = None
self.election_hdle = None
# Function to create and bind socket
def create_socket_bind(self):
peer_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
peer_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
peer_socket.bind((self.ehost, self.eport))
except (socket.error,socket.gaierror) as err_msg:
logging.exception(err_msg)
peer_socket.close()
sys.exit()
return peer_socket
# Function to accept connection, process the command from Datanode/client
def recv_cmd(self,peer_socket,lock):
logging.info("Election thread Waiting to receive")
while True:
peer_socket.listen(20);
(conn_socket,(client_ip,client_port)) = peer_socket.accept()
msg = (conn_socket.recv(8192))
rcv_msg = pickle.loads(msg)
#Handle initial leader election
#Initiate new leader when master node fail is detected
if(rcv_msg['cmd'] == 'initiate'):
logging.info("Received Fail detect/initiate message")
if(self.election_id != rcv_msg['id']):
self.current_state = 'election'
self.election_id = rcv_msg['id']
if (self.election_in_progress == False):
self.election_in_progress = True
self.election_ack = False
self.rcvd_coordination = False
self.election_hdle = threading.Thread(target=self.election_msg_hdler(lock,))
self.election_hdle.daemon = True
self.election_hdle.start()
conn_socket.sendall("Initiated")
#Receive and handle election message
elif (rcv_msg['cmd'] == 'election'):
logging.info("Received Election message ")
ip_split = client_ip.split(".")
client_id = int(ip_split[len(ip_split)-1])
#Send Ack to received election message
send_pkt = pickle.dumps({
'cmd':'election_ack'
})
self.send_query_master(send_pkt,(client_ip,int(self.eport)))
logging.info("Sent Ack to election initiator")
# print "Sent Ack to election initiator " + str(client_ip)
#Start a new election run if new election has not begun yet
if (self.election_id != rcv_msg['id']):
self.election_id = rcv_msg['id']
if (self.election_in_progress == False):
self.election_in_progress = True
self.election_ack = False
self.rcvd_coordination = False
self.election_hdle = threading.Thread(target=self.election_msg_hdler(lock,))
self.election_hdle.daemon = True
self.election_hdle.start()
else:
logging.info("Duplicate Election Message, No new election run taken")
#Receive and handle election_ack message
elif (rcv_msg['cmd'] == 'election_ack'):
logging.info("Received Election Ack message ")
self.election_ack = True
# print "Receive Ack from " + str(client_ip)
#Receive and handle coordinate message
elif (rcv_msg['cmd'] == 'coordinate'):
logging.info("Received cordinate message ")
# print "Received cordinate message from" + str(client_ip)
if (self.rcvd_coordination == False):
#New leader is communicated
self.elect_queue.put(client_ip)
self.leader = client_ip
self.rcvd_coordination = True
self.election_ack = True
self.election_in_progress = False
if self.election_hdle is not None:
self.election_hdle.join()
self.election_hdle = None
conn_socket.close()
peer_socket.close()
def election_msg_hdler(self,lock):
#ID is defined as last octet of IPv4 address
ip_split = self.current_node.split(".")
current_id = int(ip_split[len(ip_split)-1]);
lst = self.mlist.lst
#List of higher ID VM's
vm_list = []
#Find VM's with higher ID
for i in range(len(lst)):
host = lst[i]['host']
ip_split = host.split(".")
host_id = int(ip_split[len(ip_split)-1]);
if (host_id > current_id):
vm_list.append(host)
#Send Election message to higher ID VM's
send_pkt = pickle.dumps({
'cmd':'election',
'id' : self.election_id
})
if len(vm_list) > 0:
for each_vm in vm_list:
# print "X.Send Election Message to" + str(each_vm)
node_id = (each_vm, int(self.eport))
self.send_query(send_pkt,node_id)
#Wait for election acknowledge
self.election_ack_wait(lock)
#No higher ID node's exist, current node is leader
#Send co-ordination message to all nodes
else:
send_pkt = pickle.dumps({
'cmd':'coordinate',
'id' : self.election_id
})
for i in range(len(lst)):
host = lst[i]['host']
# print "1.Send Coordination Message"
node_id = (host, int(self.eport))
self.send_query(send_pkt,node_id)
#Wait for AcK message from any one higher order node
def election_ack_wait(self,lock):
size_mlist = len(self.mlist.lst)
# Set wait timeout to be function of node_id, lower node_id's wait longer than higher node_ids
# Fix for thread not yielding
mult = 16 - int(self.current_id)
if mult > 0:
t1 = mult
else:
t1 = 5
if size_mlist > 0:
wait_timeout = (2.8/(2*size_mlist - 1)) * t1
else:
wait_timeout = (0.120) * t1
# Sleep, wait for ack
# print "Wait for ack timeout"
time.sleep(wait_timeout)
lock.acquire()
ack_rcvd = self.election_ack
crd_rcvd = self.rcvd_coordination
lock.release()
#If received ACK, wait for co-ordination
if (ack_rcvd == True and crd_rcvd == False):
#wait to receive leader info
self.coordination_wait(wait_timeout,lock)
#Current Node is leader, no ACK received after timeout
elif (ack_rcvd == False and crd_rcvd == False):
send_pkt = pickle.dumps({
'cmd':'coordinate',
'id' : self.election_id
})
lst = self.mlist.lst
#Send coordinate messages to all nodes
for i in range(len(lst)):
host = lst[i]['host']
# print "2.Send Coordination Message"
node_id = (host, int(self.eport))
self.send_query(send_pkt,node_id)
else:
#end of thread
pass
#wait to receive leader info
def coordination_wait(self, wait_timeout,lock):
#Co-ordination timeout to be 3 times the wait_ack timeout
final_timeout = wait_timeout * 3.0
#Sleep for timeout
#print "Wait for co-ordination timeout"
time.sleep(final_timeout)
# If no coordinator message has arrived,
# initiate another election
# Send election message to itself
lock.acquire()
crd_rcvd = self.rcvd_coordination
lock.release()
if(crd_rcvd == False):
send_pkt = pickle.dumps({
'cmd':'election',
'id' :self.current_node
})
node_id = ('', int(self.eport))
# print "Re-election"
lock.acquire()
self.election_in_progress = False
lock.release()
self.send_query(send_pkt,node_id)
# Function establishes socket
# Sends commands to other nodes in election process
def send_query(self,query, master):
command = query
ret = ''
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(master)
send_msg = (command)
sock.sendall(send_msg)
sock.close()
except (socket.error,socket.gaierror) as err_msg:
logging.info(str(err_msg))
# print err_msg
return ret
# Function establishes socket
# Sends commands to other nodes in election process
def send_query_master(self,query, master):
command = query
ret = ''
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(master)
send_msg = (command)
sock.sendall(send_msg)
sock.close()
except (socket.error,socket.gaierror) as err_msg:
logging.info(str(err_msg))
# print err_msg
return ret
def run(self):
logging.basicConfig(filename = "leader.log", level = logging.INFO, filemode = "w")
lock = threading.Lock()
peer_socket= self.create_socket_bind()
# Start election messaging thread
election_thread = threading.Thread(target=self.recv_cmd,args=(peer_socket,lock,))
election_thread.daemon = True
election_thread.start()