class HandleAuctionRemove(ImmediateTask):

    def __init__(self, auction: Auction):
        """
        Handles the removal of an auction

        :param auction: auction to remove.
        :param seconds_to_start: seconds to wait for running the task.
        """
        super(HandleAuctionRemove, self).__init__()
        self.client_data = ClientMainData()
        self.auction_manager = AuctionManager(self.client_data.domain)
        self.bidding_object_manager = BiddingObjectManager(self.client_data.domain)
        self.agent_processor = AgentProcessor(self.client_data.domain, '')
        self.auction = auction

    async def _run_specific(self):
        try:

            self.logger.debug("start Handle Auction Remove - auction: {0}".format(str(self.auction.get_key())))
            # remove from processing the auction
            self.agent_processor.delete_auction(self.auction)

            handle_remove_bidding_objects = HandleRemoveBiddingObjectByAuction(self.auction)
            await handle_remove_bidding_objects.start()
            self.auction_manager.delete_auction(self.auction.get_key())

            self.logger.debug("end Handle Auction Remove - auction: {0}".format(str(self.auction.get_key())))

        except Exception as e:
            self.logger.error(str(e))
Ejemplo n.º 2
0
class HandleLoadAuction(ScheduledTask):
    """
    Handles auction loading from file.
    """
    def __init__(self, file_name: str, seconds_to_start: float):
        """
        Method to create the task
        :param file_name: file name to load. The file name includes the absolute path.
        :param seconds_to_start: seconds for starting the task.
        """
        super(HandleLoadAuction, self).__init__(seconds_to_start)
        self.file_name = file_name
        self.server_main_data = ServerMainData()
        self.resource_manager = ResourceManager(self.server_main_data.domain)
        self.auction_manager = AuctionManager(self.server_main_data.domain)
        self.domain = self.server_main_data.domain
        self.immediate_start = self.server_main_data.inmediate_start
        self.logger = log().get_logger()

    async def _run_specific(self):
        """
        Handles auction loading from file.

        :return:
        """
        try:
            auction_file_parser = AuctionXmlFileParser(self.domain)
            auctions = auction_file_parser.parse(self.file_name)
            for auction in auctions:
                if self.resource_manager.verify_auction(auction):
                    self.auction_manager.add_auction(auction)

                    # Schedule auction activation
                    if self.immediate_start:
                        seconds_to_start = 0
                    else:
                        seconds_to_start = (auction.get_start() -
                                            datetime.now()).total_seconds()

                    activate_task = HandleActivateAuction(
                        auction=auction, seconds_to_start=seconds_to_start)
                    activate_task.start()
                    auction.add_task(activate_task)

                    seconds_to_start = (auction.get_stop() -
                                        datetime.now()).total_seconds()
                    removal_task = HandleRemoveAuction(
                        auction=auction, seconds_to_start=seconds_to_start)
                    removal_task.start()
                    auction.add_task(removal_task)

                    self.logger.info("auction with key {0} added".format(
                        auction.get_key()))
                else:
                    self.logger.error(
                        "The auction with key {0} could not be added".format(
                            auction.get_key()))
        except Exception as e:
            self.logger.error(
                "An error occur during load actions - Error:{}".format(str(e)))
 def __init__(self, session: AuctionSession):
     self.session_manager = AuctionSessionManager()
     self.session = session
     self.client_data = ClientMainData()
     self.client_message_processor = ClientMessageProcessor()
     self.agent_processor = AgentProcessor(self.client_data.domain, "")
     self.auction_manager = AuctionManager(self.client_data.domain)
     self.logger = log().get_logger()
Ejemplo n.º 4
0
 def __init__(self, session: AuctionSession, bidding_object: BiddingObject,
              seconds_to_start: float):
     super(HandleActivateBiddingObject, self).__init__(seconds_to_start)
     self.session = session
     self.bidding_object = bidding_object
     self.server_main_data = ServerMainData()
     self.auction_manager = AuctionManager(self.server_main_data.domain)
     self.auction_processor = AuctionProcessor(self.server_main_data.domain)
 def __init__(self, server_connection: ServerConnection, message: IpapMessage, seconds_to_start: float):
     super(HandleAskResponseMessage, self).__init__(seconds_to_start)
     self.client_data = ClientMainData()
     self.server_connection = server_connection
     self.resource_request_interval: ResourceRequestInterval = \
         server_connection.get_auction_session().resource_request_interval
     self.message = message
     self.agent_template_container = AgentTemplateContainerManager()
     self.auction_manager = AuctionManager(self.client_data.domain)
     self.agent_processor = AgentProcessor(self.client_data.domain, '')
     self.template_container = None
Ejemplo n.º 6
0
 def __init__(self, session: AuctionSession, ipap_message: IpapMessage,
              seconds_to_start: float):
     super(HandleAddBiddingObjects, self).__init__(seconds_to_start)
     self.session = session
     self.ipap_message = ipap_message
     self.server_main_data = ServerMainData()
     self.server_message_processor = ServerMessageProcessor()
     self.bididing_manager = BiddingObjectManager(
         self.server_main_data.domain)
     self.auction_manager = AuctionManager(self.server_main_data.domain)
     self.template_container = IpapTemplateContainerSingleton()
     self.logger = log().get_logger()
    def __init__(self, auction: Auction):
        """
        Handles the removal of an auction

        :param auction: auction to remove.
        :param seconds_to_start: seconds to wait for running the task.
        """
        super(HandleAuctionRemove, self).__init__()
        self.client_data = ClientMainData()
        self.auction_manager = AuctionManager(self.client_data.domain)
        self.bidding_object_manager = BiddingObjectManager(self.client_data.domain)
        self.agent_processor = AgentProcessor(self.client_data.domain, '')
        self.auction = auction
Ejemplo n.º 8
0
 def __init__(self, file_name: str, seconds_to_start: float):
     """
     Method to create the task
     :param file_name: file name to load. The file name includes the absolute path.
     :param seconds_to_start: seconds for starting the task.
     """
     super(HandleLoadAuction, self).__init__(seconds_to_start)
     self.file_name = file_name
     self.server_main_data = ServerMainData()
     self.resource_manager = ResourceManager(self.server_main_data.domain)
     self.auction_manager = AuctionManager(self.server_main_data.domain)
     self.domain = self.server_main_data.domain
     self.immediate_start = self.server_main_data.inmediate_start
     self.logger = log().get_logger()
Ejemplo n.º 9
0
    def __init__(self, session: AuctionSession, message: IpapMessage,
                 seconds_to_start: float):
        """

        :param seconds_to_start:
        """
        super(HandleAskRequest, self).__init__(seconds_to_start)
        self.session = session
        self.message = message
        self.server_main_data = ServerMainData()
        self.auction_manager = AuctionManager(self.server_main_data.domain)
        self.auction_processor = AuctionProcessor(self.server_main_data.domain)
        self.field_manager = FieldDefManager()
        self.message_processor = ServerMessageProcessor()
        self.template_container = IpapTemplateContainerSingleton()
Ejemplo n.º 10
0
class HandleActivateBiddingObject(ScheduledTask):
    """
    Handles the activate of a bidding object. When active the bidding object is included in the auction for bidding.
    """
    def __init__(self, session: AuctionSession, bidding_object: BiddingObject,
                 seconds_to_start: float):
        super(HandleActivateBiddingObject, self).__init__(seconds_to_start)
        self.session = session
        self.bidding_object = bidding_object
        self.server_main_data = ServerMainData()
        self.auction_manager = AuctionManager(self.server_main_data.domain)
        self.auction_processor = AuctionProcessor(self.server_main_data.domain)

    async def _run_specific(self):
        try:
            self.logger.info("activating bidding_object with key: {0}".format(
                self.bidding_object.get_key()))
            auction = self.auction_manager.get_auction(
                self.bidding_object.get_parent_key())
            if auction.get_state() == AuctioningObjectState.ACTIVE:
                self.auction_processor.add_bidding_object_to_auction_process(
                    auction.get_key(), self.bidding_object)
                self.bidding_object.set_state(AuctioningObjectState.ACTIVE)
            else:
                raise ValueError("Auction {0} is not active".format(
                    auction.get_key()))
        except Exception as e:
            self.logger.error(str(e))
Ejemplo n.º 11
0
    def get_ipap_message(
            self, bidding_objects: List[BiddingObject],
            template_container: IpapTemplateContainer) -> IpapMessage:
        """
        get the ipap_message that contains all the bidding objects within the list given

        :param bidding_objects: bidding objects to include in the message.
        :param template_container: container with all the registered templates
        :return: ipap_message with the information
        """
        ipap_bidding_object_parser = IpapBiddingObjectParser(self.domain)
        message = IpapMessage(self.domain, IpapMessage.IPAP_VERSION, True)
        auction_manager = AuctionManager(self.domain)

        for bidding_object in bidding_objects:
            auction = auction_manager.get_auction(
                bidding_object.get_parent_key())
            ipap_bidding_object_parser.get_ipap_message(
                bidding_object, auction, template_container, message)

        return message
    def get_ipap_message(self, allocation: Allocation, template_container: IpapTemplateContainer) -> IpapMessage:
        """

        :return:
        """
        message = IpapMessage(self.domain, IpapMessage.IPAP_VERSION, True)

        auction_manager = AuctionManager(self.domain)
        auction = auction_manager.get_auction(allocation.get_auction_key())

        # Find both templates types for the bidding object.
        temp_type = IpapTemplate.get_data_template(allocation.get_template_object_type())
        data_template_id = auction.get_bidding_object_template(allocation.get_template_object_type(), temp_type)

        temp_type = IpapTemplate.get_opts_template(allocation.get_template_object_type())
        option_template_id = auction.get_bidding_object_template(allocation.get_template_object_type(), temp_type)

        # Insert allocations's templates.a
        data_template = template_container.get_template(data_template_id)
        message.make_template(data_template)

        option_template = template_container.get_template(option_template_id)
        message.make_template(option_template)

        # Include data records.
        self.include_data_record(data_template, allocation, 'Record_1', allocation.config_params, message)

        # Include option records.
        index = 1
        for interval in allocation.intervals:
            record_id = 'Record_{0}'.format(str(index))
            self.include_options_record(option_template, allocation,
                                        record_id, interval.start, interval.stop, message)
            index = index + 1

        return message
 def __init__(self, stop_datetime: datetime, resource_request: ResourceRequest, seconds_to_start: float):
     """
     Method to create the task remove resource request interval
     :param stop_datetime: date and time when the resource request interval should be removed.
     :param resource_request: resource request that should be started.
     :param seconds_to_start: seconds for starting the task.
     """
     super(HandleRemoveResourceRequestInterval, self).__init__(seconds_to_start)
     self.stop_datetime = stop_datetime
     self.resource_request = resource_request
     self.seconds_to_start = seconds_to_start
     self.client_data = ClientMainData()
     self.auction_session_manager = AuctionSessionManager()
     self.agent_processor = AgentProcessor(self.client_data.domain, "")
     self.auction_manager = AuctionManager(self.client_data.domain)
     self.client_message_processor = ClientMessageProcessor()
Ejemplo n.º 14
0
class HandleRemoveBiddingObject(ScheduledTask):
    """
    Handles the removal of a bidding object. This removes the bidding object from the auction for bidding.
    """
    def __init__(self, session: AuctionSession, bidding_object: BiddingObject,
                 periods_to_maintain: int, seconds_to_start: float):
        super(HandleRemoveBiddingObject, self).__init__(seconds_to_start)
        self.session = session
        self.bidding_object = bidding_object
        self.periods_to_maintain = periods_to_maintain
        self.server_main_data = ServerMainData()
        self.bidding_manager = BiddingObjectManager(
            self.server_main_data.domain)
        self.auction_manager = AuctionManager(self.server_main_data.domain)
        self.auction_processor = AuctionProcessor(self.server_main_data.domain)

    async def _run_specific(self):
        try:
            self.logger.info("bidding object remove key: {0}".format(
                self.bidding_object.get_key()))

            # Wait for the bid to complete execution.
            if self.bidding_object.get_type() == AuctioningObjectType.BID:
                while self.bidding_object.get_execution_periods(
                ) <= self.periods_to_maintain:
                    self.logger.info(
                        "inactivate bidding object number of periods:{0}".
                        format(str(
                            self.bidding_object.get_execution_periods())))
                    # we have to wait for the process request to execute
                    await asyncio.sleep(1)

            auction = self.auction_manager.get_auction(
                self.bidding_object.get_parent_key())
            if auction.get_state() == AuctioningObjectState.ACTIVE:
                self.auction_processor.delete_bidding_object_from_auction_process(
                    auction.get_key(), self.bidding_object)
                self.bidding_manager.del_actioning_object(
                    self.bidding_object.get_key())
            else:
                raise ValueError("Auction {0} is not active".format(
                    auction.get_key()))

        except Exception as e:
            self.logger.error(str(e))
    def __init__(self, request_process_key: str, bidding_objects: List[BiddingObject], seconds_to_start: float):
        """
        Handles the generation of new bidding objects

        :param request_process_key: process key where the bidding objects have been generated
        :param bidding_objects: bidding object list to include
        :param seconds_to_start: seconds to wait for running the task.
        """
        super(HandledAddGenerateBiddingObject, self).__init__(seconds_to_start)
        self.request_process_key = request_process_key
        self.bidding_objects = bidding_objects
        self.client_data = ClientMainData()
        self.agent_processor = AgentProcessor(self.client_data.domain, '')
        self.auction_session_manager = AuctionSessionManager()
        self.auction_manager = AuctionManager(self.client_data.domain)
        self.agent_template_container = AgentTemplateContainerManager()
        self.bidding_manager = BiddingObjectManager(self.client_data.domain)
        self.message_processor = ClientMessageProcessor()
class RemoveResourceRequestInterval:

    def __init__(self, session: AuctionSession):
        self.session_manager = AuctionSessionManager()
        self.session = session
        self.client_data = ClientMainData()
        self.client_message_processor = ClientMessageProcessor()
        self.agent_processor = AgentProcessor(self.client_data.domain, "")
        self.auction_manager = AuctionManager(self.client_data.domain)
        self.logger = log().get_logger()

    async def process_remove(self):

        self.logger.info('starting process remove request interval - session {0}'.format(self.session.get_key()))

        # searches the request interval
        resource_request_interval = self.session.get_resource_request_interval()

        self.logger.info(resource_request_interval.start)

        # removes the request interval
        auctions = self.session.get_auctions()

        self.logger.info('nbr auctions {0}'.format(str(len(auctions))))

        # deletes active request process associated with this request interval.
        resource_request_process_ids = resource_request_interval.get_resource_request_process()

        self.logger.info('starting process request to remove: {0}'.format(str(resource_request_process_ids)))

        for resource_request_process_id in resource_request_process_ids:
            self.agent_processor.delete_request(resource_request_process_id)

        # deletes the reference to the auction (a session is not referencing it anymore)
        auctions_to_remove = self.auction_manager.decrement_references(auctions, self.session.get_key())

        for auction in auctions_to_remove:
            handle_auction_remove = HandleAuctionRemove(auction)
            await handle_auction_remove.start()

        await resource_request_interval.stop_tasks()
        self.logger.info('ending process remove request interval')
Ejemplo n.º 17
0
 def _initialize_managers(self):
     """
     Initializes managers used.
     :return:
     """
     self.logger.debug("Starting _initialize_managers")
     self.auction_manager = AuctionManager(self.domain)
     self.database_manager = DataBaseManager(
         Config().get_config_param('DataBase', 'Type'),
         Config().get_config_param('DataBase', 'Host'),
         Config().get_config_param('DataBase', 'User'),
         Config().get_config_param('DataBase', 'Password'),
         Config().get_config_param('DataBase', 'Port'),
         Config().get_config_param('DataBase', 'DbName'),
         Config().get_config_param('DataBase', 'MinSize'),
         Config().get_config_param('DataBase', 'MaxSize'))
     self.bidding_object_manager = BiddingObjectManager(self.domain)
     self.resource_request_manager = ResourceRequestManager(self.domain)
     self.auction_session_manager = AuctionSessionManager()
     self.logger.debug("Ending _initialize_managers")
class HandleInactivateBiddingObject(ScheduledTask):
    """
    Handles the removal of a bidding object from the auction process.
    """

    def __init__(self, bidding_object: BiddingObject, seconds_to_start: float):
        super(HandleInactivateBiddingObject, self).__init__(seconds_to_start)
        self.bidding_object = bidding_object
        self.server_main_data = ClientMainData()
        self.bidding_manager = BiddingObjectManager(self.server_main_data.domain)
        self.auction_manager = AuctionManager(self.server_main_data.domain)

    async def _run_specific(self):
        try:
            auction = self.auction_manager.get_auction(self.bidding_object.get_parent_key())
            if auction.get_state() == AuctioningObjectState.ACTIVE:
                self.bidding_object.set_state(AuctioningObjectState.SCHEDULED)
            else:
                raise ValueError("Auction {0} is not active".format(auction.get_key()))
        except Exception as e:
            self.logger.error(str(e))
class HandleRemoveBiddingObject(ScheduledTask):
    """
    Handles the removal of a bidding object. This removes the bidding object from the auction for bidding.
    """

    def __init__(self, bidding_object: BiddingObject, seconds_to_start: float):
        super(HandleRemoveBiddingObject, self).__init__(seconds_to_start)
        self.bidding_object = bidding_object
        self.server_main_data = ClientMainData()
        self.bidding_manager = BiddingObjectManager(self.server_main_data.domain)
        self.auction_manager = AuctionManager(self.server_main_data.domain)

    async def _run_specific(self):
        try:
            self.logger.info("starting HandleRemoveBiddingObject key {0}".format(self.bidding_object.get_key()))
            auction = self.auction_manager.get_auction(self.bidding_object.get_parent_key())
            if auction.get_state() == AuctioningObjectState.ACTIVE:
                await self.bidding_object.stop_tasks([self])
                self.bidding_manager.delete_bidding_object(self.bidding_object.get_key())
            else:
                raise ValueError("Auction {0} is not active".format(auction.get_key()))

        except Exception as e:
            self.logger.error(str(e))
class HandleAskResponseMessage(ScheduledTask):

    def __init__(self, server_connection: ServerConnection, message: IpapMessage, seconds_to_start: float):
        super(HandleAskResponseMessage, self).__init__(seconds_to_start)
        self.client_data = ClientMainData()
        self.server_connection = server_connection
        self.resource_request_interval: ResourceRequestInterval = \
            server_connection.get_auction_session().resource_request_interval
        self.message = message
        self.agent_template_container = AgentTemplateContainerManager()
        self.auction_manager = AuctionManager(self.client_data.domain)
        self.agent_processor = AgentProcessor(self.client_data.domain, '')
        self.template_container = None

    def get_template_container(self):
        """
        Gets the template container for the particular server.
        """
        self.logger.debug("starting get_template_container")
        domain = self.message.get_domain()
        if domain > 0:
            try:
                self.template_container = self.agent_template_container.get_template_container(domain)
            except ValueError:
                template_container = IpapTemplateContainer()
                self.agent_template_container.add_template_container(domain, template_container)
                self.template_container = template_container
        else:
            self.logger.error("Invalid domain id associated with the message")
            raise ValueError("Invalid domain id associated with the message")

        self.logger.debug("ending get_template_container")

    def create_auctions(self, auctions: List[Auction]) -> int:
        """
        Creates the auctions answered by the server as being used to bid for the resource
        :param auctions:list of auctions
        :return: maximum duration interval.
        """
        self.logger.debug("starting create_auctions")
        # This variable maintains the auction with the maximal duration interval, so
        # The request should last at least an interval multiple.
        max_interval = 0

        for auction in auctions:
            # search the auction in the auction container, if it exists then updates its intervals.
            try:
                auction2 = self.auction_manager.get_auction(auction.get_key())
                interval = auction2.get_interval()
                if auction2.get_start() > self.resource_request_interval.start:
                    auction2.set_start(self.resource_request_interval.start)

                if auction2.get_stop() < self.resource_request_interval.stop:
                    auction2.set_stop(self.resource_request_interval.stop)

                when = DateUtils().calculate_when(auction2.get_stop())

            except ValueError:
                # the auction does not exists, so we need to create a new auction process.
                interval = auction.get_interval()
                auction.intersect_interval(interval.start, interval.stop)
                val_interval = interval.interval
                if val_interval > 0:
                    duration = (auction.get_stop() - auction.get_start()).total_seconds()
                    bid_intervals = floor(duration / val_interval)
                    modulus = fmod(duration, val_interval)

                    # If the requested time is less than the minimal interval for the auction
                    # we have to request te minimal interval.
                    if modulus > 0:
                        new_stop = auction.get_start() + timedelta(interval.interval * (bid_intervals + 1))
                        auction.set_stop(new_stop)

                self.auction_manager.add_auction(auction)

            # Update the maximum interval for the auction.
            if max_interval < interval.interval:
                max_interval = interval.interval

        self.logger.debug("ending create_auctions")
        return max_interval

    def create_process_request(self, auctions: list, max_interval: int, server_domain: int):
        """

        :param auctions: list of auction to put to process
        :param max_interval: the auction with the maximal duration interval
        :return:
        """
        self.logger.debug("starting process request")
        # Go through the list of auctions and create groups by their module
        auctions_by_module = {}

        for auction in auctions:
            module_name = auction.get_module_name()
            if module_name not in auctions_by_module:
                auctions_by_module[module_name] = []
            auctions_by_module[module_name].append(auction)
        req_start = self.resource_request_interval.start
        req_stop = self.resource_request_interval.stop

        first_time = True
        resource_request_key = None
        for module_name in auctions_by_module:
            auctions = auctions_by_module[module_name]
            resource_request_key = None
            for auction in auctions:
                if first_time:
                    if max_interval > 0:
                        bid_intervals = floor((req_stop - req_start).total_seconds() / max_interval)
                        duration = max_interval * (bid_intervals + 1)
                        req_stop = req_start + timedelta(seconds=duration)

                        resource_request_key = self.agent_processor.add_request(
                            self.server_connection.get_auction_session().get_key(),
                            self.resource_request_interval.get_fields(),
                            auction, server_domain, req_start, req_stop)

                    self.resource_request_interval.add_resource_request_process(resource_request_key)
                    first_time = False
                else:
                    self.agent_processor.add_auction_request(resource_request_key, auction)

        when = DateUtils.calculate_when(req_start)
        handle_request_process_execution = HandleRequestProcessExecution(resource_request_key, when)
        handle_request_process_execution.start()
        self.resource_request_interval.add_task(handle_request_process_execution)

        when = DateUtils.calculate_when(req_stop)
        handle_request_process_remove = HandleRequestProcessRemove(resource_request_key, when)
        handle_request_process_remove.start()
        self.resource_request_interval.add_task(handle_request_process_remove)
        self.logger.debug("ending process request")

    async def _run_specific(self):
        try:
            self.get_template_container()
            auctions = self.auction_manager.parse_ipap_message(self.message, self.template_container)
            max_interval = self.create_auctions(auctions)
            self.create_process_request(auctions, max_interval, self.message.get_domain())
            self.auction_manager.increment_references(auctions, self.server_connection.get_auction_session().get_key())
            self.server_connection.get_auction_session().set_auctions(auctions)
        except Exception as e:
            self.logger.error(str(e))
 def __init__(self, bidding_object: BiddingObject, seconds_to_start: float):
     super(HandleRemoveBiddingObject, self).__init__(seconds_to_start)
     self.bidding_object = bidding_object
     self.server_main_data = ClientMainData()
     self.bidding_manager = BiddingObjectManager(self.server_main_data.domain)
     self.auction_manager = AuctionManager(self.server_main_data.domain)
Ejemplo n.º 22
0
class HandleAskRequest(ScheduledTask):
    """
    Handles an ask request from an agent. This request is performed to get auctions applicable for a resource.
    """
    def __init__(self, session: AuctionSession, message: IpapMessage,
                 seconds_to_start: float):
        """

        :param seconds_to_start:
        """
        super(HandleAskRequest, self).__init__(seconds_to_start)
        self.session = session
        self.message = message
        self.server_main_data = ServerMainData()
        self.auction_manager = AuctionManager(self.server_main_data.domain)
        self.auction_processor = AuctionProcessor(self.server_main_data.domain)
        self.field_manager = FieldDefManager()
        self.message_processor = ServerMessageProcessor()
        self.template_container = IpapTemplateContainerSingleton()

    def is_complete(self, session_info: dict):
        """
        Establishes if the session info given as part of the message is complete.

        :param session_info: session information given.
        :return: true or false
        """
        agent_session_set = self.auction_processor.get_set_field(
            AgentFieldSet.SESSION_FIELD_SET_NAME)
        return len(session_info) == len(agent_session_set)

    async def _run_specific(self):
        """
        Handles a session request from an agent.
        """
        try:
            auctions = self.auction_processor.get_applicable_auctions(
                self.message)
            self.logger.debug("number of applicable auctions: {0}".format(
                len(auctions)))
            session_info = self.auction_processor.get_session_information(
                self.message)

            if self.server_main_data.use_ipv6:
                s_address = self.server_main_data.ip_address6.__str__()
            else:
                s_address = self.server_main_data.ip_address4.__str__()

            if self.is_complete(session_info):
                message_to_send = self.auction_manager.get_ipap_message(
                    auctions, self.server_main_data.use_ipv6, s_address,
                    self.server_main_data.local_port)

                message_to_send.set_ack_seq_no(self.message.get_seqno())
                message_to_send.set_seqno(self.session.get_next_message_id())

                await self.message_processor.send_message(
                    self.session.get_connection(),
                    message_to_send.get_message())
            else:
                ack_message = self.message_processor.build_ack_message(
                    self.session.get_next_message_id(),
                    self.message.get_seqno())
                await self.message_processor.send_message(
                    self.session.get_connnection(), ack_message.get_message())
        except Exception as e:
            self.logger.error(str(e))
Ejemplo n.º 23
0
class HandleAddBiddingObjects(ScheduledTask):
    """
    This class handles adding a new bidding object sent from an agent to the server.
    """
    def __init__(self, session: AuctionSession, ipap_message: IpapMessage,
                 seconds_to_start: float):
        super(HandleAddBiddingObjects, self).__init__(seconds_to_start)
        self.session = session
        self.ipap_message = ipap_message
        self.server_main_data = ServerMainData()
        self.server_message_processor = ServerMessageProcessor()
        self.bididing_manager = BiddingObjectManager(
            self.server_main_data.domain)
        self.auction_manager = AuctionManager(self.server_main_data.domain)
        self.template_container = IpapTemplateContainerSingleton()
        self.logger = log().get_logger()

    async def _run_specific(self):
        """
        Adds bidding objects sent from an agent.
        """
        try:
            self.logger.debug("starting HandleAddBiddingObjects")
            # parse the message
            bidding_objects = self.bididing_manager.parse_ipap_message(
                self.ipap_message, self.template_container)

            # insert bidding objects to bidding object manager
            for bidding_object in bidding_objects:
                self.logger.info(
                    "receiving bidding object with key: {0}".format(
                        bidding_object.get_key()))
                bidding_object.set_session(self.session.get_key())
                self.bididing_manager.add_auctioning_object(bidding_object)
                i = 0
                num_options = len(bidding_object.options)
                for option_name in sorted(bidding_object.options.keys()):
                    interval = bidding_object.calculate_interval(option_name)
                    when = (interval.start - datetime.now()).total_seconds()
                    handle_activate = HandleActivateBiddingObject(
                        self.session, bidding_object, when)
                    handle_activate.start()
                    bidding_object.add_task(handle_activate)

                    auction = self.auction_manager.get_auction(
                        bidding_object.get_parent_key())

                    when = (interval.stop - datetime.now()).total_seconds()
                    # calculates the number of periods that should be active given the auction frequency
                    periods = math.ceil(when / auction.interval.duration)

                    if i < num_options - 1:
                        self.logger.info(
                            "scheduling bidding object inactivate when: {0}".
                            format(str(when)))
                        handle_inactivate = HandleInactivateBiddingObject(
                            self.session, bidding_object, periods, when)
                        handle_inactivate.start()
                        bidding_object.add_task(handle_inactivate)
                    else:
                        self.logger.info(
                            "scheduling bidding object remove when: {0}".
                            format(str(when)))
                        handle_inactivate = HandleRemoveBiddingObject(
                            self.session, bidding_object, periods, when)
                        handle_inactivate.start()
                        bidding_object.add_task(handle_inactivate)

                    i = i + 1

            # confirm the message
            confim_message = self.server_message_processor.build_ack_message(
                self.session.get_next_message_id(),
                self.ipap_message.get_seqno())
            await self.server_message_processor.send_message(
                self.session.get_connection(), confim_message.get_message())
            self.logger.debug("ending HandleAddBiddingObjects")
        except Exception as e:
            self.logger.error(str(e))