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