zl程序教程

您现在的位置是:首页 >  系统

当前栏目

CentOS7系列--5.1CentOS7中配置和管理KVM

centos7配置 管理 -- 系列 kvm 5.1
2023-09-11 14:19:52 时间

CentOS7配置和管理KVM

安装与配置虚拟化软件KVM ( Kernel-based Virtual Machine ) + QEMU,它要求计算机的CPU支持Intel VT or AMD-V功能

1. 安装KVM

1.1. 安装KVM相关软件

[root@server1 ~]# yum install -y qemu-kvm libvirt virt-install bridge-utils

Loaded plugins: fastestmirror

base | 3.6 kB 00:00:00

extras | 3.4 kB 00:00:00

updates | 3.4 kB 00:00:00

(1/4): extras/7/x86_64/primary_db | 129 kB 00:00:00

clip_image002

1.2. 加载KVM模块

[root@server1 ~]# lsmod | grep kvm

kvm_intel 170086 0

kvm 566340 1 kvm_intel

irqbypass 13503 1 kvm

clip_image004

1.3. 打开虚拟化KVM服务

[root@server1 ~]# systemctl start libvirtd

[root@server1 ~]# systemctl enable libvirtd

1.4. 配置网桥

为KVM虚拟机配置网桥,并替换ens33网络接口

1)查看网络参数

[root@server1 ~]# ip addr

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1

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: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000

link/ether 00:0c:29:7f:71:6f brd ff:ff:ff:ff:ff:ff

inet 192.168.1.101/24 brd 192.168.1.255 scope global ens33

valid_lft forever preferred_lft forever

inet6 fe80::e916:a902:3eb4:bdc7/64 scope link

valid_lft forever preferred_lft forever

inet6 fe80::b882:c8d8:c451:e742/64 scope link tentative dadfailed

valid_lft forever preferred_lft forever

3: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN qlen 1000

link/ether 52:54:00:6f:2e:59 brd ff:ff:ff:ff:ff:ff

inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0

valid_lft forever preferred_lft forever

4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc pfifo_fast master virbr0 state DOWN qlen 10 00

link/ether 52:54:00:6f:2e:59 brd ff:ff:ff:ff:ff:ff

[root@server1 ~]# ip route

default via 192.168.1.1 dev ens33 proto static metric 100

192.168.1.0/24 dev ens33 proto kernel scope link src 192.168.1.101 metric 100

192.168.122.0/24 dev virbr0 proto kernel scope link src 192.168.122.1

[root@server1 ~]# cat /etc/resolv.conf

# Generated by NetworkManager

search smartmap.com

nameserver 218.30.19.50

nameserver 61.134.1.5

2)设置网桥参数

[root@server1 ~]# nmcli c add type bridge autoconnect yes con-name br0 ifname br0

Connection 'br0' (b669c790-d029-49d0-ae20-d49f48e913dd) successfully added.

[root@server1 ~]# nmcli c modify br0 ipv4.addresses 192.168.1.101/24 ipv4.method manual

[root@server1 ~]# nmcli c modify br0 ipv4.gateway 192.168.1.1

[root@server1 ~]# nmcli c modify br0 ipv4.dns 218.30.19.50 61.134.1.5

Error: invalid or not allowed setting '61': '61' not among [connection, bridge, 802-3-ethernet (ethernet), ipv4, ipv6, proxy].

[root@server1 ~]# nmcli c modify br0 ipv4.dns 218.30.19.50

[root@server1 ~]# nmcli c modify br0 +ipv4.dns 61.134.1.5

[root@server1 ~]# nmcli c delete ens33

Connection 'ens33' (d373288e-8842-4df8-89a5-c92c21d4fd89) successfully deleted.

[root@server1 ~]# nmcli c add type bridge-slave autoconnect yes con-name ens33 ifname ens33 master br0 Connection 'ens33' (91a6d2c9-b413-445e-a12a-fe16e0dae5b1) successfully added.

[root@server1 ~]# reboot

1.5. 验证网络

login as: root

root@192.168.1.101's password:

Last login: Sat Nov 11 13:12:13 2017 from 192.168.1.100

[root@server1 ~]# ip addr

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1

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: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master br0 state UP qlen 1000

link/ether 00:0c:29:7f:71:6f brd ff:ff:ff:ff:ff:ff

3: br0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP qlen 1 000

link/ether 00:0c:29:7f:71:6f brd ff:ff:ff:ff:ff:ff

inet 192.168.1.101/24 brd 192.168.1.255 scope global br0

valid_lft forever preferred_lft forever

inet6 fe80::6600:5ec3:2610:672f/64 scope link

valid_lft forever preferred_lft forever

4: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN qlen 1000

link/ether 52:54:00:6f:2e:59 brd ff:ff:ff:ff:ff:ff

inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0

valid_lft forever preferred_lft forever

5: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc pfifo_fast master virbr0 sta te DOWN qlen 1000

link/ether 52:54:00:6f:2e:59 brd ff:ff:ff:ff:ff:ff

2. 创建虚拟机

2.1. 通过网络以文本模式安装虚拟机

[root@server1 ~]# mkdir -p /var/kvm/images

[root@server1 ~]# virt-install \

> --name centos7 \

> --ram 4096 \

> --disk path=/var/kvm/images/centos7.img,size=8 \

> --vcpus 2 \

> --os-type linux \

> --os-variant centos7 \

> --network bridge=br0 \

> --graphics none \

> --console pty,target_type=serial \

> --location 'http://mirrors.163.com/centos/7/os/x86_64/' \

> --extra-args 'console=ttyS0,115200n8 serial'

clip_image006

相关参数的含义如下:

参数名

参数含义

--name

specify the name of Virtual Machine

--ram

specify the amount of memories of Virtual Machine

--disk path=xxx ,size=xxx

'path=' ⇒ specify the location of disks of Virtual Machine
'size=' ⇒ specify the amount of disks of Virtual Machine

--vcpus

specify the virtual CPUs

--os-type

specify the type of GuestOS

--os-variant

specify the kind of GuestOS - possible to confirm the list with the command below
# osinfo-query os

--network

specify network types of Virtual Machine

--graphics

specify the kind of graphics. if set 'none', it means nographics.

--console

specify the console type

--location

specify the location of installation where from

--extra-args

specify parameters that is set in kernel

2.2. 安装完成之后重启

clip_image008

2.3. 从虚拟机进入主机

按 Ctrl + ] 从虚拟机进入主机

2.4. 从主机进入虚拟机

[root@server1 ~]# virsh console centos7

Connected to domain centos7

Escape character is ^]

[root@localhost ~]#

clip_image010

2.5. 从虚拟机保存为模板

[root@server1 ~]# virt-clone --original centos7 --name template --file /var/kvm/images/template.img

Allocating 'template.img' | 8.0 GB 00:00:24

Clone 'template' created successfully.

[root@server1 ~]# ll /var/kvm/images/template.img

-rw------- 1 root root 1285816320 Nov 11 22:10 /var/kvm/images/template.img

[root@server1 ~]# ll /etc/libvirt/qemu

qemu/ qemu.conf qemu-lockd.conf

[root@server1 ~]# ll /etc/libvirt/qemu/template.xml

-rw------- 1 root root 3204 Nov 11 22:10 /etc/libvirt/qemu/template.xml

[root@server1 ~]#

clip_image012

2.6. 定义一个新的存贮池

2.6.1. 创建存贮池配置文件存放目录

[root@server1 ~]# mkdir /etc/libvirt/storage

2.6.2. 创建存贮池配置文件

[root@server1 ~]# cd /etc/libvirt/storage/

[root@server1 storage]# vi /etc/libvirt/storage/disk01.xml

写入如下的内容:

<pool type='dir'>

<name>disk01</name>

<capacity>0</capacity>

<allocation>0</allocation>

<available>0</available>

<source>

</source>

<target>

<path>/var/kvm/images</path>

<permissions>

<mode>0700</mode>

<owner>-1</owner>

<group>-1</group>

</permissions>

</target>

</pool>

2.6.3. 定义存贮池

[root@server1 storage]# virsh pool-define /etc/libvirt/storage/disk01.xml

2.6.4. 启动存贮池

[root@server1 storage]# virsh pool-start disk01

2.6.5. 设置自动启动

[root@server1 storage]# virsh pool-autostart disk01

2.6.6. 列出存贮池

[root@server1 storage]# virsh pool-info disk01

3. 应用virsh相关命令对虚拟机进行操作

3.1. 启动虚拟机

1.只是启动虚拟机

[root@server1 storage]# virsh start centos7

Domain centos7 started

2.启动并连接到虚拟机

[root@server1 storage]# virsh start centos7 --console

Domain centos7 started

Connected to domain centos7

Escape character is ^]

[ 0.000000] Initializing cgroup subsys cpuset

[ 0.000000] Initializing cgroup subsys cpu

3.2. 停止虚拟机

1.停止虚拟机

[root@server1 storage]# virsh shutdown centos7

Domain centos7 is being shutdown

2.强止停止虚拟机

[root@server1 storage]# virsh destroy centos7

Domain centos7 unmarked as autostarted

3.3. 自动启动虚拟机

1.设置自动启动虚拟机

[root@server1 storage]# virsh autostart centos7

Domain centos7 marked as autostarted

2.取消自动启动虚拟机

[root@server1 storage]# virsh autostart --disable centos7

Domain centos7 unmarked as autostarted

3.4. 列出所有虚拟机

1.列出所有启动虚拟机

[root@server1 storage]# virsh list

Id Name State

----------------------------------------------------

5 centos7 running

2.列出所有虚拟机

[root@server1 storage]# virsh list --all

Id Name State

----------------------------------------------------

5 centos7 running

- template shut off

3.5. 主机与虚拟机之前相互切换

1.从虚拟机进入主机

Ctrl + ] 从虚拟机进入主机

2.从主机进入虚拟机

[root@server1 ~]# virsh console centos7

Connected to domain centos7

Escape character is ^]

[root@localhost ~]#

3.6. virsh其它选项

[root@server1 storage]# 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):

Domain Management (help keyword 'domain')

attach-device attach device from an XML file

attach-disk attach disk device

attach-interface attach network interface

autostart autostart a domain

blkdeviotune Set or query a block device I/O tuning parameters.

blkiotune Get or set blkio parameters

blockcommit Start a block commit operation.

blockcopy Start a block copy operation.

blockjob Manage active block operations

blockpull Populate a disk from its backing image.

blockresize Resize block device of domain.

change-media Change media of CD or floppy drive

console connect to the guest console

cpu-baseline compute baseline CPU

cpu-compare compare host CPU with a CPU described by an XML file

cpu-stats show domain cpu statistics

create create a domain from an XML file

define define (but don't start) a domain from an XML file

desc show or set domain's description or title

destroy destroy (stop) a domain

detach-device detach device from an XML file

detach-disk detach disk device

detach-interface detach network interface

domdisplay domain display connection URI

domfsfreeze Freeze domain's mounted filesystems.

domfsthaw Thaw domain's mounted filesystems.

domfsinfo Get information of domain's mounted filesystems.

domfstrim Invoke fstrim on domain's mounted filesystems.

domhostname print the domain's hostname

domid convert a domain name or UUID to domain id

domif-setlink set link state of a virtual interface

domiftune get/set parameters of a virtual interface

domjobabort abort active domain job

domjobinfo domain job information

domname convert a domain id or UUID to domain name

domrename rename a domain

dompmsuspend suspend a domain gracefully using power management functions

dompmwakeup wakeup a domain from pmsuspended state

domuuid convert a domain name or id to domain UUID

domxml-from-native Convert native config to domain XML

domxml-to-native Convert domain XML to native config

dump dump the core of a domain to a file for analysis

dumpxml domain information in XML

edit edit XML configuration for a domain

event Domain Events

inject-nmi Inject NMI to the guest

iothreadinfo view domain IOThreads

iothreadpin control domain IOThread affinity

iothreadadd add an IOThread to the guest domain

iothreaddel delete an IOThread from the guest domain

send-key Send keycodes to the guest

send-process-signal Send signals to processes

lxc-enter-namespace LXC Guest Enter Namespace

managedsave managed save of a domain state

managedsave-remove Remove managed save of a domain

memtune Get or set memory parameters

perf Get or set perf event

metadata show or set domain's custom XML metadata

migrate migrate domain to another host

migrate-setmaxdowntime set maximum tolerable downtime

migrate-compcache get/set compression cache size

migrate-setspeed Set the maximum migration bandwidth

migrate-getspeed Get the maximum migration bandwidth

migrate-postcopy Switch running migration from pre-copy to post-copy

numatune Get or set numa parameters

qemu-attach QEMU Attach

qemu-monitor-command QEMU Monitor Command

qemu-monitor-event QEMU Monitor Events

qemu-agent-command QEMU Guest Agent Command

reboot reboot a domain

reset reset a domain

restore restore a domain from a saved state in a file

resume resume a domain

save save a domain state to a file

save-image-define redefine the XML for a domain's saved state file

save-image-dumpxml saved state domain information in XML

save-image-edit edit XML for a domain's saved state file

schedinfo show/set scheduler parameters

screenshot take a screenshot of a current domain console and store it into a file

set-user-password set the user password inside the domain

setmaxmem change maximum memory limit

setmem change memory allocation

setvcpus change number of virtual CPUs

shutdown gracefully shutdown a domain

start start a (previously defined) inactive domain

suspend suspend a domain

ttyconsole tty console

undefine undefine a domain

update-device update device from an XML file

vcpucount domain vcpu counts

vcpuinfo detailed domain vcpu information

vcpupin control or query domain vcpu affinity

emulatorpin control or query domain emulator affinity

vncdisplay vnc display

guestvcpus query or modify state of vcpu in the guest (via agent)

setvcpu attach/detach vcpu or groups of threads

domblkthreshold set the threshold for block-threshold event for a given block device or it's backing chain element

Domain Monitoring (help keyword 'monitor')

domblkerror Show errors on block devices

domblkinfo domain block device size information

domblklist list all domain blocks

domblkstat get device block stats for a domain

domcontrol domain control interface state

domif-getlink get link state of a virtual interface

domifaddr Get network interfaces' addresses for a running domain

domiflist list all domain virtual interfaces

domifstat get network interface stats for a domain

dominfo domain information

dommemstat get memory statistics for a domain

domstate domain state

domstats get statistics about one or multiple domains

domtime domain time

list list domains

Host and Hypervisor (help keyword 'host')

allocpages Manipulate pages pool size

capabilities capabilities

cpu-models CPU models

domcapabilities domain capabilities

freecell NUMA free memory

freepages NUMA free pages

hostname print the hypervisor hostname

maxvcpus connection vcpu maximum

node-memory-tune Get or set node memory parameters

nodecpumap node cpu map

nodecpustats Prints cpu stats of the node.

nodeinfo node information

nodememstats Prints memory stats of the node.

nodesuspend suspend the host node for a given time duration

sysinfo print the hypervisor sysinfo

uri print the hypervisor canonical URI

version show version

Interface (help keyword 'interface')

iface-begin create a snapshot of current interfaces settings, which can be later committed (iface-commit) or restored (iface-rollback)

iface-bridge create a bridge device and attach an existing network device to it

iface-commit commit changes made since iface-begin and free restore point

iface-define define an inactive persistent physical host interface or modify an existing persistent one from an XML file

iface-destroy destroy a physical host interface (disable it / "if-down")

iface-dumpxml interface information in XML

iface-edit edit XML configuration for a physical host interface

iface-list list physical host interfaces

iface-mac convert an interface name to interface MAC address

iface-name convert an interface MAC address to interface name

iface-rollback rollback to previous saved configuration created via iface-begin

iface-start start a physical host interface (enable it / "if-up")

iface-unbridge undefine a bridge device after detaching its slave device

iface-undefine undefine a physical host interface (remove it from configuration)

Network Filter (help keyword 'filter')

nwfilter-define define or update a network filter from an XML file

nwfilter-dumpxml network filter information in XML

nwfilter-edit edit XML configuration for a network filter

nwfilter-list list network filters

nwfilter-undefine undefine a network filter

Networking (help keyword 'network')

net-autostart autostart a network

net-create create a network from an XML file

net-define define an inactive persistent virtual network or modify an existing persistent one from an XML file

net-destroy destroy (stop) a network

net-dhcp-leases print lease info for a given network

net-dumpxml network information in XML

net-edit edit XML configuration for a network

net-event Network Events

net-info network information

net-list list networks

net-name convert a network UUID to network name

net-start start a (previously defined) inactive network

net-undefine undefine a persistent network

net-update update parts of an existing network's configuration

net-uuid convert a network name to network UUID

Node Device (help keyword 'nodedev')

nodedev-create create a device defined by an XML file on the node

nodedev-destroy destroy (stop) a device on the node

nodedev-detach detach node device from its device driver

nodedev-dumpxml node device details in XML

nodedev-list enumerate devices on this host

nodedev-reattach reattach node device to its device driver

nodedev-reset reset node device

nodedev-event Node Device Events

Secret (help keyword 'secret')

secret-define define or modify a secret from an XML file

secret-dumpxml secret attributes in XML

secret-event Secret Events

secret-get-value Output a secret value

secret-list list secrets

secret-set-value set a secret value

secret-undefine undefine a secret

Snapshot (help keyword 'snapshot')

snapshot-create Create a snapshot from XML

snapshot-create-as Create a snapshot from a set of args

snapshot-current Get or set the current snapshot

snapshot-delete Delete a domain snapshot

snapshot-dumpxml Dump XML for a domain snapshot

snapshot-edit edit XML for a snapshot

snapshot-info snapshot information

snapshot-list List snapshots for a domain

snapshot-parent Get the name of the parent of a snapshot

snapshot-revert Revert a domain to a snapshot

Storage Pool (help keyword 'pool')

find-storage-pool-sources-as find potential storage pool sources

find-storage-pool-sources discover potential storage pool sources

pool-autostart autostart a pool

pool-build build a pool

pool-create-as create a pool from a set of args

pool-create create a pool from an XML file

pool-define-as define a pool from a set of args

pool-define define an inactive persistent storage pool or modify an existing persistent one from an XML file

pool-delete delete a pool

pool-destroy destroy (stop) a pool

pool-dumpxml pool information in XML

pool-edit edit XML configuration for a storage pool

pool-info storage pool information

pool-list list pools

pool-name convert a pool UUID to pool name

pool-refresh refresh a pool

pool-start start a (previously defined) inactive pool

pool-undefine undefine an inactive pool

pool-uuid convert a pool name to pool UUID

pool-event Storage Pool Events

Storage Volume (help keyword 'volume')

vol-clone clone a volume.

vol-create-as create a volume from a set of args

vol-create create a vol from an XML file

vol-create-from create a vol, using another volume as input

vol-delete delete a vol

vol-download download volume contents to a file

vol-dumpxml vol information in XML

vol-info storage vol information

vol-key returns the volume key for a given volume name or path

vol-list list vols

vol-name returns the volume name for a given volume key or path

vol-path returns the volume path for a given volume name or key

vol-pool returns the storage pool for a given volume key or path

vol-resize resize a vol

vol-upload upload file contents to a volume

vol-wipe wipe a vol

Virsh itself (help keyword 'virsh')

cd change the current directory

echo echo arguments

exit quit this interactive terminal

help print help

pwd print the current directory

quit quit this interactive terminal

connect (re)connect to hypervisor

(specify help <group> for details about the commands in the group)

(specify help <command> for details about the command)

[root@server1 storage]#

4. 应用Virt-Tools相关工具操作虚拟机

4.1. 安装Virt-Tools工具

[root@server1 storage]# yum install -y libguestfs-tools virt-top

Loaded plugins: fastestmirror

base | 3.6 kB 00:00:00

extras | 3.4 kB 00:00:00

updates | 3.4 kB 00:00:00

Loading mirror speeds from cached hostfile

4.2. 虚拟机的ls命令

[root@server1 storage]# virt-ls -l -d centos7 /root

total 28

dr-xr-x---. 2 root root 135 Nov 11 14:07 .

dr-xr-xr-x. 17 root root 224 Nov 11 10:25 ..

-rw-------. 1 root root 35 Nov 11 14:07 .bash_history

-rw-r--r--. 1 root root 18 Dec 29 2013 .bash_logout

-rw-r--r--. 1 root root 176 Dec 29 2013 .bash_profile

-rw-r--r--. 1 root root 176 Dec 29 2013 .bashrc

-rw-r--r--. 1 root root 100 Dec 29 2013 .cshrc

-rw-r--r--. 1 root root 129 Dec 29 2013 .tcshrc

-rw-------. 1 root root 1285 Nov 11 10:26 anaconda-ks.cfg

4.3. 虚拟机的cat命令

[root@server1 storage]# virt-cat -d centos7 /etc/passwd

root:x:0:0:root:/root:/bin/bash

bin:x:1:1:bin:/bin:/sbin/nologin

daemon:x:2:2:daemon:/sbin:/sbin/nologin

adm:x:3:4:adm:/var/adm:/sbin/nologin

lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

sync:x:5:0:sync:/sbin:/bin/sync

shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

halt:x:7:0:halt:/sbin:/sbin/halt

mail:x:8:12:mail:/var/spool/mail:/sbin/nologin

operator:x:11:0:operator:/root:/sbin/nologin

games:x:12:100:games:/usr/games:/sbin/nologin

ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin

nobody:x:99:99:Nobody:/:/sbin/nologin

systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin

dbus:x:81:81:System message bus:/:/sbin/nologin

polkitd:x:999:997:User for polkitd:/:/sbin/nologin

postfix:x:89:89::/var/spool/postfix:/sbin/nologin

chrony:x:998:996::/var/lib/chrony:/sbin/nologin

sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin

4.4. 编辑虚拟机中的文件

[root@server1 storage]# virt-edit -d centos7 /etc/fstab

#

# /etc/fstab

# Created by anaconda on Sat Nov 11 10:16:56 2017

#

# Accessible filesystems, by reference, are maintained under '/dev/disk'

# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info

#

/dev/mapper/centos-root / xfs defaults 0 0

UUID=d2928870-570c-420c-822c-95c78d85d6f5 /boot xfs defaults 0 0

/dev/mapper/centos-swap swap swap defaults 0 0

clip_image014

4.5. 查看虚拟机中的磁盘用量

[root@server1 storage]# virt-df -d centos7

Filesystem 1K-blocks Used Available Use%

centos7:/dev/sda1 1038336 94348 943988 10%

centos7:/dev/centos/root 6486016 885592 5600424 14%

[root@server1 storage]#

4.6. 给虚拟机挂载一个磁盘

[root@server1 storage]# guestmount -d centos7 -i /media

[root@server1 storage]# ll /media/

total 16

lrwxrwxrwx. 1 root root 7 Nov 11 18:19 bin -> usr/bin

dr-xr-xr-x. 5 root root 4096 Nov 11 18:26 boot

drwxr-xr-x. 2 root root 6 Nov 11 18:16 dev

drwxr-xr-x. 75 root root 8192 Nov 11 23:47 etc

drwxr-xr-x. 2 root root 6 Nov 5 2016 home

lrwxrwxrwx. 1 root root 7 Nov 11 18:19 lib -> usr/lib

lrwxrwxrwx. 1 root root 9 Nov 11 18:19 lib64 -> usr/lib64

drwxr-xr-x. 2 root root 6 Nov 5 2016 media

drwxr-xr-x. 2 root root 6 Nov 5 2016 mnt

drwxr-xr-x. 2 root root 6 Nov 5 2016 opt

drwxr-xr-x. 2 root root 6 Nov 11 18:16 proc

dr-xr-x---. 2 root root 135 Nov 11 22:07 root

drwxr-xr-x. 2 root root 6 Nov 11 18:16 run

lrwxrwxrwx. 1 root root 8 Nov 11 18:19 sbin -> usr/sbin

drwxr-xr-x. 2 root root 6 Nov 5 2016 srv

drwxr-xr-x. 2 root root 6 Nov 11 18:16 sys

drwxrwxrwt. 7 root root 132 Nov 11 23:47 tmp

drwxr-xr-x. 13 root root 155 Nov 11 18:19 usr

drwxr-xr-x. 19 root root 267 Nov 11 18:27 var

[root@server1 storage]#

4.7. 显示虚拟机的状态

[root@server1 storage]# virt-top

virt-top 23:53:08 - x86_64 2/2CPU 2692MHz 4095MB

3 domains, 1 active, 1 running, 0 sleeping, 0 paused, 2 inactive D:0 O:0 X:0

CPU: 0.2% Mem: 500 MB (500 MB by guests)

ID S RDRQ WRRQ RXBY TXBY %CPU %MEM TIME NAME

11 R 0 0 0.2 12.0 0:03.43 guestfs-uz62s5vhlm2av04v

- (centos7)

- (template)

5. 在线迁移虚拟机

[root@server1 storage]# virsh migrate --live centos7 qemu+ssh://192.168.1.102/system

6. SPICE显示工具

安装桌面虚拟化SPICE ( Simple Protocol for Independent Computing Environment ),它能够从远程客户机连接到虚拟机。

6.1. 安装SPICE服务

[root@server1 ~]# yum install spice-server spice-protocol

Loaded plugins: fastestmirror

base | 3.6 kB 00:00:00

extras | 3.4 kB 00:00:00

updates

6.2. 修改已存在的虚拟机的xml配置文件

修改已存在的虚拟机的XML配置文件,加入SPICE服务支持图形界面的支持,修改如下:

注意:如果提示“error: XML error: Attempted double use of PCI Address 0000:00:06.0”,则需要修改slot的值

[root@server1 ~]# virsh edit centos7

<controller type='usb' index='0' model='ich9-uhci3'>

<master startport='4'/>

<address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x2'/>

</controller>

……

<input type='mouse' bus='ps2'/>

<input type='keyboard' bus='ps2'/>

<graphics type='spice' port='5900' autoport='no' listen='0.0.0.0' passwd='password'>

<listen type='address' address='0.0.0.0'/>

</graphics>

<sound model='ac97'>

<address type='pci' domain='0x0000' bus='0x00' slot='0x08' function='0x0'/>

</sound>

<video>

<model type='qxl' ram='65536' vram='32768' heads='1'/>

<address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>

</video>

<memballoon model='virtio'>

<address type='pci' domain='0x0000' bus='0x00' slot='0x07' function='0x0'/>

</memballoon>

</devices>

6.3. 在创建虚拟机时加入SPICE支持

[root@server1 ~]# virt-install \
--name Win2k12R2 \
--ram 6144 \
--disk path=/var/kvm/images/Win2k12R2.img,size=100 \
--vcpus=4 \
--os-type windows \
--os-variant=win2k12r2 \
--network bridge=br0 \
--graphics spice,listen=0.0.0.0,password=password,keymap=en \
--video qxl \
--cdrom /tmp/X64FRE_SERVER_EVAL_JA-JP-IRM_SSS_X64FREE_JA-JP_DV5.ISO

6.4. 防火墙设置

[root@server1 ~]# firewall-cmd --add-port=5900/tcp --permanent

[root@server1 ~]# firewall-cmd --reload

6.5. 客户端连接

6.5.1. 下载安装virt-viewer

https://virt-manager.org/download/

6.5.2. 连接服务器

clip_image015

clip_image017

clip_image019

7. 虚拟机嵌套

7.1. 修改KVM设置以支持虚拟机嵌套

kvm-nested.conf文件中加入如下的内容:

[root@server1 ~]# vi /etc/modprobe.d/kvm-nested.conf

options kvm_intel nested=1

7.2. 重新加载内核模块

[root@server1 ~]# modprobe -r kvm_intel

[root@server1 ~]# modprobe kvm_intel

[root@server1 ~]# cat /sys/module/kvm_intel/parameters/nested

Y

7.3. 修改虚拟机CPU设置以支持虚拟机嵌套

[root@server1 ~]# virsh edit centos7

<cpu mode='host-passthrough' match='exact' check='partial'>

8. oVirt虚拟机管理工具

8.1. 配置管理服务器

8.1.1. 安装ovirt-engine软件

[root@appclient~]# yum -y install http://resources.ovirt.org/pub/yum-repo/ovirt-release41.rpm

Loaded plugins: fastestmirror

ovirt-release41.rpm | 16 kB 00:00:00

[root@appclient~]# yum install -y ovirt-engine

Loaded plugins: fastestmirror

centos-opstools-release | 2.9 kB 00:00:00

8.1.2. 配置NFS服务

[root@appclient ~]# systemctl start rpcbind nfs-server

[root@appclient ~]# systemctl enable rpcbind nfs-server

8.1.3. 配置engine

[root@appclient ~]# engine-setup

[ INFO ] Stage: Initializing

[ INFO ] Stage: Environment setup

Configuration files: ['/etc/ovirt-engine-setup.conf.d/10-packaging-jboss.conf', '/etc/ovirt-engine-setup.conf.d/10-packaging.conf']

Log file: /var/log/ovirt-engine/setup/ovirt-engine-setup-20171112221954-wqnza2.log

Version: otopi-1.6.2 (otopi-1.6.2-1.el7.centos)

[ INFO ] Stage: Environment packages setup

[ INFO ] Stage: Programs detection

[ INFO ] Stage: Environment setup

[ INFO ] Stage: Environment customization

--== PRODUCT OPTIONS ==--

Configure Engine on this host (Yes, No) [Yes]:

Configure Image I/O Proxy on this host? (Yes, No) [Yes]:

Configure WebSocket Proxy on this host (Yes, No) [Yes]:

Please note: Data Warehouse is required for the engine. If you choose to not configure it on this host, you have to configure it on a remote host, and then configure the engine on this host so that it can access the database of the remote Data Warehouse host.

Configure Data Warehouse on this host (Yes, No) [Yes]:

Configure VM Console Proxy on this host (Yes, No) [Yes]:

--== PACKAGES ==--

[ INFO ] Checking for product updates...

[ INFO ] No product updates found

--== NETWORK CONFIGURATION ==--

Host fully qualified DNS name of this server [appclient.smartmap]:

[WARNING] Failed to resolve appclient.smartmap using DNS, it can be resolved only locally

Setup can automatically configure the firewall on this system.

Note: automatic configuration of the firewall may overwrite current settings.

Do you want Setup to configure the firewall? (Yes, No) [Yes]: no

--== DATABASE CONFIGURATION ==--

Where is the DWH database located? (Local, Remote) [Local]:

Setup can configure the local postgresql server automatically for the DWH to run. This may conflict with existing applications.

Would you like Setup to automatically configure postgresql and create DWH database, or prefer to perform that manually? (Automatic, Manual) [Automatic]:

Where is the Engine database located? (Local, Remote) [Local]:

Setup can configure the local postgresql server automatically for the engine to run. This may conflict with existing applications.

Would you like Setup to automatically configure postgresql and create Engine database, or prefer to perform that manually? (Automatic, Manual) [Automatic]:

--== OVIRT ENGINE CONFIGURATION ==--

Engine admin password:

Confirm engine admin password:

[WARNING] Password is weak: it is WAY too short

Use weak password? (Yes, No) [No]: yes

Application mode (Virt, Gluster, Both) [Both]:

--== STORAGE CONFIGURATION ==--

Default SAN wipe after delete (Yes, No) [No]:

--== PKI CONFIGURATION ==--

Organization name for certificate [smartmap]:

--== APACHE CONFIGURATION ==--

Setup can configure the default page of the web server to present the application home page. This may conflict with existing applications.

Do you wish to set the application as the default page of the web server? (Yes, No) [Yes]:

Setup can configure apache to use SSL using a certificate issued from the internal CA.

Do you wish Setup to configure that, or prefer to perform that manually? (Automatic, Manual) [Automatic]:

--== SYSTEM CONFIGURATION ==--

Configure an NFS share on this server to be used as an ISO Domain? (Yes, No) [No]: yes

Local ISO domain path [/var/lib/exports/iso]:

Please provide the ACL for the Local ISO domain.

See the exports(5) manpage for the format.

Examples:

- To allow access for host1, host2 and host3, input: host1(rw) host2(rw) host3(rw)

- To allow access to the entire Internet, input: *(rw)

For more information, see: http://www.ovirt.org/Troubleshooting_NFS_Storage_Issues

Local ISO domain ACL: 192.168.1.0/24(rw)

Local ISO domain name [ISO_DOMAIN]:

--== MISC CONFIGURATION ==--

Please choose Data Warehouse sampling scale:

(1) Basic

(2) Full

(1, 2)[1]:

--== END OF CONFIGURATION ==--

[ INFO ] Stage: Setup validation

[WARNING] Less than 16384MB of memory is available

--== CONFIGURATION PREVIEW ==--

Application mode : both

Default SAN wipe after delete : False

Update Firewall : False

Host FQDN : appclient.smartmap

Configure local Engine database : True

Set application as default page : True

Configure Apache SSL : True

Engine database secured connection : False

Engine database user name : engine

Engine database name : engine

Engine database host : localhost

Engine database port : 5432

Engine database host name validation : False

Engine installation : True

NFS setup : True

PKI organization : smartmap

NFS export ACL : 192.168.1.0/24(rw)

NFS mount point : /var/lib/exports/iso

DWH installation : True

DWH database secured connection : False

DWH database host : localhost

DWH database user name : ovirt_engine_history

DWH database name : ovirt_engine_history

DWH database port : 5432

DWH database host name validation : False

Configure local DWH database : True

Configure Image I/O Proxy : True

Configure VMConsole Proxy : True

Configure WebSocket Proxy : True

Please confirm installation settings (OK, Cancel) [OK]:

[ INFO ] Stage: Transaction setup

[ INFO ] Stopping engine service

[ INFO ] Stopping ovirt-fence-kdump-listener service

8.1.4. 配置NFS服务共享目录

[root@appclient ~]# mkdir /var/lib/exports/data

[root@appclient ~]# chown vdsm:kvm /var/lib/exports/data/

[root@appclient ~]# vi /etc/exports.d/ovirt-engine-iso-domain.exports

修改内容如下:

/var/lib/exports/iso 192.168.1.0/24(rw)

/var/lib/exports/data 192.168.1.0/24(rw)

8.1.5. 重启服务

[root@appclient ~]# systemctl restart rpc-statd nfs-server

8.2. 配置节点服务器

8.2.1. 安装KVM并配置网桥

见第1节

8.2.2. 安装ovirt节点软件

[root@server1 ~]# yum install -y vdsm

Loaded plugins: fastestmirror, versionlock

base | 3.6 kB 00:00:00

extras | 3.4 kB 00:00:00

updates | 3.4 kB 00:00:00

8.3. 进入Web管理界面进行设置

8.3.1. 进入Web管理界面

clip_image021

clip_image023

clip_image025

8.3.2. 加入节点

clip_image027

clip_image029

clip_image031

clip_image033

8.3.3. 加入存贮

clip_image035

8.3.4. 创建虚拟机

clip_image037