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.

cloudbrain.go 91 kB

4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
5 years ago
5 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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
5 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
3 years ago
3 years ago
4 years ago
3 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
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
5 years ago
4 years ago
4 years ago
5 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
5 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
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 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
5 years ago
4 years ago
3 years ago
5 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
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
5 years ago
5 years ago
3 years ago
3 years ago
5 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
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
5 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 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
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
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
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
4 years ago
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
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
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
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
3 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
3 years ago
3 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
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
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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
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
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
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
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
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
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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917
  1. package repo
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "regexp"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "unicode/utf8"
  16. "code.gitea.io/gitea/modules/grampus"
  17. "code.gitea.io/gitea/modules/timeutil"
  18. "github.com/unknwon/i18n"
  19. "code.gitea.io/gitea/models"
  20. "code.gitea.io/gitea/modules/auth"
  21. "code.gitea.io/gitea/modules/base"
  22. "code.gitea.io/gitea/modules/cloudbrain"
  23. "code.gitea.io/gitea/modules/context"
  24. "code.gitea.io/gitea/modules/git"
  25. "code.gitea.io/gitea/modules/log"
  26. "code.gitea.io/gitea/modules/modelarts"
  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. tplCloudBrainNew base.TplName = "repo/cloudbrain/new"
  33. tplCloudBrainShow base.TplName = "repo/cloudbrain/show"
  34. tplCloudBrainShowModels base.TplName = "repo/cloudbrain/models/index"
  35. tplCloudBrainBenchmarkIndex base.TplName = "repo/cloudbrain/benchmark/index"
  36. tplCloudBrainBenchmarkNew base.TplName = "repo/cloudbrain/benchmark/new"
  37. tplCloudBrainBenchmarkShow base.TplName = "repo/cloudbrain/benchmark/show"
  38. tplCloudBrainImageSubmit base.TplName = "repo/cloudbrain/image/submit"
  39. tplCloudBrainImageEdit base.TplName = "repo/cloudbrain/image/edit"
  40. tplCloudBrainTrainJobNew base.TplName = "repo/cloudbrain/trainjob/new"
  41. tplCloudBrainTrainJobShow base.TplName = "repo/cloudbrain/trainjob/show"
  42. tplCloudBrainInferenceJobNew base.TplName = "repo/cloudbrain/inference/new"
  43. tplCloudBrainInferenceJobShow base.TplName = "repo/cloudbrain/inference/show"
  44. )
  45. var (
  46. gpuInfos *models.GpuInfos
  47. categories *models.Categories
  48. benchmarkTypes *models.BenchmarkTypes
  49. benchmarkGpuInfos *models.GpuInfos
  50. benchmarkResourceSpecs *models.ResourceSpecs
  51. trainGpuInfos *models.GpuInfos
  52. inferenceGpuInfos *models.GpuInfos
  53. )
  54. const BENCHMARK_TYPE_CODE = "repo.cloudbrain.benchmark.types"
  55. const CLONE_FILE_PREFIX = "file:///"
  56. var benchmarkTypesMap = make(map[string]*models.BenchmarkTypes, 0)
  57. var jobNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-_]{1,34}[a-z0-9-]$`)
  58. // MustEnableDataset check if repository enable internal cb
  59. func MustEnableCloudbrain(ctx *context.Context) {
  60. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  61. ctx.NotFound("MustEnableCloudbrain", nil)
  62. return
  63. }
  64. }
  65. func cutString(str string, lens int) string {
  66. if len(str) < lens {
  67. return str
  68. }
  69. return str[:lens]
  70. }
  71. func jobNamePrefixValid(s string) string {
  72. lowStr := strings.ToLower(s)
  73. re := regexp.MustCompile(`[^a-z0-9_\\-]+`)
  74. removeSpecial := re.ReplaceAllString(lowStr, "")
  75. re = regexp.MustCompile(`^[_\\-]+`)
  76. return re.ReplaceAllString(removeSpecial, "")
  77. }
  78. func cloudBrainNewDataPrepare(ctx *context.Context) error {
  79. ctx.Data["PageIsCloudBrain"] = true
  80. t := time.Now()
  81. var displayJobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  82. ctx.Data["display_job_name"] = displayJobName
  83. ctx.Data["command"] = cloudbrain.GetCloudbrainDebugCommand()
  84. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  85. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  86. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  87. ctx.Data["benchmark_path"] = cloudbrain.BenchMarkMountPath
  88. ctx.Data["is_benchmark_enabled"] = setting.IsBenchmarkEnabled
  89. if categories == nil {
  90. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  91. }
  92. ctx.Data["benchmark_categories"] = categories.Category
  93. ctx.Data["benchmark_types"] = GetBenchmarkTypes(ctx).BenchmarkType
  94. queuesDetail, _ := cloudbrain.GetQueuesDetail()
  95. if queuesDetail != nil {
  96. ctx.Data["QueuesDetail"] = queuesDetail
  97. }
  98. cloudbrain.InitSpecialPool()
  99. if gpuInfos == nil {
  100. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  101. }
  102. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  103. if trainGpuInfos == nil {
  104. json.Unmarshal([]byte(setting.TrainGpuTypes), &trainGpuInfos)
  105. }
  106. ctx.Data["train_gpu_types"] = trainGpuInfos.GpuInfo
  107. if inferenceGpuInfos == nil && setting.InferenceGpuTypes != "" {
  108. json.Unmarshal([]byte(setting.InferenceGpuTypes), &inferenceGpuInfos)
  109. }
  110. if inferenceGpuInfos != nil {
  111. ctx.Data["inference_gpu_types"] = inferenceGpuInfos.GpuInfo
  112. }
  113. if benchmarkGpuInfos == nil {
  114. json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos)
  115. }
  116. ctx.Data["benchmark_gpu_types"] = benchmarkGpuInfos.GpuInfo
  117. if benchmarkResourceSpecs == nil {
  118. json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs)
  119. }
  120. ctx.Data["benchmark_resource_specs"] = benchmarkResourceSpecs.ResourceSpec
  121. if cloudbrain.ResourceSpecs == nil {
  122. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  123. }
  124. ctx.Data["resource_specs"] = cloudbrain.ResourceSpecs.ResourceSpec
  125. if cloudbrain.TrainResourceSpecs == nil {
  126. json.Unmarshal([]byte(setting.TrainResourceSpecs), &cloudbrain.TrainResourceSpecs)
  127. }
  128. ctx.Data["train_resource_specs"] = cloudbrain.TrainResourceSpecs.ResourceSpec
  129. if cloudbrain.InferenceResourceSpecs == nil && setting.InferenceResourceSpecs != "" {
  130. json.Unmarshal([]byte(setting.InferenceResourceSpecs), &cloudbrain.InferenceResourceSpecs)
  131. }
  132. if cloudbrain.InferenceResourceSpecs != nil {
  133. ctx.Data["inference_resource_specs"] = cloudbrain.InferenceResourceSpecs.ResourceSpec
  134. }
  135. if cloudbrain.SpecialPools != nil {
  136. var debugGpuTypes []*models.GpuInfo
  137. var trainGpuTypes []*models.GpuInfo
  138. for _, pool := range cloudbrain.SpecialPools.Pools {
  139. org, _ := models.GetOrgByName(pool.Org)
  140. if org != nil {
  141. isOrgMember, _ := models.IsOrganizationMember(org.ID, ctx.User.ID)
  142. if isOrgMember {
  143. for _, jobType := range pool.JobType {
  144. if jobType == string(models.JobTypeDebug) {
  145. debugGpuTypes = append(debugGpuTypes, pool.Pool...)
  146. if pool.ResourceSpec != nil {
  147. ctx.Data["resource_specs"] = pool.ResourceSpec
  148. }
  149. } else if jobType == string(models.JobTypeTrain) {
  150. trainGpuTypes = append(trainGpuTypes, pool.Pool...)
  151. if pool.ResourceSpec != nil {
  152. ctx.Data["train_resource_specs"] = pool.ResourceSpec
  153. }
  154. }
  155. }
  156. break
  157. }
  158. }
  159. }
  160. if len(debugGpuTypes) > 0 {
  161. ctx.Data["gpu_types"] = debugGpuTypes
  162. }
  163. if len(trainGpuTypes) > 0 {
  164. ctx.Data["train_gpu_types"] = trainGpuTypes
  165. }
  166. }
  167. ctx.Data["params"] = ""
  168. ctx.Data["branchName"] = ctx.Repo.BranchName
  169. ctx.Data["snn4imagenet_path"] = cloudbrain.Snn4imagenetMountPath
  170. ctx.Data["is_snn4imagenet_enabled"] = setting.IsSnn4imagenetEnabled
  171. ctx.Data["brainscore_path"] = cloudbrain.BrainScoreMountPath
  172. ctx.Data["is_brainscore_enabled"] = setting.IsBrainScoreEnabled
  173. ctx.Data["datasetType"] = models.TypeCloudBrainOne
  174. ctx.Data["benchmarkMode"] = ctx.Query("benchmarkMode")
  175. return nil
  176. }
  177. func cloudBrainTrainJobErrorPrepare(ctx *context.Context, form auth.CreateCloudBrainForm) error {
  178. ctx.Data["PageIsCloudBrain"] = true
  179. if categories == nil {
  180. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  181. }
  182. ctx.Data["benchmark_categories"] = categories.Category
  183. ctx.Data["benchmark_types"] = GetBenchmarkTypes(ctx).BenchmarkType
  184. queuesDetail, _ := cloudbrain.GetQueuesDetail()
  185. if queuesDetail != nil {
  186. ctx.Data["QueuesDetail"] = queuesDetail
  187. }
  188. cloudbrain.InitSpecialPool()
  189. if gpuInfos == nil {
  190. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  191. }
  192. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  193. if trainGpuInfos == nil {
  194. json.Unmarshal([]byte(setting.TrainGpuTypes), &trainGpuInfos)
  195. }
  196. ctx.Data["train_gpu_types"] = trainGpuInfos.GpuInfo
  197. if inferenceGpuInfos == nil && setting.InferenceGpuTypes != "" {
  198. json.Unmarshal([]byte(setting.InferenceGpuTypes), &inferenceGpuInfos)
  199. }
  200. if inferenceGpuInfos != nil {
  201. ctx.Data["inference_gpu_types"] = inferenceGpuInfos.GpuInfo
  202. }
  203. if benchmarkGpuInfos == nil {
  204. json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos)
  205. }
  206. ctx.Data["benchmark_gpu_types"] = benchmarkGpuInfos.GpuInfo
  207. if benchmarkResourceSpecs == nil {
  208. json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs)
  209. }
  210. ctx.Data["benchmark_resource_specs"] = benchmarkResourceSpecs.ResourceSpec
  211. if cloudbrain.ResourceSpecs == nil {
  212. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  213. }
  214. ctx.Data["resource_specs"] = cloudbrain.ResourceSpecs.ResourceSpec
  215. if cloudbrain.TrainResourceSpecs == nil {
  216. json.Unmarshal([]byte(setting.TrainResourceSpecs), &cloudbrain.TrainResourceSpecs)
  217. }
  218. ctx.Data["train_resource_specs"] = cloudbrain.TrainResourceSpecs.ResourceSpec
  219. if cloudbrain.InferenceResourceSpecs == nil && setting.InferenceResourceSpecs != "" {
  220. json.Unmarshal([]byte(setting.InferenceResourceSpecs), &cloudbrain.InferenceResourceSpecs)
  221. }
  222. if cloudbrain.InferenceResourceSpecs != nil {
  223. ctx.Data["inference_resource_specs"] = cloudbrain.InferenceResourceSpecs.ResourceSpec
  224. }
  225. if cloudbrain.SpecialPools != nil {
  226. var debugGpuTypes []*models.GpuInfo
  227. var trainGpuTypes []*models.GpuInfo
  228. for _, pool := range cloudbrain.SpecialPools.Pools {
  229. org, _ := models.GetOrgByName(pool.Org)
  230. if org != nil {
  231. isOrgMember, _ := models.IsOrganizationMember(org.ID, ctx.User.ID)
  232. if isOrgMember {
  233. for _, jobType := range pool.JobType {
  234. if jobType == string(models.JobTypeDebug) {
  235. debugGpuTypes = append(debugGpuTypes, pool.Pool...)
  236. if pool.ResourceSpec != nil {
  237. ctx.Data["resource_specs"] = pool.ResourceSpec
  238. }
  239. } else if jobType == string(models.JobTypeTrain) {
  240. trainGpuTypes = append(trainGpuTypes, pool.Pool...)
  241. if pool.ResourceSpec != nil {
  242. ctx.Data["train_resource_specs"] = pool.ResourceSpec
  243. }
  244. }
  245. }
  246. break
  247. }
  248. }
  249. }
  250. if len(debugGpuTypes) > 0 {
  251. ctx.Data["gpu_types"] = debugGpuTypes
  252. }
  253. if len(trainGpuTypes) > 0 {
  254. ctx.Data["train_gpu_types"] = trainGpuTypes
  255. }
  256. }
  257. var Parameters modelarts.Parameters
  258. if err := json.Unmarshal([]byte(form.Params), &Parameters); err != nil {
  259. ctx.ServerError("json.Unmarshal failed:", err)
  260. return err
  261. }
  262. ctx.Data["params"] = Parameters.Parameter
  263. ctx.Data["boot_file"] = form.BootFile
  264. ctx.Data["attachment"] = form.Attachment
  265. _, datasetNames, err := models.GetDatasetInfo(form.Attachment)
  266. if err != nil {
  267. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  268. return nil
  269. }
  270. ctx.Data["dataset_name"] = datasetNames
  271. ctx.Data["branch_name"] = form.BranchName
  272. ctx.Data["datasetType"] = models.TypeCloudBrainOne
  273. ctx.Data["display_job_name"] = form.DisplayJobName
  274. ctx.Data["image"] = form.Image
  275. ctx.Data["job_type"] = form.JobType
  276. ctx.Data["gpu_type"] = form.GpuType
  277. ctx.Data["resource_spec_id"] = form.ResourceSpecId
  278. return nil
  279. }
  280. func cloudBrainInferenceJobErrorPrepare(ctx *context.Context, form auth.CreateCloudBrainInferencForm) error {
  281. ctx.Data["PageIsCloudBrain"] = true
  282. if categories == nil {
  283. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  284. }
  285. ctx.Data["benchmark_categories"] = categories.Category
  286. ctx.Data["benchmark_types"] = GetBenchmarkTypes(ctx).BenchmarkType
  287. queuesDetail, _ := cloudbrain.GetQueuesDetail()
  288. if queuesDetail != nil {
  289. ctx.Data["QueuesDetail"] = queuesDetail
  290. }
  291. cloudbrain.InitSpecialPool()
  292. if gpuInfos == nil {
  293. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  294. }
  295. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  296. if trainGpuInfos == nil {
  297. json.Unmarshal([]byte(setting.TrainGpuTypes), &trainGpuInfos)
  298. }
  299. ctx.Data["train_gpu_types"] = trainGpuInfos.GpuInfo
  300. if inferenceGpuInfos == nil && setting.InferenceGpuTypes != "" {
  301. json.Unmarshal([]byte(setting.InferenceGpuTypes), &inferenceGpuInfos)
  302. }
  303. if inferenceGpuInfos != nil {
  304. ctx.Data["inference_gpu_types"] = inferenceGpuInfos.GpuInfo
  305. }
  306. if benchmarkGpuInfos == nil {
  307. json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos)
  308. }
  309. ctx.Data["benchmark_gpu_types"] = benchmarkGpuInfos.GpuInfo
  310. if benchmarkResourceSpecs == nil {
  311. json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs)
  312. }
  313. ctx.Data["benchmark_resource_specs"] = benchmarkResourceSpecs.ResourceSpec
  314. if cloudbrain.ResourceSpecs == nil {
  315. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  316. }
  317. ctx.Data["resource_specs"] = cloudbrain.ResourceSpecs.ResourceSpec
  318. if cloudbrain.TrainResourceSpecs == nil {
  319. json.Unmarshal([]byte(setting.TrainResourceSpecs), &cloudbrain.TrainResourceSpecs)
  320. }
  321. ctx.Data["train_resource_specs"] = cloudbrain.TrainResourceSpecs.ResourceSpec
  322. if cloudbrain.InferenceResourceSpecs == nil && setting.InferenceResourceSpecs != "" {
  323. json.Unmarshal([]byte(setting.InferenceResourceSpecs), &cloudbrain.InferenceResourceSpecs)
  324. }
  325. if cloudbrain.InferenceResourceSpecs != nil {
  326. ctx.Data["inference_resource_specs"] = cloudbrain.InferenceResourceSpecs.ResourceSpec
  327. }
  328. if cloudbrain.SpecialPools != nil {
  329. var debugGpuTypes []*models.GpuInfo
  330. var trainGpuTypes []*models.GpuInfo
  331. for _, pool := range cloudbrain.SpecialPools.Pools {
  332. org, _ := models.GetOrgByName(pool.Org)
  333. if org != nil {
  334. isOrgMember, _ := models.IsOrganizationMember(org.ID, ctx.User.ID)
  335. if isOrgMember {
  336. for _, jobType := range pool.JobType {
  337. if jobType == string(models.JobTypeDebug) {
  338. debugGpuTypes = append(debugGpuTypes, pool.Pool...)
  339. if pool.ResourceSpec != nil {
  340. ctx.Data["resource_specs"] = pool.ResourceSpec
  341. }
  342. } else if jobType == string(models.JobTypeTrain) {
  343. trainGpuTypes = append(trainGpuTypes, pool.Pool...)
  344. if pool.ResourceSpec != nil {
  345. ctx.Data["train_resource_specs"] = pool.ResourceSpec
  346. }
  347. }
  348. }
  349. break
  350. }
  351. }
  352. }
  353. if len(debugGpuTypes) > 0 {
  354. ctx.Data["gpu_types"] = debugGpuTypes
  355. }
  356. if len(trainGpuTypes) > 0 {
  357. ctx.Data["train_gpu_types"] = trainGpuTypes
  358. }
  359. }
  360. var Parameters modelarts.Parameters
  361. if err := json.Unmarshal([]byte(form.Params), &Parameters); err != nil {
  362. ctx.ServerError("json.Unmarshal failed:", err)
  363. return err
  364. }
  365. ctx.Data["params"] = Parameters.Parameter
  366. ctx.Data["boot_file"] = form.BootFile
  367. ctx.Data["attachment"] = form.Attachment
  368. _, datasetNames, err := models.GetDatasetInfo(form.Attachment)
  369. if err != nil {
  370. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  371. return nil
  372. }
  373. ctx.Data["dataset_name"] = datasetNames
  374. ctx.Data["branch_name"] = form.BranchName
  375. ctx.Data["datasetType"] = models.TypeCloudBrainOne
  376. ctx.Data["display_job_name"] = form.DisplayJobName
  377. ctx.Data["image"] = form.Image
  378. ctx.Data["job_type"] = form.JobType
  379. ctx.Data["gpu_type"] = form.GpuType
  380. ctx.Data["resource_spec_id"] = form.ResourceSpecId
  381. ctx.Data["label_names"] = form.LabelName
  382. ctx.Data["train_url"] = form.TrainUrl
  383. ctx.Data["ckpt_name"] = form.CkptName
  384. ctx.Data["model_name"] = form.ModelName
  385. ctx.Data["model_version"] = form.ModelVersion
  386. ctx.Data["description"] = form.Description
  387. return nil
  388. }
  389. func CloudBrainNew(ctx *context.Context) {
  390. err := cloudBrainNewDataPrepare(ctx)
  391. if err != nil {
  392. ctx.ServerError("get new cloudbrain info failed", err)
  393. return
  394. }
  395. ctx.HTML(200, tplCloudBrainNew)
  396. }
  397. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  398. ctx.Data["PageIsCloudBrain"] = true
  399. displayJobName := form.DisplayJobName
  400. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  401. image := strings.TrimSpace(form.Image)
  402. uuids := form.Attachment
  403. jobType := form.JobType
  404. gpuQueue := form.GpuType
  405. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  406. resourceSpecId := form.ResourceSpecId
  407. branchName := form.BranchName
  408. repo := ctx.Repo.Repository
  409. tpl := tplCloudBrainNew
  410. if jobType == string(models.JobTypeTrain) {
  411. tpl = tplCloudBrainTrainJobNew
  412. }
  413. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  414. if err == nil {
  415. if len(tasks) != 0 {
  416. log.Error("the job name did already exist", ctx.Data["MsgID"])
  417. cloudBrainTrainJobErrorPrepare(ctx, form)
  418. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  419. return
  420. }
  421. } else {
  422. if !models.IsErrJobNotExist(err) {
  423. log.Error("system error, %v", err, ctx.Data["MsgID"])
  424. cloudBrainTrainJobErrorPrepare(ctx, form)
  425. ctx.RenderWithErr("system error", tpl, &form)
  426. return
  427. }
  428. }
  429. if !jobNamePattern.MatchString(displayJobName) {
  430. cloudBrainTrainJobErrorPrepare(ctx, form)
  431. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  432. return
  433. }
  434. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) && jobType != string(models.JobTypeTrain) {
  435. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  436. cloudBrainTrainJobErrorPrepare(ctx, form)
  437. ctx.RenderWithErr("jobtype error", tpl, &form)
  438. return
  439. }
  440. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, jobType)
  441. if err != nil {
  442. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  443. cloudBrainTrainJobErrorPrepare(ctx, form)
  444. ctx.RenderWithErr("system error", tpl, &form)
  445. return
  446. } else {
  447. if count >= 1 {
  448. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  449. cloudBrainTrainJobErrorPrepare(ctx, form)
  450. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tpl, &form)
  451. return
  452. }
  453. }
  454. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuids)
  455. if err != nil {
  456. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  457. cloudBrainTrainJobErrorPrepare(ctx, form)
  458. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  459. return
  460. }
  461. command := cloudbrain.GetCloudbrainDebugCommand()
  462. if jobType == string(models.JobTypeTrain) {
  463. tpl = tplCloudBrainTrainJobNew
  464. commandTrain, err := getTrainJobCommand(form)
  465. if err != nil {
  466. log.Error("getTrainJobCommand failed: %v", err)
  467. ctx.RenderWithErr(err.Error(), tpl, &form)
  468. return
  469. }
  470. command = commandTrain
  471. }
  472. errStr := checkCloudBrainSpecialPool(ctx, jobType, gpuQueue, resourceSpecId)
  473. if errStr != "" {
  474. cloudBrainTrainJobErrorPrepare(ctx, form)
  475. ctx.RenderWithErr(errStr, tpl, &form)
  476. return
  477. }
  478. if branchName == "" {
  479. branchName = cloudbrain.DefaultBranchName
  480. }
  481. downloadCode(repo, codePath, branchName)
  482. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  483. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  484. mkModelPath(modelPath)
  485. uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/")
  486. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  487. req := cloudbrain.GenerateCloudBrainTaskReq{
  488. Ctx: ctx,
  489. DisplayJobName: displayJobName,
  490. JobName: jobName,
  491. Image: image,
  492. Command: command,
  493. Uuids: uuids,
  494. DatasetNames: datasetNames,
  495. DatasetInfos: datasetInfos,
  496. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  497. ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  498. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  499. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  500. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  501. JobType: jobType,
  502. GpuQueue: gpuQueue,
  503. Description: form.Description,
  504. BranchName: branchName,
  505. BootFile: form.BootFile,
  506. Params: form.Params,
  507. CommitID: commitID,
  508. BenchmarkTypeID: 0,
  509. BenchmarkChildTypeID: 0,
  510. ResourceSpecId: resourceSpecId,
  511. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  512. }
  513. err = cloudbrain.GenerateTask(req)
  514. if err != nil {
  515. cloudBrainTrainJobErrorPrepare(ctx, form)
  516. ctx.RenderWithErr(err.Error(), tpl, &form)
  517. return
  518. }
  519. if jobType == string(models.JobTypeTrain) {
  520. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=all")
  521. } else {
  522. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  523. }
  524. }
  525. func CloudBrainInferenceJobCreate(ctx *context.Context, form auth.CreateCloudBrainInferencForm) {
  526. ctx.Data["PageIsCloudBrain"] = true
  527. displayJobName := form.DisplayJobName
  528. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  529. image := strings.TrimSpace(form.Image)
  530. uuid := form.Attachment
  531. jobType := string(models.JobTypeInference)
  532. gpuQueue := form.GpuType
  533. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  534. resourceSpecId := form.ResourceSpecId
  535. branchName := form.BranchName
  536. labelName := form.LabelName
  537. repo := ctx.Repo.Repository
  538. ckptUrl := setting.Attachment.Minio.RealPath + form.TrainUrl + form.CkptName
  539. log.Info("ckpt url:" + ckptUrl)
  540. tpl := tplCloudBrainInferenceJobNew
  541. command, err := getInferenceJobCommand(form)
  542. if err != nil {
  543. log.Error("getTrainJobCommand failed: %v", err)
  544. ctx.RenderWithErr(err.Error(), tpl, &form)
  545. return
  546. }
  547. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  548. if err == nil {
  549. if len(tasks) != 0 {
  550. log.Error("the job name did already exist", ctx.Data["MsgID"])
  551. cloudBrainInferenceJobErrorPrepare(ctx, form)
  552. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  553. return
  554. }
  555. } else {
  556. if !models.IsErrJobNotExist(err) {
  557. log.Error("system error, %v", err, ctx.Data["MsgID"])
  558. cloudBrainInferenceJobErrorPrepare(ctx, form)
  559. ctx.RenderWithErr("system error", tpl, &form)
  560. return
  561. }
  562. }
  563. if !jobNamePattern.MatchString(displayJobName) {
  564. cloudBrainInferenceJobErrorPrepare(ctx, form)
  565. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  566. return
  567. }
  568. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, jobType)
  569. if err != nil {
  570. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  571. cloudBrainInferenceJobErrorPrepare(ctx, form)
  572. ctx.RenderWithErr("system error", tpl, &form)
  573. return
  574. } else {
  575. if count >= 1 {
  576. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  577. cloudBrainInferenceJobErrorPrepare(ctx, form)
  578. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tpl, &form)
  579. return
  580. }
  581. }
  582. if branchName == "" {
  583. branchName = cloudbrain.DefaultBranchName
  584. }
  585. downloadCode(repo, codePath, branchName)
  586. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  587. resultPath := setting.JobPath + jobName + cloudbrain.ResultPath + "/"
  588. mkResultPath(resultPath)
  589. uploadCodeToMinio(resultPath, jobName, cloudbrain.ResultPath+"/")
  590. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  591. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid)
  592. if err != nil {
  593. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  594. cloudBrainInferenceJobErrorPrepare(ctx, form)
  595. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  596. return
  597. }
  598. req := cloudbrain.GenerateCloudBrainTaskReq{
  599. Ctx: ctx,
  600. DisplayJobName: displayJobName,
  601. JobName: jobName,
  602. Image: image,
  603. Command: command,
  604. Uuids: uuid,
  605. DatasetNames: datasetNames,
  606. DatasetInfos: datasetInfos,
  607. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  608. ModelPath: setting.Attachment.Minio.RealPath + form.TrainUrl,
  609. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  610. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  611. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  612. JobType: jobType,
  613. GpuQueue: gpuQueue,
  614. Description: form.Description,
  615. BranchName: branchName,
  616. BootFile: form.BootFile,
  617. Params: form.Params,
  618. CommitID: commitID,
  619. ResourceSpecId: resourceSpecId,
  620. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  621. ModelName: form.ModelName,
  622. ModelVersion: form.ModelVersion,
  623. CkptName: form.CkptName,
  624. TrainUrl: form.TrainUrl,
  625. LabelName: labelName,
  626. }
  627. err = cloudbrain.GenerateTask(req)
  628. if err != nil {
  629. cloudBrainInferenceJobErrorPrepare(ctx, form)
  630. ctx.RenderWithErr(err.Error(), tpl, &form)
  631. return
  632. }
  633. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/inference-job")
  634. }
  635. /**
  636. 检查用户传输的参数是否符合专属资源池
  637. */
  638. func checkCloudBrainSpecialPool(ctx *context.Context, jobType string, queue string, resourceSpecId int) string {
  639. if cloudbrain.SpecialPools != nil {
  640. var isInPoolOrg = false
  641. var matchSpecialPool = false
  642. for _, specialPool := range cloudbrain.SpecialPools.Pools {
  643. if cloudbrain.IsElementExist(specialPool.JobType, jobType) && cloudbrain.IsQueueInSpecialtPool(specialPool.Pool, queue) {
  644. if cloudbrain.IsResourceSpecInSpecialPool(specialPool.ResourceSpec, resourceSpecId) {
  645. matchSpecialPool = true
  646. org, _ := models.GetOrgByName(specialPool.Org)
  647. if org != nil {
  648. isInPoolOrg, _ = models.IsOrganizationMember(org.ID, ctx.User.ID)
  649. if isInPoolOrg {
  650. break //传入参数,和专属资源池匹配上了,检查通过
  651. }
  652. }
  653. }
  654. }
  655. }
  656. //资源池有匹配上,但是用户不在相应的组织中,返回错误信息。界面已经过滤了选择,界面操作不会到这个逻辑
  657. if matchSpecialPool && !isInPoolOrg {
  658. return ctx.Tr("repo.grampus.no_operate_right")
  659. }
  660. }
  661. //没有匹配到资源池或者没有设置专属资源池,检查通过; 获取和资源池完全匹配检查通过
  662. return ""
  663. }
  664. func CloudBrainRestart(ctx *context.Context) {
  665. var ID = ctx.Params(":id")
  666. var resultCode = "0"
  667. var errorMsg = ""
  668. var status = string(models.JobWaiting)
  669. task := ctx.Cloudbrain
  670. for {
  671. if task.Status != string(models.JobStopped) && task.Status != string(models.JobSucceeded) && task.Status != string(models.JobFailed) {
  672. log.Error("the job(%s) is not stopped", task.JobName, ctx.Data["MsgID"])
  673. resultCode = "-1"
  674. errorMsg = "the job is not stopped"
  675. break
  676. }
  677. if task.Image == "" || task.GpuQueue == "" || task.Type != models.TypeCloudBrainOne {
  678. log.Error("the job(%s) version is too old", task.JobName, ctx.Data["MsgID"])
  679. resultCode = "-1"
  680. errorMsg = "the job's version is too old and can not be restarted"
  681. break
  682. }
  683. if !ctx.IsSigned || (ctx.User.ID != task.UserID && !ctx.IsUserSiteAdmin()) {
  684. log.Error("the user has no right ro restart the job", task.JobName, ctx.Data["MsgID"])
  685. resultCode = "-1"
  686. errorMsg = "you have no right to restart the job"
  687. break
  688. }
  689. var hasSameResource bool
  690. if gpuInfos == nil {
  691. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  692. }
  693. for _, resourceType := range gpuInfos.GpuInfo {
  694. if resourceType.Queue == task.GpuQueue {
  695. hasSameResource = true
  696. break
  697. }
  698. }
  699. if !hasSameResource && cloudbrain.SpecialPools != nil {
  700. for _, specialPool := range cloudbrain.SpecialPools.Pools {
  701. cloudbrain.IsElementExist(specialPool.JobType, string(models.JobTypeDebug))
  702. for _, pool := range specialPool.Pool {
  703. if pool.Queue == task.GpuQueue {
  704. hasSameResource = true
  705. }
  706. }
  707. }
  708. }
  709. if !hasSameResource {
  710. log.Error("has no same resource, can not restart", ctx.Data["MsgID"])
  711. resultCode = "-1"
  712. errorMsg = "the job's version is too old and can not be restarted"
  713. break
  714. }
  715. count, err := models.GetCloudbrainCountByUserID(ctx.User.ID, string(models.JobTypeDebug))
  716. if err != nil {
  717. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  718. resultCode = "-1"
  719. errorMsg = "system error"
  720. break
  721. } else {
  722. if count >= 1 {
  723. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  724. resultCode = "-1"
  725. errorMsg = ctx.Tr("repo.cloudbrain.morethanonejob")
  726. break
  727. }
  728. }
  729. err = cloudbrain.RestartTask(ctx, task, &ID)
  730. if err != nil {
  731. log.Error("RestartTask failed:%v", err.Error(), ctx.Data["MsgID"])
  732. resultCode = "-1"
  733. errorMsg = "system error"
  734. break
  735. }
  736. break
  737. }
  738. ctx.JSON(200, map[string]string{
  739. "result_code": resultCode,
  740. "error_msg": errorMsg,
  741. "status": status,
  742. "id": ID,
  743. })
  744. }
  745. func CloudBrainBenchMarkShow(ctx *context.Context) {
  746. cloudBrainShow(ctx, tplCloudBrainBenchmarkShow, models.JobTypeBenchmark)
  747. }
  748. func CloudBrainShow(ctx *context.Context) {
  749. cloudBrainShow(ctx, tplCloudBrainShow, models.JobTypeDebug)
  750. }
  751. func CloudBrainTrainJobShow(ctx *context.Context) {
  752. cloudBrainShow(ctx, tplCloudBrainTrainJobShow, models.JobTypeTrain)
  753. }
  754. func cloudBrainShow(ctx *context.Context, tpName base.TplName, jobType models.JobType) {
  755. ctx.Data["PageIsCloudBrain"] = true
  756. debugListType := ctx.Query("debugListType")
  757. var task *models.Cloudbrain
  758. var err error
  759. if jobType == models.JobTypeTrain || jobType == models.JobTypeInference {
  760. task, err = models.GetCloudbrainByJobID(ctx.Params(":jobid"))
  761. } else {
  762. task, err = models.GetCloudbrainByIDWithDeleted(ctx.Params(":id"))
  763. }
  764. if err != nil {
  765. log.Info("error:" + err.Error())
  766. ctx.Data["error"] = err.Error()
  767. return
  768. }
  769. result, err := cloudbrain.GetJob(task.JobID)
  770. if err != nil {
  771. log.Info("error:" + err.Error())
  772. ctx.Data["error"] = err.Error()
  773. return
  774. }
  775. if task.JobType == string(models.JobTypeTrain) {
  776. if cloudbrain.TrainResourceSpecs == nil {
  777. json.Unmarshal([]byte(setting.TrainResourceSpecs), &cloudbrain.TrainResourceSpecs)
  778. }
  779. hasSpec := false
  780. for _, tmp := range cloudbrain.TrainResourceSpecs.ResourceSpec {
  781. if tmp.Id == task.ResourceSpecId {
  782. hasSpec = true
  783. ctx.Data["GpuNum"] = tmp.GpuNum
  784. ctx.Data["CpuNum"] = tmp.CpuNum
  785. ctx.Data["MemMiB"] = tmp.MemMiB
  786. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  787. }
  788. }
  789. if !hasSpec && cloudbrain.SpecialPools != nil {
  790. for _, specialPool := range cloudbrain.SpecialPools.Pools {
  791. if specialPool.ResourceSpec != nil {
  792. for _, spec := range specialPool.ResourceSpec {
  793. if task.ResourceSpecId == spec.Id {
  794. ctx.Data["GpuNum"] = spec.GpuNum
  795. ctx.Data["CpuNum"] = spec.CpuNum
  796. ctx.Data["MemMiB"] = spec.MemMiB
  797. ctx.Data["ShareMemMiB"] = spec.ShareMemMiB
  798. break
  799. }
  800. }
  801. }
  802. }
  803. }
  804. } else if task.JobType == string(models.JobTypeInference) {
  805. if cloudbrain.InferenceResourceSpecs == nil {
  806. json.Unmarshal([]byte(setting.InferenceResourceSpecs), &cloudbrain.InferenceResourceSpecs)
  807. }
  808. for _, tmp := range cloudbrain.InferenceResourceSpecs.ResourceSpec {
  809. if tmp.Id == task.ResourceSpecId {
  810. ctx.Data["GpuNum"] = tmp.GpuNum
  811. ctx.Data["CpuNum"] = tmp.CpuNum
  812. ctx.Data["MemMiB"] = tmp.MemMiB
  813. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  814. }
  815. }
  816. } else {
  817. if cloudbrain.ResourceSpecs == nil {
  818. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  819. }
  820. for _, tmp := range cloudbrain.ResourceSpecs.ResourceSpec {
  821. if tmp.Id == task.ResourceSpecId {
  822. ctx.Data["GpuNum"] = tmp.GpuNum
  823. ctx.Data["CpuNum"] = tmp.CpuNum
  824. ctx.Data["MemMiB"] = tmp.MemMiB
  825. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  826. }
  827. }
  828. }
  829. if result != nil {
  830. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  831. jobRes.Resource.Memory = strings.ReplaceAll(jobRes.Resource.Memory, "Mi", "MB")
  832. spec := "GPU数:" + strconv.Itoa(jobRes.Resource.NvidiaComGpu) + ",CPU数:" + strconv.Itoa(jobRes.Resource.CPU) + ",内存(MB):" + jobRes.Resource.Memory
  833. ctx.Data["resource_spec"] = spec
  834. if task.JobType == string(models.JobTypeTrain) {
  835. if trainGpuInfos == nil {
  836. json.Unmarshal([]byte(setting.TrainGpuTypes), &trainGpuInfos)
  837. }
  838. for _, resourceType := range trainGpuInfos.GpuInfo {
  839. if resourceType.Queue == jobRes.Config.GpuType {
  840. ctx.Data["resource_type"] = resourceType.Value
  841. }
  842. }
  843. for _, specialPool := range cloudbrain.SpecialPools.Pools {
  844. for _, resourceType := range specialPool.Pool {
  845. if resourceType.Queue == jobRes.Config.GpuType {
  846. ctx.Data["resource_type"] = resourceType.Value
  847. }
  848. }
  849. }
  850. } else if task.JobType == string(models.JobTypeInference) {
  851. if inferenceGpuInfos == nil {
  852. json.Unmarshal([]byte(setting.InferenceGpuTypes), &inferenceGpuInfos)
  853. }
  854. for _, resourceType := range inferenceGpuInfos.GpuInfo {
  855. if resourceType.Queue == jobRes.Config.GpuType {
  856. ctx.Data["resource_type"] = resourceType.Value
  857. }
  858. }
  859. } else if cloudbrain.IsBenchmarkJob(task.JobType) {
  860. if benchmarkGpuInfos == nil {
  861. json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos)
  862. }
  863. for _, resourceType := range benchmarkGpuInfos.GpuInfo {
  864. if resourceType.Queue == jobRes.Config.GpuType {
  865. ctx.Data["resource_type"] = resourceType.Value
  866. }
  867. }
  868. } else {
  869. if gpuInfos == nil {
  870. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  871. }
  872. for _, resourceType := range gpuInfos.GpuInfo {
  873. if resourceType.Queue == jobRes.Config.GpuType {
  874. ctx.Data["resource_type"] = resourceType.Value
  875. }
  876. }
  877. }
  878. taskRoles := jobRes.TaskRoles
  879. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  880. ctx.Data["taskRes"] = taskRes
  881. ctx.Data["ExitDiagnostics"] = taskRes.TaskStatuses[0].ExitDiagnostics
  882. task.Status = taskRes.TaskStatuses[0].State
  883. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  884. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  885. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  886. if task.DeletedAt.IsZero() { //normal record
  887. err = models.UpdateJob(task)
  888. if err != nil {
  889. ctx.Data["error"] = err.Error()
  890. return
  891. }
  892. } else { //deleted record
  893. }
  894. ctx.Data["result"] = jobRes
  895. } else {
  896. log.Info("error:" + err.Error())
  897. return
  898. }
  899. user, err := models.GetUserByID(task.UserID)
  900. if err == nil {
  901. task.User = user
  902. }
  903. if task.BenchmarkTypeID > 0 {
  904. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  905. if task.BenchmarkTypeID == benchmarkType.Id {
  906. ctx.Data["BenchmarkTypeName"] = benchmarkType.First
  907. task.BenchmarkTypeName = benchmarkType.First
  908. for _, benchmarkChildType := range benchmarkType.Second {
  909. if task.BenchmarkChildTypeID == benchmarkChildType.Id {
  910. ctx.Data["BenchmarkChildTypeName"] = benchmarkChildType.Value
  911. break
  912. }
  913. }
  914. break
  915. }
  916. }
  917. }
  918. if task.JobType == string(models.JobTypeBenchmark) {
  919. task.BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.algorithm")
  920. } else if task.JobType == string(models.JobTypeSnn4imagenet) || task.JobType == string(models.JobTypeBrainScore) {
  921. task.BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.model")
  922. task.BenchmarkTypeName = task.JobType
  923. ctx.Data["BenchmarkTypeName"] = task.JobType
  924. if task.JobType == string(models.JobTypeBrainScore) {
  925. ctx.Data["BenchmarkChildTypeName"] = getBrainRegion(task.BenchmarkChildTypeID)
  926. }
  927. }
  928. if task.TrainJobDuration == "" {
  929. if task.Duration == 0 {
  930. var duration int64
  931. if task.Status == string(models.JobWaiting) {
  932. duration = 0
  933. } else if task.Status == string(models.JobRunning) {
  934. duration = time.Now().Unix() - int64(task.CreatedUnix)
  935. } else {
  936. duration = int64(task.UpdatedUnix) - int64(task.CreatedUnix)
  937. }
  938. task.Duration = duration
  939. }
  940. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  941. }
  942. ctx.Data["duration"] = task.TrainJobDuration
  943. if len(task.Parameters) > 0 {
  944. var parameters models.Parameters
  945. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  946. if err != nil {
  947. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  948. task.Parameters = ""
  949. } else {
  950. if len(parameters.Parameter) > 0 {
  951. paramTemp := ""
  952. for _, Parameter := range parameters.Parameter {
  953. param := Parameter.Label + " = " + Parameter.Value + "; "
  954. paramTemp = paramTemp + param
  955. }
  956. task.Parameters = paramTemp[:len(paramTemp)-2]
  957. } else {
  958. task.Parameters = ""
  959. }
  960. }
  961. }
  962. ctx.Data["task"] = task
  963. labelName := strings.Fields(task.LabelName)
  964. ctx.Data["LabelName"] = labelName
  965. ctx.Data["jobName"] = task.JobName
  966. ctx.Data["displayJobName"] = task.DisplayJobName
  967. version_list_task := make([]*models.Cloudbrain, 0)
  968. version_list_task = append(version_list_task, task)
  969. ctx.Data["version_list_task"] = version_list_task
  970. ctx.Data["debugListType"] = debugListType
  971. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  972. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  973. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  974. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  975. ctx.Data["branchName"] = task.BranchName
  976. ctx.HTML(200, tpName)
  977. }
  978. func CloudBrainDebug(ctx *context.Context) {
  979. task := ctx.Cloudbrain
  980. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  981. ctx.Redirect(debugUrl)
  982. }
  983. func CloudBrainCommitImageShow(ctx *context.Context) {
  984. ctx.Data["PageIsCloudBrain"] = true
  985. ctx.Data["Type"] = ctx.Cloudbrain.Type
  986. ctx.HTML(200, tplCloudBrainImageSubmit)
  987. }
  988. func CloudBrainImageEdit(ctx *context.Context) {
  989. ctx.Data["PageIsImageEdit"] = true
  990. ctx.Data["PageFrom"] = ctx.Params(":from")
  991. var ID = ctx.Params(":id")
  992. id, err := strconv.ParseInt(ID, 10, 64)
  993. if err != nil {
  994. log.Error("GetImageByID failed:%v", err.Error())
  995. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  996. }
  997. image, err := models.GetImageByID(id)
  998. if err != nil {
  999. log.Error("GetImageByID failed:%v", err.Error())
  1000. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  1001. }
  1002. ctx.Data["Image"] = image
  1003. ctx.HTML(http.StatusOK, tplCloudBrainImageEdit)
  1004. }
  1005. func CloudBrainImageEditPost(ctx *context.Context, form auth.EditImageCloudBrainForm) {
  1006. if utf8.RuneCountInString(form.Description) > 255 {
  1007. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  1008. return
  1009. }
  1010. validTopics, errMessage := checkTopics(form.Topics)
  1011. if errMessage != "" {
  1012. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  1013. return
  1014. }
  1015. image, err := models.GetImageByID(form.ID)
  1016. if err != nil {
  1017. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  1018. }
  1019. image.IsPrivate = form.IsPrivate
  1020. image.Description = form.Description
  1021. err = models.WithTx(func(ctx models.DBContext) error {
  1022. if err := models.UpdateLocalImage(image); err != nil {
  1023. return err
  1024. }
  1025. if err := models.SaveImageTopics(image.ID, validTopics...); err != nil {
  1026. return err
  1027. }
  1028. return nil
  1029. })
  1030. if err != nil {
  1031. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  1032. } else {
  1033. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  1034. }
  1035. }
  1036. func CloudBrainImageDelete(ctx *context.Context) {
  1037. var ID = ctx.Params(":id")
  1038. id, err := strconv.ParseInt(ID, 10, 64)
  1039. if err != nil {
  1040. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  1041. return
  1042. }
  1043. err = models.DeleteLocalImage(id)
  1044. if err != nil {
  1045. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_delete_fail")))
  1046. } else {
  1047. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  1048. }
  1049. }
  1050. func CloudBrainCommitImageCheck(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  1051. isExist, _ := models.IsImageExistByUser(form.Tag, ctx.User.ID)
  1052. if isExist {
  1053. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_overwrite")))
  1054. } else {
  1055. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  1056. }
  1057. }
  1058. func CloudBrainAdminCommitImage(ctx *context.Context, form auth.CommitAdminImageCloudBrainForm) {
  1059. if !NamePattern.MatchString(form.Tag) {
  1060. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  1061. return
  1062. }
  1063. if utf8.RuneCountInString(form.Description) > 255 {
  1064. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  1065. return
  1066. }
  1067. validTopics, errMessage := checkTopics(form.Topics)
  1068. if errMessage != "" {
  1069. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  1070. return
  1071. }
  1072. err := cloudbrain.CommitAdminImage(models.CommitImageParams{
  1073. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  1074. ImageDescription: form.Description,
  1075. ImageTag: form.Tag,
  1076. },
  1077. IsPrivate: form.IsPrivate,
  1078. CloudBrainType: form.Type,
  1079. Topics: validTopics,
  1080. UID: ctx.User.ID,
  1081. Type: models.GetRecommondType(form.IsRecommend),
  1082. Place: form.Place,
  1083. })
  1084. if err != nil {
  1085. log.Error("CommitImagefailed")
  1086. if models.IsErrImageTagExist(err) {
  1087. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  1088. } else if models.IsErrorImageCommitting(err) {
  1089. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  1090. } else {
  1091. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  1092. }
  1093. return
  1094. }
  1095. ctx.JSON(200, models.BaseOKMessage)
  1096. }
  1097. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  1098. if !NamePattern.MatchString(form.Tag) {
  1099. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  1100. return
  1101. }
  1102. if utf8.RuneCountInString(form.Description) > 255 {
  1103. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  1104. return
  1105. }
  1106. validTopics, errMessage := checkTopics(form.Topics)
  1107. if errMessage != "" {
  1108. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  1109. return
  1110. }
  1111. err := cloudbrain.CommitImage(ctx.Cloudbrain.JobID, models.CommitImageParams{
  1112. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  1113. Ip: ctx.Cloudbrain.ContainerIp,
  1114. TaskContainerId: ctx.Cloudbrain.ContainerID,
  1115. ImageDescription: form.Description,
  1116. ImageTag: form.Tag,
  1117. },
  1118. IsPrivate: form.IsPrivate,
  1119. CloudBrainType: form.Type,
  1120. Topics: validTopics,
  1121. UID: ctx.User.ID,
  1122. })
  1123. if err != nil {
  1124. log.Error("CommitImage(%s) failed:%v", ctx.Cloudbrain.JobName, err.Error(), ctx.Data["msgID"])
  1125. if models.IsErrImageTagExist(err) {
  1126. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  1127. } else if models.IsErrorImageCommitting(err) {
  1128. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  1129. } else {
  1130. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  1131. }
  1132. return
  1133. }
  1134. ctx.JSON(200, models.BaseOKMessage)
  1135. }
  1136. func checkTopics(Topics string) ([]string, string) {
  1137. var topics = make([]string, 0)
  1138. var topicsStr = strings.TrimSpace(Topics)
  1139. if len(topicsStr) > 0 {
  1140. topics = strings.Split(topicsStr, ",")
  1141. }
  1142. validTopics, invalidTopics := models.SanitizeAndValidateImageTopics(topics)
  1143. if len(validTopics) > 25 {
  1144. return nil, "repo.topic.count_prompt"
  1145. }
  1146. if len(invalidTopics) > 0 {
  1147. return nil, "repo.imagetopic.format_prompt"
  1148. }
  1149. return validTopics, ""
  1150. }
  1151. func CloudBrainStop(ctx *context.Context) {
  1152. var ID = ctx.Params(":id")
  1153. var resultCode = "0"
  1154. var errorMsg = ""
  1155. var status = ""
  1156. task := ctx.Cloudbrain
  1157. for {
  1158. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) || task.Status == string(models.JobSucceeded) {
  1159. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  1160. resultCode = "-1"
  1161. errorMsg = "cloudbrain.Already_stopped"
  1162. break
  1163. }
  1164. err := cloudbrain.StopJob(task.JobID)
  1165. if err != nil {
  1166. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  1167. resultCode = "-1"
  1168. errorMsg = "cloudbrain.Stopped_failed"
  1169. break
  1170. }
  1171. task.Status = string(models.JobStopped)
  1172. if task.EndTime == 0 {
  1173. task.EndTime = timeutil.TimeStampNow()
  1174. }
  1175. task.ComputeAndSetDuration()
  1176. err = models.UpdateJob(task)
  1177. if err != nil {
  1178. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  1179. resultCode = "-1"
  1180. errorMsg = "cloudbrain.Stopped_success_update_status_fail"
  1181. break
  1182. }
  1183. status = task.Status
  1184. break
  1185. }
  1186. ctx.JSON(200, map[string]interface{}{
  1187. "result_code": resultCode,
  1188. "error_msg": ctx.Tr(errorMsg),
  1189. "status": status,
  1190. "id": ID,
  1191. "StatusOK": 0,
  1192. })
  1193. }
  1194. func StopJobsByUserID(userID int64) {
  1195. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  1196. if err != nil {
  1197. log.Warn("Failed to get cloudBrain info", err)
  1198. return
  1199. }
  1200. StopJobs(cloudBrains)
  1201. }
  1202. func StopJobsByRepoID(repoID int64) {
  1203. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  1204. if err != nil {
  1205. log.Warn("Failed to get cloudBrain info", err)
  1206. return
  1207. }
  1208. StopJobs(cloudBrains)
  1209. }
  1210. /**
  1211. */
  1212. func StopJobs(cloudBrains []*models.Cloudbrain) {
  1213. for _, taskInfo := range cloudBrains {
  1214. if taskInfo.Type == models.TypeCloudBrainOne {
  1215. err := retry(3, time.Second*30, func() error {
  1216. return cloudbrain.StopJob(taskInfo.JobID)
  1217. })
  1218. logErrorAndUpdateJobStatus(err, taskInfo)
  1219. } else {
  1220. if taskInfo.JobType == string(models.JobTypeTrain) {
  1221. err := retry(3, time.Second*30, func() error {
  1222. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  1223. return err
  1224. })
  1225. logErrorAndUpdateJobStatus(err, taskInfo)
  1226. } else {
  1227. param := models.NotebookAction{
  1228. Action: models.ActionStop,
  1229. }
  1230. err := retry(3, time.Second*30, func() error {
  1231. _, err := modelarts.ManageNotebook(taskInfo.JobID, param)
  1232. return err
  1233. })
  1234. logErrorAndUpdateJobStatus(err, taskInfo)
  1235. }
  1236. }
  1237. }
  1238. }
  1239. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  1240. for i := 0; i < attempts; i++ {
  1241. if i > 0 {
  1242. log.Warn("retrying after error:", err)
  1243. time.Sleep(sleep)
  1244. }
  1245. err = f()
  1246. if err == nil {
  1247. return nil
  1248. }
  1249. }
  1250. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  1251. }
  1252. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  1253. if err != nil {
  1254. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  1255. } else {
  1256. taskInfo.Status = string(models.JobStopped)
  1257. if taskInfo.EndTime == 0 {
  1258. taskInfo.EndTime = timeutil.TimeStampNow()
  1259. }
  1260. taskInfo.ComputeAndSetDuration()
  1261. err = models.UpdateJob(taskInfo)
  1262. if err != nil {
  1263. log.Warn("UpdateJob failed", err)
  1264. }
  1265. }
  1266. }
  1267. func CloudBrainDel(ctx *context.Context) {
  1268. var listType = ctx.Query("debugListType")
  1269. if err := deleteCloudbrainJob(ctx); err != nil {
  1270. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1271. ctx.ServerError(err.Error(), err)
  1272. return
  1273. }
  1274. var isAdminPage = ctx.Query("isadminpage")
  1275. var isHomePage = ctx.Query("ishomepage")
  1276. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1277. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1278. } else if isHomePage == "true" {
  1279. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1280. } else {
  1281. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  1282. }
  1283. }
  1284. func deleteCloudbrainJob(ctx *context.Context) error {
  1285. task := ctx.Cloudbrain
  1286. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) && task.Status != string(models.JobSucceeded) {
  1287. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  1288. return errors.New("the job has not been stopped")
  1289. }
  1290. err := models.DeleteJob(task)
  1291. if err != nil {
  1292. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  1293. return err
  1294. }
  1295. deleteJobStorage(task.JobName, models.TypeCloudBrainOne)
  1296. return nil
  1297. }
  1298. func CloudBrainShowModels(ctx *context.Context) {
  1299. ctx.Data["PageIsCloudBrain"] = true
  1300. ID := ctx.Params(":id")
  1301. parentDir := ctx.Query("parentDir")
  1302. dirArray := strings.Split(parentDir, "/")
  1303. task, err := models.GetCloudbrainByID(ID)
  1304. if err != nil {
  1305. log.Error("no such job!", ctx.Data["msgID"])
  1306. ctx.ServerError("no such job:", err)
  1307. return
  1308. }
  1309. //get dirs
  1310. dirs, err := GetModelDirs(task.JobName, parentDir)
  1311. if err != nil {
  1312. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  1313. ctx.ServerError("GetModelDirs failed:", err)
  1314. return
  1315. }
  1316. var fileInfos []storage.FileInfo
  1317. err = json.Unmarshal([]byte(dirs), &fileInfos)
  1318. if err != nil {
  1319. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  1320. ctx.ServerError("json.Unmarshal failed:", err)
  1321. return
  1322. }
  1323. for i, fileInfo := range fileInfos {
  1324. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  1325. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  1326. }
  1327. sort.Slice(fileInfos, func(i, j int) bool {
  1328. return fileInfos[i].ModTime > fileInfos[j].ModTime
  1329. })
  1330. ctx.Data["Path"] = dirArray
  1331. ctx.Data["Dirs"] = fileInfos
  1332. ctx.Data["task"] = task
  1333. ctx.Data["ID"] = ID
  1334. ctx.HTML(200, tplCloudBrainShowModels)
  1335. }
  1336. func GetPublicImages(ctx *context.Context) {
  1337. uid := getUID(ctx)
  1338. opts := models.SearchImageOptions{
  1339. IncludePublicOnly: true,
  1340. UID: uid,
  1341. Keyword: ctx.Query("q"),
  1342. Topics: ctx.Query("topic"),
  1343. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  1344. SearchOrderBy: "type desc, num_stars desc,id desc",
  1345. Status: models.IMAGE_STATUS_SUCCESS,
  1346. CloudbrainType: ctx.QueryInt("cloudbrainType"),
  1347. }
  1348. getImages(ctx, &opts)
  1349. }
  1350. func GetCustomImages(ctx *context.Context) {
  1351. uid := getUID(ctx)
  1352. opts := models.SearchImageOptions{
  1353. UID: uid,
  1354. IncludeOwnerOnly: true,
  1355. Keyword: ctx.Query("q"),
  1356. Topics: ctx.Query("topic"),
  1357. Status: -1,
  1358. SearchOrderBy: "id desc",
  1359. }
  1360. getImages(ctx, &opts)
  1361. }
  1362. func GetStarImages(ctx *context.Context) {
  1363. uid := getUID(ctx)
  1364. opts := models.SearchImageOptions{
  1365. UID: uid,
  1366. IncludeStarByMe: true,
  1367. Keyword: ctx.Query("q"),
  1368. Topics: ctx.Query("topic"),
  1369. Status: models.IMAGE_STATUS_SUCCESS,
  1370. SearchOrderBy: "id desc",
  1371. }
  1372. getImages(ctx, &opts)
  1373. }
  1374. func getUID(ctx *context.Context) int64 {
  1375. var uid int64 = -1
  1376. if ctx.IsSigned {
  1377. uid = ctx.User.ID
  1378. }
  1379. return uid
  1380. }
  1381. func GetAllImages(ctx *context.Context) {
  1382. uid := getUID(ctx)
  1383. opts := models.SearchImageOptions{
  1384. UID: uid,
  1385. Keyword: ctx.Query("q"),
  1386. Topics: ctx.Query("topic"),
  1387. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  1388. SearchOrderBy: "id desc",
  1389. Status: -1,
  1390. }
  1391. if ctx.Query("private") != "" {
  1392. if ctx.QueryBool("private") {
  1393. opts.IncludePrivateOnly = true
  1394. } else {
  1395. opts.IncludePublicOnly = true
  1396. }
  1397. }
  1398. getImages(ctx, &opts)
  1399. }
  1400. func getImages(ctx *context.Context, opts *models.SearchImageOptions) {
  1401. page := ctx.QueryInt("page")
  1402. if page <= 0 {
  1403. page = 1
  1404. }
  1405. pageSize := ctx.QueryInt("pageSize")
  1406. if pageSize <= 0 {
  1407. pageSize = 15
  1408. }
  1409. opts.ListOptions = models.ListOptions{
  1410. Page: page,
  1411. PageSize: pageSize,
  1412. }
  1413. imageList, total, err := models.SearchImage(opts)
  1414. if err != nil {
  1415. log.Error("Can not get images:%v", err)
  1416. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  1417. Count: 0,
  1418. Images: []*models.Image{},
  1419. })
  1420. } else {
  1421. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  1422. Count: total,
  1423. Images: imageList,
  1424. })
  1425. }
  1426. }
  1427. func GetModelDirs(jobName string, parentDir string) (string, error) {
  1428. var req string
  1429. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  1430. if parentDir == "" {
  1431. req = "baseDir=" + modelActualPath
  1432. } else {
  1433. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  1434. }
  1435. return getDirs(req)
  1436. }
  1437. func GetResultDirs(jobName string, parentDir string) (string, error) {
  1438. var req string
  1439. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/")
  1440. if parentDir == "" {
  1441. req = "baseDir=" + modelActualPath
  1442. } else {
  1443. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  1444. }
  1445. return getDirs(req)
  1446. }
  1447. func CloudBrainDownloadModel(ctx *context.Context) {
  1448. parentDir := ctx.Query("parentDir")
  1449. fileName := ctx.Query("fileName")
  1450. jobName := ctx.Query("jobName")
  1451. filePath := "jobs/" + jobName + "/model/" + parentDir
  1452. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  1453. if err != nil {
  1454. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  1455. ctx.ServerError("PresignedGetURL", err)
  1456. return
  1457. }
  1458. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  1459. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  1460. }
  1461. func CloudBrainDownloadInferenceResult(ctx *context.Context) {
  1462. parentDir := ctx.Query("parentDir")
  1463. fileName := ctx.Query("fileName")
  1464. jobName := ctx.Query("jobName")
  1465. filePath := "jobs/" + jobName + "/result/" + parentDir
  1466. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  1467. if err != nil {
  1468. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  1469. ctx.ServerError("PresignedGetURL", err)
  1470. return
  1471. }
  1472. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  1473. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  1474. }
  1475. func GetRate(ctx *context.Context) {
  1476. isObjectDetcionAll := ctx.QueryBool("isObjectDetcionAll")
  1477. if isObjectDetcionAll {
  1478. ctx.Redirect(setting.BenchmarkServerHost + "?username=admin")
  1479. return
  1480. }
  1481. var ID = ctx.Params(":id")
  1482. job, err := models.GetCloudbrainByID(ID)
  1483. if err != nil {
  1484. ctx.ServerError("GetCloudbrainByJobID failed", err)
  1485. return
  1486. }
  1487. if job.JobType == string(models.JobTypeBenchmark) {
  1488. log.Info("url=" + setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1489. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1490. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  1491. ctx.Redirect(setting.Snn4imagenetServerHost)
  1492. } else if job.JobType == string(models.JobTypeBrainScore) {
  1493. ctx.Redirect(setting.BrainScoreServerHost)
  1494. } else {
  1495. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  1496. }
  1497. }
  1498. func downloadCode(repo *models.Repository, codePath, branchName string) error {
  1499. //add "file:///" prefix to make the depth valid
  1500. if err := git.Clone(CLONE_FILE_PREFIX+repo.RepoPath(), codePath, git.CloneRepoOptions{Branch: branchName, Depth: 1}); err != nil {
  1501. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  1502. return err
  1503. }
  1504. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  1505. if err != nil {
  1506. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  1507. return err
  1508. }
  1509. defer configFile.Close()
  1510. pos := int64(0)
  1511. reader := bufio.NewReader(configFile)
  1512. for {
  1513. line, err := reader.ReadString('\n')
  1514. if err != nil {
  1515. if err == io.EOF {
  1516. log.Error("not find the remote-url")
  1517. return nil
  1518. } else {
  1519. log.Error("read error: %v", err)
  1520. return err
  1521. }
  1522. }
  1523. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  1524. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  1525. if len(line) > len(originUrl) {
  1526. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  1527. }
  1528. bytes := []byte(originUrl)
  1529. _, err := configFile.WriteAt(bytes, pos)
  1530. if err != nil {
  1531. log.Error("WriteAt failed:%v", err)
  1532. return err
  1533. }
  1534. break
  1535. }
  1536. pos += int64(len(line))
  1537. }
  1538. return nil
  1539. }
  1540. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType, userName string) error {
  1541. err := os.MkdirAll(codePath, os.ModePerm)
  1542. if err != nil {
  1543. log.Error("mkdir codePath failed", err.Error())
  1544. return err
  1545. }
  1546. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  1547. if err != nil {
  1548. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  1549. return err
  1550. }
  1551. if err := git.Clone(CLONE_FILE_PREFIX+repoExt.RepoPath(), codePath, git.CloneRepoOptions{Depth: 1}); err != nil {
  1552. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  1553. return err
  1554. }
  1555. fileName := codePath + cloudbrain.TaskInfoName
  1556. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1557. if err != nil {
  1558. log.Error("OpenFile failed", err.Error())
  1559. return err
  1560. }
  1561. defer f.Close()
  1562. data, err := json.Marshal(models.TaskInfo{
  1563. Username: userName,
  1564. TaskName: taskName,
  1565. CodeName: repo.Name,
  1566. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  1567. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  1568. GpuType: gpuType,
  1569. })
  1570. if err != nil {
  1571. log.Error("json.Marshal failed", err.Error())
  1572. return err
  1573. }
  1574. _, err = f.Write(data)
  1575. if err != nil {
  1576. log.Error("WriteString failed", err.Error())
  1577. return err
  1578. }
  1579. return nil
  1580. }
  1581. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  1582. files, err := readDir(codePath)
  1583. if err != nil {
  1584. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  1585. return err
  1586. }
  1587. for _, file := range files {
  1588. if file.IsDir() {
  1589. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  1590. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  1591. return err
  1592. }
  1593. } else {
  1594. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  1595. sourceFile := codePath + file.Name()
  1596. err = storage.Attachments.UploadObject(destObject, sourceFile)
  1597. if err != nil {
  1598. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  1599. return err
  1600. }
  1601. }
  1602. }
  1603. return nil
  1604. }
  1605. func mkModelPath(modelPath string) error {
  1606. return mkPathAndReadMeFile(modelPath, "You can put the model file into this directory and download it by the web page.")
  1607. }
  1608. func mkResultPath(resultPath string) error {
  1609. return mkPathAndReadMeFile(resultPath, "You can put the result file into this directory and download it by the web page.")
  1610. }
  1611. func mkPathAndReadMeFile(path string, text string) error {
  1612. err := os.MkdirAll(path, os.ModePerm)
  1613. if err != nil {
  1614. log.Error("MkdirAll(%s) failed:%v", path, err)
  1615. return err
  1616. }
  1617. fileName := path + "README"
  1618. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1619. if err != nil {
  1620. log.Error("OpenFile failed", err.Error())
  1621. return err
  1622. }
  1623. defer f.Close()
  1624. _, err = f.WriteString(text)
  1625. if err != nil {
  1626. log.Error("WriteString failed", err.Error())
  1627. return err
  1628. }
  1629. return nil
  1630. }
  1631. func deleteJobStorage(jobName string, cloudbrainType int) error {
  1632. //delete local
  1633. localJobPath := setting.JobPath + jobName
  1634. err := os.RemoveAll(localJobPath)
  1635. if err != nil {
  1636. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  1637. }
  1638. //delete oss
  1639. if cloudbrainType == models.TypeCloudBrainOne {
  1640. dirPath := setting.CBCodePathPrefix + jobName + "/"
  1641. err = storage.Attachments.DeleteDir(dirPath)
  1642. if err != nil {
  1643. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  1644. }
  1645. } else if cloudbrainType == models.TypeCloudBrainTwo {
  1646. //dirPath := setting.CodePathPrefix + jobName + "/"
  1647. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  1648. //if err != nil {
  1649. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  1650. //}
  1651. log.Info("no need to delete")
  1652. } else {
  1653. log.Error("cloudbrainType(%d) error", cloudbrainType)
  1654. }
  1655. return nil
  1656. }
  1657. func SyncCloudbrainStatus() {
  1658. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  1659. if err != nil {
  1660. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  1661. return
  1662. }
  1663. for _, task := range cloudBrains {
  1664. if task.Type == models.TypeCloudBrainOne {
  1665. result, err := cloudbrain.GetJob(task.JobID)
  1666. if err != nil {
  1667. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1668. continue
  1669. }
  1670. if result != nil {
  1671. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  1672. taskRoles := jobRes.TaskRoles
  1673. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1674. task.Status = taskRes.TaskStatuses[0].State
  1675. if task.Status != string(models.JobWaiting) {
  1676. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  1677. err = models.UpdateJob(task)
  1678. if err != nil {
  1679. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1680. }
  1681. var maxDuration int64
  1682. if task.JobType == string(models.JobTypeBenchmark) {
  1683. maxDuration = setting.BenchmarkMaxDuration
  1684. } else if task.JobType == string(models.JobTypeSnn4imagenet) || task.JobType == string(models.JobTypeBrainScore) {
  1685. maxDuration = setting.ModelBenchmarkMaxDuration
  1686. } else {
  1687. maxDuration = setting.MaxDuration
  1688. }
  1689. if task.Duration >= maxDuration && task.JobType != string(models.JobTypeTrain) {
  1690. log.Info("begin to stop job(%s), because of the duration", task.DisplayJobName)
  1691. err = cloudbrain.StopJob(task.JobID)
  1692. if err != nil {
  1693. log.Error("StopJob(%s) failed:%v", task.DisplayJobName, err)
  1694. continue
  1695. }
  1696. task.Status = string(models.JobStopped)
  1697. if task.EndTime == 0 {
  1698. task.EndTime = timeutil.TimeStampNow()
  1699. }
  1700. task.ComputeAndSetDuration()
  1701. err = models.UpdateJob(task)
  1702. if err != nil {
  1703. log.Error("UpdateJob(%s) failed:%v", task.DisplayJobName, err)
  1704. continue
  1705. }
  1706. }
  1707. }
  1708. }
  1709. } else if task.Type == models.TypeCloudBrainTwo {
  1710. if task.JobType == string(models.JobTypeDebug) {
  1711. //result, err := modelarts.GetJob(task.JobID)
  1712. result, err := modelarts.GetNotebook2(task.JobID)
  1713. if err != nil {
  1714. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1715. continue
  1716. }
  1717. if result != nil {
  1718. task.Status = result.Status
  1719. if task.StartTime == 0 && result.Lease.UpdateTime > 0 {
  1720. task.StartTime = timeutil.TimeStamp(result.Lease.UpdateTime / 1000)
  1721. }
  1722. if task.EndTime == 0 && models.IsModelArtsDebugJobTerminal(task.Status) {
  1723. task.EndTime = timeutil.TimeStampNow()
  1724. }
  1725. task.CorrectCreateUnix()
  1726. task.ComputeAndSetDuration()
  1727. err = models.UpdateJob(task)
  1728. if err != nil {
  1729. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1730. continue
  1731. }
  1732. }
  1733. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1734. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1735. if err != nil {
  1736. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1737. continue
  1738. }
  1739. if result != nil {
  1740. task.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  1741. task.Duration = result.Duration / 1000
  1742. task.TrainJobDuration = result.TrainJobDuration
  1743. if task.StartTime == 0 && result.StartTime > 0 {
  1744. task.StartTime = timeutil.TimeStamp(result.StartTime / 1000)
  1745. }
  1746. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1747. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1748. task.EndTime = task.StartTime.Add(task.Duration)
  1749. }
  1750. task.CorrectCreateUnix()
  1751. err = models.UpdateJob(task)
  1752. if err != nil {
  1753. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1754. continue
  1755. }
  1756. }
  1757. } else {
  1758. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1759. }
  1760. } else if task.Type == models.TypeC2Net {
  1761. result, err := grampus.GetJob(task.JobID)
  1762. if err != nil {
  1763. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1764. continue
  1765. }
  1766. if result != nil {
  1767. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  1768. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  1769. }
  1770. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  1771. task.Duration = result.JobInfo.RunSec
  1772. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1773. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  1774. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  1775. }
  1776. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1777. task.EndTime = task.StartTime.Add(task.Duration)
  1778. }
  1779. task.CorrectCreateUnix()
  1780. err = models.UpdateJob(task)
  1781. if err != nil {
  1782. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1783. continue
  1784. }
  1785. }
  1786. } else {
  1787. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1788. }
  1789. }
  1790. return
  1791. }
  1792. func HandleTaskWithNoDuration(ctx *context.Context) {
  1793. mode := ctx.Query("mode")
  1794. log.Info("HandleTaskWithNoDuration start")
  1795. count := 0
  1796. start := time.Now().Unix()
  1797. for {
  1798. var cloudBrains []*models.Cloudbrain
  1799. var err error
  1800. if mode == "1" {
  1801. cloudBrains, err = models.GetStoppedJobWithNoStartTimeEndTime()
  1802. } else {
  1803. cloudBrains, err = models.GetStoppedJobWithNoDurationJob()
  1804. }
  1805. if err != nil {
  1806. log.Error("HandleTaskWithNoTrainJobDuration failed:", err.Error())
  1807. break
  1808. }
  1809. if len(cloudBrains) == 0 {
  1810. log.Info("HandleTaskWithNoTrainJobDuration:no task need handle")
  1811. break
  1812. }
  1813. handleNoDurationTask(cloudBrains)
  1814. count += len(cloudBrains)
  1815. if len(cloudBrains) < 100 {
  1816. log.Info("HandleTaskWithNoTrainJobDuration:task less than 100")
  1817. break
  1818. }
  1819. if time.Now().Unix()-start > 600 {
  1820. log.Info("HandleTaskWithNoDuration : time out")
  1821. ctx.JSON(200, fmt.Sprintf("task stop for time out,count=%d", count))
  1822. return
  1823. }
  1824. }
  1825. log.Info("HandleTaskWithNoTrainJobDuration:count=%d", count)
  1826. ctx.JSON(200, fmt.Sprintf("success,count=%d", count))
  1827. }
  1828. func handleNoDurationTask(cloudBrains []*models.Cloudbrain) {
  1829. for _, task := range cloudBrains {
  1830. time.Sleep(time.Millisecond * 100)
  1831. log.Info("Handle job ,%+v", task)
  1832. if task.Type == models.TypeCloudBrainOne {
  1833. result, err := cloudbrain.GetJob(task.JobID)
  1834. if err != nil {
  1835. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1836. updateDefaultDuration(task)
  1837. continue
  1838. }
  1839. if result != nil {
  1840. if result.Msg != "success" {
  1841. updateDefaultDuration(task)
  1842. continue
  1843. }
  1844. jobRes, err := models.ConvertToJobResultPayload(result.Payload)
  1845. if err != nil || len(jobRes.TaskRoles) == 0 {
  1846. updateDefaultDuration(task)
  1847. continue
  1848. }
  1849. taskRoles := jobRes.TaskRoles
  1850. taskRes, err := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1851. if err != nil || len(taskRes.TaskStatuses) == 0 {
  1852. updateDefaultDuration(task)
  1853. continue
  1854. }
  1855. task.Status = taskRes.TaskStatuses[0].State
  1856. log.Info("task startTime = %v endTime= %v ,jobId=%d", jobRes.JobStatus.StartTime, jobRes.JobStatus.EndTime, task.ID)
  1857. if jobRes.JobStatus.CreatedTime > 0 {
  1858. task.StartTime = timeutil.TimeStamp(jobRes.JobStatus.CreatedTime / 1000)
  1859. if jobRes.JobStatus.CompletedTime > 0 {
  1860. task.EndTime = timeutil.TimeStamp(jobRes.JobStatus.CompletedTime / 1000)
  1861. } else {
  1862. task.EndTime = task.UpdatedUnix
  1863. }
  1864. } else {
  1865. task.StartTime = 0
  1866. task.EndTime = 0
  1867. }
  1868. if task.EndTime < task.StartTime {
  1869. log.Info("endTime[%v] is less than starTime[%v],jobId=%d", task.EndTime, task.StartTime, task.ID)
  1870. st := task.StartTime
  1871. task.StartTime = task.EndTime
  1872. task.EndTime = st
  1873. }
  1874. task.Duration = task.EndTime.AsTime().Unix() - task.StartTime.AsTime().Unix()
  1875. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1876. err = models.UpdateJobDurationWithDeleted(task)
  1877. if err != nil {
  1878. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1879. }
  1880. }
  1881. } else if task.Type == models.TypeCloudBrainTwo {
  1882. if task.JobType == string(models.JobTypeDebug) {
  1883. //result, err := modelarts.GetJob(task.JobID)
  1884. result, err := modelarts.GetNotebook2(task.JobID)
  1885. if err != nil {
  1886. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1887. updateDefaultDuration(task)
  1888. continue
  1889. }
  1890. if result != nil {
  1891. task.Status = result.Status
  1892. startTime := result.Lease.CreateTime
  1893. duration := result.Lease.Duration / 1000
  1894. if startTime > 0 {
  1895. task.StartTime = timeutil.TimeStamp(startTime / 1000)
  1896. task.EndTime = task.StartTime.Add(duration)
  1897. }
  1898. task.CorrectCreateUnix()
  1899. task.ComputeAndSetDuration()
  1900. err = models.UpdateJobDurationWithDeleted(task)
  1901. if err != nil {
  1902. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1903. continue
  1904. }
  1905. }
  1906. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1907. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1908. if err != nil {
  1909. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1910. updateDefaultDuration(task)
  1911. continue
  1912. }
  1913. if result != nil {
  1914. startTime := result.StartTime / 1000
  1915. if startTime > 0 {
  1916. task.StartTime = timeutil.TimeStamp(startTime)
  1917. task.EndTime = task.StartTime.Add(result.Duration / 1000)
  1918. }
  1919. task.ComputeAndSetDuration()
  1920. err = models.UpdateJobDurationWithDeleted(task)
  1921. if err != nil {
  1922. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1923. continue
  1924. }
  1925. }
  1926. } else {
  1927. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1928. }
  1929. } else {
  1930. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1931. }
  1932. }
  1933. }
  1934. func updateDefaultDuration(task *models.Cloudbrain) {
  1935. log.Info("updateDefaultDuration: taskId=%d", task.ID)
  1936. task.StartTime = task.CreatedUnix
  1937. task.EndTime = task.UpdatedUnix
  1938. task.ComputeAndSetDuration()
  1939. err := models.UpdateJobDurationWithDeleted(task)
  1940. if err != nil {
  1941. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1942. }
  1943. }
  1944. func CloudBrainBenchmarkIndex(ctx *context.Context) {
  1945. MustEnableCloudbrain(ctx)
  1946. repo := ctx.Repo.Repository
  1947. page := ctx.QueryInt("page")
  1948. if page <= 0 {
  1949. page = 1
  1950. }
  1951. var jobTypes []string
  1952. jobTypes = append(jobTypes, string(models.JobTypeBenchmark), string(models.JobTypeBrainScore), string(models.JobTypeSnn4imagenet))
  1953. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  1954. ListOptions: models.ListOptions{
  1955. Page: page,
  1956. PageSize: setting.UI.IssuePagingNum,
  1957. },
  1958. RepoID: repo.ID,
  1959. Type: models.TypeCloudBrainOne,
  1960. JobTypes: jobTypes,
  1961. })
  1962. if err != nil {
  1963. ctx.ServerError("Get debugjob faild:", err)
  1964. return
  1965. }
  1966. for i, task := range ciTasks {
  1967. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1968. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  1969. if ciTasks[i].TrainJobDuration == "" {
  1970. if ciTasks[i].Duration == 0 {
  1971. var duration int64
  1972. if task.Status == string(models.JobRunning) {
  1973. duration = time.Now().Unix() - int64(task.Cloudbrain.CreatedUnix)
  1974. } else {
  1975. duration = int64(task.Cloudbrain.UpdatedUnix) - int64(task.Cloudbrain.CreatedUnix)
  1976. }
  1977. ciTasks[i].Duration = duration
  1978. }
  1979. ciTasks[i].TrainJobDuration = models.ConvertDurationToStr(ciTasks[i].Duration)
  1980. }
  1981. ciTasks[i].BenchmarkTypeName = ""
  1982. if ciTasks[i].JobType == string(models.JobTypeBenchmark) {
  1983. ciTasks[i].BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.algorithm")
  1984. } else if ciTasks[i].JobType == string(models.JobTypeSnn4imagenet) || ciTasks[i].JobType == string(models.JobTypeBrainScore) {
  1985. ciTasks[i].BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.model")
  1986. ciTasks[i].BenchmarkTypeName = ciTasks[i].JobType
  1987. if ciTasks[i].JobType == string(models.JobTypeSnn4imagenet) {
  1988. ciTasks[i].BenchmarkTypeRankLink = setting.Snn4imagenetServerHost
  1989. } else {
  1990. ciTasks[i].BenchmarkTypeRankLink = setting.BrainScoreServerHost
  1991. }
  1992. }
  1993. if task.BenchmarkTypeID > 0 {
  1994. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1995. if task.BenchmarkTypeID == benchmarkType.Id {
  1996. ciTasks[i].BenchmarkTypeRankLink = benchmarkType.RankLink
  1997. ciTasks[i].BenchmarkTypeName = benchmarkType.First
  1998. break
  1999. }
  2000. }
  2001. }
  2002. }
  2003. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  2004. ctx.Data["Page"] = pager
  2005. ctx.Data["PageIsCloudBrain"] = true
  2006. ctx.Data["Tasks"] = ciTasks
  2007. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  2008. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  2009. ctx.HTML(200, tplCloudBrainBenchmarkIndex)
  2010. }
  2011. func GetChildTypes(ctx *context.Context) {
  2012. benchmarkTypeID := ctx.QueryInt("benchmark_type_id")
  2013. re := make(map[string]interface{})
  2014. for {
  2015. var isExist bool
  2016. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  2017. if benchmarkTypeID == benchmarkType.Id {
  2018. isExist = true
  2019. re["child_types"] = benchmarkType.Second
  2020. re["result_code"] = "0"
  2021. break
  2022. }
  2023. }
  2024. if !isExist {
  2025. re["result_code"] = "1"
  2026. log.Error("no such benchmark_type_id", ctx.Data["MsgID"])
  2027. re["errMsg"] = "system error"
  2028. break
  2029. }
  2030. break
  2031. }
  2032. ctx.JSON(200, re)
  2033. }
  2034. func CloudBrainBenchmarkNew(ctx *context.Context) {
  2035. ctx.Data["description"] = ""
  2036. ctx.Data["benchmarkTypeID"] = -1
  2037. ctx.Data["benchmark_child_types_id_hidden"] = -1
  2038. err := cloudBrainNewDataPrepare(ctx)
  2039. if err != nil {
  2040. ctx.ServerError("get new cloudbrain info failed", err)
  2041. return
  2042. }
  2043. ctx.HTML(200, tplCloudBrainBenchmarkNew)
  2044. }
  2045. func getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID int, ctx *context.Context) (*models.BenchmarkDataset, error) {
  2046. var childInfo *models.BenchmarkDataset
  2047. var isExist bool
  2048. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  2049. if benchmarkType.Id == benchmarkTypeID {
  2050. for _, childType := range benchmarkType.Second {
  2051. if childType.Id == benchmarkChildTypeID {
  2052. childInfo = childType
  2053. isExist = true
  2054. break
  2055. }
  2056. }
  2057. break
  2058. }
  2059. }
  2060. if !isExist {
  2061. log.Error("no such benchmark_type_id&benchmark_child_type_id")
  2062. return childInfo, errors.New("no such benchmark_type_id&benchmark_child_type_id")
  2063. }
  2064. return childInfo, nil
  2065. }
  2066. func getBenchmarkGpuQueue(gpuQueue string) (string, error) {
  2067. queue := ""
  2068. if benchmarkGpuInfos == nil {
  2069. if err := json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos); err != nil {
  2070. log.Error("json.Unmarshal BenchmarkGpuTypes(%s) failed:%v", setting.BenchmarkGpuTypes, err)
  2071. return queue, err
  2072. }
  2073. }
  2074. var isExist bool
  2075. for _, gpuInfo := range benchmarkGpuInfos.GpuInfo {
  2076. if gpuQueue == gpuInfo.Queue {
  2077. isExist = true
  2078. queue = gpuQueue
  2079. break
  2080. }
  2081. }
  2082. if !isExist {
  2083. log.Error("no such gpuQueue, %s", gpuQueue)
  2084. return queue, errors.New("no such gpuQueue")
  2085. }
  2086. return queue, nil
  2087. }
  2088. func getBenchmarkResourceSpec(resourceSpecID int) (int, error) {
  2089. var id int
  2090. if benchmarkResourceSpecs == nil {
  2091. if err := json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs); err != nil {
  2092. log.Error("json.Unmarshal BenchmarkResourceSpecs(%s) failed:%v", setting.BenchmarkResourceSpecs, err)
  2093. return id, err
  2094. }
  2095. }
  2096. var isExist bool
  2097. for _, resourceSpec := range benchmarkResourceSpecs.ResourceSpec {
  2098. if resourceSpecID == resourceSpec.Id {
  2099. isExist = true
  2100. id = resourceSpecID
  2101. break
  2102. }
  2103. }
  2104. if !isExist {
  2105. log.Error("no such resourceSpecID, %d", resourceSpecID)
  2106. return id, errors.New("no such resourceSpec")
  2107. }
  2108. return id, nil
  2109. }
  2110. func CloudBrainBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  2111. jobType := form.JobType
  2112. if jobType == string(models.JobTypeBenchmark) {
  2113. BenchMarkAlgorithmCreate(ctx, form)
  2114. } else {
  2115. ModelBenchmarkCreate(ctx, form)
  2116. }
  2117. }
  2118. func BenchMarkAlgorithmCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  2119. ctx.Data["PageIsCloudBrain"] = true
  2120. displayJobName := form.DisplayJobName
  2121. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  2122. image := strings.TrimSpace(form.Image)
  2123. gpuQueue := form.GpuType
  2124. command := cloudbrain.CommandBenchmark
  2125. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  2126. resourceSpecId := cloudbrain.BenchMarkResourceID
  2127. benchmarkTypeID := form.BenchmarkTypeID
  2128. benchmarkChildTypeID := form.BenchmarkChildTypeID
  2129. ctx.Data["description"] = form.Description
  2130. ctx.Data["benchmarkTypeID"] = benchmarkTypeID
  2131. ctx.Data["benchmark_child_types_id_hidden"] = benchmarkChildTypeID
  2132. repo := ctx.Repo.Repository
  2133. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeBenchmark), displayJobName)
  2134. if err == nil {
  2135. if len(tasks) != 0 {
  2136. log.Error("the job name did already exist", ctx.Data["MsgID"])
  2137. cloudBrainNewDataPrepare(ctx)
  2138. ctx.RenderWithErr("the job name did already exist", tplCloudBrainBenchmarkNew, &form)
  2139. return
  2140. }
  2141. } else {
  2142. if !models.IsErrJobNotExist(err) {
  2143. log.Error("system error, %v", err, ctx.Data["MsgID"])
  2144. cloudBrainNewDataPrepare(ctx)
  2145. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2146. return
  2147. }
  2148. }
  2149. if !jobNamePattern.MatchString(jobName) {
  2150. cloudBrainNewDataPrepare(ctx)
  2151. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainBenchmarkNew, &form)
  2152. return
  2153. }
  2154. childInfo, err := getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID, ctx)
  2155. if err != nil {
  2156. log.Error("getBenchmarkAttachment failed:%v", err, ctx.Data["MsgID"])
  2157. cloudBrainNewDataPrepare(ctx)
  2158. ctx.RenderWithErr("benchmark type error", tplCloudBrainBenchmarkNew, &form)
  2159. return
  2160. }
  2161. _, err = getBenchmarkGpuQueue(gpuQueue)
  2162. if err != nil {
  2163. log.Error("getBenchmarkGpuQueue failed:%v", err, ctx.Data["MsgID"])
  2164. cloudBrainNewDataPrepare(ctx)
  2165. ctx.RenderWithErr("gpu queue error", tplCloudBrainBenchmarkNew, &form)
  2166. return
  2167. }
  2168. _, err = getBenchmarkResourceSpec(resourceSpecId)
  2169. if err != nil {
  2170. log.Error("getBenchmarkResourceSpec failed:%v", err, ctx.Data["MsgID"])
  2171. cloudBrainNewDataPrepare(ctx)
  2172. ctx.RenderWithErr("resource spec error", tplCloudBrainBenchmarkNew, &form)
  2173. return
  2174. }
  2175. count, err := models.GetBenchmarkCountByUserID(ctx.User.ID)
  2176. if err != nil {
  2177. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  2178. cloudBrainNewDataPrepare(ctx)
  2179. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2180. return
  2181. } else {
  2182. if count >= 1 {
  2183. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  2184. cloudBrainNewDataPrepare(ctx)
  2185. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tplCloudBrainBenchmarkNew, &form)
  2186. return
  2187. }
  2188. }
  2189. os.RemoveAll(codePath)
  2190. if err := downloadCode(repo, codePath, cloudbrain.DefaultBranchName); err != nil {
  2191. log.Error("downloadCode failed, %v", err, ctx.Data["MsgID"])
  2192. cloudBrainNewDataPrepare(ctx)
  2193. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2194. return
  2195. }
  2196. if _, err := os.Stat(codePath + "/train.py"); err != nil {
  2197. if os.IsNotExist(err) {
  2198. // file does not exist
  2199. log.Error("train.py does not exist, %v", err, ctx.Data["MsgID"])
  2200. cloudBrainNewDataPrepare(ctx)
  2201. ctx.RenderWithErr("train.py does not exist", tplCloudBrainBenchmarkNew, &form)
  2202. } else {
  2203. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  2204. cloudBrainNewDataPrepare(ctx)
  2205. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2206. }
  2207. return
  2208. } else if _, err := os.Stat(codePath + "/test.py"); err != nil {
  2209. if os.IsNotExist(err) {
  2210. // file does not exist
  2211. log.Error("test.py does not exist, %v", err, ctx.Data["MsgID"])
  2212. cloudBrainNewDataPrepare(ctx)
  2213. ctx.RenderWithErr("test.py does not exist", tplCloudBrainBenchmarkNew, &form)
  2214. } else {
  2215. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  2216. cloudBrainNewDataPrepare(ctx)
  2217. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2218. }
  2219. return
  2220. }
  2221. if err := uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  2222. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  2223. cloudBrainNewDataPrepare(ctx)
  2224. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2225. return
  2226. }
  2227. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  2228. var gpuType string
  2229. for _, gpuInfo := range gpuInfos.GpuInfo {
  2230. if gpuInfo.Queue == gpuQueue {
  2231. gpuType = gpuInfo.Value
  2232. }
  2233. }
  2234. if err := downloadRateCode(repo, jobName, childInfo.Owner, childInfo.RepoName, benchmarkPath, form.BenchmarkCategory, gpuType, ctx.User.Name); err != nil {
  2235. log.Error("downloadRateCode failed, %v", err, ctx.Data["MsgID"])
  2236. //cloudBrainNewDataPrepare(ctx)
  2237. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2238. //return
  2239. }
  2240. if err := uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/"); err != nil {
  2241. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  2242. //cloudBrainNewDataPrepare(ctx)
  2243. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2244. //return
  2245. }
  2246. uuid := childInfo.Attachment
  2247. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid)
  2248. if err != nil {
  2249. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  2250. cloudBrainNewDataPrepare(ctx)
  2251. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tplCloudBrainBenchmarkNew, &form)
  2252. return
  2253. }
  2254. req := cloudbrain.GenerateCloudBrainTaskReq{
  2255. Ctx: ctx,
  2256. DisplayJobName: displayJobName,
  2257. JobName: jobName,
  2258. Image: image,
  2259. Command: command,
  2260. Uuids: uuid,
  2261. DatasetNames: datasetNames,
  2262. DatasetInfos: datasetInfos,
  2263. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  2264. ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  2265. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  2266. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  2267. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  2268. JobType: string(models.JobTypeBenchmark),
  2269. GpuQueue: gpuQueue,
  2270. Description: form.Description,
  2271. BranchName: cloudbrain.DefaultBranchName,
  2272. BootFile: "",
  2273. Params: "",
  2274. CommitID: "",
  2275. BenchmarkTypeID: benchmarkTypeID,
  2276. BenchmarkChildTypeID: benchmarkChildTypeID,
  2277. ResourceSpecId: resourceSpecId,
  2278. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  2279. }
  2280. err = cloudbrain.GenerateTask(req)
  2281. if err != nil {
  2282. cloudBrainNewDataPrepare(ctx)
  2283. ctx.RenderWithErr(err.Error(), tplCloudBrainBenchmarkNew, &form)
  2284. return
  2285. }
  2286. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  2287. }
  2288. func ModelBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  2289. ctx.Data["PageIsCloudBrain"] = true
  2290. displayJobName := form.DisplayJobName
  2291. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  2292. image := form.Image
  2293. uuid := form.Attachment
  2294. jobType := form.JobType
  2295. gpuQueue := form.GpuType
  2296. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  2297. resourceSpecId := form.ResourceSpecId
  2298. branchName := cloudbrain.DefaultBranchName
  2299. repo := ctx.Repo.Repository
  2300. tpl := tplCloudBrainBenchmarkNew
  2301. command := cloudbrain.GetCloudbrainDebugCommand()
  2302. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  2303. if err == nil {
  2304. if len(tasks) != 0 {
  2305. log.Error("the job name did already exist", ctx.Data["MsgID"])
  2306. cloudBrainNewDataPrepare(ctx)
  2307. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  2308. return
  2309. }
  2310. } else {
  2311. if !models.IsErrJobNotExist(err) {
  2312. log.Error("system error, %v", err, ctx.Data["MsgID"])
  2313. cloudBrainNewDataPrepare(ctx)
  2314. ctx.RenderWithErr("system error", tpl, &form)
  2315. return
  2316. }
  2317. }
  2318. if !jobNamePattern.MatchString(displayJobName) {
  2319. cloudBrainNewDataPrepare(ctx)
  2320. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  2321. return
  2322. }
  2323. if jobType != string(models.JobTypeSnn4imagenet) && jobType != string(models.JobTypeBrainScore) {
  2324. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  2325. cloudBrainNewDataPrepare(ctx)
  2326. ctx.RenderWithErr("jobtype error", tpl, &form)
  2327. return
  2328. }
  2329. count, err := models.GetBenchmarkCountByUserID(ctx.User.ID)
  2330. if err != nil {
  2331. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  2332. cloudBrainNewDataPrepare(ctx)
  2333. ctx.RenderWithErr("system error", tpl, &form)
  2334. return
  2335. } else {
  2336. if count >= 1 {
  2337. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  2338. cloudBrainNewDataPrepare(ctx)
  2339. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tpl, &form)
  2340. return
  2341. }
  2342. }
  2343. downloadCode(repo, codePath, branchName)
  2344. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  2345. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  2346. mkModelPath(modelPath)
  2347. uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/")
  2348. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  2349. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  2350. downloadRateCode(repo, jobName, setting.Snn4imagenetOwner, setting.Snn4imagenetName, snn4imagenetPath, "", "", ctx.User.Name)
  2351. uploadCodeToMinio(snn4imagenetPath+"/", jobName, cloudbrain.Snn4imagenetMountPath+"/")
  2352. command = fmt.Sprintf(cloudbrain.Snn4imagenetCommand, displayJobName, trimSpaceNewlineInString(form.Description))
  2353. }
  2354. benchmarkChildTypeID := 0
  2355. brainScorePath := setting.JobPath + jobName + cloudbrain.BrainScoreMountPath
  2356. if setting.IsBrainScoreEnabled && jobType == string(models.JobTypeBrainScore) {
  2357. downloadRateCode(repo, jobName, setting.BrainScoreOwner, setting.BrainScoreName, brainScorePath, "", "", ctx.User.Name)
  2358. uploadCodeToMinio(brainScorePath+"/", jobName, cloudbrain.BrainScoreMountPath+"/")
  2359. benchmarkChildTypeID = form.BenchmarkChildTypeID
  2360. command = fmt.Sprintf(cloudbrain.BrainScoreCommand, getBrainRegion(benchmarkChildTypeID), displayJobName, trimSpaceNewlineInString(form.Description))
  2361. }
  2362. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid)
  2363. if err != nil {
  2364. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  2365. cloudBrainNewDataPrepare(ctx)
  2366. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  2367. return
  2368. }
  2369. req := cloudbrain.GenerateCloudBrainTaskReq{
  2370. Ctx: ctx,
  2371. DisplayJobName: displayJobName,
  2372. JobName: jobName,
  2373. Image: image,
  2374. Command: command,
  2375. Uuids: uuid,
  2376. DatasetNames: datasetNames,
  2377. DatasetInfos: datasetInfos,
  2378. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  2379. ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  2380. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  2381. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  2382. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  2383. JobType: jobType,
  2384. GpuQueue: gpuQueue,
  2385. Description: form.Description,
  2386. BranchName: branchName,
  2387. BootFile: form.BootFile,
  2388. Params: form.Params,
  2389. CommitID: "",
  2390. BenchmarkTypeID: 0,
  2391. BenchmarkChildTypeID: benchmarkChildTypeID,
  2392. ResourceSpecId: resourceSpecId,
  2393. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  2394. }
  2395. err = cloudbrain.GenerateTask(req)
  2396. if err != nil {
  2397. cloudBrainNewDataPrepare(ctx)
  2398. ctx.RenderWithErr(err.Error(), tpl, &form)
  2399. return
  2400. }
  2401. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  2402. }
  2403. func getBrainRegion(benchmarkChildTypeID int) string {
  2404. values := []string{"V1", "V2", "V4", "IT"}
  2405. return values[benchmarkChildTypeID]
  2406. }
  2407. func trimSpaceNewlineInString(s string) string {
  2408. re := regexp.MustCompile(`\r?\n`)
  2409. return re.ReplaceAllString(s, " ")
  2410. }
  2411. func BenchmarkDel(ctx *context.Context) {
  2412. if err := deleteCloudbrainJob(ctx); err != nil {
  2413. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  2414. ctx.ServerError(err.Error(), err)
  2415. return
  2416. }
  2417. var isAdminPage = ctx.Query("isadminpage")
  2418. var isHomePage = ctx.Query("ishomepage")
  2419. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  2420. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  2421. } else if isHomePage == "true" {
  2422. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  2423. } else {
  2424. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  2425. }
  2426. }
  2427. func CloudBrainTrainJobNew(ctx *context.Context) {
  2428. err := cloudBrainNewDataPrepare(ctx)
  2429. if err != nil {
  2430. ctx.ServerError("get new train-job info failed", err)
  2431. return
  2432. }
  2433. ctx.HTML(http.StatusOK, tplCloudBrainTrainJobNew)
  2434. }
  2435. func InferenceCloudBrainJobNew(ctx *context.Context) {
  2436. err := cloudBrainNewDataPrepare(ctx)
  2437. if err != nil {
  2438. ctx.ServerError("get new train-job info failed", err)
  2439. return
  2440. }
  2441. ctx.HTML(http.StatusOK, tplCloudBrainInferenceJobNew)
  2442. }
  2443. func InferenceCloudBrainJobShow(ctx *context.Context) {
  2444. cloudBrainShow(ctx, tplCloudBrainInferenceJobShow, models.JobTypeInference)
  2445. }
  2446. func DownloadInferenceResultFile(ctx *context.Context) {
  2447. var jobID = ctx.Params(":jobid")
  2448. var versionName = ctx.Query("version_name")
  2449. task, err := models.GetCloudbrainByJobIDAndVersionName(jobID, versionName)
  2450. if err != nil {
  2451. log.Error("GetCloudbrainByJobID(%s) failed:%v", task.JobName, err.Error())
  2452. return
  2453. }
  2454. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, task.ResultUrl)
  2455. returnFileName := task.DisplayJobName + ".zip"
  2456. MinioDownloadManyFile(task.ResultUrl, ctx, returnFileName, allFile)
  2457. }
  2458. func getInferenceJobCommand(form auth.CreateCloudBrainInferencForm) (string, error) {
  2459. var command string
  2460. bootFile := strings.TrimSpace(form.BootFile)
  2461. params := form.Params
  2462. if !strings.HasSuffix(bootFile, ".py") {
  2463. log.Error("bootFile(%s) format error", bootFile)
  2464. return command, errors.New("bootFile format error")
  2465. }
  2466. var parameters models.Parameters
  2467. var param string
  2468. if len(params) != 0 {
  2469. err := json.Unmarshal([]byte(params), &parameters)
  2470. if err != nil {
  2471. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  2472. return command, err
  2473. }
  2474. for _, parameter := range parameters.Parameter {
  2475. param += " --" + parameter.Label + "=" + parameter.Value
  2476. }
  2477. }
  2478. param += " --modelname" + "=" + form.CkptName
  2479. command += "python /code/" + bootFile + param + " > " + cloudbrain.ResultPath + "/" + form.DisplayJobName + "-" + cloudbrain.LogFile
  2480. return command, nil
  2481. }
  2482. func getTrainJobCommand(form auth.CreateCloudBrainForm) (string, error) {
  2483. var command string
  2484. bootFile := strings.TrimSpace(form.BootFile)
  2485. params := form.Params
  2486. if !strings.HasSuffix(bootFile, ".py") {
  2487. log.Error("bootFile(%s) format error", bootFile)
  2488. return command, errors.New("bootFile format error")
  2489. }
  2490. var parameters models.Parameters
  2491. var param string
  2492. if len(params) != 0 {
  2493. err := json.Unmarshal([]byte(params), &parameters)
  2494. if err != nil {
  2495. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  2496. return command, err
  2497. }
  2498. for _, parameter := range parameters.Parameter {
  2499. param += " --" + parameter.Label + "=" + parameter.Value
  2500. }
  2501. }
  2502. command += "python /code/" + bootFile + param + " > " + cloudbrain.ModelMountPath + "/" + form.DisplayJobName + "-" + cloudbrain.LogFile
  2503. return command, nil
  2504. }
  2505. func CloudBrainTrainJobDel(ctx *context.Context) {
  2506. var listType = ctx.Query("listType")
  2507. if err := deleteCloudbrainJob(ctx); err != nil {
  2508. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  2509. ctx.ServerError(err.Error(), err)
  2510. return
  2511. }
  2512. var isAdminPage = ctx.Query("isadminpage")
  2513. var isHomePage = ctx.Query("ishomepage")
  2514. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  2515. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  2516. } else if isHomePage == "true" {
  2517. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  2518. } else {
  2519. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  2520. }
  2521. }
  2522. func GetBenchmarkTypes(ctx *context.Context) *models.BenchmarkTypes {
  2523. var lang = ctx.Locale.Language()
  2524. if benchmarkTypesMap[lang] == nil {
  2525. var val = i18n.Tr(lang, BENCHMARK_TYPE_CODE)
  2526. //use config
  2527. val = setting.BenchmarkTypes
  2528. var tempType *models.BenchmarkTypes
  2529. if err := json.Unmarshal([]byte(val), &tempType); err != nil {
  2530. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", val, err, ctx.Data["MsgID"])
  2531. return &models.BenchmarkTypes{}
  2532. }
  2533. benchmarkTypesMap[lang] = tempType
  2534. }
  2535. return benchmarkTypesMap[lang]
  2536. }