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
4 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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  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. taskRoles := jobRes.TaskRoles
  241. if jobRes.JobStatus.State != string(models.JobFailed) {
  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. } else {
  252. task.Status = jobRes.JobStatus.State
  253. taskRes := models.TaskPod{TaskStatuses: []models.TaskStatuses{
  254. {
  255. State: jobRes.JobStatus.State,
  256. },
  257. }}
  258. ctx.Data["taskRes"] = taskRes
  259. jobRes.JobStatus.StartTime = time.Unix(int64(task.CreatedUnix), 0).Format("2006-01-02 15:04:05")
  260. jobRes.JobStatus.EndTime = time.Unix(int64(task.UpdatedUnix), 0).Format("2006-01-02 15:04:05")
  261. }
  262. ctx.Data["result"] = jobRes
  263. }
  264. ctx.Data["task"] = task
  265. ctx.Data["jobID"] = jobID
  266. ctx.HTML(200, tplCloudBrainShow)
  267. }
  268. func CloudBrainDebug(ctx *context.Context) {
  269. var jobID = ctx.Params(":jobid")
  270. task, err := models.GetCloudbrainByJobID(jobID)
  271. if err != nil {
  272. ctx.ServerError("GetCloudbrainByJobID failed", err)
  273. return
  274. }
  275. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  276. ctx.Redirect(debugUrl)
  277. }
  278. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  279. var jobID = ctx.Params(":jobid")
  280. task, err := models.GetCloudbrainByJobID(jobID)
  281. if err != nil {
  282. ctx.JSON(200, map[string]string{
  283. "result_code": "-1",
  284. "error_msg": "GetCloudbrainByJobID failed",
  285. })
  286. return
  287. }
  288. err = cloudbrain.CommitImage(jobID, models.CommitImageParams{
  289. Ip: task.ContainerIp,
  290. TaskContainerId: task.ContainerID,
  291. ImageDescription: form.Description,
  292. ImageTag: form.Tag,
  293. })
  294. if err != nil {
  295. log.Error("CommitImage(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  296. ctx.JSON(200, map[string]string{
  297. "result_code": "-1",
  298. "error_msg": "CommitImage failed",
  299. })
  300. return
  301. }
  302. ctx.JSON(200, map[string]string{
  303. "result_code": "0",
  304. "error_msg": "",
  305. })
  306. }
  307. func CloudBrainStop(ctx *context.Context) {
  308. var jobID = ctx.Params(":jobid")
  309. task, err := models.GetCloudbrainByJobID(jobID)
  310. if err != nil {
  311. ctx.ServerError("GetCloudbrainByJobID failed", err)
  312. return
  313. }
  314. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) {
  315. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  316. ctx.ServerError("the job has been stopped", errors.New("the job has been stopped"))
  317. return
  318. }
  319. err = cloudbrain.StopJob(jobID)
  320. if err != nil {
  321. log.Error("StopJob(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  322. ctx.ServerError("StopJob failed", err)
  323. return
  324. }
  325. task.Status = string(models.JobStopped)
  326. err = models.UpdateJob(task)
  327. if err != nil {
  328. ctx.ServerError("UpdateJob failed", err)
  329. return
  330. }
  331. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  332. }
  333. func StopJobsByUserID(userID int64) {
  334. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  335. if err != nil {
  336. log.Warn("Failed to get cloudBrain info", err)
  337. return
  338. }
  339. StopJobs(cloudBrains)
  340. }
  341. func StopJobsByRepoID(repoID int64) {
  342. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  343. if err != nil {
  344. log.Warn("Failed to get cloudBrain info", err)
  345. return
  346. }
  347. StopJobs(cloudBrains)
  348. }
  349. /**
  350. */
  351. func StopJobs(cloudBrains []*models.Cloudbrain) {
  352. for _, taskInfo := range cloudBrains {
  353. if taskInfo.Type == models.TypeCloudBrainOne {
  354. err := retry(3, time.Second*30, func() error {
  355. return cloudbrain.StopJob(taskInfo.JobID)
  356. })
  357. logErrorAndUpdateJobStatus(err, taskInfo)
  358. } else {
  359. param := models.NotebookAction{
  360. Action: models.ActionStop,
  361. }
  362. err := retry(3, time.Second*30, func() error {
  363. _, err := modelarts.StopJob(taskInfo.JobID, param)
  364. return err
  365. })
  366. logErrorAndUpdateJobStatus(err, taskInfo)
  367. }
  368. }
  369. }
  370. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  371. for i := 0; i < attempts; i++ {
  372. if i > 0 {
  373. log.Warn("retrying after error:", err)
  374. time.Sleep(sleep)
  375. }
  376. err = f()
  377. if err == nil {
  378. return nil
  379. }
  380. }
  381. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  382. }
  383. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  384. if err != nil {
  385. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  386. } else {
  387. taskInfo.Status = string(models.JobStopped)
  388. err = models.UpdateJob(taskInfo)
  389. if err != nil {
  390. log.Warn("UpdateJob failed", err)
  391. }
  392. }
  393. }
  394. func CloudBrainDel(ctx *context.Context) {
  395. var jobID = ctx.Params(":jobid")
  396. task, err := models.GetCloudbrainByJobID(jobID)
  397. if err != nil {
  398. ctx.ServerError("GetCloudbrainByJobID failed", err)
  399. return
  400. }
  401. if task.Status != string(models.JobStopped) {
  402. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  403. ctx.ServerError("the job has not been stopped", errors.New("the job has not been stopped"))
  404. return
  405. }
  406. err = models.DeleteJob(task)
  407. if err != nil {
  408. ctx.ServerError("DeleteJob failed", err)
  409. return
  410. }
  411. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  412. }
  413. func CloudBrainShowModels(ctx *context.Context) {
  414. ctx.Data["PageIsCloudBrain"] = true
  415. jobID := ctx.Params(":jobid")
  416. parentDir := ctx.Query("parentDir")
  417. dirArray := strings.Split(parentDir, "/")
  418. task, err := models.GetCloudbrainByJobID(jobID)
  419. if err != nil {
  420. log.Error("no such job!", ctx.Data["msgID"])
  421. ctx.ServerError("no such job:", err)
  422. return
  423. }
  424. //get dirs
  425. dirs, err := getModelDirs(task.JobName, parentDir)
  426. if err != nil {
  427. log.Error("getModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  428. ctx.ServerError("getModelDirs failed:", err)
  429. return
  430. }
  431. var fileInfos []FileInfo
  432. err = json.Unmarshal([]byte(dirs), &fileInfos)
  433. if err != nil {
  434. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  435. ctx.ServerError("json.Unmarshal failed:", err)
  436. return
  437. }
  438. ctx.Data["Path"] = dirArray
  439. ctx.Data["Dirs"] = fileInfos
  440. ctx.Data["task"] = task
  441. ctx.Data["JobID"] = jobID
  442. ctx.HTML(200, tplCloudBrainShowModels)
  443. }
  444. func GetPublicImages(ctx *context.Context) {
  445. getImages(ctx, cloudbrain.Public)
  446. }
  447. func GetCustomImages(ctx *context.Context) {
  448. getImages(ctx, cloudbrain.Custom)
  449. }
  450. func getImages(ctx *context.Context, imageType string) {
  451. log.Info("Get images begin")
  452. page := ctx.QueryInt("page")
  453. size := ctx.QueryInt("size")
  454. name := ctx.Query("name")
  455. getImagesResult, err := cloudbrain.GetImagesPageable(page, size, imageType, name)
  456. if err != nil {
  457. log.Error("Can not get images:%v", err)
  458. ctx.JSON(http.StatusOK, models.GetImagesPayload{
  459. Count: 0,
  460. TotalPages: 0,
  461. ImageInfo: []*models.ImageInfo{},
  462. })
  463. } else {
  464. ctx.JSON(http.StatusOK, getImagesResult.Payload)
  465. }
  466. log.Info("Get images end")
  467. }
  468. func getModelDirs(jobName string, parentDir string) (string, error) {
  469. var req string
  470. modelActualPath := setting.JobPath + jobName + "/model/"
  471. if parentDir == "" {
  472. req = "baseDir=" + modelActualPath
  473. } else {
  474. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  475. }
  476. return getDirs(req)
  477. }
  478. func CloudBrainDownloadModel(ctx *context.Context) {
  479. parentDir := ctx.Query("parentDir")
  480. fileName := ctx.Query("fileName")
  481. jobName := ctx.Query("jobName")
  482. filePath := "jobs/" + jobName + "/model/" + parentDir
  483. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  484. if err != nil {
  485. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  486. ctx.ServerError("PresignedGetURL", err)
  487. return
  488. }
  489. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  490. }
  491. func GetRate(ctx *context.Context) {
  492. var jobID = ctx.Params(":jobid")
  493. job, err := models.GetCloudbrainByJobID(jobID)
  494. if err != nil {
  495. ctx.ServerError("GetCloudbrainByJobID failed", err)
  496. return
  497. }
  498. if job.JobType == string(models.JobTypeBenchmark) {
  499. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  500. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  501. ctx.Redirect(setting.Snn4imagenetServerHost)
  502. } else if job.JobType == string(models.JobTypeBrainScore) {
  503. ctx.Redirect(setting.BrainScoreServerHost)
  504. } else {
  505. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  506. }
  507. }
  508. func downloadCode(repo *models.Repository, codePath string) error {
  509. if err := git.Clone(repo.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  510. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  511. return err
  512. }
  513. configFile, err := os.OpenFile(codePath + "/.git/config", os.O_RDWR, 0666)
  514. if err != nil {
  515. log.Error("open file(%s) failed:%v", codePath + "/,git/config", err)
  516. return err
  517. }
  518. defer configFile.Close()
  519. pos := int64(0)
  520. reader := bufio.NewReader(configFile)
  521. for {
  522. line, err := reader.ReadString('\n')
  523. if err != nil {
  524. if err == io.EOF {
  525. log.Error("not find the remote-url")
  526. return nil
  527. } else {
  528. log.Error("read error: %v", err)
  529. return err
  530. }
  531. }
  532. if strings.Contains(line, "url") && strings.Contains(line, ".git"){
  533. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  534. if len(line) > len(originUrl) {
  535. originUrl += strings.Repeat( " ", len(line) - len(originUrl))
  536. }
  537. bytes := []byte(originUrl)
  538. _, err := configFile.WriteAt(bytes, pos)
  539. if err != nil {
  540. log.Error("WriteAt failed:%v", err)
  541. return err
  542. }
  543. break
  544. }
  545. pos += int64(len(line))
  546. }
  547. return nil
  548. }
  549. func downloadRateCode(repo *models.Repository, taskName, gitPath, codePath, benchmarkCategory, gpuType string) error {
  550. err := os.MkdirAll(codePath, os.ModePerm)
  551. if err != nil {
  552. log.Error("mkdir codePath failed", err.Error())
  553. return err
  554. }
  555. command := "git clone " + gitPath + " " + codePath
  556. cmd := exec.Command("/bin/bash", "-c", command)
  557. output, err := cmd.Output()
  558. log.Info(string(output))
  559. if err != nil {
  560. log.Error("exec.Command(%s) failed:%v", command, err)
  561. return err
  562. }
  563. fileName := codePath + cloudbrain.TaskInfoName
  564. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  565. if err != nil {
  566. log.Error("OpenFile failed", err.Error())
  567. return err
  568. }
  569. defer f.Close()
  570. data, err := json.Marshal(models.TaskInfo{
  571. Username: repo.Owner.Name,
  572. TaskName: taskName,
  573. CodeName: repo.Name,
  574. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  575. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  576. GpuType: gpuType,
  577. })
  578. if err != nil {
  579. log.Error("json.Marshal failed", err.Error())
  580. return err
  581. }
  582. _, err = f.Write(data)
  583. if err != nil {
  584. log.Error("WriteString failed", err.Error())
  585. return err
  586. }
  587. return nil
  588. }