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.

resty.go 6.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package aisafety
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "encoding/json"
  6. "fmt"
  7. "net/url"
  8. "sort"
  9. "strings"
  10. "code.gitea.io/gitea/modules/log"
  11. "github.com/go-resty/resty/v2"
  12. )
  13. var (
  14. restyClient *resty.Client
  15. HOST string
  16. KEY string
  17. )
  18. type TaskReq struct {
  19. UnionId string //评测任务ID,唯一标识,由后端生成UUID
  20. EvalName string //评测任务名称
  21. EvalContent string //评测任务描述
  22. TLPath string //
  23. Indicators []string //评测指标,由GetAlgorithmList接口返回的指标列表中的title属性值
  24. CDPath string
  25. CDName string //对抗数据集名称
  26. BDPath string
  27. BDName string //原数据集名称
  28. }
  29. type ReturnMsg struct {
  30. Code string `json:"code"`
  31. Msg string `json:"msg"`
  32. Data ReturnData `json:"data"`
  33. Times int64 `json:"times"`
  34. }
  35. type ReturnData struct {
  36. ID int `json:"id"`
  37. No string `json:"no"`
  38. StandardJson string `json:"standardJson"`
  39. Code int `json:"code"`
  40. Status int `json:"status"`
  41. }
  42. const (
  43. APPID = "1"
  44. LogPageSize = 500
  45. LogPageTokenExpired = "5m"
  46. pageSize = 15
  47. Success = "S000"
  48. )
  49. func getRestyClient() *resty.Client {
  50. if restyClient == nil {
  51. restyClient = resty.New()
  52. }
  53. return restyClient
  54. }
  55. func checkSetting() {
  56. if len(HOST) != 0 && len(KEY) != 0 {
  57. return
  58. }
  59. _ = loginCloudbrain()
  60. }
  61. func loginCloudbrain() error {
  62. HOST = "http://221.122.70.196:8081/atp-api"
  63. KEY = "1"
  64. return nil
  65. }
  66. func createSign(params map[string]interface{}, signKey string) string {
  67. var sceneList []string
  68. for k := range params {
  69. sceneList = append(sceneList, k)
  70. }
  71. sort.Strings(sceneList)
  72. re := ""
  73. for _, key := range sceneList {
  74. if params[key] != nil {
  75. re += key + "=" + fmt.Sprint(params[key]) + "&"
  76. }
  77. }
  78. re += "key=" + signKey
  79. log.Info("sign key:" + re)
  80. h := md5.New()
  81. h.Write([]byte(re))
  82. return strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
  83. }
  84. func getParams(req TaskReq) (map[string]interface{}, string) {
  85. params := make(map[string]interface{})
  86. reStr := ""
  87. params["unionId"] = req.UnionId
  88. reStr += "unionId=" + req.UnionId
  89. params["evalName"] = req.EvalName
  90. reStr += "&evalName=" + req.EvalName
  91. params["evalContent"] = req.EvalContent
  92. reStr += "&evalContent=" + url.QueryEscape(req.EvalContent)
  93. params["TLPath"] = req.TLPath
  94. reStr += "&TLPath=" + url.QueryEscape(req.TLPath)
  95. params["CDName"] = req.CDName
  96. reStr += "&CDName=" + url.QueryEscape(req.CDName)
  97. params["BDName"] = req.BDName
  98. reStr += "&BDName=" + url.QueryEscape(req.BDName)
  99. if req.CDPath != "" {
  100. params["CDPath"] = req.CDPath
  101. reStr += "&CDPath=" + url.QueryEscape(req.CDPath)
  102. }
  103. if req.BDPath != "" {
  104. params["BDPath"] = req.BDPath
  105. reStr += "&BDPath=" + url.QueryEscape(req.BDPath)
  106. }
  107. indicators := ""
  108. if len(req.Indicators) > 0 {
  109. for _, tmp := range req.Indicators {
  110. indicators += tmp + "|"
  111. }
  112. }
  113. if len(indicators) > 0 {
  114. indicators = indicators[0 : len(indicators)-1]
  115. }
  116. params["Indicators"] = indicators
  117. log.Info("indicators=" + indicators)
  118. reStr += "&Indicators=" + url.QueryEscape(indicators)
  119. return params, reStr
  120. }
  121. func CreateSafetyTask(req TaskReq, jsonstr string) (string, error) {
  122. checkSetting()
  123. client := getRestyClient()
  124. //reqPara, _ := json.Marshal(body)
  125. //log.Warn("job req:", jsonstr)
  126. params, urlQuerys := getParams(req)
  127. bodyMap := make(map[string]interface{})
  128. //reJsonMap := make(map[string]interface{})
  129. bodyMap["resJson"] = jsonstr
  130. //bodyMap["externalEvalParam"] = reJsonMap
  131. //reqPara, _ := json.Marshal(bodyMap)
  132. //log.Warn("job req json:", string(reqPara))
  133. res, err := client.R().
  134. SetHeader("Content-Type", "application/json").
  135. SetHeader("appId", APPID).
  136. SetHeader("sign", createSign(params, KEY)).
  137. //SetAuthToken(TOKEN).
  138. SetBody(bodyMap).
  139. Post(HOST + "/v1/external/eval-standard/create?" + urlQuerys)
  140. log.Info("url=" + HOST + "/v1/external/eval-standard/create?" + urlQuerys)
  141. responseStr := string(res.Body())
  142. log.Info("CreateSafetyTask responseStr=" + responseStr + " res code=" + fmt.Sprint(res.StatusCode()))
  143. if err != nil {
  144. return "", fmt.Errorf("resty create job: %s", err)
  145. } else {
  146. log.Info("result string=" + " res code=" + fmt.Sprint(res.StatusCode()))
  147. }
  148. reMap := make(map[string]interface{})
  149. err = json.Unmarshal(res.Body(), &reMap)
  150. if err == nil && reMap["code"] == "0" {
  151. dataMap := (reMap["data"]).(map[string]interface{})
  152. return fmt.Sprint(dataMap["serialNo"]), nil
  153. }
  154. return "", nil
  155. }
  156. func GetAlgorithmList() (map[string]interface{}, error) {
  157. checkSetting()
  158. client := getRestyClient()
  159. params := make(map[string]interface{})
  160. jsonResult := make(map[string]interface{})
  161. sign := createSign(params, KEY)
  162. res, err := client.R().
  163. SetHeader("Content-Type", "application/json").
  164. SetHeader("appId", APPID).
  165. SetHeader("sign", sign).
  166. Get(HOST + "/v1/external/eval-standard/algorithmList")
  167. log.Info("url=" + HOST + "/v1/external/eval-standard/algorithmList" + " sign=" + sign + " appId=" + APPID)
  168. jsonerr := json.Unmarshal(res.Body(), &jsonResult)
  169. if jsonerr == nil {
  170. log.Info("jsonResult code=" + fmt.Sprint(jsonResult["msg"]))
  171. }
  172. responseStr := string(res.Body())
  173. log.Info("GetAlgorithmList responseStr=" + responseStr + " res code=" + fmt.Sprint(res.StatusCode()))
  174. if err != nil {
  175. log.Info("error =" + err.Error())
  176. return nil, fmt.Errorf("resty GetJob: %v", err)
  177. } else {
  178. reMap := make(map[string]interface{})
  179. err = json.Unmarshal(res.Body(), &reMap)
  180. if err == nil && reMap["code"] == "0" {
  181. return reMap, nil
  182. } else {
  183. return nil, fmt.Errorf("get error,code not 0")
  184. }
  185. }
  186. }
  187. func GetTaskStatus(jobID string) (*ReturnMsg, error) {
  188. checkSetting()
  189. client := getRestyClient()
  190. var taskResult string
  191. params := make(map[string]interface{})
  192. params["serialNo"] = jobID
  193. res, err := client.R().
  194. SetHeader("Content-Type", "application/json").
  195. SetHeader("appId", APPID).
  196. SetHeader("sign", createSign(params, KEY)).
  197. SetResult(&taskResult).
  198. Get(HOST + "/v1/external/eval-standard/query?serialNo=" + jobID)
  199. log.Info("url=" + HOST + "/v1/external/eval-standard/query?serialNo=" + jobID)
  200. responseStr := string(res.Body())
  201. log.Info("GetTaskStatus responseStr=" + responseStr + " res code=" + fmt.Sprint(res.StatusCode()))
  202. if err != nil {
  203. log.Info("error =" + err.Error())
  204. return nil, fmt.Errorf("Get task status error: %v", err)
  205. } else {
  206. var reMap *ReturnMsg
  207. err = json.Unmarshal(res.Body(), reMap)
  208. if err == nil {
  209. return reMap, nil
  210. } else {
  211. return nil, fmt.Errorf("get error,code not 0")
  212. }
  213. }
  214. }