📄 xendconfig.py
字号:
#===========================================================================# 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.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.XENAPI_PLATFORM_CFG = [ 'acpi', 'apic', 'boot', 'device_model', 'display', 'fda', 'fdb', 'keymap', 'isa', 'localtime', 'monitor', 'nographic', 'pae', 'rtc_timeoffset', 'serial', 'sdl', 'soundhw','stdvga', 'usb', 'usbdevice', 'vnc', 'vncconsole', 'vncdisplay', 'vnclisten', 'timer_mode', 'vncpasswd', 'vncunused', 'xauthority', 'pci', 'vhpt', 'guest_os_type' ]# Xen API console 'other_config' keys.XENAPI_CONSOLE_OTHER_CFG = ['vncunused', 'vncdisplay', 'vnclisten', 'vncpasswd', 'type', 'display', 'xauthority', 'keymap']# 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, 'security_label': str, 'pci': str,}# 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')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) """ def _defaults(self): defaults = { 'name_label': 'Domain-Unnamed', 'actions_after_shutdown': 'destroy', 'actions_after_reboot': 'restart', 'actions_after_crash': 'restart', 'actions_after_suspend': '', 'is_a_template': False, 'is_control_domain': False, 'features': '', 'PV_bootloader': '', 'PV_kernel': '', 'PV_ramdisk': '', 'PV_args': '', 'PV_bootloader_args': '', 'HVM_boot_policy': '', 'HVM_boot_params': {},
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -