xendconfig.py

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

PY
1,700
字号
    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': {},            'memory_static_min': 0,            'memory_dynamic_min': 0,            'shadow_memory': 0,            'memory_static_max': 0,            'memory_dynamic_max': 0,            'devices': {},            'on_xend_start': 'ignore',            'on_xend_stop': 'ignore',            'cpus': [],            'VCPUs_max': 1,            'VCPUs_live': 1,            'VCPUs_at_startup': 1,            'vcpus_params': {},            'console_refs': [],            'vif_refs': [],            'vbd_refs': [],            'vtpm_refs': [],            'other_config': {},            'platform': {},            'target': 0,        }                return defaults    #    # Here we assume these values exist in the dict.    # If they don't we have a bigger problem, lets not    # try and 'fix it up' but acutually fix the cause ;-)    #    def _memory_sanity_check(self):        log.trace("_memory_sanity_check memory_static_min: %s, "                      "memory_static_max: %i, "                      "memory_dynamic_min: %i, "                       "memory_dynamic_max: %i",                      self["memory_static_min"],                      self["memory_static_max"],                      self["memory_dynamic_min"],                      self["memory_dynamic_max"])                if not self["memory_static_min"] <= self["memory_static_max"]:            raise XendConfigError("memory_static_min must be less " \                                  "than or equal to memory_static_max")         if not self["memory_static_min"] <= self["memory_dynamic_min"]:            raise XendConfigError("memory_static_min must be less " \                                  "than or equal to memory_dynamic_min")        if not self["memory_dynamic_max"] <= self["memory_static_max"]:            raise XendConfigError("memory_dynamic_max must be less " \                                  "than or equal to memory_static_max")        if not self["memory_dynamic_max"] > 0:            raise XendConfigError("memory_dynamic_max must be greater " \                                  "than zero")        if not self["memory_static_max"] > 0:            raise XendConfigError("memory_static_max must be greater " \                                  "than zero")    def _actions_sanity_check(self):        for event in ['shutdown', 'reboot', 'crash']:            if self['actions_after_' + event] not in CONFIG_RESTART_MODES:                raise XendConfigError('Invalid event handling mode: ' +                                      event)    def _vcpus_sanity_check(self):        if 'VCPUs_max' in self and 'vcpu_avail' not in self:            self['vcpu_avail'] = (1 << self['VCPUs_max']) - 1    def _uuid_sanity_check(self):        """Make sure UUID is in proper string format with hyphens."""        if 'uuid' not in self or not self['uuid']:            self['uuid'] = uuid.createString()        else:            self['uuid'] = uuid.toString(uuid.fromString(self['uuid']))    def _name_sanity_check(self):        if 'name_label' not in self:            self['name_label'] = 'Domain-' + self['uuid']    def _platform_sanity_check(self):        if 'keymap' not in self['platform'] and XendOptions.instance().get_keymap():            self['platform']['keymap'] = XendOptions.instance().get_keymap()        if self.is_hvm() or self.has_rfb():            if 'device_model' not in self['platform']:                self['platform']['device_model'] = xen.util.auxbin.pathTo("qemu-dm")        if self.is_hvm():            if 'timer_mode' not in self['platform']:                self['platform']['timer_mode'] = 0            if 'rtc_timeoffset' not in self['platform']:                self['platform']['rtc_timeoffset'] = 0            if 'hpet' not in self['platform']:                self['platform']['hpet'] = 0            if 'loader' not in self['platform']:                # Old configs may have hvmloader set as PV_kernel param                if self.has_key('PV_kernel') and self['PV_kernel'] != '':                    self['platform']['loader'] = self['PV_kernel']                    self['PV_kernel'] = ''                else:                    self['platform']['loader'] = "/usr/lib/xen/boot/hvmloader"                log.debug("Loader is %s" % str(self['platform']['loader']))            # Compatibility hack, can go away soon.            if 'soundhw' not in self['platform'] and \               self['platform'].get('enable_audio'):                self['platform']['soundhw'] = 'sb16'    def validate(self):        self._uuid_sanity_check()        self._name_sanity_check()        self._memory_sanity_check()        self._actions_sanity_check()        self._vcpus_sanity_check()        self._platform_sanity_check()    def _dominfo_to_xapi(self, dominfo, update_mem = False):        self['domid'] = dominfo['domid']        self['online_vcpus'] = dominfo['online_vcpus']        self['VCPUs_max'] = dominfo['max_vcpu_id'] + 1        if update_mem:            self['memory_dynamic_min'] = dominfo['mem_kb'] * 1024            self['memory_dynamic_max'] = dominfo['mem_kb'] * 1024            self['memory_static_min'] = 0            self['memory_static_max'] = dominfo['maxmem_kb'] * 1024            self._memory_sanity_check()        self['cpu_time'] = dominfo['cpu_time']/1e9        if dominfo.get('ssidref'):            ssidref = int(dominfo.get('ssidref'))            import xen.util.xsm.xsm as security            self['security_label'] = security.ssidref2security_label(ssidref)        self['shutdown_reason'] = dominfo['shutdown_reason']        # parse state into Xen API states        self['running'] = dominfo['running']        self['crashed'] = dominfo['crashed']        self['dying'] = dominfo['dying']        self['shutdown'] = dominfo['shutdown']        self['paused'] = dominfo['paused']        self['blocked'] = dominfo['blocked']        if 'name' in dominfo:            self['name_label'] = dominfo['name']        if 'handle' in dominfo:            self['uuid'] = uuid.toString(dominfo['handle'])                def parse_cpuid(self, cfg, field):       def int2bin(n, count=32):           return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)])       for input, regs in cfg[field].iteritems():           if not regs is dict:               cfg[field][input] = dict(regs)       cpuid = {}       for input in cfg[field]:           inputs = input.split(',')           if inputs[0][0:2] == '0x':               inputs[0] = str(int(inputs[0], 16))           if len(inputs) == 2:               if inputs[1][0:2] == '0x':                   inputs[1] = str(int(inputs[1], 16))           new_input = ','.join(inputs)           cpuid[new_input] = {} # new input           for reg in cfg[field][input]:               val = cfg[field][input][reg]               if val[0:2] == '0x':                   cpuid[new_input][reg] = int2bin(int(val, 16))               else:                   cpuid[new_input][reg] = val       cfg[field] = cpuid    def _parse_sxp(self, sxp_cfg):        """ Populate this XendConfig using the parsed SXP.        @param sxp_cfg: Parsed SXP Configuration        @type sxp_cfg: list of lists        @rtype: dictionary        @return: A dictionary containing the parsed options of the SXP.        """        cfg = {}        for key, typ in XENAPI_CFG_TYPES.items():            val = sxp.child_value(sxp_cfg, key)            if val is not None:                try:                    cfg[key] = typ(val)                except (ValueError, TypeError), e:                    log.warn('Unable to convert type value for key: %s' % key)        # Convert deprecated options to current equivalents.                restart = sxp.child_value(sxp_cfg, 'restart')        if restart:            if restart == 'onreboot':                cfg['on_poweroff'] = 'destroy'                cfg['on_reboot'] = 'restart'                cfg['on_crash'] = 'destroy'            elif restart == 'always':                for opt in ('on_poweroff', 'on_reboot', 'on_crash'):                    cfg[opt] = 'restart'            elif restart == 'never':                for opt in ('on_poweroff', 'on_reboot', 'on_crash'):                    cfg[opt] = 'never'                            else:                log.warn('Ignoring unrecognised value for deprecated option:'                         'restart = \'%s\'', restart)        # Handle memory, passed in as MiB        if sxp.child_value(sxp_cfg, "memory") != None:            cfg["memory"] = int(sxp.child_value(sxp_cfg, "memory"))        if sxp.child_value(sxp_cfg, "maxmem") != None:            cfg["maxmem"] = int(sxp.child_value(sxp_cfg, "maxmem"))                    # Convert scheduling parameters to vcpus_params        if 'vcpus_params' not in cfg:            cfg['vcpus_params'] = {}        cfg["vcpus_params"]["weight"] = \            int(sxp.child_value(sxp_cfg, "cpu_weight", 256))        cfg["vcpus_params"]["cap"] = \            int(sxp.child_value(sxp_cfg, "cpu_cap", 0))        # Only extract options we know about.        extract_keys = LEGACY_UNSUPPORTED_BY_XENAPI_CFG + \                  XENAPI_CFG_TO_LEGACY_CFG.values()                for key in extract_keys:            val = sxp.child_value(sxp_cfg, key)            if val != None:                try:                    cfg[key] = LEGACY_CFG_TYPES[key](val)                except KeyError:                    cfg[key] = val                except (TypeError, ValueError), e:                    log.warn("Unable to parse key %s: %s: %s" %                             (key, str(val), e))        if 'platform' not in cfg:            cfg['platform'] = {}        localtime = sxp.child_value(sxp_cfg, 'localtime')        if localtime is not None:            cfg['platform']['localtime'] = localtime        # Compatibility hack -- can go soon.        for key in XENAPI_PLATFORM_CFG_TYPES.keys():            val = sxp.child_value(sxp_cfg, "platform_" + key, None)            if val is not None:                self['platform'][key] = val        # Compatibility hack -- can go soon.        boot_order = sxp.child_value(sxp_cfg, 'HVM_boot')        if boot_order:            cfg['HVM_boot_policy'] = 'BIOS order'            cfg['HVM_boot_params'] = { 'order' : boot_order }               # Parsing the device SXP's.        cfg['devices'] = {}        for dev in sxp.children(sxp_cfg, 'device'):            config = sxp.child0(dev)            dev_type = sxp.name(config)            self.device_add(dev_type, cfg_sxp = config, target = cfg)        # Extract missing data from configuration entries        image_sxp = sxp.child_value(sxp_cfg, 'image', [])        if image_sxp:            image_vcpus = sxp.child_value(image_sxp, 'vcpus')            if image_vcpus != None:                try:                    if 'VCPUs_max' not in cfg:                        cfg['VCPUs_max'] = int(image_vcpus)                    elif cfg['VCPUs_max'] != int(image_vcpus):                        cfg['VCPUs_max'] = int(image_vcpus)                        log.warn('Overriding vcpus from %d to %d using image'                                 'vcpus value.', cfg['VCPUs_max'])                except ValueError, e:                    raise XendConfigError('integer expeceted: %s: %s' %                                          image_sxp, e)        # Deprecated cpu configuration        if 'cpu' in cfg:            if 'cpus' in cfg:                cfg['cpus'] = "%s,%s" % (str(cfg['cpu']), cfg['cpus'])            else:                cfg['cpus'] = str(cfg['cpu'])        # Convert 'cpus' to list of list of ints        cpus_list = []        if 'cpus' in cfg:            # Convert the following string to list of ints.            # The string supports a list of ranges (0-3),            # seperated by commas, and negation (^1).              # Precedence is settled by order of the string:            #    "0-3,^1"      -> [0,2,3]            #    "0-3,^1,1"    -> [0,1,2,3]            def cnv(s):                l = []                for c in s.split(','):                    if c.find('-') != -1:                        (x, y) = c.split('-')                        for i in range(int(x), int(y)+1):                            l.append(int(i))                    else:                        # remove this element from the list                         if c[0] == '^':                            l = [x for x in l if x != int(c[1:])]                        else:                            l.append(int(c))                return l                        if type(cfg['cpus']) == list:                if len(cfg['cpus']) > 0 and type(cfg['cpus'][0]) == list:                    # If sxp_cfg was created from config.sxp,                    # the form of 'cpus' is list of list of string.                    # Convert 'cpus' to list of list of ints.                    # Conversion examples:                    #    [['1']]               -> [[1]]                    #    [['0','2'],['1','3']] -> [[0,2],[1,3]]                    try:                        for c1 in cfg['cpus']:                            cpus = []

⌨️ 快捷键说明

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