kvm虚拟化
1. KVM简介
在我们介绍KVM之前,首先必须要认识什么是虚拟化,KMV就是在虚拟化不断发展和优化的过程中而逐渐成熟的一个技术。
根据统计,大部分企业的服务器和数据中心能效实际上很低,日常的服务器使用率甚至不足10%,其他的处理能力一直处于空闲状态。从资源成本的角度来看,这是很不合理的,给企业带来了很大的资源浪费。
考虑到这种情况,就有了虚拟化技术的发展,应如何高效的利用服务器资源?虚拟化使得在一台物理的服务器上可以跑多台虚拟机,虚拟机共享物理机的 CPU、内存、IO 硬件资源,但逻辑上虚拟机之间是相互隔离的。
- 最初虚拟化技术是从CPU的分片开始,高效的利用CPU。1961年,IBM709机器实现了分时系统,将CPU占用切分为多个极短的时间片(1/100sec)每一个时间片执行不同的工作,通过对这些时间片进行轮询,从而将一个CPU伪装成多个CPU。
- 1972年, IBM正式将system370机的分时系统命名为虚拟机。
- 1990年, IBM推出的system390机支持逻辑分区(将一个CPU分为多份,相互独立,也就是逻辑分割)
- 2003年Xen问世,它是一个外部的hypervisor程序(虚拟机管理程序),能够控制虚拟机和给多个客户机分配资源。但是,由于它是外部程序软件,在和内核的联系过程过程中中,有性能损耗,以及性能的瓶颈。支持全虚拟化和半虚拟化。
2007年KVM问世,Kernel-based Virtual Machine的简称,现已内置在kernel内核中,支持全虚拟化。 - 广义的KVM实际上包含两部分,一部分是基于LINUX内核支持的KVM内核模块,另一部分就是经过简化和修改的Qemu。
- KWM内核模块模拟处器和内存以支持虚拟机的运行,Qemu主要处理
I/0以及为用户提供一个用户空间工具来进行虛拟机的管理。两者相互结合,相辅相成,构成了一个完整的虚拟化平台。
注意: Qemu本身并不是KVI的一部分,Qemu 是一套完整的虚拟化解决方案,是纯软件实现虚拟化,包括处理器虚拟化、内存虚拟化以及各种虚拟设备的模拟,但因为是纯软件模拟出来的,所以Qemu的性能比较低。
2. 虚拟化类型
全虚拟化:
Hypervisor 直接安装在物理机上,多个虚拟机在 Hypervisor 上运行。Hypervisor 实现方式一般是一个特殊定制的 Linux 系统。Xen 和 VMWare 的 ESXi 都属于这个类型
半虚拟化:
物理机上首先安装常规的操作系统,比如 Redhat、Ubuntu 和 Windows。Hypervisor 作为 OS 上的一个程序模块运行,并对管理虚拟机进行管理。KVM、VirtualBox 和 VMWare Workstation 都属于这个类型
3. KVM 运行时的三种模式
➢客户模式:可以简单理解成客户机在操作系统运行中的模式,客户模式又分为内核模式和用户模式。
➢用户模式:为用户提供虚拟机管理的用户空间工具以及代表用户执行I/0,Qem运行在这个模式之下。
➢内核模式:模拟CPU以及内存,实现客户模式的切换,处理从客户模式的退出。KVI内核模块运行在这个模式下。
KVM工作原理
- KVM的大致工作原理:用户模式的Qemu利用接口libkvm通过ioctl系统调用进入内核模式。KVMDriver为虚拟机创建虚拟CPU和虚拟内存,然后执行VMLAUNCH指令进入客户模式,装载Guest
OS并运行。Guest OS运行过程中如果发生中断或者影子缺页等异常,将暂停Guest
OS的运行并保存当前上下文退出到内核模式来处理这些异常。内核模式处理这些异常时如果不需要I/O则处理完成后重新进入客户模式,如果需要I/O则进入到用户模式,由Qemu来处理I/O,处理完成后进入内核模式,再进入客户模式。
4. kvm部署
系统类型 | IP |
---|---|
REHL8.2 | 192.168.200.146 |
REHL7.5 | 192.168.200.151 |
CENTOS8 | 192.168.200.150 |
kvm
//关闭防火墙
[root@kvm ~]# systemctl stop firewalld
[root@kvm ~]# vim /etc/selinux/config
SELINUX=disabled
[root@kvm ~]# reboot
//配置网络源
[root@kvm yum.repos.d]# curl -o /etc/yum.repos.d/CentOS7-Base-163.repo http://mirrors.163.com/.help/CentOS7-Base-163.repo
[root@kvm ~]# sed -i 's/\$releasever/7/g' /etc/yum.repos.d/CentOS7-Base-163.repo
[root@kvm ~]# sed -i 's/^enabled=.*/enabled=1/g' /etc/yum.repos.d/CentOS7-Base-163.repo
//验证CPU是否支持KVM;如果结果中有vmx(Intel)或svm(AMD)字样,就说明CPU的支持的
[root@kvm ~]# egrep -o 'vmx|svm' /proc/cpuinfo
vmx
vmx
vmx
vmx
//kvm安装
[root@kvm ~]# yum -y install epel-release vim wget net-tools git unzip zip gcc gcc-c++ qemu-kvm qemu-kvm-common qemu-img virt-manager libvirt python3-libvirt libvirt-client virt-install virt-viewer bridge-utils libguestfs-tools
//配置桥接网卡
[root@kvm ~]# cp /etc/sysconfig/network-scripts/ifcfg-ens160 /etc/sysconfig/network-scripts/ifcfg-br0
[root@kvm ~]# cd /etc/sysconfig/network-scripts/
[root@kvm network-scripts]# vim ifcfg-br0
[root@kvm network-scripts]# cat ifcfg-br0
TYPE=Bridge
DEVICE=br0
BOOTPROTO=static
NAME=br0
ONBOOT=yes
IPADDR=192.168.200.150
NETMASK=255.255.255.0
GATEWAY=192.168.200.2
DNS1=114.114.114.114
[root@kvm network-scripts]# vim ifcfg-ens160
[root@kvm network-scripts]# cat ifcfg-ens160
TYPE=Ethernet
DEVICE=ens33
BOOTPROTO=static
NAME=ens33
ONBOOT=yes
BRIDGE=br0
[root@kvm network-scripts]# systemctl restart NetworkManager
[root@kvm network-scripts]# ifdown ens160;ifup ens160
[root@kvm network-scripts]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq master br0 state UP group default qlen 1000
link/ether 00:0c:29:2b:b2:f4 brd ff:ff:ff:ff:ff:ff
3: br0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
link/ether 00:0c:29:2b:b2:f4 brd ff:ff:ff:ff:ff:ff
inet 192.168.200.150/24 brd 192.168.200.255 scope global noprefixroute br0
valid_lft forever preferred_lft forever
inet6 fe80::1879:1eff:febf:f76/64 scope link
valid_lft forever preferred_lft forever
//启动服务
[root@kvm ~]# systemctl enable --now libvirtd
[root@kvm ~]# systemctl status libvirtd
● libvirtd.service - Virtualization daemon
Loaded: loaded (/usr/lib/systemd/system/libvirtd.servic>
Active: active (running) since Wed 2021-10-20 13:35:47 >
//验证安装结果
[root@kvm ~]# lsmod | grep kvm
kvm_intel 294912 0
kvm 786432 1 kvm_intel
irqbypass 16384 1 kvm
[root@kvm ~]# ln -s /usr/libexec/qemu-kvm /usr/bin/
[root@kvm ~]# which qemu-kvm
/usr/bin/qemu-kvm
//查看网桥信息
[root@kvm ~]# brctl show
bridge name bridge id STP enabled interfaces
br0 8000.000c292bb2f4 no ens160
virbr0 8000.52540004f6b6 yes virbr0-nic
kvm2
//关闭防火墙
[root@kvm ~]# systemctl stop firewalld
[root@kvm ~]# vim /etc/selinux/config
SELINUX=disabled
[root@kvm ~]# reboot
//配置网络源
[root@kvm yum.repos.d]# curl -o /etc/yum.repos.d/CentOS7-Base-163.repo http://mirrors.163.com/.help/CentOS7-Base-163.repo
[root@kvm ~]# sed -i 's/\$releasever/7/g' /etc/yum.repos.d/CentOS7-Base-163.repo
[root@kvm ~]# sed -i 's/^enabled=.*/enabled=1/g' /etc/yum.repos.d/CentOS7-Base-163.repo
//验证CPU是否支持KVM;如果结果中有vmx(Intel)或svm(AMD)字样,就说明CPU的支持的
[root@kvm ~]# egrep -o 'vmx|svm' /proc/cpuinfo
vmx
vmx
vmx
vmx
//kvm安装
[root@kvm ~]# yum -y install epel-release vim wget net-tools git unzip zip gcc gcc-c++ qemu-kvm qemu-kvm-common qemu-img virt-manager libvirt python3-libvirt libvirt-client virt-install virt-viewer bridge-utils libguestfs-tools
//配置桥接网卡
[root@kvm ~]# cp /etc/sysconfig/network-scripts/ifcfg-ens160 /etc/sysconfig/network-scripts/ifcfg-br0
[root@kvm ~]# cd /etc/sysconfig/network-scripts/
[root@kvm network-scripts]# vim ifcfg-br0
[root@kvm network-scripts]# cat ifcfg-br0
TYPE=Bridge
DEVICE=br0
BOOTPROTO=static
NAME=br0
ONBOOT=yes
IPADDR=192.168.200.146
NETMASK=255.255.255.0
GATEWAY=192.168.200.2
DNS1=114.114.114.114
[root@kvm network-scripts]# vim ifcfg-ens160
[root@kvm network-scripts]# cat ifcfg-ens160
TYPE=Ethernet
DEVICE=ens160
BOOTPROTO=static
NAME=ens160
ONBOOT=yes
BRIDGE=br0
[root@kvm network-scripts]# systemctl restart NetworkManager
[root@kvm network-scripts]# ifdown ens160;ifup ens160
[root@kvm network-scripts]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq master br0 state UP group default qlen 1000
link/ether 00:0c:29:2b:b2:f4 brd ff:ff:ff:ff:ff:ff
3: br0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
link/ether 00:0c:29:2b:b2:f4 brd ff:ff:ff:ff:ff:ff
inet 192.168.200.146/24 brd 192.168.200.255 scope global noprefixroute br0
valid_lft forever preferred_lft forever
inet6 fe80::1879:1eff:febf:f76/64 scope link
valid_lft forever preferred_lft forever
//启动服务
[root@kvm ~]# systemctl enable --now libvirtd
[root@kvm ~]# systemctl status libvirtd
● libvirtd.service - Virtualization daemon
Loaded: loaded (/usr/lib/systemd/system/libvirtd.servic>
Active: active (running) since Wed 2021-10-20 13:35:47 >
//验证安装结果
[root@kvm ~]# lsmod | grep kvm
kvm_intel 294912 0
kvm 786432 1 kvm_intel
irqbypass 16384 1 kvm
[root@kvm ~]# ln -s /usr/libexec/qemu-kvm /usr/bin/
[root@kvm ~]# which qemu-kvm
/usr/bin/qemu-kvm
//查看网桥信息
[root@kvm ~]# brctl show
bridge name bridge id STP enabled interfaces
br0 8000.000c292bb2f4 no ens160
virbr0 8000.52540004f6b6 yes virbr0-nicsh
kvm web管理界面安装
//安装依赖包
[root@kvm-web ~]# yum -y install git python2-pip python3-libvirt python3-libxml2 python3-websocket-client supervisor nginx python2-devel
//从github上下载webvirtmgr代码
[root@kvm-web ~]# cd /usr/src/
[root@kvm-web src]# ls
debug kernels
[root@kvm-web src]# git clone git://github.com/retspen/webvirtmgr.git
正克隆到 'webvirtmgr'...
remote: Enumerating objects: 5614, done.
remote: Total 5614 (delta 0), reused 0 (delta 0), pack-reused 5614
接收对象中: 100% (5614/5614), 2.97 MiB | 2.15 MiB/s, 完成.
处理 delta 中: 100% (3606/3606), 完成.
//安装webvirtmgr
[root@kvm-web src]# cd webvirtmgr/
[root@kvm-web webvirtmgr]# pip2 install -r requirements.txt
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip2 install --user` instead.
Collecting django==1.5.5 (from -r requirements.txt (line 1))
webvirtmgr
......
Running setup.py install for django ... done
Successfully installed django-1.5.5 gunicorn-19.5.0 lockfile-0.12.
[root@kvm-web webvirtmgr]# ln -s /usr/bin/python2 /usr/bin/python
//初始化
[root@kvm-web webvirtmgr]# ./manage.py syncdb
WARNING:root:No local_settings file found.
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table servers_compute
Creating table instance_instance
Creating table create_flavor
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'root'): admin
Email address: 1@2.com
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 6 object(s) from 1 fixture(s)
//创建网站存放目录
[root@kvm-web webvirtmgr]# mkdir /var/www
[root@kvm-web webvirtmgr]# cd ..
[root@kvm-web src]# cp -r webvirtmgr/ /var/www/
[root@kvm-web src]# chown -R nginx.nginx /var/www/webvirtmgr/
//生成密钥 因为是在一台主机上 所以传给本主机 如果有其他kvm主机传给他即可管理
[root@kvm-web src]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:weXNRmypmHOZCX9AGfHTqnm5iaCJsBxpgM/7vTK806M root@kvm-web
The key's randomart image is:
+---[RSA 3072]----+
| .==.. |
| ..oo=+. |
| o=.B* . |
|. +.B..o |
|o So .. |
| + . o . |
| B. . . o o |
| o ==ooo . o o |
| +.E*=o . o |
+----[SHA256]-----+
[root@kvm-web src]# ssh-copy-id root@192.168.200.146
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.200.146 (192.168.200.146)' can't be established.
ECDSA key fingerprint is SHA256:lHjJVpgxAHQML7Nzdt8CT4/1AZePELgM5EEUPTONw9A.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.200.146's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.200.146'"
and check to make sure that only the key(s) you wanted were added.
//端口转发
[root@kvm-web src]# ssh root@192.168.200.146 -L localhost:8000:localhost:8000 -L localhost:6080:localhost:60
Last login: Wed Oct 20 11:58:43 2021
[root@kvm-web ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 32 192.168.122.1:53 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 127.0.0.1:6080 0.0.0.0:*
LISTEN 0 128 127.0.0.1:8000 0.0.0.0:*
LISTEN 0 128 0.0.0.0:111 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 128 [::1]:6080 [::]:*
LISTEN 0 128 [::1]:8000 [::]:*
LISTEN 0 128 [::]:111 [::]:*
//配置nginx
[root@kvm-web ~]# vim /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
[root@kvm-web nginx]# cat /etc/nginx/conf.d/webvirtmgr.conf
server {
listen 80 default_server;
server_name $hostname;
#access_log /var/log/nginx/webvirtmgr_access_log;
location /static/ {
root /var/www/webvirtmgr/webvirtmgr;
expires max;
}
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $proxy_add_x_forwarded_for;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Forwarded-Proto $remote_addr;
proxy_connect_timeout 600;
proxy_read_timeout 600;
proxy_send_timeout 600;
client_max_body_size 1024M;
}
}
[root@kvm-web nginx]# vim /var/www/webvirtmgr/conf/gunicorn.conf.py
bind = '0.0.0.0:8000'
//重启nginx
[root@kvm-web nginx]# systemctl enable --now nginx
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.
[root@kvm-web nginx]# systemctl restart nginx
//再配置文件最后添加
[root@kvm-web nginx]# vi /etc/supervisord.conf
[program:webvirtmgr]
command=/usr/bin/python2 /var/www/webvirtmgr/manage.py run_gunicorn -c /var/www/webvirtmgr/conf/gunicorn.conf.py
directory=/var/www/webvirtmgr
autostart=true
autorestart=true
logfile=/var/log/supervisor/webvirtmgr.log
log_stderr=true
user=nginx
//启动服务
[root@kvm-web nginx]# systemctl enable --now supervisord
Created symlink /etc/systemd/system/multi-user.target.wants/supervisord.service → /usr/lib/systemd/system/supervisord.service.
[root@kvm-web nginx]# systemctl restart supervisord
//配置nginx用户
[root@kvm-web nginx]# su - nginx -s /bin/bash
上一次登录:三 10月 20 14:30:17 CST 2021pts/2 上
[nginx@kvm-web ~]$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/var/lib/nginx/.ssh/id_rsa):
Created directory '/var/lib/nginx/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /var/lib/nginx/.ssh/id_rsa.
Your public key has been saved in /var/lib/nginx/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:dr2MXkvfD90MXLEf9LyE2G+Fsj8FbhYE0wSZUMitsVQ nginx@kvm-web
The key's randomart image is:
+---[RSA 3072]----+
| ..*EBoo |
| = *o+o+|
| . =.o++=|
| o. =o+=|
| S . o *+o|
| . . o =.=.|
| . = + +|
| . o o + |
| . . . +|
+----[SHA256]-----+
[nginx@kvm-web ~]$ echo -e "StrictHostKeyChecking=no\nUserKnownHostsFile=/dev/null" >> ~/.ssh/config
[nginx@kvm-web ~]$ chmod 0600 ~/.ssh/config
[nginx@kvm-web ~]$ ssh-copy-id root@192.168.200.146
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/var/lib/nginx/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
Warning: Permanently added '192.168.200.146' (ECDSA) to the list of known hosts.
root@192.168.200.146's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.200.146'"
and check to make sure that only the key(s) you wanted were added.
[nginx@kvm-web ~]$ exit
注销
[root@kvm-web nginx]# cat /etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla
[Remote libvirt SSH access]
Identity=unix-user:root
Action=org.libvirt.unix.manage
ResultAny=yes
ResultInactive=yes
ResultActive=yes
[root@kvm-web nginx]# chown -R root.root /etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla
[root@kvm-web nginx]# systemctl restart nginx
[root@kvm-web nginx]# systemctl restart libvirtd //rhel8上重启