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