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
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 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
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 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
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 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
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
3 years ago
3 years ago
3 years ago
5 years ago
5 years ago
5 years ago
3 years ago
3 years ago
4 years ago
3 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
3 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
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
3 years ago
3 years ago
3 years ago
3 years ago
3 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
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
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
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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, cloudbrain.CodeMountPath+"/")
  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, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  202. storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  203. storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  204. storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), jobType, gpuQueue, resourceSpecId)
  205. if err != nil {
  206. cloudBrainNewDataPrepare(ctx)
  207. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  208. return
  209. }
  210. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob")
  211. }
  212. func CloudBrainRestart(ctx *context.Context) {
  213. ctx.Data["PageIsCloudBrain"] = true
  214. /*
  215. 1、查询job,判断status
  216. 2、利用查询出来的配置重新启动一个debug环境(使用相同的名称)
  217. 3、更新此任务的状态
  218. */
  219. /*
  220. todo: 是否启用事务?
  221. 启用:处理时间可能比较长,容易出现大事务
  222. 不启用:容易出现脏数据
  223. */
  224. var jobID = ctx.Params(":jobid")
  225. task, err := models.GetCloudbrainByJobID(jobID)
  226. if err != nil {
  227. log.Error("GetCloudbrainByJobID(%s) failed:%v", jobID, err.Error(), ctx.Data["MsgID"])
  228. ctx.RenderWithErr(err.Error(), tplDebugJobIndex, nil)
  229. return
  230. }
  231. if task.Status != string(models.JobStopped) && task.Status != string(models.JobSucceeded) && task.Status != string(models.JobFailed) {
  232. log.Error("the job(%s) is not stopped", task.JobName, ctx.Data["MsgID"])
  233. ctx.RenderWithErr("the job is not stopped", tplDebugJobIndex, nil)
  234. return
  235. }
  236. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID)
  237. if err != nil {
  238. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  239. ctx.RenderWithErr("system error", tplDebugJobIndex, nil)
  240. return
  241. } else {
  242. if count >= 1 {
  243. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  244. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplDebugJobIndex, nil)
  245. return
  246. }
  247. }
  248. err = cloudbrain.RestartTask(ctx, task)
  249. if err != nil {
  250. log.Error("RestartTask failed:%v", err.Error(), ctx.Data["MsgID"])
  251. ctx.RenderWithErr(err.Error(), tplDebugJobIndex, nil)
  252. return
  253. }
  254. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob")
  255. }
  256. func CloudBrainShow(ctx *context.Context) {
  257. ctx.Data["PageIsCloudBrain"] = true
  258. var jobID = ctx.Params(":jobid")
  259. task, err := models.GetCloudbrainByJobID(jobID)
  260. if err != nil {
  261. ctx.Data["error"] = err.Error()
  262. }
  263. result, err := cloudbrain.GetJob(jobID)
  264. if err != nil {
  265. ctx.Data["error"] = err.Error()
  266. }
  267. if result != nil {
  268. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  269. jobRes.Resource.Memory = strings.ReplaceAll(jobRes.Resource.Memory, "Mi", "MB")
  270. taskRoles := jobRes.TaskRoles
  271. if jobRes.JobStatus.State != string(models.JobFailed) {
  272. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  273. ctx.Data["taskRes"] = taskRes
  274. task.Status = taskRes.TaskStatuses[0].State
  275. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  276. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  277. err = models.UpdateJob(task)
  278. if err != nil {
  279. ctx.Data["error"] = err.Error()
  280. }
  281. } else {
  282. task.Status = jobRes.JobStatus.State
  283. taskRes := models.TaskPod{TaskStatuses: []models.TaskStatuses{
  284. {
  285. State: jobRes.JobStatus.State,
  286. },
  287. }}
  288. ctx.Data["taskRes"] = taskRes
  289. jobRes.JobStatus.StartTime = time.Unix(int64(task.CreatedUnix), 0).Format("2006-01-02 15:04:05")
  290. jobRes.JobStatus.EndTime = time.Unix(int64(task.UpdatedUnix), 0).Format("2006-01-02 15:04:05")
  291. }
  292. ctx.Data["result"] = jobRes
  293. }
  294. ctx.Data["task"] = task
  295. ctx.Data["jobID"] = jobID
  296. ctx.HTML(200, tplCloudBrainShow)
  297. }
  298. func CloudBrainDebug(ctx *context.Context) {
  299. var jobID = ctx.Params(":jobid")
  300. if !ctx.IsSigned {
  301. log.Error("the user has not signed in")
  302. ctx.Error(http.StatusForbidden, "", "the user has not signed in")
  303. return
  304. }
  305. task, err := models.GetCloudbrainByJobID(jobID)
  306. if err != nil {
  307. ctx.ServerError("GetCloudbrainByJobID failed", err)
  308. return
  309. }
  310. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  311. ctx.Redirect(debugUrl)
  312. }
  313. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  314. var jobID = ctx.Params(":jobid")
  315. if !ctx.IsSigned {
  316. log.Error("the user has not signed in")
  317. ctx.Error(http.StatusForbidden, "", "the user has not signed in")
  318. return
  319. }
  320. task, err := models.GetCloudbrainByJobID(jobID)
  321. if err != nil {
  322. ctx.JSON(200, map[string]string{
  323. "result_code": "-1",
  324. "error_msg": "GetCloudbrainByJobID failed",
  325. })
  326. return
  327. }
  328. err = cloudbrain.CommitImage(jobID, models.CommitImageParams{
  329. Ip: task.ContainerIp,
  330. TaskContainerId: task.ContainerID,
  331. ImageDescription: form.Description,
  332. ImageTag: form.Tag,
  333. })
  334. if err != nil {
  335. log.Error("CommitImage(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  336. ctx.JSON(200, map[string]string{
  337. "result_code": "-1",
  338. "error_msg": "CommitImage failed",
  339. })
  340. return
  341. }
  342. ctx.JSON(200, map[string]string{
  343. "result_code": "0",
  344. "error_msg": "",
  345. })
  346. }
  347. func CloudBrainStop(ctx *context.Context) {
  348. var jobID = ctx.Params(":jobid")
  349. task, err := models.GetCloudbrainByJobID(jobID)
  350. if err != nil {
  351. ctx.ServerError("GetCloudbrainByJobID failed", err)
  352. return
  353. }
  354. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) {
  355. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  356. ctx.ServerError("the job has been stopped", errors.New("the job has been stopped"))
  357. return
  358. }
  359. err = cloudbrain.StopJob(jobID)
  360. if err != nil {
  361. log.Error("StopJob(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  362. ctx.ServerError("StopJob failed", err)
  363. return
  364. }
  365. task.Status = string(models.JobStopped)
  366. err = models.UpdateJob(task)
  367. if err != nil {
  368. ctx.ServerError("UpdateJob failed", err)
  369. return
  370. }
  371. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob")
  372. }
  373. func StopJobsByUserID(userID int64) {
  374. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  375. if err != nil {
  376. log.Warn("Failed to get cloudBrain info", err)
  377. return
  378. }
  379. StopJobs(cloudBrains)
  380. }
  381. func StopJobsByRepoID(repoID int64) {
  382. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  383. if err != nil {
  384. log.Warn("Failed to get cloudBrain info", err)
  385. return
  386. }
  387. StopJobs(cloudBrains)
  388. }
  389. /**
  390. */
  391. func StopJobs(cloudBrains []*models.Cloudbrain) {
  392. for _, taskInfo := range cloudBrains {
  393. if taskInfo.Type == models.TypeCloudBrainOne {
  394. err := retry(3, time.Second*30, func() error {
  395. return cloudbrain.StopJob(taskInfo.JobID)
  396. })
  397. logErrorAndUpdateJobStatus(err, taskInfo)
  398. } else {
  399. if taskInfo.JobType == string(models.JobTypeTrain) {
  400. err := retry(3, time.Second*30, func() error {
  401. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  402. return err
  403. })
  404. logErrorAndUpdateJobStatus(err, taskInfo)
  405. } else {
  406. param := models.NotebookAction{
  407. Action: models.ActionStop,
  408. }
  409. err := retry(3, time.Second*30, func() error {
  410. _, err := modelarts.ManageNotebook(taskInfo.JobID, param)
  411. return err
  412. })
  413. logErrorAndUpdateJobStatus(err, taskInfo)
  414. }
  415. }
  416. }
  417. }
  418. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  419. for i := 0; i < attempts; i++ {
  420. if i > 0 {
  421. log.Warn("retrying after error:", err)
  422. time.Sleep(sleep)
  423. }
  424. err = f()
  425. if err == nil {
  426. return nil
  427. }
  428. }
  429. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  430. }
  431. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  432. if err != nil {
  433. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  434. } else {
  435. taskInfo.Status = string(models.JobStopped)
  436. err = models.UpdateJob(taskInfo)
  437. if err != nil {
  438. log.Warn("UpdateJob failed", err)
  439. }
  440. }
  441. }
  442. func CloudBrainDel(ctx *context.Context) {
  443. var jobID = ctx.Params(":jobid")
  444. task, err := models.GetCloudbrainByJobID(jobID)
  445. if err != nil {
  446. ctx.ServerError("GetCloudbrainByJobID failed", err)
  447. return
  448. }
  449. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) {
  450. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  451. ctx.ServerError("the job has not been stopped", errors.New("the job has not been stopped"))
  452. return
  453. }
  454. err = models.DeleteJob(task)
  455. if err != nil {
  456. ctx.ServerError("DeleteJob failed", err)
  457. return
  458. }
  459. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob")
  460. }
  461. func CloudBrainShowModels(ctx *context.Context) {
  462. ctx.Data["PageIsCloudBrain"] = true
  463. jobID := ctx.Params(":jobid")
  464. parentDir := ctx.Query("parentDir")
  465. dirArray := strings.Split(parentDir, "/")
  466. task, err := models.GetCloudbrainByJobID(jobID)
  467. if err != nil {
  468. log.Error("no such job!", ctx.Data["msgID"])
  469. ctx.ServerError("no such job:", err)
  470. return
  471. }
  472. //get dirs
  473. dirs, err := GetModelDirs(task.JobName, parentDir)
  474. if err != nil {
  475. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  476. ctx.ServerError("GetModelDirs failed:", err)
  477. return
  478. }
  479. var fileInfos []storage.FileInfo
  480. err = json.Unmarshal([]byte(dirs), &fileInfos)
  481. if err != nil {
  482. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  483. ctx.ServerError("json.Unmarshal failed:", err)
  484. return
  485. }
  486. for i, fileInfo := range fileInfos {
  487. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  488. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  489. }
  490. sort.Slice(fileInfos, func(i, j int) bool {
  491. return fileInfos[i].ModTime > fileInfos[j].ModTime
  492. })
  493. ctx.Data["Path"] = dirArray
  494. ctx.Data["Dirs"] = fileInfos
  495. ctx.Data["task"] = task
  496. ctx.Data["JobID"] = jobID
  497. ctx.HTML(200, tplCloudBrainShowModels)
  498. }
  499. func GetPublicImages(ctx *context.Context) {
  500. getImages(ctx, cloudbrain.Public)
  501. }
  502. func GetCustomImages(ctx *context.Context) {
  503. getImages(ctx, cloudbrain.Custom)
  504. }
  505. func getImages(ctx *context.Context, imageType string) {
  506. log.Info("Get images begin")
  507. page := ctx.QueryInt("page")
  508. size := ctx.QueryInt("size")
  509. name := ctx.Query("name")
  510. getImagesResult, err := cloudbrain.GetImagesPageable(page, size, imageType, name)
  511. if err != nil {
  512. log.Error("Can not get images:%v", err)
  513. ctx.JSON(http.StatusOK, models.GetImagesPayload{
  514. Count: 0,
  515. TotalPages: 0,
  516. ImageInfo: []*models.ImageInfo{},
  517. })
  518. } else {
  519. ctx.JSON(http.StatusOK, getImagesResult.Payload)
  520. }
  521. log.Info("Get images end")
  522. }
  523. func GetModelDirs(jobName string, parentDir string) (string, error) {
  524. var req string
  525. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  526. if parentDir == "" {
  527. req = "baseDir=" + modelActualPath
  528. } else {
  529. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  530. }
  531. return getDirs(req)
  532. }
  533. func CloudBrainDownloadModel(ctx *context.Context) {
  534. parentDir := ctx.Query("parentDir")
  535. fileName := ctx.Query("fileName")
  536. jobName := ctx.Query("jobName")
  537. filePath := "jobs/" + jobName + "/model/" + parentDir
  538. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  539. if err != nil {
  540. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  541. ctx.ServerError("PresignedGetURL", err)
  542. return
  543. }
  544. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  545. }
  546. func GetRate(ctx *context.Context) {
  547. var jobID = ctx.Params(":jobid")
  548. job, err := models.GetCloudbrainByJobID(jobID)
  549. if err != nil {
  550. ctx.ServerError("GetCloudbrainByJobID failed", err)
  551. return
  552. }
  553. if job.JobType == string(models.JobTypeBenchmark) {
  554. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  555. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  556. ctx.Redirect(setting.Snn4imagenetServerHost)
  557. } else if job.JobType == string(models.JobTypeBrainScore) {
  558. ctx.Redirect(setting.BrainScoreServerHost)
  559. } else {
  560. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  561. }
  562. }
  563. func downloadCode(repo *models.Repository, codePath string) error {
  564. if err := git.Clone(repo.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  565. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  566. return err
  567. }
  568. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  569. if err != nil {
  570. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  571. return err
  572. }
  573. defer configFile.Close()
  574. pos := int64(0)
  575. reader := bufio.NewReader(configFile)
  576. for {
  577. line, err := reader.ReadString('\n')
  578. if err != nil {
  579. if err == io.EOF {
  580. log.Error("not find the remote-url")
  581. return nil
  582. } else {
  583. log.Error("read error: %v", err)
  584. return err
  585. }
  586. }
  587. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  588. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  589. if len(line) > len(originUrl) {
  590. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  591. }
  592. bytes := []byte(originUrl)
  593. _, err := configFile.WriteAt(bytes, pos)
  594. if err != nil {
  595. log.Error("WriteAt failed:%v", err)
  596. return err
  597. }
  598. break
  599. }
  600. pos += int64(len(line))
  601. }
  602. return nil
  603. }
  604. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType string) error {
  605. err := os.MkdirAll(codePath, os.ModePerm)
  606. if err != nil {
  607. log.Error("mkdir codePath failed", err.Error())
  608. return err
  609. }
  610. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  611. if err != nil {
  612. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  613. return err
  614. }
  615. if err := git.Clone(repoExt.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  616. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  617. return err
  618. }
  619. fileName := codePath + cloudbrain.TaskInfoName
  620. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  621. if err != nil {
  622. log.Error("OpenFile failed", err.Error())
  623. return err
  624. }
  625. defer f.Close()
  626. data, err := json.Marshal(models.TaskInfo{
  627. Username: repo.Owner.Name,
  628. TaskName: taskName,
  629. CodeName: repo.Name,
  630. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  631. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  632. GpuType: gpuType,
  633. })
  634. if err != nil {
  635. log.Error("json.Marshal failed", err.Error())
  636. return err
  637. }
  638. _, err = f.Write(data)
  639. if err != nil {
  640. log.Error("WriteString failed", err.Error())
  641. return err
  642. }
  643. return nil
  644. }
  645. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  646. files, err := readDir(codePath)
  647. if err != nil {
  648. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  649. return err
  650. }
  651. for _, file := range files {
  652. if file.IsDir() {
  653. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  654. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  655. return err
  656. }
  657. } else {
  658. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  659. sourceFile := codePath + file.Name()
  660. err = storage.Attachments.UploadObject(destObject, sourceFile)
  661. if err != nil {
  662. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  663. return err
  664. }
  665. }
  666. }
  667. return nil
  668. }
  669. func mkModelPath(modelPath string) error {
  670. err := os.MkdirAll(modelPath, os.ModePerm)
  671. if err != nil {
  672. log.Error("MkdirAll(%s) failed:%v", modelPath, err)
  673. return err
  674. }
  675. fileName := modelPath + "README"
  676. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  677. if err != nil {
  678. log.Error("OpenFile failed", err.Error())
  679. return err
  680. }
  681. defer f.Close()
  682. _, err = f.WriteString("You can put the model file into this directory and download it by the web page.")
  683. if err != nil {
  684. log.Error("WriteString failed", err.Error())
  685. return err
  686. }
  687. return nil
  688. }
  689. func SyncCloudbrainStatus() {
  690. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  691. if err != nil {
  692. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  693. return
  694. }
  695. for _, task := range cloudBrains {
  696. if task.Type == models.TypeCloudBrainOne {
  697. result, err := cloudbrain.GetJob(task.JobID)
  698. if err != nil {
  699. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  700. continue
  701. }
  702. if result != nil {
  703. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  704. taskRoles := jobRes.TaskRoles
  705. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  706. task.Status = taskRes.TaskStatuses[0].State
  707. if task.Status != string(models.JobWaiting) {
  708. task.Duration = time.Now().Unix() - taskRes.TaskStatuses[0].StartAt.Unix()
  709. err = models.UpdateJob(task)
  710. if err != nil {
  711. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  712. }
  713. if task.Duration >= setting.MaxDuration {
  714. log.Info("begin to stop job(%s), because of the duration", task.JobName)
  715. err = cloudbrain.StopJob(task.JobID)
  716. if err != nil {
  717. log.Error("StopJob(%s) failed:%v", task.JobName, err)
  718. continue
  719. }
  720. task.Status = string(models.JobStopped)
  721. err = models.UpdateJob(task)
  722. if err != nil {
  723. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  724. }
  725. }
  726. }
  727. }
  728. } else if task.Type == models.TypeCloudBrainTwo {
  729. if task.JobType == string(models.JobTypeDebug) {
  730. result, err := modelarts.GetJob(task.JobID)
  731. if err != nil {
  732. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  733. continue
  734. }
  735. if result != nil {
  736. task.Status = result.Status
  737. err = models.UpdateJob(task)
  738. if err != nil {
  739. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  740. continue
  741. }
  742. }
  743. } else if task.JobType == string(models.JobTypeTrain) {
  744. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  745. if err != nil {
  746. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  747. continue
  748. }
  749. if result != nil {
  750. task.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  751. task.Duration = result.Duration
  752. task.TrainJobDuration = result.TrainJobDuration
  753. err = models.UpdateJob(task)
  754. if err != nil {
  755. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  756. continue
  757. }
  758. }
  759. } else {
  760. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  761. }
  762. } else {
  763. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  764. }
  765. }
  766. return
  767. }