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