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