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

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