project_clean_task.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 tasks
  15. import (
  16. "context"
  17. "yunion.io/x/jsonutils"
  18. "yunion.io/x/pkg/errors"
  19. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  20. "yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
  21. "yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
  22. "yunion.io/x/onecloud/pkg/keystone/models"
  23. "yunion.io/x/onecloud/pkg/util/logclient"
  24. )
  25. type ProjectCleanTask struct {
  26. taskman.STask
  27. }
  28. func init() {
  29. taskman.RegisterTask(ProjectCleanTask{})
  30. }
  31. func (task *ProjectCleanTask) OnInit(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
  32. project := obj.(*models.SProject)
  33. empty, err := project.GetEmptyProjects()
  34. if err != nil {
  35. logclient.AddActionLogWithStartable(task, project, logclient.ACT_CLEAN_PROJECT, errors.Wrapf(err, "GetEmptyProjects"), task.UserCred, false)
  36. task.SetStageFailed(ctx, jsonutils.NewString(err.Error()))
  37. return
  38. }
  39. cnt, failed := 0, []error{}
  40. for i := range empty {
  41. lockman.LockObject(ctx, &empty[i])
  42. defer lockman.ReleaseObject(ctx, &empty[i])
  43. err = empty[i].Delete(ctx, task.UserCred)
  44. if err != nil {
  45. failed = append(failed, err)
  46. continue
  47. }
  48. cnt++
  49. }
  50. logclient.AddActionLogWithStartable(task, project, logclient.ACT_CLEAN_PROJECT, map[string]interface{}{"clean": cnt, "failed": errors.NewAggregate(failed).Error()}, task.UserCred, true)
  51. task.SetStageComplete(ctx, nil)
  52. }