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 20 kB

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