schedule.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 utils
  15. import (
  16. "context"
  17. "fmt"
  18. "sort"
  19. "yunion.io/x/jsonutils"
  20. api "yunion.io/x/onecloud/pkg/apis/compute"
  21. schedapi "yunion.io/x/onecloud/pkg/apis/scheduler"
  22. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  23. "yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
  24. "yunion.io/x/onecloud/pkg/cloudcommon/db/quotas"
  25. "yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
  26. "yunion.io/x/onecloud/pkg/cloudcommon/notifyclient"
  27. "yunion.io/x/onecloud/pkg/compute/models"
  28. "yunion.io/x/onecloud/pkg/compute/options"
  29. "yunion.io/x/onecloud/pkg/mcclient"
  30. "yunion.io/x/onecloud/pkg/mcclient/auth"
  31. "yunion.io/x/onecloud/pkg/mcclient/modules/scheduler"
  32. "yunion.io/x/onecloud/pkg/util/logclient"
  33. )
  34. type IScheduleModel interface {
  35. db.IStandaloneModel
  36. SetStatus(ctx context.Context, userCred mcclient.TokenCredential, status string, reason string) error
  37. }
  38. type IScheduleTask interface {
  39. GetUserCred() mcclient.TokenCredential
  40. GetSchedParams() (*schedapi.ScheduleInput, error)
  41. GetPendingUsage(quota quotas.IQuota, index int) error
  42. SetStage(stageName string, data *jsonutils.JSONDict) error
  43. SetStageFailed(ctx context.Context, reason jsonutils.JSONObject)
  44. OnStartSchedule(obj IScheduleModel)
  45. OnScheduleFailCallback(ctx context.Context, obj IScheduleModel, reason jsonutils.JSONObject, index int)
  46. // OnScheduleComplete(ctx context.Context, items []db.IStandaloneModel, data *jsonutils.JSONDict)
  47. SaveScheduleResult(ctx context.Context, obj IScheduleModel, candidate *schedapi.CandidateResource, index int)
  48. SaveScheduleResultWithBackup(ctx context.Context, obj IScheduleModel, master, slave *schedapi.CandidateResource, index int)
  49. OnScheduleFailed(ctx context.Context, reason jsonutils.JSONObject)
  50. }
  51. type SSchedTask struct {
  52. taskman.STask
  53. input *schedapi.ScheduleInput
  54. }
  55. func (self *SSchedTask) OnStartSchedule(obj IScheduleModel) {
  56. db.OpsLog.LogEvent(obj, db.ACT_ALLOCATING, nil, self.GetUserCred())
  57. obj.SetStatus(context.Background(), self.GetUserCred(), api.VM_SCHEDULE, "")
  58. }
  59. func (self *SSchedTask) OnScheduleFailCallback(ctx context.Context, obj IScheduleModel, reason jsonutils.JSONObject, index int) {
  60. obj.SetStatus(ctx, self.GetUserCred(), api.VM_SCHEDULE_FAILED, reason.String())
  61. db.OpsLog.LogEvent(obj, db.ACT_ALLOCATE_FAIL, reason, self.GetUserCred())
  62. logclient.AddActionLogWithStartable(self, obj, logclient.ACT_ALLOCATE, reason, self.GetUserCred(), false)
  63. notifyclient.NotifySystemErrorWithCtx(ctx, obj.GetId(), obj.GetName(), api.VM_SCHEDULE_FAILED, reason.String())
  64. }
  65. func (self *SSchedTask) OnScheduleComplete(ctx context.Context, items []db.IStandaloneModel, data *jsonutils.JSONDict) {
  66. self.SetStageComplete(ctx, nil)
  67. }
  68. func (self *SSchedTask) SaveScheduleResult(ctx context.Context, obj IScheduleModel, candidate *schedapi.CandidateResource, index int) {
  69. // ...
  70. }
  71. func (self *SSchedTask) SaveScheduleResultWithBackup(ctx context.Context, obj IScheduleModel, master, slave *schedapi.CandidateResource, index int) {
  72. // ...
  73. }
  74. func (self *SSchedTask) OnScheduleFailed(ctx context.Context, reason jsonutils.JSONObject) {
  75. self.SetStageFailed(ctx, reason)
  76. }
  77. func StartScheduleObjects(
  78. ctx context.Context,
  79. task IScheduleTask,
  80. objs []db.IStandaloneModel,
  81. ) {
  82. schedObjs := make([]IScheduleModel, len(objs))
  83. for i, obj := range objs {
  84. schedObj := obj.(IScheduleModel)
  85. schedObjs[i] = schedObj
  86. task.OnStartSchedule(schedObj)
  87. }
  88. doScheduleObjects(ctx, task, schedObjs)
  89. }
  90. func doScheduleWithInput(
  91. ctx context.Context,
  92. task IScheduleTask,
  93. schedInput *schedapi.ScheduleInput,
  94. count int,
  95. ) (*schedapi.ScheduleOutput, error) {
  96. computeUsage := models.SQuota{}
  97. task.GetPendingUsage(&computeUsage, 0)
  98. regionUsage := models.SRegionQuota{}
  99. task.GetPendingUsage(&regionUsage, 1)
  100. schedInput.PendingUsages = []jsonutils.JSONObject{
  101. jsonutils.Marshal(&computeUsage),
  102. jsonutils.Marshal(&regionUsage),
  103. }
  104. var params *jsonutils.JSONDict
  105. if count > 0 {
  106. // if object count <=0, don't need update schedule params
  107. params = jsonutils.Marshal(schedInput).(*jsonutils.JSONDict)
  108. }
  109. task.SetStage("OnScheduleComplete", params)
  110. s := auth.GetSession(ctx, task.GetUserCred(), options.Options.Region)
  111. return scheduler.SchedManager.DoSchedule(s, schedInput, count)
  112. }
  113. func doScheduleObjects(
  114. ctx context.Context,
  115. task IScheduleTask,
  116. objs []IScheduleModel,
  117. ) {
  118. schedInput, err := task.GetSchedParams()
  119. if err != nil {
  120. onSchedulerRequestFail(ctx, task, objs, jsonutils.NewString(fmt.Sprintf("GetSchedParams fail: %s", err)))
  121. return
  122. }
  123. sort.Sort(sortedIScheduleModelList(objs))
  124. schedInput.GuestIds = make([]string, len(objs))
  125. for i := range objs {
  126. schedInput.GuestIds[i] = objs[i].GetId()
  127. }
  128. output, err := doScheduleWithInput(ctx, task, schedInput, len(objs))
  129. if err != nil {
  130. onSchedulerRequestFail(ctx, task, objs, jsonutils.NewString(err.Error()))
  131. return
  132. }
  133. onSchedulerResults(ctx, task, objs, output.Candidates)
  134. }
  135. func cancelPendingUsage(ctx context.Context, task IScheduleTask) {
  136. ClearTaskPendingUsage(ctx, task.(taskman.ITask))
  137. ClearTaskPendingRegionUsage(ctx, task.(taskman.ITask))
  138. }
  139. func onSchedulerRequestFail(
  140. ctx context.Context,
  141. task IScheduleTask,
  142. objs []IScheduleModel,
  143. reason jsonutils.JSONObject,
  144. ) {
  145. for i, obj := range objs {
  146. onObjScheduleFail(ctx, task, obj, reason, i)
  147. }
  148. task.OnScheduleFailed(ctx, reason)
  149. cancelPendingUsage(ctx, task)
  150. }
  151. func onObjScheduleFail(
  152. ctx context.Context,
  153. task IScheduleTask,
  154. obj IScheduleModel,
  155. msg jsonutils.JSONObject,
  156. idx int,
  157. ) {
  158. lockman.LockObject(ctx, obj)
  159. defer lockman.ReleaseObject(ctx, obj)
  160. var reason jsonutils.JSONObject
  161. reason = jsonutils.NewString("No matching resources")
  162. if msg != nil {
  163. reason = jsonutils.NewArray(reason, msg)
  164. }
  165. task.OnScheduleFailCallback(ctx, obj, reason, idx)
  166. }
  167. type sortedIScheduleModelList []IScheduleModel
  168. func (a sortedIScheduleModelList) Len() int { return len(a) }
  169. func (a sortedIScheduleModelList) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  170. func (a sortedIScheduleModelList) Less(i, j int) bool { return a[i].GetName() < a[j].GetName() }
  171. func onSchedulerResults(
  172. ctx context.Context,
  173. task IScheduleTask,
  174. objs []IScheduleModel,
  175. results []*schedapi.CandidateResource,
  176. ) {
  177. if len(objs) == 0 {
  178. // sched with out object can't clean sched cache immediately
  179. task.SaveScheduleResult(ctx, nil, results[0], 0)
  180. return
  181. }
  182. succCount := 0
  183. for idx := 0; idx < len(objs); idx += 1 {
  184. obj := objs[idx]
  185. result := results[idx]
  186. if len(result.Error) != 0 {
  187. onObjScheduleFail(ctx, task, obj, jsonutils.NewString(result.Error), idx)
  188. continue
  189. }
  190. if result.BackupCandidate == nil {
  191. // normal schedule
  192. onScheduleSucc(ctx, task, obj, result, idx)
  193. } else {
  194. // backup schedule
  195. onMasterSlaveScheduleSucc(ctx, task, obj, result, result.BackupCandidate, idx)
  196. }
  197. succCount += 1
  198. }
  199. if succCount == 0 {
  200. task.OnScheduleFailed(ctx, jsonutils.NewString("Schedule failed"))
  201. }
  202. cancelPendingUsage(ctx, task)
  203. }
  204. func onMasterSlaveScheduleSucc(
  205. ctx context.Context,
  206. task IScheduleTask,
  207. obj IScheduleModel,
  208. master, slave *schedapi.CandidateResource,
  209. index int,
  210. ) {
  211. lockman.LockObject(ctx, obj)
  212. defer lockman.ReleaseObject(ctx, obj)
  213. task.SaveScheduleResultWithBackup(ctx, obj, master, slave, index)
  214. models.HostManager.ClearSchedDescSessionCache(master.HostId, master.SessionId)
  215. models.HostManager.ClearSchedDescSessionCache(slave.HostId, slave.SessionId)
  216. }
  217. func onScheduleSucc(
  218. ctx context.Context,
  219. task IScheduleTask,
  220. obj IScheduleModel,
  221. candidate *schedapi.CandidateResource,
  222. index int,
  223. ) {
  224. hostId := candidate.HostId
  225. lockman.LockRawObject(ctx, models.HostManager.KeywordPlural(), hostId)
  226. defer lockman.ReleaseRawObject(ctx, models.HostManager.KeywordPlural(), hostId)
  227. task.SaveScheduleResult(ctx, obj, candidate, index)
  228. models.HostManager.ClearSchedDescSessionCache(candidate.HostId, candidate.SessionId)
  229. }
  230. func GetBatchParamsAtIndex(task taskman.ITask, index int) *jsonutils.JSONDict {
  231. var data *jsonutils.JSONDict
  232. params := task.GetParams()
  233. paramsArray, _ := params.GetArray("data")
  234. if len(paramsArray) > 0 {
  235. if len(paramsArray) > index {
  236. data = paramsArray[index].(*jsonutils.JSONDict)
  237. } else {
  238. data = paramsArray[0].(*jsonutils.JSONDict)
  239. }
  240. } else {
  241. data = params
  242. }
  243. return data
  244. }