一。确认虚拟机镜像文件格式

[[email protected] vps]# qemu-img info centos1.img
p_w_picpath: centos1.img
file format: raw
virtual size: 200G (214748364800 bytes)
disk size: 6.5G


RAW格式是最原始的镜像格式,好处是速度快。但不支持很多新的功能。现在qcow2格式效率有很大提升了,而且还支持一些新的功能
1 更小的存储空间,即使是不支持holes的文件系统也可以(这下du -h和ls -lh看到的就一样了)
2 Copy-on-write support, where the p_w_picpath only represents changes made to an underlying disk p_w_picpath(这个特性SUN ZFS表现的淋漓尽致)
3 支持多个snapshot,对历史snapshot进行管理
4 支持zlib的磁盘压缩
5 支持AES的加密

见 《qcow2、raw、vmdk等镜像格式》对比。

二。想要启用快照功能,需要先转换镜像文件格式为qcow2。

[[email protected] vps]# virsh shutdown esojourn.org
先关掉VM
[[email protected] vps]# qemu-img convert -f raw -O qcow2 centos1.img centos1qcow2.img
转换格式


三。常用快照命令
这里有一份libvirt官方的命令文档。完整,但说明不详细: http://wiki.libvirt.org/page/VM_lifecycle

具体示例:

1. 列出快照:
[[email protected] vps]# virsh snapshot-list CentOS1
Name                 Creation Time             State
------------------------------------------------------------
centos1.snap1        2012-10-08 17:25:11 +0800 running
snap2                2012-10-08 17:33:14 +0800 running
snap3                2012-10-08 17:57:21 +0800 running

2. 创建快照
virsh snapshot-create-as CentOS1 snap2
virsh snapshot-create-as --domain CentOS1 --name snap2 --description "URL: www.esojourn.org"

3. 查看快照配置
virsh snapshot-current CentOS1
4. 恢复快照
virsh snapshot-revert CentOS1 snap2
5. 删除快照
birsh snapshot-delete CentOS1 snap2
6. 获取帮助
virsh help snapshot


四。关于qemu-img snapshot -c和savevm
很多互相抄袭的教程里,都提到了使用qemu-img snapshot -c的命令来创建快照。但我自己测试的结果 ,不管虚拟机是运行中,还是关闭状态,这个命令创建的快照字节都是0。也就是说什么也没保存下来。对此,我还没有找到原因。但找到Red hat员工Kashyap Chamarthy的一篇文章。文章里提到virsh在不同情况下,会调用不同方式来保存快照。其中至少包括‘qemu-img snapshot -c‘,qemu的 ‘savevm‘和qemu的 ‘snapshot_blkdev‘这三种方式。所以看起来快照保存,还是使用virsh snapshot-create的方式比较好。

原文引用

Also, discussed with Eric, in what cases does virsh invoke Qemu’s ‘savevm‘ and ‘qemu-img snapshot -c‘ commands while creating different types of snapshots discussed earlier above. Here is the outline:

- it uses ‘qemu-img snapshot -c‘ if the domain is offline and –disk-only was not specified
- it uses qemu’s ‘savevm‘ if the domain is online and –disk-only was not specified
- it uses qemu’s ‘snapshot_blkdev‘ if the domain is online and –disk-only is specified

http://kashyapc.wordpress.com/2011/10/04/snapshotting-with-libvirt-for-qcow2-p_w_picpaths/


qemu-img snapshot相关命令格式:

qemu-img snapshot -c snap1 centos1-qcow2.img

qemu-img  snapshot -l centos1-qcow2.img

Snapshot list:
ID        TAG       VM SIZE      DATE       VM CLOCK
1         snap1      0              2011-07-21 23:17:38   00:00:00.000


恢复快照:
qemu-img  snapshot   -a   CentOS5.5_64bit_Qcow2_basesys.img    CentOS5.5_64bit_Qcow2.img

其他操作:
 'snapshot' is the name of the snapshot to create, apply or delete
 '-a' applies a snapshot (revert disk to saved state)
 '-c' creates a snapshot
 '-d' deletes a snapshot
 '-l' lists all snapshots in the given p_w_picpath