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

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
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
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
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. package repo
  2. import (
  3. "code.gitea.io/gitea/modules/git"
  4. "code.gitea.io/gitea/modules/storage"
  5. "encoding/json"
  6. "errors"
  7. "net/http"
  8. "os"
  9. "os/exec"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "code.gitea.io/gitea/models"
  14. "code.gitea.io/gitea/modules/auth"
  15. "code.gitea.io/gitea/modules/base"
  16. "code.gitea.io/gitea/modules/cloudbrain"
  17. "code.gitea.io/gitea/modules/context"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/setting"
  20. )
  21. const (
  22. tplCloudBrainIndex base.TplName = "repo/cloudbrain/index"
  23. tplCloudBrainNew base.TplName = "repo/cloudbrain/new"
  24. tplCloudBrainShow base.TplName = "repo/cloudbrain/show"
  25. tplCloudBrainShowModels base.TplName = "repo/cloudbrain/models/index"
  26. )
  27. var (
  28. gpuInfos *models.GpuInfos
  29. categories *models.Categories
  30. )
  31. // MustEnableDataset check if repository enable internal cb
  32. func MustEnableCloudbrain(ctx *context.Context) {
  33. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  34. ctx.NotFound("MustEnableCloudbrain", nil)
  35. return
  36. }
  37. }
  38. func CloudBrainIndex(ctx *context.Context) {
  39. MustEnableCloudbrain(ctx)
  40. repo := ctx.Repo.Repository
  41. page := ctx.QueryInt("page")
  42. if page <= 0 {
  43. page = 1
  44. }
  45. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  46. ListOptions: models.ListOptions{
  47. Page: page,
  48. PageSize: setting.UI.IssuePagingNum,
  49. },
  50. RepoID: repo.ID,
  51. Type: models.TypeCloudBrainOne,
  52. })
  53. if err != nil {
  54. ctx.ServerError("Cloudbrain", err)
  55. return
  56. }
  57. timestamp := time.Now().Unix()
  58. for i, task := range ciTasks {
  59. if task.Status == string(models.JobRunning) && (timestamp-int64(task.CreatedUnix) > 30) {
  60. ciTasks[i].CanDebug = true
  61. } else {
  62. ciTasks[i].CanDebug = false
  63. }
  64. }
  65. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  66. pager.SetDefaultParams(ctx)
  67. ctx.Data["Page"] = pager
  68. ctx.Data["PageIsCloudBrain"] = true
  69. ctx.Data["Tasks"] = ciTasks
  70. ctx.HTML(200, tplCloudBrainIndex)
  71. }
  72. func cutString(str string, lens int) string {
  73. if len(str) < lens {
  74. return str
  75. }
  76. return str[:lens]
  77. }
  78. func CloudBrainNew(ctx *context.Context) {
  79. ctx.Data["PageIsCloudBrain"] = true
  80. t := time.Now()
  81. var jobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  82. ctx.Data["job_name"] = jobName
  83. result, err := cloudbrain.GetImages()
  84. if err != nil {
  85. ctx.Data["error"] = err.Error()
  86. log.Error("cloudbrain.GetImages failed:", err.Error(), ctx.Data["msgID"])
  87. }
  88. for i, payload := range result.Payload.ImageInfo {
  89. if strings.HasPrefix(result.Payload.ImageInfo[i].Place, "192.168") {
  90. result.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  91. } else {
  92. result.Payload.ImageInfo[i].PlaceView = payload.Place
  93. }
  94. }
  95. ctx.Data["images"] = result.Payload.ImageInfo
  96. resultPublic, err := cloudbrain.GetPublicImages()
  97. if err != nil {
  98. ctx.Data["error"] = err.Error()
  99. log.Error("cloudbrain.GetPublicImages failed:", err.Error(), ctx.Data["msgID"])
  100. }
  101. for i, payload := range resultPublic.Payload.ImageInfo {
  102. if strings.HasPrefix(resultPublic.Payload.ImageInfo[i].Place, "192.168") {
  103. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  104. } else {
  105. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place
  106. }
  107. }
  108. ctx.Data["public_images"] = resultPublic.Payload.ImageInfo
  109. attachs, err := models.GetAllUserAttachments(ctx.User.ID)
  110. if err != nil {
  111. ctx.ServerError("GetAllUserAttachments failed:", err)
  112. return
  113. }
  114. ctx.Data["attachments"] = attachs
  115. ctx.Data["command"] = cloudbrain.Command
  116. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  117. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  118. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  119. ctx.Data["benchmark_path"] = cloudbrain.BenchMarkMountPath
  120. ctx.Data["is_benchmark_enabled"] = setting.IsBenchmarkEnabled
  121. if categories == nil {
  122. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  123. }
  124. ctx.Data["benchmark_categories"] = categories.Category
  125. if gpuInfos == nil {
  126. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  127. }
  128. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  129. ctx.Data["snn4imagenet_path"] = cloudbrain.Snn4imagenetMountPath
  130. ctx.Data["is_snn4imagenet_enabled"] = setting.IsSnn4imagenetEnabled
  131. ctx.HTML(200, tplCloudBrainNew)
  132. }
  133. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  134. ctx.Data["PageIsCloudBrain"] = true
  135. jobName := form.JobName
  136. image := form.Image
  137. command := form.Command
  138. uuid := form.Attachment
  139. jobType := form.JobType
  140. gpuQueue := setting.JobType
  141. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  142. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) && jobType != string(models.JobTypeSnn4imagenet) {
  143. log.Error("jobtype error:", jobType, ctx.Data["msgID"])
  144. ctx.RenderWithErr("jobtype error", tplCloudBrainNew, &form)
  145. return
  146. }
  147. _, err := models.GetCloudbrainByName(jobName)
  148. if err == nil {
  149. log.Error("the job name did already exist", ctx.Data["MsgID"])
  150. ctx.RenderWithErr("the job name did already exist", tplCloudBrainNew, &form)
  151. return
  152. } else {
  153. if !models.IsErrJobNotExist(err) {
  154. log.Error("system error, %v", err, ctx.Data["MsgID"])
  155. ctx.RenderWithErr("system error", tplCloudBrainNew, &form)
  156. return
  157. }
  158. }
  159. repo := ctx.Repo.Repository
  160. downloadCode(repo, codePath)
  161. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath
  162. err = os.MkdirAll(modelPath, os.ModePerm)
  163. if err != nil {
  164. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  165. return
  166. }
  167. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  168. if setting.IsBenchmarkEnabled && jobType == string(models.JobTypeBenchmark) {
  169. gpuQueue = form.GpuType
  170. var gpuType string
  171. for _, gpuInfo := range gpuInfos.GpuInfo {
  172. if gpuInfo.Queue == gpuQueue {
  173. gpuType = gpuInfo.Value
  174. }
  175. }
  176. downloadRateCode(repo, jobName, setting.BenchmarkCode, benchmarkPath, form.BenchmarkCategory, gpuType)
  177. }
  178. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  179. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  180. downloadRateCode(repo, jobName, setting.Snn4imagenetCode, snn4imagenetPath, "", "")
  181. }
  182. err = cloudbrain.GenerateTask(ctx, jobName, image, command, uuid, codePath, modelPath, benchmarkPath, snn4imagenetPath, jobType, gpuQueue)
  183. if err != nil {
  184. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  185. return
  186. }
  187. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  188. }
  189. func CloudBrainShow(ctx *context.Context) {
  190. ctx.Data["PageIsCloudBrain"] = true
  191. var jobID = ctx.Params(":jobid")
  192. task, err := models.GetCloudbrainByJobID(jobID)
  193. if err != nil {
  194. ctx.Data["error"] = err.Error()
  195. }
  196. result, err := cloudbrain.GetJob(jobID)
  197. if err != nil {
  198. ctx.Data["error"] = err.Error()
  199. }
  200. if result != nil {
  201. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  202. ctx.Data["result"] = jobRes
  203. taskRoles := jobRes.TaskRoles
  204. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  205. ctx.Data["taskRes"] = taskRes
  206. task.Status = taskRes.TaskStatuses[0].State
  207. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  208. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  209. err = models.UpdateJob(task)
  210. if err != nil {
  211. ctx.Data["error"] = err.Error()
  212. }
  213. }
  214. ctx.Data["task"] = task
  215. ctx.Data["jobID"] = jobID
  216. ctx.HTML(200, tplCloudBrainShow)
  217. }
  218. func CloudBrainDebug(ctx *context.Context) {
  219. var jobID = ctx.Params(":jobid")
  220. task, err := models.GetCloudbrainByJobID(jobID)
  221. if err != nil {
  222. ctx.ServerError("GetCloudbrainByJobID failed", err)
  223. return
  224. }
  225. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  226. ctx.Redirect(debugUrl)
  227. }
  228. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  229. var jobID = ctx.Params(":jobid")
  230. task, err := models.GetCloudbrainByJobID(jobID)
  231. if err != nil {
  232. ctx.JSON(200, map[string]string{
  233. "result_code": "-1",
  234. "error_msg": "GetCloudbrainByJobID failed",
  235. })
  236. return
  237. }
  238. err = cloudbrain.CommitImage(jobID, models.CommitImageParams{
  239. Ip: task.ContainerIp,
  240. TaskContainerId: task.ContainerID,
  241. ImageDescription: form.Description,
  242. ImageTag: form.Tag,
  243. })
  244. if err != nil {
  245. log.Error("CommitImage(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  246. ctx.JSON(200, map[string]string{
  247. "result_code": "-1",
  248. "error_msg": "CommitImage failed",
  249. })
  250. return
  251. }
  252. ctx.JSON(200, map[string]string{
  253. "result_code": "0",
  254. "error_msg": "",
  255. })
  256. }
  257. func CloudBrainStop(ctx *context.Context) {
  258. var jobID = ctx.Params(":jobid")
  259. task, err := models.GetCloudbrainByJobID(jobID)
  260. if err != nil {
  261. ctx.ServerError("GetCloudbrainByJobID failed", err)
  262. return
  263. }
  264. if task.Status == string(models.JobStopped) {
  265. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  266. ctx.ServerError("the job has been stopped", errors.New("the job has been stopped"))
  267. return
  268. }
  269. err = cloudbrain.StopJob(jobID)
  270. if err != nil {
  271. log.Error("StopJob(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  272. ctx.ServerError("StopJob failed", err)
  273. return
  274. }
  275. task.Status = string(models.JobStopped)
  276. err = models.UpdateJob(task)
  277. if err != nil {
  278. ctx.ServerError("UpdateJob failed", err)
  279. return
  280. }
  281. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  282. }
  283. func CloudBrainDel(ctx *context.Context) {
  284. var jobID = ctx.Params(":jobid")
  285. task, err := models.GetCloudbrainByJobID(jobID)
  286. if err != nil {
  287. ctx.ServerError("GetCloudbrainByJobID failed", err)
  288. return
  289. }
  290. if task.Status != string(models.JobStopped) {
  291. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  292. ctx.ServerError("the job has not been stopped", errors.New("the job has not been stopped"))
  293. return
  294. }
  295. err = models.DeleteJob(task)
  296. if err != nil {
  297. ctx.ServerError("DeleteJob failed", err)
  298. return
  299. }
  300. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  301. }
  302. func CloudBrainShowModels(ctx *context.Context) {
  303. ctx.Data["PageIsCloudBrain"] = true
  304. jobID := ctx.Params(":jobid")
  305. parentDir := ctx.Query("parentDir")
  306. dirArray := strings.Split(parentDir, "/")
  307. task, err := models.GetCloudbrainByJobID(jobID)
  308. if err != nil {
  309. log.Error("no such job!", ctx.Data["msgID"])
  310. ctx.ServerError("no such job:", err)
  311. return
  312. }
  313. //get dirs
  314. dirs, err := getModelDirs(task.JobName, parentDir)
  315. if err != nil {
  316. log.Error("getModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  317. ctx.ServerError("getModelDirs failed:", err)
  318. return
  319. }
  320. var fileInfos []FileInfo
  321. err = json.Unmarshal([]byte(dirs), &fileInfos)
  322. if err != nil {
  323. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  324. ctx.ServerError("json.Unmarshal failed:", err)
  325. return
  326. }
  327. ctx.Data["Path"] = dirArray
  328. ctx.Data["Dirs"] = fileInfos
  329. ctx.Data["task"] = task
  330. ctx.Data["JobID"] = jobID
  331. ctx.HTML(200, tplCloudBrainShowModels)
  332. }
  333. func getModelDirs(jobName string, parentDir string) (string, error) {
  334. var req string
  335. modelActualPath := setting.JobPath + jobName + "/model/"
  336. if parentDir == "" {
  337. req = "baseDir=" + modelActualPath
  338. } else {
  339. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  340. }
  341. return getDirs(req)
  342. }
  343. func CloudBrainDownloadModel(ctx *context.Context) {
  344. parentDir := ctx.Query("parentDir")
  345. fileName := ctx.Query("fileName")
  346. jobName := ctx.Query("jobName")
  347. filePath := "jobs/" +jobName + "/model/" + parentDir
  348. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  349. if err != nil {
  350. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  351. ctx.ServerError("PresignedGetURL", err)
  352. return
  353. }
  354. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  355. }
  356. func GetRate(ctx *context.Context) {
  357. var jobID = ctx.Params(":jobid")
  358. job, err := models.GetCloudbrainByJobID(jobID)
  359. if err != nil {
  360. ctx.ServerError("GetCloudbrainByJobID failed", err)
  361. return
  362. }
  363. if job.JobType == string(models.JobTypeBenchmark) {
  364. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  365. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  366. ctx.Redirect(setting.Snn4imagenetServerHost)
  367. } else {
  368. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  369. }
  370. }
  371. func downloadCode(repo *models.Repository, codePath string) error {
  372. if err := git.Clone(repo.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  373. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  374. return err
  375. }
  376. return nil
  377. }
  378. func downloadRateCode(repo *models.Repository, taskName, gitPath, codePath, benchmarkCategory, gpuType string) error {
  379. err := os.MkdirAll(codePath, os.ModePerm)
  380. if err != nil {
  381. log.Error("mkdir codePath failed", err.Error())
  382. return err
  383. }
  384. command := "git clone " + gitPath + " " + codePath
  385. cmd := exec.Command("/bin/bash", "-c", command)
  386. output, err := cmd.Output()
  387. log.Info(string(output))
  388. if err != nil {
  389. log.Error("exec.Command(%s) failed:%v", command, err)
  390. return err
  391. }
  392. fileName := codePath + cloudbrain.TaskInfoName
  393. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  394. if err != nil {
  395. log.Error("OpenFile failed", err.Error())
  396. return err
  397. }
  398. defer f.Close()
  399. data, err := json.Marshal(models.TaskInfo{
  400. Username: repo.Owner.Name,
  401. TaskName: taskName,
  402. CodeName: repo.Name,
  403. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  404. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  405. GpuType: gpuType,
  406. })
  407. if err != nil {
  408. log.Error("json.Marshal failed", err.Error())
  409. return err
  410. }
  411. _, err = f.Write(data)
  412. if err != nil {
  413. log.Error("WriteString failed", err.Error())
  414. return err
  415. }
  416. return nil
  417. }