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.

commitgeneraltasklogic.go 6.6 kB

10 months ago
11 months ago
11 months ago
10 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. package cloud
  2. import (
  3. "bytes"
  4. "context"
  5. "github.com/pkg/errors"
  6. clientCore "gitlink.org.cn/JointCloud/pcm-coordinator/client"
  7. "gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/schedulers"
  8. "gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/schedulers/option"
  9. "gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/service/executor"
  10. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants"
  11. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
  12. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models/cloud"
  13. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
  14. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils/remoteUtil"
  15. "io"
  16. "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
  17. "k8s.io/apimachinery/pkg/runtime"
  18. syaml "k8s.io/apimachinery/pkg/runtime/serializer/yaml"
  19. "k8s.io/apimachinery/pkg/util/json"
  20. kyaml "k8s.io/apimachinery/pkg/util/yaml"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
  25. "gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"
  26. "github.com/zeromicro/go-zero/core/logx"
  27. )
  28. type CommitGeneralTaskLogic struct {
  29. logx.Logger
  30. ctx context.Context
  31. svcCtx *svc.ServiceContext
  32. }
  33. func NewCommitGeneralTaskLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CommitGeneralTaskLogic {
  34. return &CommitGeneralTaskLogic{
  35. Logger: logx.WithContext(ctx),
  36. ctx: ctx,
  37. svcCtx: svcCtx,
  38. }
  39. }
  40. func (l *CommitGeneralTaskLogic) CommitGeneralTask(req *types.GeneralTaskReq) error {
  41. tx := l.svcCtx.DbEngin.Begin()
  42. // 执行回滚或者提交操作
  43. defer func() {
  44. if p := recover(); p != nil {
  45. tx.Rollback()
  46. logx.Error(p)
  47. } else if tx.Error != nil {
  48. logx.Info("rollback, error", tx.Error)
  49. tx.Rollback()
  50. } else {
  51. tx = tx.Commit()
  52. logx.Info("commit success")
  53. }
  54. }()
  55. adapterId, _ := strconv.ParseUint(req.AdapterIds[0], 10, 64)
  56. var clusters []*models.CloudModel
  57. err := tx.Raw("SELECT * FROM `t_cluster` where adapter_id in ? and id in ?", req.AdapterIds, req.ClusterIds).Scan(&clusters).Error
  58. if err != nil {
  59. logx.Errorf("CommitGeneralTask() => sql execution error: %v", err)
  60. return errors.Errorf("the cluster does not match the drive resources. Check the data")
  61. }
  62. taskCloud := cloud.TaskCloudModel{}
  63. opt := &option.CloudOption{}
  64. utils.Convert(&req, &opt)
  65. sc, _ := schedulers.NewCloudScheduler(l.ctx, "", l.svcCtx.Scheduler, opt, tx, l.svcCtx.PromClient)
  66. results, err := l.svcCtx.Scheduler.AssignAndSchedule(sc, executor.SUBMIT_MODE_JOINT_CLOUD, nil)
  67. if err != nil {
  68. logx.Errorf("AssignAndSchedule() => execution error: %v", err)
  69. return err
  70. }
  71. rs := (results).([]*schedulers.CloudResult)
  72. var synergyStatus int64
  73. if len(rs) > 1 {
  74. synergyStatus = 1
  75. }
  76. var strategy int64
  77. sqlStr := `select t_dict_item.item_value
  78. from t_dict
  79. left join t_dict_item on t_dict.id = t_dict_item.dict_id
  80. where item_text = ?
  81. and t_dict.dict_code = 'schedule_Strategy'`
  82. //查询调度策略
  83. err = tx.Raw(sqlStr, req.Strategy).Scan(&strategy).Error
  84. taskModel := models.Task{
  85. Id: utils.GenSnowflakeID(),
  86. Status: constants.Saved,
  87. Name: req.Name,
  88. CommitTime: time.Now(),
  89. YamlString: strings.Join(req.ReqBody, "\n---\n"),
  90. AdapterTypeDict: "0",
  91. SynergyStatus: synergyStatus,
  92. Strategy: strategy,
  93. UserId: req.UserId,
  94. }
  95. var taskClouds []cloud.TaskCloudModel
  96. adapterName := ""
  97. tx.Table("t_adapter").Select("name").Where("id=?", adapterId).Find(&adapterName)
  98. for _, r := range rs {
  99. for _, s := range req.ReqBody {
  100. sStruct := UnMarshalK8sStruct(s, int64(r.Replica))
  101. unString, _ := sStruct.MarshalJSON()
  102. taskCloud.Id = utils.GenSnowflakeIDUint()
  103. taskCloud.Name = sStruct.GetName() + "-" + sStruct.GetKind()
  104. taskCloud.TaskId = uint(taskModel.Id)
  105. clusterId, _ := strconv.ParseUint(r.ClusterId, 10, 64)
  106. taskCloud.AdapterId = uint(adapterId)
  107. taskCloud.AdapterName = adapterName
  108. taskCloud.UserId = req.UserId
  109. taskCloud.ClusterId = uint(clusterId)
  110. taskCloud.ClusterName = r.ClusterName
  111. taskCloud.Status = constants.Saved
  112. taskCloud.YamlString = string(unString)
  113. taskCloud.Kind = sStruct.GetKind()
  114. taskCloud.Namespace = sStruct.GetNamespace()
  115. taskClouds = append(taskClouds, taskCloud)
  116. }
  117. }
  118. noticeInfo := clientCore.NoticeInfo{
  119. AdapterId: int64(adapterId),
  120. AdapterName: adapterName,
  121. NoticeType: "create",
  122. TaskName: req.Name,
  123. Incident: "任务创建中",
  124. CreatedTime: time.Now(),
  125. }
  126. db := tx.Table("task").Create(&taskModel)
  127. db = tx.Table("task_cloud").Create(&taskClouds)
  128. db = tx.Table("t_notice").Create(&noticeInfo)
  129. if db.Error != nil {
  130. logx.Errorf("Task creation failure, err: %v", db.Error)
  131. return errors.New("task creation failure")
  132. }
  133. // 数据上链
  134. bytes, _ := json.Marshal(taskModel)
  135. if err != nil {
  136. return err
  137. }
  138. // 查询资源价格
  139. var price int64
  140. for _, clusterId := range req.ClusterIds {
  141. var clusterPrice int64
  142. l.svcCtx.DbEngin.Raw("select price from resource_cost where resource_id = ?", clusterId).Scan(&clusterPrice)
  143. price = price + clusterPrice
  144. }
  145. remoteUtil.Evidence(remoteUtil.EvidenceParam{
  146. UserIp: req.UserIp,
  147. Url: l.svcCtx.Config.BlockChain.Url,
  148. ContractAddress: l.svcCtx.Config.BlockChain.ContractAddress,
  149. FunctionName: l.svcCtx.Config.BlockChain.FunctionName,
  150. Type: l.svcCtx.Config.BlockChain.Type,
  151. Token: req.Token,
  152. Amount: price,
  153. Args: []string{strconv.FormatInt(taskModel.Id, 10), string(bytes)},
  154. })
  155. return nil
  156. }
  157. func UnMarshalK8sStruct(yamlString string, replica int64) *unstructured.Unstructured {
  158. unstructuredObj := &unstructured.Unstructured{}
  159. d := kyaml.NewYAMLOrJSONDecoder(bytes.NewBufferString(yamlString), 4096)
  160. var err error
  161. for {
  162. var rawObj runtime.RawExtension
  163. err = d.Decode(&rawObj)
  164. if err == io.EOF {
  165. break
  166. }
  167. obj := &unstructured.Unstructured{}
  168. syaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme).Decode(rawObj.Raw, nil, obj)
  169. unstructuredMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
  170. if err != nil {
  171. logx.Errorf("UnMarshalK8sStruct() => Execution failure err:%v", err)
  172. }
  173. unstructuredObj = &unstructured.Unstructured{Object: unstructuredMap}
  174. // 命名空间为空 设置默认值
  175. if len(unstructuredObj.GetNamespace()) == 0 {
  176. unstructuredObj.SetNamespace("default")
  177. }
  178. //设置副本数
  179. if unstructuredObj.GetKind() == "Deployment" || unstructuredObj.GetKind() == "StatefulSet" {
  180. unstructured.SetNestedField(unstructuredObj.Object, replica, "spec", "replicas")
  181. }
  182. }
  183. return unstructuredObj
  184. }

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.