介绍完libvirt Java API的部署工作:

《Windows下Libvirt Java API使用教程(一)- 开发环境部署》

接下来我们就介绍一下接口的使用和代码样例。

libvirt的管理单位是单个主机,所以探测和监控接口所能获取的信息的最大范围也是主机。所以先从主机入手,验证libvirt接口。主机(libvirt所在管理节点)探测相关接口验证代码如下:
  1. @Before
  2. public void init() {
  3. System.setProperty("jna.library.path",
  4. "D:/Git-Repo/git/libvirt-java/libvirt-java/src/test/java/kubi/coder/");
  5. try {
  6. xenConn = new Connect("xen+tcp://10.4.55.203/");
  7. // system代表拥有系统权限/session是用户权限
  8. kvmConn = new Connect("qemu+tcp://10.4.54.10/system");
  9. } catch (LibvirtException e) {
  10. e.printStackTrace();
  11. }
  12. }
  13. /**
  14. * 主机信息探测接口验证,验证可以获取的主机属性和监控指标,分别考虑Xen环境和KVM环境
  15. *
  16. *
  17. * @author lihzh
  18. * @date 2012-5-15 下午1:28:00
  19. */
  20. @Test
  21. public void testDetectHost() {
  22. // KVM
  23. doDetectHost(kvmConn);
  24. // XEN
  25. doDetectHost(xenConn);
  26. }
  27. /**
  28. * 执行探测主机测试函数
  29. *
  30. * @param conn
  31. * @author lihzh
  32. * @date 2012-5-15 下午1:37:37
  33. */
  34. private void doDetectHost(Connect conn) {
  35. try {
  36. // Returns the free memory for the connection
  37. // System.out.println("FreeMemory: " + conn.getFreeMemory());// 不支持
  38. // Returns the system hostname on which the hypervisor is running.
  39. // (the result of the gethostname(2) system call)
  40. // If we are connected to a remote system,
  41. // then this returns the hostname of the remote system
  42. System.out.println("Host name: " + conn.getHostName());
  43. // Gets the name of the Hypervisor software used.
  44. System.out.println("Type: " + conn.getType());
  45. // Gets the version level of the Hypervisor running. This may work
  46. // only with hypervisor call, i.e. with priviledged access to the
  47. // hypervisor, not with a Read-Only connection. If the version can't
  48. // be extracted by lack of capacities returns 0.
  49. // Returns:
  50. // major * 1,000,000 + minor * 1,000 + release
  51. System.out.println(conn.getVersion());
  52. NodeInfo nodeInfo = conn.nodeInfo();
  53. System.out.println("the number of active CPUs: " + nodeInfo.cpus);
  54. System.out.println("number of core per socket: " + nodeInfo.cores);
  55. System.out.println("memory size in kilobytes: " + nodeInfo.memory);
  56. System.out.println("expected CPU frequency: " + nodeInfo.mhz);
  57. System.out.println("string indicating the CPU model: "
  58. + nodeInfo.model);
  59. System.out.println("the number of NUMA cell, 1 for uniform: "
  60. + nodeInfo.nodes);
  61. System.out.println("number of CPU socket per node: "
  62. + nodeInfo.sockets);
  63. System.out.println("number of threads per core: "
  64. + nodeInfo.threads);
  65. System.out
  66. .println("the total number of CPUs supported but not necessarily active in the host.: "
  67. + nodeInfo.maxCpus());
  68. // for (String interName : conn.listInterfaces()) {
  69. // System.out.println(interName);
  70. // } 不支持
  71. // Provides the list of names of defined interfaces on this host
  72. // for (String interName : conn.listDefinedInterfaces()) {
  73. // System.out.println(interName);
  74. // } // 不支持
  75. // Lists the active networks.
  76. for (String networkName : conn.listNetworks()) {
  77. System.out.println("Network name: " + networkName);
  78. }
  79. // Lists the names of the network filters
  80. for (String networkFilterName : conn.listNetworkFilters()) {
  81. System.out.println("Network filter name: " + networkFilterName);
  82. }
  83. System.out.println(conn.getCapabilities());
  84. } catch (LibvirtException e) {
  85. e.printStackTrace();
  86. }
  87. }

分别在KVM和XEN环境下测试了libvirt接口,测试结果如下:

Host name: s5410
Type: QEMU
9001
the number of active CPUs: 64
number of core per socket: 8
memory size in kilobytes: 49444896
expected CPU frequency: 2131
string indicating the CPU model: x86_64
the number of NUMA cell, 1 for uniform: 1
number of CPU socket per node: 4
number of threads per core: 2
the total number of CPUs supported but not necessarily active in the host.: 64
Network name: hello
Network name: default
Network filter name: no-other-l2-traffic
Network filter name: allow-dhcp
...
<capabilities>
<host>
<uuid>30b940dd-f79a-21a2-82d5-ddc1b1b4a7e4</uuid>
<cpu>
<arch>x86_64</arch>
<model>core2duo</model>
<topology sockets='4' cores='8' threads='2'/>
<feature name='lahf_lm'/>
<feature name='rdtscp'/>
...
</cpu>
<migration_features>
<live/>
<uri_transports>
<uri_transport>tcp</uri_transport>
</uri_transports>
</migration_features>
</host>
<guest>
<os_type>hvm</os_type>
<arch name='i686'>
<wordsize>32</wordsize>
<emulator>/usr/libexec/qemu-kvm</emulator>
<machine>rhel5.4.0</machine>
<machine canonical='rhel5.4.0'>pc</machine>
<machine>rhel5.4.4</machine>
<machine>rhel5.5.0</machine>
<machine>rhel5.6.0</machine>
<domain type='qemu'>
</domain>
<domain type='kvm'>
<emulator>/usr/libexec/qemu-kvm</emulator>
</domain>
</arch>
<features>
<cpuselection/>
<pae/>
<nonpae/>
<acpi default='on' toggle='yes'/>
<apic default='on' toggle='no'/>
</features>
</guest>
...
</capabilities>
Host name: s55203
Type: Xen
3001000
the number of active CPUs: 32
number of core per socket: 8
memory size in kilobytes: 50276352
expected CPU frequency: 1995
string indicating the CPU model: x86_64
the number of NUMA cell, 1 for uniform: 1
number of CPU socket per node: 2
number of threads per core: 2
the total number of CPUs supported but not necessarily active in the host.: 32
Network name: default
Network filter name: allow-dhcp-server
Network filter name: qemu-announce-self-rarp
...
<capabilities>
<host>
<cpu>
<arch>x86_64</arch>
<features>
<vmx/>
</features>
</cpu>
<migration_features>
<live/>
<uri_transports>
<uri_transport>xenmigr</uri_transport>
</uri_transports>
</migration_features>
</host>
<guest>
<os_type>xen</os_type>
<arch name='x86_64'>
<wordsize>64</wordsize>
<emulator>/usr/lib64/xen/bin/qemu-dm</emulator>
<machine>xenpv</machine>
<domain type='xen'>
</domain>
</arch>
</guest>
... 
</capabilities>

说明:

注1:标注不支持的,是在当前环境当前libvirt版本下,运行会报错的接口。

  unsupported in sys interface

注2:名词解释

hvm:
gives similar information but when running a 32 bit OS fully virtualized with Xen using the hvm support。

numa:
For processors that support hyperthreading, this is the number of hyperthreads
they have per core.  On a machine that doesn't support hyperthreading, this
will be 1.


说实话,这么多信息中,笔者关注的不多,有很多甚至说不出其代表的含义,笔者关注只是cpu的个数,核心数,内存总量等直观信息。有就足以。
看完了主机,再看看虚拟机。一个虚拟化环境中的核心资源自然是虚拟机,所以其属性和信息也自然多很多,上测试代码:

  1. /**
  2. * 测试探测虚拟机接口
  3. *
  4. * @author lihzh
  5. * @date 2012-5-16 上午11:14:20
  6. */
  7. @Test
  8. public void testDetectDomains() {
  9. // KVM
  10. doDetectDomains(kvmConn);
  11. // XEN
  12. doDetectDomains(xenConn);
  13. }
  14. /**
  15. * 执行探测虚拟机测试函数
  16. *
  17. * @param conn
  18. * @author lihzh
  19. * @date 2012-5-16 上午11:15:27
  20. */
  21. private void doDetectDomains(Connect conn) {
  22. try {
  23. // Lists the active domains.(列出所有处于启动(激活)状态的虚拟机的id)
  24. for (int activeDomId : conn.listDomains()) {
  25. System.out.println("Active vm id: " + activeDomId);
  26. // 根据Id,探测各个虚拟机的详细信息
  27. Domain domain = conn.domainLookupByID(activeDomId);
  28. // Gets the hypervisor ID number for the domain
  29. System.out.println("Domain id: " + domain.getID());
  30. // Gets the public name for this domain
  31. System.out.println("Domain name: " + domain.getName());
  32. // Gets the type of domain operation system.
  33. System.out.println("Domain os type: " + domain.getOSType());
  34. // Gets the UUID for this domain as string.
  35. System.out.println("Domain uuid: " + domain.getUUIDString());
  36. // Retrieve the maximum amount of physical memory allocated to a
  37. // domain.
  38. System.out.println("Domain max memory: "
  39. + domain.getMaxMemory());
  40. // Provides the maximum number of virtual CPUs supported for the
  41. // guest VM. If the guest is inactive, this is basically the
  42. // same as virConnectGetMaxVcpus. If the guest is running this
  43. // will reflect the maximum number of virtual CPUs the guest was
  44. // booted with.
  45. System.out.println("Domain max vcpu: " + domain.getMaxVcpus());
  46. // Provides an XML description of the domain. The description
  47. // may be
  48. // reused later to relaunch the domain with createLinux().
  49. System.out.println("Domain xml description: "
  50. + domain.getXMLDesc(0));
  51. System.out.println("Domain maxMen allowed: "
  52. + domain.getInfo().maxMem);
  53. System.out.println("Domain memory: " + domain.getInfo().memory);
  54. // domain.getJobInfo()
  55. // 不支持
  56. System.out.println("Domain state: " + domain.getInfo().state);
  57. // Provides a boolean value indicating whether the network is
  58. // configured to be automatically started when the host machine
  59. // boots.
  60. System.out.println("Domain network autostart: "
  61. + domain.getAutostart());
  62. // Extracts information about virtual CPUs of this domain
  63. for (VcpuInfo vcpuInfo : domain.getVcpusInfo()) {
  64. System.out.println("cpu: " + vcpuInfo.cpu);
  65. System.out.println("cpu time: " + vcpuInfo.cpuTime);
  66. System.out.println("cpu number: " + vcpuInfo.number);
  67. System.out.println("cpu state: " + vcpuInfo.state);
  68. }
  69. // 如果是KVM环境
  70. if (conn.getURI().startsWith("qemu")) {
  71. // This function returns block device (disk) stats for block
  72. // devices attached to the domain
  73. DomainBlockInfo blockInfo = domain
  74. .blockInfo("/opt/awcloud/instance/admin/"
  75. + domain.getName() + "/disk");
  76. System.out.println("Disk Capacity: "
  77. + blockInfo.getCapacity());
  78. System.out.println("Disk allocation: "
  79. + blockInfo.getAllocation());
  80. System.out.println("Disk physical: "
  81. + blockInfo.getPhysical());
  82. DomainBlockStats blockStats = domain.blockStats("vda");
  83. // 磁盘读取请求总数
  84. System.out.println("read request num: " + blockStats.rd_req);
  85. // 磁盘读取总bytes数
  86. System.out.println("read request num: " + blockStats.rd_bytes);
  87. // 磁盘写入请求总数
  88. System.out.println("read request num: " + blockStats.wr_req);
  89. // 磁盘写入总bytes数
  90. System.out.println("read request num: " + blockStats.wr_bytes);
  91. }
  92. }
  93. // 列出所有停止态的虚拟机
  94. for (String name : conn.listDefinedDomains()) {
  95. System.out.println("Inactive domain name: " + name);
  96. }
  97. } catch (LibvirtException e) {
  98. e.printStackTrace();
  99. }
  100. }

循环较多,摘取部分结果如下:

Active vm id: 53
Domain id: 53
Domain name: i-546A099E
Domain os type: hvm
Domain uuid: e608560a-2c03-8e48-2e60-d0d01693f530
Domain max memory: 147456
Domain max vcpu: 1
Domain xml description: <domain type='xen' id='53'>
  <name>i-546A099E</name>
  <uuid>e608560a-2c03-8e48-2e60-d0d01693f530</uuid>
  <memory>131072</memory>
  <currentMemory>131072</currentMemory>
  <vcpu>1</vcpu>
  <os>
    <type>hvm</type>
    <loader>/usr/lib/xen/boot/hvmloader</loader>
    <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/lib64/xen/bin/qemu-dm</emulator>
    <disk type='file' device='disk'>
      <driver name='file'/>
      <source file='/opt/awcloud/instance/admin/i-546A099E/disk'/>
      <target dev='hda' bus='ide'/>
    </disk>
    <disk type='file' device='disk'>
      <driver name='file'/>
      <source file='/opt/awcloud/instance/admin/i-546A099E/disk2'/>
      <target dev='hdb' bus='ide'/>
    </disk>
    <interface type='bridge'>
      <mac address='d0:0d:54:6a:09:9e'/>
      <source bridge='xenbr0'/>
      <script path='vif-bridge'/>
      <target dev='vif53.0'/>
    </interface>
    <serial type='file'>
      <source path='/opt/awcloud/instance/admin/i-546A099E/console.log'/>
      <target port='0'/>
    </serial>
    <console type='file'>
      <source path='/opt/awcloud/instance/admin/i-546A099E/console.log'/>
      <target port='0'/>
    </console>
    <input type='tablet' bus='usb'/>
    <input type='mouse' bus='ps2'/>
    <graphics type='vnc' port='17237' autoport='no'/>
  </devices>
</domain>
Domain maxMen allowed: 147456
Domain memory: 139140
Domain state: VIR_DOMAIN_BLOCKED
Domain network autostart: false
cpu: 31
cpu time: 2225977676675
cpu number: 0
cpu state: VIR_VCPU_BLOCKED
Domain network autostart: false
Inactive domain name: i-46A70811
Inactive domain name: i-38C20705
Inactive domain name: i-498E09B2
Inactive domain name: null
Inactive domain name: null
Inactive domain name: null
Inactive domain name: null
Inactive domain name: null


 

结果分析:
结果中基本包含了一个虚拟机组成的全部元素信息。如果你想做一个监控系统,你可以发现这里有:

虚拟机的名字
虚拟机的Id
虚拟机的内存大小
虚拟CPU个数
虚拟机磁盘文件信息,磁盘文件的大小。甚至包括log等信息。
虚拟磁盘读写速率。
虚拟机网络设备信息。Mac地址,设备类型等。
虚拟机网卡读写速率。


基本可以满足一个监控系统的需求。
说明一下上面的测试代码。libvirt Java API的入口基本都是通过Connect这个类,也就是首先建立与被管理主机之间的连接:

  1. Connect kvmConn = new Connect("qemu+tcp://10.4.54.10/system");

然后通过该连接获取信息:

  1. conn.listDomains()

一个接口的如果需要接受参数:

  1. conn.domainLookupByID(activeDomId)

肯定可以从其他的接口返回中找到答案:

  1. for (int activeDomId : conn.listDomains())

只是有的获取的直接,有可能需要解析xml格式的返回值来获取需要参数值。比如:disk的paht和interface的path。
最后再简单介绍一下管控接口:

  1. /**
  2. * 测试虚拟机的简单操作
  3. *
  4. * @author lihzh
  5. * @date 2012-5-16 下午3:35:43
  6. */
  7. @Test
  8. public void testControlVM() {
  9. try {
  10. Domain domain = kvmConn.domainLookupByID(8);
  11. System.out.println("Domain state: " + domain.getInfo().state);
  12. domain.suspend();
  13. System.out.println("Domain state: " + domain.getInfo().state);
  14. for (int i = 0; i < 5; i++) {
  15. System.out.println("wait for: " + (5 - i));
  16. Thread.sleep(1000);
  17. }
  18. System.out.println("Resume vm.");
  19. domain.resume();
  20. System.out.println("Domain state: " + domain.getInfo().state);
  21. } catch (LibvirtException e) {
  22. e.printStackTrace();
  23. } catch (InterruptedException e) {
  24. e.printStackTrace();
  25. }
  26. }

该用例主要测试了虚拟机的挂起和恢复操作。这类操作是比较简单的(因为无需参数)。一个复杂系统肯定需要包括虚拟机创建等操作。libvirt主要通过xml表述来创建资源,首先需要生成被创建虚拟机的完整描述,然后传递给创建的方法即可。描述的格式?呵呵,自然是上面测试结果给出的数据了。有兴趣的,大家可以自己尝试一下。libvirt的文档,还不完善,不过对于创建这样重要的功能,还是给出了说明。大家也可以下载官方的手册作为参考。

好了,相对于VMware、Xenserver等虚拟化平台的SDK,libvirt的Java API还是比较简单的,上手很快,结构很简单。当然,功能上可能还是有所欠缺,信息量上,没有其他的那么充足。基于XML的方式操作资源,减少了接口的个数,使调用更直接,但是对开发人员却增加了困难。不过仍不失为一个不错的虚拟机环境操作的API,尤其是针对KVM/XEN的环境来说,可谓不二的选择。

转载于:https://blog.51cto.com/mushiqianmeng/865174

Windows下Libvirt Java API使用教程(二)- 接口使用说明相关推荐

  1. Windows下Libvirt Java API使用教程(三)- TLS认证访问和动态链接文件依赖

    之前已经介绍过了libvirt api的上手使用方式: <Windows下Libvirt Java API使用教程(二)- 接口使用说明> <Windows下Libvirt Java ...

  2. Windows下使用Java API操作HDFS的常用方法

    场景 Windows下配置Hadoop的Java开发环境以及用Java API操作HDFS: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/det ...

  3. 基于Windows下处理Java错误:编码GBK的不可映射字符的解决方案

    基于Windows下处理Java错误:编码GBK的不可映射字符的解决方案 最近在研究Java,涉及命令行编译,使用notepad++编辑器,然后使用javac编译: 之前的几个文件没有中文的内容,都没 ...

  4. 基于Windows下Anaconda创建python虚拟环境教程

    基于Windows下Anaconda创建python虚拟环境教程 Anaconda是目前最流行的数据科学平台以及现代机器学习的基础.同时Anaconda 也是一个Python的发行版,专注于人工智能, ...

  5. windows下配置java

    WINDOWS下配置JAVA环境变量 JAVA需要的环境变量: JAVA需要配置的环境变量有三,分别是java_home环境变量.path环境变量和classpath环境变量. JAVA环境变量的意义 ...

  6. Windows下MySql主从配置实战教程

    Windows下MySql主从配置实战教程 MySql的主从配置教程 主库MySql的安装 1.MySQL的下载 2.MySQL配置文件的编写 3.初始化数据库 4.安装服务 5.启动MySql 6. ...

  7. 红米路由器ac2100怎样设置ipv6_【路由刷机】红米小米 AC2100 Windows下刷Padavan固件小小白教程、升级固件...

    [路由刷机]红米小米 AC2100 Windows下刷Padavan固件小小白教程.升级固件 2020-05-05 16:13:26 378点赞 3195收藏 424评论 你是AMD Yes党?还是i ...

  8. windows下使用java -jar运行jar包报错:Unable to open nested jar file BOT-INF/lib/geronimo-javamail_1.4_spec-1.

    windows下使用java -jar命令运行jar包报错问题:Unable to open nested jar file 'BOT-INF/lib/geronimo-javamail_1.4_sp ...

  9. Windows下右键新建.md文件教程(转)

    Windows下右键新建.md文件教程 转载自Keavnn'Blog,并有些许修正 原本创建.md文件需要首先打开markdown文本编辑器,如Typora,或者新建.txt文件然后修改后缀名,本文介 ...

最新文章

  1. python del函数_python del函数是什么以及如何使用?
  2. 词法分析-中文分词技术-正向最大匹配法与逆向最大匹配法
  3. (深入理解计算机系统) bss段,data段、text段、堆(heap)和栈(stack)(C/C++存储类型总结)(内存管理)
  4. 外星人入侵 python 飞船位置_《python从入门到实践》项目一:外星人入侵
  5. mysql 多久备份一次_教你如何通过一次单击自动备份mysql数据库
  6. 4.2 使用pytorch搭建VGG网络
  7. 【编程题目】输入一个已经按升序排序过的数组和一个数字,在数组中查找两个数,使得它们的和正好是输入的那个数字。...
  8. Sherman-Morrison公式及其应用
  9. vue请求本地json数据
  10. 基于FFmpeg的封装格式MP4(TS)
  11. Python命令行模式下调试程序
  12. tl494cn逆变器电路图_TL494CN逆变器
  13. 微型计算机是以微处理器为基础,在计算机中以微处理器为核心组成的微型计算机属于第几代计算机...
  14. encode decode 使用指南
  15. 项目知识管理体系指南阅读(2)
  16. 全连接网络实现Fashion数据集学习/预测
  17. 获取股票简单数据:腾讯、新浪、东方财富。。。
  18. [我可怜的诺基亚3110c!]
  19. 【Linux】基本系统维护命令
  20. 两种微型水泵介绍——微型电磁泵和微型隔膜泵

热门文章

  1. K155ID1辉光管驱动芯片功能测试
  2. 时间到,考试结束。请同学们交卷......
  3. 2021年春季学期-信号与系统-第三次作业参考答案-第一道题
  4. 使用AD5933测量元器件的谐振特性
  5. 波形的转换与信号处理
  6. 超详细的Java常用时间操作工具类
  7. java优先队列的入队函数,算法与数据结构番外(1):优先队列
  8. java initcause_initCause()是什么意思
  9. linux登陆连接信息,成功登录后Linux关闭连接
  10. 慧鱼机器人编程语言的特点_慧鱼机器人课程设计报告.doc