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
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
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
4 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
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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. return nil
  149. }
  150. func CloudBrainNew(ctx *context.Context) {
  151. err := cloudBrainNewDataPrepare(ctx)
  152. if err != nil {
  153. ctx.ServerError("get new cloudbrain info failed", err)
  154. return
  155. }
  156. ctx.HTML(200, tplCloudBrainNew)
  157. }
  158. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  159. ctx.Data["PageIsCloudBrain"] = true
  160. jobName := form.JobName
  161. image := form.Image
  162. command := form.Command
  163. uuid := form.Attachment
  164. jobType := form.JobType
  165. gpuQueue := setting.JobType
  166. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  167. resourceSpecId := form.ResourceSpecId
  168. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) && jobType != string(models.JobTypeSnn4imagenet) {
  169. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  170. cloudBrainNewDataPrepare(ctx)
  171. ctx.RenderWithErr("jobtype error", tplCloudBrainNew, &form)
  172. return
  173. }
  174. _, err := models.GetCloudbrainByName(jobName)
  175. if err == nil {
  176. log.Error("the job name did already exist", ctx.Data["MsgID"])
  177. cloudBrainNewDataPrepare(ctx)
  178. ctx.RenderWithErr("the job name did already exist", tplCloudBrainNew, &form)
  179. return
  180. } else {
  181. if !models.IsErrJobNotExist(err) {
  182. log.Error("system error, %v", err, ctx.Data["MsgID"])
  183. cloudBrainNewDataPrepare(ctx)
  184. ctx.RenderWithErr("system error", tplCloudBrainNew, &form)
  185. return
  186. }
  187. }
  188. repo := ctx.Repo.Repository
  189. downloadCode(repo, codePath)
  190. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath
  191. err = os.MkdirAll(modelPath, os.ModePerm)
  192. if err != nil {
  193. cloudBrainNewDataPrepare(ctx)
  194. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  195. return
  196. }
  197. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  198. if setting.IsBenchmarkEnabled && jobType == string(models.JobTypeBenchmark) {
  199. gpuQueue = form.GpuType
  200. var gpuType string
  201. for _, gpuInfo := range gpuInfos.GpuInfo {
  202. if gpuInfo.Queue == gpuQueue {
  203. gpuType = gpuInfo.Value
  204. }
  205. }
  206. downloadRateCode(repo, jobName, setting.BenchmarkCode, benchmarkPath, form.BenchmarkCategory, gpuType)
  207. }
  208. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  209. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  210. downloadRateCode(repo, jobName, setting.Snn4imagenetCode, snn4imagenetPath, "", "")
  211. }
  212. err = cloudbrain.GenerateTask(ctx, jobName, image, command, uuid, codePath, modelPath, benchmarkPath, snn4imagenetPath, jobType, gpuQueue, resourceSpecId)
  213. if err != nil {
  214. cloudBrainNewDataPrepare(ctx)
  215. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  216. return
  217. }
  218. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  219. }
  220. func CloudBrainShow(ctx *context.Context) {
  221. ctx.Data["PageIsCloudBrain"] = true
  222. var jobID = ctx.Params(":jobid")
  223. task, err := models.GetCloudbrainByJobID(jobID)
  224. if err != nil {
  225. ctx.Data["error"] = err.Error()
  226. }
  227. result, err := cloudbrain.GetJob(jobID)
  228. if err != nil {
  229. ctx.Data["error"] = err.Error()
  230. }
  231. if result != nil {
  232. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  233. jobRes.Resource.Memory = strings.ReplaceAll(jobRes.Resource.Memory, "Mi", "MB")
  234. ctx.Data["result"] = jobRes
  235. taskRoles := jobRes.TaskRoles
  236. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  237. ctx.Data["taskRes"] = taskRes
  238. task.Status = taskRes.TaskStatuses[0].State
  239. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  240. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  241. err = models.UpdateJob(task)
  242. if err != nil {
  243. ctx.Data["error"] = err.Error()
  244. }
  245. }
  246. ctx.Data["task"] = task
  247. ctx.Data["jobID"] = jobID
  248. ctx.HTML(200, tplCloudBrainShow)
  249. }
  250. func CloudBrainDebug(ctx *context.Context) {
  251. var jobID = ctx.Params(":jobid")
  252. task, err := models.GetCloudbrainByJobID(jobID)
  253. if err != nil {
  254. ctx.ServerError("GetCloudbrainByJobID failed", err)
  255. return
  256. }
  257. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  258. ctx.Redirect(debugUrl)
  259. }
  260. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  261. var jobID = ctx.Params(":jobid")
  262. task, err := models.GetCloudbrainByJobID(jobID)
  263. if err != nil {
  264. ctx.JSON(200, map[string]string{
  265. "result_code": "-1",
  266. "error_msg": "GetCloudbrainByJobID failed",
  267. })
  268. return
  269. }
  270. err = cloudbrain.CommitImage(jobID, models.CommitImageParams{
  271. Ip: task.ContainerIp,
  272. TaskContainerId: task.ContainerID,
  273. ImageDescription: form.Description,
  274. ImageTag: form.Tag,
  275. })
  276. if err != nil {
  277. log.Error("CommitImage(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  278. ctx.JSON(200, map[string]string{
  279. "result_code": "-1",
  280. "error_msg": "CommitImage failed",
  281. })
  282. return
  283. }
  284. ctx.JSON(200, map[string]string{
  285. "result_code": "0",
  286. "error_msg": "",
  287. })
  288. }
  289. func CloudBrainStop(ctx *context.Context) {
  290. var jobID = ctx.Params(":jobid")
  291. task, err := models.GetCloudbrainByJobID(jobID)
  292. if err != nil {
  293. ctx.ServerError("GetCloudbrainByJobID failed", err)
  294. return
  295. }
  296. if task.Status == string(models.JobStopped) {
  297. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  298. ctx.ServerError("the job has been stopped", errors.New("the job has been stopped"))
  299. return
  300. }
  301. err = cloudbrain.StopJob(jobID)
  302. if err != nil {
  303. log.Error("StopJob(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  304. ctx.ServerError("StopJob failed", err)
  305. return
  306. }
  307. task.Status = string(models.JobStopped)
  308. err = models.UpdateJob(task)
  309. if err != nil {
  310. ctx.ServerError("UpdateJob failed", err)
  311. return
  312. }
  313. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  314. }
  315. func StopJobsByUserID(userID int64) {
  316. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  317. if err != nil {
  318. log.Warn("Failed to get cloudBrain info", err)
  319. return
  320. }
  321. StopJobs(cloudBrains)
  322. }
  323. func StopJobsByRepoID(repoID int64) {
  324. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  325. if err != nil {
  326. log.Warn("Failed to get cloudBrain info", err)
  327. return
  328. }
  329. StopJobs(cloudBrains)
  330. }
  331. /**
  332. */
  333. func StopJobs(cloudBrains []*models.Cloudbrain) {
  334. for _, taskInfo := range cloudBrains {
  335. if taskInfo.Type == models.TypeCloudBrainOne {
  336. err := retry(3, time.Second*30, func() error {
  337. return cloudbrain.StopJob(taskInfo.JobID)
  338. })
  339. logErrorAndUpdateJobStatus(err, taskInfo)
  340. } else {
  341. param := models.NotebookAction{
  342. Action: models.ActionStop,
  343. }
  344. err := retry(3, time.Second*30, func() error {
  345. _, err := modelarts.StopJob(taskInfo.JobID, param)
  346. return err
  347. })
  348. logErrorAndUpdateJobStatus(err, taskInfo)
  349. }
  350. }
  351. }
  352. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  353. for i := 0; i < attempts; i++ {
  354. if i > 0 {
  355. log.Warn("retrying after error:", err)
  356. time.Sleep(sleep)
  357. }
  358. err = f()
  359. if err == nil {
  360. return nil
  361. }
  362. }
  363. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  364. }
  365. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  366. if err != nil {
  367. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  368. } else {
  369. taskInfo.Status = string(models.JobStopped)
  370. err = models.UpdateJob(taskInfo)
  371. if err != nil {
  372. log.Warn("UpdateJob failed", err)
  373. }
  374. }
  375. }
  376. func CloudBrainDel(ctx *context.Context) {
  377. var jobID = ctx.Params(":jobid")
  378. task, err := models.GetCloudbrainByJobID(jobID)
  379. if err != nil {
  380. ctx.ServerError("GetCloudbrainByJobID failed", err)
  381. return
  382. }
  383. if task.Status != string(models.JobStopped) {
  384. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  385. ctx.ServerError("the job has not been stopped", errors.New("the job has not been stopped"))
  386. return
  387. }
  388. err = models.DeleteJob(task)
  389. if err != nil {
  390. ctx.ServerError("DeleteJob failed", err)
  391. return
  392. }
  393. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  394. }
  395. func CloudBrainShowModels(ctx *context.Context) {
  396. ctx.Data["PageIsCloudBrain"] = true
  397. jobID := ctx.Params(":jobid")
  398. parentDir := ctx.Query("parentDir")
  399. dirArray := strings.Split(parentDir, "/")
  400. task, err := models.GetCloudbrainByJobID(jobID)
  401. if err != nil {
  402. log.Error("no such job!", ctx.Data["msgID"])
  403. ctx.ServerError("no such job:", err)
  404. return
  405. }
  406. //get dirs
  407. dirs, err := getModelDirs(task.JobName, parentDir)
  408. if err != nil {
  409. log.Error("getModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  410. ctx.ServerError("getModelDirs failed:", err)
  411. return
  412. }
  413. var fileInfos []FileInfo
  414. err = json.Unmarshal([]byte(dirs), &fileInfos)
  415. if err != nil {
  416. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  417. ctx.ServerError("json.Unmarshal failed:", err)
  418. return
  419. }
  420. ctx.Data["Path"] = dirArray
  421. ctx.Data["Dirs"] = fileInfos
  422. ctx.Data["task"] = task
  423. ctx.Data["JobID"] = jobID
  424. ctx.HTML(200, tplCloudBrainShowModels)
  425. }
  426. func GetPublicImages(ctx *context.Context) {
  427. getImages(ctx, cloudbrain.Public)
  428. }
  429. func GetCustomImages(ctx *context.Context) {
  430. getImages(ctx, cloudbrain.Custom)
  431. }
  432. func getImages(ctx *context.Context, imageType string) {
  433. log.Info("Get images begin")
  434. page := ctx.QueryInt("page")
  435. size := ctx.QueryInt("size")
  436. name := ctx.Query("name")
  437. getImagesResult, err := cloudbrain.GetImagesPageable(page, size, imageType, name)
  438. if err != nil {
  439. log.Error("Can not get images:%v", err)
  440. ctx.JSON(http.StatusOK, models.GetImagesPayload{
  441. Count: 0,
  442. TotalPages: 0,
  443. ImageInfo: []*models.ImageInfo{},
  444. })
  445. } else {
  446. ctx.JSON(http.StatusOK, getImagesResult.Payload)
  447. }
  448. log.Info("Get images end")
  449. }
  450. func getModelDirs(jobName string, parentDir string) (string, error) {
  451. var req string
  452. modelActualPath := setting.JobPath + jobName + "/model/"
  453. if parentDir == "" {
  454. req = "baseDir=" + modelActualPath
  455. } else {
  456. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  457. }
  458. return getDirs(req)
  459. }
  460. func CloudBrainDownloadModel(ctx *context.Context) {
  461. parentDir := ctx.Query("parentDir")
  462. fileName := ctx.Query("fileName")
  463. jobName := ctx.Query("jobName")
  464. filePath := "jobs/" + jobName + "/model/" + parentDir
  465. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  466. if err != nil {
  467. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  468. ctx.ServerError("PresignedGetURL", err)
  469. return
  470. }
  471. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  472. }
  473. func TrainJobloadModel(ctx *context.Context) {
  474. parentDir := ctx.Query("parentDir")
  475. fileName := ctx.Query("fileName")
  476. jobName := ctx.Query("jobName")
  477. filePath := "jobs/" + jobName + "/model/" + parentDir
  478. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  479. if err != nil {
  480. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  481. ctx.ServerError("PresignedGetURL", err)
  482. return
  483. }
  484. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  485. }
  486. func GetRate(ctx *context.Context) {
  487. var jobID = ctx.Params(":jobid")
  488. job, err := models.GetCloudbrainByJobID(jobID)
  489. if err != nil {
  490. ctx.ServerError("GetCloudbrainByJobID failed", err)
  491. return
  492. }
  493. if job.JobType == string(models.JobTypeBenchmark) {
  494. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  495. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  496. ctx.Redirect(setting.Snn4imagenetServerHost)
  497. } else {
  498. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  499. }
  500. }
  501. func downloadCode(repo *models.Repository, codePath string) error {
  502. if err := git.Clone(repo.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  503. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  504. return err
  505. }
  506. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  507. if err != nil {
  508. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  509. return err
  510. }
  511. defer configFile.Close()
  512. pos := int64(0)
  513. reader := bufio.NewReader(configFile)
  514. for {
  515. line, err := reader.ReadString('\n')
  516. if err != nil {
  517. if err == io.EOF {
  518. log.Error("not find the remote-url")
  519. return nil
  520. } else {
  521. log.Error("read error: %v", err)
  522. return err
  523. }
  524. }
  525. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  526. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  527. if len(line) > len(originUrl) {
  528. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  529. }
  530. bytes := []byte(originUrl)
  531. _, err := configFile.WriteAt(bytes, pos)
  532. if err != nil {
  533. log.Error("WriteAt failed:%v", err)
  534. return err
  535. }
  536. break
  537. }
  538. pos += int64(len(line))
  539. }
  540. return nil
  541. }
  542. func downloadRateCode(repo *models.Repository, taskName, gitPath, codePath, benchmarkCategory, gpuType string) error {
  543. err := os.MkdirAll(codePath, os.ModePerm)
  544. if err != nil {
  545. log.Error("mkdir codePath failed", err.Error())
  546. return err
  547. }
  548. command := "git clone " + gitPath + " " + codePath
  549. cmd := exec.Command("/bin/bash", "-c", command)
  550. output, err := cmd.Output()
  551. log.Info(string(output))
  552. if err != nil {
  553. log.Error("exec.Command(%s) failed:%v", command, err)
  554. return err
  555. }
  556. fileName := codePath + cloudbrain.TaskInfoName
  557. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  558. if err != nil {
  559. log.Error("OpenFile failed", err.Error())
  560. return err
  561. }
  562. defer f.Close()
  563. data, err := json.Marshal(models.TaskInfo{
  564. Username: repo.Owner.Name,
  565. TaskName: taskName,
  566. CodeName: repo.Name,
  567. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  568. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  569. GpuType: gpuType,
  570. })
  571. if err != nil {
  572. log.Error("json.Marshal failed", err.Error())
  573. return err
  574. }
  575. _, err = f.Write(data)
  576. if err != nil {
  577. log.Error("WriteString failed", err.Error())
  578. return err
  579. }
  580. return nil
  581. }