Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding KVM (Part 5)

Tech May 10 4

KVM (1) Deployment and Overview

I. KVM Overview

1.1 Virtualization Overview

In computer technology, virtualization means creating a virtual version of a device or resource, such as servers, storage devices, networks, or operating systems.

  • Types of virtualization technology:
    • System virtualization (the main focus)
    • Storage virtualization (RAID, LVM)
    • Network virtualization (SDN)
    • GPU virtualization (Bitcoin)
    • Software virtualization
    • Hardware-supported virtualization

1.1.1 System Virtualization

  • This type of virtualization typically involves running multiple operating systems on a single system
  • These virtual operating systems run simultaneously, with each being independent of the others

1.1.2 Three Ways to Implement Virtualization

(1) Pure software simulation

  • Creating a virtual platform by simulating a complete hardware environment
  • Simulating X86, ARM, PowerPC, and other CPUs
  • Low efficiency
  • QEMU, Bochs, PearPC

(2) Virtualization layer translation

  • Most virtualization uses a hypervisor
  • A hypervisor is a software layer or subsystem
    • Also known as VMM (Virtual Machine Monitor, virtual machine monitor)
  • Allows multiple operating systems to run on the same physical system
  • Controls hardware and provides access to the underlying hardware for user operating systems
  • Provides virtualized hardware to guest operating systems

Full virtualization without hardware assistance

  • Full virtualization based on binary translation
  • Hypervisor runs in Ring 0
  • Guest OS runs in Ring 1
  • Mechanism: exception, capture, translation
  • Examples:
    • VMware Workstation
    • QWMU
    • Virtual PC

Hardware-assisted full virtualization

  • Intel VT and AMD-V create a new Ring -1 for the hypervisor
  • Guest OS can directly use Ring 0 without modification
  • Examples:
    • VMware ESXi
    • Microsoft Hyper-V
    • Xen3.0
    • KVM

(3) Container Technology

1.2 KVM Overview and Related References

II. KVM Installation

2.1 Preparing the Environment

CentOS7.3 DVD image download address: http://man.linuxde.net/download/CentOS_7_3

2.1.1 Production Environment Hardware Configuration

  • CPU must support virtualization technology, enabled in BIOS
  • Most servers and desktop computers currently have this enabled

2.1.2 Experiment Preparation

We need to use a virtual machine first, then use virtualization within the virtual machine, i.e., nested virtualization

  • VMware nested virtualization
    • Products: Workstation, Player, ESXi
    • Support: ESXi, Hyper-V, KVM, Xen

2.2 KVM Installation

The virtual machine needs to install the following software during installation

After entering, ifconfig shows that

The network card does not have an IP address, we can open the ONBOOT in the network card configuration file

[root@localhost network-scripts]# pwd
/etc/sysconfig/network-scripts
[root@localhost network-scripts]# cat ifcfg-ens32 
TYPE=Ethernet
BOOTPROTO=dhcp
DEFROUTE=yes
PEERDNS=yes
PEERROUTES=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens32
UUID=17fb5987-5317-4bca-8514-9e1b73933184
DEVICE=ens32
#NBOOT=yes          #Enable this line

Then restart the network service

2.2.1 Solving Slow Xshell Connection in CentOS7.3

#Modify the ssh configuration file as follows
[root@localhost ~]# sed -n '93p;129p' /etc/ssh/sshd_config
GSSAPIAuthentication no
UseDNS no

#Restart the service
[root@localhost ~]# systemctl restart sshd

2.2.2 Resolving License Information Prompt in CentOS7.3

If license information (license not accepted) appears, it means you need to except the license. Enter 1 - Enter - 2 - Enter - c - Enter - c - Enter. This will solve the issue.

2.2.3 Setting Up a Local Yum Repository from CD-ROM and Installing Packages

#Set up a local CD-ROM source yum repository
[root@localhost ~]# cd /etc/yum.repos.d/
[root@localhost yum.repos.d]# ls
CentOS-Base.repo       CentOS-fasttrack.repo  CentOS-Vault.repo
CentOS-CR.repo         CentOS-Media.repo
CentOS-Debuginfo.repo  CentOS-Sources.repo
[root@localhost yum.repos.d]# mkdir bak
[root@localhost yum.repos.d]# mv C* bak/
[root@localhost yum.repos.d]# vim local.repo
[root@localhost yum.repos.d]# cat local.repo 
[local]
name=local
baseurl=file:///media/cdrom/
gpgcheck=0
enabled=1
[root@localhost yum.repos.d]# mount /dev/sr0 /media/cdrom/
mount: /dev/sr0 is read-only, mounting read-only
[root@localhost yum.repos.d]# yum -y clean all
Loaded plugins: fastestmirror, langpacks
Cleaning up everything
Cleaning up list of fastest mirrors
[root@localhost yum.repos.d]# yum makecache
Loaded plugins: fastestmirror, langpacks
local                                                | 3.6 kB     00:00     
(1/4): local/filelists_db                              | 3.0 MB   00:00     
(2/4): local/group_gz                                  | 155 kB   00:00     
(3/4): local/other_db                                  | 1.3 MB   00:00     
(4/4): local/primary_db                                | 3.0 MB   00:00     
Determining fastest mirrors
Metadata cache updated

The installation method has already installed the following software groups

@base
@core
@virtualization-hypervisor              #Virtualization Host option
@virtualization-platform                #Virtualization Platform option
@virtualization-tools                   #Virtualization Host option

We also need to add the following software packages

@virtualization-client
@gnome-desktop

#Install package groups
[root@localhost ~]# yum -y group install virtualization-client
[root@localhost ~]# yum -y group install gnome-desktop

2.2.3 Modify Virtualization Engine Configuration and Check CPU Features

#Check CPU features
[root@localhost ~]# grep vmx /proc/cpuinfo
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts nopl xtopology tsc_reliable nonstop_tsc aperfmperf eagerfpu pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ida arat epb pln pts dtherm hwp hwp_noitfy hwp_act_window hwp_epp tpr_shadow vnmi ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid rtm rdseed adx smap xsaveopt

[root@localhost ~]# egrep '^flags.*(vmx|svm)' /proc/cpuinfo 
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts nopl xtopology tsc_reliable nonstop_tsc aperfmperf eagerfpu pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ida arat epb pln pts dtherm hwp hwp_noitfy hwp_act_window hwp_epp tpr_shadow vnmi ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid rtm rdseed adx smap xsaveopt


2.3 KVM Remote Management

[root@localhost ~]# which virsh #Check virtual machine management commands
/usr/bin/virsh
[root@localhost ~]# virsh list --all    #Check all virtual machines
 Id    Name                         State
----------------------------------------------------

[root@localhost ~]# startx    #Switch to graphical interface mode

In the graphical interface, select Application at the top-left corner

However, in our work, we usually need to manage the KVM environment remotely. SSH mode cannot display the desktop mode.

2.3.1 Two Remote Management Methods for KVM

(1) SSH Graphical Display

Install software x-manager on Windows. Then enable X11 forwarding in Xshell.

After connecting to the virtual machine, enter virt-manager as shown below

(2) VNC Graphical Display

VNC is an excellent remote management software, consisting of two parts: VNCServer and VNCViewer.

#Check if necessary packages are present
[root@localhost ~]# rpm -qa | grep vnc
tigervnc-license-1.3.1-9.el7.noarch     #Required
gtk-vnc2-0.5.2-7.el7.x86_64
gvnc-0.5.2-7.el7.x86_64
tigervnc-server-minimal-1.3.1-9.el7.x86_64  #Required


#Install vnc-server
[root@localhost ~]# yum -y install tigervnc-server  #Install server package
[root@localhost ~]# cat /etc/sysconfig/vncservers   #Check vnc configuration file
# THIS FILE HAS BEEN REPLACED BY /lib/systemd/system/vncserver@.service
[root@localhost ~]# ll /lib/systemd/system/vncserver@.service   #This is the actual configuration file
-rw-r--r--. 1 root root 1880 11月 16 2016 /lib/systemd/system/vncserver@.service

#Then we need to create a vnc password
[root@localhost ~]# vncpasswd
Password:
Verify:

#Start vnc-server
[root@localhost ~]# vncserver

New 'localhost.localdomain:1 (root)' desktop is localhost.localdomain:1

Creating default startup script /root/.vnc/xstartup
Starting applications specified in /root/.vnc/xstartup
Log file is /root/.vnc/localhost.localdomain:1.log

[root@localhost ~]# ps aux | grep vnc
root       6241  0.9  1.6 250192 31032 pts/0    Sl   10:07   0:00 /usr/bin/vnc :1 -desktop localhost.localdomain:1 (root) -auth /root/.Xauthority -geometry 1024x768 -rfbwait 30000 -rfbauth /root/.vnc/passwd -rfbport 5901 -fp catalogue:/etc/X11/fontpath.d -pn
root       6250  0.0  0.2  96716  4068 pts/0    S    10:07   0:00 /usr/bin/vncconfig -iconic
root       6991  0.0  0.0 112668   972 pts/0    S+   10:07   0:00 grep --color=auto vnc


Then we need to disable the firewall in CentOS7.3

[root@localhost ~]# service firewalld stop  #Otherwise, the VNC client cannot connect
Redirecting to /bin/systemctl stop  firewalld.service
[root@localhost ~]# systemctl disable firewalld.service #Permanently disable the firewall

Next, install the VNC client on the Windows host

https://www.realvnc.com/en/connect/download/viewer/ You can download the VNC viewer

III. Creating a Virtual Machine

3.1 Using virt-manager to Create a Virtual Machine

  • Basic usage of virt-manager
  • Experiment
    • Environmental preparation
    • Create a Windows virtual machine
    • Create a Linux virtual machine

(1) We need to add an 80G hard drive to store the operating system installation media, ISO files

(2) Use fdisk to create a 40G partition

[root@localhost ~]# ll /dev/sdb*
brw-rw----. 1 root disk 8, 16 Apr  4 08:48 /dev/sdb
brw-rw----. 1 root disk 8, 17 Apr  4 08:48 /dev/sdb1    #40G


(3) Create an LVM logical volume

[root@localhost ~]# ll /dev/sdb*
brw-rw----. 1 root disk 8, 16 Apr  4 08:48 /dev/sdb
brw-rw----. 1 root disk 8, 17 Apr  4 08:48 /dev/sdb1
[root@localhost ~]# pvcreate /dev/sdb1
  Physical volume "/dev/sdb1" successfully created.
[root@localhost ~]# vgcreate vmvg /dev/sdb1
  Volume group "vmvg" successfully created
[root@localhost ~]# vgs
  VG   #PV #LV #SN Attr   VSize  VFree 
  cl     1   2   0 wz--n- 19.00g     0 
  vmvg   1   0   0 wz--n- 40.00g 40.00g
[root@localhost ~]# vgdisplay       #View vg details
  --- Volume group ---
  VG Name               cl
  System ID             
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  3
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                2
  Open LV               2
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               19.00 GiB
  PE Size               4.00 MiB
  Total PE              4863
  Alloc PE / Size       4863 / 19.00 GiB
  Free  PE / Size       0 / 0   
  VG UUID               6ROh78-78oc-QfPu-1YnI-pW76-TiFa-4kWjSQ
   
  --- Volume group ---
  VG Name               vmvg
  System ID             
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  1
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                0
  Open LV               0
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               40.00 GiB
  PE Size               4.00 MiB
  Total PE              10239
  Alloc PE / Size       0 / 0   
  Free  PE / Size       10239 / 40.00 GiB       #vmvg available PE total 10239
  VG UUID               Hxeycr-8UEv-qiF2-JTZi-txEl-E5G7-Iho3x5
   
[root@localhost ~]# lvcreate -n lvvm1 -l 10239 vmvg     #Allocate all available PE of vmvg to lvvm1
  Logical volume "lvvm1" created.
[root@localhost ~]# lvs
  LV    VG   Attr       LSize  Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert
  root  cl   -wi-ao---- 17.00g                                                    
  swap  cl   -wi-ao----  2.00g                                                    
  lvvm1 vmvg -wi-a----- 40.00g                                                    
[root@localhost ~]# mkfs.ext4 /dev/vmvg/lvvm1   Format lvvm1


(4) Mount the logical volume

[root@localhost ~]# mkdir /vm
[root@localhost ~]# mount /dev/vmvg/lvvm1 /vm/
[root@localhost ~]# df -hT
Filesystem             Type      Size  Used Avail Use% Mounted on
/dev/mapper/cl-root    xfs        17G  3.7G   14G  22% /
devtmpfs               devtmpfs  901M     0  901M   0% /dev
tmpfs                  tmpfs     912M     0  912M   0% /dev/shm
tmpfs                  tmpfs     912M  8.9M  903M   1% /run
tmpfs                  tmpfs     912M     0  912M   0% /sys/fs/cgroup
/dev/sda1              xfs      1014M  144M  871M  15% /boot
tmpfs                  tmpfs     183M     0  183M   0% /run/user/0
/dev/mapper/vmvg-lvvm1 ext4       40G   49M   38G   1% /vm
[root@localhost ~]# echo "mount /dev/vmvg/lvvm1 /vm/" >> /etc/rc.local


(5) Create a directory for storing ISO image files

[root@localhost ~]# mkdir /ios
root@localhost ~]# cd /iso/
[root@localhost iso]# ls
CentOS-6.5-x86_64-bin-DVD1.iso

Upload the CD installation image file to the /ios directory:

3.1.1 Basic Usage of virt-manager

  • Start virt-manager
  • Main window of virtual machine management
  • Hardware details window
    • Configure virtual machine boot options
    • Attach USB devices to the virtual machine
    • Prepare work
    • USB redirection
  • Virtual machine graphical console
  • Add remote connection
  • Display virtual machine details
  • Performance monitoring

(1) Create a virtual machine using the default settings of the wizard

Start the VNC remote management program to connect to Linux, open Virtual Machine Manager

Click to create a new virtual machine

Select the local ISO image installation

Finally, the new virtual machine automatically enters the installation state

Students choose English, minimal installation. Since we are using nested virtualization, the graphical interface may be slightly laggy. It's okay, just wait a bit.

Special Note:

When managing and creating a virtual machine manually with virt-manager, there is a high chance of keyboard failure when entering the operating system installation interface. If students encounter this problem, do not panic, as it is due to character set confusion. Adjust the virtual machine settings, and it will be resolved.

Then we normally boot and enter the installation interface, and you will find that the keyboard operation is restored.

(2) Create a virtual machine using custom planning

We found that using the default method of the wizard to install the virtual machine, the virtual machine's disk is not placed in the directory we planned

Therefore, in the work, we need to perform custom storage pool operations during the installation process, as follows

At this point, the new VM storage pool has been created, but we still need to create a Volume volume (disk) in the storage pool

Then we enter the operating system installation interface. After installation, we check and find that the disk location has been modified.

3.2 Creating a Virtual Machine Using virt-install

#Create a virtual machine's storage disk
[root@localhost ~]# qemu-img create -f qcow2 /vm/chensiqi.qcow2 10G #qcow2 format disk /vm/chensiqi.qcow2 disk location 10G disk size
Formatting '/vm/chensiqi.qcow2', fmt=qcow2 size=10737418240 encryption=off cluster_size=65536 lazy_refcounts=off 
[root@localhost ~]# ll -h /vm/
Total size 1.1G
-rw-------. 1 qemu qemu 8.1G 4月   9 12:26 centos6.5-2.qcow2    #Actually takes up 8G
-rw-r--r--  1 qemu qemu 193K 4月   9 12:09 chensiqi.qcow2       #Just a small file
drwx------  2 root root  16K 4月   4 09:03 lost+found

The disk created by qemu-img is initially a small file, until the disk space is filled. How ever, the disk created by virt-manager actually occupies 8G

#Create a virtual machine
[root@localhost ~]# virt-install \  #Command to create a virtual machine
> --name=vm1 \  #Name of the virtual machine
> --disk path=/vm/chensiqi.qcow2 \  #Path of the virtual disk
> --vcpus=1 --ram=1024 \        #CPU and memory size allocated
> --cdrom=/iso/CentOS-6.5-x86_64-bin-DVD1.iso \ #Location of the system installation disc
> --network network=default \   #Network mode, default is NAT
> --graphics vnc,listen=0.0.0.0 \   #Display type of the virtual machine is VNC
> --os-type=linux \
> --os-variant=rhel6


Executing the above command will open the Virt Viewer window and enter the installation interface

3.3 Semi-Virtualization Driver virtio

3.3.1 Purpose of Using the Semi-Virtualization Driver virtio

The device access path without virtio in full virtualization is as follows:

The device access path with virtio in full virtualization is as follows:

3.3.2 Unified Interface Principle of Semi-Virtualization Devices in virtio

3.3.3 Linux Virtual Machines Directly Selecting the virtio Semi-Virtualization Driver

3.4 QEMU Guest Agent

  • If the VM has installed the QEMU guest agent, the Host can use libivrt to send commands to the VM, such as "freeze", "unfreeze" file systems, hot addition and removal of virtual CPUs, etc.
  • RHEL/CentOS7 has the corresponding installation package. qemu-guest-agent-xxx.rpm
  • Windows requires manual installation
#This management package is already installed
[root@localhost ~]# rpm -qa | grep qemu-guest-agent
qemu-guest-agent-2.5.0-3.el7.x86_64
[root@localhost ~]# which virsh
/usr/bin/virsh

Using the QEMU guest agent through libvirt

IV. Managing Virtual Machines

4.1 Overview of the libvirt Architecture

libvirtd is a daemon process, and virsh, virt-install, etc., rely on this daemon process to indirectly access qemu-kvm and configuration files. If this process is closed, then virsh, virt-install, and virt-manager will not be able to access it. (Students can try it.)

4.2 Managing Virtual Machines Using virt-manager

  • Main functions of virt-manager:
    • Define and create virtual machines
    • Hardware management
    • Performance monitoring
    • Saving and restoring virtual machines, pausing and resuming, shutting down and starting
    • Console
    • Online and offline migration
  • virt-manager
    • Method 1: Applications menu > System Tools > Virtual Machine Manager (virt-manager)
    • Method 2: Enter virt-manager in an SSH session

4.3 Managing Virtual Machines Using virsh

4.3.1 Overview of virsh

  • virsh is a management tool built using the libvirt management API

  • The name of virsh means virtualization shell. It has two working modes

    • Immediate mode
        [root@localhost ~]# virsh list --all
     Id    Name                         State
    ----------------------------------------------------
     3     centos6.5-2                    running
     14    vm2                            running
     -     centos6.5                      shutdown
    
    
    
    
    • Interactive mode
        [root@localhost ~]# virsh
    Welcome to virsh, the virtualization interactive terminal.
    
    Input: 'help' for command help
           'quit' to exit
    
    virsh # list --all
     Id    Name                         State
    ----------------------------------------------------
     3     centos6.5-2                    running
     14    vm2                            running
     -     centos6.5                      shutdown
    
    virsh # 
    
    
    

4.3.2 About virsh Command Helpp

There are many commands supported by virsh. It is recommended that students check the help of virsh.

[root@localhost ~]# virsh --help

virsh [options]... [<command_string>]
virsh [options]... <command> [args...]

  options:
    -c | --connect=URI      hypervisor connection URI
    -d | --debug=NUM        debug level [0-4]
    -e | --escape <char>    set escape sequence for console
    -h | --help             this help
    -k | --keepalive-interval=NUM
                            keepalive interval in seconds, 0 for disable
    -K | --keepalive-count=NUM
                            number of possible missed keepalive messages
    -l | --log=FILE         output logging to file
    -q | --quiet            quiet mode
    -r | --readonly         connect readonly
    -t | --timing           print timing information
    -v                      short version
    -V                      long version
         --version[=TYPE]   version, TYPE is short or long (default short)
  commands (non interactive mode):

 **Some text omitted**


4.3.3 Common virsh Commands

CommandOverviewattach-deviceAdd a device defined in an XML file to the virtual machineattach-diskAttach a new disk device to the virtual machineattach-interfaceAttach a new network interface to the virtual machinecreateCreate and start a new virtual machine from an XML configuration filedefineOutput an XML configuration file for the virtual machinedestroyForce the virtual machine to stopdetach-deviceDetach a device from the virtual machine, using the same XML description as the attach-device commanddetach-diskDetach a disk device from the virtual machinedetach-interfaceDetach a network interface from the virtual machinedomblkstatDisplay block device statistics for a running virtual machinedomidDisplay the virtual machine IDdomifstatDisplay network interface statistics for a running virtual machinedominfoDisplay virtual machine informationdomnameDisplay the virtual machine namedomstateDisplay the virtual machine statedomuuidDisplay the virtual machine UUIDdumpxmlOutput the XML configuration file of the virtual machinehelpPrint basic help informationlistList all virtual machinesmigrateMigrate the virtual machine to another hostnodeinfoOutput information about the hypervisorquitExit this interactive terminalrebootReboot the virtual machinerestoreRestore a virtual machine saved in a fileresumeResume a suspended virtual machinesaveSave the current state of a virtual machine to a filesetmaxmemSet the memory limit for the hypervisorsetmemSet the memory allocated to the virtual machinesetvcpusModify the number of virtual CPUs allocated to the virtual machineshutdownShut down a virtual machinestartStart an inactive virtual machinesuspendSuspend the virtual machineundefineDelete all files associated with the virtual machinevcpuinfoDisplay virtual CPU information for the virtual machinevcpupinControl the virtual CPU affinity of the virtual machineversionDisplay the virsh version

4.3.4 Practical Demonstration of virsh Managing Virtual Machines

(1) Starting and Shutting Down Virtual Machines via Commands

#Manage virtual machines in interactive mode
#Start the virtual machine
[root@localhost ~]# virsh   #Enter interactive mode
Welcome to virsh, the virtualization interactive terminal.

Input: 'help' for command help
       'quit' exit

virsh # list    #Display all running virtual machines
 Id    Name                         State
----------------------------------------------------
 3     centos6.5-2                    running
 14    vm2                            running

virsh # list --all  #Display all virtual machines
 Id    Name                         State
----------------------------------------------------
 3     centos6.5-2                    running
 14    vm2                            running
 -     centos6.5                      shutdown

virsh # start centos6.5 #Start the virtual machine named centos6.5
Domain centos6.5 started

virsh # list --all
 Id    Name                         State
----------------------------------------------------
 3     centos6.5-2                    running
 14    vm2                            running
 15    centos6.5                      running   #Already started

#Shut down the virtual machine
virsh # shutdown 14 #Shutdown gracefully, but sometimes this doesn't work
Domain 14 was shut down

virsh # list --all
 Id    Name                         State
----------------------------------------------------
 3     centos6.5-2                    running
 14    vm2                            running   #Still running
 -     centos6.5                      shutdown

virsh # destroy 14      #Forcefully shut down the virtual machine
Domain 14 destroyed

virsh # list --all
 Id    Name                         State
----------------------------------------------------
 3     centos6.5-2                    running
 -     centos6.5                      shutdown
 -     vm2                            shutdown      #Was forcefully shut down.

(2) Setting the Virtual Machine to Automatically Boot on Host Startup via Commands

Regarding whether the host automatically starts the virtual machine upon boot, we can set it through the virtual machine's graphical interface or commands. The graphical interface setting method is as follows:

[root@localhost ~]# virsh list --all
 Id    Name                         State
----------------------------------------------------
 1     vm2                            running   #After setting the host to automatically start, after reboot, the virtual machine starts automatically
 -     centos6.5                      shutdown
 -     centos6.5-2                    shutdown


We can control the automatic boot of the virtual machine via commands

[root@localhost ~]# virsh   
Welcome to virsh, the virtualization interactive terminal.

Input: 'help' for command help
       'quit' exit

virsh # help autostart  #Check autostart help
  NAME
    autostart - Automatically start a domain

  SYNOPSIS
    autostart <domain> [--disable]

  DESCRIPTION
    Set a domain to start automatically when the system boots.

  OPTIONS
    [--domain] <string>  Domain name, id or uuid   #You can control it by domain name, id or uuid
    --disable        Disable automatic start


virsh # list --all
 Id    Name                         State
----------------------------------------------------
 1     vm2                            running
 -     centos6.5                      shutdown
 -     centos6.5-2                    shutdown

virsh # autostart centos6.5 #Enable automatic boot for the virtual machine
Domain centos6.5 marked as autostart

virsh # autostart centos6.5 --disable   #Disable automatic boot for the virtual machine
Domain centos6.5 unmarked as autostart

virsh # autostart centos6.5
Domain centos6.5 marked as autostart


After restarting the host, we find that the virtual machine can now start automatically

[root@localhost ~]# virsh list --all
 Id    Name                         State
----------------------------------------------------
 1     vm2                            running
 2     centos6.5                      running
 -     centos6.5-2                    shutdown


(3) Suspending and Resuming Virtual Machines via Commands

[root@localhost ~]# virsh
Welcome to virsh, the virtualization interactive terminal.

Input: 'help' for command help
       'quit' exit

virsh # help suspend    #Check command help
  NAME
    suspend - Suspend a domain

  SYNOPSIS
    suspend <domain>

  DESCRIPTION
    Suspend a running domain.

  OPTIONS
    [--domain] <string>  Domain name, id or uuid


virsh # list --all
 Id    Name                         State
----------------------------------------------------
 1     vm2                            running
 2     centos6.5                      running
 -     centos6.5-2                    shutdown

virsh # suspend vm2 #Suspend the virtual machine
Domain vm2 is suspended

virsh # list --all
 Id    Name                         State
----------------------------------------------------
 1     vm2                            Suspended      #Success
 2     centos6.5                      running
 -     centos6.5-2                    shutdown

virsh # resume vm2  #Resume the virtual machine
Domain vm2 is resumed

virsh # list --all
 Id    Name                         State
----------------------------------------------------
 1     vm2                            running
 2     centos6.5                      running
 -     centos6.5-2                    shutdown<br></br>

Tags: KVM

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.