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

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
2 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
4 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
4 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
2 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
2 years ago
3 years ago
4 years ago
2 years ago
4 years ago
2 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
4 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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
2 years ago
3 years ago
4 years ago
3 years ago
4 years ago
2 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
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
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 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
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
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
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
2 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
4 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
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917
  1. package repo
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "regexp"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "unicode/utf8"
  16. "code.gitea.io/gitea/modules/dataset"
  17. "code.gitea.io/gitea/services/cloudbrain/cloudbrainTask"
  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, jobType string) 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. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainOne, jobType)
  121. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  122. if ctx.Cloudbrain != nil {
  123. ctx.Data["branch_name"] = ctx.Cloudbrain.BranchName
  124. ctx.Data["image"] = ctx.Cloudbrain.Image
  125. ctx.Data["image_id"] = ctx.Cloudbrain.ImageID
  126. ctx.Data["boot_file"] = ctx.Cloudbrain.BootFile
  127. ctx.Data["description"] = ctx.Cloudbrain.Description
  128. spec, _ := resource.GetCloudbrainSpec(ctx.Cloudbrain.ID)
  129. if spec != nil {
  130. ctx.Data["spec_id"] = spec.ID
  131. }
  132. ctx.Data["run_para_list"] = ctx.Cloudbrain.Parameters
  133. ctx.Data["model_name"] = ctx.Cloudbrain.ModelName
  134. ctx.Data["label_name"] = ctx.Cloudbrain.LabelName
  135. ctx.Data["ckpt_name"] = ctx.Cloudbrain.CkptName
  136. ctx.Data["model_version"] = ctx.Cloudbrain.ModelVersion
  137. ctx.Data["pre_train_model_url"] = ctx.Cloudbrain.PreTrainModelUrl
  138. ctx.Data["compute_resource"] = ctx.Cloudbrain.ComputeResource
  139. uuids, datasetNames := dataset.GetFilterDeletedAttachments(ctx.Cloudbrain.Uuid)
  140. ctx.Data["attachment"] = uuids
  141. ctx.Data["dataset_name"] = datasetNames
  142. ctx.Data["cluster_type"] = models.OpenICluster
  143. }
  144. return nil
  145. }
  146. func prepareCloudbrainOneSpecs(ctx *context.Context) {
  147. debugSpecs, _ := resource.FindAvailableSpecs(ctx.User.ID, models.FindSpecsOptions{
  148. JobType: models.JobTypeDebug,
  149. ComputeResource: models.GPU,
  150. Cluster: models.OpenICluster,
  151. AiCenterCode: models.AICenterOfCloudBrainOne,
  152. })
  153. ctx.Data["debug_specs"] = debugSpecs
  154. trainSpecs, _ := resource.FindAvailableSpecs(ctx.User.ID, models.FindSpecsOptions{
  155. JobType: models.JobTypeTrain,
  156. ComputeResource: models.GPU,
  157. Cluster: models.OpenICluster,
  158. AiCenterCode: models.AICenterOfCloudBrainOne,
  159. })
  160. ctx.Data["train_specs"] = trainSpecs
  161. inferenceSpecs, _ := resource.FindAvailableSpecs(ctx.User.ID, models.FindSpecsOptions{
  162. JobType: models.JobTypeInference,
  163. ComputeResource: models.GPU,
  164. Cluster: models.OpenICluster,
  165. AiCenterCode: models.AICenterOfCloudBrainOne,
  166. })
  167. ctx.Data["inference_specs"] = inferenceSpecs
  168. benchmarkSpecs, _ := resource.FindAvailableSpecs(ctx.User.ID, models.FindSpecsOptions{
  169. JobType: models.JobTypeBenchmark,
  170. ComputeResource: models.GPU,
  171. Cluster: models.OpenICluster,
  172. AiCenterCode: models.AICenterOfCloudBrainOne,
  173. })
  174. ctx.Data["benchmark_specs"] = benchmarkSpecs
  175. }
  176. func CloudBrainNew(ctx *context.Context) {
  177. err := cloudBrainNewDataPrepare(ctx, string(models.JobTypeDebug))
  178. if err != nil {
  179. ctx.ServerError("get new cloudbrain info failed", err)
  180. return
  181. }
  182. ctx.Data["PageIsGPUDebug"] = true
  183. ctx.HTML(200, tplCloudBrainNew)
  184. }
  185. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  186. ctx.Data["IsCreate"] = true
  187. cloudBrainCreate(ctx, form)
  188. }
  189. func cloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  190. ctx.Data["PageIsCloudBrain"] = true
  191. displayJobName := form.DisplayJobName
  192. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  193. image := strings.TrimSpace(form.Image)
  194. uuids := form.Attachment
  195. jobType := form.JobType
  196. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  197. branchName := form.BranchName
  198. bootFile := strings.TrimSpace(form.BootFile)
  199. repo := ctx.Repo.Repository
  200. tpl := tplCloudBrainNew
  201. if jobType == string(models.JobTypeTrain) {
  202. tpl = tplCloudBrainTrainJobNew
  203. }
  204. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), jobType, displayJobName))
  205. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  206. if !isOk {
  207. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  208. cloudBrainNewDataPrepare(ctx, jobType)
  209. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tpl, &form)
  210. return
  211. }
  212. defer lock.UnLock()
  213. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  214. if err == nil {
  215. if len(tasks) != 0 {
  216. log.Error("the job name did already exist", ctx.Data["MsgID"])
  217. cloudBrainNewDataPrepare(ctx, jobType)
  218. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  219. return
  220. }
  221. } else {
  222. if !models.IsErrJobNotExist(err) {
  223. log.Error("system error, %v", err, ctx.Data["MsgID"])
  224. cloudBrainNewDataPrepare(ctx, jobType)
  225. ctx.RenderWithErr("system error", tpl, &form)
  226. return
  227. }
  228. }
  229. if !jobNamePattern.MatchString(displayJobName) {
  230. cloudBrainNewDataPrepare(ctx, jobType)
  231. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  232. return
  233. }
  234. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) && jobType != string(models.JobTypeTrain) {
  235. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  236. cloudBrainNewDataPrepare(ctx, jobType)
  237. ctx.RenderWithErr("jobtype error", tpl, &form)
  238. return
  239. }
  240. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainOne, jobType)
  241. if err != nil {
  242. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  243. cloudBrainNewDataPrepare(ctx, jobType)
  244. ctx.RenderWithErr("system error", tpl, &form)
  245. return
  246. } else {
  247. if count >= 1 {
  248. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  249. cloudBrainNewDataPrepare(ctx, jobType)
  250. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tpl, &form)
  251. return
  252. }
  253. }
  254. var datasetInfos map[string]models.DatasetInfo
  255. var datasetNames string
  256. //var
  257. if uuids != "" {
  258. datasetInfos, datasetNames, err = models.GetDatasetInfo(uuids)
  259. if err != nil {
  260. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  261. cloudBrainNewDataPrepare(ctx, jobType)
  262. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  263. return
  264. }
  265. }
  266. command := cloudbrain.GetCloudbrainDebugCommand()
  267. if jobType == string(models.JobTypeTrain) {
  268. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  269. if err != nil || !bootFileExist {
  270. log.Error("Get bootfile error:", err, ctx.Data["MsgID"])
  271. cloudBrainNewDataPrepare(ctx, jobType)
  272. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tpl, &form)
  273. return
  274. }
  275. tpl = tplCloudBrainTrainJobNew
  276. commandTrain, err := getTrainJobCommand(form)
  277. if err != nil {
  278. log.Error("getTrainJobCommand failed: %v", err)
  279. cloudBrainNewDataPrepare(ctx, jobType)
  280. ctx.RenderWithErr(err.Error(), tpl, &form)
  281. return
  282. }
  283. command = commandTrain
  284. }
  285. if branchName == "" {
  286. branchName = cloudbrain.DefaultBranchName
  287. }
  288. errStr := loadCodeAndMakeModelPath(repo, codePath, branchName, jobName, cloudbrain.ModelMountPath)
  289. if errStr != "" {
  290. cloudBrainNewDataPrepare(ctx, jobType)
  291. ctx.RenderWithErr(ctx.Tr(errStr), tpl, &form)
  292. return
  293. }
  294. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  295. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  296. JobType: models.JobType(jobType),
  297. ComputeResource: models.GPU,
  298. Cluster: models.OpenICluster,
  299. AiCenterCode: models.AICenterOfCloudBrainOne})
  300. if err != nil || spec == nil {
  301. cloudBrainNewDataPrepare(ctx, jobType)
  302. ctx.RenderWithErr("Resource specification not available", tpl, &form)
  303. return
  304. }
  305. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  306. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  307. cloudBrainNewDataPrepare(ctx, jobType)
  308. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tpl, &form)
  309. return
  310. }
  311. req := cloudbrain.GenerateCloudBrainTaskReq{
  312. Ctx: ctx,
  313. DisplayJobName: displayJobName,
  314. JobName: jobName,
  315. Image: image,
  316. Command: command,
  317. Uuids: uuids,
  318. DatasetNames: datasetNames,
  319. DatasetInfos: datasetInfos,
  320. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  321. ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  322. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  323. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  324. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  325. JobType: jobType,
  326. Description: form.Description,
  327. BranchName: branchName,
  328. BootFile: form.BootFile,
  329. Params: form.Params,
  330. CommitID: commitID,
  331. BenchmarkTypeID: 0,
  332. BenchmarkChildTypeID: 0,
  333. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  334. Spec: spec,
  335. }
  336. if form.ModelName != "" { //使用预训练模型训练
  337. req.ModelName = form.ModelName
  338. req.LabelName = form.LabelName
  339. req.CkptName = form.CkptName
  340. req.ModelVersion = form.ModelVersion
  341. req.PreTrainModelPath = setting.Attachment.Minio.RealPath + form.PreTrainModelUrl
  342. req.PreTrainModelUrl = form.PreTrainModelUrl
  343. }
  344. err = cloudbrain.GenerateTask(req)
  345. if err != nil {
  346. cloudBrainNewDataPrepare(ctx, jobType)
  347. ctx.RenderWithErr(err.Error(), tpl, &form)
  348. return
  349. }
  350. if jobType == string(models.JobTypeTrain) {
  351. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=all")
  352. } else {
  353. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=all")
  354. }
  355. }
  356. func CloudBrainTrainJobVersionCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  357. ctx.Data["IsCreate"] = false
  358. cloudBrainCreate(ctx, form)
  359. }
  360. func loadCodeAndMakeModelPath(repo *models.Repository, codePath string, branchName string, jobName string, resultPath string) string {
  361. err := downloadCode(repo, codePath, branchName)
  362. if err != nil {
  363. return "cloudbrain.load_code_failed"
  364. }
  365. err = uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  366. if err != nil {
  367. return "cloudbrain.load_code_failed"
  368. }
  369. modelPath := setting.JobPath + jobName + resultPath + "/"
  370. err = mkModelPath(modelPath)
  371. if err != nil {
  372. return "cloudbrain.load_code_failed"
  373. }
  374. err = uploadCodeToMinio(modelPath, jobName, resultPath+"/")
  375. if err != nil {
  376. return "cloudbrain.load_code_failed"
  377. }
  378. return ""
  379. }
  380. func CloudBrainInferenceJobCreate(ctx *context.Context, form auth.CreateCloudBrainInferencForm) {
  381. ctx.Data["PageIsCloudBrain"] = true
  382. displayJobName := form.DisplayJobName
  383. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  384. image := strings.TrimSpace(form.Image)
  385. uuid := form.Attachment
  386. jobType := string(models.JobTypeInference)
  387. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  388. branchName := form.BranchName
  389. bootFile := strings.TrimSpace(form.BootFile)
  390. labelName := form.LabelName
  391. repo := ctx.Repo.Repository
  392. tpl := tplCloudBrainInferenceJobNew
  393. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), jobType, displayJobName))
  394. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  395. if !isOk {
  396. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  397. cloudBrainNewDataPrepare(ctx, jobType)
  398. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tpl, &form)
  399. return
  400. }
  401. defer lock.UnLock()
  402. ckptUrl := setting.Attachment.Minio.RealPath + form.TrainUrl + form.CkptName
  403. log.Info("ckpt url:" + ckptUrl)
  404. command, err := getInferenceJobCommand(form)
  405. if err != nil {
  406. log.Error("getTrainJobCommand failed: %v", err)
  407. cloudBrainNewDataPrepare(ctx, jobType)
  408. ctx.RenderWithErr(err.Error(), tpl, &form)
  409. return
  410. }
  411. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  412. if err == nil {
  413. if len(tasks) != 0 {
  414. log.Error("the job name did already exist", ctx.Data["MsgID"])
  415. cloudBrainNewDataPrepare(ctx, jobType)
  416. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  417. return
  418. }
  419. } else {
  420. if !models.IsErrJobNotExist(err) {
  421. log.Error("system error, %v", err, ctx.Data["MsgID"])
  422. cloudBrainNewDataPrepare(ctx, jobType)
  423. ctx.RenderWithErr("system error", tpl, &form)
  424. return
  425. }
  426. }
  427. if !jobNamePattern.MatchString(displayJobName) {
  428. cloudBrainNewDataPrepare(ctx, jobType)
  429. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  430. return
  431. }
  432. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  433. if err != nil || !bootFileExist {
  434. log.Error("Get bootfile error:", err, ctx.Data["MsgID"])
  435. cloudBrainNewDataPrepare(ctx, jobType)
  436. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tpl, &form)
  437. return
  438. }
  439. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainOne, jobType)
  440. if err != nil {
  441. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  442. cloudBrainNewDataPrepare(ctx, jobType)
  443. ctx.RenderWithErr("system error", tpl, &form)
  444. return
  445. } else {
  446. if count >= 1 {
  447. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  448. cloudBrainNewDataPrepare(ctx, jobType)
  449. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tpl, &form)
  450. return
  451. }
  452. }
  453. if branchName == "" {
  454. branchName = cloudbrain.DefaultBranchName
  455. }
  456. errStr := loadCodeAndMakeModelPath(repo, codePath, branchName, jobName, cloudbrain.ResultPath)
  457. if errStr != "" {
  458. cloudBrainNewDataPrepare(ctx, jobType)
  459. ctx.RenderWithErr(ctx.Tr(errStr), tpl, &form)
  460. return
  461. }
  462. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  463. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid)
  464. if err != nil {
  465. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  466. cloudBrainNewDataPrepare(ctx, jobType)
  467. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  468. return
  469. }
  470. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  471. JobType: models.JobTypeInference,
  472. ComputeResource: models.GPU,
  473. Cluster: models.OpenICluster,
  474. AiCenterCode: models.AICenterOfCloudBrainOne})
  475. if err != nil || spec == nil {
  476. cloudBrainNewDataPrepare(ctx, jobType)
  477. ctx.RenderWithErr("Resource specification not available", tpl, &form)
  478. return
  479. }
  480. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  481. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  482. cloudBrainNewDataPrepare(ctx, jobType)
  483. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tpl, &form)
  484. return
  485. }
  486. req := cloudbrain.GenerateCloudBrainTaskReq{
  487. Ctx: ctx,
  488. DisplayJobName: displayJobName,
  489. JobName: jobName,
  490. Image: image,
  491. Command: command,
  492. Uuids: uuid,
  493. DatasetNames: datasetNames,
  494. DatasetInfos: datasetInfos,
  495. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  496. ModelPath: setting.Attachment.Minio.RealPath + form.TrainUrl,
  497. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  498. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  499. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  500. JobType: jobType,
  501. Description: form.Description,
  502. BranchName: branchName,
  503. BootFile: form.BootFile,
  504. Params: form.Params,
  505. CommitID: commitID,
  506. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  507. ModelName: form.ModelName,
  508. ModelVersion: form.ModelVersion,
  509. CkptName: form.CkptName,
  510. TrainUrl: form.TrainUrl,
  511. LabelName: labelName,
  512. Spec: spec,
  513. }
  514. err = cloudbrain.GenerateTask(req)
  515. if err != nil {
  516. cloudBrainNewDataPrepare(ctx, jobType)
  517. ctx.RenderWithErr(err.Error(), tpl, &form)
  518. return
  519. }
  520. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/inference-job")
  521. }
  522. /**
  523. 检查用户传输的参数是否符合专属资源池
  524. */
  525. func checkCloudBrainSpecialPool(ctx *context.Context, jobType string, queue string, resourceSpecId int) string {
  526. if cloudbrain.SpecialPools != nil {
  527. var isInPoolOrg = false
  528. var matchSpecialPool = false
  529. for _, specialPool := range cloudbrain.SpecialPools.Pools {
  530. if cloudbrain.IsElementExist(specialPool.JobType, jobType) && cloudbrain.IsQueueInSpecialtPool(specialPool.Pool, queue) {
  531. if cloudbrain.IsResourceSpecInSpecialPool(specialPool.ResourceSpec, resourceSpecId) {
  532. matchSpecialPool = true
  533. org, _ := models.GetOrgByName(specialPool.Org)
  534. if org != nil {
  535. isInPoolOrg, _ = models.IsOrganizationMember(org.ID, ctx.User.ID)
  536. if isInPoolOrg {
  537. break //传入参数,和专属资源池匹配上了,检查通过
  538. }
  539. }
  540. }
  541. }
  542. }
  543. //资源池有匹配上,但是用户不在相应的组织中,返回错误信息。界面已经过滤了选择,界面操作不会到这个逻辑
  544. if matchSpecialPool && !isInPoolOrg {
  545. return ctx.Tr("repo.grampus.no_operate_right")
  546. }
  547. }
  548. //没有匹配到资源池或者没有设置专属资源池,检查通过; 获取和资源池完全匹配检查通过
  549. return ""
  550. }
  551. func CloudBrainRestart(ctx *context.Context) {
  552. var ID = ctx.Params(":id")
  553. var resultCode = "0"
  554. var errorMsg = ""
  555. var status = string(models.JobWaiting)
  556. task := ctx.Cloudbrain
  557. for {
  558. if task.Status != string(models.JobStopped) && task.Status != string(models.JobSucceeded) && task.Status != string(models.JobFailed) {
  559. log.Error("the job(%s) is not stopped", task.JobName, ctx.Data["MsgID"])
  560. resultCode = "-1"
  561. errorMsg = "the job is not stopped"
  562. break
  563. }
  564. if task.Image == "" || task.GpuQueue == "" || task.Type != models.TypeCloudBrainOne {
  565. log.Error("the job(%s) version is too old", task.JobName, ctx.Data["MsgID"])
  566. resultCode = "-1"
  567. errorMsg = "the job's version is too old and can not be restarted"
  568. break
  569. }
  570. if !ctx.IsSigned || (ctx.User.ID != task.UserID && !ctx.IsUserSiteAdmin()) {
  571. log.Error("the user has no right ro restart the job", task.JobName, ctx.Data["MsgID"])
  572. resultCode = "-1"
  573. errorMsg = "you have no right to restart the job"
  574. break
  575. }
  576. specOld, err := resource.GetCloudbrainSpec(task.ID)
  577. if err != nil || specOld == nil {
  578. log.Error("CloudBrainRestart GetCloudbrainSpec error.task.id = %d", task.ID)
  579. resultCode = "-1"
  580. errorMsg = "Resource specification not support any more"
  581. break
  582. }
  583. spec, err := resource.GetAndCheckSpec(ctx.User.ID, specOld.ID, models.FindSpecsOptions{
  584. JobType: models.JobType(task.JobType),
  585. ComputeResource: models.GPU,
  586. Cluster: models.OpenICluster,
  587. AiCenterCode: models.AICenterOfCloudBrainOne})
  588. if err != nil || spec == nil {
  589. log.Error("CloudBrainRestart GetAndCheckSpec error.task.id = %d", task.ID)
  590. resultCode = "-1"
  591. errorMsg = "Resource specification not support any more"
  592. break
  593. }
  594. task.Spec = spec
  595. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  596. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  597. resultCode = "-1"
  598. errorMsg = ctx.Tr("points.insufficient_points_balance")
  599. break
  600. }
  601. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainOne, string(models.JobTypeDebug))
  602. if err != nil {
  603. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  604. resultCode = "-1"
  605. errorMsg = "system error"
  606. break
  607. } else {
  608. if count >= 1 {
  609. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  610. resultCode = "-1"
  611. errorMsg = ctx.Tr("repo.cloudbrain.morethanonejob")
  612. break
  613. }
  614. }
  615. err = cloudbrain.RestartTask(ctx, task, &ID)
  616. if err != nil {
  617. log.Error("RestartTask failed:%v", err.Error(), ctx.Data["MsgID"])
  618. resultCode = "-1"
  619. errorMsg = "system error"
  620. break
  621. }
  622. break
  623. }
  624. ctx.JSON(200, map[string]string{
  625. "result_code": resultCode,
  626. "error_msg": errorMsg,
  627. "status": status,
  628. "id": ID,
  629. })
  630. }
  631. func CloudBrainBenchMarkShow(ctx *context.Context) {
  632. cloudBrainShow(ctx, tplCloudBrainBenchmarkShow, models.JobTypeBenchmark)
  633. }
  634. func CloudBrainShow(ctx *context.Context) {
  635. cloudBrainShow(ctx, tplCloudBrainShow, models.JobTypeDebug)
  636. }
  637. func CloudBrainTrainJobShow(ctx *context.Context) {
  638. cloudBrainShow(ctx, tplCloudBrainTrainJobShow, models.JobTypeTrain)
  639. }
  640. func cloudBrainShow(ctx *context.Context, tpName base.TplName, jobType models.JobType) {
  641. ctx.Data["PageIsCloudBrain"] = true
  642. debugListType := ctx.Query("debugListType")
  643. cloudbrain.InitSpecialPool()
  644. var task *models.Cloudbrain
  645. var err error
  646. if jobType == models.JobTypeTrain || jobType == models.JobTypeInference {
  647. task, err = models.GetCloudbrainByJobID(ctx.Params(":jobid"))
  648. } else {
  649. task, err = models.GetCloudbrainByIDWithDeleted(ctx.Params(":id"))
  650. }
  651. if task.JobType == string(models.JobTypeModelSafety) {
  652. GetAiSafetyTaskTmpl(ctx)
  653. return
  654. }
  655. if err != nil {
  656. log.Info("error:" + err.Error())
  657. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  658. return
  659. }
  660. result, err := cloudbrain.GetJob(task.JobID)
  661. if err != nil {
  662. log.Info("error:" + err.Error())
  663. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  664. return
  665. }
  666. prepareSpec4Show(ctx, task)
  667. if ctx.Written() {
  668. return
  669. }
  670. if result != nil {
  671. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  672. taskRoles := jobRes.TaskRoles
  673. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  674. ctx.Data["taskRes"] = taskRes
  675. ctx.Data["ExitDiagnostics"] = taskRes.TaskStatuses[0].ExitDiagnostics
  676. oldStatus := task.Status
  677. task.Status = taskRes.TaskStatuses[0].State
  678. task.ContainerIp = ""
  679. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  680. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  681. if task.DeletedAt.IsZero() { //normal record
  682. if oldStatus != task.Status {
  683. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  684. }
  685. err = models.UpdateJob(task)
  686. if err != nil {
  687. ctx.Data["error"] = err.Error()
  688. return
  689. }
  690. } else { //deleted record
  691. }
  692. ctx.Data["result"] = jobRes
  693. } else {
  694. log.Info("error:" + err.Error())
  695. return
  696. }
  697. user, err := models.GetUserByID(task.UserID)
  698. if err == nil {
  699. task.User = user
  700. }
  701. if task.BenchmarkTypeID > 0 {
  702. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  703. if task.BenchmarkTypeID == benchmarkType.Id {
  704. ctx.Data["BenchmarkTypeName"] = benchmarkType.First
  705. task.BenchmarkTypeName = benchmarkType.First
  706. for _, benchmarkChildType := range benchmarkType.Second {
  707. if task.BenchmarkChildTypeID == benchmarkChildType.Id {
  708. ctx.Data["BenchmarkChildTypeName"] = benchmarkChildType.Value
  709. break
  710. }
  711. }
  712. break
  713. }
  714. }
  715. }
  716. if task.JobType == string(models.JobTypeBenchmark) {
  717. task.BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.algorithm")
  718. } else if task.JobType == string(models.JobTypeSnn4imagenet) || task.JobType == string(models.JobTypeBrainScore) {
  719. task.BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.model")
  720. task.BenchmarkTypeName = task.JobType
  721. ctx.Data["BenchmarkTypeName"] = task.JobType
  722. if task.JobType == string(models.JobTypeBrainScore) {
  723. ctx.Data["BenchmarkChildTypeName"] = getBrainRegion(task.BenchmarkChildTypeID)
  724. }
  725. }
  726. if task.TrainJobDuration == "" {
  727. if task.Duration == 0 {
  728. var duration int64
  729. if task.Status == string(models.JobWaiting) {
  730. duration = 0
  731. } else if task.Status == string(models.JobRunning) {
  732. duration = time.Now().Unix() - int64(task.CreatedUnix)
  733. } else {
  734. duration = int64(task.UpdatedUnix) - int64(task.CreatedUnix)
  735. }
  736. task.Duration = duration
  737. }
  738. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  739. }
  740. ctx.Data["duration"] = task.TrainJobDuration
  741. if len(task.Parameters) > 0 {
  742. var parameters models.Parameters
  743. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  744. if err != nil {
  745. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  746. task.Parameters = ""
  747. } else {
  748. if len(parameters.Parameter) > 0 {
  749. paramTemp := ""
  750. for _, Parameter := range parameters.Parameter {
  751. param := Parameter.Label + " = " + Parameter.Value + "; "
  752. paramTemp = paramTemp + param
  753. }
  754. task.Parameters = paramTemp[:len(paramTemp)-2]
  755. } else {
  756. task.Parameters = ""
  757. }
  758. }
  759. }
  760. ctx.Data["datasetDownload"] = GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, false)
  761. ctx.Data["task"] = task
  762. labelName := strings.Fields(task.LabelName)
  763. ctx.Data["LabelName"] = labelName
  764. ctx.Data["jobName"] = task.JobName
  765. ctx.Data["displayJobName"] = task.DisplayJobName
  766. version_list_task := make([]*models.Cloudbrain, 0)
  767. version_list_task = append(version_list_task, task)
  768. ctx.Data["version_list_task"] = version_list_task
  769. ctx.Data["debugListType"] = debugListType
  770. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  771. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  772. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  773. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  774. ctx.Data["branchName"] = task.BranchName
  775. ctx.HTML(200, tpName)
  776. }
  777. func CloudBrainDebug(ctx *context.Context) {
  778. task := ctx.Cloudbrain
  779. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  780. ctx.Redirect(debugUrl)
  781. }
  782. func prepareSpec4Show(ctx *context.Context, task *models.Cloudbrain) {
  783. s, err := resource.GetCloudbrainSpec(task.ID)
  784. if err != nil {
  785. log.Info("error:" + err.Error())
  786. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  787. return
  788. }
  789. ctx.Data["Spec"] = s
  790. }
  791. func oldPrepareSpec4Show(ctx *context.Context, task *models.Cloudbrain) {
  792. hasSpec := false
  793. if task.JobType == string(models.JobTypeTrain) {
  794. if cloudbrain.TrainResourceSpecs == nil {
  795. json.Unmarshal([]byte(setting.TrainResourceSpecs), &cloudbrain.TrainResourceSpecs)
  796. }
  797. for _, tmp := range cloudbrain.TrainResourceSpecs.ResourceSpec {
  798. if tmp.Id == task.ResourceSpecId {
  799. hasSpec = true
  800. ctx.Data["GpuNum"] = tmp.GpuNum
  801. ctx.Data["CpuNum"] = tmp.CpuNum
  802. ctx.Data["MemMiB"] = tmp.MemMiB
  803. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  804. break
  805. }
  806. }
  807. } else if task.JobType == string(models.JobTypeInference) {
  808. if cloudbrain.InferenceResourceSpecs == nil {
  809. json.Unmarshal([]byte(setting.InferenceResourceSpecs), &cloudbrain.InferenceResourceSpecs)
  810. }
  811. for _, tmp := range cloudbrain.InferenceResourceSpecs.ResourceSpec {
  812. if tmp.Id == task.ResourceSpecId {
  813. hasSpec = true
  814. ctx.Data["GpuNum"] = tmp.GpuNum
  815. ctx.Data["CpuNum"] = tmp.CpuNum
  816. ctx.Data["MemMiB"] = tmp.MemMiB
  817. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  818. break
  819. }
  820. }
  821. } else {
  822. if cloudbrain.ResourceSpecs == nil {
  823. json.Unmarshal([]byte(setting.ResourceSpecs), &cloudbrain.ResourceSpecs)
  824. }
  825. for _, tmp := range cloudbrain.ResourceSpecs.ResourceSpec {
  826. if tmp.Id == task.ResourceSpecId {
  827. hasSpec = true
  828. ctx.Data["GpuNum"] = tmp.GpuNum
  829. ctx.Data["CpuNum"] = tmp.CpuNum
  830. ctx.Data["MemMiB"] = tmp.MemMiB
  831. ctx.Data["ShareMemMiB"] = tmp.ShareMemMiB
  832. break
  833. }
  834. }
  835. }
  836. if !hasSpec && cloudbrain.SpecialPools != nil {
  837. for _, specialPool := range cloudbrain.SpecialPools.Pools {
  838. if specialPool.ResourceSpec != nil {
  839. for _, spec := range specialPool.ResourceSpec {
  840. if task.ResourceSpecId == spec.Id {
  841. ctx.Data["GpuNum"] = spec.GpuNum
  842. ctx.Data["CpuNum"] = spec.CpuNum
  843. ctx.Data["MemMiB"] = spec.MemMiB
  844. ctx.Data["ShareMemMiB"] = spec.ShareMemMiB
  845. break
  846. }
  847. }
  848. }
  849. }
  850. }
  851. }
  852. func CloudBrainCommitImageShow(ctx *context.Context) {
  853. ctx.Data["PageIsCloudBrain"] = true
  854. ctx.Data["Type"] = ctx.Cloudbrain.Type
  855. ctx.HTML(200, tplCloudBrainImageSubmit)
  856. }
  857. func GetImage(ctx *context.Context) {
  858. var ID = ctx.Params(":id")
  859. id, _ := strconv.ParseInt(ID, 10, 64)
  860. image, err := models.GetImageByID(id)
  861. if err != nil {
  862. log.Error("GetImageByID failed:%v", err.Error())
  863. ctx.JSON(http.StatusNotFound, nil)
  864. }
  865. ctx.JSON(http.StatusOK, image)
  866. }
  867. func CloudBrainImageEdit(ctx *context.Context) {
  868. ctx.Data["PageIsImageEdit"] = true
  869. ctx.Data["PageFrom"] = ctx.Params(":from")
  870. var ID = ctx.Params(":id")
  871. id, err := strconv.ParseInt(ID, 10, 64)
  872. if err != nil {
  873. log.Error("GetImageByID failed:%v", err.Error())
  874. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  875. }
  876. image, err := models.GetImageByID(id)
  877. if err != nil {
  878. log.Error("GetImageByID failed:%v", err.Error())
  879. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  880. }
  881. ctx.Data["Image"] = image
  882. ctx.HTML(http.StatusOK, tplCloudBrainImageEdit)
  883. }
  884. func CloudBrainImageEditPost(ctx *context.Context, form auth.EditImageCloudBrainForm) {
  885. if utf8.RuneCountInString(form.Description) > 255 {
  886. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  887. return
  888. }
  889. validTopics, errMessage := checkTopics(form.Topics)
  890. if errMessage != "" {
  891. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  892. return
  893. }
  894. image, err := models.GetImageByID(form.ID)
  895. if err != nil {
  896. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  897. }
  898. image.IsPrivate = form.IsPrivate
  899. image.Description = form.Description
  900. err = models.WithTx(func(ctx models.DBContext) error {
  901. if err := models.UpdateLocalImage(image); err != nil {
  902. return err
  903. }
  904. if err := models.SaveImageTopics(image.ID, validTopics...); err != nil {
  905. return err
  906. }
  907. return nil
  908. })
  909. if err != nil {
  910. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  911. } else {
  912. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  913. }
  914. }
  915. func CloudBrainImageDelete(ctx *context.Context) {
  916. var ID = ctx.Params(":id")
  917. id, err := strconv.ParseInt(ID, 10, 64)
  918. if err != nil {
  919. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  920. return
  921. }
  922. err = models.DeleteLocalImage(id)
  923. if err != nil {
  924. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_delete_fail")))
  925. } else {
  926. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  927. }
  928. }
  929. func CloudBrainCommitImageCheck(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  930. isExist, _ := models.IsImageExistByUser(form.Tag, ctx.User.ID)
  931. if isExist {
  932. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_overwrite")))
  933. } else {
  934. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  935. }
  936. }
  937. func CloudBrainAdminCommitImage(ctx *context.Context, form auth.CommitAdminImageCloudBrainForm) {
  938. if !NamePattern.MatchString(form.Tag) {
  939. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  940. return
  941. }
  942. if utf8.RuneCountInString(form.Description) > 255 {
  943. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  944. return
  945. }
  946. validTopics, errMessage := checkTopics(form.Topics)
  947. if errMessage != "" {
  948. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  949. return
  950. }
  951. err := cloudbrain.CommitAdminImage(models.CommitImageParams{
  952. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  953. ImageDescription: form.Description,
  954. ImageTag: form.Tag,
  955. },
  956. IsPrivate: form.IsPrivate,
  957. CloudBrainType: form.Type,
  958. Topics: validTopics,
  959. UID: ctx.User.ID,
  960. Type: models.GetRecommondType(form.IsRecommend),
  961. Place: form.Place,
  962. }, ctx.User)
  963. if err != nil {
  964. log.Error("CommitImagefailed")
  965. if models.IsErrImageTagExist(err) {
  966. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  967. } else if models.IsErrorImageCommitting(err) {
  968. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  969. } else {
  970. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  971. }
  972. return
  973. }
  974. ctx.JSON(200, models.BaseOKMessage)
  975. }
  976. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  977. if !NamePattern.MatchString(form.Tag) {
  978. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  979. return
  980. }
  981. if utf8.RuneCountInString(form.Description) > 255 {
  982. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  983. return
  984. }
  985. validTopics, errMessage := checkTopics(form.Topics)
  986. if errMessage != "" {
  987. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  988. return
  989. }
  990. err := cloudbrain.CommitImage(ctx.Cloudbrain.JobID, models.CommitImageParams{
  991. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  992. Ip: ctx.Cloudbrain.ContainerIp,
  993. TaskContainerId: ctx.Cloudbrain.ContainerID,
  994. ImageDescription: form.Description,
  995. ImageTag: form.Tag,
  996. },
  997. IsPrivate: form.IsPrivate,
  998. CloudBrainType: form.Type,
  999. Topics: validTopics,
  1000. UID: ctx.User.ID,
  1001. }, ctx.User)
  1002. if err != nil {
  1003. log.Error("CommitImage(%s) failed:%v", ctx.Cloudbrain.JobName, err.Error(), ctx.Data["msgID"])
  1004. if models.IsErrImageTagExist(err) {
  1005. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  1006. } else if models.IsErrorImageCommitting(err) {
  1007. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  1008. } else if isOver20GError(err) {
  1009. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_over_20g")))
  1010. } else {
  1011. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  1012. }
  1013. return
  1014. }
  1015. ctx.JSON(200, models.BaseOKMessage)
  1016. }
  1017. func isOver20GError(err error) bool {
  1018. return strings.Contains(err.Error(), "over max image size 20GB")
  1019. }
  1020. func checkTopics(Topics string) ([]string, string) {
  1021. var topics = make([]string, 0)
  1022. var topicsStr = strings.TrimSpace(Topics)
  1023. if len(topicsStr) > 0 {
  1024. topics = strings.Split(topicsStr, ",")
  1025. }
  1026. validTopics, invalidTopics := models.SanitizeAndValidateImageTopics(topics)
  1027. if len(validTopics) > 25 {
  1028. return nil, "repo.topic.count_prompt"
  1029. }
  1030. if len(invalidTopics) > 0 {
  1031. return nil, "repo.imagetopic.format_prompt"
  1032. }
  1033. return validTopics, ""
  1034. }
  1035. func CloudBrainStop(ctx *context.Context) {
  1036. var ID = ctx.Params(":id")
  1037. var resultCode = "0"
  1038. var errorMsg = ""
  1039. var status = ""
  1040. task := ctx.Cloudbrain
  1041. for {
  1042. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) || task.Status == string(models.JobSucceeded) {
  1043. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  1044. resultCode = "-1"
  1045. errorMsg = "cloudbrain.Already_stopped"
  1046. resultCode = task.Status
  1047. break
  1048. }
  1049. err := cloudbrain.StopJob(task.JobID)
  1050. if err != nil {
  1051. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  1052. resultCode = "-1"
  1053. errorMsg = "cloudbrain.Stopped_failed"
  1054. break
  1055. }
  1056. oldStatus := task.Status
  1057. task.Status = string(models.JobStopped)
  1058. if task.EndTime == 0 {
  1059. task.EndTime = timeutil.TimeStampNow()
  1060. }
  1061. task.ComputeAndSetDuration()
  1062. if oldStatus != task.Status {
  1063. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  1064. }
  1065. err = models.UpdateJob(task)
  1066. if err != nil {
  1067. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  1068. resultCode = "-1"
  1069. errorMsg = "cloudbrain.Stopped_success_update_status_fail"
  1070. break
  1071. }
  1072. status = task.Status
  1073. break
  1074. }
  1075. ctx.JSON(200, map[string]interface{}{
  1076. "result_code": resultCode,
  1077. "error_msg": ctx.Tr(errorMsg),
  1078. "status": status,
  1079. "id": ID,
  1080. "StatusOK": 0,
  1081. })
  1082. }
  1083. func StopJobsByUserID(userID int64) {
  1084. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  1085. if err != nil {
  1086. log.Warn("Failed to get cloudBrain info", err)
  1087. return
  1088. }
  1089. StopJobs(cloudBrains)
  1090. }
  1091. func StopJobsByRepoID(repoID int64) {
  1092. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  1093. if err != nil {
  1094. log.Warn("Failed to get cloudBrain info", err)
  1095. return
  1096. }
  1097. StopJobs(cloudBrains)
  1098. }
  1099. func DeleteJobsByRepoID(repoID int64) {
  1100. cloudBrains, err := models.GetCloudbrainsNeededDeleteByRepoID(repoID)
  1101. if err != nil {
  1102. log.Warn("Failed to get cloudBrain info", err)
  1103. return
  1104. }
  1105. DeleteJobs(cloudBrains)
  1106. }
  1107. /**
  1108. */
  1109. func StopJobs(cloudBrains []*models.Cloudbrain) {
  1110. for _, taskInfo := range cloudBrains {
  1111. if taskInfo.Type == models.TypeCloudBrainOne {
  1112. err := retry(3, time.Second*30, func() error {
  1113. return cloudbrain.StopJob(taskInfo.JobID)
  1114. })
  1115. logErrorAndUpdateJobStatus(err, taskInfo)
  1116. } else if taskInfo.Type == models.TypeCloudBrainTwo {
  1117. if taskInfo.JobType == string(models.JobTypeTrain) {
  1118. err := retry(3, time.Second*30, func() error {
  1119. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  1120. return err
  1121. })
  1122. logErrorAndUpdateJobStatus(err, taskInfo)
  1123. } else {
  1124. param := models.NotebookAction{
  1125. Action: models.ActionStop,
  1126. }
  1127. err := retry(3, time.Second*30, func() error {
  1128. _, err := modelarts.ManageNotebook(taskInfo.JobID, param)
  1129. return err
  1130. })
  1131. logErrorAndUpdateJobStatus(err, taskInfo)
  1132. }
  1133. } else if taskInfo.Type == models.TypeC2Net {
  1134. if taskInfo.JobType == string(models.JobTypeTrain) {
  1135. err := retry(3, time.Second*30, func() error {
  1136. _, err := grampus.StopJob(taskInfo.JobID)
  1137. return err
  1138. })
  1139. logErrorAndUpdateJobStatus(err, taskInfo)
  1140. }
  1141. }
  1142. }
  1143. }
  1144. func DeleteJobs(cloudBrains []*models.Cloudbrain) {
  1145. for _, taskInfo := range cloudBrains {
  1146. err := models.DeleteJob(taskInfo)
  1147. if err != nil {
  1148. log.Warn("Failed to DeleteJob:", err)
  1149. return
  1150. }
  1151. if taskInfo.Type == models.TypeCloudBrainOne {
  1152. cloudbrain.DelCloudBrainJob(taskInfo.JobName)
  1153. DeleteCloudbrainJobStorage(taskInfo.JobName, models.TypeCloudBrainOne)
  1154. }
  1155. if taskInfo.Type == models.TypeCloudBrainTwo {
  1156. if taskInfo.JobType == string(models.JobTypeTrain) || taskInfo.JobType == string(models.JobTypeInference) {
  1157. modelarts.DelTrainJob(taskInfo.JobID)
  1158. DeleteJobStorage(taskInfo.JobName)
  1159. }
  1160. if taskInfo.JobType == string(models.JobTypeDebug) {
  1161. modelarts.DelNotebook2(taskInfo.JobID)
  1162. }
  1163. }
  1164. if taskInfo.Type == models.TypeC2Net {
  1165. if taskInfo.JobType == string(models.JobTypeTrain) {
  1166. cloudbrain.DelCloudBrainJob(taskInfo.JobName)
  1167. DeleteCloudbrainJobStorage(taskInfo.JobName, models.TypeCloudBrainOne)
  1168. }
  1169. }
  1170. }
  1171. }
  1172. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  1173. for i := 0; i < attempts; i++ {
  1174. if i > 0 {
  1175. log.Warn("retrying after error:", err)
  1176. time.Sleep(sleep)
  1177. }
  1178. err = f()
  1179. if err == nil {
  1180. return nil
  1181. }
  1182. }
  1183. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  1184. }
  1185. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  1186. if err != nil {
  1187. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  1188. } else {
  1189. oldStatus := taskInfo.Status
  1190. taskInfo.Status = string(models.JobStopped)
  1191. if taskInfo.EndTime == 0 {
  1192. taskInfo.EndTime = timeutil.TimeStampNow()
  1193. }
  1194. taskInfo.ComputeAndSetDuration()
  1195. if oldStatus != taskInfo.Status {
  1196. notification.NotifyChangeCloudbrainStatus(taskInfo, oldStatus)
  1197. }
  1198. err = models.UpdateJob(taskInfo)
  1199. if err != nil {
  1200. log.Warn("UpdateJob failed", err)
  1201. }
  1202. }
  1203. }
  1204. func CloudBrainDel(ctx *context.Context) {
  1205. var listType = ctx.Query("debugListType")
  1206. if err := deleteCloudbrainJob(ctx); err != nil {
  1207. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1208. ctx.ServerError(err.Error(), err)
  1209. return
  1210. }
  1211. var isAdminPage = ctx.Query("isadminpage")
  1212. var isHomePage = ctx.Query("ishomepage")
  1213. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1214. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1215. } else if isHomePage == "true" {
  1216. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1217. } else {
  1218. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  1219. }
  1220. }
  1221. func deleteCloudbrainJob(ctx *context.Context) error {
  1222. task := ctx.Cloudbrain
  1223. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) && task.Status != string(models.JobSucceeded) {
  1224. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  1225. return errors.New("the job has not been stopped")
  1226. }
  1227. err := models.DeleteJob(task)
  1228. if err != nil {
  1229. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  1230. return err
  1231. }
  1232. DeleteCloudbrainJobStorage(task.JobName, models.TypeCloudBrainOne)
  1233. return nil
  1234. }
  1235. func CloudBrainShowModels(ctx *context.Context) {
  1236. ctx.Data["PageIsCloudBrain"] = true
  1237. ID := ctx.Params(":id")
  1238. parentDir := ctx.Query("parentDir")
  1239. dirArray := strings.Split(parentDir, "/")
  1240. task, err := models.GetCloudbrainByID(ID)
  1241. if err != nil {
  1242. log.Error("no such job!", ctx.Data["msgID"])
  1243. ctx.ServerError("no such job:", err)
  1244. return
  1245. }
  1246. //get dirs
  1247. dirs, err := GetModelDirs(task.JobName, parentDir)
  1248. if err != nil {
  1249. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  1250. ctx.ServerError("GetModelDirs failed:", err)
  1251. return
  1252. }
  1253. var fileInfos []storage.FileInfo
  1254. err = json.Unmarshal([]byte(dirs), &fileInfos)
  1255. if err != nil {
  1256. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  1257. ctx.ServerError("json.Unmarshal failed:", err)
  1258. return
  1259. }
  1260. for i, fileInfo := range fileInfos {
  1261. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  1262. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  1263. }
  1264. sort.Slice(fileInfos, func(i, j int) bool {
  1265. return fileInfos[i].ModTime > fileInfos[j].ModTime
  1266. })
  1267. ctx.Data["Path"] = dirArray
  1268. ctx.Data["Dirs"] = fileInfos
  1269. ctx.Data["task"] = task
  1270. ctx.Data["ID"] = ID
  1271. ctx.HTML(200, tplCloudBrainShowModels)
  1272. }
  1273. func GetPublicImages(ctx *context.Context) {
  1274. uid := getUID(ctx)
  1275. opts := models.SearchImageOptions{
  1276. IncludePublicOnly: true,
  1277. UID: uid,
  1278. Keyword: ctx.Query("q"),
  1279. Topics: ctx.Query("topic"),
  1280. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  1281. SearchOrderBy: "type desc, num_stars desc,id desc",
  1282. Status: models.IMAGE_STATUS_SUCCESS,
  1283. CloudbrainType: ctx.QueryInt("cloudbrainType"),
  1284. }
  1285. getImages(ctx, &opts)
  1286. }
  1287. func GetCustomImages(ctx *context.Context) {
  1288. uid := getUID(ctx)
  1289. opts := models.SearchImageOptions{
  1290. UID: uid,
  1291. IncludeOwnerOnly: true,
  1292. Keyword: ctx.Query("q"),
  1293. Topics: ctx.Query("topic"),
  1294. Status: -1,
  1295. SearchOrderBy: "id desc",
  1296. }
  1297. getImages(ctx, &opts)
  1298. }
  1299. func GetStarImages(ctx *context.Context) {
  1300. uid := getUID(ctx)
  1301. opts := models.SearchImageOptions{
  1302. UID: uid,
  1303. IncludeStarByMe: true,
  1304. Keyword: ctx.Query("q"),
  1305. Topics: ctx.Query("topic"),
  1306. Status: models.IMAGE_STATUS_SUCCESS,
  1307. SearchOrderBy: "id desc",
  1308. }
  1309. getImages(ctx, &opts)
  1310. }
  1311. func getUID(ctx *context.Context) int64 {
  1312. var uid int64 = -1
  1313. if ctx.IsSigned {
  1314. uid = ctx.User.ID
  1315. }
  1316. return uid
  1317. }
  1318. func GetAllImages(ctx *context.Context) {
  1319. uid := getUID(ctx)
  1320. opts := models.SearchImageOptions{
  1321. UID: uid,
  1322. Keyword: ctx.Query("q"),
  1323. Topics: ctx.Query("topic"),
  1324. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  1325. SearchOrderBy: "id desc",
  1326. Status: -1,
  1327. }
  1328. if ctx.Query("private") != "" {
  1329. if ctx.QueryBool("private") {
  1330. opts.IncludePrivateOnly = true
  1331. } else {
  1332. opts.IncludePublicOnly = true
  1333. }
  1334. }
  1335. getImages(ctx, &opts)
  1336. }
  1337. func getImages(ctx *context.Context, opts *models.SearchImageOptions) {
  1338. page := ctx.QueryInt("page")
  1339. if page <= 0 {
  1340. page = 1
  1341. }
  1342. pageSize := ctx.QueryInt("pageSize")
  1343. if pageSize <= 0 {
  1344. pageSize = 15
  1345. }
  1346. opts.ListOptions = models.ListOptions{
  1347. Page: page,
  1348. PageSize: pageSize,
  1349. }
  1350. imageList, total, err := models.SearchImage(opts)
  1351. if err != nil {
  1352. log.Error("Can not get images:%v", err)
  1353. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  1354. Count: 0,
  1355. Images: []*models.Image{},
  1356. })
  1357. } else {
  1358. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  1359. Count: total,
  1360. Images: imageList,
  1361. })
  1362. }
  1363. }
  1364. func GetModelDirs(jobName string, parentDir string) (string, error) {
  1365. var req string
  1366. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  1367. if parentDir == "" {
  1368. req = "baseDir=" + modelActualPath
  1369. } else {
  1370. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  1371. }
  1372. return getDirs(req)
  1373. }
  1374. func GetResultDirs(jobName string, parentDir string) (string, error) {
  1375. var req string
  1376. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/")
  1377. if parentDir == "" {
  1378. req = "baseDir=" + modelActualPath
  1379. } else {
  1380. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  1381. }
  1382. return getDirs(req)
  1383. }
  1384. func CloudBrainDownloadModel(ctx *context.Context) {
  1385. parentDir := ctx.Query("parentDir")
  1386. fileName := ctx.Query("fileName")
  1387. jobName := ctx.Query("jobName")
  1388. filePath := "jobs/" + jobName + "/model/" + parentDir
  1389. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  1390. if err != nil {
  1391. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  1392. ctx.ServerError("PresignedGetURL", err)
  1393. return
  1394. }
  1395. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  1396. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  1397. }
  1398. func CloudBrainDownloadInferenceResult(ctx *context.Context) {
  1399. parentDir := ctx.Query("parentDir")
  1400. fileName := ctx.Query("fileName")
  1401. jobName := ctx.Query("jobName")
  1402. filePath := "jobs/" + jobName + "/result/" + parentDir
  1403. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  1404. if err != nil {
  1405. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  1406. ctx.ServerError("PresignedGetURL", err)
  1407. return
  1408. }
  1409. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  1410. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  1411. }
  1412. func GetRate(ctx *context.Context) {
  1413. isObjectDetcionAll := ctx.QueryBool("isObjectDetcionAll")
  1414. if isObjectDetcionAll {
  1415. ctx.Redirect(setting.BenchmarkServerHost + "?username=admin")
  1416. return
  1417. }
  1418. var ID = ctx.Params(":id")
  1419. job, err := models.GetCloudbrainByID(ID)
  1420. if err != nil {
  1421. ctx.ServerError("GetCloudbrainByJobID failed", err)
  1422. return
  1423. }
  1424. if job.JobType == string(models.JobTypeBenchmark) {
  1425. log.Info("url=" + setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1426. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1427. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  1428. ctx.Redirect(setting.Snn4imagenetServerHost)
  1429. } else if job.JobType == string(models.JobTypeBrainScore) {
  1430. ctx.Redirect(setting.BrainScoreServerHost)
  1431. } else {
  1432. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  1433. }
  1434. }
  1435. func downloadCode(repo *models.Repository, codePath, branchName string) error {
  1436. //add "file:///" prefix to make the depth valid
  1437. if err := git.Clone(CLONE_FILE_PREFIX+repo.RepoPath(), codePath, git.CloneRepoOptions{Branch: branchName, Depth: 1}); err != nil {
  1438. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  1439. return err
  1440. }
  1441. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  1442. if err != nil {
  1443. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  1444. return err
  1445. }
  1446. defer configFile.Close()
  1447. pos := int64(0)
  1448. reader := bufio.NewReader(configFile)
  1449. for {
  1450. line, err := reader.ReadString('\n')
  1451. if err != nil {
  1452. if err == io.EOF {
  1453. log.Error("not find the remote-url")
  1454. return nil
  1455. } else {
  1456. log.Error("read error: %v", err)
  1457. return err
  1458. }
  1459. }
  1460. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  1461. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  1462. if len(line) > len(originUrl) {
  1463. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  1464. }
  1465. bytes := []byte(originUrl)
  1466. _, err := configFile.WriteAt(bytes, pos)
  1467. if err != nil {
  1468. log.Error("WriteAt failed:%v", err)
  1469. return err
  1470. }
  1471. break
  1472. }
  1473. pos += int64(len(line))
  1474. }
  1475. return nil
  1476. }
  1477. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType, userName string) error {
  1478. err := os.MkdirAll(codePath, os.ModePerm)
  1479. if err != nil {
  1480. log.Error("mkdir codePath failed", err.Error())
  1481. return err
  1482. }
  1483. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  1484. if err != nil {
  1485. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  1486. return err
  1487. }
  1488. if err := git.Clone(CLONE_FILE_PREFIX+repoExt.RepoPath(), codePath, git.CloneRepoOptions{Depth: 1}); err != nil {
  1489. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  1490. return err
  1491. }
  1492. fileName := codePath + cloudbrain.TaskInfoName
  1493. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1494. if err != nil {
  1495. log.Error("OpenFile failed", err.Error())
  1496. return err
  1497. }
  1498. defer f.Close()
  1499. data, err := json.Marshal(models.TaskInfo{
  1500. Username: userName,
  1501. TaskName: taskName,
  1502. CodeName: repo.Name,
  1503. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  1504. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  1505. GpuType: gpuType,
  1506. })
  1507. if err != nil {
  1508. log.Error("json.Marshal failed", err.Error())
  1509. return err
  1510. }
  1511. _, err = f.Write(data)
  1512. if err != nil {
  1513. log.Error("WriteString failed", err.Error())
  1514. return err
  1515. }
  1516. return nil
  1517. }
  1518. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  1519. files, err := readDir(codePath)
  1520. if err != nil {
  1521. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  1522. return err
  1523. }
  1524. for _, file := range files {
  1525. if file.IsDir() {
  1526. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  1527. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  1528. return err
  1529. }
  1530. } else {
  1531. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  1532. sourceFile := codePath + file.Name()
  1533. err = storage.Attachments.UploadObject(destObject, sourceFile)
  1534. if err != nil {
  1535. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  1536. return err
  1537. }
  1538. }
  1539. }
  1540. return nil
  1541. }
  1542. func mkModelPath(modelPath string) error {
  1543. return mkPathAndReadMeFile(modelPath, "You can put the files into this directory and download the files by the web page.")
  1544. }
  1545. func mkPathAndReadMeFile(path string, text string) error {
  1546. err := os.MkdirAll(path, os.ModePerm)
  1547. if err != nil {
  1548. log.Error("MkdirAll(%s) failed:%v", path, err)
  1549. return err
  1550. }
  1551. fileName := path + "README"
  1552. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1553. if err != nil {
  1554. log.Error("OpenFile failed", err.Error())
  1555. return err
  1556. }
  1557. defer f.Close()
  1558. _, err = f.WriteString(text)
  1559. if err != nil {
  1560. log.Error("WriteString failed", err.Error())
  1561. return err
  1562. }
  1563. return nil
  1564. }
  1565. func DeleteCloudbrainJobStorage(jobName string, cloudbrainType int) error {
  1566. //delete local
  1567. localJobPath := setting.JobPath + jobName
  1568. err := os.RemoveAll(localJobPath)
  1569. if err != nil {
  1570. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  1571. }
  1572. //delete oss
  1573. if cloudbrainType == models.TypeCloudBrainOne {
  1574. dirPath := setting.CBCodePathPrefix + jobName + "/"
  1575. err = storage.Attachments.DeleteDir(dirPath)
  1576. if err != nil {
  1577. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  1578. }
  1579. } else if cloudbrainType == models.TypeCloudBrainTwo {
  1580. //dirPath := setting.CodePathPrefix + jobName + "/"
  1581. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  1582. //if err != nil {
  1583. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  1584. //}
  1585. log.Info("no need to delete")
  1586. } else {
  1587. log.Error("cloudbrainType(%d) error", cloudbrainType)
  1588. }
  1589. return nil
  1590. }
  1591. func SyncCloudbrainStatus() {
  1592. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  1593. if err != nil {
  1594. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  1595. return
  1596. }
  1597. for _, task := range cloudBrains {
  1598. if task.JobType == string(models.JobTypeModelSafety) {
  1599. continue
  1600. }
  1601. if task.Type == models.TypeCloudBrainOne {
  1602. result, err := cloudbrain.GetJob(task.JobID)
  1603. if err != nil {
  1604. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1605. continue
  1606. }
  1607. if result != nil {
  1608. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  1609. taskRoles := jobRes.TaskRoles
  1610. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1611. oldStatus := task.Status
  1612. task.Status = taskRes.TaskStatuses[0].State
  1613. if task.Status != string(models.JobWaiting) {
  1614. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  1615. if oldStatus != task.Status {
  1616. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  1617. }
  1618. err = models.UpdateJob(task)
  1619. if err != nil {
  1620. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1621. }
  1622. var maxDuration int64
  1623. if task.JobType == string(models.JobTypeBenchmark) {
  1624. maxDuration = setting.BenchmarkMaxDuration
  1625. } else if task.JobType == string(models.JobTypeSnn4imagenet) || task.JobType == string(models.JobTypeBrainScore) {
  1626. maxDuration = setting.ModelBenchmarkMaxDuration
  1627. } else {
  1628. maxDuration = setting.MaxDuration
  1629. }
  1630. if task.Duration >= maxDuration && task.JobType != string(models.JobTypeTrain) {
  1631. log.Info("begin to stop job(%s), because of the duration", task.DisplayJobName)
  1632. err = cloudbrain.StopJob(task.JobID)
  1633. if err != nil {
  1634. log.Error("StopJob(%s) failed:%v", task.DisplayJobName, err)
  1635. continue
  1636. }
  1637. task.Status = string(models.JobStopped)
  1638. if task.EndTime == 0 {
  1639. task.EndTime = timeutil.TimeStampNow()
  1640. }
  1641. task.ComputeAndSetDuration()
  1642. if oldStatus != task.Status {
  1643. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  1644. }
  1645. err = models.UpdateJob(task)
  1646. if err != nil {
  1647. log.Error("UpdateJob(%s) failed:%v", task.DisplayJobName, err)
  1648. continue
  1649. }
  1650. }
  1651. }
  1652. }
  1653. } else if task.Type == models.TypeCloudBrainTwo {
  1654. if task.JobType == string(models.JobTypeDebug) {
  1655. err := modelarts.HandleNotebookInfo(task)
  1656. if err != nil {
  1657. log.Error("HandleNotebookInfo(%s) failed:%v", task.DisplayJobName, err)
  1658. continue
  1659. }
  1660. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1661. err := modelarts.HandleTrainJobInfo(task)
  1662. if err != nil {
  1663. log.Error("HandleTrainJobInfo(%s) failed:%v", task.DisplayJobName, err)
  1664. continue
  1665. }
  1666. } else {
  1667. log.Error("task.JobType(%s) is error:%s", task.DisplayJobName, task.JobType)
  1668. }
  1669. } else if task.Type == models.TypeC2Net {
  1670. result, err := grampus.GetJob(task.JobID)
  1671. if err != nil {
  1672. log.Error("GetTrainJob(%s) failed:%v", task.DisplayJobName, err)
  1673. continue
  1674. }
  1675. if result != nil {
  1676. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  1677. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  1678. }
  1679. oldStatus := task.Status
  1680. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  1681. task.Duration = result.JobInfo.RunSec
  1682. if task.Duration < 0 {
  1683. task.Duration = 0
  1684. }
  1685. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1686. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  1687. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  1688. }
  1689. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1690. task.EndTime = task.StartTime.Add(task.Duration)
  1691. }
  1692. task.CorrectCreateUnix()
  1693. if oldStatus != task.Status {
  1694. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  1695. }
  1696. err = models.UpdateJob(task)
  1697. if err != nil {
  1698. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1699. continue
  1700. }
  1701. }
  1702. } else {
  1703. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1704. }
  1705. }
  1706. return
  1707. }
  1708. func HandleTaskWithNoDuration(ctx *context.Context) {
  1709. mode := ctx.Query("mode")
  1710. log.Info("HandleTaskWithNoDuration start")
  1711. count := 0
  1712. start := time.Now().Unix()
  1713. for {
  1714. var cloudBrains []*models.Cloudbrain
  1715. var err error
  1716. if mode == "1" {
  1717. cloudBrains, err = models.GetStoppedJobWithNoStartTimeEndTime()
  1718. } else {
  1719. cloudBrains, err = models.GetStoppedJobWithNoDurationJob()
  1720. }
  1721. if err != nil {
  1722. log.Error("HandleTaskWithNoTrainJobDuration failed:", err.Error())
  1723. break
  1724. }
  1725. if len(cloudBrains) == 0 {
  1726. log.Info("HandleTaskWithNoTrainJobDuration:no task need handle")
  1727. break
  1728. }
  1729. handleNoDurationTask(cloudBrains)
  1730. count += len(cloudBrains)
  1731. if len(cloudBrains) < 100 {
  1732. log.Info("HandleTaskWithNoTrainJobDuration:task less than 100")
  1733. break
  1734. }
  1735. if time.Now().Unix()-start > 600 {
  1736. log.Info("HandleTaskWithNoDuration : time out")
  1737. ctx.JSON(200, fmt.Sprintf("task stop for time out,count=%d", count))
  1738. return
  1739. }
  1740. }
  1741. log.Info("HandleTaskWithNoTrainJobDuration:count=%d", count)
  1742. ctx.JSON(200, fmt.Sprintf("success,count=%d", count))
  1743. }
  1744. func handleNoDurationTask(cloudBrains []*models.Cloudbrain) {
  1745. for _, task := range cloudBrains {
  1746. time.Sleep(time.Millisecond * 100)
  1747. log.Info("Handle job ,%+v", task)
  1748. if task.Type == models.TypeCloudBrainOne {
  1749. result, err := cloudbrain.GetJob(task.JobID)
  1750. if err != nil {
  1751. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1752. updateDefaultDuration(task)
  1753. continue
  1754. }
  1755. if result != nil {
  1756. if result.Msg != "success" {
  1757. updateDefaultDuration(task)
  1758. continue
  1759. }
  1760. jobRes, err := models.ConvertToJobResultPayload(result.Payload)
  1761. if err != nil || len(jobRes.TaskRoles) == 0 {
  1762. updateDefaultDuration(task)
  1763. continue
  1764. }
  1765. taskRoles := jobRes.TaskRoles
  1766. taskRes, err := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1767. if err != nil || len(taskRes.TaskStatuses) == 0 {
  1768. updateDefaultDuration(task)
  1769. continue
  1770. }
  1771. task.Status = taskRes.TaskStatuses[0].State
  1772. log.Info("task startTime = %v endTime= %v ,jobId=%d", jobRes.JobStatus.StartTime, jobRes.JobStatus.EndTime, task.ID)
  1773. if jobRes.JobStatus.CreatedTime > 0 {
  1774. task.StartTime = timeutil.TimeStamp(jobRes.JobStatus.CreatedTime / 1000)
  1775. if jobRes.JobStatus.CompletedTime > 0 {
  1776. task.EndTime = timeutil.TimeStamp(jobRes.JobStatus.CompletedTime / 1000)
  1777. } else {
  1778. task.EndTime = task.UpdatedUnix
  1779. }
  1780. } else {
  1781. task.StartTime = 0
  1782. task.EndTime = 0
  1783. }
  1784. if task.EndTime < task.StartTime {
  1785. log.Info("endTime[%v] is less than starTime[%v],jobId=%d", task.EndTime, task.StartTime, task.ID)
  1786. st := task.StartTime
  1787. task.StartTime = task.EndTime
  1788. task.EndTime = st
  1789. }
  1790. task.Duration = task.EndTime.AsTime().Unix() - task.StartTime.AsTime().Unix()
  1791. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1792. err = models.UpdateJobDurationWithDeleted(task)
  1793. if err != nil {
  1794. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1795. }
  1796. }
  1797. } else if task.Type == models.TypeCloudBrainTwo {
  1798. if task.JobType == string(models.JobTypeDebug) {
  1799. //result, err := modelarts.GetJob(task.JobID)
  1800. result, err := modelarts.GetNotebook2(task.JobID)
  1801. if err != nil {
  1802. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1803. updateDefaultDuration(task)
  1804. continue
  1805. }
  1806. if result != nil {
  1807. task.Status = result.Status
  1808. startTime := result.Lease.CreateTime
  1809. duration := result.Lease.Duration / 1000
  1810. if startTime > 0 {
  1811. task.StartTime = timeutil.TimeStamp(startTime / 1000)
  1812. task.EndTime = task.StartTime.Add(duration)
  1813. }
  1814. task.CorrectCreateUnix()
  1815. task.ComputeAndSetDuration()
  1816. err = models.UpdateJobDurationWithDeleted(task)
  1817. if err != nil {
  1818. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1819. continue
  1820. }
  1821. }
  1822. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1823. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1824. if err != nil {
  1825. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1826. updateDefaultDuration(task)
  1827. continue
  1828. }
  1829. if result != nil {
  1830. startTime := result.StartTime / 1000
  1831. if startTime > 0 {
  1832. task.StartTime = timeutil.TimeStamp(startTime)
  1833. task.EndTime = task.StartTime.Add(result.Duration / 1000)
  1834. }
  1835. task.ComputeAndSetDuration()
  1836. err = models.UpdateJobDurationWithDeleted(task)
  1837. if err != nil {
  1838. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1839. continue
  1840. }
  1841. }
  1842. } else {
  1843. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1844. }
  1845. } else {
  1846. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1847. }
  1848. }
  1849. }
  1850. func updateDefaultDuration(task *models.Cloudbrain) {
  1851. log.Info("updateDefaultDuration: taskId=%d", task.ID)
  1852. task.StartTime = task.CreatedUnix
  1853. task.EndTime = task.UpdatedUnix
  1854. task.ComputeAndSetDuration()
  1855. err := models.UpdateJobDurationWithDeleted(task)
  1856. if err != nil {
  1857. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1858. }
  1859. }
  1860. func CloudBrainBenchmarkIndex(ctx *context.Context) {
  1861. MustEnableCloudbrain(ctx)
  1862. repo := ctx.Repo.Repository
  1863. page := ctx.QueryInt("page")
  1864. if page <= 0 {
  1865. page = 1
  1866. }
  1867. var jobTypes []string
  1868. jobTypes = append(jobTypes, string(models.JobTypeBenchmark), string(models.JobTypeBrainScore), string(models.JobTypeSnn4imagenet), string(models.JobTypeModelSafety))
  1869. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  1870. ListOptions: models.ListOptions{
  1871. Page: page,
  1872. PageSize: setting.UI.IssuePagingNum,
  1873. },
  1874. RepoID: repo.ID,
  1875. Type: -1,
  1876. JobTypes: jobTypes,
  1877. })
  1878. if err != nil {
  1879. ctx.ServerError("Get debugjob faild:", err)
  1880. return
  1881. }
  1882. for i, task := range ciTasks {
  1883. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1884. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  1885. if ciTasks[i].TrainJobDuration == "" {
  1886. if ciTasks[i].Duration == 0 {
  1887. var duration int64
  1888. if task.Status == string(models.JobRunning) {
  1889. duration = time.Now().Unix() - int64(task.Cloudbrain.CreatedUnix)
  1890. } else {
  1891. duration = int64(task.Cloudbrain.UpdatedUnix) - int64(task.Cloudbrain.CreatedUnix)
  1892. }
  1893. ciTasks[i].Duration = duration
  1894. }
  1895. ciTasks[i].TrainJobDuration = models.ConvertDurationToStr(ciTasks[i].Duration)
  1896. }
  1897. ciTasks[i].BenchmarkTypeName = ""
  1898. if ciTasks[i].JobType == string(models.JobTypeBenchmark) {
  1899. ciTasks[i].BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.algorithm")
  1900. } else if ciTasks[i].JobType == string(models.JobTypeSnn4imagenet) || ciTasks[i].JobType == string(models.JobTypeBrainScore) {
  1901. ciTasks[i].BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.model")
  1902. ciTasks[i].BenchmarkTypeName = ciTasks[i].JobType
  1903. if ciTasks[i].JobType == string(models.JobTypeSnn4imagenet) {
  1904. ciTasks[i].BenchmarkTypeRankLink = setting.Snn4imagenetServerHost
  1905. } else {
  1906. ciTasks[i].BenchmarkTypeRankLink = setting.BrainScoreServerHost
  1907. }
  1908. }
  1909. if task.BenchmarkTypeID > 0 {
  1910. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1911. if task.BenchmarkTypeID == benchmarkType.Id {
  1912. ciTasks[i].BenchmarkTypeRankLink = benchmarkType.RankLink
  1913. ciTasks[i].BenchmarkTypeName = benchmarkType.First
  1914. break
  1915. }
  1916. }
  1917. }
  1918. if task.JobType == string(models.JobTypeModelSafety) {
  1919. ciTasks[i].BenchmarkType = "安全评测"
  1920. ciTasks[i].BenchmarkTypeName = "Image Classification"
  1921. }
  1922. }
  1923. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  1924. ctx.Data["Page"] = pager
  1925. ctx.Data["PageIsCloudBrain"] = true
  1926. ctx.Data["Tasks"] = ciTasks
  1927. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  1928. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  1929. ctx.HTML(200, tplCloudBrainBenchmarkIndex)
  1930. }
  1931. func GetChildTypes(ctx *context.Context) {
  1932. benchmarkTypeID := ctx.QueryInt("benchmark_type_id")
  1933. re := make(map[string]interface{})
  1934. for {
  1935. var isExist bool
  1936. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1937. if benchmarkTypeID == benchmarkType.Id {
  1938. isExist = true
  1939. re["child_types"] = benchmarkType.Second
  1940. re["result_code"] = "0"
  1941. break
  1942. }
  1943. }
  1944. if !isExist {
  1945. re["result_code"] = "1"
  1946. log.Error("no such benchmark_type_id", ctx.Data["MsgID"])
  1947. re["errMsg"] = "system error"
  1948. break
  1949. }
  1950. break
  1951. }
  1952. ctx.JSON(200, re)
  1953. }
  1954. func CloudBrainBenchmarkNew(ctx *context.Context) {
  1955. ctx.Data["description"] = ""
  1956. ctx.Data["benchmarkTypeID"] = -1
  1957. ctx.Data["benchmark_child_types_id_hidden"] = -1
  1958. err := cloudBrainNewDataPrepare(ctx, string(models.JobTypeBenchmark))
  1959. if err != nil {
  1960. ctx.ServerError("get new cloudbrain info failed", err)
  1961. return
  1962. }
  1963. ctx.HTML(200, tplCloudBrainBenchmarkNew)
  1964. }
  1965. func getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID int, ctx *context.Context) (*models.BenchmarkDataset, error) {
  1966. var childInfo *models.BenchmarkDataset
  1967. var isExist bool
  1968. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1969. if benchmarkType.Id == benchmarkTypeID {
  1970. for _, childType := range benchmarkType.Second {
  1971. if childType.Id == benchmarkChildTypeID {
  1972. childInfo = childType
  1973. isExist = true
  1974. break
  1975. }
  1976. }
  1977. break
  1978. }
  1979. }
  1980. if !isExist {
  1981. log.Error("no such benchmark_type_id&benchmark_child_type_id")
  1982. return childInfo, errors.New("no such benchmark_type_id&benchmark_child_type_id")
  1983. }
  1984. return childInfo, nil
  1985. }
  1986. func getBenchmarkGpuQueue(gpuQueue string) (string, error) {
  1987. queue := ""
  1988. if benchmarkGpuInfos == nil {
  1989. if err := json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos); err != nil {
  1990. log.Error("json.Unmarshal BenchmarkGpuTypes(%s) failed:%v", setting.BenchmarkGpuTypes, err)
  1991. return queue, err
  1992. }
  1993. }
  1994. var isExist bool
  1995. for _, gpuInfo := range benchmarkGpuInfos.GpuInfo {
  1996. if gpuQueue == gpuInfo.Queue {
  1997. isExist = true
  1998. queue = gpuQueue
  1999. break
  2000. }
  2001. }
  2002. if !isExist {
  2003. log.Error("no such gpuQueue, %s", gpuQueue)
  2004. return queue, errors.New("no such gpuQueue")
  2005. }
  2006. return queue, nil
  2007. }
  2008. func getBenchmarkResourceSpec(resourceSpecID int) (int, error) {
  2009. var id int
  2010. if benchmarkResourceSpecs == nil {
  2011. if err := json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs); err != nil {
  2012. log.Error("json.Unmarshal BenchmarkResourceSpecs(%s) failed:%v", setting.BenchmarkResourceSpecs, err)
  2013. return id, err
  2014. }
  2015. }
  2016. var isExist bool
  2017. for _, resourceSpec := range benchmarkResourceSpecs.ResourceSpec {
  2018. if resourceSpecID == resourceSpec.Id {
  2019. isExist = true
  2020. id = resourceSpecID
  2021. break
  2022. }
  2023. }
  2024. if !isExist {
  2025. log.Error("no such resourceSpecID, %d", resourceSpecID)
  2026. return id, errors.New("no such resourceSpec")
  2027. }
  2028. return id, nil
  2029. }
  2030. func CloudBrainBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  2031. jobType := form.JobType
  2032. if jobType == string(models.JobTypeBenchmark) {
  2033. BenchMarkAlgorithmCreate(ctx, form)
  2034. } else {
  2035. ModelBenchmarkCreate(ctx, form)
  2036. }
  2037. }
  2038. func BenchMarkAlgorithmCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  2039. ctx.Data["PageIsCloudBrain"] = true
  2040. displayJobName := form.DisplayJobName
  2041. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  2042. image := strings.TrimSpace(form.Image)
  2043. command := cloudbrain.CommandBenchmark
  2044. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  2045. benchmarkTypeID := form.BenchmarkTypeID
  2046. benchmarkChildTypeID := form.BenchmarkChildTypeID
  2047. repo := ctx.Repo.Repository
  2048. jobType := form.JobType
  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, jobType)
  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, jobType, 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, jobType)
  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, jobType)
  2073. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  2074. return
  2075. }
  2076. }
  2077. if !jobNamePattern.MatchString(jobName) {
  2078. cloudBrainNewDataPrepare(ctx, jobType)
  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, jobType)
  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, jobType)
  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, jobType)
  2102. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplCloudBrainBenchmarkNew, &form)
  2103. return
  2104. }
  2105. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainOne, jobType)
  2106. if err != nil {
  2107. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  2108. cloudBrainNewDataPrepare(ctx, jobType)
  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, jobType)
  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, jobType)
  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, jobType)
  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, jobType)
  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, jobType)
  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, jobType)
  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, jobType)
  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, jobType)
  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, jobType)
  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, jobType)
  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, jobType)
  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, jobType)
  2246. ctx.RenderWithErr("system error", tpl, &form)
  2247. return
  2248. }
  2249. }
  2250. if !jobNamePattern.MatchString(displayJobName) {
  2251. cloudBrainNewDataPrepare(ctx, jobType)
  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, jobType)
  2258. ctx.RenderWithErr("jobtype error", tpl, &form)
  2259. return
  2260. }
  2261. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeCloudBrainOne, jobType)
  2262. if err != nil {
  2263. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  2264. cloudBrainNewDataPrepare(ctx, jobType)
  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, jobType)
  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, jobType)
  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, jobType)
  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, jobType)
  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, jobType)
  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, string(models.JobTypeTrain))
  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, string(models.JobTypeInference))
  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. }