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.

imageInference.go 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. package imageInference
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "github.com/go-resty/resty/v2"
  6. "github.com/zeromicro/go-zero/core/logx"
  7. "gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/database"
  8. "gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/schedulers/option"
  9. "gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/service/inference"
  10. "gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/strategy"
  11. "gitlink.org.cn/JointCloud/pcm-coordinator/internal/storeLink"
  12. "gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"
  13. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants"
  14. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
  15. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
  16. "log"
  17. "math/rand"
  18. "mime/multipart"
  19. "net/http"
  20. "sort"
  21. "strconv"
  22. "sync"
  23. "time"
  24. )
  25. type IImageInference interface {
  26. AppendRoute(urls []*inference.InferUrl) error
  27. GetAiType() string
  28. }
  29. type ImageFile struct {
  30. ImageResult *types.ImageResult
  31. File multipart.File
  32. }
  33. type FilteredCluster struct {
  34. urls []*inference.InferUrl
  35. clusterId string
  36. clusterName string
  37. clusterType string
  38. imageNum int32
  39. }
  40. type ImageInference struct {
  41. inference IImageInference
  42. files []*ImageFile
  43. clusters []*strategy.AssignedCluster
  44. instances []types.DeployInstance
  45. opt *option.InferOption
  46. storage *database.AiStorage
  47. inferAdapter map[string]map[string]inference.ICluster
  48. errMap map[string]string
  49. adapterName string
  50. }
  51. func New(
  52. inference IImageInference,
  53. files []*ImageFile,
  54. clusters []*strategy.AssignedCluster,
  55. instances []types.DeployInstance,
  56. opt *option.InferOption,
  57. storage *database.AiStorage,
  58. inferAdapter map[string]map[string]inference.ICluster,
  59. adapterName string) (*ImageInference, error) {
  60. return &ImageInference{
  61. inference: inference,
  62. files: files,
  63. clusters: clusters,
  64. instances: instances,
  65. opt: opt,
  66. storage: storage,
  67. inferAdapter: inferAdapter,
  68. adapterName: adapterName,
  69. errMap: make(map[string]string),
  70. }, nil
  71. }
  72. func (i *ImageInference) CreateTask() (int64, error) {
  73. id, err := i.saveTask()
  74. if err != nil {
  75. return 0, err
  76. }
  77. err = i.saveAiTask(id)
  78. if err != nil {
  79. return 0, err
  80. }
  81. return id, nil
  82. }
  83. func (i *ImageInference) InferTask(id int64) error {
  84. clusters, err := i.filterClusters()
  85. if err != nil {
  86. return err
  87. }
  88. aiTaskList, err := i.storage.GetAiTaskListById(id)
  89. if err != nil || len(aiTaskList) == 0 {
  90. return err
  91. }
  92. err = i.updateStatus(aiTaskList, clusters)
  93. if err != nil {
  94. return err
  95. }
  96. results, err := i.inferImages(clusters)
  97. if err != nil {
  98. return err
  99. }
  100. err = i.saveAiSubTasks(id, aiTaskList, clusters, results)
  101. if err != nil {
  102. return err
  103. }
  104. return nil
  105. }
  106. func (i *ImageInference) saveTask() (int64, error) {
  107. var synergystatus int64
  108. if len(i.clusters) > 1 {
  109. synergystatus = 1
  110. }
  111. strategyCode, err := i.storage.GetStrategyCode(i.opt.Strategy)
  112. if err != nil {
  113. return 0, err
  114. }
  115. id, err := i.storage.SaveTask(i.opt.TaskName, strategyCode, synergystatus, i.inference.GetAiType())
  116. if err != nil {
  117. return 0, err
  118. }
  119. i.storage.AddNoticeInfo("", "", "", "", i.opt.TaskName, "create", "任务创建中")
  120. return id, nil
  121. }
  122. func (i *ImageInference) saveAiTask(id int64) error {
  123. for _, c := range i.clusters {
  124. clusterName, _ := i.storage.GetClusterNameById(c.ClusterId)
  125. i.opt.Replica = c.Replicas
  126. err := i.storage.SaveAiTask(id, i.opt, i.adapterName, c.ClusterId, clusterName, "", constants.Saved, "")
  127. if err != nil {
  128. return err
  129. }
  130. }
  131. return nil
  132. }
  133. func (i *ImageInference) filterClustersTemp() ([]*FilteredCluster, error) {
  134. var wg sync.WaitGroup
  135. var ch = make(chan *FilteredCluster, len(i.clusters))
  136. var cs []*FilteredCluster
  137. var mutex sync.Mutex
  138. inferMap := i.inferAdapter[i.opt.AdapterId]
  139. for _, cluster := range i.clusters {
  140. wg.Add(1)
  141. c := cluster
  142. go func() {
  143. r := http.Request{}
  144. clusterInferUrl, err := inferMap[c.ClusterId].GetClusterInferUrl(r.Context(), i.opt)
  145. if err != nil {
  146. mutex.Lock()
  147. i.errMap[c.ClusterId] = err.Error()
  148. mutex.Unlock()
  149. wg.Done()
  150. return
  151. }
  152. i.inference.AppendRoute(clusterInferUrl.InferUrls)
  153. var f FilteredCluster
  154. f.urls = clusterInferUrl.InferUrls
  155. f.clusterId = c.ClusterId
  156. f.clusterName = clusterInferUrl.ClusterName
  157. f.clusterType = clusterInferUrl.ClusterType
  158. f.imageNum = c.Replicas
  159. ch <- &f
  160. wg.Done()
  161. return
  162. }()
  163. }
  164. wg.Wait()
  165. close(ch)
  166. for s := range ch {
  167. cs = append(cs, s)
  168. }
  169. return cs, nil
  170. }
  171. func (i *ImageInference) filterClusters() ([]*FilteredCluster, error) {
  172. var cs []*FilteredCluster
  173. for _, cluster := range i.clusters {
  174. var inferurls []*inference.InferUrl
  175. var clustertype string
  176. for _, instance := range i.instances {
  177. if cluster.ClusterId == instance.ClusterId {
  178. r := http.Request{}
  179. deployInstance, err := i.inferAdapter[instance.AdapterId][instance.ClusterId].GetInferDeployInstance(r.Context(), instance.InstanceId)
  180. if err != nil {
  181. continue
  182. }
  183. var url inference.InferUrl
  184. url.Url = deployInstance.InferUrl
  185. url.Card = deployInstance.InferCard
  186. inferurls = append(inferurls, &url)
  187. clustertype = deployInstance.ClusterType
  188. }
  189. }
  190. if len(inferurls) == 0 {
  191. continue
  192. }
  193. i.inference.AppendRoute(inferurls)
  194. var f FilteredCluster
  195. f.urls = inferurls
  196. f.clusterName = cluster.ClusterName
  197. f.clusterType = clustertype
  198. f.imageNum = cluster.Replicas
  199. cs = append(cs, &f)
  200. }
  201. return cs, nil
  202. }
  203. func (i *ImageInference) inferImages(cs []*FilteredCluster) ([]*types.ImageResult, error) {
  204. var wg sync.WaitGroup
  205. var ch = make(chan *types.ImageResult, len(i.files))
  206. var results []*types.ImageResult
  207. limit := make(chan bool, 7)
  208. var imageNumIdx int32 = 0
  209. var imageNumIdxEnd int32 = 0
  210. for _, c := range cs {
  211. new_images := make([]*ImageFile, len(i.files))
  212. copy(new_images, i.files)
  213. imageNumIdxEnd = imageNumIdxEnd + c.imageNum
  214. new_images = new_images[imageNumIdx:imageNumIdxEnd]
  215. imageNumIdx = imageNumIdx + c.imageNum
  216. wg.Add(len(new_images))
  217. go i.sendInferReq(new_images, c, &wg, ch, limit)
  218. }
  219. wg.Wait()
  220. close(ch)
  221. for s := range ch {
  222. results = append(results, s)
  223. }
  224. sort.Slice(results, func(p, q int) bool {
  225. return results[p].ClusterName < results[q].ClusterName
  226. })
  227. return results, nil
  228. }
  229. func (i *ImageInference) updateStatus(aiTaskList []*models.TaskAi, cs []*FilteredCluster) error {
  230. //no cluster available
  231. if len(cs) == 0 {
  232. for _, t := range aiTaskList {
  233. t.Status = constants.Failed
  234. t.EndTime = time.Now().Format(time.RFC3339)
  235. if _, ok := i.errMap[strconv.Itoa(int(t.ClusterId))]; ok {
  236. t.Msg = i.errMap[strconv.Itoa(int(t.ClusterId))]
  237. }
  238. err := i.storage.UpdateAiTask(t)
  239. if err != nil {
  240. logx.Errorf(err.Error())
  241. }
  242. }
  243. i.storage.AddNoticeInfo(i.opt.AdapterId, i.adapterName, "", "", i.opt.TaskName, "failed", "任务失败")
  244. return errors.New("available clusters' empty, image infer task failed")
  245. }
  246. //change cluster status
  247. if len(i.clusters) != len(cs) {
  248. var acs []*strategy.AssignedCluster
  249. var rcs []*strategy.AssignedCluster
  250. for _, cluster := range i.clusters {
  251. if contains(cs, cluster.ClusterId) {
  252. var ac *strategy.AssignedCluster
  253. ac = cluster
  254. rcs = append(rcs, ac)
  255. } else {
  256. var ac *strategy.AssignedCluster
  257. ac = cluster
  258. acs = append(acs, ac)
  259. }
  260. }
  261. // update failed cluster status
  262. for _, ac := range acs {
  263. for _, t := range aiTaskList {
  264. if ac.ClusterId == strconv.Itoa(int(t.ClusterId)) {
  265. t.Status = constants.Failed
  266. t.EndTime = time.Now().Format(time.RFC3339)
  267. if _, ok := i.errMap[strconv.Itoa(int(t.ClusterId))]; ok {
  268. t.Msg = i.errMap[strconv.Itoa(int(t.ClusterId))]
  269. }
  270. err := i.storage.UpdateAiTask(t)
  271. if err != nil {
  272. logx.Errorf(err.Error())
  273. }
  274. }
  275. }
  276. }
  277. // update running cluster status
  278. for _, ac := range rcs {
  279. for _, t := range aiTaskList {
  280. if ac.ClusterId == strconv.Itoa(int(t.ClusterId)) {
  281. t.Status = constants.Running
  282. err := i.storage.UpdateAiTask(t)
  283. if err != nil {
  284. logx.Errorf(err.Error())
  285. }
  286. }
  287. }
  288. }
  289. i.storage.AddNoticeInfo(i.opt.AdapterId, i.adapterName, "", "", i.opt.TaskName, "failed", "任务失败")
  290. } else {
  291. for _, t := range aiTaskList {
  292. t.Status = constants.Running
  293. err := i.storage.UpdateAiTask(t)
  294. if err != nil {
  295. logx.Errorf(err.Error())
  296. }
  297. }
  298. i.storage.AddNoticeInfo(i.opt.AdapterId, i.adapterName, "", "", i.opt.TaskName, "running", "任务运行中")
  299. }
  300. return nil
  301. }
  302. func (i *ImageInference) sendInferReq(images []*ImageFile, cluster *FilteredCluster, wg *sync.WaitGroup, ch chan<- *types.ImageResult, limit chan bool) {
  303. for _, image := range images {
  304. limit <- true
  305. go func(t *ImageFile, c *FilteredCluster) {
  306. if len(c.urls) == 1 {
  307. r, err := getInferResult(c.urls[0].Url, t.File, t.ImageResult.ImageName, c.clusterId, c.clusterType, i.inferAdapter, i.opt.AdapterId)
  308. if err != nil {
  309. t.ImageResult.ImageResult = err.Error()
  310. t.ImageResult.ClusterId = c.clusterId
  311. t.ImageResult.ClusterName = c.clusterName
  312. t.ImageResult.Card = c.urls[0].Card
  313. ch <- t.ImageResult
  314. wg.Done()
  315. <-limit
  316. return
  317. }
  318. t.ImageResult.ImageResult = r
  319. t.ImageResult.ClusterId = c.clusterId
  320. t.ImageResult.ClusterName = c.clusterName
  321. t.ImageResult.Card = c.urls[0].Card
  322. ch <- t.ImageResult
  323. wg.Done()
  324. <-limit
  325. return
  326. } else {
  327. idx := rand.Intn(len(c.urls))
  328. r, err := getInferResult(c.urls[idx].Url, t.File, t.ImageResult.ImageName, c.clusterId, c.clusterType, i.inferAdapter, i.opt.AdapterId)
  329. if err != nil {
  330. t.ImageResult.ImageResult = err.Error()
  331. t.ImageResult.ClusterId = c.clusterId
  332. t.ImageResult.ClusterName = c.clusterName
  333. t.ImageResult.Card = c.urls[idx].Card
  334. ch <- t.ImageResult
  335. wg.Done()
  336. <-limit
  337. return
  338. }
  339. t.ImageResult.ImageResult = r
  340. t.ImageResult.ClusterId = c.clusterId
  341. t.ImageResult.ClusterName = c.clusterName
  342. t.ImageResult.Card = c.urls[idx].Card
  343. ch <- t.ImageResult
  344. wg.Done()
  345. <-limit
  346. return
  347. }
  348. }(image, cluster)
  349. <-limit
  350. }
  351. }
  352. func (i *ImageInference) saveAiSubTasks(id int64, aiTaskList []*models.TaskAi, cs []*FilteredCluster, results []*types.ImageResult) error {
  353. //save ai sub tasks
  354. for _, r := range results {
  355. for _, task := range aiTaskList {
  356. if r.ClusterId == strconv.Itoa(int(task.ClusterId)) {
  357. taskAiSub := models.TaskAiSub{
  358. TaskId: id,
  359. TaskName: task.Name,
  360. TaskAiId: task.TaskId,
  361. TaskAiName: task.Name,
  362. ImageName: r.ImageName,
  363. Result: r.ImageResult,
  364. Card: r.Card,
  365. ClusterId: task.ClusterId,
  366. ClusterName: r.ClusterName,
  367. }
  368. err := i.storage.SaveAiTaskImageSubTask(&taskAiSub)
  369. if err != nil {
  370. panic(err)
  371. }
  372. }
  373. }
  374. }
  375. // update succeeded cluster status
  376. var successStatusCount int
  377. for _, c := range cs {
  378. for _, t := range aiTaskList {
  379. if c.clusterId == strconv.Itoa(int(t.ClusterId)) {
  380. t.Status = constants.Completed
  381. t.EndTime = time.Now().Format(time.RFC3339)
  382. err := i.storage.UpdateAiTask(t)
  383. if err != nil {
  384. logx.Errorf(err.Error())
  385. }
  386. successStatusCount++
  387. } else {
  388. continue
  389. }
  390. }
  391. }
  392. if len(cs) == successStatusCount {
  393. i.storage.AddNoticeInfo(i.opt.AdapterId, i.adapterName, "", "", i.opt.TaskName, "completed", "任务完成")
  394. } else {
  395. i.storage.AddNoticeInfo(i.opt.AdapterId, i.adapterName, "", "", i.opt.TaskName, "failed", "任务失败")
  396. }
  397. return nil
  398. }
  399. func getInferResult(url string, file multipart.File, fileName string, clusterId string, clusterType string, inferAdapter map[string]map[string]inference.ICluster, adapterId string) (string, error) {
  400. inferMap := inferAdapter[adapterId]
  401. switch clusterType {
  402. case storeLink.TYPE_OCTOPUS:
  403. r := http.Request{}
  404. result, err := inferMap[clusterId].GetInferResult(r.Context(), url, file, fileName)
  405. if err != nil {
  406. return "", err
  407. }
  408. return result, nil
  409. case storeLink.TYPE_MODELARTS:
  410. r, err := getInferResultModelarts(url, file, fileName)
  411. if err != nil {
  412. return "", err
  413. }
  414. return r, nil
  415. default:
  416. var res Res
  417. req := GetRestyRequest(20)
  418. _, err := req.
  419. SetFileReader("file", fileName, file).
  420. SetResult(&res).
  421. Post(url)
  422. if err != nil {
  423. return "", err
  424. }
  425. return res.Result, nil
  426. }
  427. }
  428. func getInferResultModelarts(url string, file multipart.File, fileName string) (string, error) {
  429. var res Res
  430. /* req := GetRestyRequest(20)
  431. _, err := req.
  432. SetFileReader("file", fileName, file).
  433. SetHeaders(map[string]string{
  434. "ak": "UNEHPHO4Z7YSNPKRXFE4",
  435. "sk": "JWXCE9qcYbc7RjpSRIWt4WgG3ZKF6Q4lPzkJReX9",
  436. }).
  437. SetResult(&res).
  438. Post(url)
  439. if err != nil {
  440. return "", err
  441. }*/
  442. body, err := utils.SendRequest("POST", url, file, fileName)
  443. if err != nil {
  444. return "", err
  445. }
  446. errjson := json.Unmarshal([]byte(body), &res)
  447. if errjson != nil {
  448. log.Fatalf("Error parsing JSON: %s", errjson)
  449. }
  450. return res.Result, nil
  451. }
  452. func GetRestyRequest(timeoutSeconds int64) *resty.Request {
  453. client := resty.New().SetTimeout(time.Duration(timeoutSeconds) * time.Second)
  454. request := client.R()
  455. return request
  456. }
  457. type Res struct {
  458. Result string `json:"result"`
  459. }
  460. func contains(cs []*FilteredCluster, e string) bool {
  461. for _, c := range cs {
  462. if c.clusterId == e {
  463. return true
  464. }
  465. }
  466. return false
  467. }

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.