def listen(self): while True: log('listening to receive message') response, address = self.socket.receive() if (response is None and address is None): continue message = Message.parse(response) if (message.type == MessageType.JOIN_SWARM): self.saveNewMemberToSwarm(address) if (self.sharedData['leader']['isSelf']): self.announceLeadership(address) continue if (message.type == MessageType.LEADER): self.sharedData['leader']['isSelf'] = False self.sharedData['leader']['address'] = address log('Leader is ', address) continue if (message.type == MessageType.ALIVE): self.socket.send(MessageType.ALIVE_OK, address) continue if (message.type == MessageType.ALIVE_OK): self.sharedData['leader']['isAlive'] = True continue if (message.type == MessageType.ELECTION): self.handleElectionMessage(message, address) continue if (message.type == MessageType.OK): log('Received OK for election id ', message.params[1]) self.sharedData['elections'][ message.params[1]]['isLeader'] = False continue raise NotImplementedError(message.type)
def receive(self): response, address = self.socket.recvfrom(BUFFERSIZE) message = Message.parse(response) if (self.sharedData['failProcess']): if (message.type != MessageType.LEADER): log('%s message received ignored' % message.type.name) return (None, None) self.storeStatistics(message.type, 'received') log('%s message received' % message.type.name) return (response, address)
def sendMessage(self, message, address): messageParsed = Message.parse(message) name = messageParsed.type.name if (self.sharedData['failProcess']): log("%s message sent blocked" % name) return log("%s message sent" % name) self.storeStatistics(messageParsed.type, 'sent') return self.socket.sendto(message, address)
def initListening(self): print('tracker will start listening...', flush=True) while True: response, address = self.socket.recvfrom(1024) message = Message.parse(response) if (message.type == MessageType.GET_MEMBERS): self.joinSwarm(address) continue if (message.type == MessageType.KILL): print('finishing', flush=True) os._exit(0) raise NotImplementedError(message.type)
def getSwarmMembers(self): self.socket.send(MessageType.GET_MEMBERS, self.trackerAddress) response, address = self.socket.receive() message = Message.parse(response) self.sharedData['swarmMembers'] = json.loads(message.params[0])