qemu-kvm.go 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package guestman
  15. import (
  16. "context"
  17. "fmt"
  18. "io/ioutil"
  19. "os"
  20. "path"
  21. "path/filepath"
  22. "regexp"
  23. "strconv"
  24. "strings"
  25. "sync/atomic"
  26. "syscall"
  27. "time"
  28. "yunion.io/x/jsonutils"
  29. "yunion.io/x/log"
  30. "yunion.io/x/pkg/appctx"
  31. "yunion.io/x/pkg/errors"
  32. "yunion.io/x/pkg/util/regutils"
  33. "yunion.io/x/pkg/util/seclib"
  34. "yunion.io/x/pkg/util/version"
  35. "yunion.io/x/pkg/utils"
  36. "yunion.io/x/onecloud/pkg/apis"
  37. api "yunion.io/x/onecloud/pkg/apis/compute"
  38. hostapi "yunion.io/x/onecloud/pkg/apis/host"
  39. noapi "yunion.io/x/onecloud/pkg/apis/notify"
  40. "yunion.io/x/onecloud/pkg/cloudcommon/consts"
  41. "yunion.io/x/onecloud/pkg/cloudcommon/notifyclient"
  42. "yunion.io/x/onecloud/pkg/hostman/guestman/arch"
  43. "yunion.io/x/onecloud/pkg/hostman/guestman/desc"
  44. deployapi "yunion.io/x/onecloud/pkg/hostman/hostdeployer/apis"
  45. "yunion.io/x/onecloud/pkg/hostman/hostdeployer/deployclient"
  46. "yunion.io/x/onecloud/pkg/hostman/hostinfo"
  47. "yunion.io/x/onecloud/pkg/hostman/hostinfo/hostbridge"
  48. "yunion.io/x/onecloud/pkg/hostman/hostinfo/hostconsts"
  49. "yunion.io/x/onecloud/pkg/hostman/hostutils"
  50. "yunion.io/x/onecloud/pkg/hostman/isolated_device"
  51. "yunion.io/x/onecloud/pkg/hostman/monitor"
  52. "yunion.io/x/onecloud/pkg/hostman/monitor/qga"
  53. "yunion.io/x/onecloud/pkg/hostman/options"
  54. "yunion.io/x/onecloud/pkg/hostman/storageman"
  55. "yunion.io/x/onecloud/pkg/hostman/storageman/lvmutils"
  56. "yunion.io/x/onecloud/pkg/httperrors"
  57. "yunion.io/x/onecloud/pkg/image/drivers/s3"
  58. "yunion.io/x/onecloud/pkg/mcclient"
  59. "yunion.io/x/onecloud/pkg/mcclient/auth"
  60. modules "yunion.io/x/onecloud/pkg/mcclient/modules/compute"
  61. identity_modules "yunion.io/x/onecloud/pkg/mcclient/modules/identity"
  62. "yunion.io/x/onecloud/pkg/util/cgrouputils"
  63. "yunion.io/x/onecloud/pkg/util/cgrouputils/cpuset"
  64. "yunion.io/x/onecloud/pkg/util/fileutils2"
  65. "yunion.io/x/onecloud/pkg/util/fuseutils"
  66. "yunion.io/x/onecloud/pkg/util/procutils"
  67. "yunion.io/x/onecloud/pkg/util/qemuimg"
  68. "yunion.io/x/onecloud/pkg/util/regutils2"
  69. "yunion.io/x/onecloud/pkg/util/seclib2"
  70. "yunion.io/x/onecloud/pkg/util/timeutils2"
  71. )
  72. const (
  73. STATE_FILE_PREFIX = "STATEFILE"
  74. MONITOR_PORT_BASE = 55900
  75. QMP_MONITOR_PORT_BASE = 56100
  76. LIVE_MIGRATE_PORT_BASE = 4396
  77. BUILT_IN_NBD_SERVER_PORT_BASE = 7777
  78. MAX_TRY = 3
  79. )
  80. type SKVMInstanceRuntime struct {
  81. QemuVersion string
  82. VncPassword string
  83. LiveMigrateDestPort *int64
  84. LiveMigrateUseTls bool
  85. syncMeta *jsonutils.JSONDict
  86. cgroupPid int
  87. cgroupName string
  88. stopping bool
  89. needSyncStreamDisks bool
  90. blockJobTigger map[string]chan struct{}
  91. quorumFailed int32
  92. StartupTask *SGuestResumeTask
  93. MigrateTask *SGuestLiveMigrateTask
  94. pciUninitialized bool
  95. pciAddrs *desc.SGuestPCIAddresses
  96. }
  97. type SKVMGuestInstance struct {
  98. SKVMInstanceRuntime
  99. *sBaseGuestInstance
  100. Monitor monitor.Monitor
  101. guestAgent *qga.QemuGuestAgent
  102. kickstartMonitor *SKickstartSerialMonitor
  103. archMan arch.Arch
  104. }
  105. func NewKVMGuestInstance(id string, manager *SGuestManager) *SKVMGuestInstance {
  106. qemuArch := arch.Arch_x86_64
  107. if manager.host.IsAarch64() {
  108. qemuArch = arch.Arch_aarch64
  109. } else if manager.host.IsRiscv64() {
  110. qemuArch = arch.Arch_riscv64
  111. }
  112. return &SKVMGuestInstance{
  113. SKVMInstanceRuntime: SKVMInstanceRuntime{
  114. blockJobTigger: make(map[string]chan struct{}),
  115. },
  116. sBaseGuestInstance: newBaseGuestInstance(id, manager, api.HYPERVISOR_KVM),
  117. archMan: arch.NewArch(qemuArch),
  118. }
  119. }
  120. // update guest runtime desc from source desc
  121. // and check is need regenerate runtime desc
  122. // these property can't be upate in running guest
  123. func (s *SKVMGuestInstance) updateGuestDesc() error {
  124. s.Desc = new(desc.SGuestDesc)
  125. err := jsonutils.Marshal(s.SourceDesc).Unmarshal(s.Desc)
  126. if err != nil {
  127. return errors.Wrap(err, "unmarshal source desc")
  128. }
  129. if s.isPcie() {
  130. s.setPcieExtendBus()
  131. }
  132. err = s.initGuestDesc()
  133. if err != nil {
  134. return err
  135. }
  136. return SaveLiveDesc(s, s.Desc)
  137. }
  138. // release allocated numa mems and realloc numa mems
  139. func (s *SKVMGuestInstance) reallocateNumaNodes(isMigrate bool) error {
  140. s.manager.cpuSet.Lock.Lock()
  141. defer s.manager.cpuSet.Lock.Unlock()
  142. ReleaseCpuNumaPin(s.manager, s.Desc.CpuNumaPin)
  143. s.Desc.CpuNumaPin = nil
  144. if isMigrate {
  145. if err := s.reallocateMigrateNumaNodes(); err != nil {
  146. return errors.Wrap(err, "reallocateMigrateNumaNodes")
  147. }
  148. } else {
  149. if err := s.allocGuestNumaCpuset(); err != nil {
  150. return errors.Wrap(err, "allocGuestNumaCpuset")
  151. }
  152. if err := s.initMemDesc(s.Desc.Mem); err != nil {
  153. return errors.Wrap(err, "fixNumaAllocate")
  154. }
  155. }
  156. return SaveLiveDesc(s, s.Desc)
  157. }
  158. func (s *SKVMGuestInstance) reallocateMigrateNumaNodes() error {
  159. nodeNumaCpus, err := s.manager.cpuSet.AllocCpusetWithNodeCount(int(s.Desc.Cpu), s.Desc.Mem*1024, s.Desc.MemDesc.GuestNumaNodeCount(), s.GetId())
  160. if err != nil {
  161. return errors.Wrap(err, "AllocCpusetWithNodeCount")
  162. }
  163. var cpuNumaPin = make([]*desc.SCpuNumaPin, 0)
  164. if len(nodeNumaCpus) > 0 {
  165. for nodeId, numaCpus := range nodeNumaCpus {
  166. unodeId := uint16(nodeId)
  167. vcpuPin := make([]desc.SVCpuPin, len(numaCpus.Cpuset))
  168. for i := range numaCpus.Cpuset {
  169. vcpuPin[i].Pcpu = numaCpus.Cpuset[i]
  170. }
  171. memPin := &desc.SCpuNumaPin{
  172. SizeMB: numaCpus.MemSizeKB / 1024, // MB
  173. NodeId: &unodeId,
  174. VcpuPin: vcpuPin,
  175. Unregular: numaCpus.Unregular,
  176. }
  177. cpuNumaPin = append(cpuNumaPin, memPin)
  178. }
  179. }
  180. if len(cpuNumaPin) > 0 {
  181. s.Desc.CpuNumaPin = cpuNumaPin
  182. if s.Desc.MemDesc.Mem != nil {
  183. s.Desc.MemDesc.Mem.SMemDesc.SetHostNodes(int(*cpuNumaPin[0].NodeId))
  184. for i := range s.Desc.MemDesc.Mem.Mems {
  185. s.Desc.MemDesc.Mem.Mems[i].SetHostNodes(int(*cpuNumaPin[i+1].NodeId))
  186. }
  187. }
  188. } else {
  189. if s.Desc.MemDesc.Mem != nil {
  190. s.Desc.MemDesc.Mem.SMemDesc.SetHostNodes(-1)
  191. for i := range s.Desc.MemDesc.Mem.Mems {
  192. s.Desc.MemDesc.Mem.Mems[i].SetHostNodes(-1)
  193. }
  194. }
  195. }
  196. return nil
  197. }
  198. func (s *SKVMGuestInstance) validateNumaAllocated(keywords string, isMigrate, isHotPlug bool, vcpuOrder [][]int) error {
  199. if len(s.Desc.CpuNumaPin) > 0 {
  200. if isMigrate {
  201. for i := range s.Desc.CpuNumaPin {
  202. for j := range s.Desc.CpuNumaPin[i].VcpuPin {
  203. s.Desc.CpuNumaPin[i].VcpuPin[j].Vcpu = vcpuOrder[i][j]
  204. }
  205. }
  206. return SaveLiveDesc(s, s.Desc)
  207. }
  208. if !isHotPlug {
  209. return SaveLiveDesc(s, s.Desc)
  210. }
  211. }
  212. guestPid := s.GetPid()
  213. if guestPid <= 0 {
  214. return errors.Errorf("guest not running? pid %d", guestPid)
  215. }
  216. numaMapPath := fmt.Sprintf("/proc/%d/numa_maps", guestPid)
  217. for {
  218. if !fileutils2.Exists(numaMapPath) {
  219. return errors.Errorf("guest not running? pid %d", guestPid)
  220. }
  221. // wait hugepage mem allocate
  222. if s.Monitor != nil && s.Monitor.IsConnected() {
  223. break
  224. }
  225. time.Sleep(time.Millisecond * 300)
  226. }
  227. content, err := fileutils2.FileGetContents(numaMapPath)
  228. if err != nil {
  229. return errors.Wrap(err, "read numa_maps")
  230. }
  231. readNodeAllocateMap := map[int]int{}
  232. numaNodeRegex := regexp.MustCompile(`^N[0-9]+=[0-9]+$`)
  233. for _, line := range strings.Split(content, "\n") {
  234. if idx := strings.Index(line, "hugepages"); idx < 0 {
  235. continue
  236. }
  237. if idx := strings.Index(line, keywords); idx < 0 {
  238. continue
  239. }
  240. // ... huge dirty=15 N0=3 N1=5 N2=5 N3=2 kernelpagesize_kB=1048576
  241. segs := strings.Split(line, " ")
  242. for _, seg := range segs {
  243. if !numaNodeRegex.MatchString(seg) {
  244. continue
  245. }
  246. log.Infof("hugepages segs %v", seg)
  247. nodeAllocate := strings.Split(seg[1:], "=")
  248. if len(nodeAllocate) != 2 {
  249. continue
  250. }
  251. node, _ := strconv.Atoi(nodeAllocate[0])
  252. size, _ := strconv.Atoi(nodeAllocate[1])
  253. if _, ok := readNodeAllocateMap[node]; !ok {
  254. readNodeAllocateMap[node] = 0
  255. }
  256. readNodeAllocateMap[node] += size * 1024
  257. }
  258. }
  259. log.Infof("read node allocate map %v", readNodeAllocateMap)
  260. s.manager.cpuSet.Lock.Lock()
  261. defer s.manager.cpuSet.Lock.Unlock()
  262. nodeNumaCpus := s.manager.cpuSet.setNumaNodes(readNodeAllocateMap, s.Desc.Cpu)
  263. var cpuNumaPin = make([]*desc.SCpuNumaPin, 0)
  264. for nodeId, numaCpus := range nodeNumaCpus {
  265. unodeId := uint16(nodeId)
  266. vcpuPin := make([]desc.SVCpuPin, len(numaCpus.Cpuset))
  267. for i := range numaCpus.Cpuset {
  268. vcpuPin[i].Pcpu = numaCpus.Cpuset[i]
  269. }
  270. memPin := &desc.SCpuNumaPin{
  271. SizeMB: numaCpus.MemSizeKB / 1024, // MB
  272. NodeId: &unodeId,
  273. VcpuPin: vcpuPin,
  274. Unregular: numaCpus.Unregular,
  275. }
  276. cpuNumaPin = append(cpuNumaPin, memPin)
  277. }
  278. if len(s.Desc.CpuNumaPin) > 0 { // hotplug mems
  279. s.Desc.CpuNumaPin = append(s.Desc.CpuNumaPin, cpuNumaPin...)
  280. return SaveLiveDesc(s, s.Desc)
  281. }
  282. if len(vcpuOrder) > 0 {
  283. for i := range cpuNumaPin {
  284. for j := range cpuNumaPin[i].VcpuPin {
  285. cpuNumaPin[i].VcpuPin[j].Vcpu = vcpuOrder[i][j]
  286. }
  287. }
  288. }
  289. s.Desc.CpuNumaPin = cpuNumaPin
  290. return SaveLiveDesc(s, s.Desc)
  291. }
  292. func (s *SKVMGuestInstance) initLiveDescFromSourceGuest(srcDesc *desc.SGuestDesc) error {
  293. srcDesc.SGuestProjectDesc = s.SourceDesc.SGuestProjectDesc
  294. srcDesc.SGuestRegionDesc = s.SourceDesc.SGuestRegionDesc
  295. srcDesc.SGuestControlDesc = s.SourceDesc.SGuestControlDesc
  296. srcDesc.SGuestMetaDesc = s.SourceDesc.SGuestMetaDesc
  297. for i := 0; i < len(srcDesc.Cdroms); i++ {
  298. if i == len(s.SourceDesc.Cdroms) {
  299. break
  300. }
  301. srcDesc.Cdroms[i].Path = s.SourceDesc.Cdroms[i].Path
  302. }
  303. for i := 0; i < len(srcDesc.Disks); i++ {
  304. for j := 0; j < len(s.SourceDesc.Disks); j++ {
  305. if srcDesc.Disks[i].Index == s.SourceDesc.Disks[j].Index {
  306. numQueues := srcDesc.Disks[i].NumQueues
  307. var targetStorage string
  308. if srcDesc.Disks[i].TargetStorageId != "" && storageman.GetManager().GetStorage(srcDesc.Disks[i].TargetStorageId) != nil {
  309. targetStorage = srcDesc.Disks[i].TargetStorageId
  310. }
  311. srcDesc.Disks[i].GuestdiskJsonDesc = s.SourceDesc.Disks[j].GuestdiskJsonDesc
  312. srcDesc.Disks[i].NumQueues = numQueues
  313. if targetStorage != "" {
  314. srcDesc.Disks[i].StorageId = targetStorage
  315. srcDesc.Disks[i].TargetStorageId = ""
  316. }
  317. }
  318. }
  319. }
  320. for i := 0; i < len(srcDesc.Nics); i++ {
  321. var numQueues, vectors int
  322. for j := 0; j < len(s.SourceDesc.Nics); j++ {
  323. if srcDesc.Nics[i].Index == s.SourceDesc.Nics[j].Index {
  324. numQueues = srcDesc.Nics[i].NumQueues
  325. if srcDesc.Nics[i].Vectors != nil {
  326. vectors = *srcDesc.Nics[i].Vectors
  327. }
  328. srcDesc.Nics[i].GuestnetworkJsonDesc = s.SourceDesc.Nics[j].GuestnetworkJsonDesc
  329. break
  330. }
  331. }
  332. if err := s.generateNicScripts(srcDesc.Nics[i]); err != nil {
  333. return errors.Wrapf(err, "generateNicScripts for nic: %v", srcDesc.Nics[i])
  334. }
  335. srcDesc.Nics[i].NumQueues = numQueues
  336. if vectors > 0 {
  337. srcDesc.Nics[i].Vectors = &vectors
  338. }
  339. srcDesc.Nics[i].UpscriptPath = s.getNicUpScriptPath(srcDesc.Nics[i])
  340. srcDesc.Nics[i].DownscriptPath = s.getNicDownScriptPath(srcDesc.Nics[i])
  341. }
  342. var cpuNumaPin []*desc.SCpuNumaPin
  343. if len(s.Desc.CpuNumaPin) > 0 {
  344. // cpu numa pin allocated by controller
  345. cpuNumaPin = s.Desc.CpuNumaPin
  346. } else {
  347. // allocate cpu numa pin local
  348. nodeNumaCpus, err := s.manager.cpuSet.AllocCpusetWithNodeCount(int(srcDesc.Cpu), srcDesc.Mem*1024, srcDesc.MemDesc.GuestNumaNodeCount(), s.GetId())
  349. if err != nil {
  350. return errors.Wrap(err, "AllocCpusetWithNodeCount")
  351. }
  352. var cpus = make([]int, 0)
  353. cpuNumaPin = make([]*desc.SCpuNumaPin, 0)
  354. for nodeId, numaCpus := range nodeNumaCpus {
  355. if s.manager.hostagentNumaAllocate {
  356. unodeId := uint16(nodeId)
  357. vcpuPin := make([]desc.SVCpuPin, len(numaCpus.Cpuset))
  358. for i := range numaCpus.Cpuset {
  359. vcpuPin[i].Pcpu = numaCpus.Cpuset[i]
  360. }
  361. memPin := &desc.SCpuNumaPin{
  362. SizeMB: numaCpus.MemSizeKB / 1024, // MB
  363. NodeId: &unodeId,
  364. VcpuPin: vcpuPin,
  365. Unregular: numaCpus.Unregular,
  366. }
  367. cpuNumaPin = append(cpuNumaPin, memPin)
  368. }
  369. cpus = append(cpus, numaCpus.Cpuset...)
  370. }
  371. if s.manager.hostagentNumaAllocate {
  372. // reset origin cpu numa pin
  373. srcDesc.VcpuPin = nil
  374. srcDesc.CpuNumaPin = nil
  375. } else {
  376. // if host not enable cpu numa pin
  377. if scpuset, ok := srcDesc.Metadata[api.VM_METADATA_CGROUP_CPUSET]; ok {
  378. s.manager.cpuSet.Lock.Lock()
  379. s.manager.cpuSet.ReleaseCpus(cpus, int(srcDesc.Cpu))
  380. s.manager.cpuSet.Lock.Unlock()
  381. cpusetJson, err := jsonutils.ParseString(scpuset)
  382. if err != nil {
  383. log.Errorf("failed parse server %s cpuset %s: %s", s.Id, scpuset, err)
  384. return errors.Errorf("failed parse server %s cpuset %s: %s", s.Id, scpuset, err)
  385. }
  386. input := new(api.ServerCPUSetInput)
  387. err = cpusetJson.Unmarshal(input)
  388. if err != nil {
  389. log.Errorf("failed unmarshal server %s cpuset %s", s.Id, err)
  390. return errors.Errorf("failed unmarshal server %s cpuset %s", s.Id, err)
  391. }
  392. cpus = input.CPUS
  393. }
  394. srcDesc.VcpuPin = []desc.SCpuPin{
  395. {
  396. Vcpus: fmt.Sprintf("0-%d", srcDesc.Cpu-1),
  397. Pcpus: cpuset.NewCPUSet(cpus...).String(),
  398. },
  399. }
  400. for i := range srcDesc.CpuNumaPin {
  401. srcDesc.CpuNumaPin[i].Unregular = true
  402. }
  403. }
  404. }
  405. if len(cpuNumaPin) > 0 {
  406. if srcDesc.MemDesc.Mem != nil {
  407. srcDesc.MemDesc.Mem.SMemDesc.SetHostNodes(int(*cpuNumaPin[0].NodeId))
  408. for i := range srcDesc.MemDesc.Mem.Mems {
  409. srcDesc.MemDesc.Mem.Mems[i].SetHostNodes(int(*cpuNumaPin[i+1].NodeId))
  410. }
  411. }
  412. srcDesc.CpuNumaPin = cpuNumaPin
  413. } else {
  414. if srcDesc.MemDesc.Mem != nil {
  415. srcDesc.MemDesc.Mem.SMemDesc.SetHostNodes(-1)
  416. for i := range srcDesc.MemDesc.Mem.Mems {
  417. srcDesc.MemDesc.Mem.Mems[i].SetHostNodes(-1)
  418. }
  419. }
  420. }
  421. s.Desc = srcDesc
  422. err := s.loadGuestPciAddresses()
  423. if err != nil {
  424. return errors.Wrap(err, "initLiveDescFromSourceGuest")
  425. }
  426. return SaveLiveDesc(s, srcDesc)
  427. }
  428. func (s *SKVMGuestInstance) IsStopping() bool {
  429. return s.stopping
  430. }
  431. func (s *SKVMGuestInstance) getStateFilePathRootPrefix() string {
  432. return path.Join(s.HomeDir(), STATE_FILE_PREFIX)
  433. }
  434. func (s *SKVMGuestInstance) GetStateFilePath(version string) string {
  435. p := s.getStateFilePathRootPrefix()
  436. if version != "" {
  437. p = fmt.Sprintf("%s_%s", p, version)
  438. }
  439. return p
  440. }
  441. func (s *SKVMGuestInstance) getKickstartTmpDir() string {
  442. return path.Join(s.HomeDir(), "kickstart")
  443. }
  444. func (s *SKVMGuestInstance) getQemuLogPath() string {
  445. return path.Join(s.HomeDir(), "qemu.log")
  446. }
  447. func (s *SKVMGuestInstance) generateScreenDumpPath() string {
  448. return path.Join(s.HomeDir(), fmt.Sprintf("%s.%d", s.GetId(), time.Now().Unix()))
  449. }
  450. func (s *SKVMGuestInstance) RecycleDir() string {
  451. return path.Join(s.manager.ServersPath, "recycle")
  452. }
  453. func (s *SKVMGuestInstance) GetPidFilePath() string {
  454. return path.Join(s.HomeDir(), "pid")
  455. }
  456. func (s *SKVMGuestInstance) GetVncFilePath() string {
  457. return path.Join(s.HomeDir(), "vnc")
  458. }
  459. func (s *SKVMGuestInstance) getEncryptKeyPath() string {
  460. return path.Join(s.HomeDir(), "key")
  461. }
  462. func (s *SKVMGuestInstance) getEncryptKeyId() string {
  463. return s.Desc.EncryptKeyId
  464. }
  465. func (s *SKVMGuestInstance) isEncrypted() bool {
  466. return len(s.getEncryptKeyId()) > 0
  467. }
  468. func (s *SKVMGuestInstance) getEncryptKey(ctx context.Context, userCred mcclient.TokenCredential) (apis.SEncryptInfo, error) {
  469. ret := apis.SEncryptInfo{}
  470. encKeyId := s.getEncryptKeyId()
  471. if len(encKeyId) > 0 {
  472. if userCred == nil {
  473. return ret, errors.Wrap(httperrors.ErrUnauthorized, "no credential to fetch encrypt key")
  474. }
  475. session := auth.GetSession(ctx, userCred, consts.GetRegion())
  476. secKey, err := identity_modules.Credentials.GetEncryptKey(session, encKeyId)
  477. if err != nil {
  478. return ret, errors.Wrap(err, "GetEncryptKey")
  479. }
  480. ret.Id = secKey.KeyId
  481. ret.Name = secKey.KeyName
  482. ret.Key = secKey.Key
  483. ret.Alg = secKey.Alg
  484. return ret, nil
  485. }
  486. return ret, nil
  487. }
  488. func (s *SKVMGuestInstance) saveEncryptKeyFile(key string) error {
  489. return fileutils2.FilePutContents(s.getEncryptKeyPath(), key, false)
  490. }
  491. func (s *SKVMGuestInstance) getOriginId() string {
  492. if s.Desc == nil {
  493. return ""
  494. }
  495. return s.Desc.Metadata["__origin_id"]
  496. }
  497. func (s *SKVMGuestInstance) isImportFromLibvirt() bool {
  498. return s.getOriginId() != ""
  499. }
  500. func (s *SKVMGuestInstance) GetPid() int {
  501. return s.getPid(s.GetPidFilePath(), s.getOriginId())
  502. }
  503. /*
  504. pid -> running qemu's pid
  505. -1 -> pid file does not exists
  506. -2 -> pid file ok but content does not match any qemu process
  507. */
  508. func (s *SKVMGuestInstance) getPid(pidFile, uuid string) int {
  509. if !fileutils2.Exists(pidFile) {
  510. return -1
  511. }
  512. pidStr, err := fileutils2.FileGetContents(pidFile)
  513. if err != nil {
  514. log.Errorf("Get pid file %s error %s: %s", pidFile, s.GetName(), err)
  515. return -2
  516. }
  517. pidStr = strings.TrimSpace(pidStr)
  518. pid := s.findPid(strings.Split(pidStr, "\n"), uuid)
  519. if len(pid) > 0 && regutils.MatchInteger(pid) {
  520. v, _ := strconv.ParseInt(pid, 10, 0)
  521. return int(v)
  522. }
  523. return -2
  524. }
  525. func (s *SKVMGuestInstance) findPid(pids []string, uuid string) string {
  526. if len(pids) == 0 {
  527. return ""
  528. }
  529. for _, pid := range pids {
  530. pid := strings.TrimSpace(pid)
  531. if s.isSelfQemuPid(pid, uuid) {
  532. return pid
  533. }
  534. }
  535. return ""
  536. }
  537. func (s *SKVMGuestInstance) isSelfQemuPid(pid, uuid string) bool {
  538. if len(pid) == 0 {
  539. return false
  540. }
  541. cmdlineFile := fmt.Sprintf("/proc/%s/cmdline", pid)
  542. fi, err := os.Stat(cmdlineFile)
  543. if err != nil {
  544. return false
  545. }
  546. if !fi.Mode().IsRegular() {
  547. return false
  548. }
  549. cmdline, err := ioutil.ReadFile(cmdlineFile)
  550. if err != nil {
  551. log.Warningf("IsSelfQemuPid Read File %s error %s", cmdlineFile, err)
  552. return false
  553. }
  554. return s.isSelfCmdline(string(cmdline), uuid)
  555. }
  556. func (s *SKVMGuestInstance) isSelfCmdline(cmdline, uuid string) bool {
  557. return (strings.Index(cmdline, "qemu-system") >= 0 ||
  558. strings.Index(cmdline, "qemu-kvm") >= 0) &&
  559. strings.Index(cmdline, uuid) >= 0
  560. }
  561. func (s *SKVMGuestInstance) GetRescueDirPath() string {
  562. if s.manager.host.IsAarch64() {
  563. return path.Join("/opt/cloud/host-deployer/yunionos/aarch64")
  564. } else if s.manager.host.IsRiscv64() {
  565. return path.Join("/opt/cloud/host-deployer/yunionos/riscv64")
  566. } else {
  567. return path.Join("/opt/cloud/host-deployer/yunionos/x86_64")
  568. }
  569. }
  570. func (s *SKVMGuestInstance) LoadDesc() error {
  571. if err := LoadDesc(s); err != nil {
  572. return errors.Wrap(err, "LoadDesc")
  573. }
  574. if s.IsRunning() {
  575. if len(s.Desc.PCIControllers) > 0 {
  576. if err := s.loadGuestPciAddresses(); err != nil {
  577. log.Errorf("failed load guest %s pci addresses %s", s.GetName(), err)
  578. if len(s.Desc.AnonymousPCIDevs) > 0 {
  579. s.Desc = s.SourceDesc
  580. s.pciUninitialized = true
  581. } else {
  582. return err
  583. }
  584. }
  585. } else {
  586. s.pciUninitialized = true
  587. }
  588. }
  589. return nil
  590. }
  591. func (s *SKVMGuestInstance) PostLoad(m *SGuestManager) error {
  592. if s.needSyncStreamDisks {
  593. go s.sendStreamDisksComplete(context.Background())
  594. }
  595. return LoadGuestCpuset(m, s)
  596. }
  597. func (s *SKVMGuestInstance) IsDirtyShotdown() bool {
  598. return s.GetPid() == -2
  599. }
  600. func (s *SKVMGuestInstance) DirtyServerRequestStart() {
  601. var body = jsonutils.NewDict()
  602. body.Set("guest_id", jsonutils.NewString(s.Id))
  603. body.Set("host_id", jsonutils.NewString(s.Desc.HostId))
  604. _, err := modules.Servers.PerformClassAction(
  605. hostutils.GetComputeSession(context.Background()), "dirty-server-start", body)
  606. if err != nil {
  607. log.Errorf("Dirty server request start error %s: %s", s.GetName(), err)
  608. }
  609. }
  610. func (s *SKVMGuestInstance) fuseMount(encryptInfo *apis.SEncryptInfo) error {
  611. disks := s.Desc.Disks
  612. for i := 0; i < len(disks); i++ {
  613. if disks[i].MergeSnapshot && len(disks[i].Url) > 0 {
  614. disk, err := storageman.GetManager().GetDiskByPath(disks[i].Path)
  615. if err != nil {
  616. return errors.Wrapf(err, "GetDiskByPath(%s)", disks[i].Path)
  617. }
  618. storage := disk.GetStorage()
  619. mntPath := path.Join(storage.GetFuseMountPath(), disk.GetId())
  620. if err := procutils.NewCommand("mountpoint", mntPath).Run(); err == nil {
  621. // fetcherfs is mounted
  622. continue
  623. }
  624. tmpdir := storage.GetFuseTmpPath()
  625. err = fuseutils.MountFusefs(
  626. options.HostOptions.FetcherfsPath, disks[i].Url, tmpdir,
  627. auth.GetTokenString(), mntPath,
  628. options.HostOptions.FetcherfsBlockSize,
  629. encryptInfo,
  630. )
  631. if err != nil {
  632. return err
  633. }
  634. }
  635. }
  636. return nil
  637. }
  638. func (s *SKVMGuestInstance) asyncScriptStart(ctx context.Context, params interface{}) (jsonutils.JSONObject, error) {
  639. data, ok := params.(*jsonutils.JSONDict)
  640. if !ok {
  641. return nil, hostutils.ParamsError
  642. }
  643. var err error
  644. var encryptInfo *apis.SEncryptInfo
  645. if data.Contains("encrypt_info") {
  646. encryptInfo = new(apis.SEncryptInfo)
  647. data.Unmarshal(encryptInfo, "encrypt_info")
  648. }
  649. //err = s.fuseMount(encryptInfo)
  650. //if err != nil {
  651. // return nil, errors.Wrap(err, "fuse mount")
  652. //}
  653. var vcpuOrder = make([][]int, 0)
  654. isMigrate := jsonutils.QueryBoolean(data, "need_migrate", false)
  655. if isMigrate {
  656. var sourceDesc = new(desc.SGuestDesc)
  657. err = data.Unmarshal(sourceDesc, "src_desc")
  658. if err != nil {
  659. return nil, errors.Wrap(err, "unmarshal src desc")
  660. }
  661. for i := range sourceDesc.CpuNumaPin {
  662. vcpus := make([]int, 0)
  663. for j := range sourceDesc.CpuNumaPin[i].VcpuPin {
  664. vcpus = append(vcpus, sourceDesc.CpuNumaPin[i].VcpuPin[j].Vcpu)
  665. }
  666. vcpuOrder = append(vcpuOrder, vcpus)
  667. }
  668. err = s.initLiveDescFromSourceGuest(sourceDesc)
  669. } else {
  670. err = s.updateGuestDesc()
  671. }
  672. // init live migrate listen port
  673. if isMigrate || s.Desc.IsSlave {
  674. migratePort := s.manager.GetLiveMigrateFreePort()
  675. defer s.manager.unsetPort(migratePort)
  676. migratePortInt64 := int64(migratePort)
  677. s.LiveMigrateDestPort = &migratePortInt64
  678. log.Infof("backup guest alloc dest port %v", s.LiveMigrateDestPort)
  679. }
  680. if err != nil {
  681. if ctx != nil && len(appctx.AppContextTaskId(ctx)) >= 0 {
  682. hostutils.TaskFailed(ctx, fmt.Sprintf("Async start server failed: %s", err))
  683. }
  684. return nil, errors.Wrap(err, "asyncScriptStart init desc")
  685. }
  686. hostbridge.CleanDeletedPorts(options.HostOptions.BridgeDriver)
  687. time.Sleep(100 * time.Millisecond)
  688. var isStarted, tried = false, 0
  689. for !isStarted && tried < MAX_TRY {
  690. tried += 1
  691. vncPort := s.manager.GetFreeVncPort()
  692. defer s.manager.unsetPort(vncPort)
  693. log.Infof("Use vnc port %d", vncPort)
  694. if err = s.saveVncPort(vncPort); err != nil {
  695. goto finally
  696. } else {
  697. data.Set("vnc_port", jsonutils.NewInt(int64(vncPort)))
  698. }
  699. if tried > 1 && s.manager.hostagentNumaAllocate {
  700. if err = s.reallocateNumaNodes(isMigrate); err != nil {
  701. log.Errorf("failed fix numa allocated mems %s", err)
  702. goto finally
  703. }
  704. }
  705. err = s.saveScripts(data)
  706. if err != nil {
  707. goto finally
  708. } else {
  709. err = s.scriptStart(ctx)
  710. if err == nil {
  711. isStarted = true
  712. } else {
  713. // call script stop if guest start failed
  714. s.scriptStop()
  715. }
  716. }
  717. finally:
  718. if !isStarted {
  719. log.Errorf("Start VM failed %s: %s", s.GetName(), err)
  720. time.Sleep(time.Duration(1<<uint(tried-1)) * time.Second)
  721. } else {
  722. if s.manager.hostagentNumaAllocate {
  723. if err = s.validateNumaAllocated(s.Desc.Uuid, isMigrate, false, vcpuOrder); err != nil {
  724. log.Errorf("VM %s validateNumaAllocated: %s", s.GetName(), err)
  725. isStarted = false
  726. s.scriptStop()
  727. continue
  728. }
  729. }
  730. log.Infof("VM started %s ...", s.GetName())
  731. }
  732. }
  733. // is on_async_script_start
  734. if isStarted {
  735. log.Infof("Async start server %s success!", s.GetName())
  736. s.syncMeta = s.CleanImportMetadata()
  737. return nil, nil
  738. }
  739. // release guest acquired cpu mems on guest start failed
  740. ReleaseGuestCpuset(s.manager, s)
  741. log.Errorf("Async start server %s failed: %s!!!", s.GetName(), err)
  742. if ctx != nil && len(appctx.AppContextTaskId(ctx)) >= 0 {
  743. hostutils.TaskFailed(ctx, fmt.Sprintf("Async start server failed: %s", err))
  744. }
  745. //needMigrate := jsonutils.QueryBoolean(data, "need_migrate", false)
  746. //// do not syncstatus if need_migrate
  747. //if !needMigrate {
  748. // s.SyncStatus("")
  749. //}
  750. return nil, err
  751. }
  752. func (s *SKVMGuestInstance) saveScripts(data *jsonutils.JSONDict) error {
  753. startScript, err := s.generateStartScript(data)
  754. if err != nil {
  755. return err
  756. }
  757. if err = fileutils2.FilePutContents(s.GetStartScriptPath(), startScript, false); err != nil {
  758. return err
  759. }
  760. if jsonutils.QueryBoolean(data, "sync_qemu_cmdline", false) {
  761. cmdline, err := s.getQemuCmdlineFromContent(startScript)
  762. if err != nil {
  763. log.Errorf("failed parse cmdline from start script: %s", err)
  764. } else {
  765. s.SyncQemuCmdline(cmdline)
  766. }
  767. }
  768. launcher := fmt.Sprintf(guestLauncher, s.GetStartScriptPath(), s.GetStateFilePath(""), s.LogFilePath())
  769. if err := fileutils2.FilePutContents(s.pyLauncherPath(), launcher, false); err != nil {
  770. return errors.Wrap(err, "generate guest launcher")
  771. }
  772. stopScript := s.generateStopScript(data)
  773. return fileutils2.FilePutContents(s.GetStopScriptPath(), stopScript, false)
  774. }
  775. func (s *SKVMGuestInstance) GetStartScriptPath() string {
  776. return path.Join(s.HomeDir(), "startvm")
  777. }
  778. func (s *SKVMGuestInstance) GetStopScriptPath() string {
  779. return path.Join(s.HomeDir(), "stopvm")
  780. }
  781. func (s *SKVMGuestInstance) ImportServer(pendingDelete bool) {
  782. // verify host_id consistency
  783. if s.Desc.HostId != hostinfo.Instance().HostId {
  784. // fix host_id
  785. s.Desc.HostId = hostinfo.Instance().HostId
  786. SaveLiveDesc(s, s.Desc)
  787. }
  788. s.manager.SaveServer(s.Id, s)
  789. s.manager.RemoveCandidateServer(s)
  790. if s.IsDirtyShotdown() && !pendingDelete {
  791. log.Infof("Server dirty shutdown or a daemon %s", s.GetName())
  792. if len(s.GetNeedMergeBackingFileDiskIndexs()) > 0 {
  793. go s.DirtyServerRequestStart()
  794. } else if s.Desc.IsMaster {
  795. go s.SyncStatus("Server dirty shutdown")
  796. } else if s.Desc.IsSlave {
  797. go s.DirtyServerRequestStart()
  798. } else {
  799. s.StartGuest(context.Background(), auth.AdminCredential(), jsonutils.NewDict())
  800. }
  801. return
  802. }
  803. if s.IsRunning() {
  804. log.Infof("%s is running, pending_delete=%t", s.GetName(), pendingDelete)
  805. if !pendingDelete {
  806. s.StartMonitor(context.Background(), nil, false)
  807. }
  808. } else if s.IsDaemon() {
  809. s.StartGuest(context.Background(), nil, jsonutils.NewDict())
  810. } else {
  811. var action = "stopped"
  812. if s.IsSuspend() {
  813. action = "suspend"
  814. }
  815. log.Infof("%s is %s, pending_delete=%t", s.GetName(), action, pendingDelete)
  816. s.SyncStatus("")
  817. }
  818. }
  819. func (s *SKVMGuestInstance) IsRunning() bool {
  820. return s.GetPid() > 0
  821. }
  822. func (s *SKVMGuestInstance) IsStopped() bool {
  823. return !s.IsRunning()
  824. }
  825. func (s *SKVMGuestInstance) IsSuspend() bool {
  826. if !s.IsRunning() && len(s.ListStateFilePaths()) > 0 {
  827. return true
  828. }
  829. return false
  830. }
  831. func (s *SKVMGuestInstance) IsMonitorAlive() bool {
  832. return s.Monitor != nil && s.Monitor.IsConnected()
  833. }
  834. // func (s *SKVMGuestInstance) ListStateFilePaths() []string {
  835. // files, err := ioutil.ReadDir(s.HomeDir())
  836. // if err == nil {
  837. // var ret = make([]string, 0)
  838. // for i := 0; i < len(files); i++ {
  839. // if strings.HasPrefix(files[i].Name(), STATE_FILE_PREFIX) {
  840. // ret = append(ret, files[i].Name())
  841. // }
  842. // }
  843. // return ret
  844. // }
  845. // return nil
  846. // }
  847. func (s *SKVMGuestInstance) onImportGuestMonitorDisConnect(err error) {
  848. log.Infof("Import Guest %s monitor disconnect reason: %v", s.Id, err)
  849. s.SyncStatus(fmt.Sprintf("import guest monitor disconnect %v", err))
  850. // clean import pid file
  851. if s.GetPid() == -2 {
  852. spath := s.GetPidFilePath()
  853. if fileutils2.Exists(spath) {
  854. os.Remove(spath)
  855. }
  856. }
  857. }
  858. func (s *SKVMGuestInstance) onImportGuestMonitorTimeout(ctx context.Context, err error) {
  859. log.Errorf("Import guest %s monitor connect timeout: %s", s.Id, err)
  860. // clean import pid file
  861. if s.GetPid() == -2 {
  862. spath := s.GetPidFilePath()
  863. if fileutils2.Exists(spath) {
  864. os.Remove(spath)
  865. }
  866. }
  867. }
  868. func (s *SKVMGuestInstance) onImportGuestMonitorConnected(ctx context.Context) {
  869. log.Infof("Guest %s Monitor connect success", s.Id)
  870. s.Monitor.GetVersion(func(version string) {
  871. log.Infof("Guest %s qemu version %s", s.Id, version)
  872. s.QemuVersion = version
  873. meta := jsonutils.NewDict()
  874. meta.Set(api.VM_METADATA_HOTPLUG_CPU_MEM, jsonutils.NewString("disable"))
  875. meta.Set(api.VM_METADATA_HOT_REMOVE_NIC, jsonutils.NewString("disable"))
  876. meta.Set("__qemu_version", jsonutils.NewString(s.GetQemuVersionStr()))
  877. s.SyncMetadata(meta)
  878. s.SyncStatus("")
  879. })
  880. }
  881. func (s *SKVMGuestInstance) GetMonitorPath() string {
  882. return s.Desc.Metadata["__monitor_path"]
  883. }
  884. func (s *SKVMGuestInstance) StartMonitorWithImportGuestSocketFile(ctx context.Context, socketFile string, cb func()) error {
  885. var mon monitor.Monitor
  886. mon = monitor.NewQmpMonitor(
  887. s.GetName(),
  888. s.Id,
  889. s.onImportGuestMonitorDisConnect, // on monitor disconnect
  890. func(err error) { s.onImportGuestMonitorTimeout(ctx, err) }, // on monitor timeout
  891. func() {
  892. s.Monitor = mon
  893. s.onImportGuestMonitorConnected(ctx)
  894. if cb != nil {
  895. cb()
  896. }
  897. }, // on monitor connected
  898. s.onReceiveQMPEvent, // on reveive qmp event
  899. )
  900. return mon.ConnectWithSocket(socketFile, 0)
  901. }
  902. func (s *SKVMGuestInstance) StartMonitor(ctx context.Context, cb func(), isScriptStart bool) error {
  903. if s.GetQmpMonitorPort(-1) > 0 {
  904. var mon monitor.Monitor
  905. var onMonitorTimeout = func(err error) {
  906. if isScriptStart {
  907. if ctx != nil && len(appctx.AppContextTaskId(ctx)) >= 0 {
  908. hostutils.TaskFailed(ctx, fmt.Sprintf("Async start server failed: %s", err))
  909. }
  910. s.forceScriptStop()
  911. } else {
  912. s.onMonitorTimeout(ctx, err)
  913. }
  914. }
  915. var onMonitorConnected = func() {
  916. s.Monitor = mon
  917. s.onMonitorConnected(ctx)
  918. if cb != nil {
  919. cb()
  920. }
  921. }
  922. mon = monitor.NewQmpMonitor(
  923. s.GetName(), s.Id,
  924. s.onMonitorDisConnect, // on monitor disconnect
  925. onMonitorTimeout, // on monitor timeout
  926. onMonitorConnected, // on monitor connected
  927. s.onReceiveQMPEvent, // on receive qmp event
  928. )
  929. err := mon.Connect("127.0.0.1", s.GetQmpMonitorPort(-1))
  930. if err != nil {
  931. mon = nil
  932. log.Errorf("Guest %s qmp monitor connect failed %s, something wrong", s.GetName(), err)
  933. return errors.Errorf("connect qmp monitor: %s", err)
  934. }
  935. return nil
  936. } else if monitorPath := s.GetMonitorPath(); len(monitorPath) > 0 {
  937. return s.StartMonitorWithImportGuestSocketFile(ctx, monitorPath, cb)
  938. } else {
  939. log.Warningf("Guest %s start monitor failed, can't get qmp monitor port or monitor path", s.Id)
  940. return errors.Errorf("Guest %s start monitor failed, can't get qmp monitor port or monitor path", s.Id)
  941. }
  942. }
  943. func (s *SKVMGuestInstance) onReceiveQMPEvent(event *monitor.Event) {
  944. switch event.Event {
  945. case `"BLOCK_JOB_READY"`, `"BLOCK_JOB_COMPLETED"`:
  946. s.eventBlockJobReady(event)
  947. case `"BLOCK_JOB_ERROR"`:
  948. s.eventBlockJobError(event)
  949. case `"GUEST_PANICKED"`:
  950. s.eventGuestPaniced(event)
  951. case `"STOP"`:
  952. s.eventGuestStop()
  953. case `"QUORUM_REPORT_BAD"`:
  954. s.eventQuorumReportBad(event)
  955. case `"MIGRATION"`:
  956. s.eventMigration(event)
  957. }
  958. }
  959. func (s *SKVMGuestInstance) eventMigration(event *monitor.Event) {
  960. if s.MigrateTask == nil {
  961. return
  962. }
  963. status, ok := event.Data["status"]
  964. if !ok {
  965. return
  966. }
  967. if status == "pre-switchover" {
  968. // migrating complete
  969. s.MigrateTask.onMigrateReceivedPreSwitchoverEvent()
  970. hostutils.UpdateServerProgress(context.Background(), s.Id, 0.0, 0)
  971. } else if status == "completed" {
  972. s.MigrateTask.migrateComplete(nil)
  973. }
  974. }
  975. func (s *SKVMGuestInstance) eventBlockJobError(event *monitor.Event) {
  976. if s.MigrateTask != nil {
  977. s.MigrateTask.onMigrateReceivedBlockJobError(event.String())
  978. } else {
  979. s.SyncMirrorJobFailed(event.String())
  980. }
  981. }
  982. func (s *SKVMGuestInstance) eventGuestStop() {
  983. // do nothing
  984. }
  985. func (s *SKVMGuestInstance) eventQuorumReportBad(event *monitor.Event) {
  986. if !atomic.CompareAndSwapInt32(&s.quorumFailed, 0, 1) {
  987. return
  988. }
  989. disks := s.Desc.Disks
  990. for i := 0; i < len(disks); i++ {
  991. diskIndex := disks[i].Index
  992. drive := fmt.Sprintf("drive_%d", diskIndex)
  993. node := fmt.Sprintf("node_%d", diskIndex)
  994. child := fmt.Sprintf("children.%d", s.getQuorumChildIndex())
  995. s.Monitor.XBlockdevChange(drive, "", child, func(res string) {
  996. if len(res) > 0 {
  997. log.Errorf("On QUORUM_REPORT_BAD failed remove child %s for parent %s: %s", drive, node, res)
  998. return
  999. }
  1000. s.Monitor.DriveDel(node, func(res string) {
  1001. if len(res) > 0 {
  1002. log.Errorf("On QUORUM_REPORT_BAD failed remove drive %s: %s", node, res)
  1003. return
  1004. }
  1005. })
  1006. })
  1007. }
  1008. s.SyncMirrorJobFailed(event.String())
  1009. }
  1010. func (s *SKVMGuestInstance) eventGuestPaniced(event *monitor.Event) {
  1011. // qemu runc state event source qemu/src/qapi/run-state.json
  1012. params := jsonutils.NewDict()
  1013. if action, ok := event.Data["action"]; ok {
  1014. sAction, _ := action.(string)
  1015. params.Set("action", jsonutils.NewString(sAction))
  1016. }
  1017. if info, ok := event.Data["info"]; ok {
  1018. params.Set("info", jsonutils.Marshal(info))
  1019. }
  1020. screenDumpPath := s.generateScreenDumpPath()
  1021. screenDumpName := filepath.Base(screenDumpPath)
  1022. c := make(chan struct{})
  1023. s.Monitor.ScreenDump(screenDumpPath, func(res string) {
  1024. log.Infof("qmp screendump res %s", res)
  1025. if fileutils2.Exists(screenDumpPath) {
  1026. log.Infof("screendump success at %s", screenDumpPath)
  1027. _, err := s3.Put(context.Background(), screenDumpPath, screenDumpName, 50, 4, nil)
  1028. if err != nil {
  1029. log.Errorf("faild put screenDumpPath %s to s3 %s", screenDumpPath, err)
  1030. } else {
  1031. screenDumpInfo := api.SGuestScreenDumpInfo{
  1032. S3AccessKey: options.HostOptions.S3AccessKey,
  1033. S3SecretKey: options.HostOptions.S3SecretKey,
  1034. S3Endpoint: options.HostOptions.S3Endpoint,
  1035. S3BucketName: options.HostOptions.S3BucketName,
  1036. S3ObjectName: screenDumpName,
  1037. S3UseSSL: options.HostOptions.S3UseSSL,
  1038. }
  1039. params.Set("screen_dump_info", jsonutils.Marshal(screenDumpInfo))
  1040. log.Infof("put screendump %s success", screenDumpName)
  1041. os.Remove(screenDumpPath)
  1042. }
  1043. }
  1044. c <- struct{}{}
  1045. })
  1046. // wait screen dump
  1047. select {
  1048. case <-time.After(time.Second * 5):
  1049. log.Errorf("ScreenDump no response after 5 seconds")
  1050. case <-c:
  1051. break
  1052. }
  1053. params.Set("event", jsonutils.NewString(strings.Trim(event.Event, "\"")))
  1054. _, err := modules.Servers.PerformAction(
  1055. hostutils.GetComputeSession(context.Background()),
  1056. s.GetId(), "event", params)
  1057. if err != nil {
  1058. log.Errorf("Server %s send event guest paniced got error %s", s.GetId(), err)
  1059. }
  1060. }
  1061. func (s *SKVMGuestInstance) eventBlockJobReady(event *monitor.Event) {
  1062. if !s.IsSlave() {
  1063. return
  1064. }
  1065. itype, ok := event.Data["type"]
  1066. if !ok {
  1067. log.Errorf("block job missing event type")
  1068. return
  1069. }
  1070. stype, _ := itype.(string)
  1071. if stype != "mirror" && stype != "stream" {
  1072. return
  1073. }
  1074. iDevice, ok := event.Data["device"]
  1075. if !ok {
  1076. return
  1077. }
  1078. device := iDevice.(string)
  1079. if !strings.HasPrefix(device, "drive_") {
  1080. return
  1081. }
  1082. disks := s.Desc.Disks
  1083. diskIndex, err := strconv.Atoi(device[len("drive_"):])
  1084. if err != nil || diskIndex < 0 || diskIndex >= len(disks) {
  1085. log.Errorf("failed get disk from index %d", diskIndex)
  1086. return
  1087. }
  1088. var diskId, diskPath, diskUrl string
  1089. var mergeSnapshots bool
  1090. for i := 0; i < len(disks); i++ {
  1091. index := disks[i].Index
  1092. if index == int8(diskIndex) {
  1093. diskId = disks[i].DiskId
  1094. diskPath = disks[i].Path
  1095. diskUrl = disks[i].Url
  1096. mergeSnapshots = disks[i].MergeSnapshot
  1097. }
  1098. }
  1099. if len(diskId) == 0 {
  1100. log.Errorf("failed find disk %s", device)
  1101. return
  1102. }
  1103. disk, err := storageman.GetManager().GetDiskByPath(diskPath)
  1104. if err != nil {
  1105. log.Errorf("eventBlockJobReady failed get disk %s", diskPath)
  1106. return
  1107. }
  1108. if mergeSnapshots {
  1109. disk.PostCreateFromRemoteHostImage(diskUrl)
  1110. }
  1111. blockJobCount := s.BlockJobsCount()
  1112. if blockJobCount == 0 {
  1113. for {
  1114. _, err := modules.Servers.PerformAction(
  1115. hostutils.GetComputeSession(context.Background()), s.GetId(), "slave-block-stream-ready", nil,
  1116. )
  1117. if err != nil {
  1118. log.Errorf("onReceiveQMPEvent sync slave block stream ready error: %s", err)
  1119. time.Sleep(3 * time.Second)
  1120. } else {
  1121. break
  1122. }
  1123. }
  1124. }
  1125. }
  1126. func (s *SKVMGuestInstance) QgaPath() string {
  1127. return path.Join(s.HomeDir(), "qga.sock")
  1128. }
  1129. func (s *SKVMGuestInstance) InitQga() error {
  1130. guestAgent, err := qga.NewQemuGuestAgent(s.Id, s.QgaPath())
  1131. if err != nil {
  1132. return err
  1133. }
  1134. s.guestAgent = guestAgent
  1135. return nil
  1136. }
  1137. func (s *SKVMGuestInstance) SyncMirrorJobFailed(reason string) {
  1138. params := jsonutils.NewDict()
  1139. params.Set("reason", jsonutils.NewString(reason))
  1140. _, err := modules.Servers.PerformAction(
  1141. hostutils.GetComputeSession(context.Background()),
  1142. s.GetId(), "block-stream-failed", params,
  1143. )
  1144. if err != nil {
  1145. log.Errorf("Server %s perform block-stream-failed got error %s", s.GetId(), err)
  1146. }
  1147. }
  1148. func (s *SKVMGuestInstance) onMonitorConnected(ctx context.Context) {
  1149. log.Infof("Monitor connected ...")
  1150. s.Monitor.GetVersion(func(v string) {
  1151. s.onGetQemuVersion(ctx, v)
  1152. })
  1153. s.startKickstartMonitorIfNeeded()
  1154. }
  1155. func (s *SKVMGuestInstance) setDestMigrateTLS(ctx context.Context, data *jsonutils.JSONDict) {
  1156. port, _ := data.Int("live_migrate_dest_port")
  1157. s.Monitor.ObjectAdd("tls-creds-x509", map[string]string{
  1158. "dir": s.getPKIDirPath(),
  1159. "endpoint": "server",
  1160. "id": "tls0",
  1161. "verify-peer": "no",
  1162. }, func(res string) {
  1163. if strings.Contains(strings.ToLower(res), "error") {
  1164. hostutils.TaskFailed(ctx, fmt.Sprintf("Migrate add tls-creds-x509 object server tls0 error: %s", res))
  1165. return
  1166. }
  1167. s.Monitor.MigrateSetParameter("tls-creds", "tls0", func(res string) {
  1168. if strings.Contains(strings.ToLower(res), "error") {
  1169. hostutils.TaskFailed(ctx, fmt.Sprintf("Migrate set tls-creds tls0 error: %s", res))
  1170. return
  1171. }
  1172. address := fmt.Sprintf("tcp:0:%d", port)
  1173. s.Monitor.MigrateIncoming(address, func(res string) {
  1174. if strings.Contains(strings.ToLower(res), "error") {
  1175. hostutils.TaskFailed(ctx, fmt.Sprintf("Migrate set incoming %q error: %s", address, res))
  1176. return
  1177. }
  1178. hostutils.TaskComplete(ctx, data)
  1179. })
  1180. })
  1181. })
  1182. }
  1183. func (s *SKVMGuestInstance) migrateEnableMultifd() error {
  1184. // https://bugzilla.redhat.com/show_bug.cgi?id=1899442
  1185. // Migration fails if both multifd and tls are enabled
  1186. if version.LT(s.QemuVersion, "4.0.0") || s.LiveMigrateUseTls {
  1187. return nil
  1188. }
  1189. var err = make(chan error)
  1190. cb := func(res string) {
  1191. if len(res) > 0 {
  1192. err <- errors.Errorf("failed enable multifd %s", res)
  1193. } else {
  1194. err <- nil
  1195. }
  1196. }
  1197. log.Infof("migrate dest guest enable multifd")
  1198. s.Monitor.MigrateSetCapability("multifd", "on", cb)
  1199. return <-err
  1200. }
  1201. func (s *SKVMGuestInstance) migrateStartNbdServer(nbdServerPort int) error {
  1202. var err = make(chan error)
  1203. onNbdServerStarted := func(res string) {
  1204. if len(res) > 0 {
  1205. err <- errors.Errorf("failed start nbd server %s", res)
  1206. } else {
  1207. err <- nil
  1208. }
  1209. }
  1210. log.Infof("migrate dest guest start nbd server on %d", nbdServerPort)
  1211. s.Monitor.StartNbdServer(nbdServerPort, true, true, onNbdServerStarted)
  1212. return <-err
  1213. }
  1214. func (s *SKVMGuestInstance) onGetQemuVersion(ctx context.Context, version string) {
  1215. s.QemuVersion = version
  1216. log.Infof("Guest(%s) qemu version %s", s.Id, s.QemuVersion)
  1217. if s.pciUninitialized {
  1218. if err := s.collectGuestDescription(); err != nil {
  1219. log.Errorf("failed init desc from existing guest: %s", err)
  1220. s.syncStatusUnsync(fmt.Sprintf("failed init desc from existing guest: %s", err))
  1221. return
  1222. }
  1223. s.pciUninitialized = false
  1224. }
  1225. s.guestRun(ctx)
  1226. }
  1227. func (s *SKVMGuestInstance) syncStatusUnsync(reason string) {
  1228. statusInput := &apis.PerformStatusInput{
  1229. Status: api.VM_UNSYNC,
  1230. Reason: reason,
  1231. PowerStates: GetPowerStates(s),
  1232. }
  1233. if _, err := hostutils.UpdateServerStatus(context.Background(), s.Id, statusInput); err != nil {
  1234. log.Errorf("failed update guest status %s", err)
  1235. }
  1236. }
  1237. func (s *SKVMGuestInstance) collectGuestDescription() error {
  1238. var cpuList []monitor.HotpluggableCPU
  1239. var err error
  1240. if s.manager.host.IsX8664() {
  1241. cpuList, err = s.getHotpluggableCPUList()
  1242. if err != nil {
  1243. return errors.Wrap(err, "get hotpluggable cpus")
  1244. }
  1245. }
  1246. pciInfoList, err := s.getPciDevices()
  1247. if err != nil {
  1248. return errors.Wrap(err, "get pci devices")
  1249. }
  1250. memoryDevicesInfoList, err := s.getMemoryDevices()
  1251. if err != nil {
  1252. return errors.Wrap(err, "get memory devices")
  1253. }
  1254. memDevs, err := s.getMemoryDevs()
  1255. if err != nil {
  1256. return errors.Wrap(err, "query mem devs")
  1257. }
  1258. if s.Desc.Machine == "" {
  1259. s.Desc.Machine = s.getMachine()
  1260. }
  1261. qtree := s.infoQtree()
  1262. scsiNumQueues := s.getScsiNumQueues(qtree)
  1263. for i := range s.Desc.Disks {
  1264. // fix virtio disk driver num-queues
  1265. if s.Desc.Disks[i].Driver == "virtio" {
  1266. diskDriver := fmt.Sprintf("drive_%d", s.Desc.Disks[i].Index)
  1267. numQueues := s.getDiskDriverNumQueues(qtree, diskDriver)
  1268. log.Infof("disk driver %s num queues %d", diskDriver, numQueues)
  1269. if numQueues > 0 {
  1270. s.Desc.Disks[i].NumQueues = uint8(numQueues)
  1271. }
  1272. }
  1273. }
  1274. err = s.initGuestDescFromExistingGuest(
  1275. cpuList, pciInfoList, memoryDevicesInfoList, memDevs, scsiNumQueues, qtree)
  1276. if err != nil {
  1277. return errors.Wrap(err, "failed init guest devices")
  1278. }
  1279. if err := SaveLiveDesc(s, s.Desc); err != nil {
  1280. return errors.Wrap(err, "failed save live desc")
  1281. }
  1282. return nil
  1283. }
  1284. func (s *SKVMGuestInstance) syncVirtioDiskNumQueues() error {
  1285. qtree := s.infoQtree()
  1286. for i := range s.Desc.Disks {
  1287. // fix virtio disk driver num-queues
  1288. if s.Desc.Disks[i].Driver == "virtio" {
  1289. diskDriver := fmt.Sprintf("drive_%d", s.Desc.Disks[i].Index)
  1290. numQueues := s.getDiskDriverNumQueues(qtree, diskDriver)
  1291. log.Infof("disk driver %s num queues %d", diskDriver, numQueues)
  1292. if numQueues > 0 {
  1293. s.Desc.Disks[i].NumQueues = uint8(numQueues)
  1294. }
  1295. }
  1296. }
  1297. return SaveLiveDesc(s, s.Desc)
  1298. }
  1299. func (s *SKVMGuestInstance) getHotpluggableCPUList() ([]monitor.HotpluggableCPU, error) {
  1300. var res []monitor.HotpluggableCPU
  1301. var errChan = make(chan error)
  1302. cb := func(cpuList []monitor.HotpluggableCPU, err string) {
  1303. if err != "" {
  1304. errChan <- errors.Errorf("%s", err)
  1305. } else {
  1306. res = cpuList
  1307. errChan <- nil
  1308. }
  1309. }
  1310. s.Monitor.GetHotPluggableCpus(cb)
  1311. err := <-errChan
  1312. return res, err
  1313. }
  1314. func (s *SKVMGuestInstance) infoQtree() string {
  1315. var qtreeChan = make(chan string)
  1316. cb := func(qtree string) {
  1317. qtreeChan <- qtree
  1318. }
  1319. s.Monitor.InfoQtree(cb)
  1320. return <-qtreeChan
  1321. }
  1322. func getScsiNumQueuesQmp(output string) int64 {
  1323. // if output is response from hmp, sep should use \r\n
  1324. var lines = strings.Split(strings.TrimSuffix(output, "\r\n"), "\\r\\n")
  1325. for i, line := range lines {
  1326. line := strings.TrimSpace(line)
  1327. if strings.HasPrefix(line, "dev: virtio-scsi-device") {
  1328. if len(lines) <= i+1 {
  1329. log.Errorf("failed parse num queues")
  1330. return -1
  1331. }
  1332. line = strings.TrimSpace(lines[i+1])
  1333. segs := strings.Split(line, " ")
  1334. numQueue, err := strconv.ParseInt(segs[2], 10, 0)
  1335. if err != nil {
  1336. log.Errorf("failed parse num queue %s: %s", line, err)
  1337. return -1
  1338. } else {
  1339. return numQueue
  1340. }
  1341. }
  1342. }
  1343. return -1
  1344. }
  1345. func (s *SKVMGuestInstance) getScsiNumQueues(qtree string) int64 {
  1346. return getScsiNumQueuesQmp(qtree)
  1347. }
  1348. func (s *SKVMGuestInstance) getDiskDriverNumQueues(qtree, driver string) int64 {
  1349. var lines = strings.Split(strings.TrimSuffix(qtree, "\r\n"), "\\r\\n")
  1350. var currentIndentLevel = -1
  1351. for _, line := range lines {
  1352. trimmedLine := strings.TrimSpace(line)
  1353. if trimmedLine == "" {
  1354. continue
  1355. }
  1356. if currentIndentLevel > 0 {
  1357. // disk has been found
  1358. newIndentLevel := len(line) - len(trimmedLine)
  1359. if newIndentLevel <= currentIndentLevel { // run out disk driver block
  1360. break
  1361. }
  1362. if strings.HasPrefix(trimmedLine, "num-queues =") {
  1363. segs := strings.Split(trimmedLine, " ")
  1364. numQueue, err := strconv.ParseInt(segs[2], 10, 0)
  1365. if err != nil {
  1366. log.Errorf("failed parse num queue %s: %s", trimmedLine, err)
  1367. return -1
  1368. } else {
  1369. return numQueue
  1370. }
  1371. } else {
  1372. continue
  1373. }
  1374. }
  1375. if strings.HasPrefix(trimmedLine, "dev: virtio-blk-pci") && strings.Contains(line, driver) {
  1376. currentIndentLevel = len(line) - len(trimmedLine)
  1377. } else {
  1378. continue
  1379. }
  1380. }
  1381. return -1
  1382. }
  1383. func (s *SKVMGuestInstance) hasHpet(qtree string) bool {
  1384. var lines = strings.Split(strings.TrimSuffix(qtree, "\r\n"), "\\r\\n")
  1385. for _, line := range lines {
  1386. line := strings.TrimSpace(line)
  1387. if strings.HasPrefix(line, "dev: hpet") {
  1388. return true
  1389. }
  1390. }
  1391. return false
  1392. }
  1393. func (s *SKVMGuestInstance) getPciDevices() ([]monitor.PCIInfo, error) {
  1394. var res []monitor.PCIInfo
  1395. var errChan = make(chan error)
  1396. cb := func(pciInfoList []monitor.PCIInfo, err string) {
  1397. if err != "" {
  1398. errChan <- errors.Errorf("%s", err)
  1399. } else {
  1400. res = pciInfoList
  1401. errChan <- nil
  1402. }
  1403. }
  1404. s.Monitor.QueryPci(cb)
  1405. err := <-errChan
  1406. return res, err
  1407. }
  1408. func (s *SKVMGuestInstance) getMemoryDevs() ([]monitor.Memdev, error) {
  1409. var res []monitor.Memdev
  1410. var errChan = make(chan error)
  1411. cb := func(memDevs []monitor.Memdev, err string) {
  1412. if err != "" {
  1413. errChan <- errors.Errorf("%s", err)
  1414. } else {
  1415. res = memDevs
  1416. errChan <- nil
  1417. }
  1418. }
  1419. s.Monitor.GetMemdevList(cb)
  1420. err := <-errChan
  1421. return res, err
  1422. }
  1423. func (s *SKVMGuestInstance) getMemoryDevices() ([]monitor.MemoryDeviceInfo, error) {
  1424. var res []monitor.MemoryDeviceInfo
  1425. var errChan = make(chan error)
  1426. cb := func(memoryDevicesInfoList []monitor.MemoryDeviceInfo, err string) {
  1427. if err != "" {
  1428. errChan <- errors.Errorf("%s", err)
  1429. } else {
  1430. res = memoryDevicesInfoList
  1431. errChan <- nil
  1432. }
  1433. }
  1434. s.Monitor.GetMemoryDevicesInfo(cb)
  1435. err := <-errChan
  1436. return res, err
  1437. }
  1438. func (s *SKVMGuestInstance) hasVirtioBlkDriver() bool {
  1439. for i := range s.Desc.Disks {
  1440. if s.Desc.Disks[i].Driver == "virtio" {
  1441. return true
  1442. }
  1443. }
  1444. return false
  1445. }
  1446. func (s *SKVMGuestInstance) guestRun(ctx context.Context) {
  1447. if s.LiveMigrateDestPort != nil && ctx != nil && !s.IsSlave() {
  1448. // dest migrate guest
  1449. body := jsonutils.NewDict()
  1450. body.Set("live_migrate_dest_port", jsonutils.NewInt(*s.LiveMigrateDestPort))
  1451. err := s.migrateEnableMultifd()
  1452. if err != nil {
  1453. hostutils.TaskFailed(ctx, err.Error())
  1454. return
  1455. }
  1456. err = s.setupGuest()
  1457. if err != nil {
  1458. hostutils.TaskFailed(ctx, err.Error())
  1459. return
  1460. }
  1461. if s.hasVirtioBlkDriver() {
  1462. // virtio driver bind iothread, need migrate use driver mirror
  1463. nbdServerPort := s.manager.GetNBDServerFreePort()
  1464. defer s.manager.unsetPort(nbdServerPort)
  1465. err = s.migrateStartNbdServer(nbdServerPort)
  1466. if err != nil {
  1467. hostutils.TaskFailed(ctx, err.Error())
  1468. return
  1469. }
  1470. body.Set("nbd_server_port", jsonutils.NewInt(int64(nbdServerPort)))
  1471. } else {
  1472. body.Set("nbd_server_disabled", jsonutils.JSONTrue)
  1473. }
  1474. if s.LiveMigrateUseTls {
  1475. s.setDestMigrateTLS(ctx, body)
  1476. } else {
  1477. hostutils.TaskComplete(ctx, body)
  1478. }
  1479. } else if s.IsSlave() {
  1480. s.startQemuBuiltInNbdServer(ctx)
  1481. } else {
  1482. if s.IsMaster() {
  1483. s.startDiskBackupMirror(ctx)
  1484. } else {
  1485. s.DoResumeTask(ctx, true, false)
  1486. }
  1487. if err := s.InitQga(); err != nil {
  1488. log.Errorf("Guest %s init qga failed %s", s.Id, err)
  1489. }
  1490. }
  1491. }
  1492. func (s *SKVMGuestInstance) onMonitorDisConnect(err error) {
  1493. log.Errorf("Guest %s on Monitor Disconnect reason: %v", s.Id, err)
  1494. s.CleanStartupTask()
  1495. s.scriptStop()
  1496. s.SyncStatus(fmt.Sprintf("monitor disconnect %v", err))
  1497. if s.guestAgent != nil {
  1498. s.guestAgent.Close()
  1499. s.guestAgent = nil
  1500. }
  1501. s.clearCgroup(0)
  1502. s.Monitor = nil
  1503. }
  1504. func (s *SKVMGuestInstance) startDiskBackupMirror(ctx context.Context) {
  1505. if ctx == nil || len(appctx.AppContextTaskId(ctx)) == 0 {
  1506. s.DoResumeTask(ctx, true, false)
  1507. } else {
  1508. nbdUri, ok := s.Desc.Metadata["backup_nbd_server_uri"]
  1509. if !ok {
  1510. hostutils.TaskFailed(ctx, "Missing dest nbd location")
  1511. return
  1512. }
  1513. nbdOpts := strings.Split(nbdUri, ":")
  1514. if len(nbdOpts) != 3 {
  1515. hostutils.TaskFailed(ctx, fmt.Sprintf("Nbd uri is not vaild %s", nbdUri))
  1516. return
  1517. }
  1518. s.quorumFailed = 0
  1519. onSucc := func() {
  1520. if err := s.updateChildIndex(); err != nil {
  1521. hostutils.TaskFailed(ctx, err.Error())
  1522. return
  1523. }
  1524. s.DoResumeTask(ctx, true, false)
  1525. }
  1526. onFail := func(res string) {
  1527. s.SyncMirrorJobFailed(res)
  1528. s.DoResumeTask(ctx, true, false)
  1529. }
  1530. NewGuestBlockReplicationTask(ctx, s, nbdOpts[1], nbdOpts[2], "full", onSucc, onFail).Start()
  1531. }
  1532. }
  1533. func (s *SKVMGuestInstance) startQemuBuiltInNbdServer(ctx context.Context) {
  1534. if ctx != nil && len(appctx.AppContextTaskId(ctx)) > 0 {
  1535. nbdServerPort := s.manager.GetNBDServerFreePort()
  1536. defer s.manager.unsetPort(nbdServerPort)
  1537. var onNbdServerStarted = func(res string) {
  1538. if len(res) > 0 {
  1539. log.Errorf("Start Qemu Builtin nbd server error %s", res)
  1540. hostutils.TaskFailed(ctx, res)
  1541. } else {
  1542. res := jsonutils.NewDict()
  1543. res.Set("nbd_server_port", jsonutils.NewInt(int64(nbdServerPort)))
  1544. hostutils.TaskComplete(ctx, res)
  1545. }
  1546. }
  1547. s.Monitor.StartNbdServer(nbdServerPort, true, true, onNbdServerStarted)
  1548. } else {
  1549. s.SyncStatus("")
  1550. }
  1551. }
  1552. func (s *SKVMGuestInstance) SlaveDisksBlockStream() error {
  1553. errChan := make(chan string, 1)
  1554. disks := s.Desc.Disks
  1555. for i := 0; i < len(disks); i++ {
  1556. diskIndex := disks[i].Index
  1557. drive := fmt.Sprintf("drive_%d", diskIndex)
  1558. s.Monitor.BlockStream(drive, func(res string) {
  1559. errChan <- res
  1560. })
  1561. if errStr := <-errChan; len(errStr) > 0 {
  1562. return fmt.Errorf("block stream disk %s: %s", drive, errStr)
  1563. }
  1564. }
  1565. return nil
  1566. }
  1567. func (s *SKVMGuestInstance) clearCgroup(pid int) {
  1568. ReleaseGuestCpuset(s.manager, s)
  1569. if pid == 0 && s.cgroupPid > 0 {
  1570. pid = s.cgroupPid
  1571. }
  1572. cgrupName := s.GetCgroupName()
  1573. log.Infof("cgroup destroy %d %s", pid, cgrupName)
  1574. if pid > 0 && !options.HostOptions.DisableSetCgroup {
  1575. s.CleanupCpuset()
  1576. cgrouputils.CgroupDestroy(strconv.Itoa(pid), cgrupName)
  1577. }
  1578. }
  1579. func (s *SKVMGuestInstance) IsMaster() bool {
  1580. return s.Desc.IsMaster
  1581. }
  1582. func (s *SKVMGuestInstance) IsSlave() bool {
  1583. return s.Desc.IsSlave
  1584. }
  1585. func (s *SKVMGuestInstance) IsMigratingDestGuest() bool {
  1586. return s.LiveMigrateDestPort != nil
  1587. }
  1588. func (s *SKVMGuestInstance) DiskCount() int {
  1589. return len(s.Desc.Disks)
  1590. }
  1591. func (s *SKVMGuestInstance) BlockJobsCount() int {
  1592. res := make(chan []monitor.BlockJob)
  1593. log.Debugf("BlockJobsCount start...")
  1594. s.Monitor.GetBlockJobs(func(jobs []monitor.BlockJob) {
  1595. res <- jobs
  1596. })
  1597. select {
  1598. case <-time.After(time.Second * 30):
  1599. log.Debugf("BlockJobsCount timeout")
  1600. return -1
  1601. case v := <-res:
  1602. log.Debugf("BlockJobsCount %d", len(v))
  1603. return len(v)
  1604. }
  1605. }
  1606. func (s *SKVMGuestInstance) detachStartupTask() {
  1607. log.Infof("[%s] detachStartupTask", s.GetId())
  1608. s.StartupTask = nil
  1609. }
  1610. func (s *SKVMGuestInstance) CleanStartupTask() {
  1611. if s.StartupTask != nil {
  1612. log.Infof("[%s] Clean startup task ... stop task ...", s.GetId())
  1613. s.StartupTask.Stop()
  1614. s.StartupTask = nil
  1615. } else {
  1616. log.Infof("[%s] Clean startup task ... no task", s.GetId())
  1617. }
  1618. }
  1619. func (s *SKVMGuestInstance) onMonitorTimeout(ctx context.Context, err error) {
  1620. log.Errorf("Monitor connect timeout, VM %s frozen: %s force restart!!!!", s.Id, err)
  1621. s.ForceStop()
  1622. timeutils2.AddTimeout(
  1623. time.Second*3, func() { s.StartGuest(ctx, nil, jsonutils.NewDict()) })
  1624. }
  1625. func (s *SKVMGuestInstance) GetHmpMonitorPort(vncPort int) int {
  1626. if vncPort <= 0 {
  1627. vncPort = s.GetVncPort()
  1628. }
  1629. if vncPort > 0 {
  1630. return vncPort + MONITOR_PORT_BASE
  1631. } else {
  1632. return -1
  1633. }
  1634. }
  1635. func (s *SKVMGuestInstance) GetQmpMonitorPort(vncPort int) int {
  1636. if vncPort <= 0 {
  1637. vncPort = s.GetVncPort()
  1638. }
  1639. if vncPort > 0 {
  1640. return vncPort + QMP_MONITOR_PORT_BASE
  1641. } else {
  1642. return -1
  1643. }
  1644. }
  1645. func (s *SKVMGuestInstance) GetVncPort() int {
  1646. if s.IsRunning() {
  1647. vncPort, err := ioutil.ReadFile(s.GetVncFilePath())
  1648. if err != nil {
  1649. return -1
  1650. }
  1651. strPort := strings.TrimSpace(string(vncPort))
  1652. if len(strPort) > 0 {
  1653. port, err := strconv.Atoi(strPort)
  1654. if err == nil {
  1655. return port
  1656. }
  1657. }
  1658. }
  1659. return -1
  1660. }
  1661. func (s *SKVMGuestInstance) saveVncPort(port int) error {
  1662. return fileutils2.FilePutContents(s.GetVncFilePath(), fmt.Sprintf("%d", port), false)
  1663. }
  1664. func (s *SKVMGuestInstance) DoResumeTask(ctx context.Context, isTimeout bool, cleanTls bool) {
  1665. s.StartupTask = NewGuestResumeTask(ctx, s, isTimeout, false)
  1666. s.StartupTask.Start()
  1667. }
  1668. func (s *SKVMGuestInstance) SyncStatus(reason string) {
  1669. if s.IsRunning() {
  1670. s.Monitor.GetBlockJobCounts(s.CheckBlockOrRunning)
  1671. return
  1672. }
  1673. var status = api.VM_READY
  1674. if s.IsSuspend() {
  1675. status = api.VM_SUSPEND
  1676. }
  1677. statusInput := &apis.PerformStatusInput{
  1678. Status: status,
  1679. Reason: reason,
  1680. PowerStates: GetPowerStates(s),
  1681. HostId: hostinfo.Instance().HostId,
  1682. }
  1683. if _, err := hostutils.UpdateServerStatus(context.Background(), s.Id, statusInput); err != nil {
  1684. log.Errorf("failed update guest status %s", err)
  1685. }
  1686. }
  1687. func (s *SKVMGuestInstance) CheckBlockOrRunning(jobs int) {
  1688. var status = api.VM_RUNNING
  1689. if jobs > 0 {
  1690. // TODO: check block jobs ready
  1691. status = api.VM_BLOCK_STREAM
  1692. }
  1693. var statusInput = &apis.PerformStatusInput{
  1694. Status: status,
  1695. BlockJobsCount: jobs,
  1696. PowerStates: GetPowerStates(s),
  1697. HostId: hostinfo.Instance().HostId,
  1698. }
  1699. _, err := hostutils.UpdateServerStatus(context.Background(), s.Id, statusInput)
  1700. if err != nil {
  1701. log.Errorln(err)
  1702. }
  1703. }
  1704. //func (s *SKVMGuestInstance) GetRescueDesc() error {
  1705. // if !s.SourceDesc.LightMode {
  1706. // return errors.Errorf("guest %s not in rescue mode", s.Id)
  1707. // }
  1708. //
  1709. // s.SourceDesc.RescueInitrdPath = path.Join(s.GetRescueDirPath(), api.GUEST_RESCUE_INITRAMFS)
  1710. // s.SourceDesc.RescueKernelPath = path.Join(s.GetRescueDirPath(), api.GUEST_RESCUE_KERNEL)
  1711. // s.SourceDesc.RescueDiskPath = path.Join(s.GetRescueDirPath(), api.GUEST_RESCUE_SYS_DISK_NAME)
  1712. // if s.manager.GetHost().IsAarch64() {
  1713. // s.SourceDesc.RescueInitrdPath = path.Join(s.GetRescueDirPath(), api.GUEST_RESCUE_INITRAMFS_ARM64)
  1714. // s.SourceDesc.RescueKernelPath = path.Join(s.GetRescueDirPath(), api.GUEST_RESCUE_KERNEL_ARM64)
  1715. // }
  1716. //
  1717. // // Address
  1718. // bus, slot, found := s.findUnusedSlotForController(desc.CONTROLLER_TYPE_PCI_ROOT, 0)
  1719. // if !found {
  1720. // return errors.Errorf("no valid pci address found ?")
  1721. // }
  1722. // s.SourceDesc.RescueDiskDeviceBus = uint(bus)
  1723. // s.SourceDesc.RescueDiskDeviceSlot = uint(slot)
  1724. //
  1725. // return nil
  1726. //}
  1727. type guestStartTask struct {
  1728. s *SKVMGuestInstance
  1729. ctx context.Context
  1730. params *jsonutils.JSONDict
  1731. }
  1732. func (t *guestStartTask) Run() {
  1733. if _, err := t.s.asyncScriptStart(t.ctx, t.params); err != nil {
  1734. log.Errorf("failed asyncScriptStart %s: %s", t.s.GetId(), err)
  1735. }
  1736. }
  1737. func (t *guestStartTask) Dump() string {
  1738. return fmt.Sprintf("guest %s params: %v", t.s.Id, t.params)
  1739. }
  1740. func (s *SKVMGuestInstance) prepareEncryptKeyForStart(ctx context.Context, userCred mcclient.TokenCredential, params *jsonutils.JSONDict) (*jsonutils.JSONDict, error) {
  1741. if s.isEncrypted() {
  1742. ekey, err := s.getEncryptKey(ctx, userCred)
  1743. if err != nil {
  1744. log.Errorf("fail to fetch encrypt key: %s", err)
  1745. return nil, errors.Wrap(err, "getEncryptKey")
  1746. }
  1747. if params == nil {
  1748. params = jsonutils.NewDict()
  1749. }
  1750. params.Add(jsonutils.NewString(ekey.Key), "encrypt_key")
  1751. params.Add(jsonutils.Marshal(ekey), "encrypt_info")
  1752. }
  1753. return params, nil
  1754. }
  1755. func (s *SKVMGuestInstance) HandleGuestStart(ctx context.Context, userCred mcclient.TokenCredential, body jsonutils.JSONObject) (jsonutils.JSONObject, error) {
  1756. if s.IsStopped() {
  1757. data, err := body.Get("params")
  1758. if err != nil {
  1759. data = jsonutils.NewDict()
  1760. }
  1761. err = s.StartGuest(ctx, userCred, data.(*jsonutils.JSONDict))
  1762. if err != nil {
  1763. return nil, errors.Wrap(err, "StartGuest")
  1764. }
  1765. res := jsonutils.NewDict()
  1766. res.Set("vnc_port", jsonutils.NewInt(0))
  1767. if !s.manager.host.IsSchedulerNumaAllocateEnabled() {
  1768. res.Set("cpu_numa_pin", jsonutils.Marshal(s.Desc.CpuNumaPin))
  1769. }
  1770. return res, nil
  1771. } else {
  1772. vncPort := s.GetVncPort()
  1773. if vncPort > 0 {
  1774. res := jsonutils.NewDict()
  1775. res.Set("vnc_port", jsonutils.NewInt(int64(vncPort)))
  1776. res.Set("is_running", jsonutils.JSONTrue)
  1777. return res, nil
  1778. } else {
  1779. return nil, httperrors.NewBadRequestError("Seems started, but no VNC info")
  1780. }
  1781. }
  1782. }
  1783. func (s *SKVMGuestInstance) StartGuest(ctx context.Context, userCred mcclient.TokenCredential, params *jsonutils.JSONDict) error {
  1784. var err error
  1785. params, err = s.prepareEncryptKeyForStart(ctx, userCred, params)
  1786. if err != nil {
  1787. return errors.Wrap(err, "prepareEncryptKeyForStart")
  1788. }
  1789. task := &guestStartTask{
  1790. s: s,
  1791. ctx: ctx,
  1792. params: params,
  1793. }
  1794. s.manager.GuestStartWorker.Run(task, nil, nil)
  1795. return nil
  1796. }
  1797. func (s *SKVMGuestInstance) HandleStop(ctx context.Context, timeout int64) error {
  1798. hostutils.DelayTaskWithoutReqctx(ctx, s.ExecStopTask, timeout)
  1799. return nil
  1800. }
  1801. func (s *SKVMGuestInstance) DeployFs(ctx context.Context, userCred mcclient.TokenCredential, deployInfo *deployapi.DeployInfo) (jsonutils.JSONObject, error) {
  1802. if len(s.Desc.Disks) == 0 {
  1803. return nil, fmt.Errorf("Guest dosen't have disk ??")
  1804. }
  1805. diskInfo := deployapi.DiskInfo{}
  1806. if s.isEncrypted() {
  1807. ekey, err := s.getEncryptKey(ctx, userCred)
  1808. if err != nil {
  1809. log.Errorf("fail to fetch encrypt key: %s", err)
  1810. return nil, errors.Wrap(err, "getEncryptKey")
  1811. }
  1812. diskInfo.EncryptPassword = ekey.Key
  1813. diskInfo.EncryptAlg = string(ekey.Alg)
  1814. }
  1815. var sysDisk storageman.IDisk
  1816. disks := s.Desc.Disks
  1817. var diskPaths = make([]string, len(disks))
  1818. for i := range disks {
  1819. diskPath := disks[i].Path
  1820. diskPaths[i] = diskPath
  1821. // GetDiskByPath will probe disks
  1822. disk, err := storageman.GetManager().GetDiskByPath(diskPath)
  1823. if err != nil {
  1824. return nil, errors.Wrapf(err, "GetDiskByPath(%s)", diskPath)
  1825. }
  1826. if i == 0 {
  1827. // sys disk
  1828. diskInfo.Path = disk.GetPath()
  1829. sysDisk = disk
  1830. }
  1831. disks[i].Path = disk.GetPath()
  1832. }
  1833. ret, err := sysDisk.DeployGuestFs(&diskInfo, s.Desc, deployInfo)
  1834. for i := range diskPaths {
  1835. diskPath := diskPaths[i]
  1836. disks[i].Path = diskPath
  1837. disk, e := storageman.GetManager().GetDiskByPath(diskPath)
  1838. if e != nil {
  1839. log.Errorf("failed get disk bypath %s %s", diskPath, e)
  1840. }
  1841. if utils.IsInStringArray(disk.GetType(), []string{api.STORAGE_SLVM, api.STORAGE_CLVM}) {
  1842. if errDeactive := lvmutils.LVDeactivate(diskPath); err != nil {
  1843. log.Errorf("failed deactive disk %s: %s", diskPath, errDeactive)
  1844. }
  1845. }
  1846. }
  1847. return ret, err
  1848. }
  1849. // Delay process
  1850. func (s *SKVMGuestInstance) CleanGuest(ctx context.Context, params interface{}) (jsonutils.JSONObject, error) {
  1851. migrated, ok := params.(bool)
  1852. if !ok {
  1853. return nil, hostutils.ParamsError
  1854. }
  1855. if err := s.StartDelete(ctx, migrated); err != nil {
  1856. return nil, err
  1857. }
  1858. return nil, nil
  1859. }
  1860. func (s *SKVMGuestInstance) CleanDirtyGuest(ctx context.Context) error {
  1861. for s.IsRunning() {
  1862. s.ForceStop()
  1863. time.Sleep(time.Second * 1)
  1864. }
  1865. return s.Delete(ctx, false, true)
  1866. }
  1867. func (s *SKVMGuestInstance) StartDelete(ctx context.Context, migrated bool) error {
  1868. for s.IsRunning() {
  1869. s.ForceStop()
  1870. time.Sleep(time.Second * 1)
  1871. }
  1872. // ensure interface down
  1873. for i := range s.Desc.Nics {
  1874. scriptPath := s.getNicDownScriptPath(s.Desc.Nics[i])
  1875. out, err := procutils.NewRemoteCommandAsFarAsPossible("bash", scriptPath).Output()
  1876. if err != nil {
  1877. log.Errorf("failed run nic down script %s: %s", out, err)
  1878. }
  1879. }
  1880. return s.Delete(ctx, migrated, false)
  1881. }
  1882. func (s *SKVMGuestInstance) ForceStop() bool {
  1883. s.ExitCleanup(true)
  1884. if s.IsRunning() {
  1885. output, err := procutils.NewCommand("kill", "-9", fmt.Sprintf("%d", s.GetPid())).Output()
  1886. if err != nil {
  1887. log.Errorf("kill process %d failed: %s, %s", s.GetPid(), err, output)
  1888. return false
  1889. }
  1890. for _, f := range s.GetCleanFiles() {
  1891. output, err := procutils.NewCommand("rm", "-f", f).Output()
  1892. if err != nil {
  1893. log.Errorf("rm %s failed: %s, %s", f, err, output)
  1894. return false
  1895. }
  1896. }
  1897. return true
  1898. }
  1899. return false
  1900. }
  1901. func (s *SKVMGuestInstance) ExitCleanup(clear bool) {
  1902. s.cleanupKickstartMonitor()
  1903. if clear {
  1904. pid := s.GetPid()
  1905. if pid > 0 {
  1906. s.clearCgroup(pid)
  1907. } else {
  1908. s.clearCgroup(0)
  1909. }
  1910. }
  1911. if s.Monitor != nil {
  1912. s.Monitor.Disconnect()
  1913. s.Monitor = nil
  1914. }
  1915. s.LiveMigrateDestPort = nil
  1916. }
  1917. func (s *SKVMGuestInstance) CleanupCpuset() {
  1918. cgPath := path.Join(cgrouputils.GetSubModulePath("cpuset"), s.GetCgroupName())
  1919. cgName := s.GetCgroupName()
  1920. cgFiles, err := ioutil.ReadDir(cgPath)
  1921. if err != nil {
  1922. log.Warningf("failed read dir %s: %s", cgPath, err)
  1923. }
  1924. for _, fi := range cgFiles {
  1925. if !fi.IsDir() {
  1926. continue
  1927. }
  1928. subCgName := path.Join(cgName, fi.Name())
  1929. task := cgrouputils.NewCGroupCPUSetTask(strconv.Itoa(s.GetPid()), subCgName, "", "")
  1930. if !task.RemoveTask() {
  1931. log.Warningf("remove cpuset cgroup error: %s, pid: %d", s.Id, s.GetPid())
  1932. }
  1933. }
  1934. task := cgrouputils.NewCGroupCPUSetTask(strconv.Itoa(s.GetPid()), s.GetCgroupName(), "", "")
  1935. if !task.RemoveTask() {
  1936. log.Warningf("remove cpuset cgroup error: %s, pid: %d", s.Id, s.GetPid())
  1937. }
  1938. }
  1939. func (s *SKVMGuestInstance) GetCleanFiles() []string {
  1940. return []string{s.GetPidFilePath(), s.GetVncFilePath(), s.getEncryptKeyPath()}
  1941. }
  1942. func (s *SKVMGuestInstance) delTmpDisks(ctx context.Context, migrated bool) error {
  1943. disks := s.Desc.Disks
  1944. for _, disk := range disks {
  1945. if disk.Path != "" {
  1946. diskPath := disk.Path
  1947. d, _ := storageman.GetManager().GetDiskByPath(diskPath)
  1948. if d != nil && d.GetType() == api.STORAGE_LOCAL && migrated {
  1949. skipRecycle := true
  1950. if err := d.DeleteAllSnapshot(skipRecycle); err != nil {
  1951. log.Errorln(err)
  1952. return err
  1953. }
  1954. if _, err := d.Delete(ctx, api.DiskDeleteInput{SkipRecycle: &skipRecycle}); err != nil {
  1955. log.Errorln(err)
  1956. return err
  1957. }
  1958. }
  1959. if d != nil && disk.MergeSnapshot {
  1960. d.PostCreateFromRemoteHostImage(disk.Url)
  1961. }
  1962. if migrated {
  1963. if d != nil && utils.IsInStringArray(d.GetType(), []string{api.STORAGE_SLVM, api.STORAGE_CLVM}) {
  1964. if err := lvmutils.LVDeactivate(d.GetPath()); err != nil {
  1965. log.Errorf("lv %s deactive failed %s", d.GetPath(), err)
  1966. return err
  1967. }
  1968. }
  1969. // remove memory snapshot files
  1970. dir := GetMemorySnapshotPath(s.GetId(), "")
  1971. if err := procutils.NewRemoteCommandAsFarAsPossible("rm", "-rf", dir).Run(); err != nil {
  1972. return errors.Wrapf(err, "remove dir %q", dir)
  1973. }
  1974. }
  1975. }
  1976. }
  1977. return nil
  1978. }
  1979. func (s *SKVMGuestInstance) delFlatFiles(ctx context.Context) error {
  1980. if eid, ok := s.Desc.Metadata["__server_convert_from_esxi"]; ok && len(eid) > 0 {
  1981. disks := s.Desc.Disks
  1982. connections := new(deployapi.EsxiDisksConnectionInfo)
  1983. connections.Disks = make([]*deployapi.EsxiDiskInfo, len(disks))
  1984. for i := 0; i < len(disks); i++ {
  1985. connections.Disks[i] = &deployapi.EsxiDiskInfo{DiskPath: disks[i].EsxiFlatFilePath}
  1986. }
  1987. _, err := deployclient.GetDeployClient().DisconnectEsxiDisks(ctx, connections)
  1988. if err != nil {
  1989. log.Errorf("Disconnect %s esxi disks failed %s", s.GetName(), err)
  1990. return err
  1991. }
  1992. }
  1993. return nil
  1994. }
  1995. func (s *SKVMGuestInstance) Delete(ctx context.Context, migrated, recycle bool) error {
  1996. CleanupKickstartFiles(s.Id, s.getKickstartTmpDir())
  1997. if err := s.delTmpDisks(ctx, migrated); err != nil {
  1998. return errors.Wrap(err, "delTmpDisks")
  1999. }
  2000. if recycle {
  2001. if !fileutils2.Exists(s.RecycleDir()) {
  2002. output, err := procutils.NewCommand("mkdir", "-p", s.RecycleDir()).Output()
  2003. if err != nil {
  2004. return errors.Wrapf(err, "mkdir %s failed: %s", s.RecycleDir(), output)
  2005. }
  2006. }
  2007. output, err := procutils.NewCommand("mv", "-f", s.HomeDir(), s.RecycleDir()).Output()
  2008. if err != nil {
  2009. return errors.Wrapf(err, "mv %s to %s failed: %s", s.HomeDir(), s.RecycleDir(), output)
  2010. }
  2011. } else {
  2012. return DeleteHomeDir(s)
  2013. }
  2014. return nil
  2015. }
  2016. func (s *SKVMGuestInstance) Stop() bool {
  2017. s.ExitCleanup(true)
  2018. if s.scriptStop() {
  2019. return true
  2020. } else {
  2021. return false
  2022. }
  2023. }
  2024. func (s *SKVMGuestInstance) LogFilePath() string {
  2025. return path.Join(s.manager.QemuLogDir(), s.Id)
  2026. }
  2027. func (s *SKVMGuestInstance) readQemuLogFileEnd(size int64) string {
  2028. fname := s.LogFilePath()
  2029. file, err := os.Open(fname)
  2030. if err != nil {
  2031. return fmt.Sprintf("failed open log file %s: %s", fname, err)
  2032. }
  2033. defer file.Close()
  2034. buf := make([]byte, size)
  2035. stat, err := os.Stat(fname)
  2036. if err != nil {
  2037. return fmt.Sprintf("failed stat file %s: %s", fname, err)
  2038. }
  2039. start := stat.Size() - size
  2040. _, err = file.ReadAt(buf, start)
  2041. if err != nil {
  2042. return fmt.Sprintf("failed read logfile %s: %s", fname, err)
  2043. }
  2044. return string(buf)
  2045. }
  2046. func (s *SKVMGuestInstance) pyLauncherPath() string {
  2047. return path.Join(s.HomeDir(), "startvm.py")
  2048. }
  2049. func (s *SKVMGuestInstance) getTmpDirPath() string {
  2050. hasResetDisk := false
  2051. for i := range s.Desc.Disks {
  2052. if s.Desc.Disks[i].AutoReset {
  2053. hasResetDisk = true
  2054. }
  2055. if s.Desc.Disks[i].AutoReset && utils.IsInStringArray(s.Desc.Disks[i].StorageType, api.FIEL_STORAGE) {
  2056. return filepath.Dir(s.Desc.Disks[i].Path)
  2057. }
  2058. }
  2059. if hasResetDisk {
  2060. return options.HostOptions.ResetDiskTmpDir
  2061. }
  2062. return ""
  2063. }
  2064. func (s *SKVMGuestInstance) scriptStart(ctx context.Context) error {
  2065. tmpDir := s.getTmpDirPath()
  2066. cmd := procutils.NewRemoteCommandAsFarAsPossible(s.manager.getPythonPath(), s.pyLauncherPath())
  2067. if tmpDir != "" {
  2068. envs := []string{fmt.Sprintf("TMPDIR=%s", tmpDir)}
  2069. cmd.SetEnv(envs)
  2070. }
  2071. output, err := cmd.Output()
  2072. if err != nil {
  2073. return fmt.Errorf("Start VM Failed %s %s", output, err)
  2074. }
  2075. pid, err := strconv.Atoi(string(output))
  2076. if err != nil {
  2077. return errors.Wrapf(err, "failed parse pid %s", output)
  2078. }
  2079. proc, err := os.FindProcess(pid)
  2080. if err != nil {
  2081. return errors.Wrapf(err, "find process pid(%d)", pid)
  2082. }
  2083. for {
  2084. err = proc.Signal(syscall.Signal(0))
  2085. if err != nil { // qemu process exited
  2086. log.Errorf("Guest %s check qemu(%d) process failed: %s", s.Id, pid, err)
  2087. return errors.Errorf("%s", s.readQemuLogFileEnd(64))
  2088. }
  2089. if err = s.StartMonitor(ctx, nil, true); err == nil {
  2090. return nil
  2091. } else {
  2092. log.Warningf("Guest %s waiting monitor connect", s.GetName())
  2093. }
  2094. time.Sleep(time.Millisecond * 100)
  2095. }
  2096. }
  2097. func (s *SKVMGuestInstance) scriptStop() bool {
  2098. _, err := procutils.NewRemoteCommandAsFarAsPossible("bash", s.GetStopScriptPath()).Output()
  2099. if err != nil {
  2100. log.Errorln(err)
  2101. return false
  2102. }
  2103. return true
  2104. }
  2105. func (s *SKVMGuestInstance) forceScriptStop() bool {
  2106. _, err := procutils.NewRemoteCommandAsFarAsPossible("bash", s.GetStopScriptPath(), "--force").Output()
  2107. if err != nil {
  2108. log.Errorln(err)
  2109. return false
  2110. }
  2111. return true
  2112. }
  2113. func (s *SKVMGuestInstance) ExecStopTask(ctx context.Context, params interface{}) (jsonutils.JSONObject, error) {
  2114. timeout, ok := params.(int64)
  2115. if !ok {
  2116. return nil, hostutils.ParamsError
  2117. }
  2118. NewGuestStopTask(s, ctx, timeout).Start()
  2119. return nil, nil
  2120. }
  2121. func (s *SKVMGuestInstance) ExecSuspendTask(ctx context.Context) {
  2122. NewGuestSuspendTask(s, ctx, nil).Start()
  2123. }
  2124. func pathEqual(disk, ndisk *desc.SGuestDisk) bool {
  2125. if disk.Path != "" && ndisk.Path != "" {
  2126. return disk.Path == ndisk.Path
  2127. } else if disk.Url != "" && ndisk.Url != "" {
  2128. //path1 := disk.AssumedPath
  2129. //path2 := ndisk.AssumedPath
  2130. //return path1 == path2
  2131. // not assumed path found
  2132. return true
  2133. } else {
  2134. return false
  2135. }
  2136. }
  2137. func (s *SKVMGuestInstance) compareDescDisks(newDesc *desc.SGuestDesc) ([]*desc.SGuestDisk, []*desc.SGuestDisk) {
  2138. var delDisks, addDisks = make([]*desc.SGuestDisk, 0), make([]*desc.SGuestDisk, 0)
  2139. newDisks := newDesc.Disks
  2140. for _, disk := range newDisks {
  2141. if utils.IsInStringArray(disk.Driver, []string{"virtio", "scsi"}) {
  2142. newDisk := *disk
  2143. addDisks = append(addDisks, &newDisk)
  2144. }
  2145. }
  2146. oldDisks := s.Desc.Disks
  2147. for _, disk := range oldDisks {
  2148. if utils.IsInStringArray(disk.Driver, []string{"virtio", "scsi"}) {
  2149. var find = false
  2150. for idx, ndisk := range addDisks {
  2151. diskIndex := disk.Index
  2152. nDiskIndex := ndisk.Index
  2153. if diskIndex == nDiskIndex && pathEqual(disk, ndisk) {
  2154. addDisks = append(addDisks[:idx], addDisks[idx+1:]...)
  2155. find = true
  2156. break
  2157. }
  2158. }
  2159. if !find {
  2160. delDisks = append(delDisks, disk)
  2161. }
  2162. }
  2163. }
  2164. return delDisks, addDisks
  2165. }
  2166. func (s *SKVMGuestInstance) compareDescIsolatedDevices(newDesc *desc.SGuestDesc,
  2167. ) ([]*desc.SGuestIsolatedDevice, []*desc.SGuestIsolatedDevice) {
  2168. var delDevs, addDevs = []*desc.SGuestIsolatedDevice{}, []*desc.SGuestIsolatedDevice{}
  2169. newDevs := newDesc.IsolatedDevices
  2170. for _, dev := range newDevs {
  2171. newDev := *dev
  2172. addDevs = append(addDevs, &newDev)
  2173. }
  2174. oldDevs := s.Desc.IsolatedDevices
  2175. for _, oldDev := range oldDevs {
  2176. var find = false
  2177. oVendorDevId := oldDev.VendorDeviceId
  2178. oAddr := oldDev.Addr
  2179. for idx, addDev := range addDevs {
  2180. nVendorDevId := addDev.VendorDeviceId
  2181. nAddr := addDev.Addr
  2182. if oVendorDevId == nVendorDevId && oAddr == nAddr {
  2183. addDevs = append(addDevs[:idx], addDevs[idx+1:]...)
  2184. find = true
  2185. break
  2186. }
  2187. }
  2188. if !find {
  2189. delDevs = append(delDevs, oldDev)
  2190. }
  2191. }
  2192. return delDevs, addDevs
  2193. }
  2194. func (s *SKVMGuestInstance) compareDescCdroms(newDesc *desc.SGuestDesc) []*desc.SGuestCdrom {
  2195. var changeCdroms []*desc.SGuestCdrom
  2196. newCdroms := newDesc.Cdroms
  2197. for i := 0; i < options.HostOptions.CdromCount; i++ {
  2198. changeCdrom := new(desc.SGuestCdrom)
  2199. changeCdrom.Ordinal = int64(i)
  2200. changeCdrom.Path = ""
  2201. s.archMan.GenerateCdromDesc(s.GetOsName(), changeCdrom)
  2202. changeCdroms = append(changeCdroms, changeCdrom)
  2203. }
  2204. for _, newCdrom := range newCdroms {
  2205. ordinal := newCdrom.Ordinal
  2206. path := newCdrom.Path
  2207. changeCdrom := new(desc.SGuestCdrom)
  2208. changeCdrom.Ordinal = ordinal
  2209. changeCdrom.Path = path
  2210. s.archMan.GenerateCdromDesc(s.GetOsName(), changeCdrom)
  2211. for i, tmp := range changeCdroms {
  2212. if tmp.Ordinal == ordinal {
  2213. changeCdroms[i] = changeCdrom
  2214. }
  2215. }
  2216. }
  2217. return changeCdroms
  2218. }
  2219. func (s *SKVMGuestInstance) compareDescFloppys(newDesc *desc.SGuestDesc) []*desc.SGuestFloppy {
  2220. var changeFloppys []*desc.SGuestFloppy
  2221. newFloppys := newDesc.Floppys
  2222. for i := 0; i < options.HostOptions.FloppyCount; i++ {
  2223. changeFloppy := new(desc.SGuestFloppy)
  2224. changeFloppy.Ordinal = int64(i)
  2225. changeFloppy.Path = ""
  2226. s.archMan.GenerateFloppyDesc(s.GetOsName(), changeFloppy)
  2227. changeFloppys = append(changeFloppys, changeFloppy)
  2228. }
  2229. for _, newFloppy := range newFloppys {
  2230. ordinal := newFloppy.Ordinal
  2231. path := newFloppy.Path
  2232. changeFloppy := new(desc.SGuestFloppy)
  2233. changeFloppy.Ordinal = ordinal
  2234. changeFloppy.Path = path
  2235. s.archMan.GenerateFloppyDesc(s.GetOsName(), changeFloppy)
  2236. for i, tmp := range changeFloppys { //如果新增的跟changeCdrom重叠,则以新增为准
  2237. if tmp.Ordinal == ordinal {
  2238. changeFloppys[i] = changeFloppy
  2239. }
  2240. }
  2241. }
  2242. return changeFloppys
  2243. }
  2244. func (s *SKVMGuestInstance) compareDescNetworks(newDesc *desc.SGuestDesc,
  2245. ) ([]*desc.SGuestNetwork, []*desc.SGuestNetwork, [][2]*desc.SGuestNetwork) {
  2246. var isValidHotplug = func(net *desc.SGuestNetwork) bool {
  2247. return net.Driver == "virtio" || net.Driver == "vfio-pci"
  2248. }
  2249. var findNet = func(nets []*desc.SGuestNetwork, net *desc.SGuestNetwork) int {
  2250. for i := 0; i < len(nets); i++ {
  2251. if nets[i].Mac == net.Mac {
  2252. return i
  2253. }
  2254. }
  2255. return -1
  2256. }
  2257. var delNics, addNics = []*desc.SGuestNetwork{}, []*desc.SGuestNetwork{}
  2258. var changedNics = [][2]*desc.SGuestNetwork{}
  2259. for _, n := range newDesc.Nics {
  2260. newNic := *n
  2261. // assume all nics in new desc are new
  2262. addNics = append(addNics, &newNic)
  2263. }
  2264. for _, n := range s.Desc.Nics {
  2265. idx := findNet(addNics, n)
  2266. if idx >= 0 {
  2267. // check if bridge changed
  2268. changedNics = append(changedNics, [2]*desc.SGuestNetwork{
  2269. n, // old
  2270. addNics[idx], // new
  2271. })
  2272. if isValidHotplug(n) {
  2273. // remove existing nic from new
  2274. addNics = append(addNics[:idx], addNics[idx+1:]...)
  2275. }
  2276. } else {
  2277. if isValidHotplug(n) {
  2278. // not found, remove the nic
  2279. delNics = append(delNics, n)
  2280. }
  2281. }
  2282. }
  2283. return delNics, addNics, changedNics
  2284. }
  2285. func getNicBridge(nic *desc.SGuestNetwork) string {
  2286. if nic.Bridge == "" && nic.Vpc.Provider == api.VPC_PROVIDER_OVN {
  2287. return options.HostOptions.OvnIntegrationBridge
  2288. } else {
  2289. return options.HostOptions.NicBridgeDevName(nic.Bridge)
  2290. }
  2291. }
  2292. func (s *SKVMGuestInstance) onNicChange(oldNic, newNic *desc.SGuestNetwork) error {
  2293. log.Infof("nic changed old: %s new: %s", jsonutils.Marshal(oldNic), jsonutils.Marshal(newNic))
  2294. if oldNic.Driver == "vfio-pci" {
  2295. err := s.reconfigureVfioNicsBandwidth(newNic)
  2296. if err != nil {
  2297. log.Errorf("failed configure %s:%s vfio nics bandwidth %s", s.GetId(), oldNic.Mac, err)
  2298. }
  2299. return nil
  2300. } else if oldNic.Driver == "virtio" {
  2301. oldbr := getNicBridge(oldNic)
  2302. oldifname := oldNic.Ifname
  2303. newbr := getNicBridge(newNic)
  2304. newifname := newNic.Ifname
  2305. newvlan := newNic.Vlan
  2306. if oldbr != newbr {
  2307. // bridge changed
  2308. if oldifname == newifname {
  2309. args := []string{
  2310. "--", "del-port", oldbr, oldifname,
  2311. "--", "add-port", newbr, newifname,
  2312. }
  2313. if newvlan > 1 {
  2314. args = append(args, fmt.Sprintf("tag=%d", newvlan))
  2315. }
  2316. output, err := procutils.NewRemoteCommandAsFarAsPossible("ovs-vsctl", args...).Output()
  2317. log.Infof("ovs-vsctl %v: %s", args, output)
  2318. if err != nil {
  2319. return errors.Wrap(err, "NewRemoteCommandAsFarAsPossible")
  2320. }
  2321. } else {
  2322. log.Errorf("cannot change both bridge(%s!=%s) and ifname(%s!=%s)!!!!!", oldbr, newbr, oldifname, newifname)
  2323. }
  2324. } else {
  2325. // bridge not changed
  2326. if oldifname == newifname {
  2327. if newvlan > 1 {
  2328. output, err := procutils.NewRemoteCommandAsFarAsPossible("ovs-vsctl", "set", "port", newifname, fmt.Sprintf("tag=%d", newvlan)).Output()
  2329. if err != nil {
  2330. return errors.Wrapf(err, "NewRemoteCommandAsFarAsPossible change vlan tag to %d: %s", newvlan, output)
  2331. }
  2332. } else {
  2333. // clear vlan
  2334. output, err := procutils.NewRemoteCommandAsFarAsPossible("ovs-vsctl", "get", "port", newifname, "tag").Output()
  2335. if err != nil {
  2336. return errors.Wrapf(err, "NewRemoteCommandAsFarAsPossible get vlan tag: %s", output)
  2337. }
  2338. tagStr := strings.TrimSpace(string(output))
  2339. if tag, err := strconv.Atoi(tagStr); err == nil && tag > 1 {
  2340. if output, err := procutils.NewRemoteCommandAsFarAsPossible("ovs-vsctl", "remove", "port", newifname, "tag", tagStr).Output(); err != nil {
  2341. return errors.Wrapf(err, "NewRemoteCommandAsFarAsPossible remove vlan tag %s: %s", tagStr, output)
  2342. }
  2343. }
  2344. }
  2345. }
  2346. }
  2347. }
  2348. // override network base desc
  2349. oldNic.GuestnetworkBaseDesc = newNic.GuestnetworkBaseDesc
  2350. return nil
  2351. }
  2352. func (s *SKVMGuestInstance) SyncConfig(ctx context.Context, guestDesc *desc.SGuestDesc, fwOnly, setUefiBootOrder bool) (jsonutils.JSONObject, error) {
  2353. var delDisks, addDisks []*desc.SGuestDisk
  2354. var delNetworks, addNetworks []*desc.SGuestNetwork
  2355. var changedNetworks [][2]*desc.SGuestNetwork
  2356. var delDevs, addDevs []*desc.SGuestIsolatedDevice
  2357. var cdroms []*desc.SGuestCdrom
  2358. var floppys []*desc.SGuestFloppy
  2359. if err := SaveDesc(s, guestDesc); err != nil {
  2360. return nil, err
  2361. }
  2362. if !fwOnly && !s.isImportFromLibvirt() {
  2363. delDisks, addDisks = s.compareDescDisks(guestDesc)
  2364. cdroms = s.compareDescCdroms(guestDesc)
  2365. floppys = s.compareDescFloppys(guestDesc)
  2366. delNetworks, addNetworks, changedNetworks = s.compareDescNetworks(guestDesc)
  2367. delDevs, addDevs = s.compareDescIsolatedDevices(guestDesc)
  2368. }
  2369. if len(changedNetworks) > 0 && s.IsRunning() {
  2370. // process changed networks
  2371. for i := range changedNetworks {
  2372. err := s.onNicChange(changedNetworks[i][0], changedNetworks[i][1])
  2373. if err != nil {
  2374. return nil, errors.Wrap(err, "onNicChange")
  2375. }
  2376. }
  2377. }
  2378. if !s.IsRunning() {
  2379. if setUefiBootOrder && s.getBios() == api.VM_BOOT_MODE_UEFI {
  2380. if err := s.setUefiBootOrder(ctx); err != nil {
  2381. log.Errorf("failed set uefi boot order %s", err)
  2382. return nil, errors.Wrap(err, "setUefiBootOrder")
  2383. }
  2384. }
  2385. return nil, nil
  2386. }
  2387. // update guest live desc, don't be here update cpu and mem
  2388. // cpu and memory should update from SGuestHotplugCpuMemTask
  2389. s.UpdateLiveDesc(guestDesc)
  2390. SaveLiveDesc(s, s.Desc)
  2391. if fwOnly {
  2392. res := jsonutils.NewDict()
  2393. res.Set("task", jsonutils.NewArray(jsonutils.NewString("secgroupsync")))
  2394. return res, nil
  2395. }
  2396. var runTaskNames = []jsonutils.JSONObject{}
  2397. var tasks = []IGuestTasks{}
  2398. if len(delDisks)+len(addDisks) > 0 || cdroms != nil || floppys != nil {
  2399. task := NewGuestDiskSyncTask(s, delDisks, addDisks, cdroms, floppys)
  2400. runTaskNames = append(runTaskNames, jsonutils.NewString("disksync"))
  2401. tasks = append(tasks, task)
  2402. }
  2403. if len(delDevs)+len(addDevs) > 0 {
  2404. task := NewGuestIsolatedDeviceSyncTask(s, delDevs, addDevs)
  2405. runTaskNames = append(runTaskNames, jsonutils.NewString("isolated_device_sync"))
  2406. tasks = append(tasks, task)
  2407. }
  2408. // make sure network sync before isolated device
  2409. if len(delNetworks)+len(addNetworks) > 0 {
  2410. task := NewGuestNetworkSyncTask(s, delNetworks, addNetworks)
  2411. runTaskNames = append(runTaskNames, jsonutils.NewString("networksync"))
  2412. tasks = append(tasks, task)
  2413. }
  2414. lenTasks := len(tasks)
  2415. var callBack = func(errs []error) {
  2416. SaveLiveDesc(s, s.Desc)
  2417. if lenTasks > 0 { // devices updated, regenerate start script
  2418. vncPort := s.GetVncPort()
  2419. data := jsonutils.NewDict()
  2420. data.Set("vnc_port", jsonutils.NewInt(int64(vncPort)))
  2421. data.Set("sync_qemu_cmdline", jsonutils.JSONTrue)
  2422. if err := s.saveScripts(data); err != nil {
  2423. log.Errorf("failed save script: %s", err)
  2424. }
  2425. }
  2426. if setUefiBootOrder && s.getBios() == api.VM_BOOT_MODE_UEFI {
  2427. if err := s.setUefiBootOrder(ctx); err != nil {
  2428. log.Errorf("failed set uefi boot order %s", err)
  2429. errs = append(errs, err)
  2430. }
  2431. }
  2432. if len(errs) == 0 {
  2433. hostutils.TaskComplete(ctx, nil)
  2434. } else {
  2435. var reason string
  2436. for _, err := range errs {
  2437. reason += "; " + err.Error()
  2438. }
  2439. hostutils.TaskFailed(ctx, reason[2:])
  2440. }
  2441. }
  2442. NewGuestSyncConfigTaskExecutor(ctx, s, tasks, callBack).Start(1)
  2443. res := jsonutils.NewDict()
  2444. res.Set("task", jsonutils.NewArray(runTaskNames...))
  2445. return res, nil
  2446. }
  2447. func (s *SKVMGuestInstance) getApptags() []string {
  2448. if tagsStr, ok := s.Desc.Metadata["app_tags"]; ok {
  2449. if len(tagsStr) > 0 {
  2450. return strings.Split(tagsStr, ",")
  2451. }
  2452. }
  2453. return nil
  2454. }
  2455. func (s *SKVMGuestInstance) getStorageDeviceId() string {
  2456. disks := s.Desc.Disks
  2457. if len(disks) > 0 {
  2458. if len(disks[0].Path) > 0 {
  2459. return fileutils2.GetDevId(disks[0].Path)
  2460. }
  2461. }
  2462. return ""
  2463. }
  2464. func (s *SKVMGuestInstance) GetCgroupName() string {
  2465. if s.cgroupPid == 0 {
  2466. return ""
  2467. }
  2468. return fmt.Sprintf("%s/server_%s_%d", hostconsts.HOST_CGROUP, s.Id, s.cgroupPid)
  2469. }
  2470. func (s *SKVMGuestInstance) GuestPrelaunchSetCgroup() {
  2471. s.cgroupPid = s.GetPid()
  2472. //s.setCgroupIo()
  2473. s.setCgroupCpu()
  2474. if err := s.setCgroupCPUSet(); err != nil {
  2475. log.Errorf("Guest %s failed set cgroup cpuset: %s", s.GetName(), err)
  2476. }
  2477. }
  2478. func (s *SKVMGuestInstance) setCgroupPid() {
  2479. s.cgroupPid = s.GetPid()
  2480. }
  2481. func (s *SKVMGuestInstance) setCgroupCpu() {
  2482. var (
  2483. cpu = s.Desc.Cpu
  2484. cpuWeight = 1024
  2485. )
  2486. cgrouputils.NewCGroupCPUTask(strconv.Itoa(s.cgroupPid), s.GetCgroupName(), int(cpu)*cpuWeight).SetTask()
  2487. }
  2488. func (s *SKVMGuestInstance) setCgroupCPUSet() error {
  2489. if !s.IsRunning() {
  2490. return nil
  2491. }
  2492. cgName := s.GetCgroupName()
  2493. if cgName == "" {
  2494. return errors.Errorf("failed get cgroup name")
  2495. }
  2496. var cpusetStr string
  2497. if len(s.Desc.CpuNumaPin) == 0 {
  2498. cpus := []string{}
  2499. for _, vcpuPin := range s.Desc.VcpuPin {
  2500. cpus = append(cpus, vcpuPin.Pcpus)
  2501. }
  2502. cpusetStr = strings.Join(cpus, ",")
  2503. } else {
  2504. pcpuSetBuilder := cpuset.NewBuilder()
  2505. for i := range s.Desc.CpuNumaPin {
  2506. for j := range s.Desc.CpuNumaPin[i].VcpuPin {
  2507. pcpuSetBuilder.Add(s.Desc.CpuNumaPin[i].VcpuPin[j].Pcpu)
  2508. }
  2509. }
  2510. cpusetStr = pcpuSetBuilder.Result().String()
  2511. }
  2512. guestPid := strconv.Itoa(s.GetPid())
  2513. // guest root cpuset group
  2514. task := cgrouputils.NewCGroupCPUSetTask(guestPid, cgName, cpusetStr, "")
  2515. if !task.SetTask() {
  2516. return errors.Errorf("Cgroup cpuset task failed")
  2517. }
  2518. vcpuThreads, err := s.getVcpuThreadIdMap(s.GetPid())
  2519. if err != nil {
  2520. return err
  2521. }
  2522. if len(s.Desc.CpuNumaPin) > 0 {
  2523. for i := range s.Desc.CpuNumaPin {
  2524. if s.Desc.CpuNumaPin[i].Unregular || s.Desc.CpuNumaPin[i].VcpuPin == nil {
  2525. continue
  2526. }
  2527. for j := range s.Desc.CpuNumaPin[i].VcpuPin {
  2528. vcpuThreadId, ok := vcpuThreads[s.Desc.CpuNumaPin[i].VcpuPin[j].Vcpu]
  2529. if !ok {
  2530. return errors.Errorf("failed get vcpu %d thread id from %v", s.Desc.CpuNumaPin[i].VcpuPin[j].Vcpu, vcpuThreads)
  2531. }
  2532. pcpu := s.Desc.CpuNumaPin[i].VcpuPin[j].Pcpu
  2533. vcpuCgname := path.Join(cgName, vcpuThreadId)
  2534. taskVcpu := cgrouputils.NewCGroupSubCPUSetTask(guestPid, vcpuCgname, strconv.Itoa(pcpu), []string{vcpuThreadId})
  2535. if !taskVcpu.SetTask() {
  2536. return errors.Errorf("Vcpu set cgroup cpuset task failed")
  2537. }
  2538. }
  2539. }
  2540. } else if len(s.Desc.VcpuPin) > 1 {
  2541. // for guest manual set cpuset
  2542. for i := range s.Desc.VcpuPin {
  2543. vcpu, err := strconv.Atoi(s.Desc.VcpuPin[i].Vcpus)
  2544. if err != nil {
  2545. return errors.Wrapf(err, "failed parse vcpupin %s", s.Desc.VcpuPin[i].Vcpus)
  2546. }
  2547. vcpuThreadId, ok := vcpuThreads[vcpu]
  2548. if !ok {
  2549. return errors.Errorf("failed get vcpu %s thread id from %v", s.Desc.VcpuPin[i].Vcpus, vcpuThreads)
  2550. }
  2551. pcpu := s.Desc.VcpuPin[i].Pcpus
  2552. vcpuCgname := path.Join(cgName, vcpuThreadId)
  2553. taskVcpu := cgrouputils.NewCGroupSubCPUSetTask(guestPid, vcpuCgname, pcpu, []string{vcpuThreadId})
  2554. if !taskVcpu.SetTask() {
  2555. return errors.Errorf("Vcpu set cgroup cpuset task failed")
  2556. }
  2557. }
  2558. }
  2559. return nil
  2560. }
  2561. func (s *SKVMGuestInstance) allocGuestNumaCpuset() error {
  2562. var cpus = make([]int, 0)
  2563. var cpuNumaPin = make([]*desc.SCpuNumaPin, 0)
  2564. var preferNumaNodes = make([]int8, 0)
  2565. for i := range s.Desc.IsolatedDevices {
  2566. if s.Desc.IsolatedDevices[i].NumaNode >= 0 {
  2567. preferNumaNodes = append(preferNumaNodes, s.Desc.IsolatedDevices[i].NumaNode)
  2568. break
  2569. }
  2570. }
  2571. if scpuset, ok := s.Desc.Metadata[api.VM_METADATA_CGROUP_CPUSET]; ok {
  2572. cpusetJson, err := jsonutils.ParseString(scpuset)
  2573. if err != nil {
  2574. log.Errorf("failed parse server %s cpuset %s: %s", s.Id, scpuset, err)
  2575. return errors.Errorf("failed parse server %s cpuset %s: %s", s.Id, scpuset, err)
  2576. }
  2577. input := new(api.ServerCPUSetInput)
  2578. err = cpusetJson.Unmarshal(input)
  2579. if err != nil {
  2580. log.Errorf("failed unmarshal server %s cpuset %s", s.Id, err)
  2581. return errors.Errorf("failed unmarshal server %s cpuset %s", s.Id, err)
  2582. }
  2583. cpus = input.CPUS
  2584. if len(cpus) == int(s.Desc.Cpu) {
  2585. s.Desc.VcpuPin = make([]desc.SCpuPin, len(cpus))
  2586. for i := 0; i < int(s.Desc.Cpu); i++ {
  2587. s.Desc.VcpuPin[i] = desc.SCpuPin{
  2588. Vcpus: strconv.Itoa(i),
  2589. Pcpus: strconv.Itoa(cpus[i]),
  2590. }
  2591. }
  2592. } else {
  2593. s.Desc.VcpuPin = []desc.SCpuPin{
  2594. {
  2595. Vcpus: fmt.Sprintf("0-%d", s.Desc.Cpu-1),
  2596. Pcpus: cpuset.NewCPUSet(cpus...).String(),
  2597. },
  2598. }
  2599. }
  2600. return nil
  2601. }
  2602. nodeNumaCpus, err := s.manager.cpuSet.AllocCpuset(int(s.Desc.Cpu), s.Desc.Mem*1024, preferNumaNodes, s.GetId())
  2603. if err != nil {
  2604. return err
  2605. }
  2606. log.Infof("alloc numa cpus %v", nodeNumaCpus)
  2607. for nodeId, numaCpus := range nodeNumaCpus {
  2608. if s.manager.hostagentNumaAllocate {
  2609. unodeId := uint16(nodeId)
  2610. vcpuPin := make([]desc.SVCpuPin, len(numaCpus.Cpuset))
  2611. for i := range numaCpus.Cpuset {
  2612. vcpuPin[i].Pcpu = numaCpus.Cpuset[i]
  2613. }
  2614. memPin := &desc.SCpuNumaPin{
  2615. SizeMB: numaCpus.MemSizeKB / 1024, // MB
  2616. NodeId: &unodeId,
  2617. VcpuPin: vcpuPin,
  2618. Unregular: numaCpus.Unregular,
  2619. }
  2620. cpuNumaPin = append(cpuNumaPin, memPin)
  2621. }
  2622. cpus = append(cpus, numaCpus.Cpuset...)
  2623. }
  2624. if len(cpuNumaPin) > 0 {
  2625. s.Desc.CpuNumaPin = cpuNumaPin
  2626. } else if !s.manager.hostagentNumaAllocate {
  2627. s.Desc.VcpuPin = []desc.SCpuPin{
  2628. {
  2629. Vcpus: fmt.Sprintf("0-%d", s.Desc.Cpu-1),
  2630. Pcpus: cpuset.NewCPUSet(cpus...).String(),
  2631. },
  2632. }
  2633. }
  2634. return nil
  2635. }
  2636. func (s *SKVMGuestInstance) GetNeedMergeBackingFileDiskIndexs() []int {
  2637. if s.isDisableAutoMergeSnapshots() {
  2638. return nil
  2639. }
  2640. res := make([]int, 0)
  2641. for _, disk := range s.Desc.Disks {
  2642. if disk.MergeSnapshot {
  2643. res = append(res, int(disk.Index))
  2644. }
  2645. }
  2646. return res
  2647. }
  2648. func (s *SKVMGuestInstance) streamDisksComplete(ctx context.Context) {
  2649. disks := s.Desc.Disks
  2650. for i, _ := range disks {
  2651. d, _ := storageman.GetManager().GetDiskByPath(disks[i].Path)
  2652. if disks[i].MergeSnapshot {
  2653. if d != nil {
  2654. log.Infof("Disk %s do post create from fuse", d.GetId())
  2655. d.PostCreateFromRemoteHostImage(disks[i].Url)
  2656. }
  2657. disks[i].MergeSnapshot = false
  2658. s.needSyncStreamDisks = true
  2659. }
  2660. }
  2661. if err := SaveLiveDesc(s, s.Desc); err != nil {
  2662. log.Errorf("save guest desc failed %s", err)
  2663. }
  2664. if err := s.delFlatFiles(ctx); err != nil {
  2665. log.Errorf("del flat files failed %s", err)
  2666. }
  2667. go s.sendStreamDisksComplete(ctx)
  2668. }
  2669. func (s *SKVMGuestInstance) sendStreamDisksComplete(ctx context.Context) {
  2670. for {
  2671. _, err := modules.Servers.PerformAction(hostutils.GetComputeSession(ctx),
  2672. s.Id, "stream-disks-complete", nil)
  2673. if err != nil {
  2674. log.Errorf("stream disks complete sync error %s", err)
  2675. time.Sleep(30 * time.Second)
  2676. continue
  2677. } else {
  2678. break
  2679. }
  2680. }
  2681. s.needSyncStreamDisks = false
  2682. if err := SaveLiveDesc(s, s.Desc); err != nil {
  2683. log.Errorf("save guest desc failed %s", err)
  2684. }
  2685. s.SyncStatus("")
  2686. }
  2687. func (s *SKVMGuestInstance) GetQemuVersionStr() string {
  2688. return s.QemuVersion
  2689. }
  2690. func (s *SKVMGuestInstance) optimizeOom() error {
  2691. pid := s.GetPid()
  2692. if pid > 0 {
  2693. return fileutils2.FilePutContents(fmt.Sprintf("/proc/%d/oom_adj", pid), "-17", false)
  2694. }
  2695. return fmt.Errorf("Guest %s not running?", s.GetId())
  2696. }
  2697. func (s *SKVMGuestInstance) SyncMetadata(meta *jsonutils.JSONDict) error {
  2698. if s.Desc.Metadata == nil {
  2699. s.Desc.Metadata = make(map[string]string)
  2700. }
  2701. meta.Unmarshal(&s.Desc.Metadata)
  2702. _, err := modules.Servers.SetMetadata(hostutils.GetComputeSession(context.Background()),
  2703. s.Id, meta)
  2704. if err != nil {
  2705. log.Errorf("sync metadata error: %v", err)
  2706. return errors.Wrap(err, "set metadata")
  2707. }
  2708. return nil
  2709. }
  2710. func (s *SKVMGuestInstance) updateChildIndex() error {
  2711. idx := s.getQuorumChildIndex() + 1
  2712. s.Desc.Metadata[api.QUORUM_CHILD_INDEX] = strconv.Itoa(int(idx))
  2713. SaveLiveDesc(s, s.Desc)
  2714. meta := jsonutils.NewDict()
  2715. meta.Set(api.QUORUM_CHILD_INDEX, jsonutils.NewInt(idx))
  2716. return s.SyncMetadata(meta)
  2717. }
  2718. func (s *SKVMGuestInstance) SetVncPassword() {
  2719. password := seclib.RandomPassword(8)
  2720. s.VncPassword = password
  2721. var callback = func(res string) {
  2722. if len(res) > 0 {
  2723. log.Errorf("Set vnc password failed: %s", res)
  2724. }
  2725. }
  2726. timeutils2.AddTimeout(time.Second*3,
  2727. func() { s.Monitor.SetVncPassword(s.GetVdiProtocol(), password, callback) })
  2728. }
  2729. func (s *SKVMGuestInstance) OnResumeSyncMetadataInfo() {
  2730. meta := jsonutils.NewDict()
  2731. meta.Set("__qemu_version", jsonutils.NewString(s.GetQemuVersionStr()))
  2732. meta.Set("__vnc_port", jsonutils.NewInt(int64(s.GetVncPort())))
  2733. meta.Set("__enable_cgroup_cpuset", jsonutils.JSONTrue)
  2734. meta.Set(api.VM_METADATA_HOTPLUG_CPU_MEM, jsonutils.NewString("enable"))
  2735. meta.Set(api.VM_METADATA_HOT_REMOVE_NIC, jsonutils.NewString("enable"))
  2736. if len(s.VncPassword) > 0 {
  2737. meta.Set("__vnc_password", jsonutils.NewString(s.VncPassword))
  2738. }
  2739. if s.manager.host.IsHugepagesEnabled() {
  2740. meta.Set("__hugepage", jsonutils.NewString("native"))
  2741. }
  2742. // not exactly
  2743. if !options.HostOptions.HostCpuPassthrough || s.GetOsName() == OS_NAME_MACOS {
  2744. meta.Set("__cpu_mode", jsonutils.NewString(api.CPU_MODE_QEMU))
  2745. } else {
  2746. meta.Set("__cpu_mode", jsonutils.NewString(api.CPU_MODE_HOST))
  2747. }
  2748. if s.hasPcieExtendBus() {
  2749. meta.Set("__pcie_extend_bus", jsonutils.JSONTrue)
  2750. }
  2751. cmdline, err := s.getQemuCmdline()
  2752. if err != nil {
  2753. log.Errorf("Get qemu process cmdline error: %v", err)
  2754. } else {
  2755. meta.Set("__qemu_cmdline", jsonutils.NewString(cmdline))
  2756. }
  2757. //if !s.manager.host.IsSchedulerNumaAllocateEnabled() {
  2758. // meta.Set(api.VM_METADATA_CPU_NUMA_PIN, jsonutils.Marshal(s.Desc.CpuNumaPin))
  2759. //}
  2760. if s.syncMeta != nil {
  2761. meta.Update(s.syncMeta)
  2762. }
  2763. s.SyncMetadata(meta)
  2764. }
  2765. func (s *SKVMGuestInstance) SyncQemuCmdline(cmdline string) {
  2766. meta := jsonutils.NewDict()
  2767. meta.Set("__qemu_cmdline", jsonutils.NewString(cmdline))
  2768. s.SyncMetadata(meta)
  2769. }
  2770. func (s *SKVMGuestInstance) doBlockIoThrottle() {
  2771. disks := s.Desc.Disks
  2772. if len(disks) > 0 {
  2773. s.BlockIoThrottle(context.Background())
  2774. }
  2775. }
  2776. func (s *SKVMGuestInstance) startHotPlugVcpus(vcpuSet []int) error {
  2777. var c = make(chan error)
  2778. for i := range vcpuSet {
  2779. if vcpuSet[i] == 0 {
  2780. // skip vcpu 0, added on qemu cmdline -smp 1
  2781. continue
  2782. }
  2783. s.Monitor.AddCpu(vcpuSet[i], func(res string) {
  2784. var e error = nil
  2785. if len(res) > 0 {
  2786. e = errors.Errorf("failed add cpu %d: %s", vcpuSet[i], res)
  2787. }
  2788. c <- e
  2789. })
  2790. if err, _ := <-c; err != nil {
  2791. return err
  2792. }
  2793. }
  2794. return nil
  2795. }
  2796. func (s *SKVMGuestInstance) hotPlugCpus() error {
  2797. var vcpuSet = make([]int, 0)
  2798. if s.Desc.MemDesc.Mem != nil && len(s.Desc.MemDesc.Mem.Mems) > 0 {
  2799. for i := range s.Desc.CpuNumaPin {
  2800. for j := range s.Desc.CpuNumaPin[i].VcpuPin {
  2801. vcpuSet = append(vcpuSet, s.Desc.CpuNumaPin[i].VcpuPin[j].Vcpu)
  2802. }
  2803. }
  2804. }
  2805. return s.startHotPlugVcpus(vcpuSet)
  2806. }
  2807. func (s *SKVMGuestInstance) onGuestPrelaunch() error {
  2808. if s.LiveMigrateDestPort == nil && !s.Desc.IsSlave {
  2809. if err := s.setupGuest(); err != nil {
  2810. return err
  2811. }
  2812. }
  2813. if !s.Desc.IsSlave {
  2814. if options.HostOptions.SetVncPassword {
  2815. s.SetVncPassword()
  2816. }
  2817. if s.isMemcleanEnabled() {
  2818. if err := s.startMemCleaner(); err != nil {
  2819. return err
  2820. }
  2821. }
  2822. s.OnResumeSyncMetadataInfo()
  2823. s.doBlockIoThrottle()
  2824. }
  2825. s.LiveMigrateDestPort = nil
  2826. return nil
  2827. }
  2828. func (s *SKVMGuestInstance) setupGuest() error {
  2829. if err := s.hotPlugCpus(); err != nil {
  2830. return err
  2831. }
  2832. s.GuestPrelaunchSetCgroup()
  2833. s.optimizeOom()
  2834. return nil
  2835. }
  2836. func (s *SKVMGuestInstance) CleanImportMetadata() *jsonutils.JSONDict {
  2837. meta := jsonutils.NewDict()
  2838. if len(s.Desc.Metadata["__origin_id"]) > 0 {
  2839. meta.Set("__origin_id", jsonutils.NewString(""))
  2840. delete(s.Desc.Metadata, "__origin_id")
  2841. }
  2842. if len(s.Desc.Metadata["__monitor_path"]) > 0 {
  2843. meta.Set("__monitor_path", jsonutils.NewString(""))
  2844. delete(s.Desc.Metadata, "__monitor_path")
  2845. }
  2846. if meta.Length() > 0 {
  2847. // update local metadata record, after monitor started updata region record
  2848. SaveLiveDesc(s, s.Desc)
  2849. return meta
  2850. }
  2851. return nil
  2852. }
  2853. func (s *SKVMGuestInstance) ListStateFilePaths() []string {
  2854. var ret = []string{}
  2855. if fileutils2.Exists(s.HomeDir()) {
  2856. files, err := ioutil.ReadDir(s.HomeDir())
  2857. if err != nil {
  2858. log.Errorln(err)
  2859. return nil
  2860. }
  2861. for _, f := range files {
  2862. if strings.HasPrefix(f.Name(), STATE_FILE_PREFIX) {
  2863. ret = append(ret, path.Join(s.HomeDir(), f.Name()))
  2864. }
  2865. }
  2866. }
  2867. return ret
  2868. }
  2869. func (s *SKVMGuestInstance) CleanStatefiles() {
  2870. for _, stateFile := range s.ListStateFilePaths() {
  2871. log.Infof("Server %s remove statefile %q", s.GetName(), stateFile)
  2872. if _, err := procutils.NewCommand("mountpoint", stateFile).Output(); err == nil {
  2873. if output, err := procutils.NewCommand("umount", stateFile).Output(); err != nil {
  2874. log.Errorf("umount %s failed: %s, %s", stateFile, err, output)
  2875. }
  2876. }
  2877. if output, err := procutils.NewCommand("rm", "-rf", stateFile).Output(); err != nil {
  2878. log.Errorf("failed rm %s: %s, %s", stateFile, err, output)
  2879. }
  2880. }
  2881. if output, err := procutils.NewCommand("rm", "-rf", s.GetFuseTmpPath()).Output(); err != nil {
  2882. log.Errorf("failed rm %s: %s, %s", s.GetFuseTmpPath(), err, output)
  2883. }
  2884. }
  2885. func (s *SKVMGuestInstance) GetFuseTmpPath() string {
  2886. return path.Join(s.HomeDir(), "tmp")
  2887. }
  2888. func (s *SKVMGuestInstance) StreamDisks(ctx context.Context, callback func(), disksIdx []int, totalCnt, completedCnt int) {
  2889. log.Infof("Start guest block stream task %s ...", s.GetName())
  2890. task := NewGuestStreamDisksTask(ctx, s, callback, disksIdx, totalCnt, completedCnt)
  2891. task.Start()
  2892. }
  2893. func (s *SKVMGuestInstance) isLiveSnapshotEnabled() bool {
  2894. if version.GE(s.QemuVersion, "2.12.1") {
  2895. return true
  2896. } else {
  2897. return false
  2898. }
  2899. }
  2900. func (s *SKVMGuestInstance) ExecReloadDiskTask(ctx context.Context, disk storageman.IDisk) (jsonutils.JSONObject, error) {
  2901. if s.IsRunning() {
  2902. if s.isLiveSnapshotEnabled() {
  2903. task := NewGuestReloadDiskTask(ctx, s, disk)
  2904. return nil, task.WaitSnapshotReplaced(task.Start)
  2905. } else {
  2906. return nil, fmt.Errorf("Guest dosen't support reload disk")
  2907. }
  2908. } else {
  2909. res := jsonutils.NewDict()
  2910. res.Set("reopen", jsonutils.JSONTrue)
  2911. return res, nil
  2912. }
  2913. }
  2914. func (s *SKVMGuestInstance) DoSnapshot(ctx context.Context, snapshotParams *SDiskSnapshot) (jsonutils.JSONObject, error) {
  2915. return s.ExecDiskSnapshotTask(ctx, snapshotParams.UserCred, snapshotParams.Disk, snapshotParams.SnapshotId)
  2916. }
  2917. func (s *SKVMGuestInstance) ExecDiskSnapshotTask(
  2918. ctx context.Context, userCred mcclient.TokenCredential, disk storageman.IDisk, snapshotId string,
  2919. ) (jsonutils.JSONObject, error) {
  2920. var (
  2921. encryptKey = ""
  2922. encFormat qemuimg.TEncryptFormat
  2923. encAlg seclib2.TSymEncAlg
  2924. )
  2925. if s.isEncrypted() {
  2926. key, err := s.getEncryptKey(ctx, userCred)
  2927. if err != nil {
  2928. return nil, errors.Wrap(err, "getEncryptKey")
  2929. }
  2930. encryptKey = key.Key
  2931. encFormat = qemuimg.EncryptFormatLuks
  2932. encAlg = key.Alg
  2933. }
  2934. if s.IsRunning() {
  2935. if !s.isLiveSnapshotEnabled() {
  2936. return nil, fmt.Errorf("Guest dosen't support live snapshot")
  2937. }
  2938. err := disk.CreateSnapshot(snapshotId, encryptKey, encFormat, encAlg)
  2939. if err != nil {
  2940. return nil, errors.Wrap(err, "disk.CreateSnapshot")
  2941. }
  2942. task := NewGuestDiskSnapshotTask(ctx, s, disk, snapshotId)
  2943. task.Start()
  2944. return nil, nil
  2945. } else {
  2946. return s.StaticSaveSnapshot(ctx, disk, snapshotId, encryptKey, encFormat, encAlg)
  2947. }
  2948. }
  2949. func (s *SKVMGuestInstance) StaticSaveSnapshot(
  2950. ctx context.Context, disk storageman.IDisk, snapshotId string,
  2951. encryptKey string, encFormat qemuimg.TEncryptFormat, encAlg seclib2.TSymEncAlg,
  2952. ) (jsonutils.JSONObject, error) {
  2953. err := disk.CreateSnapshot(snapshotId, encryptKey, encFormat, encAlg)
  2954. if err != nil {
  2955. return nil, errors.Wrap(err, "disk.CreateSnapshot")
  2956. }
  2957. location := path.Join(disk.GetSnapshotLocation(), snapshotId)
  2958. res := jsonutils.NewDict()
  2959. res.Set("location", jsonutils.NewString(location))
  2960. return res, nil
  2961. }
  2962. func (s *SKVMGuestInstance) DeleteSnapshot(ctx context.Context, delParams *SDeleteDiskSnapshot) (jsonutils.JSONObject, error) {
  2963. if len(delParams.ConvertSnapshot) > 0 || delParams.BlockStream {
  2964. return s.ExecDeleteSnapshotTask(ctx, delParams.Disk, delParams.DeleteSnapshot,
  2965. delParams.ConvertSnapshot, delParams.BlockStream, delParams.EncryptInfo,
  2966. delParams.TotalDeleteSnapshotCount, delParams.DeletedSnapshotCount)
  2967. } else {
  2968. res := jsonutils.NewDict()
  2969. res.Set("deleted", jsonutils.JSONTrue)
  2970. return res, delParams.Disk.DeleteSnapshot(delParams.DeleteSnapshot, "", false, delParams.EncryptInfo)
  2971. }
  2972. }
  2973. func (s *SKVMGuestInstance) ExecDeleteSnapshotTask(
  2974. ctx context.Context, disk storageman.IDisk,
  2975. deleteSnapshot string, convertSnapshot string, blockStream bool, encryptInfo apis.SEncryptInfo,
  2976. totalDeleteSnapshotCount, deletedSnapshotCount int,
  2977. ) (jsonutils.JSONObject, error) {
  2978. if s.IsRunning() {
  2979. if s.isLiveSnapshotEnabled() {
  2980. task := NewGuestSnapshotDeleteTask(ctx, s, disk, deleteSnapshot, convertSnapshot, blockStream, encryptInfo)
  2981. task.Start(totalDeleteSnapshotCount, deletedSnapshotCount)
  2982. return nil, nil
  2983. } else {
  2984. return nil, fmt.Errorf("Guest dosen't support live snapshot delete")
  2985. }
  2986. } else {
  2987. return s.deleteStaticSnapshotFile(ctx, disk, deleteSnapshot, convertSnapshot, blockStream, encryptInfo)
  2988. }
  2989. }
  2990. func (s *SKVMGuestInstance) deleteStaticSnapshotFile(
  2991. ctx context.Context, disk storageman.IDisk, deleteSnapshot, convertSnapshot string, blockStream bool, encryptInfo apis.SEncryptInfo,
  2992. ) (jsonutils.JSONObject, error) {
  2993. if err := disk.DeleteSnapshot(deleteSnapshot, convertSnapshot, blockStream, encryptInfo); err != nil {
  2994. log.Errorln(err)
  2995. return nil, err
  2996. }
  2997. res := jsonutils.NewDict()
  2998. res.Set("deleted", jsonutils.JSONTrue)
  2999. return res, nil
  3000. }
  3001. func GetMemorySnapshotPath(serverId, instanceSnapshotId string) string {
  3002. dir := options.HostOptions.MemorySnapshotsPath
  3003. memSnapPath := filepath.Join(dir, serverId, instanceSnapshotId)
  3004. return memSnapPath
  3005. }
  3006. func (s *SKVMGuestInstance) ExecMemorySnapshotTask(ctx context.Context, input *hostapi.GuestMemorySnapshotRequest) (jsonutils.JSONObject, error) {
  3007. if !s.IsRunning() {
  3008. return nil, errors.Errorf("Server is not running status")
  3009. }
  3010. if s.IsSuspend() {
  3011. return nil, errors.Errorf("Server is suspend status")
  3012. }
  3013. memSnapPath := GetMemorySnapshotPath(s.GetId(), input.InstanceSnapshotId)
  3014. dir := filepath.Dir(memSnapPath)
  3015. if err := procutils.NewRemoteCommandAsFarAsPossible("mkdir", "-p", dir).Run(); err != nil {
  3016. return nil, errors.Wrapf(err, "mkdir -p %q", dir)
  3017. }
  3018. NewGuestSuspendTask(s, ctx, func(_ *SGuestSuspendTask, memStatPath string) {
  3019. log.Infof("Memory state file %q saved, move it to %q", memStatPath, memSnapPath)
  3020. sizeBytes := fileutils2.FileSize(memStatPath)
  3021. sizeKB := sizeBytes / 1024
  3022. checksum, err := fileutils2.FastCheckSum(memStatPath)
  3023. if err != nil {
  3024. hostutils.TaskFailed(ctx, fmt.Sprintf("calculate statefile %q checksum: %v", memStatPath, err))
  3025. return
  3026. }
  3027. if err := procutils.NewRemoteCommandAsFarAsPossible("mv", memStatPath, memSnapPath).Run(); err != nil {
  3028. hostutils.TaskFailed(ctx, fmt.Sprintf("move statefile %q to memory snapshot %q: %v", memStatPath, memSnapPath, err))
  3029. return
  3030. }
  3031. resumeTask := NewGuestResumeTask(ctx, s, false, false)
  3032. resumeTask.SetGetTaskData(func() (jsonutils.JSONObject, error) {
  3033. resp := &hostapi.GuestMemorySnapshotResponse{
  3034. MemorySnapshotPath: memSnapPath,
  3035. SizeKB: sizeKB,
  3036. Checksum: checksum,
  3037. }
  3038. return jsonutils.Marshal(resp), nil
  3039. })
  3040. resumeTask.Start()
  3041. }).Start()
  3042. return nil, nil
  3043. }
  3044. func (s *SKVMGuestInstance) ExecMemorySnapshotResetTask(ctx context.Context, input *hostapi.GuestMemorySnapshotResetRequest) (jsonutils.JSONObject, error) {
  3045. if !s.IsStopped() {
  3046. return nil, errors.Errorf("Server is not stopped status")
  3047. }
  3048. memStatPath := s.GetStateFilePath("")
  3049. if err := procutils.NewRemoteCommandAsFarAsPossible("ln", "-s", input.Path, memStatPath).Run(); err != nil {
  3050. hostutils.TaskFailed(ctx, fmt.Sprintf("move %q to %q: %v", input.Path, memStatPath, err))
  3051. return nil, err
  3052. }
  3053. if input.Checksum != "" {
  3054. handleErr := func(msg string) error {
  3055. // remove linked snapshot path
  3056. if err := procutils.NewRemoteCommandAsFarAsPossible("unlink", memStatPath).Run(); err != nil {
  3057. msg = errors.Wrapf(err, "unlink statfile cause %s", msg).Error()
  3058. }
  3059. hostutils.TaskFailed(ctx, msg)
  3060. return errors.Error(msg)
  3061. }
  3062. checksum, err := fileutils2.FastCheckSum(memStatPath)
  3063. if err != nil {
  3064. return nil, handleErr(fmt.Sprintf("calculate statefile %s checksum: %v", memStatPath, err))
  3065. }
  3066. if checksum != input.Checksum {
  3067. data := jsonutils.NewDict()
  3068. data.Set("name", jsonutils.NewString(input.InstanceSnapshotId))
  3069. notifyclient.SystemExceptionNotifyWithResult(context.Background(), noapi.ActionChecksumTest, noapi.TOPIC_RESOURCE_SNAPSHOT, noapi.ResultFailed, data)
  3070. return nil, handleErr(fmt.Sprintf("calculate checksum %s != %s", checksum, input.Checksum))
  3071. }
  3072. }
  3073. hostutils.TaskComplete(ctx, nil)
  3074. return nil, nil
  3075. }
  3076. func (s *SKVMGuestInstance) PrepareDisksMigrate(liveMigrate bool) (*jsonutils.JSONDict, *jsonutils.JSONDict, bool, error) {
  3077. disksBackFile := jsonutils.NewDict()
  3078. diskSnapsChain := jsonutils.NewDict()
  3079. sysDiskHasTemplate := false
  3080. storageIdUpdated := false
  3081. for i := range s.Desc.Disks {
  3082. disk := s.Desc.Disks[i]
  3083. if disk.Path != "" {
  3084. d, err := storageman.GetManager().GetDiskByPath(disk.Path)
  3085. if err != nil {
  3086. return nil, nil, false, errors.Wrapf(err, "GetDiskByPath(%s)", disk.Path)
  3087. }
  3088. if d.GetType() == api.STORAGE_LOCAL || d.GetType() == api.STORAGE_LVM {
  3089. snaps, back, hasTemplate, err := d.PrepareMigrate(liveMigrate)
  3090. if err != nil {
  3091. return nil, nil, false, err
  3092. }
  3093. if len(back) > 0 {
  3094. disksBackFile.Set(disk.DiskId, jsonutils.NewString(back))
  3095. }
  3096. if len(snaps) > 0 {
  3097. diskSnapsChain.Set(disk.DiskId, jsonutils.NewStringArray(snaps))
  3098. }
  3099. if hasTemplate {
  3100. sysDiskHasTemplate = hasTemplate
  3101. }
  3102. } else if d.GetType() == api.STORAGE_SLVM {
  3103. if d.GetStorage().Lvmlockd() {
  3104. if err := lvmutils.LVActive(d.GetPath(), d.GetStorage().Lvmlockd(), false); err != nil {
  3105. return nil, nil, false, errors.Wrap(err, "lvm active with share")
  3106. }
  3107. }
  3108. }
  3109. storage := d.GetStorage()
  3110. if storage != nil && storage.GetId() != disk.StorageId && storage.GetId() == disk.TargetStorageId {
  3111. // fix storage id not correct
  3112. disk.StorageId = disk.TargetStorageId
  3113. disk.TargetStorageId = ""
  3114. storageIdUpdated = true
  3115. }
  3116. }
  3117. }
  3118. if storageIdUpdated {
  3119. err := SaveLiveDesc(s, s.Desc)
  3120. if err != nil {
  3121. return nil, nil, false, err
  3122. }
  3123. }
  3124. return disksBackFile, diskSnapsChain, sysDiskHasTemplate, nil
  3125. }
  3126. func (s *SKVMGuestInstance) prepareNicsForVolatileGuestResume() error {
  3127. for _, nic := range s.Desc.Nics {
  3128. bridge := nic.Bridge
  3129. dev := s.manager.GetHost().GetBridgeDev(bridge)
  3130. if dev == nil {
  3131. return fmt.Errorf("Can't find bridge %s", bridge)
  3132. }
  3133. if err := dev.OnVolatileGuestResume(nic); err != nil {
  3134. return errors.Wrap(err, "dev.OnVolatileGuestResume")
  3135. }
  3136. }
  3137. return nil
  3138. }
  3139. func (s *SKVMGuestInstance) OnlineResizeDisk(ctx context.Context, disk storageman.IDisk, sizeMB int64) {
  3140. task := NewGuestOnlineResizeDiskTask(ctx, s, disk, sizeMB)
  3141. task.Start()
  3142. }
  3143. func (s *SKVMGuestInstance) BlockIoThrottle(ctx context.Context) {
  3144. task := SGuestBlockIoThrottleTask{s, ctx}
  3145. task.Start()
  3146. }
  3147. func (s *SKVMGuestInstance) IsSharedStorage() bool {
  3148. disks := s.Desc.Disks
  3149. for i := 0; i < len(disks); i++ {
  3150. disk, err := storageman.GetManager().GetDiskByPath(disks[i].Path)
  3151. if err != nil {
  3152. log.Errorf("failed find disk by path %s", disks[i].Path)
  3153. return false
  3154. }
  3155. if !utils.IsInStringArray(disk.GetType(), api.SHARED_STORAGE) {
  3156. return false
  3157. }
  3158. }
  3159. return true
  3160. }
  3161. func (s *SKVMGuestInstance) generateDiskSetupScripts(disks []*desc.SGuestDisk) (string, error) {
  3162. slvmImages := map[string]string{}
  3163. cmd := " "
  3164. for i := range disks {
  3165. diskPath := disks[i].Path
  3166. d, err := storageman.GetManager().GetDiskByPath(diskPath)
  3167. if err != nil {
  3168. return "", errors.Wrapf(err, "GetDiskByPath(%s)", diskPath)
  3169. }
  3170. if d.GetType() == api.STORAGE_SLVM && disks[i].TemplateId != "" {
  3171. slvmImages[disks[i].StorageId] = disks[i].TemplateId
  3172. }
  3173. if len(disks[i].StorageType) == 0 {
  3174. disks[i].StorageType = d.GetType()
  3175. }
  3176. diskIndex := disks[i].Index
  3177. cmd += d.GetDiskSetupScripts(int(diskIndex))
  3178. }
  3179. for storageId, imageId := range slvmImages {
  3180. storage := storageman.GetManager().GetStorage(storageId)
  3181. imageCacheManager := storageman.GetManager().GetStoragecacheById(storage.GetStoragecacheId())
  3182. imageCacheManager.LoadImageCache(imageId)
  3183. }
  3184. return cmd, nil
  3185. }
  3186. func (s *SKVMGuestInstance) GetSriovDeviceByNetworkIndex(networkIndex int) (isolated_device.IDevice, error) {
  3187. manager := s.manager.GetHost().GetIsolatedDeviceManager()
  3188. for i := 0; i < len(s.Desc.IsolatedDevices); i++ {
  3189. if s.Desc.IsolatedDevices[i].DevType == api.NIC_TYPE &&
  3190. s.Desc.IsolatedDevices[i].NetworkIndex == networkIndex {
  3191. if dev := manager.GetDeviceByAddr(s.Desc.IsolatedDevices[i].Addr); dev == nil {
  3192. return nil, errors.Errorf("get device by addr failed")
  3193. } else {
  3194. return dev, nil
  3195. }
  3196. }
  3197. }
  3198. return nil, errors.Errorf("network index %d no sriov device found", networkIndex)
  3199. }
  3200. var sriovInitFunc = `
  3201. function sriov_vf_init() {
  3202. ip link set dev $1 vf $2 mac $3 vlan $4
  3203. ip link set dev $1 vf $2 spoofchk $5
  3204. ip link set dev $1 vf $2 max_tx_rate $6
  3205. }`
  3206. func srcMacCheckFunc(srcMacCheck bool) string {
  3207. if srcMacCheck {
  3208. return "on"
  3209. }
  3210. return "off"
  3211. }
  3212. func getVfVlan(vlan int) int {
  3213. if vlan == 1 {
  3214. return 0
  3215. }
  3216. return vlan
  3217. }
  3218. func getIbNodeMac(mac string) string {
  3219. return "00:01:" + mac
  3220. }
  3221. func getIbPortMac(mac string) string {
  3222. return "00:10:" + mac
  3223. }
  3224. func (s *SKVMGuestInstance) sriovNicAttachInitScript(networkIndex int, dev isolated_device.IDevice) (string, error) {
  3225. for i := range s.Desc.Nics {
  3226. if s.Desc.Nics[i].Driver == "vfio-pci" && s.Desc.Nics[i].Index == networkIndex {
  3227. cmd := s.generateSriovInitCmd(i, dev)
  3228. return sriovInitFunc + " && " + cmd, nil
  3229. }
  3230. }
  3231. return "", errors.Errorf("no nic found for index %d", networkIndex)
  3232. }
  3233. func (s *SKVMGuestInstance) generateSRIOVInitScripts() (string, error) {
  3234. var cmd = ""
  3235. for i := range s.Desc.Nics {
  3236. if s.Desc.Nics[i].Driver == "vfio-pci" {
  3237. dev, err := s.GetSriovDeviceByNetworkIndex(s.Desc.Nics[i].Index)
  3238. if err != nil {
  3239. return "", err
  3240. }
  3241. cmd += s.generateSriovInitCmd(i, dev)
  3242. }
  3243. }
  3244. if len(cmd) > 0 {
  3245. cmd = sriovInitFunc + "\n" + cmd
  3246. }
  3247. return cmd, nil
  3248. }
  3249. func (s *SKVMGuestInstance) generateSriovInitCmd(i int, dev isolated_device.IDevice) string {
  3250. var cmd = ""
  3251. if dev.GetOvsOffloadInterfaceName() != "" {
  3252. cmd += fmt.Sprintf("ip link set dev %s vf %d mac %s max_tx_rate %d\n",
  3253. dev.GetPfName(), dev.GetVirtfn(), s.Desc.Nics[i].Mac, s.Desc.Nics[i].Bw)
  3254. cmd += s.getNicUpScriptPath(s.Desc.Nics[i]) + "\n"
  3255. } else if dev.IsInfinibandNic() {
  3256. sriovPath := path.Join("/sys/class/net", dev.GetPfName(), "device/sriov", strconv.Itoa(dev.GetVirtfn()))
  3257. cmd = fmt.Sprintf("echo Follow > %s/policy\n", sriovPath)
  3258. cmd += fmt.Sprintf("echo %s > %s/node\n", getIbNodeMac(s.Desc.Nics[i].Mac), sriovPath)
  3259. cmd += fmt.Sprintf("echo %s > %s/port\n", getIbPortMac(s.Desc.Nics[i].Mac), sriovPath)
  3260. } else {
  3261. cmd += fmt.Sprintf(
  3262. "sriov_vf_init %s %d %s %d %s %d\n",
  3263. dev.GetPfName(), dev.GetVirtfn(), s.Desc.Nics[i].Mac,
  3264. getVfVlan(s.Desc.Nics[i].Vlan), srcMacCheckFunc(s.Desc.SrcMacCheck), s.Desc.Nics[i].Bw,
  3265. )
  3266. }
  3267. return cmd
  3268. }
  3269. func (s *SKVMGuestInstance) reconfigureVfioNicsBandwidth(nicDesc *desc.SGuestNetwork) error {
  3270. if nicDesc.Driver == "vfio-pci" {
  3271. dev, err := s.GetSriovDeviceByNetworkIndex(nicDesc.Index)
  3272. if err != nil {
  3273. return errors.Wrap(err, "reconfigureVfioNicsBandwidth")
  3274. }
  3275. out, err := procutils.NewRemoteCommandAsFarAsPossible("ip", "link", "set", "dev", dev.GetPfName(),
  3276. "vf", strconv.Itoa(dev.GetVirtfn()), "max_tx_rate", strconv.Itoa(nicDesc.Bw)).Output()
  3277. if err != nil {
  3278. return errors.Wrapf(err, "reconfigureVfioNicsBandwidth set max_tx_rate %s", out)
  3279. }
  3280. }
  3281. return nil
  3282. }
  3283. func (s *SKVMGuestInstance) getQemuCmdline() (string, error) {
  3284. content, err := fileutils2.FileGetContents(s.GetStartScriptPath())
  3285. if err != nil {
  3286. return "", errors.Wrap(err, "get startvm content")
  3287. }
  3288. return s.getQemuCmdlineFromContent(content)
  3289. }
  3290. func (s *SKVMGuestInstance) getQemuCmdlineFromContent(content string) (string, error) {
  3291. cmdReg := regexp.MustCompile(`CMD="(?P<cmd>.*)"`)
  3292. cmdStr := regutils2.GetParams(cmdReg, content)["cmd"]
  3293. if cmdStr == "" {
  3294. return "", errors.Errorf("Not found CMD content")
  3295. }
  3296. return cmdStr, nil
  3297. }
  3298. func (s *SKVMGuestInstance) CPUSet(ctx context.Context, input []int) (*api.ServerCPUSetResp, error) {
  3299. if !s.IsRunning() {
  3300. return nil, nil
  3301. }
  3302. var cpusetStr string
  3303. if input != nil {
  3304. cpus := []string{}
  3305. for _, id := range input {
  3306. cpus = append(cpus, fmt.Sprintf("%d", id))
  3307. }
  3308. cpusetStr = strings.Join(cpus, ",")
  3309. }
  3310. task := cgrouputils.NewCGroupCPUSetTask(strconv.Itoa(s.GetPid()), s.GetCgroupName(), cpusetStr, "")
  3311. if !task.SetTask() {
  3312. return nil, errors.Errorf("Cgroup cpuset task failed")
  3313. }
  3314. return new(api.ServerCPUSetResp), nil
  3315. }
  3316. func (s *SKVMGuestInstance) getVcpuThreadIdMap(guestPid int) (map[int]string, error) {
  3317. tasksDir := fmt.Sprintf("/proc/%d/task", guestPid)
  3318. taskFiles, err := ioutil.ReadDir(tasksDir)
  3319. if err != nil {
  3320. return nil, errors.Wrapf(err, "read dir %s", tasksDir)
  3321. }
  3322. var vcpuThreads = map[int]string{}
  3323. for i := range taskFiles {
  3324. if !taskFiles[i].IsDir() {
  3325. log.Warningf("task %s/%s is not dir?", tasksDir, taskFiles[i].Name())
  3326. continue
  3327. }
  3328. _, err := strconv.Atoi(taskFiles[i].Name())
  3329. if err != nil {
  3330. return nil, errors.Wrapf(err, "failed parse thread id %s", taskFiles[i].Name())
  3331. }
  3332. // vcpu thread comm eg: CPU 0/KVM
  3333. taskComm := path.Join(tasksDir, taskFiles[i].Name(), "comm")
  3334. if cmd, err := fileutils2.FileGetContents(taskComm); err != nil {
  3335. return nil, errors.Wrapf(err, "failed get task %s command", taskComm)
  3336. } else {
  3337. cmd = strings.TrimSpace(cmd)
  3338. if strings.HasPrefix(cmd, "CPU ") && strings.HasSuffix(cmd, "/KVM") {
  3339. vcpuId, err := strconv.Atoi(cmd[4 : len(cmd)-4])
  3340. if err != nil {
  3341. return nil, errors.Wrapf(err, "failed parse %s to int", cmd)
  3342. }
  3343. vcpuThreads[vcpuId] = taskFiles[i].Name()
  3344. }
  3345. }
  3346. }
  3347. return vcpuThreads, nil
  3348. }
  3349. func (s *SKVMGuestInstance) CPUSetRemove(ctx context.Context) error {
  3350. delete(s.Desc.Metadata, api.VM_METADATA_CGROUP_CPUSET)
  3351. if err := SaveLiveDesc(s, s.Desc); err != nil {
  3352. return errors.Wrap(err, "save desc after update metadata")
  3353. }
  3354. if !s.IsRunning() {
  3355. return nil
  3356. }
  3357. task := cgrouputils.NewCGroupCPUSetTask(strconv.Itoa(s.GetPid()), s.GetCgroupName(), "", "")
  3358. if !task.RemoveTask() {
  3359. return errors.Errorf("Remove task error happened, please lookup host log")
  3360. }
  3361. return nil
  3362. }
  3363. func (s *SKVMGuestInstance) GetUploadStatus(ctx context.Context, reason string) (*api.HostUploadGuestStatusInput, error) {
  3364. var status = api.VM_READY
  3365. if s.IsSuspend() {
  3366. status = api.VM_SUSPEND
  3367. }
  3368. statusInput := &apis.PerformStatusInput{
  3369. Status: status,
  3370. Reason: reason,
  3371. PowerStates: GetPowerStates(s),
  3372. HostId: hostinfo.Instance().HostId,
  3373. }
  3374. if s.IsRunning() {
  3375. blkJobCnt := s.BlockJobsCount()
  3376. statusInput.Status = api.VM_RUNNING
  3377. if blkJobCnt > 0 {
  3378. statusInput.Status = api.VM_BLOCK_STREAM
  3379. }
  3380. }
  3381. return &api.HostUploadGuestStatusInput{
  3382. PerformStatusInput: *statusInput,
  3383. }, nil
  3384. }
  3385. func (s *SKVMGuestInstance) PostUploadStatus(resp *api.HostUploadGuestStatusInput, reason string) {
  3386. }
  3387. // except isBatch is false, the call is a sync call
  3388. func (s *SKVMGuestInstance) HandleGuestStatus(ctx context.Context, resp *api.HostUploadGuestStatusInput, isBatch bool) *api.HostUploadGuestStatusInput {
  3389. if resp.Status == GUEST_RUNNING && s.pciUninitialized {
  3390. resp.Status = api.VM_UNSYNC
  3391. } else if resp.Status == GUEST_RUNNING {
  3392. var runCb = func() {
  3393. blockJobsCount := s.BlockJobsCount()
  3394. if blockJobsCount > 0 {
  3395. resp.Status = GUEST_BLOCK_STREAM
  3396. }
  3397. resp.BlockJobsCount = blockJobsCount
  3398. hostutils.TaskComplete(ctx, jsonutils.Marshal(resp))
  3399. }
  3400. if s.Monitor == nil && !s.IsStopping() && !isBatch {
  3401. // 处理虚拟机手动启动,这里同步状态恢复monitor的情况,正常探测状态不会走这里,可以忽略
  3402. if err := s.StartMonitor(context.Background(), runCb, false); err != nil {
  3403. // 如果启动Monitor失败,则放弃启动,直接返回
  3404. log.Errorf("guest %s failed start monitor %s", s.GetName(), err)
  3405. } else {
  3406. // start monitor success, the task will be handled there, return nil to inform the caller
  3407. return nil
  3408. }
  3409. } else if s.Monitor != nil && s.IsRunning() {
  3410. blockJobsCount := s.BlockJobsCount()
  3411. if blockJobsCount > 0 {
  3412. resp.Status = GUEST_BLOCK_STREAM
  3413. }
  3414. resp.BlockJobsCount = blockJobsCount
  3415. }
  3416. }
  3417. return resp
  3418. }
  3419. func (s *SKVMGuestInstance) startKickstartMonitorIfNeeded() {
  3420. if s.kickstartMonitor == nil {
  3421. return
  3422. }
  3423. if !s.shouldUseKickstart() {
  3424. log.Infof("Kickstart not needed for server %s, skip starting monitor", s.Id)
  3425. return
  3426. }
  3427. log.Infof("Starting kickstart monitor for server %s", s.Id)
  3428. if err := s.kickstartMonitor.updateKickstartStatus(api.VM_KICKSTART_INSTALLING); err != nil {
  3429. log.Errorf("Failed to update kickstart status to installing for server %s: %v", s.Id, err)
  3430. } else {
  3431. log.Debugf("Kickstart status updated to installing for server %s", s.Id)
  3432. }
  3433. if err := s.kickstartMonitor.Start(); err != nil {
  3434. log.Errorf("Failed to start kickstart monitor for server %s: %s", s.Id, err)
  3435. }
  3436. }
  3437. func (s *SKVMGuestInstance) cleanupKickstartMonitor() {
  3438. if s.kickstartMonitor != nil {
  3439. s.kickstartMonitor.Close()
  3440. s.kickstartMonitor = nil
  3441. log.Infof("Kickstart monitor cleaned up for server %s", s.Id)
  3442. }
  3443. }