天天看點

VIII virtualization&kvm

VIII virtualization&kvm

OS将對硬體資源的使用都虛拟成system call,某個程序隻要與硬體打交道都要經過kernel提供的接口(system call)

rss(程序啟動後必須要位于記憶體中,絕對不可以被交換出去(不被清出去))

page cache(程序運作時打開的檔案,可放到交換分區中(可被清出去))

anon page(程序運作過程當中産生的資料,如堆中的一部分資料)

第一個程序運作打開一個很大的檔案,第二個程序運作沒有足夠的記憶體時,核心會将第一個程序打開的檔案(page cache)統統清出去,之後CPU又切到第一個程序時發現打開的檔案沒了,産生缺頁異常,再重新從硬碟上調取

MMU(memory management unit,線性位址-->實體位址,MMU每次轉換都要一級頁目錄查找、二級頁目錄查找,再平移計算才得到記憶體,為加速這個過程有TLB)

CPU通過IO port知道在某時刻與哪個IO打交道(CPU與IO裝置交換資料通過IOport實作),IO裝置在啟動時要向CPU注冊它使用的IO port,一個IO裝置可使用一片連續的IO port,并注冊使用中斷号(讓IO裝置通知CPU有緊急事件要處理)以實作當IO裝置上有信号讓CPU知道哪個IO裝置有信号,而且要通過IO port與這個裝置打交道,CPU通過可程式設計中斷控制器讓每一個IO裝置注冊使用中斷線上的中斷裝置号,如網卡上有人ping來一個封包,要将産生的電信号讀下來放在記憶體網絡緩沖區,若是disk IO放在disk緩沖區(每個裝置都有緩沖區)

站在OS核心角度,kernel認為自己可使用所有硬體:CPU(全量CPU時間片),記憶體(連續,全部的記憶體空間0x0000-max,32bitOS記憶體最開始1M給BIOS,16M留給DMA;64bitOS有1G給DMA,這1G核心也能用),I/O(全部可用IO)

VA(virtual address線性位址)

PA(physical address)

虛拟化(将一個實體硬體平台虛拟成多個)

vmware(模拟出一堆硬體裝置,每一個硬體裝置都是獨立平台)

虛拟化要解決的問題(硬體之上的OS,有使用者空間、核心空間;vmware虛拟機所模拟出的多個硬體平台上的每一個OS也有使用者空間、核心空間;每個核心都意識不到其它主機存在,直接使用硬體裝置(記憶體),這将會覆寫掉其它的正在使用的記憶體空間,産生資源争用會使系統崩潰,硬體之上的這個OS将記憶體留一部分給kernel用,其它的給程序用,vmware虛拟機及其它程序使用的記憶體是高位址記憶體空間(非0位址空間),關鍵是每個核心都要使用從0開始的記憶體位址空間)

guest OS(虛拟出來的虛拟機,記憶體位址轉換要有兩次,效率低,多個guest OS要與IO裝置(網卡、磁盤)互動)

hypervisor(虛拟機管理程式)

CPU虛拟化(将時間片再分細點,指令分普通指令和特權指令,ring{0,1,2,3},ring0,privileged ring特權環是能運作敏感指令(特權指令)的,程序運作隻能運作普通指令(程序在cpu上運作無非将程序的代碼轉換為cpu上運作的指令),要想用特權指令,如要通路硬碟、通路記憶體中的資料時通過system call,這時程序要退出,核心在cpu的ring0上運作;guest OS的kernel中同樣有普通指令、特權指令,當guest OS上的程序需要運作特權指令(實際上管理虛拟機軟體vmware的運作是在使用者空間的,是以guest OS是不能運作敏感指令的,不能讓虛拟機的核心運作在ring0上,隻能運作在ring3上,否則它會将硬體資源視為可全量使用,會清空其它程序的記憶體、重新開機系統等操作)又不能運作這顯然不合适,每一個kernel都認為自己在ring0上,通過模拟讓guest OS認為自己在ring0上,保留一些關鍵的特權指令(如重新開機系統等),否則無法保證整個OS的安全性,實際上guest OS并不真正運作特權指令,每次guest OS的程序-->guest OS的核心-->host OS的核心,ring0就是一堆特權指令集來保證各guest OS間是隔離的,當host OS要關機就能控制整個系統關機,不管guest允不允許,host OS的核心才是真正意義的特權階層,host OS要能監控每一個guest OS執行的指令并判定它能否運作)

X86平台要實作CPU的虛拟化面臨的挑戰(特權級壓縮ring compression,VMM,virtual machine monitor必須要運作在ring0上,為避免guest OS控制系統資源,guestOS不得不降低自身的運作級别在ring3上(特權級不夠使用),VMM使用分頁或段限制的方式保護實體記憶體的通路,但64bit模式下段限制不起作用,而分頁又不區分ring{0,1,2},為統一和簡化VMM的設計,guest OS隻能和使用者程序一樣運作在ring3上,VMM必須監控guest OS對GDT、IDT(CPU寄存器)等特權資源的位置,防止guest OS運作在ring0,同時又要保護降級後的guest OS不受guest程序的主動攻擊或無意破壞;特權級别名ring alias,搞一些假的特權指令集告訴guest OS這就是ring0;位址空間壓縮address space compression;非特權敏感指令;靜默特權失敗silentprivilege failure;中斷虛拟化interrupt virtualization)

classical virtualization的基本需求(1974,Popek、Goldberg,真正意義的VMM至少需要三個方面的标準:等價執行equivalient execution,除資源可用性及時間上的不同之外,程式在虛拟化環境中及真正環境中的執行是完全相同的;性能performance,指令集中的大部分指令要能直接運作在CPU上;安全safety,VMM要能完全控制系統資源,某個guest OS運作不能影響到其它的guest OS,各guest OS間要實作隔離,且任何一個guest OS要執行特權指令,host OS要能提前捕獲對其處理,任何一個guest OS都不能越過host OS對整個實體硬體發出任何特權控制指令)

注:Intel和AMD的CPU(X86)上有模糊地帶(普通指令與特權指令間)

CPU硬體虛拟化(Intel:VT-x;AMD:AMD-V;特權級别加入ring-1,guest OS在ring0上,事實上ring0是空出來的一環沒有指令,當guestOS試圖要在ring0上運作時會觸發ring-1,由ring-1決定執行指令、轉換并翻譯這個指令運作)

記憶體虛拟化(Intel(EPT,extended page table)和AMD(RVI,rapid virtualization indexing;NPT,nested pagetables)分别通過EPT、RVI技術為虛拟化應用提升shadow MMU(完成VA-->HA一步到位)的性能,降低CPU的占用率,提供良好的吞吐量;并通過标記tagged TLB來避免虛拟機切換時頻繁清寫flush TLB以提高TLB緩存的命中率(用TLB儲存MMU的轉換結果)

KVM 還借助于KSM(KernelSame-pageMerging)這個核心特性實作了記憶體頁面共享。KSM 通過掃描每個虛拟機的記憶體查找各虛拟機間相同的記憶體頁,并将這些記憶體頁合并為一個被各相關虛拟機共享的單獨頁面。在某虛拟機試圖修改此頁面中的資料時,KSM 會重新為其提供一個新的頁面副本。實踐中,運作于同一台實體主機上的具有相同 GuestOS 的虛拟機之間出現相同記憶體頁面的機率是很的,比如共享庫、核心或其它記憶體對象等都有可能表現為相同的記憶體頁,是以,KSM 技術可以降低記憶體占用進而提高整體性能。

注:将離散的記憶體位址空間在hypervisor上再整合在一起分給guest OS,guest OS的VA-->guest OS的PA-->host OS的PA(HA);MMU,memory management unit

VIII virtualization&kvm

IO裝置虛拟化(網卡、硬碟等大多數的IO裝置是通過軟體(如vmware)模拟(假網卡、假硬碟),guestOS的網卡往外發封包(IP封包本身是獨立的),來的封包哪個主機收(guest OS還是host OS),是根據MAC接收封包的,假硬碟上存的資料最終都要到實體硬碟上,在實體硬碟上建立本地回環鏡像檔案(如用dd指令建立的檔案,格式化後能充當swap分區用)與模拟的磁盤建立關聯關系,guest OS就把假硬碟當硬碟用,但真正在實體機上表現的是個檔案,虛拟的磁盤沒實體硬碟性能好,IO要轉換兩次,若要讓guest OS的IO disk性能好點,使用共享存儲(iSCSI),guest OS作為client直接使用共享存儲;網卡也是這樣,模拟一個假網卡與本地的檔案建立關聯關系,guest OS A同guest OS B之間經網卡通信(或guest OS同host OS通信)借助于OS通過IPC解決(vmware中有虛拟通道),無論使用什麼MAC都無所謂,若與外部網絡通信,通過bridge、NAT,NAT這種方式是将實體機網卡上的MAC當作網關,源位址轉換,類似各guest OS組成網絡,要與外部網絡通信時将封包發至網關,實體機通過位址轉換送到外部網絡,外部網絡是看不到guest OS的,bridge這種方式将guest OS的虛拟網卡綁定在實體網卡上且讓實體網卡運作在混雜模式下(無論目标MAC是不是它都要接收,接收下來轉給guest OS,二層代理機制,在二層就轉了),bridge這種方式可将實體網卡了解為是switch,host OS的網卡可了解為也是虛拟網卡,guest OS上的網卡也是虛拟網卡,實體網卡接收到封包目标MAC是哪個虛拟網卡就轉發到對應的虛拟網卡上(橋接就是網橋,模拟的是switch))

IO虛拟化(Intel和AMD在主機闆上建立晶片組時,這個晶片組可完成IO虛拟化(在硬體級别上),如Intel:IOMMU,IO裝置要映射到目前OS上,為IO配置設定緩沖區,在passthrough技術上要借助IOMMU)

VIII virtualization&kvm

半虛拟化PV(para virtualization,IO裝置虛拟化,guest OS的kernel-->vmware-->host OS的kernel-->實體網卡,性能不好,若直接與host OS的核心打交道則性能會好很多,将中間那步繞過去,模拟的檔案該存在讓它存在直接繞過它,将host OS網卡的驅動程式做成system call直接輸出給虛拟機使用(guest OS-->host OS的system call),這違反虛拟化原則,guest OS就知道它在虛拟化環境中,這種技術叫半虛拟化para virtualization,性能好,直接與硬體打交道速度要快)

完全虛拟化FV(full virtualization,guest OS不認為它在虛拟化環境中;CPU不支援硬體虛拟化技術,要模拟特權指令)

硬體輔助的虛拟化HVM(hardware-assistant VM,CPU支援硬體虛拟化技術,VMM運作在ring-1,guest OS運作在ring0, HVM,hardware-assistant VM,硬體輔助的虛拟化)

PV和HVM整合(guest OS知道自己在虛拟化環境中,隻要與硬體打交道,host OS都向guest OS輸出system call(将特權指令集也輸出為system call)或叫hypercall(hypervisor call),這樣性能會好很多,要求在PV下的OS必須要改核心才能使用hypercall(win不能改核心))

PV on HVM(基于HVM的PV技術,把PV中的CPU不用了而用HVM,用IO的PV,這樣既利用了CPU的HVM,又利用IO的PV技術,性能會很好)

注:cpu、memory、io都可用PV,有了HVM,cpu的PV将用不着,io的PV能用得上,硬體再輔助,某一種IO裝置就那一個,有資源争用

IO穿透技術passthrough I/O(guest OS直接使用獨立的網卡)

常見的虛拟化模型:

有主控端的VMM,VMM要借助于核心才能完成虛拟化(hosted VMM)

硬體之上直接是VMM,這種模型下的VMM稱為hypervisor,VMM具備OS的管理機制(VMM自帶對CPU、memory等的管理),可了解為是精簡的OS隻提供虛拟化服務,VMM具備驅動底層硬體的能力(安裝前要檢視VMM所支援的硬體類型)

注:vmware workstation,vmware server,vmware ESX商業(hypervisor),vmware ESXi(免費,簡易版)

Xen提供對CPU、memory、interrupt這三個關鍵性硬體管理外,其它功能如驅動等都不提供,Xen它自己驅動不了任何硬體裝置,要在Xen之上立即安裝一個虛拟機(Linux),這個特權Linux提供驅動,提供管理界面,可直接操作底層硬體,Xen中的虛拟機稱為Dom{0,1,2,3……}(domain),Dom0為特權虛拟機,通過Dom0來管理其它的Dom{1,2,3}(稱為DomU),Dom0要使用CPU、memory、interrupt這三個關鍵性硬體要通過Xen,而其它的IO裝置可直接使用,在Dom0上建立一模拟裝置,要通過Xen關聯至Dom1上(Dom0将半虛拟化的硬體驅動程式通過Xen的hypercall送給Dom1),Dom1要使用網卡向外發資料要先發至Dom0由Dom0通路硬體網卡,Xen不管理IO等硬體裝置,Dom1要使用CPU(或memory或interrupt)則直接由Xen管理,這樣一部分要交由Xen管理,一部分交由Dom0管理,Xen是一種半虛拟化的解決方案,就算cpu、memory不支援HVM,Xen照樣可高性能運作,若cpu、memory支援HVM,Xen也可使用full virtualization,各硬體是模拟的性能較差,完全虛拟化FV和PV的最大差別,FV中的guest OS的kernel不用修改了,那Xen之上的虛拟機可使用win了(FV的好處),若Dom1是Linux可使用PV on HVM(CPU不虛拟化了使用HVM,而對于其它的IO硬體使用PV))

Qemu(quickemulator,是獨立虛拟軟體,能獨立運作虛拟機,kqemu是該軟體的加速軟體;常用于模拟器,1M,虛拟化軟體,跨平台虛拟,如将硬體CPUx86的模拟成蘋果的arm或IBM的power pc,可幫助程式員提供測試環境,好處如底層是X86的CPU,可在guest OS上也使用X86的CPU并進行優化,讓其接近硬體CPU的性能運作)

通常Xen和Qemu結合使用,Qemu主要實作為其它guest OS基于軟體方式模拟硬體(虛拟網卡、虛拟硬碟等)、本地回環檔案(用檔案充當虛拟硬碟用),qemu-img支援衆多的格式,包括vmware的格式

Xend/xm(在Xen上建立虛拟機,安裝OS并引導,Xen提供了專門的管理工具Xend/xm,Xend是管理服務,xm是指令(可start、pause、suspend某個虛拟機,完全在CLI下),Xen将其對硬體的管理功能通過API輸出給xm這個管理工具,建立好硬體不用重新開機直接附加在虛拟機上并能讓虛拟機識别出來,Xen可虛拟CPU,用xm通過Xen的API建立多個CPU,虛拟機可直接使用,比vmware workstation要強大靈活,通過Xen的API可開發出圖形管理工具,有數十種管理工具(CLI下和GUI下),如openstack、cloudstack,這些雲平台就是利用虛拟機(Xen)的API提供了能夠管理虛拟機程序的管理程式

注:如redhat為Xen提供的管理工具virsh比xm更強大且易用,virsh支援衆多虛拟化技術且更通用

VIII virtualization&kvm

KVM(kernel-based VM,基于核心的虛拟機,KVM是核心子產品,沒有這個子產品OS還是本來的OS,這個子產品一旦被kernel裝載了,OS就搖身變成了hypervisor,KVM可讓OS成為hypervisor,KVM取巧利用核心提供的各種驅動,在OS kernel的基礎上成為hypervisor,在hypervisor之上跑的是虛拟機(實際上是程序),用ps也能看到,核心自身管理硬體,在核心之上還要提供OS用來管理虛拟機,在硬體之上的 host OS可啟動額外的程序(虛拟機),所有的虛拟機都表現為程序,在guest mode(來賓模式)下有user space和kernel space)

kvm(結構簡單,分兩部分(裝置驅動/dev/kvm;針對模拟pc硬體的使用者空間元件);

注:百科上的kvm:KVM 是 kernel-based Virtual Machine 的簡稱,是一個開源的系統虛拟化子產品,自Linux2.6.20之後內建在Linux的各個主要發行版本中。它使用Linux自身的排程器進行管理,是以相對于Xen,其核心源碼很少。KVM已成為學術界的主流VMM之一。KVM的虛拟化需要硬體支援(如Intel VT技術或者AMD V技術)。是基于硬體的完全虛拟化。而Xen早期則是基于軟體模拟的Para-Virtualization,新版本則是基于硬體支援的完全虛拟化。但Xen本身有自己到程序排程器,存儲管理子產品等,是以代碼較為龐大。廣為流傳的商業系統虛拟化軟體VMware ESX系列也是基于軟體模拟的Para-Virtualization。

KVM (全稱是 Kernel-based Virtual Machine) 是 Linux 下 x86 硬體平台上的全功能虛拟化解決方案,包含一個可加載的核心子產品 kvm.ko 提供和虛拟化核心架構和處理器規範子產品。

使用 KVM ,可允許運作多個虛拟機,包括 Linux 和 Windows作業系統。每個虛拟機有私有的硬體,包括網卡、磁盤以及圖形适配卡等。

KVM如何使用硬體(kernel将CPU時間片分給虛拟機;memory,kernel虛拟化一部分即可;iodevice,管理的OS模拟硬體,虛拟機用網卡時,虛拟機的kernel-->管理的OS模拟的硬體-->真正的kernel-->硬體(類似Xen);模拟硬體借助Qemu,它可虛拟化任何硬體,乍看KVM是多餘的,沒有KVM,Qemu照樣可虛拟化,KVM有Qemu沒有的優勢,Qemu對CPU的虛拟是在user space通過軟體模拟加速實作的,性能再好也無法與kernel性能相比,而KVM是核心子產品比Qemu模拟出的硬體性能要好,更能接近硬體性能)

通常使用KVM+Qemu,KVM要求隻能裝在支援硬體虛拟化的CPU上,而且隻能在X86_64平台(Xen若硬體不支援虛拟化可半虛拟化);KVM在2.6.20後直接整合進kernel上,Xen沒有;2.6.37以後Xen也加入kernel(注意是運作在Xen上的DomU而非Dom0);3.0以後的kernel運作在Dom0上的Xen也收入核心(也就是3.0以後的kernel可直接使用Xen,3.0之前的kernel要使用Xen得打更新檔);redhat2008年收購了KVM(以色列公司的KVM),redhat6.0之後隻支援KVM;Xen比KVM強大、穩定,Xen(英國劍橋大學)被Citrix思傑(僅次于vmware第二大虛拟化提供商)收購

redhat(KVM)、citrix(Xen)、vmware(vmware)、microsoft(hyper-V)

KVM(redhat引入virtio(将IO實作PV),支援passthroughI/O)

container(在kernel之上提供了userspace(有對網卡、硬碟的配置程式,可了解為是VM),kernel是公共的,性能比FV和PV要好,對于FV和PV要運作兩個kernel,若任何一個VM管理不慎将kernel搞崩潰了,其它VM将不能正常運作,VM間隔離效果沒FV和PV好)

openVZ(Linux上的container技術,很多IDC提供VPS(virtualprivate server)時使用openVZ或Xen)

wine(虛拟出win的庫,這樣win的所有程式都能運作,cywin在win下虛拟linux的庫運作linux程式)

注:隻要底層有真正硬體,所有硬體都能模拟,Qemu還可跨平台模拟

常見的虛拟化技術(virtualization products at a glance):

VIII virtualization&kvm

X86平台虛拟化技術(Intel:VT-x、EPT、IOMMU)

虛拟化中的網絡模型(如vmware下的NAT、host-only、bridge、vmnet{1,2,3},NAT模型下可自動配置設定IP):

可了解為VMM用軟體模拟了一個switch,建立的虛拟機VM1隻要關聯到虛拟網絡上,就意味着關聯到虛拟的switch上,這個虛拟的switch是連到host OS的虛拟網卡上的(網路上的芳鄰可看到vmnet1);host-only,VM1通過虛拟網卡可與實體機通信,不能同外部網絡通信,若在實體機上有一dhcp服務指定在實體網卡上,switch不隔離廣播封包,那VM{1,2,3}均可擷取到位址;虛拟通道是專用網絡,如vmnet2是僅模拟了一個switch,實體機上沒有對應的虛拟網卡,僅能讓在此虛拟通道上的VM{1,2,3}通信;NAT模型下VM{1,2,3}可通路外網,而外網主機不能主動通路VM{1,2,3}除非做DNAT規則要定義在實體主機上(win下的vmware會自動生成規則,而linux下要自己寫規則);bridge模型下可了解為實體網卡成為了模拟的switch,所有的封包都通過switch出去,對于發來的封包switch會全部接收下來,再根據MAC判斷是哪個網卡上的,是實體網卡還是VM{1,2,3}的網卡,橋接時是不提供dhcp服務的

虛拟機多時,彼此間通信要統一管理會比較麻煩,openstack和cloudstack提供了一種平台,能讓實體機随時能加進來,如目前的實體機不夠用再加幾台進來,正在運作的虛拟機流動的在不同的實體機上運作(實時遷移),某一實體機出問題,其上的虛拟機會遷移到其它實體機上運作,不影響虛拟機的使用,雲還能管理網絡,虛拟機加進來後要給這個虛拟機配置設定IP,如何與其它公司的虛拟機隔離,雲還要提供存儲,雲為虛拟機更友善的使用提供了統一管理的接口(IaaS基礎架構即服務)

raw格式(優點:尋址簡單,通路效率較高,可通過格式轉換工具友善的轉換為其它格式,可友善的被主控端挂載,可在不啟動VM的情況下和主控端進行資料傳輸;缺點:實作簡單,不支援壓縮、快照、加密、cow等特性,raw格式檔案在建立時指定大小之後就占用了主控端指定大小的空間,而qcow2等稀疏模式的鏡像格式可從很小的檔案按需增長);

qcow2格式(是qcow的改進,建議使用,是qemu實作的一種VM鏡像格式,qcow2檔案存儲資料的基本單元是cluster,每一個cluster由若幹個資料扇區組成,每個資料扇區的大小是512byte,在qcow2中,要定位鏡像檔案的cluster,需要經過兩次位址查詢操作,類似于主存二級頁表轉換機制;更小的存儲空間,即使不支援holes FS也可,使用du -h和ll看到的一模一樣;copy on write support,where the p_w_picpath only represents changes madeto an underlying disk p_w_picpath,此特性在SUN ZFS表現的淋漓盡緻;支援多個snapshot;支援zlib磁盤壓縮;支援AES加密

VIII virtualization&kvm

[root@master ~]# virsh -h   #(management user interface,The virsh program is the main interface for managing virsh guest domains. The program can be used to create,pause, and shutdown domains. It canalso be used to list current domains.)

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

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

 options:

   -c | --connect=URI      hypervisorconnection URI

   -r | --readonly         connectreadonly

   -d | --debug=NUM        debuglevel [0-4]

   -h | --help             this help

   -q | --quiet            quiet mode

   -t | --timing           printtiming information

   -l | --log=FILE         outputlogging to file

   -v                      shortversion

   -V                      longversion

        --version[=TYPE]   version, TYPEis short or long (default short)

   -e | --escape <char>    setescape sequence for console

commands (non interactive mode):

Domain Management

   attach-device                 attach device from an XML file

   attach-disk                   attach disk device

   attach-interface              attach network interface

   autostart                     autostart a domain

   blkdeviotune                   Setor query a block device I/O tuning parameters.

   blkiotune                      Getor 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 p_w_picpath.

   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'tstart) 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

   domhostname                    print the domain's hostname

   domid                         convert a domain name or UUID to domain id

   domif-setlink                  setlink 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

   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 inXML

    edit                           edit XML configuration for a domain

   inject-nmi                    Inject NMI to the guest

   send-key                      Send keycodes to the guest

   managedsave                   managed save of a domain state

   managedsave-remove            Remove managed save of a domain

   maxvcpus                      connection vcpu maximum

   memtune                        Getor set memory parameters

   migrate                       migrate domain to another host

   migrate-setmaxdowntime         setmaximum tolerable downtime

   migrate-setspeed               Setthe maximum migration bandwidth

   migrate-getspeed               Getthe maximum migration bandwidth

   numatune                       Getor set numa parameters

    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 stateto a file

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

   save-p_w_picpath-dumpxml            saved state domain information in XML

   save-p_w_picpath-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

   setmaxmem                     change maximum memory limit

   setmem                        change memory allocation

   setvcpus                      change number of virtual CPUs

    shutdown                       gracefully shutdown adomain

    start                          start a (previously defined)inactive domain

    suspend                        suspend a domain

   ttyconsole                     ttyconsole

    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                     vncdisplay

Domain Monitoring

   domblkerror                   Show errors on block devices

   domblkinfo                    domain block device size information

   domblklist                    list all domain blocks

   domblkstat                     getdevice block stats for a domain

   domcontrol                    domain control interface state

   domif-getlink                  getlink state of a virtual interface

   domiflist                     list all domain virtual interfaces

   domifstat                      getnetwork interface stats for a domain

   dominfo                       domain information

   dommemstat                     getmemory statistics for a domain

   domstate                      domain state

    list                           list domains

Host and Hypervisor

Interface

    iface-bridge                   create a bridge device andattach an existing network device to it

    iface-unbridge                 undefine a bridge device afterdetaching its slave device

Network Filter

Networking

Node Device

Secret

Snapshot

   snapshot-create               Create a snapshot from XML

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

   snapshot-current               Getor 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                Getthe name of the parent of a snapshot

   snapshot-revert               Revert a domain to a snapshot

Storage Pool

Storage Volume

Virsh itself

   cd                            change the current directory

   connect                       (re)connect to hypervisor

   echo                          echo arguments

   exit                          quit this interactive terminal

   help                           print help

   pwd                           print the current directory

   quit                          quit this interactive terminal

[root@master ~]# qemu-img -h

qemu-img version 0.12.1, Copyright (c) 2004-2008Fabrice Bellard

usage: qemu-img command [command options]

QEMU disk p_w_picpath utility

Command syntax:

  check [-f fmt] [--output=ofmt] [-r [leaks |all]] [-T src_cache] filename

  create [-f fmt] [-o options] filename [size]

 commit [-f fmt] [-t cache] filename

 compare [-f fmt] [-F fmt] [-T src_cache] [-p] [-s] filename1 filename2

  convert [-c] [-p] [-f fmt] [-t cache] [-Tsrc_cache] [-O output_fmt] [-o options] [-S sparse_size] filename [filename2[...]] output_filename

  info [-f fmt] [--output=ofmt] filename

  map[-f fmt] [--output=ofmt] filename

  snapshot [-l | -a snapshot | -c snapshot | -dsnapshot] filename

 rebase [-f fmt] [-t cache] [-T src_cache] [-p] [-u] -b backing_file [-Fbacking_fmt] filename

  resize filename [+ | -]size

Command parameters:

 'filename' is a disk p_w_picpath filename

 'fmt' is the disk p_w_picpath format. It is guessed automatically in mostcases

 'cache' is the cache mode used to write the output disk p_w_picpath, the valid

   options are: 'none', 'writeback' (default), 'writethrough', 'directsync'

   and 'unsafe'

 'size' is the disk p_w_picpath size in bytes. Optional suffixes

   'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte,1024M)

   and T (terabyte, 1024G) are supported. 'b' is ignored.

 'output_filename' is the destination disk p_w_picpath filename

 'output_fmt' is the destination format

 'options' is a comma separated list of format specific options in a

   name=value format. Use -o ? for an overview of the options supported bythe

   used format

 '-c' indicates that target p_w_picpath must be compressed (qcow format only)

 '-u' enables unsafe rebasing. It is assumed that old and new backingfile

      match exactly. The p_w_picpath doesn't need a working backing file before

      rebasing in this case (useful for renaming the backing file)

 '-h' with or without a command shows this help and lists the supportedformats

 '-p' show progress of command (only certain commands)

 '-S' indicates the consecutive number of bytes that must contain onlyzeros

      for qemu-img to create a sparse p_w_picpath during conversion

 '--output' takes the format in which the output must be done (human orjson)

Parameters to checksubcommand:

 '-r' tries to repair any inconsistencies that are found during thecheck.

      '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all

      kinds of errors, with a higher risk of choosing the wrong fix or

      hiding corruption that has already occurred.

Parameters to snapshotsubcommand:

 'snapshot' is the name of the snapshot to create, apply or delete

 '-a' applies a snapshot (revert disk to saved state)

 '-c' creates a snapshot

 '-d' deletes a snapshot

 '-l' lists all snapshots in the given p_w_picpath

Parameters to compare subcommand:

 '-f' first p_w_picpath format

 '-F' second p_w_picpath format

 '-s' run in Strict mode - fail on different p_w_picpath size or sectorallocation

Supported formats: raw cow qcow vdi vmdkcloop dmg bochs vpc vvfat qcow2 qed vhdx parallels nbd blkdebug null host_cdromhost_floppy host_device file gluster

[root@master ~]# qemu-kvm -h

QEMU PC emulator version 0.12.1(qemu-kvm-0.12.1.2-2.491.el6_8.3), Copyright (c) 2003-2008

usage: qemu [options] [disk_p_w_picpath]

'disk_p_w_picpath' is a raw hard p_w_picpath p_w_picpath forIDE hard disk 0

Standard options:

-h or -help     display this help and exit

-version        display version information and exit

-M machine      select emulated machine (-M ? for list)

-cpu cpu        select CPU (-cpu ? for list)

-smp n[,maxcpus=cpus][,cores=cores][,threads=threads][,sockets=sockets]

                set the number of CPUs to 'n'[default=1]

                maxcpus= maximum number oftotal cpus, including

                  offline CPUs for hotplug etc.

                cores= number of CPU cores onone socket

                threads= number of threads onone CPU core

                sockets= number of discretesockets in the system

-numa node[,mem=size][,cpus=cpu[-cpu]][,nodeid=node]

-fda/-fdb file  use 'file' as floppy disk 0/1 p_w_picpath

-hda/-hdb file  use 'file' as IDE hard disk 0/1 p_w_picpath

-hdc/-hdd file  use 'file' as IDE hard disk 2/3 p_w_picpath

-cdrom file     use 'file' as IDE cdrom p_w_picpath (cdrom iside1 master)

-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]

      [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]

      [,cache=writethrough|writeback|none|directsync|unsafe][,format=f]

      [,serial=s][,addr=A][,id=name][,aio=threads|native]

       [,readonly=on|off][,copy-on-read=on|off]

                use 'file' as a drive p_w_picpath

-set group.id.arg=value

                set <arg> parameter foritem <id> of type <group>

                i.e. -setdrive.$id.file=/path/to/p_w_picpath

-global driver.prop=value

                set a global default for adriver property

-mtdblock file  use 'file' as on-board Flash memory p_w_picpath

-sd file        use 'file' as SecureDigital card p_w_picpath

-pflash file    use 'file' as a parallel flash p_w_picpath

-boot [order=drives][,once=drives][,menu=on|off]

      [,reboot-timeout=rb_time][,strict=on|off]

                'drives': floppy (a), hard disk(c), CD-ROM (d), network (n)

                'rb_timeout': the timeoutbefore guest reboot when boot failed, unit is ms

-snapshot      write to temporary filesinstead of disk p_w_picpath files

-m megs         set virtual RAM sizeto megs MB [default=128]

-redhat-disable-KSM  disable KSM on guest physical memory

-k language     use keyboard layout (for example 'fr' forFrench)

-audio-help    print list of audio drivers andtheir options

-soundhw c1,... enable audio support

                and only specified sound cards(comma separated list)

                use -soundhw ? to get the listof supported cards

                use -soundhw all to enable allof them

-usb            enable the USB driver (will be thedefault soon)

-usbdevice name add the host or guest USB device 'name'

-device driver[,prop[=value][,...]]

                add device (based on driver)

                prop=value,... sets driverproperties

                use -device ? to print allpossible drivers

                use -device driver,? to printall possible properties

-name string1[,process=string2]    set the name of the guest

           string1 sets the window title andstring2 the process name (on Linux)

-uuid %08x-%04x-%04x-%04x-%012x

                specify machine UUID

Display options:

-nographic      disable graphical output and redirectserial I/Os to console

-spice [port=port][,tls-port=secured-port][,x509-dir=<dir>]

      [,x509-key-file=<file>][,x509-key-password=<file>]

      [,x509-cert-file=<file>][,x509-cacert-file=<file>]

      [,x509-dh-key-file=<file>][,addr=addr][,ipv4|ipv6]

      [,tls-ciphers=<list>]

      [,tls-channel=[main|display|cursor|inputs|record|playback]]

      [,plaintext-channel=[main|display|cursor|inputs|record|playback]]

      [,sasl][,password=<secret>][,disable-ticketing]

      [,p_w_picpath-compression=[auto_glz|auto_lz|quic|glz|lz|off]]

      [,jpeg-wan-compression=[auto|never|always]]

      [,zlib-glz-wan-compression=[auto|never|always]]

      [,streaming-video=[off|all|filter]][,disable-copy-paste]

      [,disable-agent-file-xfer][,agent-mouse=[on|off]]

      [,playback-compression=[on|off]][,seamless-migration=[on|off]]

  enable spice

   atleast one of {port, tls-port} is mandatory

-portrait       rotate graphical output 90 deg left(only PXA LCD)

-vga [std|cirrus|vmware|qxl|xenfb|none]

                select video card type

-full-screen    start in full screen

-vnc display    start a VNC server on display

i386 target only:

-win2k-hack     use it when installing Windows 2000 toavoid a disk full bug

-no-fd-bootchk  disable boot signature checking for floppydisks

-no-acpi       disable ACPI

-balloon none   disable balloon device

-balloon virtio[,addr=str]

                enable virtio balloon device(default)

-acpitable[sig=str][,rev=n][,oem_id=str][,oem_table_id=str][,oem_rev=n][,asl_compiler_id=str][,asl_compiler_rev=n][,data=file1[:file2]...]

                ACPI table description

-smbios file=binary

                Load SMBIOS entry from binaryfile

-smbiostype=0[,vendor=str][,version=str][,date=str][,release=%d.%d]

                Specify SMBIOS type 0 fields

-smbios type=1[,manufacturer=str][,product=str][,version=str][,serial=str]

             [,uuid=uuid][,sku=str][,family=str]

                Specify SMBIOS type 1 fields

Network options:

-netnic[,vlan=n][,macaddr=mac][,model=type][,name=str][,addr=str][,vectors=v]

                create a new Network InterfaceCard and connect it to VLAN 'n'

-netuser[,vlan=n][,name=str][,net=addr[/mask]][,host=addr][,restrict=y|n]

        [,hostname=host][,dhcpstart=addr][,dns=addr][,tftp=dir][,bootfile=f]

        [,hostfwd=rule][,guestfwd=rule][,smb=dir[,smbserver=addr]]

                connect the user mode networkstack to VLAN 'n', configure its

                DHCP server and enabledoptional services

-nettap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile][,sndbuf=nbytes][,vnet_hdr=on|off][,vhost=on|off][,vhostfd=h][,vhostforce=on|off]

                connect the host TAP networkinterface to VLAN 'n' and use the

               network scripts 'file'(default=/etc/qemu-ifup)

                and 'dfile'(default=/etc/qemu-ifdown);

                use '[down]script=no' todisable script execution;

                use 'fd=h' to connect to analready opened TAP interface

               use 'sndbuf=nbytes' tolimit the size of the send buffer (the

                default is disabled 'sndbuf=0'to enable flow control set 'sndbuf=1048576')

                use vnet_hdr=off to avoidenabling the IFF_VNET_HDR tap flag; use

               vnet_hdr=on to make the lack ofIFF_VNET_HDR support an error condition

                use vhost=on to enableexperimental in kernel accelerator

                    (only has effect for virtioguests which use MSIX)

                use vhostforce=on to forcevhost on for non-MSIX virtio guests

                use 'vhostfd=h' to connect toan already opened vhost net device

-netsocket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]

                connect the vlan 'n' to anotherVLAN using a socket connection

-netsocket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]

                connect the vlan 'n' tomulticast maddr and port

-net dump[,vlan=n][,file=f][,len=n]

                dump traffic on vlan 'n' tofile 'f' (max n bytes per packet)

-net none       use it alone to have zero networkdevices; if no -net option

                is provided, the default is'-net nic -net user'

-netdev[user|tap|socket],id=str[,option][,option][,...]

Character device options:

-chardev null,id=id

-chardevsocket,id=id[,host=host],port=host[,to=to][,ipv4][,ipv6][,nodelay]

        [,server][,nowait][,telnet] (tcp)

-chardevsocket,id=id,path=path[,server][,nowait][,telnet] (unix)

-chardevudp,id=id[,host=host],port=port[,localaddr=localaddr]

        [,localport=localport][,ipv4][,ipv6]

-chardev msmouse,id=id

-chardevvc,id=id[[,width=width][,height=height]][[,cols=cols][,rows=rows]]

-chardev file,id=id,path=path

-chardev pipe,id=id,path=path

-chardev pty,id=id

-chardev stdio,id=id

-chardev serial,id=id,path=path

-chardev tty,id=id,path=path

-chardev parallel,id=id,path=path

-chardev parport,id=id,path=path

-chardevspicevmc,id=id,debug=debug,name=name

Bluetooth(R) options:

-bt hci,null    dumb bluetooth HCI - doesn't respond tocommands

-bt hci,host[:id]

                use host's HCI with the givenname

-bt hci[,vlan=n]

                emulate a standard HCI invirtual scatternet 'n'

-bt vhci[,vlan=n]

                add host computer to virtualscatternet 'n' using VHCI

-bt device:dev[,vlan=n]

                emulate a bluetooth device'dev' in scatternet 'n'

Linux/Multiboot boot specific:

-kernel bzImage use 'bzImage' as kernelp_w_picpath

-append cmdline use 'cmdline' as kernelcommand line

-initrd file    use 'file' as initial ram disk

Debug/Expert options:

-serial dev     redirect the serial port to char device'dev'

-parallel dev   redirect the parallel port to char device'dev'

-monitor dev    redirect the monitor to char device 'dev'

-qmp dev        like -monitor but opens in 'control'mode.

-monchardev=[name][,mode=readline|control][,default]

-debugcon dev   redirect the debug console to char device'dev'

-pidfile file   write PID to 'file'

-singlestep   always run in singlestep mode

-S              freeze CPU at startup (use 'c' tostart execution)

-realtime [mlock=on|off]

                run qemu with realtime features

                mlock=on|off controls mlocksupport (default: on)

-gdb dev        wait for gdb connection on 'dev'

-s              shorthand for -gdb tcp::1234

-d item1,...    output log to /tmp/qemu.log (use -d ? for alist of log items)

-hdachs c,h,s[,t]

                force hard disk 0 physicalgeometry and the optional BIOS

                translation (t=none or lba)(usually qemu can guess them)

-L path         set the directory for the BIOS, VGABIOS and keymaps

-bios file      set the filename for the BIOS

-enable-kvm     enable KVM full virtualization support

-machine [type=]name[,prop[=value][,...]]

                selects emulated machine(-machine ? for list)

                propertyaccel=accel1[:accel2[:...]] selects accelerator

                supported accelerators are kvm,tcg (default: kvm:tcg)

                dump-guest-core=on|off includeguest memory in a core dump (default=on)

-no-reboot      exit instead of rebooting

-no-shutdown    stop before shutdown

-loadvm [tag|id]

                start right away with a savedstate (loadvm in monitor)

-daemonize      daemonize QEMU after initializing

-option-rom rom load a file, rom, into theoption ROM space

-clock          force the use of the given methodsfor timer alarm.

                To see what timers areavailable use -clock ?

-rtc[base=utc|localtime|date][,clock=host|vm][,driftfix=none|slew]

                set the RTC base and clock,enable drift fix for clock ticks

-icount [N|auto]

                enable virtual instructioncounter with 2^N clock ticks per

                instruction

-watchdog i6300esb|ib700

                enable virtual hardwarewatchdog [default=none]

-watchdog-actionreset|shutdown|poweroff|pause|debug|none

                action when watchdog fires[default=reset]

-echr chr       set terminal escape character instead ofctrl-a

-virtioconsole c

                set virtio console

-show-cursor    show cursor

-tb-size n      set TB size

-incoming p     prepare for incoming migration, listen onport p

-nodefaults     don't create default devices.

-chroot dir     Chroot to dir just before starting the VM.

-runas user     Change to user id user just before startingthe VM.

-nodefconfig

                do not load default configfiles at startup

-readconfig <file>

-writeconfig <file>

                read/write config file

-no-kvm         disable KVM hardware virtualization

-no-kvm-irqchip disable KVM kernel modePIC/IOAPIC/LAPIC

-no-kvm-pit     disable KVM kernel mode PIT

-no-kvm-pit-reinjection disable KVM kernelmode PIT interrupt reinjection

-pcidevicehost=[seg:]bus:dev.func[,dma=none][,name=string]

                expose a PCI device to theguest OS.

                dma=none: don't perform any dmatranslations (default is to use an iommu)

                'string' is used in log output.

-nvram FILE          provide ia64 nvram contents

-tdf                 enable guest time driftcompensation

-kvm-shadow-memory MEGABYTES

                     allocate MEGABYTES for kvmmmu shadowing

-mem-path FILE       provide backing storage for guest RAM

-mem-prealloc        preallocate guest memory (use with-mempath)

-msg timestamp[=on|off]

                change the format of messages

                on|off controls leadingtimestamps (default:on)

-object TYPENAME[,PROP1=VALUE1,...]

                create an new object of typeTYPENAME setting properties

                in the order they arespecified.  Note that the 'id'

                property must be set.  These objects are placed in the

                '/objects' path.

-dump-vmstate <file>

                Output vmstate information inJSON format to file.

                Use the scripts/vmstate-static-checker.pyfile to

                check for possible regressionsin migration code

                by comparing two such vmstatedumps.

During emulation, the following keys areuseful:

ctrl-alt-f      toggle full screen

ctrl-alt-n      switch to virtual console 'n'

ctrl-alt        toggle mouse and keyboard grab

When using -nographic, press 'ctrl-a h' toget some help.

[root@master ~]# virt-install -h

Usage: virt-install --name NAME --ram RAMSTORAGE INSTALL [options]

Options:

 --version             showprogram's version number and exit

  -h,--help            show this help messageand exit

 --connect=URI         Connect tohypervisor with libvirt URI

  General Options:

    -n NAME, --name=NAME

                        Name of the guestinstance

    -r MEMORY, --ram=MEMORY

                        Memory to allocate forguest instance in megabytes

    --vcpus=VCPUS      Number of vcpus to configure for your guest. Ex:

                        --vcpus 5

                        --vcpus 5,maxcpus=10

                        --vcpussockets=2,cores=4,threads=2

   --cpuset=CPUSET     Set whichphysical CPUs domain can use.

   --cpu=CPU           CPU model andfeatures. Ex: --cpu coreduo,+x2apic

   --description=DESCRIPTION

                       Human readabledescription of the VM to store in the

                        generated XML.

   --security=SECURITY

                        Set domain securitydriver configuration.

   --numatune=NUMATUNE

                        Tune NUMA policy forthe domain process.

  Installation Method Options:

    -c CDROM, --cdrom=CDROM

                        CD-ROM installationmedia

   -l LOCATION, --location=LOCATION

                        Installation source(eg, nfs:host:/path,

                        http://host/path,ftp://host/path)

   --pxe               Boot from thenetwork using the PXE protocol

   --import            Build guestaround an existing disk p_w_picpath

   --init=INIT         Path to initbinary for container guest. Ex:

                        --init /path/to/app (tocontain an application)

                        --init /sbin/init (fora full OS container)

   --livecd            Treat theCD-ROM media as a Live CD

   -x EXTRA, --extra-args=EXTRA

                        Additional arguments to pass to theinstall kernel

                        booted from --location

   --initrd-inject=INITRD_INJECTIONS

                        Add given file to rootof initrd from --location

    --os-type=DISTRO_TYPE

                       The OS type beinginstalled, e.g. 'linux', 'unix',

                        'windows'

    --os-variant=DISTRO_VARIANT

                        The OS variant beinginstalled guests, e.g. 'fedora6',

                        'rhel5', 'solaris10','win2k'

   --boot=BOOTOPTS     Optionallyconfigure post-install boot order, menu,

                        permanent kernel boot,etc.

  Storage Configuration:

    --disk=DISKOPTS     Specify storage with various options. Ex.

                        --disk path=/my/existing/disk

                        --diskpath=/my/new/disk,size=5 (in gigabytes)

                        --disk vol=poolname:volname,device=cdrom,bus=scsi,...

   --nodisks           Don't set upany disks for the guest.

   --filesystem=FILESYSTEMS

                        Pass host directory tothe guest. Ex:

                        --filesystem/my/source/dir,/dir/in/guest

                        --filesystemtemplate_name,/,type=template

  Networking Configuration:

    -w NETWORK, --network=NETWORK

                        Configure a guestnetwork interface. Ex:

                        --network bridge=mybr0

                        --network network=my_libvirt_virtual_net

                        --networknetwork=mynet,model=virtio,mac=00:11...

   --nonetworks        Don't createnetwork interfaces for the guest.

  Graphics Configuration:

    --graphics=GRAPHICS

                        Configure guest displaysettings. Ex:

                        --graphics vnc

                       --graphicsspice,port=5901,tlsport=5902

                        --graphics none

                        --graphics vnc,password=foobar,port=5910,keymap=ja

    --noautoconsole     Don't automatically try to connect to theguest

                        console

  Device Options:

   --serial=SERIALS    Configure aguest serial device

   --parallel=PARALLELS

                        Configure a guestparallel device

   --channel=CHANNELS  Configure aguest communication channel

   --console=CONSOLES  Configure atext console connection between the guest

                        and host

   --host-device=HOSTDEVS

                        Configure physical hostdevices attached to the guest

   --soundhw=SOUNDHW   Configureguest sound device emulation

   --watchdog=WATCHDOG

                        Configure a guestwatchdog device

   --video=VIDEO       Configureguest video hardware.

   --smartcard=SMARTCARD

                        Configure a guestsmartcard device. Ex:

                        --smartcardmode=passthrough

   --redirdev=REDIRDEV

                        Configure a guestredirection device. Ex:

                        --redirdevusb,type=tcp,server=192.168.1.1:4000

   --panic=PANIC       Configure aguest panic device. Ex:

                        --panic default

  Virtualization Platform Options:

   -v, --hvm           This guestshould be a fully virtualized guest

   -p, --paravirt      This guestshould be a paravirtualized guest

   --container         This guestshould be a container guest

    --virt-type=HV_TYPE

                        Hypervisor name to use(kvm, qemu, xen, ...)

   --arch=ARCH         The CPUarchitecture to simulate

   --machine=MACHINE   The machinetype to emulate

   --noapic            Disables APICfor fully virtualized guest (overrides

                        value inos-type/os-variant db)

   --noacpi            Disables ACPIfor fully virtualized guest (overrides

   -u UUID, --uuid=UUID

                        UUID for the guest.

  Miscellaneous Options:

   --autostart         Have domainautostart on host boot up.

   --print-xml         Print thegenerated domain XML rather than define the

                        guest.

   --print-step=XMLSTEP

                        Print XML of a specificinstall step (1, 2, 3, all)

                        rather than define theguest.

   --noreboot          Don't bootguest after completing install.

   --wait=WAIT         Time to wait(in minutes)

   --dry-run           Run throughinstall process, but do not create devices

                        or define the guest.

   --force             Forces 'yes' for any applicableprompts, terminates

                        for all others

   -q, --quiet         Suppressnon-error output

   --prompt            Request userinput for ambiguous situations or

                        required options.

   -d, --debug         Printdebugging information

操作(KVM):

1、準備:

VIII virtualization&amp;kvm

注:kvm僅可在具有虛拟化功能的cpu上運作,intel-vt技術或amd-v技術;記憶體方面intel的EPT或amd的RVI

[root@master ~]# uname -rm

2.6.32-431.el6.x86_64 x86_64

[root@master ~]# cat /etc/redhat-release

Red Hat Enterprise Linux Server release 6.5(Santiago)

[root@master ~]# egrep --color "vmx|svm" /proc/cpuinfo   #(intel-vt關鍵字用vmx,amd-v關鍵字svm)

flags                   :fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflushdts mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tscarch_perfmon pebs bts xtopology tsc_reliable nonstop_tsc aperfmperfunfair_spinlock pni pclmulqdq vmx ssse3 fma cx16pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16crdrand hypervisor lahf_lm abm ida arat xsaveopt pln pts dts tpr_shadow vnmi eptvpid fsgsbase bmi1 avx2 smep bmi2 invpcid

[root@master ~]# lsmod | grep kvm

[root@master ~]# modprobe kvm   #(啟用kvm子產品)

[root@master ~]# modprobe kvm-intel   #(是intel加載kvm-intel,是amd加載kvm-amd)

kvm_intel              54285  0

kvm                   333172  1 kvm_intel

2、部署kvm環境:

[root@master ~]# llepel-release-6-8.noarch.rpm

-rw-r--r--. 1 root root 14540 Nov  5  2012epel-release-6-8.noarch.rpm

[root@master ~]# rpm -ivhepel-release-6-8.noarch.rpm   #(利用epel的yum源安裝相關軟體包)

[root@master ~]# yum -y install libvirt qemu-kvm virt-manager   #(KVM 虛拟機的建立依賴qemu-kvm :雖然 kvm 的技術已經相當成熟而且可以對很多東西進行隔離,但是在某些方面還是無法虛拟出真實的機器,比如對網卡的虛拟,那這個時候就需要另外的技術來做補充,而qemu-kvm則是這樣一種技術,它補充了 kvm 技術的不足,而且在性能上對 kvm 進行了優化。還可用 virt-manager,virt-viewer 來管理虛拟機;在建立和管理 KVM 虛拟機時還需要 libvirt 這個重要的元件:它是一系列提供出來的庫函數,用以其他技術調用,來管理機器上的虛拟機。包括各種虛拟機技術, kvm 、 xen 與 lxc 等,都可以調用 libvirt 提供的 api 對虛拟機進行管理。有這麼多的虛拟機技術,它為何能提供這麼多的管理功能那。是因為它的設計理念,它是面向驅動的架構設計。對任何一種虛拟機技術都開發設計相對于該技術的驅動。這樣不同虛拟機技術就可以使用不同驅動,而且互相直接不會影響,友善擴充。而且 libvirt 提供了多種語言的程式設計接口,可以直接通過程式設計,調用 libvirt 提供的對外接口實作對虛拟機的操作。如今流行的雲計算中的 IaaS 是與該庫聯系相當密切的)

Installed:

 libvirt.x86_64 0:0.10.2-60.el6        qemu-kvm.x86_64 2:0.12.1.2-2.491.el6_8.3         virt-manager.x86_64 0:0.9.0-31.el6       

Dependency Installed:

……

VIII virtualization&amp;kvm

注:libvirt的架構設計思想,在 libvirtapi 之上會有很多個 driver ,對于每一種虛拟機技術都會有一種 driver ,用來充當該虛拟機技術與 libvirt 之間的包裝接口。如此設計就可以避免 libvirt 需要設計各種針對不同虛拟機技術的接口,它主要關注底層的實作,提供對外接口調用,而不同的虛拟機技術通過調用 libvirt 提供的接口來完成自己所需要的功能。

[root@master ~]# service libvirtd start

Starting libvirtd daemon: libvirtd:relocation error: libvirtd: symbol dm_task_get_info_with_deferred_remove,version Base not defined in file libdevmapper.so.1.02 with link time reference

                                                           [FAILED]

[root@master ~]# yum-y install device-mapper

Starting libvirtd daemon:                                  [  OK  ]

[root@master ~]# ifconfig   #(libvirtd啟動後,會自動建立一個橋裝置,相當于vmware中host-only網絡裝置)

eth0     Link encap:Ethernet  HWaddr00:0C:29:1F:B6:AC 

         inet addr:10.96.20.113 Bcast:10.96.20.255 Mask:255.255.255.0

         inet6 addr: fe80::20c:29ff:fe1f:b6ac/64 Scope:Link

         UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

         RX packets:49554 errors:0 dropped:0 overruns:0 frame:0

         TX packets:16997 errors:0 dropped:0 overruns:0 carrier:0

         collisions:0 txqueuelen:1000

         RX bytes:47453022 (45.2 MiB)  TXbytes:1472183 (1.4 MiB)

eth1     Link encap:Ethernet  HWaddr00:0C:29:1F:B6:B6 

         inet addr:192.168.10.113 Bcast:192.168.10.255 Mask:255.255.255.0

         inet6 addr: fe80::20c:29ff:fe1f:b6b6/64 Scope:Link

         UP BROADCAST RUNNING MULTICAST MTU:1500  Metric:1

         RX packets:16561 errors:0 dropped:0 overruns:0 frame:0

         TX packets:10 errors:0 dropped:0 overruns:0 carrier:0

         RX bytes:1380247 (1.3 MiB)  TXbytes:636 (636.0 b)

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:390 errors:0 dropped:0 overruns:0 frame:0

         TX packets:390 errors:0 dropped:0 overruns:0 carrier:0

         collisions:0 txqueuelen:0

         RX bytes:26626 (26.0 KiB)  TXbytes:26626 (26.0 KiB)

virbr0    Link encap:Ethernet  HWaddr 52:54:00:A4:A9:C5 

          inet addr:192.168.122.1  Bcast:192.168.122.255  Mask:255.255.255.0

         RX packets:0 errors:0 dropped:0 overruns:0 frame:0

         TX packets:0 errors:0 dropped:0 overruns:0 carrier:0

         RX bytes:0 (0.0 b)  TX bytes:0(0.0 b)

[root@master ~]# brctl show   #(使用網橋管理指令檢視)

bridge name    bridgeid            STP enabled     interfaces

virbr0                 8000.525400a4a9c5        yes            virbr0-nic

[root@master ~]# rpm -ql qemu-kvm

/etc/ksmtuned.conf

/etc/modprobe.d/blacklist-kvm.conf

/etc/rc.d/init.d/ksm

/etc/rc.d/init.d/ksmtuned

/etc/sasl2/qemu-kvm.conf

/etc/sysconfig/ksm

/etc/sysconfig/modules/kvm.modules

/etc/udev/rules.d/80-kvm.rules

/usr/libexec/qemu-kvm

/usr/sbin/ksmtuned

[root@master ~]# ln -sv /usr/libexec/qemu-kvm /usr/bin/qemu-kvm

`/usr/bin/qemu-kvm' ->`/usr/libexec/qemu-kvm'

[root@master ~]# ll /etc/sysconfig/modules/kvm.modules

-rwxr-xr-x. 1 root root 245 Aug  9 10:55 /etc/sysconfig/modules/kvm.modules

[root@master ~]# service NetworkManager stop

Stopping NetworkManager daemon:                            [  OK  ]

[root@master ~]# chkconfig NetworkManageroff

[root@master ~]# virsh iface-bridge eth0 br0   #(使用virsh建立橋裝置,關聯網卡到橋裝置上,類似vmware中建立的實體橋接裝置;文法virsh  iface-bridge interfacebridge [--no-stp] [delay] [--no-start];virsh iface-unbridgebridge [--no-start])

Created bridge br0 with attached deviceeth0

Bridge interface br0 started

[root@master ~]# ifconfig

br0      Link encap:Ethernet  HWaddr00:0C:29:1F:B6:AC 

         RX packets:758 errors:0 dropped:0 overruns:0 frame:0

         TX packets:29 errors:0 dropped:0 overruns:0 carrier:0

         RX bytes:55900 (54.5 KiB)  TXbytes:2250 (2.1 KiB)

         RX packets:54072 errors:0 dropped:0 overruns:0 frame:0

         TX packets:17300 errors:0 dropped:0 overruns:0 carrier:0

         RX bytes:47983909 (45.7 MiB)  TXbytes:1514563 (1.4 MiB)

[root@master ~]# brctl show

br0            8000.000c291fb6ac          yes            eth0

[root@master ~]# yum -y install tigervnc tigervnc-server  #(安裝vncviewer)

[root@master ~]# rpm -ql tigervnc-server

/etc/rc.d/init.d/vncserver

/etc/sysconfig/vncservers

/usr/bin/Xvnc

/usr/bin/vncconfig

/usr/bin/vncpasswd

/usr/bin/vncserver

/usr/bin/x0vncserver

[root@master ~]# vncpasswd   

Password:

Verify:

[root@master ~]# vncserver   #(啟動vncserver)

New 'master:1 (root)' desktop is master:1

Creating default startup script/root/.vnc/xstartup

Starting applications specified in/root/.vnc/xstartup

Log file is /root/.vnc/master:1.log

[root@master ~]# vncserver -list

TigerVNC server sessions:

X DISPLAY #      PROCESSID

:1               6469

3、在kvm上部署guest os:

方式一(使用qemu-kvm):

[root@master ~]# mkdir -pv /kvm/p_w_picpaths

mkdir: created directory `/kvm'

mkdir: created directory `/kvm/p_w_picpaths'

[root@master ~]# qemu-img create -f raw /kvm/p_w_picpaths/test.raw 5G

Formatting '/kvm/p_w_picpaths/test.raw', fmt=rawsize=5368709120

[root@master ~]# ll -h /kvm/p_w_picpaths/test.raw

-rw-r--r--. 1 root root 5.0G Sep  5 18:46 /kvm/p_w_picpaths/test.raw

[root@master ~]# dd if=/dev/cdrom1 of=/kvm/p_w_picpaths/rhel6.iso  #(制作安裝guest os的CD光牒鏡像)

7526400+0 records in

7526400+0 records out

3853516800 bytes (3.9 GB) copied, 385.314s, 10.0 MB/s

[root@master ~]# qemu-kvm -cpu host -smp 1 -m 512 -drive file=/kvm/p_w_picpaths/test.raw,if=ide,media=disk,format=raw -drive file=/kvm/p_w_picpaths/rhel6.iso,media=cdrom -boot dc -usbdevice tablet   #(此指令是在前台運作,占據目前終端,預設位置在/usr/libexec/qemu-kvm已将其連結至/usr/bin/qemu-kvm)

VNC server running on `::1:5900'

[root@master ~]# vncviewer :5900   #(開啟另一視窗進入guestos,在前台運作占據目前終端視窗)

TigerVNC Viewer for X version 1.1.0 - builtMay 11 2016 13:00:50

Copyright (C) 1999-2011 TigerVNC Team andmany others (see README.txt)

See http://www.tigervnc.org for informationon TigerVNC.

Mon Sep 5 19:07:08 2016

 CConn:      connected to host localhost port 5900

 CConnection: Server supports RFB protocolversion 3.8

 CConnection: Using RFB protocol version 3.8

 TXImage:    Using default colormap and visual, TrueColor, depth 24.

 CConn:      Using pixel format depth 24 (32bpp) little-endian rgb888

 CConn:      Using Tight encoding

VIII virtualization&amp;kvm
VIII virtualization&amp;kvm

[root@master ~]# qemu-img info /kvm/p_w_picpaths/test.raw

p_w_picpath: /kvm/p_w_picpaths/test.raw

file format: raw

virtual size: 5.0G (5368709120 bytes)

disk size: 1.5G

方式二(使用virt-install):

[root@master ~]# qemu-img create -f qcow2 /kvm/p_w_picpaths/test2.qcow2 5G

Formatting '/kvm/p_w_picpaths/test2.qcow2',fmt=qcow2 size=5368709120 encryption=off cluster_size=65536

[root@master ~]# qemu-img info /kvm/p_w_picpaths/test2.qcow2

p_w_picpath: /kvm/p_w_picpaths/test2.qcow2

file format: qcow2

disk size: 196K

cluster_size: 65536

[root@master ~]# qemu-img check /kvm/p_w_picpaths/test2.qcow2

No errors were found on the p_w_picpath.

Image end offset: 262144

[root@master ~]# ll -h /kvm/p_w_picpaths/

total 5.1G

-rw-r--r--. 1 qemu qemu 3.6G Sep  5 03:20 rhel6.iso

-rw-r--r--. 1 root root193K Sep  5 19:32 test2.qcow2

-rw-r--r--. 1 root root 5.0G Sep  5 19:30 test.raw

[root@master ~]# virt-install --name=test2 --ram=512 --vcpus=1 --os-variant=rhel6 --disk path=/kvm/p_w_picpaths/test2.qcow2,format=qcow2,size=5,bus=virtio --accelerate --cdrom=/kvm/p_w_picpaths/rhel6.iso --graphics vnc,listen=0.0.0.0,port=5911 --network bridge=br0,model=virtio --noautoconsole   #(使用qcow2鏡像格式,建立guestos時必須要在此處指定其格式和使用virtio驅動,否則系統無法正常安裝,會提示virtio block device為0M)

Starting install...

Creating domain...                                                                                           |    0 B     00:00    

Domain installation still in progress. You can reconnect to

the console to complete the installationprocess.

[root@master ~]# ps aux | grep kvm

root       903  0.0  0.0     0     0 ?        S   17:58   0:00 [kvm-irqfd-clean]

qemu      9804  0.5 32.0 1370892 321788?      Sl   21:20  0:24 /usr/libexec/qemu-kvm -name test2 -S -M rhel6.6.0 -enable-kvm -m512 -realtime mlock=off -smp 1,sockets=1,cores=1,threads=1 -uuid5b4b8e46-3036-31a6-5670-77370675a550 -nodefconfig -nodefaults -chardevsocket,id=charmonitor,path=/var/lib/libvirt/qemu/test2.monitor,server,nowait-mon chardev=charmonitor,id=monitor,mode=control -rtc base=utc -no-shutdown-device ich9-usb-ehci1,id=usb,bus=pci.0,addr=0x4.0x7 -deviceich9-usb-uhci1,masterbus=usb.0,firstport=0,bus=pci.0,multifunction=on,addr=0x4-device ich9-usb-uhci2,masterbus=usb.0,firstport=2,bus=pci.0,addr=0x4.0x1-device ich9-usb-uhci3,masterbus=usb.0,firstport=4,bus=pci.0,addr=0x4.0x2-drive file=/kvm/p_w_picpaths/test2.qcow2,if=none,id=drive-virtio-disk0,format=qcow2,cache=none-devicevirtio-blk-pci,scsi=off,bus=pci.0,addr=0x5,drive=drive-virtio-disk0,id=virtio-disk0,bootindex=1-drive if=none,media=cdrom,id=drive-ide0-1-0,readonly=on,format=raw -deviceide-drive,bus=ide.1,unit=0,drive=drive-ide0-1-0,id=ide0-1-0 -netdevtap,fd=22,id=hostnet0,vhost=on,vhostfd=23 -devicevirtio-net-pci,netdev=hostnet0,id=net0,mac=52:54:00:7f:03:2f,bus=pci.0,addr=0x3-chardev pty,id=charserial0 -device isa-serial,chardev=charserial0,id=serial0-device usb-tablet,id=input0 -vnc 0.0.0.0:11 -vga cirrus -devicevirtio-balloon-pci,id=balloon0,bus=pci.0,addr=0x6 -msg timestamp=on

root      9827  0.0  0.0     0     0 ?        S   21:20   0:00 [kvm-pit-wq]

root     12075  0.0  0.0 103256  832 pts/1    S+   22:34  0:00 grep kvm

在win上使用TigerVNC連接配接

VIII virtualization&amp;kvm
VIII virtualization&amp;kvm
VIII virtualization&amp;kvm

裝完系統後會要求重新開機,此視窗會關閉

[root@master ~]# virsh start test2

Domain test2 started

[root@master ~]# virsh list   #(#virsh list--all可檢視所有domain包括關機的)

 Id    Name                           State

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

 6    test2                         running

[root@master ~]# ls /etc/libvirt

libvirt.conf  libvirtd.conf lxc.conf  nwfilter  qemu qemu.conf

[root@master ~]# ll /etc/libvirt/qemu/   #(自動生成test2.xml,此檔案很關鍵記錄着VM的所有配置)

total 8

drwx------. 3 root root 4096 Sep  4 23:58 networks

-rw-------. 1 root root3031 Sep  5 20:27 test2.xml

4、更改guest os配置:

注:使用#virsh reboot test2,不能加載新配置,要先用destroy再start

方式一(通過virsh edit DOMAIN直接編輯):

[root@master ~]# head -13 /etc/libvirt/qemu/test2.xml

<domain type='kvm'>

 <name>test2</name>

 <uuid>5b4b8e46-3036-31a6-5670-77370675a550</uuid>

  <memoryunit='KiB'>524288</memory>

  <currentMemoryunit='KiB'>524288</currentMemory>

 <vcpu placement='static'>1</vcpu>

[root@master ~]# virsh edit test2

 <memory unit='KiB'>824288</memory>

 <currentMemory unit='KiB'>824288</currentMemory>

[root@master ~]# virsh list --all

 Id   Name                          State

 [root@master~]# virsh destroy test2

Domain test2 destroyed

 [root@master~]# virsh list --all

 -    test2                          shut off

[root@master ~]# virsh start test2

 [root@master~]# virsh list

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

6 test2 running

VIII virtualization&amp;kvm

方式二(用dumpxml導出-->通過vim編輯-->用define重新定義domain的xml配置檔案):

[root@master ~]# virsh dumpxml test2 > test_tmp.xml

[root@master ~]# vim test_tmp.xml

<domain type='kvm' id='7'>

 <memory unit='KiB'>424320</memory>

 <currentMemory unit='KiB'>424288</currentMemory>

[root@master ~]# cp test_tmp.xml /etc/libvirt/qemu/test2.xml

cp: overwrite`/etc/libvirt/qemu/test2.xml'? y

[root@master ~]# virsh define /etc/libvirt/qemu/test2.xml

Domain test2 defined from/etc/libvirt/qemu/test2.xml

[root@master ~]# virsh destroy test2

VIII virtualization&amp;kvm

注:

#qemu-img convert -c -f raw -O qcow2 test.rawtest.qcow2   #(-c,compressed)

#virsh edit test

   <disk type='file' device='disk'>

     <driver name='qemu' type='qcow2'cache='none'/>

     <source file='/kvm/p_w_picpaths/test.qcow2'/>

     <target dev='vda' bus='virtio'/>

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

繼續閱讀