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

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