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

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