⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xenapi_create.py

📁 xen虚拟机源代码安装包
💻 PY
📖 第 1 页 / 共 3 页
字号:
#!/usr/bin/python#============================================================================# This library is free software; you can redistribute it and/or# modify it under the terms of version 2.1 of the GNU Lesser General Public# License as published by the Free Software Foundation.## This library is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU# Lesser General Public License for more details.## You should have received a copy of the GNU Lesser General Public# License along with this library; if not, write to the Free Software# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA#============================================================================# Copyright (C) 2007 Tom Wilkie <tom.wilkie@gmail.com>#============================================================================"""Domain creation using new XenAPI"""from xen.xm.main import server, get_default_SRfrom xml.dom.minidom import parse, getDOMImplementationfrom xml.parsers.xmlproc import xmlproc, xmlval, xmldtdfrom xen.xend import sxpfrom xen.xend.XendAPIConstants import XEN_API_ON_NORMAL_EXIT, \     XEN_API_ON_CRASH_BEHAVIOURfrom xen.xm.opts import OptionErrorfrom xen.util import xsconstantsimport xen.util.xsm.xsm as securityimport sysimport osimport tracebackimport redef log(_, msg):    #print "> " + msg    passDEBUG = 0def get_name_label(node):    name_node = node.getElementsByTagName("name")[0]    label_node = name_node.getElementsByTagName("label")[0]    return " ".join([child.nodeValue for child in label_node.childNodes])def get_name_description(node):    name_node = node.getElementsByTagName("name")[0]    description_node = name_node.getElementsByTagName("description")[0]    return " ".join([child.nodeValue for child in description_node.childNodes])def get_text_in_child_node(node, child):    tag_node = node.getElementsByTagName(child)[0]    return " ".join([child.nodeValue for child in tag_node.childNodes])def get_child_node_attribute(node, child, attribute):    tag_node = node.getElementsByTagName(child)[0]    return tag_node.attributes[attribute].valuedef get_child_nodes_as_dict(node, child_name,                            key_attribute_name,                            value_attribute_name):    return dict([(child.attributes[key_attribute_name].value,                  child.attributes[value_attribute_name].value)                 for child in node.getElementsByTagName(child_name)])def try_quietly(fn, *args):    try:        return fn(*args)    except:        return Noneclass xenapi_create:    def __init__(self):        self.DEFAULT_STORAGE_REPOSITORY = get_default_SR()        self.dtd = "/usr/share/xen/create.dtd"    def create(self, filename=None, document=None, skipdtd=False):        """        Create a domain from an XML file or DOM tree        """        if skipdtd:            print "Skipping DTD checks.  Dangerous!"                if filename is not None:            if not skipdtd:                self.check_dtd(filename)            document = parse(filename)        elif document is not None:            if not skipdtd:                self.check_dom_against_dtd(document)        self.check_doc(document)        vdis = document.getElementsByTagName("vdi")        vdi_refs_dict = self.create_vdis(vdis)        networks = document.getElementsByTagName("network")        network_refs_dict = self.create_networks(networks)                try:                vms = document.getElementsByTagName("vm")            return self.create_vms(vms, vdi_refs_dict, network_refs_dict)        except Exception, exn:            try_quietly(self.cleanup_vdis(vdi_refs_dict))            raise exn    # Methods to check xml file    # try to use dtd to check where possible    def check_dtd(self, file):        """        Check file against DTD.        Use this if possible as it gives nice        error messages        """        dtd = xmldtd.load_dtd(self.dtd)        parser = xmlproc.XMLProcessor()        parser.set_application(xmlval.ValidatingApp(dtd, parser))        parser.dtd = dtd        parser.ent = dtd        parser.parse_resource(file)    def check_dom_against_dtd(self, dom):        """        Check DOM again DTD.        Doesn't give as nice error messages.        (no location info)        """        dtd = xmldtd.load_dtd(self.dtd)        app = xmlval.ValidatingApp(dtd, self)        app.set_locator(self)        self.dom2sax(dom, app)    # Get errors back from ValidatingApp           def report_error(self, number, args=None):        self.errors = xmlproc.errors.english        try:            msg = self.errors[number]            if args != None:                msg = msg % args        except KeyError:            msg = self.errors[4002] % number # Unknown err msg :-)        print msg         sys.exit(-1)    # Here for compatibility with ValidatingApp    def get_line(self):        return -1    def get_column(self):        return -1    def dom2sax(self, dom, app):        """        Take a dom tree and tarverse it,        issuing SAX calls to app.        """        for child in dom.childNodes:            if child.nodeType == child.TEXT_NODE:                data = child.nodeValue                app.handle_data(data, 0, len(data))            else:                app.handle_start_tag(                    child.nodeName,                    self.attrs_to_dict(child.attributes))                self.dom2sax(child, app)                app.handle_end_tag(child.nodeName)    def attrs_to_dict(self, attrs):        return dict(attrs.items())         #    # Checks which cannot be done with dtd    #    def check_doc(self, doc):        vms = doc.getElementsByTagName("vm")        self.check_vms(vms)    def check_vms(self, vms):        map(self.check_vm, vms)    def check_vm(self, vm):        vifs = vm.getElementsByTagName("vif")        self.check_vifs(vifs)    def check_vifs(self, vifs):        map(self.check_vif, vifs)    def check_vif(self, vif):        pass    # Cleanup methods here    def cleanup_vdis(self, vdi_refs_dict):        map(self.cleanup_vdi, vdi_refs_dict.values())    def cleanup_vdi(self, vdi_ref):        server.xenapi.VDI.destroy(vdi_ref)    def cleanup_vms(self, vm_refs):        map(self.cleanup_vm, vm_refs)    def cleanup_vm(self, vm_ref):        server.xenapi.VM.destroy(vm_ref)    # Create methods here    def create_vdis(self, vdis):        log(DEBUG, "create_vdis")        return dict(map(self.create_vdi, vdis))    def create_vdi(self, vdi):        log(DEBUG, "create_vdi")        vdi_record = {            "name_label":       get_name_label(vdi),            "name_description": get_name_description(vdi),            "SR":               self.DEFAULT_STORAGE_REPOSITORY,              "virtual_size":     vdi.attributes["size"].value,            "type":             vdi.attributes["type"].value,            "sharable":         bool(vdi.attributes["sharable"].value),            "read_only":        bool(vdi.attributes["read_only"].value),            "other_config":     {"location":                vdi.attributes["src"].value}            }        key = vdi.attributes["name"].value        value = server.xenapi.VDI.create(vdi_record)                return (key, value)    def create_networks(self, networks):        log(DEBUG, "create_networks")        return dict(map(self.create_network, networks))    def create_network(self, network):        log(DEBUG, "create_network")        network_record = {            "name_label":       get_name_label(network),            "name_description": get_name_description(network),            "other_config":                get_child_nodes_as_dict(network, "other_config",                                        "key", "value"),            "default_netmask":  network.attributes["default_netmask"].value,            "default_gateway":  network.attributes["default_gateway"].value            }        key = network.attributes["name"].value        value = server.xenapi.network.create(network_record)        return (key, value)            def create_vms(self, vms, vdis, networks):        log(DEBUG, "create_vms")        return map(lambda vm: self.create_vm(vm, vdis, networks), vms)    def create_vm(self, vm, vdis, networks):        log(DEBUG, "create_vm")        vm_record = {            "name_label":                get_name_label(vm),            "name_description":                get_name_description(vm),            "user_version":                get_text_in_child_node(vm, "version"),            "is_a_template":                vm.attributes["is_a_template"].value == 'true',            "auto_power_on":                vm.attributes["auto_power_on"].value == 'true',            "memory_static_max":                get_child_node_attribute(vm, "memory", "static_max"),            "memory_static_min":                get_child_node_attribute(vm, "memory", "static_min"),            "memory_dynamic_max":                get_child_node_attribute(vm, "memory", "dynamic_max"),            "memory_dynamic_min":                get_child_node_attribute(vm, "memory", "dynamic_min"),            "VCPUs_params":                get_child_nodes_as_dict(vm, "vcpu_param", "key", "value"),            "VCPUs_max":                vm.attributes["vcpus_max"].value,            "VCPUs_at_startup":                vm.attributes["vcpus_at_startup"].value,            "actions_after_shutdown":                vm.attributes["actions_after_shutdown"].value,            "actions_after_reboot":                vm.attributes["actions_after_reboot"].value,            "actions_after_crash":                vm.attributes["actions_after_crash"].value,            "platform":                get_child_nodes_as_dict(vm, "platform", "key", "value"),            "other_config":                get_child_nodes_as_dict(vm, "other_config", "key", "value"),            "PV_bootloader":                "",            "PV_kernel":                "",            "PV_ramdisk":                "",            "PV_args":                "",            "PV_bootloader_args":                "",            "HVM_boot_policy":                "",            "HVM_boot_params":                {},            "PCI_bus":               ""            }        if vm.attributes.has_key("security_label"):            vm_record.update({                "security_label":                    vm.attributes["security_label"].value                })        if len(vm.getElementsByTagName("pv")) > 0:            vm_record.update({                "PV_bootloader":                    get_child_node_attribute(vm, "pv", "bootloader"),                "PV_kernel":                    get_child_node_attribute(vm, "pv", "kernel"),                "PV_ramdisk":                    get_child_node_attribute(vm, "pv", "ramdisk"),                "PV_args":                    get_child_node_attribute(vm, "pv", "args"),                "PV_bootloader_args":                    get_child_node_attribute(vm, "pv", "bootloader_args")

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -