manager.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 workmanager
  15. import (
  16. "context"
  17. "runtime/debug"
  18. "sync/atomic"
  19. "time"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/log"
  22. "yunion.io/x/pkg/appctx"
  23. "yunion.io/x/pkg/errors"
  24. "yunion.io/x/pkg/util/version"
  25. "yunion.io/x/onecloud/pkg/appsrv"
  26. "yunion.io/x/onecloud/pkg/mcclient/modules/yunionconf"
  27. )
  28. type DelayTaskFunc func(context.Context, interface{}) (jsonutils.JSONObject, error)
  29. type OnTaskFailed func(context.Context, string)
  30. type OnTaskCompleted func(context.Context, jsonutils.JSONObject)
  31. type SWorkManager struct {
  32. curCount int32
  33. onFailed OnTaskFailed
  34. onCompleted OnTaskCompleted
  35. worker *appsrv.SWorkerManager
  36. }
  37. func (w *SWorkManager) add() {
  38. atomic.AddInt32(&w.curCount, 1)
  39. }
  40. func (w *SWorkManager) done() {
  41. atomic.AddInt32(&w.curCount, -1)
  42. }
  43. func (w *SWorkManager) DelayTask(ctx context.Context, task DelayTaskFunc, params interface{}) {
  44. w.delayTask(ctx, task, params, w.worker)
  45. }
  46. func (w *SWorkManager) DelayTaskWithWorker(
  47. ctx context.Context, task DelayTaskFunc, params interface{}, worker *appsrv.SWorkerManager,
  48. ) {
  49. w.delayTask(ctx, task, params, worker)
  50. }
  51. type workerTask struct {
  52. ctx context.Context
  53. w *SWorkManager
  54. task DelayTaskFunc
  55. params interface{}
  56. }
  57. func (t *workerTask) Run() {
  58. defer t.w.done()
  59. defer func() {
  60. if r := recover(); r != nil {
  61. log.Errorf("DelayTask panic: %s", r)
  62. yunionconf.BugReport.SendBugReport(t.ctx, version.GetShortString(), string(debug.Stack()), errors.Errorf("%s", r))
  63. debug.PrintStack()
  64. switch val := r.(type) {
  65. case string:
  66. t.w.onFailed(t.ctx, val)
  67. case error:
  68. t.w.onFailed(t.ctx, val.Error())
  69. default:
  70. t.w.onFailed(t.ctx, "Unknown panic")
  71. }
  72. }
  73. }()
  74. // HACK: callback only
  75. if t.task == nil {
  76. t.w.onCompleted(t.ctx, nil)
  77. return
  78. }
  79. res, err := t.task(t.ctx, t.params)
  80. if err != nil {
  81. log.Infof("DelayTask failed: %s", err)
  82. t.w.onFailed(t.ctx, err.Error())
  83. } else {
  84. log.Infof("DelayTask complete: %v", res)
  85. t.w.onCompleted(t.ctx, res)
  86. }
  87. }
  88. func (t *workerTask) Dump() string {
  89. return ""
  90. }
  91. // If delay task is not panic and task func return err is nil
  92. // task complete will be called, otherwise called task failed
  93. // Params is interface for receive any type, task func should do type assertion
  94. func (w *SWorkManager) delayTask(ctx context.Context, task DelayTaskFunc, params interface{}, worker *appsrv.SWorkerManager) {
  95. if ctx == nil || ctx.Value(appctx.APP_CONTEXT_KEY_TASK_ID) == nil {
  96. w.delayTaskWithoutReqctx(ctx, task, params, worker)
  97. return
  98. } else {
  99. // delayTask should have a new context.Context with value 'taskid'
  100. ctx = context.WithValue(context.Background(), appctx.APP_CONTEXT_KEY_TASK_ID, ctx.Value(appctx.APP_CONTEXT_KEY_TASK_ID))
  101. w.add()
  102. t := workerTask{
  103. ctx: ctx,
  104. w: w,
  105. task: task,
  106. params: params,
  107. }
  108. worker.Run(&t, nil, nil)
  109. }
  110. }
  111. func (w *SWorkManager) DelayTaskWithoutReqctx(ctx context.Context, task DelayTaskFunc, params interface{}) {
  112. w.delayTaskWithoutReqctx(ctx, task, params, w.worker)
  113. }
  114. type delayWorkerTask struct {
  115. w *SWorkManager
  116. task DelayTaskFunc
  117. ctx context.Context
  118. params interface{}
  119. }
  120. func (t *delayWorkerTask) Run() {
  121. defer t.w.done()
  122. defer func() {
  123. if r := recover(); r != nil {
  124. log.Errorln("DelayTaskWithoutReqctx panic: ", r)
  125. debug.PrintStack()
  126. yunionconf.BugReport.SendBugReport(t.ctx, version.GetShortString(), string(debug.Stack()), errors.Errorf("%s", r))
  127. }
  128. }()
  129. if t.task == nil {
  130. return
  131. }
  132. if _, err := t.task(t.ctx, t.params); err != nil {
  133. log.Errorln("DelayTaskWithoutReqctx error: ", err)
  134. t.w.onFailed(t.ctx, err.Error())
  135. }
  136. }
  137. func (t *delayWorkerTask) Dump() string {
  138. return ""
  139. }
  140. // response task by self, did not callback
  141. func (w *SWorkManager) delayTaskWithoutReqctx(
  142. ctx context.Context, task DelayTaskFunc, params interface{}, worker *appsrv.SWorkerManager,
  143. ) {
  144. // delayTaskWithoutReqctx should have a new context.Context
  145. newCtx := context.Background()
  146. if ctx != nil && ctx.Value(appctx.APP_CONTEXT_KEY_TASK_ID) != nil {
  147. newCtx = context.WithValue(newCtx, appctx.APP_CONTEXT_KEY_TASK_ID, ctx.Value(appctx.APP_CONTEXT_KEY_TASK_ID))
  148. }
  149. ctx = newCtx
  150. w.add()
  151. t := delayWorkerTask{
  152. w: w,
  153. task: task,
  154. ctx: ctx,
  155. params: params,
  156. }
  157. w.worker.Run(&t, nil, nil)
  158. }
  159. func (w *SWorkManager) Stop() {
  160. log.Infof("WorkManager stop, waitting for workers ...")
  161. for w.curCount > 0 {
  162. log.Warningf("Busy workers count %d, waiting stopped", w.curCount)
  163. time.Sleep(1 * time.Second)
  164. }
  165. }
  166. func NewWorkManger(name string, onFailed OnTaskFailed, onCompleted OnTaskCompleted, workerCount int) *SWorkManager {
  167. if len(name) == 0 {
  168. name = "RequestWorker"
  169. }
  170. if workerCount <= 0 {
  171. workerCount = 1
  172. }
  173. return &SWorkManager{
  174. onFailed: onFailed,
  175. onCompleted: onCompleted,
  176. worker: appsrv.NewWorkerManager(
  177. name, workerCount, appsrv.DEFAULT_BACKLOG, false),
  178. }
  179. }