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.

cloudbrain.go 19 kB

4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. package repo
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "os/exec"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "code.gitea.io/gitea/modules/modelarts"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/storage"
  18. "code.gitea.io/gitea/models"
  19. "code.gitea.io/gitea/modules/auth"
  20. "code.gitea.io/gitea/modules/base"
  21. "code.gitea.io/gitea/modules/cloudbrain"
  22. "code.gitea.io/gitea/modules/context"
  23. "code.gitea.io/gitea/modules/log"
  24. "code.gitea.io/gitea/modules/setting"
  25. )
  26. const (
  27. tplCloudBrainIndex base.TplName = "repo/cloudbrain/index"
  28. tplCloudBrainNew base.TplName = "repo/cloudbrain/new"
  29. tplCloudBrainShow base.TplName = "repo/cloudbrain/show"
  30. tplCloudBrainShowModels base.TplName = "repo/cloudbrain/models/index"
  31. )
  32. var (
  33. gpuInfos *models.GpuInfos
  34. categories *models.Categories
  35. )
  36. // MustEnableDataset check if repository enable internal cb
  37. func MustEnableCloudbrain(ctx *context.Context) {
  38. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  39. ctx.NotFound("MustEnableCloudbrain", nil)
  40. return
  41. }
  42. }
  43. func CloudBrainIndex(ctx *context.Context) {
  44. MustEnableCloudbrain(ctx)
  45. repo := ctx.Repo.Repository
  46. page := ctx.QueryInt("page")
  47. if page <= 0 {
  48. page = 1
  49. }
  50. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  51. ListOptions: models.ListOptions{
  52. Page: page,
  53. PageSize: setting.UI.IssuePagingNum,
  54. },
  55. RepoID: repo.ID,
  56. Type: models.TypeCloudBrainOne,
  57. })
  58. if err != nil {
  59. ctx.ServerError("Cloudbrain", err)
  60. return
  61. }
  62. timestamp := time.Now().Unix()
  63. for i, task := range ciTasks {
  64. if task.Status == string(models.JobRunning) && (timestamp-int64(task.Cloudbrain.CreatedUnix) > 10) {
  65. ciTasks[i].CanDebug = true
  66. } else {
  67. ciTasks[i].CanDebug = false
  68. }
  69. ciTasks[i].CanDel = models.CanDelJob(ctx.IsSigned, ctx.User, task)
  70. }
  71. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  72. pager.SetDefaultParams(ctx)
  73. ctx.Data["Page"] = pager
  74. ctx.Data["PageIsCloudBrain"] = true
  75. ctx.Data["Tasks"] = ciTasks
  76. ctx.HTML(200, tplCloudBrainIndex)
  77. }
  78. func cutString(str string, lens int) string {
  79. if len(str) < lens {
  80. return str
  81. }
  82. return str[:lens]
  83. }
  84. func jobNamePrefixValid(s string) string {
  85. lowStr := strings.ToLower(s)
  86. re := regexp.MustCompile(`[^a-z0-9_\\-]+`)
  87. removeSpecial := re.ReplaceAllString(lowStr, "")
  88. re = regexp.MustCompile(`^[_\\-]+`)
  89. return re.ReplaceAllString(removeSpecial, "")
  90. }
  91. func cloudBrainNewDataPrepare(ctx *context.Context) error{
  92. ctx.Data["PageIsCloudBrain"] = true
  93. t := time.Now()
  94. var jobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  95. ctx.Data["job_name"] = jobName
  96. result, err := cloudbrain.GetImages()
  97. if err != nil {
  98. ctx.Data["error"] = err.Error()
  99. log.Error("cloudbrain.GetImages failed:", err.Error(), ctx.Data["MsgID"])
  100. }
  101. for i, payload := range result.Payload.ImageInfo {
  102. if strings.HasPrefix(result.Payload.ImageInfo[i].Place, "192.168") {
  103. result.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  104. } else {
  105. result.Payload.ImageInfo[i].PlaceView = payload.Place
  106. }
  107. }
  108. ctx.Data["images"] = result.Payload.ImageInfo
  109. resultPublic, err := cloudbrain.GetPublicImages()
  110. if err != nil {
  111. ctx.Data["error"] = err.Error()
  112. log.Error("cloudbrain.GetPublicImages failed:", err.Error(), ctx.Data["MsgID"])
  113. }
  114. for i, payload := range resultPublic.Payload.ImageInfo {
  115. if strings.HasPrefix(resultPublic.Payload.ImageInfo[i].Place, "192.168") {
  116. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  117. } else {
  118. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place
  119. }
  120. }
  121. ctx.Data["public_images"] = resultPublic.Payload.ImageInfo
  122. attachs, err := models.GetAllUserAttachments(ctx.User.ID)
  123. if err != nil {
  124. log.Error("GetAllUserAttachments failed: %v", err, ctx.Data["MsgID"])
  125. return err
  126. }
  127. ctx.Data["attachments"] = attachs
  128. ctx.Data["command"] = cloudbrain.Command
  129. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  130. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  131. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  132. ctx.Data["benchmark_path"] = cloudbrain.BenchMarkMountPath
  133. ctx.Data["is_benchmark_enabled"] = setting.IsBenchmarkEnabled
  134. if categories == nil {
  135. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  136. }
  137. ctx.Data["benchmark_categories"] = categories.Category
  138. if gpuInfos == nil {
  139. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  140. }
  141. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  142. if cloudbrain.ResourceSpecs == nil {
  143. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  144. }
  145. ctx.Data["resource_specs"] = cloudbrain.ResourceSpecs.ResourceSpec
  146. ctx.Data["snn4imagenet_path"] = cloudbrain.Snn4imagenetMountPath
  147. ctx.Data["is_snn4imagenet_enabled"] = setting.IsSnn4imagenetEnabled
  148. ctx.Data["brainscore_path"] = cloudbrain.BrainScoreMountPath
  149. ctx.Data["is_brainscore_enabled"] = setting.IsBrainScoreEnabled
  150. return nil
  151. }
  152. func CloudBrainNew(ctx *context.Context) {
  153. err := cloudBrainNewDataPrepare(ctx)
  154. if err != nil {
  155. ctx.ServerError("get new cloudbrain info failed", err)
  156. return
  157. }
  158. ctx.HTML(200, tplCloudBrainNew)
  159. }
  160. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  161. ctx.Data["PageIsCloudBrain"] = true
  162. jobName := form.JobName
  163. image := form.Image
  164. command := form.Command
  165. uuid := form.Attachment
  166. jobType := form.JobType
  167. gpuQueue := setting.JobType
  168. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  169. resourceSpecId := form.ResourceSpecId
  170. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) && jobType != string(models.JobTypeSnn4imagenet) && jobType != string(models.JobTypeBrainScore) {
  171. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  172. cloudBrainNewDataPrepare(ctx)
  173. ctx.RenderWithErr("jobtype error", tplCloudBrainNew, &form)
  174. return
  175. }
  176. _, err := models.GetCloudbrainByName(jobName)
  177. if err == nil {
  178. log.Error("the job name did already exist", ctx.Data["MsgID"])
  179. cloudBrainNewDataPrepare(ctx)
  180. ctx.RenderWithErr("the job name did already exist", tplCloudBrainNew, &form)
  181. return
  182. } else {
  183. if !models.IsErrJobNotExist(err) {
  184. log.Error("system error, %v", err, ctx.Data["MsgID"])
  185. cloudBrainNewDataPrepare(ctx)
  186. ctx.RenderWithErr("system error", tplCloudBrainNew, &form)
  187. return
  188. }
  189. }
  190. repo := ctx.Repo.Repository
  191. downloadCode(repo, codePath)
  192. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath
  193. err = os.MkdirAll(modelPath, os.ModePerm)
  194. if err != nil {
  195. cloudBrainNewDataPrepare(ctx)
  196. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  197. return
  198. }
  199. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  200. if setting.IsBenchmarkEnabled && jobType == string(models.JobTypeBenchmark) {
  201. gpuQueue = form.GpuType
  202. var gpuType string
  203. for _, gpuInfo := range gpuInfos.GpuInfo {
  204. if gpuInfo.Queue == gpuQueue {
  205. gpuType = gpuInfo.Value
  206. }
  207. }
  208. downloadRateCode(repo, jobName, setting.BenchmarkCode, benchmarkPath, form.BenchmarkCategory, gpuType)
  209. }
  210. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  211. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  212. downloadRateCode(repo, jobName, setting.Snn4imagenetCode, snn4imagenetPath, "", "")
  213. }
  214. brainScorePath := setting.JobPath + jobName + cloudbrain.BrainScoreMountPath
  215. if setting.IsBrainScoreEnabled && jobType == string(models.JobTypeBrainScore) {
  216. downloadRateCode(repo, jobName, setting.BrainScoreCode, brainScorePath, "", "")
  217. }
  218. err = cloudbrain.GenerateTask(ctx, jobName, image, command, uuid, codePath, modelPath, benchmarkPath, snn4imagenetPath, jobType, gpuQueue, resourceSpecId)
  219. if err != nil {
  220. cloudBrainNewDataPrepare(ctx)
  221. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  222. return
  223. }
  224. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  225. }
  226. func CloudBrainShow(ctx *context.Context) {
  227. ctx.Data["PageIsCloudBrain"] = true
  228. var jobID = ctx.Params(":jobid")
  229. task, err := models.GetCloudbrainByJobID(jobID)
  230. if err != nil {
  231. ctx.Data["error"] = err.Error()
  232. }
  233. result, err := cloudbrain.GetJob(jobID)
  234. if err != nil {
  235. ctx.Data["error"] = err.Error()
  236. }
  237. if result != nil {
  238. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  239. jobRes.Resource.Memory = strings.ReplaceAll(jobRes.Resource.Memory, "Mi", "MB")
  240. ctx.Data["result"] = jobRes
  241. taskRoles := jobRes.TaskRoles
  242. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  243. ctx.Data["taskRes"] = taskRes
  244. task.Status = taskRes.TaskStatuses[0].State
  245. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  246. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  247. err = models.UpdateJob(task)
  248. if err != nil {
  249. ctx.Data["error"] = err.Error()
  250. }
  251. }
  252. ctx.Data["task"] = task
  253. ctx.Data["jobID"] = jobID
  254. ctx.HTML(200, tplCloudBrainShow)
  255. }
  256. func CloudBrainDebug(ctx *context.Context) {
  257. var jobID = ctx.Params(":jobid")
  258. task, err := models.GetCloudbrainByJobID(jobID)
  259. if err != nil {
  260. ctx.ServerError("GetCloudbrainByJobID failed", err)
  261. return
  262. }
  263. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  264. ctx.Redirect(debugUrl)
  265. }
  266. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  267. var jobID = ctx.Params(":jobid")
  268. task, err := models.GetCloudbrainByJobID(jobID)
  269. if err != nil {
  270. ctx.JSON(200, map[string]string{
  271. "result_code": "-1",
  272. "error_msg": "GetCloudbrainByJobID failed",
  273. })
  274. return
  275. }
  276. err = cloudbrain.CommitImage(jobID, models.CommitImageParams{
  277. Ip: task.ContainerIp,
  278. TaskContainerId: task.ContainerID,
  279. ImageDescription: form.Description,
  280. ImageTag: form.Tag,
  281. })
  282. if err != nil {
  283. log.Error("CommitImage(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  284. ctx.JSON(200, map[string]string{
  285. "result_code": "-1",
  286. "error_msg": "CommitImage failed",
  287. })
  288. return
  289. }
  290. ctx.JSON(200, map[string]string{
  291. "result_code": "0",
  292. "error_msg": "",
  293. })
  294. }
  295. func CloudBrainStop(ctx *context.Context) {
  296. var jobID = ctx.Params(":jobid")
  297. task, err := models.GetCloudbrainByJobID(jobID)
  298. if err != nil {
  299. ctx.ServerError("GetCloudbrainByJobID failed", err)
  300. return
  301. }
  302. if task.Status == string(models.JobStopped) {
  303. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  304. ctx.ServerError("the job has been stopped", errors.New("the job has been stopped"))
  305. return
  306. }
  307. err = cloudbrain.StopJob(jobID)
  308. if err != nil {
  309. log.Error("StopJob(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  310. ctx.ServerError("StopJob failed", err)
  311. return
  312. }
  313. task.Status = string(models.JobStopped)
  314. err = models.UpdateJob(task)
  315. if err != nil {
  316. ctx.ServerError("UpdateJob failed", err)
  317. return
  318. }
  319. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  320. }
  321. func StopJobsByUserID(userID int64) {
  322. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  323. if err != nil {
  324. log.Warn("Failed to get cloudBrain info", err)
  325. return
  326. }
  327. StopJobs(cloudBrains)
  328. }
  329. func StopJobsByRepoID(repoID int64) {
  330. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  331. if err != nil {
  332. log.Warn("Failed to get cloudBrain info", err)
  333. return
  334. }
  335. StopJobs(cloudBrains)
  336. }
  337. /**
  338. */
  339. func StopJobs(cloudBrains []*models.Cloudbrain) {
  340. for _, taskInfo := range cloudBrains {
  341. if taskInfo.Type == models.TypeCloudBrainOne {
  342. err := retry(3, time.Second*30, func() error {
  343. return cloudbrain.StopJob(taskInfo.JobID)
  344. })
  345. logErrorAndUpdateJobStatus(err, taskInfo)
  346. } else {
  347. param := models.NotebookAction{
  348. Action: models.ActionStop,
  349. }
  350. err := retry(3, time.Second*30, func() error {
  351. _, err := modelarts.StopJob(taskInfo.JobID, param)
  352. return err
  353. })
  354. logErrorAndUpdateJobStatus(err, taskInfo)
  355. }
  356. }
  357. }
  358. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  359. for i := 0; i < attempts; i++ {
  360. if i > 0 {
  361. log.Warn("retrying after error:", err)
  362. time.Sleep(sleep)
  363. }
  364. err = f()
  365. if err == nil {
  366. return nil
  367. }
  368. }
  369. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  370. }
  371. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  372. if err != nil {
  373. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  374. } else {
  375. taskInfo.Status = string(models.JobStopped)
  376. err = models.UpdateJob(taskInfo)
  377. if err != nil {
  378. log.Warn("UpdateJob failed", err)
  379. }
  380. }
  381. }
  382. func CloudBrainDel(ctx *context.Context) {
  383. var jobID = ctx.Params(":jobid")
  384. task, err := models.GetCloudbrainByJobID(jobID)
  385. if err != nil {
  386. ctx.ServerError("GetCloudbrainByJobID failed", err)
  387. return
  388. }
  389. if task.Status != string(models.JobStopped) {
  390. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  391. ctx.ServerError("the job has not been stopped", errors.New("the job has not been stopped"))
  392. return
  393. }
  394. err = models.DeleteJob(task)
  395. if err != nil {
  396. ctx.ServerError("DeleteJob failed", err)
  397. return
  398. }
  399. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  400. }
  401. func CloudBrainShowModels(ctx *context.Context) {
  402. ctx.Data["PageIsCloudBrain"] = true
  403. jobID := ctx.Params(":jobid")
  404. parentDir := ctx.Query("parentDir")
  405. dirArray := strings.Split(parentDir, "/")
  406. task, err := models.GetCloudbrainByJobID(jobID)
  407. if err != nil {
  408. log.Error("no such job!", ctx.Data["msgID"])
  409. ctx.ServerError("no such job:", err)
  410. return
  411. }
  412. //get dirs
  413. dirs, err := getModelDirs(task.JobName, parentDir)
  414. if err != nil {
  415. log.Error("getModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  416. ctx.ServerError("getModelDirs failed:", err)
  417. return
  418. }
  419. var fileInfos []FileInfo
  420. err = json.Unmarshal([]byte(dirs), &fileInfos)
  421. if err != nil {
  422. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  423. ctx.ServerError("json.Unmarshal failed:", err)
  424. return
  425. }
  426. ctx.Data["Path"] = dirArray
  427. ctx.Data["Dirs"] = fileInfos
  428. ctx.Data["task"] = task
  429. ctx.Data["JobID"] = jobID
  430. ctx.HTML(200, tplCloudBrainShowModels)
  431. }
  432. func GetPublicImages(ctx *context.Context) {
  433. getImages(ctx, cloudbrain.Public)
  434. }
  435. func GetCustomImages(ctx *context.Context) {
  436. getImages(ctx, cloudbrain.Custom)
  437. }
  438. func getImages(ctx *context.Context, imageType string) {
  439. log.Info("Get images begin")
  440. page := ctx.QueryInt("page")
  441. size := ctx.QueryInt("size")
  442. name := ctx.Query("name")
  443. getImagesResult, err := cloudbrain.GetImagesPageable(page, size, imageType, name)
  444. if err != nil {
  445. log.Error("Can not get images:%v", err)
  446. ctx.JSON(http.StatusOK, models.GetImagesPayload{
  447. Count: 0,
  448. TotalPages: 0,
  449. ImageInfo: []*models.ImageInfo{},
  450. })
  451. } else {
  452. ctx.JSON(http.StatusOK, getImagesResult.Payload)
  453. }
  454. log.Info("Get images end")
  455. }
  456. func getModelDirs(jobName string, parentDir string) (string, error) {
  457. var req string
  458. modelActualPath := setting.JobPath + jobName + "/model/"
  459. if parentDir == "" {
  460. req = "baseDir=" + modelActualPath
  461. } else {
  462. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  463. }
  464. return getDirs(req)
  465. }
  466. func CloudBrainDownloadModel(ctx *context.Context) {
  467. parentDir := ctx.Query("parentDir")
  468. fileName := ctx.Query("fileName")
  469. jobName := ctx.Query("jobName")
  470. filePath := "jobs/" + jobName + "/model/" + parentDir
  471. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  472. if err != nil {
  473. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  474. ctx.ServerError("PresignedGetURL", err)
  475. return
  476. }
  477. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  478. }
  479. func GetRate(ctx *context.Context) {
  480. var jobID = ctx.Params(":jobid")
  481. job, err := models.GetCloudbrainByJobID(jobID)
  482. if err != nil {
  483. ctx.ServerError("GetCloudbrainByJobID failed", err)
  484. return
  485. }
  486. if job.JobType == string(models.JobTypeBenchmark) {
  487. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  488. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  489. ctx.Redirect(setting.Snn4imagenetServerHost)
  490. } else if job.JobType == string(models.JobTypeBrainScore) {
  491. ctx.Redirect(setting.BrainScoreServerHost)
  492. } else {
  493. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  494. }
  495. }
  496. func downloadCode(repo *models.Repository, codePath string) error {
  497. if err := git.Clone(repo.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  498. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  499. return err
  500. }
  501. configFile, err := os.OpenFile(codePath + "/.git/config", os.O_RDWR, 0666)
  502. if err != nil {
  503. log.Error("open file(%s) failed:%v", codePath + "/,git/config", err)
  504. return err
  505. }
  506. defer configFile.Close()
  507. pos := int64(0)
  508. reader := bufio.NewReader(configFile)
  509. for {
  510. line, err := reader.ReadString('\n')
  511. if err != nil {
  512. if err == io.EOF {
  513. log.Error("not find the remote-url")
  514. return nil
  515. } else {
  516. log.Error("read error: %v", err)
  517. return err
  518. }
  519. }
  520. if strings.Contains(line, "url") && strings.Contains(line, ".git"){
  521. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  522. if len(line) > len(originUrl) {
  523. originUrl += strings.Repeat( " ", len(line) - len(originUrl))
  524. }
  525. bytes := []byte(originUrl)
  526. _, err := configFile.WriteAt(bytes, pos)
  527. if err != nil {
  528. log.Error("WriteAt failed:%v", err)
  529. return err
  530. }
  531. break
  532. }
  533. pos += int64(len(line))
  534. }
  535. return nil
  536. }
  537. func downloadRateCode(repo *models.Repository, taskName, gitPath, codePath, benchmarkCategory, gpuType string) error {
  538. err := os.MkdirAll(codePath, os.ModePerm)
  539. if err != nil {
  540. log.Error("mkdir codePath failed", err.Error())
  541. return err
  542. }
  543. command := "git clone " + gitPath + " " + codePath
  544. cmd := exec.Command("/bin/bash", "-c", command)
  545. output, err := cmd.Output()
  546. log.Info(string(output))
  547. if err != nil {
  548. log.Error("exec.Command(%s) failed:%v", command, err)
  549. return err
  550. }
  551. fileName := codePath + cloudbrain.TaskInfoName
  552. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  553. if err != nil {
  554. log.Error("OpenFile failed", err.Error())
  555. return err
  556. }
  557. defer f.Close()
  558. data, err := json.Marshal(models.TaskInfo{
  559. Username: repo.Owner.Name,
  560. TaskName: taskName,
  561. CodeName: repo.Name,
  562. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  563. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  564. GpuType: gpuType,
  565. })
  566. if err != nil {
  567. log.Error("json.Marshal failed", err.Error())
  568. return err
  569. }
  570. _, err = f.Write(data)
  571. if err != nil {
  572. log.Error("WriteString failed", err.Error())
  573. return err
  574. }
  575. return nil
  576. }