guest_detach_all_disks_task.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 guest
  15. import (
  16. "context"
  17. "yunion.io/x/jsonutils"
  18. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  19. "yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
  20. "yunion.io/x/onecloud/pkg/compute/models"
  21. )
  22. type GuestDetachAllDisksTask struct {
  23. SGuestBaseTask
  24. }
  25. func init() {
  26. taskman.RegisterTask(GuestDetachAllDisksTask{})
  27. }
  28. func (self *GuestDetachAllDisksTask) OnInit(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
  29. self.SetStage("OnDiskDeleteComplete", nil)
  30. self.OnDiskDeleteComplete(ctx, obj, data)
  31. }
  32. func (self *GuestDetachAllDisksTask) OnDiskDeleteComplete(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
  33. guest := obj.(*models.SGuest)
  34. cnt, err := guest.DiskCount()
  35. if err != nil {
  36. self.SetStageFailed(ctx, jsonutils.NewString(err.Error()))
  37. return
  38. }
  39. if cnt == 0 {
  40. self.SetStageComplete(ctx, nil)
  41. return
  42. }
  43. host, _ := guest.GetHost()
  44. purge := false
  45. if (host == nil || !host.GetEnabled()) && jsonutils.QueryBoolean(self.Params, "purge", false) {
  46. purge = true
  47. }
  48. guestDisks, _ := guest.GetGuestDisks()
  49. for _, guestdisk := range guestDisks {
  50. taskData := jsonutils.NewDict()
  51. taskData.Add(jsonutils.NewString(guestdisk.DiskId), "disk_id")
  52. if purge {
  53. taskData.Add(jsonutils.JSONTrue, "purge")
  54. }
  55. if jsonutils.QueryBoolean(self.Params, "override_pending_delete", false) {
  56. taskData.Add(jsonutils.JSONTrue, "override_pending_delete")
  57. }
  58. taskData.Add(jsonutils.JSONFalse, "keep_disk")
  59. task, err := taskman.TaskManager.NewTask(ctx, "GuestDetachDiskTask", guest, self.UserCred, taskData, self.GetTaskId(), "", nil)
  60. if err != nil {
  61. self.SetStageFailed(ctx, jsonutils.NewString(err.Error()))
  62. } else {
  63. task.ScheduleRun(nil)
  64. }
  65. break
  66. }
  67. }