Ejemplo n.º 1
0
def load_message(data):
    try:
        o = json.loads(data)
    except json.decoder.JSONDecodeError as e:
        raise Message.InvalidMessageError(e)

    if 'type_name' not in o:
        raise Message.InvalidMessageError('field, `type_name` is missing: %s',
                                          o)

    if o['type_name'] == 'message':
        return Message.from_json(data)

    if o['type_name'] == 'ballot-message':
        return BallotMessage.from_json(data)
Ejemplo n.º 2
0
 def send_accepted(self, proposal_uid, accepted_value):
     """
     Broadcasts an Accepted message to all Learners
     """
     for i, addr in enumerate(SERVER_ADDRESSES):
         msg = Message(
             Message.MSG_DECIDE, self.owner.uid,
             (self.owner.server.address, self.owner.server.port), (addr, LEARNER_PORT + i*10),
             data=(proposal_uid, accepted_value))
         self.owner.server.send_message(msg)
Ejemplo n.º 3
0
 def send_proposal(self, replica_id, proposal_value):
     """
     Broadcasts an (uid, value) message to all Acceptors
     """
     for i, addr in enumerate(SERVER_ADDRESSES):
         if i != replica_id:
             msg = Message(
                 Message.MSG_ACCEPT, self.owner.uid,
                 (self.owner.server.address, self.owner.server.port), (addr, ACCEPTOR_PORT + i*10),
                 data=(replica_id, proposal_value))
             self.owner.server.send_message(msg)
Ejemplo n.º 4
0
 def send_prepare(self, proposal_id):
     """
     Broadcasts a Prepare message to all Acceptors
     """
     for i, addr in enumerate(SERVER_ADDRESSES):
         msg = Message(Message.MSG_PREPARE,
                       self.owner.uid,
                       (self.owner.server.address, self.owner.server.port),
                       (addr, ACCEPTOR_PORT + i * 10),
                       data=proposal_id)
         self.owner.server.send_message(msg)
Ejemplo n.º 5
0
 def send_promise(self, proposer_uid, proposal_id, previous_id,
                  accepted_value):
     """
     Sends a Promise message to the specified Proposer
     """
     msg = Message(Message.MSG_PROMISE,
                   self.owner.uid,
                   (self.owner.server.address, self.owner.server.port),
                   (SERVER_ADDRESSES[proposer_uid],
                    PROPOSER_PORT + proposer_uid * 10),
                   data=(proposal_id, previous_id, accepted_value))
     self.owner.server.send_message(msg)
Ejemplo n.º 6
0
    def join(self, name, actor_type):
        """Sends the join request to the server.

        :param name: Player name to join with.
        :type name: str

        :param actor_type: Player type
        :type actor_type: :enum:`game.player.PlayerType`
        """
        LOG.info('Trying to join server')

        msg = Message(MT.join, {MF.name: name, MF.entity_type: actor_type})
        self.proxy.enqueue(msg)
Ejemplo n.º 7
0
    def ping(self):
        """Pings the server to start te timing offset calculation.
        """
        LOG.debug('Sending ping')

        # Create and enqueue the ping message
        sync_id = next(self.sync_counter)
        msg = Message(MT.ping, {MF.id: sync_id, MF.timestamp: tstamp()})

        def callback():
            self._syncing[sync_id] = tstamp()

        self.proxy.enqueue(msg, callback)
Ejemplo n.º 8
0
def start_move_action(context, position):
    """Start a move action to the defined position.

    :param context: The game context.
    :type context: :class:`context.Context`

    :param position: The position in world ccoordinates
    :type position: :class:`tuple`
    """
    msg = Message(MessageType.move, {
        MessageField.x_pos: position[0],
        MessageField.y_pos: position[1],
    })

    context.msg_queue.append(msg)
Ejemplo n.º 9
0
    def on_resolution(self, proposal_uid, value, log=None):
        """
        Called when a resolution is reached
        """
        print('###')
        print('Value {v} is accepted by {o}, proposed by {pid}.'.format(v=value, o=self.owner.server.port, pid=proposal_uid))
        print('###')

        time.sleep(2)

        for i, addr in enumerate(SERVER_ADDRESSES):
            msg = Message(
                Message.MSG_STOP, self.owner.uid,
                (self.owner.server.address, self.owner.server.port), (addr, NODE_PORT + i*10), data=(proposal_uid, value, log))
            self.owner.server.send_message(msg)
Ejemplo n.º 10
0
async def check_message_in_storage(node):
    global MESSAGE

    if check_message_in_storage.is_running:
        return

    check_message_in_storage.is_running = True

    found = list()
    log.main.info('%s: checking input message was stored: %s', node.name,
                  MESSAGE)
    while len(found) < len(servers):
        for node_name, server in servers.items():
            if node_name in found:
                continue

            storage = server.consensus.storage

            is_exists = storage.is_exists(MESSAGE)
            if is_exists:
                log.main.critical(
                    '> %s: is_exists=%s state=%s ballot=%s',
                    node_name,
                    is_exists,
                    server.consensus.ballot.state,
                    # json.dumps(storage.ballot_history.get(MESSAGE.message_id), indent=2),
                    '',  # json.dumps(storage.ballot_history.get(MESSAGE.message_id)),
                )
                found.append(node_name)

            await asyncio.sleep(0.01)

    await asyncio.sleep(3)

    check_message_in_storage.is_running = False

    MESSAGE = Message.new(uuid1().hex)
    servers['n0'].transport.send(nodes['n0'].endpoint,
                                 MESSAGE.serialize(client0_node))
    log.main.info('inject message %s -> n0: %s', client0_node.name, MESSAGE)

    return
Ejemplo n.º 11
0
def start_build_action(context, position):
    """Start a build action to the defined position.

    NOTE: the game context has all the information required.

    :param context: The game context.
    :type context: :class:`context.Context`

    :param position: The position in world coordinates
    :type position: :class:`tuple`
    """
    building_type = context.building_type
    msg = Message(
        MessageType.build, {
            MessageField.building_type: building_type,
            MessageField.x_pos: position[0],
            MessageField.y_pos: position[1],
        })

    context.msg_queue.append(msg)
    send_event(GameModeToggle(context.GameMode.building))
Ejemplo n.º 12
0
    def from_json(cls, data):
        try:
            o = json.loads(data)
        except json.decoder.JSONDecodeError as e:
            raise cls.InvalidBallotMessageError(e)

        if 'type_name' not in o or o['type_name'] != 'ballot-message':
            raise cls.InvalidBallotMessageError(
                '`type_name` is not "ballot-message"')

        message = None
        try:
            message = Message.from_dict(o)
        except Message.InvalidMessageError as e:
            raise cls.InvalidBallotMessageError(e)

        return cls(
            Node(o['node'], None, None),
            State.from_name(o['state']),
            message,
            BallotVoteResult.from_name(o['result']),
        )
Ejemplo n.º 13
0
        transports[name] = LocalTransport(name, config.endpoint, loop)
        log.main.debug('transports created: %s', transports)

        consensuses[name] = TestConsensus(nodes[name], quorums[name],
                                          transports[name])
        log.main.debug('consensuses created: %s', consensuses)

        servers[name] = Server(nodes[name],
                               consensuses[name],
                               name,
                               transport=transports[name])
        log.main.debug('servers created: %s', servers)

    for server in servers.values():
        server.start()

    # send message to `server0`
    MESSAGE = Message.new(uuid1().hex)
    servers['n0'].transport.send(nodes['n0'].endpoint,
                                 MESSAGE.serialize(client0_node))
    log.main.info('inject message %s -> n0: %s', client0_node.name, MESSAGE)

    try:
        loop.run_forever()
    except (KeyboardInterrupt, SystemExit):
        log.main.debug('goodbye~')
        sys.exit(1)
    finally:
        loop.close()