Quản Trị Mạng - Công nghệ ảo hóa trong Linux với KVM (Kernel-based Virtual Machine) hẳn không còn xa lạ với các nhà quản trị mạng cũng như nhiều người dùng. Tuy nhiên sự phát triển của những hệ điều hành có nhân Linux hết sức nhanh chóng, kéo theo sự thay đổi trong cách sử dụng KVM khiến không ít người e ngại nâng cấp cho hệ thống của mình. Chuyên mục Linux trên QuanTriMang sẽ cố gắng cập nhật đầy đủ các hướng dẫn tối ưu nhất để bạn đọc có thể dễ dàng thao tác, kịp thời, nhanh chóng. Bài hướng dẫn sau đây sẽ trình bày cách sử dụng KVM trên hệ thống Ubuntu 11.10.
1. Một số lưu ý
Trước hết bạn cần đảm bảo rằng phần cứng của mình hỗ trợ công nghệ ảo hóa, tức là CPU thuộc dòng Intel VT hoặc AMD-V.
Phần minh họa sau chúng tôi sử dụng hostname server1.example.com, địa chỉ IP của KVM host là 192.168.0.100.
Toàn bộ các lệnh dưới đây cần được chạy dưới quyền root, vì vậy bạn hãy trở thành root trước khi bắt đầu thực hiện:
Sudo su
2. Cài đặt KVM và vmbuilder
Trước khi tiến hành, bạn cần xác định xem CPU của mình có hỗ trợ ảo hóa phần cứng hay không:
egrep '(vmx|svm)' --color=always /proc/cpuinfo
Nếu màn hình hiển thị thông tin dạng như sau:
root@server1:~# egrep '(vmx|svm)' --color=always /proc/cpuinfo
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush
mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt rdtscp lm 3dnowext 3dnow rep_good nopl extd_apicid
pni cx16 lahf_lm cmp_legacy svm extapic cr8_legacy 3dnowprefetch lbrv
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush
mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt rdtscp lm 3dnowext 3dnow rep_good nopl extd_apicid
pni cx16 lahf_lm cmp_legacy svm extapic cr8_legacy 3dnowprefetch lbrv
root@server1:~#
Như vậy là CPU của bạn có hỗ trợ, ngược lại nếu không hiển thị gì thì bạn hãy dừng lại ở đây.
Để cài đặt KVM và vmbuilder (một script để khởi tạo hệ thống máy ảo Ubuntu cơ bản) chúng ta chạy:
apt-get install ubuntu-virt-server python-vm-builder kvm-pxe
Sau đó cần thêm vào user như là đăng nhập hiện tại (root) cho nhóm libvirtd:
adduser `id -un` libvirtd
adduser `id -un` kvm
Bạn cần đăng xuất và đăng nhập lại để các thành viên trong nhóm mới có hiệu lực:
Kiểm tra xem KVM đã cài đặt thành công hay chưa, chạy lệnh:
virsh -c qemu:///system list
Nếu màn hình hiển thị các thông tin như dưới đây chứng tỏ bạn đã thành công:
Id Name State
----------------------------------
root@server1:~#
Ngược lại, nếu có lỗi nào đó hãy thực hiện thêm lần nữa.
Tiếp theo chúng ta cần thiết lập một cầu nối cho mạng trên máy chủ (network bridge) để có thể truy cập máy ảo từ xa bằng các host khác nhau như hệ thống vật lý trong mạng. Để làm điều này, chỉ cần cài đặt gói bridge-utils...
apt-get install bridge-utils
…và cấu hình một bridge. Mở /etc/network/interfaces:
vi /etc/network/interfaces
Trước khi sửa đổi tập tin sẽ trông như sau:
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
auto eth0
iface eth0 inet static
address 192.168.0.100
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255
gateway 192.168.0.1
Bạn tiến hành sửa lại như dưới đây:
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
auto eth0
iface eth0 inet manual
auto br0
iface br0 inet static
address 192.168.0.100
network 192.168.0.0
netmask 255.255.255.0
broadcast 192.168.0.255
gateway 192.168.0.1
bridge_ports eth0
bridge_fd 9
bridge_hello 2
bridge_maxage 12
bridge_stp off
(Hãy chắc chắn rằng các thiết lập chính xác đối với mạng của bạn!)
Khởi động lại mạng:
/etc/init.d/networking restart
Và chạy:
ifconfig
Network bridge (br0) sẽ hiển thị như sau:
root@server1:~# ifconfig
br0 Link encap:Ethernet HWaddr 00:1e:90:f3:f0:02
inet addr:192.168.0.100 Bcast:192.168.0.255 Mask:255.255.255.0
inet6 addr: fe80::21e:90ff:fef3:f002/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:17 errors:0 dropped:0 overruns:0 frame:0
TX packets:17 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:1196 (1.1 KB) TX bytes:1966 (1.9 KB)
eth0 Link encap:Ethernet HWaddr 00:1e:90:f3:f0:02
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:35100 errors:0 dropped:0 overruns:0 frame:0
TX packets:18619 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:51126318 (51.1 MB) TX bytes:1521772 (1.5 MB)
Interrupt:41 Base address:0x6000
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
virbr0 Link encap:Ethernet HWaddr 46:b4:d1:49:75:eb
inet addr:192.168.122.1 Bcast:192.168.122.255 Mask:255.255.255.0
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
root@server1:~#
Trước khi chúng ta bắt đầu máy ảo đầu tiên, nên khởi động lại hệ thống:
Reboot
Nếu không có thể sảy ra thông báo lỗi open /dev/kvm: Permission denied trong thư mục /var/log/libvirt/qemu/.
3. Tạo một image-based VM
Bây giờ chúng ta có thể tạo ra máy ảo đầu tiên - image-based VM (nếu bạn muốn có thật nhiều lượng traffic và các thao tác đọc – ghi cho máy ảo, hãy sử dụng một LVM-based VM như mục 6 sau đây sẽ giới thiệu. Image-based VM gây nặng cho đĩa cứng IO).
Ở đây tôi muốn tạo máy ảo của mình trong thư mục /var/lib/libvirt/images/ (không thể tạo trong /root bởi user libvirt-qemu không có quyền đọc trong thư thư mục này).
Chúng tôi sẽ tạo một thư mục mới cho mỗi máy ảo, chẳng hạn như /var/lib/libvirt/images/vm1, /var/lib/libvirt/images/vm2, /var/lib/libvirt/images/vm3,… bởi vì mỗi máy ảo sẽ có một thư mục con có tên ubuntu-kvm tương ứng với mỗi thư mục vừa tạo. Nếu cố gắng tạo một thư mục thứ hai trong /var/lib/libvirt/images/vm1, bạn sẽ nhận được thông báo lỗi ubuntu-kvm already exists (trừ khi bạn chạy vmbuilder với đối số --dest=DESTDIR):
2009-05-07 16:32:44,185 INFO Cleaning up
ubuntu-kvm already exists
root@server1:/var/lib/libvirt/images/vm1#
Chúng tôi sử dụng công cụ vmbuilder để tạo các máy ảo (tìm hiểu thêm vmbuilder tại đây). Vmbuilder sử dụng một template để tạo máy ảo – template này nằm trong thư mục /etc/vmbuilder/libvirt/. Đầu tiên ta tạo một bản sao:
cp /etc/vmbuilder/libvirt/* /var/lib/libvirt/images/vm1/mytemplates/libvirt/
Tiếp theo là đến phần phân vùng cho VM. Chúng ta tạo một tập tin có tên vmbuilder.partition...
vi /var/lib/libvirt/images/vm1/vmbuilder.partition
… và xác định phân vùng mong muốn như sau:
root 8000
swap 4000
---
/var 20000
Như vậy phân vùng root (/) được xác định với kích thước 8000MB, một phân vùng swap 4000MB, và một phân vùng /var với 20000MB. Dòng --- có tác dụng làm cho các phân vùng bên dưới nó (ở đây là /var) là một ảnh đĩa riêng biệt. Tức là tạo ra hai ảnh đĩa, một cho root và swa, một cho /var. Tất nhiên, bạn được tự do định nghĩa bất cứ phân vùng nào mình thích (miễn là bao gồm cả root và swap).
Tôi muốn cài đặt openssh-server trong VM. Để đảm bảo rằng mỗi VM có một OpenSSH key duy nhất, chúng ta không thể cài đặt openssh-server khi tạo VM. Vì vậy giải pháp là tạo một script có tên boot.sh để thực thi khi khởi động VM lần đầu tiên. Nó sẽ cài đặt openssh-server (với một key duy nhất) và có hiệu lực với user (ở đây sử dụng username mặc định là administrator với mật khẩu mặc định quantrimang) để thay đổi mật khẩu khi đăng nhập lần đầu tiên.
vi /var/lib/libvirt/images/vm1/boot.sh
# This script will run the first time the virtual machine boots
# It is ran as root.
# Expire the user account
passwd -e administrator
# Install openssh-server
apt-get update
apt-get install -qqy --force-yes openssh-server
Lưu ý thay đổi username administrator với tên đăng nhập mặc định của bạn.
Bây giờ hãy nhìn vào:
vmbuilder kvm ubuntu –help
để tìm hiểu thêm về các tùy chọn có sẵn.
Tiếp theo, tạo VM đầu tiên, vm1, chúng ta vào thư mục VM…
cd /var/lib/libvirt/images/vm1/
… và chạy vmbuilder:
Hầu hết các tùy chọn là tự nó giải thích. --part quy định cụ thể các tập tin với chi tiết các phân vùng, có liên quan tới thư mục đang hoạt động (đó là lý do tại sao chúng ta cần đi tới thư mục VM trước khi chạy vmbuilder). --templates quy định cụ thể thư mục lưu giữ tập tin template (liên quan tới thư mục đang hoạt động), và --firstboot quy định script cho lần khởi động đầu tiên. --libvirt=qemu:///system sẽ “nói” cho KVM để thêm VM này vào danh sách máy ảo có sẵn. --addpkg cho phép bạn chỉ định các gói Ubuntu muốn cài đặt trong quá trình khởi tạo VM (đây là lý do tại sao không nên thêm openssh-server vào danh sách và sử dụng script để thay thế). --bridge thiết lập một bridge network; như bridge br0 mà chúng ta đã tạo trong mục 2. Bây giờ là lúc xác định bridge.
Trong dòng --mirror bạn có thể chỉ định một kho lưu trữ chính thức của Ubuntu, chẳng hạn http://de.archive.ubuntu.com/ubuntu. Nếu bỏ qua --mirror, Ubuntu sẽ sử dụng kho mặc định (http://archive.ubuntu.com/ubuntu).
Quá trình xây dựng có thể mất vài phút. Sau đó bạn sẽ tìm thấy tập tin cấu hình XML cho VM trong /etc/libvirt/qemu/ (=> /etc/libvirt/qemu/vm1.xml):
root@server1:/var/lib/libvirt/images/vm1# ls -l /etc/libvirt/qemu/
total 8
drwxr-xr-x 3 root root 4096 2011-11-16 11:01 networks
-rw------- 1 root root 2017 2011-11-16 11:18 vm1.xml
root@server1:/var/lib/libvirt/images/vm1#
Các ảnh đĩa được đặt trong ubuntu-kvm/ - thư mục con của thư mục VM:
root@server1:/var/lib/libvirt/images/vm1# ls -l /var/lib/libvirt/images/vm1/ubuntu-kvm/
total 627736
-rw-r--r-- 1 root root 315424768 2011-11-16 11:17 tmpYxLTYF.qcow2
-rw-r--r-- 1 root root 327614464 2011-11-16 11:18 tmpyyxauA.qcow2
root@server1:/var/lib/libvirt/images/vm1
4. Tạo một VM thứ hai
Tương tự như trên, nếu muốn tạo thêm một VM nữa (vm2), dưới đây là một tóm tắt về các lệnh cần thực hiện:
cp /etc/vmbuilder/libvirt/* /var/lib/libvirt/images/vm2/mytemplates/libvirt/
vi /var/lib/libvirt/images/vm2/vmbuilder.partition
vi /var/lib/libvirt/images/vm2/boot.sh
vmbuilder kvm ubuntu --suite=oneiric --flavour=virtual --arch=amd64 --mirror=http://de.archive.ubuntu.com/ubuntu -o --libvirt=qemu:///system --ip=192.168.0.102 --gw=192.168.0.1 --part=vmbuilder.partition --templates=mytemplates --user=administrator --name=Administrator --pass=howtoforge --addpkg=vim-nox --addpkg=unattended-upgrades --addpkg=acpid --firstboot=/var/lib/libvirt/images/vm2/boot.sh --mem=256 --hostname=vm2 --bridge=br0
(Lưu ý rằng bạn không thể tạo một thư mục mới cho VM (/var/lib/libvirt/images/vm2) nếu truyền đối số -d DESTDIR cho lệnh vmbuilder – nó cho phép bạn tạo một VM mới trong thư mục đã tạo VM khác. Trong trường hợp đó không cần tạo mới tập tin vmbuilder.partition và boot.sh, cũng không cần chỉnh sửa template, nhưng có thể dễ dàng sử dụng các tập tin đã tồn tại:
vmbuilder kvm ubuntu --suite=oneiric --flavour=virtual --arch=amd64 --mirror=http://de.archive.ubuntu.com/ubuntu -o --libvirt=qemu:///system --ip=192.168.0.102 --gw=192.168.0.1 --part=vmbuilder.partition --templates=mytemplates --user=administrator --name=Administrator --pass=howtoforge --addpkg=vim-nox --addpkg=unattended-upgrades --addpkg=acpid --firstboot=/var/lib/libvirt/images/vm1/boot.sh --mem=256 --hostname=vm2 --bridge=br0 -d vm2-kvm
)
5. Quản trị máy ảo
Các máy cảo có thể được quản trị thông qua virsh, là một "virtual shell". Để kết nối tới virtual shell ta chạy:
virsh --connect qemu:///system
virtual shell sẽ trông như sau:
Welcome to virsh, the virtualization interactive terminal.
Type: 'help' for help with commands
'quit' to quit
virsh #
Bây giờ có thể nhập vào lệnh sau trên virtual shell để quản trị máy ảo của bạn:
Help
Một danh sách các lệnh có sẵn sẽ được liệt kê:
virsh # help
Grouped commands:
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
blkiotune Get or set blkio parameters
console connect to the guest console
cpu-baseline compute baseline CPU
cpu-compare compare host CPU with a CPU described by an XML file
create create a domain from an XML file
define define (but don't start) a domain from an XML file
destroy destroy a domain
detach-device detach device from an XML file
detach-disk detach disk device
detach-interface detach network interface
domid convert a domain name or UUID to domain id
domjobabort abort active domain job
domjobinfo domain job information
domname convert a domain id or UUID to domain name
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
inject-nmi Inject NMI to the guest
managedsave managed save of a domain state
managedsave-remove Remove managed save of a domain
maxvcpus connection vcpu maximum
memtune Get or set memory parameters
migrate migrate domain to another host
migrate-setmaxdowntime set maximum tolerable downtime
reboot reboot 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
schedinfo show/set scheduler parameters
screenshot take a screenshot of a current domain console and store it into a file
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 an inactive domain
update-device update device from an XML file
vcpucount domain vcpu counts
vcpuinfo detailed domain vcpu information
vcpupin control domain vcpu affinity
version show version
vncdisplay vnc display
Domain Monitoring (help keyword 'monitor'):
domblkinfo domain block device size information
domblkstat get device block stats for a domain
domifstat get network interface stats for a domain
dominfo domain information
dommemstat get memory statistics for a domain
domstate domain state
list list domains
Host and Hypervisor (help keyword 'host'):
capabilities capabilities
connect (re)connect to hypervisor
freecell NUMA free memory
hostname print the hypervisor hostname
nodeinfo node information
qemu-monitor-command Qemu Monitor Command
sysinfo print the hypervisor sysinfo
uri print the hypervisor canonical URI
Interface (help keyword 'interface'):
iface-begin create a snapshot of current interfaces settings, which can be later commited (iface-commit) or restored (iface-rollback)
iface-commit commit changes made since iface-begin and free restore point
iface-define define (but don't start) a physical host interface 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-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 (but don't start) a network from an XML file
net-destroy destroy a network
net-dumpxml network information in XML
net-edit edit XML configuration for a network
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 an inactive network
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 a device on the node
nodedev-dettach dettach 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
Secret (help keyword 'secret'):
secret-define define or modify a secret from an XML file
secret-dumpxml secret attributes in XML
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
snapshot-current Get the current snapshot
snapshot-delete Delete a domain snapshot
snapshot-dumpxml Dump XML for a domain snapshot
snapshot-list List snapshots for a domain
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 (but don't start) a pool from an XML file
pool-delete delete a pool
pool-destroy destroy 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
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 a volume 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-upload upload a file into 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
virsh #
List
Để hiển thị toàn bộ máy ảo, chạy lệnh:
list –all
Để hiển thị toàn bộ máy ảo đang và không hoạt động:
Id Name State
----------------------------------
- vm1 shut off
- vm2 shut off
virsh #
Trước khi khởi động máy ảo mới lần đầu tiên, bạn cần định nghĩa nó từ tập tin xml trong thư mục /etc/libvirt/qemu/:
define /etc/libvirt/qemu/vm1.xml
Lưu ý rằng bất cứ khi nào chỉnh sửa tập tin xml của máy ảo trong /etc/libvirt/qemu/ bạn đều phải chạy lại lệnh define.
Bây giờ chúng ta đã có thể khởi động VM:
start vm1
Sau một vài khoảnh khắc, bạn có thể kết nối tới VM với SSH client như PuTTY; đăng nhập với username và password mặc định. Lần đăng nhập đầu tiên bạn sẽ được yêu cầu thay đổi password.
List
Hiển thị các máy ảo đang chạy:
Id Name State
----------------------------------
1 vm1 running
virsh #
Để dừng một máy ảo, chạy lệnh:
shutdown vm1
Để dừng máy ảo ngay lập tức (như việc rút phích cắm điện):
destroy vm1
Tạm dừng máy ảo:
suspend vm1
Tiếp tục hoạt động của máy ảo (khi đang ở trạng thái dừng):
resume vm1
Trên đây là những lệnh quan trọng nhất bạn cần ghi nhớ. Thoát khỏi virtual shell:
Quit
6. Tạo một LVM-Based VM
LVM-Based VM có một số ưu điểm hơn các image-based VM. Chúng không gây nặng ổ cứng IO và dễ dàng sao lưu bằng cách sử dụng LVM snapshots.
Để có thể sử dụng LVM-based VM, bạn cần một nhóm volume có không gian hợp lý và chưa được phân bố cho bất kỳ volume vật lý nào. Ở đây chúng tôi dùng /dev/vg0 với kích thước khoảng 465GB.
root@server1:~# vgdisplay
--- Volume group ---
VG Name vg0
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 465.27 GiB
PE Size 4.00 MiB
Total PE 119109
Alloc PE / Size 24079 / 94.06 GiB
Free PE / Size 95030 / 371.21 GiB
VG UUID NQOLhN-wBWi-pUdD-el7p-TADJ-fJGd-3ALJbf
root@server1:~#
… có chứa khối vật lý /dev/vg0/root với kích thước khoảng 100GB và /dev/vg0/swap_1 kích thước 1GB – phần còn lại không được phân bố và có thể sử dụng cho các máy ảo:
root@server1:~# lvdisplay
--- Logical volume ---
LV Name /dev/vg0/root
VG Name vg0
LV UUID KHbV2K-QKet-b660-aerE-x03F-nGVB-iR028M
LV Write Access read/write
LV Status available
# open 1
LV Size 93.13 GiB
Current LE 23841
Segments 1
Allocation inherit
Read ahead sectors auto
- currently set to 256
Block device 252:0
--- Logical volume ---
LV Name /dev/vg0/swap_1
VG Name vg0
LV UUID NfmS1J-nVcl-l0W0-vBVG-2sDO-Rwwc-bnl9Yo
LV Write Access read/write
LV Status available
# open 2
LV Size 952.00 MiB
Current LE 238
Segments 1
Allocation inherit
Read ahead sectors auto
- currently set to 256
Block device 252:1
root@server1:~#
Bây giờ chúng ta tạo máy ảo vm5 như một LVM-based VM. Chúng ta có thể dùng lại lệnh vmbuilder. Vmbuilder biết rõ tùy chọn --raw cho phép ghi máy ảo tới một thiết bị block (ví dụ /dev/vg0/vm5) – và không có lỗi nào xảy ra. Tuy nhiên bạn không thể khở động máy ảo trên, do đó cần tạo một vm5 như image-based VM đầu tiên và sau đó chuyển đổi sang LVM-based VM.
cp /etc/vmbuilder/libvirt/* /var/lib/libvirt/images/vm5/mytemplates/libvirt/
Hãy chắn rằng bạn đã tạo toàn bộ phân vùng trong một file ảnh, vì vậy không cần sử dụng --- trong tập tin vmbuilder.partition:
root 8000
swap 2000
/var 10000vi /var/lib/libvirt/images/vm5/boot.sh
# This script will run the first time the virtual machine boots
# It is ran as root.
# Expire the user account
passwd -e administrator
# Install openssh-server
apt-get update
apt-get install -qqy --force-yes openssh-server
Như bạn thấy từ tập tin vmbuilder.partition, VM sẽ sử dụng tối đa 20GB, do đó chúng ta tạo một khối vật lý có tên /dev/vg0/vm5 có kích thước 20GB:
lvcreate -L20G -n vm5 vg0
Không tạo ra một hệ thống tập tin trong khối vật lý mới!
Sử dụng lệnh qemu-img để chuyển đổi hình ảnh sang LVM-based VM. Trước tiên hãy đi tới thư mục ubuntu-kvm/ của VM…
cd /var/lib/libvirt/images/vm5/ubuntu-kvm/
… và tìm tên của hình ảnh:
root@server1:/var/lib/libvirt/images/vm5/ubuntu-kvm# ls -l
total 622732
-rw-r--r-- 1 root root 637796352 2011-11-16 12:49 tmpN27tbO.qcow2
root@server1:/var/lib/libvirt/images/vm5/ubuntu-kvm#
Sau khi xác được tên của ảnh (tmpN27tbO.qcow2), chúng ta có thể convert như sau:
qemu-img convert tmpN27tbO.qcow2 -O raw /dev/vg0/vm5
Và sau đó có thể xóa ảnh đĩa:
rm -f tmpN27tbO.qcow2
Tiếp theo chúng ta cần thay đổi cấu hình của VM:
virsh edit vm5
Thay đổi những phần sau:
[...]
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2'/>
<source file='/var/lib/libvirt/images/vm5/ubuntu-kvm/tmpN27tbO.qcow2'/>
<target dev='hda' bus='ide'/>
<address type='drive' controller='0' bus='0' unit='0'/>
</disk>
[...]
Để trở thành như thế này:
[...]
<disk type='file' device='disk'>
<driver name='qemu' type='raw'/>
<source file='/dev/vg0/vm5'/>
<target dev='hda' bus='ide'/>
<address type='drive' controller='0' bus='0' unit='0'/>
</disk>
[...]
Bạn có thể sử dụng virsh để quản trị VM:
virsh --connect qemu:///system
Bởi vì chúng ta đã sửa đổi tập tin xml của VM, cho nên cần chạy lại lệnh define…
define /etc/libvirt/qemu/vm5.xml
… trước khi khởi động VM:
start vm5
7. Các liên kết tham khảo
- KVM (Ubuntu Community Documentation): https://help.ubuntu.com/community/KVM
- Vmbuilder: https://help.ubuntu.com/community/JeOSVMBuilder
- JeOS and vmbuilder: http://doc.ubuntu.com/ubuntu/serverguide/C/jeos-and-vmbuilder.html
- Ubuntu: http://www.ubuntu.com/