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