balancer.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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 balancer
  15. import (
  16. "context"
  17. "fmt"
  18. "math"
  19. "sort"
  20. "sync"
  21. "yunion.io/x/jsonutils"
  22. "yunion.io/x/log"
  23. "yunion.io/x/pkg/errors"
  24. "yunion.io/x/pkg/utils"
  25. computeapi "yunion.io/x/onecloud/pkg/apis/compute"
  26. "yunion.io/x/onecloud/pkg/apis/monitor"
  27. "yunion.io/x/onecloud/pkg/mcclient"
  28. "yunion.io/x/onecloud/pkg/mcclient/modules/compute"
  29. compute_options "yunion.io/x/onecloud/pkg/mcclient/options/compute"
  30. "yunion.io/x/onecloud/pkg/monitor/alerting"
  31. "yunion.io/x/onecloud/pkg/monitor/datasource"
  32. "yunion.io/x/onecloud/pkg/monitor/models"
  33. "yunion.io/x/onecloud/pkg/monitor/tsdb"
  34. )
  35. func init() {
  36. for _, drv := range []IMetricDriver{
  37. newMemAvailable(),
  38. newCPUUsageActive(),
  39. } {
  40. GetMetricDrivers().register(drv)
  41. }
  42. }
  43. var (
  44. drivers *MetricDrivers
  45. )
  46. type MetricDrivers struct {
  47. *sync.Map
  48. }
  49. func NewMetricDrivers() *MetricDrivers {
  50. return &MetricDrivers{
  51. Map: new(sync.Map),
  52. }
  53. }
  54. func (d *MetricDrivers) register(id IMetricDriver) *MetricDrivers {
  55. d.Store(id.GetType(), id)
  56. return d
  57. }
  58. func (d *MetricDrivers) Get(mT monitor.MigrationAlertMetricType) (IMetricDriver, error) {
  59. drv, ok := d.Load(mT)
  60. if !ok {
  61. return nil, errors.Errorf("Not found driver by %q", mT)
  62. }
  63. return drv.(IMetricDriver), nil
  64. }
  65. func GetMetricDrivers() *MetricDrivers {
  66. if drivers == nil {
  67. drivers = NewMetricDrivers()
  68. }
  69. return drivers
  70. }
  71. type IMetricDriver interface {
  72. GetType() monitor.MigrationAlertMetricType
  73. GetTsdbQuery() *TsdbQuery
  74. GetCandidate(gst jsonutils.JSONObject, host IHost, ds *tsdb.DataSource) (ICandidate, error)
  75. SetHostCurrent(h IHost, values map[string]float64) error
  76. GetTarget(host jsonutils.JSONObject) (ITarget, error)
  77. GetCondition(s *monitor.AlertSetting) (ICondition, error)
  78. }
  79. type ICondition interface {
  80. GetThreshold() float64
  81. // GetSourceThresholdDelta must > 0
  82. GetSourceThresholdDelta(threshold float64, srcHost IHost) float64
  83. IsFitTarget(settings *monitor.MigrationAlertSettings, t ITarget, c ICandidate) error
  84. }
  85. type Rules struct {
  86. Alert *models.SMigrationAlert
  87. Condtion ICondition
  88. Source *SourceRule
  89. Target *TargetRule
  90. ResultMustPair bool
  91. }
  92. func (r *Rules) GetAlert() *models.SMigrationAlert {
  93. return r.Alert
  94. }
  95. func NewRules(_ *alerting.EvalContext, m *monitor.EvalMatch, alert *models.SMigrationAlert, drv IMetricDriver, resultMustPair bool) (*Rules, error) {
  96. hostId, ok := m.Tags["host_id"]
  97. if !ok {
  98. return nil, errors.Errorf("Not found host_id in tags: %#v", m.Tags)
  99. }
  100. ok, hObjs := models.MonitorResourceManager.GetResourceObjByResType(monitor.METRIC_RES_TYPE_HOST)
  101. if !ok {
  102. return nil, errors.Errorf("GetResourceObjByResType host returns false")
  103. }
  104. var srcHostObj jsonutils.JSONObject = nil
  105. for _, obj := range hObjs {
  106. id, err := obj.GetString("id")
  107. if err != nil {
  108. return nil, errors.Wrapf(err, "get host obj id: %s", obj)
  109. }
  110. if id == hostId {
  111. srcHostObj = obj
  112. break
  113. }
  114. }
  115. if srcHostObj == nil {
  116. return nil, errors.Errorf("Not found source host object by id: %q, %q", hostId, srcHostObj)
  117. }
  118. srcHost, err := drv.GetTarget(srcHostObj)
  119. if err != nil {
  120. return nil, errors.Wrap(err, "new host")
  121. }
  122. allHosts := []IResource{srcHost}
  123. msettings, _ := alert.GetMigrationSettings()
  124. targetHosts, err := filterTargetHosts(drv, srcHost, hObjs, msettings)
  125. if err != nil {
  126. return nil, errors.Wrap(err, "filterTargetHosts")
  127. }
  128. for _, oh := range targetHosts {
  129. allHosts = append(allHosts, oh)
  130. }
  131. ds, err := datasource.GetDefaultSource("telegraf")
  132. if err != nil {
  133. return nil, errors.Wrapf(err, "Get default DataSource")
  134. }
  135. // find guests to filtered by source setting of source host alerted
  136. cds, err := findGuestsOfHost(drv, srcHost, ds, msettings)
  137. if err != nil {
  138. return nil, errors.Wrapf(err, "findGuestsOfHost %s", srcHost.GetName())
  139. }
  140. metrics, err := InfluxdbQuery(ds, "host_id", allHosts, drv.GetTsdbQuery())
  141. if err != nil {
  142. return nil, errors.Wrapf(err, "InfluxdbQuery all hosts metrics")
  143. }
  144. for _, host := range allHosts {
  145. m := metrics.Get(host.GetId())
  146. if m == nil {
  147. return nil, errors.Errorf("Influxdb metrics of %s(%s) not found", host.GetName(), host.GetId())
  148. }
  149. if err := drv.SetHostCurrent(host.(IHost), m.Values); err != nil {
  150. return nil, errors.Wrapf(err, "SetHostCurrent %q", host.GetName())
  151. }
  152. }
  153. settings, err := alert.GetSettings()
  154. if err != nil {
  155. return nil, errors.Wrapf(err, "Get alert settings")
  156. }
  157. cond, err := drv.GetCondition(settings)
  158. if err != nil {
  159. return nil, errors.Wrapf(err, "Get Condtion")
  160. }
  161. rs := &Rules{
  162. Alert: alert,
  163. Condtion: cond,
  164. ResultMustPair: resultMustPair,
  165. }
  166. rs.Source = NewSourceRule(srcHost, cds)
  167. rs.Target = NewTargetRule(targetHosts)
  168. return rs, nil
  169. }
  170. func filterTargetHosts(drv IMetricDriver, srcHost IHost, allHost []jsonutils.JSONObject, ms *monitor.MigrationAlertSettings) ([]ITarget, error) {
  171. specifyTargetHostIds := []string{}
  172. specifySrcHostIds := []string{}
  173. if ms != nil && ms.Target != nil {
  174. specifyTargetHostIds = ms.Target.HostIds
  175. }
  176. if ms != nil && ms.Source != nil {
  177. specifySrcHostIds = ms.Source.HostIds
  178. }
  179. srcHostId := srcHost.GetId()
  180. srcHostObj := srcHost.GetObject()
  181. srcHostType, err := srcHostObj.GetString("host_type")
  182. if err != nil {
  183. return nil, errors.Wrap(err, "get source host_type")
  184. }
  185. srcArch, err := srcHostObj.GetString("cpu_architecture")
  186. if err != nil {
  187. return nil, errors.Wrapf(err, "get source cpu_architecture")
  188. }
  189. targets := make([]ITarget, 0)
  190. for _, obj := range allHost {
  191. id, err := obj.GetString("id")
  192. if err != nil {
  193. return nil, errors.Wrapf(err, "get host obj id: %s", obj)
  194. }
  195. if id == srcHostId {
  196. continue
  197. }
  198. if len(specifySrcHostIds) != 0 {
  199. if utils.IsInStringArray(id, specifySrcHostIds) {
  200. // filter target host if it in source specified hosts
  201. continue
  202. }
  203. }
  204. if len(specifyTargetHostIds) != 0 {
  205. // filter target host if it not in target specified hosts
  206. if !utils.IsInStringArray(id, specifyTargetHostIds) {
  207. continue
  208. }
  209. }
  210. hostType, _ := obj.GetString("host_type")
  211. if hostType != srcHostType {
  212. continue
  213. }
  214. arch, _ := obj.GetString("cpu_architecture")
  215. if arch != srcArch {
  216. continue
  217. }
  218. enabled, _ := obj.Bool("enabled")
  219. if !enabled {
  220. continue
  221. }
  222. hostStatus, _ := obj.GetString("host_status")
  223. if hostStatus != "online" {
  224. continue
  225. }
  226. th, err := drv.GetTarget(obj)
  227. if err != nil {
  228. return nil, errors.Wrapf(err, "drv.GetTarget %s", obj)
  229. }
  230. targets = append(targets, th)
  231. }
  232. return targets, nil
  233. }
  234. func findGuestsOfHost(drv IMetricDriver, host IHost, ds *tsdb.DataSource, ms *monitor.MigrationAlertSettings) ([]ICandidate, error) {
  235. ok, objs := models.MonitorResourceManager.GetResourceObjByResType(monitor.METRIC_RES_TYPE_GUEST)
  236. if !ok {
  237. return nil, errors.Errorf("GetResourceObjByResType by guest return false")
  238. }
  239. specifyGuestIds := []string{}
  240. if ms != nil && ms.Source != nil {
  241. specifyGuestIds = ms.Source.GuestIds
  242. }
  243. ret := make([]ICandidate, 0)
  244. found := false
  245. errs := []error{}
  246. for _, obj := range objs {
  247. gHostId, err := obj.GetString("host_id")
  248. if err != nil {
  249. return nil, errors.Wrapf(err, "get host_id from cache guest %s", obj)
  250. }
  251. if gHostId == host.GetId() {
  252. status, err := obj.GetString("status")
  253. if err != nil {
  254. return nil, errors.Wrapf(err, "get status of guest: %s", obj)
  255. }
  256. name, _ := obj.GetString("name")
  257. // filter running guest
  258. if status != computeapi.VM_RUNNING {
  259. log.Debugf("ignore guest %s cause status is %s", name, status)
  260. continue
  261. }
  262. gId, _ := obj.GetString("id")
  263. if len(specifyGuestIds) != 0 {
  264. if !utils.IsInStringArray(gId, specifyGuestIds) {
  265. log.Debugf("ignore guest %s(%s) cause not in specified ids %v", name, gId, specifyGuestIds)
  266. continue
  267. }
  268. }
  269. c, err := drv.GetCandidate(obj, host, ds)
  270. if err != nil {
  271. errs = append(errs, errors.Wrapf(err, "drv.GetCandidate of guest %s", obj))
  272. continue
  273. }
  274. if c.GetScore() == 0 {
  275. log.Debugf("ignore guest %s cause %s score is 0", c.GetName(), drv.GetType())
  276. continue
  277. }
  278. ret = append(ret, c)
  279. found = true
  280. }
  281. }
  282. if !found {
  283. return nil, errors.NewAggregate(errs)
  284. }
  285. if len(errs) != 0 {
  286. log.Warningf("not all guests found: %s", errors.NewAggregate(errs))
  287. }
  288. return ret, nil
  289. }
  290. // SourceRule 定义触发了报警的宿主机和上面可以迁移的虚拟机
  291. type SourceRule struct {
  292. Host IHost
  293. Candidates []ICandidate
  294. }
  295. func NewSourceRule(host IHost, cds []ICandidate) *SourceRule {
  296. return &SourceRule{
  297. Host: host,
  298. Candidates: cds,
  299. }
  300. }
  301. type IHost interface {
  302. IResource
  303. GetHostResource() *HostResource
  304. GetCurrent() float64
  305. SetCurrent(float64) IHost
  306. Compare(oh IHost) bool
  307. }
  308. // TargetRule 定义可以选择迁移的宿主机
  309. type TargetRule struct {
  310. Items []ITarget
  311. }
  312. func NewTargetRule(hosts []ITarget) *TargetRule {
  313. return &TargetRule{
  314. Items: hosts,
  315. }
  316. }
  317. type ItemType string
  318. const (
  319. ItemTypeHost = "host"
  320. ItemTypeGuest = "guest"
  321. )
  322. type ITarget interface {
  323. IHost
  324. Selected(c ICandidate) ITarget
  325. }
  326. type iTargets []ITarget
  327. func (i iTargets) Len() int {
  328. return len(i)
  329. }
  330. func (ts iTargets) Less(i, j int) bool {
  331. a, b := ts[i], ts[j]
  332. return a.Compare(b)
  333. }
  334. func (ts iTargets) Swap(i, j int) {
  335. ts[i], ts[j] = ts[j], ts[i]
  336. }
  337. func RecoverInProcessAlerts(ctx context.Context, s *mcclient.ClientSession) error {
  338. alerts, err := models.GetMigrationAlertManager().GetInMigrationAlerts()
  339. if err != nil {
  340. return errors.Wrap(err, "GetInMigrationAlerts")
  341. }
  342. recorder := NewRecorder()
  343. errs := make([]error, 0)
  344. for _, alert := range alerts {
  345. notes, err := alert.GetMigrateNotes()
  346. if err != nil {
  347. errs = append(errs, errors.Wrapf(err, "GetMigrateNotes for %s", alert.GetId()))
  348. continue
  349. }
  350. for _, note := range notes {
  351. log.Infof("Start recover alert %s(%s) note %s", alert.GetName(), alert.GetId(), jsonutils.Marshal(note))
  352. notePrt := &note
  353. recorder.StartWatchMigratingProcess(ctx, s, alert, notePrt)
  354. }
  355. }
  356. return errors.NewAggregate(errs)
  357. }
  358. func DoBalance(ctx context.Context, s *mcclient.ClientSession, rules *Rules, recorder IRecorder) error {
  359. // check whether having migration in process
  360. alerts, err := models.GetMigrationAlertManager().GetInMigrationAlerts()
  361. if err != nil {
  362. return errors.Wrap(err, "GetInMigrationAlerts")
  363. }
  364. if len(alerts) != 0 {
  365. ids := make([]string, len(alerts))
  366. for i := range alerts {
  367. alert := alerts[i]
  368. ids[i] = fmt.Sprintf("%s(%s)", alert.GetName(), alert.GetId())
  369. }
  370. return errors.Errorf("Others migration alerts in process: %v", ids)
  371. }
  372. rst, err := findResult(rules)
  373. if err != nil {
  374. err = errors.Wrapf(err, "find result to migrate")
  375. recorder.RecordError(s.GetToken(), rules.GetAlert(), err, EventActionFindResultFail)
  376. return err
  377. }
  378. if err := doMigrate(ctx, s, rules, rst, recorder); err != nil {
  379. return errors.Wrapf(err, "do migrate for result %#v", rst)
  380. }
  381. return nil
  382. }
  383. type result struct {
  384. pairs []*resultPair
  385. }
  386. type resultPair struct {
  387. source ICandidate
  388. target ITarget
  389. }
  390. func findResult(rules *Rules) (*result, error) {
  391. // 找到 rules.Source 里面可以迁移的虚拟机
  392. // guests, err := findCandidates(rules.Source, rules.Condtion)
  393. // if err != nil {
  394. // return nil, errors.Wrap(err, "find source candidates to migrate")
  395. // }
  396. // TODO
  397. // 将找到的 guests 进行配对,调用 scheduler-forecast 接口判断能否迁移到宿主机
  398. // 如果不能迁就提出这些 guests,重新 findCandidates
  399. // 将找到的虚拟机分配到对应的宿主机,形成 1-1 配对
  400. settings, _ := rules.GetAlert().GetMigrationSettings()
  401. return pairMigratResult(settings, rules.Source, rules.Target, rules.Condtion, rules.ResultMustPair)
  402. }
  403. type IResource interface {
  404. GetId() string
  405. GetName() string
  406. GetObject() jsonutils.JSONObject
  407. }
  408. type ICandidate interface {
  409. IResource
  410. GetHostName() string
  411. GetScore() float64
  412. }
  413. func getCScores(css []ICandidate) []float64 {
  414. ret := make([]float64, len(css))
  415. for i := range css {
  416. ret[i] = css[i].GetScore()
  417. }
  418. return ret
  419. }
  420. func findFitCandidates(css []ICandidate, delta float64) ([]ICandidate, error) {
  421. if len(css) == 0 {
  422. return nil, errors.Errorf("Not found fit guest candidate for delta %f", delta)
  423. }
  424. first := css[0]
  425. rest := css[1:]
  426. if first.GetScore() >= delta {
  427. return []ICandidate{first}, nil
  428. }
  429. rRests, err := findFitCandidates(rest, delta-first.GetScore())
  430. if err != nil {
  431. return nil, errors.Wrapf(err, "Found in rest %v", rest)
  432. }
  433. ret := []ICandidate{first}
  434. ret = append(ret, rRests...)
  435. return ret, nil
  436. }
  437. type candidatesThresholdSort struct {
  438. cds []ICandidate
  439. threshold float64
  440. }
  441. func newCandidatesThresholdSort(cds []ICandidate, th float64) *candidatesThresholdSort {
  442. return &candidatesThresholdSort{
  443. cds: cds,
  444. threshold: th,
  445. }
  446. }
  447. func (s *candidatesThresholdSort) Len() int {
  448. return len(s.cds)
  449. }
  450. func (s *candidatesThresholdSort) Swap(i, j int) {
  451. s.cds[i], s.cds[j] = s.cds[j], s.cds[i]
  452. }
  453. func (s *candidatesThresholdSort) Less(i, j int) bool {
  454. d1 := math.Abs(s.cds[i].GetScore() - s.threshold)
  455. d2 := math.Abs(s.cds[j].GetScore() - s.threshold)
  456. return d1 < d2
  457. }
  458. func (s *candidatesThresholdSort) CandidatesString() string {
  459. str := fmt.Sprintf("delta: %f\n", s.threshold)
  460. for _, c := range s.cds {
  461. str += fmt.Sprintf("%s: %f\n", c.GetName(), c.GetScore())
  462. }
  463. return str
  464. }
  465. func (s *candidatesThresholdSort) Debug(prefix string) {
  466. log.Infof("%s:\n%s", prefix, s.CandidatesString())
  467. }
  468. func sortCandidatesByThreshold(cds []ICandidate, th float64) []ICandidate {
  469. ss := newCandidatesThresholdSort(cds, th)
  470. // ss.Debug("Pre sort")
  471. sort.Sort(ss)
  472. // ss.Debug("After sort")
  473. return ss.cds
  474. }
  475. func findCandidates(src *SourceRule, cond ICondition) ([]ICandidate, error) {
  476. threshold := cond.GetThreshold()
  477. delta := cond.GetSourceThresholdDelta(threshold, src.Host)
  478. cds := sortCandidatesByThreshold(src.Candidates, threshold)
  479. return findFitCandidates(cds, delta)
  480. }
  481. func findFitTarget(settings *monitor.MigrationAlertSettings, c ICandidate, tr *TargetRule, targets iTargets, cond ICondition) (ITarget, error) {
  482. // sort targets
  483. sort.Sort(targets)
  484. var errs []error
  485. for i := range targets {
  486. target := targets[i]
  487. if err := cond.IsFitTarget(settings, target, c); err == nil {
  488. return target, nil
  489. } else {
  490. errs = append(errs, err)
  491. }
  492. }
  493. return nil, errors.NewAggregate(errs)
  494. }
  495. func pairMigratResult(
  496. settings *monitor.MigrationAlertSettings,
  497. src *SourceRule, target *TargetRule, cond ICondition, mustPair bool) (*result, error) {
  498. // all guests of source host to migrate
  499. gsts := src.Candidates
  500. pairs := make([]*resultPair, 0)
  501. hosts := target.Items
  502. errs := []error{}
  503. for _, gst := range gsts {
  504. host, err := findFitTarget(settings, gst, target, hosts, cond)
  505. if err != nil {
  506. err = errors.Wrapf(err, "not found target for guest %s on %s", gst.GetName(), gst.GetHostName())
  507. if mustPair {
  508. return nil, err
  509. } else {
  510. errs = append(errs, err)
  511. continue
  512. }
  513. }
  514. host.Selected(gst)
  515. pairs = append(pairs, &resultPair{
  516. source: gst,
  517. target: host,
  518. })
  519. }
  520. if len(gsts) != len(pairs) {
  521. if mustPair {
  522. return nil, errors.Errorf("%v: Paired: %d candidates != %d hosts", errors.NewAggregate(errs), len(gsts), len(pairs))
  523. }
  524. }
  525. if len(pairs) == 0 {
  526. return nil, errors.Errorf("%v: Not found any pairs, mustPair is %v", errors.NewAggregate(errs), mustPair)
  527. }
  528. if !mustPair && len(errs) != 0 {
  529. log.Warningf("some guest not paired: %v", errors.NewAggregate(errs))
  530. }
  531. return &result{
  532. pairs: pairs,
  533. }, nil
  534. }
  535. func doMigrate(ctx context.Context, s *mcclient.ClientSession, rules *Rules, rst *result, recorder IRecorder) error {
  536. // migrate must be executed on by one
  537. alert := rules.GetAlert()
  538. for _, pair := range rst.pairs {
  539. note, err := NewMigrateNote(pair, nil)
  540. if err != nil {
  541. return errors.Wrap(err, "NewMigrateNotes")
  542. }
  543. if obj, err := doMigrateByPair(s, pair); err != nil {
  544. err = errors.Wrapf(err, "doMigrateByPair %s to %s", pair.source.GetName(), pair.target.GetName())
  545. if rErr := recorder.RecordMigrateError(s.GetToken(), alert, note, err); rErr != nil {
  546. log.Errorf("RecordMigrate %s to %s error: %v", obj, pair.target.GetId(), rErr)
  547. }
  548. return err
  549. } else {
  550. if err := recorder.RecordMigrate(ctx, s, alert, note); err != nil {
  551. log.Errorf("RecordMigrate %s to %s error: %v", obj, pair.target.GetId(), err)
  552. }
  553. }
  554. }
  555. return nil
  556. }
  557. func doMigrateByPair(s *mcclient.ClientSession, pair *resultPair) (jsonutils.JSONObject, error) {
  558. gst := pair.source
  559. trueObj := true
  560. input := &compute_options.ServerLiveMigrateOptions{
  561. ID: gst.GetId(),
  562. PreferHost: pair.target.GetId(),
  563. SkipCpuCheck: &trueObj,
  564. SkipKernelCheck: &trueObj,
  565. }
  566. params, err := input.Params()
  567. if err != nil {
  568. return nil, errors.Wrapf(err, "live migrate input %#v", input)
  569. }
  570. obj, err := compute.Servers.PerformAction(s, input.GetId(), "live-migrate", params)
  571. if err != nil {
  572. return nil, errors.Wrapf(err, "live migrate with params: %s", params)
  573. }
  574. return obj, nil
  575. }
  576. type resource struct {
  577. id string
  578. name string
  579. obj jsonutils.JSONObject
  580. }
  581. func newResource(obj jsonutils.JSONObject) (IResource, error) {
  582. id, err := obj.GetString("id")
  583. if err != nil {
  584. return nil, errors.Wrap(err, "get id")
  585. }
  586. name, err := obj.GetString("name")
  587. if err != nil {
  588. return nil, errors.Wrap(err, "get name")
  589. }
  590. return &resource{
  591. id: id,
  592. name: name,
  593. obj: obj,
  594. }, nil
  595. }
  596. func (r *resource) GetId() string {
  597. return r.id
  598. }
  599. func (r *resource) GetName() string {
  600. return r.name
  601. }
  602. func (r *resource) GetObject() jsonutils.JSONObject {
  603. return r.obj
  604. }
  605. type guestResource struct {
  606. IResource
  607. hostName string
  608. guest jsonutils.JSONObject
  609. }
  610. func newGuestResource(gst jsonutils.JSONObject, hostName string) (*guestResource, error) {
  611. res, err := newResource(gst)
  612. if err != nil {
  613. return nil, errors.Wrap(err, "newResource")
  614. }
  615. return &guestResource{
  616. IResource: res,
  617. hostName: hostName,
  618. guest: gst,
  619. }, nil
  620. }
  621. func (s *guestResource) GetHostName() string {
  622. return s.hostName
  623. }
  624. type HostResource struct {
  625. IResource
  626. host jsonutils.JSONObject
  627. totalMemSize float64
  628. cpuCount int64
  629. }
  630. func newHostResource(host jsonutils.JSONObject) (*HostResource, error) {
  631. res, err := newResource(host)
  632. if err != nil {
  633. return nil, errors.Wrap(err, "newResource")
  634. }
  635. memSize, err := host.Int("mem_size")
  636. if err != nil {
  637. return nil, errors.Wrap(err, "get mem_size")
  638. }
  639. cpuCount, err := host.Int("cpu_count")
  640. if err != nil {
  641. return nil, errors.Wrap(err, "get cpu_count")
  642. }
  643. return &HostResource{
  644. IResource: res,
  645. host: host,
  646. totalMemSize: float64(memSize * 1024 * 1024),
  647. cpuCount: cpuCount,
  648. }, nil
  649. }
  650. func (h *HostResource) GetHostResource() *HostResource {
  651. return h
  652. }