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

📄 xendconfig.py

📁 xen 3.2.2 源码
💻 PY
📖 第 1 页 / 共 5 页
字号:
            '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': {}        }                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():            # 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_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:            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 ints        if 'cpus' in cfg:            cpus = []            if type(cfg['cpus']) == list:                # If sxp_cfg was created from config.sxp,                # the form of 'cpus' is list of string.                # Convert 'cpus' to list of ints.                #    ['1']         -> [1]                #    ['0','2','3'] -> [0,2,3]                try:                    for c in cfg['cpus']:                        cpus.append(int(c))                                        cfg['cpus'] = cpus                except ValueError, e:                    raise XendConfigError('cpus = %s: %s' % (cfg['cpus'], e))            else:                # Convert 'cpus' string to list of ints                # 'cpus' 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]                try:                    for c in cfg['cpus'].split(','):                        if c.find('-') != -1:                                         (x, y) = c.split('-')                            for i in range(int(x), int(y)+1):                                cpus.append(int(i))                        else:                            # remove this element from the list                             if c[0] == '^':                                cpus = [x for x in cpus if x != int(c[1:])]                            else:                                cpus.append(int(c))                                        cfg['cpus'] = cpus                except ValueError, e:                    raise XendConfigError('cpus = %s: %s' % (cfg['cpus'], e))        import xen.util.xsm.xsm as security        if security.on():            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'])

⌨️ 快捷键说明

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