Skip to content

Commit

Permalink
added terminal colors
Browse files Browse the repository at this point in the history
  • Loading branch information
rohinrohin committed Dec 2, 2017
1 parent a2b8e8b commit 352c2c2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 53 deletions.
43 changes: 1 addition & 42 deletions project/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,27 +27,18 @@ def _check_size_limit(self):


class codes(Enum):
<<<<<<< 17dcf3916e4c634834cb7464dc4429e3d62a14ef
SUCCESS = 1
FAIL = 2
ERR_KEY_ALREADY_EXISTS = 3
ERR_KEY_NOT_RESPONSIBLE = 4
ERR_KEY_NOT_FOUND = 5
ERR_SERVER_NOT_INIT = 6
=======
SUCCESS = 1
FAIL = 2
ERR_KEY_ALREADY_EXISTS = 3
ERR_KEY_NOT_RESPONSIBLE = 4
ERR_KEY_NOT_FOUND = 5
>>>>>>> added terminal colors
ERR_SERVER_NOT_INIT = 6

def connect_to_server(request, port_num, isMaster):
address_append = "/keystore" if not isMaster else "/master"
address="ws://127.0.0.1:"+port_num+address_append
print("Address: " + address)
ws=create_connection(address)
<<<<<<< 17dcf3916e4c634834cb7464dc4429e3d62a14ef
if request['type'] == "get":
if isMaster:
listCacheKeys=list(client_cache.keys())
Expand All @@ -59,31 +50,6 @@ def connect_to_server(request, port_num, isMaster):
elif request['type'] == "put":
if request['value'][0] == '{':
request['value'] = literal_eval(request['value'])
=======
request = input().split()
#if len(request) > 3:
# hack to allow spaces in json value input
# request = [request[0],request[1],''.join(request[2:])]
print(request[0])
print(request[1])
#print(request[2])
method, params = request[0].lower(), ""
if method == "get":
listCacheKeys=list(client_cache.keys())
for i in listCacheKeys:
if i==(request[1]):
print("recieved locally without master")
#value=client_cache[]
print("cache returned:", client_cache[i])
return connect_to_server(str(client_cache[i]), isMaster=False)
params = {
"key": request[1]
}
elif method == "put":
value = ''.join(request[2:])
if value[0] == '{':
value = literal_eval(value)
>>>>>>> added terminal colors
else:
request['value'] = request['value'].strip()
#elif method == "getmultiple":
Expand All @@ -103,15 +69,8 @@ def connect_to_server(request, port_num, isMaster):
result = ws.recv()
result = json.loads(result)
print ("Server returned ",result["status"])
<<<<<<< 17dcf3916e4c634834cb7464dc4429e3d62a14ef
if(result['status'] == codes.SUCCESS.name):
client_cache[request['key']] = port_num
=======
#print(client_cache[request[1]])

if(result['status']==codes.SUCCESS.name):
client_cache[request[1]]=port_num
>>>>>>> added terminal colors
print(client_cache) #if the master contains the key. 9001 is the current static master address

if(result['status'] == codes.ERR_KEY_NOT_RESPONSIBLE.name):
Expand Down
31 changes: 20 additions & 11 deletions project/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ class KeyStoreService(BaseService):
def onMessage(self, payload, isBinary):
if not isBinary:
payload = json.loads(payload.decode('utf-8'))
printout("[SLAVE SERVER]", YELLOW)
printout("[SLAVE]", YELLOW)
print("RECIEVED: " + str(payload))
payloadType = payload['type'].upper()
payloadParams = payload['params']
Expand All @@ -109,12 +109,15 @@ def onMessage(self, payload, isBinary):
}

if payloadType == 'SETKEY':
printout("[SLAVE]", YELLOW)
print("KEYSET RECIEVED FROM MASTER")
self.keyRange["range"] = payloadParams['data']
self.keyRange["status"] = "true"
printout("[SLAVE]", YELLOW)
print("KEYRANGE: ", self.keyRange)
msg = json.dumps(res)
print("SERVER SENT: " + msg)
printout("[SLAVE]", YELLOW)
print("SENT KEYSET ACK. ")
self.proto.sendMessage(msg.encode('utf8'))
return

Expand Down Expand Up @@ -406,16 +409,19 @@ def onClose(self, wasClean, code, reason):
logging.basicConfig()

currInstance = zk.create('/app/instance', ephemeral=True, sequence=True, makepath=True)
printout("[INIT]", WHITE)
print(currInstance, " started. ")

children = zk.get_children('/app')
printout("[INIT]", WHITE)
print(children)

portno = 0

if len(children) == 1:
portno = 8080
print("MASTER")
printout("[MASTER]", RED)
print("MASTER INIT")
if zk.exists('/meta'):
zk.delete('/meta', recursive=True)

Expand All @@ -434,7 +440,7 @@ def onClose(self, wasClean, code, reason):
"numOfServers": len(children)
}
zk.create('/meta/config', json.dumps(config).encode('utf-8'))
print('Server init')
printout("[MASTER]", RED)
print(children)
totalKeyRange = 122 - 48 + 1
individualRange = int(math.floor(totalKeyRange / len(children)))
Expand All @@ -444,7 +450,8 @@ def onClose(self, wasClean, code, reason):
ranges.append(str(start) + "-" + str(start+individualRange))
start = start + individualRange + 1
ranges[-1] = ranges[-1].split("-")[0] + "-122" # change this later please
print(ranges)
printout("[MASTER]", RED)
print("RANGES: ", ranges)
MasterService.keyRange["range"] = ranges[0]
MasterService.keyRange["status"] == "True"

Expand All @@ -459,20 +466,22 @@ def onClose(self, wasClean, code, reason):
}

ws = create_connection("ws://127.0.0.1:" + str(port) + "/keystore")
print(json.dumps(signal))
printout("[MASTER]", RED)
print("SENDING SIGNAL TO (" + str(port) + "): ", json.dumps(signal))
ws.send(json.dumps(signal))
print ("Sent")
print ("Receiving...")
result = ws.recv()
print ("Received '%s'" % result)
printout("[MASTER]", RED)
print ("RECIEVED ACK. ")
ws.close()

else:
print("SLAVE")
printout("[SLAVE]", YELLOW)
print("SLAVE INIT")
portno, _ = zk.get('/meta/lastport')
portno = int(portno.decode('utf-8')) + 1
zk.set('/meta/lastport', str(portno).encode())
print("LISTENING FOR MASTER KEYSET")
printout("[SLAVE]", YELLOW)
print("LISTENING FOR KEYSET")

factory = WebSocketServerFactory(u"ws://127.0.0.1:%s" % str(portno))
factory.protocol = ServiceServerProtocol
Expand Down

0 comments on commit 352c2c2

Please sign in to comment.