Пример #1
0
    def Subscribe(self, request, context):
        """RadioStation 이 broadcast 하는 채널에 Peer 를 등록한다.

        :param request: SubscribeRequest
        :param context:
        :return: CommonReply
        """
        channel = conf.LOOPCHAIN_DEFAULT_CHANNEL if request.channel == '' else request.channel
        logging.debug("Radio Station Subscription peer_id: " + str(request))
        ObjectManager().rs_service.channel_manager.add_audience(channel, request.peer_target)

        peer: PeerInfo = ObjectManager().rs_service.channel_manager.get_peer_manager(channel).update_peer_status(
            peer_id=request.peer_id, peer_status=PeerStatus.connected)

        try:
            peer_dumped = peer.dump()
            request.peer_order = peer.order
            request.peer_object = peer_dumped
            ObjectManager().rs_service.channel_manager.get_peer_manager(channel).announce_new_peer(request)

            return loopchain_pb2.CommonReply(
                response_code=message_code.get_response_code(message_code.Response.success),
                message=message_code.get_response_msg(message_code.Response.success))

        except Exception as e:
            logging.warning("Fail Peer Dump: " + str(e))
            return loopchain_pb2.CommonReply(response_code=message_code.get_response_code(message_code.Response.fail),
                                             message=message_code.get_response_msg(message_code.Response.fail))
Пример #2
0
    def UnSubscribe(self, request, context):
        """BlockGenerator 의 broadcast 채널에서 Peer 를 제외한다.

        :param request:
        :param context:
        :return:
        """
        channel_name = conf.LOOPCHAIN_DEFAULT_CHANNEL if request.channel == '' else request.channel

        channel_stub = StubCollection().channel_stubs[channel_name]
        peer_list = [target['peer_target'] for target in self.peer_service.channel_infos[channel_name]["peers"]]

        if (request.peer_target in peer_list and conf.ENABLE_CHANNEL_AUTH) or \
                (request.node_type == loopchain_pb2.CommunityNode and not conf.ENABLE_CHANNEL_AUTH):
            asyncio.run_coroutine_threadsafe(
                channel_stub.async_task().remove_audience(peer_target=request.peer_target),
                self.peer_service.inner_service.loop
            )
            util.logger.spam(f"peer_outer_service::Unsubscribe remove_audience target({request.peer_target}) "
                             f"in channel({request.channel})")
        else:
            logging.error(f"This target({request.peer_target}), {request.node_type} failed to unsubscribe.")
            return loopchain_pb2.CommonReply(response_code=message_code.get_response_code(message_code.Response.fail),
                                             message=message_code.get_response_msg("Unknown type peer"))

        return loopchain_pb2.CommonReply(response_code=message_code.get_response_code(message_code.Response.success),
                                         message=message_code.get_response_msg(message_code.Response.success))
Пример #3
0
    def Subscribe(self, request, context):
        """BlockGenerator 가 broadcast(unconfirmed or confirmed block) 하는 채널에
        Peer 를 등록한다.

        :param request:
        :param context:
        :return:
        """
        channel_name = conf.LOOPCHAIN_DEFAULT_CHANNEL if request.channel == '' else request.channel
        if not request.peer_id or not request.peer_target:
            return loopchain_pb2.CommonReply(
                response_code=message_code.get_response_code(message_code.Response.fail_wrong_subscribe_info),
                message=message_code.get_response_msg(message_code.Response.fail_wrong_subscribe_info)
            )

        channel_stub = StubCollection().channel_stubs[channel_name]
        peer_list = [target['peer_target'] for target in self.peer_service.channel_infos[channel_name]["peers"]]

        if (request.peer_target in peer_list and conf.ENABLE_CHANNEL_AUTH) or \
                (request.node_type == loopchain_pb2.CommunityNode and not conf.ENABLE_CHANNEL_AUTH):
            channel_stub.sync_task().add_audience(peer_target=request.peer_target)
            util.logger.spam(f"peer_outer_service::Subscribe add_audience "
                             f"target({request.peer_target}) in channel({request.channel})")
        else:
            logging.error(f"This target({request.peer_target}, {request.node_type}) failed to subscribe.")
            return loopchain_pb2.CommonReply(response_code=message_code.get_response_code(message_code.Response.fail),
                                             message=message_code.get_response_msg("Unknown type peer"))

        return loopchain_pb2.CommonReply(response_code=message_code.get_response_code(message_code.Response.success),
                                         message=message_code.get_response_msg(message_code.Response.success))
Пример #4
0
    def response_simple_success(self):
        result = json.loads('{}')
        result['response_code'] = message_code.Response.success
        result['message'] = message_code.get_response_msg(
            message_code.Response.success)

        return result
Пример #5
0
    def VoteUnconfirmedBlock(self, request, context):
        channel_name = conf.LOOPCHAIN_DEFAULT_CHANNEL if request.channel == '' else request.channel
        block_manager = self.peer_service.channel_manager.get_block_manager(
            channel_name)
        util.logger.spam(
            f"peer_outer_service:VoteUnconfirmedBlock ({channel_name})")

        if conf.CONSENSUS_ALGORITHM != conf.ConsensusAlgorithm.lft:
            if block_manager.peer_type == loopchain_pb2.PEER:
                # util.logger.warning(f"peer_outer_service:VoteUnconfirmedBlock ({channel_name}) Not Leader Peer!")
                return loopchain_pb2.CommonReply(
                    response_code=message_code.Response.fail_no_leader_peer,
                    message=message_code.get_response_msg(
                        message_code.Response.fail_no_leader_peer))

        logging.info("Peer vote to : " + request.block_hash + " " +
                     str(request.vote_code) + f"from {request.peer_id}")

        block_manager.get_candidate_blocks().vote_to_block(
            request.block_hash,
            (False, True)[request.vote_code ==
                          message_code.Response.success_validate_block],
            request.peer_id, request.group_id)

        return loopchain_pb2.CommonReply(
            response_code=message_code.Response.success, message="success")
Пример #6
0
    def __handler_status(self, status_param):
        logging.debug(f"Broadcast Status, param({status_param}) audience({len(self.__audience)})")

        status = dict()
        status['result'] = message_code.get_response_msg(message_code.Response.success)
        status['Audience'] = str(len(self.__audience))
        return json.dumps(status)
Пример #7
0
 def response_simple_success(self):
     result = {
         'response_code': message_code.Response.success,
         'message':
         message_code.get_response_msg(message_code.Response.success)
     }
     return result
Пример #8
0
    async def icx_getTransactionByAddress(**kwargs):
        channel_name = conf.LOOPCHAIN_DEFAULT_CHANNEL

        address = kwargs.get("address", None)
        index = kwargs.get("index", None)

        if address is None or index is None:
            return {
                'response_code':
                message_code.Response.fail_illegal_params,
                'message':
                message_code.get_response_msg(
                    message_code.Response.fail_illegal_params)
            }

        channel_stub = StubCollection().channel_stubs[channel_name]
        tx_list, next_index = await channel_stub.async_task(
        ).get_tx_by_address(address=address, index=index)

        response = {
            'next_index': next_index,
            'response': tx_list[:-1],
            'response_code': message_code.Response.success
        }
        return response
Пример #9
0
    def AnnounceNewLeader(self, request, context):
        channel_name = conf.LOOPCHAIN_DEFAULT_CHANNEL if request.channel == '' else request.channel

        new_leader_peer = ObjectManager(
        ).rs_service.channel_manager.get_peer_manager(channel_name).get_peer(
            request.new_leader_id, None)

        if new_leader_peer is None:
            logging.warning(
                f"RadioStation Has No live Peer Connection(candidate reason is RS's restart)"
            )
            logging.warning(
                f"RadioStation Request to Peers make Re-Connection")

            return loopchain_pb2.CommonReply(
                response_code=message_code.Response.fail_no_peer_info_in_rs,
                message=message_code.get_response_msg(
                    message_code.Response.fail_no_peer_info_in_rs))
        else:
            logging.debug(f"AnnounceNewLeader({channel_name}) "
                          f"id({request.new_leader_id}) "
                          f"target({new_leader_peer.target}): " +
                          request.message)

            ObjectManager().rs_service.channel_manager.get_peer_manager(
                channel_name).set_leader_peer(peer=new_leader_peer,
                                              group_id=None)

            return loopchain_pb2.CommonReply(
                response_code=message_code.Response.success, message="success")
Пример #10
0
    def GetPeerStatus(self, request, context):
        # request parsing
        channel_name = conf.LOOPCHAIN_DEFAULT_CHANNEL if not request.channel else request.channel
        logging.debug(
            f"rs service GetPeerStatus peer_id({request.peer_id}) group_id({request.group_id})"
        )

        # get stub of target peer
        peer_stub_manager = ObjectManager(
        ).rs_service.channel_manager.get_peer_manager(
            channel_name).get_peer_stub_manager(
                ObjectManager().rs_service.channel_manager.get_peer_manager(
                    channel_name).get_peer(request.peer_id))
        if peer_stub_manager is not None:
            try:
                response = peer_stub_manager.call_in_times(
                    "GetStatus",
                    loopchain_pb2.StatusRequest(
                        request="get peer status from rs",
                        channel=channel_name))
                if response is not None:
                    return response
            except Exception as e:
                logging.warning(f"fail GetStatus... ({e})")

        return loopchain_pb2.StatusReply(status=message_code.get_response_msg(
            message_code.Response.fail),
                                         block_height=0,
                                         total_tx=0)
Пример #11
0
 def __abort_if_arg_isnt_enough(self, param_name):
     result = dict()
     result['response_code'] = message_code.Response.fail_validate_params
     result['message'] = \
         message_code.get_response_msg(result['response_code']) \
         + ". You must throw all of parameters : " + param_name
     return result
Пример #12
0
    async def post(self, request):
        result = dict()
        request_data = request.json

        try:
            if request_data is None:
                result['response_code'] = message_code.Response.fail
                result[
                    'message'] = 'You must throw parameter of JSON when you call (/api/v1/conf) by post method.'

            else:
                grpc_response = ServerComponents().set_configuration(
                    json.dumps(request_data))
                result = {
                    'response_code':
                    grpc_response.code,
                    'message':
                    message_code.get_response_msg(
                        message_code.Response.success)
                }

        except ValueError as e:
            result['response_code'] = message_code.Response.fail
            result['message'] = str(e)

        return response.json(result)
Пример #13
0
    def __subscribe_call_to_rs_stub(self, rs_rest_stub):
        response = {'response_code': message_code.Response.fail,
                    'message': message_code.get_response_msg(message_code.Response.fail)}

        try:
            if conf.REST_SSL_TYPE == conf.SSLAuthType.none:
                peer_target = ChannelProperty().rest_target
            else:
                peer_target = f"https://{ChannelProperty().rest_target}"
            response = rs_rest_stub.call(
                "Subscribe", {
                    'channel': ChannelProperty().name,
                    'peer_target': peer_target
                }
            )

        except Exception as e:
            logging.warning(f"Due to Subscription fail to RadioStation(mother peer), "
                            f"automatically retrying subscribe call")

        if response['response_code'] == message_code.Response.success:
            if TimerService.TIMER_KEY_SUBSCRIBE in self.__timer_service.timer_list.keys():
                self.__timer_service.stop_timer(TimerService.TIMER_KEY_SUBSCRIBE)
                self.radio_station_stub.update_methods_version()
                logging.debug(f"Subscription to RadioStation(mother peer) is successful.")

            if TimerService.TIMER_KEY_SHUTDOWN_WHEN_FAIL_SUBSCRIBE in self.__timer_service.timer_list.keys():
                self.__timer_service.stop_timer(TimerService.TIMER_KEY_SHUTDOWN_WHEN_FAIL_SUBSCRIBE)

            # start next get_status timer
            timer_key = TimerService.TIMER_KEY_GET_LAST_BLOCK_KEEP_CITIZEN_SUBSCRIPTION
            if timer_key not in self.__timer_service.timer_list.keys():
                util.logger.spam(f"add timer for check_block_height_call to radiostation...")
                self.__timer_service.add_timer(
                    timer_key,
                    Timer(
                        target=timer_key,
                        duration=conf.GET_LAST_BLOCK_TIMER,
                        is_repeat=True,
                        callback=self.__check_block_height_call_to_rs_stub,
                        callback_kwargs={"rs_rest_stub": rs_rest_stub}
                    )
                )
        else:
            timer_key = TimerService.TIMER_KEY_SHUTDOWN_WHEN_FAIL_SUBSCRIBE
            if timer_key not in self.__timer_service.timer_list.keys():
                error = f"Shutdown by Subscribe retry timeout({conf.SHUTDOWN_TIMER})"
                self.__timer_service.add_timer(
                    timer_key,
                    Timer(
                        target=timer_key,
                        duration=conf.SHUTDOWN_TIMER,
                        callback=self.__shutdown_peer,
                        callback_kwargs={"message": error}
                    )
                )

        return response
Пример #14
0
    def announce_new_leader(self, complained_leader_id, new_leader_id, is_broadcast=True, self_peer_id=None):
        """Announce New Leader Id to Network

        :param complained_leader_id:
        :param new_leader_id:
        :param is_broadcast: False(notify to RS only), True(broadcast to network include RS)
        :param self_peer_id:
        :return:
        """
        util.logger.spam(f"peer_manager:announce_new_leader channel({self.__channel_name}), "
                         f"complained_leader_id({complained_leader_id}), "
                         f"new_leader_id({new_leader_id}), "
                         f"is_broadcast({is_broadcast})")
        is_rs = ObjectManager().rs_service is not None

        announce_message = loopchain_pb2.ComplainLeaderRequest(
            complained_leader_id=complained_leader_id,
            channel=self.__channel_name,
            new_leader_id=new_leader_id,
            message="Announce New Leader"
        )

        # new_leader_peer = self.get_peer(new_leader_id)

        # Announce New Leader to Radio station
        try:
            channel_service = ObjectManager().channel_service
            if channel_service:
                response = channel_service.radio_station_stub.call("AnnounceNewLeader", announce_message)
                if response.response_code == message_code.Response.fail_no_peer_info_in_rs:
                    util.logger.spam(
                        f"peer_manager:announce_new_leader fail no peer info in rs! is_broadcast({is_broadcast})")
                    announce_message.message = message_code.get_response_msg(
                        message_code.Response.fail_no_peer_info_in_rs)
                    ObjectManager().channel_service.connect_to_radio_station(is_reconnect=True)

                    ObjectManager().channel_service.broadcast_scheduler.schedule_broadcast(
                        "Request",
                        loopchain_pb2.Message(
                            code=message_code.Request.peer_reconnect_to_rs,
                            channel=self.__channel_name))
        except Exception as e:
            # logging.debug("in RS there is no peer_service....")
            is_rs = True

        if is_broadcast is True:
            for peer_id in list(self.peer_list[conf.ALL_GROUP_ID]):
                if new_leader_id == peer_id and is_rs is not True:
                    util.logger.spam(f"Prevent reset leader loop in AnnounceNewLeader message")
                    continue

                peer_each = self.peer_list[conf.ALL_GROUP_ID][peer_id]
                stub_manager = self.get_peer_stub_manager(peer_each, conf.ALL_GROUP_ID)
                try:
                    stub_manager.call_async("AnnounceNewLeader", announce_message, is_stub_reuse=True)
                except Exception as e:
                    logging.warning("gRPC Exception: " + str(e))
                    logging.debug("No response target: " + str(peer_each.target))
Пример #15
0
    def Subscribe(self, request, context):
        """RadioStation 이 broadcast 하는 채널에 Peer 를 등록한다.

        :param request: SubscribeRequest
        :param context:
        :return: CommonReply
        """
        channel = conf.LOOPCHAIN_DEFAULT_CHANNEL if request.channel == '' else request.channel
        logging.debug("Radio Station Subscription peer_id: " + str(request))
        ObjectManager().rs_service.common_service.add_audience(request)

        peer = ObjectManager().rs_service.channel_manager.get_peer_manager(
            channel).update_peer_status(peer_id=request.peer_id,
                                        peer_status=PeerStatus.connected)

        try:
            peer_dump = pickle.dumps(peer)
            request.peer_order = peer.order
            request.peer_object = peer_dump

            # self.__broadcast_new_peer(request)
            # TODO RS subsribe 를 이용하는 경우, RS 가 재시작시 peer broadcast 가 전체로 되지 않는 문제가 있다.
            # peer_list 를 이용하여 broadcast 하는 구조가되면 RS 혹은 Leader 에 대한 Subscribe 구조는 유효하지 않다.
            # 하지만 broadcast process 는 peer_list broadcast 인 경우 사용되어지지 않는다. peer_list 에서 broadcast 하는 동안
            # block 되는 구조. broadcast Process 를 peer_list 를 이용한 broadcast 에서도 활용할 수 있게 하거나.
            # RS 혹은 Leader 가 재시작 후에 Subscribe 정보를 복원하게 하거나.
            # 혹은 peer_list 가 broadcast 하여도 성능상(동시성에 있어) 문제가 없는지 보증하여야 한다. TODO TODO TODO
            ObjectManager().rs_service.channel_manager.get_peer_manager(
                channel).announce_new_peer(request)

            # logging.debug("get_IP_of_peers_in_group: " + str(self.__peer_manager.get_IP_of_peers_in_group()))

            return loopchain_pb2.CommonReply(
                response_code=message_code.get_response_code(
                    message_code.Response.success),
                message=message_code.get_response_msg(
                    message_code.Response.success))

        except pickle.PicklingError as e:
            logging.warning("Fail Peer Dump: " + str(e))
            return loopchain_pb2.CommonReply(
                response_code=message_code.get_response_code(
                    message_code.Response.fail),
                message=message_code.get_response_msg(
                    message_code.Response.fail))
Пример #16
0
 async def node_Unsubscribe(**kwargs):
     channel, peer_target = kwargs['channel'], kwargs['peer_target']
     channel_stub = StubCollection().channel_stubs[channel]
     response_code = await channel_stub.async_task(
     ).remove_audience_subscriber(peer_target=peer_target)
     return {
         "response_code": response_code,
         "message": message_code.get_response_msg(response_code)
     }
Пример #17
0
        def __handler_status(status_param):
            logging.debug(f"({self.__process_name}) Status, param({status_param}) audience({len(__audience)})")

            status = dict()
            status['result'] = message_code.get_response_msg(message_code.Response.success)
            status['Audience'] = str(len(__audience))
            status_json = json.dumps(status)

            # return way of manage_process
            manager_dic["status"] = status_json
Пример #18
0
 async def node_AnnounceConfirmedBlock(**kwargs):
     channel, block, commit_state = kwargs['channel'], kwargs[
         'block'], kwargs.get('commit_state', "{}")
     channel_stub = StubCollection().channel_stubs[channel]
     response_code = await channel_stub.async_task(
     ).announce_confirmed_block(block.encode('utf-8'), commit_state)
     return {
         "response_code": response_code,
         "message": message_code.get_response_msg(response_code)
     }
Пример #19
0
        def __handler_status(status_param):
            logging.debug("TxProcess Status, param: " + str(status_param))

            status = dict()
            status['result'] = message_code.get_response_msg(
                message_code.Response.success)
            status_json = json.dumps(status)

            # return way of manage_process
            manager_dic["status"] = status_json
Пример #20
0
    def Subscribe(self, request, context):
        """BlockGenerator 가 broadcast(unconfirmed or confirmed block) 하는 채널에
        Peer 를 등록한다.

        :param request:
        :param context:
        :return:
        """
        self.peer_service.common_service.add_audience(request)
        return loopchain_pb2.CommonReply(response_code=message_code.get_response_code(message_code.Response.success),
                                         message=message_code.get_response_msg(message_code.Response.success))
Пример #21
0
    def VoteUnconfirmedBlock(self, request, context):
        if self.peer_service.peer_type == loopchain_pb2.PEER:
            return loopchain_pb2.CommonReply(
                response_code=message_code.Response.fail_no_leader_peer,
                message=message_code.get_response_msg(message_code.Response.fail_no_leader_peer))
        else:
            logging.info("Peer vote to : " + request.block_hash + " " + str(request.vote_code))
            self.peer_service.block_manager.get_candidate_blocks().vote_to_block(
                request.block_hash, (False, True)[request.vote_code == message_code.Response.success_validate_block],
                request.peer_id, request.group_id)

            return loopchain_pb2.CommonReply(response_code=message_code.Response.success, message="success")
Пример #22
0
    def Subscribe(self, request, context):
        """RadioStation 이 broadcast 하는 채널에 Peer 를 등록한다.

        :param request: SubscribeRequest
        :param context:
        :return: CommonReply
        """
        logging.debug("Radio Station Subscription peer_id: " + str(request))
        self.__common_service.add_audience(request)
        return loopchain_pb2.CommonReply(
            response_code=message_code.get_response_code(
                message_code.Response.success),
            message=message_code.get_response_msg(
                message_code.Response.success))
Пример #23
0
    def AddTx(self, request, context):
        """피어로부터 받은 tx 를 Block Manager 에 추가한다.
        이 기능은 Block Generator 에서만 동작해야 한다. 일반 Peer 는 이 기능을 사용할 권한을 가져서는 안된다.

        :param request:
        :param context:
        :return:
        """

        if self.peer_service.peer_type == loopchain_pb2.PEER:
            return loopchain_pb2.CommonReply(
                response_code=message_code.Response.fail_no_leader_peer,
                message=message_code.get_response_msg(message_code.Response.fail_no_leader_peer))
        else:  # Block Manager 에 tx 추가
            if self.peer_service.block_manager.consensus.block is None:
                return loopchain_pb2.CommonReply(
                    response_code=message_code.Response.fail_made_block_count_limited,
                    message="this leader can't make more block")

            self.peer_service.block_manager.add_tx_unloaded(request.tx)
            return loopchain_pb2.CommonReply(response_code=message_code.Response.success, message="success")
Пример #24
0
    def post(self):
        result = json.loads('{}')
        request_data = request.get_json()

        try:
            if request_data is None:
                result['response_code'] = message_code.Response.fail
                result['message'] = 'You must throw parameter of JSON when you call (/api/v1/conf) by post method.'

            else:
                response = ServerComponents().set_configuration(json.dumps(request_data))

                result = json.loads('{}')
                result['response_code'] = response.code
                result['message'] = message_code.get_response_msg(message_code.Response.success)

        except ValueError as e:
            result['response_code'] = message_code.Response.fail
            result['message'] = str(e)

        return result
Пример #25
0
    def get(self, request_type):
        args = ServerComponents().parser.parse_args()
        channel = get_channel_name_from_args(args)
        logging.debug(f'channel name : {channel}')
        if request_type == self.__REQUEST_TYPE['PEER_LIST']:
            response = ServerComponents().get_peer_list(channel)

            peer_manager = PeerManager()
            peer_list_data = pickle.loads(response.peer_list)
            peer_manager.load(peer_list_data, False)

            all_peer_list = []
            connected_peer_list = []

            leader_peer_id = ""
            leader_peer = peer_manager.get_leader_peer(conf.ALL_GROUP_ID, is_peer=False)  # for set peer_type info to peer
            if leader_peer is not None:
                leader_peer_id = leader_peer.peer_id
            
            for peer_id in peer_manager.peer_list[conf.ALL_GROUP_ID]:
                peer_each = peer_manager.peer_list[conf.ALL_GROUP_ID][peer_id]
                peer_data = self.__change_format_to_json(peer_each)

                if peer_each.peer_id == leader_peer_id:
                    peer_data['peer_type'] = loopchain_pb2.BLOCK_GENERATOR
                else:
                    peer_data['peer_type'] = loopchain_pb2.PEER

                all_peer_list.append(peer_data)

                if peer_each.status == PeerStatus.connected:
                    connected_peer_list.append(peer_data)

            json_data = json.loads('{}')
            json_data['registered_peer_count'] = peer_manager.get_peer_count()
            json_data['connected_peer_count'] = peer_manager.get_connected_peer_count()
            json_data['registered_peer_list'] = all_peer_list
            json_data['connected_peer_list'] = connected_peer_list

            result = json.loads('{}')
            result['response_code'] = message_code.Response.success
            result['data'] = json_data
            
        elif request_type == self.__REQUEST_TYPE['PEER_STATUS_LIST']:
            response = ServerComponents().get_peer_list(channel)

            peer_manager = PeerManager()
            peer_list_data = pickle.loads(response.peer_list)
            peer_manager.load(peer_list_data, False)

            all_peer_list = []

            for peer_id in peer_manager. peer_list[conf.ALL_GROUP_ID]:
                response = ServerComponents().get_peer_status(peer_id, conf.ALL_GROUP_ID, channel)
                if response is not None and response.status != "":
                    peer_each = peer_manager.peer_list[conf.ALL_GROUP_ID][peer_id]
                    status_json = json.loads(response.status)
                    status_json["order"] = peer_each.order
                    all_peer_list.append(status_json)

            json_data = json.loads('{}')
            json_data['registered_peer_count'] = peer_manager.get_peer_count()
            json_data['connected_peer_count'] = peer_manager.get_connected_peer_count()
            json_data['peer_status_list'] = all_peer_list

            result = json.loads('{}')
            result['response_code'] = message_code.Response.success
            result['data'] = json_data

        elif request_type == self.__REQUEST_TYPE['LEADER_PEER']:
            response = ServerComponents().get_leader_peer(channel)

            result = json.loads('{}')
            result['response_code'] = response.code

            if response.code == message_code.Response.success:
                result['data'] = self.__change_format_to_json(pickle.loads(response.object))
            else:
                result['message'] = message_code.get_response_msg(response.code)

        elif request_type == self.__REQUEST_TYPE['PEER_STATUS']:
            peer_id = args['peer_id']
            group_id = args['group_id']

            if peer_id is None or group_id is None:
                return self.__abort_if_arg_isnt_enough('peer_id, group_id')

            # logging.debug(f"try get_peer_status peer_id({peer_id}), group_id({group_id})")
            response = ServerComponents().get_peer_status(args['peer_id'], args['group_id'], channel)
            result = json.loads(response.status)

        else:
            return ServerComponents().abort_if_url_doesnt_exist(request_type, self.__REQUEST_TYPE)

        return result
Пример #26
0
    async def get(self, request, request_type):
        # args = ServerComponents().parser.parse_args()
        args = request.raw_args
        channel = get_channel_name_from_args(args)
        logging.debug(f'channel name : {channel}')
        if request_type == self.__REQUEST_TYPE['PEER_LIST']:
            grpc_response = ServerComponents().get_peer_list(channel)

            peer_manager = PeerManager(channel)
            peer_list_data = pickle.loads(grpc_response.peer_list)
            peer_manager.load(peer_list_data, False)

            all_peer_list = []
            connected_peer_list = []

            leader_peer_id = ""
            leader_peer = peer_manager.get_leader_peer(
                conf.ALL_GROUP_ID,
                is_peer=False)  # for set peer_type info to peer
            if leader_peer is not None:
                leader_peer_id = leader_peer.peer_id

            for peer_id in peer_manager.peer_list[conf.ALL_GROUP_ID]:
                peer_each = peer_manager.peer_list[conf.ALL_GROUP_ID][peer_id]
                peer_data = self.__change_format_to_json(peer_each)

                if peer_each.peer_id == leader_peer_id:
                    peer_data['peer_type'] = loopchain_pb2.BLOCK_GENERATOR
                else:
                    peer_data['peer_type'] = loopchain_pb2.PEER

                all_peer_list.append(peer_data)

                if peer_each.status == PeerStatus.connected:
                    connected_peer_list.append(peer_data)

            json_data = {
                'registered_peer_count': peer_manager.get_peer_count(),
                'connected_peer_count':
                peer_manager.get_connected_peer_count(),
                'registered_peer_list': all_peer_list,
                'connected_peer_list': connected_peer_list
            }
            result = {
                'response_code': message_code.Response.success,
                'data': json_data
            }

        elif request_type == self.__REQUEST_TYPE['PEER_STATUS_LIST']:
            grpc_response = ServerComponents().get_peer_list(channel)

            peer_manager = PeerManager(channel)
            peer_list_data = pickle.loads(grpc_response.peer_list)
            peer_manager.load(peer_list_data, False)

            async_futures: List[grpc.Future] = []
            for peer_id in peer_manager.peer_list[conf.ALL_GROUP_ID]:
                async_future = ServerComponents().get_peer_status_async(
                    peer_id, conf.ALL_GROUP_ID, channel)
                async_futures.append(async_future)
            futures.as_completed(async_futures)

            all_peer_list = []
            for async_future, peer_id in zip(
                    async_futures, peer_manager.peer_list[conf.ALL_GROUP_ID]):
                if async_future.exception():
                    logging.warning(
                        f'RequestType({request_type}), exception({async_future.exception()})'
                    )
                    continue

                grpc_response = async_future.result()
                if grpc_response is not None and grpc_response.status != "":
                    peer_each = peer_manager.peer_list[
                        conf.ALL_GROUP_ID][peer_id]
                    status_json = json.loads(grpc_response.status)
                    status_json["order"] = peer_each.order
                    all_peer_list.append(status_json)

            json_data = {
                'registered_peer_count': peer_manager.get_peer_count(),
                'connected_peer_count':
                peer_manager.get_connected_peer_count(),
                'peer_status_list': all_peer_list
            }
            result = {
                'response_code': message_code.Response.success,
                'data': json_data
            }

        elif request_type == self.__REQUEST_TYPE['LEADER_PEER']:
            grpc_response = ServerComponents().get_leader_peer(channel)

            result = dict()
            result['response_code'] = grpc_response.code

            if grpc_response.code == message_code.Response.success:
                result['data'] = self.__change_format_to_json(
                    pickle.loads(grpc_response.object))
            else:
                result['message'] = message_code.get_response_msg(
                    grpc_response.code)

        elif request_type == self.__REQUEST_TYPE['PEER_STATUS']:
            peer_id = args['peer_id']
            group_id = args['group_id']

            if peer_id is None or group_id is None:
                return self.__abort_if_arg_isnt_enough('peer_id, group_id')

            # logging.debug(f"try get_peer_status peer_id({peer_id}), group_id({group_id})")
            grpc_response = ServerComponents().get_peer_status(
                args['peer_id'], args['group_id'], channel)
            result = json.loads(grpc_response.status)

        else:
            return ServerComponents().abort_if_url_doesnt_exist(
                request_type, self.__REQUEST_TYPE)

        return response.json(result)