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

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