worker.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 models
  15. import (
  16. "fmt"
  17. "yunion.io/x/log"
  18. "yunion.io/x/onecloud/pkg/appsrv"
  19. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  20. )
  21. var modelTaskMan *appsrv.SWorkerManager
  22. func GetModelTaskManager() *appsrv.SWorkerManager {
  23. if modelTaskMan == nil {
  24. modelTaskMan = appsrv.NewWorkerManager("ModelTaskWorkerManager", 4, 1024, true)
  25. }
  26. return modelTaskMan
  27. }
  28. type modelTask struct {
  29. name string
  30. object db.IStandaloneModel
  31. backgroundFunc func() error
  32. }
  33. func newModelTask(name string, obj db.IStandaloneModel, f func() error) appsrv.IWorkerTask {
  34. return &modelTask{
  35. name: name,
  36. object: obj,
  37. backgroundFunc: f,
  38. }
  39. }
  40. func (t *modelTask) getObjectDesc() string {
  41. return fmt.Sprintf("%s(%s)", t.object.GetName(), t.object.GetId())
  42. }
  43. func (t *modelTask) Run() {
  44. if err := t.backgroundFunc(); err != nil {
  45. log.Errorf("execute %s for model %s: %v", t.name, t.getObjectDesc(), err)
  46. }
  47. }
  48. func (t *modelTask) Dump() string {
  49. return fmt.Sprintf("Task %s for model %s", t.name, t.getObjectDesc())
  50. }
  51. func RunModelTask(name string, obj db.IStandaloneModel, f func() error) {
  52. GetModelTaskManager().Run(newModelTask(name, obj, f), nil, nil)
  53. }