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

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