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

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