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 23 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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  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. "fmt"
  10. "github.com/unknwon/com"
  11. "io"
  12. "net/http"
  13. "os"
  14. "path"
  15. "strconv"
  16. "strings"
  17. "time"
  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/context"
  22. "code.gitea.io/gitea/modules/log"
  23. "code.gitea.io/gitea/modules/setting"
  24. )
  25. const (
  26. tplModelArtsNotebookIndex base.TplName = "repo/modelarts/notebook/index"
  27. tplModelArtsNotebookNew base.TplName = "repo/modelarts/notebook/new"
  28. tplModelArtsNotebookShow base.TplName = "repo/modelarts/notebook/show"
  29. tplModelArtsTrainJobIndex base.TplName = "repo/modelarts/trainjob/index"
  30. tplModelArtsTrainJobNew base.TplName = "repo/modelarts/trainjob/new"
  31. tplModelArtsTrainJobShow base.TplName = "repo/modelarts/trainjob/show"
  32. )
  33. // MustEnableDataset check if repository enable internal cb
  34. func MustEnableModelArts(ctx *context.Context) {
  35. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  36. ctx.NotFound("MustEnableCloudbrain", nil)
  37. return
  38. }
  39. }
  40. func NotebookIndex(ctx *context.Context) {
  41. MustEnableModelArts(ctx)
  42. repo := ctx.Repo.Repository
  43. page := ctx.QueryInt("page")
  44. if page <= 0 {
  45. page = 1
  46. }
  47. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  48. ListOptions: models.ListOptions{
  49. Page: page,
  50. PageSize: setting.UI.IssuePagingNum,
  51. },
  52. RepoID: repo.ID,
  53. Type: models.TypeCloudBrainNotebook,
  54. })
  55. if err != nil {
  56. ctx.ServerError("Cloudbrain", err)
  57. return
  58. }
  59. for i, task := range ciTasks {
  60. if task.Status == string(models.JobRunning) {
  61. ciTasks[i].CanDebug = true
  62. } else {
  63. ciTasks[i].CanDebug = false
  64. }
  65. }
  66. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  67. pager.SetDefaultParams(ctx)
  68. ctx.Data["Page"] = pager
  69. ctx.Data["PageIsNotebook"] = true
  70. ctx.Data["Tasks"] = ciTasks
  71. ctx.HTML(200, tplModelArtsNotebookIndex)
  72. }
  73. func NotebookNew(ctx *context.Context) {
  74. ctx.Data["PageIsNotebook"] = true
  75. t := time.Now()
  76. var jobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  77. ctx.Data["job_name"] = jobName
  78. attachs, err := models.GetModelArtsUserAttachments(ctx.User.ID)
  79. if err != nil {
  80. ctx.ServerError("GetAllUserAttachments failed:", err)
  81. return
  82. }
  83. ctx.Data["attachments"] = attachs
  84. ctx.Data["dataset_path"] = modelarts.DataSetMountPath
  85. ctx.Data["env"] = modelarts.NotebookEnv
  86. ctx.Data["notebook_type"] = modelarts.NotebookType
  87. ctx.Data["flavor"] = modelarts.FlavorInfo
  88. ctx.HTML(200, tplModelArtsNotebookNew)
  89. }
  90. func NotebookCreate(ctx *context.Context, form auth.CreateModelArtsNotebookForm) {
  91. ctx.Data["PageIsNotebook"] = true
  92. jobName := form.JobName
  93. uuid := form.Attachment
  94. description := form.Description
  95. err := modelarts.GenerateTask(ctx, jobName, uuid, description)
  96. if err != nil {
  97. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookNew, &form)
  98. return
  99. }
  100. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/notebook")
  101. }
  102. func NotebookShow(ctx *context.Context) {
  103. ctx.Data["PageIsNotebook"] = true
  104. var jobID = ctx.Params(":jobid")
  105. task, err := models.GetCloudbrainByJobID(jobID)
  106. if err != nil {
  107. ctx.Data["error"] = err.Error()
  108. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  109. return
  110. }
  111. result, err := modelarts.GetJob(jobID)
  112. if err != nil {
  113. ctx.Data["error"] = err.Error()
  114. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  115. return
  116. }
  117. if result != nil {
  118. task.Status = result.Status
  119. err = models.UpdateJob(task)
  120. if err != nil {
  121. ctx.Data["error"] = err.Error()
  122. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  123. return
  124. }
  125. createTime, _ := com.StrTo(result.CreationTimestamp).Int64()
  126. result.CreateTime = time.Unix(int64(createTime/1000), 0).Format("2006-01-02 15:04:05")
  127. endTime, _ := com.StrTo(result.LatestUpdateTimestamp).Int64()
  128. result.LatestUpdateTime = time.Unix(int64(endTime/1000), 0).Format("2006-01-02 15:04:05")
  129. result.QueuingInfo.BeginTime = time.Unix(int64(result.QueuingInfo.BeginTimestamp/1000), 0).Format("2006-01-02 15:04:05")
  130. result.QueuingInfo.EndTime = time.Unix(int64(result.QueuingInfo.EndTimestamp/1000), 0).Format("2006-01-02 15:04:05")
  131. }
  132. ctx.Data["task"] = task
  133. ctx.Data["jobID"] = jobID
  134. ctx.Data["result"] = result
  135. ctx.HTML(200, tplModelArtsNotebookShow)
  136. }
  137. func NotebookDebug(ctx *context.Context) {
  138. var jobID = ctx.Params(":jobid")
  139. _, err := models.GetCloudbrainByJobID(jobID)
  140. if err != nil {
  141. ctx.ServerError("GetCloudbrainByJobID failed", err)
  142. return
  143. }
  144. result, err := modelarts.GetJob(jobID)
  145. if err != nil {
  146. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  147. return
  148. }
  149. res, err := modelarts.GetJobToken(jobID)
  150. if err != nil {
  151. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  152. return
  153. }
  154. urls := strings.Split(result.Spec.Annotations.Url, "/")
  155. urlPrefix := result.Spec.Annotations.TargetDomain
  156. for i, url := range urls {
  157. if i > 2 {
  158. urlPrefix += "/" + url
  159. }
  160. }
  161. debugUrl := urlPrefix + "?token=" + res.Token
  162. ctx.Redirect(debugUrl)
  163. }
  164. func NotebookStop(ctx *context.Context) {
  165. var jobID = ctx.Params(":jobid")
  166. log.Info(jobID)
  167. task, err := models.GetCloudbrainByJobID(jobID)
  168. if err != nil {
  169. ctx.ServerError("GetCloudbrainByJobID failed", err)
  170. return
  171. }
  172. if task.Status != string(models.JobRunning) {
  173. log.Error("the job(%s) is not running", task.JobName)
  174. ctx.ServerError("the job is not running", errors.New("the job is not running"))
  175. return
  176. }
  177. param := models.NotebookAction{
  178. Action: models.ActionStop,
  179. }
  180. res, err := modelarts.StopJob(jobID, param)
  181. if err != nil {
  182. log.Error("StopJob(%s) failed:%v", task.JobName, err.Error())
  183. ctx.ServerError("StopJob failed", err)
  184. return
  185. }
  186. task.Status = res.CurrentStatus
  187. err = models.UpdateJob(task)
  188. if err != nil {
  189. ctx.ServerError("UpdateJob failed", err)
  190. return
  191. }
  192. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/notebook")
  193. }
  194. func NotebookDel(ctx *context.Context) {
  195. var jobID = ctx.Params(":jobid")
  196. task, err := models.GetCloudbrainByJobID(jobID)
  197. if err != nil {
  198. ctx.ServerError("GetCloudbrainByJobID failed", err)
  199. return
  200. }
  201. if task.Status != string(models.JobStopped) {
  202. log.Error("the job(%s) has not been stopped", task.JobName)
  203. ctx.ServerError("the job has not been stopped", errors.New("the job has not been stopped"))
  204. return
  205. }
  206. _, err = modelarts.DelNotebook(jobID)
  207. if err != nil {
  208. log.Error("DelJob(%s) failed:%v", task.JobName, err.Error())
  209. ctx.ServerError("DelJob failed", err)
  210. return
  211. }
  212. err = models.DeleteJob(task)
  213. if err != nil {
  214. ctx.ServerError("DeleteJob failed", err)
  215. return
  216. }
  217. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/notebook")
  218. }
  219. func TrainJobIndex(ctx *context.Context) {
  220. MustEnableModelArts(ctx)
  221. can, err := canUserCreateTrainJob(ctx.User.ID)
  222. if err != nil {
  223. ctx.ServerError("canUserCreateTrainJob", err)
  224. return
  225. }
  226. ctx.Data["CanCreate"] = can
  227. repo := ctx.Repo.Repository
  228. page := ctx.QueryInt("page")
  229. if page <= 0 {
  230. page = 1
  231. }
  232. tasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  233. ListOptions: models.ListOptions{
  234. Page: page,
  235. PageSize: setting.UI.IssuePagingNum,
  236. },
  237. RepoID: repo.ID,
  238. Type: models.TypeCloudBrainTrainJob,
  239. })
  240. if err != nil {
  241. ctx.ServerError("Cloudbrain", err)
  242. return
  243. }
  244. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  245. pager.SetDefaultParams(ctx)
  246. ctx.Data["Page"] = pager
  247. ctx.Data["PageIsTrainJob"] = true
  248. ctx.Data["Tasks"] = tasks
  249. ctx.HTML(200, tplModelArtsTrainJobIndex)
  250. }
  251. func TrainJobNew(ctx *context.Context) {
  252. ctx.Data["PageIsTrainJob"] = true
  253. can, err := canUserCreateTrainJob(ctx.User.ID)
  254. if err != nil {
  255. ctx.ServerError("canUserCreateTrainJob", err)
  256. return
  257. }
  258. if !can {
  259. log.Error("the user can not create train-job")
  260. ctx.ServerError("the user can not create train-job", fmt.Errorf("the user can not create train-job"))
  261. return
  262. }
  263. t := time.Now()
  264. var jobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  265. ctx.Data["job_name"] = jobName
  266. attachs, err := models.GetModelArtsUserAttachments(ctx.User.ID)
  267. if err != nil {
  268. ctx.ServerError("GetAllUserAttachments failed:", err)
  269. return
  270. }
  271. ctx.Data["attachments"] = attachs
  272. var resourcePools modelarts.ResourcePool
  273. if err = json.Unmarshal([]byte(modelarts.ResourcePools), &resourcePools); err != nil {
  274. ctx.ServerError("json.Unmarshal failed:", err)
  275. return
  276. }
  277. ctx.Data["resource_pools"] = resourcePools.Info
  278. var engines modelarts.Engine
  279. if err = json.Unmarshal([]byte(modelarts.Engines), &engines); err != nil {
  280. ctx.ServerError("json.Unmarshal failed:", err)
  281. return
  282. }
  283. ctx.Data["engines"] = engines.Info
  284. var versionInfos modelarts.VersionInfo
  285. if err = json.Unmarshal([]byte(modelarts.EngineVersions), &versionInfos); err != nil {
  286. ctx.ServerError("json.Unmarshal failed:", err)
  287. return
  288. }
  289. ctx.Data["engine_versions"] = versionInfos.Version
  290. var flavorInfos modelarts.Flavor
  291. if err = json.Unmarshal([]byte(modelarts.FlavorInfos), &flavorInfos); err != nil {
  292. ctx.ServerError("json.Unmarshal failed:", err)
  293. return
  294. }
  295. ctx.Data["flavor_infos"] = flavorInfos.Info
  296. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath
  297. ctx.Data["train_url"] = outputObsPath
  298. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  299. if err != nil {
  300. ctx.ServerError("getConfigList failed:", err)
  301. return
  302. }
  303. ctx.Data["config_list"] = configList.ParaConfigs
  304. ctx.HTML(200, tplModelArtsTrainJobNew)
  305. }
  306. func TrainJobCreate(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) {
  307. ctx.Data["PageIsTrainJob"] = true
  308. jobName := form.JobName
  309. uuid := form.Attachment
  310. description := form.Description
  311. workServerNumber := form.WorkServerNumber
  312. engineID := form.EngineID
  313. bootFile := form.BootFile
  314. flavorCode := form.Flavor
  315. params := form.Params
  316. poolID := form.PoolID
  317. isSaveParam := form.IsSaveParam
  318. repo := ctx.Repo.Repository
  319. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  320. codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath
  321. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath
  322. logObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.LogPath
  323. dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + "/"
  324. can, err := canUserCreateTrainJob(ctx.User.ID)
  325. if err != nil {
  326. ctx.ServerError("canUserCreateTrainJob", err)
  327. return
  328. }
  329. if !can {
  330. log.Error("the user can not create train-job")
  331. ctx.RenderWithErr("the user can not create train-job", tplModelArtsTrainJobNew, &form)
  332. return
  333. }
  334. //param check
  335. if err := paramCheckCreateTrainJob(form); err != nil {
  336. log.Error("paramCheckCreateTrainJob failed:(%v)", err)
  337. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobNew, &form)
  338. return
  339. }
  340. if err := git.Clone(repo.RepoPath(), codeLocalPath, git.CloneRepoOptions{}); err != nil {
  341. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  342. ctx.RenderWithErr("Failed to clone repository", tplModelArtsTrainJobNew, &form)
  343. return
  344. }
  345. //todo: upload code (send to file_server todo this work?)
  346. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath); err != nil {
  347. log.Error("Failed to obsMkdir_output: %s (%v)", repo.FullName(), err)
  348. ctx.RenderWithErr("Failed to obsMkdir_output", tplModelArtsTrainJobNew, &form)
  349. return
  350. }
  351. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.LogPath); err != nil {
  352. log.Error("Failed to obsMkdir_log: %s (%v)", repo.FullName(), err)
  353. ctx.RenderWithErr("Failed to obsMkdir_log", tplModelArtsTrainJobNew, &form)
  354. return
  355. }
  356. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  357. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  358. ctx.RenderWithErr("Failed to uploadCodeToObs", tplModelArtsTrainJobNew, &form)
  359. return
  360. }
  361. //todo: del local code?
  362. var parameters models.Parameters
  363. param := make([]models.Parameter, 0)
  364. param = append(param, models.Parameter{
  365. Label: modelarts.TrainUrl,
  366. Value: outputObsPath,
  367. }, models.Parameter{
  368. Label: modelarts.DataUrl,
  369. Value: dataPath,
  370. })
  371. if len(params) != 0 {
  372. err := json.Unmarshal([]byte(params), &parameters)
  373. if err != nil {
  374. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  375. ctx.RenderWithErr("运行参数错误", tplModelArtsTrainJobNew, &form)
  376. return
  377. }
  378. for _, parameter := range parameters.Parameter {
  379. if parameter.Label != modelarts.TrainUrl && parameter.Label != modelarts.DataUrl {
  380. param = append(param, models.Parameter{
  381. Label: parameter.Label,
  382. Value: parameter.Value,
  383. })
  384. }
  385. }
  386. }
  387. //save param config
  388. if isSaveParam == "on" {
  389. if form.ParameterTemplateName == "" {
  390. log.Error("ParameterTemplateName is empty")
  391. ctx.RenderWithErr("保存作业参数时,作业参数名称不能为空", tplModelArtsTrainJobNew, &form)
  392. return
  393. }
  394. _, err := modelarts.CreateTrainJobConfig(models.CreateConfigParams{
  395. ConfigName: form.ParameterTemplateName,
  396. Description: form.PrameterDescription,
  397. DataUrl: dataPath,
  398. AppUrl: codeObsPath,
  399. BootFileUrl: codeObsPath + bootFile,
  400. TrainUrl: outputObsPath,
  401. Flavor: models.Flavor{
  402. Code: flavorCode,
  403. },
  404. WorkServerNum: workServerNumber,
  405. EngineID: int64(engineID),
  406. LogUrl: logObsPath,
  407. PoolID: poolID,
  408. Parameter: param,
  409. })
  410. if err != nil {
  411. log.Error("Failed to CreateTrainJobConfig: %v", err)
  412. ctx.RenderWithErr("保存作业参数失败:"+err.Error(), tplModelArtsTrainJobNew, &form)
  413. return
  414. }
  415. }
  416. req := &modelarts.GenerateTrainJobReq{
  417. JobName: jobName,
  418. DataUrl: dataPath,
  419. Description: description,
  420. CodeObsPath: codeObsPath,
  421. BootFile: codeObsPath + bootFile,
  422. TrainUrl: outputObsPath,
  423. FlavorCode: flavorCode,
  424. WorkServerNumber: workServerNumber,
  425. EngineID: int64(engineID),
  426. LogUrl: logObsPath,
  427. PoolID: poolID,
  428. Uuid: uuid,
  429. Parameters: param,
  430. }
  431. err = modelarts.GenerateTrainJob(ctx, req)
  432. if err != nil {
  433. log.Error("GenerateTrainJob failed:%v", err.Error())
  434. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobNew, &form)
  435. return
  436. }
  437. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  438. }
  439. // readDir reads the directory named by dirname and returns
  440. // a list of directory entries sorted by filename.
  441. func readDir(dirname string) ([]os.FileInfo, error) {
  442. f, err := os.Open(dirname)
  443. if err != nil {
  444. return nil, err
  445. }
  446. list, err := f.Readdir(100)
  447. f.Close()
  448. if err != nil {
  449. //todo: can not upload empty folder
  450. if err == io.EOF {
  451. return nil, nil
  452. }
  453. return nil, err
  454. }
  455. //sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() })
  456. return list, nil
  457. }
  458. func uploadCodeToObs(codePath, jobName, parentDir string) error {
  459. files, err := readDir(codePath)
  460. if err != nil {
  461. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  462. return err
  463. }
  464. for _, file := range files {
  465. if file.IsDir() {
  466. input := &obs.PutObjectInput{}
  467. input.Bucket = setting.Bucket
  468. input.Key = parentDir + file.Name() + "/"
  469. _, err = storage.ObsCli.PutObject(input)
  470. if err != nil {
  471. log.Error("PutObject(%s) failed: %s", input.Key, err.Error())
  472. return err
  473. }
  474. if err = uploadCodeToObs(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  475. log.Error("uploadCodeToObs(%s) failed: %s", file.Name(), err.Error())
  476. return err
  477. }
  478. } else {
  479. input := &obs.PutFileInput{}
  480. input.Bucket = setting.Bucket
  481. input.Key = setting.CodePathPrefix + jobName + "/code/" + parentDir + file.Name()
  482. input.SourceFile = codePath + file.Name()
  483. _, err = storage.ObsCli.PutFile(input)
  484. if err != nil {
  485. log.Error("PutFile(%s) failed: %s", input.SourceFile, err.Error())
  486. return err
  487. }
  488. }
  489. }
  490. return nil
  491. }
  492. func obsMkdir(dir string) error {
  493. input := &obs.PutObjectInput{}
  494. input.Bucket = setting.Bucket
  495. input.Key = dir
  496. _, err := storage.ObsCli.PutObject(input)
  497. if err != nil {
  498. log.Error("PutObject(%s) failed: %s", input.Key, err.Error())
  499. return err
  500. }
  501. return nil
  502. }
  503. func paramCheckCreateTrainJob(form auth.CreateModelArtsTrainJobForm) error {
  504. if !strings.HasSuffix(form.BootFile, ".py") {
  505. log.Error("the boot file(%s) must be a python file", form.BootFile)
  506. return errors.New("启动文件必须是python文件")
  507. }
  508. if form.WorkServerNumber > 25 || form.WorkServerNumber < 1 {
  509. log.Error("the WorkServerNumber(%d) must be in (1,25)", form.WorkServerNumber)
  510. return errors.New("计算节点数必须在1-25之间")
  511. }
  512. return nil
  513. }
  514. func TrainJobShow(ctx *context.Context) {
  515. ctx.Data["PageIsTrainJob"] = true
  516. var jobID = ctx.Params(":jobid")
  517. task, err := models.GetCloudbrainByJobID(jobID)
  518. if err != nil {
  519. log.Error("GetCloudbrainByJobID(%s) failed:%v", jobID, err.Error())
  520. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  521. return
  522. }
  523. attach, err := models.GetAttachmentByUUID(task.Uuid)
  524. if err != nil {
  525. log.Error("GetAttachmentByUUID(%s) failed:%v", jobID, err.Error())
  526. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  527. return
  528. }
  529. result, err := modelarts.GetTrainJob(jobID, strconv.FormatInt(task.VersionID, 10))
  530. if err != nil {
  531. log.Error("GetJob(%s) failed:%v", jobID, err.Error())
  532. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  533. return
  534. }
  535. if result != nil {
  536. result.CreateTime = time.Unix(int64(result.LongCreateTime/1000), 0).Format("2006-01-02 15:04:05")
  537. result.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  538. result.DatasetName = attach.Name
  539. }
  540. resultLogFile, resultLog, err := trainJobGetLog(jobID)
  541. if err != nil {
  542. log.Error("trainJobGetLog(%s) failed:%v", jobID, err.Error())
  543. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  544. return
  545. }
  546. ctx.Data["log_file_name"] = resultLogFile.LogFileList[0]
  547. ctx.Data["log"] = resultLog
  548. ctx.Data["task"] = task
  549. ctx.Data["jobID"] = jobID
  550. ctx.Data["result"] = result
  551. ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  552. }
  553. func TrainJobGetLog(ctx *context.Context) {
  554. ctx.Data["PageIsTrainJob"] = true
  555. var jobID = ctx.Params(":jobid")
  556. var logFileName = ctx.Query("file_name")
  557. var baseLine = ctx.Query("base_line")
  558. var order = ctx.Query("order")
  559. if order != modelarts.OrderDesc && order != modelarts.OrderAsc {
  560. log.Error("order(%s) check failed", order)
  561. ctx.HTML(http.StatusBadRequest, tplModelArtsTrainJobShow)
  562. return
  563. }
  564. task, err := models.GetCloudbrainByJobID(jobID)
  565. if err != nil {
  566. log.Error("GetCloudbrainByJobID(%s) failed:%v", jobID, err.Error())
  567. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  568. return
  569. }
  570. result, err := modelarts.GetTrainJobLog(jobID, strconv.FormatInt(task.VersionID, 10), baseLine, logFileName, order, modelarts.Lines)
  571. if err != nil {
  572. log.Error("GetTrainJobLog(%s) failed:%v", jobID, err.Error())
  573. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  574. return
  575. }
  576. ctx.Data["log"] = result
  577. //ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  578. }
  579. func trainJobGetLog(jobID string) (*models.GetTrainJobLogFileNamesResult, *models.GetTrainJobLogResult, error) {
  580. task, err := models.GetCloudbrainByJobID(jobID)
  581. if err != nil {
  582. log.Error("GetCloudbrainByJobID(%s) failed:%v", jobID, err.Error())
  583. return nil, nil, err
  584. }
  585. resultLogFile, err := modelarts.GetTrainJobLogFileNames(jobID, strconv.FormatInt(task.VersionID, 10))
  586. if err != nil {
  587. log.Error("GetTrainJobLogFileNames(%s) failed:%v", jobID, err.Error())
  588. return nil, nil, err
  589. }
  590. result, err := modelarts.GetTrainJobLog(jobID, strconv.FormatInt(task.VersionID, 10), "", resultLogFile.LogFileList[0], modelarts.OrderDesc, modelarts.Lines)
  591. if err != nil {
  592. log.Error("GetTrainJobLog(%s) failed:%v", jobID, err.Error())
  593. return nil, nil, err
  594. }
  595. return resultLogFile, result, err
  596. }
  597. func TrainJobDel(ctx *context.Context) {
  598. var jobID = ctx.Params(":jobid")
  599. task, err := models.GetCloudbrainByJobID(jobID)
  600. if err != nil {
  601. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  602. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  603. return
  604. }
  605. _, err = modelarts.DelTrainJob(jobID)
  606. if err != nil {
  607. log.Error("DelTrainJob(%s) failed:%v", task.JobName, err.Error())
  608. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  609. return
  610. }
  611. err = models.DeleteJob(task)
  612. if err != nil {
  613. ctx.ServerError("DeleteJob failed", err)
  614. return
  615. }
  616. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  617. }
  618. func TrainJobStop(ctx *context.Context) {
  619. var jobID = ctx.Params(":jobid")
  620. task, err := models.GetCloudbrainByJobID(jobID)
  621. if err != nil {
  622. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  623. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  624. return
  625. }
  626. _, err = modelarts.StopTrainJob(jobID, strconv.FormatInt(task.VersionID, 10))
  627. if err != nil {
  628. log.Error("StopTrainJob(%s) failed:%v", task.JobName, err.Error())
  629. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  630. return
  631. }
  632. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  633. }
  634. func canUserCreateTrainJob(uid int64) (bool, error) {
  635. org, err := models.GetOrgByName(setting.AllowedOrg)
  636. if err != nil {
  637. log.Error("get allowed org failed: ", setting.AllowedOrg)
  638. return false, err
  639. }
  640. return org.IsOrgMember(uid)
  641. }
  642. func TrainJobGetConfigList(ctx *context.Context) {
  643. ctx.Data["PageIsTrainJob"] = true
  644. var jobID = ctx.Params(":jobid")
  645. var logFileName = ctx.Query("file_name")
  646. var baseLine = ctx.Query("base_line")
  647. var order = ctx.Query("order")
  648. if order != modelarts.OrderDesc && order != modelarts.OrderAsc {
  649. log.Error("order(%s) check failed", order)
  650. ctx.HTML(http.StatusBadRequest, tplModelArtsTrainJobShow)
  651. return
  652. }
  653. task, err := models.GetCloudbrainByJobID(jobID)
  654. if err != nil {
  655. log.Error("GetCloudbrainByJobID(%s) failed:%v", jobID, err.Error())
  656. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  657. return
  658. }
  659. result, err := modelarts.GetTrainJobLog(jobID, strconv.FormatInt(task.VersionID, 10), baseLine, logFileName, order, modelarts.Lines)
  660. if err != nil {
  661. log.Error("GetTrainJobLog(%s) failed:%v", jobID, err.Error())
  662. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  663. return
  664. }
  665. ctx.Data["log"] = result
  666. //ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  667. }
  668. func getConfigList(perPage, page int, sortBy, order, searchContent, configType string) (*models.GetConfigListResult, error) {
  669. var result models.GetConfigListResult
  670. list, err := modelarts.GetConfigList(perPage, page, sortBy, order, searchContent, configType)
  671. if err != nil {
  672. log.Error("GetConfigList failed:", err)
  673. return &result, err
  674. }
  675. for _, config := range list.ParaConfigs {
  676. paraConfig, err := modelarts.GetParaConfig(config.ConfigName, configType)
  677. if err != nil {
  678. log.Error("GetParaConfig failed:", err)
  679. return &result, err
  680. }
  681. config.Result = paraConfig
  682. }
  683. return list, nil
  684. }