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 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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/common"
  22. "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/scheduler/schedulers/option"
  23. "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/scheduler/service/collector"
  24. "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/scheduler/strategy"
  25. "gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/scheduler/strategy/param"
  26. "gitlink.org.cn/JointCloud/pcm-coordinator/api/pkg/response"
  27. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants"
  28. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
  29. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
  30. "gitlink.org.cn/JointCloud/pcm-modelarts/client/modelartsservice"
  31. "gitlink.org.cn/JointCloud/pcm-octopus/octopus"
  32. "sync"
  33. )
  34. type AiScheduler struct {
  35. yamlString string
  36. task *response.TaskInfo
  37. *scheduler.Scheduler
  38. option *option.AiOption
  39. ctx context.Context
  40. }
  41. type AiResult struct {
  42. JobId string
  43. ClusterId string
  44. Strategy string
  45. Replica int32
  46. Card string
  47. Msg string
  48. }
  49. func NewAiScheduler(ctx context.Context, val string, scheduler *scheduler.Scheduler, option *option.AiOption) (*AiScheduler, error) {
  50. return &AiScheduler{ctx: ctx, yamlString: val, Scheduler: scheduler, option: option}, nil
  51. }
  52. func (as *AiScheduler) GetNewStructForDb(task *response.TaskInfo, resource string, participantId int64) (interface{}, error) {
  53. ai := models.Ai{
  54. AdapterId: participantId,
  55. TaskId: task.TaskId,
  56. Status: "Saved",
  57. YamlString: as.yamlString,
  58. }
  59. utils.Convert(task.Metadata, &ai)
  60. return ai, nil
  61. }
  62. func (as *AiScheduler) PickOptimalStrategy() (strategy.Strategy, error) {
  63. if as.option.ComputeCard != "" {
  64. m, ok := as.AiService.AiCollectorAdapterMap[as.option.AdapterId]
  65. if ok {
  66. for _, id := range as.option.ClusterIds {
  67. cm, ok := m[id]
  68. if ok {
  69. cards, err := cm.GetComputeCards(as.ctx)
  70. if err != nil {
  71. return nil, err
  72. }
  73. if common.Contains(cards, as.option.ComputeCard) {
  74. return &strategy.SingleAssignment{Cluster: &strategy.AssignedCluster{ClusterId: id, Replicas: 1}}, nil
  75. }
  76. }
  77. }
  78. }
  79. }
  80. if len(as.option.ClusterIds) == 1 {
  81. return &strategy.SingleAssignment{Cluster: &strategy.AssignedCluster{ClusterId: as.option.ClusterIds[0], Replicas: 1}}, nil
  82. }
  83. resources, err := as.findClustersWithResources()
  84. if err != nil {
  85. return nil, err
  86. }
  87. if len(resources) == 0 {
  88. return nil, errors.New("no cluster has resources")
  89. }
  90. if len(resources) == 1 {
  91. var cluster strategy.AssignedCluster
  92. cluster.ClusterId = resources[0].ClusterId
  93. cluster.Replicas = 1
  94. return &strategy.SingleAssignment{Cluster: &cluster}, nil
  95. }
  96. params := &param.Params{Resources: resources}
  97. switch as.option.StrategyName {
  98. case strategy.REPLICATION:
  99. var clusterIds []string
  100. for _, resource := range resources {
  101. clusterIds = append(clusterIds, resource.ClusterId)
  102. }
  103. strategy := strategy.NewReplicationStrategy(clusterIds, 1)
  104. return strategy, nil
  105. case strategy.RESOURCES_PRICING:
  106. strategy := strategy.NewPricingStrategy(&param.ResourcePricingParams{Params: params, Replicas: 1})
  107. return strategy, nil
  108. case strategy.DYNAMIC_RESOURCES:
  109. strategy := strategy.NewDynamicResourcesStrategy(params.Resources, as.option, 1)
  110. return strategy, nil
  111. case strategy.STATIC_WEIGHT:
  112. //todo resources should match cluster StaticWeightMap
  113. strategy := strategy.NewStaticWeightStrategy(as.option.ClusterToStaticWeight, as.option.Replica)
  114. return strategy, nil
  115. }
  116. return nil, errors.New("no strategy has been chosen")
  117. }
  118. func (as *AiScheduler) AssignTask(clusters []*strategy.AssignedCluster) (interface{}, error) {
  119. if clusters == nil {
  120. return nil, errors.New("clusters is nil")
  121. }
  122. for i := len(clusters) - 1; i >= 0; i-- {
  123. if clusters[i].Replicas == 0 {
  124. clusters = append(clusters[:i], clusters[i+1:]...)
  125. }
  126. }
  127. if len(clusters) == 0 {
  128. return nil, errors.New("clusters is nil")
  129. }
  130. var wg sync.WaitGroup
  131. var results []*AiResult
  132. var mu sync.Mutex
  133. var errs []interface{}
  134. var taskNum int32
  135. for _, cluster := range clusters {
  136. taskNum += cluster.Replicas
  137. }
  138. var ch = make(chan *AiResult, taskNum)
  139. var errCh = make(chan interface{}, taskNum)
  140. executorMap := as.AiService.AiExecutorAdapterMap[as.option.AdapterId]
  141. for _, cluster := range clusters {
  142. c := cluster
  143. for i := 0; i < int(c.Replicas); i++ {
  144. wg.Add(1)
  145. go func() {
  146. opt, _ := cloneAiOption(as.option)
  147. resp, err := executorMap[c.ClusterId].Execute(as.ctx, opt)
  148. if err != nil {
  149. e := struct {
  150. err error
  151. clusterId string
  152. }{
  153. err: err,
  154. clusterId: c.ClusterId,
  155. }
  156. errCh <- e
  157. wg.Done()
  158. return
  159. }
  160. mu.Lock()
  161. result, _ := convertType(resp)
  162. mu.Unlock()
  163. result.Replica = c.Replicas
  164. result.ClusterId = c.ClusterId
  165. result.Strategy = as.option.StrategyName
  166. result.Card = opt.ComputeCard
  167. ch <- result
  168. wg.Done()
  169. }()
  170. }
  171. }
  172. wg.Wait()
  173. close(ch)
  174. close(errCh)
  175. for e := range errCh {
  176. errs = append(errs, e)
  177. }
  178. for s := range ch {
  179. results = append(results, s)
  180. }
  181. if len(errs) != 0 {
  182. var synergystatus int64
  183. if len(clusters) > 1 {
  184. synergystatus = 1
  185. }
  186. strategyCode, err := as.AiStorages.GetStrategyCode(as.option.StrategyName)
  187. taskId, err := as.AiStorages.SaveTask(as.option.TaskName, strategyCode, synergystatus)
  188. if err != nil {
  189. return nil, errors.New("database add failed: " + err.Error())
  190. }
  191. var errmsg string
  192. for _, err := range errs {
  193. e := (err).(struct {
  194. err error
  195. clusterId string
  196. })
  197. msg := fmt.Sprintf("clusterId: %v , error: %v \n", e.clusterId, e.err.Error())
  198. errmsg += msg
  199. clusterName, _ := as.AiStorages.GetClusterNameById(e.clusterId)
  200. err := as.AiStorages.SaveAiTask(taskId, as.option, e.clusterId, clusterName, "", constants.Failed, msg)
  201. if err != nil {
  202. return nil, errors.New("database add failed: " + err.Error())
  203. }
  204. }
  205. for _, s := range results {
  206. as.option.ComputeCard = s.Card //execute card
  207. clusterName, _ := as.AiStorages.GetClusterNameById(s.ClusterId)
  208. if s.Msg != "" {
  209. msg := fmt.Sprintf("clusterId: %v , error: %v \n", s.ClusterId, s.Msg)
  210. errmsg += msg
  211. err := as.AiStorages.SaveAiTask(taskId, as.option, s.ClusterId, clusterName, "", constants.Failed, msg)
  212. if err != nil {
  213. return nil, errors.New("database add failed: " + err.Error())
  214. }
  215. } else {
  216. msg := fmt.Sprintf("clusterId: %v , submitted successfully, jobId: %v \n", s.ClusterId, s.JobId)
  217. errmsg += msg
  218. err := as.AiStorages.SaveAiTask(taskId, as.option, s.ClusterId, clusterName, s.JobId, constants.Saved, msg)
  219. if err != nil {
  220. return nil, errors.New("database add failed: " + err.Error())
  221. }
  222. }
  223. }
  224. logx.Errorf(errors.New(errmsg).Error())
  225. return nil, errors.New(errmsg)
  226. }
  227. return results, nil
  228. }
  229. func (as *AiScheduler) findClustersWithResources() ([]*collector.ResourceStats, error) {
  230. var wg sync.WaitGroup
  231. var clustersNum = len(as.AiService.AiCollectorAdapterMap[as.option.AdapterId])
  232. var ch = make(chan *collector.ResourceStats, clustersNum)
  233. var errCh = make(chan interface{}, clustersNum)
  234. var resourceSpecs []*collector.ResourceStats
  235. var errs []interface{}
  236. for s, resourceCollector := range as.AiService.AiCollectorAdapterMap[as.option.AdapterId] {
  237. wg.Add(1)
  238. rc := resourceCollector
  239. id := s
  240. go func() {
  241. spec, err := rc.GetResourceStats(as.ctx)
  242. if err != nil {
  243. e := struct {
  244. err error
  245. clusterId string
  246. }{
  247. err: err,
  248. clusterId: id,
  249. }
  250. errCh <- e
  251. wg.Done()
  252. return
  253. }
  254. ch <- spec
  255. wg.Done()
  256. }()
  257. }
  258. wg.Wait()
  259. close(ch)
  260. close(errCh)
  261. for s := range ch {
  262. resourceSpecs = append(resourceSpecs, s)
  263. }
  264. for e := range errCh {
  265. errs = append(errs, e)
  266. }
  267. if len(errs) == clustersNum {
  268. return nil, errors.New("get resources failed")
  269. }
  270. if len(errs) != 0 {
  271. var msg string
  272. for _, err := range errs {
  273. e := (err).(struct {
  274. err error
  275. clusterId string
  276. })
  277. msg += fmt.Sprintf("clusterId: %v , error: %v \n", e.clusterId, e.err.Error())
  278. }
  279. return nil, errors.New(msg)
  280. }
  281. return resourceSpecs, nil
  282. }
  283. func convertType(in interface{}) (*AiResult, error) {
  284. var result AiResult
  285. switch (in).(type) {
  286. case *hpcAC.SubmitTaskAiResp:
  287. resp := (in).(*hpcAC.SubmitTaskAiResp)
  288. if resp.Code == "0" {
  289. result.JobId = resp.Data
  290. } else {
  291. result.Msg = resp.Msg
  292. }
  293. return &result, nil
  294. case *octopus.CreateTrainJobResp:
  295. resp := (in).(*octopus.CreateTrainJobResp)
  296. if resp.Success {
  297. result.JobId = resp.Payload.JobId
  298. } else {
  299. result.Msg = resp.Error.Message
  300. }
  301. return &result, nil
  302. case *modelartsservice.CreateTrainingJobResp:
  303. resp := (in).(*modelartsservice.CreateTrainingJobResp)
  304. if resp.ErrorMsg != "" {
  305. result.Msg = resp.ErrorMsg
  306. } else {
  307. result.JobId = resp.Metadata.Id
  308. }
  309. return &result, nil
  310. default:
  311. return nil, errors.New("ai task response failed")
  312. }
  313. }
  314. func cloneAiOption(opt *option.AiOption) (*option.AiOption, error) {
  315. origJSON, err := json.Marshal(opt)
  316. if err != nil {
  317. return nil, err
  318. }
  319. clone := option.AiOption{}
  320. if err = json.Unmarshal(origJSON, &clone); err != nil {
  321. return nil, err
  322. }
  323. return &clone, nil
  324. }

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.