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

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
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
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
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
3 years ago
4 years ago
4 years ago
4 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
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
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 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
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
3 years ago
4 years ago
4 years ago
4 years ago
3 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
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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  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/models"
  16. "code.gitea.io/gitea/modules/auth"
  17. "code.gitea.io/gitea/modules/base"
  18. "code.gitea.io/gitea/modules/cloudbrain"
  19. "code.gitea.io/gitea/modules/context"
  20. "code.gitea.io/gitea/modules/git"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/modelarts"
  23. "code.gitea.io/gitea/modules/setting"
  24. "code.gitea.io/gitea/modules/storage"
  25. "code.gitea.io/gitea/modules/util"
  26. )
  27. const (
  28. tplCloudBrainIndex base.TplName = "repo/cloudbrain/index"
  29. tplCloudBrainNew base.TplName = "repo/cloudbrain/new"
  30. tplCloudBrainShow base.TplName = "repo/cloudbrain/show"
  31. tplCloudBrainShowModels base.TplName = "repo/cloudbrain/models/index"
  32. )
  33. var (
  34. gpuInfos *models.GpuInfos
  35. categories *models.Categories
  36. )
  37. var jobNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-_]{1,34}[a-z0-9-]$`)
  38. // MustEnableDataset check if repository enable internal cb
  39. func MustEnableCloudbrain(ctx *context.Context) {
  40. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  41. ctx.NotFound("MustEnableCloudbrain", nil)
  42. return
  43. }
  44. }
  45. func cutString(str string, lens int) string {
  46. if len(str) < lens {
  47. return str
  48. }
  49. return str[:lens]
  50. }
  51. func jobNamePrefixValid(s string) string {
  52. lowStr := strings.ToLower(s)
  53. re := regexp.MustCompile(`[^a-z0-9_\\-]+`)
  54. removeSpecial := re.ReplaceAllString(lowStr, "")
  55. re = regexp.MustCompile(`^[_\\-]+`)
  56. return re.ReplaceAllString(removeSpecial, "")
  57. }
  58. func cloudBrainNewDataPrepare(ctx *context.Context) error {
  59. ctx.Data["PageIsCloudBrain"] = true
  60. t := time.Now()
  61. var jobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  62. ctx.Data["job_name"] = jobName
  63. result, err := cloudbrain.GetImages()
  64. if err != nil {
  65. ctx.Data["error"] = err.Error()
  66. log.Error("cloudbrain.GetImages failed:", err.Error(), ctx.Data["MsgID"])
  67. }
  68. for i, payload := range result.Payload.ImageInfo {
  69. if strings.HasPrefix(result.Payload.ImageInfo[i].Place, "192.168") {
  70. result.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  71. } else {
  72. result.Payload.ImageInfo[i].PlaceView = payload.Place
  73. }
  74. }
  75. ctx.Data["images"] = result.Payload.ImageInfo
  76. resultPublic, err := cloudbrain.GetPublicImages()
  77. if err != nil {
  78. ctx.Data["error"] = err.Error()
  79. log.Error("cloudbrain.GetPublicImages failed:", err.Error(), ctx.Data["MsgID"])
  80. }
  81. for i, payload := range resultPublic.Payload.ImageInfo {
  82. if strings.HasPrefix(resultPublic.Payload.ImageInfo[i].Place, "192.168") {
  83. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  84. } else {
  85. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place
  86. }
  87. }
  88. ctx.Data["public_images"] = resultPublic.Payload.ImageInfo
  89. attachs, err := models.GetAllUserAttachments(ctx.User.ID)
  90. if err != nil {
  91. log.Error("GetAllUserAttachments failed: %v", err, ctx.Data["MsgID"])
  92. return err
  93. }
  94. ctx.Data["attachments"] = attachs
  95. ctx.Data["command"] = cloudbrain.Command
  96. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  97. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  98. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  99. ctx.Data["benchmark_path"] = cloudbrain.BenchMarkMountPath
  100. ctx.Data["is_benchmark_enabled"] = setting.IsBenchmarkEnabled
  101. if categories == nil {
  102. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  103. }
  104. ctx.Data["benchmark_categories"] = categories.Category
  105. if gpuInfos == nil {
  106. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  107. }
  108. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  109. if cloudbrain.ResourceSpecs == nil {
  110. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  111. }
  112. ctx.Data["resource_specs"] = cloudbrain.ResourceSpecs.ResourceSpec
  113. ctx.Data["snn4imagenet_path"] = cloudbrain.Snn4imagenetMountPath
  114. ctx.Data["is_snn4imagenet_enabled"] = setting.IsSnn4imagenetEnabled
  115. ctx.Data["brainscore_path"] = cloudbrain.BrainScoreMountPath
  116. ctx.Data["is_brainscore_enabled"] = setting.IsBrainScoreEnabled
  117. return nil
  118. }
  119. func CloudBrainNew(ctx *context.Context) {
  120. err := cloudBrainNewDataPrepare(ctx)
  121. if err != nil {
  122. ctx.ServerError("get new cloudbrain info failed", err)
  123. return
  124. }
  125. ctx.HTML(200, tplCloudBrainNew)
  126. }
  127. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  128. ctx.Data["PageIsCloudBrain"] = true
  129. jobName := form.JobName
  130. image := form.Image
  131. command := form.Command
  132. uuid := form.Attachment
  133. jobType := form.JobType
  134. gpuQueue := form.GpuType
  135. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  136. resourceSpecId := form.ResourceSpecId
  137. if !jobNamePattern.MatchString(jobName) {
  138. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainNew, &form)
  139. return
  140. }
  141. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) && jobType != string(models.JobTypeSnn4imagenet) && jobType != string(models.JobTypeBrainScore) {
  142. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  143. cloudBrainNewDataPrepare(ctx)
  144. ctx.RenderWithErr("jobtype error", tplCloudBrainNew, &form)
  145. return
  146. }
  147. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID)
  148. if err != nil {
  149. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  150. cloudBrainNewDataPrepare(ctx)
  151. ctx.RenderWithErr("system error", tplCloudBrainNew, &form)
  152. return
  153. } else {
  154. if count >= 1 {
  155. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  156. cloudBrainNewDataPrepare(ctx)
  157. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplCloudBrainNew, &form)
  158. return
  159. }
  160. }
  161. _, err = models.GetCloudbrainByName(jobName)
  162. if err == nil {
  163. log.Error("the job name did already exist", ctx.Data["MsgID"])
  164. cloudBrainNewDataPrepare(ctx)
  165. ctx.RenderWithErr("the job name did already exist", tplCloudBrainNew, &form)
  166. return
  167. } else {
  168. if !models.IsErrJobNotExist(err) {
  169. log.Error("system error, %v", err, ctx.Data["MsgID"])
  170. cloudBrainNewDataPrepare(ctx)
  171. ctx.RenderWithErr("system error", tplCloudBrainNew, &form)
  172. return
  173. }
  174. }
  175. repo := ctx.Repo.Repository
  176. downloadCode(repo, codePath)
  177. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  178. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  179. mkModelPath(modelPath)
  180. uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/")
  181. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  182. if setting.IsBenchmarkEnabled && jobType == string(models.JobTypeBenchmark) {
  183. var gpuType string
  184. for _, gpuInfo := range gpuInfos.GpuInfo {
  185. if gpuInfo.Queue == gpuQueue {
  186. gpuType = gpuInfo.Value
  187. }
  188. }
  189. downloadRateCode(repo, jobName, setting.BenchmarkOwner, setting.BenchmarkName, benchmarkPath, form.BenchmarkCategory, gpuType)
  190. uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/")
  191. }
  192. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  193. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  194. downloadRateCode(repo, jobName, setting.Snn4imagenetOwner, setting.Snn4imagenetName, snn4imagenetPath, "", "")
  195. uploadCodeToMinio(snn4imagenetPath+"/", jobName, cloudbrain.Snn4imagenetMountPath+"/")
  196. }
  197. brainScorePath := setting.JobPath + jobName + cloudbrain.BrainScoreMountPath
  198. if setting.IsBrainScoreEnabled && jobType == string(models.JobTypeBrainScore) {
  199. downloadRateCode(repo, jobName, setting.BrainScoreOwner, setting.BrainScoreName, brainScorePath, "", "")
  200. uploadCodeToMinio(brainScorePath+"/", jobName, cloudbrain.BrainScoreMountPath+"/")
  201. }
  202. err = cloudbrain.GenerateTask(ctx, jobName, image, command, uuid, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  203. storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  204. storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  205. storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), jobType, gpuQueue, resourceSpecId)
  206. if err != nil {
  207. cloudBrainNewDataPrepare(ctx)
  208. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  209. return
  210. }
  211. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  212. }
  213. func CloudBrainRestart(ctx *context.Context) {
  214. var jobID = ctx.Params(":jobid")
  215. var resultCode = "0"
  216. var errorMsg = ""
  217. var status = string(models.JobWaiting)
  218. task := ctx.Cloudbrain
  219. for {
  220. if task.Status != string(models.JobStopped) && task.Status != string(models.JobSucceeded) && task.Status != string(models.JobFailed) {
  221. log.Error("the job(%s) is not stopped", task.JobName, ctx.Data["MsgID"])
  222. resultCode = "-1"
  223. errorMsg = "the job is not stopped"
  224. break
  225. }
  226. if task.Image == "" || task.GpuQueue == "" || task.Type != models.TypeCloudBrainOne {
  227. log.Error("the job(%s) version is too old", task.JobName, ctx.Data["MsgID"])
  228. resultCode = "-1"
  229. errorMsg = "the job's version is too old and can not be restarted"
  230. break
  231. }
  232. if !ctx.IsSigned || (ctx.User.ID != task.UserID && !ctx.IsUserSiteAdmin()) {
  233. log.Error("the user has no right ro restart the job", task.JobName, ctx.Data["MsgID"])
  234. resultCode = "-1"
  235. errorMsg = "you have no right to restart the job"
  236. break
  237. }
  238. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID)
  239. if err != nil {
  240. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  241. resultCode = "-1"
  242. errorMsg = "system error"
  243. break
  244. } else {
  245. if count >= 1 {
  246. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  247. resultCode = "-1"
  248. errorMsg = "you have already a running or waiting task, can not create more"
  249. break
  250. }
  251. }
  252. err = cloudbrain.RestartTask(ctx, task, &jobID)
  253. if err != nil {
  254. log.Error("RestartTask failed:%v", err.Error(), ctx.Data["MsgID"])
  255. resultCode = "-1"
  256. errorMsg = "system error"
  257. break
  258. }
  259. break
  260. }
  261. ctx.JSON(200, map[string]string{
  262. "result_code": resultCode,
  263. "error_msg": errorMsg,
  264. "status": status,
  265. "job_id": jobID,
  266. })
  267. }
  268. func CloudBrainShow(ctx *context.Context) {
  269. ctx.Data["PageIsCloudBrain"] = true
  270. var jobID = ctx.Params(":jobid")
  271. task, err := models.GetCloudbrainByJobID(jobID)
  272. if err != nil {
  273. ctx.Data["error"] = err.Error()
  274. }
  275. result, err := cloudbrain.GetJob(jobID)
  276. if err != nil {
  277. ctx.Data["error"] = err.Error()
  278. }
  279. if result != nil {
  280. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  281. jobRes.Resource.Memory = strings.ReplaceAll(jobRes.Resource.Memory, "Mi", "MB")
  282. taskRoles := jobRes.TaskRoles
  283. if jobRes.JobStatus.State != string(models.JobFailed) {
  284. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  285. ctx.Data["taskRes"] = taskRes
  286. task.Status = taskRes.TaskStatuses[0].State
  287. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  288. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  289. err = models.UpdateJob(task)
  290. if err != nil {
  291. ctx.Data["error"] = err.Error()
  292. }
  293. } else {
  294. task.Status = jobRes.JobStatus.State
  295. taskRes := models.TaskPod{TaskStatuses: []models.TaskStatuses{
  296. {
  297. State: jobRes.JobStatus.State,
  298. },
  299. }}
  300. ctx.Data["taskRes"] = taskRes
  301. jobRes.JobStatus.StartTime = time.Unix(int64(task.CreatedUnix), 0).Format("2006-01-02 15:04:05")
  302. jobRes.JobStatus.EndTime = time.Unix(int64(task.UpdatedUnix), 0).Format("2006-01-02 15:04:05")
  303. }
  304. ctx.Data["result"] = jobRes
  305. }
  306. ctx.Data["task"] = task
  307. ctx.Data["jobID"] = jobID
  308. ctx.HTML(200, tplCloudBrainShow)
  309. }
  310. func CloudBrainDebug(ctx *context.Context) {
  311. debugUrl := setting.DebugServerHost + "jpylab_" + ctx.Cloudbrain.JobID + "_" + ctx.Cloudbrain.SubTaskName
  312. ctx.Redirect(debugUrl)
  313. }
  314. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  315. err := cloudbrain.CommitImage(ctx.Cloudbrain.JobID, models.CommitImageParams{
  316. Ip: ctx.Cloudbrain.ContainerIp,
  317. TaskContainerId: ctx.Cloudbrain.ContainerID,
  318. ImageDescription: form.Description,
  319. ImageTag: form.Tag,
  320. })
  321. if err != nil {
  322. log.Error("CommitImage(%s) failed:%v", ctx.Cloudbrain.JobName, err.Error(), ctx.Data["msgID"])
  323. ctx.JSON(200, map[string]string{
  324. "result_code": "-1",
  325. "error_msg": "CommitImage failed",
  326. })
  327. return
  328. }
  329. ctx.JSON(200, map[string]string{
  330. "result_code": "0",
  331. "error_msg": "",
  332. })
  333. }
  334. func CloudBrainStop(ctx *context.Context) {
  335. var jobID = ctx.Params(":jobid")
  336. var resultCode = "0"
  337. var errorMsg = ""
  338. var status = ""
  339. task := ctx.Cloudbrain
  340. for {
  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. resultCode = "-1"
  344. errorMsg = "system error"
  345. break
  346. }
  347. err := cloudbrain.StopJob(jobID)
  348. if err != nil {
  349. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  350. resultCode = "-1"
  351. errorMsg = "system error"
  352. break
  353. }
  354. task.Status = string(models.JobStopped)
  355. err = models.UpdateJob(task)
  356. if err != nil {
  357. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  358. resultCode = "-1"
  359. errorMsg = "system error"
  360. break
  361. }
  362. status = task.Status
  363. break
  364. }
  365. ctx.JSON(200, map[string]string{
  366. "result_code": resultCode,
  367. "error_msg": errorMsg,
  368. "status": status,
  369. "job_id": jobID,
  370. })
  371. }
  372. func StopJobsByUserID(userID int64) {
  373. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  374. if err != nil {
  375. log.Warn("Failed to get cloudBrain info", err)
  376. return
  377. }
  378. StopJobs(cloudBrains)
  379. }
  380. func StopJobsByRepoID(repoID int64) {
  381. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  382. if err != nil {
  383. log.Warn("Failed to get cloudBrain info", err)
  384. return
  385. }
  386. StopJobs(cloudBrains)
  387. }
  388. /**
  389. */
  390. func StopJobs(cloudBrains []*models.Cloudbrain) {
  391. for _, taskInfo := range cloudBrains {
  392. if taskInfo.Type == models.TypeCloudBrainOne {
  393. err := retry(3, time.Second*30, func() error {
  394. return cloudbrain.StopJob(taskInfo.JobID)
  395. })
  396. logErrorAndUpdateJobStatus(err, taskInfo)
  397. } else {
  398. if taskInfo.JobType == string(models.JobTypeTrain) {
  399. err := retry(3, time.Second*30, func() error {
  400. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  401. return err
  402. })
  403. logErrorAndUpdateJobStatus(err, taskInfo)
  404. } else {
  405. param := models.NotebookAction{
  406. Action: models.ActionStop,
  407. }
  408. err := retry(3, time.Second*30, func() error {
  409. _, err := modelarts.ManageNotebook(taskInfo.JobID, param)
  410. return err
  411. })
  412. logErrorAndUpdateJobStatus(err, taskInfo)
  413. }
  414. }
  415. }
  416. }
  417. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  418. for i := 0; i < attempts; i++ {
  419. if i > 0 {
  420. log.Warn("retrying after error:", err)
  421. time.Sleep(sleep)
  422. }
  423. err = f()
  424. if err == nil {
  425. return nil
  426. }
  427. }
  428. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  429. }
  430. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  431. if err != nil {
  432. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  433. } else {
  434. taskInfo.Status = string(models.JobStopped)
  435. err = models.UpdateJob(taskInfo)
  436. if err != nil {
  437. log.Warn("UpdateJob failed", err)
  438. }
  439. }
  440. }
  441. func CloudBrainDel(ctx *context.Context) {
  442. task := ctx.Cloudbrain
  443. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) {
  444. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  445. ctx.ServerError("the job has not been stopped", errors.New("the job has not been stopped"))
  446. return
  447. }
  448. err := models.DeleteJob(task)
  449. if err != nil {
  450. ctx.ServerError("DeleteJob failed", err)
  451. return
  452. }
  453. deleteJobStorage(task.JobName, models.TypeCloudBrainOne)
  454. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  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 deleteJobStorage(jobName string, cloudbrainType int) error {
  685. //delete local
  686. localJobPath := setting.JobPath + jobName
  687. err := os.RemoveAll(localJobPath)
  688. if err != nil {
  689. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  690. }
  691. //delete oss
  692. if cloudbrainType == models.TypeCloudBrainOne {
  693. dirPath := setting.CBCodePathPrefix + jobName + "/"
  694. err = storage.Attachments.DeleteDir(dirPath)
  695. if err != nil {
  696. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  697. }
  698. } else if cloudbrainType == models.TypeCloudBrainTwo {
  699. //dirPath := setting.CodePathPrefix + jobName + "/"
  700. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  701. //if err != nil {
  702. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  703. //}
  704. log.Info("no need to delete")
  705. } else {
  706. log.Error("cloudbrainType(%d) error", cloudbrainType)
  707. }
  708. return nil
  709. }
  710. func SyncCloudbrainStatus() {
  711. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  712. if err != nil {
  713. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  714. return
  715. }
  716. for _, task := range cloudBrains {
  717. if task.Type == models.TypeCloudBrainOne {
  718. result, err := cloudbrain.GetJob(task.JobID)
  719. if err != nil {
  720. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  721. continue
  722. }
  723. if result != nil {
  724. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  725. taskRoles := jobRes.TaskRoles
  726. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  727. task.Status = taskRes.TaskStatuses[0].State
  728. if task.Status != string(models.JobWaiting) {
  729. task.Duration = time.Now().Unix() - taskRes.TaskStatuses[0].StartAt.Unix()
  730. err = models.UpdateJob(task)
  731. if err != nil {
  732. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  733. }
  734. if task.Duration >= setting.MaxDuration {
  735. log.Info("begin to stop job(%s), because of the duration", task.JobName)
  736. err = cloudbrain.StopJob(task.JobID)
  737. if err != nil {
  738. log.Error("StopJob(%s) failed:%v", task.JobName, err)
  739. continue
  740. }
  741. task.Status = string(models.JobStopped)
  742. err = models.UpdateJob(task)
  743. if err != nil {
  744. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  745. }
  746. }
  747. }
  748. }
  749. } else if task.Type == models.TypeCloudBrainTwo {
  750. if task.JobType == string(models.JobTypeDebug) {
  751. result, err := modelarts.GetJob(task.JobID)
  752. if err != nil {
  753. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  754. continue
  755. }
  756. if result != nil {
  757. task.Status = result.Status
  758. err = models.UpdateJob(task)
  759. if err != nil {
  760. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  761. continue
  762. }
  763. }
  764. } else if task.JobType == string(models.JobTypeTrain) {
  765. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  766. if err != nil {
  767. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  768. continue
  769. }
  770. if result != nil {
  771. task.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  772. task.Duration = result.Duration
  773. task.TrainJobDuration = result.TrainJobDuration
  774. if result.Duration != 0 {
  775. task.TrainJobDuration = util.AddZero(result.Duration/3600000) + ":" + util.AddZero(result.Duration%3600000/60000) + ":" + util.AddZero(result.Duration%60000/1000)
  776. } else {
  777. task.TrainJobDuration = "00:00:00"
  778. }
  779. err = models.UpdateJob(task)
  780. if err != nil {
  781. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  782. continue
  783. }
  784. }
  785. } else {
  786. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  787. }
  788. } else {
  789. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  790. }
  791. }
  792. return
  793. }