当前位置: 首页>>代码示例>>Python>>正文


Python vms.VMModel类代码示例

本文整理汇总了Python中wok.plugins.kimchi.model.vms.VMModel的典型用法代码示例。如果您正苦于以下问题:Python VMModel类的具体用法?Python VMModel怎么用?Python VMModel使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了VMModel类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: create

    def create(self, vmid, params):
        dev_name = params['name']
        dev_info = self.dev_model.lookup(dev_name)

        if dev_info['device_type'] == 'pci':
            taskid = AsyncTask(u'/plugins/kimchi/vms/%s/hostdevs/' %
                               VMModel.get_vm(vmid, self.conn).name(),
                               self._attach_pci_device,
                               {'vmid': vmid, 'dev_info': dev_info,
                                'lock': threading.RLock()}).id
            return self.task.lookup(taskid)

        with RollbackContext() as rollback:
            try:
                dev = self.conn.get().nodeDeviceLookupByName(dev_name)
                dev.dettach()
            except Exception:
                raise OperationFailed('KCHVMHDEV0005E', {'name': dev_name})
            else:
                rollback.prependDefer(dev.reAttach)

            rollback.commitAll()

        taskid = AsyncTask(u'/plugins/kimchi/vms/%s/hostdevs/' %
                           VMModel.get_vm(vmid, self.conn).name(),
                           '_attach_%s_device' % dev_info['device_type'],
                           {'vmid': vmid, 'dev_info': dev_info,
                            'lock': threading.RLock()}).id

        return self.task.lookup(taskid)
开发者ID:aiminickwong,项目名称:kimchi,代码行数:30,代码来源:vmhostdevs.py

示例2: create

    def create(self, vmid, params):
        dev_name = params['name']
        self._passthrough_device_validate(dev_name)
        dev_info = DeviceModel(conn=self.conn).lookup(dev_name)

        if dev_info['device_type'] == 'pci':
            taskid = add_task(u'/plugins/kimchi/vms/%s/hostdevs/' %
                              VMModel.get_vm(vmid, self.conn).name(),
                              self._attach_pci_device, self.objstore,
                              {'vmid': vmid, 'dev_info': dev_info})
            return self.task.lookup(taskid)

        with RollbackContext() as rollback:
            try:
                dev = self.conn.get().nodeDeviceLookupByName(dev_name)
                dev.dettach()
            except Exception:
                raise OperationFailed('KCHVMHDEV0005E', {'name': dev_name})
            else:
                rollback.prependDefer(dev.reAttach)

            rollback.commitAll()

        taskid = add_task(u'/plugins/kimchi/vms/%s/hostdevs/' %
                          VMModel.get_vm(vmid, self.conn).name(),
                          '_attach_%s_device' % dev_info['device_type'],
                          self.objstore, {'vmid': vmid, 'dev_info': dev_info})

        return self.task.lookup(taskid)
开发者ID:encrypt94,项目名称:kimchi,代码行数:29,代码来源:vmhostdevs.py

示例3: delete

    def delete(self, vmid, dev_name):
        dom = VMModel.get_vm(vmid, self.conn)
        xmlstr = dom.XMLDesc(0)
        root = objectify.fromstring(xmlstr)

        try:
            hostdev = root.devices.hostdev

        except AttributeError:
            raise NotFoundError('KCHVMHDEV0001E', {
                                'vmid': vmid, 'dev_name': dev_name})

        task_params = {
            'vmid': vmid,
            'dev_name': dev_name,
            'dom': dom,
            'hostdev': hostdev,
            'lock': threading.RLock(),
        }
        task_uri = u'/plugins/kimchi/vms/%s/hostdevs/%s' % (
            VMModel.get_vm(vmid, self.conn).name(),
            dev_name,
        )
        taskid = AsyncTask(task_uri, self._detach_device, task_params).id
        return self.task.lookup(taskid)
开发者ID:alinefm,项目名称:kimchi,代码行数:25,代码来源:vmhostdevs.py

示例4: create

    def create(self, vm_name, params={}):
        """Create a snapshot with the current domain state.

        The VM must be stopped and contain only disks with format 'qcow2';
        otherwise an exception will be raised.

        Parameters:
        vm_name -- the name of the VM where the snapshot will be created.
        params -- a dict with the following values:
            "name": The snapshot name (optional). If omitted, a default value
            based on the current time will be used.

        Return:
        A Task running the operation.
        """
        vir_dom = VMModel.get_vm(vm_name, self.conn)
        if DOM_STATE_MAP[vir_dom.info()[0]] != u'shutoff':
            raise InvalidOperation('KCHSNAP0001E', {'vm': vm_name})

        # if the VM has a non-CDROM disk with type 'raw', abort.
        for storage_name in self.vmstorages.get_list(vm_name):
            storage = self.vmstorage.lookup(vm_name, storage_name)
            type = storage['type']
            format = storage['format']

            if type != u'cdrom' and format != u'qcow2':
                raise InvalidOperation('KCHSNAP0010E', {'vm': vm_name,
                                                        'format': format})

        name = params.get('name', unicode(int(time.time())))

        task_params = {'vm_name': vm_name, 'name': name}
        taskid = add_task(u'/plugins/kimchi/vms/%s/snapshots/%s' % (vm_name,
                          name), self._create_task, self.objstore, task_params)
        return self.task.lookup(taskid)
开发者ID:Finn10111,项目名称:kimchi,代码行数:35,代码来源:vmsnapshots.py

示例5: _create_task

    def _create_task(self, cb, params):
        """Asynchronous function which actually creates the snapshot.

        Parameters:
        cb -- a callback function to signal the Task's progress.
        params -- a dict with the following values:
            "vm_name": the name of the VM where the snapshot will be created.
            "name": the snapshot name.
        """
        vm_name = params['vm_name']
        name = params['name']

        cb('building snapshot XML')
        root_elem = E.domainsnapshot()
        root_elem.append(E.name(name))
        xml = ET.tostring(root_elem, encoding='utf-8').decode('utf-8')

        try:
            cb('fetching snapshot domain')
            vir_dom = VMModel.get_vm(vm_name, self.conn)
            cb('creating snapshot')
            vir_dom.snapshotCreateXML(xml, 0)
        except (NotFoundError, OperationFailed, libvirt.libvirtError) as e:
            raise OperationFailed(
                'KCHSNAP0002E', {'name': name, 'vm': vm_name, 'err': str(e)}
            )

        cb('OK', True)
开发者ID:alinefm,项目名称:kimchi,代码行数:28,代码来源:vmsnapshots.py

示例6: update

    def update(self, vm, mac, params):
        dom = VMModel.get_vm(vm, self.conn)
        iface = self._get_vmiface(vm, mac)

        if iface is None:
            raise NotFoundError("KCHVMIF0001E", {'name': vm, 'iface': mac})

        # cannot change mac address in a running system
        if DOM_STATE_MAP[dom.info()[0]] != "shutoff":
            raise InvalidOperation('KCHVMIF0011E')

        # mac address is a required parameter
        if 'mac' not in params:
            raise MissingParameter('KCHVMIF0008E')

        # new mac address must be unique
        if self._get_vmiface(vm, params['mac']) is not None:
            raise InvalidParameter('KCHVMIF0009E',
                                   {'name': vm, 'mac': params['mac']})

        flags = 0
        if dom.isPersistent():
            flags |= libvirt.VIR_DOMAIN_AFFECT_CONFIG

        # remove the current nic
        xml = etree.tostring(iface)
        dom.detachDeviceFlags(xml, flags=flags)

        # add the nic with the desired mac address
        iface.mac.attrib['address'] = params['mac']
        xml = etree.tostring(iface)
        dom.attachDeviceFlags(xml, flags=flags)

        return [vm, params['mac']]
开发者ID:Drooids,项目名称:kimchi,代码行数:34,代码来源:vmifaces.py

示例7: lookup

    def lookup(self, vmid, dev_name):
        dom = VMModel.get_vm(vmid, self.conn)
        xmlstr = dom.XMLDesc(0)
        root = objectify.fromstring(xmlstr)
        try:
            hostdev = root.devices.hostdev
        except AttributeError:
            raise NotFoundError('KCHVMHDEV0001E', {
                                'vmid': vmid, 'dev_name': dev_name})

        for e in hostdev:
            deduced_name = DeviceModel.deduce_dev_name(e, self.conn)
            if deduced_name == dev_name:
                dev_info = self.dev_model.lookup(dev_name)
                return {
                    'name': dev_name,
                    'type': e.attrib['type'],
                    'product': dev_info.get('product', None),
                    'vendor': dev_info.get('vendor', None),
                    'multifunction': dev_info.get('multifunction', None),
                    'vga3d': dev_info.get('vga3d', None),
                }

        raise NotFoundError('KCHVMHDEV0001E', {
                            'vmid': vmid, 'dev_name': dev_name})
开发者ID:alinefm,项目名称:kimchi,代码行数:25,代码来源:vmhostdevs.py

示例8: delete

    def delete(self, vm_name, dev_name):
        try:
            bus_type = self.lookup(vm_name, dev_name)['bus']
            dom = VMModel.get_vm(vm_name, self.conn)
        except NotFoundError:
            raise

        if (bus_type not in HOTPLUG_TYPE and
                DOM_STATE_MAP[dom.info()[0]] != 'shutoff'):
            raise InvalidOperation('KCHVMSTOR0011E')

        try:
            disk = get_device_node(dom, dev_name)
            path = get_vm_disk_info(dom, dev_name)['path']
            if path is None or len(path) < 1:
                path = self.lookup(vm_name, dev_name)['path']
            # This has to be done before it's detached. If it wasn't
            #   in the obj store, its ref count would have been updated
            #   by get_disk_used_by()
            if path is not None:
                used_by = get_disk_used_by(self.objstore, self.conn, path)
            else:
                wok_log.error("Unable to decrement volume used_by on"
                              " delete because no path could be found.")
            dom.detachDeviceFlags(etree.tostring(disk),
                                  get_vm_config_flag(dom, 'all'))
        except Exception as e:
            raise OperationFailed("KCHVMSTOR0010E", {'error': e.message})

        if used_by is not None and vm_name in used_by:
            used_by.remove(vm_name)
            set_disk_used_by(self.objstore, path, used_by)
        else:
            wok_log.error("Unable to update %s:%s used_by on delete."
                          % (vm_name, dev_name))
开发者ID:MalleshKoti,项目名称:kimchi,代码行数:35,代码来源:vmstorages.py

示例9: update_mmio_guest

    def update_mmio_guest(self, vmid, is_attaching):
        dom = VMModel.get_vm(vmid, self.conn)
        # get the number of 3D graphic cards already attached to the guest
        # based on this number we will decide if the memory size will be
        # increased or not
        counter = self._count_3D_devices_attached(dom)
        if counter == 0 and is_attaching:
            return

        size = 0
        if is_attaching:
            # suppose this is the 3rd graphic card to be attached to the same
            # guest, counter will be 2+1 (2 existing + this attachment) times
            # 32G (0x80000000)
            size = hex((counter + 1) * WINDOW_SIZE_BAR)

        else:
            size = hex(counter * WINDOW_SIZE_BAR)

        # if the guest already has the xml file we will simply update the
        # value, otherwise we will add the new field
        new_xml = self._update_win_memory_size(dom, counter, size)
        if new_xml is None and is_attaching:
            new_xml = self._add_win_memory_size(dom, size)

        # update the XML
        if new_xml is not None:
            self.conn.get().defineXML(new_xml)
开发者ID:aiminickwong,项目名称:kimchi,代码行数:28,代码来源:vmhostdevs.py

示例10: _get_available_bus_address

 def _get_available_bus_address(self, bus_type, vm_name):
     if bus_type not in ['ide']:
         return dict()
     # libvirt limitation of just 1 ide controller
     # each controller have at most 2 buses and each bus 2 units.
     dom = VMModel.get_vm(vm_name, self.conn)
     disks = self.get_list(vm_name)
     valid_id = [('0', '0'), ('0', '1'), ('1', '0'), ('1', '1')]
     controller_id = '0'
     for dev_name in disks:
         disk = get_device_node(dom, dev_name)
         if disk.target.attrib['bus'] == 'ide':
             controller_id = disk.address.attrib['controller']
             bus_id = disk.address.attrib['bus']
             unit_id = disk.address.attrib['unit']
             if (bus_id, unit_id) in valid_id:
                 valid_id.remove((bus_id, unit_id))
                 continue
     if not valid_id:
         raise OperationFailed('KCHVMSTOR0014E',
                               {'type': 'ide', 'limit': 4})
     else:
         address = {'controller': controller_id,
                    'bus': valid_id[0][0], 'unit': valid_id[0][1]}
         return dict(address=address)
开发者ID:MalleshKoti,项目名称:kimchi,代码行数:25,代码来源:vmstorages.py

示例11: get_disk_used_by

def get_disk_used_by(objstore, conn, path):
    try:
        with objstore as session:
            try:
                used_by = session.get("storagevolume", path)["used_by"]
            except (KeyError, NotFoundError):
                wok_log.info("Volume %s not found in obj store." % path)
                used_by = []
                # try to find this volume in existing vm
                vms_list = VMsModel.get_vms(conn)
                for vm in vms_list:
                    dom = VMModel.get_vm(vm, conn)
                    storages = get_vm_disks(dom)
                    for disk in storages.keys():
                        d_info = get_vm_disk_info(dom, disk)
                        if path == d_info["path"]:
                            used_by.append(vm)
                try:
                    session.store("storagevolume", path, {"used_by": used_by}, get_kimchi_version())
                except Exception as e:
                    # Let the exception be raised. If we allow disks'
                    #   used_by to be out of sync, data corruption could
                    #   occour if a disk is added to two guests
                    #   unknowingly.
                    wok_log.error("Unable to store storage volume id in" " objectstore due error: %s", e.message)
                    raise OperationFailed("KCHVOL0017E", {"err": e.message})
    except Exception as e:
        # This exception is going to catch errors returned by 'with',
        # specially ones generated by 'session.store'. It is outside
        # to avoid conflict with the __exit__ function of 'with'
        raise OperationFailed("KCHVOL0017E", {"err": e.message})
    return used_by
开发者ID:madhawa,项目名称:kimchi,代码行数:32,代码来源:diskutils.py

示例12: delete

    def delete(self, vmid, dev_name):
        dom = VMModel.get_vm(vmid, self.conn)
        xmlstr = dom.XMLDesc(0)
        root = objectify.fromstring(xmlstr)

        try:
            hostdev = root.devices.hostdev
        except AttributeError:
            raise NotFoundError('KCHVMHDEV0001E',
                                {'vmid': vmid, 'dev_name': dev_name})

        pci_devs = [(DeviceModel.deduce_dev_name(e, self.conn), e)
                    for e in hostdev if e.attrib['type'] == 'pci']

        dev_model = DeviceModel(conn=self.conn)
        dev_info = dev_model.lookup(dev_name)
        is_3D_device = dev_model.is_device_3D_controller(dev_info)
        if is_3D_device and DOM_STATE_MAP[dom.info()[0]] != "shutoff":
            raise InvalidOperation('KCHVMHDEV0006E',
                                   {'name': dev_info['name']})

        for e in hostdev:
            if DeviceModel.deduce_dev_name(e, self.conn) == dev_name:
                xmlstr = etree.tostring(e)
                dom.detachDeviceFlags(
                    xmlstr, get_vm_config_flag(dom, mode='all'))
                if e.attrib['type'] == 'pci':
                    self._delete_affected_pci_devices(dom, dev_name, pci_devs)
                if is_3D_device:
                    devsmodel = VMHostDevsModel(conn=self.conn)
                    devsmodel.update_mmio_guest(vmid, False)
                break
        else:
            raise NotFoundError('KCHVMHDEV0001E',
                                {'vmid': vmid, 'dev_name': dev_name})
开发者ID:cclauss,项目名称:kimchi,代码行数:35,代码来源:vmhostdevs.py

示例13: _get_ips

    def _get_ips(self, vm, mac, network):
        ips = []

        # Return empty list if shutoff, even if leases still valid or ARP
        #   cache has entries for this MAC.
        conn = self.conn.get()
        dom = VMModel.get_vm(vm, self.conn)
        if DOM_STATE_MAP[dom.info()[0]] == "shutoff":
            return ips

        # An iface may have multiple IPs
        # An IP could have been assigned without libvirt.
        # First check the ARP cache.
        with open('/proc/net/arp') as f:
            ips = [line.split()[0] for line in f.xreadlines() if mac in line]

        # Some ifaces may be inactive, so if the ARP cache didn't have them,
        # and they happen to be assigned via DHCP, we can check there too.
        try:
            # Some type of interfaces may not have a network associated with
            net = conn.networkLookupByName(network)
            leases = net.DHCPLeases(mac)
            for lease in leases:
                ip = lease.get('ipaddr')
                if ip not in ips:
                    ips.append(ip)
        except libvirt.libvirtError:
            pass

        return ips
开发者ID:Drooids,项目名称:kimchi,代码行数:30,代码来源:vmifaces.py

示例14: delete

    def delete(self, vmid, dev_name):
        dom = VMModel.get_vm(vmid, self.conn)
        xmlstr = dom.XMLDesc(0)
        root = objectify.fromstring(xmlstr)

        try:
            hostdev = root.devices.hostdev
        except AttributeError:
            raise NotFoundError('KCHVMHDEV0001E',
                                {'vmid': vmid, 'dev_name': dev_name})

        pci_devs = [(DeviceModel.deduce_dev_name(e, self.conn), e)
                    for e in hostdev if e.attrib['type'] == 'pci']

        for e in hostdev:
            if DeviceModel.deduce_dev_name(e, self.conn) == dev_name:
                xmlstr = etree.tostring(e)
                dom.detachDeviceFlags(
                    xmlstr, get_vm_config_flag(dom, mode='all'))
                if e.attrib['type'] == 'pci':
                    self._delete_affected_pci_devices(dom, dev_name, pci_devs)
                break
        else:
            raise NotFoundError('KCHVMHDEV0001E',
                                {'vmid': vmid, 'dev_name': dev_name})
开发者ID:madhawa,项目名称:kimchi,代码行数:25,代码来源:vmhostdevs.py

示例15: test_vm_livemigrate_transient

    def test_vm_livemigrate_transient(self):
        inst = model.Model(libvirt_uri='qemu:///system',
                           objstore_loc=self.tmp_store)

        self.create_vm_test()

        with RollbackContext() as rollback:
            try:
                # removing cdrom because it is not shared storage and will make
                # the migration fail
                dev_list = self.inst.vmstorages_get_list('test_vm_migrate')
                self.inst.vmstorage_delete('test_vm_migrate',  dev_list[0])

                self.inst.vm_start('test_vm_migrate')

                # to make the VM transient, undefine it while it's running
                vm = VMModel.get_vm(
                    'test_vm_migrate',
                    LibvirtConnection('qemu:///system')
                )
                vm.undefine()

                task = inst.vm_migrate('test_vm_migrate',
                                       KIMCHI_LIVE_MIGRATION_TEST)
                inst.task_wait(task['id'])
                self.assertIn('test_vm_migrate', self.get_remote_vm_list())

                remote_conn = self.get_remote_conn()
                rollback.prependDefer(remote_conn.close)

                remote_vm = remote_conn.lookupByName('test_vm_migrate')
                self.assertFalse(remote_vm.isPersistent())

                remote_vm.destroy()
            except Exception, e:
                # Clean up here instead of rollback because if the
                # VM was turned transient and shut down it might
                # not exist already - rollback in this case  will cause
                # a QEMU error
                vm = VMModel.get_vm(
                    'test_vm_migrate',
                    LibvirtConnection('qemu:///system')
                )
                if vm.isPersistent():
                    vm.undefine()
                vm.shutdown()
                self.fail('Migration test failed: %s' % e.message)
开发者ID:louis-cao,项目名称:kimchi,代码行数:47,代码来源:test_livemigration.py


注:本文中的wok.plugins.kimchi.model.vms.VMModel类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。