Skip to content

Instantly share code, notes, and snippets.

@danquixote
Last active November 22, 2017 04:55
Show Gist options
  • Save danquixote/e4f6d586ebdd1eab351964e8acc27c1c to your computer and use it in GitHub Desktop.
Save danquixote/e4f6d586ebdd1eab351964e8acc27c1c to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import logging
import random
import requests
import sys
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
SERVERS = [
'127.0.0.1:8081',
'127.0.0.2:8082',
'127.0.0.3:8083',
]
class myHandler(BaseHTTPRequestHandler):
def do_GET(self):
logging.warning(self.server.server_address)
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
if self.path == '/':
choices = make_a_choice(self)
if self.path == '/node':
choices = random.choice(['yes', 'no'])
self.wfile.write(choices)
return
def make_a_choice(host_self):
choices = {'yes': 0, 'no': 0}
choices[random.choice(['yes', 'no'])] += 1
for each_server in SERVERS:
if each_server != ':'.join(str(ea_item) for ea_item
in host_self.server.server_address):
logging.warning('requesting {}'.format(each_server))
choices1 = requests.get('http://{}/node'.format(each_server))
choices[choices1.text] += 1
else:
logging.warning('samve server!')
logging.warning(host_self.server.server_address)
return 'yes' if choices['yes'] > choices['no'] else 'no'
def setup_server(host, port):
server = HTTPServer(('{}'.format(host), int(port)), myHandler)
logging.warning('Started httpserver on \
server {} and port {}'.format(host, port))
server.serve_forever()
if __name__ == '__main__':
for each_node in SERVERS:
each_node = each_node.split(':')
setup_server(each_node[0], each_node[1])
@danquixote
Copy link
Author

Your task is to build a simple distributed decision system. Think of it as an over complicated magic eight ball that only answers “yes” or “no”. The result is random and each node must be involved in the decision. The system has the following additional requirements:

● There must be three nodes in the system.
● Each node must be involved in the vote.
● Clients communicate with the system via an HTTP GET and expects a response body containing yes or no.
● Any node in the system must be able to handle a client request.
● The system must run on either three separate computers or a single computer for testing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment