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