You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

cloudbrain.go 94 kB

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