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