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 46 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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477
  1. package repo
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io"
  6. "net/http"
  7. "os"
  8. "path"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/auth"
  14. "code.gitea.io/gitea/modules/base"
  15. "code.gitea.io/gitea/modules/context"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/modelarts"
  19. "code.gitea.io/gitea/modules/obs"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/storage"
  22. "github.com/unknwon/com"
  23. )
  24. const (
  25. tplDebugJobIndex base.TplName = "repo/debugjob/index"
  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. tplModelArtsTrainJobVersionNew base.TplName = "repo/modelarts/trainjob/version_new"
  33. )
  34. func DebugJobIndex(ctx *context.Context) {
  35. MustEnableCloudbrain(ctx)
  36. repo := ctx.Repo.Repository
  37. page := ctx.QueryInt("page")
  38. if page <= 0 {
  39. page = 1
  40. }
  41. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  42. ListOptions: models.ListOptions{
  43. Page: page,
  44. PageSize: setting.UI.IssuePagingNum,
  45. },
  46. RepoID: repo.ID,
  47. Type: modelarts.DebugType,
  48. JobType: string(models.JobTypeDebug),
  49. })
  50. if err != nil {
  51. ctx.ServerError("Get debugjob faild:", err)
  52. return
  53. }
  54. timestamp := time.Now().Unix()
  55. for i, task := range ciTasks {
  56. if task.Cloudbrain.Type == models.TypeCloudBrainOne {
  57. if task.Status == string(models.JobRunning) && (timestamp-int64(task.Cloudbrain.CreatedUnix) > 10) {
  58. ciTasks[i].CanDebug = true
  59. } else {
  60. ciTasks[i].CanDebug = false
  61. }
  62. ciTasks[i].CanDel = models.CanDelJob(ctx.IsSigned, ctx.User, task)
  63. ciTasks[i].Cloudbrain.ComputeResource = modelarts.GPUResource
  64. }
  65. if task.Cloudbrain.Type == models.TypeCloudBrainTwo {
  66. if task.Status == string(models.JobRunning) {
  67. ciTasks[i].CanDebug = true
  68. } else {
  69. ciTasks[i].CanDebug = false
  70. }
  71. ciTasks[i].Cloudbrain.ComputeResource = modelarts.NPUResource
  72. }
  73. }
  74. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  75. pager.SetDefaultParams(ctx)
  76. ctx.Data["Page"] = pager
  77. ctx.Data["PageIsCloudBrain"] = true
  78. ctx.Data["Tasks"] = ciTasks
  79. ctx.HTML(200, tplDebugJobIndex)
  80. }
  81. // MustEnableDataset check if repository enable internal cb
  82. func MustEnableModelArts(ctx *context.Context) {
  83. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  84. ctx.NotFound("MustEnableCloudbrain", nil)
  85. return
  86. }
  87. }
  88. func NotebookIndex(ctx *context.Context) {
  89. MustEnableModelArts(ctx)
  90. repo := ctx.Repo.Repository
  91. page := ctx.QueryInt("page")
  92. if page <= 0 {
  93. page = 1
  94. }
  95. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  96. ListOptions: models.ListOptions{
  97. Page: page,
  98. PageSize: setting.UI.IssuePagingNum,
  99. },
  100. RepoID: repo.ID,
  101. Type: models.TypeCloudBrainTwo,
  102. JobType: string(models.JobTypeDebug),
  103. })
  104. if err != nil {
  105. ctx.ServerError("Cloudbrain", err)
  106. return
  107. }
  108. for i, task := range ciTasks {
  109. if task.Status == string(models.JobRunning) {
  110. ciTasks[i].CanDebug = true
  111. } else {
  112. ciTasks[i].CanDebug = false
  113. }
  114. }
  115. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  116. pager.SetDefaultParams(ctx)
  117. ctx.Data["Page"] = pager
  118. ctx.Data["PageIsCloudBrain"] = true
  119. ctx.Data["Tasks"] = ciTasks
  120. ctx.HTML(200, tplModelArtsNotebookIndex)
  121. }
  122. func NotebookNew(ctx *context.Context) {
  123. ctx.Data["PageIsCloudBrain"] = true
  124. t := time.Now()
  125. var jobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  126. ctx.Data["job_name"] = jobName
  127. attachs, err := models.GetModelArtsUserAttachments(ctx.User.ID)
  128. if err != nil {
  129. ctx.ServerError("GetAllUserAttachments failed:", err)
  130. return
  131. }
  132. ctx.Data["attachments"] = attachs
  133. ctx.Data["dataset_path"] = modelarts.DataSetMountPath
  134. ctx.Data["env"] = modelarts.NotebookEnv
  135. ctx.Data["notebook_type"] = modelarts.NotebookType
  136. if modelarts.FlavorInfos == nil {
  137. json.Unmarshal([]byte(setting.FlavorInfos), &modelarts.FlavorInfos)
  138. }
  139. ctx.Data["flavors"] = modelarts.FlavorInfos.FlavorInfo
  140. ctx.HTML(200, tplModelArtsNotebookNew)
  141. }
  142. func NotebookCreate(ctx *context.Context, form auth.CreateModelArtsNotebookForm) {
  143. ctx.Data["PageIsNotebook"] = true
  144. jobName := form.JobName
  145. uuid := form.Attachment
  146. description := form.Description
  147. flavor := form.Flavor
  148. err := modelarts.GenerateTask(ctx, jobName, uuid, description, flavor)
  149. if err != nil {
  150. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookNew, &form)
  151. return
  152. }
  153. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/notebook")
  154. }
  155. func NotebookShow(ctx *context.Context) {
  156. ctx.Data["PageIsCloudBrain"] = true
  157. var jobID = ctx.Params(":jobid")
  158. task, err := models.GetCloudbrainByJobID(jobID)
  159. if err != nil {
  160. ctx.Data["error"] = err.Error()
  161. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookShow, nil)
  162. return
  163. }
  164. result, err := modelarts.GetJob(jobID)
  165. if err != nil {
  166. ctx.Data["error"] = err.Error()
  167. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookShow, nil)
  168. return
  169. }
  170. if result != nil {
  171. task.Status = result.Status
  172. err = models.UpdateJob(task)
  173. if err != nil {
  174. ctx.Data["error"] = err.Error()
  175. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookShow, nil)
  176. return
  177. }
  178. createTime, _ := com.StrTo(result.CreationTimestamp).Int64()
  179. result.CreateTime = time.Unix(int64(createTime/1000), 0).Format("2006-01-02 15:04:05")
  180. endTime, _ := com.StrTo(result.LatestUpdateTimestamp).Int64()
  181. result.LatestUpdateTime = time.Unix(int64(endTime/1000), 0).Format("2006-01-02 15:04:05")
  182. result.QueuingInfo.BeginTime = time.Unix(int64(result.QueuingInfo.BeginTimestamp/1000), 0).Format("2006-01-02 15:04:05")
  183. result.QueuingInfo.EndTime = time.Unix(int64(result.QueuingInfo.EndTimestamp/1000), 0).Format("2006-01-02 15:04:05")
  184. }
  185. ctx.Data["task"] = task
  186. ctx.Data["jobID"] = jobID
  187. ctx.Data["result"] = result
  188. ctx.HTML(200, tplModelArtsNotebookShow)
  189. }
  190. func NotebookDebug(ctx *context.Context) {
  191. var jobID = ctx.Params(":jobid")
  192. _, err := models.GetCloudbrainByJobID(jobID)
  193. if err != nil {
  194. ctx.ServerError("GetCloudbrainByJobID failed", err)
  195. return
  196. }
  197. result, err := modelarts.GetJob(jobID)
  198. if err != nil {
  199. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  200. return
  201. }
  202. res, err := modelarts.GetJobToken(jobID)
  203. if err != nil {
  204. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  205. return
  206. }
  207. urls := strings.Split(result.Spec.Annotations.Url, "/")
  208. urlPrefix := result.Spec.Annotations.TargetDomain
  209. for i, url := range urls {
  210. if i > 2 {
  211. urlPrefix += "/" + url
  212. }
  213. }
  214. debugUrl := urlPrefix + "?token=" + res.Token
  215. ctx.Redirect(debugUrl)
  216. }
  217. func NotebookStop(ctx *context.Context) {
  218. var jobID = ctx.Params(":jobid")
  219. log.Info(jobID)
  220. task, err := models.GetCloudbrainByJobID(jobID)
  221. if err != nil {
  222. ctx.ServerError("GetCloudbrainByJobID failed", err)
  223. return
  224. }
  225. if task.Status != string(models.JobRunning) {
  226. log.Error("the job(%s) is not running", task.JobName)
  227. ctx.ServerError("the job is not running", errors.New("the job is not running"))
  228. return
  229. }
  230. param := models.NotebookAction{
  231. Action: models.ActionStop,
  232. }
  233. res, err := modelarts.StopJob(jobID, param)
  234. if err != nil {
  235. log.Error("StopJob(%s) failed:%v", task.JobName, err.Error())
  236. ctx.ServerError("StopJob failed", err)
  237. return
  238. }
  239. task.Status = res.CurrentStatus
  240. err = models.UpdateJob(task)
  241. if err != nil {
  242. ctx.ServerError("UpdateJob failed", err)
  243. return
  244. }
  245. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/notebook")
  246. }
  247. func NotebookDel(ctx *context.Context) {
  248. var jobID = ctx.Params(":jobid")
  249. task, err := models.GetCloudbrainByJobID(jobID)
  250. if err != nil {
  251. ctx.ServerError("GetCloudbrainByJobID failed", err)
  252. return
  253. }
  254. if task.Status != string(models.JobStopped) {
  255. log.Error("the job(%s) has not been stopped", task.JobName)
  256. ctx.ServerError("the job has not been stopped", errors.New("the job has not been stopped"))
  257. return
  258. }
  259. _, err = modelarts.DelNotebook(jobID)
  260. if err != nil {
  261. log.Error("DelJob(%s) failed:%v", task.JobName, err.Error())
  262. ctx.ServerError("DelJob failed", err)
  263. return
  264. }
  265. err = models.DeleteJob(task)
  266. if err != nil {
  267. ctx.ServerError("DeleteJob failed", err)
  268. return
  269. }
  270. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/notebook")
  271. }
  272. func TrainJobIndex(ctx *context.Context) {
  273. MustEnableModelArts(ctx)
  274. repo := ctx.Repo.Repository
  275. page := ctx.QueryInt("page")
  276. if page <= 0 {
  277. page = 1
  278. }
  279. tasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  280. ListOptions: models.ListOptions{
  281. Page: page,
  282. PageSize: setting.UI.IssuePagingNum,
  283. },
  284. RepoID: repo.ID,
  285. Type: models.TypeCloudBrainTwo,
  286. JobType: string(models.JobTypeTrain),
  287. IsLatestVersion: modelarts.IsLatestVersion,
  288. })
  289. if err != nil {
  290. ctx.ServerError("Cloudbrain", err)
  291. return
  292. }
  293. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  294. pager.SetDefaultParams(ctx)
  295. ctx.Data["Page"] = pager
  296. ctx.Data["PageIsCloudBrain"] = true
  297. ctx.Data["Tasks"] = tasks
  298. ctx.HTML(200, tplModelArtsTrainJobIndex)
  299. }
  300. func TrainJobNew(ctx *context.Context) {
  301. err := trainJobNewDataPrepare(ctx)
  302. if err != nil {
  303. ctx.ServerError("get new train-job info failed", err)
  304. return
  305. }
  306. ctx.HTML(200, tplModelArtsTrainJobNew)
  307. }
  308. func trainJobNewDataPrepare(ctx *context.Context) error {
  309. ctx.Data["PageIsCloudBrain"] = true
  310. //can, err := canUserCreateTrainJob(ctx.User.ID)
  311. //if err != nil {
  312. // ctx.ServerError("canUserCreateTrainJob", err)
  313. // return
  314. //}
  315. //
  316. //if !can {
  317. // log.Error("the user can not create train-job")
  318. // ctx.ServerError("the user can not create train-job", fmt.Errorf("the user can not create train-job"))
  319. // return
  320. //}
  321. t := time.Now()
  322. var jobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  323. ctx.Data["job_name"] = jobName
  324. attachs, err := models.GetModelArtsUserAttachments(ctx.User.ID)
  325. if err != nil {
  326. ctx.ServerError("GetAllUserAttachments failed:", err)
  327. return err
  328. }
  329. ctx.Data["attachments"] = attachs
  330. var resourcePools modelarts.ResourcePool
  331. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  332. ctx.ServerError("json.Unmarshal failed:", err)
  333. return err
  334. }
  335. ctx.Data["resource_pools"] = resourcePools.Info
  336. var engines modelarts.Engine
  337. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  338. ctx.ServerError("json.Unmarshal failed:", err)
  339. return err
  340. }
  341. ctx.Data["engines"] = engines.Info
  342. var versionInfos modelarts.VersionInfo
  343. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  344. ctx.ServerError("json.Unmarshal failed:", err)
  345. return err
  346. }
  347. ctx.Data["engine_versions"] = versionInfos.Version
  348. var flavorInfos modelarts.Flavor
  349. if err = json.Unmarshal([]byte(setting.TrainJobFLAVORINFOS), &flavorInfos); err != nil {
  350. ctx.ServerError("json.Unmarshal failed:", err)
  351. return err
  352. }
  353. ctx.Data["flavor_infos"] = flavorInfos.Info
  354. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath
  355. ctx.Data["train_url"] = outputObsPath
  356. Branches, err := ctx.Repo.GitRepo.GetBranches()
  357. if err != nil {
  358. ctx.ServerError("GetBranches error:", err)
  359. return err
  360. }
  361. ctx.Data["Branches"] = Branches
  362. ctx.Data["BranchesCount"] = len(Branches)
  363. ctx.Data["params"] = ""
  364. ctx.Data["BranchName"] = ctx.Repo.BranchName
  365. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  366. if err != nil {
  367. ctx.ServerError("getConfigList failed:", err)
  368. return err
  369. }
  370. ctx.Data["config_list"] = configList.ParaConfigs
  371. return nil
  372. }
  373. func trainJobErrorNewDataPrepare(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) error {
  374. ctx.Data["PageIsCloudBrain"] = true
  375. //can, err := canUserCreateTrainJob(ctx.User.ID)
  376. //if err != nil {
  377. // ctx.ServerError("canUserCreateTrainJob", err)
  378. // return
  379. //}
  380. //
  381. //if !can {
  382. // log.Error("the user can not create train-job")
  383. // ctx.ServerError("the user can not create train-job", fmt.Errorf("the user can not create train-job"))
  384. // return
  385. //}
  386. t := time.Now()
  387. var jobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  388. ctx.Data["job_name"] = jobName
  389. attachs, err := models.GetModelArtsUserAttachments(ctx.User.ID)
  390. if err != nil {
  391. ctx.ServerError("GetAllUserAttachments failed:", err)
  392. return err
  393. }
  394. ctx.Data["attachments"] = attachs
  395. var resourcePools modelarts.ResourcePool
  396. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  397. ctx.ServerError("json.Unmarshal failed:", err)
  398. return err
  399. }
  400. ctx.Data["resource_pools"] = resourcePools.Info
  401. var engines modelarts.Engine
  402. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  403. ctx.ServerError("json.Unmarshal failed:", err)
  404. return err
  405. }
  406. ctx.Data["engines"] = engines.Info
  407. var versionInfos modelarts.VersionInfo
  408. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  409. ctx.ServerError("json.Unmarshal failed:", err)
  410. return err
  411. }
  412. ctx.Data["engine_versions"] = versionInfos.Version
  413. var flavorInfos modelarts.Flavor
  414. if err = json.Unmarshal([]byte(setting.TrainJobFLAVORINFOS), &flavorInfos); err != nil {
  415. ctx.ServerError("json.Unmarshal failed:", err)
  416. return err
  417. }
  418. ctx.Data["flavor_infos"] = flavorInfos.Info
  419. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath
  420. ctx.Data["train_url"] = outputObsPath
  421. Branches, err := ctx.Repo.GitRepo.GetBranches()
  422. if err != nil {
  423. ctx.ServerError("GetBranches error:", err)
  424. return err
  425. }
  426. ctx.Data["Branches"] = Branches
  427. ctx.Data["BranchesCount"] = len(Branches)
  428. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  429. if err != nil {
  430. ctx.ServerError("getConfigList failed:", err)
  431. return err
  432. }
  433. var Parameters modelarts.Parameters
  434. if err = json.Unmarshal([]byte(form.Params), &Parameters); err != nil {
  435. ctx.ServerError("json.Unmarshal failed:", err)
  436. return err
  437. }
  438. ctx.Data["params"] = Parameters.Parameter
  439. ctx.Data["config_list"] = configList.ParaConfigs
  440. ctx.Data["bootFile"] = form.BootFile
  441. ctx.Data["uuid"] = form.Attachment
  442. ctx.Data["branch_name"] = form.BranchName
  443. return nil
  444. }
  445. func TrainJobNewVersion(ctx *context.Context) {
  446. err := trainJobNewVersionDataPrepare(ctx)
  447. if err != nil {
  448. ctx.ServerError("get new train-job info failed", err)
  449. return
  450. }
  451. ctx.HTML(200, tplModelArtsTrainJobVersionNew)
  452. }
  453. func trainJobNewVersionDataPrepare(ctx *context.Context) error {
  454. ctx.Data["PageIsCloudBrain"] = true
  455. var jobID = ctx.Params(":jobid")
  456. var versionName = ctx.Query("version_name")
  457. // canNewJob, err := canUserCreateTrainJobVersion(ctx, jobID, versionName)
  458. // if err != nil {
  459. // ctx.ServerError("canNewJob can info failed", err)
  460. // return err
  461. // }
  462. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  463. if err != nil {
  464. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", jobID, err.Error())
  465. return err
  466. }
  467. t := time.Now()
  468. var jobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  469. ctx.Data["job_name"] = task.JobName
  470. attachs, err := models.GetModelArtsUserAttachments(ctx.User.ID)
  471. if err != nil {
  472. ctx.ServerError("GetAllUserAttachments failed:", err)
  473. return err
  474. }
  475. ctx.Data["attachments"] = attachs
  476. var resourcePools modelarts.ResourcePool
  477. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  478. ctx.ServerError("json.Unmarshal failed:", err)
  479. return err
  480. }
  481. ctx.Data["resource_pools"] = resourcePools.Info
  482. var engines modelarts.Engine
  483. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  484. ctx.ServerError("json.Unmarshal failed:", err)
  485. return err
  486. }
  487. ctx.Data["engines"] = engines.Info
  488. var versionInfos modelarts.VersionInfo
  489. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  490. ctx.ServerError("json.Unmarshal failed:", err)
  491. return err
  492. }
  493. ctx.Data["engine_versions"] = versionInfos.Version
  494. var flavorInfos modelarts.Flavor
  495. if err = json.Unmarshal([]byte(setting.TrainJobFLAVORINFOS), &flavorInfos); err != nil {
  496. ctx.ServerError("json.Unmarshal failed:", err)
  497. return err
  498. }
  499. ctx.Data["flavor_infos"] = flavorInfos.Info
  500. var Parameters modelarts.Parameters
  501. if err = json.Unmarshal([]byte(task.Parameters), &Parameters); err != nil {
  502. ctx.ServerError("json.Unmarshal failed:", err)
  503. return err
  504. }
  505. ctx.Data["params"] = Parameters.Parameter
  506. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath
  507. ctx.Data["train_url"] = outputObsPath
  508. Branches, err := ctx.Repo.GitRepo.GetBranches()
  509. if err != nil {
  510. ctx.ServerError("GetBranches error:", err)
  511. return err
  512. }
  513. ctx.Data["branches"] = Branches
  514. ctx.Data["branch_name"] = task.BranchName
  515. ctx.Data["description"] = task.Description
  516. ctx.Data["boot_file"] = task.BootFile
  517. ctx.Data["dataset_name"] = task.DatasetName
  518. ctx.Data["work_server_number"] = task.WorkServerNumber
  519. ctx.Data["flavor_name"] = task.FlavorName
  520. ctx.Data["engine_name"] = task.EngineName
  521. ctx.Data["uuid"] = task.Uuid
  522. ctx.Data["flavor_code"] = task.FlavorCode
  523. ctx.Data["engine_id"] = task.EngineID
  524. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  525. if err != nil {
  526. ctx.ServerError("getConfigList failed:", err)
  527. return err
  528. }
  529. ctx.Data["config_list"] = configList.ParaConfigs
  530. return nil
  531. }
  532. func versionErrorDataPrepare(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) error {
  533. ctx.Data["PageIsCloudBrain"] = true
  534. var jobID = ctx.Params(":jobid")
  535. // var versionName = ctx.Params(":version-name")
  536. var versionName = ctx.Query("version_name")
  537. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  538. if err != nil {
  539. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", jobID, err.Error())
  540. return err
  541. }
  542. t := time.Now()
  543. var jobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  544. ctx.Data["job_name"] = task.JobName
  545. attachs, err := models.GetModelArtsUserAttachments(ctx.User.ID)
  546. if err != nil {
  547. ctx.ServerError("GetAllUserAttachments failed:", err)
  548. return err
  549. }
  550. ctx.Data["attachments"] = attachs
  551. var resourcePools modelarts.ResourcePool
  552. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  553. ctx.ServerError("json.Unmarshal failed:", err)
  554. return err
  555. }
  556. ctx.Data["resource_pools"] = resourcePools.Info
  557. var engines modelarts.Engine
  558. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  559. ctx.ServerError("json.Unmarshal failed:", err)
  560. return err
  561. }
  562. ctx.Data["engines"] = engines.Info
  563. var versionInfos modelarts.VersionInfo
  564. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  565. ctx.ServerError("json.Unmarshal failed:", err)
  566. return err
  567. }
  568. ctx.Data["engine_versions"] = versionInfos.Version
  569. var flavorInfos modelarts.Flavor
  570. if err = json.Unmarshal([]byte(setting.TrainJobFLAVORINFOS), &flavorInfos); err != nil {
  571. ctx.ServerError("json.Unmarshal failed:", err)
  572. return err
  573. }
  574. ctx.Data["flavor_infos"] = flavorInfos.Info
  575. var Parameters modelarts.Parameters
  576. if err = json.Unmarshal([]byte(form.Params), &Parameters); err != nil {
  577. ctx.ServerError("json.Unmarshal failed:", err)
  578. return err
  579. }
  580. ctx.Data["params"] = Parameters.Parameter
  581. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath
  582. ctx.Data["train_url"] = outputObsPath
  583. Branches, err := ctx.Repo.GitRepo.GetBranches()
  584. if err != nil {
  585. ctx.ServerError("GetBranches error:", err)
  586. return err
  587. }
  588. ctx.Data["branches"] = Branches
  589. ctx.Data["description"] = form.Description
  590. ctx.Data["dataset_name"] = task.DatasetName
  591. ctx.Data["work_server_number"] = form.WorkServerNumber
  592. ctx.Data["flavor_name"] = form.FlavorName
  593. ctx.Data["engine_name"] = form.EngineName
  594. ctx.Data["flavor_code"] = task.FlavorCode
  595. ctx.Data["engine_id"] = task.EngineID
  596. ctx.Data["version_name"] = form.VersionName
  597. ctx.Data["bootFile"] = form.BootFile
  598. ctx.Data["uuid"] = form.Attachment
  599. ctx.Data["branch_name"] = form.BranchName
  600. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  601. if err != nil {
  602. ctx.ServerError("getConfigList failed:", err)
  603. return err
  604. }
  605. ctx.Data["config_list"] = configList.ParaConfigs
  606. return nil
  607. }
  608. func TrainJobCreate(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) {
  609. ctx.Data["PageIsTrainJob"] = true
  610. VersionOutputPath := modelarts.GetVersionOutputPathByTotalVersionCount(modelarts.TotalVersionCount)
  611. jobName := form.JobName
  612. uuid := form.Attachment
  613. description := form.Description
  614. workServerNumber := form.WorkServerNumber
  615. engineID := form.EngineID
  616. bootFile := form.BootFile
  617. flavorCode := form.Flavor
  618. params := form.Params
  619. poolID := form.PoolID
  620. isSaveParam := form.IsSaveParam
  621. repo := ctx.Repo.Repository
  622. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  623. codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath
  624. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath + VersionOutputPath + "/"
  625. logObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.LogPath + VersionOutputPath + "/"
  626. dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/"
  627. branch_name := form.BranchName
  628. isLatestVersion := modelarts.IsLatestVersion
  629. FlavorName := form.FlavorName
  630. VersionCount := modelarts.VersionCount
  631. EngineName := form.EngineName
  632. if err := paramCheckCreateTrainJob(form); err != nil {
  633. log.Error("paramCheckCreateTrainJob failed:(%v)", err)
  634. trainJobErrorNewDataPrepare(ctx, form)
  635. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobNew, &form)
  636. return
  637. }
  638. // attach, err := models.GetAttachmentByUUID(uuid)
  639. // if err != nil {
  640. // log.Error("GetAttachmentByUUID(%s) failed:%v", uuid, err.Error())
  641. // return
  642. // }
  643. //todo: del the codeLocalPath
  644. // _, err := ioutil.ReadDir(codeLocalPath)
  645. // if err == nil {
  646. // os.RemoveAll(codeLocalPath)
  647. // }
  648. os.RemoveAll(codeLocalPath)
  649. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  650. commitID, _ := gitRepo.GetBranchCommitID(branch_name)
  651. if err := git.Clone(repo.RepoPath(), codeLocalPath, git.CloneRepoOptions{
  652. Branch: branch_name,
  653. }); err != nil {
  654. log.Error("创建任务失败,服务器超时!: %s (%v)", repo.FullName(), err)
  655. trainJobErrorNewDataPrepare(ctx, form)
  656. ctx.RenderWithErr("创建任务失败,服务器超时!", tplModelArtsTrainJobNew, &form)
  657. return
  658. }
  659. //todo: upload code (send to file_server todo this work?)
  660. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath + VersionOutputPath + "/"); err != nil {
  661. log.Error("Failed to obsMkdir_output: %s (%v)", repo.FullName(), err)
  662. trainJobErrorNewDataPrepare(ctx, form)
  663. ctx.RenderWithErr("Failed to obsMkdir_output", tplModelArtsTrainJobNew, &form)
  664. return
  665. }
  666. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.LogPath + VersionOutputPath + "/"); err != nil {
  667. log.Error("Failed to obsMkdir_log: %s (%v)", repo.FullName(), err)
  668. trainJobErrorNewDataPrepare(ctx, form)
  669. ctx.RenderWithErr("Failed to obsMkdir_log", tplModelArtsTrainJobNew, &form)
  670. return
  671. }
  672. // parentDir := VersionOutputPath + "/"
  673. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  674. // if err := uploadCodeToObs(codeLocalPath, jobName, parentDir); err != nil {
  675. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  676. trainJobErrorNewDataPrepare(ctx, form)
  677. ctx.RenderWithErr("Failed to uploadCodeToObs", tplModelArtsTrainJobNew, &form)
  678. return
  679. }
  680. //todo: del local code?
  681. var parameters models.Parameters
  682. param := make([]models.Parameter, 0)
  683. param = append(param, models.Parameter{
  684. Label: modelarts.TrainUrl,
  685. Value: outputObsPath,
  686. }, models.Parameter{
  687. Label: modelarts.DataUrl,
  688. Value: dataPath,
  689. })
  690. if len(params) != 0 {
  691. err := json.Unmarshal([]byte(params), &parameters)
  692. if err != nil {
  693. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  694. trainJobErrorNewDataPrepare(ctx, form)
  695. ctx.RenderWithErr("运行参数错误", tplModelArtsTrainJobNew, &form)
  696. return
  697. }
  698. for _, parameter := range parameters.Parameter {
  699. if parameter.Label != modelarts.TrainUrl && parameter.Label != modelarts.DataUrl {
  700. param = append(param, models.Parameter{
  701. Label: parameter.Label,
  702. Value: parameter.Value,
  703. })
  704. }
  705. }
  706. }
  707. //save param config
  708. if isSaveParam == "on" {
  709. if form.ParameterTemplateName == "" {
  710. log.Error("ParameterTemplateName is empty")
  711. trainJobNewDataPrepare(ctx)
  712. ctx.RenderWithErr("保存作业参数时,作业参数名称不能为空", tplModelArtsTrainJobNew, &form)
  713. return
  714. }
  715. _, err := modelarts.CreateTrainJobConfig(models.CreateConfigParams{
  716. ConfigName: form.ParameterTemplateName,
  717. Description: form.PrameterDescription,
  718. DataUrl: dataPath,
  719. AppUrl: codeObsPath,
  720. BootFileUrl: codeObsPath + bootFile,
  721. TrainUrl: outputObsPath,
  722. Flavor: models.Flavor{
  723. Code: flavorCode,
  724. },
  725. WorkServerNum: workServerNumber,
  726. EngineID: int64(engineID),
  727. LogUrl: logObsPath,
  728. PoolID: poolID,
  729. Parameter: param,
  730. })
  731. if err != nil {
  732. log.Error("Failed to CreateTrainJobConfig: %v", err)
  733. trainJobErrorNewDataPrepare(ctx, form)
  734. ctx.RenderWithErr("保存作业参数失败:"+err.Error(), tplModelArtsTrainJobNew, &form)
  735. return
  736. }
  737. }
  738. req := &modelarts.GenerateTrainJobReq{
  739. JobName: jobName,
  740. DataUrl: dataPath,
  741. Description: description,
  742. CodeObsPath: codeObsPath,
  743. BootFileUrl: codeObsPath + bootFile,
  744. BootFile: bootFile,
  745. TrainUrl: outputObsPath,
  746. FlavorCode: flavorCode,
  747. WorkServerNumber: workServerNumber,
  748. EngineID: int64(engineID),
  749. LogUrl: logObsPath,
  750. PoolID: poolID,
  751. Uuid: uuid,
  752. Parameters: parameters.Parameter,
  753. CommitID: commitID,
  754. IsLatestVersion: isLatestVersion,
  755. BranchName: branch_name,
  756. Params: form.Params,
  757. FlavorName: FlavorName,
  758. EngineName: EngineName,
  759. VersionCount: VersionCount,
  760. TotalVersionCount: modelarts.TotalVersionCount,
  761. }
  762. //将params转换Parameters.Parameter,出错时返回给前端
  763. var Parameters modelarts.Parameters
  764. if err := json.Unmarshal([]byte(params), &Parameters); err != nil {
  765. ctx.ServerError("json.Unmarshal failed:", err)
  766. return
  767. }
  768. err := modelarts.GenerateTrainJob(ctx, req)
  769. if err != nil {
  770. log.Error("GenerateTrainJob failed:%v", err.Error())
  771. trainJobErrorNewDataPrepare(ctx, form)
  772. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobNew, &form)
  773. return
  774. }
  775. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  776. }
  777. func TrainJobCreateVersion(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) {
  778. ctx.Data["PageIsTrainJob"] = true
  779. var jobID = ctx.Params(":jobid")
  780. latestTask, err := models.GetCloudbrainByJobIDAndIsLatestVersion(jobID, modelarts.IsLatestVersion)
  781. if err != nil {
  782. ctx.ServerError("GetCloudbrainByJobIDAndIsLatestVersion faild:", err)
  783. return
  784. }
  785. VersionOutputPath := modelarts.GetVersionOutputPathByTotalVersionCount(latestTask.TotalVersionCount + 1)
  786. jobName := form.JobName
  787. uuid := form.Attachment
  788. description := form.Description
  789. workServerNumber := form.WorkServerNumber
  790. engineID := form.EngineID
  791. bootFile := form.BootFile
  792. flavorCode := form.Flavor
  793. params := form.Params
  794. poolID := form.PoolID
  795. isSaveParam := form.IsSaveParam
  796. repo := ctx.Repo.Repository
  797. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  798. codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath + VersionOutputPath + "/"
  799. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath + VersionOutputPath + "/"
  800. logObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.LogPath + VersionOutputPath + "/"
  801. dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/"
  802. branch_name := form.BranchName
  803. PreVersionName := form.VersionName
  804. FlavorName := form.FlavorName
  805. EngineName := form.EngineName
  806. isLatestVersion := modelarts.IsLatestVersion
  807. //判断权限
  808. canNewJob, _ := canUserCreateTrainJobVersion(ctx, latestTask.UserID)
  809. if !canNewJob {
  810. ctx.RenderWithErr("user cann't new trainjob", tplModelArtsTrainJobVersionNew, &form)
  811. return
  812. }
  813. if err := paramCheckCreateTrainJob(form); err != nil {
  814. log.Error("paramCheckCreateTrainJob failed:(%v)", err)
  815. versionErrorDataPrepare(ctx, form)
  816. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobVersionNew, &form)
  817. return
  818. }
  819. // attach, err := models.GetAttachmentByUUID(uuid)
  820. // if err != nil {
  821. // log.Error("GetAttachmentByUUID(%s) failed:%v", uuid, err.Error())
  822. // return
  823. // }
  824. //todo: del the codeLocalPath
  825. // _, err = ioutil.ReadDir(codeLocalPath)
  826. // if err == nil {
  827. // os.RemoveAll(codeLocalPath)
  828. // }
  829. os.RemoveAll(codeLocalPath)
  830. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  831. commitID, _ := gitRepo.GetBranchCommitID(branch_name)
  832. if err := git.Clone(repo.RepoPath(), codeLocalPath, git.CloneRepoOptions{
  833. Branch: branch_name,
  834. }); err != nil {
  835. log.Error("创建任务失败,任务名称已存在!: %s (%v)", repo.FullName(), err)
  836. versionErrorDataPrepare(ctx, form)
  837. ctx.RenderWithErr("创建任务失败,任务名称已存在!", tplModelArtsTrainJobVersionNew, &form)
  838. return
  839. }
  840. //todo: upload code (send to file_server todo this work?)
  841. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath + VersionOutputPath + "/"); err != nil {
  842. log.Error("Failed to obsMkdir_output: %s (%v)", repo.FullName(), err)
  843. versionErrorDataPrepare(ctx, form)
  844. ctx.RenderWithErr("Failed to obsMkdir_output", tplModelArtsTrainJobVersionNew, &form)
  845. return
  846. }
  847. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.LogPath + VersionOutputPath + "/"); err != nil {
  848. log.Error("Failed to obsMkdir_log: %s (%v)", repo.FullName(), err)
  849. versionErrorDataPrepare(ctx, form)
  850. ctx.RenderWithErr("Failed to obsMkdir_log", tplModelArtsTrainJobVersionNew, &form)
  851. return
  852. }
  853. parentDir := VersionOutputPath + "/"
  854. // parentDir := ""
  855. // if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  856. if err := uploadCodeToObs(codeLocalPath, jobName, parentDir); err != nil {
  857. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  858. versionErrorDataPrepare(ctx, form)
  859. ctx.RenderWithErr("Failed to uploadCodeToObs", tplModelArtsTrainJobVersionNew, &form)
  860. return
  861. }
  862. //todo: del local code?
  863. var parameters models.Parameters
  864. param := make([]models.Parameter, 0)
  865. param = append(param, models.Parameter{
  866. Label: modelarts.TrainUrl,
  867. Value: outputObsPath,
  868. }, models.Parameter{
  869. Label: modelarts.DataUrl,
  870. Value: dataPath,
  871. })
  872. if len(params) != 0 {
  873. err := json.Unmarshal([]byte(params), &parameters)
  874. if err != nil {
  875. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  876. versionErrorDataPrepare(ctx, form)
  877. ctx.RenderWithErr("运行参数错误", tplModelArtsTrainJobVersionNew, &form)
  878. return
  879. }
  880. for _, parameter := range parameters.Parameter {
  881. if parameter.Label != modelarts.TrainUrl && parameter.Label != modelarts.DataUrl {
  882. param = append(param, models.Parameter{
  883. Label: parameter.Label,
  884. Value: parameter.Value,
  885. })
  886. }
  887. }
  888. }
  889. //save param config
  890. if isSaveParam == "on" {
  891. if form.ParameterTemplateName == "" {
  892. log.Error("ParameterTemplateName is empty")
  893. versionErrorDataPrepare(ctx, form)
  894. ctx.RenderWithErr("保存作业参数时,作业参数名称不能为空", tplModelArtsTrainJobVersionNew, &form)
  895. return
  896. }
  897. _, err := modelarts.CreateTrainJobConfig(models.CreateConfigParams{
  898. ConfigName: form.ParameterTemplateName,
  899. Description: form.PrameterDescription,
  900. DataUrl: dataPath,
  901. AppUrl: codeObsPath,
  902. BootFileUrl: codeObsPath + bootFile,
  903. TrainUrl: outputObsPath,
  904. Flavor: models.Flavor{
  905. Code: flavorCode,
  906. },
  907. WorkServerNum: workServerNumber,
  908. EngineID: int64(engineID),
  909. LogUrl: logObsPath,
  910. PoolID: poolID,
  911. Parameter: parameters.Parameter,
  912. })
  913. if err != nil {
  914. log.Error("Failed to CreateTrainJobConfig: %v", err)
  915. versionErrorDataPrepare(ctx, form)
  916. ctx.RenderWithErr("保存作业参数失败:"+err.Error(), tplModelArtsTrainJobVersionNew, &form)
  917. return
  918. }
  919. }
  920. if err != nil {
  921. log.Error("getFlavorNameByEngineID(%s) failed:%v", engineID, err.Error())
  922. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobVersionNew, &form)
  923. return
  924. }
  925. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, PreVersionName)
  926. if err != nil {
  927. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", jobID, err.Error())
  928. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobVersionNew, &form)
  929. return
  930. }
  931. req := &modelarts.GenerateTrainJobReq{
  932. JobName: task.JobName,
  933. DataUrl: dataPath,
  934. Description: description,
  935. CodeObsPath: codeObsPath,
  936. BootFileUrl: codeObsPath + bootFile,
  937. BootFile: bootFile,
  938. TrainUrl: outputObsPath,
  939. FlavorCode: flavorCode,
  940. WorkServerNumber: workServerNumber,
  941. IsLatestVersion: isLatestVersion,
  942. EngineID: int64(engineID),
  943. LogUrl: logObsPath,
  944. PoolID: poolID,
  945. Uuid: uuid,
  946. Params: form.Params,
  947. Parameters: parameters.Parameter,
  948. PreVersionId: task.VersionID,
  949. CommitID: commitID,
  950. BranchName: branch_name,
  951. FlavorName: FlavorName,
  952. EngineName: EngineName,
  953. PreVersionName: PreVersionName,
  954. TotalVersionCount: latestTask.TotalVersionCount + 1,
  955. }
  956. err = modelarts.GenerateTrainJobVersion(ctx, req, jobID)
  957. if err != nil {
  958. log.Error("GenerateTrainJob failed:%v", err.Error())
  959. versionErrorDataPrepare(ctx, form)
  960. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobVersionNew, &form)
  961. return
  962. }
  963. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job/" + jobID)
  964. // ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  965. }
  966. // readDir reads the directory named by dirname and returns
  967. // a list of directory entries sorted by filename.
  968. func readDir(dirname string) ([]os.FileInfo, error) {
  969. f, err := os.Open(dirname)
  970. if err != nil {
  971. return nil, err
  972. }
  973. list, err := f.Readdir(100)
  974. f.Close()
  975. if err != nil {
  976. //todo: can not upload empty folder
  977. if err == io.EOF {
  978. return nil, nil
  979. }
  980. return nil, err
  981. }
  982. //sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() })
  983. return list, nil
  984. }
  985. func uploadCodeToObs(codePath, jobName, parentDir string) error {
  986. files, err := readDir(codePath)
  987. if err != nil {
  988. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  989. return err
  990. }
  991. for _, file := range files {
  992. if file.IsDir() {
  993. input := &obs.PutObjectInput{}
  994. input.Bucket = setting.Bucket
  995. input.Key = parentDir + file.Name() + "/"
  996. _, err = storage.ObsCli.PutObject(input)
  997. if err != nil {
  998. log.Error("PutObject(%s) failed: %s", input.Key, err.Error())
  999. return err
  1000. }
  1001. if err = uploadCodeToObs(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  1002. log.Error("uploadCodeToObs(%s) failed: %s", file.Name(), err.Error())
  1003. return err
  1004. }
  1005. } else {
  1006. input := &obs.PutFileInput{}
  1007. input.Bucket = setting.Bucket
  1008. input.Key = setting.CodePathPrefix + jobName + "/code/" + parentDir + file.Name()
  1009. input.SourceFile = codePath + file.Name()
  1010. _, err = storage.ObsCli.PutFile(input)
  1011. if err != nil {
  1012. log.Error("PutFile(%s) failed: %s", input.SourceFile, err.Error())
  1013. return err
  1014. }
  1015. }
  1016. }
  1017. return nil
  1018. }
  1019. func obsMkdir(dir string) error {
  1020. input := &obs.PutObjectInput{}
  1021. input.Bucket = setting.Bucket
  1022. input.Key = dir
  1023. _, err := storage.ObsCli.PutObject(input)
  1024. if err != nil {
  1025. log.Error("PutObject(%s) failed: %s", input.Key, err.Error())
  1026. return err
  1027. }
  1028. return nil
  1029. }
  1030. func paramCheckCreateTrainJob(form auth.CreateModelArtsTrainJobForm) error {
  1031. if !strings.HasSuffix(form.BootFile, ".py") {
  1032. log.Error("the boot file(%s) must be a python file", form.BootFile)
  1033. return errors.New("启动文件必须是python文件")
  1034. }
  1035. if form.WorkServerNumber > 25 || form.WorkServerNumber < 1 {
  1036. log.Error("the WorkServerNumber(%d) must be in (1,25)", form.WorkServerNumber)
  1037. return errors.New("计算节点数必须在1-25之间")
  1038. }
  1039. return nil
  1040. }
  1041. func TrainJobShow(ctx *context.Context) {
  1042. ctx.Data["PageIsCloudBrain"] = true
  1043. var jobID = ctx.Params(":jobid")
  1044. repo := ctx.Repo.Repository
  1045. page := ctx.QueryInt("page")
  1046. if page <= 0 {
  1047. page = 1
  1048. }
  1049. VersionListTasks, VersionListCount, err := models.CloudbrainsVersionList(&models.CloudbrainsOptions{
  1050. ListOptions: models.ListOptions{
  1051. Page: page,
  1052. PageSize: setting.UI.IssuePagingNum,
  1053. },
  1054. RepoID: repo.ID,
  1055. Type: models.TypeCloudBrainTwo,
  1056. JobType: string(models.JobTypeTrain),
  1057. JobID: jobID,
  1058. })
  1059. if err != nil {
  1060. log.Error("GetVersionListTasks(%s) failed:%v", jobID, err.Error())
  1061. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  1062. return
  1063. }
  1064. //设置权限
  1065. canNewJob, err := canUserCreateTrainJobVersion(ctx, VersionListTasks[0].UserID)
  1066. if err != nil {
  1067. ctx.ServerError("canNewJob failed", err)
  1068. return
  1069. }
  1070. ctx.Data["canNewJob"] = canNewJob
  1071. //将运行参数转化为epoch_size = 3, device_target = Ascend的格式
  1072. for i, _ := range VersionListTasks {
  1073. var parameters models.Parameters
  1074. err := json.Unmarshal([]byte(VersionListTasks[i].Parameters), &parameters)
  1075. if err != nil {
  1076. log.Error("Failed to Unmarshal Parameters: %s (%v)", VersionListTasks[i].Parameters, err)
  1077. trainJobNewDataPrepare(ctx)
  1078. return
  1079. }
  1080. if len(parameters.Parameter) > 0 {
  1081. paramTemp := ""
  1082. for _, Parameter := range parameters.Parameter {
  1083. param := Parameter.Label + " = " + Parameter.Value + "; "
  1084. paramTemp = paramTemp + param
  1085. }
  1086. VersionListTasks[i].Parameters = paramTemp[:len(paramTemp)-2]
  1087. } else {
  1088. VersionListTasks[i].Parameters = ""
  1089. }
  1090. }
  1091. pager := context.NewPagination(VersionListCount, setting.UI.IssuePagingNum, page, 5)
  1092. pager.SetDefaultParams(ctx)
  1093. ctx.Data["Page"] = pager
  1094. ctx.Data["jobID"] = jobID
  1095. ctx.Data["jobName"] = VersionListTasks[0].JobName
  1096. ctx.Data["version_list_task"] = VersionListTasks
  1097. ctx.Data["version_list_count"] = VersionListCount
  1098. ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  1099. }
  1100. func TrainJobGetLog(ctx *context.Context) {
  1101. ctx.Data["PageIsTrainJob"] = true
  1102. var jobID = ctx.Params(":jobid")
  1103. var logFileName = ctx.Query("file_name")
  1104. var baseLine = ctx.Query("base_line")
  1105. var order = ctx.Query("order")
  1106. if order != modelarts.OrderDesc && order != modelarts.OrderAsc {
  1107. log.Error("order(%s) check failed", order)
  1108. ctx.HTML(http.StatusBadRequest, tplModelArtsTrainJobShow)
  1109. return
  1110. }
  1111. task, err := models.GetCloudbrainByJobID(jobID)
  1112. if err != nil {
  1113. log.Error("GetCloudbrainByJobID(%s) failed:%v", jobID, err.Error())
  1114. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  1115. return
  1116. }
  1117. result, err := modelarts.GetTrainJobLog(jobID, strconv.FormatInt(task.VersionID, 10), baseLine, logFileName, order, modelarts.Lines)
  1118. if err != nil {
  1119. log.Error("GetTrainJobLog(%s) failed:%v", jobID, err.Error())
  1120. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  1121. return
  1122. }
  1123. ctx.Data["log"] = result
  1124. //ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  1125. }
  1126. func trainJobGetLog(jobID string) (*models.GetTrainJobLogFileNamesResult, *models.GetTrainJobLogResult, error) {
  1127. task, err := models.GetCloudbrainByJobID(jobID)
  1128. if err != nil {
  1129. log.Error("GetCloudbrainByJobID(%s) failed:%v", jobID, err.Error())
  1130. return nil, nil, err
  1131. }
  1132. resultLogFile, err := modelarts.GetTrainJobLogFileNames(jobID, strconv.FormatInt(task.VersionID, 10))
  1133. if err != nil {
  1134. log.Error("GetTrainJobLogFileNames(%s) failed:%v", jobID, err.Error())
  1135. return nil, nil, err
  1136. }
  1137. result, err := modelarts.GetTrainJobLog(jobID, strconv.FormatInt(task.VersionID, 10), "", resultLogFile.LogFileList[0], modelarts.OrderDesc, modelarts.Lines)
  1138. if err != nil {
  1139. log.Error("GetTrainJobLog(%s) failed:%v", jobID, err.Error())
  1140. return nil, nil, err
  1141. }
  1142. return resultLogFile, result, err
  1143. }
  1144. func TrainJobDel(ctx *context.Context) {
  1145. var jobID = ctx.Params(":jobid")
  1146. repo := ctx.Repo.Repository
  1147. VersionListTasks, _, err := models.CloudbrainsVersionList(&models.CloudbrainsOptions{
  1148. RepoID: repo.ID,
  1149. Type: models.TypeCloudBrainTwo,
  1150. JobType: string(models.JobTypeTrain),
  1151. JobID: jobID,
  1152. })
  1153. if err != nil {
  1154. ctx.ServerError("get VersionListTasks failed", err)
  1155. return
  1156. }
  1157. //删除modelarts上的任务记录
  1158. _, err = modelarts.DelTrainJob(jobID)
  1159. if err != nil {
  1160. log.Error("DelTrainJob(%s) failed:%v", jobID, err.Error())
  1161. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  1162. return
  1163. }
  1164. //删除数据库Cloudbrain表的记录
  1165. for _, task := range VersionListTasks {
  1166. err = models.DeleteJob(&task.Cloudbrain)
  1167. if err != nil {
  1168. ctx.ServerError("DeleteJob failed", err)
  1169. return
  1170. }
  1171. }
  1172. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  1173. }
  1174. func TrainJobStop(ctx *context.Context) {
  1175. var jobID = ctx.Params(":jobid")
  1176. task, err := models.GetCloudbrainByJobID(jobID)
  1177. if err != nil {
  1178. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  1179. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  1180. return
  1181. }
  1182. _, err = modelarts.StopTrainJob(jobID, strconv.FormatInt(task.VersionID, 10))
  1183. if err != nil {
  1184. log.Error("StopTrainJob(%s) failed:%v", task.JobName, err.Error())
  1185. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  1186. return
  1187. }
  1188. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  1189. }
  1190. func canUserCreateTrainJob(uid int64) (bool, error) {
  1191. org, err := models.GetOrgByName(setting.AllowedOrg)
  1192. if err != nil {
  1193. log.Error("get allowed org failed: ", setting.AllowedOrg)
  1194. return false, err
  1195. }
  1196. return org.IsOrgMember(uid)
  1197. }
  1198. func canUserCreateTrainJobVersion(ctx *context.Context, userID int64) (bool, error) {
  1199. if ctx == nil || ctx.User == nil {
  1200. log.Error("user unlogin!")
  1201. return false, nil
  1202. }
  1203. if userID == ctx.User.ID || ctx.User.IsAdmin {
  1204. return true, nil
  1205. } else {
  1206. log.Error("Only user itself and admin can new trainjob!")
  1207. return false, nil
  1208. }
  1209. }
  1210. func TrainJobGetConfigList(ctx *context.Context) {
  1211. ctx.Data["PageIsTrainJob"] = true
  1212. var jobID = ctx.Params(":jobid")
  1213. var logFileName = ctx.Query("file_name")
  1214. var baseLine = ctx.Query("base_line")
  1215. var order = ctx.Query("order")
  1216. if order != modelarts.OrderDesc && order != modelarts.OrderAsc {
  1217. log.Error("order(%s) check failed", order)
  1218. ctx.HTML(http.StatusBadRequest, tplModelArtsTrainJobShow)
  1219. return
  1220. }
  1221. task, err := models.GetCloudbrainByJobID(jobID)
  1222. if err != nil {
  1223. log.Error("GetCloudbrainByJobID(%s) failed:%v", jobID, err.Error())
  1224. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  1225. return
  1226. }
  1227. result, err := modelarts.GetTrainJobLog(jobID, strconv.FormatInt(task.VersionID, 10), baseLine, logFileName, order, modelarts.Lines)
  1228. if err != nil {
  1229. log.Error("GetTrainJobLog(%s) failed:%v", jobID, err.Error())
  1230. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  1231. return
  1232. }
  1233. ctx.Data["log"] = result
  1234. //ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  1235. }
  1236. func getConfigList(perPage, page int, sortBy, order, searchContent, configType string) (*models.GetConfigListResult, error) {
  1237. var result models.GetConfigListResult
  1238. list, err := modelarts.GetConfigList(perPage, page, sortBy, order, searchContent, configType)
  1239. if err != nil {
  1240. log.Error("GetConfigList failed:", err)
  1241. return &result, err
  1242. }
  1243. for _, config := range list.ParaConfigs {
  1244. paraConfig, err := modelarts.GetParaConfig(config.ConfigName, configType)
  1245. if err != nil {
  1246. log.Error("GetParaConfig failed:", err)
  1247. return &result, err
  1248. }
  1249. config.Result = paraConfig
  1250. }
  1251. return list, nil
  1252. }
  1253. func ModelDownload(ctx *context.Context) {
  1254. var (
  1255. err error
  1256. )
  1257. var jobID = ctx.Params(":jobid")
  1258. versionName := ctx.Query("version_name")
  1259. parentDir := ctx.Query("parent_dir")
  1260. fileName := ctx.Query("file_name")
  1261. log.Info("DownloadSingleModelFile start.")
  1262. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  1263. if err != nil {
  1264. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  1265. return
  1266. }
  1267. path := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, task.JobName, setting.OutPutPath, versionName, parentDir, fileName), "/")
  1268. log.Info("Download path is:%s", path)
  1269. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  1270. if err != nil {
  1271. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  1272. ctx.ServerError("GetObsCreateSignedUrl", err)
  1273. return
  1274. }
  1275. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  1276. }