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

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