Product SiteDocumentation Site

4.5.3. Memory / CPU Resources

CPU and memory resources can be set at the time the domain is created or dynamically while the domain is either active or inactive.
CPU resources are set at domain creation using tags in the XML definition of the domain. The hypervisor defines a limit on the number of virtual CPUs that may not be exceeded either at domain creation or at a later time. This maximum can be dependent on a number of resource and hypervisor limits. An example of the CPU XML specification follows.
<domain>
  ...
  <vcpu placement='static' cpuset="1-4,^3,6" current="1">2</vcpu>
  ...
</domain>
Memory resources are also set at domain creation using tags in the XML definition of the domain. Both the maximum and the current allocation of memory to the domain should be set. An example of the Memory XML specification follows.
<domain>
  ...
  <maxMemory slots='16' unit='KiB'>1524288</maxMemory>
  <memory unit='KiB'>524288</memory>
  <currentMemory unit='KiB'>524288</currentMemory>
  ...
</domain>
After the domain has been created the number of virtual CPUs can be increased via the setVcpus or the setVcpusFlags methods. The number CPUs may not exceed the hypervisor maximum discussed above.

Example 4.39. Set the number of maximum virtual cpus for a domain

# Example-29.py
#!/usr/bin/env python3
import sys
import libvirt

domName = 'Fedora22-x86_64-1'

conn = None
try:
    conn = libvirt.open("qemu:///system")
except libvirt.libvirtError as e:
    print(repr(e), file=sys.stderr)
    exit(1)

dom = conn.lookupByID(6)
if dom == None:
    print('Failed to find the domain '+domName, file=sys.stderr)
    exit(1)

dom.setVcpus(2)

conn.close()
exit(0)
Also after the domain has been created the amount of memory can be changes via the setMemory or the setMemoryFlags methods. The amount of memory should be expressed in kilobytes.

Example 4.40. Set the amount of memory for a domain

# Example-30.py
#!/usr/bin/env python3
import sys
import libvirt

domName = 'Fedora22-x86_64-1'

conn = None
try:
    conn = libvirt.open("qemu:///system")
except libvirt.libvirtError as e:
    print(repr(e), file=sys.stderr)
    exit(1)

dom = conn.lookupByID(6)
if dom == None:
    print('Failed to find the domain '+domName, file=sys.stderr)
    exit(1)

dom.setMemory(4096) # 4 GigaBytes

conn.close()
exit(0)
In addition to the setMemory method, the alternative method setMemoryFlags is also available.