def __init__(self, agent, p2p=False):  # , msgrecv):
        self._client = agent.getAID().getName()
        #self.msgrecv = msgrecv
        self.myAgent = agent
        self._server = agent.server

        # Add Disco Behaviour
        agent.addBehaviour(
            DiscoBehaviour(),
            Behaviour.MessageTemplate(Iq(queryNS=NS_DISCO_INFO)))

        # Add Stream Initiation Behaviour
        iqsi = Iq()
        si = iqsi.addChild("si")
        si.setNamespace(NS_SI)  #"http://jabber.org/protocol/si")
        agent.addBehaviour(StreamInitiationBehaviour(),
                           Behaviour.MessageTemplate(iqsi))

        # Add P2P Behaviour
        self.p2p_ready = False  # Actually ready for P2P communication
        self.p2p = p2p
        self.p2p_routes = {}
        self.p2p_lock = thread.allocate_lock()
        self.p2p_send_lock = thread.allocate_lock()
        self._p2p_failures = 0  # Counter for failed attempts to send p2p messages
        if p2p:
            agent.registerLogComponent("p2p")
            self.P2PPORT = random.randint(70000,
                                          80000)  # Random P2P port number
            p2pb = P2PBehaviour()
            agent.addBehaviour(p2pb)
    def myCreate(self):
        if not self.checkGoal(self.goalList):
            raise NotValidGoal
        elif not self.checkType():
            raise NotVvalidType
        elif not self.testRoomName():
            raise NotValidName
        elif not self.createRoom():
            raise CreationError
        else:
            self.state = "available"
            if self.agentList != []:
                #enviando invitaciones
                self.invite(self.agentList)
        #registrando en el DF
        # dad = DF.DfAgentDescription()
        # ds = DF.ServiceDescription()
        # ds.setType("ORGANIZATION")
        # ds.setName(self.name)
        # dad.setAID(self.myAgent.getAID())
        # dad.addService(ds)
        # res = self.myAgent.registerService(dad)

            self.owner = True
            self.orgOwner = self.myAgent.JID
            p = Presence()
            t = Behaviour.MessageTemplate(p)
            self.presenceBehaviour = self.PresenceBehaviour(
                self.muc_name, self.name, self.nick, self)
            self.myAgent.addBehaviour(self.presenceBehaviour, t)
            if self.type == "Matrix" or self.type == "Federation":
                self.createTeam()
 def checkIsMember(self, unit):
     ismember = False
     units = self.getUnitList()
     if unit in units:
         units.remove(unit)
     team = "Team:" + self.name
     if team in units:
         units.remove(team)
     jid = str(self.myAgent.JID)
     ID = "".join([
         string.ascii_letters[int(
             random.randint(0,
                            len(string.ascii_letters) - 1))]
         for a in range(5)
     ])
     p = Iq(frm=jid, attrs={"id": ID})
     t1 = Behaviour.MessageTemplate(p)
     b = self.IsMemberBehaviour(jid, ID)
     self.myAgent.addBehaviour(b, t1)
     b.join()
     b.result
     for u in units:
         if u in b.result:
             ismember = True
     return ismember
Beispiel #4
0
    def _setup(self):

        self.agentdb = dict()

        AAD = AmsAgentDescription()
        AAD.name = self.getAID()
        AAD.ownership = "SPADE"
        AAD.state = "active"

        self.agentdb[self.getAID().getName()] = AAD

        if self.getDF():
            AAD = AmsAgentDescription()
            AAD.name = self.getDF()
            AAD.ownership = "SPADE"
            AAD.state = "active"
            self.agentdb[self.getDF().getName()] = AAD

        db = self.DefaultBehaviour()
        #db.setPeriod(0.25)
        #self.setDefaultBehaviour(db)
        mt = Behaviour.ACLTemplate()
        mt.setOntology("FIPA-Agent-Management")
        mt.setPerformative("request")
        mt.setProtocol('fipa-request')
        self.addBehaviour(db, Behaviour.MessageTemplate(mt))

        self.wui.start()
 def destroy(self):
     #deberia implicar dejar tambien las salas de la organizacion???
     """
    Organization owner destroys the organization
     """
     if self.state == "unavailable":
         raise Unavailable
         return
     units = self.getUnitLis
     units.append(self.name)
     if self.owner is True:
         for u in units:
             ID = "".join([
                 string.ascii_letters[int(
                     random.randint(0,
                                    len(string.ascii_letters) - 1))]
                 for a in range(5)
             ])
             p = Iq(frm=self.name + "@" + self.muc_name, attrs={"id": ID})
             t1 = Behaviour.MessageTemplate(p)
             b = self.DestroyBehaviour(self.muc_name, u, ID)
             self.myAgent.addBehaviour(b, t1)
             b.join()
         #destruir los comportamientos
         self.myAgent.removeBehaviour(self.presenceBehaviour)
         self.myAgent.removeBehaviour(self)
         self.state = "unavailable"
         #destruir las unidades
     else:
         raise DestroyError
 def myJoinRoom(self):
     p = Presence(frm=self.name + "@" + self.muc_name + "/" + self.nick,
                  attrs={"type": "error"})
     t1 = Behaviour.MessageTemplate(p)
     b = self.MyJoinRoomBehaviour(self.muc_name, self.name, self.nick)
     self.myAgent.addBehaviour(b, t1)
     b.join()
     return b.result
 def __init__(self, agent):  # , msgrecv):
     self._client = agent.getAID().getName()
     #self.msgrecv = msgrecv
     self.myAgent = agent
     self._server = agent.server
     agent.addBehaviour(
         RPCServerBehaviour(),
         Behaviour.MessageTemplate(Iq(typ='set', queryNS=NS_RPC)))
 def getSupervisorList(self):
     list = []
     ID = "".join([
         string.ascii_letters[int(
             random.randint(0,
                            len(string.ascii_letters) - 1))]
         for a in range(5)
     ])
     p = Iq(frm="Team:" + self.name + "@" + self.muc_name, attrs={"id": ID})
     t1 = Behaviour.MessageTemplate(p)
     b = self.GetMemberListBehaviour(self.muc_name, "Team:" + self.name, ID)
     self.myAgent.addBehaviour(b, t1)
     b.join()
     member = b.result
     ID = "".join([
         string.ascii_letters[int(
             random.randint(0,
                            len(string.ascii_letters) - 1))]
         for a in range(5)
     ])
     p = Iq(frm="Team:" + self.name + "@" + self.muc_name, attrs={"id": ID})
     t = Behaviour.MessageTemplate(p)
     b = self.GetOwnerListBehaviour(self.muc_name, "Team:" + self.name, ID)
     self.myAgent.addBehaviour(b, t)
     b.join()
     owner = b.result
     ID = "".join([
         string.ascii_letters[int(
             random.randint(0,
                            len(string.ascii_letters) - 1))]
         for a in range(5)
     ])
     p = Iq(frm=self.name + "@" + self.muc_name, attrs={"id": ID})
     t = Behaviour.MessageTemplate(p)
     b = self.GetAdminListBehaviour(self.muc_name, "Team:" + self.name, ID)
     self.myAgent.addBehaviour(b, t)
     b.join()
     admin = b.result
     for i in owner:
         list.append(i)
     for i in member:
         list.append(i)
     for i in admin:
         list.append(i)
     return list
 def testRoomName(self):
     ID = "".join([
         string.ascii_letters[int(
             random.randint(0,
                            len(string.ascii_letters) - 1))]
         for a in range(5)
     ])
     iq = Iq(frm=self.muc_name, attrs={"id": ID})
     t = Behaviour.MessageTemplate(iq)
     b = self.TestRoomNameBehaviour(ID, self.muc_name, self.name)
     self.myAgent.addBehaviour(b, t)
     b.join()
     return b.result
 def createRoom(self):
     ID = "".join([
         string.ascii_letters[int(
             random.randint(0,
                            len(string.ascii_letters) - 1))]
         for a in range(5)
     ])
     p = Presence(frm=self.name + "@" + self.muc_name + "/" + self.nick)
     t1 = Behaviour.MessageTemplate(p)
     b = self.CreateRoomBehaviour(ID, self.muc_name, self.name, self.nick,
                                  self.contentLanguage, self.type,
                                  self.goalList)
     self.myAgent.addBehaviour(b, t1)
     b.join()
     return b.result
 def _process(self):
     self.result = []
     iq = Iq(to=self.muc_name, typ='get', attrs={"id": self.ID})
     query = Protocol('query',
                      xmlns="http://jabber.org/protocol/disco#items")
     iq.addChild(node=query)
     self.myAgent.jabber.send(iq)
     msg = self._receive(True, 10)
     if msg:
         if query:
             items = msg.getQueryChildren()
             for item in items:
                 if item.getAttr("jid"):
                     iq = Iq(to=item.getAttr("jid"),
                             typ='get',
                             attrs={"id": self.ID})
                     query = Protocol(
                         'query',
                         xmlns="http://jabber.org/protocol/disco#info")
                     iq.addChild(node=query)
                     name = str(item.getAttr("name"))
                     self.myAgent.jabber.send(iq)
                     template = Iq(frm=item.getAttr("jid"),
                                   typ='result',
                                   attrs={"id": self.ID})
                     t = Behaviour.MessageTemplate(template)
                     self.setTemplate(t)
                     msg = self._receive(True, 10)
                     if msg:
                         query = msg.getTag("query")
                         if query:
                             x = query.getTag("x")
                             if x:
                                 items = x.getChildren()
                                 for item in items:
                                     value = None
                                     if item.getAttr(
                                             "var"
                                     ) == "muc#roominfo_type":
                                         if item.getTags("value"):
                                             value = item.getTags(
                                                 "value")[0].getData()
                                             if value == "Unit:" + self.roomname:
                                                 self.result.append(
                                                     name)
 def getUnitList(self):
     """
     Returns a dataform with all requested information for joining
     """
     if self.state == "unavailable":
         raise Unavailable
         return
     ID = "".join([
         string.ascii_letters[int(
             random.randint(0,
                            len(string.ascii_letters) - 1))]
         for a in range(5)
     ])
     iq = Iq(frm=self.muc_name, attrs={"id": ID})
     t = Behaviour.MessageTemplate(iq)
     b = self.GetUnitListBehaviour(ID, self.muc_name, self.name)
     self.myAgent.addBehaviour(b, t)
     b.join()
     return b.result
 def myJoin(self):
     #The Organization exists
     if not self.testOrganizationName():
         #The room no existe
         raise NotValidName
     elif not self.myJoinRoom():
         #No es una organizacion
         #raise JoinError
         pass
     else:
         info = self.getInfo()
         if info:
             self.type = info["type"]
             self.contentLanguage = info["contentLanguage"]
             self.parent = info["parent"]
             self.goal = info["goal"]
         self.state = "available"
         p = Presence()
         t = Behaviour.MessageTemplate(p)
         self.presenceBehaviour = self.PresenceBehaviour(
             self.muc_name, self.name, self.nick, self)
         self.myAgent.addBehaviour(self.presenceBehaviour, t)
    def getUnitInfo(self, unitname):
        if self.state == "unavailable":
            raise Unavailable
            return
        if unitname not in selg.getUnitList():
            raise NotValidUnit
            return

        ID = "".join([
            string.ascii_letters[int(
                random.randint(0,
                               len(string.ascii_letters) - 1))]
            for a in range(5)
        ])
        p = Iq(frm=self.name + "@" + self.muc_name,
               typ='result',
               attrs={"id": ID})
        t1 = Behaviour.MessageTemplate(p)
        b = self.GetUnitInfoBehaviour(self.muc_name, unitname, ID)
        self.myAgent.addBehaviour(b, t1)
        b.join()
        return b.result
    def getRegistrationForm(self, unitName):
        """
        Returns a dataform with all requested information for joining
        """
        if self.state == "unavailable":
            raise Unavailable
            return
        if unitName not in self.getUnitList():
            raise NotValidUnit
            return

        ID = "".join([
            string.ascii_letters[int(
                random.randint(0,
                               len(string.ascii_letters) - 1))]
            for a in range(5)
        ])
        p = Iq(frm=unitName + "@" + self.muc_name, attrs={"id": ID})
        t1 = Behaviour.MessageTemplate(p)
        b = self.GetRegistrationFormBehaviour(self.muc_name, ID, unitName)
        self.myAgent.addBehaviour(b, t1)
        b.join()
        return b.result
 def sendRegistrationForm(self, unitName, dataForm):
     """
     Sends a dataform for a specific unit. If valid, agent is registered and allowed to join
     """
     if self.state == "unavailable":
         raise Unavailable
         return
     #comprobando que es una unidad de la organizacion
     if unitName not in self.getUnitList():
         raise NotValidUnit
         return
     ID = "".join([
         string.ascii_letters[int(
             random.randint(0,
                            len(string.ascii_letters) - 1))]
         for a in range(5)
     ])
     p = Iq(frm=unitName + "@" + self.muc_name, attrs={"id": ID})
     t1 = Behaviour.MessageTemplate(p)
     b = self.GetRegistrationFormBehaviour(self.muc_name, self.name, ID,
                                           unitName, dataForm)
     self.myAgent.addBehaviour(b, t1)
     b.join()
     return b.result
Beispiel #17
0
        def _process(self):
            error = False
            msg = self._receive(True)
            if msg is not None:
                self.myAgent.DEBUG("AMS received message " + str(msg), "info",
                                   "ams")
                if msg.getPerformative().lower() == 'request':
                    if msg.getOntology() and msg.getOntology().lower(
                    ) == "fipa-agent-management":
                        if msg.getLanguage().lower() == "fipa-sl0":
                            content = self.sl0parser.parse(msg.getContent())
                            ACLtemplate = Behaviour.ACLTemplate()
                            ACLtemplate.setConversationId(
                                msg.getConversationId())
                            ACLtemplate.setSender(msg.getSender())
                            template = (Behaviour.MessageTemplate(ACLtemplate))

                            if "action" in content:
                                self.myAgent.DEBUG(
                                    "AMS: " + str(content.action) +
                                    " request. " + str(content), "info", "ams")
                                if "register" in content.action \
                                        or "deregister" in content.action:
                                    self.myAgent.addBehaviour(
                                        AMS.RegisterBehaviour(msg, content),
                                        template)
                                elif "get-description" in content.action:
                                    self.myAgent.addBehaviour(
                                        AMS.PlatformBehaviour(msg, content),
                                        template)
                                elif "search" in content.action:
                                    self.myAgent.addBehaviour(
                                        AMS.SearchBehaviour(msg, content),
                                        template)
                                elif "modify" in content.action:
                                    self.myAgent.addBehaviour(
                                        AMS.ModifyBehaviour(msg, content),
                                        template)
                            else:
                                reply = msg.createReply()
                                reply.setSender(self.myAgent.getAID())
                                reply.setPerformative("refuse")
                                reply.setContent("( " + msg.getContent() +
                                                 "(unsuported-function " +
                                                 content.keys()[0] + "))")
                                self.myAgent.send(reply)

                                return -1

                        elif msg.getLanguage().lower() == "rdf":
                            # Content in RDF
                            co = msg.getContentObject()
                            content = msg.getContent()
                            ACLtemplate = Behaviour.ACLTemplate()
                            ACLtemplate.setConversationId(
                                msg.getConversationId())
                            ACLtemplate.setSender(msg.getSender())
                            template = (Behaviour.MessageTemplate(ACLtemplate))

                            if "fipa:action" in co.keys(
                            ) and "fipa:act" in co["fipa:action"].keys():
                                self.myAgent.DEBUG(
                                    "AMS: " +
                                    str(co["fipa:action"]["fipa:act"]) +
                                    " request. " + str(co.asRDFXML()), "info",
                                    "ams")
                                if co["fipa:action"]["fipa:act"] in [
                                        "register", "deregister"
                                ]:
                                    self.myAgent.addBehaviour(
                                        AMS.RegisterBehaviour(msg, content),
                                        template)
                                elif co["fipa:action"][
                                        "fipa:act"] == "get-description":
                                    self.myAgent.addBehaviour(
                                        AMS.PlatformBehaviour(msg, content),
                                        template)
                                elif co["fipa:action"]["fipa:act"] == "search":
                                    self.myAgent.addBehaviour(
                                        AMS.SearchBehaviour(msg, content),
                                        template)
                                elif co["fipa:action"]["fipa:act"] == "modify":
                                    self.myAgent.addBehaviour(
                                        AMS.ModifyBehaviour(msg, content),
                                        template)
                            else:
                                reply = msg.createReply()
                                reply.setSender(self.myAgent.getAID())
                                reply.setPerformative("refuse")
                                co["unsuported-function"] = "true"
                                reply.setContentObject(co)
                                self.myAgent.send(reply)
                                return -1

                        else:
                            error = "(unsupported-language " + msg.getLanguage(
                            ) + ")"
                    else:
                        error = "(unsupported-ontology " + msg.getOntology(
                        ) + ")"

                # By adding 'not-understood' to the following list of unsupported acts, we prevent an
                # infinite loop of counter-answers between the AMS and the registering agents
                elif msg.getPerformative().lower() not in [
                        'failure', 'refuse', 'not-understood'
                ]:
                    error = "(unsupported-act " + msg.getPerformative() + ")"
                if error:
                    reply = msg.createReply()
                    reply.setSender(self.myAgent.getAID())
                    reply.setPerformative("not-understood")
                    reply.setContent("( " + msg.getContent() + error + ")")
                    self.myAgent.send(reply)
                    return -1

            return 1
Beispiel #18
0
 def onStart(self):
     self.myAgent.addBehaviour(
         self.SubscribeBehaviour(),
         Behaviour.MessageTemplate(xmpp.Presence()))
        def _process(self):
            p = Presence(to=self.name + "@" + self.muc_name + "/" + self.nick)
            x = Protocol("x", xmlns="http://jabber.org/protocol/muc")
            p.addChild(node=x)
            self.myAgent.jabber.send(p)
            msg = self._receive(True, 10)
            if msg:
                if msg.getAttr("type") == "error":
                    print "Room creation is restricted"
                    self.result = False
                    return
            else:
                self.result = False
                return
            template = Iq(frm=self.name + "@" + self.muc_name,
                          attrs={"id": self.ID})
            t = Behaviour.MessageTemplate(template)
            self.setTemplate(t)
            iq = Iq(to=self.name + "@" + self.muc_name,
                    typ='get',
                    attrs={"id": self.ID})
            query = Protocol('query',
                             xmlns="http://jabber.org/protocol/muc#owner")
            iq.addChild(node=query)
            self.myAgent.jabber.send(iq)
            msg = self._receive(True, 10)
            #para descartar los presence anteriores
            while msg and msg.getName() != "iq":
                msg = self._receive(True, 10)

            #setting room configuration
            if not msg or msg.getAttr("type") == "error":
                print "No configuration is possible: "
                self.result = False
                return
            #falta por revisar!!!!
            iq = Iq(to=self.name + "@" + self.muc_name,
                    typ='set',
                    attrs={"id": self.ID})
            query = Protocol('query',
                             xmlns="http://jabber.org/protocol/muc#owner")
            x = Node(tag="x",
                     attrs={
                         "xmlns": "jabber:x:data",
                         " type": "submit"
                     })
            resquery = msg.getQueryChildren()[
                0]  # nos quedamos con el hijo de query
            if resquery:
                items = resquery.getTags("field")
            if resquery is None:
                print "No configuration is possible"
                self.result = False
            for item in items:
                value = None
                if item.getAttr("var"):
                    value = item.getAttr("value")  # tomamos el valor
                if item.getAttr("var") == "muc#roomconfig_lang":
                    value = self.contentLanguage
                if item.getAttr("var") == "muc#roomconfig_roomdesc":
                    value = self.type
                if item.getAttr("var") == "muc#roomconfig_roomtype":
                    value = "Unit:" + self.parent
                if item.getAttr("var") == "muc#roomconfig_roomname":
                    value = self.name
                if item.getAttr("var") == "muc#roomconfig_presencebroadcast":
                    value = "moderator"
                if item.getAttr("var") == "muc#roomconfig_persistentroom":
                    value = "1"
                if item.getAttr("var") == "muc#roomconfig_publicroom":
                    value = "1"
                if item.getAttr("var") == "muc#roomconfig_moderatedroom":
                    value = "0"
                if item.getAttr("var") == "muc#roomconfig_membersonly":
                    value = "1"
                if item.getAttr(
                        "var") == "muc#roomconfig_passwordprotectedroom":
                    value = "0"
                if item.getAttr("var") == "muc#roomconfig_whois":
                    value = "anyone"  # como es esto??
                if item.getAttr("var") == "muc#roomconfig_changeSubject":
                    value = "0"
                if value:
                    node = Node(tag="field",
                                attrs={"var": item.getAttr("var")})
                    valnode = Node(tag="value")
                    valnode.addData(value)
                    node.addChild(node=valnode)
                    x.addChild(node=node)
            query.addChild(node=x)
            iq.addChild(node=query)
            self.myAgent.jabber.send(iq)
            msg = self._receive(True, 10)
            if msg and msg.getAttr(
                    "type"
            ) == "result":  # comprobar mejor el mensaje que se devuelve
                #añadiendo los members invitacion
                for agent in self.agentList:
                    iq = Iq(to=self.name + "@" + self.muc_name,
                            typ='set',
                            attrs={"id": self.ID})
                    query = Protocol(
                        'query', xmlns="http://jabber.org/protocol/muc#admin")
                    item = Node(tag="item",
                                attrs={
                                    "affiliation": "owner",
                                    "jid": agent
                                })
                    query.addChild(node=item)
                    iq.addChild(node=query)
                    self.myAgent.jabber.send(iq)
                m = Message(to=self.name + "@" + self.muc_name,
                            typ="groupchat")
                sub = Node(tag="subject")
                sub.addData(str(self.goal))
                m.addChild(node=sub)
                self.myAgent.jabber.send(m)
                self.result = True
            else:
                self.result = False