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