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