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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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. res, err := modelarts.GetResourceSpecs()
  279. if err != nil {
  280. log.Error("GetResourceSpecs failed: %v", err)
  281. ctx.ServerError("GetResourceSpecs failed:", err)
  282. return
  283. }
  284. log.Info("", res.SpecTotalCount)
  285. ctx.HTML(200, tplModelArtsTrainJobNew)
  286. }
  287. func TrainJobCreate(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) {
  288. ctx.Data["PageIsCloudBrain"] = true
  289. jobName := form.JobName
  290. uuid := form.Attachment
  291. description := form.Description
  292. workServerNumber := form.WorkServerNumber
  293. engineID := form.EngineID
  294. bootFile := form.BootFile
  295. flavorCode := form.Flavor
  296. poolID := form.PoolID
  297. specID := form.SpecID
  298. repo := ctx.Repo.Repository
  299. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  300. codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath
  301. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath
  302. dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + "/"
  303. if err := git.Clone(repo.RepoPath(), codeLocalPath, git.CloneRepoOptions{}); err != nil {
  304. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  305. ctx.RenderWithErr("Failed to clone repository", tplModelArtsTrainJobNew, &form)
  306. return
  307. }
  308. //todo: upload code (send to file_server todo this work?)
  309. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath); err != nil {
  310. log.Error("Failed to obsMkdir: %s (%v)", repo.FullName(), err)
  311. ctx.RenderWithErr("Failed to obsMkdir", tplModelArtsTrainJobNew, &form)
  312. return
  313. }
  314. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  315. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  316. ctx.RenderWithErr("Failed to uploadCodeToObs", tplModelArtsTrainJobNew, &form)
  317. return
  318. }
  319. req := &modelarts.GenerateTrainJobReq{
  320. JobName: jobName,
  321. DataUrl: dataPath,
  322. Description: description,
  323. CodeObsPath: codeObsPath,
  324. BootFile: codeObsPath + bootFile,
  325. TrainUrl: outputObsPath,
  326. FlavorCode: flavorCode,
  327. PoolID: poolID,
  328. WorkServerNumber: workServerNumber,
  329. EngineID: int64(engineID),
  330. SpecID: int64(specID),
  331. }
  332. err := modelarts.GenerateTrainJob(ctx, req)
  333. if err != nil {
  334. log.Error("GenerateTrainJob failed:%v", err.Error())
  335. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobNew, &form)
  336. return
  337. }
  338. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  339. }
  340. // readDir reads the directory named by dirname and returns
  341. // a list of directory entries sorted by filename.
  342. func readDir(dirname string) ([]os.FileInfo, error) {
  343. f, err := os.Open(dirname)
  344. if err != nil {
  345. return nil, err
  346. }
  347. list, err := f.Readdir(100)
  348. f.Close()
  349. if err != nil {
  350. //todo: can not upload empty folder
  351. if err == io.EOF {
  352. return nil, nil
  353. }
  354. return nil, err
  355. }
  356. //sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() })
  357. return list, nil
  358. }
  359. func uploadCodeToObs(codePath, jobName, parentDir string) error {
  360. files, err := readDir(codePath)
  361. if err != nil {
  362. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  363. return err
  364. }
  365. for _, file := range files {
  366. if file.IsDir() {
  367. input := &obs.PutObjectInput{}
  368. input.Bucket = setting.Bucket
  369. input.Key = parentDir + file.Name() + "/"
  370. _, err = storage.ObsCli.PutObject(input)
  371. if err != nil {
  372. log.Error("PutObject(%s) failed: %s", input.Key, err.Error())
  373. return err
  374. }
  375. if err = uploadCodeToObs(codePath + file.Name() + "/", jobName, parentDir + file.Name() + "/"); err != nil {
  376. log.Error("uploadCodeToObs(%s) failed: %s", file.Name(), err.Error())
  377. return err
  378. }
  379. } else {
  380. input := &obs.PutFileInput{}
  381. input.Bucket = setting.Bucket
  382. input.Key = setting.CodePathPrefix + jobName + "/code/" + parentDir + file.Name()
  383. input.SourceFile = codePath + file.Name()
  384. _, err = storage.ObsCli.PutFile(input)
  385. if err != nil {
  386. log.Error("PutFile(%s) failed: %s", input.SourceFile, err.Error())
  387. return err
  388. }
  389. }
  390. }
  391. return nil
  392. }
  393. func obsMkdir(dir string) error {
  394. input := &obs.PutObjectInput{}
  395. input.Bucket = setting.Bucket
  396. input.Key = dir
  397. _, err := storage.ObsCli.PutObject(input)
  398. if err != nil {
  399. log.Error("PutObject(%s) failed: %s", input.Key, err.Error())
  400. return err
  401. }
  402. return nil
  403. }