本文整理汇总了Python中kimchi.model.vms.VMModel类的典型用法代码示例。如果您正苦于以下问题:Python VMModel类的具体用法?Python VMModel怎么用?Python VMModel使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了VMModel类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create
def create(self, vm, params):
conn = self.conn.get()
networks = conn.listNetworks() + conn.listDefinedNetworks()
if params["type"] == "network" and params["network"] not in networks:
raise InvalidParameter("KCHVMIF0002E",
{'name': vm, 'network': params["network"]})
dom = VMModel.get_vm(vm, self.conn)
if DOM_STATE_MAP[dom.info()[0]] != "shutoff":
raise InvalidOperation("KCHVMIF0003E")
macs = (iface.mac.get('address')
for iface in self.get_vmifaces(vm, self.conn))
while True:
params['mac'] = VMIfacesModel.random_mac()
if params['mac'] not in macs:
break
os_data = VMModel.vm_get_os_metadata(dom, self.caps.metadata_support)
os_distro, os_version = os_data
xml = get_iface_xml(params, conn.getInfo()[0], os_distro, os_version)
dom.attachDeviceFlags(xml, libvirt.VIR_DOMAIN_AFFECT_CURRENT)
return params['mac']
示例2: create
def create(self, vm_name, params):
dom = VMModel.get_vm(vm_name, self.conn)
if DOM_STATE_MAP[dom.info()[0]] != 'shutoff':
raise InvalidOperation('KCHCDROM0011E')
# Use device name passed or pick next
dev_name = params.get('dev', None)
if dev_name is None:
params['dev'] = self._get_storage_device_name(vm_name)
else:
devices = self.get_list(vm_name)
if dev_name in devices:
raise OperationFailed('KCHCDROM0004E', {'dev_name': dev_name,
'vm_name': vm_name})
# Path will never be blank due to API.json verification.
# There is no need to cover this case here.
path = params['path']
params['src_type'] = _check_cdrom_path(path)
# Check if path is an url
# Add device to VM
dev_xml = _get_storage_xml(params)
try:
conn = self.conn.get()
dom = conn.lookupByName(vm_name)
dom.attachDeviceFlags(dev_xml, libvirt.VIR_DOMAIN_AFFECT_CURRENT)
except Exception as e:
raise OperationFailed("KCHCDROM0008E", {'error': e.message})
return params['dev']
示例3: 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']]
示例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'/vms/%s/snapshots/%s' % (vm_name, name),
self._create_task, self.objstore, task_params)
return self.task.lookup(taskid)
示例5: _get_ref_cnt
def _get_ref_cnt(self, pool, name, path):
vol_id = '%s:%s' % (pool, name)
try:
with self.objstore as session:
try:
ref_cnt = session.get('storagevolume', vol_id)['ref_cnt']
except NotFoundError:
# Fix storage volume created outside kimchi scope
ref_cnt = 0
# try to find this volume in exsisted vm
vms = VMsModel.get_vms(self.conn)
for vm in vms:
dom = VMModel.get_vm(vm, self.conn)
storages = get_vm_disk_list(dom)
for disk in storages:
d_info = get_vm_disk(dom, disk)
if path == d_info['path']:
ref_cnt = ref_cnt + 1
session.store('storagevolume', vol_id,
{'ref_cnt': ref_cnt})
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 ref_cnt
示例6: create
def create(self, vm, params):
def randomMAC():
mac = [0x52, 0x54, 0x00, random.randint(0x00, 0x7F), random.randint(0x00, 0xFF), random.randint(0x00, 0xFF)]
return ":".join(map(lambda x: "%02x" % x, mac))
conn = self.conn.get()
networks = conn.listNetworks() + conn.listDefinedNetworks()
if params["type"] == "network" and params["network"] not in networks:
raise InvalidParameter("KCHVMIF0002E", {"name": vm, "network": params["network"]})
dom = VMModel.get_vm(vm, self.conn)
if DOM_STATE_MAP[dom.info()[0]] != "shutoff":
raise InvalidOperation("KCHVMIF0003E")
macs = (iface.mac.get("address") for iface in self.get_vmifaces(vm, self.conn))
mac = randomMAC()
while True:
if mac not in macs:
break
mac = randomMAC()
children = [E.mac(address=mac)]
("network" in params.keys() and children.append(E.source(network=params["network"])))
("model" in params.keys() and children.append(E.model(type=params["model"])))
attrib = {"type": params["type"]}
xml = etree.tostring(E.interface(*children, **attrib))
dom.attachDeviceFlags(xml, libvirt.VIR_DOMAIN_AFFECT_CURRENT)
return mac
示例7: _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')
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), e:
raise OperationFailed('KCHSNAP0002E',
{'name': name, 'vm': vm_name,
'err': e.message})
示例8: 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})
flags = 0
if dom.isPersistent():
flags |= libvirt.VIR_DOMAIN_AFFECT_CONFIG
if DOM_STATE_MAP[dom.info()[0]] != "shutoff":
flags |= libvirt.VIR_DOMAIN_AFFECT_LIVE
if iface.attrib['type'] == 'network' and 'network' in params:
iface.source.attrib['network'] = params['network']
xml = etree.tostring(iface)
dom.updateDeviceFlags(xml, flags=flags)
if 'model' in params:
iface.model.attrib["type"] = params['model']
xml = etree.tostring(iface)
dom.updateDeviceFlags(xml, flags=flags)
return mac
示例9: 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:
kimchi_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:
kimchi_log.error("Unable to update %s:%s used_by on delete."
% (vm_name, dev_name))
示例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_xml(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)
示例11: 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})
devsmodel = VMHostDevsModel(conn=self.conn)
pci_devs = [(devsmodel._deduce_dev_name(e), e) for e in hostdev
if e.attrib['type'] == 'pci']
for e in hostdev:
if devsmodel._deduce_dev_name(e) == 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})
示例12: create
def create(self, vm, params):
conn = self.conn.get()
networks = conn.listNetworks() + conn.listDefinedNetworks()
networks = map(lambda x: x.decode('utf-8'), networks)
if params['type'] == 'network':
network = params.get("network")
if network is None:
raise MissingParameter('KCHVMIF0007E')
if network not in networks:
raise InvalidParameter('KCHVMIF0002E',
{'name': vm, 'network': network})
macs = (iface.mac.get('address')
for iface in self.get_vmifaces(vm, self.conn))
# user defined customized mac address
if 'mac' in params and params['mac']:
# make sure it is unique
if params['mac'] in macs:
raise InvalidParameter('KCHVMIF0009E',
{'name': vm, 'mac': params['mac']})
# otherwise choose a random mac address
else:
while True:
params['mac'] = VMIfacesModel.random_mac()
if params['mac'] not in macs:
break
dom = VMModel.get_vm(vm, self.conn)
os_data = VMModel.vm_get_os_metadata(dom)
os_version, os_distro = os_data
xml = get_iface_xml(params, conn.getInfo()[0], os_distro, os_version)
flags = 0
if dom.isPersistent():
flags |= libvirt.VIR_DOMAIN_AFFECT_CONFIG
if DOM_STATE_MAP[dom.info()[0]] != "shutoff":
flags |= libvirt.VIR_DOMAIN_AFFECT_LIVE
dom.attachDeviceFlags(xml, flags)
return params['mac']
示例13: _attach_pci_device
def _attach_pci_device(self, vmid, dev_info):
self._validate_pci_passthrough_env()
dom = VMModel.get_vm(vmid, self.conn)
# Due to libvirt limitation, we don't support live assigne device to
# vfio driver.
driver = ('vfio' if DOM_STATE_MAP[dom.info()[0]] == "shutoff" and
self.caps.kernel_vfio else 'kvm')
# on powerkvm systems it must be vfio driver.
distro, _, _ = platform.linux_distribution()
if distro == 'IBM_PowerKVM':
driver = 'vfio'
# Attach all PCI devices in the same IOMMU group
dev_model = DeviceModel(conn=self.conn)
devs_model = DevicesModel(conn=self.conn)
affected_names = devs_model.get_list(
_passthrough_affected_by=dev_info['name'])
passthrough_names = devs_model.get_list(
_cap='pci', _passthrough='true')
group_names = list(set(affected_names) & set(passthrough_names))
pci_infos = [dev_model.lookup(dev_name) for dev_name in group_names]
pci_infos.append(dev_info)
# all devices in the group that is going to be attached to the vm
# must be detached from the host first
with RollbackContext() as rollback:
for pci_info in pci_infos:
try:
dev = self.conn.get().nodeDeviceLookupByName(
pci_info['name'])
dev.dettach()
except Exception:
raise OperationFailed('KCHVMHDEV0005E',
{'name': pci_info['name']})
else:
rollback.prependDefer(dev.reAttach)
rollback.commitAll()
device_flags = get_vm_config_flag(dom, mode='all')
with RollbackContext() as rollback:
for pci_info in pci_infos:
pci_info['detach_driver'] = driver
xmlstr = self._get_pci_device_xml(pci_info)
try:
dom.attachDeviceFlags(xmlstr, device_flags)
except libvirt.libvirtError:
kimchi_log.error(
'Failed to attach host device %s to VM %s: \n%s',
pci_info['name'], vmid, xmlstr)
raise
rollback.prependDefer(dom.detachDeviceFlags,
xmlstr, device_flags)
rollback.commitAll()
return dev_info['name']
示例14: _get_device_xml
def _get_device_xml(self, vm_name, dev_name):
# Get VM xml and then devices xml
dom = VMModel.get_vm(vm_name, self.conn)
xml = dom.XMLDesc(0)
devices = objectify.fromstring(xml).devices
disk = devices.xpath("./disk/target[@dev='%s']/.." % dev_name)
if not disk:
return None
return disk[0]
示例15: revert
def revert(self, vm_name, name):
try:
vir_dom = VMModel.get_vm(vm_name, self.conn)
vir_snap = self.get_vmsnapshot(vm_name, name)
vir_dom.revertToSnapshot(vir_snap, 0)
except libvirt.libvirtError, e:
raise OperationFailed('KCHSNAP0009E', {'name': name,
'vm': vm_name,
'err': e.message})