xendconfig.py

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

PY
1,700
字号
                dev_uuid = cfg_xenapi.get('uuid', None)                if not dev_uuid:                    dev_uuid = uuid.createString()                dev_info['uuid'] = dev_uuid                target['devices'][dev_uuid] = (dev_type, dev_info)                target['vif_refs'].append(dev_uuid)                        elif dev_type in ('vbd', 'tap'):                dev_info['type'] = cfg_xenapi.get('type', 'Disk')                if dev_info['type'] == 'CD':                    old_vbd_type = 'cdrom'                else:                    old_vbd_type = 'disk'                                    dev_info['uname'] = cfg_xenapi.get('image', '')                dev_info['dev'] = '%s:%s' % (cfg_xenapi.get('device'),                                             old_vbd_type)                dev_info['bootable'] = int(cfg_xenapi.get('bootable', 0))                dev_info['driver'] = cfg_xenapi.get('driver', '')                dev_info['VDI'] = cfg_xenapi.get('VDI', '')                                    if cfg_xenapi.get('mode') == 'RW':                    dev_info['mode'] = 'w'                else:                    dev_info['mode'] = 'r'                dev_uuid = cfg_xenapi.get('uuid', None)                if not dev_uuid:                    dev_uuid = uuid.createString()                dev_info['uuid'] = dev_uuid                target['devices'][dev_uuid] = (dev_type, dev_info)                target['vbd_refs'].append(dev_uuid)                            elif dev_type == 'vtpm':                if cfg_xenapi.get('type'):                    dev_info['type'] = cfg_xenapi.get('type')                dev_uuid = cfg_xenapi.get('uuid', None)                if not dev_uuid:                    dev_uuid = uuid.createString()                dev_info['uuid'] = dev_uuid                dev_info['other_config'] = cfg_xenapi.get('other_config', {})                target['devices'][dev_uuid] = (dev_type, dev_info)                target['vtpm_refs'].append(dev_uuid)            elif dev_type == 'console':                dev_uuid = cfg_xenapi.get('uuid', None)                if not dev_uuid:                    dev_uuid = uuid.createString()                dev_info['uuid'] = dev_uuid                dev_info['protocol'] = cfg_xenapi.get('protocol', 'rfb')                console_other_config = cfg_xenapi.get('other_config', {})                dev_info['other_config'] = console_other_config                if dev_info['protocol'] == 'rfb':                    # collapse other config into devinfo for things                    # such as vncpasswd, vncunused, etc.                                        dev_info.update(console_other_config)                    dev_info['type'] = console_other_config.get('type', 'vnc')                     target['devices'][dev_uuid] = ('vfb', dev_info)                    target['console_refs'].append(dev_uuid)                    # if console is rfb, set device_model ensuring qemu                    # is invoked for pvfb services                    if 'device_model' not in target['platform']:                        target['platform']['device_model'] = \                            xen.util.auxbin.pathTo("qemu-dm")                    # Finally, if we are a pvfb, we need to make a vkbd                    # as well that is not really exposed to Xen API                    vkbd_uuid = uuid.createString()                    target['devices'][vkbd_uuid] = ('vkbd', {})                                    elif dev_info['protocol'] == 'vt100':                    # if someone tries to create a VT100 console                    # via the Xen API, we'll have to ignore it                    # because we create one automatically in                    # XendDomainInfo._update_consoles                    raise XendConfigError('Creating vt100 consoles via '                                          'Xen API is unsupported')            return dev_uuid        # no valid device to add        return ''    def phantom_device_add(self, dev_type, cfg_xenapi = None,                   target = None):        """Add a phantom tap device configuration in XenAPI struct format.        """        if target == None:            target = self                if dev_type not in XendDevices.valid_devices() and \           dev_type not in XendDevices.pseudo_devices():                    raise XendConfigError("XendConfig: %s not a valid device type" %                            dev_type)        if cfg_xenapi == None:            raise XendConfigError("XendConfig: device_add requires some "                                  "config.")        if cfg_xenapi:            log.debug("XendConfig.phantom_device_add: %s" % str(cfg_xenapi))         if cfg_xenapi:            dev_info = {}                        if dev_type in ('vbd', 'tap'):                if dev_type == 'vbd':                    dev_info['uname'] = cfg_xenapi.get('image', '')                    dev_info['dev'] = '%s:disk' % cfg_xenapi.get('device')                elif dev_type == 'tap':                    if cfg_xenapi.get('image').find('tap:') == -1:                        dev_info['uname'] = 'tap:qcow:%s' % cfg_xenapi.get('image')                    dev_info['dev'] =  '/dev/%s' % cfg_xenapi.get('device')                    dev_info['uname'] = cfg_xenapi.get('image')                dev_info['mode'] = cfg_xenapi.get('mode')                dev_info['backend'] = '0'                dev_uuid = cfg_xenapi.get('uuid', uuid.createString())                dev_info['uuid'] = dev_uuid                self['devices'][dev_uuid] = (dev_type, dev_info)                self['vbd_refs'].append(dev_uuid)                return dev_uuid        return ''    def pci_convert_sxp_to_dict(self, dev_sxp):        """Convert pci device sxp to dict        @param dev_sxp: device configuration        @type  dev_sxp: SXP object (parsed config)        @return: dev_config        @rtype: dictionary        """        # Parsing the device SXP's. In most cases, the SXP looks        # like this:        #        # [device, [vif, [mac, xx:xx:xx:xx:xx:xx], [ip 1.3.4.5]]]        #        # However, for PCI devices it looks like this:        #        # [device, [pci, [dev, [domain, 0], [bus, 0], [slot, 1], [func, 2]]]        #        # It seems the reasoning for this difference is because        # pciif.py needs all the PCI device configurations at        # the same time when creating the devices.        #        # To further complicate matters, Xen 2.0 configuration format        # uses the following for pci device configuration:        #        # [device, [pci, [domain, 0], [bus, 0], [dev, 1], [func, 2]]]        # For PCI device hotplug support, the SXP of PCI devices is        # extendend like this:        #        # [device, [pci, [dev, [domain, 0], [bus, 0], [slot, 1], [func, 2],        #                      [vslt, 0]],        #                [state, 'Initialising']]]        #        # 'vslt' shows the virtual hotplug slot number which the PCI device        # is inserted in. This is only effective for HVM domains.        #        # state 'Initialising' indicates that the device is being attached,        # while state 'Closing' indicates that the device is being detached.        #        # The Dict looks like this:        #        # { devs: [{domain: 0, bus: 0, slot: 1, func: 2, vslt: 0}],        #   states: ['Initialising'] }        dev_config = {}        pci_devs = []        for pci_dev in sxp.children(dev_sxp, 'dev'):            pci_dev_info = {}            for opt_val in pci_dev[1:]:                try:                    opt, val = opt_val                    pci_dev_info[opt] = val                except TypeError:                    pass                # append uuid for each pci device.                dpci_uuid = pci_dev_info.get('uuid', uuid.createString())                pci_dev_info['uuid'] = dpci_uuid            pci_devs.append(pci_dev_info)        dev_config['devs'] = pci_devs         pci_states = []        for pci_state in sxp.children(dev_sxp, 'state'):            try:                pci_states.append(pci_state[1])            except IndexError:                raise XendError("Error reading state while parsing pci sxp")        dev_config['states'] = pci_states        return dev_config    def console_add(self, protocol, location, other_config = {}):        dev_uuid = uuid.createString()        if protocol == 'vt100':            dev_info = {                'uuid': dev_uuid,                'protocol': protocol,                'location': location,                'other_config': other_config,            }            if 'devices' not in self:                self['devices'] = {}                        self['devices'][dev_uuid] = ('console', dev_info)            self['console_refs'].append(dev_uuid)            return dev_info        return {}    def console_update(self, console_uuid, key, value):        for dev_uuid, (dev_type, dev_info) in self['devices'].items():            if dev_uuid == console_uuid:                dev_info[key] = value                # collapse other_config into dev_info for things                # such as vncpasswd, vncunused, etc.                if key == 'other_config':                    for k in XENAPI_CONSOLE_OTHER_CFG:                        if k in dev_info and k not in value:                            del dev_info[k]                    dev_info.update(value)                break    def console_get_all(self, protocol):        if protocol == 'vt100':            consoles = [dinfo for dtype, dinfo in self['devices'].values()                        if dtype == 'console']            return [c for c in consoles if c.get('protocol') == protocol]        elif protocol == 'rfb':            vfbs = [dinfo for dtype, dinfo in self['devices'].values()                   if dtype == 'vfb']            # move all non-console key values to other_config before            # returning console config            valid_keys = ['uuid', 'location']            for vfb in vfbs:                other_config = {}                for key, val in vfb.items():                    if key not in valid_keys:                        other_config[key] = vfb[key]                    del vfb[key]                vfb['other_config'] = other_config                vfb['protocol'] = 'rfb'                                    return vfbs        else:            return []    def device_update(self, dev_uuid, cfg_sxp = [], cfg_xenapi = {}):        """Update an existing device with the new configuration.        @rtype: boolean        @return: Returns True if succesfully found and updated a device conf        """        if dev_uuid in self['devices'] and cfg_sxp:            if sxp.child0(cfg_sxp) == 'device':                            config = sxp.child0(cfg_sxp)            else:                config = cfg_sxp            dev_type, dev_info = self['devices'][dev_uuid]            if dev_type == 'pci' or dev_type == 'vscsi': # Special case for pci                pci_dict = self.pci_convert_sxp_to_dict(config)                pci_devs = pci_dict['devs']                # destroy existing XenAPI DPCI objects                for dpci_uuid in XendDPCI.get_by_VM(self['uuid']):                    XendAPIStore.deregister(dpci_uuid, "DPCI")                if dev_type != 'vscsi':                    # create XenAPI DPCI objects.                    for pci_dev in pci_devs:                        dpci_uuid = pci_dev.get('uuid')                        ppci_uuid = XendPPCI.get_by_sbdf(pci_dev['domain'],                                                         pci_dev['bus'],                                                         pci_dev['slot'],                                                         pci_dev['func'])                        if ppci_uuid is None:                            continue                        dpci_record = {                            'VM': self['uuid'],                            'PPCI': ppci_uuid,                            'hotplug_slot': pci_dev.get('vslot', 0)                        }                        XendDPCI(dpci_uuid, dpci_record)                self['devices'][dev_uuid] = (dev_type,                                             {'devs': pci_devs,                                              'uuid': dev_uuid})                return True                            for opt_val in config[1:]:                try:                    opt, val = opt_val                    dev_info[opt] = val                except (TypeError, ValueError):                    pass # no value for this config option            self['devices'][dev_uuid] = (dev_type, dev_info)            return True                elif dev_uuid in self['devices'] and cfg_xenapi:            dev_type, dev_info = self['devices'][dev_uuid]            for key, val in cfg_xenapi.items():                dev_info[key] = val            self['devices'][dev_uuid] = (dev_type, dev_info)        return False    def device_sxpr(self, dev_uuid = None, dev_type = None, dev_info = None, target = None):        """Get Device SXPR by either giving the device UUID or (type, config).        @rtype: list of lists        @return: device config sxpr        """        sxpr = []        if target == None:            target = self        if dev_uuid != None and dev_uuid in target['devices']:            dev_type, dev_info = target['devices'][dev_uuid]        if dev_type == None or dev_info == None:            raise XendConfigError("Required either UUID or device type and "                                  "configuration dictionary.")                    sxpr.append(dev_type)        if dev_type in ('console', 'vfb'):            config = [(opt, val) for opt, val in dev_info.items()   

⌨️ 快捷键说明

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