guesttasks.go 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299
  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. "math"
  19. "net"
  20. "os"
  21. "path"
  22. "regexp"
  23. "strconv"
  24. "strings"
  25. "time"
  26. "yunion.io/x/jsonutils"
  27. "yunion.io/x/log"
  28. "yunion.io/x/pkg/appctx"
  29. "yunion.io/x/pkg/errors"
  30. "yunion.io/x/pkg/util/version"
  31. "yunion.io/x/pkg/utils"
  32. "yunion.io/x/onecloud/pkg/apis"
  33. api "yunion.io/x/onecloud/pkg/apis/compute"
  34. hostapi "yunion.io/x/onecloud/pkg/apis/host"
  35. "yunion.io/x/onecloud/pkg/hostman/guestman/desc"
  36. "yunion.io/x/onecloud/pkg/hostman/guestman/qemu"
  37. "yunion.io/x/onecloud/pkg/hostman/hostinfo"
  38. "yunion.io/x/onecloud/pkg/hostman/hostutils"
  39. "yunion.io/x/onecloud/pkg/hostman/isolated_device"
  40. "yunion.io/x/onecloud/pkg/hostman/monitor"
  41. "yunion.io/x/onecloud/pkg/hostman/options"
  42. "yunion.io/x/onecloud/pkg/hostman/storageman"
  43. "yunion.io/x/onecloud/pkg/mcclient/auth"
  44. "yunion.io/x/onecloud/pkg/util/cgrouputils/cpuset"
  45. "yunion.io/x/onecloud/pkg/util/procutils"
  46. "yunion.io/x/onecloud/pkg/util/qemuimg"
  47. "yunion.io/x/onecloud/pkg/util/timeutils2"
  48. )
  49. type IGuestTasks interface {
  50. Start(func(...error))
  51. }
  52. /**
  53. * GuestStopTask
  54. **/
  55. type SGuestStopTask struct {
  56. *SKVMGuestInstance
  57. ctx context.Context
  58. timeout int64
  59. startPowerdown time.Time
  60. }
  61. func NewGuestStopTask(guest *SKVMGuestInstance, ctx context.Context, timeout int64) *SGuestStopTask {
  62. return &SGuestStopTask{
  63. SKVMGuestInstance: guest,
  64. ctx: ctx,
  65. timeout: timeout,
  66. startPowerdown: time.Time{},
  67. }
  68. }
  69. func (s *SGuestStopTask) Start() {
  70. s.stopping = true
  71. s.startPowerdown = time.Now()
  72. if s.IsRunning() && s.IsMonitorAlive() {
  73. s.Monitor.SimpleCommand("system_powerdown", s.onPowerdownGuest)
  74. }
  75. s.checkGuestRunning()
  76. }
  77. func (s *SGuestStopTask) onPowerdownGuest(results string) {
  78. //s.ExitCleanup(true)
  79. log.Debugf("system_powerdown callback successfully")
  80. // s.checkGuestRunning()
  81. }
  82. func (s *SGuestStopTask) checkGuestRunning() {
  83. if !s.IsRunning() || time.Now().Sub(s.startPowerdown) > time.Duration(s.timeout)*time.Second {
  84. s.Stop() // force stop
  85. s.stopping = false
  86. hostutils.TaskComplete(s.ctx, nil)
  87. } else {
  88. s.CheckGuestRunningLater()
  89. }
  90. }
  91. func (s *SGuestStopTask) CheckGuestRunningLater() {
  92. time.Sleep(time.Second * 1)
  93. s.checkGuestRunning()
  94. }
  95. type SGuestSuspendTask struct {
  96. *SKVMGuestInstance
  97. ctx context.Context
  98. onFinishCallback func(*SGuestSuspendTask, string)
  99. }
  100. func NewGuestSuspendTask(
  101. guest *SKVMGuestInstance,
  102. ctx context.Context,
  103. onFinishCallback func(*SGuestSuspendTask, string),
  104. ) *SGuestSuspendTask {
  105. t := &SGuestSuspendTask{
  106. SKVMGuestInstance: guest,
  107. ctx: ctx,
  108. }
  109. if onFinishCallback == nil {
  110. onFinishCallback = t.onSaveMemStateComplete
  111. }
  112. t.onFinishCallback = onFinishCallback
  113. return t
  114. }
  115. func (s *SGuestSuspendTask) Start() {
  116. s.Monitor.SimpleCommand("stop", s.onSuspendGuest)
  117. }
  118. func (s *SGuestSuspendTask) GetStateFilePath() string {
  119. return s.SKVMGuestInstance.GetStateFilePath("")
  120. }
  121. func (s *SGuestSuspendTask) onSuspendGuest(results string) {
  122. if strings.Contains(strings.ToLower(results), "error") {
  123. hostutils.TaskFailed(s.ctx, fmt.Sprintf("Suspend error: %s", results))
  124. return
  125. }
  126. statFile := s.GetStateFilePath()
  127. s.Monitor.SaveState(statFile, s.onSaveMemStateWait)
  128. }
  129. func (s *SGuestSuspendTask) onSaveMemStateWait(results string) {
  130. if strings.Contains(strings.ToLower(results), "error") {
  131. hostutils.TaskFailed(s.ctx, fmt.Sprintf("Save memory state error: %s", results))
  132. // TODO: send cont command
  133. return
  134. }
  135. s.Monitor.GetMigrateStatus(s.onSaveMemStateCheck)
  136. }
  137. func (s *SGuestSuspendTask) onSaveMemStateCheck(status string) {
  138. if status == "failed" {
  139. hostutils.TaskFailed(s.ctx, "Save memory state failed")
  140. // TODO: send cont command
  141. return
  142. } else if status != "completed" {
  143. time.Sleep(time.Second * 3)
  144. log.Infof("Server %s saving memory state status %q", s.GetName(), status)
  145. s.onSaveMemStateWait("")
  146. } else {
  147. log.Infof("Server %s save memory completed", s.GetName())
  148. s.onFinishCallback(s, s.GetStateFilePath())
  149. }
  150. }
  151. func (s *SGuestSuspendTask) onSaveMemStateComplete(_ *SGuestSuspendTask, _ string) {
  152. log.Infof("Server %s memory state saved, stopping server", s.GetName())
  153. s.ExecStopTask(s.ctx, int64(3))
  154. }
  155. /**
  156. * GuestSyncConfigTaskExecutor
  157. **/
  158. type SGuestSyncConfigTaskExecutor struct {
  159. ctx context.Context
  160. guest *SKVMGuestInstance
  161. tasks []IGuestTasks
  162. errors []error
  163. callback func([]error)
  164. }
  165. func NewGuestSyncConfigTaskExecutor(ctx context.Context, guest *SKVMGuestInstance, tasks []IGuestTasks, callback func([]error)) *SGuestSyncConfigTaskExecutor {
  166. return &SGuestSyncConfigTaskExecutor{ctx, guest, tasks, make([]error, 0), callback}
  167. }
  168. func (t *SGuestSyncConfigTaskExecutor) Start(delay int) {
  169. timeutils2.AddTimeout(1*time.Second, t.runNextTask)
  170. }
  171. func (t *SGuestSyncConfigTaskExecutor) runNextTask() {
  172. if len(t.tasks) > 0 {
  173. task := t.tasks[len(t.tasks)-1]
  174. t.tasks = t.tasks[:len(t.tasks)-1]
  175. task.Start(t.runNextTaskCallback)
  176. } else {
  177. t.doCallback()
  178. }
  179. }
  180. func (t *SGuestSyncConfigTaskExecutor) doCallback() {
  181. if t.callback != nil {
  182. t.callback(t.errors)
  183. t.callback = nil
  184. }
  185. }
  186. func (t *SGuestSyncConfigTaskExecutor) runNextTaskCallback(err ...error) {
  187. if err != nil {
  188. t.errors = append(t.errors, err...)
  189. }
  190. t.runNextTask()
  191. }
  192. /**
  193. * GuestDiskSyncTask
  194. **/
  195. type SGuestDiskSyncTask struct {
  196. guest *SKVMGuestInstance
  197. delDisks []*desc.SGuestDisk
  198. addDisks []*desc.SGuestDisk
  199. cdroms []*desc.SGuestCdrom
  200. floppys []*desc.SGuestFloppy
  201. errors []error
  202. callback func(...error)
  203. checkDrivers []string
  204. }
  205. func NewGuestDiskSyncTask(guest *SKVMGuestInstance, delDisks, addDisks []*desc.SGuestDisk, cdroms []*desc.SGuestCdrom, floppys []*desc.SGuestFloppy) *SGuestDiskSyncTask {
  206. return &SGuestDiskSyncTask{guest, delDisks, addDisks, cdroms, floppys, make([]error, 0), nil, nil}
  207. }
  208. func (d *SGuestDiskSyncTask) Start(callback func(...error)) {
  209. d.callback = callback
  210. d.syncDisksConf()
  211. }
  212. func (d *SGuestDiskSyncTask) syncDisksConf() {
  213. if len(d.delDisks) > 0 {
  214. disk := d.delDisks[len(d.delDisks)-1]
  215. d.delDisks = d.delDisks[:len(d.delDisks)-1]
  216. d.removeDisk(disk)
  217. return
  218. }
  219. if len(d.addDisks) > 0 {
  220. disk := d.addDisks[len(d.addDisks)-1]
  221. d.addDisks = d.addDisks[:len(d.addDisks)-1]
  222. d.addDisk(disk)
  223. return
  224. }
  225. if len(d.cdroms) > 0 {
  226. cdrom := d.cdroms[len(d.cdroms)-1]
  227. d.cdroms = d.cdroms[:len(d.cdroms)-1]
  228. d.changeCdrom(cdrom)
  229. return
  230. }
  231. if len(d.floppys) > 0 {
  232. floppy := d.floppys[len(d.floppys)-1]
  233. d.floppys = d.floppys[:len(d.floppys)-1]
  234. d.changeFloppy(floppy)
  235. return
  236. }
  237. if idxs := d.guest.GetNeedMergeBackingFileDiskIndexs(); len(idxs) > 0 {
  238. d.guest.StreamDisks(context.Background(),
  239. func() { d.guest.streamDisksComplete(context.Background()) }, idxs, -1, -1,
  240. )
  241. }
  242. d.callback(d.errors...)
  243. }
  244. func (d *SGuestDiskSyncTask) changeCdrom(cdrom *desc.SGuestCdrom) {
  245. d.guest.Monitor.GetBlocks(func(blocks []monitor.QemuBlock) {
  246. var cdName string
  247. for _, r := range blocks {
  248. if regexp.MustCompile(fmt.Sprintf(`^(ide|scsi)?(%d-)?cd\d+$`, cdrom.Ordinal)).MatchString(r.Device) {
  249. cdName = r.Device
  250. break
  251. }
  252. }
  253. if len(cdName) > 0 {
  254. d.changeCdromContent(cdName, cdrom)
  255. } else {
  256. if cdrom.Path != "" && cdrom.Scsi != nil {
  257. cb2 := func(res string) {
  258. d.changeCdromContent(cdName, cdrom)
  259. }
  260. cb := func(res string) {
  261. cdrom.Scsi.Options["drive"] = cdrom.Id
  262. d.guest.Monitor.DeviceAdd(cdrom.Scsi.DevType, cdrom.Scsi.Options, cb2)
  263. }
  264. params := map[string]string{}
  265. for k, v := range cdrom.DriveOptions {
  266. params[k] = v
  267. }
  268. params["file"] = cdrom.Path
  269. params["id"] = cdrom.Id
  270. d.guest.Monitor.DriveAdd("0", "", params, cb)
  271. } else {
  272. cdrom.Path = ""
  273. d.syncDisksConf()
  274. }
  275. }
  276. })
  277. }
  278. func (d *SGuestDiskSyncTask) changeCdromContent(cdName string, cdrom *desc.SGuestCdrom) {
  279. if cdrom.Path == "" {
  280. d.guest.Monitor.EjectCdrom(cdName, func(s string) {
  281. d.OnEjectCdromContentSucc(cdName)
  282. })
  283. } else {
  284. d.guest.Monitor.ChangeCdrom(cdName, cdrom.Path, func(s string) {
  285. d.OnChangeCdromContentSucc(cdrom)
  286. })
  287. }
  288. }
  289. func (d *SGuestDiskSyncTask) OnEjectCdromContentSucc(cdName string) {
  290. for i, cdrom := range d.guest.Desc.Cdroms {
  291. if cdrom.Id == cdName {
  292. d.guest.Desc.Cdroms[i].Path = ""
  293. d.guest.Desc.Cdroms[i].BootIndex = nil
  294. }
  295. }
  296. d.syncDisksConf()
  297. }
  298. func (d *SGuestDiskSyncTask) OnChangeCdromContentSucc(cdrom *desc.SGuestCdrom) {
  299. if d.guest.Desc.Cdroms == nil {
  300. d.guest.Desc.Cdroms = make([]*desc.SGuestCdrom, options.HostOptions.CdromCount)
  301. for i := range d.guest.Desc.Cdroms {
  302. d.guest.Desc.Cdroms[i] = new(desc.SGuestCdrom)
  303. d.guest.Desc.Cdroms[i].Ordinal = int64(i)
  304. }
  305. }
  306. for i := range d.guest.Desc.Cdroms {
  307. if cdrom.Ordinal == d.guest.Desc.Cdroms[i].Ordinal {
  308. d.guest.Desc.Cdroms[i] = cdrom
  309. }
  310. }
  311. d.syncDisksConf()
  312. }
  313. func (d *SGuestDiskSyncTask) changeFloppy(floppy *desc.SGuestFloppy) {
  314. d.guest.Monitor.GetBlocks(func(blocks []monitor.QemuBlock) {
  315. var flName string
  316. for _, r := range blocks {
  317. if regexp.MustCompile(fmt.Sprintf(`^floppy%d$`, floppy.Ordinal)).MatchString(r.Device) {
  318. flName = r.Device
  319. break
  320. }
  321. }
  322. if len(flName) > 0 {
  323. d.changeFloppyContent(flName, floppy)
  324. } else {
  325. floppy.Path = ""
  326. d.syncDisksConf()
  327. }
  328. })
  329. }
  330. func (d *SGuestDiskSyncTask) changeFloppyContent(flName string, floppy *desc.SGuestFloppy) {
  331. if floppy.Path == "" {
  332. d.guest.Monitor.EjectCdrom(flName, func(s string) {
  333. d.OnEjectFloppyContentSucc(flName)
  334. })
  335. } else {
  336. d.guest.Monitor.ChangeCdrom(flName, floppy.Path, func(s string) {
  337. d.OnChangeFloppyContentSucc(floppy)
  338. })
  339. }
  340. }
  341. func (d *SGuestDiskSyncTask) OnEjectFloppyContentSucc(flName string) {
  342. for i, floppy := range d.guest.Desc.Floppys {
  343. if floppy.Id == flName {
  344. d.guest.Desc.Floppys[i].Path = ""
  345. }
  346. }
  347. d.syncDisksConf()
  348. }
  349. func (d *SGuestDiskSyncTask) OnChangeFloppyContentSucc(floppy *desc.SGuestFloppy) {
  350. if d.guest.Desc.Floppys == nil {
  351. d.guest.Desc.Floppys = make([]*desc.SGuestFloppy, options.HostOptions.FloppyCount)
  352. for i := range d.guest.Desc.Floppys {
  353. d.guest.Desc.Floppys[i] = new(desc.SGuestFloppy)
  354. d.guest.Desc.Floppys[i].Ordinal = int64(i)
  355. }
  356. }
  357. for i := range d.guest.Desc.Floppys {
  358. if floppy.Ordinal == d.guest.Desc.Floppys[i].Ordinal {
  359. d.guest.Desc.Floppys[i] = floppy
  360. }
  361. }
  362. d.syncDisksConf()
  363. }
  364. func (d *SGuestDiskSyncTask) removeDisk(disk *desc.SGuestDisk) {
  365. devId := fmt.Sprintf("drive_%d", disk.Index)
  366. d.guest.Monitor.DriveDel(devId, func(results string) {
  367. d.onRemoveDriveSucc(devId, results, disk.Index)
  368. })
  369. }
  370. func (d *SGuestDiskSyncTask) onRemoveDriveSucc(devId, results string, diskIdx int8) {
  371. log.Infof("remove drive %s results: %s", devId, results)
  372. d.guest.Monitor.DeviceDel(devId, func(results string) {
  373. d.onRemoveDiskSucc(results, diskIdx)
  374. })
  375. }
  376. func (d *SGuestDiskSyncTask) onRemoveDiskSucc(results string, diskIdx int8) {
  377. var i = 0
  378. for ; i < len(d.guest.Desc.Disks); i++ {
  379. if d.guest.Desc.Disks[i].Index == diskIdx {
  380. if d.guest.Desc.Disks[i].Pci != nil {
  381. err := d.guest.pciAddrs.ReleasePCIAddress(d.guest.Desc.Disks[i].Pci.PCIAddr)
  382. if err != nil {
  383. log.Errorf("failed release disk pci addr %s", d.guest.Desc.Disks[i].Pci.PCIAddr)
  384. }
  385. }
  386. break
  387. }
  388. }
  389. if i < len(d.guest.Desc.Disks) {
  390. d.guest.Desc.Disks = append(d.guest.Desc.Disks[:i], d.guest.Desc.Disks[i+1:]...)
  391. }
  392. d.syncDisksConf()
  393. }
  394. func (d *SGuestDiskSyncTask) checkDiskDriver(disk *desc.SGuestDisk) {
  395. if d.checkDrivers == nil {
  396. d.checkDrivers = make([]string, 0)
  397. }
  398. log.Debugf("sync disk driver: %s", disk.Driver)
  399. if disk.Driver == DISK_DRIVER_SCSI && d.guest.Desc.VirtioScsi == nil {
  400. // insert virtio scsi
  401. var cType = d.guest.getHotPlugPciControllerType()
  402. if cType == nil {
  403. err := errors.Errorf("failed get hotplugable pci controller")
  404. d.errors = append(d.errors, err)
  405. d.syncDisksConf()
  406. return
  407. }
  408. d.guest.Desc.VirtioScsi = &desc.SGuestVirtioScsi{
  409. PCIDevice: desc.NewPCIDevice(*cType, "virtio-scsi-pci", "scsi"),
  410. }
  411. if err := d.guest.ensureDevicePciAddress(d.guest.Desc.VirtioScsi.PCIDevice, -1, nil); err != nil {
  412. d.guest.Desc.VirtioScsi = nil
  413. err = errors.Wrap(err, "ensureDevicePciAddress for virtio scsi device")
  414. d.errors = append(d.errors, err)
  415. d.syncDisksConf()
  416. return
  417. }
  418. cb := func(ret string) {
  419. log.Infof("Add scsi controller %s", ret)
  420. d.checkDrivers = append(d.checkDrivers, DISK_DRIVER_SCSI)
  421. d.startAddDisk(disk)
  422. }
  423. params := map[string]string{
  424. "id": d.guest.Desc.VirtioScsi.Id,
  425. "bus": d.guest.Desc.VirtioScsi.BusStr(),
  426. "addr": d.guest.Desc.VirtioScsi.SlotFunc(),
  427. }
  428. d.guest.Monitor.DeviceAdd(d.guest.Desc.VirtioScsi.DevType, params, cb)
  429. } else if disk.Driver == DISK_DRIVER_SATA && d.guest.Desc.SataController == nil {
  430. // insert sata ahci controller
  431. var cType = d.guest.getHotPlugPciControllerType()
  432. if cType == nil {
  433. err := errors.Errorf("failed get hotplugable pci controller")
  434. d.errors = append(d.errors, err)
  435. d.syncDisksConf()
  436. return
  437. }
  438. d.guest.Desc.SataController = &desc.SGuestAhciDevice{
  439. PCIDevice: desc.NewPCIDevice(*cType, "ahci", "ahci0"),
  440. }
  441. err := d.guest.ensureDevicePciAddress(d.guest.Desc.SataController.PCIDevice, -1, nil)
  442. if err != nil {
  443. d.guest.Desc.SataController = nil
  444. err = errors.Wrap(err, "ensureDevicePciAddress sata controller")
  445. d.errors = append(d.errors, err)
  446. d.syncDisksConf()
  447. return
  448. }
  449. cb := func(ret string) {
  450. log.Infof("Add sata ahci controller %s", ret)
  451. d.checkDrivers = append(d.checkDrivers, DISK_DRIVER_SATA)
  452. d.startAddDisk(disk)
  453. }
  454. params := map[string]string{
  455. "id": d.guest.Desc.SataController.Id,
  456. "bus": d.guest.Desc.SataController.BusStr(),
  457. "addr": d.guest.Desc.SataController.SlotFunc(),
  458. }
  459. d.guest.Monitor.DeviceAdd(d.guest.Desc.SataController.DevType, params, cb)
  460. } else {
  461. d.startAddDisk(disk)
  462. }
  463. }
  464. func (d *SGuestDiskSyncTask) addDisk(disk *desc.SGuestDisk) {
  465. d.checkDiskDriver(disk)
  466. }
  467. func (d *SGuestDiskSyncTask) startAddDisk(disk *desc.SGuestDisk) {
  468. iDisk, _ := storageman.GetManager().GetDiskByPath(disk.Path)
  469. if iDisk == nil {
  470. d.syncDisksConf()
  471. return
  472. }
  473. var (
  474. diskIndex = disk.Index
  475. aio = disk.AioMode
  476. diskDriver = disk.Driver
  477. cacheMode = disk.CacheMode
  478. )
  479. var params = map[string]string{
  480. "file": iDisk.GetPath(),
  481. "if": "none",
  482. "id": fmt.Sprintf("drive_%d", diskIndex),
  483. "cache": cacheMode,
  484. "aio": aio,
  485. }
  486. if iDisk.IsFile() {
  487. params["file.locking"] = "off"
  488. }
  489. if d.guest.isEncrypted() {
  490. params["encrypt.format"] = "luks"
  491. params["encrypt.key-secret"] = "sec0"
  492. }
  493. var bus string
  494. var cType *desc.PCI_CONTROLLER_TYPE
  495. switch diskDriver {
  496. case DISK_DRIVER_SCSI:
  497. bus = "scsi.0"
  498. case DISK_DRIVER_VIRTIO:
  499. cType = d.guest.getHotPlugPciControllerType()
  500. if cType == nil {
  501. log.Errorf("no hotplugable pci controller found")
  502. d.errors = append(d.errors, errors.Errorf("no hotplugable pci controller found"))
  503. d.syncDisksConf()
  504. return
  505. }
  506. bus = d.guest.GetPciBus()
  507. case DISK_DRIVER_IDE:
  508. bus = fmt.Sprintf("ide.%d", diskIndex/2)
  509. case DISK_DRIVER_SATA:
  510. bus = fmt.Sprintf("ahci0.%d", diskIndex)
  511. }
  512. // drive_add bus is a placeholder
  513. d.guest.Monitor.DriveAdd(bus, "", params, func(result string) { d.onAddDiskSucc(disk, result, cType) })
  514. }
  515. func (d *SGuestDiskSyncTask) onAddDiskSucc(disk *desc.SGuestDisk, results string, cType *desc.PCI_CONTROLLER_TYPE) {
  516. var (
  517. diskIndex = disk.Index
  518. diskDriver = disk.Driver
  519. devType = qemu.GetDiskDeviceModel(diskDriver)
  520. id = fmt.Sprintf("drive_%d", diskIndex)
  521. )
  522. switch diskDriver {
  523. case DISK_DRIVER_VIRTIO:
  524. disk.Pci = desc.NewPCIDevice(*cType, devType, id)
  525. err := d.guest.ensureDevicePciAddress(disk.Pci, -1, nil)
  526. if err != nil {
  527. log.Errorln(err)
  528. d.guest.Monitor.DriveDel(id, func(res string) {
  529. log.Infof("drive %s del %s", id, res)
  530. })
  531. d.errors = append(d.errors, err)
  532. d.syncDisksConf()
  533. return
  534. }
  535. case DISK_DRIVER_SCSI:
  536. disk.Scsi = desc.NewScsiDevice(d.guest.Desc.VirtioScsi.Id, devType, id)
  537. case DISK_DRIVER_PVSCSI:
  538. disk.Scsi = desc.NewScsiDevice(d.guest.Desc.PvScsi.Id, devType, id)
  539. case DISK_DRIVER_IDE:
  540. disk.Ide = desc.NewIdeDevice(devType, id)
  541. case DISK_DRIVER_SATA: // -device ahci,id=ahci pci device
  542. disk.Ide = desc.NewIdeDevice(devType, id)
  543. }
  544. d.guest.Desc.Disks = append(d.guest.Desc.Disks, disk)
  545. var params = map[string]string{
  546. "drive": fmt.Sprintf("drive_%d", diskIndex),
  547. "id": fmt.Sprintf("drive_%d", diskIndex),
  548. }
  549. if diskDriver == DISK_DRIVER_VIRTIO && disk.Pci != nil {
  550. params["bus"] = disk.Pci.BusStr()
  551. params["addr"] = disk.Pci.SlotFunc()
  552. } else if DISK_DRIVER_IDE == diskDriver {
  553. params["unit"] = strconv.Itoa(int(diskIndex % 2))
  554. }
  555. d.guest.Monitor.DeviceAdd(devType, params, d.onAddDeviceSucc)
  556. }
  557. func (d *SGuestDiskSyncTask) onAddDeviceSucc(results string) {
  558. log.Infof("%s device add res: %s", d.guest.GetName(), results)
  559. d.syncDisksConf()
  560. }
  561. /**
  562. * GuestNetworkSyncTask
  563. **/
  564. type SGuestNetworkSyncTask struct {
  565. guest *SKVMGuestInstance
  566. delNics []*desc.SGuestNetwork
  567. addNics []*desc.SGuestNetwork
  568. errors []error
  569. delNicCnt int
  570. addNicMacs []string
  571. addNicConfs []*monitor.NetworkModify
  572. callback func(...error)
  573. }
  574. func (n *SGuestNetworkSyncTask) Start(callback func(...error)) {
  575. n.callback = callback
  576. if len(n.addNics) > 0 {
  577. addNicMacs := make([]string, 0)
  578. addNicConfs := make([]*monitor.NetworkModify, 0)
  579. for i := range n.addNics {
  580. addNicMacs = append(addNicMacs, n.addNics[i].Mac)
  581. netMod := &monitor.NetworkModify{}
  582. if len(n.addNics[i].Ip) > 0 {
  583. netMod.Ipmask = fmt.Sprintf("%s/%d", n.addNics[i].Ip, n.addNics[i].Masklen)
  584. netMod.Gateway = n.addNics[i].Gateway
  585. }
  586. if len(n.addNics[i].Ip6) > 0 {
  587. netMod.Ip6mask = fmt.Sprintf("%s/%d", n.addNics[i].Ip6, n.addNics[i].Masklen6)
  588. }
  589. addNicConfs = append(addNicConfs, netMod)
  590. }
  591. n.addNicMacs = addNicMacs
  592. n.addNicConfs = addNicConfs
  593. // deploy nics configure before do add nics
  594. allNics := append(n.guest.Desc.Nics, n.addNics...)
  595. if err := n.guest.QgaDeployNicsConfigure(allNics); err != nil {
  596. log.Errorf("failed do QgaDeployNicsConfigure %s", err)
  597. }
  598. }
  599. n.delNicCnt = len(n.delNics)
  600. n.syncNetworkConf()
  601. }
  602. func (n *SGuestNetworkSyncTask) syncNetworkConf() {
  603. if len(n.delNics) > 0 {
  604. nic := n.delNics[len(n.delNics)-1]
  605. n.delNics = n.delNics[:len(n.delNics)-1]
  606. n.removeNic(nic)
  607. } else if len(n.addNics) > 0 {
  608. nic := n.addNics[len(n.addNics)-1]
  609. n.addNics = n.addNics[:len(n.addNics)-1]
  610. n.addNic(nic)
  611. } else {
  612. func() {
  613. if len(n.addNicMacs) > 0 || n.delNicCnt > 0 {
  614. // redeploy nics config after add/del nics
  615. if err := n.guest.QgaDeployNicsConfigure(n.guest.Desc.Nics); err != nil {
  616. log.Errorf("failed do QgaDeployNicsConfigure %s", err)
  617. return
  618. }
  619. }
  620. if len(n.addNicMacs) > 0 {
  621. // try restart added nics, wait for added nic ready
  622. time.Sleep(6 * time.Second)
  623. if err := n.qgaRestartAddedNics(); err != nil {
  624. log.Errorf("failed qgaRestartAddedNics %s", err)
  625. return
  626. }
  627. }
  628. }()
  629. n.callback(n.errors...)
  630. }
  631. }
  632. func (n *SGuestNetworkSyncTask) qgaRestartAddedNics() error {
  633. err := n.qgaGetAddedNicDevs()
  634. if err != nil {
  635. return err
  636. }
  637. for i := range n.addNicConfs {
  638. if n.addNicConfs[i].Device != "" {
  639. err = n.guest.guestAgent.QgaRestartNetwork(n.addNicConfs[i])
  640. if err != nil {
  641. log.Errorf("Failed QgaRestartNetwork %s %s", n.addNicConfs[i].Device, err)
  642. }
  643. }
  644. }
  645. return nil
  646. }
  647. func (n *SGuestNetworkSyncTask) qgaGetAddedNicDevs() error {
  648. data, err := n.guest.guestAgent.QgaGetNetwork()
  649. if err != nil {
  650. return errors.Wrap(err, "QgaGetNetwork")
  651. }
  652. var parsedData []api.IfnameDetail
  653. ifnames, err := jsonutils.Parse(data)
  654. if err != nil {
  655. return errors.Wrapf(err, "parse qga network output %s", data)
  656. }
  657. err = ifnames.Unmarshal(&parsedData)
  658. if err != nil {
  659. return errors.Wrap(err, "unmarshal ifnames")
  660. }
  661. for i := range n.addNicMacs {
  662. for j := range parsedData {
  663. if n.addNicMacs[i] == parsedData[j].HardwareAddress {
  664. n.addNicConfs[i].Device = parsedData[j].Name
  665. break
  666. }
  667. }
  668. }
  669. return nil
  670. }
  671. func (n *SGuestNetworkSyncTask) removeNic(nic *desc.SGuestNetwork) {
  672. if nic.Driver == "vfio-pci" {
  673. n.onDeviceDel(nic)
  674. return
  675. }
  676. callback := func(res string) {
  677. if len(res) > 0 && !strings.Contains(res, "not found") {
  678. log.Errorf("netdev del failed %s", res)
  679. n.errors = append(n.errors, fmt.Errorf("netdev del failed %s", res))
  680. n.syncNetworkConf()
  681. } else {
  682. n.onNetdevDel(nic)
  683. }
  684. }
  685. n.guest.Monitor.NetdevDel(nic.Ifname, callback)
  686. }
  687. func (n *SGuestNetworkSyncTask) onNetdevDel(nic *desc.SGuestNetwork) {
  688. downScript := n.guest.getNicDownScriptPath(nic)
  689. output, err := procutils.NewCommand("sh", downScript).Output()
  690. if err != nil {
  691. log.Errorf("script down nic failed %s", output)
  692. n.errors = append(n.errors, err)
  693. }
  694. n.delNicDevice(nic)
  695. }
  696. func (n *SGuestNetworkSyncTask) onDeviceDel(nic *desc.SGuestNetwork) {
  697. var i = 0
  698. for ; i < len(n.guest.Desc.Nics); i++ {
  699. if n.guest.Desc.Nics[i].Index == nic.Index {
  700. if nic.Pci != nil {
  701. err := n.guest.pciAddrs.ReleasePCIAddress(nic.Pci.PCIAddr)
  702. if err != nil {
  703. log.Errorf("failed release nic pci addr %s", nic.Pci.PCIAddr)
  704. }
  705. }
  706. break
  707. }
  708. }
  709. if i < len(n.guest.Desc.Nics) {
  710. n.guest.Desc.Nics = append(n.guest.Desc.Nics[:i], n.guest.Desc.Nics[i+1:]...)
  711. }
  712. n.syncNetworkConf()
  713. }
  714. func (n *SGuestNetworkSyncTask) delNicDevice(nic *desc.SGuestNetwork) {
  715. callback := func(res string) {
  716. if len(res) > 0 {
  717. log.Errorf("network device del failed %s", res)
  718. n.errors = append(n.errors, fmt.Errorf("network device del failed %s", res))
  719. } else {
  720. n.onDeviceDel(nic)
  721. }
  722. }
  723. n.guest.Monitor.DeviceDel(fmt.Sprintf("netdev-%s", nic.Ifname), callback)
  724. }
  725. func (n *SGuestNetworkSyncTask) addNic(nic *desc.SGuestNetwork) {
  726. if err := n.guest.generateNicScripts(nic); err != nil {
  727. log.Errorln(err)
  728. n.errors = append(n.errors, err)
  729. n.syncNetworkConf()
  730. return
  731. }
  732. if nic.Driver == "vfio-pci" {
  733. // vfio device will add on isolated devices sync task
  734. n.onDeviceAdd(nic)
  735. return
  736. }
  737. var (
  738. netType = "tap"
  739. upscript = n.guest.getNicUpScriptPath(nic)
  740. downscript = n.guest.getNicDownScriptPath(nic)
  741. params = map[string]string{
  742. "ifname": nic.Ifname, "script": upscript, "downscript": downscript,
  743. "vhost": "on", "vhostforce": "off",
  744. }
  745. cType = n.guest.getHotPlugPciControllerType()
  746. )
  747. if cType == nil {
  748. err := errors.Errorf("no hotplugable pci controller found")
  749. log.Errorln(err)
  750. n.errors = append(n.errors, err)
  751. n.syncNetworkConf()
  752. return
  753. }
  754. callback := func(res string) {
  755. if len(res) > 0 {
  756. log.Errorf("netdev add failed %s", res)
  757. n.errors = append(n.errors, fmt.Errorf("netdev add failed %s", res))
  758. n.syncNetworkConf()
  759. } else {
  760. nic.UpscriptPath = upscript
  761. nic.DownscriptPath = downscript
  762. n.onNetdevAdd(nic, cType)
  763. }
  764. }
  765. n.guest.Monitor.NetdevAdd(nic.Ifname, netType, params, callback)
  766. }
  767. func (n *SGuestNetworkSyncTask) onNetdevAdd(nic *desc.SGuestNetwork, cType *desc.PCI_CONTROLLER_TYPE) {
  768. id := fmt.Sprintf("netdev-%s", nic.Ifname)
  769. devType := n.guest.getNicDeviceModel(nic.Driver)
  770. onFail := func(e error) {
  771. log.Errorln(e)
  772. n.errors = append(n.errors, e)
  773. n.guest.Monitor.NetdevDel(nic.Ifname, func(res string) {
  774. log.Infof("netdev %s del %s", id, res)
  775. })
  776. n.syncNetworkConf()
  777. }
  778. switch nic.Driver {
  779. case "virtio":
  780. nic.Pci = desc.NewPCIDevice(*cType, devType, id)
  781. case "e1000":
  782. nic.Pci = desc.NewPCIDevice(*cType, devType, id)
  783. case "vmxnet3":
  784. nic.Pci = desc.NewPCIDevice(*cType, devType, id)
  785. default:
  786. err := errors.Errorf("unknown nic driver %s", nic.Driver)
  787. onFail(err)
  788. return
  789. }
  790. err := n.guest.ensureDevicePciAddress(nic.Pci, -1, nil)
  791. if err != nil {
  792. onFail(err)
  793. return
  794. }
  795. params := map[string]string{
  796. "id": fmt.Sprintf("netdev-%s", nic.Ifname),
  797. "netdev": nic.Ifname,
  798. "mac": nic.Mac,
  799. "bus": nic.Pci.BusStr(),
  800. "addr": nic.Pci.SlotFunc(),
  801. }
  802. callback := func(res string) {
  803. if len(res) > 0 {
  804. err := fmt.Errorf("device add failed %s", res)
  805. onFail(err)
  806. return
  807. } else {
  808. n.onDeviceAdd(nic)
  809. }
  810. }
  811. n.guest.Monitor.DeviceAdd(devType, params, callback)
  812. }
  813. func (n *SGuestNetworkSyncTask) onDeviceAdd(nic *desc.SGuestNetwork) {
  814. n.guest.Desc.Nics = append(n.guest.Desc.Nics, nic)
  815. n.syncNetworkConf()
  816. }
  817. func NewGuestNetworkSyncTask(
  818. guest *SKVMGuestInstance, delNics, addNics []*desc.SGuestNetwork,
  819. ) *SGuestNetworkSyncTask {
  820. return &SGuestNetworkSyncTask{guest, delNics, addNics, make([]error, 0), 0, nil, nil, nil}
  821. }
  822. /**
  823. * GuestIsolatedDeviceSyncTask
  824. **/
  825. type SGuestIsolatedDeviceSyncTask struct {
  826. guest *SKVMGuestInstance
  827. delDevs []*desc.SGuestIsolatedDevice
  828. addDevs []*desc.SGuestIsolatedDevice
  829. errors []error
  830. callback func(...error)
  831. }
  832. func NewGuestIsolatedDeviceSyncTask(guest *SKVMGuestInstance, delDevs, addDevs []*desc.SGuestIsolatedDevice) *SGuestIsolatedDeviceSyncTask {
  833. return &SGuestIsolatedDeviceSyncTask{guest, delDevs, addDevs, make([]error, 0), nil}
  834. }
  835. func (t *SGuestIsolatedDeviceSyncTask) Start(cb func(...error)) {
  836. t.callback = cb
  837. t.syncDevice()
  838. }
  839. func (t *SGuestIsolatedDeviceSyncTask) syncDevice() {
  840. if len(t.delDevs) > 0 {
  841. dev := t.delDevs[len(t.delDevs)-1]
  842. t.delDevs = t.delDevs[:len(t.delDevs)-1]
  843. t.removeDevice(dev)
  844. } else if len(t.addDevs) > 0 {
  845. dev := t.addDevs[len(t.addDevs)-1]
  846. t.addDevs = t.addDevs[:len(t.addDevs)-1]
  847. t.addDevice(dev)
  848. } else {
  849. t.callback(t.errors...)
  850. }
  851. }
  852. func (t *SGuestIsolatedDeviceSyncTask) removeDevice(dev *desc.SGuestIsolatedDevice) {
  853. cb := func(res string) {
  854. if len(res) > 0 {
  855. t.errors = append(t.errors, fmt.Errorf("device del failed: %s", res))
  856. } else {
  857. var i = 0
  858. for ; i < len(t.guest.Desc.IsolatedDevices); i++ {
  859. if t.guest.Desc.IsolatedDevices[i].Id == dev.Id {
  860. for j := 0; j < len(t.guest.Desc.IsolatedDevices[i].VfioDevs); j++ {
  861. pciaddr := t.guest.Desc.IsolatedDevices[i].VfioDevs[j].PCIAddr
  862. if pciaddr != nil {
  863. if e := t.guest.pciAddrs.ReleasePCIAddress(pciaddr); e != nil {
  864. log.Errorf("failed release vfio pci address %s", pciaddr)
  865. }
  866. }
  867. }
  868. break
  869. }
  870. }
  871. if i < len(t.guest.Desc.IsolatedDevices) {
  872. // remove device
  873. t.guest.Desc.IsolatedDevices = append(t.guest.Desc.IsolatedDevices[:i], t.guest.Desc.IsolatedDevices[i+1:]...)
  874. }
  875. }
  876. t.syncDevice()
  877. }
  878. devObj := hostinfo.Instance().IsolatedDeviceMan.GetDeviceByIdent(dev.VendorDeviceId, dev.Addr, dev.MdevId)
  879. if devObj == nil {
  880. cb(fmt.Sprintf("Not found host isolated_device by %s %s", dev.VendorDeviceId, dev.Addr))
  881. return
  882. }
  883. opts, err := devObj.GetHotUnplugOptions(dev)
  884. if err != nil {
  885. cb(errors.Wrap(err, "GetHotPlugOptions").Error())
  886. return
  887. }
  888. t.delDeviceCallBack(opts, 0, cb)
  889. }
  890. func (t *SGuestIsolatedDeviceSyncTask) addDevice(dev *desc.SGuestIsolatedDevice) {
  891. var err error
  892. devObj := hostinfo.Instance().IsolatedDeviceMan.GetDeviceByIdent(dev.VendorDeviceId, dev.Addr, dev.MdevId)
  893. if devObj == nil {
  894. err = errors.Errorf("Not found host isolated_device by %s %s", dev.VendorDeviceId, dev.Addr)
  895. log.Errorln(err)
  896. t.errors = append(t.errors, err)
  897. t.syncDevice()
  898. return
  899. }
  900. var setupScript string
  901. if dev.DevType == api.NIC_TYPE {
  902. setupScript, err = t.guest.sriovNicAttachInitScript(dev.NetworkIndex, devObj)
  903. if err != nil {
  904. err = errors.Errorf("sriovNicAttachInitScript %s", err)
  905. log.Errorln(err)
  906. t.errors = append(t.errors, err)
  907. t.syncDevice()
  908. return
  909. }
  910. }
  911. onFail := func(err error) {
  912. for i := 0; i < len(dev.VfioDevs); i++ {
  913. if dev.VfioDevs[i].PCIAddr != nil {
  914. if eRelease := t.guest.pciAddrs.ReleasePCIAddress(dev.VfioDevs[i].PCIAddr); eRelease != nil {
  915. log.Errorf("failed release pci pci address %s: %s", dev.VfioDevs[i].PCIAddr, eRelease)
  916. }
  917. }
  918. }
  919. log.Errorln(err)
  920. t.errors = append(t.errors, err)
  921. t.syncDevice()
  922. return
  923. }
  924. var cType *desc.PCI_CONTROLLER_TYPE
  925. if dev.DevType == api.USB_TYPE {
  926. dev.Usb = desc.NewUsbDevice("usb-host", devObj.GetQemuId())
  927. dev.Usb.Options = devObj.GetPassthroughOptions()
  928. } else {
  929. cType = t.guest.getVfioDeviceHotPlugPciControllerType()
  930. if cType == nil {
  931. log.Errorf("no hotplugable pci controller found")
  932. t.errors = append(t.errors, errors.Errorf("no hotplugable pci controller found"))
  933. t.syncDevice()
  934. return
  935. }
  936. id := devObj.GetQemuId()
  937. dev.VfioDevs = make([]*desc.VFIODevice, 0)
  938. vfioDev := desc.NewVfioDevice(
  939. *cType, "vfio-pci", id, devObj.GetAddr(), dev.DevType == api.GPU_VGA_TYPE,
  940. )
  941. dev.VfioDevs = append(dev.VfioDevs, vfioDev)
  942. groupDevAddrs := devObj.GetIOMMUGroupRestAddrs()
  943. for j := 0; j < len(groupDevAddrs); j++ {
  944. gid := fmt.Sprintf("%s-%d", id, j+1)
  945. vfioDev = desc.NewVfioDevice(*cType, "vfio-pci", gid, groupDevAddrs[j], false)
  946. dev.VfioDevs = append(dev.VfioDevs, vfioDev)
  947. }
  948. multiFunc := true
  949. err := t.guest.ensureDevicePciAddress(dev.VfioDevs[0].PCIDevice, 0, &multiFunc)
  950. if err != nil {
  951. err = errors.Wrapf(err, "ensure isolated device %s pci address", dev.VfioDevs[0].PCIAddr)
  952. } else {
  953. for j := 1; j < len(dev.VfioDevs); j++ {
  954. dev.VfioDevs[j].PCIAddr = dev.VfioDevs[0].PCIAddr.Copy()
  955. err = t.guest.ensureDevicePciAddress(dev.VfioDevs[j].PCIDevice, j, nil)
  956. if err != nil {
  957. err = errors.Wrapf(err, "ensure isolated device %s pci address", dev.VfioDevs[j].PCIAddr)
  958. break
  959. }
  960. }
  961. }
  962. if err != nil {
  963. onFail(err)
  964. return
  965. }
  966. }
  967. cb := func(res string) {
  968. if len(res) > 0 {
  969. onFail(fmt.Errorf("device add failed: %s", res))
  970. } else {
  971. t.guest.Desc.IsolatedDevices = append(t.guest.Desc.IsolatedDevices, dev)
  972. t.syncDevice()
  973. }
  974. }
  975. if len(setupScript) > 0 {
  976. output, err := procutils.NewRemoteCommandAsFarAsPossible("sh", "-c", setupScript).Output()
  977. if err != nil {
  978. log.Errorf("isolated device setup error %s, %s", output, err)
  979. }
  980. }
  981. opts, err := devObj.GetHotPlugOptions(dev, t.guest.Desc)
  982. if err != nil {
  983. cb(errors.Wrap(err, "GetHotPlugOptions").Error())
  984. return
  985. }
  986. t.addDeviceCallBack(opts, 0, cb)
  987. }
  988. func (t *SGuestIsolatedDeviceSyncTask) addDeviceCallBack(opts []*isolated_device.HotPlugOption, idx int, onAddFinish func(string)) {
  989. if idx >= len(opts) {
  990. onAddFinish("")
  991. return
  992. }
  993. opt := opts[idx]
  994. t.guest.Monitor.DeviceAdd(opt.Device, opt.Options, func(err string) {
  995. if err != "" {
  996. onAddFinish(fmt.Sprintf("monitor add %d device: %s", idx, err))
  997. return
  998. }
  999. t.addDeviceCallBack(opts, idx+1, onAddFinish)
  1000. })
  1001. }
  1002. func (t *SGuestIsolatedDeviceSyncTask) delDeviceCallBack(opts []*isolated_device.HotUnplugOption, idx int, onDelFinish func(string)) {
  1003. if idx >= len(opts) {
  1004. onDelFinish("")
  1005. return
  1006. }
  1007. opt := opts[idx]
  1008. t.guest.Monitor.DeviceDel(opt.Id, func(err string) {
  1009. if err != "" {
  1010. onDelFinish(fmt.Sprintf("monitor del %d device: %s", idx, err))
  1011. return
  1012. }
  1013. t.delDeviceCallBack(opts, idx+1, onDelFinish)
  1014. })
  1015. }
  1016. /**
  1017. * GuestLiveMigrateTask
  1018. **/
  1019. type SGuestLiveMigrateTask struct {
  1020. *SKVMGuestInstance
  1021. ctx context.Context
  1022. params *SLiveMigrate
  1023. c chan struct{}
  1024. timeoutAt time.Time
  1025. doTimeoutMigrate bool
  1026. cancelled bool
  1027. expectDowntime int64
  1028. dirtySyncCount int64
  1029. diskDriverMirrorIndex int
  1030. onBlockJobsCancelled func()
  1031. totalTransferMb int64
  1032. }
  1033. func NewGuestLiveMigrateTask(
  1034. ctx context.Context, guest *SKVMGuestInstance, params *SLiveMigrate,
  1035. ) *SGuestLiveMigrateTask {
  1036. task := &SGuestLiveMigrateTask{SKVMGuestInstance: guest, ctx: ctx, params: params}
  1037. task.expectDowntime = 300 // qemu default downtime 300ms
  1038. task.MigrateTask = task
  1039. task.totalTransferMb = task.Desc.Mem
  1040. for i := 0; i < len(task.Desc.Disks); i++ {
  1041. if utils.IsInStringArray(task.Desc.Disks[i].StorageType, api.STORAGE_LOCAL_TYPES) {
  1042. task.totalTransferMb += int64(task.Desc.Disks[i].Size)
  1043. }
  1044. }
  1045. return task
  1046. }
  1047. func (s *SGuestLiveMigrateTask) Start() {
  1048. s.Monitor.MigrateSetCapability("zero-blocks", "on", s.onSetZeroBlocks)
  1049. }
  1050. func (s *SGuestLiveMigrateTask) onSetZeroBlocks(res string) {
  1051. if strings.Contains(strings.ToLower(res), "error") {
  1052. s.migrateFailed(fmt.Sprintf("Migrate set capability zero-blocks error: %s", res))
  1053. return
  1054. }
  1055. // https://wiki.qemu.org/Features/AutoconvergeLiveMigration
  1056. s.Monitor.MigrateSetCapability("auto-converge", "on", s.onSetAutoConverge)
  1057. }
  1058. func (s *SGuestLiveMigrateTask) onSetAutoConverge(res string) {
  1059. if strings.Contains(strings.ToLower(res), "error") {
  1060. s.migrateFailed(fmt.Sprintf("Migrate set capability zero-blocks error: %s", res))
  1061. return
  1062. }
  1063. s.Monitor.MigrateSetParameter("cpu-throttle-initial", options.HostOptions.LiveMigrateCpuThrottleInitial, s.onSetCpuThrottleInitial)
  1064. }
  1065. func (s *SGuestLiveMigrateTask) onSetCpuThrottleInitial(res string) {
  1066. if strings.Contains(strings.ToLower(res), "error") {
  1067. s.migrateFailed(fmt.Sprintf("Migrate set params cpu-throttle-initial error: %s", res))
  1068. return
  1069. }
  1070. s.Monitor.MigrateSetParameter("cpu-throttle-increment", options.HostOptions.LiveMigrateCpuThrottleIncrement, s.onSetCpuThrottleIncrement)
  1071. }
  1072. func (s *SGuestLiveMigrateTask) onSetCpuThrottleIncrement(res string) {
  1073. if strings.Contains(strings.ToLower(res), "error") {
  1074. s.migrateFailed(fmt.Sprintf("Migrate set params cpu-throttle-increment error: %s", res))
  1075. return
  1076. }
  1077. s.Monitor.MigrateSetCapability("events", "on", s.onMigrateEnableEvents)
  1078. }
  1079. func (s *SGuestLiveMigrateTask) onMigrateEnableEvents(res string) {
  1080. if strings.Contains(strings.ToLower(res), "error") {
  1081. s.migrateFailed(fmt.Sprintf("Migrate set capability events error: %s", res))
  1082. return
  1083. }
  1084. s.Monitor.MigrateSetCapability("pause-before-switchover", "on", s.onMigrateSetPauseBeforeSwitchover)
  1085. }
  1086. func (s *SGuestLiveMigrateTask) onMigrateSetPauseBeforeSwitchover(res string) {
  1087. if strings.Contains(strings.ToLower(res), "error") {
  1088. s.migrateFailed(fmt.Sprintf("Migrate set capability pause-before-switchover error: %s", res))
  1089. return
  1090. }
  1091. if version.LT(s.QemuVersion, "4.0.0") {
  1092. s.startMigrate()
  1093. return
  1094. }
  1095. if s.params.EnableTLS {
  1096. s.Monitor.MigrateSetCapability("multifd", "off", s.onSetMulitfd)
  1097. return
  1098. }
  1099. log.Infof("migrate src guest enable multifd")
  1100. s.Monitor.MigrateSetCapability("multifd", "on", s.onSetMulitfd)
  1101. }
  1102. func (s *SGuestLiveMigrateTask) onSetMulitfd(res string) {
  1103. if strings.Contains(strings.ToLower(res), "error") {
  1104. s.migrateFailed(fmt.Sprintf("Migrate set capability multifd error: %s", res))
  1105. return
  1106. }
  1107. s.startMigrate()
  1108. }
  1109. func (s *SGuestLiveMigrateTask) startRamMigrateTimeout() {
  1110. if !s.timeoutAt.IsZero() {
  1111. // timeout has been set
  1112. return
  1113. }
  1114. memMb := s.Desc.Mem
  1115. migSeconds := int(memMb) / options.HostOptions.MigrateExpectRate
  1116. if migSeconds < options.HostOptions.MinMigrateTimeoutSeconds {
  1117. migSeconds = options.HostOptions.MinMigrateTimeoutSeconds
  1118. }
  1119. s.timeoutAt = time.Now().Add(time.Second * time.Duration(migSeconds))
  1120. log.Infof("migrate timeout seconds: %d now: %v expectfinial: %v", migSeconds, time.Now(), s.timeoutAt)
  1121. }
  1122. func (s *SGuestLiveMigrateTask) startMigrate() {
  1123. if s.params.EnableTLS {
  1124. // https://wiki.qemu.org/Features/MigrationTLS
  1125. // first remove possible existing tls0
  1126. s.Monitor.ObjectDel("tls0", func(res string) {
  1127. log.Infof("cleanup possible existing tls0: %s", res)
  1128. s.Monitor.ObjectAdd("tls-creds-x509", map[string]string{
  1129. "dir": s.getPKIDirPath(),
  1130. "endpoint": "client",
  1131. "id": "tls0",
  1132. "verify-peer": "no",
  1133. }, func(res string) {
  1134. if strings.Contains(strings.ToLower(res), "error") {
  1135. s.migrateFailed(fmt.Sprintf("Migrate add tls-creds-x509 object client tls0 error: %s", res))
  1136. return
  1137. }
  1138. s.Monitor.MigrateSetParameter("tls-creds", "tls0", func(res string) {
  1139. if strings.Contains(strings.ToLower(res), "error") {
  1140. s.migrateFailed(fmt.Sprintf("Migrate set tls-creds tls0 error: %s", res))
  1141. return
  1142. }
  1143. s.doMigrate()
  1144. })
  1145. })
  1146. })
  1147. } else {
  1148. s.Monitor.MigrateSetParameter("tls-creds", "", func(res string) {
  1149. if strings.Contains(strings.ToLower(res), "error") {
  1150. s.migrateFailed(fmt.Sprintf("Migrate set tls-creds to empty error: %s", res))
  1151. return
  1152. }
  1153. s.doMigrate()
  1154. })
  1155. }
  1156. }
  1157. func (s *SGuestLiveMigrateTask) waitMirrorJobsReady() {
  1158. cb := func(jobs []monitor.BlockJob) {
  1159. var allReady = true
  1160. var remaining = s.Desc.Mem * 1024 * 1024
  1161. var mbps float64
  1162. for i := 0; i < len(jobs); i++ {
  1163. if jobs[i].Status != "ready" {
  1164. allReady = false
  1165. remaining += (jobs[i].Len - jobs[i].Offset)
  1166. mbps += float64(jobs[i].Speed) / 1024 / 1024
  1167. }
  1168. }
  1169. if !allReady {
  1170. progress := (1 - float64(remaining)/float64(s.totalTransferMb*1024*1024)) * 100.0
  1171. hostutils.UpdateServerProgress(context.Background(), s.Id, progress, mbps)
  1172. time.Sleep(time.Second * 3)
  1173. s.waitMirrorJobsReady()
  1174. return
  1175. }
  1176. s.Monitor.Migrate(fmt.Sprintf("tcp:%s", net.JoinHostPort(s.params.DestIp, strconv.Itoa(s.params.DestPort))),
  1177. false, false, s.setMaxBandwidth)
  1178. }
  1179. s.Monitor.GetBlockJobs(cb)
  1180. }
  1181. func (s *SGuestLiveMigrateTask) mirrorDisks(res string) {
  1182. if len(res) > 0 {
  1183. log.Errorf("disk %d driver mirror failed %s", s.diskDriverMirrorIndex, res)
  1184. s.onDriveMirrorDisksFailed(res)
  1185. return
  1186. }
  1187. if s.diskDriverMirrorIndex == len(s.Desc.Disks) {
  1188. s.waitMirrorJobsReady()
  1189. return
  1190. }
  1191. i := s.diskDriverMirrorIndex
  1192. s.diskDriverMirrorIndex += 1
  1193. storageType := s.Desc.Disks[i].StorageType
  1194. if storageType == "" {
  1195. storageType = storageman.GetManager().GetStorage(s.Desc.Disks[i].StorageId).StorageType()
  1196. }
  1197. if utils.IsInStringArray(storageType, api.STORAGE_LOCAL_TYPES) {
  1198. var drive = fmt.Sprintf("drive_%d", s.Desc.Disks[i].Index)
  1199. var target = fmt.Sprintf("nbd:%s:%d:exportname=drive_%d", s.params.DestIp, s.params.NbdServerPort, s.Desc.Disks[i].Index)
  1200. var speed int64 = 0
  1201. if s.params.MaxBandwidthMB != nil {
  1202. speed = *s.params.MaxBandwidthMB * 1024 * 1024
  1203. }
  1204. s.Monitor.DriveMirror(s.mirrorDisks, drive, target, "top", s.Desc.Disks[i].Format, true, false, speed)
  1205. } else {
  1206. s.mirrorDisks("")
  1207. }
  1208. }
  1209. func (s *SGuestLiveMigrateTask) onDriveMirrorDisksFailed(res string) {
  1210. s.migrateFailed(fmt.Sprintf("Migrate error: %s", res))
  1211. }
  1212. func (s *SGuestLiveMigrateTask) doMigrate() {
  1213. if s.params.NbdServerPort > 0 {
  1214. s.mirrorDisks("")
  1215. } else {
  1216. var copyIncremental = false
  1217. if s.params.IsLocal {
  1218. // copy disk data
  1219. copyIncremental = true
  1220. }
  1221. s.Monitor.Migrate(fmt.Sprintf("tcp:%s", net.JoinHostPort(s.params.DestIp, strconv.Itoa(s.params.DestPort))),
  1222. copyIncremental, false, s.setMaxBandwidth)
  1223. }
  1224. }
  1225. func (s *SGuestLiveMigrateTask) setMaxBandwidth(res string) {
  1226. if strings.Contains(strings.ToLower(res), "error") {
  1227. s.migrateFailed(fmt.Sprintf("Migrate set capability auto-converge error: %s", res))
  1228. return
  1229. }
  1230. // default set bandwidth no limit
  1231. var maxBandwidth int64 = math.MaxInt64
  1232. if s.params.MaxBandwidthMB != nil && *s.params.MaxBandwidthMB > 0 {
  1233. maxBandwidth = *s.params.MaxBandwidthMB * 1024 * 1024
  1234. }
  1235. s.Monitor.MigrateSetParameter("max-bandwidth", maxBandwidth, s.startMigrateStatusCheck)
  1236. }
  1237. func (s *SGuestLiveMigrateTask) startMigrateStatusCheck(res string) {
  1238. if strings.Contains(strings.ToLower(res), "error") {
  1239. s.migrateFailed(fmt.Sprintf("Migrate error: %s", res))
  1240. return
  1241. }
  1242. s.startRamMigrateTimeout()
  1243. s.c = make(chan struct{})
  1244. for s.c != nil {
  1245. select {
  1246. case <-s.c: // on c close
  1247. s.c = nil
  1248. break
  1249. case <-time.After(time.Second * 5):
  1250. if s.Monitor != nil {
  1251. s.Monitor.GetMigrateStats(s.onGetMigrateStats)
  1252. } else {
  1253. log.Errorf("server %s(%s) migrate stopped unexpectedly", s.GetId(), s.GetName())
  1254. s.migrateFailed(fmt.Sprintf("Migrate error: %s", res))
  1255. return
  1256. }
  1257. }
  1258. }
  1259. }
  1260. func (s *SGuestLiveMigrateTask) onGetMigrateStats(stats *monitor.MigrationInfo, err error) {
  1261. if err != nil {
  1262. log.Errorf("%s get migrate stats failed %s", s.GetName(), err)
  1263. s.migrateFailed(fmt.Sprintf("%s get migrate stats failed %s", s.GetName(), err))
  1264. return
  1265. }
  1266. s.onGetMigrateStatus(stats)
  1267. }
  1268. /*
  1269. { 'enum': 'MigrationStatus',
  1270. 'data': [ 'none', 'setup', 'cancelling', 'cancelled',
  1271. 'active', 'postcopy-active', 'postcopy-paused',
  1272. 'postcopy-recover', 'completed', 'failed', 'colo',
  1273. 'pre-switchover', 'device', 'wait-unplug' ] }
  1274. */
  1275. func (s *SGuestLiveMigrateTask) onGetMigrateStatus(stats *monitor.MigrationInfo) {
  1276. status := string(*stats.Status)
  1277. if status == "completed" {
  1278. jsonStats := jsonutils.Marshal(stats)
  1279. log.Infof("migration info %s", jsonStats)
  1280. } else if status == "failed" {
  1281. s.migrateFailed(fmt.Sprintf("Query migrate got status: %s", status))
  1282. } else if status == "cancelled" {
  1283. s.migrateFailed(status)
  1284. } else if status == "active" {
  1285. if !s.doTimeoutMigrate && s.timeoutAt.Before(time.Now()) {
  1286. s.Monitor.SimpleCommand("stop", s.onMigrateStartPostcopy)
  1287. s.doTimeoutMigrate = true
  1288. }
  1289. if s.doTimeoutMigrate {
  1290. return
  1291. }
  1292. var (
  1293. ramRemain int64
  1294. mbps float64
  1295. )
  1296. if stats.RAM != nil {
  1297. mbps = stats.RAM.Mbps
  1298. ramRemain = stats.RAM.Remaining
  1299. }
  1300. if ramRemain > 0 {
  1301. progress := (1 - float64(ramRemain)/float64(s.totalTransferMb*1024*1024)) * 100.0
  1302. hostutils.UpdateServerProgress(context.Background(), s.Id, progress, mbps)
  1303. }
  1304. if s.params.QuicklyFinish && stats.RAM != nil && stats.RAM.Remaining > 0 {
  1305. if stats.CPUThrottlePercentage == nil {
  1306. // qemu do not enable cpu throttle, don't need set downtime
  1307. return
  1308. }
  1309. if *stats.CPUThrottlePercentage < options.HostOptions.LiveMigrateCpuThrottleMax {
  1310. return
  1311. }
  1312. if stats.ExpectedDowntime != nil && *stats.ExpectedDowntime > s.expectDowntime {
  1313. if s.dirtySyncCount == 0 {
  1314. // record dirty sync count
  1315. s.dirtySyncCount = stats.RAM.DirtySyncCount
  1316. return
  1317. }
  1318. // run more than one round dirty ram sync after cpu throttle 99%
  1319. if stats.RAM.DirtySyncCount <= s.dirtySyncCount+1 {
  1320. return
  1321. }
  1322. cb := func(res string) {
  1323. if len(res) == 0 {
  1324. s.expectDowntime = *stats.ExpectedDowntime
  1325. log.Infof("migrate update downtime to %d", *stats.ExpectedDowntime)
  1326. } else {
  1327. log.Errorf("failed set migrate downtime %s", res)
  1328. }
  1329. }
  1330. s.Monitor.MigrateSetDowntime(float64(*stats.ExpectedDowntime)/1000.0, cb)
  1331. }
  1332. }
  1333. }
  1334. }
  1335. func (s *SGuestLiveMigrateTask) onMigrateStartPostcopy(res string) {
  1336. if strings.Contains(strings.ToLower(res), "error") {
  1337. s.migrateFailed(fmt.Sprintf("onMigrateStartPostcopy error: %s", res))
  1338. return
  1339. } else {
  1340. log.Infof("onMigrateStartPostcopy success")
  1341. }
  1342. }
  1343. func (s *SGuestLiveMigrateTask) migrateContinueFromPreSwitchover() {
  1344. s.Monitor.MigrateContinue("pre-switchover", s.onMigrateContinue)
  1345. }
  1346. func (s *SGuestLiveMigrateTask) onMigrateContinue(res string) {
  1347. if len(res) > 0 {
  1348. s.migrateFailed(res)
  1349. }
  1350. }
  1351. func (s *SGuestLiveMigrateTask) onMigrateReceivedPreSwitchoverEvent() {
  1352. s.onBlockJobsCancelled = s.migrateContinueFromPreSwitchover
  1353. s.cancelBlockJobs("")
  1354. }
  1355. func (s *SGuestLiveMigrateTask) onMigrateReceivedBlockJobError(res string) {
  1356. if !s.cancelled {
  1357. s.migrateFailed(res)
  1358. }
  1359. }
  1360. func (s *SGuestLiveMigrateTask) migrateComplete(stats jsonutils.JSONObject) {
  1361. s.MigrateTask = nil
  1362. if s.c != nil {
  1363. close(s.c)
  1364. s.c = nil
  1365. }
  1366. s.Monitor.Disconnect()
  1367. s.Monitor = nil
  1368. res := jsonutils.NewDict()
  1369. if stats != nil {
  1370. res.Set("migration_info", stats)
  1371. }
  1372. hostutils.TaskComplete(s.ctx, res)
  1373. hostutils.UpdateServerProgress(context.Background(), s.Id, 0.0, 0)
  1374. }
  1375. func (s *SGuestLiveMigrateTask) cancelBlockJobs(res string) {
  1376. log.Infof("%s cancel block jobs %s", s.GetName(), res)
  1377. if s.diskDriverMirrorIndex == 0 {
  1378. s.onBlockJobsCancelled()
  1379. return
  1380. }
  1381. s.diskDriverMirrorIndex -= 1
  1382. i := s.diskDriverMirrorIndex
  1383. if utils.IsInStringArray(s.Desc.Disks[i].StorageType, api.STORAGE_LOCAL_TYPES) {
  1384. s.Monitor.CancelBlockJob(fmt.Sprintf("drive_%d", s.Desc.Disks[i].Index), false, s.cancelBlockJobs)
  1385. } else {
  1386. s.cancelBlockJobs("")
  1387. }
  1388. }
  1389. func (s *SGuestLiveMigrateTask) migrateFailed(msg string) {
  1390. s.onBlockJobsCancelled = func() {
  1391. s.onMigrateFailBlockJobsCancelled(msg)
  1392. }
  1393. s.cancelBlockJobs("")
  1394. }
  1395. func (s *SGuestLiveMigrateTask) onMigrateFailBlockJobsCancelled(msg string) {
  1396. cleanup := func() {
  1397. s.MigrateTask = nil
  1398. if s.c != nil {
  1399. close(s.c)
  1400. s.c = nil
  1401. }
  1402. hostutils.TaskFailed(s.ctx, msg)
  1403. }
  1404. if s.params.EnableTLS {
  1405. s.Monitor.ObjectDel("tls0", func(res string) {
  1406. log.Infof("cleanup possible existing tls0: %s", res)
  1407. cleanup()
  1408. })
  1409. } else {
  1410. cleanup()
  1411. }
  1412. }
  1413. func (s *SGuestLiveMigrateTask) SetLiveMigrateCancelled() {
  1414. s.cancelled = true
  1415. }
  1416. /**
  1417. * GuestResumeTask
  1418. **/
  1419. type SGuestResumeTask struct {
  1420. *SKVMGuestInstance
  1421. ctx context.Context
  1422. startTime time.Time
  1423. isTimeout bool
  1424. cleanTLS bool
  1425. resumed bool
  1426. isResumeFromMigrate bool
  1427. getTaskData func() (jsonutils.JSONObject, error)
  1428. }
  1429. func NewGuestResumeTask(ctx context.Context, s *SKVMGuestInstance, isTimeout bool, cleanTLS bool) *SGuestResumeTask {
  1430. return &SGuestResumeTask{
  1431. SKVMGuestInstance: s,
  1432. ctx: ctx,
  1433. isTimeout: isTimeout,
  1434. cleanTLS: cleanTLS,
  1435. getTaskData: nil,
  1436. }
  1437. }
  1438. func (s *SGuestResumeTask) Start() {
  1439. log.Debugf("[%s] GuestResumeTask start", s.GetId())
  1440. s.startTime = time.Now()
  1441. if s.cleanTLS {
  1442. s.Monitor.ObjectDel("tls0", func(res string) {
  1443. log.Infof("Clean %s tls0 object: %s", s.GetName(), res)
  1444. pkiPath := s.getPKIDirPath()
  1445. if err := os.RemoveAll(pkiPath); err != nil {
  1446. log.Warningf("Remove tls pki dir %s error: %v", pkiPath, err)
  1447. }
  1448. s.confirmRunning()
  1449. })
  1450. return
  1451. }
  1452. s.confirmRunning()
  1453. }
  1454. func (s *SGuestResumeTask) GetStateFilePath() string {
  1455. return s.SKVMGuestInstance.GetStateFilePath("")
  1456. }
  1457. func (s *SGuestResumeTask) Stop() {
  1458. // TODO
  1459. // stop stream disk
  1460. s.taskFailed(fmt.Sprintf("[%s] qemu quit unexpectedly on resume", s.GetId()))
  1461. }
  1462. func (s *SGuestResumeTask) confirmRunning() {
  1463. if s.Monitor != nil {
  1464. s.Monitor.QueryStatus(s.onConfirmRunning)
  1465. } else {
  1466. s.taskFailed(fmt.Sprintf("[%s] qemu quit unexpectedly on resume confirmRunning", s.GetId()))
  1467. }
  1468. }
  1469. func (s *SGuestResumeTask) onConfirmRunning(status string) {
  1470. log.Infof("[%s] onConfirmRunning status %s", s.GetId(), status)
  1471. switch status {
  1472. case "paused (prelaunch)":
  1473. /* ref: qemu/src/qapi/run-state.json
  1474. * prelaunch: QEMU was started with -S and guest has not started.
  1475. * we need resume guest at state prelaunch */
  1476. if err := s.onGuestPrelaunch(); err != nil {
  1477. s.ForceStop()
  1478. s.taskFailed(err.Error())
  1479. return
  1480. }
  1481. s.resumeGuest()
  1482. case "running", "paused (suspended)":
  1483. s.onStartRunning()
  1484. case "paused (postmigrate)":
  1485. s.isResumeFromMigrate = true
  1486. s.resumeGuest()
  1487. case "paused (inmigrate)":
  1488. // guest is paused waiting for an incoming migration
  1489. time.Sleep(time.Second * 1)
  1490. s.confirmRunning()
  1491. default:
  1492. switch {
  1493. case strings.Contains(status, "error"):
  1494. // handle error first, results may be 'paused (internal-error)'
  1495. s.taskFailed(status)
  1496. case strings.Contains(status, "paused"):
  1497. if s.resumed {
  1498. s.taskFailed("resume guest twice")
  1499. return
  1500. }
  1501. if err := s.onGuestPrelaunch(); err != nil {
  1502. s.ForceStop()
  1503. s.taskFailed(err.Error())
  1504. return
  1505. }
  1506. s.Monitor.GetBlocks(s.onGetBlockInfo)
  1507. default:
  1508. memMb := s.Desc.Mem
  1509. migSeconds := int(memMb) / options.HostOptions.MigrateExpectRate
  1510. if migSeconds < options.HostOptions.MinMigrateTimeoutSeconds {
  1511. migSeconds = options.HostOptions.MinMigrateTimeoutSeconds
  1512. }
  1513. log.Infof("start guest timeout seconds: %d", migSeconds)
  1514. if s.isTimeout && time.Now().Sub(s.startTime) >= time.Second*time.Duration(migSeconds) {
  1515. s.taskFailed("Timeout")
  1516. return
  1517. } else {
  1518. time.Sleep(time.Second * 3)
  1519. s.confirmRunning()
  1520. }
  1521. }
  1522. }
  1523. }
  1524. func (s *SGuestResumeTask) taskFailed(reason string) {
  1525. log.Infof("Start guest %s failed: %s", s.Id, reason)
  1526. s.ForceStop()
  1527. if s.ctx != nil && len(appctx.AppContextTaskId(s.ctx)) > 0 {
  1528. hostutils.TaskFailed(s.ctx, reason)
  1529. } else {
  1530. s.SyncStatus(reason)
  1531. }
  1532. }
  1533. func (s *SGuestResumeTask) onGetBlockInfo(blocks []monitor.QemuBlock) {
  1534. log.Debugf("onGetBlockInfo %v", blocks)
  1535. // for _, drv := range results.GetArray() {
  1536. // // encryption not work
  1537. // }
  1538. //time.Sleep(time.Second * 1)
  1539. s.resumeGuest()
  1540. }
  1541. func (s *SGuestResumeTask) resumeGuest() {
  1542. if s.resumed {
  1543. s.taskFailed("resume guest twice")
  1544. return
  1545. }
  1546. if s.Desc.IsVolatileHost {
  1547. if err := s.prepareNicsForVolatileGuestResume(); err != nil {
  1548. s.taskFailed(err.Error())
  1549. return
  1550. }
  1551. s.Desc.IsVolatileHost = false
  1552. SaveLiveDesc(s, s.Desc)
  1553. }
  1554. s.startTime = time.Now()
  1555. s.Monitor.SimpleCommand("cont", s.onResumeSucc)
  1556. }
  1557. func (s *SGuestResumeTask) onResumeSucc(res string) {
  1558. s.resumed = true
  1559. s.confirmRunning()
  1560. }
  1561. func (s *SGuestResumeTask) SetGetTaskData(f func() (jsonutils.JSONObject, error)) {
  1562. s.getTaskData = f
  1563. }
  1564. func (s *SGuestResumeTask) onStartRunning() {
  1565. if s.Desc.IsVolatileHost {
  1566. s.Desc.IsVolatileHost = false
  1567. SaveLiveDesc(s, s.Desc)
  1568. }
  1569. s.setCgroupPid()
  1570. s.removeStatefile()
  1571. if s.ctx != nil && len(appctx.AppContextTaskId(s.ctx)) > 0 {
  1572. var (
  1573. data jsonutils.JSONObject
  1574. err error
  1575. )
  1576. if s.getTaskData != nil {
  1577. data, err = s.getTaskData()
  1578. if err != nil {
  1579. s.taskFailed(err.Error())
  1580. return
  1581. }
  1582. }
  1583. hostutils.TaskComplete(s.ctx, data)
  1584. if s.isResumeFromMigrate {
  1585. return
  1586. }
  1587. }
  1588. disksIdx := s.GetNeedMergeBackingFileDiskIndexs()
  1589. if len(disksIdx) > 0 {
  1590. s.startStreamDisks(disksIdx)
  1591. //s.SyncStatus("")
  1592. } else if options.HostOptions.AutoMergeBackingTemplate {
  1593. s.SyncStatus("")
  1594. timeutils2.AddTimeout(
  1595. time.Second*time.Duration(options.HostOptions.AutoMergeDelaySeconds),
  1596. func() { s.startStreamDisks(nil) })
  1597. } else {
  1598. s.SyncStatus("")
  1599. s.detachStartupTask()
  1600. }
  1601. }
  1602. func (s *SGuestResumeTask) startStreamDisks(disksIdx []int) {
  1603. s.startTime = time.Time{}
  1604. s.detachStartupTask()
  1605. if s.IsMonitorAlive() {
  1606. s.StreamDisks(s.ctx, func() { s.onStreamComplete(disksIdx) }, disksIdx, -1, -1)
  1607. }
  1608. }
  1609. func (s *SGuestResumeTask) onStreamComplete(disksIdx []int) {
  1610. if len(disksIdx) == 0 {
  1611. // if disks idx length == 0 indicate merge backing template
  1612. s.SyncStatus("")
  1613. } else {
  1614. s.streamDisksComplete(context.Background())
  1615. }
  1616. }
  1617. func (s *SGuestResumeTask) removeStatefile() {
  1618. go s.CleanStatefiles()
  1619. }
  1620. type IGuestBlockProgressTask interface {
  1621. OnGetBlockJobs(jobs []monitor.BlockJob)
  1622. StreamingDiskCompletedCount() int
  1623. StreamingDiskCount() int
  1624. }
  1625. type SGuestBlockProgressBaseTask struct {
  1626. *SKVMGuestInstance
  1627. ctx context.Context
  1628. totalSizeMb int
  1629. completedSizeMb int
  1630. c chan struct{}
  1631. jobs map[string]monitor.BlockJob
  1632. task IGuestBlockProgressTask
  1633. }
  1634. func NewGuestBlockProgressBaseTask(
  1635. ctx context.Context, guest *SKVMGuestInstance, blkTask IGuestBlockProgressTask,
  1636. ) *SGuestBlockProgressBaseTask {
  1637. return &SGuestBlockProgressBaseTask{
  1638. SKVMGuestInstance: guest,
  1639. ctx: ctx,
  1640. task: blkTask,
  1641. jobs: map[string]monitor.BlockJob{},
  1642. }
  1643. }
  1644. func (s *SGuestBlockProgressBaseTask) startWaitBlockJob(res string) {
  1645. s.c = make(chan struct{})
  1646. for {
  1647. select {
  1648. case <-s.c:
  1649. s.c = nil
  1650. return
  1651. case <-time.After(time.Second * 10):
  1652. s.Monitor.GetBlockJobs(s.onGetBlockJobs)
  1653. }
  1654. }
  1655. }
  1656. func (s *SGuestBlockProgressBaseTask) onGetBlockJobs(jobs []monitor.BlockJob) {
  1657. if len(jobs) == 0 && s.c != nil {
  1658. close(s.c)
  1659. s.c = nil
  1660. }
  1661. for i := range jobs {
  1662. job := jobs[i]
  1663. _job, ok := s.jobs[job.Device]
  1664. if !ok {
  1665. job.CalcOffset(0)
  1666. s.jobs[job.Device] = job
  1667. continue
  1668. }
  1669. if _job.Status == "ready" {
  1670. delete(s.jobs, _job.Device)
  1671. continue
  1672. }
  1673. job.Start, job.Now = _job.Start, _job.Now
  1674. job.CalcOffset(_job.Offset)
  1675. s.jobs[job.Device] = job
  1676. }
  1677. mbps, progress := 0.0, 0.0
  1678. totalSize, totalOffset := int64(1), int64(0)
  1679. for _, job := range s.jobs {
  1680. mbps += job.SpeedMbps
  1681. totalSize += job.Len
  1682. totalOffset += job.Offset
  1683. }
  1684. if len(s.jobs) == 0 && len(jobs) == 0 {
  1685. progress = 100.0
  1686. } else {
  1687. progress = float64(totalOffset) / float64(totalSize) * 100
  1688. }
  1689. diskCount := s.task.StreamingDiskCount()
  1690. streamedDiskCount := s.task.StreamingDiskCompletedCount()
  1691. if diskCount > 0 {
  1692. progress = float64(streamedDiskCount)/float64(diskCount)*100.0 + 1.0/float64(diskCount)*progress
  1693. log.Debugf("stream disk111111 progress %v, streamedDiskCount %v, diskCount %v ", progress, streamedDiskCount, diskCount)
  1694. }
  1695. hostutils.UpdateServerProgress(context.Background(), s.GetId(), progress, mbps)
  1696. s.task.OnGetBlockJobs(jobs)
  1697. }
  1698. func (s *SGuestBlockProgressBaseTask) cancelWaitBlockJobs() {
  1699. if s.c != nil {
  1700. close(s.c)
  1701. s.c = nil
  1702. }
  1703. }
  1704. /**
  1705. * GuestStreamDisksTask
  1706. **/
  1707. type SGuestStreamDisksTask struct {
  1708. *SGuestBlockProgressBaseTask
  1709. callback func()
  1710. disksIdx []int
  1711. c chan struct{}
  1712. streamDevs []string
  1713. lvmBacking []string
  1714. progressTotalDiskCnt int
  1715. progressCompletedDiskCnt int
  1716. }
  1717. func NewGuestStreamDisksTask(ctx context.Context, guest *SKVMGuestInstance, callback func(), disksIdx []int, totalCnt, completedCnt int) *SGuestStreamDisksTask {
  1718. task := &SGuestStreamDisksTask{
  1719. callback: callback,
  1720. disksIdx: disksIdx,
  1721. progressTotalDiskCnt: totalCnt,
  1722. progressCompletedDiskCnt: completedCnt,
  1723. }
  1724. task.SGuestBlockProgressBaseTask = NewGuestBlockProgressBaseTask(ctx, guest, task)
  1725. return task
  1726. }
  1727. func (s *SGuestStreamDisksTask) Start() {
  1728. s.Monitor.GetBlockJobCounts(s.onInitCheckStreamJobs)
  1729. }
  1730. func (s *SGuestStreamDisksTask) onInitCheckStreamJobs(jobs int) {
  1731. if jobs > 0 {
  1732. log.Warningf("GuestStreamDisksTask: duplicate block streaming???")
  1733. s.startWaitBlockJob("")
  1734. } else if jobs == 0 {
  1735. s.startBlockStreaming()
  1736. }
  1737. }
  1738. func (s *SGuestStreamDisksTask) startBlockStreaming() {
  1739. s.checkBlockDrives()
  1740. }
  1741. func (s *SGuestStreamDisksTask) checkBlockDrives() {
  1742. s.Monitor.GetBlocks(s.onBlockDrivesSucc)
  1743. }
  1744. func (s *SGuestStreamDisksTask) onBlockDrivesSucc(blocks []monitor.QemuBlock) {
  1745. s.streamDevs = []string{}
  1746. s.lvmBacking = []string{}
  1747. for _, block := range blocks {
  1748. if len(block.Inserted.File) > 0 && len(block.Inserted.BackingFile) > 0 {
  1749. var stream = false
  1750. idx := block.Device[len(block.Device)-1] - '0'
  1751. for i := 0; i < len(s.disksIdx); i++ {
  1752. if int(idx) == s.disksIdx[i] {
  1753. stream = true
  1754. }
  1755. }
  1756. if !stream {
  1757. continue
  1758. }
  1759. s.streamDevs = append(s.streamDevs, block.Device)
  1760. disk, err := storageman.GetManager().GetDiskByPath(block.Inserted.File)
  1761. if err == nil && disk.GetType() == api.STORAGE_SLVM {
  1762. s.lvmBacking = append(s.lvmBacking, block.Inserted.BackingFile)
  1763. } else {
  1764. log.Errorf("failed get disk by path %s: %s", block.Inserted.File, err)
  1765. }
  1766. }
  1767. }
  1768. log.Infof("Stream devices %s: %v , backingfiles %v", s.GetName(), s.streamDevs, s.lvmBacking)
  1769. if len(s.streamDevs) == 0 {
  1770. s.taskComplete()
  1771. } else {
  1772. s.startDoBlockStream()
  1773. s.SyncStatus("")
  1774. }
  1775. }
  1776. func (s *SGuestStreamDisksTask) startDoBlockStream() {
  1777. if len(s.streamDevs) > 0 {
  1778. dev := s.streamDevs[0]
  1779. s.streamDevs = s.streamDevs[1:]
  1780. s.Monitor.BlockStream(dev, s.startWaitBlockJob)
  1781. } else {
  1782. s.taskComplete()
  1783. }
  1784. }
  1785. func (s *SGuestStreamDisksTask) StreamingDiskCompletedCount() int {
  1786. completedCnt := len(s.disksIdx) - len(s.streamDevs) - 1
  1787. if s.progressCompletedDiskCnt > 0 {
  1788. completedCnt += s.progressCompletedDiskCnt
  1789. }
  1790. return completedCnt
  1791. }
  1792. func (s *SGuestStreamDisksTask) StreamingDiskCount() int {
  1793. if s.progressTotalDiskCnt > 0 {
  1794. return s.progressTotalDiskCnt
  1795. }
  1796. return len(s.disksIdx)
  1797. }
  1798. func (s *SGuestStreamDisksTask) OnGetBlockJobs(jobs []monitor.BlockJob) {
  1799. if len(jobs) == 0 {
  1800. s.cancelWaitBlockJobs()
  1801. if s.streamDevs == nil {
  1802. s.checkBlockDrives()
  1803. } else {
  1804. s.startDoBlockStream()
  1805. }
  1806. }
  1807. }
  1808. func (s *SGuestStreamDisksTask) deactivateLvmBackingFile() {
  1809. for _, lvPath := range s.lvmBacking {
  1810. storageman.TryDeactivateBackingLvs(lvPath)
  1811. }
  1812. }
  1813. func (s *SGuestStreamDisksTask) taskComplete() {
  1814. s.deactivateLvmBackingFile()
  1815. hostutils.UpdateServerProgress(context.Background(), s.Id, 100.0, 0.0)
  1816. s.SyncStatus("Guest Disks Block Stream Complete")
  1817. if s.callback != nil {
  1818. s.callback()
  1819. }
  1820. }
  1821. /**
  1822. * GuestReloadDiskTask
  1823. **/
  1824. type SGuestReloadDiskTask struct {
  1825. *SKVMGuestInstance
  1826. ctx context.Context
  1827. disk storageman.IDisk
  1828. }
  1829. func NewGuestReloadDiskTask(
  1830. ctx context.Context, s *SKVMGuestInstance, disk storageman.IDisk,
  1831. ) *SGuestReloadDiskTask {
  1832. return &SGuestReloadDiskTask{
  1833. SKVMGuestInstance: s,
  1834. ctx: ctx,
  1835. disk: disk,
  1836. }
  1837. }
  1838. func (s *SGuestReloadDiskTask) WaitSnapshotReplaced(callback func()) error {
  1839. var retry = 0
  1840. for {
  1841. retry += 1
  1842. if retry == 300 {
  1843. return fmt.Errorf(
  1844. "SnapshotDeleteJob.deleting_disk_snapshot always has %s", s.disk.GetId())
  1845. }
  1846. if _, ok := storageman.DELETEING_SNAPSHOTS.Load(s.disk.GetId()); ok {
  1847. time.Sleep(time.Second * 1)
  1848. } else {
  1849. break
  1850. }
  1851. }
  1852. callback()
  1853. return nil
  1854. }
  1855. func (s *SGuestReloadDiskTask) Start() {
  1856. s.fetchDisksInfo(s.startReloadDisk)
  1857. }
  1858. func (s *SGuestReloadDiskTask) fetchDisksInfo(callback func(string)) {
  1859. s.Monitor.GetBlocks(func(blocks []monitor.QemuBlock) { s.onGetBlocksSucc(blocks, callback) })
  1860. }
  1861. func (s *SGuestReloadDiskTask) onGetBlocksSucc(blocks []monitor.QemuBlock, callback func(string)) {
  1862. var device string
  1863. for i := range blocks {
  1864. device = s.getDiskOfDrive(blocks[i])
  1865. if len(device) > 0 {
  1866. callback(device)
  1867. break
  1868. }
  1869. }
  1870. if len(device) == 0 {
  1871. s.taskFailed("Device not found")
  1872. }
  1873. }
  1874. func (s *SGuestReloadDiskTask) getDiskOfDrive(block monitor.QemuBlock) string {
  1875. if len(block.Inserted.File) == 0 {
  1876. return ""
  1877. }
  1878. filePath, err := qemuimg.ParseQemuFilepath(block.Inserted.File)
  1879. if err != nil {
  1880. log.Errorf("qemuimg.ParseQemuFilepath %s fail %s", block.Inserted.File, err)
  1881. return ""
  1882. }
  1883. if filePath == s.disk.GetPath() {
  1884. return block.Device
  1885. }
  1886. return ""
  1887. }
  1888. func (s *SGuestReloadDiskTask) startReloadDisk(device string) {
  1889. s.doReloadDisk(device, s.onReloadSucc)
  1890. }
  1891. func (s *SGuestReloadDiskTask) doReloadDisk(device string, callback func(string)) {
  1892. s.Monitor.SimpleCommand("stop", func(string) {
  1893. path := s.disk.GetPath()
  1894. if s.isEncrypted() {
  1895. path = qemuimg.GetQemuFilepath(path, "sec0", qemuimg.EncryptFormatLuks)
  1896. }
  1897. s.Monitor.ReloadDiskBlkdev(device, path, callback)
  1898. })
  1899. }
  1900. func (s *SGuestReloadDiskTask) onReloadSucc(err string) {
  1901. if len(err) > 0 {
  1902. log.Errorf("monitor new snapshot blkdev error: %s", err)
  1903. }
  1904. s.Monitor.SimpleCommand("cont", s.onResumeSucc)
  1905. }
  1906. func (s *SGuestReloadDiskTask) onResumeSucc(results string) {
  1907. log.Infof("guest reload disk task resume succ %s", results)
  1908. params := jsonutils.NewDict()
  1909. params.Set("reopen", jsonutils.JSONTrue)
  1910. hostutils.TaskComplete(s.ctx, params)
  1911. }
  1912. func (s *SGuestReloadDiskTask) taskFailed(reason string) {
  1913. hostutils.TaskFailed(s.ctx, reason)
  1914. }
  1915. /**
  1916. * GuestDiskSnapshotTask
  1917. **/
  1918. type SGuestDiskSnapshotTask struct {
  1919. *SGuestReloadDiskTask
  1920. snapshotId string
  1921. }
  1922. func NewGuestDiskSnapshotTask(
  1923. ctx context.Context, s *SKVMGuestInstance, disk storageman.IDisk, snapshotId string,
  1924. ) *SGuestDiskSnapshotTask {
  1925. return &SGuestDiskSnapshotTask{
  1926. SGuestReloadDiskTask: NewGuestReloadDiskTask(ctx, s, disk),
  1927. snapshotId: snapshotId,
  1928. }
  1929. }
  1930. func (s *SGuestDiskSnapshotTask) Start() {
  1931. s.fetchDisksInfo(s.startSnapshot)
  1932. }
  1933. func (s *SGuestDiskSnapshotTask) startSnapshot(device string) {
  1934. s.doReloadDisk(device, s.onReloadBlkdevSucc)
  1935. }
  1936. func (s *SGuestDiskSnapshotTask) onReloadBlkdevSucc(res string) {
  1937. var cb = s.onResumeSucc
  1938. if len(res) > 0 {
  1939. cb = func(string) {
  1940. s.onSnapshotBlkdevFail(fmt.Sprintf("onReloadBlkdevFail: %s", res))
  1941. }
  1942. }
  1943. s.Monitor.SimpleCommand("cont", cb)
  1944. }
  1945. func (s *SGuestDiskSnapshotTask) onSnapshotBlkdevFail(reason string) {
  1946. // rollback snapshot to disk file
  1947. if err := s.disk.RollbackDiskOnSnapshotFail(s.snapshotId); err != nil {
  1948. log.Errorf("failed do rollback %s", err)
  1949. }
  1950. hostutils.TaskFailed(s.ctx, fmt.Sprintf("Reload blkdev error: %s", reason))
  1951. }
  1952. func (s *SGuestDiskSnapshotTask) onResumeSucc(res string) {
  1953. log.Infof("guest disk snapshot task resume succ %s", res)
  1954. snapshotLocation := path.Join(s.disk.GetSnapshotLocation(), s.snapshotId)
  1955. body := jsonutils.NewDict()
  1956. body.Set("location", jsonutils.NewString(snapshotLocation))
  1957. hostutils.TaskComplete(s.ctx, body)
  1958. }
  1959. /**
  1960. * GuestSnapshotDeleteTask
  1961. **/
  1962. type SGuestSnapshotDeleteTask struct {
  1963. *SGuestReloadDiskTask
  1964. deleteSnapshot string
  1965. convertSnapshot string
  1966. blockStream bool
  1967. encryptInfo apis.SEncryptInfo
  1968. tmpPath string
  1969. delSnapshotPathAfterReload func() error
  1970. }
  1971. func NewGuestSnapshotDeleteTask(
  1972. ctx context.Context, s *SKVMGuestInstance, disk storageman.IDisk,
  1973. deleteSnapshot, convertSnapshot string, blockStream bool, encryptInfo apis.SEncryptInfo,
  1974. ) *SGuestSnapshotDeleteTask {
  1975. return &SGuestSnapshotDeleteTask{
  1976. SGuestReloadDiskTask: NewGuestReloadDiskTask(ctx, s, disk),
  1977. deleteSnapshot: deleteSnapshot,
  1978. convertSnapshot: convertSnapshot,
  1979. blockStream: blockStream,
  1980. encryptInfo: encryptInfo,
  1981. }
  1982. }
  1983. func (s *SGuestSnapshotDeleteTask) Start(totalDeleteSnapshotCount, deletedSnapshotCount int) {
  1984. if s.blockStream {
  1985. s.startBlockStream(totalDeleteSnapshotCount, deletedSnapshotCount)
  1986. return
  1987. }
  1988. cb, err := s.disk.ConvertSnapshotRelyOnReloadDisk(s.convertSnapshot, s.encryptInfo)
  1989. if err != nil {
  1990. s.taskFailed(err.Error())
  1991. return
  1992. }
  1993. s.delSnapshotPathAfterReload = cb
  1994. s.fetchDisksInfo(s.doReloadDisk)
  1995. }
  1996. func (s *SGuestSnapshotDeleteTask) startBlockStream(totalDeleteSnapshotCount, deletedSnapshotCount int) {
  1997. diskIdx := []int{}
  1998. for i := range s.Desc.Disks {
  1999. if s.Desc.Disks[i].DiskId == s.disk.GetId() {
  2000. diskIdx = append(diskIdx, int(s.Desc.Disks[i].Index))
  2001. break
  2002. }
  2003. }
  2004. s.StreamDisks(s.ctx, s.onStreamDiskComplete, diskIdx, totalDeleteSnapshotCount, deletedSnapshotCount)
  2005. }
  2006. func (s *SGuestSnapshotDeleteTask) onStreamDiskComplete() {
  2007. // remove snapshot file
  2008. if err := s.disk.DoDeleteSnapshot(s.deleteSnapshot); err != nil {
  2009. hostutils.TaskFailed(s.ctx, err.Error())
  2010. return
  2011. }
  2012. body := jsonutils.NewDict()
  2013. body.Set("deleted", jsonutils.JSONTrue)
  2014. hostutils.TaskComplete(s.ctx, body)
  2015. }
  2016. func (s *SGuestSnapshotDeleteTask) doReloadDisk(device string) {
  2017. s.SGuestReloadDiskTask.doReloadDisk(device, s.onReloadBlkdevSucc)
  2018. }
  2019. func (s *SGuestSnapshotDeleteTask) onReloadBlkdevSucc(err string) {
  2020. if s.delSnapshotPathAfterReload != nil {
  2021. if e := s.delSnapshotPathAfterReload(); e != nil {
  2022. log.Errorf("failed do delSnapshotPathAfterReload: %s", e)
  2023. }
  2024. }
  2025. var callback = s.onResumeSucc
  2026. if len(err) > 0 {
  2027. callback = func(string) {
  2028. s.onSnapshotBlkdevFail(fmt.Sprintf("onReloadBlkdevFail %s", err))
  2029. }
  2030. }
  2031. s.Monitor.SimpleCommand("cont", callback)
  2032. }
  2033. func (s *SGuestSnapshotDeleteTask) onSnapshotBlkdevFail(res string) {
  2034. snapshotPath := path.Join(s.disk.GetSnapshotDir(), s.convertSnapshot)
  2035. if output, err := procutils.NewCommand("mv", "-f", s.tmpPath, snapshotPath).Output(); err != nil {
  2036. log.Errorf("mv %s to %s failed: %s, %s", s.tmpPath, snapshotPath, err, output)
  2037. }
  2038. s.taskFailed(fmt.Sprintf("Reload blkdev failed %s", res))
  2039. }
  2040. func (s *SGuestSnapshotDeleteTask) onResumeSucc(res string) {
  2041. log.Infof("guest do new snapshot task resume succ %s", res)
  2042. if len(s.tmpPath) > 0 {
  2043. output, err := procutils.NewCommand("rm", "-f", s.tmpPath).Output()
  2044. if err != nil {
  2045. log.Errorf("rm %s failed: %s, %s", s.tmpPath, err, output)
  2046. }
  2047. }
  2048. s.disk.DoDeleteSnapshot(s.deleteSnapshot)
  2049. body := jsonutils.NewDict()
  2050. body.Set("deleted", jsonutils.JSONTrue)
  2051. hostutils.TaskComplete(s.ctx, body)
  2052. }
  2053. /**
  2054. * GuestDriveMirrorTask
  2055. **/
  2056. type SDriveMirrorTask struct {
  2057. *SKVMGuestInstance
  2058. ctx context.Context
  2059. nbdUri string
  2060. onSucc func()
  2061. syncMode string
  2062. index int
  2063. blockReplication bool
  2064. }
  2065. func NewDriveMirrorTask(
  2066. ctx context.Context, s *SKVMGuestInstance, nbdUri, syncMode string,
  2067. blockReplication bool, onSucc func(),
  2068. ) *SDriveMirrorTask {
  2069. return &SDriveMirrorTask{
  2070. SKVMGuestInstance: s,
  2071. ctx: ctx,
  2072. nbdUri: nbdUri,
  2073. syncMode: syncMode,
  2074. onSucc: onSucc,
  2075. blockReplication: blockReplication,
  2076. }
  2077. }
  2078. func (s *SDriveMirrorTask) Start() {
  2079. s.startMirror("")
  2080. }
  2081. func (s *SDriveMirrorTask) supportBlockReplication() bool {
  2082. c := make(chan bool)
  2083. s.Monitor.HumanMonitorCommand("help drive_mirror", func(res string) {
  2084. if strings.Index(res, "[-c]") > 0 {
  2085. c <- true
  2086. } else {
  2087. c <- false
  2088. }
  2089. })
  2090. return <-c
  2091. }
  2092. func (s *SDriveMirrorTask) startMirror(res string) {
  2093. log.Infof("drive mirror results:%s", res)
  2094. if len(res) > 0 {
  2095. hostutils.TaskFailed(s.ctx, res)
  2096. return
  2097. }
  2098. var blockReplication = false
  2099. if s.blockReplication && s.supportBlockReplication() {
  2100. blockReplication = true
  2101. log.Infof("mirror block replication supported")
  2102. }
  2103. if s.index < len(s.Desc.Disks) {
  2104. target := fmt.Sprintf("%s:exportname=drive_%d_backend", s.nbdUri, s.index)
  2105. s.Monitor.DriveMirror(s.startMirror, fmt.Sprintf("drive_%d", s.index), target, s.syncMode, "", true, blockReplication, 0)
  2106. s.index += 1
  2107. } else {
  2108. if s.onSucc != nil {
  2109. s.onSucc()
  2110. } else {
  2111. hostutils.TaskComplete(s.ctx, nil)
  2112. }
  2113. }
  2114. }
  2115. type SDriveBackupTask struct {
  2116. *SKVMGuestInstance
  2117. ctx context.Context
  2118. nbdUri string
  2119. onSucc func()
  2120. syncMode string
  2121. index int
  2122. }
  2123. func NewDriveBackupTask(
  2124. ctx context.Context, s *SKVMGuestInstance, nbdUri, syncMode string, onSucc func(),
  2125. ) *SDriveBackupTask {
  2126. return &SDriveBackupTask{
  2127. SKVMGuestInstance: s,
  2128. ctx: ctx,
  2129. nbdUri: nbdUri,
  2130. syncMode: syncMode,
  2131. onSucc: onSucc,
  2132. }
  2133. }
  2134. func (s *SDriveBackupTask) Start() {
  2135. s.startBackup("")
  2136. }
  2137. func (s *SDriveBackupTask) startBackup(res string) {
  2138. log.Infof("drive backup results:%s", res)
  2139. if len(res) > 0 {
  2140. hostutils.TaskFailed(s.ctx, res)
  2141. return
  2142. }
  2143. disks := s.Desc.Disks
  2144. if s.index < len(disks) {
  2145. target := fmt.Sprintf("%s:exportname=drive_%d_backend", s.nbdUri, s.index)
  2146. s.Monitor.DriveBackup(s.startBackup, fmt.Sprintf("drive_%d", s.index), target, s.syncMode, "raw")
  2147. s.index += 1
  2148. } else {
  2149. if s.onSucc != nil {
  2150. s.onSucc()
  2151. } else {
  2152. hostutils.TaskComplete(s.ctx, nil)
  2153. }
  2154. }
  2155. }
  2156. type SGuestBlockReplicationTask struct {
  2157. *SKVMGuestInstance
  2158. ctx context.Context
  2159. nbdHost string
  2160. nbdPort string
  2161. onSucc func()
  2162. onFail func(string)
  2163. syncMode string
  2164. index int
  2165. }
  2166. func NewGuestBlockReplicationTask(
  2167. ctx context.Context, s *SKVMGuestInstance,
  2168. nbdHost, nbdPort, syncMode string, onSucc func(), onFail func(string),
  2169. ) *SGuestBlockReplicationTask {
  2170. return &SGuestBlockReplicationTask{
  2171. SKVMGuestInstance: s,
  2172. ctx: ctx,
  2173. nbdHost: nbdHost,
  2174. nbdPort: nbdPort,
  2175. syncMode: syncMode,
  2176. onSucc: onSucc,
  2177. onFail: onFail,
  2178. }
  2179. }
  2180. func (s *SGuestBlockReplicationTask) Start() {
  2181. s.onXBlockdevChange("")
  2182. }
  2183. func (s *SGuestBlockReplicationTask) onXBlockdevChange(res string) {
  2184. if len(res) > 0 {
  2185. log.Errorf("SGuestBlockReplicationTask onXBlockdevChange %s", res)
  2186. if s.onFail != nil {
  2187. s.onFail(res)
  2188. } else {
  2189. hostutils.TaskFailed(s.ctx, res)
  2190. }
  2191. return
  2192. }
  2193. disks := s.Desc.Disks
  2194. if s.index < len(disks) {
  2195. diskIndex := disks[s.index].Index
  2196. drive := fmt.Sprintf("drive_%d", diskIndex)
  2197. node := fmt.Sprintf("node_%d", diskIndex)
  2198. s.Monitor.DriveAdd("", "buddy", map[string]string{
  2199. "file.driver": "nbd", "file.host": s.nbdHost, "file.port": s.nbdPort,
  2200. "file.export": drive, "node-name": node,
  2201. }, s.onNbdDriveAddSucc(drive, node))
  2202. s.index += 1
  2203. } else {
  2204. if s.onSucc != nil {
  2205. s.onSucc()
  2206. } else {
  2207. hostutils.TaskComplete(s.ctx, nil)
  2208. }
  2209. }
  2210. }
  2211. func (s *SGuestBlockReplicationTask) onNbdDriveAddSucc(parent, node string) monitor.StringCallback {
  2212. return func(res string) {
  2213. if len(res) > 0 {
  2214. log.Errorf("SGuestBlockReplicationTask onNbdDriveAddSucc %s", res)
  2215. if s.onFail != nil {
  2216. s.onFail(res)
  2217. } else {
  2218. hostutils.TaskFailed(s.ctx, res)
  2219. }
  2220. return
  2221. }
  2222. s.Monitor.XBlockdevChange(parent, node, "", s.onXBlockdevChange)
  2223. }
  2224. }
  2225. /**
  2226. * GuestOnlineResizeDiskTask
  2227. **/
  2228. type SGuestOnlineResizeDiskTask struct {
  2229. *SKVMGuestInstance
  2230. ctx context.Context
  2231. disk storageman.IDisk
  2232. sizeMB int64
  2233. }
  2234. func NewGuestOnlineResizeDiskTask(
  2235. ctx context.Context, s *SKVMGuestInstance, disk storageman.IDisk, sizeMB int64,
  2236. ) *SGuestOnlineResizeDiskTask {
  2237. return &SGuestOnlineResizeDiskTask{
  2238. SKVMGuestInstance: s,
  2239. ctx: ctx,
  2240. disk: disk,
  2241. sizeMB: sizeMB,
  2242. }
  2243. }
  2244. func (task *SGuestOnlineResizeDiskTask) Start() {
  2245. task.Monitor.GetBlocks(task.OnGetBlocksSucc)
  2246. }
  2247. func (task *SGuestOnlineResizeDiskTask) OnGetBlocksSucc(blocks []monitor.QemuBlock) {
  2248. for i := 0; i < len(blocks); i += 1 {
  2249. image := ""
  2250. if strings.HasPrefix(blocks[i].Inserted.File, "json:") {
  2251. //RBD磁盘格式如下
  2252. //json:{"driver": "raw", "file": {"pool": "testpool01", "image": "952636e3-73ed-4a19-8648-05e69e6bb57a", "driver": "rbd", "=keyvalue-pairs": "[\"mon_host\", \"10.127.10.230;10.127.10.237;10.127.10.238\", \"key\", \"AQBZ/Ddd0j5BCxAAfuvl5oHWsmuTGer6T9LzeQ==\", \"rados_mon_op_timeout\", \"5\", \"rados_osd_op_timeout\", \"1200\", \"client_mount_timeout\", \"120\"]"}
  2253. fileJson, err := jsonutils.ParseString(blocks[i].Inserted.File[5:])
  2254. if err != nil {
  2255. hostutils.TaskFailed(task.ctx, fmt.Sprintf("parse file json %s error: %v", blocks[i].Inserted.File, err))
  2256. return
  2257. }
  2258. image, _ = fileJson.GetString("file", "image")
  2259. }
  2260. if len(blocks[i].Inserted.File) > 0 && strings.HasSuffix(blocks[i].Inserted.File, task.disk.GetId()) || image == task.disk.GetId() {
  2261. if err := task.disk.PreResize(task.ctx, task.sizeMB); err != nil {
  2262. hostutils.TaskFailed(task.ctx, fmt.Sprintf("disk %s preResize failed %s", task.disk.GetId(), err))
  2263. return
  2264. }
  2265. task.Monitor.ResizeDisk(blocks[i].Device, task.sizeMB, task.OnResizeSucc)
  2266. return
  2267. }
  2268. }
  2269. hostutils.TaskFailed(task.ctx, fmt.Sprintf("disk %s not found on this guest", task.disk.GetId()))
  2270. }
  2271. func (task *SGuestOnlineResizeDiskTask) OnResizeSucc(err string) {
  2272. if len(err) == 0 {
  2273. if e := task.guestAgent.GuestPing(1); e == nil {
  2274. if e := task.guestAgent.QgaResizeDisk(task.disk.GetId()); e != nil {
  2275. log.Errorf("failed qga resize disk %s: %s", task.disk.GetId(), e)
  2276. }
  2277. }
  2278. params := jsonutils.NewDict()
  2279. params.Add(jsonutils.NewInt(task.sizeMB), "disk_size")
  2280. hostutils.TaskComplete(task.ctx, params)
  2281. return
  2282. }
  2283. hostutils.TaskFailed(task.ctx, fmt.Sprintf("resize disk %s %dMb error: %v", task.disk.GetId(), task.sizeMB, err))
  2284. }
  2285. /**
  2286. * GuestHotplugCpuMem
  2287. **/
  2288. type SGuestHotplugCpuMemTask struct {
  2289. *SKVMGuestInstance
  2290. ctx context.Context
  2291. addCpuCount int
  2292. addMemSize int
  2293. addMemNodeIndex int
  2294. originalCpuCount int
  2295. addedCpuCount int
  2296. addedVcpuIds []int
  2297. cpuNumaPin []*desc.SCpuNumaPin
  2298. addedMemSize int
  2299. memSlotNewIndex *int
  2300. memSlotNewIndexs []int
  2301. memSlots []*desc.SMemSlot
  2302. }
  2303. func NewGuestHotplugCpuMemTask(
  2304. ctx context.Context, s *SKVMGuestInstance, input *SGuestHotplugCpuMem,
  2305. ) *SGuestHotplugCpuMemTask {
  2306. t := &SGuestHotplugCpuMemTask{
  2307. SKVMGuestInstance: s,
  2308. ctx: ctx,
  2309. addCpuCount: int(input.AddCpuCount),
  2310. addMemSize: int(input.AddMemSize),
  2311. cpuNumaPin: input.CpuNumaPin,
  2312. }
  2313. if input.TotalCpuCount != nil && input.AddCpuCount > 0 {
  2314. if s.Desc.Cpu > *input.TotalCpuCount {
  2315. addedCpuCount := int(s.Desc.Cpu - *input.TotalCpuCount)
  2316. t.addCpuCount -= addedCpuCount
  2317. }
  2318. }
  2319. log.Infof("guest %s add cpu count %d", s.Id, t.addCpuCount)
  2320. if input.TotalMemSize != nil && input.AddMemSize > 0 {
  2321. if s.Desc.Mem > *input.TotalMemSize {
  2322. addedMemSize := int(s.Desc.Mem - *input.TotalMemSize)
  2323. t.addMemSize -= addedMemSize
  2324. }
  2325. }
  2326. log.Infof("guest %s add mem size %d", s.Id, t.addMemSize)
  2327. return t
  2328. }
  2329. // First at all add cpu count, second add mem size
  2330. func (task *SGuestHotplugCpuMemTask) Start() {
  2331. if task.addCpuCount > 0 {
  2332. task.startAddCpu()
  2333. } else if task.addMemSize > 0 {
  2334. task.startAddMem()
  2335. } else {
  2336. task.onSucc()
  2337. }
  2338. }
  2339. func (task *SGuestHotplugCpuMemTask) startAddCpu() {
  2340. if task.Desc.MemDesc.Mem != nil && task.Desc.MemDesc.Mem.Cpus != nil && len(task.Desc.CpuNumaPin) > 0 {
  2341. task.buildVcpusMap()
  2342. } else {
  2343. task.Monitor.GetCpuCount(task.onGetCpuCount)
  2344. }
  2345. }
  2346. func (task *SGuestHotplugCpuMemTask) buildVcpusMap() {
  2347. vcpuSet, _ := cpuset.Parse(*task.Desc.MemDesc.Mem.Cpus)
  2348. for i := range task.Desc.MemDesc.Mem.Mems {
  2349. if task.Desc.MemDesc.Mem.Mems[i].Cpus != nil {
  2350. memVcpuSet, _ := cpuset.Parse(*task.Desc.MemDesc.Mem.Mems[i].Cpus)
  2351. vcpuSet = vcpuSet.Union(memVcpuSet)
  2352. }
  2353. }
  2354. allocatedVcpus := make([]int, 0)
  2355. for i := range task.Desc.CpuNumaPin {
  2356. for j := range task.Desc.CpuNumaPin[i].VcpuPin {
  2357. allocatedVcpus = append(allocatedVcpus, task.Desc.CpuNumaPin[i].VcpuPin[j].Vcpu)
  2358. }
  2359. }
  2360. allocatedCpuset := cpuset.NewCPUSet(allocatedVcpus...)
  2361. vcpuSet = vcpuSet.Difference(allocatedCpuset)
  2362. task.startAddCpusWithFreeVcpuSet(vcpuSet.ToSlice())
  2363. }
  2364. func (task *SGuestHotplugCpuMemTask) startAddCpusWithFreeVcpuSet(vcpuSet []int) {
  2365. if task.addedCpuCount >= task.addCpuCount {
  2366. task.startAddMem()
  2367. return
  2368. }
  2369. vcpuId := vcpuSet[0]
  2370. cb := func(reason string) {
  2371. if len(reason) > 0 {
  2372. log.Errorln(reason)
  2373. task.onFail(reason)
  2374. return
  2375. }
  2376. if len(task.cpuNumaPin) > 0 {
  2377. for i := range task.cpuNumaPin {
  2378. for j := range task.cpuNumaPin[i].VcpuPin {
  2379. if task.cpuNumaPin[i].VcpuPin[j].Vcpu == -1 {
  2380. task.cpuNumaPin[i].VcpuPin[j].Vcpu = vcpuId
  2381. }
  2382. }
  2383. }
  2384. } else {
  2385. cpus, _ := task.manager.cpuSet.AllocCpuset(1, 0, nil, task.GetId())
  2386. for _, cpus := range cpus {
  2387. //pcpus := cpuset.NewCPUSet(cpus.Cpuset...).String()
  2388. //vcpus := fmt.Sprintf("%d-%d", vcpuId, vcpuId)
  2389. vcpuPin := make([]desc.SVCpuPin, 1)
  2390. vcpuPin[0].Pcpu = cpus.Cpuset[0]
  2391. vcpuPin[0].Vcpu = vcpuId
  2392. cpuPin := &desc.SCpuNumaPin{
  2393. SizeMB: 0,
  2394. VcpuPin: vcpuPin,
  2395. Unregular: false,
  2396. }
  2397. task.Desc.CpuNumaPin = append(task.Desc.CpuNumaPin, cpuPin)
  2398. }
  2399. }
  2400. if task.addedVcpuIds == nil {
  2401. task.addedVcpuIds = []int{vcpuId}
  2402. } else {
  2403. task.addedVcpuIds = append(task.addedVcpuIds, vcpuId)
  2404. }
  2405. task.addedCpuCount += 1
  2406. task.startAddCpusWithFreeVcpuSet(vcpuSet[1:])
  2407. }
  2408. task.Monitor.AddCpu(vcpuId, cb)
  2409. }
  2410. func (task *SGuestHotplugCpuMemTask) onGetCpuCount(count int) {
  2411. task.originalCpuCount = count
  2412. task.doAddCpu()
  2413. }
  2414. func (task *SGuestHotplugCpuMemTask) doAddCpu() {
  2415. if task.addedCpuCount < task.addCpuCount {
  2416. task.Monitor.AddCpu(task.originalCpuCount+task.addedCpuCount, task.onAddCpu)
  2417. } else {
  2418. task.startAddMem()
  2419. }
  2420. }
  2421. func (task *SGuestHotplugCpuMemTask) onAddCpu(reason string) {
  2422. if len(reason) > 0 {
  2423. log.Errorln(reason)
  2424. task.onFail(reason)
  2425. return
  2426. }
  2427. task.addedCpuCount += 1
  2428. task.doAddCpu()
  2429. }
  2430. func (task *SGuestHotplugCpuMemTask) startAddMem() {
  2431. if task.addMemSize > 0 {
  2432. task.Monitor.GeMemtSlotIndex(task.onGetSlotIndex)
  2433. } else {
  2434. task.onSucc()
  2435. }
  2436. }
  2437. func (task *SGuestHotplugCpuMemTask) onGetSlotIndex(index int) {
  2438. var newIndex = index
  2439. if task.Desc.MemDesc.Mem != nil {
  2440. newIndex += len(task.Desc.MemDesc.Mem.Mems)
  2441. }
  2442. task.memSlotNewIndex = &newIndex
  2443. var addMemSize = task.addMemSize
  2444. var numaNodeDesc *desc.SCpuNumaPin
  2445. for i := task.addMemNodeIndex; i < len(task.cpuNumaPin); i++ {
  2446. if task.cpuNumaPin[i].SizeMB > 0 {
  2447. task.addMemNodeIndex = i + 1
  2448. numaNodeDesc = task.cpuNumaPin[i]
  2449. addMemSize = int(task.cpuNumaPin[i].SizeMB)
  2450. break
  2451. }
  2452. }
  2453. var hostNodes *uint16
  2454. if numaNodeDesc != nil {
  2455. hostNodes = numaNodeDesc.NodeId
  2456. }
  2457. var objType string
  2458. var id = fmt.Sprintf("mem%d", *task.memSlotNewIndex)
  2459. var opts map[string]string
  2460. if task.manager.host.IsHugepagesEnabled() {
  2461. memPath := fmt.Sprintf("/dev/hugepages/%s-%d", task.GetId(), index)
  2462. err := procutils.NewRemoteCommandAsFarAsPossible("mkdir", "-p", memPath).Run()
  2463. if err != nil {
  2464. reason := fmt.Sprintf("mkdir %s fail: %s", memPath, err)
  2465. log.Errorf("%s", reason)
  2466. task.onFail(reason)
  2467. return
  2468. }
  2469. err = procutils.NewRemoteCommandAsFarAsPossible("mount", "-t", "hugetlbfs", "-o",
  2470. fmt.Sprintf("pagesize=%dK,size=%dM", task.manager.host.HugepageSizeKb(), addMemSize),
  2471. fmt.Sprintf("hugetlbfs-%s-%d", task.GetId(), index),
  2472. memPath,
  2473. ).Run()
  2474. if err != nil {
  2475. reason := fmt.Sprintf("mount %s fail: %s", memPath, err)
  2476. log.Errorf("%s", reason)
  2477. task.onFail(reason)
  2478. return
  2479. }
  2480. objType = "memory-backend-file"
  2481. opts = map[string]string{
  2482. "size": fmt.Sprintf("%dM", addMemSize),
  2483. "mem-path": memPath,
  2484. "share": "on",
  2485. "prealloc": "on",
  2486. }
  2487. if hostNodes != nil {
  2488. opts["host-nodes"] = fmt.Sprintf("%d", *hostNodes)
  2489. opts["policy"] = "bind"
  2490. }
  2491. } else {
  2492. objType = "memory-backend-ram"
  2493. opts = map[string]string{
  2494. "size": fmt.Sprintf("%dM", task.addMemSize),
  2495. }
  2496. }
  2497. opts["id"] = id
  2498. cb := func(reason string) {
  2499. memObj := desc.NewMemDesc(objType, id, nil, nil)
  2500. memObj.Options = opts
  2501. memSlot := new(desc.SMemSlot)
  2502. memSlot.MemObj = memObj
  2503. memSlot.SizeMB = int64(addMemSize)
  2504. task.onAddMemObject(reason, memSlot)
  2505. }
  2506. task.Monitor.ObjectAdd(objType, opts, cb)
  2507. }
  2508. func (task *SGuestHotplugCpuMemTask) onAddMemFailed(reason string) {
  2509. log.Errorln(reason)
  2510. cb := func(res string) { log.Infof("%s", res) }
  2511. task.Monitor.ObjectDel(fmt.Sprintf("mem%d", *task.memSlotNewIndex), cb)
  2512. task.onFail(reason)
  2513. }
  2514. func (task *SGuestHotplugCpuMemTask) onAddMemObject(reason string, memSlot *desc.SMemSlot) {
  2515. if len(reason) > 0 {
  2516. task.onAddMemFailed(reason)
  2517. return
  2518. }
  2519. params := map[string]string{
  2520. "id": fmt.Sprintf("dimm%d", *task.memSlotNewIndex),
  2521. "memdev": fmt.Sprintf("mem%d", *task.memSlotNewIndex),
  2522. }
  2523. cb := func(reason string) {
  2524. if reason == "" {
  2525. memSlot.MemDev = &desc.SMemDevice{
  2526. Type: "pc-dimm",
  2527. Id: fmt.Sprintf("dimm%d", *task.memSlotNewIndex),
  2528. }
  2529. }
  2530. task.onAddMemDevice(reason, memSlot)
  2531. }
  2532. task.Monitor.DeviceAdd("pc-dimm", params, cb)
  2533. }
  2534. func (task *SGuestHotplugCpuMemTask) onAddMemDevice(reason string, memSlot *desc.SMemSlot) {
  2535. if len(reason) > 0 {
  2536. task.onAddMemFailed(reason)
  2537. return
  2538. }
  2539. task.addedMemSize = int(memSlot.SizeMB)
  2540. task.addMemSize -= int(memSlot.SizeMB)
  2541. if task.memSlots == nil {
  2542. task.memSlots = []*desc.SMemSlot{memSlot}
  2543. task.memSlotNewIndexs = []int{*task.memSlotNewIndex}
  2544. } else {
  2545. task.memSlots = append(task.memSlots, memSlot)
  2546. task.memSlotNewIndexs = append(task.memSlotNewIndexs, *task.memSlotNewIndex)
  2547. }
  2548. if task.addMemSize > 0 {
  2549. task.startAddMem()
  2550. } else {
  2551. task.onSucc()
  2552. }
  2553. }
  2554. func (task *SGuestHotplugCpuMemTask) updateGuestDesc() {
  2555. task.Desc.Cpu += int64(task.addedCpuCount)
  2556. task.Desc.CpuDesc.Cpus += uint(task.addedCpuCount)
  2557. task.Desc.Mem += int64(task.addedMemSize)
  2558. if len(task.cpuNumaPin) > 0 {
  2559. task.Desc.CpuNumaPin = append(task.Desc.CpuNumaPin, task.cpuNumaPin...)
  2560. }
  2561. if task.addedMemSize > 0 {
  2562. if task.Desc.MemDesc.MemSlots == nil {
  2563. task.Desc.MemDesc.MemSlots = make([]*desc.SMemSlot, 0)
  2564. }
  2565. task.Desc.MemDesc.MemSlots = append(task.Desc.MemDesc.MemSlots, task.memSlots...)
  2566. if task.manager.hostagentNumaAllocate {
  2567. for i := range task.memSlotNewIndexs {
  2568. hugepageId := fmt.Sprintf("%s-%d", task.getOriginId(), task.memSlotNewIndexs[i])
  2569. task.validateNumaAllocated(hugepageId, false, true, nil)
  2570. }
  2571. }
  2572. }
  2573. if len(task.addedVcpuIds) > 0 {
  2574. task.setCgroupCPUSet()
  2575. }
  2576. if task.addedCpuCount > 0 && len(task.Desc.VcpuPin) == 1 {
  2577. task.Desc.VcpuPin[0].Vcpus = fmt.Sprintf("0-%d", task.Desc.Cpu-1)
  2578. }
  2579. if task.addedCpuCount > 0 || task.addedMemSize > 0 {
  2580. SaveLiveDesc(task, task.Desc)
  2581. }
  2582. if task.addedMemSize > 0 {
  2583. vncPort := task.GetVncPort()
  2584. data := jsonutils.NewDict()
  2585. data.Set("vnc_port", jsonutils.NewInt(int64(vncPort)))
  2586. data.Set("sync_qemu_cmdline", jsonutils.JSONTrue)
  2587. if err := task.saveScripts(data); err != nil {
  2588. log.Errorf("failed save script: %s", err)
  2589. }
  2590. }
  2591. }
  2592. func (task *SGuestHotplugCpuMemTask) onFail(reason string) {
  2593. body := jsonutils.NewDict()
  2594. if task.addedCpuCount < task.addCpuCount {
  2595. body.Set("add_cpu_failed", jsonutils.JSONTrue)
  2596. body.Set("added_cpu", jsonutils.NewInt(int64(task.addedCpuCount)))
  2597. } else if task.memSlotNewIndex != nil {
  2598. body.Set("add_mem_failed", jsonutils.JSONTrue)
  2599. }
  2600. task.updateGuestDesc()
  2601. hostutils.TaskFailed2(task.ctx, reason, body)
  2602. }
  2603. func (task *SGuestHotplugCpuMemTask) onSucc() {
  2604. task.updateGuestDesc()
  2605. res := jsonutils.NewDict()
  2606. if len(task.cpuNumaPin) > 0 {
  2607. res.Set("cpu_numa_pin", jsonutils.Marshal(task.Desc.CpuNumaPin))
  2608. }
  2609. hostutils.TaskComplete(task.ctx, res)
  2610. }
  2611. type SGuestBlockIoThrottleTask struct {
  2612. *SKVMGuestInstance
  2613. ctx context.Context
  2614. }
  2615. func (task *SGuestBlockIoThrottleTask) Start() {
  2616. go task.startDoIoThrottle(0)
  2617. }
  2618. func (task *SGuestBlockIoThrottleTask) startDoIoThrottle(idx int) {
  2619. if idx < len(task.Desc.Disks) {
  2620. _cb := func(res string) {
  2621. if len(res) > 0 {
  2622. task.taskFail(res)
  2623. } else {
  2624. task.startDoIoThrottle(idx + 1)
  2625. }
  2626. }
  2627. task.Monitor.BlockIoThrottle(
  2628. fmt.Sprintf("drive_%d", task.Desc.Disks[idx].Index),
  2629. int64(task.Desc.Disks[idx].Bps), int64(task.Desc.Disks[idx].Iops), _cb)
  2630. } else {
  2631. task.taskComplete(nil)
  2632. }
  2633. }
  2634. func (task *SGuestBlockIoThrottleTask) taskFail(reason string) {
  2635. if taskId := task.ctx.Value(appctx.APP_CONTEXT_KEY_TASK_ID); taskId != nil {
  2636. hostutils.TaskFailed(task.ctx, reason)
  2637. } else {
  2638. log.Errorln(reason)
  2639. }
  2640. }
  2641. func (task *SGuestBlockIoThrottleTask) taskComplete(data jsonutils.JSONObject) {
  2642. if taskId := task.ctx.Value(appctx.APP_CONTEXT_KEY_TASK_ID); taskId != nil {
  2643. hostutils.TaskComplete(task.ctx, data)
  2644. }
  2645. }
  2646. type CancelBlockReplication struct {
  2647. SCancelBlockJobs
  2648. }
  2649. func NewCancelBlockReplicationTask(ctx context.Context, guest *SKVMGuestInstance) *CancelBlockReplication {
  2650. return &CancelBlockReplication{SCancelBlockJobs{guest, ctx}}
  2651. }
  2652. func (task *CancelBlockReplication) Start() {
  2653. // start remove child node of block device
  2654. disks := task.Desc.Disks
  2655. for i := 0; i < len(disks); i++ {
  2656. diskIndex := disks[i].Index
  2657. drive := fmt.Sprintf("drive_%d", diskIndex)
  2658. node := fmt.Sprintf("node_%d", diskIndex)
  2659. child := fmt.Sprintf("children.%d", task.getQuorumChildIndex())
  2660. task.Monitor.XBlockdevChange(drive, "", child, func(res string) {
  2661. if len(res) > 0 {
  2662. log.Errorf("failed remove child %s for parent %s: %s", drive, node, res)
  2663. return
  2664. }
  2665. task.Monitor.DriveDel(node, func(res string) {
  2666. if len(res) > 0 {
  2667. log.Errorf("failed remove drive %s: %s", node, res)
  2668. return
  2669. }
  2670. })
  2671. })
  2672. }
  2673. if task.ctx != nil {
  2674. hostutils.TaskComplete(task.ctx, nil)
  2675. }
  2676. }
  2677. type SCancelBlockJobs struct {
  2678. *SKVMGuestInstance
  2679. ctx context.Context
  2680. }
  2681. func NewCancelBlockJobsTask(ctx context.Context, guest *SKVMGuestInstance) *SCancelBlockJobs {
  2682. return &SCancelBlockJobs{guest, ctx}
  2683. }
  2684. func (task *SCancelBlockJobs) Start() {
  2685. task.findBlockDevices()
  2686. }
  2687. func (task *SCancelBlockJobs) findBlockDevices() {
  2688. task.Monitor.GetBlocks(task.onBlockDriversSucc)
  2689. }
  2690. func (task *SCancelBlockJobs) onBlockDriversSucc(blocks []monitor.QemuBlock) {
  2691. drivers := make([]string, 0)
  2692. for i := 0; i < len(blocks); i++ {
  2693. if strings.HasPrefix(blocks[i].Device, "drive_") {
  2694. drivers = append(drivers, blocks[i].Device)
  2695. }
  2696. }
  2697. task.StartCancelBlockJobs(drivers)
  2698. }
  2699. func (task *SCancelBlockJobs) StartCancelBlockJobs(drivers []string) {
  2700. if len(drivers) > 0 {
  2701. driver := drivers[0]
  2702. drivers = drivers[1:]
  2703. onCancelBlockJob := func(res string) {
  2704. if len(res) > 0 {
  2705. log.Errorln(res)
  2706. }
  2707. task.StartCancelBlockJobs(drivers)
  2708. }
  2709. task.Monitor.CancelBlockJob(driver, false, onCancelBlockJob)
  2710. } else {
  2711. task.taskComplete()
  2712. }
  2713. }
  2714. func (task *SCancelBlockJobs) taskComplete() {
  2715. if task.ctx != nil {
  2716. hostutils.TaskComplete(task.ctx, nil)
  2717. }
  2718. }
  2719. type SGuestStorageCloneDiskTask struct {
  2720. *SGuestBlockProgressBaseTask
  2721. started bool
  2722. diskIndex int
  2723. resp *hostapi.ServerCloneDiskFromStorageResponse
  2724. params *SStorageCloneDisk
  2725. }
  2726. func NewGuestStorageCloneDiskTask(ctx context.Context, guest *SKVMGuestInstance, params *SStorageCloneDisk) *SGuestStorageCloneDiskTask {
  2727. task := &SGuestStorageCloneDiskTask{
  2728. params: params,
  2729. }
  2730. task.SGuestBlockProgressBaseTask = NewGuestBlockProgressBaseTask(ctx, guest, task)
  2731. return task
  2732. }
  2733. func (t *SGuestStorageCloneDiskTask) Start(guestRunning bool) {
  2734. var diskIndex = -1
  2735. disks := t.Desc.Disks
  2736. for diskIndex = 0; diskIndex < len(disks); diskIndex++ {
  2737. if disks[diskIndex].DiskId == t.params.SourceDisk.GetId() {
  2738. diskIndex = int(disks[diskIndex].Index)
  2739. break
  2740. }
  2741. }
  2742. if diskIndex < 0 {
  2743. hostutils.TaskFailed(
  2744. t.ctx, fmt.Sprintf("failed find disk index %s", t.params.SourceDisk.GetId()),
  2745. )
  2746. return
  2747. }
  2748. encryptInfo, err := t.getEncryptKey(t.ctx, auth.AdminCredential())
  2749. if err != nil {
  2750. hostutils.TaskFailed(
  2751. t.ctx, fmt.Sprintf("failed get guest encrypt info %s", t.params.SourceDisk.GetId()),
  2752. )
  2753. return
  2754. }
  2755. resp, err := t.params.TargetStorage.CloneDiskFromStorage(t.ctx, t.params.SourceStorage, t.params.SourceDisk, t.params.TargetDiskId, !guestRunning, encryptInfo)
  2756. if err != nil {
  2757. hostutils.TaskFailed(
  2758. t.ctx, fmt.Sprintf("Clone disk %s to storage %s failed %s",
  2759. t.params.SourceDisk.GetPath(), t.params.TargetStorage.GetId(), err),
  2760. )
  2761. return
  2762. }
  2763. targetDisk, err := t.params.TargetStorage.GetDiskById(t.params.TargetDiskId)
  2764. if err != nil {
  2765. hostutils.TaskFailed(
  2766. t.ctx, fmt.Sprintf("Failed get target disk %s %s", t.params.TargetDiskId, err),
  2767. )
  2768. return
  2769. }
  2770. targetDiskFormat, err := targetDisk.GetFormat()
  2771. if err != nil {
  2772. hostutils.TaskFailed(
  2773. t.ctx, fmt.Sprintf("Failed get target disk format %s %s", t.params.TargetDiskId, err),
  2774. )
  2775. return
  2776. }
  2777. if !guestRunning {
  2778. hostutils.TaskComplete(t.ctx, jsonutils.Marshal(resp))
  2779. return
  2780. } else {
  2781. t.resp = resp
  2782. t.diskIndex = diskIndex
  2783. }
  2784. t.Monitor.DriveMirror(t.onDriveMirror, fmt.Sprintf("drive_%d", diskIndex), targetDisk.GetPath(), "full", targetDiskFormat, true, false, 0)
  2785. }
  2786. func (t *SGuestStorageCloneDiskTask) onDriveMirror(res string) {
  2787. if len(res) > 0 {
  2788. hostutils.TaskFailed(
  2789. t.ctx, fmt.Sprintf("Clone disk %s to storage %s drive mirror failed %s",
  2790. t.params.SourceDisk.GetPath(), t.params.TargetStorage.GetId(), res),
  2791. )
  2792. } else {
  2793. t.started = true
  2794. hostutils.TaskComplete(t.ctx, jsonutils.Marshal(t.resp))
  2795. go t.startWaitBlockJob(res)
  2796. timeutils2.AddTimeout(time.Second*3, func() {
  2797. t.SyncStatus("drive mirror started")
  2798. })
  2799. }
  2800. }
  2801. func (t *SGuestStorageCloneDiskTask) OnGetBlockJobs(jobs []monitor.BlockJob) {
  2802. if len(jobs) == 0 {
  2803. if !t.started {
  2804. targetDisk, err := t.params.TargetStorage.GetDiskById(t.params.TargetDiskId)
  2805. if err != nil {
  2806. hostutils.TaskFailed(
  2807. t.ctx, fmt.Sprintf("Failed get target disk %s %s", t.params.TargetDiskId, err),
  2808. )
  2809. return
  2810. }
  2811. targetDiskFormat, err := targetDisk.GetFormat()
  2812. if err != nil {
  2813. hostutils.TaskFailed(
  2814. t.ctx, fmt.Sprintf("Failed get target disk format %s %s", t.params.TargetDiskId, err),
  2815. )
  2816. return
  2817. }
  2818. t.Monitor.DriveMirror(t.onDriveMirror, fmt.Sprintf("drive_%d", t.diskIndex), targetDisk.GetPath(), "full", targetDiskFormat, true, false, 0)
  2819. } else {
  2820. hostutils.TaskFailed(t.ctx, fmt.Sprintf("Disk %s Block job not found", t.params.SourceDisk.GetId()))
  2821. }
  2822. return
  2823. }
  2824. for i := range jobs {
  2825. if jobs[i].Status == "ready" && jobs[i].Device == fmt.Sprintf("drive_%d", t.diskIndex) {
  2826. t.cancelWaitBlockJobs()
  2827. params := jsonutils.NewDict()
  2828. params.Set("block_jobs_ready", jsonutils.JSONTrue)
  2829. hostutils.TaskComplete(t.ctx, params)
  2830. break
  2831. }
  2832. }
  2833. }
  2834. func (t *SGuestStorageCloneDiskTask) StreamingDiskCompletedCount() int {
  2835. return t.params.CompletedDiskCount
  2836. }
  2837. func (t *SGuestStorageCloneDiskTask) StreamingDiskCount() int {
  2838. return t.params.CloneDiskCount
  2839. }
  2840. type SGuestLiveChangeDisk struct {
  2841. *SKVMGuestInstance
  2842. ctx context.Context
  2843. params *SStorageCloneDisk
  2844. guestNeedResume bool
  2845. diskIndex int
  2846. targetDisk storageman.IDisk
  2847. }
  2848. func NewGuestLiveChangeDiskTask(ctx context.Context, guest *SKVMGuestInstance, params *SStorageCloneDisk) (*SGuestLiveChangeDisk, error) {
  2849. disk, err := params.TargetStorage.GetDiskById(params.TargetDiskId)
  2850. if err != nil {
  2851. return nil, err
  2852. }
  2853. var diskIndex = -1
  2854. disks := guest.Desc.Disks
  2855. for diskIndex = 0; diskIndex < len(disks); diskIndex++ {
  2856. if disks[diskIndex].DiskId == params.SourceDisk.GetId() {
  2857. diskIndex = int(disks[diskIndex].Index)
  2858. break
  2859. }
  2860. }
  2861. if diskIndex < 0 {
  2862. return nil, fmt.Errorf("failed found disk %s index", params.SourceDisk.GetId())
  2863. }
  2864. diskFormat, err := params.SourceDisk.GetFormat()
  2865. if err != nil {
  2866. return nil, errors.Wrap(err, "failed get disk fromat")
  2867. }
  2868. params.DiskFormat = diskFormat
  2869. return &SGuestLiveChangeDisk{
  2870. SKVMGuestInstance: guest,
  2871. ctx: ctx,
  2872. params: params,
  2873. guestNeedResume: false,
  2874. diskIndex: diskIndex,
  2875. targetDisk: disk,
  2876. }, nil
  2877. }
  2878. func (t *SGuestLiveChangeDisk) Start() {
  2879. // pause guest first
  2880. if !t.IsSuspend() {
  2881. t.Monitor.SimpleCommand("stop", t.onGuestPaused)
  2882. t.guestNeedResume = true
  2883. } else {
  2884. t.onGuestPaused("")
  2885. }
  2886. }
  2887. func (t *SGuestLiveChangeDisk) onGuestPaused(res string) {
  2888. if strings.Contains(strings.ToLower(res), "error") {
  2889. hostutils.TaskFailed(t.ctx, fmt.Sprintf("pause error: %s", res))
  2890. return
  2891. }
  2892. t.Monitor.BlockJobComplete(fmt.Sprintf("drive_%d", t.diskIndex), t.onReopenImageSuccess)
  2893. }
  2894. func (t *SGuestLiveChangeDisk) onReopenImageSuccess(res string) {
  2895. // resume guest first
  2896. if t.guestNeedResume {
  2897. t.Monitor.SimpleCommand("cont", nil)
  2898. }
  2899. if len(res) > 0 {
  2900. hostutils.TaskFailed(t.ctx, fmt.Sprintf("reopen image failed: %s", res))
  2901. return
  2902. }
  2903. if t.params.TargetDiskDesc != nil {
  2904. for i := 0; i < len(t.Desc.Disks); i++ {
  2905. if t.Desc.Disks[i].Index == int8(t.diskIndex) {
  2906. log.Debugf("update guest disk %s desc", t.Desc.Disks[i].DiskId)
  2907. t.Desc.Disks[i].GuestdiskJsonDesc = *t.params.TargetDiskDesc
  2908. SaveLiveDesc(t, t.Desc)
  2909. break
  2910. }
  2911. }
  2912. }
  2913. resp := &hostapi.ServerCloneDiskFromStorageResponse{
  2914. TargetAccessPath: t.targetDisk.GetPath(),
  2915. }
  2916. hostutils.TaskComplete(t.ctx, jsonutils.Marshal(resp))
  2917. }