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