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

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