xendconfig.py

来自「xen虚拟机源代码安装包」· Python 代码 · 共 1,700 行 · 第 1/5 页

PY
1,700
字号
#===========================================================================# 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) 2006-2007 XenSource Ltd#============================================================================import loggingimport reimport timeimport typesfrom xen.xend import sxpfrom xen.xend import uuidfrom xen.xend import XendOptionsfrom xen.xend import XendAPIStorefrom xen.xend.XendPPCI import XendPPCIfrom xen.xend.XendDPCI import XendDPCIfrom xen.xend.XendError import VmErrorfrom xen.xend.XendDevices import XendDevicesfrom xen.xend.PrettyPrint import prettyprintstringfrom xen.xend.XendConstants import DOM_STATE_HALTEDfrom xen.xend.xenstore.xstransact import xstransactfrom xen.xend.server.BlktapController import blktap_disk_typesfrom xen.xend.server.netif import randomMACfrom xen.util.blkif import blkdev_name_to_number, blkdev_uname_to_filefrom xen.util import xsconstantsimport xen.util.auxbinlog = logging.getLogger("xend.XendConfig")log.setLevel(logging.WARN)"""XendConfig API  XendConfig will try to mirror as closely the Xen API VM Struct  with extra parameters for those options that are not supported."""def reverse_dict(adict):    """Return the reverse mapping of a dictionary."""    return dict([(v, k) for k, v in adict.items()])def bool0(v):    return v != '0' and v != 'False' and bool(v)# Recursively copy a data struct, scrubbing out VNC passwords.# Will scrub any dict entry with a key of 'vncpasswd' or any# 2-element list whose first member is 'vncpasswd'. It will# also scrub a string matching '(vncpasswd XYZ)'. Everything# else is no-op passthroughdef scrub_password(data):    if type(data) == dict or type(data) == XendConfig:        scrubbed = {}        for key in data.keys():            if key == "vncpasswd":                scrubbed[key] = "XXXXXXXX"            else:                scrubbed[key] = scrub_password(data[key])        return scrubbed    elif type(data) == list:        if len(data) == 2 and type(data[0]) == str and data[0] == 'vncpasswd':            return ['vncpasswd', 'XXXXXXXX']        else:            scrubbed = []            for entry in data:                scrubbed.append(scrub_password(entry))            return scrubbed    elif type(data) == tuple:        scrubbed = []        for entry in data:            scrubbed.append(scrub_password(entry))        return tuple(scrubbed)    elif type(data) == str:        return re.sub(r'\(vncpasswd\s+[^\)]+\)','(vncpasswd XXXXXX)', data)    else:        return data## CPU fields:## VCPUs_max    -- the maximum number of vcpus that this domain may ever have.#                 aka XendDomainInfo.getVCpuCount().# vcpus        -- the legacy configuration name for above.# max_vcpu_id  -- vcpus_number - 1.  This is given to us by Xen.## cpus         -- the list of pCPUs available to each vCPU.## vcpu_avail   -- a bitmap telling the guest domain whether it may use each of#                 its VCPUs.  This is translated to#                 <dompath>/cpu/<id>/availability = {online,offline} for use#                 by the guest domain.# VCPUs_live   -- the number of VCPUs currently up, as reported by Xen.  This#                 is changed by changing vcpu_avail, and waiting for the#                 domain to respond.## Mapping from XendConfig configuration keys to the old# legacy configuration keys that map directly.XENAPI_CFG_TO_LEGACY_CFG = {    'uuid': 'uuid',    'VCPUs_max': 'vcpus',    'cpus': 'cpus',    'name_label': 'name',    'actions_after_shutdown': 'on_poweroff',    'actions_after_reboot': 'on_reboot',    'actions_after_crash': 'on_crash',     'PV_bootloader': 'bootloader',    'PV_bootloader_args': 'bootloader_args',}LEGACY_CFG_TO_XENAPI_CFG = reverse_dict(XENAPI_CFG_TO_LEGACY_CFG)# Platform configuration keys and their types.XENAPI_PLATFORM_CFG_TYPES = {    'acpi': int,    'apic': int,    'boot': str,    'device_model': str,    'loader': str,    'display' : str,    'fda': str,    'fdb': str,    'keymap': str,    'isa' : int,    'localtime': int,    'monitor': int,    'nographic': int,    'pae' : int,    'rtc_timeoffset': int,    'serial': str,    'sdl': int,    'opengl': int,    'soundhw': str,    'stdvga': int,    'usb': int,    'usbdevice': str,    'hpet': int,    'vnc': int,    'vncconsole': int,    'vncdisplay': int,    'vnclisten': str,    'timer_mode': int,    'vncpasswd': str,    'vncunused': int,    'xauthority': str,    'pci': str,    'vhpt': int,    'guest_os_type': str,    'hap': int,}# Xen API console 'other_config' keys.XENAPI_CONSOLE_OTHER_CFG = ['vncunused', 'vncdisplay', 'vnclisten',                            'vncpasswd', 'type', 'display', 'xauthority',                            'keymap', 'opengl']# List of XendConfig configuration keys that have no direct equivalent# in the old world.XENAPI_CFG_TYPES = {    'uuid': str,    'name_label': str,    'name_description': str,    'user_version': str,    'is_a_template': bool0,    'resident_on': str,    'memory_static_min': int,  # note these are stored in bytes, not KB!    'memory_static_max': int,    'memory_dynamic_min': int,    'memory_dynamic_max': int,    'cpus': list,    'vcpus_params': dict,    'VCPUs_max': int,    'VCPUs_at_startup': int,    'VCPUs_live': int,    'actions_after_shutdown': str,    'actions_after_reboot': str,    'actions_after_crash': str,    'PV_bootloader': str,    'PV_kernel': str,    'PV_ramdisk': str,    'PV_args': str,    'PV_bootloader_args': str,    'HVM_boot_policy': str,    'HVM_boot_params': dict,    'PCI_bus': str,    'platform': dict,    'tools_version': dict,    'other_config': dict,    'target': int,    'security_label': str,    'pci': str,    'cpuid' : dict,    'cpuid_check' : dict,    'machine_address_size': int,}# List of legacy configuration keys that have no equivalent in the# Xen API, but are still stored in XendConfig.LEGACY_UNSUPPORTED_BY_XENAPI_CFG = [    # roundtripped (dynamic, unmodified)    'shadow_memory',    'vcpu_avail',    'features',    # read/write    'on_xend_start',    'on_xend_stop',    # read-only    'domid',    'start_time',    'cpu_time',    'online_vcpus',    # write-once    'cpu',    'cpus',]LEGACY_CFG_TYPES = {    'uuid':          str,    'name':          str,    'vcpus':         int,    'vcpu_avail':    long,    'memory':        int,    'shadow_memory': int,    'maxmem':        int,    'start_time':    float,    'cpu_time':      float,    'features':      str,    'localtime':     int,    'name':          str,    'on_poweroff':   str,    'on_reboot':     str,    'on_crash':      str,    'on_xend_stop':  str,    'on_xend_start': str,    'online_vcpus':  int,    'rtc/timeoffset': str,}# Values that should be stored in xenstore's /vm/<uuid> that is used# by Xend. Used in XendDomainInfo to restore running VM state from# xenstore.LEGACY_XENSTORE_VM_PARAMS = [    'uuid',    'name',    'vcpus',    'vcpu_avail',    'memory',    'shadow_memory',    'maxmem',    'start_time',    'name',    'on_poweroff',    'on_crash',    'on_reboot',    'on_xend_start',    'on_xend_stop',]#### Config Choices##CONFIG_RESTART_MODES = ('restart', 'destroy', 'preserve', 'rename-restart',                        'coredump-destroy', 'coredump-restart')CONFIG_OLD_DOM_STATES = ('running', 'blocked', 'paused', 'shutdown',                         'crashed', 'dying')class XendConfigError(VmError):    def __str__(self):        return 'Invalid Configuration: %s' % str(self.value)#### XendConfig Class (an extended dictionary)##class XendConfig(dict):    """ The new Xend VM Configuration.    Stores the configuration in xenapi compatible format but retains    import and export functions for SXP.    """    def __init__(self, filename = None, sxp_obj = None,                 xapi = None, dominfo = None):                dict.__init__(self)        self.update(self._defaults())        if filename:            try:                sxp_obj = sxp.parse(open(filename,'r'))                sxp_obj = sxp_obj[0]            except IOError, e:                raise XendConfigError("Unable to read file: %s" % filename)                if sxp_obj:            self._sxp_to_xapi(sxp_obj)            self._sxp_to_xapi_unsupported(sxp_obj)        elif xapi:            self.update_with_xenapi_config(xapi)        elif dominfo:            # output from xc.domain_getinfo            self._dominfo_to_xapi(dominfo, update_mem = True)        log.debug('XendConfig.init: %s' % scrub_password(self))        # validators go here        self.validate()    """ In time, we should enable this type checking addition. It is great        also for tracking bugs and unintended writes to XendDomainInfo.info    def __setitem__(self, key, value):        type_conv = XENAPI_CFG_TYPES.get(key)        if callable(type_conv):            try:                dict.__setitem__(self, key, type_conv(value))            except (ValueError, TypeError):                raise XendConfigError("Wrong type for configuration value " +                                      "%s. Expected %s" %                                      (key, type_conv.__name__))        else:            dict.__setitem__(self, key, value)    """

⌨️ 快捷键说明

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