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