Example #1
0
 def AskBackhaulBids(self, serviceId):
     messageAsk = Message('')
     messageAsk.setMethod(Message.GET_BEST_BIDS)
     messageAsk.setParameter('Provider', self._list_vars['strId'])
     messageAsk.setParameter('Service', serviceId)
     messageResult = self.sendMessageMarketBuy(messageAsk)
     if messageResult.isMessageStatusOk():
         document = self.removeIlegalCharacters(messageResult.getBody())
         try:
             dom = xml.dom.minidom.parseString(document)
             return self.handleBestBids(dom)
         except Exception as e:
             raise FoundationException(str(e))
     else:
         raise FoundationException("Best bids not received")
Example #2
0
 def receive_purchase_feedback(self, message):
     self.lock.acquire()
     try:
         logger.debug('Initiating Receive Purchase feedback Agent:%s', str(self._list_args['Id']))
         agent_type = self._list_args['Type']
         if (( agent_type.getType() == AgentType.PROVIDER_ISP) 
            or ( agent_type.getType() == AgentType.PROVIDER_BACKHAUL) 
               or ( agent_type.getType() == AgentType.PRESENTER_TYPE)):
             period = int(message.getParameter("Period"))
             self._list_args['Current_Period'] = period
             document = self.removeIlegalCharacters(message.getBody())
             #print document
             dom = xml.dom.minidom.parseString(document)
             # receive purchase statistics
             purchaseXmlNodes = dom.getElementsByTagName("Receive_Purchases")        
             for purchaseXmlNode in purchaseXmlNodes:
                 self.handleReceivePurchases(period, purchaseXmlNode)
             # After receiving the purchase information the provider can 
             # start to create new bids.
             if (( agent_type.getType() == AgentType.PROVIDER_ISP) 
                 or (agent_type.getType() == AgentType.PROVIDER_BACKHAUL)):
                 self._list_args['State'] = AgentServerHandler.BID_PERMITED    
             logger.debug('Receive Purchase feedback - Agent:%s Period: %s ', str(self._list_args['Id']), str(self._list_args['Current_Period'] ))        
     except Exception as e: 
        raise FoundationException(str(e))
     finally:
        if self.testThread == True:
            time.sleep(2)
        self.lock.release()
Example #3
0
 def receive_bid_information(self, message):
     self.lock.acquire()
     if self.testThread == True:
         logger.debug('Acquire the lock')
     try:
         logger.debug('Initiating competitor bid information - Agent:%s', str(self._list_args['Id']) )
         agent_type = self._list_args['Type']
         if (( agent_type.getType() == AgentType.PROVIDER_ISP) or 
              (agent_type.getType() == AgentType.PROVIDER_BACKHAUL) or 
               (agent_type.getType() == AgentType.PRESENTER_TYPE)):
             period = int(message.getParameter("Period"))
             period = period - 1 # The server sends the information tagged with the next period.
                                 # TODO: Change the Market Place Server to send the correct period.
             document = self.removeIlegalCharacters(message.getBody())
             logger.info('Period' + str(period) + 'bid document' + str(document))
             dom = xml.dom.minidom.parseString(document)
             competitorsXmlNodes = dom.getElementsByTagName("New_Bids")
             for competitorsXmlNode in competitorsXmlNodes:
                 self.handleCompetitorBids(period, competitorsXmlNode)
         logger.debug('Competitor bids Loaded Agent: %s', str(self._list_args['Id']))
     except Exception as e: 
         logger.debug('Exception raised' + str(e) ) 
         raise FoundationException(str(e))
     finally:
        if self.testThread == True:
            logger.info('Going to sleep')
            time.sleep(2)
            logger.info('After sleep')
        self.lock.release()
Example #4
0
 def create(self, typ):
     if typ in self._list_classes:
         targetClass = self._list_classes[typ]
         return targetClass()
     else:
         err = 'Class' + typ + 'not found to be loaded'
         raise FoundationException(err)
def test_initialization(provider):
    provider.start_agent()
    provider.initialize()

    if ((provider._list_vars['Type']).getType() !=
            AgentType.PROVIDER_BACKHAUL):
        raise FoundationException(
            "error in test_initialization, we are expecting a backhaul provider"
        )
Example #6
0
 def handleGetService(self, document):
     logger.debug('Starting get service handler Id:%s',
                  self._list_vars['Id'])
     document = self.removeIlegalCharacters(document)
     logger.debug('document:%s', document)
     try:
         dom = xml.dom.minidom.parseString(document)
         servicesXml = dom.getElementsByTagName("Service")
         if (len(servicesXml) > 1):
             raise FoundationException(
                 "The server sent more than one service")
         else:
             service = Service()
             for servicexml in servicesXml:
                 service.setFromXmlNode(servicexml)
             logger.debug('Ending get service handler')
             return service
     except Exception as e:
         raise FoundationException(str(e))
     logger.debug('Ending get service handler Id:%s', self._list_vars['Id'])
Example #7
0
 def getServices(self):
     logger.debug('Starting get services Id:%s', self._list_vars['Id'])
     messageAsk = Message('')
     messageAsk.setMethod(Message.GET_SERVICES)
     messageResult = self.sendMessageClock(messageAsk)
     if messageResult.isMessageStatusOk():
         return self.handleGetServices(messageResult.getBody())
     else:
         raise FoundationException(
             'Services not received! Communication failed')
     logger.debug('Ending get services Id:%s', self._list_vars['Id'])
def getExecutionCount(cursor):
    executionCount = 0
    sql = "select execution_count from Network_Simulation.simulation_generalparameters limit 1"
    cursor.execute(sql)
    results = cursor.fetchall()
    for row in results:
        executionCount = int(row[0])
        break
    if (executionCount == 0):
        raise FoundationException("execution count not defined")
    return executionCount
Example #9
0
    def getEvaluation(self, variableValue):
        # Verifies existance of all parameters.
        parameters = self.getParameters()
        for parameter in parameters:
            name = parameters[parameter]
            if name not in self._parameters.keys():
                raise FoundationException(
                    'parameter for cost evaluation not found' + name)

        a = self._parameters['a']
        b = self._parameters['b']
        return (a * math.log(variableValue + 1)) + b
Example #10
0
    def getEvaluation(self, variableValue):
        # Verifies existance of all parameters.
        parameters = self.getParameters()
        for parameter in parameters:
            name = parameters[parameter]
            if name not in self._parameters.keys():
                raise FoundationException(
                    'parameter for cost evaluation not found' + name)

        intercept = self._parameters['intercept']
        slope = self._parameters['slope']
        return intercept + (slope * variableValue)
Example #11
0
 def getServiceFromServer(self, serviceId):
     logger.debug('Starting getServiceFromServer Id:%s',
                  self._list_vars['Id'])
     try:
         connect = Message("")
         connect.setMethod(Message.GET_SERVICES)
         connect.setParameter("Service", serviceId)
         response = self.sendMessageClock(connect)
         if (response.isMessageStatusOk()):
             logger.debug('ending  getServiceFromServer')
             return self.handleGetService(response.getBody())
     except FoundationException as e:
         raise FoundationException(e.__str__())
Example #12
0
 def getServiceFromServer(self, serviceId):
     logger.debug('Starting getServiceFromServer Id: %s',
                  self._list_vars['Id'])
     try:
         if (str(serviceId) not in (self._services).keys()):
             service = self._agntClient.getServiceFromServer(str(serviceId))
             self._services[serviceId] = service
             logger.debug('Ending getServiceFromServer Id: %s',
                          self._list_vars['Id'])
     except FoundationException as e:
         logger.error('exception Id:%s - Message:%s', self._list_vars['Id'],
                      e.__str__())
         raise FoundationException(e.__str__())
Example #13
0
 def handle_accept(self):
     logger.debug('handle Accept Id: %s', self._list_args['Id'])
     pair = self.accept()
     if pair is not None:
         logger.debug('handle Accept Id: %s address:%s port:%s', self._list_args['Id'], self._address, self._port)
         sock, addr = pair
         logger.debug('Incoming connection from %s', repr(addr))
         string_pair = repr(addr) + repr(sock)
         self._strings_received[string_pair] = ''
         try:
             handler = AgentServerHandler( addr, sock, self._thread_sockets, self._lock, self._testThread, self._list_args, self._strings_received)
         except asyncore.ExitNow, e:
             raise FoundationException(str(e))
         logger.debug('Ending handle Accept Id: %s address:%s port:%s', self._list_args['Id'], self._address, self._port)
Example #14
0
    def connect(self):
        try:
            strID = self._list_vars['strId']
            agent_type = self._list_vars['Type']
            sellingAddress = self._list_vars['SellingAddres']
            buyingAddress = self._list_vars['BuyingAddres']
            capacityControl = self._list_vars['capacityControl']

            # Connect to servers.
            self._agntClient.connect_servers(agent_type, strID, sellingAddress,
                                             buyingAddress, capacityControl)
            # Request the definition of the service
        except FoundationException as e:
            raise FoundationException(e.__str__())
Example #15
0
 def handleGetServices(self, document):
     logger.debug('Starting get service Id:%s', self._list_vars['Id'])
     document = self.removeIlegalCharacters(document)
     try:
         dom = xml.dom.minidom.parseString(document)
         servicesXml = dom.getElementsByTagName("Service")
         services = {}
         for servicexml in servicesXml:
             service = Service()
             service.setFromXmlNode(servicexml)
             services[service.getId()] = service
         return services
     except Exception as e:
         raise FoundationException(str(e))
     logger.debug('Ending get service Id:%s', self._list_vars['Id'])
Example #16
0
    def handleCompetitorBids(self, period, competitorsXmlNode):
        bids = competitorsXmlNode.getElementsByTagName("Bid")
        try:
            agent_type = self._list_args['Type']
            if ( agent_type.getType() == AgentType.PRESENTER_TYPE):
                logger.debug('Handle competitor bids')
                self._list_args['Current_Bids'] = {}  
                logger.debug('clear Handle competitor bids')
                
            for bid in bids:
                logger.debug('We are inside the bid loop')
                competitor_bid = Bid()
                competitor_bid.setFromXmlNode(bid)                
                if (competitor_bid.getProvider() != self._list_args['strId']):
                    if (competitor_bid.getService() == (self._list_args['serviceId'])):                        
                        if (competitor_bid.getId() in self._list_args['Related_Bids']):
                            # The bid must be replaced as the provider update it.
                            oldCompetitorBid = (self._list_args['Related_Bids'])[competitor_bid.getId()]
                            competitor_bid.setCreationPeriod(oldCompetitorBid.getCreationPeriod())  
                            (self._list_args['Related_Bids'])[competitor_bid.getId()] = competitor_bid
                        else:
                            if (competitor_bid.isActive() == True):
                                competitor_bid.setCreationPeriod(period)

                            # Replace the parent bid, looking for the actual one already in the dictionary 
                            if (competitor_bid.getParentBid() != None):
                                parentBidId = competitor_bid.getParentBid().getId() 
                                if parentBidId not in self._list_args['Related_Bids']:
                                    logger.error('Parent BidId %s not found in related bids', parentBidId)
                                else:
                                    parentBid = (self._list_args['Related_Bids'])[parentBidId]
                                    competitor_bid.insertParentBid(parentBid)
                                
                            #logger.debug('Inserting competitor bid:' + competitor_bid.__str__())
                            (self._list_args['Related_Bids'])[competitor_bid.getId()] = competitor_bid
                        
                        # Inserts on exchanged bids
                        if (agent_type.getType() == AgentType.PRESENTER_TYPE):
                            (self._list_args['Current_Bids'])[competitor_bid.getId()] = competitor_bid
                                    
            if (agent_type.getType() == AgentType.PRESENTER_TYPE):
                logger.debug('End Handle competitor bids - num exchanged:' + str(len(self._list_args['Current_Bids'])))
            logger.debug('clear 3 Handle competitor bids')
            logger.debug('Ending handled bid competitors for agent is:' + str(self._list_args['Id']))
            
        except Exception as e:
            raise FoundationException(str(e))
Example #17
0
    def connect_servers(self, agent_type, strID, sellingAddress, buyingAddress,
                        capacityControl):
        logger.info(
            'Starting connect servers agent %s selling Address:%s buyingAddress:%s',
            strID, sellingAddress, buyingAddress)
        if (agent_type.getType() == AgentType.PROVIDER_ISP):
            logger.debug('Agent Provider ISP %s', strID)
            port = agent_properties.mkt_place_listening_port
            address = sellingAddress
            # This will be the channel to put bids.
            self._channelMarketPlace = Channel_Marketplace(address, port)
            address = buyingAddress
            # This will be the channel to buy resources.
            self._channelMarketPlaceBuy = Channel_Marketplace(address, port)
        elif (agent_type.getType() == AgentType.PROVIDER_BACKHAUL):
            logger.debug('Agent Provider Backhaul %s', strID)
            port = agent_properties.mkt_place_listening_port
            address = sellingAddress
            # This will be the channel to put bids.
            self._channelMarketPlace = Channel_Marketplace(address, port)
        else:
            logger.debug('Agent Other %s', strID)
            port = agent_properties.mkt_place_listening_port
            address = agent_properties.addr_mktplace_isp
            self._channelMarketPlace = Channel_Marketplace(address, port)
        self._channelClockServer = Channel_ClockServer()

        # Send the Connect message to ClockServer
        connect = self.create_connect_message(strID)
        response1 = (self._channelClockServer).sendMessage(connect)
        if (response1.isMessageStatusOk() == False):
            raise FoundationException(
                "Agent: It could not connect to clock server")

        # Send the Connect message to MarketPlace
        if (agent_type.getType() == AgentType.PROVIDER_ISP):
            response2 = (self._channelMarketPlace).sendMessage(connect)
            if (response2.isMessageStatusOk()):
                response3 = (self._channelMarketPlaceBuy).sendMessage(connect)
                if (response3.isMessageStatusOk()):
                    logger.debug('We could connect to servers')
                else:
                    logger.error(
                        'Provider ISP: It could not connect to the market place to Buy'
                    )
                    raise FoundationException(
                        "Provider ISP: It could not connect to the market place to Buy"
                    )
            else:
                logger.error(
                    'Provider ISP: It could not connect to market place to sell'
                )
                raise FoundationException(
                    "Provider ISP: It could not connect to market place to sell"
                )
        else:
            response2 = (self._channelMarketPlace).sendMessage(connect)
            if (response2.isMessageStatusOk()):
                logger.info('We could connect servers')
            else:
                logger.error('The agent could not connect to market place')
                raise FoundationException(
                    "Agent: It could not connect to market place")
        logger.debug('Ending connect servers agent %s', strID)
                              buyingAddress, capacityControl, purchase_service)
            providers.append(provider)
            i = i + 1

        logger.info('Starting test public provider')

        # Test providers' initialization.
        provider1 = providers[0]  # Public provider

        fileResult1 = open(provider1.getProviderId() + '.log', "a")

        test_initialization(provider1)
        radius = 0.05
        output = provider1.initializeBidParameters(radius, fileResult1)
        if len(output) != 20:
            raise FoundationException("We expect 20 outputs - numCalculated:" +
                                      str(len(output)))

        # The following code verifies some of the outputs. The decision variables are 3 and 4.

        if ((output[0])['3'] != 0):
            raise FoundationException(
                "We expect quality 0 for output 0 - numCalculated:" +
                str((output[0])['3']))

        print 'Here we are'
        quality = (output[3])['3']
        if (round(quality, 2) != 0.15):
            raise FoundationException(
                "We expect quality 0.15 for output 3 - numCalculated:" +
                str(quality))