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