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 82 kB

4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545
  1. package repo
  2. import (
  3. "archive/zip"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "path"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "unicode/utf8"
  16. "code.gitea.io/gitea/modules/notification"
  17. "code.gitea.io/gitea/modules/timeutil"
  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/cloudbrain"
  22. "code.gitea.io/gitea/modules/context"
  23. "code.gitea.io/gitea/modules/git"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/modelarts"
  26. "code.gitea.io/gitea/modules/obs"
  27. "code.gitea.io/gitea/modules/setting"
  28. "code.gitea.io/gitea/modules/storage"
  29. "code.gitea.io/gitea/modules/util"
  30. )
  31. const (
  32. tplDebugJobIndex base.TplName = "repo/debugjob/index"
  33. tplModelArtsNotebookIndex base.TplName = "repo/modelarts/notebook/index"
  34. tplModelArtsNotebookNew base.TplName = "repo/modelarts/notebook/new"
  35. tplModelArtsNotebookShow base.TplName = "repo/modelarts/notebook/show"
  36. tplModelArtsTrainJobIndex base.TplName = "repo/modelarts/trainjob/index"
  37. tplModelArtsTrainJobNew base.TplName = "repo/modelarts/trainjob/new"
  38. tplModelArtsTrainJobShow base.TplName = "repo/modelarts/trainjob/show"
  39. tplModelArtsTrainJobVersionNew base.TplName = "repo/modelarts/trainjob/version_new"
  40. tplModelArtsInferenceJobIndex base.TplName = "repo/modelarts/inferencejob/index"
  41. tplModelArtsInferenceJobNew base.TplName = "repo/modelarts/inferencejob/new"
  42. tplModelArtsInferenceJobShow base.TplName = "repo/modelarts/inferencejob/show"
  43. )
  44. func DebugJobIndex(ctx *context.Context) {
  45. listType := ctx.Query("debugListType")
  46. if listType == "" {
  47. listType = models.AllResource
  48. }
  49. ctx.Data["ListType"] = listType
  50. MustEnableCloudbrain(ctx)
  51. repo := ctx.Repo.Repository
  52. page := ctx.QueryInt("page")
  53. if page <= 0 {
  54. page = 1
  55. }
  56. typeCloudBrain := models.TypeCloudBrainAll
  57. jobTypeNot := false
  58. if listType == models.GPUResource {
  59. typeCloudBrain = models.TypeCloudBrainOne
  60. } else if listType == models.NPUResource {
  61. typeCloudBrain = models.TypeCloudBrainTwo
  62. } else if listType == models.AllResource {
  63. typeCloudBrain = models.TypeCloudBrainAll
  64. } else {
  65. log.Error("listType(%s) error", listType)
  66. ctx.ServerError("listType error", errors.New("listType error"))
  67. return
  68. }
  69. var jobTypes []string
  70. jobTypes = append(jobTypes, string(models.JobTypeDebug))
  71. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  72. ListOptions: models.ListOptions{
  73. Page: page,
  74. PageSize: setting.UI.IssuePagingNum,
  75. },
  76. RepoID: repo.ID,
  77. Type: typeCloudBrain,
  78. JobTypeNot: jobTypeNot,
  79. JobTypes: jobTypes,
  80. })
  81. if err != nil {
  82. ctx.ServerError("Get debugjob faild:", err)
  83. return
  84. }
  85. for i, task := range ciTasks {
  86. ciTasks[i].CanDebug = cloudbrain.CanModifyJob(ctx, &task.Cloudbrain)
  87. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  88. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  89. }
  90. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  91. pager.AddParam(ctx, "debugListType", "ListType")
  92. ctx.Data["Page"] = pager
  93. ctx.Data["PageIsCloudBrain"] = true
  94. ctx.Data["Tasks"] = ciTasks
  95. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  96. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  97. ctx.Data["debugListType"] = listType
  98. ctx.HTML(200, tplDebugJobIndex)
  99. }
  100. // MustEnableDataset check if repository enable internal cb
  101. func MustEnableModelArts(ctx *context.Context) {
  102. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  103. ctx.NotFound("MustEnableCloudbrain", nil)
  104. return
  105. }
  106. }
  107. func NotebookNew(ctx *context.Context) {
  108. notebookNewDataPrepare(ctx)
  109. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  110. ctx.Data["WaitCount"] = waitCount
  111. ctx.HTML(200, tplModelArtsNotebookNew)
  112. }
  113. func notebookNewDataPrepare(ctx *context.Context) error {
  114. ctx.Data["PageIsCloudBrain"] = true
  115. t := time.Now()
  116. var displayJobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  117. ctx.Data["display_job_name"] = displayJobName
  118. attachs, err := models.GetModelArtsUserAttachments(ctx.User.ID)
  119. if err != nil {
  120. ctx.ServerError("GetAllUserAttachments failed:", err)
  121. return err
  122. }
  123. ctx.Data["attachments"] = attachs
  124. if modelarts.ImageInfos == nil {
  125. json.Unmarshal([]byte(setting.ImageInfos), &modelarts.ImageInfos)
  126. }
  127. ctx.Data["images"] = modelarts.ImageInfos.ImageInfo
  128. if modelarts.FlavorInfos == nil {
  129. json.Unmarshal([]byte(setting.FlavorInfos), &modelarts.FlavorInfos)
  130. }
  131. ctx.Data["flavors"] = modelarts.FlavorInfos.FlavorInfo
  132. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  133. return nil
  134. }
  135. func NotebookCreate(ctx *context.Context, form auth.CreateModelArtsNotebookForm) {
  136. ctx.Data["PageIsNotebook"] = true
  137. jobName := form.JobName
  138. uuid := form.Attachment
  139. description := form.Description
  140. flavor := form.Flavor
  141. count, err := models.GetCloudbrainNotebookCountByUserID(ctx.User.ID)
  142. if err != nil {
  143. log.Error("GetCloudbrainNotebookCountByUserID failed:%v", err, ctx.Data["MsgID"])
  144. cloudBrainNewDataPrepare(ctx)
  145. ctx.RenderWithErr("system error", tplModelArtsNotebookNew, &form)
  146. return
  147. } else {
  148. if count >= 1 {
  149. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  150. cloudBrainNewDataPrepare(ctx)
  151. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplModelArtsNotebookNew, &form)
  152. return
  153. }
  154. }
  155. _, err = models.GetCloudbrainByName(jobName)
  156. if err == nil {
  157. log.Error("the job name did already exist", ctx.Data["MsgID"])
  158. cloudBrainNewDataPrepare(ctx)
  159. ctx.RenderWithErr("the job name did already exist", tplModelArtsNotebookNew, &form)
  160. return
  161. } else {
  162. if !models.IsErrJobNotExist(err) {
  163. log.Error("system error, %v", err, ctx.Data["MsgID"])
  164. cloudBrainNewDataPrepare(ctx)
  165. ctx.RenderWithErr("system error", tplModelArtsNotebookNew, &form)
  166. return
  167. }
  168. }
  169. err = modelarts.GenerateTask(ctx, jobName, uuid, description, flavor)
  170. if err != nil {
  171. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookNew, &form)
  172. return
  173. }
  174. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  175. }
  176. func Notebook2Create(ctx *context.Context, form auth.CreateModelArtsNotebookForm) {
  177. ctx.Data["PageIsNotebook"] = true
  178. displayJobName := form.DisplayJobName
  179. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  180. uuid := form.Attachment
  181. description := form.Description
  182. flavor := form.Flavor
  183. imageId := form.ImageId
  184. repo := ctx.Repo.Repository
  185. count, err := models.GetCloudbrainNotebookCountByUserID(ctx.User.ID)
  186. if err != nil {
  187. log.Error("GetCloudbrainNotebookCountByUserID failed:%v", err, ctx.Data["MsgID"])
  188. notebookNewDataPrepare(ctx)
  189. ctx.RenderWithErr("system error", tplModelArtsNotebookNew, &form)
  190. return
  191. } else {
  192. if count >= 1 {
  193. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  194. notebookNewDataPrepare(ctx)
  195. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplModelArtsNotebookNew, &form)
  196. return
  197. }
  198. }
  199. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeDebug), displayJobName)
  200. if err == nil {
  201. if len(tasks) != 0 {
  202. log.Error("the job name did already exist", ctx.Data["MsgID"])
  203. notebookNewDataPrepare(ctx)
  204. ctx.RenderWithErr("the job name did already exist", tplModelArtsNotebookNew, &form)
  205. return
  206. }
  207. } else {
  208. if !models.IsErrJobNotExist(err) {
  209. log.Error("system error, %v", err, ctx.Data["MsgID"])
  210. notebookNewDataPrepare(ctx)
  211. ctx.RenderWithErr("system error", tplModelArtsNotebookNew, &form)
  212. return
  213. }
  214. }
  215. err = modelarts.GenerateNotebook2(ctx, displayJobName, jobName, uuid, description, flavor, imageId)
  216. if err != nil {
  217. log.Error("GenerateNotebook2 failed, %v", err, ctx.Data["MsgID"])
  218. notebookNewDataPrepare(ctx)
  219. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookNew, &form)
  220. return
  221. }
  222. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  223. }
  224. func NotebookShow(ctx *context.Context) {
  225. ctx.Data["PageIsCloudBrain"] = true
  226. debugListType := ctx.Query("debugListType")
  227. if debugListType == "" {
  228. debugListType = "all"
  229. }
  230. var ID = ctx.Params(":id")
  231. task, err := models.GetCloudbrainByIDWithDeleted(ID)
  232. if err != nil {
  233. ctx.Data["error"] = err.Error()
  234. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookShow, nil)
  235. return
  236. }
  237. result, err := modelarts.GetNotebook2(task.JobID)
  238. if err != nil {
  239. ctx.Data["error"] = err.Error()
  240. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookShow, nil)
  241. return
  242. }
  243. if result != nil {
  244. if task.DeletedAt.IsZero() { //normal record
  245. if task.Status != result.Status {
  246. task.Status = result.Status
  247. models.ParseAndSetDurationFromModelArtsNotebook(result, task)
  248. err = models.UpdateJob(task)
  249. if err != nil {
  250. ctx.Data["error"] = err.Error()
  251. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookShow, nil)
  252. return
  253. }
  254. }
  255. } else { //deleted record
  256. }
  257. }
  258. datasetDownload := make([]models.DatasetDownload, 0)
  259. if ctx.IsSigned {
  260. if task.Uuid != "" && task.UserID == ctx.User.ID {
  261. uuidList := strings.Split(task.Uuid, ";")
  262. for _, uuidStr := range uuidList {
  263. attachment, err := models.GetAttachmentByUUID(uuidStr)
  264. if err != nil {
  265. log.Error("GetAttachmentByUUID failed:%v", err.Error())
  266. return
  267. }
  268. dataset, err := models.GetDatasetByID(attachment.DatasetID)
  269. if err != nil {
  270. log.Error("GetDatasetByID failed:%v", err.Error())
  271. return
  272. }
  273. repo, err := models.GetRepositoryByID(dataset.RepoID)
  274. if err != nil {
  275. log.Error("GetRepositoryByID failed:%v", err.Error())
  276. return
  277. }
  278. datasetDownload = append(datasetDownload, models.DatasetDownload{
  279. DatasetName: attachment.Name,
  280. DatasetDownloadLink: attachment.S3DownloadURL(),
  281. RepositoryLink: repo.Link() + "/datasets",
  282. })
  283. }
  284. // datasetName, err := GetDatasetNameByUUID(task.Uuid)
  285. // if err == nil {
  286. // task.DatasetName = datasetName
  287. // }
  288. }
  289. }
  290. user, err := models.GetUserByID(task.UserID)
  291. if err == nil {
  292. task.User = user
  293. }
  294. if modelarts.FlavorInfos == nil {
  295. json.Unmarshal([]byte(setting.FlavorInfos), &modelarts.FlavorInfos)
  296. }
  297. if modelarts.FlavorInfos != nil {
  298. ctx.Data["resource_spec"] = modelarts.FlavorInfos.FlavorInfo[0].Desc
  299. for _, f := range modelarts.FlavorInfos.FlavorInfo {
  300. if fmt.Sprint(f.Value) == task.FlavorCode {
  301. ctx.Data["resource_spec"] = f.Desc
  302. break
  303. }
  304. }
  305. }
  306. if task.TrainJobDuration == "" {
  307. if task.Duration == 0 {
  308. var duration int64
  309. if task.Status == string(models.JobRunning) {
  310. duration = time.Now().Unix() - int64(task.CreatedUnix)
  311. } else {
  312. duration = int64(task.UpdatedUnix) - int64(task.CreatedUnix)
  313. }
  314. task.Duration = duration
  315. }
  316. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  317. }
  318. ctx.Data["duration"] = task.TrainJobDuration
  319. ctx.Data["datasetDownload"] = datasetDownload
  320. ctx.Data["task"] = task
  321. ctx.Data["ID"] = ID
  322. ctx.Data["jobName"] = task.JobName
  323. ctx.Data["debugListType"] = debugListType
  324. ctx.HTML(200, tplModelArtsNotebookShow)
  325. }
  326. func NotebookDebug(ctx *context.Context) {
  327. var jobID = ctx.Params(":jobid")
  328. result, err := modelarts.GetJob(jobID)
  329. if err != nil {
  330. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  331. return
  332. }
  333. res, err := modelarts.GetJobToken(jobID)
  334. if err != nil {
  335. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  336. return
  337. }
  338. urls := strings.Split(result.Spec.Annotations.Url, "/")
  339. urlPrefix := result.Spec.Annotations.TargetDomain
  340. for i, url := range urls {
  341. if i > 2 {
  342. urlPrefix += "/" + url
  343. }
  344. }
  345. debugUrl := urlPrefix + "?token=" + res.Token
  346. ctx.Redirect(debugUrl)
  347. }
  348. func NotebookDebug2(ctx *context.Context) {
  349. task := ctx.Cloudbrain
  350. result, err := modelarts.GetNotebook2(task.JobID)
  351. if err != nil {
  352. ctx.RenderWithErr(err.Error(), tplModelArtsNotebookIndex, nil)
  353. return
  354. }
  355. ctx.Redirect(result.Url + "?token=" + result.Token)
  356. }
  357. func NotebookManage(ctx *context.Context) {
  358. var ID = ctx.Params(":id")
  359. var action = ctx.Params(":action")
  360. var resultCode = "0"
  361. var errorMsg = ""
  362. var status = ""
  363. for {
  364. task, err := models.GetCloudbrainByID(ID)
  365. if err != nil {
  366. log.Error("get task(%s) failed:%v", task.JobName, err.Error(), ctx.Data["MsgID"])
  367. resultCode = "-1"
  368. errorMsg = "system error"
  369. break
  370. }
  371. if action == models.ActionStop {
  372. if task.Status != string(models.ModelArtsRunning) {
  373. log.Error("the job(%s) is not running", task.JobName, ctx.Data["MsgID"])
  374. resultCode = "-1"
  375. errorMsg = "the job is not running"
  376. break
  377. }
  378. if !ctx.IsSigned || (ctx.User.ID != task.UserID && !ctx.IsUserSiteAdmin() && !ctx.IsUserRepoOwner()) {
  379. log.Error("the user has no right ro stop the job", task.JobName, ctx.Data["MsgID"])
  380. resultCode = "-1"
  381. errorMsg = "you have no right to stop the job"
  382. break
  383. }
  384. } else if action == models.ActionRestart {
  385. ctx.CheckWechatBind()
  386. if ctx.Written() {
  387. return
  388. }
  389. if task.Status != string(models.ModelArtsStopped) && task.Status != string(models.ModelArtsStartFailed) && task.Status != string(models.ModelArtsCreateFailed) {
  390. log.Error("the job(%s) is not stopped", task.JobName, ctx.Data["MsgID"])
  391. resultCode = "-1"
  392. errorMsg = "the job is not stopped"
  393. break
  394. }
  395. if !ctx.IsSigned || (ctx.User.ID != task.UserID && !ctx.IsUserSiteAdmin()) {
  396. log.Error("the user has no right ro restart the job", task.JobName, ctx.Data["MsgID"])
  397. resultCode = "-1"
  398. errorMsg = "you have no right to restart the job"
  399. break
  400. }
  401. count, err := models.GetCloudbrainNotebookCountByUserID(ctx.User.ID)
  402. if err != nil {
  403. log.Error("GetCloudbrainNotebookCountByUserID failed:%v", err, ctx.Data["MsgID"])
  404. resultCode = "-1"
  405. errorMsg = "system error"
  406. break
  407. } else {
  408. if count >= 1 {
  409. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  410. resultCode = "-1"
  411. errorMsg = "you have already a running or waiting task, can not create more"
  412. break
  413. }
  414. }
  415. action = models.ActionStart
  416. } else {
  417. log.Error("the action(%s) is illegal", action, ctx.Data["MsgID"])
  418. resultCode = "-1"
  419. errorMsg = "非法操作"
  420. break
  421. }
  422. param := models.NotebookAction{
  423. Action: action,
  424. }
  425. createTime := timeutil.TimeStampNow()
  426. res, err := modelarts.ManageNotebook2(task.JobID, param)
  427. if err != nil {
  428. log.Error("ManageNotebook2(%s) failed:%v", task.JobName, err.Error(), ctx.Data["MsgID"])
  429. resultCode = "-1"
  430. errorMsg = err.Error()
  431. if strings.Contains(err.Error(), modelarts.NotebookNotFound) {
  432. errorMsg = "the job's version is too old and can not be restarted"
  433. }
  434. break
  435. }
  436. status = res.Status
  437. if action == models.ActionStart {
  438. newTask := &models.Cloudbrain{
  439. Status: status,
  440. UserID: task.UserID,
  441. RepoID: task.RepoID,
  442. JobID: task.JobID,
  443. JobName: task.JobName,
  444. DisplayJobName: task.DisplayJobName,
  445. JobType: task.JobType,
  446. Type: task.Type,
  447. Uuid: task.Uuid,
  448. Image: task.Image,
  449. ComputeResource: task.ComputeResource,
  450. Description: task.Description,
  451. CreatedUnix: createTime,
  452. UpdatedUnix: createTime,
  453. }
  454. err = models.RestartCloudbrain(task, newTask)
  455. if err != nil {
  456. log.Error("RestartCloudbrain(%s) failed:%v", task.JobName, err.Error(), ctx.Data["MsgID"])
  457. resultCode = "-1"
  458. errorMsg = "system error"
  459. break
  460. }
  461. ID = strconv.FormatInt(newTask.ID, 10)
  462. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, ID, task.DisplayJobName, models.ActionCreateDebugNPUTask)
  463. } else {
  464. task.Status = res.Status
  465. if task.EndTime == 0 && models.IsModelArtsDebugJobTerminal(task.Status) {
  466. task.EndTime = timeutil.TimeStampNow()
  467. }
  468. task.ComputeAndSetDuration()
  469. err = models.UpdateJob(task)
  470. if err != nil {
  471. log.Error("UpdateJob(%s) failed:%v", task.JobName, err.Error(), ctx.Data["MsgID"])
  472. resultCode = "-1"
  473. errorMsg = "system error"
  474. break
  475. }
  476. }
  477. break
  478. }
  479. ctx.JSON(200, map[string]string{
  480. "result_code": resultCode,
  481. "error_msg": errorMsg,
  482. "status": status,
  483. "id": ID,
  484. })
  485. }
  486. func NotebookDel(ctx *context.Context) {
  487. var listType = ctx.Query("debugListType")
  488. task := ctx.Cloudbrain
  489. if task.Status != string(models.ModelArtsCreateFailed) && task.Status != string(models.ModelArtsStartFailed) && task.Status != string(models.ModelArtsStopped) {
  490. log.Error("the job(%s) has not been stopped", task.JobName)
  491. ctx.RenderWithErr("the job has not been stopped", tplDebugJobIndex, nil)
  492. return
  493. }
  494. _, err := modelarts.DelNotebook2(task.JobID)
  495. if err != nil {
  496. log.Error("DelNotebook2(%s) failed:%v", task.JobName, err.Error())
  497. if strings.Contains(err.Error(), modelarts.NotebookNotFound) || strings.Contains(err.Error(), modelarts.NotebookNoPermission) || strings.Contains(err.Error(), modelarts.NotebookInvalid) {
  498. log.Info("old notebook version")
  499. } else {
  500. ctx.RenderWithErr(err.Error(), tplDebugJobIndex, nil)
  501. return
  502. }
  503. }
  504. err = models.DeleteJob(task)
  505. if err != nil {
  506. ctx.RenderWithErr(err.Error(), tplDebugJobIndex, nil)
  507. return
  508. }
  509. var isAdminPage = ctx.Query("isadminpage")
  510. var isHomePage = ctx.Query("ishomepage")
  511. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  512. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  513. } else if isHomePage == "true" {
  514. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  515. } else {
  516. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  517. }
  518. }
  519. func TrainJobIndex(ctx *context.Context) {
  520. MustEnableModelArts(ctx)
  521. repo := ctx.Repo.Repository
  522. page := ctx.QueryInt("page")
  523. if page <= 0 {
  524. page = 1
  525. }
  526. listType := ctx.Query("listType")
  527. ctx.Data["ListType"] = listType
  528. if listType == models.AllResource {
  529. listType = ""
  530. }
  531. var jobTypes []string
  532. jobTypes = append(jobTypes, string(models.JobTypeTrain))
  533. tasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  534. ListOptions: models.ListOptions{
  535. Page: page,
  536. PageSize: setting.UI.IssuePagingNum,
  537. },
  538. RepoID: repo.ID,
  539. JobTypeNot: false,
  540. JobTypes: jobTypes,
  541. IsLatestVersion: modelarts.IsLatestVersion,
  542. ComputeResource: listType,
  543. Type: models.TypeCloudBrainAll,
  544. })
  545. if err != nil {
  546. ctx.ServerError("Cloudbrain", err)
  547. return
  548. }
  549. for i, task := range tasks {
  550. tasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  551. tasks[i].CanModify = cloudbrain.CanModifyJob(ctx, &task.Cloudbrain)
  552. }
  553. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  554. pager.SetDefaultParams(ctx)
  555. pager.AddParam(ctx, "listType", "ListType")
  556. ctx.Data["Page"] = pager
  557. ctx.Data["PageIsCloudBrain"] = true
  558. ctx.Data["Tasks"] = tasks
  559. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  560. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  561. ctx.HTML(200, tplModelArtsTrainJobIndex)
  562. }
  563. func TrainJobNew(ctx *context.Context) {
  564. err := trainJobNewDataPrepare(ctx)
  565. if err != nil {
  566. ctx.ServerError("get new train-job info failed", err)
  567. return
  568. }
  569. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  570. ctx.Data["WaitCount"] = waitCount
  571. ctx.HTML(200, tplModelArtsTrainJobNew)
  572. }
  573. func trainJobNewDataPrepare(ctx *context.Context) error {
  574. ctx.Data["PageIsCloudBrain"] = true
  575. //can, err := canUserCreateTrainJob(ctx.User.ID)
  576. //if err != nil {
  577. // ctx.ServerError("canUserCreateTrainJob", err)
  578. // return
  579. //}
  580. //
  581. //if !can {
  582. // log.Error("the user can not create train-job")
  583. // ctx.ServerError("the user can not create train-job", fmt.Errorf("the user can not create train-job"))
  584. // return
  585. //}
  586. t := time.Now()
  587. var displayJobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  588. ctx.Data["display_job_name"] = displayJobName
  589. attachs, err := models.GetModelArtsTrainAttachments(ctx.User.ID)
  590. if err != nil {
  591. ctx.ServerError("GetAllUserAttachments failed:", err)
  592. return err
  593. }
  594. ctx.Data["attachments"] = attachs
  595. var resourcePools modelarts.ResourcePool
  596. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  597. ctx.ServerError("json.Unmarshal failed:", err)
  598. return err
  599. }
  600. ctx.Data["resource_pools"] = resourcePools.Info
  601. var engines modelarts.Engine
  602. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  603. ctx.ServerError("json.Unmarshal failed:", err)
  604. return err
  605. }
  606. ctx.Data["engines"] = engines.Info
  607. var versionInfos modelarts.VersionInfo
  608. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  609. ctx.ServerError("json.Unmarshal failed:", err)
  610. return err
  611. }
  612. ctx.Data["engine_versions"] = versionInfos.Version
  613. var flavorInfos modelarts.Flavor
  614. if err = json.Unmarshal([]byte(setting.TrainJobFLAVORINFOS), &flavorInfos); err != nil {
  615. ctx.ServerError("json.Unmarshal failed:", err)
  616. return err
  617. }
  618. ctx.Data["flavor_infos"] = flavorInfos.Info
  619. ctx.Data["params"] = ""
  620. ctx.Data["branchName"] = ctx.Repo.BranchName
  621. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  622. if err != nil {
  623. ctx.ServerError("getConfigList failed:", err)
  624. return err
  625. }
  626. ctx.Data["config_list"] = configList.ParaConfigs
  627. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  628. return nil
  629. }
  630. func trainJobErrorNewDataPrepare(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) error {
  631. ctx.Data["PageIsCloudBrain"] = true
  632. //can, err := canUserCreateTrainJob(ctx.User.ID)
  633. //if err != nil {
  634. // ctx.ServerError("canUserCreateTrainJob", err)
  635. // return
  636. //}
  637. //
  638. //if !can {
  639. // log.Error("the user can not create train-job")
  640. // ctx.ServerError("the user can not create train-job", fmt.Errorf("the user can not create train-job"))
  641. // return
  642. //}
  643. t := time.Now()
  644. var displayJobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  645. ctx.Data["display_job_name"] = displayJobName
  646. attachs, err := models.GetModelArtsTrainAttachments(ctx.User.ID)
  647. if err != nil {
  648. ctx.ServerError("GetAllUserAttachments failed:", err)
  649. return err
  650. }
  651. ctx.Data["attachments"] = attachs
  652. var resourcePools modelarts.ResourcePool
  653. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  654. ctx.ServerError("json.Unmarshal failed:", err)
  655. return err
  656. }
  657. ctx.Data["resource_pools"] = resourcePools.Info
  658. var engines modelarts.Engine
  659. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  660. ctx.ServerError("json.Unmarshal failed:", err)
  661. return err
  662. }
  663. ctx.Data["engines"] = engines.Info
  664. var versionInfos modelarts.VersionInfo
  665. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  666. ctx.ServerError("json.Unmarshal failed:", err)
  667. return err
  668. }
  669. ctx.Data["engine_versions"] = versionInfos.Version
  670. var flavorInfos modelarts.Flavor
  671. if err = json.Unmarshal([]byte(setting.TrainJobFLAVORINFOS), &flavorInfos); err != nil {
  672. ctx.ServerError("json.Unmarshal failed:", err)
  673. return err
  674. }
  675. ctx.Data["flavor_infos"] = flavorInfos.Info
  676. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  677. if err != nil {
  678. ctx.ServerError("getConfigList failed:", err)
  679. return err
  680. }
  681. var Parameters modelarts.Parameters
  682. if err = json.Unmarshal([]byte(form.Params), &Parameters); err != nil {
  683. ctx.ServerError("json.Unmarshal failed:", err)
  684. return err
  685. }
  686. ctx.Data["params"] = Parameters.Parameter
  687. ctx.Data["config_list"] = configList.ParaConfigs
  688. ctx.Data["bootFile"] = form.BootFile
  689. ctx.Data["uuid"] = form.Attachment
  690. ctx.Data["branch_name"] = form.BranchName
  691. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  692. return nil
  693. }
  694. func TrainJobNewVersion(ctx *context.Context) {
  695. err := trainJobNewVersionDataPrepare(ctx)
  696. if err != nil {
  697. ctx.ServerError("get new train-job info failed", err)
  698. return
  699. }
  700. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  701. ctx.Data["WaitCount"] = waitCount
  702. ctx.HTML(200, tplModelArtsTrainJobVersionNew)
  703. }
  704. func trainJobNewVersionDataPrepare(ctx *context.Context) error {
  705. ctx.Data["PageIsCloudBrain"] = true
  706. var jobID = ctx.Params(":jobid")
  707. var versionName = ctx.Query("version_name")
  708. // canNewJob, err := canUserCreateTrainJobVersion(ctx, jobID, versionName)
  709. // if err != nil {
  710. // ctx.ServerError("canNewJob can info failed", err)
  711. // return err
  712. // }
  713. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  714. if err != nil {
  715. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", jobID, err.Error())
  716. return err
  717. }
  718. ctx.Data["display_job_name"] = task.DisplayJobName
  719. ctx.Data["job_name"] = task.JobName
  720. attachs, err := models.GetModelArtsTrainAttachments(ctx.User.ID)
  721. if err != nil {
  722. ctx.ServerError("GetAllUserAttachments failed:", err)
  723. return err
  724. }
  725. ctx.Data["attachments"] = attachs
  726. var resourcePools modelarts.ResourcePool
  727. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  728. ctx.ServerError("json.Unmarshal failed:", err)
  729. return err
  730. }
  731. ctx.Data["resource_pools"] = resourcePools.Info
  732. var engines modelarts.Engine
  733. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  734. ctx.ServerError("json.Unmarshal failed:", err)
  735. return err
  736. }
  737. ctx.Data["engines"] = engines.Info
  738. var versionInfos modelarts.VersionInfo
  739. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  740. ctx.ServerError("json.Unmarshal failed:", err)
  741. return err
  742. }
  743. ctx.Data["engine_versions"] = versionInfos.Version
  744. var flavorInfos modelarts.Flavor
  745. if err = json.Unmarshal([]byte(setting.TrainJobFLAVORINFOS), &flavorInfos); err != nil {
  746. ctx.ServerError("json.Unmarshal failed:", err)
  747. return err
  748. }
  749. ctx.Data["flavor_infos"] = flavorInfos.Info
  750. var Parameters modelarts.Parameters
  751. if err = json.Unmarshal([]byte(task.Parameters), &Parameters); err != nil {
  752. ctx.ServerError("json.Unmarshal failed:", err)
  753. return err
  754. }
  755. ctx.Data["params"] = Parameters.Parameter
  756. branches, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  757. if err != nil {
  758. ctx.ServerError("GetBranches error:", err)
  759. return err
  760. }
  761. ctx.Data["branches"] = branches
  762. ctx.Data["branch_name"] = task.BranchName
  763. ctx.Data["description"] = task.Description
  764. ctx.Data["boot_file"] = task.BootFile
  765. ctx.Data["dataset_name"] = task.DatasetName
  766. ctx.Data["work_server_number"] = task.WorkServerNumber
  767. ctx.Data["flavor_name"] = task.FlavorName
  768. ctx.Data["engine_name"] = task.EngineName
  769. ctx.Data["uuid"] = task.Uuid
  770. ctx.Data["flavor_code"] = task.FlavorCode
  771. ctx.Data["engine_id"] = task.EngineID
  772. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  773. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  774. if err != nil {
  775. ctx.ServerError("getConfigList failed:", err)
  776. return err
  777. }
  778. ctx.Data["config_list"] = configList.ParaConfigs
  779. return nil
  780. }
  781. func versionErrorDataPrepare(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) error {
  782. ctx.Data["PageIsCloudBrain"] = true
  783. var jobID = ctx.Params(":jobid")
  784. // var versionName = ctx.Params(":version-name")
  785. var versionName = ctx.Query("version_name")
  786. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  787. if err != nil {
  788. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", jobID, err.Error())
  789. return err
  790. }
  791. t := time.Now()
  792. var jobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  793. ctx.Data["job_name"] = task.JobName
  794. attachs, err := models.GetModelArtsTrainAttachments(ctx.User.ID)
  795. if err != nil {
  796. ctx.ServerError("GetAllUserAttachments failed:", err)
  797. return err
  798. }
  799. ctx.Data["attachments"] = attachs
  800. var resourcePools modelarts.ResourcePool
  801. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  802. ctx.ServerError("json.Unmarshal failed:", err)
  803. return err
  804. }
  805. ctx.Data["resource_pools"] = resourcePools.Info
  806. var engines modelarts.Engine
  807. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  808. ctx.ServerError("json.Unmarshal failed:", err)
  809. return err
  810. }
  811. ctx.Data["engines"] = engines.Info
  812. var versionInfos modelarts.VersionInfo
  813. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  814. ctx.ServerError("json.Unmarshal failed:", err)
  815. return err
  816. }
  817. ctx.Data["engine_versions"] = versionInfos.Version
  818. var flavorInfos modelarts.Flavor
  819. if err = json.Unmarshal([]byte(setting.TrainJobFLAVORINFOS), &flavorInfos); err != nil {
  820. ctx.ServerError("json.Unmarshal failed:", err)
  821. return err
  822. }
  823. ctx.Data["flavor_infos"] = flavorInfos.Info
  824. var Parameters modelarts.Parameters
  825. if err = json.Unmarshal([]byte(form.Params), &Parameters); err != nil {
  826. ctx.ServerError("json.Unmarshal failed:", err)
  827. return err
  828. }
  829. ctx.Data["params"] = Parameters.Parameter
  830. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath
  831. ctx.Data["train_url"] = outputObsPath
  832. branches, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  833. if err != nil {
  834. ctx.ServerError("GetBranches error:", err)
  835. return err
  836. }
  837. ctx.Data["branches"] = branches
  838. ctx.Data["description"] = form.Description
  839. ctx.Data["dataset_name"] = task.DatasetName
  840. ctx.Data["work_server_number"] = form.WorkServerNumber
  841. ctx.Data["flavor_name"] = form.FlavorName
  842. ctx.Data["engine_name"] = form.EngineName
  843. ctx.Data["flavor_code"] = task.FlavorCode
  844. ctx.Data["engine_id"] = task.EngineID
  845. ctx.Data["version_name"] = form.VersionName
  846. ctx.Data["bootFile"] = form.BootFile
  847. ctx.Data["uuid"] = form.Attachment
  848. ctx.Data["branch_name"] = form.BranchName
  849. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  850. if err != nil {
  851. ctx.ServerError("getConfigList failed:", err)
  852. return err
  853. }
  854. ctx.Data["config_list"] = configList.ParaConfigs
  855. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  856. return nil
  857. }
  858. func TrainJobCreate(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) {
  859. ctx.Data["PageIsTrainJob"] = true
  860. VersionOutputPath := modelarts.GetOutputPathByCount(modelarts.TotalVersionCount)
  861. displayJobName := form.DisplayJobName
  862. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  863. uuid := form.Attachment
  864. description := form.Description
  865. workServerNumber := form.WorkServerNumber
  866. engineID := form.EngineID
  867. bootFile := strings.TrimSpace(form.BootFile)
  868. flavorCode := form.Flavor
  869. params := form.Params
  870. poolID := form.PoolID
  871. isSaveParam := form.IsSaveParam
  872. repo := ctx.Repo.Repository
  873. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  874. codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath
  875. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath + VersionOutputPath + "/"
  876. logObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.LogPath + VersionOutputPath + "/"
  877. // dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/"
  878. branch_name := form.BranchName
  879. isLatestVersion := modelarts.IsLatestVersion
  880. FlavorName := form.FlavorName
  881. VersionCount := modelarts.VersionCount
  882. EngineName := form.EngineName
  883. count, err := models.GetCloudbrainTrainJobCountByUserID(ctx.User.ID)
  884. if err != nil {
  885. log.Error("GetCloudbrainTrainJobCountByUserID failed:%v", err, ctx.Data["MsgID"])
  886. trainJobErrorNewDataPrepare(ctx, form)
  887. ctx.RenderWithErr("system error", tplModelArtsTrainJobNew, &form)
  888. return
  889. } else {
  890. if count >= 1 {
  891. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  892. trainJobErrorNewDataPrepare(ctx, form)
  893. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplModelArtsTrainJobNew, &form)
  894. return
  895. }
  896. }
  897. if err := paramCheckCreateTrainJob(form); err != nil {
  898. log.Error("paramCheckCreateTrainJob failed:(%v)", err)
  899. trainJobErrorNewDataPrepare(ctx, form)
  900. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobNew, &form)
  901. return
  902. }
  903. //Determine whether the task name of the task in the project is duplicated
  904. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeTrain), displayJobName)
  905. if err == nil {
  906. if len(tasks) != 0 {
  907. log.Error("the job name did already exist", ctx.Data["MsgID"])
  908. trainJobErrorNewDataPrepare(ctx, form)
  909. ctx.RenderWithErr("the job name did already exist", tplModelArtsTrainJobNew, &form)
  910. return
  911. }
  912. } else {
  913. if !models.IsErrJobNotExist(err) {
  914. log.Error("system error, %v", err, ctx.Data["MsgID"])
  915. trainJobErrorNewDataPrepare(ctx, form)
  916. ctx.RenderWithErr("system error", tplModelArtsTrainJobNew, &form)
  917. return
  918. }
  919. }
  920. //todo: del the codeLocalPath
  921. _, err = ioutil.ReadDir(codeLocalPath)
  922. if err == nil {
  923. os.RemoveAll(codeLocalPath)
  924. }
  925. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  926. commitID, _ := gitRepo.GetBranchCommitID(branch_name)
  927. if err := downloadCode(repo, codeLocalPath, branch_name); err != nil {
  928. log.Error("downloadCode failed, server timed out: %s (%v)", repo.FullName(), err)
  929. trainJobErrorNewDataPrepare(ctx, form)
  930. ctx.RenderWithErr("Create task failed, server timed out", tplModelArtsTrainJobNew, &form)
  931. return
  932. }
  933. //todo: upload code (send to file_server todo this work?)
  934. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath + VersionOutputPath + "/"); err != nil {
  935. log.Error("Failed to obsMkdir_output: %s (%v)", repo.FullName(), err)
  936. trainJobErrorNewDataPrepare(ctx, form)
  937. ctx.RenderWithErr("Failed to obsMkdir_output", tplModelArtsTrainJobNew, &form)
  938. return
  939. }
  940. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.LogPath + VersionOutputPath + "/"); err != nil {
  941. log.Error("Failed to obsMkdir_log: %s (%v)", repo.FullName(), err)
  942. trainJobErrorNewDataPrepare(ctx, form)
  943. ctx.RenderWithErr("Failed to obsMkdir_log", tplModelArtsTrainJobNew, &form)
  944. return
  945. }
  946. // parentDir := VersionOutputPath + "/"
  947. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  948. // if err := uploadCodeToObs(codeLocalPath, jobName, parentDir); err != nil {
  949. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  950. trainJobErrorNewDataPrepare(ctx, form)
  951. ctx.RenderWithErr("Failed to uploadCodeToObs", tplModelArtsTrainJobNew, &form)
  952. return
  953. }
  954. var parameters models.Parameters
  955. param := make([]models.Parameter, 0)
  956. existDeviceTarget := false
  957. if len(params) != 0 {
  958. err := json.Unmarshal([]byte(params), &parameters)
  959. if err != nil {
  960. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  961. trainJobErrorNewDataPrepare(ctx, form)
  962. ctx.RenderWithErr("运行参数错误", tplModelArtsTrainJobNew, &form)
  963. return
  964. }
  965. for _, parameter := range parameters.Parameter {
  966. if parameter.Label == modelarts.DeviceTarget {
  967. existDeviceTarget = true
  968. }
  969. if parameter.Label != modelarts.TrainUrl && parameter.Label != modelarts.DataUrl {
  970. param = append(param, models.Parameter{
  971. Label: parameter.Label,
  972. Value: parameter.Value,
  973. })
  974. }
  975. }
  976. }
  977. if !existDeviceTarget {
  978. param = append(param, models.Parameter{
  979. Label: modelarts.DeviceTarget,
  980. Value: modelarts.Ascend,
  981. })
  982. }
  983. datasUrlList, dataUrl, datasetNames, isMultiDataset, err := getDatasUrlListByUUIDS(uuid)
  984. if err != nil {
  985. log.Error("Failed to getDatasUrlListByUUIDS: %v", err)
  986. trainJobErrorNewDataPrepare(ctx, form)
  987. ctx.RenderWithErr("Failed to getDatasUrlListByUUIDS:"+err.Error(), tplModelArtsTrainJobNew, &form)
  988. return
  989. }
  990. dataPath := dataUrl
  991. jsondatas, err := json.Marshal(datasUrlList)
  992. if err != nil {
  993. log.Error("Failed to Marshal: %v", err)
  994. trainJobErrorNewDataPrepare(ctx, form)
  995. ctx.RenderWithErr("json error:"+err.Error(), tplModelArtsTrainJobNew, &form)
  996. return
  997. }
  998. if isMultiDataset {
  999. param = append(param, models.Parameter{
  1000. Label: modelarts.MultiDataUrl,
  1001. Value: string(jsondatas),
  1002. })
  1003. }
  1004. //save param config
  1005. if isSaveParam == "on" {
  1006. saveparams := append(param, models.Parameter{
  1007. Label: modelarts.TrainUrl,
  1008. Value: outputObsPath,
  1009. }, models.Parameter{
  1010. Label: modelarts.DataUrl,
  1011. Value: dataPath,
  1012. })
  1013. if form.ParameterTemplateName == "" {
  1014. log.Error("ParameterTemplateName is empty")
  1015. trainJobNewDataPrepare(ctx)
  1016. ctx.RenderWithErr("保存作业参数时,作业参数名称不能为空", tplModelArtsTrainJobNew, &form)
  1017. return
  1018. }
  1019. _, err := modelarts.CreateTrainJobConfig(models.CreateConfigParams{
  1020. ConfigName: form.ParameterTemplateName,
  1021. Description: form.PrameterDescription,
  1022. DataUrl: dataPath,
  1023. AppUrl: codeObsPath,
  1024. BootFileUrl: codeObsPath + bootFile,
  1025. TrainUrl: outputObsPath,
  1026. Flavor: models.Flavor{
  1027. Code: flavorCode,
  1028. },
  1029. WorkServerNum: workServerNumber,
  1030. EngineID: int64(engineID),
  1031. LogUrl: logObsPath,
  1032. PoolID: poolID,
  1033. Parameter: saveparams,
  1034. })
  1035. if err != nil {
  1036. log.Error("Failed to CreateTrainJobConfig: %v", err)
  1037. trainJobErrorNewDataPrepare(ctx, form)
  1038. ctx.RenderWithErr("保存作业参数失败:"+err.Error(), tplModelArtsTrainJobNew, &form)
  1039. return
  1040. }
  1041. }
  1042. req := &modelarts.GenerateTrainJobReq{
  1043. JobName: jobName,
  1044. DisplayJobName: displayJobName,
  1045. DataUrl: dataPath,
  1046. Description: description,
  1047. CodeObsPath: codeObsPath,
  1048. BootFileUrl: codeObsPath + bootFile,
  1049. BootFile: bootFile,
  1050. TrainUrl: outputObsPath,
  1051. FlavorCode: flavorCode,
  1052. WorkServerNumber: workServerNumber,
  1053. EngineID: int64(engineID),
  1054. LogUrl: logObsPath,
  1055. PoolID: poolID,
  1056. Uuid: uuid,
  1057. Parameters: param,
  1058. CommitID: commitID,
  1059. IsLatestVersion: isLatestVersion,
  1060. BranchName: branch_name,
  1061. Params: form.Params,
  1062. FlavorName: FlavorName,
  1063. EngineName: EngineName,
  1064. VersionCount: VersionCount,
  1065. TotalVersionCount: modelarts.TotalVersionCount,
  1066. DatasetName: datasetNames,
  1067. }
  1068. //将params转换Parameters.Parameter,出错时返回给前端
  1069. var Parameters modelarts.Parameters
  1070. if err := json.Unmarshal([]byte(params), &Parameters); err != nil {
  1071. ctx.ServerError("json.Unmarshal failed:", err)
  1072. return
  1073. }
  1074. err = modelarts.GenerateTrainJob(ctx, req)
  1075. if err != nil {
  1076. log.Error("GenerateTrainJob failed:%v", err.Error())
  1077. trainJobErrorNewDataPrepare(ctx, form)
  1078. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobNew, &form)
  1079. return
  1080. }
  1081. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  1082. }
  1083. func TrainJobCreateVersion(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) {
  1084. ctx.Data["PageIsTrainJob"] = true
  1085. var jobID = ctx.Params(":jobid")
  1086. count, err := models.GetCloudbrainTrainJobCountByUserID(ctx.User.ID)
  1087. if err != nil {
  1088. log.Error("GetCloudbrainTrainJobCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1089. versionErrorDataPrepare(ctx, form)
  1090. ctx.RenderWithErr("system error", tplModelArtsTrainJobVersionNew, &form)
  1091. return
  1092. } else {
  1093. if count >= 1 {
  1094. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  1095. versionErrorDataPrepare(ctx, form)
  1096. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tplModelArtsTrainJobVersionNew, &form)
  1097. return
  1098. }
  1099. }
  1100. latestTask, err := models.GetCloudbrainByJobIDAndIsLatestVersion(jobID, modelarts.IsLatestVersion)
  1101. if err != nil {
  1102. ctx.ServerError("GetCloudbrainByJobIDAndIsLatestVersion faild:", err)
  1103. return
  1104. }
  1105. VersionOutputPath := modelarts.GetOutputPathByCount(latestTask.TotalVersionCount + 1)
  1106. displayJobName := form.DisplayJobName
  1107. jobName := form.JobName
  1108. uuid := form.Attachment
  1109. description := form.Description
  1110. workServerNumber := form.WorkServerNumber
  1111. engineID := form.EngineID
  1112. bootFile := strings.TrimSpace(form.BootFile)
  1113. flavorCode := form.Flavor
  1114. params := form.Params
  1115. poolID := form.PoolID
  1116. isSaveParam := form.IsSaveParam
  1117. repo := ctx.Repo.Repository
  1118. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  1119. codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath + VersionOutputPath + "/"
  1120. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath + VersionOutputPath + "/"
  1121. logObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.LogPath + VersionOutputPath + "/"
  1122. // dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/"
  1123. branch_name := form.BranchName
  1124. PreVersionName := form.VersionName
  1125. FlavorName := form.FlavorName
  1126. EngineName := form.EngineName
  1127. isLatestVersion := modelarts.IsLatestVersion
  1128. canNewJob, _ := canUserCreateTrainJobVersion(ctx, latestTask.UserID)
  1129. if !canNewJob {
  1130. ctx.RenderWithErr("user cann't new trainjob", tplModelArtsTrainJobVersionNew, &form)
  1131. return
  1132. }
  1133. if err := paramCheckCreateTrainJob(form); err != nil {
  1134. log.Error("paramCheckCreateTrainJob failed:(%v)", err)
  1135. versionErrorDataPrepare(ctx, form)
  1136. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1137. return
  1138. }
  1139. //todo: del the codeLocalPath
  1140. _, err = ioutil.ReadDir(codeLocalPath)
  1141. if err == nil {
  1142. os.RemoveAll(codeLocalPath)
  1143. }
  1144. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  1145. commitID, _ := gitRepo.GetBranchCommitID(branch_name)
  1146. if err := downloadCode(repo, codeLocalPath, branch_name); err != nil {
  1147. log.Error("Failed git clone repo to local(!: %s (%v)", repo.FullName(), err)
  1148. versionErrorDataPrepare(ctx, form)
  1149. ctx.RenderWithErr("Failed git clone repo to local!", tplModelArtsTrainJobVersionNew, &form)
  1150. return
  1151. }
  1152. //todo: upload code (send to file_server todo this work?)
  1153. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath + VersionOutputPath + "/"); err != nil {
  1154. log.Error("Failed to obsMkdir_output: %s (%v)", repo.FullName(), err)
  1155. versionErrorDataPrepare(ctx, form)
  1156. ctx.RenderWithErr("Failed to obsMkdir_output", tplModelArtsTrainJobVersionNew, &form)
  1157. return
  1158. }
  1159. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.LogPath + VersionOutputPath + "/"); err != nil {
  1160. log.Error("Failed to obsMkdir_log: %s (%v)", repo.FullName(), err)
  1161. versionErrorDataPrepare(ctx, form)
  1162. ctx.RenderWithErr("Failed to obsMkdir_log", tplModelArtsTrainJobVersionNew, &form)
  1163. return
  1164. }
  1165. parentDir := VersionOutputPath + "/"
  1166. // parentDir := ""
  1167. // if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  1168. if err := uploadCodeToObs(codeLocalPath, jobName, parentDir); err != nil {
  1169. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  1170. versionErrorDataPrepare(ctx, form)
  1171. ctx.RenderWithErr("Failed to uploadCodeToObs", tplModelArtsTrainJobVersionNew, &form)
  1172. return
  1173. }
  1174. //todo: del local code?
  1175. var parameters models.Parameters
  1176. param := make([]models.Parameter, 0)
  1177. existDeviceTarget := false
  1178. if len(params) != 0 {
  1179. err := json.Unmarshal([]byte(params), &parameters)
  1180. if err != nil {
  1181. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  1182. versionErrorDataPrepare(ctx, form)
  1183. ctx.RenderWithErr("运行参数错误", tplModelArtsTrainJobVersionNew, &form)
  1184. return
  1185. }
  1186. for _, parameter := range parameters.Parameter {
  1187. if parameter.Label == modelarts.DeviceTarget {
  1188. existDeviceTarget = true
  1189. }
  1190. if parameter.Label != modelarts.TrainUrl && parameter.Label != modelarts.DataUrl {
  1191. param = append(param, models.Parameter{
  1192. Label: parameter.Label,
  1193. Value: parameter.Value,
  1194. })
  1195. }
  1196. }
  1197. }
  1198. if !existDeviceTarget {
  1199. param = append(param, models.Parameter{
  1200. Label: modelarts.DeviceTarget,
  1201. Value: modelarts.Ascend,
  1202. })
  1203. }
  1204. datasUrlList, dataUrl, datasetNames, isMultiDataset, err := getDatasUrlListByUUIDS(uuid)
  1205. if err != nil {
  1206. log.Error("Failed to getDatasUrlListByUUIDS: %v", err)
  1207. versionErrorDataPrepare(ctx, form)
  1208. ctx.RenderWithErr("Failed to getDatasUrlListByUUIDS:"+err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1209. return
  1210. }
  1211. dataPath := dataUrl
  1212. jsondatas, err := json.Marshal(datasUrlList)
  1213. if err != nil {
  1214. log.Error("Failed to Marshal: %v", err)
  1215. versionErrorDataPrepare(ctx, form)
  1216. ctx.RenderWithErr("json error:"+err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1217. return
  1218. }
  1219. if isMultiDataset {
  1220. param = append(param, models.Parameter{
  1221. Label: modelarts.MultiDataUrl,
  1222. Value: string(jsondatas),
  1223. })
  1224. }
  1225. //save param config
  1226. if isSaveParam == "on" {
  1227. saveparams := append(param, models.Parameter{
  1228. Label: modelarts.TrainUrl,
  1229. Value: outputObsPath,
  1230. }, models.Parameter{
  1231. Label: modelarts.DataUrl,
  1232. Value: dataPath,
  1233. })
  1234. if form.ParameterTemplateName == "" {
  1235. log.Error("ParameterTemplateName is empty")
  1236. versionErrorDataPrepare(ctx, form)
  1237. ctx.RenderWithErr("保存作业参数时,作业参数名称不能为空", tplModelArtsTrainJobVersionNew, &form)
  1238. return
  1239. }
  1240. _, err := modelarts.CreateTrainJobConfig(models.CreateConfigParams{
  1241. ConfigName: form.ParameterTemplateName,
  1242. Description: form.PrameterDescription,
  1243. DataUrl: dataPath,
  1244. AppUrl: codeObsPath,
  1245. BootFileUrl: codeObsPath + bootFile,
  1246. TrainUrl: outputObsPath,
  1247. Flavor: models.Flavor{
  1248. Code: flavorCode,
  1249. },
  1250. WorkServerNum: workServerNumber,
  1251. EngineID: int64(engineID),
  1252. LogUrl: logObsPath,
  1253. PoolID: poolID,
  1254. Parameter: saveparams,
  1255. })
  1256. if err != nil {
  1257. log.Error("Failed to CreateTrainJobConfig: %v", err)
  1258. versionErrorDataPrepare(ctx, form)
  1259. ctx.RenderWithErr("保存作业参数失败:"+err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1260. return
  1261. }
  1262. }
  1263. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, PreVersionName)
  1264. if err != nil {
  1265. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", jobID, err.Error())
  1266. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1267. return
  1268. }
  1269. req := &modelarts.GenerateTrainJobReq{
  1270. JobName: jobName,
  1271. DisplayJobName: displayJobName,
  1272. DataUrl: dataPath,
  1273. Description: description,
  1274. CodeObsPath: codeObsPath,
  1275. BootFileUrl: codeObsPath + bootFile,
  1276. BootFile: bootFile,
  1277. TrainUrl: outputObsPath,
  1278. FlavorCode: flavorCode,
  1279. WorkServerNumber: workServerNumber,
  1280. IsLatestVersion: isLatestVersion,
  1281. EngineID: int64(engineID),
  1282. LogUrl: logObsPath,
  1283. PoolID: poolID,
  1284. Uuid: uuid,
  1285. Params: form.Params,
  1286. Parameters: param,
  1287. PreVersionId: task.VersionID,
  1288. CommitID: commitID,
  1289. BranchName: branch_name,
  1290. FlavorName: FlavorName,
  1291. EngineName: EngineName,
  1292. PreVersionName: PreVersionName,
  1293. TotalVersionCount: latestTask.TotalVersionCount + 1,
  1294. DatasetName: datasetNames,
  1295. }
  1296. err = modelarts.GenerateTrainJobVersion(ctx, req, jobID)
  1297. if err != nil {
  1298. log.Error("GenerateTrainJob failed:%v", err.Error())
  1299. versionErrorDataPrepare(ctx, form)
  1300. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobVersionNew, &form)
  1301. return
  1302. }
  1303. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job/" + jobID)
  1304. // ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  1305. }
  1306. // readDir reads the directory named by dirname and returns
  1307. // a list of directory entries sorted by filename.
  1308. func readDir(dirname string) ([]os.FileInfo, error) {
  1309. f, err := os.Open(dirname)
  1310. if err != nil {
  1311. return nil, err
  1312. }
  1313. list, err := f.Readdir(0)
  1314. f.Close()
  1315. if err != nil {
  1316. //todo: can not upload empty folder
  1317. if err == io.EOF {
  1318. return nil, nil
  1319. }
  1320. return nil, err
  1321. }
  1322. //sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() })
  1323. return list, nil
  1324. }
  1325. func uploadCodeToObs(codePath, jobName, parentDir string) error {
  1326. files, err := readDir(codePath)
  1327. if err != nil {
  1328. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  1329. return err
  1330. }
  1331. for _, file := range files {
  1332. if file.IsDir() {
  1333. input := &obs.PutObjectInput{}
  1334. input.Bucket = setting.Bucket
  1335. input.Key = parentDir + file.Name() + "/"
  1336. _, err = storage.ObsCli.PutObject(input)
  1337. if err != nil {
  1338. log.Error("PutObject(%s) failed: %s", input.Key, err.Error())
  1339. return err
  1340. }
  1341. if err = uploadCodeToObs(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  1342. log.Error("uploadCodeToObs(%s) failed: %s", file.Name(), err.Error())
  1343. return err
  1344. }
  1345. } else {
  1346. input := &obs.PutFileInput{}
  1347. input.Bucket = setting.Bucket
  1348. input.Key = setting.CodePathPrefix + jobName + "/code/" + parentDir + file.Name()
  1349. input.SourceFile = codePath + file.Name()
  1350. _, err = storage.ObsCli.PutFile(input)
  1351. if err != nil {
  1352. log.Error("PutFile(%s) failed: %s", input.SourceFile, err.Error())
  1353. return err
  1354. }
  1355. }
  1356. }
  1357. return nil
  1358. }
  1359. func obsMkdir(dir string) error {
  1360. input := &obs.PutObjectInput{}
  1361. input.Bucket = setting.Bucket
  1362. input.Key = dir
  1363. _, err := storage.ObsCli.PutObject(input)
  1364. if err != nil {
  1365. log.Error("PutObject(%s) failed: %s", input.Key, err.Error())
  1366. return err
  1367. }
  1368. return nil
  1369. }
  1370. func paramCheckCreateTrainJob(form auth.CreateModelArtsTrainJobForm) error {
  1371. if !strings.HasSuffix(strings.TrimSpace(form.BootFile), ".py") {
  1372. log.Error("the boot file(%s) must be a python file", strings.TrimSpace(form.BootFile))
  1373. return errors.New("启动文件必须是python文件")
  1374. }
  1375. if form.WorkServerNumber > 2 || form.WorkServerNumber < 1 {
  1376. log.Error("the WorkServerNumber(%d) must be in (1,2)", form.WorkServerNumber)
  1377. return errors.New("计算节点数必须在1-2之间")
  1378. }
  1379. if form.BranchName == "" {
  1380. log.Error("the branch must not be null!", form.BranchName)
  1381. return errors.New("代码分支不能为空!")
  1382. }
  1383. return nil
  1384. }
  1385. func paramCheckCreateInferenceJob(form auth.CreateModelArtsInferenceJobForm) error {
  1386. if !strings.HasSuffix(strings.TrimSpace(form.BootFile), ".py") {
  1387. log.Error("the boot file(%s) must be a python file", strings.TrimSpace(form.BootFile))
  1388. return errors.New("启动文件必须是python文件")
  1389. }
  1390. if form.WorkServerNumber > 2 || form.WorkServerNumber < 1 {
  1391. log.Error("the WorkServerNumber(%d) must be in (1,2)", form.WorkServerNumber)
  1392. return errors.New("计算节点数必须在1-2之间")
  1393. }
  1394. if form.ModelName == "" {
  1395. log.Error("the ModelName(%d) must not be nil", form.ModelName)
  1396. return errors.New("模型名称不能为空")
  1397. }
  1398. if form.ModelVersion == "" {
  1399. log.Error("the ModelVersion(%d) must not be nil", form.ModelVersion)
  1400. return errors.New("模型版本不能为空")
  1401. }
  1402. if form.CkptName == "" {
  1403. log.Error("the CkptName(%d) must not be nil", form.CkptName)
  1404. return errors.New("权重文件不能为空")
  1405. }
  1406. if form.BranchName == "" {
  1407. log.Error("the Branch(%d) must not be nil", form.BranchName)
  1408. return errors.New("分支名不能为空")
  1409. }
  1410. if utf8.RuneCountInString(form.Description) > 255 {
  1411. log.Error("the Description length(%d) must not more than 255", form.Description)
  1412. return errors.New("描述字符不能超过255个字符")
  1413. }
  1414. return nil
  1415. }
  1416. func TrainJobShow(ctx *context.Context) {
  1417. ctx.Data["PageIsCloudBrain"] = true
  1418. var jobID = ctx.Params(":jobid")
  1419. repo := ctx.Repo.Repository
  1420. page := ctx.QueryInt("page")
  1421. if page <= 0 {
  1422. page = 1
  1423. }
  1424. var jobTypes []string
  1425. jobTypes = append(jobTypes, string(models.JobTypeTrain))
  1426. VersionListTasks, VersionListCount, err := models.CloudbrainsVersionList(&models.CloudbrainsOptions{
  1427. ListOptions: models.ListOptions{
  1428. Page: page,
  1429. PageSize: setting.UI.IssuePagingNum,
  1430. },
  1431. RepoID: repo.ID,
  1432. Type: models.TypeCloudBrainTwo,
  1433. JobTypes: jobTypes,
  1434. JobID: jobID,
  1435. })
  1436. if err != nil {
  1437. log.Error("GetVersionListTasks(%s) failed:%v", jobID, err.Error())
  1438. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  1439. return
  1440. }
  1441. //设置权限
  1442. canNewJob, err := canUserCreateTrainJobVersion(ctx, VersionListTasks[0].UserID)
  1443. if err != nil {
  1444. ctx.ServerError("canNewJob failed", err)
  1445. return
  1446. }
  1447. ctx.Data["canNewJob"] = canNewJob
  1448. //将运行参数转化为epoch_size = 3, device_target = Ascend的格式
  1449. for i, task := range VersionListTasks {
  1450. var parameters models.Parameters
  1451. err := json.Unmarshal([]byte(VersionListTasks[i].Parameters), &parameters)
  1452. if err != nil {
  1453. log.Error("Failed to Unmarshal Parameters: %s (%v)", VersionListTasks[i].Parameters, err)
  1454. trainJobNewDataPrepare(ctx)
  1455. return
  1456. }
  1457. if len(parameters.Parameter) > 0 {
  1458. paramTemp := ""
  1459. for _, Parameter := range parameters.Parameter {
  1460. param := Parameter.Label + " = " + Parameter.Value + "; "
  1461. paramTemp = paramTemp + param
  1462. }
  1463. VersionListTasks[i].Parameters = paramTemp[:len(paramTemp)-2]
  1464. } else {
  1465. VersionListTasks[i].Parameters = ""
  1466. }
  1467. VersionListTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1468. VersionListTasks[i].CanModify = cloudbrain.CanModifyJob(ctx, &task.Cloudbrain)
  1469. }
  1470. pager := context.NewPagination(VersionListCount, setting.UI.IssuePagingNum, page, 5)
  1471. pager.SetDefaultParams(ctx)
  1472. ctx.Data["Page"] = pager
  1473. ctx.Data["jobID"] = jobID
  1474. ctx.Data["displayJobName"] = VersionListTasks[0].DisplayJobName
  1475. ctx.Data["version_list_task"] = VersionListTasks
  1476. ctx.Data["version_list_count"] = VersionListCount
  1477. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, &VersionListTasks[0].Cloudbrain)
  1478. ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  1479. }
  1480. func TrainJobGetLog(ctx *context.Context) {
  1481. ctx.Data["PageIsTrainJob"] = true
  1482. var jobID = ctx.Params(":jobid")
  1483. var logFileName = ctx.Query("file_name")
  1484. var baseLine = ctx.Query("base_line")
  1485. var order = ctx.Query("order")
  1486. if order != modelarts.OrderDesc && order != modelarts.OrderAsc {
  1487. log.Error("order(%s) check failed", order)
  1488. ctx.HTML(http.StatusBadRequest, tplModelArtsTrainJobShow)
  1489. return
  1490. }
  1491. task, err := models.GetCloudbrainByJobID(jobID)
  1492. if err != nil {
  1493. log.Error("GetCloudbrainByJobID(%s) failed:%v", jobID, err.Error())
  1494. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  1495. return
  1496. }
  1497. result, err := modelarts.GetTrainJobLog(jobID, strconv.FormatInt(task.VersionID, 10), baseLine, logFileName, order, modelarts.Lines)
  1498. if err != nil {
  1499. log.Error("GetTrainJobLog(%s) failed:%v", jobID, err.Error())
  1500. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  1501. return
  1502. }
  1503. ctx.Data["log"] = result
  1504. //ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  1505. }
  1506. func trainJobGetLog(jobID string) (*models.GetTrainJobLogFileNamesResult, *models.GetTrainJobLogResult, error) {
  1507. task, err := models.GetCloudbrainByJobID(jobID)
  1508. if err != nil {
  1509. log.Error("GetCloudbrainByJobID(%s) failed:%v", jobID, err.Error())
  1510. return nil, nil, err
  1511. }
  1512. resultLogFile, err := modelarts.GetTrainJobLogFileNames(jobID, strconv.FormatInt(task.VersionID, 10))
  1513. if err != nil {
  1514. log.Error("GetTrainJobLogFileNames(%s) failed:%v", jobID, err.Error())
  1515. return nil, nil, err
  1516. }
  1517. result, err := modelarts.GetTrainJobLog(jobID, strconv.FormatInt(task.VersionID, 10), "", resultLogFile.LogFileList[0], modelarts.OrderDesc, modelarts.Lines)
  1518. if err != nil {
  1519. log.Error("GetTrainJobLog(%s) failed:%v", jobID, err.Error())
  1520. return nil, nil, err
  1521. }
  1522. return resultLogFile, result, err
  1523. }
  1524. func TrainJobDel(ctx *context.Context) {
  1525. var jobID = ctx.Params(":jobid")
  1526. var listType = ctx.Query("listType")
  1527. repo := ctx.Repo.Repository
  1528. var jobTypes []string
  1529. jobTypes = append(jobTypes, string(models.JobTypeTrain))
  1530. VersionListTasks, _, err := models.CloudbrainsVersionList(&models.CloudbrainsOptions{
  1531. RepoID: repo.ID,
  1532. Type: models.TypeCloudBrainTwo,
  1533. JobTypes: jobTypes,
  1534. JobID: jobID,
  1535. })
  1536. if err != nil {
  1537. ctx.ServerError("get VersionListTasks failed", err)
  1538. return
  1539. }
  1540. //删除modelarts上的任务记录
  1541. _, err = modelarts.DelTrainJob(jobID)
  1542. if err != nil {
  1543. log.Error("DelTrainJob(%s) failed:%v", jobID, err.Error())
  1544. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  1545. return
  1546. }
  1547. //删除数据库Cloudbrain表的记录
  1548. for _, task := range VersionListTasks {
  1549. err = models.DeleteJob(&task.Cloudbrain)
  1550. if err != nil {
  1551. ctx.ServerError("DeleteJob failed", err)
  1552. return
  1553. }
  1554. }
  1555. //删除存储
  1556. if len(VersionListTasks) > 0 {
  1557. DeleteJobStorage(VersionListTasks[0].JobName)
  1558. }
  1559. var isAdminPage = ctx.Query("isadminpage")
  1560. var isHomePage = ctx.Query("ishomepage")
  1561. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1562. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1563. } else if isHomePage == "true" {
  1564. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1565. } else {
  1566. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  1567. }
  1568. }
  1569. func TrainJobStop(ctx *context.Context) {
  1570. var jobID = ctx.Params(":jobid")
  1571. var listType = ctx.Query("listType")
  1572. task := ctx.Cloudbrain
  1573. _, err := modelarts.StopTrainJob(jobID, strconv.FormatInt(task.VersionID, 10))
  1574. if err != nil {
  1575. log.Error("StopTrainJob(%s) failed:%v", task.JobName, err.Error())
  1576. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobIndex, nil)
  1577. return
  1578. }
  1579. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  1580. }
  1581. func canUserCreateTrainJob(uid int64) (bool, error) {
  1582. org, err := models.GetOrgByName(setting.AllowedOrg)
  1583. if err != nil {
  1584. log.Error("get allowed org failed: ", setting.AllowedOrg)
  1585. return false, err
  1586. }
  1587. return org.IsOrgMember(uid)
  1588. }
  1589. func canUserCreateTrainJobVersion(ctx *context.Context, userID int64) (bool, error) {
  1590. if ctx == nil || ctx.User == nil {
  1591. log.Error("user unlogin!")
  1592. return false, nil
  1593. }
  1594. if userID == ctx.User.ID || ctx.User.IsAdmin {
  1595. return true, nil
  1596. } else {
  1597. log.Error("Only user itself and admin can new trainjob!")
  1598. return false, nil
  1599. }
  1600. }
  1601. func TrainJobGetConfigList(ctx *context.Context) {
  1602. ctx.Data["PageIsTrainJob"] = true
  1603. var jobID = ctx.Params(":jobid")
  1604. var logFileName = ctx.Query("file_name")
  1605. var baseLine = ctx.Query("base_line")
  1606. var order = ctx.Query("order")
  1607. if order != modelarts.OrderDesc && order != modelarts.OrderAsc {
  1608. log.Error("order(%s) check failed", order)
  1609. ctx.HTML(http.StatusBadRequest, tplModelArtsTrainJobShow)
  1610. return
  1611. }
  1612. task, err := models.GetCloudbrainByJobID(jobID)
  1613. if err != nil {
  1614. log.Error("GetCloudbrainByJobID(%s) failed:%v", jobID, err.Error())
  1615. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  1616. return
  1617. }
  1618. result, err := modelarts.GetTrainJobLog(jobID, strconv.FormatInt(task.VersionID, 10), baseLine, logFileName, order, modelarts.Lines)
  1619. if err != nil {
  1620. log.Error("GetTrainJobLog(%s) failed:%v", jobID, err.Error())
  1621. ctx.RenderWithErr(err.Error(), tplModelArtsTrainJobShow, nil)
  1622. return
  1623. }
  1624. ctx.Data["log"] = result
  1625. //ctx.HTML(http.StatusOK, tplModelArtsTrainJobShow)
  1626. }
  1627. func getConfigList(perPage, page int, sortBy, order, searchContent, configType string) (*models.GetConfigListResult, error) {
  1628. var result models.GetConfigListResult
  1629. list, err := modelarts.GetConfigList(perPage, page, sortBy, order, searchContent, configType)
  1630. if err != nil {
  1631. log.Error("GetConfigList failed:", err)
  1632. return &result, err
  1633. }
  1634. for _, config := range list.ParaConfigs {
  1635. paraConfig, err := modelarts.GetParaConfig(config.ConfigName, configType)
  1636. if err != nil {
  1637. log.Error("GetParaConfig failed:", err)
  1638. return &result, err
  1639. }
  1640. config.Result = paraConfig
  1641. }
  1642. return list, nil
  1643. }
  1644. func InferenceJobCreate(ctx *context.Context, form auth.CreateModelArtsInferenceJobForm) {
  1645. ctx.Data["PageIsTrainJob"] = true
  1646. VersionOutputPath := modelarts.GetOutputPathByCount(modelarts.TotalVersionCount)
  1647. displayJobName := form.DisplayJobName
  1648. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  1649. uuid := form.Attachment
  1650. description := form.Description
  1651. workServerNumber := form.WorkServerNumber
  1652. engineID := form.EngineID
  1653. bootFile := strings.TrimSpace(form.BootFile)
  1654. flavorCode := form.Flavor
  1655. params := form.Params
  1656. poolID := form.PoolID
  1657. repo := ctx.Repo.Repository
  1658. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  1659. codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath
  1660. resultObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.ResultPath + VersionOutputPath + "/"
  1661. logObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.LogPath + VersionOutputPath + "/"
  1662. dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/"
  1663. branch_name := form.BranchName
  1664. FlavorName := form.FlavorName
  1665. EngineName := form.EngineName
  1666. LabelName := form.LabelName
  1667. isLatestVersion := modelarts.IsLatestVersion
  1668. VersionCount := modelarts.VersionCount
  1669. trainUrl := form.TrainUrl
  1670. modelName := form.ModelName
  1671. modelVersion := form.ModelVersion
  1672. ckptName := form.CkptName
  1673. ckptUrl := "/" + form.TrainUrl + form.CkptName
  1674. log.Info("ckpt url:" + ckptUrl)
  1675. count, err := models.GetCloudbrainInferenceJobCountByUserID(ctx.User.ID)
  1676. if err != nil {
  1677. log.Error("GetCloudbrainInferenceJobCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1678. inferenceJobErrorNewDataPrepare(ctx, form)
  1679. ctx.RenderWithErr("system error", tplModelArtsInferenceJobNew, &form)
  1680. return
  1681. } else {
  1682. if count >= 1 {
  1683. log.Error("the user already has running or waiting inference task", ctx.Data["MsgID"])
  1684. inferenceJobErrorNewDataPrepare(ctx, form)
  1685. ctx.RenderWithErr("you have already a running or waiting inference task, can not create more", tplModelArtsInferenceJobNew, &form)
  1686. return
  1687. }
  1688. }
  1689. if err := paramCheckCreateInferenceJob(form); err != nil {
  1690. log.Error("paramCheckCreateInferenceJob failed:(%v)", err)
  1691. inferenceJobErrorNewDataPrepare(ctx, form)
  1692. ctx.RenderWithErr(err.Error(), tplModelArtsInferenceJobNew, &form)
  1693. return
  1694. }
  1695. //Determine whether the task name of the task in the project is duplicated
  1696. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeInference), displayJobName)
  1697. if err == nil {
  1698. if len(tasks) != 0 {
  1699. log.Error("the job name did already exist", ctx.Data["MsgID"])
  1700. inferenceJobErrorNewDataPrepare(ctx, form)
  1701. ctx.RenderWithErr("the job name did already exist", tplModelArtsInferenceJobNew, &form)
  1702. return
  1703. }
  1704. } else {
  1705. if !models.IsErrJobNotExist(err) {
  1706. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1707. inferenceJobErrorNewDataPrepare(ctx, form)
  1708. ctx.RenderWithErr("system error", tplModelArtsInferenceJobNew, &form)
  1709. return
  1710. }
  1711. }
  1712. //todo: del the codeLocalPath
  1713. _, err = ioutil.ReadDir(codeLocalPath)
  1714. if err == nil {
  1715. os.RemoveAll(codeLocalPath)
  1716. }
  1717. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  1718. commitID, _ := gitRepo.GetBranchCommitID(branch_name)
  1719. if err := downloadCode(repo, codeLocalPath, branch_name); err != nil {
  1720. log.Error("Create task failed, server timed out: %s (%v)", repo.FullName(), err)
  1721. inferenceJobErrorNewDataPrepare(ctx, form)
  1722. ctx.RenderWithErr("Create task failed, server timed out", tplModelArtsInferenceJobNew, &form)
  1723. return
  1724. }
  1725. //todo: upload code (send to file_server todo this work?)
  1726. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.ResultPath + VersionOutputPath + "/"); err != nil {
  1727. log.Error("Failed to obsMkdir_result: %s (%v)", repo.FullName(), err)
  1728. inferenceJobErrorNewDataPrepare(ctx, form)
  1729. ctx.RenderWithErr("Failed to obsMkdir_result", tplModelArtsInferenceJobNew, &form)
  1730. return
  1731. }
  1732. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.LogPath + VersionOutputPath + "/"); err != nil {
  1733. log.Error("Failed to obsMkdir_log: %s (%v)", repo.FullName(), err)
  1734. inferenceJobErrorNewDataPrepare(ctx, form)
  1735. ctx.RenderWithErr("Failed to obsMkdir_log", tplModelArtsInferenceJobNew, &form)
  1736. return
  1737. }
  1738. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  1739. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  1740. inferenceJobErrorNewDataPrepare(ctx, form)
  1741. ctx.RenderWithErr("Failed to uploadCodeToObs", tplModelArtsInferenceJobNew, &form)
  1742. return
  1743. }
  1744. var parameters models.Parameters
  1745. param := make([]models.Parameter, 0)
  1746. param = append(param, models.Parameter{
  1747. Label: modelarts.ResultUrl,
  1748. Value: "s3:/" + resultObsPath,
  1749. }, models.Parameter{
  1750. Label: modelarts.CkptUrl,
  1751. Value: "s3:/" + ckptUrl,
  1752. })
  1753. existDeviceTarget := false
  1754. if len(params) != 0 {
  1755. err := json.Unmarshal([]byte(params), &parameters)
  1756. if err != nil {
  1757. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  1758. inferenceJobErrorNewDataPrepare(ctx, form)
  1759. ctx.RenderWithErr("运行参数错误", tplModelArtsInferenceJobNew, &form)
  1760. return
  1761. }
  1762. for _, parameter := range parameters.Parameter {
  1763. if parameter.Label == modelarts.DeviceTarget {
  1764. existDeviceTarget = true
  1765. }
  1766. if parameter.Label != modelarts.TrainUrl && parameter.Label != modelarts.DataUrl {
  1767. param = append(param, models.Parameter{
  1768. Label: parameter.Label,
  1769. Value: parameter.Value,
  1770. })
  1771. }
  1772. }
  1773. }
  1774. if !existDeviceTarget {
  1775. param = append(param, models.Parameter{
  1776. Label: modelarts.DeviceTarget,
  1777. Value: modelarts.Ascend,
  1778. })
  1779. }
  1780. req := &modelarts.GenerateInferenceJobReq{
  1781. JobName: jobName,
  1782. DisplayJobName: displayJobName,
  1783. DataUrl: dataPath,
  1784. Description: description,
  1785. CodeObsPath: codeObsPath,
  1786. BootFileUrl: codeObsPath + bootFile,
  1787. BootFile: bootFile,
  1788. TrainUrl: trainUrl,
  1789. FlavorCode: flavorCode,
  1790. WorkServerNumber: workServerNumber,
  1791. EngineID: int64(engineID),
  1792. LogUrl: logObsPath,
  1793. PoolID: poolID,
  1794. Uuid: uuid,
  1795. Parameters: param, //modelarts train parameters
  1796. CommitID: commitID,
  1797. BranchName: branch_name,
  1798. Params: form.Params,
  1799. FlavorName: FlavorName,
  1800. EngineName: EngineName,
  1801. LabelName: LabelName,
  1802. IsLatestVersion: isLatestVersion,
  1803. VersionCount: VersionCount,
  1804. TotalVersionCount: modelarts.TotalVersionCount,
  1805. ModelName: modelName,
  1806. ModelVersion: modelVersion,
  1807. CkptName: ckptName,
  1808. ResultUrl: resultObsPath,
  1809. }
  1810. err = modelarts.GenerateInferenceJob(ctx, req)
  1811. if err != nil {
  1812. log.Error("GenerateTrainJob failed:%v", err.Error())
  1813. inferenceJobErrorNewDataPrepare(ctx, form)
  1814. ctx.RenderWithErr(err.Error(), tplModelArtsInferenceJobNew, &form)
  1815. return
  1816. }
  1817. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/inference-job")
  1818. }
  1819. func InferenceJobIndex(ctx *context.Context) {
  1820. MustEnableModelArts(ctx)
  1821. repo := ctx.Repo.Repository
  1822. page := ctx.QueryInt("page")
  1823. if page <= 0 {
  1824. page = 1
  1825. }
  1826. listType := ctx.Query("listType")
  1827. ctx.Data["ListType"] = listType
  1828. if listType == models.AllResource {
  1829. listType = ""
  1830. }
  1831. var jobTypes []string
  1832. jobTypes = append(jobTypes, string(models.JobTypeInference))
  1833. tasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  1834. ListOptions: models.ListOptions{
  1835. Page: page,
  1836. PageSize: setting.UI.IssuePagingNum,
  1837. },
  1838. RepoID: repo.ID,
  1839. ComputeResource: listType,
  1840. JobTypes: jobTypes,
  1841. Type: models.TypeCloudBrainAll,
  1842. })
  1843. if err != nil {
  1844. ctx.ServerError("Cloudbrain", err)
  1845. return
  1846. }
  1847. for i, task := range tasks {
  1848. tasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1849. tasks[i].CanModify = cloudbrain.CanModifyJob(ctx, &task.Cloudbrain)
  1850. }
  1851. repoId := ctx.Repo.Repository.ID
  1852. Type := -1
  1853. _, model_count, _ := models.QueryModel(&models.AiModelQueryOptions{
  1854. ListOptions: models.ListOptions{
  1855. Page: 1,
  1856. PageSize: 2,
  1857. },
  1858. RepoID: repoId,
  1859. Type: Type,
  1860. New: MODEL_LATEST,
  1861. })
  1862. ctx.Data["MODEL_COUNT"] = model_count
  1863. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  1864. pager.SetDefaultParams(ctx)
  1865. ctx.Data["Page"] = pager
  1866. ctx.Data["PageIsCloudBrain"] = true
  1867. ctx.Data["Tasks"] = tasks
  1868. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  1869. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  1870. ctx.HTML(200, tplModelArtsInferenceJobIndex)
  1871. }
  1872. func InferenceJobNew(ctx *context.Context) {
  1873. err := inferenceJobNewDataPrepare(ctx)
  1874. if err != nil {
  1875. ctx.ServerError("get new inference-job info failed", err)
  1876. return
  1877. }
  1878. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  1879. ctx.Data["WaitCount"] = waitCount
  1880. ctx.HTML(200, tplModelArtsInferenceJobNew)
  1881. }
  1882. func inferenceJobNewDataPrepare(ctx *context.Context) error {
  1883. ctx.Data["PageIsCloudBrain"] = true
  1884. ctx.Data["newInference"] = true
  1885. t := time.Now()
  1886. var displayJobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  1887. ctx.Data["display_job_name"] = displayJobName
  1888. attachs, err := models.GetModelArtsTrainAttachments(ctx.User.ID)
  1889. if err != nil {
  1890. ctx.ServerError("GetAllUserAttachments failed:", err)
  1891. return err
  1892. }
  1893. ctx.Data["attachments"] = attachs
  1894. var resourcePools modelarts.ResourcePool
  1895. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  1896. ctx.ServerError("json.Unmarshal failed:", err)
  1897. return err
  1898. }
  1899. ctx.Data["resource_pools"] = resourcePools.Info
  1900. var engines modelarts.Engine
  1901. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  1902. ctx.ServerError("json.Unmarshal failed:", err)
  1903. return err
  1904. }
  1905. ctx.Data["engines"] = engines.Info
  1906. var versionInfos modelarts.VersionInfo
  1907. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  1908. ctx.ServerError("json.Unmarshal failed:", err)
  1909. return err
  1910. }
  1911. ctx.Data["engine_versions"] = versionInfos.Version
  1912. var flavorInfos modelarts.Flavor
  1913. if err = json.Unmarshal([]byte(setting.TrainJobFLAVORINFOS), &flavorInfos); err != nil {
  1914. ctx.ServerError("json.Unmarshal failed:", err)
  1915. return err
  1916. }
  1917. ctx.Data["flavor_infos"] = flavorInfos.Info
  1918. ctx.Data["params"] = ""
  1919. ctx.Data["branchName"] = ctx.Repo.BranchName
  1920. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  1921. if err != nil {
  1922. ctx.ServerError("getConfigList failed:", err)
  1923. return err
  1924. }
  1925. ctx.Data["config_list"] = configList.ParaConfigs
  1926. repoId := ctx.Repo.Repository.ID
  1927. Type := -1
  1928. _, model_count, _ := models.QueryModel(&models.AiModelQueryOptions{
  1929. ListOptions: models.ListOptions{
  1930. Page: 1,
  1931. PageSize: 2,
  1932. },
  1933. RepoID: repoId,
  1934. Type: Type,
  1935. New: MODEL_LATEST,
  1936. })
  1937. ctx.Data["MODEL_COUNT"] = model_count
  1938. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  1939. return nil
  1940. }
  1941. func inferenceJobErrorNewDataPrepare(ctx *context.Context, form auth.CreateModelArtsInferenceJobForm) error {
  1942. ctx.Data["PageIsCloudBrain"] = true
  1943. t := time.Now()
  1944. var jobName = "inference" + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  1945. ctx.Data["job_name"] = jobName
  1946. attachs, err := models.GetModelArtsTrainAttachments(ctx.User.ID)
  1947. if err != nil {
  1948. ctx.ServerError("GetAllUserAttachments failed:", err)
  1949. return err
  1950. }
  1951. ctx.Data["attachments"] = attachs
  1952. var resourcePools modelarts.ResourcePool
  1953. if err = json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  1954. ctx.ServerError("json.Unmarshal failed:", err)
  1955. return err
  1956. }
  1957. ctx.Data["resource_pools"] = resourcePools.Info
  1958. var engines modelarts.Engine
  1959. if err = json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  1960. ctx.ServerError("json.Unmarshal failed:", err)
  1961. return err
  1962. }
  1963. ctx.Data["engines"] = engines.Info
  1964. var versionInfos modelarts.VersionInfo
  1965. if err = json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  1966. ctx.ServerError("json.Unmarshal failed:", err)
  1967. return err
  1968. }
  1969. ctx.Data["engine_versions"] = versionInfos.Version
  1970. var flavorInfos modelarts.Flavor
  1971. if err = json.Unmarshal([]byte(setting.TrainJobFLAVORINFOS), &flavorInfos); err != nil {
  1972. ctx.ServerError("json.Unmarshal failed:", err)
  1973. return err
  1974. }
  1975. ctx.Data["flavor_infos"] = flavorInfos.Info
  1976. configList, err := getConfigList(modelarts.PerPage, 1, modelarts.SortByCreateTime, "desc", "", modelarts.ConfigTypeCustom)
  1977. if err != nil {
  1978. ctx.ServerError("getConfigList failed:", err)
  1979. return err
  1980. }
  1981. var Parameters modelarts.Parameters
  1982. if err = json.Unmarshal([]byte(form.Params), &Parameters); err != nil {
  1983. ctx.ServerError("json.Unmarshal failed:", err)
  1984. return err
  1985. }
  1986. ctx.Data["params"] = Parameters.Parameter
  1987. ctx.Data["config_list"] = configList.ParaConfigs
  1988. ctx.Data["bootFile"] = form.BootFile
  1989. ctx.Data["uuid"] = form.Attachment
  1990. ctx.Data["branch_name"] = form.BranchName
  1991. ctx.Data["model_name"] = form.ModelName
  1992. ctx.Data["model_version"] = form.ModelVersion
  1993. ctx.Data["ckpt_name"] = form.CkptName
  1994. ctx.Data["train_url"] = form.TrainUrl
  1995. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  1996. return nil
  1997. }
  1998. func InferenceJobShow(ctx *context.Context) {
  1999. ctx.Data["PageIsCloudBrain"] = true
  2000. var jobID = ctx.Params(":jobid")
  2001. page := ctx.QueryInt("page")
  2002. if page <= 0 {
  2003. page = 1
  2004. }
  2005. task, err := models.GetCloudbrainByJobID(jobID)
  2006. if err != nil {
  2007. log.Error("GetInferenceTask(%s) failed:%v", jobID, err.Error())
  2008. ctx.RenderWithErr(err.Error(), tplModelArtsInferenceJobShow, nil)
  2009. return
  2010. }
  2011. //设置权限
  2012. canNewJob, err := canUserCreateTrainJobVersion(ctx, task.UserID)
  2013. if err != nil {
  2014. ctx.ServerError("canNewJob failed", err)
  2015. return
  2016. }
  2017. ctx.Data["canNewJob"] = canNewJob
  2018. //将运行参数转化为epoch_size = 3, device_target = Ascend的格式
  2019. var parameters models.Parameters
  2020. err = json.Unmarshal([]byte(task.Parameters), &parameters)
  2021. if err != nil {
  2022. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  2023. trainJobNewDataPrepare(ctx)
  2024. return
  2025. }
  2026. if len(parameters.Parameter) > 0 {
  2027. paramTemp := ""
  2028. for _, Parameter := range parameters.Parameter {
  2029. param := Parameter.Label + " = " + Parameter.Value + "; "
  2030. paramTemp = paramTemp + param
  2031. }
  2032. task.Parameters = paramTemp[:len(paramTemp)-2]
  2033. } else {
  2034. task.Parameters = ""
  2035. }
  2036. LabelName := strings.Fields(task.LabelName)
  2037. ctx.Data["labelName"] = LabelName
  2038. ctx.Data["jobID"] = jobID
  2039. ctx.Data["jobName"] = task.JobName
  2040. ctx.Data["displayJobName"] = task.DisplayJobName
  2041. ctx.Data["task"] = task
  2042. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  2043. tempUids := []int64{}
  2044. tempUids = append(tempUids, task.UserID)
  2045. JobCreater, err := models.GetUserNamesByIDs(tempUids)
  2046. if err != nil {
  2047. log.Error("GetUserNamesByIDs (WhitelistUserIDs): %v", err)
  2048. }
  2049. ctx.Data["userName"] = JobCreater[0]
  2050. ctx.HTML(http.StatusOK, tplModelArtsInferenceJobShow)
  2051. }
  2052. func ModelDownload(ctx *context.Context) {
  2053. var (
  2054. err error
  2055. )
  2056. jobID := ctx.Params(":jobid")
  2057. versionName := ctx.Query("version_name")
  2058. parentDir := ctx.Query("parent_dir")
  2059. fileName := ctx.Query("file_name")
  2060. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  2061. if err != nil {
  2062. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", task.JobName, err.Error())
  2063. return
  2064. }
  2065. var url string
  2066. if task.ComputeResource == models.NPUResource {
  2067. path := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, task.JobName, setting.OutPutPath, versionName, parentDir, fileName), "/")
  2068. url, err = storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  2069. if err != nil {
  2070. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  2071. ctx.ServerError("GetObsCreateSignedUrl", err)
  2072. return
  2073. }
  2074. } else if task.ComputeResource == models.GPUResource {
  2075. filePath := setting.CBCodePathPrefix + task.JobName + cloudbrain.ModelMountPath + "/" + parentDir
  2076. url, err = storage.Attachments.PresignedGetURL(filePath, fileName)
  2077. if err != nil {
  2078. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  2079. ctx.ServerError("PresignedGetURL", err)
  2080. return
  2081. }
  2082. }
  2083. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  2084. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  2085. }
  2086. func ResultDownload(ctx *context.Context) {
  2087. var (
  2088. err error
  2089. )
  2090. versionName := ctx.Query("version_name")
  2091. parentDir := ctx.Query("parent_dir")
  2092. fileName := ctx.Query("file_name")
  2093. task := ctx.Cloudbrain
  2094. if err != nil {
  2095. ctx.Data["error"] = err.Error()
  2096. }
  2097. path := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, task.JobName, "result/", versionName, parentDir, fileName), "/")
  2098. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  2099. if err != nil {
  2100. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  2101. ctx.ServerError("GetObsCreateSignedUrl", err)
  2102. return
  2103. }
  2104. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  2105. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  2106. }
  2107. func DeleteJobStorage(jobName string) error {
  2108. //delete local
  2109. localJobPath := setting.JobPath + jobName
  2110. err := os.RemoveAll(localJobPath)
  2111. if err != nil {
  2112. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  2113. }
  2114. //delete oss
  2115. dirPath := setting.CodePathPrefix + jobName + "/"
  2116. err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  2117. if err != nil {
  2118. log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  2119. }
  2120. return nil
  2121. }
  2122. func DownloadMultiResultFile(ctx *context.Context) {
  2123. var jobID = ctx.Params(":jobid")
  2124. var versionName = ctx.Query("version_name")
  2125. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  2126. if err != nil {
  2127. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  2128. return
  2129. }
  2130. // if !isCanDeleteOrDownload(ctx, task) {
  2131. // ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  2132. // return
  2133. // }
  2134. // path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  2135. path := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, task.JobName, "result/", versionName), "/") + "/"
  2136. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  2137. if err == nil {
  2138. //count++
  2139. // models.ModifyModelDownloadCount(id)
  2140. returnFileName := task.DisplayJobName + ".zip"
  2141. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+returnFileName)
  2142. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  2143. w := zip.NewWriter(ctx.Resp)
  2144. defer w.Close()
  2145. for _, oneFile := range allFile {
  2146. if oneFile.IsDir {
  2147. log.Info("zip dir name:" + oneFile.FileName)
  2148. } else {
  2149. log.Info("zip file name:" + oneFile.FileName)
  2150. fDest, err := w.Create(oneFile.FileName)
  2151. if err != nil {
  2152. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  2153. ctx.ServerError("download file failed:", err)
  2154. return
  2155. }
  2156. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  2157. if err != nil {
  2158. log.Info("download file failed: %s\n", err.Error())
  2159. ctx.ServerError("download file failed:", err)
  2160. return
  2161. } else {
  2162. defer body.Close()
  2163. p := make([]byte, 1024)
  2164. var readErr error
  2165. var readCount int
  2166. // 读取对象内容
  2167. for {
  2168. readCount, readErr = body.Read(p)
  2169. if readCount > 0 {
  2170. fDest.Write(p[:readCount])
  2171. }
  2172. if readErr != nil {
  2173. break
  2174. }
  2175. }
  2176. }
  2177. }
  2178. }
  2179. } else {
  2180. log.Info("error,msg=" + err.Error())
  2181. ctx.ServerError("no file to download.", err)
  2182. }
  2183. }
  2184. func SetJobCount(ctx *context.Context) {
  2185. repoId := ctx.Repo.Repository.ID
  2186. _, jobCount, err := models.Cloudbrains(&models.CloudbrainsOptions{
  2187. RepoID: repoId,
  2188. Type: models.TypeCloudBrainAll,
  2189. })
  2190. if err != nil {
  2191. ctx.ServerError("Get job faild:", err)
  2192. return
  2193. }
  2194. ctx.Data["jobCount"] = jobCount
  2195. }
  2196. func TrainJobDownloadLogFile(ctx *context.Context) {
  2197. var (
  2198. err error
  2199. )
  2200. var jobID = ctx.Params(":jobid")
  2201. versionName := ctx.Query("version_name")
  2202. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  2203. if err != nil {
  2204. log.Error("GetCloudbrainByJobIDAndVersionName(%s) failed:%v", task.JobName, err.Error(), ctx.Data["msgID"])
  2205. ctx.ServerError("GetCloudbrainByJobIDAndVersionName", err)
  2206. return
  2207. }
  2208. prefix := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, task.JobName, modelarts.LogPath, versionName), "/") + "/job"
  2209. key, err := storage.GetObsLogFileName(prefix)
  2210. if err != nil {
  2211. log.Error("GetObsLogFileName(%s) failed:%v", jobID, err.Error(), ctx.Data["msgID"])
  2212. ctx.ServerError("GetObsLogFileName", err)
  2213. return
  2214. }
  2215. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, key)
  2216. if err != nil {
  2217. log.Error("GetObsCreateSignedUrlByBucketAndKey failed: %v", err.Error(), ctx.Data["msgID"])
  2218. ctx.ServerError("GetObsCreateSignedUrlByBucketAndKey", err)
  2219. return
  2220. }
  2221. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  2222. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  2223. }
  2224. func getDatasUrlListByUUIDS(uuidStr string) ([]models.Datasurl, string, string, bool, error) {
  2225. var isMultiDataset bool
  2226. var dataUrl string
  2227. var datasetNames string
  2228. var datasUrlList []models.Datasurl
  2229. uuids := strings.Split(uuidStr, ";")
  2230. if len(uuids) > setting.MaxDatasetNum {
  2231. log.Error("the dataset count(%d) exceed the limit", len(uuids))
  2232. return datasUrlList, dataUrl, datasetNames, isMultiDataset, errors.New("the dataset count exceed the limit")
  2233. }
  2234. datasetInfos := make(map[string]models.DatasetInfo)
  2235. attachs, err := models.GetAttachmentsByUUIDs(uuids)
  2236. if err != nil {
  2237. log.Error("GetAttachmentsByUUIDs failed: %v", err)
  2238. return datasUrlList, dataUrl, datasetNames, isMultiDataset, errors.New("GetAttachmentsByUUIDs failed")
  2239. }
  2240. for i, attach := range attachs {
  2241. fileName := strings.TrimSuffix(strings.TrimSuffix(strings.TrimSuffix(attach.Name, ".zip"), ".tar.gz"), ".tgz")
  2242. for _, datasetInfo := range datasetInfos {
  2243. if fileName == datasetInfo.Name {
  2244. log.Error("the dataset name is same: %v", attach.Name)
  2245. return datasUrlList, dataUrl, datasetNames, isMultiDataset, errors.New("the dataset name is same")
  2246. }
  2247. }
  2248. if len(attachs) <= 1 {
  2249. dataUrl = "/" + setting.Bucket + "/" + setting.BasePath + path.Join(attach.UUID[0:1], attach.UUID[1:2]) + "/" + attach.UUID + attach.UUID + "/"
  2250. isMultiDataset = false
  2251. } else {
  2252. dataUrl = "/" + setting.Bucket + "/" + setting.BasePath + path.Join(attachs[0].UUID[0:1], attachs[0].UUID[1:2]) + "/" + attachs[0].UUID + attachs[0].UUID + "/"
  2253. datasetUrl := "s3://" + setting.Bucket + "/" + setting.BasePath + path.Join(attach.UUID[0:1], attach.UUID[1:2]) + "/" + attach.UUID + attach.UUID + "/"
  2254. datasUrlList = append(datasUrlList, models.Datasurl{
  2255. DatasetUrl: datasetUrl,
  2256. DatasetName: fileName,
  2257. })
  2258. isMultiDataset = true
  2259. }
  2260. if i == 0 {
  2261. datasetNames = attach.Name
  2262. } else {
  2263. datasetNames += ";" + attach.Name
  2264. }
  2265. }
  2266. return datasUrlList, dataUrl, datasetNames, isMultiDataset, nil
  2267. }