Last active
June 17, 2020 22:25
-
-
Save vishwanath79/2aae082b938c6c5d208ad5977f8b3a59 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# bully algorithm sample /no sockets | |
import random | |
def resurrect(x): | |
if running[x] == 1: | |
print("Leader is running") | |
return | |
print("node ", x, " back to life") | |
running[x] = 1 | |
if x: | |
print("node ", x, " is the leader") | |
else: | |
election(set_reporter(x)) | |
def kill(x): | |
running[x] = 0 | |
if x == leader: | |
print("Killing leader ", x) | |
election(set_reporter(x)) | |
else: | |
print('Not a leader') | |
def election(x): | |
greater_process = [] | |
for i in range(n): | |
if node_id[i] > x: | |
print("node ", x, "sends to", node_id[i]) | |
# print("node ", node_id[i]) | |
if running[i] == 1: | |
print("ok message from ", node_id[i]) | |
greater_process += [node_id[i]] | |
print('greater node ', greater_process, len(greater_process)) | |
if len(greater_process) == 0: | |
return True | |
else: | |
for i in range(len(greater_process)): | |
flag = election(greater_process[i]) | |
if flag is True: | |
break | |
return True | |
def set_reporter(reporter): | |
while reporter == leader: | |
reporter = random.randint(0, n - 1) # randomly pick a node to identify failure | |
print("node ", reporter, "identifies the failure") | |
return reporter | |
if __name__ == "__main__": | |
n = 6 # number of nodes to simulate | |
node_id = [1, 1, 1, 1, 1, 1] # list to limit number of nodes/ if not, appends would keep adding to the list | |
# print(f'Processs ID = {node_id}') | |
for i in range(n): | |
node_id[i] = i | |
# print(node_id) | |
running = [int(1)] * n | |
leader = max(node_id) | |
print(f'Current Leader is {leader}') | |
# resurrect(3) | |
kill(leader) | |
resurrect(leader) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment