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