您最多选择25个标签 标签必须以中文、字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

cloudbrain.go 25 kB

4 年前
4 年前
5 年前
5 年前
4 年前
5 年前
4 年前
5 年前
5 年前
4 年前
5 年前
4 年前
5 年前
4 年前
5 年前
5 年前
5 年前
5 年前
4 年前
5 年前
4 年前
5 年前
5 年前
5 年前
4 年前
4 年前
4 年前
5 年前
4 年前
5 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
5 年前
4 年前
5 年前
5 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
5 年前
4 年前
5 年前
4 年前
5 年前
5 年前
5 年前
5 年前
4 年前
5 年前
4 年前
4 年前
4 年前
4 年前
5 年前
5 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
5 年前
5 年前
4 年前
4 年前
5 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
4 年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  1. package repo
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "regexp"
  11. "sort"
  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. var jobNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-_]{1,34}[a-z0-9-]$`)
  37. // MustEnableDataset check if repository enable internal cb
  38. func MustEnableCloudbrain(ctx *context.Context) {
  39. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  40. ctx.NotFound("MustEnableCloudbrain", nil)
  41. return
  42. }
  43. }
  44. func CloudBrainIndex(ctx *context.Context) {
  45. MustEnableCloudbrain(ctx)
  46. repo := ctx.Repo.Repository
  47. page := ctx.QueryInt("page")
  48. if page <= 0 {
  49. page = 1
  50. }
  51. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  52. ListOptions: models.ListOptions{
  53. Page: page,
  54. PageSize: setting.UI.IssuePagingNum,
  55. },
  56. RepoID: repo.ID,
  57. Type: models.TypeCloudBrainOne,
  58. })
  59. if err != nil {
  60. ctx.ServerError("Cloudbrain", err)
  61. return
  62. }
  63. timestamp := time.Now().Unix()
  64. for i, task := range ciTasks {
  65. if task.Status == string(models.JobRunning) && (timestamp-int64(task.Cloudbrain.CreatedUnix) > 10) {
  66. ciTasks[i].CanDebug = cloudbrain.CanCreateOrDebugJob(ctx)
  67. } else {
  68. ciTasks[i].CanDebug = false
  69. }
  70. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  71. }
  72. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  73. pager.SetDefaultParams(ctx)
  74. ctx.Data["Page"] = pager
  75. ctx.Data["PageIsCloudBrain"] = true
  76. ctx.Data["Tasks"] = ciTasks
  77. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  78. ctx.HTML(200, tplCloudBrainIndex)
  79. }
  80. func cutString(str string, lens int) string {
  81. if len(str) < lens {
  82. return str
  83. }
  84. return str[:lens]
  85. }
  86. func jobNamePrefixValid(s string) string {
  87. lowStr := strings.ToLower(s)
  88. re := regexp.MustCompile(`[^a-z0-9_\\-]+`)
  89. removeSpecial := re.ReplaceAllString(lowStr, "")
  90. re = regexp.MustCompile(`^[_\\-]+`)
  91. return re.ReplaceAllString(removeSpecial, "")
  92. }
  93. func cloudBrainNewDataPrepare(ctx *context.Context) error {
  94. ctx.Data["PageIsCloudBrain"] = true
  95. t := time.Now()
  96. var jobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  97. ctx.Data["job_name"] = jobName
  98. result, err := cloudbrain.GetImages()
  99. if err != nil {
  100. ctx.Data["error"] = err.Error()
  101. log.Error("cloudbrain.GetImages failed:", err.Error(), ctx.Data["MsgID"])
  102. }
  103. for i, payload := range result.Payload.ImageInfo {
  104. if strings.HasPrefix(result.Payload.ImageInfo[i].Place, "192.168") {
  105. result.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  106. } else {
  107. result.Payload.ImageInfo[i].PlaceView = payload.Place
  108. }
  109. }
  110. ctx.Data["images"] = result.Payload.ImageInfo
  111. resultPublic, err := cloudbrain.GetPublicImages()
  112. if err != nil {
  113. ctx.Data["error"] = err.Error()
  114. log.Error("cloudbrain.GetPublicImages failed:", err.Error(), ctx.Data["MsgID"])
  115. }
  116. for i, payload := range resultPublic.Payload.ImageInfo {
  117. if strings.HasPrefix(resultPublic.Payload.ImageInfo[i].Place, "192.168") {
  118. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  119. } else {
  120. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place
  121. }
  122. }
  123. ctx.Data["public_images"] = resultPublic.Payload.ImageInfo
  124. attachs, err := models.GetAllUserAttachments(ctx.User.ID)
  125. if err != nil {
  126. log.Error("GetAllUserAttachments failed: %v", err, ctx.Data["MsgID"])
  127. return err
  128. }
  129. ctx.Data["attachments"] = attachs
  130. ctx.Data["command"] = cloudbrain.Command
  131. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  132. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  133. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  134. ctx.Data["benchmark_path"] = cloudbrain.BenchMarkMountPath
  135. ctx.Data["is_benchmark_enabled"] = setting.IsBenchmarkEnabled
  136. if categories == nil {
  137. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  138. }
  139. ctx.Data["benchmark_categories"] = categories.Category
  140. if gpuInfos == nil {
  141. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  142. }
  143. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  144. if cloudbrain.ResourceSpecs == nil {
  145. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  146. }
  147. ctx.Data["resource_specs"] = cloudbrain.ResourceSpecs.ResourceSpec
  148. ctx.Data["snn4imagenet_path"] = cloudbrain.Snn4imagenetMountPath
  149. ctx.Data["is_snn4imagenet_enabled"] = setting.IsSnn4imagenetEnabled
  150. ctx.Data["brainscore_path"] = cloudbrain.BrainScoreMountPath
  151. ctx.Data["is_brainscore_enabled"] = setting.IsBrainScoreEnabled
  152. return nil
  153. }
  154. func CloudBrainNew(ctx *context.Context) {
  155. err := cloudBrainNewDataPrepare(ctx)
  156. if err != nil {
  157. ctx.ServerError("get new cloudbrain info failed", err)
  158. return
  159. }
  160. ctx.HTML(200, tplCloudBrainNew)
  161. }
  162. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  163. ctx.Data["PageIsCloudBrain"] = true
  164. jobName := form.JobName
  165. image := form.Image
  166. command := form.Command
  167. uuid := form.Attachment
  168. jobType := form.JobType
  169. gpuQueue := form.GpuType
  170. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  171. resourceSpecId := form.ResourceSpecId
  172. if !jobNamePattern.MatchString(jobName) {
  173. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainNew, &form)
  174. return
  175. }
  176. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) && jobType != string(models.JobTypeSnn4imagenet) && jobType != string(models.JobTypeBrainScore) {
  177. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  178. cloudBrainNewDataPrepare(ctx)
  179. ctx.RenderWithErr("jobtype error", tplCloudBrainNew, &form)
  180. return
  181. }
  182. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID)
  183. if err != nil {
  184. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  185. cloudBrainNewDataPrepare(ctx)
  186. ctx.RenderWithErr("system error", tplCloudBrainNew, &form)
  187. return
  188. } else {
  189. if count >= 1 {
  190. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  191. cloudBrainNewDataPrepare(ctx)
  192. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplCloudBrainNew, &form)
  193. return
  194. }
  195. }
  196. _, err = models.GetCloudbrainByName(jobName)
  197. if err == nil {
  198. log.Error("the job name did already exist", ctx.Data["MsgID"])
  199. cloudBrainNewDataPrepare(ctx)
  200. ctx.RenderWithErr("the job name did already exist", tplCloudBrainNew, &form)
  201. return
  202. } else {
  203. if !models.IsErrJobNotExist(err) {
  204. log.Error("system error, %v", err, ctx.Data["MsgID"])
  205. cloudBrainNewDataPrepare(ctx)
  206. ctx.RenderWithErr("system error", tplCloudBrainNew, &form)
  207. return
  208. }
  209. }
  210. repo := ctx.Repo.Repository
  211. downloadCode(repo, codePath)
  212. uploadCodeToMinio(codePath + "/", jobName, "/code/")
  213. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  214. mkModelPath(modelPath)
  215. uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath + "/")
  216. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  217. if setting.IsBenchmarkEnabled && jobType == string(models.JobTypeBenchmark) {
  218. var gpuType string
  219. for _, gpuInfo := range gpuInfos.GpuInfo {
  220. if gpuInfo.Queue == gpuQueue {
  221. gpuType = gpuInfo.Value
  222. }
  223. }
  224. downloadRateCode(repo, jobName, setting.BenchmarkOwner, setting.BrainScoreName, benchmarkPath, form.BenchmarkCategory, gpuType)
  225. uploadCodeToMinio(benchmarkPath + "/", jobName, cloudbrain.BenchMarkMountPath + "/")
  226. }
  227. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  228. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  229. downloadRateCode(repo, jobName, setting.Snn4imagenetOwner, setting.Snn4imagenetName, snn4imagenetPath, "", "")
  230. uploadCodeToMinio(snn4imagenetPath + "/", jobName, cloudbrain.Snn4imagenetMountPath + "/")
  231. }
  232. brainScorePath := setting.JobPath + jobName + cloudbrain.BrainScoreMountPath
  233. if setting.IsBrainScoreEnabled && jobType == string(models.JobTypeBrainScore) {
  234. downloadRateCode(repo, jobName, setting.BrainScoreOwner, setting.BrainScoreName, brainScorePath, "", "")
  235. uploadCodeToMinio(brainScorePath + "/", jobName, cloudbrain.BrainScoreMountPath + "/")
  236. }
  237. err = cloudbrain.GenerateTask(ctx, jobName, image, command, uuid, codePath, getMinioPath(jobName, cloudbrain.ModelMountPath + "/"),
  238. getMinioPath(jobName, cloudbrain.BenchMarkMountPath + "/"), getMinioPath(jobName, cloudbrain.Snn4imagenetMountPath + "/"),
  239. getMinioPath(jobName, cloudbrain.BrainScoreMountPath + "/"), jobType, gpuQueue, resourceSpecId)
  240. if err != nil {
  241. cloudBrainNewDataPrepare(ctx)
  242. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  243. return
  244. }
  245. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  246. }
  247. func CloudBrainShow(ctx *context.Context) {
  248. ctx.Data["PageIsCloudBrain"] = true
  249. var jobID = ctx.Params(":jobid")
  250. task, err := models.GetCloudbrainByJobID(jobID)
  251. if err != nil {
  252. ctx.Data["error"] = err.Error()
  253. }
  254. result, err := cloudbrain.GetJob(jobID)
  255. if err != nil {
  256. ctx.Data["error"] = err.Error()
  257. }
  258. if result != nil {
  259. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  260. jobRes.Resource.Memory = strings.ReplaceAll(jobRes.Resource.Memory, "Mi", "MB")
  261. taskRoles := jobRes.TaskRoles
  262. if jobRes.JobStatus.State != string(models.JobFailed) {
  263. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  264. ctx.Data["taskRes"] = taskRes
  265. task.Status = taskRes.TaskStatuses[0].State
  266. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  267. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  268. err = models.UpdateJob(task)
  269. if err != nil {
  270. ctx.Data["error"] = err.Error()
  271. }
  272. } else {
  273. task.Status = jobRes.JobStatus.State
  274. taskRes := models.TaskPod{TaskStatuses: []models.TaskStatuses{
  275. {
  276. State: jobRes.JobStatus.State,
  277. },
  278. }}
  279. ctx.Data["taskRes"] = taskRes
  280. jobRes.JobStatus.StartTime = time.Unix(int64(task.CreatedUnix), 0).Format("2006-01-02 15:04:05")
  281. jobRes.JobStatus.EndTime = time.Unix(int64(task.UpdatedUnix), 0).Format("2006-01-02 15:04:05")
  282. }
  283. ctx.Data["result"] = jobRes
  284. }
  285. ctx.Data["task"] = task
  286. ctx.Data["jobID"] = jobID
  287. ctx.HTML(200, tplCloudBrainShow)
  288. }
  289. func CloudBrainDebug(ctx *context.Context) {
  290. var jobID = ctx.Params(":jobid")
  291. if !ctx.IsSigned {
  292. log.Error("the user has not signed in")
  293. ctx.Error(http.StatusForbidden, "", "the user has not signed in")
  294. return
  295. }
  296. task, err := models.GetCloudbrainByJobID(jobID)
  297. if err != nil {
  298. ctx.ServerError("GetCloudbrainByJobID failed", err)
  299. return
  300. }
  301. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  302. ctx.Redirect(debugUrl)
  303. }
  304. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  305. var jobID = ctx.Params(":jobid")
  306. if !ctx.IsSigned {
  307. log.Error("the user has not signed in")
  308. ctx.Error(http.StatusForbidden, "", "the user has not signed in")
  309. return
  310. }
  311. task, err := models.GetCloudbrainByJobID(jobID)
  312. if err != nil {
  313. ctx.JSON(200, map[string]string{
  314. "result_code": "-1",
  315. "error_msg": "GetCloudbrainByJobID failed",
  316. })
  317. return
  318. }
  319. err = cloudbrain.CommitImage(jobID, models.CommitImageParams{
  320. Ip: task.ContainerIp,
  321. TaskContainerId: task.ContainerID,
  322. ImageDescription: form.Description,
  323. ImageTag: form.Tag,
  324. })
  325. if err != nil {
  326. log.Error("CommitImage(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  327. ctx.JSON(200, map[string]string{
  328. "result_code": "-1",
  329. "error_msg": "CommitImage failed",
  330. })
  331. return
  332. }
  333. ctx.JSON(200, map[string]string{
  334. "result_code": "0",
  335. "error_msg": "",
  336. })
  337. }
  338. func CloudBrainStop(ctx *context.Context) {
  339. var jobID = ctx.Params(":jobid")
  340. task, err := models.GetCloudbrainByJobID(jobID)
  341. if err != nil {
  342. ctx.ServerError("GetCloudbrainByJobID failed", err)
  343. return
  344. }
  345. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) {
  346. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  347. ctx.ServerError("the job has been stopped", errors.New("the job has been stopped"))
  348. return
  349. }
  350. err = cloudbrain.StopJob(jobID)
  351. if err != nil {
  352. log.Error("StopJob(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  353. ctx.ServerError("StopJob failed", err)
  354. return
  355. }
  356. task.Status = string(models.JobStopped)
  357. err = models.UpdateJob(task)
  358. if err != nil {
  359. ctx.ServerError("UpdateJob failed", err)
  360. return
  361. }
  362. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  363. }
  364. func StopJobsByUserID(userID int64) {
  365. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  366. if err != nil {
  367. log.Warn("Failed to get cloudBrain info", err)
  368. return
  369. }
  370. StopJobs(cloudBrains)
  371. }
  372. func StopJobsByRepoID(repoID int64) {
  373. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  374. if err != nil {
  375. log.Warn("Failed to get cloudBrain info", err)
  376. return
  377. }
  378. StopJobs(cloudBrains)
  379. }
  380. /**
  381. */
  382. func StopJobs(cloudBrains []*models.Cloudbrain) {
  383. for _, taskInfo := range cloudBrains {
  384. if taskInfo.Type == models.TypeCloudBrainOne {
  385. err := retry(3, time.Second*30, func() error {
  386. return cloudbrain.StopJob(taskInfo.JobID)
  387. })
  388. logErrorAndUpdateJobStatus(err, taskInfo)
  389. } else {
  390. if taskInfo.JobType == string(models.JobTypeTrain) {
  391. err := retry(3, time.Second*30, func() error {
  392. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  393. return err
  394. })
  395. logErrorAndUpdateJobStatus(err, taskInfo)
  396. } else {
  397. param := models.NotebookAction{
  398. Action: models.ActionStop,
  399. }
  400. err := retry(3, time.Second*30, func() error {
  401. _, err := modelarts.StopJob(taskInfo.JobID, param)
  402. return err
  403. })
  404. logErrorAndUpdateJobStatus(err, taskInfo)
  405. }
  406. }
  407. }
  408. }
  409. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  410. for i := 0; i < attempts; i++ {
  411. if i > 0 {
  412. log.Warn("retrying after error:", err)
  413. time.Sleep(sleep)
  414. }
  415. err = f()
  416. if err == nil {
  417. return nil
  418. }
  419. }
  420. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  421. }
  422. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  423. if err != nil {
  424. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  425. } else {
  426. taskInfo.Status = string(models.JobStopped)
  427. err = models.UpdateJob(taskInfo)
  428. if err != nil {
  429. log.Warn("UpdateJob failed", err)
  430. }
  431. }
  432. }
  433. func CloudBrainDel(ctx *context.Context) {
  434. var jobID = ctx.Params(":jobid")
  435. task, err := models.GetCloudbrainByJobID(jobID)
  436. if err != nil {
  437. ctx.ServerError("GetCloudbrainByJobID failed", err)
  438. return
  439. }
  440. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) {
  441. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  442. ctx.ServerError("the job has not been stopped", errors.New("the job has not been stopped"))
  443. return
  444. }
  445. err = models.DeleteJob(task)
  446. if err != nil {
  447. ctx.ServerError("DeleteJob failed", err)
  448. return
  449. }
  450. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  451. }
  452. func CloudBrainShowModels(ctx *context.Context) {
  453. ctx.Data["PageIsCloudBrain"] = true
  454. jobID := ctx.Params(":jobid")
  455. parentDir := ctx.Query("parentDir")
  456. dirArray := strings.Split(parentDir, "/")
  457. task, err := models.GetCloudbrainByJobID(jobID)
  458. if err != nil {
  459. log.Error("no such job!", ctx.Data["msgID"])
  460. ctx.ServerError("no such job:", err)
  461. return
  462. }
  463. //get dirs
  464. dirs, err := GetModelDirs(task.JobName, parentDir)
  465. if err != nil {
  466. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  467. ctx.ServerError("GetModelDirs failed:", err)
  468. return
  469. }
  470. var fileInfos []storage.FileInfo
  471. err = json.Unmarshal([]byte(dirs), &fileInfos)
  472. if err != nil {
  473. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  474. ctx.ServerError("json.Unmarshal failed:", err)
  475. return
  476. }
  477. for i, fileInfo := range fileInfos {
  478. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  479. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  480. }
  481. sort.Slice(fileInfos, func(i, j int) bool {
  482. return fileInfos[i].ModTime > fileInfos[j].ModTime
  483. })
  484. ctx.Data["Path"] = dirArray
  485. ctx.Data["Dirs"] = fileInfos
  486. ctx.Data["task"] = task
  487. ctx.Data["JobID"] = jobID
  488. ctx.HTML(200, tplCloudBrainShowModels)
  489. }
  490. func GetPublicImages(ctx *context.Context) {
  491. getImages(ctx, cloudbrain.Public)
  492. }
  493. func GetCustomImages(ctx *context.Context) {
  494. getImages(ctx, cloudbrain.Custom)
  495. }
  496. func getImages(ctx *context.Context, imageType string) {
  497. log.Info("Get images begin")
  498. page := ctx.QueryInt("page")
  499. size := ctx.QueryInt("size")
  500. name := ctx.Query("name")
  501. getImagesResult, err := cloudbrain.GetImagesPageable(page, size, imageType, name)
  502. if err != nil {
  503. log.Error("Can not get images:%v", err)
  504. ctx.JSON(http.StatusOK, models.GetImagesPayload{
  505. Count: 0,
  506. TotalPages: 0,
  507. ImageInfo: []*models.ImageInfo{},
  508. })
  509. } else {
  510. ctx.JSON(http.StatusOK, getImagesResult.Payload)
  511. }
  512. log.Info("Get images end")
  513. }
  514. func GetModelDirs(jobName string, parentDir string) (string, error) {
  515. var req string
  516. modelActualPath := getMinioPath(jobName, cloudbrain.ModelMountPath + "/")
  517. if parentDir == "" {
  518. req = "baseDir=" + modelActualPath
  519. } else {
  520. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  521. }
  522. return getDirs(req)
  523. }
  524. func getMinioPath(jobName, suffixPath string) string {
  525. return setting.Attachment.Minio.RealPath + setting.Attachment.Minio.Bucket + "/" + setting.CBCodePathPrefix + jobName + suffixPath
  526. }
  527. func CloudBrainDownloadModel(ctx *context.Context) {
  528. parentDir := ctx.Query("parentDir")
  529. fileName := ctx.Query("fileName")
  530. jobName := ctx.Query("jobName")
  531. filePath := "jobs/" + jobName + "/model/" + parentDir
  532. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  533. if err != nil {
  534. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  535. ctx.ServerError("PresignedGetURL", err)
  536. return
  537. }
  538. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  539. }
  540. func GetRate(ctx *context.Context) {
  541. var jobID = ctx.Params(":jobid")
  542. job, err := models.GetCloudbrainByJobID(jobID)
  543. if err != nil {
  544. ctx.ServerError("GetCloudbrainByJobID failed", err)
  545. return
  546. }
  547. if job.JobType == string(models.JobTypeBenchmark) {
  548. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  549. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  550. ctx.Redirect(setting.Snn4imagenetServerHost)
  551. } else if job.JobType == string(models.JobTypeBrainScore) {
  552. ctx.Redirect(setting.BrainScoreServerHost)
  553. } else {
  554. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  555. }
  556. }
  557. func downloadCode(repo *models.Repository, codePath string) error {
  558. if err := git.Clone(repo.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  559. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  560. return err
  561. }
  562. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  563. if err != nil {
  564. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  565. return err
  566. }
  567. defer configFile.Close()
  568. pos := int64(0)
  569. reader := bufio.NewReader(configFile)
  570. for {
  571. line, err := reader.ReadString('\n')
  572. if err != nil {
  573. if err == io.EOF {
  574. log.Error("not find the remote-url")
  575. return nil
  576. } else {
  577. log.Error("read error: %v", err)
  578. return err
  579. }
  580. }
  581. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  582. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  583. if len(line) > len(originUrl) {
  584. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  585. }
  586. bytes := []byte(originUrl)
  587. _, err := configFile.WriteAt(bytes, pos)
  588. if err != nil {
  589. log.Error("WriteAt failed:%v", err)
  590. return err
  591. }
  592. break
  593. }
  594. pos += int64(len(line))
  595. }
  596. return nil
  597. }
  598. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType string) error {
  599. err := os.MkdirAll(codePath, os.ModePerm)
  600. if err != nil {
  601. log.Error("mkdir codePath failed", err.Error())
  602. return err
  603. }
  604. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  605. if err != nil {
  606. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  607. return err
  608. }
  609. if err := git.Clone(repoExt.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  610. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  611. return err
  612. }
  613. fileName := codePath + cloudbrain.TaskInfoName
  614. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  615. if err != nil {
  616. log.Error("OpenFile failed", err.Error())
  617. return err
  618. }
  619. defer f.Close()
  620. data, err := json.Marshal(models.TaskInfo{
  621. Username: repo.Owner.Name,
  622. TaskName: taskName,
  623. CodeName: repo.Name,
  624. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  625. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  626. GpuType: gpuType,
  627. })
  628. if err != nil {
  629. log.Error("json.Marshal failed", err.Error())
  630. return err
  631. }
  632. _, err = f.Write(data)
  633. if err != nil {
  634. log.Error("WriteString failed", err.Error())
  635. return err
  636. }
  637. return nil
  638. }
  639. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  640. files, err := readDir(codePath)
  641. if err != nil {
  642. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  643. return err
  644. }
  645. for _, file := range files {
  646. if file.IsDir() {
  647. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  648. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  649. return err
  650. }
  651. } else {
  652. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  653. sourceFile := codePath + file.Name()
  654. err = storage.Attachments.UploadObject(destObject, sourceFile)
  655. if err != nil {
  656. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  657. return err
  658. }
  659. }
  660. }
  661. return nil
  662. }
  663. func mkModelPath(modelPath string) error {
  664. err := os.MkdirAll(modelPath, os.ModePerm)
  665. if err != nil {
  666. log.Error("MkdirAll(%s) failed:%v", modelPath, err)
  667. return err
  668. }
  669. fileName := modelPath + "README"
  670. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  671. if err != nil {
  672. log.Error("OpenFile failed", err.Error())
  673. return err
  674. }
  675. defer f.Close()
  676. _, err = f.WriteString("You can put the model file into this directory and download it by the web page.")
  677. if err != nil {
  678. log.Error("WriteString failed", err.Error())
  679. return err
  680. }
  681. return nil
  682. }
  683. func SyncCloudbrainStatus() {
  684. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  685. if err != nil {
  686. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  687. return
  688. }
  689. for _, task := range cloudBrains {
  690. if task.Type == models.TypeCloudBrainOne {
  691. result, err := cloudbrain.GetJob(task.JobID)
  692. if err != nil {
  693. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  694. continue
  695. }
  696. if result != nil {
  697. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  698. taskRoles := jobRes.TaskRoles
  699. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  700. task.Status = taskRes.TaskStatuses[0].State
  701. if task.Status != string(models.JobWaiting) {
  702. err = models.UpdateJob(task)
  703. if err != nil {
  704. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  705. continue
  706. }
  707. }
  708. }
  709. } else if task.Type == models.TypeCloudBrainTwo {
  710. if task.JobType == string(models.JobTypeDebug) {
  711. result, err := modelarts.GetJob(task.JobID)
  712. if err != nil {
  713. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  714. continue
  715. }
  716. if result != nil {
  717. task.Status = result.Status
  718. err = models.UpdateJob(task)
  719. if err != nil {
  720. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  721. continue
  722. }
  723. }
  724. } else if task.JobType == string(models.JobTypeTrain) {
  725. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  726. if err != nil {
  727. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  728. continue
  729. }
  730. if result != nil {
  731. task.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  732. task.Duration = result.Duration
  733. task.TrainJobDuration = result.TrainJobDuration
  734. err = models.UpdateJob(task)
  735. if err != nil {
  736. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  737. continue
  738. }
  739. }
  740. } else {
  741. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  742. }
  743. } else {
  744. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  745. }
  746. }
  747. return
  748. }