项目介绍
我们的项目地址为 minicloud,这里的代码是001_create_vm.
项目依赖
sudo dnf install python3-devel libvirt-devel libvirt-client
XML解释
kvm中,虚拟机的定义是通过xml来定义的。完整的domain定义,我们可以从下文代码中看到
下面是对domain细节的解释
domain 在kvm中,我们把虚拟机称为domain
- name 虚拟机名字
- memory 内存数量
- vcpu cpu数量
os 操作系统
- arch 架构
- boot 启动设备
- clock 时钟
devices 设备
- emulator
- disk 磁盘
- interface 网络
- graphics 显示器
使用defineXML接口创建虚拟机
#!/usr/bin/env python3
import shutil
import os
from jinja2 import Template
import libvirt
import uuid
import random
xml_template = """
<domain type='kvm'>
<name>{{ name }}</name>
<memory>{{ memory }}</memory>
<vcpu>{{ cpu }}</vcpu>
<os>
<type arch="x86_64">hvm</type>
<boot dev="hd"/>
</os>
<clock sync="localtime"/>
<devices>
<emulator>/usr/bin/qemu-system-x86_64</emulator>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2' />
<source file='{{ image }}'/>
<target dev='hda'/>
</disk>
<interface type='network'>
<source network='default'/>
<mac address='{{ mac }}'/>
<model type='virtio' />
</interface>
<graphics type='vnc' port='-1' keymap='de'/>
</devices>
</domain>
"""
image_path = "/home/sin/vms/cirros-0.6.1-x86_64-disk.img"
disk_path = None
name = str(uuid.uuid4())
def random_mac():
mac = [0x00, 0x16, 0x3e, random.randint(0x00, 0x7f), random.randint(0x00, 0x7f), random.randint(0x00, 0x7f)]
return ":".join(map(lambda x: "%02x" % x, mac))
def copy_image_to_disk():
global disk_path
global name
disk_base_path = os.path.join("/home/sin/vms", name)
os.mkdir(disk_base_path)
disk_path = os.path.join(disk_base_path, "disk.img")
shutil.copyfile(image_path, disk_path)
def main():
conn = libvirt.open("qemu:///system")
copy_image_to_disk()
data = {
"name": name,
"cpu": 1,
"memory": 1024 * 128,
"image": disk_path,
"mac": random_mac()
}
template = Template(xml_template)
xml = template.render(**data)
conn.defineXML(xml)
main()
执行脚本成功
virsh
virsh命令是使用kvm的另一种方法, 我们下面做简单介绍
列出所有虚拟机
sudo virsh list