Skip to content

Instantly share code, notes, and snippets.

@0x3bfc
Created October 25, 2017 03:41
Show Gist options
  • Select an option

  • Save 0x3bfc/95d7ffdaf162eff26d8f7ae1ce75d4aa to your computer and use it in GitHub Desktop.

Select an option

Save 0x3bfc/95d7ffdaf162eff26d8f7ae1ce75d4aa to your computer and use it in GitHub Desktop.
"""Simple failure detector"""
import time
import zmq
def pingo(url, hosts, node_id):
ctx = zmq.Context.instance()
server = ctx.socket(zmq.REP)
server.bind(url)
while True:
hosts_status = {}
# initial status
status = {h: (False if h != url else True) for h in hosts }
token = 1
# initial tokens
for host in hosts:
hosts_status[host] = '%s-%i' % (host, token)
token += 1
for host in hosts:
client = ctx.socket(zmq.REQ)
# not my ip
if host != url:
client.connect(host)
# send heartbeat to peer
client.send_string('%s' % hosts_status[host])
# receive acknowledgement
try:
msg = server.recv()
except ConnectionRefusedError:
msg = b''
# print(msg, hosts_status[host])
for k, v in hosts_status.items():
print(msg.decode("utf-8"), v)
if msg.decode("utf-8") == v:
status[host] = True
print('ID: %d --- %s live!' % (node_id, host))
time.sleep(0.1)
client.close()
for h in hosts:
if h != url:
if not status[h]:
pass
# print('ID: %d --- %s down!' % (node_id, h))
server.close()
nodes = ['tcp://127.0.0.1:5550',
'tcp://127.0.0.1:5551',
'tcp://127.0.0.1:5552',
'tcp://127.0.0.1:5553'
]
pingo('tcp://127.0.0.1:5550', nodes, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment