xendconfig.py

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

PY
1,700
字号
                            for c2 in c1:                                cpus.append(int(c2))                            cpus_list.append(cpus)                    except ValueError, e:                        raise XendConfigError('cpus = %s: %s' % (cfg['cpus'], e))                else:                    # Conversion examples:                    #    ["1"]               -> [[1]]                    #    ["0,2","1,3"]       -> [[0,2],[1,3]]                    #    ["0-3,^1","1-4,^2"] -> [[0,2,3],[1,3,4]]                    try:                        for c in cfg['cpus']:                            cpus = cnv(c)                            cpus_list.append(cpus)                    except ValueError, e:                        raise XendConfigError('cpus = %s: %s' % (cfg['cpus'], e))                                if len(cpus_list) != cfg['vcpus']:                    raise XendConfigError('vcpus and the item number of cpus are not same')            else:                # Conversion examples:                #  vcpus=1:                #    "1"      -> [[1]]                #    "0-3,^1" -> [[0,2,3]]                #  vcpus=2:                #    "1"      -> [[1],[1]]                #    "0-3,^1" -> [[0,2,3],[0,2,3]]                try:                    cpus = cnv(cfg['cpus'])                    for v in range(0, cfg['vcpus']):                        cpus_list.append(cpus)                except ValueError, e:                    raise XendConfigError('cpus = %s: %s' % (cfg['cpus'], e))        else:            # Generation examples:            #  vcpus=1:            #    -> [[]]            #  vcpus=2:            #    -> [[],[]]            for v in range(0, cfg['vcpus']):                cpus_list.append(list())                cfg['cpus'] = cpus_list        # Parse cpuid        if 'cpuid' in cfg:            self.parse_cpuid(cfg, 'cpuid')        if 'cpuid_check' in cfg:            self.parse_cpuid(cfg, 'cpuid_check')        import xen.util.xsm.xsm as security        if security.on() == xsconstants.XS_POLICY_ACM:            from xen.util.acmpolicy import ACM_LABEL_UNLABELED            if not 'security' in cfg and sxp.child_value(sxp_cfg, 'security'):                cfg['security'] = sxp.child_value(sxp_cfg, 'security')            elif not cfg.get('security_label'):                cfg['security'] = [['access_control',                                     ['policy', security.get_active_policy_name() ],                                     ['label', ACM_LABEL_UNLABELED ]]]            if 'security' in cfg and not cfg.get('security_label'):                secinfo = cfg['security']                # The xm command sends a list formatted like this:                # [['access_control', ['policy', 'xm-test'],['label', 'red']],                #                     ['ssidref', 196611]]                policy = ""                label = ""                for idx in range(0, len(secinfo)):                    if secinfo[idx][0] == "access_control":                        for aidx in range(1, len(secinfo[idx])):                            if secinfo[idx][aidx][0] == "policy":                                policy = secinfo[idx][aidx][1]                            if secinfo[idx][aidx][0] == "label":                                label  = secinfo[idx][aidx][1]                cfg['security_label'] = \                    security.set_security_label(policy, label)                if not sxp.child_value(sxp_cfg, 'security_label'):                    del cfg['security']            sec_lab = cfg['security_label'].split(":")            if len(sec_lab) != 3:                raise XendConfigError("Badly formatted security label: %s"                                      % cfg['security_label'])        old_state = sxp.child_value(sxp_cfg, 'state')        if old_state:            for i in range(len(CONFIG_OLD_DOM_STATES)):                cfg[CONFIG_OLD_DOM_STATES[i]] = int(old_state[i] != '-')        return cfg        def _sxp_to_xapi(self, sxp_cfg):        """Read in an SXP Configuration object and        populate at much of the Xen API with valid values.        """        log.debug('_sxp_to_xapi(%s)' % scrub_password(sxp_cfg))        # _parse_sxp() below will call device_add() and construct devices.        # Some devices (currently only pci) may require VM's uuid, so        # setup self['uuid'] beforehand.        self['uuid'] = sxp.child_value(sxp_cfg, 'uuid', uuid.createString())        cfg = self._parse_sxp(sxp_cfg)        for key, typ in XENAPI_CFG_TYPES.items():            val = cfg.get(key)            if val is not None:                self[key] = typ(val)        # Convert parameters that can be directly mapped from        # the Legacy Config to Xen API Config                for apikey, cfgkey in XENAPI_CFG_TO_LEGACY_CFG.items():            try:                type_conv = XENAPI_CFG_TYPES.get(apikey)                if callable(type_conv):                    self[apikey] = type_conv(cfg[cfgkey])                else:                    log.warn("Unconverted key: " + apikey)                    self[apikey] = cfg[cfgkey]            except KeyError:                pass        # Lets try and handle memory correctly        MiB = 1024 * 1024        if "memory" in cfg:            self["memory_static_min"] = 0            self["memory_static_max"] = int(cfg["memory"]) * MiB            self["memory_dynamic_min"] = int(cfg["memory"]) * MiB            self["memory_dynamic_max"] = int(cfg["memory"]) * MiB                        if "maxmem" in cfg:                self["memory_static_max"] = int(cfg["maxmem"]) * MiB        self._memory_sanity_check()        def update_with(n, o):            if not self.get(n):                self[n] = cfg.get(o, '')        update_with('PV_bootloader',      'bootloader')        update_with('PV_bootloader_args', 'bootloader_args')        image_sxp = sxp.child_value(sxp_cfg, 'image', [])        if image_sxp:            self.update_with_image_sxp(image_sxp)        # Convert Legacy HVM parameters to Xen API configuration        for key in XENAPI_PLATFORM_CFG_TYPES.keys():            if key in cfg:                self['platform'][key] = cfg[key]        # set device references in the configuration        self['devices'] = cfg.get('devices', {})        self['console_refs'] = cfg.get('console_refs', [])        self['vif_refs'] = cfg.get('vif_refs', [])        self['vbd_refs'] = cfg.get('vbd_refs', [])        self['vtpm_refs'] = cfg.get('vtpm_refs', [])        # coalesce hvm vnc frame buffer with vfb config        if self.is_hvm() and int(self['platform'].get('vnc', 0)) != 0:            # add vfb device if it isn't there already            if not self.has_rfb():                dev_config = ['vfb']                dev_config.append(['type', 'vnc'])                # copy VNC related params from platform config to vfb dev conf                for key in ['vncpasswd', 'vncunused', 'vncdisplay',                            'vnclisten']:                    if key in self['platform']:                        dev_config.append([key, self['platform'][key]])                self.device_add('vfb', cfg_sxp = dev_config)    def has_rfb(self):        for console_uuid in self['console_refs']:            if self['devices'][console_uuid][1].get('protocol') == 'rfb':                return True            if self['devices'][console_uuid][0] == 'vfb':                return True        return False    def _sxp_to_xapi_unsupported(self, sxp_cfg):        """Read in an SXP configuration object and populate        values are that not related directly supported in        the Xen API.        """        log.debug('_sxp_to_xapi_unsupported(%s)' % scrub_password(sxp_cfg))        # Parse and convert parameters used to configure        # the image (as well as HVM images)        image_sxp = sxp.child_value(sxp_cfg, 'image', [])        if image_sxp:            image_type = sxp.name(image_sxp)            if image_type != 'hvm' and image_type != 'linux':                self['platform']['image_type'] = image_type                        for key in XENAPI_PLATFORM_CFG_TYPES.keys():                val = sxp.child_value(image_sxp, key, None)                if val is not None and val != '':                    self['platform'][key] = val                        notes = sxp.children(image_sxp, 'notes')            if notes:                self['notes'] = self.notes_from_sxp(notes[0])            self._hvm_boot_params_from_sxp(image_sxp)        # extract backend value                            backend = []        for c in sxp.children(sxp_cfg, 'backend'):            backend.append(sxp.name(sxp.child0(c)))        if backend:            self['backend'] = backend        # Parse and convert other Non Xen API parameters.        def _set_cfg_if_exists(sxp_arg):            val = sxp.child_value(sxp_cfg, sxp_arg)            if val != None:                if LEGACY_CFG_TYPES.get(sxp_arg):                    self[sxp_arg] = LEGACY_CFG_TYPES[sxp_arg](val)                else:                    self[sxp_arg] = val        _set_cfg_if_exists('shadow_memory')        _set_cfg_if_exists('features')        _set_cfg_if_exists('on_xend_stop')        _set_cfg_if_exists('on_xend_start')        _set_cfg_if_exists('vcpu_avail')                # Parse and store runtime configuration         _set_cfg_if_exists('start_time')        _set_cfg_if_exists('cpu_time')        _set_cfg_if_exists('shutdown_reason')        _set_cfg_if_exists('up_time')        _set_cfg_if_exists('status') # TODO, deprecated      def _get_old_state_string(self):        """Returns the old xm state string.        @rtype: string        @return: old state string        """        state_string = ''        for state_name in CONFIG_OLD_DOM_STATES:            on_off = self.get(state_name, 0)            if on_off:                state_string += state_name[0]            else:                state_string += '-'        return state_string    def update_config(self, dominfo):        """Update configuration with the output from xc.domain_getinfo().        @param dominfo: Domain information via xc.domain_getinfo()        @type dominfo: dict        """        self._dominfo_to_xapi(dominfo)        self.validate()    def update_with_xenapi_config(self, xapi):        """Update configuration with a Xen API VM struct        @param xapi: Xen API VM Struct        @type xapi: dict        """        log.debug('update_with_xenapi_config: %s' % scrub_password(xapi))        for key, val in xapi.items():            type_conv = XENAPI_CFG_TYPES.get(key)            if type_conv is None:                key = key.lower()                type_conv = XENAPI_CFG_TYPES.get(key)            if callable(type_conv):                self[key] = type_conv(val)            else:                self[key] = val        # XenAPI defines platform as a string-string map.  If platform        # configuration exists, convert values to appropriate type.        if 'platform' in xapi:            for key, val in xapi['platform'].items():                type_conv = XENAPI_PLATFORM_CFG_TYPES.get(key)                if type_conv is None:                    key = key.lower()                    type_conv = XENAPI_PLATFORM_CFG_TYPES.get(key)                    if callable(type_conv):                        self['platform'][key] = type_conv(val)                    else:                        self['platform'][key] = val                        self['vcpus_params']['weight'] = \            int(self['vcpus_params'].get('weight', 256))        self['vcpus_params']['cap'] = int(self['vcpus_params'].get('cap', 0))    def cpuid_to_sxp(self, sxpr, field):        regs_list = []        for input, regs in self[field].iteritems():            reg_list = []            for reg, val in regs.iteritems():                reg_list.append([reg, val])            regs_list.append([input, reg_list])        sxpr.append([field, regs_list])    def to_sxp(self, domain = None, ignore_devices = False, ignore = [],               legacy_only = True):        """ Get SXP representation of this config object.        Incompat: removed store_mfn, console_mfn        @keyword domain: (optional) XendDomainInfo to get extra information                         from such as domid and running devices.        @type    domain: XendDomainInfo        @keyword ignore: (optional) list of 'keys' that we do not want                         to export.        @type    ignore: list of strings        @rtype: list of list (SXP representation)        """        sxpr = ['domain']        # TODO: domid/dom is the same thing but called differently        #       depending if it is from xenstore or sxpr.        if domain.getDomid() is not None:            sxpr.append(['domid', domain.getDomid()])        if not legacy_only:            for name, typ in XENAPI_CFG_TYPES.items():                if name in self and self[name] not in (None, []):                    if typ == dict:                        s = self[name].items()

⌨️ 快捷键说明

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