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