You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

aiScheduler.go 9.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*
  2. Copyright (c) [2023] [pcm]
  3. [pcm-coordinator] is licensed under Mulan PSL v2.
  4. You can use this software according to the terms and conditions of the Mulan PSL v2.
  5. You may obtain a copy of Mulan PSL v2 at:
  6. http://license.coscl.org.cn/MulanPSL2
  7. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
  8. EITHER EXPaRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
  9. MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
  10. See the Mulan PSL v2 for more details.
  11. */
  12. package schedulers
  13. import (
  14. "context"
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "github.com/zeromicro/go-zero/core/logx"
  19. "gitlink.org.cn/JointCloud/pcm-ac/hpcAC"
  20. "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/scheduler"
  21. "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/scheduler/schedulers/option"
  22. "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/scheduler/service/collector"
  23. "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/scheduler/strategy"
  24. "gitlink.org.cn/JointCloud/pcm-coordinator/api/pkg/response"
  25. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants"
  26. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
  27. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
  28. "gitlink.org.cn/JointCloud/pcm-octopus/octopus"
  29. "sync"
  30. )
  31. type AiScheduler struct {
  32. yamlString string
  33. task *response.TaskInfo
  34. *scheduler.Scheduler
  35. option *option.AiOption
  36. ctx context.Context
  37. }
  38. type AiResult struct {
  39. JobId string
  40. ClusterId string
  41. Strategy string
  42. Replica int32
  43. Card string
  44. Msg string
  45. }
  46. func NewAiScheduler(ctx context.Context, val string, scheduler *scheduler.Scheduler, option *option.AiOption) (*AiScheduler, error) {
  47. return &AiScheduler{ctx: ctx, yamlString: val, Scheduler: scheduler, option: option}, nil
  48. }
  49. func (as *AiScheduler) GetNewStructForDb(task *response.TaskInfo, resource string, participantId int64) (interface{}, error) {
  50. ai := models.Ai{
  51. AdapterId: participantId,
  52. TaskId: task.TaskId,
  53. Status: "Saved",
  54. YamlString: as.yamlString,
  55. }
  56. utils.Convert(task.Metadata, &ai)
  57. return ai, nil
  58. }
  59. func (as *AiScheduler) PickOptimalStrategy() (strategy.Strategy, error) {
  60. if len(as.option.ClusterIds) == 1 {
  61. return &strategy.SingleAssignment{Cluster: &strategy.AssignedCluster{ClusterId: as.option.ClusterIds[0], Replicas: 1}}, nil
  62. }
  63. /* resources, err := as.findClustersWithResources()
  64. if err != nil {
  65. return nil, err
  66. }
  67. if len(resources) == 0 {
  68. return nil, errors.New("no cluster has resources")
  69. }
  70. if len(resources) == 1 {
  71. var cluster strategy.AssignedCluster
  72. cluster.ClusterId = resources[0].ClusterId
  73. cluster.Replicas = 1
  74. return &strategy.SingleAssignment{Cluster: &cluster}, nil
  75. }
  76. params := &param.Params{Resources: resources}*/
  77. switch as.option.StrategyName {
  78. case strategy.REPLICATION:
  79. var clusterIds []string
  80. /* for _, resource := range resources {
  81. clusterIds = append(clusterIds, resource.ClusterId)
  82. }*/
  83. strategy := strategy.NewReplicationStrategy(clusterIds, 1)
  84. return strategy, nil
  85. /* case strategy.RESOURCES_PRICING:
  86. strategy := strategy.NewPricingStrategy(&param.ResourcePricingParams{Params: params, Replicas: 1})
  87. return strategy, nil
  88. case strategy.DYNAMIC_RESOURCES:
  89. strategy := strategy.NewDynamicResourcesStrategy(params.Resources, as.option, 1)
  90. return strategy, nil*/
  91. case strategy.STATIC_WEIGHT:
  92. //todo resources should match cluster StaticWeightMap
  93. strategy := strategy.NewStaticWeightStrategy(as.option.ClusterToStaticWeight, as.option.Replica)
  94. return strategy, nil
  95. case strategy.RANDOM:
  96. strategy := strategy.NewRandomStrategy(as.option.ClusterIds, as.option.Replica)
  97. return strategy, nil
  98. }
  99. return nil, errors.New("no strategy has been chosen")
  100. }
  101. func (as *AiScheduler) AssignTask(clusters []*strategy.AssignedCluster) (interface{}, error) {
  102. if clusters == nil {
  103. return nil, errors.New("clusters is nil")
  104. }
  105. for i := len(clusters) - 1; i >= 0; i-- {
  106. if clusters[i].Replicas == 0 {
  107. clusters = append(clusters[:i], clusters[i+1:]...)
  108. }
  109. }
  110. if len(clusters) == 0 {
  111. return nil, errors.New("clusters is nil")
  112. }
  113. var wg sync.WaitGroup
  114. var results []*AiResult
  115. var errs []interface{}
  116. var ch = make(chan *AiResult, len(clusters))
  117. var errCh = make(chan interface{}, len(clusters))
  118. executorMap := as.AiService.AiExecutorAdapterMap[as.option.AdapterId]
  119. for _, cluster := range clusters {
  120. c := cluster
  121. wg.Add(1)
  122. go func() {
  123. opt, _ := cloneAiOption(as.option)
  124. resp, err := executorMap[c.ClusterId].Execute(as.ctx, opt)
  125. if err != nil {
  126. e := struct {
  127. err error
  128. clusterId string
  129. }{
  130. err: err,
  131. clusterId: c.ClusterId,
  132. }
  133. errCh <- e
  134. wg.Done()
  135. return
  136. }
  137. result, _ := convertType(resp)
  138. result.Replica = c.Replicas
  139. result.ClusterId = c.ClusterId
  140. result.Strategy = as.option.StrategyName
  141. result.Card = opt.ComputeCard
  142. ch <- result
  143. wg.Done()
  144. }()
  145. }
  146. wg.Wait()
  147. close(ch)
  148. close(errCh)
  149. for e := range errCh {
  150. errs = append(errs, e)
  151. }
  152. for s := range ch {
  153. results = append(results, s)
  154. }
  155. if len(errs) != 0 {
  156. var synergystatus int64
  157. if len(clusters) > 1 {
  158. synergystatus = 1
  159. }
  160. strategyCode, err := as.AiStorages.GetStrategyCode(as.option.StrategyName)
  161. taskId, err := as.AiStorages.SaveTask(as.option.TaskName, strategyCode, synergystatus)
  162. if err != nil {
  163. return nil, errors.New("database add failed: " + err.Error())
  164. }
  165. var errmsg string
  166. for _, err := range errs {
  167. e := (err).(struct {
  168. err error
  169. clusterId string
  170. })
  171. msg := fmt.Sprintf("clusterId: %v , error: %v \n", e.clusterId, e.err.Error())
  172. errmsg += msg
  173. clusterName, _ := as.AiStorages.GetClusterNameById(e.clusterId)
  174. err := as.AiStorages.SaveAiTask(taskId, as.option, e.clusterId, clusterName, "", constants.Failed, msg)
  175. if err != nil {
  176. return nil, errors.New("database add failed: " + err.Error())
  177. }
  178. }
  179. for _, s := range results {
  180. as.option.ComputeCard = s.Card //execute card
  181. clusterName, _ := as.AiStorages.GetClusterNameById(s.ClusterId)
  182. if s.Msg != "" {
  183. msg := fmt.Sprintf("clusterId: %v , error: %v \n", s.ClusterId, s.Msg)
  184. errmsg += msg
  185. err := as.AiStorages.SaveAiTask(taskId, as.option, s.ClusterId, clusterName, "", constants.Failed, msg)
  186. if err != nil {
  187. return nil, errors.New("database add failed: " + err.Error())
  188. }
  189. } else {
  190. msg := fmt.Sprintf("clusterId: %v , submitted successfully, jobId: %v \n", s.ClusterId, s.JobId)
  191. errmsg += msg
  192. err := as.AiStorages.SaveAiTask(taskId, as.option, s.ClusterId, clusterName, s.JobId, constants.Saved, msg)
  193. if err != nil {
  194. return nil, errors.New("database add failed: " + err.Error())
  195. }
  196. }
  197. }
  198. logx.Errorf(errors.New(errmsg).Error())
  199. return nil, errors.New(errmsg)
  200. }
  201. return results, nil
  202. }
  203. func (as *AiScheduler) findClustersWithResources() ([]*collector.ResourceStats, error) {
  204. var wg sync.WaitGroup
  205. var clustersNum = len(as.AiService.AiCollectorAdapterMap[as.option.AdapterId])
  206. var ch = make(chan *collector.ResourceStats, clustersNum)
  207. var errCh = make(chan interface{}, clustersNum)
  208. var resourceSpecs []*collector.ResourceStats
  209. var errs []interface{}
  210. for s, resourceCollector := range as.AiService.AiCollectorAdapterMap[as.option.AdapterId] {
  211. wg.Add(1)
  212. rc := resourceCollector
  213. id := s
  214. go func() {
  215. spec, err := rc.GetResourceStats(as.ctx)
  216. if err != nil {
  217. e := struct {
  218. err error
  219. clusterId string
  220. }{
  221. err: err,
  222. clusterId: id,
  223. }
  224. errCh <- e
  225. wg.Done()
  226. return
  227. }
  228. ch <- spec
  229. wg.Done()
  230. }()
  231. }
  232. wg.Wait()
  233. close(ch)
  234. close(errCh)
  235. for s := range ch {
  236. resourceSpecs = append(resourceSpecs, s)
  237. }
  238. for e := range errCh {
  239. errs = append(errs, e)
  240. }
  241. if len(errs) == clustersNum {
  242. return nil, errors.New("get resources failed")
  243. }
  244. if len(errs) != 0 {
  245. var msg string
  246. for _, err := range errs {
  247. e := (err).(struct {
  248. err error
  249. clusterId string
  250. })
  251. msg += fmt.Sprintf("clusterId: %v , error: %v \n", e.clusterId, e.err.Error())
  252. }
  253. return nil, errors.New(msg)
  254. }
  255. return resourceSpecs, nil
  256. }
  257. func convertType(in interface{}) (*AiResult, error) {
  258. var result AiResult
  259. switch (in).(type) {
  260. case *hpcAC.SubmitTaskAiResp:
  261. resp := (in).(*hpcAC.SubmitTaskAiResp)
  262. if resp.Code == "0" {
  263. result.JobId = resp.Data
  264. } else {
  265. result.Msg = resp.Msg
  266. }
  267. return &result, nil
  268. case *octopus.CreateTrainJobResp:
  269. resp := (in).(*octopus.CreateTrainJobResp)
  270. if resp.Success {
  271. result.JobId = resp.Payload.JobId
  272. } else {
  273. result.Msg = resp.Error.Message
  274. }
  275. return &result, nil
  276. default:
  277. return nil, errors.New("ai task response failed")
  278. }
  279. }
  280. func cloneAiOption(opt *option.AiOption) (*option.AiOption, error) {
  281. origJSON, err := json.Marshal(opt)
  282. if err != nil {
  283. return nil, err
  284. }
  285. clone := option.AiOption{}
  286. if err = json.Unmarshal(origJSON, &clone); err != nil {
  287. return nil, err
  288. }
  289. return &clone, nil
  290. }

PCM is positioned as Software stack over Cloud, aiming to build the standards and ecology of heterogeneous cloud collaboration for JCC in a non intrusive and autonomous peer-to-peer manner.