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.

modelarts.go 11 kB

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
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
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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. package repo
  2. import (
  3. "code.gitea.io/gitea/modules/git"
  4. "code.gitea.io/gitea/modules/modelarts"
  5. "code.gitea.io/gitea/modules/obs"
  6. "code.gitea.io/gitea/modules/storage"
  7. "errors"
  8. "github.com/unknwon/com"
  9. "io"
  10. "os"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/auth"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/context"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/setting"
  20. )
  21. const (
  22. tplModelArtsNotebookIndex base.TplName = "repo/modelarts/notebook/index"
  23. tplModelArtsNotebookNew base.TplName = "repo/modelarts/notebook/new"
  24. tplModelArtsNotebookShow base.TplName = "repo/modelarts/notebook/show"
  25. tplModelArtsTrainJobIndex base.TplName = "repo/modelarts/trainjob/index"
  26. tplModelArtsTrainJobNew base.TplName = "repo/modelarts/trainjob/new"
  27. tplModelArtsTrainJobShow base.TplName = "repo/modelarts/trainjob/show"
  28. )
  29. // MustEnableDataset check if repository enable internal cb
  30. func MustEnableModelArts(ctx *context.Context) {
  31. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  32. ctx.NotFound("MustEnableCloudbrain", nil)
  33. return
  34. }
  35. }
  36. func NotebookIndex(ctx *context.Context) {
  37. MustEnableModelArts(ctx)
  38. repo := ctx.Repo.Repository
  39. page := ctx.QueryInt("page")
  40. if page <= 0 {
  41. page = 1
  42. }
  43. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  44. ListOptions: models.ListOptions{
  45. Page: page,
  46. PageSize: setting.UI.IssuePagingNum,
  47. },
  48. RepoID: repo.ID,
  49. Type: models.TypeCloudBrainNotebook,
  50. })
  51. if err != nil {
  52. ctx.ServerError("Cloudbrain", err)
  53. return
  54. }
  55. for i, task := range ciTasks {
  56. if task.Status == string(models.JobRunning) {
  57. ciTasks[i].CanDebug = true
  58. } else {
  59. ciTasks[i].CanDebug = false
  60. }
  61. }
  62. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  63. pager.SetDefaultParams(ctx)
  64. ctx.Data["Page"] = pager
  65. ctx.Data["PageIsCloudBrain"] = true
  66. ctx.Data["Tasks"] = ciTasks
  67. ctx.HTML(200, tplModelArtsNotebookIndex)
  68. }
  69. func NotebookNew(ctx *context.Context) {
  70. ctx.Data["PageIsCloudBrain"] = true
  71. t := time.Now()
  72. var jobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  73. ctx.Data["job_name"] = jobName
  74. attachs, err := models.GetModelArtsUserAttachments(ctx.User.ID)
  75. if err != nil {
  76. ctx.ServerError("GetAllUserAttachments failed:", err)
  77. return
  78. }
  79. ctx.Data["attachments"] = attachs
  80. ctx.Data["dataset_path"] = modelarts.DataSetMountPath
  81. ctx.Data["env"] = modelarts.NotebookEnv
  82. ctx.Data["notebook_type"] = modelarts.NotebookType
  83. ctx.Data["flavor"] = modelarts.FlavorInfo
  84. ctx.HTML(200, tplModelArtsNotebookNew)
  85. }
  86. func NotebookCreate(ctx *context.Context, form auth.CreateModelArtsNotebookForm) {
  87. ctx.Data["PageIsCloudBrain"] = true
  88. jobName := form.JobName
  89. uuid := form.Attachment
  90. description := form.Description
  91. err := modelarts.GenerateTask(ctx, jobName, uuid, description)
  92. if err != nil {
  93. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookNew, &form)
  94. return
  95. }
  96. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/notebook")
  97. }
  98. func NotebookShow(ctx *context.Context) {
  99. ctx.Data["PageIsCloudBrain"] = true
  100. var jobID = ctx.Params(":jobid")
  101. task, err := models.GetCloudbrainByJobID(jobID)
  102. if err != nil {
  103. ctx.Data["error"] = err.Error()
  104. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  105. return
  106. }
  107. result, err := modelarts.GetJob(jobID)
  108. if err != nil {
  109. ctx.Data["error"] = err.Error()
  110. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  111. return
  112. }
  113. if result != nil {
  114. task.Status = result.Status
  115. err = models.UpdateJob(task)
  116. if err != nil {
  117. ctx.Data["error"] = err.Error()
  118. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  119. return
  120. }
  121. createTime, _ := com.StrTo(result.CreationTimestamp).Int64()
  122. result.CreateTime = time.Unix(int64(createTime/1000), 0).Format("2006-01-02 15:04:05")
  123. endTime, _ := com.StrTo(result.LatestUpdateTimestamp).Int64()
  124. result.LatestUpdateTime = time.Unix(int64(endTime/1000), 0).Format("2006-01-02 15:04:05")
  125. result.QueuingInfo.BeginTime = time.Unix(int64(result.QueuingInfo.BeginTimestamp/1000), 0).Format("2006-01-02 15:04:05")
  126. result.QueuingInfo.EndTime = time.Unix(int64(result.QueuingInfo.EndTimestamp/1000), 0).Format("2006-01-02 15:04:05")
  127. }
  128. ctx.Data["task"] = task
  129. ctx.Data["jobID"] = jobID
  130. ctx.Data["result"] = result
  131. ctx.HTML(200, tplModelArtsNotebookShow)
  132. }
  133. func NotebookDebug(ctx *context.Context) {
  134. var jobID = ctx.Params(":jobid")
  135. _, err := models.GetCloudbrainByJobID(jobID)
  136. if err != nil {
  137. ctx.ServerError("GetCloudbrainByJobID failed", err)
  138. return
  139. }
  140. result, err := modelarts.GetJob(jobID)
  141. if err != nil {
  142. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  143. return
  144. }
  145. res, err := modelarts.GetJobToken(jobID)
  146. if err != nil {
  147. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  148. return
  149. }
  150. urls := strings.Split(result.Spec.Annotations.Url, "/")
  151. urlPrefix := result.Spec.Annotations.TargetDomain
  152. for i, url := range urls {
  153. if i > 2 {
  154. urlPrefix += "/" + url
  155. }
  156. }
  157. debugUrl := urlPrefix + "?token=" + res.Token
  158. ctx.Redirect(debugUrl)
  159. }
  160. func NotebookStop(ctx *context.Context) {
  161. var jobID = ctx.Params(":jobid")
  162. log.Info(jobID)
  163. task, err := models.GetCloudbrainByJobID(jobID)
  164. if err != nil {
  165. ctx.ServerError("GetCloudbrainByJobID failed", err)
  166. return
  167. }
  168. if task.Status != string(models.JobRunning) {
  169. log.Error("the job(%s) is not running", task.JobName)
  170. ctx.ServerError("the job is not running", errors.New("the job is not running"))
  171. return
  172. }
  173. param := models.NotebookAction{
  174. Action: models.ActionStop,
  175. }
  176. res, err := modelarts.StopJob(jobID, param)
  177. if err != nil {
  178. log.Error("StopJob(%s) failed:%v", task.JobName, err.Error())
  179. ctx.ServerError("StopJob failed", err)
  180. return
  181. }
  182. task.Status = res.CurrentStatus
  183. err = models.UpdateJob(task)
  184. if err != nil {
  185. ctx.ServerError("UpdateJob failed", err)
  186. return
  187. }
  188. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/notebook")
  189. }
  190. func NotebookDel(ctx *context.Context) {
  191. var jobID = ctx.Params(":jobid")
  192. task, err := models.GetCloudbrainByJobID(jobID)
  193. if err != nil {
  194. ctx.ServerError("GetCloudbrainByJobID failed", err)
  195. return
  196. }
  197. if task.Status != string(models.JobStopped) {
  198. log.Error("the job(%s) has not been stopped", task.JobName)
  199. ctx.ServerError("the job has not been stopped", errors.New("the job has not been stopped"))
  200. return
  201. }
  202. _, err = modelarts.DelJob(jobID)
  203. if err != nil {
  204. log.Error("DelJob(%s) failed:%v", task.JobName, err.Error())
  205. ctx.ServerError("DelJob failed", err)
  206. return
  207. }
  208. err = models.DeleteJob(task)
  209. if err != nil {
  210. ctx.ServerError("DeleteJob failed", err)
  211. return
  212. }
  213. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/notebook")
  214. }
  215. func TrainJobIndex(ctx *context.Context) {
  216. MustEnableModelArts(ctx)
  217. repo := ctx.Repo.Repository
  218. page := ctx.QueryInt("page")
  219. if page <= 0 {
  220. page = 1
  221. }
  222. tasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  223. ListOptions: models.ListOptions{
  224. Page: page,
  225. PageSize: setting.UI.IssuePagingNum,
  226. },
  227. RepoID: repo.ID,
  228. Type: models.TypeCloudBrainTrainJob,
  229. })
  230. if err != nil {
  231. ctx.ServerError("Cloudbrain", err)
  232. return
  233. }
  234. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  235. pager.SetDefaultParams(ctx)
  236. ctx.Data["Page"] = pager
  237. ctx.Data["PageIsCloudBrain"] = true
  238. ctx.Data["Tasks"] = tasks
  239. ctx.HTML(200, tplModelArtsTrainJobIndex)
  240. }
  241. func TrainJobNew(ctx *context.Context) {
  242. ctx.Data["PageIsCloudBrain"] = true
  243. t := time.Now()
  244. var jobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  245. ctx.Data["job_name"] = jobName
  246. attachs, err := models.GetModelArtsUserAttachments(ctx.User.ID)
  247. if err != nil {
  248. ctx.ServerError("GetAllUserAttachments failed:", err)
  249. return
  250. }
  251. ctx.Data["attachments"] = attachs
  252. ctx.Data["dataset_path"] = modelarts.DataSetMountPath
  253. ctx.Data["env"] = modelarts.NotebookEnv
  254. ctx.Data["notebook_type"] = modelarts.NotebookType
  255. ctx.Data["flavor"] = modelarts.FlavorInfo
  256. ctx.HTML(200, tplModelArtsTrainJobNew)
  257. }
  258. func TrainJobCreate(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) {
  259. ctx.Data["PageIsCloudBrain"] = true
  260. jobName := form.JobName
  261. /*
  262. uuid := form.Attachment
  263. description := form.Description
  264. */
  265. repo := ctx.Repo.Repository
  266. codePath := setting.JobPath + jobName + modelarts.CodeLocalPath
  267. if err := git.Clone(repo.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  268. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  269. ctx.RenderWithErr("Failed to clone repository", tplModelArtsTrainJobNew, &form)
  270. return
  271. }
  272. //todo: upload code (send to file_server todo this work?)
  273. if err := uploadCodeToObs(codePath, jobName, ""); err != nil {
  274. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  275. ctx.RenderWithErr("Failed to uploadCodeToObs", tplModelArtsTrainJobNew, &form)
  276. return
  277. }
  278. /*
  279. err := modelarts.GenerateTask(ctx, jobName, uuid, description)
  280. if err != nil {
  281. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookNew, &form)
  282. return
  283. }
  284. */
  285. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  286. }
  287. // readDir reads the directory named by dirname and returns
  288. // a list of directory entries sorted by filename.
  289. func readDir(dirname string) ([]os.FileInfo, error) {
  290. f, err := os.Open(dirname)
  291. if err != nil {
  292. return nil, err
  293. }
  294. list, err := f.Readdir(100)
  295. f.Close()
  296. if err != nil {
  297. if err == io.EOF {
  298. return nil, nil
  299. }
  300. return nil, err
  301. }
  302. //sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() })
  303. return list, nil
  304. }
  305. func uploadCodeToObs(codePath, jobName, parentDir string) error {
  306. log.Info(codePath)
  307. files, err := readDir(codePath)
  308. if err != nil {
  309. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  310. return err
  311. }
  312. for _, file := range files {
  313. if file.IsDir() {
  314. input := &obs.PutObjectInput{}
  315. input.Bucket = setting.Bucket
  316. input.Key = codePath + file.Name() + "/"
  317. log.Info(input.Key)
  318. _, err = storage.ObsCli.PutObject(input)
  319. if err != nil {
  320. log.Error("PutObject(%s) failed: %s", input.Key, err.Error())
  321. return err
  322. }
  323. if err = uploadCodeToObs(codePath + file.Name() + "/", jobName, parentDir + file.Name() + "/"); err != nil {
  324. log.Error("uploadCodeToObs(%s) failed: %s", file.Name(), err.Error())
  325. return err
  326. }
  327. } else {
  328. input := &obs.PutFileInput{}
  329. input.Bucket = setting.Bucket
  330. input.Key = setting.CodePathPrefix + jobName + "/" + parentDir + file.Name()
  331. log.Info(input.Key)
  332. input.SourceFile = codePath + file.Name()
  333. log.Info(input.SourceFile)
  334. _, err = storage.ObsCli.PutFile(input)
  335. if err != nil {
  336. log.Error("PutFile(%s) failed: %s", input.SourceFile, err.Error())
  337. return err
  338. }
  339. }
  340. }
  341. return nil
  342. }