delay.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 handler
  15. import (
  16. "context"
  17. "fmt"
  18. "yunion.io/x/jsonutils"
  19. "yunion.io/x/onecloud/pkg/appsrv"
  20. "yunion.io/x/onecloud/pkg/mcclient"
  21. modules "yunion.io/x/onecloud/pkg/mcclient/modules/compute"
  22. )
  23. var delayTaskWorkerMan *appsrv.SWorkerManager
  24. func init() {
  25. delayTaskWorkerMan = appsrv.NewWorkerManager("DelayTaskWorkerManager", 8, 1024, false)
  26. }
  27. type ProcessFunc func(ctx context.Context, data jsonutils.JSONObject) (jsonutils.JSONObject, error)
  28. type delayTask struct {
  29. ctx context.Context
  30. process ProcessFunc
  31. taskId string
  32. session *mcclient.ClientSession
  33. data jsonutils.JSONObject
  34. }
  35. func (t *delayTask) Run() {
  36. ret, err := t.process(t.ctx, t.data)
  37. if err != nil {
  38. modules.ComputeTasks.TaskFailed(t.session, t.taskId, err)
  39. return
  40. }
  41. if len(t.taskId) > 0 {
  42. modules.ComputeTasks.TaskComplete(t.session, t.taskId, ret)
  43. }
  44. }
  45. func (t *delayTask) Dump() string {
  46. return fmt.Sprintf("taskId: %s data: %v", t.taskId, t.data)
  47. }
  48. func newDelayTask(process ProcessFunc, session *mcclient.ClientSession, taskId string, data jsonutils.JSONObject) *delayTask {
  49. return &delayTask{
  50. process: process,
  51. taskId: taskId,
  52. session: session,
  53. data: data,
  54. }
  55. }
  56. func DelayProcess(process ProcessFunc, session *mcclient.ClientSession, taskId string, data jsonutils.JSONObject) {
  57. task := &delayTask{
  58. process: process,
  59. taskId: taskId,
  60. session: session,
  61. data: data,
  62. }
  63. delayTaskWorkerMan.Run(task, nil, nil)
  64. }