示例#1
0
文件: storage.py 项目: zenny/Archipel
 def iq_getiso(self, iq):
     """
     Get the virtual cdrom ISO of the virtual machine.
     @type iq: xmpp.Protocol.Iq
     @param iq: the received IQ
     @rtype: xmpp.Protocol.Iq
     @return: a ready to send IQ containing the result of the action
     """
     try:
         nodes = []
         isos = os.listdir(self.entity.folder)
         for iso in isos:
             if self._is_file_an_iso(os.path.join(self.entity.folder, iso)):
                 node = xmpp.Node(tag="iso", attrs={"name": iso, "path": os.path.join(self.entity.folder, iso)})
                 nodes.append(node)
         sharedisos = os.listdir(self.shared_isos_folder)
         for iso in sharedisos:
             if self._is_file_an_iso(os.path.join(self.shared_isos_folder, iso)):
                 node = xmpp.Node(tag="iso", attrs={"name": iso, "path": os.path.join(self.shared_isos_folder, iso)})
                 nodes.append(node)
         reply = iq.buildReply("result")
         reply.setQueryPayload(nodes)
         self.entity.log.info("Info about iso sent.")
     except Exception as ex:
         reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_DRIVES_GETISO)
     return reply
示例#2
0
 def iq_get(self, iq):
     """
     List all virtual networks.
     @type iq: xmpp.Protocol.Iq
     @param iq: the received IQ
     @rtype: xmpp.Protocol.Iq
     @return: a ready to send IQ containing the result of the action
     """
     try:
         reply                   = iq.buildReply("result")
         active_networks_nodes   = []
         inactive_networks_nodes = []
         networks                = self.get()
         for network_name in networks["active"]:
             network = self.entity.libvirt_connection.networkLookupByName(network_name)
             desc = network.XMLDesc(0)
             n = xmpp.simplexml.NodeBuilder(data=desc).getDom()
             n.setAttr("autostart", self.getAutostart(network_name))
             active_networks_nodes.append(n)
         for network_name in networks["inactive"]:
             network = self.entity.libvirt_connection.networkLookupByName(network_name)
             desc = network.XMLDesc(0)
             n = xmpp.simplexml.NodeBuilder(data=desc).getDom()
             n.setAttr("autostart", self.getAutostart(network_name))
             inactive_networks_nodes.append(n)
         active_networks_root_node   = xmpp.Node(tag="activedNetworks", payload=active_networks_nodes)
         inactive_networks_root_node = xmpp.Node(tag="unactivedNetworks", payload=inactive_networks_nodes)
         reply.setQueryPayload([active_networks_root_node, inactive_networks_root_node])
     except libvirt.libvirtError as ex:
         reply = build_error_iq(self, ex, iq, ex.get_error_code(), ns=ARCHIPEL_NS_LIBVIRT_GENERIC_ERROR)
     except Exception as ex:
         reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_NETWORKS_GET)
     return reply
示例#3
0
 def iq_group_list(self, iq):
     """
     List shared groups.
     @type iq: xmpp.Protocol.Iq
     @param iq: the received IQ
     @rtype: xmpp.Protocol.Iq
     @return: a ready to send IQ containing the result of the action
     """
     try:
         reply = iq.buildReply("result")
         groups = self.group_list()
         groupsNode = []
         for group in groups:
             members = group["members"]
             del group["members"]
             displayed_groups = group["displayed_groups"]
             del group["displayed_groups"]
             newNode = xmpp.Node("group", attrs=group)
             for member in members:
                 newNode.addChild("user", attrs={"jid": member})
             for displayed_group in displayed_groups:
                 if(displayed_group != ''):
                     newNode.addChild("displayed_group", attrs={"id": displayed_group})
             groupsNode.append(newNode)
             newNode = xmpp.Node("displayed_groups")
         reply.setQueryPayload(groupsNode)
     except Exception as ex:
         reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_XMPPSERVER_GROUP_LIST)
     return reply
示例#4
0
        def on_receive_info(conn, iq):

            _users_management_capabilities  = {"xmpp": False, "xmlrpc": False}
            _groups_management_capabilities = {"xmpp": False, "xmlrpc": False}

            _info_msg="XMPPSERVER - User and SRG Management : "
            if iq.getType() == "result":
               _users_management_capabilities["xmpp"] = True
               _info_msg += "XEP-133 allowed"
            else:
               _users_management_capabilities["xmpp"] = False
               _info_msg += "XEP-133 NOT allowed"

            # next try to use xmlrpc and mod_admin_extra to manage srg
            try:
                answer = self._send_xmlrpc_call("srg_list", {"host": self.xmlrpc_host})
                _groups_management_capabilities["xmlrpc"] = True
                _info_msg += " and SRG allowed through xmlrpc"
            except Exception as ex:
                _groups_management_capabilities["xmlrpc"] = False
                _info_msg += " and SRG NOT allowed through xmlrpc, reason : %s" % str(ex)


            # now send back the reply
            _users_node  = xmpp.Node("users",  attrs={"xmpp":_users_management_capabilities["xmpp"],  "xmlrpc":_users_management_capabilities["xmlrpc"]})
            _groups_node = xmpp.Node("groups", attrs={"xmpp":_groups_management_capabilities["xmpp"], "xmlrpc":_groups_management_capabilities["xmlrpc"]})
            reply.setQueryPayload([_users_node, _groups_node])
            self.entity.log.debug(_info_msg)
            self.entity.xmppclient.send(reply)
示例#5
0
    def commit_to_db(self, action, table, callback):
        """
        Sends a command to active central agent for execution
        @type command: string
        @param command: the sql command to execute
        @type table: table
        @param command: the table of dicts of values associated with the command.
        """
        central_agent_jid = self.central_agent_jid()

        if central_agent_jid:

            # send an iq to central agent

            dbCommand = xmpp.Node(tag="event", attrs={"jid": self.entity.jid})

            for entry in table:

                entryTag = xmpp.Node(tag="entry")

                for key, value in entry.iteritems():

                    entryTag.addChild("item",
                                      attrs={
                                          "key": key,
                                          "value": value
                                      })

                dbCommand.addChild(node=entryTag)

            def commit_to_db_callback(conn, resp):

                if callback:

                    unpacked_entries = self.unpack_entries(resp)
                    callback(unpacked_entries)

            iq = xmpp.Iq(typ="set",
                         queryNS=ARCHIPEL_NS_CENTRALAGENT,
                         to=central_agent_jid)
            iq.getTag("query").addChild(name="archipel",
                                        attrs={"action": action})
            iq.getTag("query").getTag("archipel").addChild(node=dbCommand)
            self.entity.log.debug("CENTRALDB: commit to db request %s" % iq)
            xmpp.dispatcher.ID += 1
            iq.setID("%s-%d" % (self.entity.jid.getNode(), xmpp.dispatcher.ID))
            self.entity.xmppclient.SendAndCallForResponse(
                iq, commit_to_db_callback)

        else:

            self.entity.log.warning(
                "CENTRALDB: cannot commit to db because we have not detected any central agent"
            )
示例#6
0
 def iq_getgolden(self, iq):
     """
     Get the list of golden qcow2 images
     @type iq: xmpp.Protocol.Iq
     @param iq: the received IQ
     @rtype: xmpp.Protocol.Iq
     @return: a ready to send IQ containing the result of the action
     """
     try:
         nodes = []
         goldens = os.listdir(self.golden_drives_dir)
         for golden in goldens:
             if self._is_file_a_qcow(os.path.join(self.golden_drives_dir, golden)) \
             or self._is_file_a_qcow2(os.path.join(self.golden_drives_dir, golden)):
                 node = xmpp.Node(tag="golden",
                                  attrs={
                                      "name":
                                      golden,
                                      "path":
                                      os.path.join(self.golden_drives_dir,
                                                   golden)
                                  })
                 nodes.append(node)
         reply = iq.buildReply("result")
         reply.setQueryPayload(nodes)
         self.entity.log.info("Info about golden sent.")
     except Exception as ex:
         reply = build_error_iq(self, ex, iq,
                                ARCHIPEL_ERROR_CODE_DRIVES_GETGOLDEN)
     return reply
示例#7
0
文件: network.py 项目: zenny/Archipel
 def iq_bridges(self, iq):
     """
     List all bridge names.
     @type iq: xmpp.Protocol.Iq
     @param iq: the received IQ
     @rtype: xmpp.Protocol.Iq
     @return: a ready to send IQ containing the result of the action
     """
     try:
         reply = iq.buildReply("result")
         bridges_list = commands.getoutput(
             "brctl show 2>/dev/null | grep -v -E '^[[:space:]]|bridge name' | cut -f 1"
         ).split("\n")
         bridges_list += commands.getoutput(
             "ovs-vsctl list-br 2>/dev/null").split("\n")
         bridges_list = sorted(set(bridges_list))
         bridges_names = []
         for bridge_name in bridges_list:
             if bridge_name:
                 bridge_node = xmpp.Node(tag="bridge",
                                         attrs={"name": bridge_name})
                 bridges_names.append(bridge_node)
         reply.setQueryPayload(bridges_names)
     except Exception as ex:
         reply = build_error_iq(self, ex, iq,
                                ARCHIPEL_ERROR_CODE_NETWORKS_BRIDGES)
     return reply
示例#8
0
文件: network.py 项目: zenny/Archipel
 def iq_get_names(self, iq):
     """
     List all virtual network names.
     @type iq: xmpp.Protocol.Iq
     @param iq: the received IQ
     @rtype: xmpp.Protocol.Iq
     @return: a ready to send IQ containing the result of the action
     """
     try:
         reply = iq.buildReply("result")
         active_networks_nodes = []
         actives_networks_names = self.get(inactive=False)["active"]
         for network_name in actives_networks_names:
             network = xmpp.Node(tag="network",
                                 attrs={"name": network_name})
             active_networks_nodes.append(network)
         reply.setQueryPayload(active_networks_nodes)
     except libvirt.libvirtError as ex:
         reply = build_error_iq(self,
                                ex,
                                iq,
                                ex.get_error_code(),
                                ns=ARCHIPEL_NS_LIBVIRT_GENERIC_ERROR)
     except Exception as ex:
         reply = build_error_iq(self, ex, iq,
                                ARCHIPEL_ERROR_CODE_NETWORKS_GETNAMES)
     return reply
示例#9
0
    def iq_jobs(self, iq):
        """
        Get jobs.
        @type iq: xmpp.Protocol.Iq
        @param iq: the received IQ
        @rtype: xmpp.Protocol.Iq
        @return: a ready to send IQ containing the result of the action
        """
        try:
            reply = iq.buildReply("result")
            nodes = []
            if hasattr(self.scheduler, "get_jobs"):
                jobs = self.scheduler.get_jobs()
            else:
                jobs = self.scheduler.jobs

            for job in jobs:
                job_node = xmpp.Node(tag="job",
                                     attrs={
                                         "action": str(job.args[0]),
                                         "uid": str(job.args[1]),
                                         "date": str(job.args[2]),
                                         "comment": job.args[3]
                                     })
                nodes.append(job_node)
            reply.setQueryPayload(nodes)
        except Exception as ex:
            reply = build_error_iq(self, ex, iq)
        return reply
示例#10
0
 def iq_get_installed_appliances(self, iq):
     """
     Get all installed appliances.
     @type iq: xmpp.Protocol.Iq
     @param iq: the sender request IQ
     @rtype: xmpp.Protocol.Iq
     @return: a ready-to-send IQ containing the results
     """
     reply = iq.buildReply("result")
     nodes = []
     try:
         self.cursor.execute(
             "SELECT save_path, name, description FROM vmcastappliances WHERE status=%d"
             % (ARCHIPEL_APPLIANCES_INSTALLED))
         for values in self.cursor:
             path, name, description = values
             node = xmpp.Node(tag="appliance",
                              attrs={
                                  "path": path,
                                  "name": name,
                                  "description": description
                              })
             nodes.append(node)
         reply.setQueryPayload(nodes)
     except Exception as ex:
         reply = build_error_iq(self, ex, iq,
                                ARCHIPEL_ERROR_CODE_VMCASTS_GETINSTALLED)
     return reply
示例#11
0
 def iq_get_appliance(self, iq):
     """
     Get the info about an appliances according to its uuid.
     @type iq: xmpp.Protocol.Iq
     @param iq: the sender request IQ
     @rtype: xmpp.Protocol.Iq
     @return: a ready-to-send IQ containing the results
     """
     reply = iq.buildReply("result")
     uuid = iq.getTag("query").getTag("archipel").getAttr("uuid")
     try:
         self.cursor.execute(
             "SELECT save_path, name, description FROM vmcastappliances WHERE uuid='%s'"
             % uuid)
         path, name, description = self.cursor.fetchone()
         node = xmpp.Node(tag="appliance",
                          attrs={
                              "path": path,
                              "name": name,
                              "description": description
                          })
         reply.setQueryPayload([node])
     except Exception as ex:
         reply = build_error_iq(self, ex, iq,
                                ARCHIPEL_ERROR_CODE_VMCASTS_GETAPPLIANCES)
     return reply
示例#12
0
文件: storage.py 项目: zenny/Archipel
 def iq_get(self, iq):
     """
     Get the virtual hard drives of the virtual machine.
     @type iq: xmpp.Protocol.Iq
     @param iq: the received IQ
     @rtype: xmpp.Protocol.Iq
     @return: a ready to send IQ containing the result of the action
     """
     try:
         disks = os.listdir(self.entity.folder)
         nodes = []
         for disk in disks:
             if self._is_file_a_drive(os.path.join(self.entity.folder, disk)):
                 diskPath = os.path.join(self.entity.folder, disk)
                 diskSize = os.path.getsize(diskPath)
                 diskInfo = subprocess.Popen([self.qemu_img_bin, "info", diskPath], stdout=subprocess.PIPE).communicate()[0].split("\n")
                 currentAttributes = {
                     "name": os.path.basename(os.path.splitext(disk)[0]),
                     "path": diskPath,
                     "format": diskInfo[1].split(": ")[1],
                     "virtualSize": diskInfo[2].split(" ")[3].replace("(", ""),
                     "diskSize": diskSize
                 }
                 if len(diskInfo) == 7:
                     currentAttributes["backingFile"] = os.path.basename(diskInfo[5].split()[2])
                 node = xmpp.Node(tag="disk", attrs=currentAttributes)
                 nodes.append(node)
         reply = iq.buildReply("result")
         reply.setQueryPayload(nodes)
         self.entity.log.info("Info about disks sent.")
     except Exception as ex:
         reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_DRIVES_GET)
     return reply
示例#13
0
    def become_central_agent(self):
        """
        triggered when becoming active central agent
        """
        self.is_central_agent = True
        self.manage_database()
        initial_keepalive = xmpp.Node("event",
                                      attrs={
                                          "type": "keepalive",
                                          "jid": self.jid
                                      })
        initial_keepalive.setAttr("force_update", "true")
        initial_keepalive.setAttr("salt", self.salt)
        initial_keepalive.setAttr("keepalive_interval",
                                  self.keepalive_interval)
        initial_keepalive.setAttr("hypervisor_timeout_threshold",
                                  self.hypervisor_timeout_threshold)

        if self.required_stats_xml:
            initial_keepalive.addChild(node=self.required_stats_xml)

        self.central_keepalive_pubsub.add_item(initial_keepalive)
        self.log.debug("CENTRALAGENT: initial keepalive sent")
        self.last_keepalive_sent = datetime.datetime.now()
        self.last_hyp_check = datetime.datetime.now()
        self.change_presence("", "Active")
示例#14
0
        def _on_centralagent_reply(vms):
            try:
                self.entity.log.debug(
                    "VMPARKING: We got %s entry from central db" % len(vms))
                reply = iq.buildReply("result")
                nodes = []
                for vm in vms:
                    try:
                        vm_node = xmpp.Node("virtualmachine",
                                            attrs={
                                                "uuid": vm["uuid"],
                                                "parker": vm["parker"],
                                                "date": vm["creation_date"],
                                                'name': vm['name']
                                            })
                        xmldef = xmpp.simplexml.NodeBuilder(
                            vm["domain"]).getDom()
                        xmldef.delChild("description")
                        vm_node.addChild(node=xmldef)
                        nodes.append(vm_node)
                    except:
                        self.entity.log.warning(
                            "VMPARKING: Error parsing entry %s" % vm)

                reply.setQueryPayload(nodes)
            except Exception as ex:
                reply = build_error_iq(self, ex, iq,
                                       ARCHIPEL_ERROR_CODE_VMPARK_LIST)
            self.entity.xmppclient.send(reply)
            raise xmpp.protocol.NodeProcessed
示例#15
0
    def iq_bridges(self, iq):
        """
        List all bridge names.
        @type iq: xmpp.Protocol.Iq
        @param iq: the received IQ
        @rtype: xmpp.Protocol.Iq
        @return: a ready to send IQ containing the result of the action
        """
        try:
            reply = iq.buildReply("result")
            bridges = []

            for std_bridge in commands.getoutput("brctl show 2>/dev/null | grep -v -E '^[[:space:]]|bridge name' | cut -f 1").split("\n"):
                if std_bridge:
                    bridges.append({"name": std_bridge, "type": "linux-bridge"})

            for ovs_bridge in commands.getoutput("ovs-vsctl list-br 2>/dev/null").split("\n"):
                if ovs_bridge:
                    bridges.append({"name": ovs_bridge, "type": "openvswitch"})

            bridges = sorted(bridges, key=lambda k: k["name"])

            bridges_list = []
            for bridge in bridges:
                if bridge.get("name", None) and bridge.get("type", None):
                    bridge_node = xmpp.Node(tag="bridge", attrs={"name": bridge["name"], "type": bridge["type"]})
                    bridges_list.append(bridge_node)

            reply.setQueryPayload(bridges_list)
        except Exception as ex:
            reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_NETWORKS_BRIDGES)
        return reply
示例#16
0
 def iq_get_logs(self, iq):
     """
     Read the hypervisor's log file.
     @type iq: xmpp.Protocol.Iq
     @param iq: the sender request IQ
     @rtype: xmpp.Protocol.Iq
     @return: a ready-to-send IQ containing the results
     """
     try:
         reply = iq.buildReply("result")
         limit = int(iq.getTag("query").getTag("archipel").getAttr("limit"))
         output = commands.getoutput("tail -n %d %s" %
                                     (limit, self.logfile))
         nodes = []
         for line in output.split("\n"):
             try:
                 infos = line.split("::")
                 log_node = xmpp.Node("log",
                                      attrs={
                                          "level": infos[0],
                                          "date": infos[1],
                                          "file": "",
                                          "method": ""
                                      })
                 log_node.setData(line)
                 nodes.append(log_node)
             except Exception as ex:
                 pass
         reply.setQueryPayload(nodes)
     except Exception as ex:
         print str(ex)
         reply = build_error_iq(self, ex, iq,
                                ARCHIPEL_ERROR_CODE_HEALTH_LOG)
     return reply
示例#17
0
    def become_central_agent(self):
        """
        triggered when becoming active central agent
        """
        self.is_central_agent = True
        self.manage_database()
        initial_keepalive = xmpp.Node("event",
                                      attrs={
                                          "type": "keepalive",
                                          "jid": self.jid
                                      })
        initial_keepalive.setAttr("force_update", "true")
        initial_keepalive.setAttr("salt", self.salt)
        now = datetime.datetime.now()
        now_string = now.strftime("%Y-%m-%d %H:%M:%S.%f")
        initial_keepalive.setAttr("central_agent_time", now_string)

        if self.required_stats_xml:

            initial_keepalive.addChild(node=self.required_stats_xml)

        self.central_keepalive_pubsub.add_item(initial_keepalive)
        self.log.debug("CENTRALAGENT: initial keepalive sent")
        self.last_keepalive_sent = datetime.datetime.now()
        self.last_hyp_check = datetime.datetime.now()
        self.change_presence("", "Active")
示例#18
0
 def iq_get_download_queue(self, iq):
     """
     Get the state of the download queue.
     @type iq: xmpp.Protocol.Iq
     @param iq: the sender request IQ
     @rtype: xmpp.Protocol.Iq
     @return: a ready-to-send IQ containing the results
     """
     reply = iq.buildReply("result")
     nodes = []
     try:
         for uuid, download in self.download_queue.items():
             dl = xmpp.Node(tag="download",
                            attrs={
                                "uuid": download.get_uuid(),
                                "name": download.get_name(),
                                "percentage": download.get_progress(),
                                "total": download.get_total_size()
                            })
             nodes.append(dl)
         reply.setQueryPayload(nodes)
     except Exception as ex:
         reply = build_error_iq(self, ex, iq,
                                ARCHIPEL_ERROR_CODE_VMCASTS_DOWNLOADQUEUE)
     return reply
示例#19
0
 def send_number(base_reply):
     n = 0
     for user in self.users:
         if only_humans and not user["type"] == "human":
             continue
         n = n + 1
     base_reply.setQueryPayload([xmpp.Node("users", attrs={"total": n})])
     self.entity.xmppclient.send(base_reply)
示例#20
0
 def send_users(base_reply):
     nodes = []
     bound_begin = page * self.user_page_size
     bound_end = bound_begin + self.user_page_size
     users = sorted(self.users, cmp=lambda x, y: cmp(x["jid"], y["jid"]))
     for user in users:
         if only_humans and not user["type"] == "human":
             continue
         nodes.append(xmpp.Node("user", attrs={"jid": user["jid"], "type": user["type"]}))
     base_reply.setQueryPayload(nodes[bound_begin:bound_end])
     self.entity.xmppclient.send(base_reply)
示例#21
0
    def handle_first_keepalive(self, keepalive_jid):
        """
        this is the first keepalive. We query hypervisors that have started somewhere else
        then we trigger method manage_persistence to start the vms.
        """
        vms_from_local_db = self.entity.get_vms_from_local_db()

        if len(vms_from_local_db) > 0:

            dbCommand = xmpp.Node(tag="event", attrs={"jid": self.entity.jid})

            for vm in vms_from_local_db:

                entryTag = xmpp.Node(tag="entry")
                uuid = xmpp.JID(vm["string_jid"]).getNode()
                entryTag.addChild("item", attrs={"key": "uuid", "value": uuid})
                dbCommand.addChild(node=entryTag)

            iq = xmpp.Iq(typ="set",
                         queryNS=ARCHIPEL_NS_CENTRALAGENT,
                         to=keepalive_jid)
            iq.getTag("query").addChild(
                name="archipel",
                attrs={"action": "read_vms_started_elsewhere"})
            iq.getTag("query").getTag("archipel").addChild(node=dbCommand)
            xmpp.dispatcher.ID += 1
            iq.setID("%s-%d" % (self.entity.jid.getNode(), xmpp.dispatcher.ID))

            def _read_vms_started_elsewhere_callback(conn, packed_vms):

                vms_started_elsewhere = self.unpack_entries(packed_vms)
                self.entity.manage_persistence(vms_from_local_db,
                                               vms_started_elsewhere)

            self.entity.xmppclient.SendAndCallForResponse(
                iq, _read_vms_started_elsewhere_callback)

        else:

            # update status to Online(0)
            self.entity.manage_persistence([], [])
示例#22
0
    def handle_first_keepalive(self, keepalive_jid):
        """
        this is the first keepalive. We query hypervisors that have vm entities somewhere else
        then we trigger method manage_persistence to instantiate vm entities.
        """
        vms_from_local_db = self.entity.get_vms_from_local_db()

        if len(vms_from_local_db) > 0:

            dbCommand = xmpp.Node(tag="event", attrs={"jid": self.entity.jid})

            for vm in vms_from_local_db:

                entryTag = xmpp.Node(tag="entry")
                uuid = xmpp.JID(vm["string_jid"]).getNode()
                entryTag.addChild("item", attrs={"key": "uuid", "value": uuid})
                dbCommand.addChild(node=entryTag)

            iq = xmpp.Iq(typ="set",
                         queryNS=ARCHIPEL_NS_CENTRALAGENT,
                         to=keepalive_jid)
            iq.getTag("query").addChild(
                name="archipel",
                attrs={"action": "get_existing_vms_instances"})
            iq.getTag("query").getTag("archipel").addChild(node=dbCommand)

            def _get_existing_vms_instances_callback(conn, packed_vms):

                existing_vms_entities = self.unpack_entries(packed_vms)
                self.entity.manage_persistence(vms_from_local_db,
                                               existing_vms_entities)

            self.entity.xmppclient.SendAndCallForResponse(
                iq, _get_existing_vms_instances_callback)

        else:

            # update status to Online(0)
            self.entity.manage_persistence()
示例#23
0
        def send_filtered_users(base_reply):
            nodes = []
            users = sorted(self.users, cmp=lambda x, y: cmp(x["jid"], y["jid"]))
            for user in users:
                if not user["jid"].upper().find(filterString.upper()) > -1:
                    continue
                nodes.append(xmpp.Node("user", attrs={"jid": user["jid"], "type": user["type"]}))
            base_reply.setQueryPayload(nodes)

            if self.entity.__class__.__name__ == "TNArchipelVirtualMachine":
                self.entity.hypervisor.xmppclient.send(base_reply)
            else:
                self.entity.xmppclient.send(base_reply)
示例#24
0
    def read_from_db(self, action, columns, where_statement, callback):
        """
        Send a select statement to central db.
        @type command: string
        @param command: the sql command to execute
        @type columns: string
        @param columns: the list of database columns to return
        @type where_statement: string
        @param where_statement: for database reads, provides "where" constraint
        """
        central_agent_jid = self.central_agent_jid()

        if central_agent_jid:

            # send an iq to central agent
            dbCommand = xmpp.Node(tag="event", attrs={"jid": self.entity.jid})

            if where_statement:
                dbCommand.setAttr("where_statement", where_statement)

            if columns:
                dbCommand.setAttr("columns", columns)

            self.entity.log.debug("CENTRALDB: central agent jid %s" %
                                  central_agent_jid)
            iq = xmpp.Iq(typ="set",
                         queryNS=ARCHIPEL_NS_CENTRALAGENT,
                         to=central_agent_jid)
            iq.getTag("query").addChild(name="archipel",
                                        attrs={"action": action})
            iq.getTag("query").getTag("archipel").addChild(node=dbCommand)
            xmpp.dispatcher.ID += 1
            iq.setID("%s-%d" % (self.entity.jid.getNode(), xmpp.dispatcher.ID))

            def _read_from_db_callback(conn, resp):

                self.entity.log.debug("CENTRALDB: reply to read statement %s" %
                                      resp)
                unpacked_entries = self.unpack_entries(resp)
                self.entity.log.debug("CENTRALDB: unpacked reply %s" %
                                      unpacked_entries)
                callback(unpacked_entries)

            self.entity.xmppclient.SendAndCallForResponse(
                iq, _read_from_db_callback)

        else:

            self.entity.log.warning(
                "CENTRALDB: cannot read from db because we have not detected any central agent"
            )
示例#25
0
 def iq_display(self, iq):
     """
     Get the VNC display used in the virtual machine.
     @type iq: xmpp.Protocol.Iq
     @param iq: the received IQ
     @rtype: xmpp.Protocol.Iq
     @return: a ready to send IQ containing the result of the action
     """
     reply = iq.buildReply("result")
     try:
         if not self.entity.domain:
             return iq.buildReply('ignore')
         ports = self.display()
         if not ports:
             payload = xmpp.Node("display", attrs={})
         else:
             payload = xmpp.Node("display", attrs={"type": ports["type"], "port": str(ports["direct"]), "proxy": str(ports["proxy"]), "host": self.entity.ipaddr, "onlyssl": str(ports["onlyssl"]), "supportssl": str(ports["supportssl"])})
         reply.setQueryPayload([payload])
     except libvirt.libvirtError as ex:
         reply = build_error_iq(self, ex, iq, ex.get_error_code(), ns=archipel.archipelLibvirtEntity.ARCHIPEL_NS_LIBVIRT_GENERIC_ERROR)
     except Exception as ex:
         reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_VM_VNC)
     return reply
示例#26
0
 def pack_entries(self, entries):
     """
     Pack the list of entries to send to remote entity.
     @rtype: list
     @return: list of xmpp nodes, one per entry
     @type entries: list
     @param entries: list of dict entities
     """
     packed_entries = []
     for entry in entries:
         entryTag = xmpp.Node(tag="entry")
         for key, value in entry.iteritems():
             entryTag.addChild("item", attrs={"key": key, "value": value})
         packed_entries.append(entryTag)
     return packed_entries
示例#27
0
        def _on_centralagent_reply(vms):
            try:
                self.entity.log.debug(
                    "VMPARKING: We got %s entry from central db" % len(vms))
                reply = iq.buildReply("result")
                parked_vms = []
                for vm in vms:
                    try:
                        parked_vms.append({
                            "info": {
                                "uuid": vm["uuid"],
                                "parker": vm["parker"],
                                "date": vm["creation_date"]
                            },
                            "domain":
                            xmpp.simplexml.NodeBuilder(vm["domain"]).getDom()
                        })
                    except:
                        self.entity.log.warning(
                            "VMPARKING: Error parsing entry %s" % vm)

                def sorting(a, b):
                    a_name = ""
                    b_name = ""
                    if a["domain"]:
                        a_name = a["domain"].getTag("name").getData()
                    if b["domain"]:
                        b_name = b["domain"].getTag("name").getData()
                    return cmp(a_name, b_name)

                parked_vms.sort(sorting)
                nodes = []
                for parked_vm in parked_vms:
                    vm_node = xmpp.Node("virtualmachine",
                                        attrs=parked_vm["info"])
                    if parked_vm["domain"] and parked_vm["domain"].getTag(
                            'description'):
                        parked_vm["domain"].delChild("description")
                    vm_node.addChild(node=parked_vm["domain"])
                    nodes.append(vm_node)
                reply.setQueryPayload(nodes)
            except Exception as ex:
                reply = build_error_iq(self, ex, iq,
                                       ARCHIPEL_ERROR_CODE_VMPARK_LIST)
            self.entity.xmppclient.send(reply)
            raise xmpp.protocol.NodeProcessed
示例#28
0
 def iq_get_nwfilters(self, iq):
     """
     List all existing libvirt network filters.
     @type iq: xmpp.Protocol.Iq
     @param iq: the received IQ
     @rtype: xmpp.Protocol.Iq
     @return: a ready to send IQ containing the result of the action
     """
     try:
         reply = iq.buildReply("result")
         nodes = []
         for nwfilter in self.getnwfilters():
             nodes.append(xmpp.Node("filter", attrs={"name": nwfilter}))
         reply.setQueryPayload(nodes)
     except Exception as ex:
         reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_NETWORKS_GETNWFILTERS)
     return reply
示例#29
0
 def iq_get_nics(self, iq):
     """
     List all existing networks cards on the hypervisor.
     @type iq: xmpp.Protocol.Iq
     @param iq: the received IQ
     @rtype: xmpp.Protocol.Iq
     @return: a ready to send IQ containing the result of the action
     """
     try:
         reply = iq.buildReply("result")
         nodes = []
         for n in self.getnics():
             nodes.append(xmpp.Node("nic", attrs={"name": n}))
         reply.setQueryPayload(nodes)
     except Exception as ex:
         reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_NETWORKS_GETNICS)
     return reply
示例#30
0
 def iq_get(self, iq):
     """
     Get all installed appliances.
     @type iq: xmpp.Protocol.Iq
     @param iq: the sender request IQ
     @rtype: xmpp.Protocol.Iq
     @return: a ready-to-send IQ containing the results
     """
     try:
         nodes = []
         reply = iq.buildReply("result")
         appliances = self.get()
         for appliance in appliances:
             node = xmpp.Node(tag="appliance", attrs=appliance)
             nodes.append(node)
         reply.setQueryPayload(nodes)
     except Exception as ex:
         reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_VMAPPLIANCES_GET)
     return reply