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