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

cloudbrain.go 93 kB

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