QEMU img: KVM disk management tool for virtualization technology

Time:2021-1-12

In the previous blog, we have a general understanding of the operation of virsh on KVM virtual machine. Please refer to the review https://www.cnblogs.com/qiuhom-1874/tag/virsh/ Today, let’s learn about the usage of common commands of QEMU img, the disk management tool of KVM;

1. Help information for QEMU img

[[email protected] ~]# qemu-img -h
qemu-img version 1.5.3, Copyright (c) 2004-2008 Fabrice Bellard
usage: qemu-img command [command options]
QEMU disk image utility

Command syntax:
  check [-q] [-f fmt] [--output=ofmt] [-r [leaks | all]] [-T src_cache] filename
  create [-q] [-f fmt] [-o options] filename [size]
  commit [-q] [-f fmt] [-t cache] filename
  compare [-f fmt] [-F fmt] [-T src_cache] [-p] [-q] [-s] filename1 filename2
  convert [-c] [-p] [-q] [-n] [-f fmt] [-t cache] [-T src_cache] [-O output_fmt] [-o options] [-s snapshot_name] [-S sparse_size] filename [filename2 [...]] output_filename
  info [-f fmt] [--output=ofmt] [--backing-chain] filename
  map [-f fmt] [--output=ofmt] filename
  snapshot [-q] [-l | -a snapshot | -c snapshot | -d snapshot] filename
  rebase [-q] [-f fmt] [-t cache] [-T src_cache] [-p] [-u] -b backing_file [-F backing_fmt] filename
  resize [-q] filename [+ | -]size
  amend [-q] [-f fmt] [-t cache] -o options filename

Command parameters:
  'filename' is a disk image filename
  'fmt' is the disk image format. It is guessed automatically in most cases
  'cache' is the cache mode used to write the output disk image, the valid
    options are: 'none', 'writeback' (default, except for convert), 'writethrough',
    'directsync' and 'unsafe' (default for convert)
  'src_cache' is the cache mode used to read input disk images, the valid
    options are the same as for the 'cache' option
  'size' is the disk image size in bytes. Optional suffixes
    'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),
    'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P)  are
    supported. 'b' is ignored.
  'output_filename' is the destination disk image filename
  'output_fmt' is the destination format
  'options' is a comma separated list of format specific options in a
    name=value format. Use -o ? for an overview of the options supported by the
    used format
  '-c' indicates that target image must be compressed (qcow format only)
  '-u' enables unsafe rebasing. It is assumed that old and new backing file
       match exactly. The image doesn't need a working backing file before
       rebasing in this case (useful for renaming the backing file)
  '-h' with or without a command shows this help and lists the supported formats
  '-p' show progress of command (only certain commands)
  '-q' use Quiet mode - do not print any output (except errors)
  '-S' indicates the consecutive number of bytes (defaults to 4k) that must
       contain only zeros for qemu-img to create a sparse image during
       conversion. If the number of bytes is 0, the source will not be scanned for
       unallocated or zero sectors, and the destination image will always be
       fully allocated
  '--output' takes the format in which the output must be done (human or json)
  '-n' skips the target volume creation (useful if the volume is created
       prior to running qemu-img)

Parameters to check subcommand:
  '-r' tries to repair any inconsistencies that are found during the check.
       '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all
       kinds of errors, with a higher risk of choosing the wrong fix or
       hiding corruption that has already occurred.

Parameters to snapshot subcommand:
  '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 image

Parameters to compare subcommand:
  '-f' first image format
  '-F' second image format
  '-s' run in Strict mode - fail on different image size or sector allocation

Supported formats: vvfat vpc vmdk vhdx vdi ssh sheepdog rbd raw host_cdrom host_floppy host_device file qed qcow2 qcow parallels nbd iscsi gluster dmg tftp ftps ftp https http cloop bochs blkverify blkdebug
[[email protected] ~]#

Tip: from the help information above, we can see that QEMU img is divided into check, create, commit, compare, convert, info, map, snapshot, rebase, reset, and amend sub commands. Each sub command has its own functions, syntax, and options;

QEMU img create: the command used to create a disk file, syntax format: QEMU img create [- q] [- f FMT] [- O options] file name [size]; where – F is used to specify the format of the disk, commonly used formats are, raw, qcow, qcow2; if you want to see which options are available in the create subcommand, you can use – o? To specify, as shown in the following example;

Example: to view the option description of the create subcommand, you can use QEMU img create – F qcow2 – o? / KVM / images/ test.img

[[email protected] ~]# qemu-img create -f qcow2 -o ? /kvm/images/test.img
Supported options:
size             Virtual disk size
compat           Compatibility level (0.10 or 1.1)
backing_file     File name of a base image
backing_fmt      Image format of the base image
encryption       Encrypt the image
cluster_size     qcow2 cluster size
preallocation    Preallocation mode (allowed values: off, metadata, falloc, full)
lazy_refcounts   Postpone refcount updates
[[email protected] ~]# 

Tip: the above example indicates that you want to create / KVM / images/ test.img The disk file format is qcow2. What options does it have? Here we need to explain that the suffix of the file is just for people to see on the Linux system, which is convenient for people to distinguish it. The system does not determine its format by suffix. From the help information above, we can see that the option of the create subcommand is size, which is used to specify the creation Create the size of the disk file; compat option is used to specify compatibility; backing_ File specifies the name of the backup file; backing_ FMT is used to specify the format of backup file; encryption is used to specify whether to encrypt, true means to encrypt, false means not to encrypt, and false is not specified by default; cluster_ Size specifies the cluster size of the disk; preallocation is used to specify the disk pre allocation policy, where off means no pre allocation, metadata means only pre allocation of metadata size, falloc means allocation with the increase of files, and full means immediate allocation of all disk space; default means no pre allocation of disk space;

Example: create a 2G disk with different pre allocation policy mechanisms

[[email protected] ~]# qemu-img create -f qcow2 -o preallocation=off,size=2G /kvm/images/a1.img
Formatting '/kvm/images/a1.img', fmt=qcow2 size=2147483648 encryption=off cluster_size=65536 preallocation='off' lazy_refcounts=off 
[[email protected] ~]# ll -h /kvm/images/a1.img
-Rw-r -- R -- 1 root 193k August 18 22:17 / KVM / images / a1.img
[[email protected] ~]# qemu-img info /kvm/images/a1.img
image: /kvm/images/a1.img
file format: qcow2
virtual size: 2.0G (2147483648 bytes)
disk size: 196K
cluster_size: 65536
Format specific information:
    compat: 1.1
    lazy refcounts: false
[[email protected] ~]# qemu-img  create -f qcow2 -o preallocation=metadata,size=2G /kvm/images/a2.img
Formatting '/kvm/images/a2.img', fmt=qcow2 size=2147483648 encryption=off cluster_size=65536 preallocation='metadata' lazy_refcounts=off 
[[email protected] ~]# ll -h /kvm/images/a2.img
-Rw-r -- R -- 1 root 2.1g August 18 22:18 / KVM / images / a2.img
[[email protected] ~]# qemu-img info /kvm/images/a2.img
image: /kvm/images/a2.img
file format: qcow2
virtual size: 2.0G (2147483648 bytes)
disk size: 708K
cluster_size: 65536
Format specific information:
    compat: 1.1
    lazy refcounts: false
[[email protected] ~]# qemu-img  create -f qcow2 -o preallocation=falloc,size=2G /kvm/images/a3.img               
Formatting '/kvm/images/a3.img', fmt=qcow2 size=2147483648 encryption=off cluster_size=65536 preallocation='falloc' lazy_refcounts=off 
[[email protected] ~]# ll -h /kvm/images/a3.img
-Rw-r -- R -- 1 root 2.1g August 18 22:19 / KVM / images / a3.img
[[email protected] ~]# qemu-img info /kvm/images/a3.img
image: /kvm/images/a3.img
file format: qcow2
virtual size: 2.0G (2147483648 bytes)
disk size: 2.0G
cluster_size: 65536
Format specific information:
    compat: 1.1
    lazy refcounts: false
[[email protected] ~]# qemu-img  create -f qcow2 -o preallocation=full,size=2G /kvm/images/a4.img              
Formatting '/kvm/images/a4.img', fmt=qcow2 size=2147483648 encryption=off cluster_size=65536 preallocation='full' lazy_refcounts=off 
[[email protected] ~]# ll -h /kvm/images/a4.img                                                  
-Rw-r -- R -- 1 root 2.1g August 18 22:21 / KVM / images / a4.img
[[email protected] ~]# qemu-img info /kvm/images/a4.img                                          
image: /kvm/images/a4.img
file format: qcow2
virtual size: 2.0G (2147483648 bytes)
disk size: 2.0G
cluster_size: 65536
Format specific information:
    compat: 1.1
    lazy refcounts: false
[root[email protected] ~]#

Tip: from the above example, we can see that except for the disk created by off, the size we see is a very small size, and other modes are represented by the space we specify on the file system; from the QEMU img info command, off and metadata disk size are very small, and the virtual space is the size we specify; the latter is falloc and full Both disk size and virtual size are the sizes we specify. The reason why the disk file we see on the file system is larger than the space we specify is that it exists as a file on the file system, and it also has element data information;

QEMU img Info: used to view the details of the specified disk file; usage format: QEMU img info [- f FMT] [– output = OFMT] [– backing chain] file name

[[email protected] ~]# qemu-img info /kvm/images/centos7.qcow2 
image: /kvm/images/centos7.qcow2
file format: qcow2
virtual size: 10G (10737418240 bytes)
disk size: 196K
cluster_size: 65536
Format specific information:
    compat: 1.1
    lazy refcounts: false
[[email protected] ~]# qemu-img info /kvm/images/win7.qcow2 
image: /kvm/images/win7.qcow2
file format: qcow2
virtual size: 50G (53687091200 bytes)
disk size: 8.5G
cluster_size: 65536
Format specific information:
    compat: 1.1
    lazy refcounts: false
[[email protected] ~]# 

QEMU img check: check the specified disk file; usage format: QEMU img check [- q] [- f FMT] [– output = OFMT] [- R [leaks | all]]] [- t SRC_ cache] filename

[[email protected] ~]# qemu-img check /kvm/images/win7.qcow2
No errors were found on the image.
138808/819200 = 16.94% allocated, 27.22% fragmented, 0.00% compressed clusters
Image end offset: 9098887168
[[email protected] ~]# qemu-img check /kvm/images/centos7.qcow2 
No errors were found on the image.
Image end offset: 262144
[[email protected] ~]# 

QEMU img snapshot: do snapshot related operations on the specified disk file; syntax format: QEMU img snapshot [- q] [- L | – a snapshot | – C snapshot | – D snapshot] file name

-c: Represents the creation of a snapshot

[[email protected] ~]# qemu-img snapshot -c snapshot_centos7_1 /kvm/images/centos7.qcow2 

-l: View the snapshot list of the specified disk file

[[email protected] ~]# qemu-img snapshot -l /kvm/images/centos7.qcow2                     
Snapshot list:
ID        TAG                 VM SIZE                DATE       VM CLOCK
1         snapshot_centos7_1        0 2017-03-29 01:16:08   00:00:00.000
[[email protected] ~]#

-a: Apply the snapshot to restore the disk to the moment of snapshot;

[[email protected] ~]# qemu-img snapshot -a snapshot_centos7_1 /kvm/images/centos7.qcow2 
[[email protected] ~]# 

-d: Delete snapshot

[[email protected] ~]# qemu-img snapshot -l /kvm/images/centos7.qcow2   
Snapshot list:
ID        TAG                 VM SIZE                DATE       VM CLOCK
1         snapshot_centos7_1        0 2017-03-29 01:16:08   00:00:00.000
[[email protected] ~]# qemu-img snapshot -d snapshot_centos7_1 /kvm/images/centos7.qcow2
[[email protected] ~]# qemu-img snapshot -l /kvm/images/centos7.qcow2                   
[[email protected] ~]# 

QEMU img convert: image format conversion, syntax format: QEMU img convert [- C] [- P] [- q] [- n] [- f FMT] [- t cache] [- t SRC_ cache] [-O output_ fmt] [-o options] [-s snapshot_ name] [-S sparse_ size] filename [filename2 […]] output_ The file name; – C represents the compressed output file, but only the image files of qcow2 and qcow format can support compression, and this compression is read-only. If the compressed sector is rewritten, it will be rewritten as uncompressed data. -P is used to display the conversion progress; – O is used to specify the options of the output file, such as encryption, size, etc..

Example 1: convert the disk file of qcow2 format directly without output format

[[email protected] ~]# qemu-img create -f qcow2 /kvm/images/test1.img 1G
Formatting '/kvm/images/test1.img', fmt=qcow2 size=1073741824 encryption=off cluster_size=65536 lazy_refcounts=off 
[[email protected] ~]# qemu-img info /kvm/images/test1.img 
image: /kvm/images/test1.img
file format: qcow2
virtual size: 1.0G (1073741824 bytes)
disk size: 196K
cluster_size: 65536
Format specific information:
    compat: 1.1
    lazy refcounts: false
[[email protected] ~]# qemu-img convert /kvm/images/test1.img test1-1.img
[[email protected] ~]# qemu-img info test1-1.img
image: test1-1.img
file format: raw
virtual size: 1.0G (1073741824 bytes)
disk size: 0
[[email protected] ~]# 

Tip: QEMU img convert will automatically recognize the input file format. If the output format is not specified, it will be converted to raw format by default;

Example 2: convert vmdk format file to qcow2 format disk file

[[email protected] ~]# cd /kvm/images/
[[email protected] images]# ls
centos7.qcow2  test1.img
[[email protected] images]# rz
rz waiting to receive.
 zmodem trl+C ȡ

  100%     512 KB  512 KB/s 00:00:01       0 Errors01-s001.vmdk...

[[email protected] images]# ls
CentOS-6.9-x86_64-000001-s001.vmdk  centos7.qcow2  test1.img
[[email protected] images]# qemu-img info CentOS-6.9-x86_64-000001-s001.vmdk 
image: CentOS-6.9-x86_64-000001-s001.vmdk
file format: vmdk
virtual size: 4.0G (4261412864 bytes)
disk size: 512K
cluster_size: 65536
Format specific information:
    cid: 4294967295
    parent cid: 4294967295
    create type: monolithicSparse
    extents:
        [0]:
            virtual size: 4261412864
            filename: CentOS-6.9-x86_64-000001-s001.vmdk
            cluster size: 65536
            format: 
[[email protected] images]# qemu-img convert ./CentOS-6.9-x86_64-000001-s001.vmdk -O qcow2 ./centos6.qcow2
[[email protected] images]# ll
Total consumption 1244560
-Rw-r -- R -- 1 root 524288 April 19 2020 centos-6.9-x86_ 64-000001-s001.vmdk
-Rw-r -- R -- 1 root 197120 March 29 01:33 centos6.qcow2
-Rw-r -- R -- 1 QEMU QEMU 1273561600 March 29 01:32 centos7.qcow2
-Rw-r -- R -- 1 root 197120 March 29 01:24 test1.img
[[email protected] images]# qemu-img info ./centos6.qcow2
image: ./centos6.qcow2
file format: qcow2
virtual size: 4.0G (4261412864 bytes)
disk size: 196K
cluster_size: 65536
Format specific information:
    compat: 1.1
    lazy refcounts: false
[[email protected] images]#

Tip: we can convert disk files of different formats to each other, so as to realize the migration of virtual machine from one platform to another;

QEMU img reset: dynamically add or delete the size of the disk; syntax format: QEMU img reset [- q] file name [+ | -] size;

[[email protected] images]# ll -h
The total dosage is 1.2g
-Rw-r -- R -- 1 root 512k April 19, 2020 centos-6.9-x86_ 64-000001-s001.vmdk
-Rw-r -- R -- 1 root 193k March 29 01:33 centos6.qcow2
-Rw-r -- R -- 1 QEMU QEMU 1.2g March 29 02:03 centos7.qcow2
-Rw-r -- R -- 1 root 193k March 29 01:24 test1.img
[[email protected] images]# qemu-img info test1.img 
image: test1.img
file format: qcow2
virtual size: 1.0G (1073741824 bytes)
disk size: 196K
cluster_size: 65536
Format specific information:
    compat: 1.1
    lazy refcounts: false
[[email protected] images]# qemu-img resize test1.img +1G
Image resized.
[[email protected] images]# qemu-img info test1.img      
image: test1.img
file format: qcow2
virtual size: 2.0G (2147483648 bytes)
disk size: 260K
cluster_size: 65536
Format specific information:
    compat: 1.1
    lazy refcounts: false
[[email protected] images]# ll -h 
The total dosage is 1.2g
-Rw-r -- R -- 1 root 512k April 19, 2020 centos-6.9-x86_ 64-000001-s001.vmdk
-Rw-r -- R -- 1 root 193k March 29 01:33 centos6.qcow2
-Rw-r -- R -- 1 QEMU QEMU 1.2g March 29 02:04 centos7.qcow2
-Rw-r -- R -- 1 root 257k March 29 02:04 test1.img
[[email protected] images]#

Tips: dynamic reduction of space must ensure that the disk space is larger than the data space stored in it, and it is necessary to back up before deleting to avoid data loss caused by disk damage;

[[email protected] images]# qemu-img info test1.img 
image: test1.img
file format: qcow2
virtual size: 2.0G (2147483648 bytes)
disk size: 200K
cluster_size: 65536
Format specific information:
    compat: 1.1
    lazy refcounts: false
[[email protected] images]# qemu-img resize test1.img -1G
qemu-img: qcow2 doesn't support shrinking images yet
qemu-img: This image does not support resize
[[email protected] images]# 

Tip: it should be noted that the format disk of qcow2 does not support deletion;

2. Example: dynamically insert the created disk into the running virtual machine;

New disk

[[email protected] ~]# qemu-img create -f qcow2 -o preallocation=metadata,size=2G /kvm/images/c1.img   
Formatting '/kvm/images/c1.img', fmt=qcow2 size=2147483648 encryption=off cluster_size=65536 preallocation='metadata' lazy_refcounts=off 
[[email protected] ~]# qemu-img info /kvm/images/c1.img
image: /kvm/images/c1.img
file format: qcow2
virtual size: 2.0G (2147483648 bytes)
disk size: 708K
cluster_size: 65536
Format specific information:
    compat: 1.1
    lazy refcounts: false
[[email protected] ~]# ll -h /kvm/images/c1.img
-Rw-r -- R -- 1 root 2.1g March 29 02:18 / KVM / images / c1.img
[[email protected] ~]#

Attach the disk to the running virtual machine

[[email protected] ~]# virsh list --all
 ID name status
----------------------------------------------------
 2     centos7                        running

[[email protected] ~]# virsh domblklist centos7 
Target source
------------------------------------------------
vda        /kvm/images/centos7.qcow2
hda        -

[[email protected] ~]# virsh help attach-disk
  NAME
    Attach disk - attach disk device

  SYNOPSIS
    attach-disk    [--targetbus ] [--driver ] [--subdriver ] [--iothread ] [--cache ] [--io ] [--type ] [--mode ] [--sourcetype ] [--serial ] [--wwn ] [--rawio] [--address ] [--multifunction] [--print-xml] [--persistent] [--config] [--live] [--current]

  DESCRIPTION
    Attach a new disk device

  OPTIONS
    [--domain]   domain name, id or uuid
    [-- source] disk device source
    [-- target] disk device target
    --targetbus   target bus of disk device
    --Driver disk device driver
    --Sub driver disk device sub driver
    --iothread   IOThread to be used by supported device
    --Cache mode of disk device
    --io     io policy of disk device
    --Type target device type
    --Mode device read write mode
    --Sourcetype source type (block|file)
    --Serial disk device serial number
    --WWN disk device's WWN
    --Rawio needs rawio capacity
    --Address disk device address
    --Multi function uses multi-function PCI in the specified address
    --Print XML outputs the XML document instead of attaching the disk
    --Persistent makes real-time changes persistent
    --Config affects next boot
    --Live affects the domain in which it runs
    --Current affects the current domain


[[email protected] ~]# virsh attach-disk centos7 /kvm/images/c1.img hda
Error: attach disk failed
Error: XML error: disk source 'HDA' and '' have duplicate target '/ KVM / images / C1. Img'

[[email protected] ~]# virsh attach-disk centos7 /kvm/images/c1.img hdb
Error: attach disk failed
Error: Unsupported operation: unable to hot swap disk bus' ide '.

[[email protected] ~]# virsh attach-disk centos7 /kvm/images/c1.img vdb
Disk attached successfully

[[email protected] ~]# virsh domblklist centos7 
Target source
------------------------------------------------
vda        /kvm/images/centos7.qcow2
vdb        /kvm/images/c1.img
hda        -

[[email protected] ~]#

Tip: the IDE interface on the HD type disk does not support hot swap, so we need to identify it as a disk type that supports hot swap, such as VD (virtual disk)

Verification: connect to the centos7 console and use the fdisk – L command to check whether new disks are added to the virtual machine?

[[email protected] ~]# virsh console centos7 
Connect to the domain centos7
The escape character is ^]


CentOS Linux 7 (Core)
Kernel 3.10.0-693.el7.x86_64 on an x86_64

localhost login: root
Password: 
Last login: Wed Aug 19 09:30:56 on tty1
[[email protected] ~]# fdisk -l

Disk /dev/vda: 10.7 GB, 10737418240 bytes, 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x000a5c54

   Device Boot      Start         End      Blocks   Id  System
/dev/vda1   *        2048     1050623      524288   83  Linux
/dev/vda2         1050624    20971519     9960448   8e  Linux LVM

Disk /dev/mapper/centos-root: 10.2 GB, 10192158720 bytes, 19906560 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes


Disk /dev/mapper/centos-swap: 4 MB, 4194304 bytes, 8192 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes


Disk /dev/vdb: 2148 MB, 2148073472 bytes, 4195456 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

[[email protected] ~]#

Tip: you can see that a VDB disk has been recognized by the virtual machine;

Partition / dev / VDB in the virtual machine and format it

[[email protected] ~]# fdisk /dev/vdb 
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Device does not contain a recognized partition table
Building a new DOS disklabel with disk identifier 0xe6bebed1.

Command (m for help): p

Disk /dev/vdb: 2148 MB, 2148073472 bytes, 4195456 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0xe6bebed1

   Device Boot      Start         End      Blocks   Id  System

Command (m for help): n
Partition type:
   p   primary (0 primary, 0 extended, 4 free)
   e   extended
Select (default p): p
Partition number (1-4, default 1): 
First sector (2048-4195455, default 2048): 
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-4195455, default 4195455): 
Using default value 4195455
Partition 1 of type Linux and of size 2 GiB is set

Command (m for help): p

Disk /dev/vdb: 2148 MB, 2148073472 bytes, 4195456 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0xe6bebed1

   Device Boot      Start         End      Blocks   Id  System
/dev/vdb1            2048     4195455     2096704   83  Linux

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.
[[email protected] ~]# mkfs.xfs /dev/vdb1
meta-data=/dev/vdb1              isize=512    agcount=4, agsize=131044 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=1        finobt=0, sparse=0
data     =                       bsize=4096   blocks=524176, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=1
log      =internal log           bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
[[email protected] ~]# 

Tip: Here we add a new hard disk can be used to achieve the mount;

Mount / dev / vdb1 to / MNT

[[email protected] ~]# df -TH
Filesystem              Type      Size  Used Avail Use% Mounted on
/dev/mapper/centos-root xfs        11G  940M  9.3G  10% /
devtmpfs                devtmpfs  509M     0  509M   0% /dev
tmpfs                   tmpfs     521M     0  521M   0% /dev/shm
tmpfs                   tmpfs     521M   14M  507M   3% /run
tmpfs                   tmpfs     521M     0  521M   0% /sys/fs/cgroup
/dev/vda1               xfs       534M  124M  410M  24% /boot
tmpfs                   tmpfs     105M     0  105M   0% /run/user/0
[[email protected] ~]# mount /dev/vdb1 /mnt
[[email protected] ~]# df -Th
Filesystem              Type      Size  Used Avail Use% Mounted on
/dev/mapper/centos-root xfs       9.5G  897M  8.7G  10% /
devtmpfs                devtmpfs  486M     0  486M   0% /dev
tmpfs                   tmpfs     497M     0  497M   0% /dev/shm
tmpfs                   tmpfs     497M   13M  484M   3% /run
tmpfs                   tmpfs     497M     0  497M   0% /sys/fs/cgroup
/dev/vda1               xfs       509M  119M  391M  24% /boot
tmpfs                   tmpfs     100M     0  100M   0% /run/user/0
/dev/vdb1               xfs       2.0G   33M  2.0G   2% /mnt
[[email protected] ~]# 

3. Example: dynamically disassemble the disk inserted into the virtual machine;

[[email protected] ~]# virsh domblklist centos7    
Target source
------------------------------------------------
vda        /kvm/images/centos7.qcow2
vdb        /kvm/images/c1.img
hda        -

[[email protected] ~]# virsh help detach-disk 
  NAME
    Detach disk - detach disk device

  SYNOPSIS
    detach-disk   [--persistent] [--config] [--live] [--current] [--print-xml]

  DESCRIPTION
    Detach the disk device.

  OPTIONS
    [--domain]   domain name, id or uuid
    [-- target] disk device target
    --Persistent makes real-time changes persistent
    --Config affects next boot
    --Live affects the domain in which it runs
    --Current affects the current domain
    --print-xml      print XML document rather than detach the disk


[[email protected] ~]# virsh  detach-disk centos7 vdb
Disk detached successfully

[[email protected] ~]# virsh domblklist centos7 
Target source
------------------------------------------------
vda        /kvm/images/centos7.qcow2
hda        -

[[email protected] ~]#

Tips: you can use virsh detach disk to remove the hard disk directly;

Verification: link to the virtual machine to see if the disk is disassembled?

[[email protected] ~]# virsh console centos7 
Connect to the domain centos7
The escape character is ^]


[[email protected] ~]# fdisk -l

Disk /dev/vda: 10.7 GB, 10737418240 bytes, 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x000a5c54

   Device Boot      Start         End      Blocks   Id  System
/dev/vda1   *        2048     1050623      524288   83  Linux
/dev/vda2         1050624    20971519     9960448   8e  Linux LVM

Disk /dev/mapper/centos-root: 10.2 GB, 10192158720 bytes, 19906560 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes


Disk /dev/mapper/centos-swap: 4 MB, 4194304 bytes, 8192 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

[[email protected] ~]#

Tip: you can see that there is only VDA but no VDB inside the virtual machine, which means that we have successfully removed the disk;

View removed disk information

[[email protected] ~]# qemu-img info /kvm/images/c1.img 
image: /kvm/images/c1.img
file format: raw
virtual size: 2.0G (2148073472 bytes)
disk size: 11M
[[email protected] ~]#

Tip: Here we need to explain that after we attach the disk to the virtual interior, if the disk is partitioned and formatted, its format will change to raw format by default;

4. Example: snapshot virtual machine;

[[email protected] ~]# virsh help snapshot-create-as
  NAME
    Snapshot create as - uses a set of parameters to generate a snapshot

  SYNOPSIS
    snapshot-create-as  [--name ] [--description ] [--print-xml] [--no-metadata] [--halt] [--disk-only] [--reuse-external] [--quiesce] [--atomic] [--live] [--memspec ] [[--diskspec] ]...

  DESCRIPTION
    Use a set of parameters to generate a snapshot (disk and RAM)

  OPTIONS
    [--domain]   domain name, id or uuid
    --Name snapshot name
    --Description snapshot description
    --Print XML outputs XML documents instead of generating XML
    --No metadata extracts the snapshot but does not generate metadata
    --Halt stop domain after snapshot
    --Disk only captures disk state instead of VM state
    --Reuse external reuses any existing external file
    --The file system of quiesce silent virtual machine
    --Atomic needs automatic operation
    --Live extract real time snapshot
    --Memspec memory attribute: [file] = name [, snapshot = type]
    [-- diskspec] disk properties: disk [, snapshot = type] [, driver = type] [, file = name]


[[email protected] ~]# virsh snapshot-create-as centos7 --name centos7-snap1 --description "touch test file before" 
Generated domain snapshot centos7-snap1
[[email protected] ~]# virsh snapshot-list centos7 
 Name generation time status
------------------------------------------------------------
 centos7-snap1        2017-03-29 02:44:58 +0800 running

[[email protected] ~]#

Tip: the above command uses command line parameters to create a virtual machine snapshot. By default, it will store the snapshot configuration file in / var / lib / libvirt / QEMU / snapshot / VM name / snapshot name. XML;

View snapshot file

[[email protected] ~]# ll /var/lib/libvirt/qemu/snapshot/
Total dosage 0
Drwxr-xr-x 2 root 31 March 29 02:45 centos7
[[email protected] ~]# tree /var/lib/libvirt/qemu/snapshot/
/var/lib/libvirt/qemu/snapshot/
└── centos7
    └── centos7-snap1.xml

1 directory, 1 file
[[email protected] ~]# cat /var/lib/libvirt/qemu/snapshot/centos7/centos7-snap1.xml 



  centos7-snap1
  touch test file before
  running
  1490726698
  
  
    
    
  
  
    centos7
    a15b793e-055b-4c91-89a5-ceba0c7ec98d
    1048576
    1048576
    2
    
      /machine
    
    
      hvm
      
    
    
      
      
    
    
      Broadwell
    
    
      
      
      
    
    destroy
    restart
    destroy
    
      
      
    
    
      /usr/libexec/qemu-kvm
      
        
        
        
        
      
      
        
        
        
        
      
      
        
      
      
        
        
      
      
        
        
      
      
        
        
      
      
        
      
      
        
      
      
      
        
        
        
        
      
      
        
          
        
      
      
        
      
      
        
        
      
      
        
      
      
      
      
        
      
      
        
        
      
      
        
      
      
        /dev/urandom
        
      
    
  
  
    
      Broadwell
      
      
      
    
  
  1

[[email protected] ~]#

5. Example: restore the virtual machine to the state of snapshot;

First, connect to the virtual machine without creating a new test file in the root directory, then shut down the virtual machine, restore to the snapshot state before creating the test file, and then turn on the virtual machine to see if it returns to the state before creating the test file?

[[email protected] ~]# virsh console centos7 
Connect to the domain centos7
The escape character is ^]


[[email protected] ~]# ls
anaconda-ks.cfg
[[email protected] ~]# echo "this is test file" >test.xml
[[email protected] ~]# cat test.xml
this is test file
[[email protected] ~]# 
[[email protected] ~]# virsh destroy centos7 
The domain centos7 was deleted

[[email protected] ~]# virsh list --all
 ID name status
----------------------------------------------------
 -Centos7 off

[[email protected] ~]# virsh domstate centos7
close

[[email protected] ~]#

Welcome the virtual machine to the snapshot state you just created

[[email protected] ~]# virsh snapshot-list centos7 
 Name generation time status
------------------------------------------------------------
 centos7-snap1        2017-03-29 02:44:58 +0800 running

[[email protected] ~]# virsh snapshot-revert centos7 centos7-snap1 

[[email protected] ~]# virsh list --all
 ID name status
----------------------------------------------------
 3     centos7                        running

[[email protected] ~]# virsh snapshot-current centos7 

  centos7-snap1
  touch test file before
  running
  1490726698
  
  
    
    
  
  
    centos7
    a15b793e-055b-4c91-89a5-ceba0c7ec98d
    1048576
    1048576
    2
    
      /machine
    
    
      hvm
      
    
    
      
      
    
    
      Broadwell
    
    
      
      
      
    
    destroy
    restart
    destroy
    
      
      
    
    
      /usr/libexec/qemu-kvm
      
        
        
        
        
      
      
        
        
        
        
      
      
        
      
      
        
        
      
      
        
        
      
      
        
        
      
      
        
      
      
        
      
      
      
        
        
        
        
      
      
        
          
        
      
      
        
      
      
        
        
      
      
        
      
      
      
      
        
      
      
        
        
      
      
        
      
      
        /dev/urandom
        
      
    
  
  
    
      Broadwell
      
      
      
    
  


[[email protected] ~]#

Tip: from the above information, we can see that after we restore the virtual machine to our snapshot state, the virtual machine is running, and the current virtual machine snapshot is centos7_ Snap1 is the snapshot we created before creating a new test file;

Verification: connect the virtual console to check whether the test file still exists?

[[email protected] ~]# virsh console centos7 
Connect to the domain centos7
The escape character is ^]


[[email protected] ~]# ls
anaconda-ks.cfg
[[email protected] ~]# pwd
/root
[[email protected] ~]#

Tip: you can see that there is no test file;

View current virtual machine disk file information

[[email protected] ~]# virsh domblklist centos7 
Target source
------------------------------------------------
vda        /kvm/images/centos7.qcow2
hda        -

[[email protected] ~]# qemu-img info /kvm/images/centos7.qcow2 
image: /kvm/images/centos7.qcow2
file format: qcow2
virtual size: 10G (10737418240 bytes)
disk size: 1.5G
cluster_size: 65536
Snapshot list:
ID        TAG                 VM SIZE                DATE       VM CLOCK
1         centos7-snap1          294M 2017-03-29 02:44:58   01:33:32.709
Format specific information:
    compat: 1.1
    lazy refcounts: false
[[email protected] ~]#

Tip: you can see that the disk information contains the snapshot information for the virtual machine;

The commands for virtual machine snapshots are

[[email protected] ~]# virsh help snapshot
 Snapshot (help keyword 'snapshot'):
    Snapshot create uses XML to generate snapshots
    Snapshot create as uses a set of parameters to generate a snapshot
    Snapshot current gets or sets the current snapshot
    Snapshot delete delete domain snapshot
    Snapshot dumpxml dumps XML for domain snapshot
    Snapshot edit edit snapshot XML
    Snapshot info snapshot information
    Snapshot list lists snapshots for the domain
    Snapshot parent gets the name of the superior snapshot of the snapshot
    Snapshot revert converts a domain to a snapshot

[[email protected] ~]#

Tip: the above commands are similar to other commands of virsh. I’ll just elaborate here. If I don’t know the command syntax, I can check the help information of each command to use it;