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