准备:
1.确保你的linux平台搭建了kvm环境
2.下载libvirt-java-0.4.7.tar.gz 官方网站:http://libvirt.org/sources/java/
3.打开eclipse,新建工程,导入libvirt包
开发:
1.根据xml配置文件创建虚拟机
- public class Test {
- /**
- * @param args
- */
- public static void main(String[] args) {
- Connect conn = null;
- int flags = 0;
- try {
- conn = new Connect("qemu:///system", false);
- String dumpxml = "<domain type='kvm'>"+
- "<name>tt2</name>"+
- "<memory>524288</memory>"+
- "<currentMemory>524288</currentMemory>"+
- "<vcpu>1</vcpu>"+
- "<os>"+
- " <type arch='i686' machine='pc-0.11'>hvm</type>"+
- " <boot dev='hd'/>"+
- "</os>"+
- "<features>"+
- " <acpi/>"+
- " <apic/>"+
- " <pae/>"+
- "</features>"+
- "<clock offset='utc'/>"+
- "<on_poweroff>destroy</on_poweroff>"+
- "<on_reboot>restart</on_reboot>"+
- "<on_crash>restart</on_crash>"+
- "<devices>"+
- " <emulator>/usr/bin/qemu-kvm</emulator>"+
- " <disk type='file' device='disk'>"+
- " <driver name='qemu' cache='none'/>"+
- " <source file='/var/lib/libvirt/images/tt.img'/>"+
- " <target dev='hda' bus='ide'/>"+
- " </disk>"+
- " <interface type='network'>"+
- " <mac address='54:52:00:02:02:2c'/>"+
- " <source network='default'/>"+
- " </interface>"+
- " <serial type='pty'>"+
- " <target port='0'/>"+
- " </serial>"+
- " <console type='pty'>"+
- " <target port='0'/>"+
- " </console>"+
- " <input type='mouse' bus='ps2'/>"+
- " <graphics type='vnc' port='-1' autoport='yes' keymap='en-us'/>"+
- "</devices>"+
- "</domain>";
- Domain dm = null;
- Domain dm1 = conn.domainDefineXML(dumpxml);
- //Domain dm1 = conn.domainDefineXML(dumpxml); //创建一个域,但不启动
- //dm1.undefine(); //undefind一个域,如果活动,则不停止
- /****
- try{
- Domain dm1 =conn.domainLookupByName("tt2");
- }
- catch (LibvirtException e) {
- System.out.println("libvirt 错误" + e);
- // TODO: handle exception
- }
- if(dm!=null)
- {
- dm.undefine();
- }
- ****/
- /********
- Domain dm2 = conn.domainDefineXML(dumpxml);
- dm2.undefine();
- *******/
- } catch (LibvirtException e) { //LibvirtException 返回错误详细信息
- System.out.println("exception caught:" + e);
- System.out.println("获取的错误;" + e.getError());
- return;
- }
- System.out.println("Clean exit");
- }
- }
2 libvirt库函数说明
(1)
- conn = new Connect("qemu:///system",true)
- conn = new Connect("qemu:///system",false)
第一个是以只读的方式打开连接
第二个可以对domain进行写操作
(2)
- Domain dm1 = conn.domainDefineXML(dumpxml);
创建一个域, 但不启动
(3)
-
dm1.undefine();
undefind一个域,如果活动,则不停止
3.官方API文档:http://libvirt.org/sources/java/javadoc/
精彩科技工作室