kvm
简介
KVM — 全称是基于内核的虚拟机(Kernel-based Virtual Machine)
-
KVM是一个开源软件,基于内核的虚拟化技术,实际是嵌入系统的一个虚拟化模块,通过优化内核来使用虚拟技术,该内核模块使得 Linux 变成了一个Hypervisor,虚拟机使用 Linux 自身的调度器进行管理。
-
KVM 是基于虚拟化扩展(Intel VT 或者 AMD-V)的 X86 硬件的开源的 Linux 原生的全虚拟化解决方案。KVM 中,虚拟机被实现为常规的 Linux 进程,由标准 Linux 调度程序进行调度;虚机的每个虚拟 CPU 被实现为一个常规的 Linux 进程。这使得 KMV 能够使用 Linux 内核的已有功能。但是,KVM 本身不执行任何硬件模拟,需要客户空间程序通过 /dev/kvm 接口设置一个客户机虚拟服务器的地址空间,向它提供模拟的 I/O,并将它的视频显示映射回宿主的显示屏。目前这个应用程序是 QEMU。
-
Guest:客户机系统,包括CPU(vCPU)、内存、驱动(Console、网卡、I/O 设备驱动等),被 KVM 置于一种受限制的 CPU 模式下运行。
-
KVM:运行在内核空间,提供CPU 和内存的虚级化,以及客户机的 I/O 拦截。Guest 的 I/O 被 KVM 拦截后,交给 QEMU 处理。
-
QEMU:修改过的为 KVM 虚机使用的 QEMU 代码,运行在用户空间,提供硬件 I/O 虚拟化,通过IOCTL /dev/kvm 设备和 KVM 交互。
KVM模块和管理工具
KVM有一个内核模块叫 kvm.ko,只用于管理虚拟 CPU 和内存。IO 的虚拟化,就交给 Linux 内核和qemu来实现。
Libvirt:是 KVM 的管理工具。Libvirt 除了能管理 KVM 这种 Hypervisor,还能管理 Xen,VirtualBox 等。OpenStack 底层也使用 Libvirt。
Libvirt 包含 3 个东西:后台 daemon 程序 libvirtd、API 库和命令行工具 virsh
- libvirtd是服务程序,接收和处理 API 请求;
- API 库使得其他人可以开发基于 Libvirt 的高级工具,比如 virt-manager,这是个图形化的 KVM 管理工具,后面我们也会介绍;
- virsh 是我们运维工程师经常要用的 KVM 命令行工具。作为 KVM 和 OpenStack 的实施人员,virsh 和 virt-manager 是一定要会用的。
KVM安装
主机 | ip | 职责 | 系统 |
---|---|---|---|
localhost | 192.168.200.128 | kvm | redhat8 |
server | 192.168.200.129 | nginx、kvm Web | centos7 |
//关闭防火墙和selinux
[root@localhost ~]# systemctl disable --now firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@localhost ~]# setenforce 0
[root@localhost ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config
[root@localhost ~]# getenforce
Permissive
[root@localhost ~]# reboot
[root@localhost ~]# getenforce
Disabled
//配置网络源并下载相应的工具
dnf -y install epel-release vim wget net-tools unzip zip gcc gcc-c++
//验证cpu是否支持kvm,如果结果中有vmx或svm字样,就说明cpu是支持的
svm //svm的多少在于你给的cpu核数
//安装依赖包和kvm
[root@localhost ~]# yum -y install qemu-kvm qemu-kvm-common qemu-img virt-manager libvirt python3-libvirt libvirt-client virt-install virt-viewer bridge-utils libguestfs-tools
//配置桥接网卡
因为虚拟机中网络,我们一般都是和公司的其他服务器是同一个网段,所以我们需要把
KVM服务器的网卡配置成桥接模式。这样的话KVM的虚拟机就可以通过该桥接网卡和公司内部
其他服务器处于同一网段
此处我的网卡是ens160,所以用br0来桥接ens160网卡
[root@localhost network-scripts]# cat ifcfg-br0
TYPE=Bridge
BOOTPROTO=static
NAME=br0
DEVICE=br0
ONBOOT=yes
IPADDR=192.168.200.128
PREFIX=24
GATEWAY=192.168.200.2
DNS1=114.114.114.114
[root@localhost network-scripts]# cat ifcfg-ens160
TYPE=Ethernet
BOOTPROTO=static
NAME=ens160
DEVICE=ens160
ONBOOT=yes
IPV6_PRIVACY=no
BRIDGE=br0
//重启网卡
[root@localhost network-scripts]# systemctl restart NetworkManager
[root@localhost 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 fq_codel state UP group default qlen 1000
link/ether 00:0c:29:b3:3f:d7 brd ff:ff:ff:ff:ff:ff
inet 192.168.200.128/24 brd 192.168.200.255 scope global noprefixroute ens160
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:feb3:3fd7/64 scope link noprefixroute
valid_lft forever preferred_lft forever
3: br0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default qlen 1000
link/ether 56:52:c9:55:1d:23 brd ff:ff:ff:ff:ff:ff
inet 192.168.200.128/24 brd 192.168.200.255 scope global noprefixroute br0
valid_lft forever preferred_lft forever
//启动服务并验证安装结果
[root@localhost network-scripts]# lsmod|grep kvm
kvm_intel 315392 0
kvm 847872 1 kvm_intel
irqbypass 16384 1 kvm
[root@localhost network-scripts]# virsh -c qemu:///system list
Id 名称 状态
-------------------
[root@localhost network-scripts]# virsh --version
6.0.0
[root@localhost network-scripts]# virt-install --version
2.2.1
[root@localhost network-scripts]# ln -s /usr/libexec/qemu-kvm /usr/bin/qemu-kvm
[root@localhost network-scripts]# ll /usr/bin/qemu-kvm
lrwxrwxrwx 1 root root 21 10月 20 23:05 /usr/bin/qemu-kvm -> /usr/libexec/qemu-kvm
[root@localhost network-scripts]# brctl show
bridge name bridge id STP enabled interfaces
br0 8000.000000000000 no
virbr0 8000.52540016ec1b yes virbr0-nic
kvm web管理界面部署
//关闭防火墙
[root@server ~]# systemctl disable --now firewalld
Removed symlink /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
set[root@server ~]# setenforce 0
[root@server ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config
[root@server ~]# getenforce
Permissive
[root@server ~]# reboot
//安装依赖包
[root@server ~]# yum -y install git python-pip libvirt-python libxml2-python python-websockify supervisor nginx python-devel
//从github下载webbvirtmgr代码
[root@server ~]# cd /usr/local/src/
[root@server src]# ls
[root@server 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 | 260.00 KiB/s, done.
处理 delta 中: 100% (3606/3606), done.
//安装webvirtmgr
[root@server webvirtmgr]# pip install -r requirements.txt
Collecting django==1.5.5 (from -r requirements.txt (line 1))
Downloading https://files.pythonhosted.org/packages/38/49/93511c5d3367b6b21fc2995a0e53399721afc15e4cd6
100% |████████████████████████████████| 122kB 38kB/s
Collecting lockfile>=0.9 (from -r requirements.txt (line 5))
Downloading https://files.pythonhosted.org/packages/c8/22/9460e311f340cb62d26a38c419b1381b8593b0bb6b5d1f056938b086d362/lockfile-0.12.2-py2.py3-none-any.whl
Installing collected packages: django, gunicorn, lockfile
Running setup.py install for django ... done
Successfully installed django-1.5.5 gunicorn-19.5.0 lockfile-0.12.2
You are using pip version 8.1.2, however version 21.3 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
//检查sqlite3是否安装
[root@server webvirtmgr]# python
Python 2.7.5 (default, Nov 16 2020, 22:23:17)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
//初始化账号信息
[root@server webvirtmgr]# python 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'): //指定超级管理员帐号用户名,默认留空为root
Email address: 1@2.com //设置超级管理员邮箱
Password: //设置超级管理员密码
Password (again): //再次输入超级管理员密码
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 6 object(s) from 1 fixture(s)
拷贝web网页至指定目录
[root@server webvirtmgr]# mkdir /var/www
[root@server webvirtmgr]# cp -r /usr/local/src/webvirtmgr /var/www/
[root@server webvirtmgr]# chown -R nginx.nginx /var/www/webvirtmgr/
[root@server webvirtmgr]#
//生成密钥
[root@server webvirtmgr]# 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:7dzh2MDq1TBn4sgJHLbJHr32z9u3rT+6lHQlJfAXbWo root@server
The key's randomart image is:
+---[RSA 2048]----+
| ....o|
| . o+|
| o ooo|
| + = o Eo.|
| B S B +o . |
| . + O &..o |
| . B * =o |
| o o ... .o|
| . ..++===|
+----[SHA256]-----+
[root@server webvirtmgr]#
由于这里webvirtmgr和kvm服务部署在同一台机器,所以这里本地信任。如果kvm部署在其他机器,那么这个是它的ip
[root@server webvirtmgr]# ssh-copy-id 192.168.200.128
/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.128 (192.168.58.100)' can't be established.
ECDSA key fingerprint is SHA256:0qeDQqmqWp043fYVLxhUYGCNuDxcjkwmDGkO7717TPU.
ECDSA key fingerprint is MD5:26:6a:f7:d5:d6:57:79:50:ff:09:ea:42:a5:a5:b1:0a.
Are you sure you want to continue connecting (yes/no)? 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.128's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '192.168.200.128'"
and check to make sure that only the key(s) you wanted were added.
//配置端口转发
[root@server webvirtmgr]# ssh root@192.168.200.128 -L localhost:8000:localhost:8000 -L localhost:6080:localhost:60
Last login: Wed Oct 20 20:54:07 2021 from 192.168.58.1
[root@localhost ~]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:111 0.0.0.0:*
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 [::]:111 [::]:*
LISTEN 0 128 [::]:22 [::]:*
配置nginx
[root@server ~]# cat /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
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;
include /etc/nginx/conf.d/*.conf;
server {
listen 80;
server_name localhost;
include /etc/nginx/default.d/*.conf;
location / {
root html;
index index.html index.htm;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
}
[root@server ~]# 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;
}
}
//确保bind绑定的本机的8080端口
[root@server ~]# cat /var/www/webvirtmgr/conf/gunicorn.conf.py
import os
# Sample Gunicorn configuration file.
#
# Server socket
#
# bind - The socket to bind.
#
# A string of the form: 'HOST', 'HOST:PORT', 'unix:PATH'.
# An IP is a valid HOST.
#
# backlog - The number of pending connections. This refers
# to the number of clients that can be waiting to be
# served. Exceeding this number results in the client
# getting an error when attempting to connect. It should
# only affect servers under significant load.
#
# Must be a positive integer. Generally set in the 64-2048
# range.
#
bind = '0.0.0.0:8000' //确保此处绑定的是本机的8000端口,这个在nginx配置中定义了,被代理的端口
backlog = 2048
重启nginx
[root@server ~ ]# systemctl restart nginx
[root@server ~]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:80 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 :::22 :::*
LISTEN 0 100 ::1:25 :::*
[root@server ~]#
//设置supervisor
[root@server ~ ]# 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
[program:webvirtmgr-console]
command=/usr/bin/python2 /var/www/webvirtmgr/console/webvirtmgr-console
directory=/var/www/webvirtmgr
autostart=true
autorestart=true
stdout_logfile=/var/log/supervisor/webvirtmgr-console.log
redirect_stderr=true
user=nginx
//启动supervisor并设置开机自启
[root@server ~]# systemctl start supervisord
[root@server ~]# systemctl enable supervisord
Created symlink from /etc/systemd/system/multi-user.target.wants/supervisord.service to /usr/lib/systemd/system/supervisord.service.
[root@server ~]# systemctl status supervisord
● supervisord.service - Process Monitoring and Control Daemon
Loaded: loaded (/usr/lib/systemd/system/supervisord.service; enabled; vendor preset: disabled)
Active: active (running) since 三 2021-10-20 22:07:41 CST; 14s ago
Main PID: 36263 (supervisord)
CGroup: /system.slice/supervisord.service
├─36263 /usr/bin/python /usr/bin/supervisord -c /etc/supervisord.conf
├─36276 /usr/bin/python2 /var/www/webvirtmgr/console/webvirtmgr-console
├─36277 /usr/bin/python2 /var/www/webvirtmgr/manage.py run_gunicorn -c /var/www/webvirtmgr/con...
├─36283 /usr/bin/python2 /var/www/webvirtmgr/manage.py run_gunicorn -c /var/www/webvirtmgr/con...
├─36284 /usr/bin/python2 /var/www/webvirtmgr/manage.py run_gunicorn -c /var/www/webvirtmgr/con...
├─36291 /usr/bin/python2 /var/www/webvirtmgr/manage.py run_gunicorn -c /var/www/webvirtmgr/con...
├─36294 /usr/bin/python2 /var/www/webvirtmgr/manage.py run_gunicorn -c /var/www/webvirtmgr/con...
└─36296 /usr/bin/python2 /var/www/webvirtmgr/manage.py run_gunicorn -c /var/www/webvirtmgr/con...
10月 20 23:45:41 server systemd[1]: Starting Process Monitoring and Control Daemon...
10月 20 23:45:41 server systemd[1]: Started Process Monitoring and Control Daemon.
[root@server ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:8000 *:*
LISTEN 0 100 *:6080 *:*
LISTEN 0 128 *:80 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 :::22 :::*
LISTEN 0 100 ::1:25 :::*
//配置nginx用户
[root@server ~]# su - nginx -s /bin/bash
-bash-4.2$ 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:xSP4aQPpdLbEAsyDiCY0JkcjWsMsSdIlix9pTsvag/4 nginx@server
The key's randomart image is:
+---[RSA 2048]----+
|B%B=o |
|@***+. + . |
|=.* .* * + |
| * o o B = . |
| = . S |
| + . . |
|o o |
|. . |
| ..E |
+----[SHA256]-----+
-bash-4.2$ touch ~/.ssh/config && echo -e "StrictHostKeyChecking=no\nUserKnownHostsFile=/dev/null"
StrictHostKeyChecking=no
UserKnownHostsFile=/dev/null
-bash-4.2$ chmod 0600 ~/.ssh/config
-bash-4.2$
-bash-4.2$ ssh-copy-id root@192.168.200.128
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/var/lib/nginx/.ssh/id_rsa.pub"
The authenticity of host '192.168.200.128 (192.168.200.128)' can't be established.
ECDSA key fingerprint is SHA256:0qeDQqmqWp043fYVLxhUYGCNuDxcjkwmDGkO7717TPU.
ECDSA key fingerprint is MD5:26:6a:f7:d5:d6:57:79:50:ff:09:ea:42:a5:a5:b1:0a.
Are you sure you want to continue connecting (yes/no)? yes
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/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.128's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.200.128'"
and check to make sure that only the key(s) you wanted were added.
-bash-4.2$
-bash-4.2$ exit
登出
[root@server ~]# vi /etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla
[root@server ~]# vi /etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla
[root@server ~]# systemctl restart nginx
[root@server ~]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:8000 *:*
LISTEN 0 100 *:6080 *:*
LISTEN 0 128 *:80 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 :::22 :::*
LISTEN 0 100 ::1:25 :::*
[root@localhost network-scripts]# systemctl restart libvirtd
[root@localhost network-scripts]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:111 0.0.0.0:*
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 [::]:111 [::]:*
LISTEN 0 128 [::]:22 [::]:*
KVM连接管理
创建ssh连接
KVM存储管理
创建存储:
#创建存储目录
[root@KVM ~]# mkdir /test
进入存储:
通过xftp将ISO镜像文件传至存储目录
[root@kvm ~]# cd /test/
[root@kvm test]# ls
CentOS-7-x86_64-DVD-1804-7.5.iso
创建系统安装镜像
kvm网络管理
添加桥接网络
实例管理
虚拟机创建
虚拟机插入光盘
设置在web上访问虚拟机的密码
启动虚拟机
故障案例
无法创建存储
[root@kvm ~]# rpm -qa | grep libgcrypt //升级libcrypyt
libgcrypt-1.8.3-4.el8.x86_64
[root@kvm ~]# yum update libgcrypt
[root@kvm ~]# rpm -qa | grep libgcrypt
libgcrypt-1.8.5-4.el8.x86_64
web界面配置完成后可能会出现以下错误界面
安装novnc并通过novnc_server启动一个vnc
[root@kvm-web ~]# yum -y install novnc
[root@kvm-web ~]# vim /etc/rc.d/rc.local
nohup novnc_server 192.168.200.129:5920 &
[root@kvm-web ~]# . /etc/rc.d/rc.local