libvirt
Overview
1. 前言
云计算离不开虚拟化,虚拟化绕不开libvirt。
因为开发虚拟机监控程序,花了一些时间学习libvirt, 这是一篇用来熟悉libvirt的博客。
2. libvirt
按照官方主页的介绍,libvirt项目是:
- 一套用于管理虚拟化平台的工具
- 支持C、Python、Perl、Java及其他语言
- 使用开源license
- 支持KVM、QEMU、Xen、Virtuozzo、VMWare ESX、LXC、BHyve及其他驱动
- 支持Linux、FreeBSD、Windows及macOS等操作系统
- 被许多应用使用
在Linux平台上以C/S的形式存在,libvirtd程序作为服务端管理虚拟机,接收和解析客户端请求,客户端可以是virsh命令行工具,也可以是基于libvirt库自行开发的程序。
架构如下,图片来自维基百科:
可以看到libvirt对用户屏蔽了底层hypervisor,向上提供了统一的接口。
2.1 为什么不直接使用KVM
博主在接触libvirtd前,一直都是直接使用qemu-kvm来玩虚拟机的,一般配置好参数和脚本后手动操作,控制虚拟机起停。
qemu本身也是一个模拟器,在Linux下可以利用kvm模块加速虚拟化,但qemu只是一个命令行工具,且参数多如牛毛,在用kvm调试安装黑苹果成功后,还是需要配置libvirtd实现开机自启动。
如果需要实现可编程的的虚拟机操作,我们需要:
- 定义结构化的数据来虚拟机配置
- 维护虚拟机的生命周期,包括创建、启动、停止、删除,并处理异常情况
- 本地的Daemon维护虚拟机,向服务端提供API
开发和维护的工作量都不小,而libvirt不止做到这些,还提供一套虚拟化管理方案。
2.2 从virsh命令看libvirt
由于libvirt主要使用者都是云厂商的开发者,技术的应用者也不太可能公开分享实践经验。因此博主在入门时从virsh命令开始,熟悉通过virsh命令操作虚拟机后,再从API库中寻找对应的接口完成功能。
virsh帮助命令输出
1➜ ~ virsh
2
3virsh [options]... [<command_string>]
4virsh [options]... <command> [args...]
5
6 options:
7 -c | --connect=URI hypervisor connection URI
8 -d | --debug=NUM debug level [0-4]
9 -e | --escape <char> set escape sequence for console
10 -h | --help this help
11 -k | --keepalive-interval=NUM
12 keepalive interval in seconds, 0 for disable
13 -K | --keepalive-count=NUM
14 number of possible missed keepalive messages
15 -l | --log=FILE output logging to file
16 -q | --quiet quiet mode
17 -r | --readonly connect readonly
18 -t | --timing print timing information
19 -v short version
20 -V long version
21 --version[=TYPE] version, TYPE is short or long (default short)
22 commands (non interactive mode):
23
24 Domain Management (help keyword 'domain')
25 attach-device attach device from an XML file
26 attach-disk attach disk device
27 attach-interface attach network interface
28 autostart autostart a domain
29 blkdeviotune Set or query a block device I/O tuning parameters.
30 blkiotune Get or set blkio parameters
31 blockcommit Start a block commit operation.
32 blockcopy Start a block copy operation.
33 blockjob Manage active block operations
34 blockpull Populate a disk from its backing image.
35 blockresize Resize block device of domain.
36 change-media Change media of CD or floppy drive
37 console connect to the guest console
38 cpu-stats show domain cpu statistics
39 create create a domain from an XML file
40 define define (but don't start) a domain from an XML file
41 desc show or set domain's description or title
42 destroy destroy (stop) a domain
43 detach-device detach device from an XML file
44 detach-device-alias detach device from an alias
45 detach-disk detach disk device
46 detach-interface detach network interface
47 domdisplay domain display connection URI
48 domfsfreeze Freeze domain's mounted filesystems.
49 domfsthaw Thaw domain's mounted filesystems.
50 domfsinfo Get information of domain's mounted filesystems.
51 domfstrim Invoke fstrim on domain's mounted filesystems.
52 domhostname print the domain's hostname
53 domid convert a domain name or UUID to domain id
54 domif-setlink set link state of a virtual interface
55 domiftune get/set parameters of a virtual interface
56 domjobabort abort active domain job
57 domjobinfo domain job information
58 domname convert a domain id or UUID to domain name
59 domrename rename a domain
60 dompmsuspend suspend a domain gracefully using power management functions
61 dompmwakeup wakeup a domain from pmsuspended state
62 domuuid convert a domain name or id to domain UUID
63 domxml-from-native Convert native config to domain XML
64 domxml-to-native Convert domain XML to native config
65 dump dump the core of a domain to a file for analysis
66 dumpxml domain information in XML
67 edit edit XML configuration for a domain
68 event Domain Events
69 inject-nmi Inject NMI to the guest
70 iothreadinfo view domain IOThreads
71 iothreadpin control domain IOThread affinity
72 iothreadadd add an IOThread to the guest domain
73 iothreaddel delete an IOThread from the guest domain
74 send-key Send keycodes to the guest
75 send-process-signal Send signals to processes
76 lxc-enter-namespace LXC Guest Enter Namespace
77 managedsave managed save of a domain state
78 managedsave-remove Remove managed save of a domain
79 managedsave-edit edit XML for a domain's managed save state file
80 managedsave-dumpxml Domain information of managed save state file in XML
81 managedsave-define redefine the XML for a domain's managed save state file
82 memtune Get or set memory parameters
83 perf Get or set perf event
84 metadata show or set domain's custom XML metadata
85 migrate migrate domain to another host
86 migrate-setmaxdowntime set maximum tolerable downtime
87 migrate-getmaxdowntime get maximum tolerable downtime
88 migrate-compcache get/set compression cache size
89 migrate-setspeed Set the maximum migration bandwidth
90 migrate-getspeed Get the maximum migration bandwidth
91 migrate-postcopy Switch running migration from pre-copy to post-copy
92 numatune Get or set numa parameters
93 qemu-attach QEMU Attach
94 qemu-monitor-command QEMU Monitor Command
95 qemu-monitor-event QEMU Monitor Events
96 qemu-agent-command QEMU Guest Agent Command
97 reboot reboot a domain
98 reset reset a domain
99 restore restore a domain from a saved state in a file
100 resume resume a domain
101 save save a domain state to a file
102 save-image-define redefine the XML for a domain's saved state file
103 save-image-dumpxml saved state domain information in XML
104 save-image-edit edit XML for a domain's saved state file
105 schedinfo show/set scheduler parameters
106 screenshot take a screenshot of a current domain console and store it into a file
107 set-lifecycle-action change lifecycle actions
108 set-user-password set the user password inside the domain
109 setmaxmem change maximum memory limit
110 setmem change memory allocation
111 setvcpus change number of virtual CPUs
112 shutdown gracefully shutdown a domain
113 start start a (previously defined) inactive domain
114 suspend suspend a domain
115 ttyconsole tty console
116 undefine undefine a domain
117 update-device update device from an XML file
118 vcpucount domain vcpu counts
119 vcpuinfo detailed domain vcpu information
120 vcpupin control or query domain vcpu affinity
121 emulatorpin control or query domain emulator affinity
122 vncdisplay vnc display
123 guestvcpus query or modify state of vcpu in the guest (via agent)
124 setvcpu attach/detach vcpu or groups of threads
125 domblkthreshold set the threshold for block-threshold event for a given block device or it's backing chain element
126
127 Domain Monitoring (help keyword 'monitor')
128 domblkerror Show errors on block devices
129 domblkinfo domain block device size information
130 domblklist list all domain blocks
131 domblkstat get device block stats for a domain
132 domcontrol domain control interface state
133 domif-getlink get link state of a virtual interface
134 domifaddr Get network interfaces' addresses for a running domain
135 domiflist list all domain virtual interfaces
136 domifstat get network interface stats for a domain
137 dominfo domain information
138 dommemstat get memory statistics for a domain
139 domstate domain state
140 domstats get statistics about one or multiple domains
141 domtime domain time
142 list list domains
143
144 Host and Hypervisor (help keyword 'host')
145 allocpages Manipulate pages pool size
146 capabilities capabilities
147 cpu-baseline compute baseline CPU
148 cpu-compare compare host CPU with a CPU described by an XML file
149 cpu-models CPU models
150 domcapabilities domain capabilities
151 freecell NUMA free memory
152 freepages NUMA free pages
153 hostname print the hypervisor hostname
154 hypervisor-cpu-baseline compute baseline CPU usable by a specific hypervisor
155 hypervisor-cpu-compare compare a CPU with the CPU created by a hypervisor on the host
156 maxvcpus connection vcpu maximum
157 node-memory-tune Get or set node memory parameters
158 nodecpumap node cpu map
159 nodecpustats Prints cpu stats of the node.
160 nodeinfo node information
161 nodememstats Prints memory stats of the node.
162 nodesuspend suspend the host node for a given time duration
163 sysinfo print the hypervisor sysinfo
164 uri print the hypervisor canonical URI
165 version show version
166
167 Interface (help keyword 'interface')
168 iface-begin create a snapshot of current interfaces settings, which can be later committed (iface-commit) or restored (iface-rollback)
169 iface-bridge create a bridge device and attach an existing network device to it
170 iface-commit commit changes made since iface-begin and free restore point
171 iface-define define an inactive persistent physical host interface or modify an existing persistent one from an XML file
172 iface-destroy destroy a physical host interface (disable it / "if-down")
173 iface-dumpxml interface information in XML
174 iface-edit edit XML configuration for a physical host interface
175 iface-list list physical host interfaces
176 iface-mac convert an interface name to interface MAC address
177 iface-name convert an interface MAC address to interface name
178 iface-rollback rollback to previous saved configuration created via iface-begin
179 iface-start start a physical host interface (enable it / "if-up")
180 iface-unbridge undefine a bridge device after detaching its slave device
181 iface-undefine undefine a physical host interface (remove it from configuration)
182
183 Network Filter (help keyword 'filter')
184 nwfilter-define define or update a network filter from an XML file
185 nwfilter-dumpxml network filter information in XML
186 nwfilter-edit edit XML configuration for a network filter
187 nwfilter-list list network filters
188 nwfilter-undefine undefine a network filter
189 nwfilter-binding-create create a network filter binding from an XML file
190 nwfilter-binding-delete delete a network filter binding
191 nwfilter-binding-dumpxml network filter information in XML
192 nwfilter-binding-list list network filter bindings
193
194 Networking (help keyword 'network')
195 net-autostart autostart a network
196 net-create create a network from an XML file
197 net-define define an inactive persistent virtual network or modify an existing persistent one from an XML file
198 net-destroy destroy (stop) a network
199 net-dhcp-leases print lease info for a given network
200 net-dumpxml network information in XML
201 net-edit edit XML configuration for a network
202 net-event Network Events
203 net-info network information
204 net-list list networks
205 net-name convert a network UUID to network name
206 net-start start a (previously defined) inactive network
207 net-undefine undefine a persistent network
208 net-update update parts of an existing network's configuration
209 net-uuid convert a network name to network UUID
210
211 Node Device (help keyword 'nodedev')
212 nodedev-create create a device defined by an XML file on the node
213 nodedev-destroy destroy (stop) a device on the node
214 nodedev-detach detach node device from its device driver
215 nodedev-dumpxml node device details in XML
216 nodedev-list enumerate devices on this host
217 nodedev-reattach reattach node device to its device driver
218 nodedev-reset reset node device
219 nodedev-event Node Device Events
220
221 Secret (help keyword 'secret')
222 secret-define define or modify a secret from an XML file
223 secret-dumpxml secret attributes in XML
224 secret-event Secret Events
225 secret-get-value Output a secret value
226 secret-list list secrets
227 secret-set-value set a secret value
228 secret-undefine undefine a secret
229
230 Snapshot (help keyword 'snapshot')
231 snapshot-create Create a snapshot from XML
232 snapshot-create-as Create a snapshot from a set of args
233 snapshot-current Get or set the current snapshot
234 snapshot-delete Delete a domain snapshot
235 snapshot-dumpxml Dump XML for a domain snapshot
236 snapshot-edit edit XML for a snapshot
237 snapshot-info snapshot information
238 snapshot-list List snapshots for a domain
239 snapshot-parent Get the name of the parent of a snapshot
240 snapshot-revert Revert a domain to a snapshot
241
242 Storage Pool (help keyword 'pool')
243 find-storage-pool-sources-as find potential storage pool sources
244 find-storage-pool-sources discover potential storage pool sources
245 pool-autostart autostart a pool
246 pool-build build a pool
247 pool-create-as create a pool from a set of args
248 pool-create create a pool from an XML file
249 pool-define-as define a pool from a set of args
250 pool-define define an inactive persistent storage pool or modify an existing persistent one from an XML file
251 pool-delete delete a pool
252 pool-destroy destroy (stop) a pool
253 pool-dumpxml pool information in XML
254 pool-edit edit XML configuration for a storage pool
255 pool-info storage pool information
256 pool-list list pools
257 pool-name convert a pool UUID to pool name
258 pool-refresh refresh a pool
259 pool-start start a (previously defined) inactive pool
260 pool-undefine undefine an inactive pool
261 pool-uuid convert a pool name to pool UUID
262 pool-event Storage Pool Events
263
264 Storage Volume (help keyword 'volume')
265 vol-clone clone a volume.
266 vol-create-as create a volume from a set of args
267 vol-create create a vol from an XML file
268 vol-create-from create a vol, using another volume as input
269 vol-delete delete a vol
270 vol-download download volume contents to a file
271 vol-dumpxml vol information in XML
272 vol-info storage vol information
273 vol-key returns the volume key for a given volume name or path
274 vol-list list vols
275 vol-name returns the volume name for a given volume key or path
276 vol-path returns the volume path for a given volume name or key
277 vol-pool returns the storage pool for a given volume key or path
278 vol-resize resize a vol
279 vol-upload upload file contents to a volume
280 vol-wipe wipe a vol
281
282 Virsh itself (help keyword 'virsh')
283 cd change the current directory
284 echo echo arguments
285 exit quit this interactive terminal
286 help print help
287 pwd print the current directory
288 quit quit this interactive terminal
289 connect (re)connect to hypervisor
在virsh的帮助命令中,所有的命令被划分为以下几类:
- domain:虚拟机管理命令,domain对应虚拟机,libvirt使用xml描述虚拟机配置。需要首先通过define将虚拟机导入libvirtd,然后才能执行start、shutdown、destroy等开机、关机、强制关机操作,domain相关的命令接收ID或Name作为参数(在每台宿主机上需唯一)。domain相关命令对应API中Domain对象的方法集合,我们首选需要获取到一个domain引用,然后才能执行操作。
- monitor:监控命令,可获取domain的配置、运行状态、统计数据等。
- host:宿主机管理命令,用于获取和操作宿主机。
- interface:网卡管理命令,比较少用,一般自行管理网络,使用VXLAN、Bridge、TUN/TAP将虚拟机接入用户网络。
- filter:防火墙管理命令,可读取xml格式定义等防火墙规则,按虚拟机网卡配置防火墙。
- network:网络相关命令,这里指的是libvirt的网络,默认使用Bridge和TUN/TAP将虚拟机加入宿主机网络,使用DHCP和iptables为虚拟机提供网络。
- nodedev:宿主机设备管理命令,可将宿主机设备,例如GPU、USB、PCIe设备等分配给虚拟机。
- secret:密钥管理命令。
- snapshot:快照管理命令。
- pool:存储池管理命令,一个存储池内可存放多个卷。
- volume:数据卷管理命令。
virsh命令基于libvirt库开发的,因为libvirt有着良好的API架构,熟悉virsh命令对使用API有很大的帮助。
2.3 API
官方文档链接:Reference Manual for libvirt
在目录中我们可以看到与virsh命令几乎一一对应的API。
libvirt使用C语言编写,提供稳定的C API,对其他语言的支持也是通过C API的绑定实现的,因此本地需要安装相关的C开发库,并运行libvirtd守护进程。
以Go语言和CentOS 7为例,官方Go语言库为:libvirt-go,与C库版本同步向后兼容到v1.2.0,可用于生产环境。
开发环境需要安装gcc、libvirt、libvirt-devel、centos-release-qemu-ev等,该库通过CGO调用libvrt C库,访问本地的UNIX套接字来与libvirtd通信。因此不可避免需要开发本地Daemon程序,相当于在libvirtd基础上再封装一层,但这也方便操作NFS、VXLAN、系统镜像等,实现更多自定义功能。
以获取虚拟机运行状态为例,流程通常为:
获取libvirt连接 -> 按ID获取domain -> 执行操作 -> 释放domain
如下所示:
1conn, err := libvirt.NewConnect("qemu:///system")
2if err != nil {
3 ...
4}
5defer conn.Close()
6doms, err := conn.ListAllDomains(libvirt.CONNECT_LIST_DOMAINS_ACTIVE)
7if err != nil {
8 ...
9}
10fmt.Printf("%d running domains:\n", len(doms))
11for _, dom := range doms {
12 name, err := dom.GetName()
13 if err == nil {
14 fmt.Printf(" %s\n", name)
15 }
16 dom.Free()
17}
我们可以把常用的操作封装为函数,确保所有成功打开的连接和domain都被正确释放。
有CGO的地方,就有纯GO实现。digitalocean开源了他们内部使用的libvirt库:go-libvirt,这个库通过libvirt的RPC接口与守护进程通信,不需要引用C库,可通过网络远程调用libvirtd,唯一的缺点是不稳定。
2.4 虚拟机状态
libvirt-go提供的虚拟机状态分为当前状态state与导致当前状态的原因reason,由于含义都在源码注释中,下面整理了英文注释:
1/**
2 * virDomainState:
3 *
4 * A domain may be in different states at a given point in time
5 */
6typedef enum {
7 VIR_DOMAIN_NOSTATE = 0, /* no state */
8 VIR_DOMAIN_RUNNING = 1, /* the domain is running */
9 VIR_DOMAIN_BLOCKED = 2, /* the domain is blocked on resource */
10 VIR_DOMAIN_PAUSED = 3, /* the domain is paused by user */
11 VIR_DOMAIN_SHUTDOWN= 4, /* the domain is being shut down */
12 VIR_DOMAIN_SHUTOFF = 5, /* the domain is shut off */
13 VIR_DOMAIN_CRASHED = 6, /* the domain is crashed */
14 VIR_DOMAIN_PMSUSPENDED = 7, /* the domain is suspended by guest
15 power management */
16
17# ifdef VIR_ENUM_SENTINELS
18 VIR_DOMAIN_LAST
19 /*
20 * NB: this enum value will increase over time as new events are
21 * added to the libvirt API. It reflects the last state supported
22 * by this version of the libvirt API.
23 */
24# endif
25} virDomainState;
26
27typedef enum {
28 VIR_DOMAIN_NOSTATE_UNKNOWN = 0,
29
30# ifdef VIR_ENUM_SENTINELS
31 VIR_DOMAIN_NOSTATE_LAST
32# endif
33} virDomainNostateReason;
34
35typedef enum {
36 VIR_DOMAIN_RUNNING_UNKNOWN = 0,
37 VIR_DOMAIN_RUNNING_BOOTED = 1, /* normal startup from boot */
38 VIR_DOMAIN_RUNNING_MIGRATED = 2, /* migrated from another host */
39 VIR_DOMAIN_RUNNING_RESTORED = 3, /* restored from a state file */
40 VIR_DOMAIN_RUNNING_FROM_SNAPSHOT = 4, /* restored from snapshot */
41 VIR_DOMAIN_RUNNING_UNPAUSED = 5, /* returned from paused state */
42 VIR_DOMAIN_RUNNING_MIGRATION_CANCELED = 6, /* returned from migration */
43 VIR_DOMAIN_RUNNING_SAVE_CANCELED = 7, /* returned from failed save process */
44 VIR_DOMAIN_RUNNING_WAKEUP = 8, /* returned from pmsuspended due to
45 wakeup event */
46 VIR_DOMAIN_RUNNING_CRASHED = 9, /* resumed from crashed */
47 VIR_DOMAIN_RUNNING_POSTCOPY = 10, /* running in post-copy migration mode */
48
49# ifdef VIR_ENUM_SENTINELS
50 VIR_DOMAIN_RUNNING_LAST
51# endif
52} virDomainRunningReason;
53
54typedef enum {
55 VIR_DOMAIN_BLOCKED_UNKNOWN = 0, /* the reason is unknown */
56
57# ifdef VIR_ENUM_SENTINELS
58 VIR_DOMAIN_BLOCKED_LAST
59# endif
60} virDomainBlockedReason;
61
62typedef enum {
63 VIR_DOMAIN_PAUSED_UNKNOWN = 0, /* the reason is unknown */
64 VIR_DOMAIN_PAUSED_USER = 1, /* paused on user request */
65 VIR_DOMAIN_PAUSED_MIGRATION = 2, /* paused for offline migration */
66 VIR_DOMAIN_PAUSED_SAVE = 3, /* paused for save */
67 VIR_DOMAIN_PAUSED_DUMP = 4, /* paused for offline core dump */
68 VIR_DOMAIN_PAUSED_IOERROR = 5, /* paused due to a disk I/O error */
69 VIR_DOMAIN_PAUSED_WATCHDOG = 6, /* paused due to a watchdog event */
70 VIR_DOMAIN_PAUSED_FROM_SNAPSHOT = 7, /* paused after restoring from snapshot */
71 VIR_DOMAIN_PAUSED_SHUTTING_DOWN = 8, /* paused during shutdown process */
72 VIR_DOMAIN_PAUSED_SNAPSHOT = 9, /* paused while creating a snapshot */
73 VIR_DOMAIN_PAUSED_CRASHED = 10, /* paused due to a guest crash */
74 VIR_DOMAIN_PAUSED_STARTING_UP = 11, /* the domain is being started */
75 VIR_DOMAIN_PAUSED_POSTCOPY = 12, /* paused for post-copy migration */
76 VIR_DOMAIN_PAUSED_POSTCOPY_FAILED = 13, /* paused after failed post-copy */
77
78# ifdef VIR_ENUM_SENTINELS
79 VIR_DOMAIN_PAUSED_LAST
80# endif
81} virDomainPausedReason;
82
83typedef enum {
84 VIR_DOMAIN_SHUTDOWN_UNKNOWN = 0, /* the reason is unknown */
85 VIR_DOMAIN_SHUTDOWN_USER = 1, /* shutting down on user request */
86
87# ifdef VIR_ENUM_SENTINELS
88 VIR_DOMAIN_SHUTDOWN_LAST
89# endif
90} virDomainShutdownReason;
91
92typedef enum {
93 VIR_DOMAIN_SHUTOFF_UNKNOWN = 0, /* the reason is unknown */
94 VIR_DOMAIN_SHUTOFF_SHUTDOWN = 1, /* normal shutdown */
95 VIR_DOMAIN_SHUTOFF_DESTROYED = 2, /* forced poweroff */
96 VIR_DOMAIN_SHUTOFF_CRASHED = 3, /* domain crashed */
97 VIR_DOMAIN_SHUTOFF_MIGRATED = 4, /* migrated to another host */
98 VIR_DOMAIN_SHUTOFF_SAVED = 5, /* saved to a file */
99 VIR_DOMAIN_SHUTOFF_FAILED = 6, /* domain failed to start */
100 VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT = 7, /* restored from a snapshot which was
101 * taken while domain was shutoff */
102 VIR_DOMAIN_SHUTOFF_DAEMON = 8, /* daemon decides to kill domain
103 during reconnection processing */
104# ifdef VIR_ENUM_SENTINELS
105 VIR_DOMAIN_SHUTOFF_LAST
106# endif
107} virDomainShutoffReason;
108
109typedef enum {
110 VIR_DOMAIN_CRASHED_UNKNOWN = 0, /* crashed for unknown reason */
111 VIR_DOMAIN_CRASHED_PANICKED = 1, /* domain panicked */
112
113# ifdef VIR_ENUM_SENTINELS
114 VIR_DOMAIN_CRASHED_LAST
115# endif
116} virDomainCrashedReason;
117
118typedef enum {
119 VIR_DOMAIN_PMSUSPENDED_UNKNOWN = 0,
120
121# ifdef VIR_ENUM_SENTINELS
122 VIR_DOMAIN_PMSUSPENDED_LAST
123# endif
124} virDomainPMSuspendedReason;
125
126typedef enum {
127 VIR_DOMAIN_PMSUSPENDED_DISK_UNKNOWN = 0,
128
129# ifdef VIR_ENUM_SENTINELS
130 VIR_DOMAIN_PMSUSPENDED_DISK_LAST
131# endif
132} virDomainPMSuspendedDiskReason;
博主按照枚举数值整理如下:
- 0:nostate,无状态
- 1:running,运行中
- unknown:未知
- booted:正常开机启动
- migrated:从其他宿主机迁移后启动
- restored:从状态文件恢复运行
- fromSnapshot:从快照恢复运行
- unpaused:从挂起状态恢复运行
- migrationCanceled:取消迁移状态后恢复运行
- saveCancel:取消保存后恢复运行
- wakeup:唤醒后恢复运行
- crashed:从crash状态恢复启动
- postCopy:复制结束后恢复启动
- 2:blocked,因为资源阻塞
- unknown:未知
- 3:pause,挂起
- unkown:未知
- user:用户主动执行挂起
- migration:执行迁移导致的挂起
- save:保存虚拟机导致的挂起
- dump:dump虚拟机导致的挂起
- IOError:磁盘IO错误导致的挂起
- watchdog:看门狗事件导致的挂起
- fromSnapshot:从快照恢复后挂起
- shuttingDown:关机时挂起
- snapshot:创建快照时挂起
- crash:虚拟机crash导致的挂起
- startingUp:虚拟机正在启动
- postCopy:post-copy迁移导致的挂起
- postCopyFaiied:post-copy失败后的挂起
- 4:shutdown,正在关机
- unknown:未知
- user:用户主动关机
- 5:shutoff,已关闭
- unknown:未知
- shutdown:正常关机
- destroyed:强制关机
- crashed:domain crash
- migrated:已迁移到其他host
- saved:已保存到文件
- failed:domain无法启动
- fromSnapshot:从domain关闭时生成的快照恢复
- daemon:被守护进程终结
- 6:crash,crash
- unknown:未知
- panicked:domain panic
- 7:pmsuspend,由虚拟机的电源管理挂起
- unknown:未知
3. 写在最后
博主的负责的虚拟机监控程序涉及libvirt内容比较简单,基本仅限于上面的示例代码:获取虚拟机状态上报服务端。
状态通过调接口就可以获取,比较麻烦的是做相关测试来确定libvirtd状态与业务状态的转换关系。
如果未来有更多虚拟机相关的开发工作时,应该会再深入研究一些API内部实现。