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